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CAChE,CACA,EAASxD,GAAetK,CAAM,CAC/B,CACA,SAASgO,GAAgB,CACxB,OAAO,IACR,CACA,OAAOA,CACR,CAYA,SAASC,GAAe,EAAQ,EAAM,CACrC,KAAOjO,IAAW,MAAM,CACvB,IAAM8N,EAAOvD,EAAyBvK,EAAQ+N,CAAI,EAClD,GAAID,EAAM,OAAOA,EAAK,IAAM5C,GAAQ4C,EAAK,GAAG,EAAI,KAChD,EAASxD,GAAetK,CAAM,CAC/B,CACA,OAAO,IACR,CACA,SAASkO,GAAQ,EAAO,CACvB,GAAI,CAACrK,EAAO,MAAO,GACnB,GAAI,CAEH,OADA6I,GAAW7I,EAAO,EAAE,EACb,EACR,MAAkB,CACjB,MAAO,EACR,CACD,CACA,IAAMsK,GAAS3D,GAAO,ipBAwHtB,CAAC,EACK4D,GAAQ5D,GAAO,8UA4CrB,CAAC,EACK6D,GAAa7D,GAAO,CACzB,UACA,gBACA,sBACA,cACA,mBACA,oBACA,oBACA,iBACA,eACA,UACA,UACA,UACA,UACA,UACA,iBACA,UACA,UACA,cACA,eACA,WACA,eACA,qBACA,cACA,SACA,cACD,CAAC,EACK8D,GAAgB9D,GAAO,CAC5B,UACA,gBACA,SACA,UACA,YACA,mBACA,iBACA,gBACA,gBACA,gBACA,QACA,YACA,OACA,eACA,YACA,UACA,gBACA,SACA,MACA,aACA,UACA,KACD,CAAC,EACK+D,GAAW/D,GAAO,qNA+BxB,CAAC,EACKgE,GAAmBhE,GAAO,CAC/B,UACA,cACA,aACA,WACA,YACA,UACA,UACA,SACA,SACA,QACA,YACA,aACA,iBACA,cACA,MACD,CAAC,EACKiE,GAAOjE,GAAO,CAAC,OAAO,CAAC,EACvBkE,GAAOlE,GAAO,u7BAuHpB,CAAC,EACKmE,GAAMnE,GAAO,g2DAiMnB,CAAC,EACKoE,GAASpE,GAAO,sgBAuDtB,CAAC,EACKqE,GAAMrE,GAAO,CAClB,aACA,SACA,cACA,YACA,aACD,CAAC,EACKsE,IAAgBrE,GAA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AAK,0DAA0D,EAMrE,CAAC,OAAO,kBAAoB,SAAS,eAAiBA,MACxDx3c,GAAK,E","names":["REACT_ELEMENT_TYPE","REACT_PORTAL_TYPE","REACT_FRAGMENT_TYPE","REACT_STRICT_MODE_TYPE","REACT_PROFILER_TYPE","REACT_CONSUMER_TYPE","REACT_CONTEXT_TYPE","REACT_FORWARD_REF_TYPE","REACT_SUSPENSE_TYPE","REACT_MEMO_TYPE","REACT_LAZY_TYPE","REACT_ACTIVITY_TYPE","REACT_VIEW_TRANSITION_TYPE","MAYBE_ITERATOR_SYMBOL","getIteratorFn","maybeIterable","ReactNoopUpdateQueue","assign","emptyObject","Component","props","context","updater","partialState","callback","ComponentDummy","PureComponent","pureComponentPrototype","isArrayImpl","noop","ReactSharedInternals","hasOwnProperty","ReactElement","refProp","cloneAndReplaceKey","oldElement","newKey","isValidElement","object","escape","escaperLookup","key","match","userProvidedKeyEscapeRegex","getElementKey","element","index","resolveThenable","thenable","fulfilledValue","error","mapIntoArray","type","children","invokeCallback","array","escapedPrefix","nameSoFar","c","nextNamePrefix","i","mapChildren","result","count","func","child","lazyInitializer","payload","ctor","moduleObject","reportGlobalError","event","startTransition","prevTransition","currentTransition","returnValue","scope","onStartTransitionFinish","addTransitionType","transition","transitionTypes","Children","forEachFunc","forEachContext","n","size","fn","config","propName","childArray","defaultValue","childrenLength","compare","usable","action","initialState","permalink","deps","Context","value","initialValue","create","ref","passthrough","reducer","initialArg","init","subscribe","getSnapshot","getServerSnapshot","require_react_production","getOwnPropertySymbols","propIsEnumerable","toObject","val","shouldUseNative","test1","test2","test3","letter","from","to","target","symbols","s","_assign","require_object_assign","_invariant","condition","format","args","a","b","d","e","f","argIndex","MIXINS_KEY","identity","factory","injectedMixins","ReactClassInterface","ReactClassStaticInterface","RESERVED_SPEC_KEYS","displayName","mixins","mixSpecIntoComponent","Constructor","childContextTypes","contextTypes","createMergedResultFunction","getDefaultProps","propTypes","mixStaticSpecIntoComponent","statics","validateMethodOverride","specPolicy","name","ReactClassMixin","isAlreadyDefined","spec","proto","autoBindPairs","property","isReactClassMethod","createChainedFunction","mergeIntoWithNoDuplicateKeys","one","two","bindAutoBindMethod","method","component","bindAutoBindMethods","pairs","autoBindKey","IsMountedPreMixin","IsMountedPostMixin","newState","ReactClassComponent","ReactComponent","createClass","methodName","React","require_react","require_factory","_OverloadYield","_arrayLikeToArray","r","_arrayWithHoles","_iterableToArrayLimit","t","u","o","l","_nonIterableRest","_slicedToArray","_unsupportedIterableToArray","AsyncGenerator","resume","settle","entries","objectKeys","setPrototypeOf","isFrozen","getPrototypeOf","getOwnPropertyDescriptor","freeze","seal","_ref","apply","construct","x","apply$1","thisArg","Func","arrayForEach","unapply","arrayLastIndexOf","arrayPop","arrayPush","arraySlice","arraySplice","arrayIsArray","setCreate","unconstruct","setAdd","setHas","stringToLowerCase","stringToString","stringMatch","stringReplace","stringIndexOf","stringTrim","numberToString","booleanToString","bigintToString","symbolToString","objectHasOwnProperty","objectToString","regExpTestRaw","regExpTest","regExp","typeErrorCreate","addToSet","transformCaseFunc","set","lcElement","cleanArray","clone","newObject","_ref2","_ref3","cloneSet","newSet","keys","stringifyValue","valueAsRecord","valueToString","lookupGetter","stringified","desc","prop","fallbackValue","lookupAccessor","isRegex","html$1","svg$1","svgFilters","svgDisallowed","mathMl$1","mathMlDisallowed","text","html","svg","mathMl","xml","MUSTACHE_EXPR","ERB_EXPR","TMPLIT_EXPR","TMPL_MARKER_SERIALIZED","DATA_ATTR","ARIA_ATTR","IS_ALLOWED_URI","IS_SCRIPT_OR_DATA","ATTR_WHITESPACE","DOCTYPE_NAME","CUSTOM_ELEMENT","ELEMENT_MARKUP_PROBE","COMMENT_MARKUP_PROBE","FALLBACK_TAG_CLOSE","SELF_CLOSING_TAG","ATTR_VALUE_BREAKOUT","LEADING_WHITESPACE","NODE_TYPE","LITERAL_TEXT_ELEMENTS","getGlobal","_createTrustedTypesPolicy","trustedTypes","suffix","ATTR_NAME","purifyHostElement","policyName","scriptUrl","_createHooksMap","_resolveSetOption","cfg","options","fallback","_resolveObjectOption","createDOMPurify","window","DOMPurify","root","document","originalDocument","currentScript","HTMLTemplateElement","Node","Element","NodeFilter","DOMParser","ElementPrototype","cloneNode","remove","removeAttributeNode","getNextSibling","getChildNodes","getParentNode","getShadowRoot","getAttributes","getNodeType","getNodeName","getOwnerDocument","_readNodeType","node","_readNodeName","getNamespaceURI","_readNamespaceURI","template","trustedTypesPolicy","emptyHTML","defaultTrustedTypesPolicy","defaultTrustedTypesPolicyResolved","IN_TRUSTED_TYPES_POLICY","_assertNotInTrustedTypesPolicy","_createTrustedHTML","_signOutput","RETURN_TRUSTED_TYPE","_createTrustedScriptURL","_getDefaultTrustedTypesPolicy","_document","implementation","createNodeIterator","createDocumentFragment","getElementsByTagName","importNode","hooks","MUSTACHE_EXPR$1","ERB_EXPR$1","TMPLIT_EXPR$1","DATA_ATTR$1","ARIA_ATTR$1","IS_SCRIPT_OR_DATA$1","ATTR_WHITESPACE$1","CUSTOM_ELEMENT$1","IS_ALLOWED_URI$1","ALLOWED_TAGS","DEFAULT_ALLOWED_TAGS","ALLOWED_ATTR","DEFAULT_ALLOWED_ATTR","CUSTOM_ELEMENT_HANDLING","FORBID_TAGS","FORBID_ATTR","EXTRA_ELEMENT_HANDLING","ALLOW_ARIA_ATTR","ALLOW_DATA_ATTR","ALLOW_UNKNOWN_PROTOCOLS","ALLOW_SELF_CLOSE_IN_ATTR","SAFE_FOR_TEMPLATES","SAFE_FOR_XML","WHOLE_DOCUMENT","SET_CONFIG","SET_CONFIG_ALLOWED_TAGS","SET_CONFIG_ALLOWED_ATTR","FORCE_BODY","RETURN_DOM","RETURN_DOM_FRAGMENT","SANITIZE_DOM","SANITIZE_NAMED_PROPS","SANITIZE_NAMED_PROPS_PREFIX","KEEP_CONTENT","IN_PLACE","IN_PLACE_VISITED","USE_PROFILES","FORBID_CONTENTS","DEFAULT_FORBID_CONTENTS","DATA_URI_TAGS","DEFAULT_DATA_URI_TAGS","URI_SAFE_ATTRIBUTES","DEFAULT_URI_SAFE_ATTRIBUTES","MATHML_NAMESPACE","SVG_NAMESPACE","HTML_NAMESPACE","NAMESPACE","IS_EMPTY_INPUT","ALLOWED_NAMESPACES","DEFAULT_ALLOWED_NAMESPACES","DEFAULT_MATHML_TEXT_INTEGRATION_POINTS","MATHML_TEXT_INTEGRATION_POINTS","DEFAULT_HTML_INTEGRATION_POINTS","HTML_INTEGRATION_POINTS","DEFAULT_CUSTOM_ELEMENT_HANDLING","COMMON_SVG_AND_HTML_ELEMENTS","PARSER_MEDIA_TYPE","SUPPORTED_PARSER_MEDIA_TYPES","CONFIG","formElement","isRegexOrFunction","testValue","_parseConfig","customElementHandling","previousTrustedTypesPolicy","ALL_SVG_TAGS","ALL_MATHML_TAGS","_checkSvgNamespace","parentNamespace","tagName","parentTagName","_checkMathMlNamespace","_checkHtmlNamespace","_checkValidNamespace","elementNamespace","parentNode","_forceRemove","_stripAttributeNode","attribute","_neutralizeRoot","_neutralizeSubtree","childNodes","_stripAttributes","_removeAttribute","attr","attributes","keepAllowed","_walkTree","intoShadow","stack","visit","shadowRoot","_isDocumentFragment","_collectLiveNodes","nodes","_neutralizeEscapedElements","reachable","before","_neutralizeDiscarded","rootRemoved","entry","_sanitizeUnvisitedNodes","visited","original","getOriginal","beforeNode","round","live","containers","pending","_sanitizeUnvisitedIn","container","iterator","_createNodeIterator","inShadow","_executeHooks","_sanitizeNode","_markVisited","_isPatchLinkageAttribute","lcName","lcTag","_neutralizePatchLinkage","nodeType","_initDocument","doc","leadingWhitespace","dirty","matches","dirtyPayload","body","characterDataOnly","_stripTemplateExpressions","_scrubTemplateExpressions2","_scrubOwnCharacterData","templates","tmpl","walker","currentNode","_isClobbered","realTagName","_nodeTypeOf","_isNode","hook","data","_isUnsafeNode","_matchesNameCheck","check","_sanitizeDisallowedNode","_isBasicCustomElement","childCount","hoisted","_forkSharedAllowlist","hookList","defaultSet","setConfigSet","_handleHookDetachedNode","_sanitizeElements","removed","content","_isValidAttribute","nameIsPermitted","compactValue","RESERVED_CUSTOM_ELEMENT_NAMES","_applyTrustedTypesToAttribute","namespaceURI","_setAttributeValue","_isUnsafeAttributeValue","_sanitizeAttributes","hookEvent","attrValue","initValue","recreatedNamedProp","_sanitizeShadowDOM2","shadowNode","shadowIterator","fragment","innerSr","_sanitizeAttachedShadowRoots","item","isElement","rootName","sr","importedNode","returnNode","inPlace","inPlaceNodes","outerVisited","nn","walkRoot","nodeIterator","serialize","serializedHTML","tag","hookFunction","entryPoint","purify_default","browser_default","sanitize","G","S","ue","q","D","g","O","_e","he","Ge","Ne","Fe","V","Qe","ce","J","$e","Le","We","de","Ue","ge","Ke","Xe","ke","Ve","Ce","Je","Ye","fe","Pe","tt","nt","rt","st","Ie","it","L","N","Y","ot","at","Ae","lt","ut","pt","Ee","ct","ht","gt","ze","kt","ft","xt","bt","Tt","Ot","Pt","yt","St","_t","$t","Lt","Me","ie","Ct","It","At","ye","Et","zt","Se","Bt","me","Dt","pe","qt","ee","F","vt","Be","y","De","xe","be","C","Re","W","Te","Q","Oe","qe","ve","oe","ae","te","Ht","He","h","Zt","Ze","_","m","p","k","R","E","T","H","K","re","B","X","se","le","we","Z","$","j","je","U","w","#t","#e","qe$1","ve$3","I","z","P","A","M","ne","M$3","A$1","v","jt","Bn","Dn","vn","HYDRATION_ERROR","UNINITIALIZED","is_array","index_of","includes","array_from","define_property","get_descriptor","get_descriptors","object_prototype","array_prototype","get_prototype_of","is_extensible","is_function","thing","is_promise","run_all","arr","deferred","resolve","reject","res","rej","lazy","to_array","STATE_SYMBOL","COMPONENT_SYMBOL","LEGACY_PROPS","LOADING_ATTR_SYMBOL","ATTRIBUTES_CACHE","CLASS_CACHE","STYLE_CACHE","TEXT_CACHE","FORM_RESET_HANDLER","STALE_REACTION","IS_XHTML","derived_inert","hydration_mismatch","select_multiple_invalid_value","svelte_boundary_reset_noop","hydrating","set_hydrating","hydrate_node","set_hydrate_node","hydrate_next","get_next_sibling","reset","next","skip_nodes","depth","node_type","get_node_value","remove_node","read_hydration_instruction","equals","safe_not_equal","safe_equals","lifecycle_outside_component","each_key_duplicate","effect_in_teardown","effect_in_unowned_derived","effect_orphan","effect_update_depth_exceeded","props_invalid_value","state_descriptors_fixed","state_prototype_fixed","state_unsafe_mutation","svelte_boundary_reset_onerror","empty","snapshot","no_tojson","unwrapped","cloned","copy","path","paths","micro_tasks","run_micro_tasks","tasks","queue_micro_task","is_flushing_sync","flush_tasks","STATUS_MASK","set_signal_status","signal","status","update_derived_status","derived","get_parent_context","parent","get_or_init_context_map","component_context","set_component_context","getContext","setContext","getAllContexts","push","active_effect","pop","effects","create_user_effect","mark_as_component","is_runes","current_renderer","flatten","deriveds","sync","derived_safe_equal","blockers","restore","capture","decrement_pending","increment_pending","run","invoke_error_boundary","unset_context","async","signals","async_expression","effect","block","is_uninitialized","get","branch","current_batch","previous_effect","previous_reaction","active_reaction","previous_component_context","previous_batch","set_active_effect","set_active_reaction","batch","merge_target","deactivate_batch","current_runner","boundary","OBSOLETE","source","deferreds","runner","resolver","waiting","flush_waiting","fns","continued","async_effect","promise","abort_signal","abort_controller","handler","obsolete","same","onready","teardown","batch_values","user_derived","push_reaction_value","destroy_derived_effects","destroy_effect","execute_derived","prev_active_effect","is_destroying_effect","update_reaction","update_derived","is_dirty","records","view_batch","record","is_current","promote_record","get_view","cache","view_cache","written","held","assigned","changed_since","freeze_derived_effects","abort_all","remove_reactions","destroy_effect_children","unfreeze_derived_effects","update_effect","first_batch","last_batch","processing_batch","teardown_context","set_teardown_context","push_teardown_context","values","teardown_write","last_scheduled_effect","rebases","collected_effects","legacy_updates","flush_count","seen","count_deps","uid","last_processed","Batch","#pending","#skipped_branches","#unskipped_branches","#skips","flags","roots","#scheduled","covered","#unprocessed","#add","render_effects","revealed_boundaries","updates","#unlink","infinite_loop_guard","#resolve","#traverse","reset_branch","#is_deferred","sorted","#defer_effects","earlier","#merge","#process","earlier_batch","#find_earlier_batch","#release_records","#run_callbacks","#commit_callbacks","flush_queued_effects","#deferred","next_batch","sources","reactions","reaction","is_branch","#intersects","previous","replaced","abort_record","#add_dirty_effect","discard","later","later_writer","increment_write_version","updated_during_traversal","eager_effects","eager_effects_deferred","flush_eager_effects","#decrement_queued","#discard_callbacks","is_earlier","own","#revalidate","#commit","#move_to_front","eager_block_writes","untrack","writes","callbacks","write","runes","length","seen$1","not_dirty","eager_block_effects","is_outdated","commit","prune_edges","prev","first","flushSync","was_flushing_sync","previous_view_batch","defer_if_pending","earlier_writes","version","write_version","unlink_effect","previous_teardown_context","previous_eager_block_writes","ordered_effects","ancestor","in_real_world","previous_batch_values","previous_view_cache","force","state","mutable_source","initial_value","immutable","untracking","current_sources","internal_set","should_proxy","proxy","untracked_writes","set_untracked_writes","run_eager_effects","increment","set$1","prototype","is_proxied_array","parent_version","update_version","with_parent","set_update_version","descriptor","exists","receiver","has","other_s","ls","own_keys","get_proxied_value","is","$window","$document","is_firefox","first_child_getter","next_sibling_getter","init_operations","element_prototype","node_prototype","text_prototype","create_text","get_first_child","append_child","is_text","insert_before","merge_text_nodes","first_child","is_comment","only_child","sibling","next_sibling","last_sibling","insert_after","clear_text_content","should_defer_append","create_element","namespace","create_fragment","create_comment","set_attribute","node_name","get_last_child","get_parent_node","ref_node","new_node","remove_child","set_text_content","set_node_value","set_element_value","set_element_checked","checked","set_element_default_value","existing_value","set_element_default_checked","get_attribute","remove_attribute","has_attribute","set_inner_html","clone_node","deep","import_node","add_event_listener","remove_event_listener","dispatch_event","style_set_property","priority","style_remove_property","set_css_text","class_list_toggle","handle_error","validate_effect","rune","push_effect","parent_last","parent_effect","create_effect","effect_tracking","user_effect","user_pre_effect","effect_root","component_root","pause_effect","fulfil","render_effect","template_effect","flatten$1","deferred_template_effect","managed","execute_effect_teardown","previously_destroying_effect","previous_teardown_version","teardown_version","set_is_destroying_effect","remove_dom","destroy_block_effect_children","remove_effect_dom","transitions","end","pause_children","destroy","remaining","previous_context","local","transparent","resume_effect","resume_children","move_effect","captured_signals","autofocus","dom","remove_textarea_child","listening_to_form_reset","add_form_reset_listener","evt","without_reactive_context","listen_to_event_and_reset_event","on_reset","teardown_run","new_deps","skipped_deps","read_version","version_of","dv","dep","wv","unchanged","run_of","dependency","schedule_possible_effect_self_invalidation","controller","abort_replaced","is_derived","real","supersedes","set_global_signal","other","is_recorded_effect","previous_deps","previous_skipped_deps","previous_untracked_writes","previous_sources","previous_untracking","previous_update_version","previous_abort_controller","update_dependencies","teardown_version_of","keep_global_run","set_derived_value","update_record","should_record","read","seen_version","keep","has_batch_record","tracking","edges","remove_reaction","added","derived_version","ac","add_reaction","new_length","dependencies","tick","late_reader","teardown_view","view","should_connect","is_new","reconnect","record_late_read","holds","is_capture_event","DELEGATED_EVENTS","can_delegate_event","event_name","DOM_BOOLEAN_ATTRIBUTES","ATTRIBUTE_ALIASES","normalize_attribute","PASSIVE_EVENTS","is_passive_event","RAW_TEXT_ELEMENTS","is_raw_text_element","event_symbol","propagation_stopped_at","all_registered_events","root_event_handles","replay_events","create_event","is_custom_renderer","target_handler","handle_event_propagation","on","delegated","delegate","events","delegated_listeners","listen_to_delegated_events","registered_events","event_handle","passive","counts","last_propagated_event","last_propagated_event_clear_scheduled","handler_element","was_stopped","owner_document","current_target","path_idx","handled_at","at_idx","handler_idx","throw_error","other_errors","policy","create_trusted_html","create_fragment_from_html","elem","assign_nodes","from_html","is_fragment","use_import_node","has_start","comment","frag","start","anchor","append","props_id","node_value","id","createSubscriber","subscribers","stop","Boundary","transform_error","#effect_pending","#local_pending_count","#anchor","#props","#children","#effect","comment_data","#hydrate_open","server_rendered_pending","serialized_error","#hydrate_failed_content","#hydrate_pending_content","#hydrate_resolved_content","#render","#main_effect","failed","#create_reset","invoke_onerror","#failed_effect","did_reset","calling_on_error","#is_destroyed","#run","err","#pending_effect","#offscreen_fragment","#effects","previous_ctx","owner","#pending_count_update_queued","#effect_pending_subscriber","#handle_error","handle_error_result","transformed_error","set_text","str","mount","_mount","_mount_inner","unmount","anchor_node","ctx","transformError","stop_listening","renderer","mounted_components","BranchManager","#transition","#renderer","#batches","onscreen","#onscreen","#outroing","offscreen","#offscreen","#discard","on_destroy","defer","snippet","branches","get_snippet","onMount","cleanup","onDestroy","createAttachmentKey","PENDING","THEN","CATCH","await_block","current","forks","is_latest","input","get_input","fork","mismatch","resolved","then_fn","catch_fn","pending_fn","if_block","marker","elseif","update_branch","has_branch","NAN","legacy","get_key","render_fn","clsx","_clsx","whitespace","to_class","classname","hash","directives","len","append_styles","separator","important","css","styles","to_css_name","to_style","new_style","normal_styles","important_styles","in_str","in_apo","in_comment","reserved_names","start_index","name_index","css_props","get_styles","pause_effects","to_destroy","group","groups","destroy_effects","fast_path","controlled_anchor","parent_node","selected_effects","selected","preserved_effects","link$1","is_outroing","offscreen_anchors","dom_weak_key","get_offscreen_anchor","cached","offscreen_anchor","each","items","each_array","collection","get_collection","first_run","reconcile","move$1","destroy_unselected","create_item","fallback_fn","skip_to_branch","is_animated","to_animate","matched","stashed","destroy_length","move","dest","next_node","link","is_controlled","get_value","last","wrapper","mathml","hydration_start_node","get_component","now","raf","run_tasks","task","loop","fulfill","css_property_to_camelcase","style","parts","word","css_to_keyframe","keyframe","part","formatted_property","linear","animation_effect_override","set_animation_effect_override","animation","original_styles","get_fn","get_params","animate","position","width","height","transform","is_intro","t2","aborted","counterpart","on_begin","on_finish","get_t","keyframes","delay","t1","delta","duration","needs_overflow_hidden","easing","time","was_hydrating","next_tag","get_tag","ns","get_namespace","is_svg","is_hydrating","tmp_comment","child_anchor","head","previous_hydrate_node","head_anchor","attach","set_class","next_class_name","next_classes","is_html","set_attribute$1","prev_classes","is_present","update_styles","set_style","next_style_attr","next_styles","prev_styles","set_selected","option","set_default_select_value","mounting","select","apply_default_select_value","multiple","preserve","option_value","get_option_value","was_selected","select_option","w.select_multiple_invalid_value","init_select","observer","is_selectedcontent_mutation","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","get_setters","set_attributes","should_remove_defaults","is_custom_element","preserve_attribute_case","is_hydrating_custom_element","is_option_element","is_select_element","css_hash","setters","skip_warning","prev_value","prefix","opts","event_handle_key","is_delegated","handle","is_default","use_default","attribute_effect","is_select","inited","symbol","attrs","setters_cache","cache_key","descriptors","element_proto","bind_value","batches","is_reset","is_numberlike_input","to_number","resize_observer_border_box","ResizeObserverSingleton","#options","listeners","#listeners","listener","#getObserver","#observer","bind_element_size","unsub","is_bound_this","bound_value","element_or_component","bind_this","component_effect","old_parts","get_parts","update","original_teardown","is_store_binding","capture_store_binding","previous_is_store_binding","rest_props_handler","rest_props","spread_props_handler","spread_props","bindable","fallback_value","fallback_dirty","fallback_signal","get_fallback","setter","is_entry_props","is_store_sub","getter","legacy_parent","mutation","overridden","new_value","bidiChars","nameChars","notNameStart","parseNameValue","pos","startBidi","endBidi","parseUnquotedLiteralValue","cstKey","MessageError","message","MessageSyntaxError","expected","MessageDataModelError","MessageResolutionError","cause","MessageFunctionError","whitespaceChars","MissingSyntax","SyntaxError","expect","searchString","consume","parseMessage","source_","decl","declarations","selectMessage","quoted","pattern_","pattern","ws$1","selectors","variable","variants","variant","literal","expression","inputDeclaration","localDeclaration","valueStart","name_","arg","sigil","functionRef","markup","identifier","options_","allowMarkup","attributes_","exp","isEmpty","esc","required","quotedLiteral","ws","hasWS","req","visitors","handleOptions","value_","handleAttributes","handleElement","endA","handlePattern","pat","el","msg","declaration","sel","vari","validate","selectorCount","missingFallback","annotated","declared","functions","localVars","variables","setArgAsDeclared","visit$2","onError","strKeys","lv","RTL","getLocaleDir","locale","info","script","asBoolean","asPositiveInteger","asString","readNumericOperand","valueOf","getMessageNumber","canSelect","nf","cat","dir","locales","numVal","pluralOpt","number","operand","optval","exprOpt","integer","currency","strval","numval","dateFieldsValues","dateLengthValues","timePrecisionValues","timeZoneStyleValues","datetime","dateTimeImplementation","date","opt","functionName","tz","dfName","dlName","dateFieldsValue","readStringOption","dateLength","dateFields","dtf","allowed","offset","add","sub","percent","string","selStr","unit","DefaultFunctions","string$1","DraftFunctions","date$1","time$1","BIDI_ISOLATE","unknown","MessageFunctionContext","#ctx","#source","dirOpt","resolveValue","getValueSource","idOpt","#litKeys","mfError","resolveFunctionRef","fnSource","fnInput","rf","msgCtx","resolveOptions","override","resolveExpression","msgStr","resolveVariableRef","UnresolvedExpression","isScope","getValue","tail","lookupVariableRef","mv","msgFn","formatMarkup","rv","selectPattern","selector","selectKey","candidates","sc","#bidiIsolation","#localeMatcher","#locales","lc","#dir","#message","validate$1","#functions","#createContext","msgParams","pre","errStr","mp","fb","_locale","$.state","requestedLocale","$.proxy","dictionary","fallbackLocale","_resolvedFallback","missingMessageHandler","customFormats","customFunctions","messageFormats","assertNonEmptyString","label","assertString","assertFunction","parsedTags","parseLocaleTag","parsed","maximized","region","negotiateLocale","requested","available","parsedRequest","code","language","anyScript","findByRegion","preferredRegion","flattenMessages","map","flatKey","acc","registerLocaleCode","localeCode","resolveLocale","renegotiateActiveLocale","$.get","addMessages","maps","messages","MESSAGE_FUNCTIONS","loaderQueue","loaderPromises","waitLocale","loader","isRTL","register","getLocaleFromNavigator","languages","lang","getMessage","getLookupLocales","active","localeOverride","defaultString","lookupLocales","found","formats","handled","DEFAULT_FORMAT_KEY","BUILT_IN_FORMATS","getNamedPreset","kind","getDefaultPreset","getMessagePreset","overrideMessageValue","presetLocale","formatter","wrapMessageFunction","preset","rest","Formatter","Icon","restProps","$.rest_props","$$props","rest_excludes","span","$.only_child","$$anchor","Alert_content","$.prop","icon","$0","$.derived","$$render","consequent","alternate","$.sibling","$.noop","$.set_text","getAlertRole","getAlertAriaLive","ariaLive","role","Alert","div","$.child","_isMac","isMac","MODIFIER_KEYS","MODIFIER_EVENT_KEYS","PHYSICAL_TOKENS","createTokenMatcher","token","digitCode","namedKey","lowerToken","letterCode","resolveAccel","shortcuts","parsedShortcutCache","parseShortcuts","shortcut","matchesParsedShortcuts","parsedShortcuts","ctrl","ctrlKey","meta","metaKey","alt","altKey","shift","shiftKey","matchers","matchesShortcuts","shortcutTargets","activateElement","disabled","isClickable","left","top","NON_TEXT_INPUT_TYPES","isTextEntryTarget","isTextEditingWithOption","handleKeyDown","updateShortcutsAttribute","registrations","activateKeyShortcuts","registration","getValueType","castValue","Truncated_text","lines","$.set_style","sleep","ms","uuidPattern","generateUUID","uuid","base32Alphabet","encodeBase32","output","buffer","bits","bytes","byte","generateRandomId","getHash","digest","algorithm","visibilityResolvers","sharedVisibilityObserver","generateElementId","removeVisibilityResolver","getSharedVisibilityObserver","isIntersecting","sharedVisibilityObservers","getMarginVisibilityObserver","shared","rootMargin","states","elementListeners","observeVisibility","whenSteadilyVisible","cancelled","timer","visible","isVisible","bottom","right","innerHeight","innerWidth","scheduleVisibilityCheck","waitForVisibility","previousResolve","FOCUSABLE_SELECTOR","focusAdjacentTabStop","candidate","step","backwards","restoreFocus","activeElement","hasModifier","getArrowKeys","orientation","rtl","getLinearTargetIndex","prevKey","nextKey","getGridTargetIndex","lastIndex","backward","forward","columnCount","mirrorPosition","mirrored","clipRect","anchorRect","viewport","flip","room","otherRoom","flipEither","isOn","side","sideA","sideB","sides","roomA","roomB","rooms","calculatePopupStyle","preferredPosition","rect","topMargin","bottomMargin","leftMargin","rightMargin","downwardMargin","upwardMargin","flipVertically","contentHeight","contentWidth","isShallowEqual","Popup","#open","anchorElement","positionBaseElement","#anchorIsTextField","#anchorListeners","on$2","#onAnchorClick","#onAnchorKeyDown","#onAnchorTransitionStart","popupElement","contentElement","nested","identifiedElement","#popupListeners","#onPopupClick","#onPopupKeyDown","appliedMaxHeight","appliedMaxWidth","activatePopup","getLongestTime","getTransitionTimeout","transitionDuration","transitionDelay","openModalDialogs","forgetModalDialog","dialog","rememberModalDialog","Placeholder","RETAINER_KEY","Modal","dialogSnippet","dialog_1","event_handler","event_handler_1","downTarget","pointerDownTarget","lightDismiss","close","event_handler_2","modal","escapeDismiss","event_handler_3","event_handler_4","requestedOpen","open","showDialog","setOpenClass","showBackdrop","setActiveClass","node_1","boundDialog","mounted","keepContent","focus","retainCount","parentRetainer","generation","lastActiveElement","restoreFocusTimer","moveFocusBack","waitForTransition","timeout","openDialog","gen","closeDialog","wasOpen","placeholder","contentWrapper","boundContent","$.set_class","contentType","classes","touch","parentDialogElement","popupInstance","hovered","hoveredTimeout","touchOptimized","dialogElement","touchEnabled","focusContent","focused","tabStopOnly","$.spread_props","$$value","OPPOSITE_SIDES","clamp","min","max","getTooltipPosition","preferred","opposite","placement","centredLeft","centredTop","maxLeft","maxTop","toggleIdInList","ids","list","include","getAccessibleText","collect","Tooltip","$.props_id","dismissed","schedule","onPointerEnter","onPointerLeave","updatePosition","onAnchorPointerEnter","onFocusIn","onPointerDown","onFocusOut","setDescribedBy","popover","onKeyDown","resizeObserver","text_1","$.set","Button","labelText","labelDir","boundElement","className","valueType","hidden","readonly","pressed","keyShortcuts","iconic","pill","flex","popupPosition","showPopupBackdrop","tooltip","tooltipPosition","button","$.first_child","fragment_1","span_1","consequent_2","consequent_1","alternate_1","node_8","consequent_3","Infobar","show","dismissible","root_1","div_1","node_2","div_2","node_3","$.clsx","Bottom_navigation","Copy_button","ariaLabel","copied","buttonElement","Floating_action_button_wrapper","CONTEXT_KEY","OptionRegistry","#entries","#snapshotVersion","#version","#snapshot","#entrySet","createOptionRegistry","getOptionRegistry","getSelectedItemDetail","DIACRITIC_RE","fold","normalize","getItemLabel","textFallback","isPrintableKey","findTypeAheadMatch","cycling","char","needle","currentIndex","labels","TypeAhead","#timer","#prefix","activateBefore","widget","activateLater","isDestroyed","CompositeWidget","#controller","createWidgetAttachment","isGetter","paramsOrGetter","Widget","scrollIntoViewIfNeeded","getMenuOpener","opener","getParentMenuItem","menu","closeMenuChain","outermost","parentMenu","leaveMenu","enterSubmenu","submenuId","submenu","leaveSubmenu","handleMenuKey","parentMenuItem","outOfSubmenuKey","intoSubmenuKey","currentTarget","setTabIndex","tabIndex","isSelectable","setFocusedMember","member","activateGroup","Group","raw","#searchValueCache","normalized","controlTargetId","shown","panel","clickToSelect","childRoles","childSelectedAttr","focusChild","selectFirst","controlsPanel","rovingTabStop","#affectsMembers","#memberCache","defaultSelected","allMembers","isSelected","controlTarget","#getControlTarget","#setPanelShown","activeMembers","holders","tabStop","laidOut","firstTop","#members","all","hasMember","addedNodes","removedNodes","#clickingRadio","isMenuItemRadio","selectable","multiSelect","singleSelect","targetSelectable","changed","isTarget","selecting","#setMemberSelected","#clickRadio","scrollTargets","affected","newTarget","targetAffected","targetRole","targetParent","#applySelection","#moveCursor","#moveFocus","#scrollTimer","elements","isMenu","#getCurrentTarget","fromMember","#getTypeAheadTarget","#getArrowTarget","inlineIndex","members","targetIndex","params","searchTerms","terms","_terms","searchValue","#getNormalizedSearchValue","term","#hiddenState","Select_button_group","invalid","Select_button","Menu_button","popupPositionBaseElement","Split_button","endIcon","popup","Checkbox_group","getToggleLabelAttrs","hasVisibleLabel","getModalLabelAttrs","labelledby","ariaLabelledby","hasCustomHeader","title","getAccessibleName","getLabelAboveText","showLabelAbove","Checkbox","labelAttrs","indeterminate","label_1","node_4","$.set_attribute","consequent_4","Spacer","Modal_close_button","closeIcon","startIcon","distance","after","Dialog","movable","showClose","showOk","showCancel","okLabel","okShortcuts","okDisabled","cancelLabel","cancelShortcuts","cancelDisabled","focusInput","onBeforeOk","modalComponent","okBusy","confirm","dragStart","recenter","onHeaderPointerDown","headerElement","control","pointerId","clientX","clientY","onHeaderPointerMove","buttons","startOffset","onHeaderPointerUp","dragHandlers","root_4","fragment_2","div_3","node_7","div_4","root_3","node_11","$1","consequent_5","consequent_6","Alert_dialog","Confirmation_dialog","Label_above","htmlFor","getTarget","MIRROR_STYLE_PROPERTIES","getFieldCaretRect","fieldRect","singleLine","mirror","mirrorRect","markerRects","markerRect","offsetTop","offsetLeft","offsetRight","EMOJI_TRIGGER_REGEX","WORD_SEPARATOR_REGEX","emojiList","parseEmojiData","emoji","shortcodes","keywords","line","otherShortcodes","getEmojiNameMatchRank","words","query","getEmojiAliasMatchRank","aliases","alias","getEmojiMatchRank","nameRank","aliasRank","getMatchCentrality","searchEmojis","normalizedQuery","rank","getEmojiInsertText","textAfterCaret","detectEmojiTrigger","textBeforeCaret","getSuggestionListPosition","spaceBelow","spaceAbove","flipped","listMaxHeight","anchorLeft","listWidth","Emoji_suggestions","listId","ariaOwner","trigger","selectedIndex","listElement","dismissedShortcodeId","rowHeight","listChrome","isOpen","newTrigger","moveSelection","selectHighlighted","row","paddingTop","paddingBottom","borderTopWidth","borderBottomWidth","reposition","Emoji_autocomplete","findTrigger","selectionStart","selectionEnd","getAnchorRect","insertEmoji","inserted","field","refresh","onBlur","EmojiSuggestions","Text_input","showInlineLabel","inputmode","monospace","debounce","useEmojiAutocomplete","inputId","labelAbove","debounceTimer","fireInput","handleInput","inputEvent","Emoji_autocomplete$1","classes_1","Prompt_dialog","textboxAttrs","Divider","getSwipeDirection","getSwipeOffset","sign","addSwipeSample","samples","sample","getSwipeVelocity","shouldDismissSwipe","velocity","Drawer","closeButton","swipeDismiss","swipe","swipeOffset","isPrimary","excluded","axis","onPointerMove","timeStamp","onPointerUp","dismiss","node_5","div_5","node_9","div_6","root_2","File_picker","accept","onSelect","onCancel","filePicker","input_1","files","Grid_body","expanded","collapsible","hasExpander","toggle","handleCaptionClick","element$1","Table_part","Grid_cell","Grid_col_header","sortOrder","handleSortButton","onClick","$.attachment","Grid_head","Grid_row","isUnselectableRow","_ariaSelected","focusSortButton","Grid","Listbox","filtered","_onChange","total","Option_group","Option","fallbackId","_value","_searchValue","wrap","registry","newValue","rendered","Menu","Menu_item","isPopupOpen","isPopupHovered","hoverTimer","hasItems","scheduleHoverChange","Menu_item_checkable","roleClass","Menu_item_checkbox","Menu_item_radio","Progressbar","percentage","Radio_group","Radio","isGroupReadOnly","isChecked","startPointerDrag","onEnd","onMove","resolveToPercent","trimmed","matchedPercent","env","containerSize","matchedPx","matchedViewport","viewportValue","viewportSize","resolveDefaultSize","defaultSize","resolvePaneConstraints","paneDef","minSize","maxSize","spreadSize","amount","adjustable","indexes","share","moved","constraints","sizes","diff","sum","getInitialSizes","specified","resolvedDefaults","totalSpecified","unspecifiedCount","allConstraints","fitted","getNewPaneSize","paneCount","sortByDomOrder","getPosition","order","getKey","clampResizeDelta","canGrow","constraintsBefore","sizeBefore","sizeAfter","constraintsAfter","canShrink","deltaPercent","getHandleRange","pairSize","pixelDeltaToPercent","percentDelta","isHorizontal","shareSpaceAmongPanes","neighbors","neighbor","exclude","getConstraints","getHandleKeyAction","Resizable_handle","showHandleBar","handleIndex","currentPaneSize","range","dragging","startScreenPos","startPaneSize","stopDrag","keyResizing","screenPos","screenX","screenY","onDragEnd","Resizable_pane_group","direction","_paneDefs","_handles","_savedSizes","measurePaneSpace","groupSize","handleSize","getSizeEnvironment","getPaneConstraints","paneIndex","reportedSizes","roundSizes","initSizes","reportSizes","rounded","resize","beforeIdx","afterIdx","prevBefore","prevAfter","toggleCollapse","minBefore","saved","shareSpace","syncOrder","paneIds","defs","def","newSizes","wanted","handleElements","handles","getElement","Resizable_pane","pane","sizeStyle","Infinite_scroll","itemChunkSize","loadedItemSize","spinner","loading","scrollContainer","isScrollContainerFinal","getScrollContainer","nearest","cubicOut","ox","oy","zoom","get_zoom","sx","sy","fx","fy","tx","ty","dx","dy","dsx","dsy","Search_bar","inputElement","Combobox","editable","filterThreshold","selectOnTypeAhead","comboboxElement","popupContent","idleHost","optionHost","listboxSlot","showFilter","pendingSearchTerms","matchedOptions","hasMatchingOptions","accessibleName","dispatchEntryChange","entryLabel","entryValue","_onSelect","detail","onTextInput","typeAhead","onComboboxKeyDown","getListbox","revealSelectedOption","listbox","$.CLASS","$2","node_10","div_7","Select","moveItem","newList","getKeyboardMoveTarget","getDropIndex","getDropTarget","dropIndex","fromIndex","Select_tags","optionMap","selectedValues","hasUnselectedOptions","wrapperElement","selectedValue","dragIndex","moveValue","newValues","moveAndFocus","span_2","span_3","toIndex","$$item","normalizeStep","getMaximumFractionDigits","mantissa","exponent","num","digits","getSliderSteps","_step","stepRatio","stepCount","stepWidth","barWidth","emptyArray","decimals","toLogicalX","physicalX","findNearestStepIndex","positionList","logicalX","getSliderKeyDirection","getSliderKeyTargetIndex","page","clampThumbIndex","otherIndex","sliderPositions","clampedIndex","valueIndex","getSliderCurrentIndex","valueList","decreasing","upperIndex","getNearestThumbIndex","position0","position1","diff0","diff1","Slider","sliderLabel","sliderLabels","optionLabels","multiThumb","base","getValueText","startX","startScreenX","targetValueIndex","setValue","_values","moveThumb","targetValue","screenDiff","updatePositions","value0","value1","styles_2","styles_3","styles_1","Switch","Table_cell","Table_row","Table","getIndicatorStyle","offsetWidth","offsetHeight","Tab_list","indicatorStyle","updateIndicator","selectionObserver","Tab_panel","Tab","modals","getHost","raiseBase","moveBase","host","moveBefore","getLane","lane","mountCount","onToggle","onClose","acquireBase","dialogs","releaseBase","Toast","toast","mql","setMode","toCodeBlock","longestRun","fence","parseCodeBlock","markdown","o$4","i$2","l$3","c$5","f$3","h$3","E$2","Y$2","et","dt","mt","Nt","wt","Mt","Ft","Kt","Rt","Wt","Ut","Jt","Vt","Vt$6","Yt","Xt","Gt","Xt$6","Qt","te$4","ni","mc","Yl","ge$3","uc","jl","Ml","Ql","rl","Xf","Fc","Cl","js","Bs","ii","Wu","Od","Mi","Ys","xl","Ne$2","Me$2","$e$2","tn","en","rn","sn","ln","un","gn","mn","xn","bn","In","kn","Tn","wn","xu","En","An","da","On","Mn","Fn","\"$\"","gs","Pn","Ln","Kn","zn","ci","ei","Rn","Wn","ro","oo","io","so","bo","Jn","jn","$n","Un","Vn","Hn","qn","Yn","Xn","Gn","Qn","Zn","eo","no","lo","co","ao","uo","fo","ho","zo","pa","go$1","To","ho$1","_l","go","_o","po","yo","hl","mo","xo","Il","vo","So","Ic","Co","So$1","wo$1","vc","ko","rh","oh","No","wo","Po","ih","Ws","Pc","xo$1","Eo","Mo","Oo","Fo","Ao","Ba","Do","Sl","Po$1","Qn$1","Io","Lo","Eo$1","Us","Ko","nu","Bo","sh","Al","Fd","Qf","Zd","Ro","Wo","jo","$o","Uo","ra","e$2","ya","Ds","nh","cg","ig","bu","Su","Is","Ec","vh","xc","Rc","Bc","Zc","ta","oa","Bo$1","zl","lh","Gd","Uf","Ks","Ls","th","os","eh","Rh","Jo","Vo","Ho","qo","zs","Yo","Xo","Go","Qo","Zo","tr","er","nr","or","rr","ir","lr","la","cr","ar","Yc","ur","qr","Yr","Xr","Gr","Qr","Zr","un$2","mn$1","rn$1","nn$2","xn$1","tn$1","ti","dh","hh","fh","Os","bd","Yd","Xd","Qd","oi","Oo$1","ri","si","mu","li","Hs","ai","ui","di","hi","fn$1","gi","_i","pi","gl","yi","mi","xi","vi","Si","Ni","bi","Ai","Ci","Oi","Pd","Id","Di","ki","Ti","Wd","wi","gc","Ei","Kl","Pi","Bl","Wh","Vi","Fi","Ph","Ih","jh","Lh","Ii","kd","Li","Ki","ng","tg","Gh","zi","Ah","Uh","Bi","Ri","Wi","Ji","Ps","ji","yc","Fl","qs","Zh","$i","Vh","Ui","Hi","qi","Yi","Xi","Dd","Gi","Qi","Ll","Zi","ts","ah","es","Dc","Oc","Mc","rs","ss","cs","as","us","fs","ds","_s","ps","ys","Es","Ul","rc","$s","bs","ic","fc","vs","Cs","Ss","su","ks","Ts","Ns","As","Ms","vu","Rs","Js","Vs","wc","xd","Xs","Gs","Qs","Zs","tl","nl","ol","il","Md","ul","fl","dl","gg","yl","ml","vl","Lu","bl","kl","Tl","Nl","wl","El","Ol","Dl","Pl","Rl","Wl","$l","dc","Jl","Vl","Hl","ql","Nu","Xl","Gl","tc","ec","nc","oc","cc","hc","_c","pc","bc","kc","Tc","Nc","Ac","Lc","Kc","zc","Wc","qc","Qc","jc","Gc","Xc","ea","ga","fa","aa","ia","sa","$c","Uc","Jc","Vc","Hc","na","ca","ua","_a","ma","Ca","xa","va","Sa","Du","Ia","La","Ra","Wa","Ka","za","ja","$a","tu","lf","eu","ou","yf","xf","Sf","Cf","Pf","ru","iu","ju","Vu","Rf","Hu","Lf","Ff","Pu","qu","ef","Tf","vf","mf","Nf","cf","pf","wf","$u","Bf","zf","Ed","uf","Nd","If","tf","Uu","sf","Fu","cu","uu","au","Mu","_u","Ru","ku","lu","fu","du","hu","gu","pu","yu","Tu","Cu","wu","Eu","Au","Ou","Ch","Iu","Ku","zd","zu","Bu","Ju","Zt$5","Kf","Yu","Xu","Gu","af","Qu","Zu","Ad","of","Cd","gd","ff","df","hf","gf","a$2","_f","m$3","pd","jf","md","bf","kf","d$5","u$2","g$3","Vf","Ef","Af","Of","Mf","Df","Wf","$f","Jf","Hf","qf","Yf","uh","Gf","Sd","nd","Hd","Ud","$d","qd","Ld","ld","cd","sd","Qh","Td","ad","hd","dd","Zf","td","ed","ud","fd","_d","yd","og","rg","vd","wd","Kd","Bd","Rd","jd","Jd","Vd","ch","gh","_h","ph","yh","mh","xh","Sh","kh","Th","Nh","eg","wh","Oh","Eh","Mh","Dh","Kh","zh","Bh","$h","qh","Jh","Hh","Yh","sg","lg","ag","ug","hg","_g","pg","fe$3","r$1","h$2","g$2","t$2","f$1","b$1","g$1","p$1","n$1","Pt$6","et$2","St$5","pt$5","Rt$5","Ht$5","ge$2","he$3","Se$2","Ce$2","Lt$4","Cn","Dn$1","Gt$3","ln$2","sn$2","ft$2","$t$4","Fe$1","se$2","yt$3","on$1","pt$3","Nt$4","Dt$4","$t$3","Kt$3","Wt$3","fe$1","ge$1","pe$1","Pt$2","kn$1","an","cn","dn","Tt$3","Ft$1","wn$1","Rt$1","UNESCAPED_LOOKBEHIND","countBackslashesBefore","WHITESPACE_OR_PUNCTUATION","WHITESPACE_OR_PUNCTUATION_REGEX","isWordChar","THEMATIC_BREAK","SETEXT_UNDERLINE","ORDERED_LIST_NUMBER","LIST_MARKER","MARKER_END","TAG_SPACE","HTML_TAG_SOURCE","UNESCAPED_LT_SOURCE","INLINE_HTML_REGEX","UNSAFE_SCHEME_SOURCE","scheme","AUTOLINK_REGEX","FOOTNOTE_REFERENCE_REGEX","NAMED_CHARACTER_REFERENCE_REGEX","LINE_FENCE_REGEX","findCodeBlocks","blocks","openBlock","contentIndent","codeBlockCache","getCodeBlocks","lastSplit","lineCacheDepth","withLineCache","steps","splitLines","OPENING_FENCE_REGEX","parseOpeningFence","indentedFence","mapOutsideCodeBlocks","flush","mapLinesOutsideCodeBlocks","codeLines","isInListItemCodeBlock","closingFenceLengthCache","hasClosingFence","lengths","CODE","LEXICAL_CODE","exportChildren","openingLine","startLineIndex","startMatch","isClosed","blankLineCount","codeNode","textNode","isCodeNode","isTextNode","isWhitespaceCode","getFormatExportNode","getView","isLexicalEmptyParagraph","isParagraphNode","getParagraphLineBreaks","paragraph","isRootNode","LEADING_INLINE_CODE","exportNode","hasExtraPadding","exportFormat","createTextNode","FORMAT_DELIMITERS","DELIMITER_REGEX","getExportedText","getOuterFormats","isSeparated","isLineBreakNode","getChar","stripDelimiters","delimiters","delimiter","closing","LINK","LEXICAL_LINK","isLinkNode","linkNode","stripped","TASK_LIST_ITEM_REGEX","TASK_LIST","CHECK_LIST","isImport","EDITOR_THEME","AVAILABLE_BUTTONS","TEXT_FORMAT_BUTTON_TYPES","INLINE_BUTTON_TYPES","BLOCK_BUTTON_TYPES","HTML_ONLY_BUTTON_TYPES","isHtmlOnlyButton","HTML_ONLY_FORMAT_TYPES","OPTIONAL_BUTTON_TYPES","DEFAULT_BUTTON_TYPES","LIST_TYPES","INSERT_UNORDERED_LIST_COMMAND","INSERT_ORDERED_LIST_COMMAND","INSERT_CHECK_LIST_COMMAND","NODE_MAP","HeadingNode","ListNode","ListItemNode","QuoteNode","CodeNode","CodeHighlightNode","LinkNode","TRANSFORMER_MAP","HEADING","UNORDERED_LIST","ORDERED_LIST","QUOTE","INLINE_CODE","BOLD_STAR","BOLD_UNDERSCORE","BOLD_ITALIC_STAR","BOLD_ITALIC_UNDERSCORE","ITALIC_UNDERSCORE","ITALIC_STAR","STRIKETHROUGH","DISABLED_MARKDOWN_TAGS","OPEN_LINK_EDITOR_COMMAND","createCommand","ALIGNMENT_OPTIONS","DECORATOR_INTERACTIVE_SELECTOR","isStaticDecoratorContent","decorator","interactive","$moveCaretIntoBlock","selection","getSelection","isRangeSelection","getRoot","isElementNode","createParagraphNode","updateNodeWithFocus","editor","getNearestNodeFromDOMNode","placeCaretAfterDecorator","isDecoratorNode","placeCaretAtBlockEnd","handleEditorMouseDown","focusEditor","_n","hn","pn","Sn","Ft$3","gn$1","Ht$6","IndexedDB","#database","#databaseName","databaseName","#storeName","storeName","#storeOptions","#indexes","#openDatabase","request","database","store","keyPath","#getDatabase","#isUpgradeNeeded","#query","#databasePromise","transaction","mode","getRequest","keysRequest","#getSource","#search","cursor","safeParse","LocalStorage","LANGUAGES","\"id\"","\"name\"","\"aliases\"","THEMES","\"displayName\"","\"type\"","DATABASE_NAME","STORE_NAME","purgePromise","enabled","getDatabase","purgeStaleVersions","stale","db","getCachedPayload","cachePayload","SHIKI_CDN_BASE_URL","UI_CDN_BASE_URL","getEngineURL","getLanguageURL","getThemeURL","loaders","getCodeHighlighterLoaders","getBackgroundUpdateTags","tags","getCodeTheme","theme","onCodeThemeChange","media","observeCodeTheme","PLAIN_LANGUAGES","DIFF_LANGUAGE_REGEX","engine","highlighter","engineUnavailable","getDiffedLanguage","isPlainLanguage","isEngineLoaded","isEngineUnavailable","isCodeLanguageLoaded","pendingLoads","loadOnce","pendingLoads$1","onLoaded","loadEngine","resolvePayload","module","load","loadAsset","findLanguage","normalizeCodeLanguage","loadCodeLanguage","isCodeThemeLoaded","loadCodeTheme","tokenizeCode","diffedLanguage","getTokenStyle","getHighlightTheme","resolvedTheme","highlightCodeToHTML","highlightCodeToTokens","tokens","color","fg","fontStyle","decorateTaskList","decorateTaskListItem","isListNode","checkbox","isTaskListCheckbox","dropElement","HTML_TASK_LIST_IMPORT_MAP","isPreformatted","TEXT_FORMAT_TAGS","PARAGRAPH_ENDING_TAGS","isParagraphEndingElement","isHTMLElement","findEdgeTextNode","isDOMTextNode","TEXT_FORMAT_TAG_NAMES","isBlank","splitParagraphAroundBlocks","newParagraph","ALLOWED_ATTRIBUTES","ALIGNABLE_TAGS","removeExtraAttributes","allowedAttributes","textAlign","exportElementNode","newElement","exportParagraphNode","TableCellNode","exportTextNode","exportCodeNode","TABLE_STRUCTURE_SELECTOR","exportTableNode","colgroup","exportDecoratedElementNode","decorate","HTML_EXPORT_MAP","TextNode","TabNode","ParagraphNode","HorizontalRuleNode","TableNode","exportHtml","generateHtmlFromNodes","editorComponents","componentConversionMaps","getComponentConversionMap","elementComponents","getElementComponent","isInlineComponentElement","getEditor","getCodeLanguage","getTextWithLineBreaks","convertPreElement","createCodeNode","findContentInLine","parentElement","display","isInlineDomNode","descendant","convertTextNode","textContent","domNode","drop","previousText","isEndOfLine","HTML_IMPORT_MAP","HTML_CODE_IMPORT_MAP","PASSTHROUGH_TAGS","DOCUMENT_TAGS","getComponentOnlyTagNames","components","componentNodes","otherTagNames","klass","findUnsupportedNode","componentOnlyTagNames","findWithin","getHtmlConfig","hasCodeBlock","hasTaskList","refreshCodeNode","getNodeByKey","codeNodeKey","refreshers","getCodeNodeRefresher","refresher","mapTokensToLexicalStructure","lineIndex","createLineBreakNode","tokenIndex","prefixes","prefixTypes","prefixIndex","createCodeHighlightNode","createTabNode","getHighlightNodes","shikiTokenizer","plainifyCodeContent","updateCodeGutter","codeElement","gutter","isEqual","isCodeHighlightNode","nodeA","nodeB","isTabNode","getDiffRange","leadingMatch","prevNodes","nextNodes","prevNodesLength","nextNodesLength","maxTrailingMatch","trailingMatch","updateAndRetainSelection","nodeKey","updateFn","anchorNode","anchorOffset","isNewLineAnchor","textOffset","node_","textContentSize","codeNodeTransform","transformState","tokenizer","isPlain","inFlight","nodesCurrentlyHighlighting","staleNode","highlightNodes","nodesForReplacement","textNodeTransform","registerCodeHighlighting","mutations","registerCodeIndentation","mergeRegister","HR","isHorizontalRuleNode","createHorizontalRuleNode","BLOCK_SYNTAX","DEFINITION_SYNTAX","RAW_SYNTAX_REGEX","rawSyntaxState","createState","getImportedRawSyntax","getState","getRawSyntax","RAW_SYNTAX","RAW_HTML","$insertBlockNode","getPreviousSelection","insertNodeToNearestRoot","$insertHorizontalRule","rule","parseTableSize","createTableMarkdown","columns","rows","isRightToLeftTable","table","cell","$getTableCell","findMatchingParent","isTableCellNode","$getSelectedTableCellKey","isTableSelection","$insertTable","findTableNode","createTableNodeWithDimensions","$ensureParagraphAfterTable","$normalizeTableHeaders","isTableRowNode","headerState","rowIndex","TableCellHeaderStates","$moveCaretOutOfTable","isDeleteAction","$selectionSpansTable","point","$runTableAction","cellKey","findCodeSpans","runs","spans","mapCodeSpans","piece","outside","inside","BLOCK_SYNTAX_REGEX","ORDERED_LIST_ITEM_REGEX","escapeBlockSyntax","unescapeText","underscores","REFERENCED_CHARS","EMAIL_AUTOLINK_START_REGEX","unescapeCharacterReferences","isAtLineEnd","isInLink","escapeNamedCharacterReferences","isItalicWithinWord","isItalicText","firstText","lastText","BLOCK_SYNTAX_ESCAPE","rawSyntax","TABLE_ROW_REG_EXP","TABLE_ROW_DIVIDER_REG_EXP","ALIGNMENT_DELIMITERS","getColumnAlignment","CELL_LINE_BREAK_REG_EXP","UNESCAPED_PIPE_REG_EXP","getTableColumnsSize","createTableCell","createTableCellNode","transformers","mapToTableCells","exportTableRow","rowOutput","cells","isHeaderRow","convertToMarkdownString","$applyHeaderRow","isTableNode","lastRow","alignments","$takePrecedingRows","firstChild","previousSibling","$createTable","createTableNode","tableRow","createTableRowNode","columnsSize","$insertImportedTable","headerRow","headerCells","hasHeaderRow","createTableTransformer","cellTransformers","TRANSFORMERS","transformer","exportTransformers","TableRowNode","matchCells","SETEXT_UNDERLINE_REGEX","ATX_HEADING_REGEX","THEMATIC_BREAK_REGEX","HTML_BLOCK_CONDITION_SOURCES","HTML_BLOCK_START_REGEX","HTML_BLOCK_CONDITIONS","STANDALONE_HTML_TAG_REGEX","NON_PARAGRAPH_LINE_REGEX","TABLE_ROW_LINE_REGEX","SINGLE_LINE_BLOCK_REGEX","PARAGRAPH_INTERRUPTION_REGEX","isParagraphLine","endsParagraph","interruptsParagraph","findHtmlBlockLines","isInParagraph","isBlankLine","convertTildeFences","closed","longestFence","backticks","indent","SETEXT_UNDERLINE_MULTILINE_REGEX","convertSetextHeadings","paragraphLine","padBlankBlockquoteLines","trimBlankBlockquoteLines","getBlockquotePrefix","createMultilineFormattingRegex","edgeUnit","isWithinWordAllowed","opening","lineBreak","MULTILINE_FORMATTING_REGEXES","getBlockquoteLevel","splitFormattedLines","quote","isInSameBlockquote","level","hasMultilineFormatting","regex","MULTILINE_LINK_REGEX","splitMultilineLinks","codeSpans","matchEnd","linkText","lastLine","lineText","lineEnd","SPAN_BOUNDARY_REGEX","splitCodeSpan","codeSpan","fenceLength","padding","splitMultilineSpans","htmlBlockLines","quotes","contents","paragraphs","paragraphLines","HAS_MULTILINE_LINK_TEXT_REGEX","hasLineBreakInSpan","splitMultilineFormatting","formattedText","GLOBAL_INLINE_HTML_REGEX","markLineEndBackslashes","hasHardLineBreak","backslashes","MARKER_BACKSLASH_REGEX","markMarkersNextToBackslashes","MARKER_UNICODE_PUNCTUATION_REGEX","markMarkersNextToUnicodePunctuation","markCodeSpanWhitespace","markHtml","addImportPlaceholders","removeImportPlaceholders","convertBlockSyntax","fencedValue","hasCodeBlocks","hasHeadings","toLexicalMarkdown","splitValue","markedValue","$getSelectedAlignment","getNearestElementNode","ElementNode","getNearestNodeOfType","getSelectionTypes","inlineTypes","isListItemNode","blockType","isHeadingNode","listType","isQuoteNode","mergeUnregisters","unregisters","handlers","unregister","exportMarkdown","enabledTransformers","exportValue","registerValueExport","updateCount","contentChanged","lastValue","disposed","scheduled","triggerExport","onExport","dirtyElements","dirtyLeaves","currentCount","getComponentMarkdown","createMarkdown","createEditor","newNode","createNode","isInlineComponent","cleanMatch","clean","skipHtmlBlockPlaceholder","isLineStart","cleanReplaceArg","removePlaceholdersFromMatch","overrides","handleImportAfterStartMatch","importRegExp","regExpStart","regExpEnd","replace","limitToSingleLine","getInlineContent","$joinIntoSingleParagraph","lastChar","$replaceLineBreak","space","isSameLink","registerSingleLine","KEY_ENTER_COMMAND","INSERT_PARAGRAPH_COMMAND","INSERT_LINE_BREAK_COMMAND","LineBreakNode","RootNode","normalizeConfig","getEditorSetup","enabledButtons","isCodeEditor","multiline","registerCodeEditorCommands","DELETE_CHARACTER_COMMAND","isBackward","defaultLanguage","registerListCommands","enabledLists","command","wt$3","handleListInsertParagraph","registerCheckList","registerTabIndentation","onKeydown","OUTDENT_CONTENT_COMMAND","INDENT_CONTENT_COMMAND","$removeFormat","registerFormatGuard","FORMAT_TEXT_COMMAND","registerTaskListGuard","registerGuards","escapeRegExp","truncate","chars","ellipsis","stripSlashes","sharedDOMParser","stripTags","isURL","SAFE_LINK_URL_SCHEMES","isSafeLinkURL","normalizedURL","url","registerLinkCommands","Xt$5","TOGGLE_LINK_COMMAND","Ut$3","PASTE_COMMAND","objectKlassEquals","clipboardText","$findSelectedLink","getSelectionRect","createDOMRange","getLinkAnchorRect","loadCodeHighlighter","WHITESPACE","PUNCTUATION","isFlanking","primary","secondary","isLeft","canEmphasis","adjacent","findDelimiters","spanIndex","canOpen","canClose","pairDelimiters","openersBottom","closer","bottomKey","openIndex","canPair","maxLength","createSplitIndexFinder","regexes","textMatchTransformers","findSplitIndex","wrapsCode","outer","addCodeSpanSplit","getEndIndex","splitIndex","removePlaceholders","newText","getCodeBlockLanguages","prepareMarkdown","$importMarkdown","preparedValue","toRoot","generateNodesFromMarkdownString","hasPlaceholders","latestImports","importValue","importId","isSuperseded","ex","$import","formatName","$export","convertMarkdownToLexical","convertHtmlToLexical","unsupportedNode","Cn$1","pasteMarkdown","PASTE_AS_MARKDOWN_TIMEOUT","getPasteAsMarkdownShortcuts","registerPasteAsMarkdown","pasteAsMarkdown","KEY_DOWN_COMMAND","isClipboardEvent","HISTORY_MAX_DEPTH","pickForButtons","createEditorExtension","defineExtension","CodeExtension","hasTable","configExtension","TableExtension","hasHorizontalRule","HorizontalRuleExtension","hasBlockSyntax","getEnabledTransformers","componentTransformers","registerEditorListeners","unregisterFeatures","registerRichText","registerDragonSupport","registerHistory","createEmptyHistoryState","useMarkdownShortcuts","registerMarkdownShortcuts","hasLink","valueExport","unregisterInput","initEditor","setup","buildEditorFromExtensions","Lexical_root","editorStore","lexicalRoot","exportedValue","hasConverterError","useRichText","inputValue","onMouseDown","isOtherDialog","pressedComponentElement","onComponentMouseDown","checkComponentFocus","relatedTarget","onRootFocusOut","dispose","inputValueListeners","createEditorStore","editorId","initialized","textArea","toolbarHeight","componentHasFocus","showConverterError","runningOperations","lastImport","importCount","importing","setConverterError","convertToLexical","originalValue","exported","hasChange","done","syncEditorProps","appliedValue","latestValue","setPending","getInputValue","Code_language_switcher","codeLanguages","selectedLanguage","selectedKey","getCodeNode","blockNodeKey","changeLanguage","endOperation","Toolbar","Toolbar_wrapper","observeHeight","toolbar","Code_editor","showLanguageSwitcher","ariaDescribedby","ariaLabelAttr","ariaLabelledbyAttr","ariaDescribedbyAttr","_lang","_code","getHighlightedTokens","highlight","Text_area","autoResize","textareaId","cloneValue","highlightedTokens","cloneElement","textarea","onScroll","textarea_1","$.index","classes_2","domSelection","registerCommands","whileOpen","KEY_ARROW_DOWN_COMMAND","KEY_ARROW_UP_COMMAND","KEY_TAB_COMMAND","KEY_ESCAPE_COMMAND","editorState","INLINE_MARKERS","BLOCK_PREFIX_REGEX","CODE_FENCE_REGEX","getLineRange","lineStart","lineEndIndex","getStartLineIndex","findCodeBlock","getBlockType","hashes","toggleInlineFormat","leading","trailing","caret","setBlockType","codeBlock","blockStart","blockEnd","contentStart","edit","oldLines","getPrefix","newLines","oldPrefix","newPrefix","oldLineStart","oldContentStart","oldLineEnd","newContentStart","insertLink","insertMarkdown","trimmedStart","trimmedEnd","getRawTextState","focusTextArea","deadline","isRawTextEditable","readOnly","applyRawTextEdit","editRawText","getEdit","registerRawTextShortcut","insertComponent","LINE_BREAK_REGEX","joinLines","registerRawTextSingleLine","onBeforeInput","inputType","onInput","joined","SELECTION_EVENT_TYPES","registerRawTextSelection","onChange","runEditorAction","rich","refocusEditor","insertEditorComponent","Floating_link_editor","currentLink","hasFocus","dismissedLinkKey","editTarget","openInNewTab","initialOpenInNewTab","canSetTarget","popupHeight","editing","isValidURL","startEditing","initialURL","newTab","stopEditing","onOpenCommand","findSelectedLink","applyURL","newURL","cancelEditing","removeLink","onInputKeyDown","isWithin","node_6","fragment_6","MAX_CLOSE_FRAMES","waitForMenuToClose","frames","Table_action_menu","ITEM_GROUPS","runAction","labelKey","$$array","Table_cell_menu_button","getWrapper","cellRect","tableRect","rootRect","wrapperRect","focusTimer","updateFocus","getSelectedTableCellKey","isObject","toRaw","obj","isObjectArray","unique","getCodeFenceLanguages","createSourceHighlighter","codeTheme","loadCount","isActive","getSource","Button_group","Align_menu_button","alignment","align","FORMAT_ELEMENT_COMMAND","Format_text_button","selectionTypeMatches","SHORTCUT_KEYS","Insert_horizontal_rule_button","insert","Insert_item_button","Insert_link_button","hasAnchor","anchorURL","anchorText","openCreateDialog","createLink","getTextContent","onButtonClick","onDialogClose","_selection","createRangeSelection","_registerCommand","Insert_menu_button","computed_const","getInputMode","fractional","decimalSeparatorCache","getDecimalSeparator","normalizeNumber","parseNumber","toNumber","isAtMin","isAtMax","stepNumber","maximumFractionDigits","nearestPosition","isOnGrid","newPosition","isInvalidNumber","Number_input","edited","stepEnabled","stepSize","isFractional","rangeDescription","hasMin","hasMax","describedBy","numberValue","isMin","isMax","stepValue","newInputValue","decrease","increase","$3","$4","canStep","Insert_table_button","rowCount","isValid","rowSize","columnSize","Toggle_block_menu_item","NODE_FACTORIES","createQuoteNode","changeBlockType","headingLevel","createHeadingNode","ee$4","Text_editor_toolbar","blockLevelButtons","isHtml","canFormat","canUseHtmlOnlyButtons","$$d","canAlign","tableCellKey","inMarkdownTable","menuitems","hasInsertButtons","canChangeBlock","inlineLevelButtons","node_14","node_17","consequent_7","consequent_8","node_20","consequent_9","consequent_10","consequent_11","node_22","consequent_12","Text_editor","modes","minimal","usePlainText","textAreaDir","highlightSource","Color_input","handleClick","Date_time_input","Masked_input","Password_input","Secret_input","Tree_item","_valueType","handleChange","handleExpand","handleSelect","handleEvents","alternate_2","ITEM_SELECTOR","activateTree","Tree","selectionFollowsFocus","expandOnSelect","walk","allItems","activeItems","multi","anchorIndex","additive","parentItem","currentItem","backwardKey","forwardKey","newItem","childItem","TEXT_INPUT_TYPES","shouldAllowContextMenu","App_shell","fontLoaded","mediaQuery","applyTheme","dataset","fontTimer","Font_links","Empty_state","Visibility_observer","eager","en_US_default$1","\"ok\"","\"cancel\"","\"close\"","\"clear\"","\"insert\"","\"update\"","\"remove\"","\"collapse\"","\"expand\"","\"dismiss\"","\"alert\"","\"error\"","\"warning\"","\"info\"","\"success\"","\"role_descriptions\"","\"disclosure\"","\"option_group\"","\"menu_item_group\"","\"checkbox_group\"","\"table_head\"","\"table_body\"","\"table_foot\"","\"grid_head\"","\"grid_body\"","\"grid_foot\"","\"emoji_suggestions\"","\"calendar\"","\"year\"","\"previous_decade\"","\"next_decade\"","\"month\"","\"previous_month\"","\"next_month\"","\"today\"","\"copy_button\"","\"copy\"","\"copied\"","\"split_button\"","\"x_options\"","\"more_options\"","\"combobox\"","\"select_an_option\"","\"filter_options\"","\"no_matching_options\"","\"number_input\"","\"increase\"","\"decrease\"","\"range\"","\"min\"","\"max\"","\"password_input\"","\"show_password\"","\"hide_password\"","\"secret_input\"","\"show_secret\"","\"hide_secret\"","\"select_tags\"","\"selected_options\"","\"remove_x\"","\"text_editor\"","\"code_editor\"","\"text_style_options\"","\"show_text_style_options\"","\"paragraph\"","\"heading_1\"","\"heading_2\"","\"heading_3\"","\"heading_4\"","\"heading_5\"","\"heading_6\"","\"bulleted_list\"","\"numbered_list\"","\"task_list\"","\"blockquote\"","\"code_block\"","\"bold\"","\"italic\"","\"underline\"","\"strikethrough\"","\"code\"","\"link\"","\"insert_link\"","\"edit_link\"","\"remove_link\"","\"text\"","\"url\"","\"open_in_new_tab\"","\"insert_table\"","\"rows\"","\"columns\"","\"table_options\"","\"show_table_options\"","\"insert_row_above\"","\"insert_row_below\"","\"insert_column_left\"","\"insert_column_right\"","\"delete_row\"","\"delete_column\"","\"delete_table\"","\"insert_horizontal_rule\"","\"alignment_options\"","\"show_alignment_options\"","\"align_left\"","\"align_center\"","\"align_right\"","\"align_justify\"","\"edit_in_markdown\"","\"edit_in_html\"","\"converter_error\"","\"language\"","\"plain_text\"","getBlobRegex","filePathRegEx","textFileTypes","isTextFileType","getPathInfo","dirname","basename","filename","extension","isValidFileType","specifiers","fileName","file","specifier","rawSpecifier","subtype","scanFiles","getFile","readEntries","reader","readEntry","readAsText","toBlob","encodeBase64","blob","decodeBase64","base64","typeExtensions","getExtensionForType","essence","mapped","saveFile","blobURL","equal","DEV$1","\"DEV\"","DEV_SITE_URL","DEV","VITE_SITE_URL","SUPPORTED_TYPES","staticKeys","$.snapshot","createRawState","createDeepState","createDerivedState","createStableDerivedState","requestAnswer","answer","createRootEffect","$.effect_root","watch","getDependencies","watchAsync","onResult","syncValues","syncedInput","updateInput","toInput","getInput","setInput","updateValue","toValue","cmsConfig","parsedCmsConfig","rawCmsConfig","cmsConfigVersion","cmsConfigErrors","cmsConfigLoaded","collectors","isEntryCollection","isFileCollection","isSingletonCollection","isArrayFileCollection","isValidCollection","isValidCollectionFile","getValidCollectionFiles","BUILTIN_FIELD_TYPES","SIMPLE_VALUE_FIELD_TYPES","STRING_VALUE_FIELD_TYPES","MEDIA_FIELD_TYPES","RICH_TEXT_FIELD_TYPES","TEXT_FIELD_TYPES","MULTI_VALUE_FIELD_TYPES","MIN_MAX_VALUE_FIELD_TYPES","read_methods","set_like_methods","SvelteSet","#size","#init","#update_version","set_proto","#sources","deleted","SvelteMap","#read_all","callbackfn","this_arg","callbackFn","prev_res","v_reactions","customComponentRegistry","customPageRegistry","customFieldTypeRegistry","customFileFormatRegistry","customPreviewStyleRegistry","customPreviewTemplateRegistry","customStringTransformationRegistry","eventHookRegistry","TEMPLATE_TAG_REGEX","TEMPLATE_TAG_REPLACE_REGEX","DATE_TIME_FIELDS","DATE_TIME_TEMPLATE_REGEX","FIELD_TAG_PREFIX_REGEX","DEFAULT_TRANSFORMATION_REGEX","UUID_TYPES","getAdjacentChar","replaceTemplateTags","searchIndex","quoteState","nextChar","closeIndex","unescape","replacer","splitTemplateTags","getTemplateTags","hasTemplateTags","stripFieldTagPrefix","getFileNameParts","dotIndex","localeSuffixes","getFileNameLocaleSuffixes","_i18n","getTemplatePattern","wildcard","DEFAULT_INDEX_FILE_NAME","indexFileCacheMap","getIndexFileName","indexFile","getIndexFile","appLocale","isCollectionIndexFilePath","isCollectionIndexFile","MARKDOWN_EXTENSIONS","FORMAT_EXTENSION_MAP","EXTENSION_FORMAT_MAP","FRONTMATTER_DELIMITER_MAP","FRONTMATTER_FORMATS","BUILTIN_FILE_FORMATS","TOML_FORMATS","FORMAT_SYNTAX_MAP","getFormatSyntax","isNonEmptyString","isHttpURL","escapeAttr","HTML_ESCAPE_MAP","escapeHTML","LINK_SANITIZE_OPTIONS","makeLink","href","sanitizeInlineMarkdown","parseInline","allowedTags","allowedAttr","sanitizeHelpText","DEFAULT_INDEX_FILE_NAMES","CONTENT_EXTENSIONS","normalizeIndexFileName","nestedFilterPath","getNestedConfig","rawCollection","summary","subfolders","hasNestedEntries","getMetaPathConfig","getNestedIndexFileName","getSharedEntryFileName","stripIndexFileName","indexFileName","slug","usesCustomEntryPath","currentPath","isNew","originalPath","getEntryDirPath","subPath","getNameInFolder","dirPath","isDescendantPath","isNestedFolder","basePath","filterNestedEntries","getOrCreate","touchEntry","setEntry","createLRUMap","getOrCreateBounded","shareInFlight","getOrCreateAsync","memoizeOnSource","build","memoizeOnSources","getSources","LOCALE_FOLDER_REGEX","hasLocalePlaceholder","isValidLocaleFolderPath","folderPath","omitLocalePlaceholder","canOmitLocalePlaceholder","fillLocalePlaceholder","omitLocale","getLocaleFolderPattern","localeFolderMatcher","localeFolderPrefixRegExpCache","stripLocaleFolderPath","filePath","LANG_FORMATTER_OPTIONS","getCanonicalLocale","canonicalLocale","getDirection","displayNamesCache","getLocaleLabel","displayLocale","formatterOptions","firstLetter","listFormatterCache","getListFormatter","effectiveOptions","getLocalePath","omitDefaultLocaleFromFilePath","defaultLocale","detectFileExtension","detectFileFormat","getFilePathMatcher","escapedIndexFileName","separateIndex","indexSuffix","indexAlternative","entryMatcher","nestedDepth","fileMatcher","remainingDepth","entrySuffix","getEntryPathRegEx","joinedLocales","allLocales","joinedNonDefaultLocales","localeMatcher","localeFileMatcher","localeInBasePath","basePathMatcher","entryExtension","indexExtension","indexFileExtension","getSuffixMatcher","localeMatcherCopy","i18nMultiFile","ext","i18nMultiRootFolder","i18nMultiFolder","getFrontMatterDelimiters","getIndexFileFormat","_indexExtension","_indexFormat","indexFormat","entryFormat","getFileConfig","dataFile","_extension","_format","_delimiter","bodyField","yamlQuote","_isEntryCollection","arrayFile","__extension","__format","_isFolderCollection","folder","indexFileFormat","resolveFileConfig","collectionFile","isIndexFile","_file","I18N_STRUCTURES","LOCALE_ROOT_FOLDER_STRUCTURES","DEFAULT_CANONICAL_SLUG","mergeI18nConfigs","siteConfig","collectionI18n","getOmitDefaultLocaleOption","DEFAULT_I18N_CONFIG","getDraftI18nConfig","draft","determineStructure","defaultStructure","createStructureMap","i18nEnabled","structure","usesSingleFileStructure","i18nSingleFile","i18nSingleFileDefaultRoot","usesMultiFileStructure","determineDefaultLocale","specifiedDefault","determineInitialLocales","initialLocalesConfig","determineOmitDefaultLocale","omitDefaultLocale","structureMap","normalizeI18nConfig","specifiedDefaultLocale","saveAllLocalesConfig","canonicalSlugConfig","omitDefaultLocaleLegacy","omitDefaultLocaleFromPreviewPath","canonicalSlugKey","canonicalSlugTemplate","saveAllLocales","initialLocales","hasMultipleInMediaLibraries","mediaLibraries","libs","lib","hasMultipleInMediaLibrary","mediaLibrary","isMultiple","_cmsConfig","fieldConfig","selectedCollection","collectionCacheMap","getValidCollections","collections","getFirstCollection","getThumbnailFieldNames","thumbnail","fields","fieldType","parseEntryCollection","parseFileCollection","__i18n","__file","getSingletonCollection","singletons","getCollection","entryCollection","fileCollection","getCollectionLabel","singularLabel","_type","useSingular","getCollectionIndex","collectionName","isHighSurrogate","codePoint","isLowSurrogate","charLength","curByteLength","segment","getLength","byteLength","prevCodePoint","require_truncate","require_browser$1","require_browser","illegalRe","controlRe","reservedRe","windowsReservedRe","replaceTrailingDotsAndSpaces","replacement","sanitized","decodeSafely","decoder","sequence","decodeURISafely","uri","decodeURIComponentSafely","encodeURLSafely","encodeRFC3986","encodePathSegments","encodeSegment","trimTrailingSlashes","createPathRegEx","encodeFilePath","hasAtPrefix","foldFileName","foldPath","stripLeadingDotSlash","normalizeFolderPath","renameIfNeeded","foldedName","foldedNames","otherNames","otherName","hasExtension","highest","WINDOWS_RESERVED_NAME_REGEX","renameReservedFileName","sanitizeFileName","normalizedName","EQUIVALENT_FILE_EXTENSIONS","isEquivalentFileExtension","_b","createPath","segments","getDirName","getBaseName","stripPathPrefix","sanitizePath","resolvePath","nameFound","getBlob","getByteSize","computeGitHash","gitHashCache","getGitHash","readBlobAsFile","getEntryDisplayLocale","getEntryLocaleFile","getEntryPaths","includePrevious","getEntryDirName","fullPathRegEx","entryPath","_basePath","FOLDER_PATH_REGEX","isSharedIndexFile","getOwnedEntryFolderPath","entryFilePath","lastSubPathSegment","getEntryAssetFolderPath","internalPath","getExistingEntryAssetFolderPath","entryFolderPath","allAssets","publishedAssets","workflow","selectedAssets","selectedAssetPathSet","asset","focusedAsset","selectedOrFocusedAssets","overlaidAsset","uploadingAssets","editingAsset","renamingAsset","assetMoveRequest","draggedFiles","getAssetPathMap","_allAssets","partOptions","formatterCache","getFormatter","timeZone","getDateTimeParts","UNSAFE_UNICODE_SLUG_CHARS_REGEX","UNSAFE_ASCII_SLUG_CHARS_REGEX","createLazyModule","loadPromise","loaded","notLoadedMessage","scriptURL","getUnpkgURL","libVersion","loadModule","__vitePreload","library","getLeafletMarkerIconURL","NPM_CDN_HOSTS","parseUnpinnedScriptURL","parsedURL","packagePath","versionSpec","pinScriptURL","pinnedURL","getScriptVersionSpec","getChunkURLs","devChunkLoaders","loadChunk","lastError","COMBINING_MARKS_REGEX","transliterator","loadTransliterator","transliterateString","decomposed","LEADING_DOTS_REGEX","TRAILING_DOTS_REGEX","UNSAFE_CHARS_REGEXES","slugReplacementRegexCache","getReplacementRegexes","escapedReplacement","getTrailingDotsPattern","trim","trimSlugEnd","getSlugTimeZone","slugify","maxLengthParam","cleanAccents","transliterateLocale","sanitizeReplacement","maxLengthOption","trimReplacement","encoding","leadingDotsPattern","cachedSlugRegexes","trailingDotsPattern","lowercase","getNewFolderName","validateNewFolderName","trimmedName","folderName","isReserved","takenNames","taken","characterEntitiesLegacy","characterReferenceInvalid","isDecimal","character","isHexadecimal","isAlphabetical","isAlphanumerical","decodeNamedCharacterReference","characterReference","parseEntities","settings","additional","queue","column","following","begin","characterReferenceCharacters","characters","test","terminated","namedReference","reference","warning","reason","referenceCode","prohibited","disallowed","resolveNestedTemplateValues","resolveTag","innerTag","processNestedTemplates","transformations","newArgs","hasChanges","resolvedDefaultValue","truthyValue","resolvedTruthyValue","falsyValue","resolvedFalsyValue","newCustomArgs","customArgs","exports","this$6","this$5","this$4","this$3","TIMEZONE_ENUM","configCacheMap","isCustomTimeZone","parseDateTimeConfig","dateFormat","timeFormat","pickerUTC","inputTimeZone","outputUTC","normalizedInputTimeZone","dateFormatStr","timeFormatStr","dateOnly","timeOnly","defaultMax","_inputTimeZone","normalizedConfig","loadLocaleData","DAYJS_LOCALE_KEYS","loadedLocaleKeys","localeKeyCache","findDayjsLocaleKey","intlLocale","getDayjsLocaleKey","loadDayjsLocale","import_dayjs_min","loadDayjsLocales","getFormatLocale","localizeFormat","this$2","this$1","dayjs","dayjsAdvancedFormat","dayjsCustomParseFormat","dayjsLocalizedFormat","dayjsUTC","dayjsTimeZone","isValidDate","getParser","utc","OFFSET_SUFFIX_REGEX","FORMAT_OFFSET_TOKEN_REGEX","FORMAT_TIME_TOKEN_REGEX","getFormatTokens","hasOffsetToken","hasOffsetOutsideFormat","parseWithFormat","parse","localeKey","parseWithFormatFallback","parseAsUTC","formatInLocale","instance","getDateInTimeZone","wallTime","parseISODate","getStoredValueTimeZone","singleCustomTimeZone","getDate","currentValue","removeMarkdownSyntax","markdownParser","Marked","HTML_BLOCK_BOUNDARY_REGEX","plainTextCache","stripMarkdown","DATE_ONLY_REGEX","DATE_PART_REGEX","BUILTIN_STRING_TRANSFORMATIONS","STRING_TRANSFORMATION_NAME_REGEX","OTHER_TRANSFORMATION_REGEX","OTHER_TRANSFORMATION_ARG_REGEX","TRANSFORMATION_PARSERS","parseOtherTransformationArgs","parseTransformation","transformation","splitTransformations","parsedTransformationsCache","parseTransformations","rawTransformations","applyUpperCaseTransformation","applyLowerCaseTransformation","applyDateTransformation","sValue","storedFormat","useUTC","applyDefaultTransformation","ternaryTransformation","applyTruncateTransformation","applyPlainifyTransformation","failedCustomTransformations","applyCustomTransformation","failedNames","applyTransformation","applyTransformations","dataLoaded","dataLoadedProgress","allEntryFolders","allEntries","getEntriesByPath","findEntryByPaths","entriesByPath","entryParseErrors","getCollectionFile","_collection","resolveCollectionAndFile","getCollectionFileLabel","getCollectionFilesByEntry","getCollectionFileEntry","folderInfo","getCollectionFileIndex","getIdentifierFieldName","getWildcardKeyPathPattern","isKeyPathWithin","sortedKeyCacheMap","getSortedKeys","valueMap","getKeysByPrefix","low","high","mid","ITEM_INDEX_SUFFIX_REGEX","LIST_ITEM_KEY_REGEX","listItemKeyCacheMap","getListItemKeys","isBuffer","keyIdentity","maxDepth","transformKey","isarray","isbuffer","isobject","currentDepth","unflatten","overwrite","getkey","parsedKey","addKeys","keyPrefix","recipient","isArray","split","key1","key2","ESCAPED_DOT","ESCAPE_CHAR","ESCAPE_REGEX","UNESCAPE_REGEX","ESCAPED_KEY_REGEX","STRING_KEY_PREFIX","INDEX_KEY_REGEX","isNumericStringKey","prefixStringKey","isPlainObject","restoreStringKeys","escapeKeySegment","unescapeKeySegment","isNonEmptyCollection","hasIndexLikeKey","hasIndexLikeChildKey","flattenKeys","parentKeyPath","transformSegment","unflattenKeys","unflattenMap","isValueEmpty","isPlaceholder","getSubtreeEntries","getSubtree","getComparableValue","getMemoizedSubtree","lastKeys","memo","lastValues","deleteSubtree","setSubtree","isInlinePatternComponent","definition","getInlinePattern","resolveInlinePatternComponent","fromInline","fromBlock","toInline","toBlock","searchPatternCache","getSearchPattern","sticky","findInlineMatches","searchPattern","limit","nextIndex","createInlineMatcher","isInternalPropKey","isMultiLinePattern","dotAll","isInlineComponentDef","inlinePattern","getSelectorSubjects","subjects","afterCombinator","getSelectorTagNames","names","subject","isValidSelector","supportsHTML","htmlSelector","fromBlockHTML","toBlockHTML","normalizeProps","getParentComponentNames","observeReadonly","textbox","followReadonly","frame","unescapeTitle","escapeTitle","escapeAlt","ALT_PATTERN","SRC_PATTERN","getTitlePattern","getImagePattern","IMAGE_REGEX","LINKED_IMAGE_REGEX","IMAGE_OR_LINKED_IMAGE_REGEX","HTML_ATTRS_PATTERN","HTML_IMAGE_PATTERN","getFigurePattern","linked","SANITIZE_OPTIONS","ALLOWED_CHECKBOX_ATTRIBUTES","filterInputs","ALLOWED_STYLE_PROPERTIES","filterInlineStyle","ALLOWED_SANDBOX_TOKENS","ALLOWED_PERMISSIONS_POLICY_FEATURES","filterPermissionsPolicy","allow","iframe","directive","validateIframe","src","currentOrigin","currentSandbox","sandboxTokens","sanitizeRichTextHTML","getImageProps","img","createImageElement","toImageMarkdown","toImagePreview","getFigureProps","figcaption","figure","hasOtherText","getMatchProps","fromImage","toFigureHTML","caption","createFigureElement","IMAGE_COMPONENT_LABELS","getImageMatchProps","getLinkedImageMatchProps","src2","alt2","singleQuotedTitle","title2","singleQuotedTitle2","getImageComponentId","captioned","IMAGE_COMPONENT_VARIANTS","IMAGE_COMPONENT_IDS","createImageComponentDef","getLabel","getEnglishImageLabel","getLocalizedImageLabel","getBuiltInComponentDefs","getCustomComponentName","unprefixedName","getComponentDef","customComponentName","registeredDef","customComponentDef","NUMERIC_VALUE_REGEX","isNumeric","roundFloatError","shiftDecimalPoint","places","toFixed","TYPE_MATCH_REGEX","fieldConfigCacheMap","hasRootField","isFieldMultiple","parseExplicitType","typeName","resolveNextSegment","explicitType","pendingExplicitType","isNumericKey","cleanKey","isWildcardKey","subField","subFields","subFieldName","keyPathArray","segmentIndex","types","resolvedType","typeKey","getDraftFieldArgs","getField","cacheKey","componentName","regularFields","currentExplicitType","hasVariableTypeField","getTypedKeyPath","currentKeyPath","parentField","parentFieldType","getFieldKind","isFieldRequired","getCurrentValue","isList","isCustomFieldType","itemKeys","DATE_REGEX","TIME_SUFFIX_REGEX","DATE_FORMAT_OPTIONS","TIME_FORMAT_OPTIONS","DATE_TIME_FORMAT_OPTIONS","dateTimeFormatterCache","formatDate","formatRecentDateTime","sameYear","timestamp","sameDay","TIMEZONE_OFFSET_REGEX","formatPart","offsetFormatterCache","getOffsetFormatter","getTimeZoneForStoredValue","offsetMatch","storedOffset","hours","minutes","getInitialTimeZone","storedTimeZone","browserTimeZone","getTimeZoneLabel","cityName","DATE_ONLY_MATCH_REGEX","TIME_SUFFIX_MATCH_REGEX","TIME_WITH_SECONDS_REGEX","formatDateTimeValue","dateStr","year","month","day","timeStr","hour","minute","includeSeconds","second","includeUTCSeconds","shouldUpdateValue","newDate","oldDate","getCurrentDateTime","formatInTimeZone","epoch","instant","formatInFieldTimeZone","configOutputUTC","_outputUTC","hasSeconds","inputFormat","effectiveTimeZone","timeSuffix","timeValue","getCurrentStorableValue","displayTimeZone","dateForParts","getLocalizedDateTimeValue","sourceLocaleKey","sourceLocale","targetLocaleKey","targetLocale","displayFormatterCache","getDisplayFormatter","OFFSET_TEXT_REGEX","isWrittenWithOffset","getDateTimeFieldDisplayValue","numberFormatterCache","getNumberFormatter","isFloatType","isStringOutput","yieldsNumber","storesNumber","castNumber","isInvalidNumberValue","getNumberFieldValue","getNumberInputValue","isEmptyValue","getListedEntryValue","getPropertyValue","normalizeMultiValue","getEntryFolderCache","fileMap","regexFolders","_allEntryFolders","getEntryFoldersByPath","getEntryFoldersCache","getEntryFolders","getAssociatedCollections","getFlatSubFields","getTypeSubFields","typeConfig","getValueSubFields","mapSubValues","mapObject","mapItem","getAllSubFields","forEachSubFieldConfig","_field","typed","someSubField","predicate","ARRAY_INDEX_REGEX","ITEM_SUBFIELD_KEY_PATH_REGEX","getMapKeyField","keyField","isArrayIndexKey","mapToItems","itemsToMap","mapListCache","hasMapList","convertValue","toItems","converted","convertMapLists","getMapKeyInfo","getFieldArgs","listKeyPath","listField","getMapKeyPaths","isMapKeyTaken","otherKeyPath","ALIAS","DOC","MAP","PAIR","SCALAR","SEQ","isAlias","isDocument","isMap","isPair","isScalar","isSeq","isCollection","isNode","BREAK","SKIP","REMOVE","visitor_","initVisitor","visitor","visit_","callVisitor","replaceNode","ck","cv","escapeChars","escapeTagName","Directives","yaml","verbatim","tagEntries","tagNames","visit$1","anchorIsValid","anchorNames","anchors","findNewAnchor","createNodeAnchors","aliasObjects","sourceObjects","prevAnchors","applyReviver","v0","v1","reviver","toJS","NodeBase","mapAsMap","maxAliasCount","onAnchor","Alias","getAliasCount","isScalarValue","Scalar","defaultTagPrefix","findTagObject","tagObj","aliasDuplicateObjects","schema","onTagObj","collectionFromPath","isEmptyPath","Collection","keepScalar","allowScalar","stringifyComment","indentComment","lineComment","foldFlowLines","lineWidth","minContentWidth","endStep","folds","escapedFolds","indentAtStart","overflow","escStart","escEnd","consumeMoreIndentedLines","onOverflow","onFold","getFoldOptions","isBlock","containsDocumentMarker","lineLengthOverLimit","indentLength","strLen","doubleQuotedString","json","minMultiLineLength","implicitKey","singleQuotedString","quotedString","singleQuote","hasDouble","hasSingle","blockEndNewlines","blockString","blockQuote","chomp","endStart","endNlPos","onChompKeep","startWithSpace","startEnd","startNlPos","header","commentString","onComment","foldedValue","literalFallback","foldOptions","plainString","inFlow","indentStep","actualString","compat","stringifyString","_stringify","defaultKeyType","defaultStringType","createStringifyContext","getTagObject","testMatch","stringifyProps","stringify","stringifyPair","keyComment","simpleKeys","explicitKey","allNullValues","keyCommentDone","chompKeep","vsb","vcb","valueComment","indentSeq","valueCommentDone","valueStr","vs0","nl0","hasNewline","flow","hasPropsLine","sp0","warn","logLevel","MERGE_KEY","merge","addMergeToJSMap","isMergeKey","resolveAliasValue","mergeValue","srcMap","addPairToJSMap","jsKey","stringKey","stringifyKey","jsValue","strCtx","strKey","jsonStr","createPair","Pair","stringifyCollection","stringifyFlowCollection","stringifyBlockCollection","itemCtx","itemIndent","addCommentBefore","ik","blockItemPrefix","flowChars","fcPadding","reqNewline","linesAtValue","iv","findPair","YAMLMap","keepUndefined","_pair","pair","sortEntries","Type","YAMLSeq","idx","asItemIndex","seq","nullTag","boolTag","stringifyNumber","minFractionDigits","floatNaN","floatExp","float","dot","intIdentify","intResolve","intAsBigInt","radix","intStringify","intOct","int","intHex","stringifyJSON","jsonScalars","binary","buf","resolvePairs","createPairs","iterable","YAMLOMap","omap","seenKeys","boolStringify","trueTag","falseTag","intBin","YAMLSet","keepPair","parseSexagesimal","asBigInt","stringifySexagesimal","_60","intTime","floatTime","millisec","schemas","schema$1","schema$2","tagsByName","float$1","floatExp$1","floatNaN$1","int$1","intHex$1","intOct$1","merge$1","coreKnownTags","getTags","schemaTags","schemaName","customTags","addMergeTag","sortMapEntriesByKey","Schema","resolveKnownTags","toStringDefaults","sortMapEntries","stringifyDocument","hasDirectives","contentComment","Document","_replacer","assertCollection","asStr","anchorPrefix","setAnchors","sv","jsonArg","YAMLError","YAMLParseError","YAMLWarning","prettifyError","col","lineStr","trimStart","pointer","resolveProps","spaceBefore","atNewline","startOnNewline","hasSpace","commentSep","reqSpace","tab","newlineAfterProp","comma","indicator","cb","parentIndent","containsNewline","flowIndentCheck","mapIncludes","uniqueKeys","search","startColMsg","resolveBlockMap","bm","commentEnd","collItem","keyProps","sep","keyStart","keyNode","composeNode","composeEmptyNode","valueProps","valueNode","resolveBlockSeq","resolveEnd","blockMsg","resolveFlowCollection","fcName","coll","atRoot","prevItemComment","endRange","expectedEnd","cePos","resolveCollection","CN","Coll","composeCollection","tagToken","lastProp","expType","resolveBlockScalar","scalar","parseBlockScalarHeader","chompStart","trimIndent","prevMoreIndented","crlf","strict","resolveFlowScalar","_onError","rel","plainValue","singleQuotedValue","doubleQuotedValue","valueEnd","badChar","unfoldLines","trimEnd","trimBoth","lm","foldNewline","escapeCodes","parseCharCode","wsStart","composeScalar","findScalarTagByName","findScalarTagByTest","matchWithTest","atKey","emptyScalarPosition","isSrcToken","composeAlias","composeDoc","contentEnd","getErrorPos","parsePrelude","atComment","afterEmptyLine","prelude","Composer","afterDoc","forceDoc","endOffset","cst","_visit","tok","tokenType","hexDigits","tagChars","flowIndicatorChars","invalidAnchorChars","isNotAnchorChar","Lexer","incomplete","dirEnd","sp","ch0","ch1","qb","allowEmpty","allowTabs","LineCounter","includesToken","findNonEmptyIndex","isFlowToken","getPrevProps","getFirstKeyStartProps","arrayPushArray","fixFlowSeqItems","Parser","onNewLine","lexeme","bv","atMapIndent","atNextItem","docEnd","parseOptions","prettyErrors","parseDocument","parser","lineCounter","composer","_doc","_reviver","fileStates","setFileState","updateFileState","takeOverFileState","previousPath","WHOLE_NUMBER_FLOAT_REGEX","YAML_INTEGER_REGEX","YAML_FLOAT_REGEX","JSON_NUMBER_REGEX","JSON_INTEGER_REGEX","mayHaveWholeNumberFloat","isWholeNumber","getFloatText","rememberUniqueSource","knownSource","joinKeyPath","escapedKey","collectYAMLFloatSources","sourceMap","SourcedValue","reviveWholeNumberFloat","collectJSONFloatSources","rememberValueSources","moveArrayItemSources","itemSources","valueSource","positions","replaceUnchangedValue","parsedValue","restoreValueSources","isFloatSource","getJSONSourceText","sourcedValueYAMLTag","sourcedValue","unsafeIntegerSources","LONG_DIGIT_RUN_REGEX","mayHaveUnsafeInteger","rememberSource","replaceBigInts","reviveUnsafeInteger","getUnsafeIntegerSource","hasUnsafeIntegerSources","restoreBigInts","getLineColFromPtr","ptr","makeCodeBlock","codeblock","numberLen","TomlError","parseString","startPtr","isLiteral","isMultiline","sliceStart","errPtr","hex","digit","DATE_TIME_RE","TomlDate","hasDate","hasTime","fasttype","unsafeDelim","#hasDate","#hasTime","#offset","iso","jsDate","isDigit","isEndOfValue","delim","extractValue","parseArray","parseInlineTable","parseDate","parseTime","startChr","hasUnderscores","endChr","parseIntegerBaseN","parseInteger","underscore","unsafeSeparator","readDate","temporalSuffix","skipComment","skipVoid","banNewLines","banComments","parseKey","hasOwn","unsafe","peekTable","validateTablePeek","peek","toml","tmp","skipping","tbl","isTableArray","BARE_KEY","HAS_WELLFORMED","extendedTypeOf","isArrayOfTables","formatWellFormedStringUnchecked","formatString","formatKey","numberAsFloat","stringifyInlineTable","strictTemporal","stringifyArray","tzc","stringifyArrayTable","stringifyTable","preamble","tables","tblKey","tableKey","numbersAsFloat","COMMENT_OR_BLANK_LINES_REGEX","getLeadingComment","rememberLeadingComment","leadingComment","prependLeadingComment","TOML_DATE_TIME_REGEX","TOML_NUMBER_REGEX","TOML_STRING_OR_COMMENT_REGEX","TOML_FLOAT_REGEX","SourcedTomlDate","createSourcedTomlFloat","findWholeNumberFloatSources","integers","isFloat","findDateSources","collectSources","dateSources","floatSources","rememberTomlValueSources","isUnchanged","replaceUnchangedTomlValue","restoreTomlValueSources","reviveNumber","parseJSON","parseTOML","libParseTOML","parseYAMLWithFloatSources","parseYAML","hasUnsafeInteger","_options","libParseYAML","detectFrontMatterFormat","firstLine","DOUBLE_BRACE_JSON_FRONT_MATTER_REGEX","parseJSONFrontMatterHead","trimmedHead","withLeadingComment","PARSERS","FRONT_MATTER_PARSERS","frontMatterRegexCache","parseFrontMatterBlock","bodyKey","bodyInline","startDelimiter","endDelimiter","fmDelimiters","trimmedText","syntax","parsedHead","resolveEntryFile","hasCustomParser","parseEntryFile","customParser","isDetected","hasFrontMatter","yieldToMain","scheduler","runInChunks","budget","createLatestGuard","call","createConcurrencyLimiter","running","concurrency","lastInFirstOut","SLUG_TEMPLATE_TAG_REGEX","slugRegexCache","getSlug","subPathTemplate","regexPattern","hasCircularReference","ancestors","getParsedContentKey","cacheParsedContent","parsedFileMap","parseFileContent","_key","errors","transformRoot","fieldName","rawContent","normalizeDefaultRootContent","nonDefaultLocales","defaultContent","transformRootContent","transformRawContent","localizedContent","shouldSkipIndexFile","extractPathInfo","isMultiFileStructure","filePathMap","locPath","processNonI18nEntry","processI18nSingleFileEntry","processI18nMultiFileEntry","canonicalSlug","localizedEntry","tempId","existingEntry","entryMap","arrayFileItems","createArrayItemEntry","prepareArrayFileEntries","prepareEntry","isArrayFile","effectiveRawContent","isI18nSingleFile","transformedContent","entryArgs","prepareEntries","entryFiles","FULL_REGEX_PATTERN","STATEFUL_FLAGS_REGEX","areValidFlags","getRegex","selectedEntries","selectedEntryIdSet","filterConditionCache","getFilterCondition","filter","matchesCollectionFilter","getListedCollections","entriesByCollectionCache","getCollectionBuckets","buckets","queryEntriesByCollection","syncEntriesByCollectionCache","entrySource","folderSource","getEntriesByCollection","getForeignEntriesInFolder","ownEntrySet","ownEntries","subPaths","getEntriesInCollectionFolder","countCollectionEntries","canCreateIndexFile","DEFAULT_ORDER_FIELD_KEY","isManuallyOrdered","getOrderFieldKey","reorder","isManualOrderKey","getReorderGroupName","getOrderValueGetter","orderKey","sortEntriesByOrderField","getOrderValue","keyed","optionLabelMapCache","getOptionLabelMap","labelMap","objectIdentityMap","nextObjectId","getObjectId","normalizeFieldName","isComplexListField","hasFields","hasTypes","getStoredValue","getFieldReplacement","fallbackContext","stored","getDisplayValue","getLabelFallback","getEntrySummaryFromContent","replaceTemplateFields","hasEmptyValueTag","fieldNames","storedValue","extractFieldNames","prepareFieldTemplates","valueField","_valueField","displayFields","identifierField","searchFields","_displayField","_searchField","allFieldNames","LIST_KEY_PATH_MATCH_REGEX","analyzeListFields","listFieldConfigs","baseFieldName","fieldConfigForList","buildListItemOption","replaceWildcards","replacements","itemValue","staticFieldNames","singleSubfieldRegexCache","collectIndexedValues","filterRegex","indexMatch","indexRegex","processSingleSubfieldList","groupEntries","COMPLEX_LIST_FIELD_REGEX","complexListIndexRegexCache","getSubFieldMatch","subFieldMatch","processComplexListField","baseFieldNameForList","subKey","listValues","escapedBase","escapedSub","wildcardFieldName","subFieldKey","processListFields","results","hasProcessedListFields","baseFieldGroups","firstConfig","createSimpleOption","excludeOptionsWithoutValue","processEntry","refEntry","getFieldDisplayValue","hasListFields","isFieldTranslatable","i18n","isFieldMirrored","isFieldLocalized","isFieldI18nDisabled","getInheritedI18nOption","isDuplicatedField","isSyncedField","isFieldInLocale","hasAncestor","inheritedI18n","sharedValueCache","addSharedValues","getDraftSharedValues","FIELD_TEMPLATE_REGEX","listItemRegexCache","getFieldValue","resolveFilterValues","filters","currentSlug","currentLocaleValues","sharedValues","filterAndPrepareEntries","localizedFieldCache","getFilterFieldValue","refEntries","hasContent","entryFilters","isEntrySlug","fieldKey","fieldValue","getRepositoryDatabase","repository","readCacheEntries","updateCacheEntries","newEntries","staleKeys","COMPARISON_OPERATORS","getViewConditions","conditions","operator","hasComparison","getConditionKey","operators","getGroupLabel","buildGroupMap","groupItems","matchesFilter","compareSortKeys","isStringType","sortItemsByKey","keyedItems","valuedItems","emptyItems","aKey","bKey","getCollapsibleGroupNames","getGroupingKey","isCollapsedByDefault","getToggledGroupsProp","collapsedByDefault","isGroupCollapsed","setToggledGroups","_current","others","_previous","setGroupCollapsed","_name","collapsed","setAllGroupsCollapsed","initViewSettingsStorage","settingsDB","storageKey","initial","defaults","lastSaved","_settings","settingsState","parseViewOptions","optionsKey","defaultName","defaultItem","isValidArray","hasDefaultSort","parseSortableFieldList","parseCustomSortableFields","customSortableFields","METADATA_KEYS","METADATA_TEMPLATE_TAGS","SINGLE_TAG_REGEX","isTemplateColumnKey","getConfiguredTableColumns","tableColumns","summaryFields","likelyLocaleCache","getLikelyLocale","getLanguageScript","likelyLocale","getLanguageScriptOrCode","findUiLocaleKey","uiLocale","languageScript","getLocalizedValueMap","getLocalizedOption","locale$9","uiLocaleKey","getFieldLabel","localizeDefaultValue","_localized","DEFAULT_SORT_KEYS","SORT_ORDERS","DATE_FIELDS","SPECIAL_SORT_KEY_TYPES","\"_summary\"","SPECIAL_SORT_KEYS","getDefaultSortKeys","customIdField","getSortConfig","summaryTemplate","specialKeys","hasCommitAuthorKey","hasCommitDateKey","isCommitAuthorAvailable","isCommitDateAvailable","defaultKey","defaultOrder","getSortKeyType","resolveSortFieldKey","getSortKeyLabel","sortKeys","_allEntries","sortKey","MARKDOWN_SORT_KEY_LENGTH","MARKDOWN_FIELD_KEYS","getSortKeyGetter","getEntrySummary","dateFieldConfig","isMarkdownField","getEntrySortKeyGetter","moveIndexFileToTop","_entries","getSortKey","getRelationSortKeyGetter","isSharedField","sortOptions","sortBy","optionCacheMap","MAX_OPTION_CACHE_SIZE","optionsInProgress","MAX_MERGED_ENTRIES_CACHE_SIZE","mergedEntriesCache","getPendingEntriesKey","pendingEntries","pendingEntry","mergeEntries","pendingMap","withPendingEntries","pendingCache","buildOptionGroups","buildOptions","getRefEntries","getOptions","resolvedFilters","resolvedKey","manuallyOrdered","getEntryOptions","getReferencedOptionLabel","optionLabelMap","labelCacheMap","MAX_LABEL_CACHE_SIZE","optionsKeyCache","getOptionsKey","getOptionLabel","hasLabels","rawValues","getOptionValue","isOptionValue","getPreviewLabels","getOptionValueType","getEmptyOptionValue","firstValue","getCommitAuthorName","author","CO_AUTHOR_TRAILER_REGEX","getBotCoAuthor","email","isRichTextField","plainText","getVisibleFieldDisplayValue","visibleItemKeyPath","keyPathPrefix","_keyPath","commitAuthor","commitDate","resolveRef","itemKey","ownValue","subKeys","LINE_REGEX","ATX_HEADING_START_REGEX","CODE_FENCE_START_REGEX","removeClosingSequence","removeHeadingAnchor","getHeadingText","getBodyHeader","openingFence","LT_PLACEHOLDER","NON_FORMATTING_TAG_REGEX","sanitizeEntrySummary","allowMarkdown","idField","useBody","replaceSub","relationLabelResolved","isDisplayValueFromOtherEntries","parsedTransformations","replaceSubContext","fallbackSummary","summaryCacheMap","lastAllEntries","entriesGeneration","getEntriesGeneration","getOwnSummaryOptions","formatEntrySummary","ownTemplate","useIndexFileLabel","useTemplate","collectionSummaryTemplate","contentLocale","replaceContext","locale$8","optionCache","outerFlag","dependsOnEntries","getCollectionFileSummary","handleDateTimeTag","dateTimeParts","handleUuidTag","handleSlugTag","handleFilePathTag","getRandomValue","randomValues","generate","replaceTemplateTag","dateTimeValue","_dateTimeParts","slugValue","assetFileName","filePathValue","replaceTemplatePlaceholder","hasValueTransformation","hasCustomTransformation","isMissingValue","bailOnUnresolvableTag","getFallbackValue","isAdditionsEnabled","backend","getAdditionsURL","additionsChunk","loadAdditions","getAdditions","requireAdditions","globToRegExp","anchored","glob","ignoreCase","parseFilterRules","findLfsTrackedPath","getRules","rules","lfs","relativePath","OPERATION_MARKERS","ZERO_OID","normalizeRootDir","getRootDir","toRepoPath","rootDir","fromRepoPath","rootSegments","pathSegments","common","isInRootDir","toRepoChanges","changes","change","isNotFoundError","isTypeMismatchError","hasOtherSpellings","pickEntryName","entryName","findEntryName","dirHandle","getHandleByPath","normalizedPath","rootDirHandle","pathParts","getFileHandle","getDirectoryHandle","readFile","readFileIfExists","getScopedRootDirHandle","repoRootDirHandle","ERROR_CODES","createFileSystemError","toFileSystemError","splitPath","getDirectory","getEntry","parentHandle","openWritable","writable","getStats","isDirectory","lastModified","createGitFileSystem","operation","getParent","writeThrough","stat","Buffer","isMissingError","textEncoder","textDecoder","compareBytes","concatBytes","toHex","fromHex","hmacSha256","encoder","cryptoKey","signature","ENTRY_HEADER_SIZE","parseCacheTree","trees","readUntil","terminator","readTree","parentPath","entryCount","subtreeCount","parseIndex","extensions","pathStart","pathLength","cacheTree","hasRequiredExtension","createIndexEntry","pathBytes","seconds","mtimeMs","nanoseconds","oid","comparePaths","findIndexEntry","middle","comparison","updateIndexEntries","removedPaths","addedEntries","serializeCacheTree","entryCounts","subtree","subtreeName","tree","serializeIndex","PACKED_OBJECT_TYPES","OFS_DELTA","REF_DELTA","MAX_DELTA_DEPTH","encodeObject","hashObject","inflate","stream","deflate","writer","compressed","readable","writeLooseObject","applyDelta","readSize","factor","instruction","parseLooseObject","nullIndex","parsePackIndex","oidsStart","offsetsStart","largeOffsetsStart","fanout","offsets","findPackedObject","byteIndex","oids","getPackedObjectEnd","pack","sortedOffsets","createObjectReader","packsPromise","loadPacks","packs","packDirHandle","gitDirHandle","packHandle","findInPacks","oidBytes","readLooseObject","readPackedObject","typeNumber","baseOid","readObjectAtDepth","looseObject","sortTreeEntries","serializeTree","parseTree","spaceIndex","getCommitTree","getAncestorDirs","buildTree","changedDirs","changedPaths","indexEntries","subdir","previousTree","subtrees","dirs","writeChangedTrees","baseObject","readObject","baseEntries","baseEntry","writeTree","indexCache","clearLocalGitCache","setIndexCache","getIndexChecksum","checksum","resolveBranchHead","git","getIndexTree","readIndex","identifyOperation","isTrueConfigValue","getBooleanConfig","inspectRepository","objectFormat","refStorage","autocrlf","onLock","markers","foundMarker","indexBuffer","indexChecksum","stage","headOid","headTreeOid","indexTree","runConcurrently","work","mapConcurrently","LocalizedError","createLocalizedError","getErrorMessage","createNoAccessError","createNoWriteAccessError","createPermissionError","canRead","repo","toRepositoryAccessError","LEGACY_USER_STORAGE_KEYS","user","_user","forkedRepository","openAuthoring","openAuthoringInitialized","isEntryAlreadyPublished","getForkPath","getForkURL","repoURL","forkPermissionRequest","requestForkPermission","DEFAULT_COMMIT_MESSAGES","SKIP_CI_REGEX","hasSkipCIMarker","fillTemplate","getBackendOptions","getAuthorValues","login","createBaseCommitMessage","customCommitMessages","backendOptions","firstSlug","firstPath","remainingPaths","collectionLabel","commitType","authorValues","applyUserMessage","userMessage","isDeployingCommit","skipCIEnabled","autoDeploy","skipCI","createCommitMessage","promptMode","TRAILER_LINE_REGEX","cleanTrailerValue","formatPersonTrailer","addCommitTrailer","lastParagraph","trailer","accountsWarnedAboutEmail","signOffCommitMessage","account","cleanEmail","emailSuffix","dedupeFileCommits","commitMap","commits","createLastCommitError","assertBranchNotMoved","fetchLastCommit","expectedHead","fetchPerPathCommits","fetchHistory","parseCommit","STAGING_CONCURRENCY","getIndexPathResolver","spellings","spelling","getWorkingTreePath","getAddedPaths","getRemovedPaths","convertToLF","stageFiles","formatTimezoneOffset","addToReflogs","oldOid","timezoneOffset","newOid","stageAndCommit","toIndexPath","addedPaths","treeEntries","commitSavedChanges","localGitNotice","enqueue","describeError","getLocalGitStatus","_repository","saveAndCommitChanges","repoChanges","lockedFs","inspection","lfsPath","save","__classPrivateFieldGet","_Mime_extensionToType","_Mime_typeToExtension","_Mime_typeToExtensions","Mime","typeMap","allExtensions","starred","currentType","hasPath","standardTypes","mime_default","otherTypes","MEDIA_KINDS","THUMBNAIL_KINDS","isPDF","canCreateThumbnail","ASSET_KINDS","DOC_EXTENSION_REGEX","MEDIA_TYPE_REGEX","isMediaKind","canPreviewFile","mime","canPreviewAsset","getMediaKindFromType","mimeType","subType","getMediaKindFromPath","hostname","pathname","getMediaKind","canEditAsset","getAssetKind","GIT_CONFIG_FILE_REGEX","gitConfigFiles","CMS_FOLDER_NAMES","SITE_ROOT_FOLDERS","isCmsFolderName","getConfiguredSiteRootFolder","mediaFolder","publicFolder","pub","getAdminPageFolders","decoded","cmsFolderPathsCache","getCmsFolderPaths","siteRootFolder","isCmsFolderPath","CMS_FILE_NAME_REGEX","isCmsFile","isInCmsFolder","assertOutsideCmsFolders","lockedBranch","mergeLockedBranch","recordBranchAccess","access","fetchAccess","LEGACY_CMS_LABEL_PREFIXES","WORKFLOW_STAGES","OPEN_AUTHORING_STAGES","WORKFLOW_STATUSES","WORKFLOW_STATUS_LABELS","WORKFLOW_MODES","normalizePublishMode","getConfiguredStages","stages","getPublishModeOptions","directPublish","allowIncompleteDrafts","getPublishMode","isWorkflowMode","getPublishModeScopes","isWorkflowConfigured","WORKFLOW_BRANCH_PREFIX","MAX_SLUG_BYTES","MAX_BRANCH_BYTES","MIN_SLUG_BYTES","segmenter","joinPrefix","toUpstreamBranchName","forkPrefix","getBranchPrefix","getBranchListPrefix","encodeSlug","decodeSlug","getSlugByteLength","getMaxSlugBytes","dirBytes","truncateSlugBytes","maxBytes","getBranchName","parseBranchName","listPrefix","isEntryBranch","SEPARATOR","getForkBranchName","parseForkBranchName","slash","getUpstreamBranchName","getForkHead","isForkEntry","isLockedFork","isLockedForkEntry","getForkEntryNotice","isViewer","isConfigReadonly","isLockedByBranch","isReadonly","isDraftLockedByOthers","additions","isDraftConfigReadonly","isDraftReadonly","getReadonlyMessage","allAssetFolders","globalAssetFolder","typedKeyPath","selectedAssetFolder","targetAssetFolder","_selectedAssetFolder","getAssetFolder","cond","getEntryRelativePathRegEx","localeFolderNames","internalSubPath","firstSegment","subPathPattern","getAssetFolderPathCache","entryRelative","_allAssetFolders","isRelative","getAssetFoldersByPath","dirMatches","matchSubFolders","matchesByDir","itemMatches","regexSub","regexExact","getAssetFolderKey","publicPath","canCreateAsset","assetFolder","assetsLocked","getReadonlyFolderPaths","hasReadonlyAsset","assets","getStaticPrefix","collectConfiguredPaths","filePaths","folderPaths","folderPathMap","getManagedPaths","configuredFilePaths","STALE_TEMP_FILE_AGE","limitDirListing","getPathRegex","getPathPrefixRegex","leadsToScanningPath","scanningPaths","pathRegexCache","scanningPath","deleteStaleTempFile","fileHandle","scanDir","subdirectories","hasMatchingPath","scanningPathsRegEx","subdirFileHandles","fileHandles","collectScanningPaths","getAllFiles","deferRejection","createFileList","assetFiles","configFiles","entryPaths","fileInfo","entryFolder","allFiles","describeFileList","createDebugLogger","startTime","lastTime","details","MAX_FILE_SIZE","FILE_PROCESS_CONCURRENCY","parseTextFileInfo","parseAssetFileInfo","cachedHashes","sha","newHashes","loadFiles","log","cachedHashesPromise","hashCacheDB","fileList","assetsPromise","entryFileItems","configFileItems","currentPaths","LOCALHOST_REGEX","isLocalHostname","isSecureURL","baseURL","protocol","isRetryableRequest","TRANSIENT_STATUSES","DEFAULT_RETRY_DELAY","getRetryDelay","headers","fetchOK","response","sendRequest","responseType","retryWithNewToken","refreshAccessToken","retryDelay","retries","retryable","shouldRetry","retryAfterDelay","ok","assertResponseOK","allowNotFound","errorText","initUserEnvDetection","userAgentData","brand","platform","mqlSmall","matchMedia","mqlMedium","mqlLarge","mqlPointer","isSmallScreenSetter","isMediumScreenSetter","isLargeScreenSetter","hasMouseSetter","opensOnClick","RENAME_ATTEMPTS","RENAME_RETRY_DELAY","canMoveFile","writeFile","createTempFile","moveFile","newDirname","newBasename","oldDirname","newDirHandle","oldDirHandle","newFileHandle","tempFileHandle","renameFile","attempt","pendingRename","deleteEmptyParentDirs","dirName","_entry","deleteFile","deleteEmptyDirs","dirPaths","saveChange","isEntryChange","saveChangeBatch","saveChanges","assetChanges","entryChanges","normalizeBaseURL","normalizeRestBaseURL","normalizeGraphQLBaseURL","apiConfig","graphqlVars","requestAccessToken","tokenURL","includeCredentials","pendingRefreshes","requestTokenRefresh","sentRefreshToken","refreshToken","clientId","TOKEN_REFRESH_LOCK_NAME","withTokenRefreshLock","locks","getStoredTokens","storedUser","readStoredTokens","isRefreshedElsewhere","fetchAPI","isGraphQL","graphqlBaseURL","restBaseURL","authScheme","isUserToken","fetchGraphQL","fetchUserProfile","tokenBefore","fieldMap","getUserProfile","BACKEND_NAMES","isGiteaBackendName","inAuthPopup","cancelAuthorization","AUTH_SECRETS_STORAGE_KEY","AUTH_POPUP_STORAGE_KEY","getAuthChannelName","formatHandshakeMessage","provider","formatResultMessage","parseResultMessage","getAuthPopupState","setAuthPopupState","clearAuthSecrets","createAbortError","openPopup","availHeight","availWidth","authURL","authorize","authPopup","backendName","channel","cleanUp","cancel","handleResult","resultStr","origin","initServerSideAuth","siteDomain","createAuthSecrets","codeVerifier","codeChallenge","initClientSideAuth","_authURL","redirectURL","csrfToken","sendMessage","_state","onMessage","finishClientSideAuth","handleClientSideAuthPopup","errorDescription","realAuthURL","isAuthPopup","handleAuthFlow","authType","authArgs","authScope","inPopup","auto","getTokens","signInToBackend","sharedApiConfig","signOut","getTokenPageURL","instanceURL","signIn","signOutFromBackend","MIN_REPORTED_TOTAL","saveProgress","startPreparing","advancePreparing","progress","reportCommits","estimatedTotal","clearSaveProgress","prefsError","prefs","storedLocaleApplied","localeSwitchCount","appliedLocalePref","navigatorLocale","_prefs","devMode","autoTheming","autoTheme","localePref","appLocales","previousLocale","switchedByUser","switchCount","REPOSITORY_INFO_PLACEHOLDER","API_PATH_REGEX","getInstanceURL","restApiRoot","getRepoURL","repoPath","getRepositoryPath","toRepositoryPath","fullName","isSameRepository","getPullRequestPath","getRestBranchPath","createBaseURLsGetter","getScopedBaseURLs","urls","getBaseURLs","initRepositoryInfo","service","defaultApiRoot","applyDefaultBranch","isRateLimited","fetchRepositoryAccess","getRefusalError","isPrivate","allowForking","permissions","checkRepositoryAccess","canWrite","FETCH_BRANCH_ACCESS_QUERY","checkBranchAccess","FETCH_DEFAULT_BRANCH_NAME_QUERY","fetchDefaultBranchName","fetchAPIOrUndefined","SETTLE_POLL","pollUntil","isSettled","attempts","interval","DELETION_GROUP_REGEX","DELETION_GROUP_RECORD_REGEX","formatDeletionGroup","deletionGroup","getPullRequestDescription","getDeletionGroup","description","setDeletionGroup","createDraftTitleCodec","isDraft","parseRestFiles","removedStatus","toCommitAuthor","parseRestPullRequest","getLabelPrefix","getKnownLabelPrefixes","getStatusLabel","getAllStatusLabels","replaceStatusLabel","cmsLabels","getStatusFromLabels","FORK_POLL","isOpenAuthoringConfiguredFor","resolveWorkflowRepository","getForkRequestStatus","toForkPullRequest","headBranch","resolveBranchRepository","ensureForkPermission","createForkError","requestForkWithFallbackName","requestFork","conflictStatuses","isNameTaken","requestRenamedFork","pollForFork","checkFork","attemptsLeft","runOpenAuthoringSetUp","setUp","setUpForkFor","existingFork","fetchFork","prepareFork","fetchForkingAllowed","checkPublishAllowed","checkDirectCommitAllowed","checkStatusAllowed","checkMergedBranch","fetchBranchHead","mergedSHA","deleteBranch","warnForkSyncError","warnForkNotFastForwarded","syncForkWith","fetchForkByNameFor","userName","pruneForkBranches","leftover","classify","updateForkStatusWith","pullRequest","requestKey","createRequest","fetchRequest","merged","isEntryRequest","getMergedSHA","applyStatus","createDraftPullRequest","isOpenAuthoringConfigured","getWorkflowRepository","getBranchRepository","getContentRepository","hasPendingInvitation","invited","getNoAccessError","createError","scopes","fetchOpenAuthoringAccess","fetchForkByName","FETCH_USER_FORK_QUERY","fetchForkFromNetwork","waitForFork","createFork","syncFork","setUpOpenAuthoring","repository$1","initOpenAuthoring","BLOB_CONCURRENCY","RATE_LIMIT_DELAYS","sendWithBackoff","isText","createGitDataCommit","binaryAdditions","addition","baseCommit","blobShas","fileShas","expectedHeadOid","deletions","treeSha","toggleListItem","included","splitIntoChunks","splitIntoSizedChunks","chunks","chunk","chunkSize","getSize","maxItems","buildAliasedQuery","innerQuery","useBranch","fetchAliasedBatch","getFragment","UPLOAD_FAILURE_STATUSES","sortAdditions","deletedPaths","takeAdditions","getPayloadSize","estimateRemainingCommits","payloadSize","isUploadFailure","repositoryHead","dataGeneration","createStaleCheck","FETCH_LAST_COMMIT_QUERY","branchName","MAX_GRAPHQL_BLOB_SIZE","getExpectedHeadOid","TARGET_COMMIT_DURATION","getNextPayloadSize","splitCommitMessage","headline","createGraphQLCommit","coAuthor","createCommit","onWorkflowBranch","commitChanges","timedOutSize","commitCount","isLast","addedAgain","FILE_COMMITS_CHUNK_SIZE","MAX_COMMIT_AUTHORS","fetchFileCommits","actor","PREVIEW_NAME_REGEX","PRODUCTION_NAME_REGEX","NO_BUILD_DESCRIPTION_REGEX","SOURCE_RANK","getPreviewContext","normalizeURL","findURLInSummary","dashboardHost","detailsURL","isGitServiceURL","selfURL","claimsDeployment","previewContext","canSupplyURL","getScore","isProductionName","pickDeployment","exact","best","addCandidates","toCandidate","collectSafely","resolveDeployments","validTargets","targets","shas","candidateMap","fetchRestBranchHeadSHA","getPath","triggerDeployment","MAX_ITEMS","STATUS_STATE_MAP","DEPLOYMENT_STATE_MAP","CHECK_CONCLUSION_MAP","PREVIEW_CHECK_NAME_REGEX","fetchBranchHeadSHA","fetchCommits","SOURCES","targetUrl","latestStatus","environment","suite","conclusion","detailsUrl","askSeparately","collectTogether","collectOneByOne","collectCandidates","fetchDeployments","getFileKey","arrayIndex","reconcileEntries","previousByPath","claimed","previousPaths","reconcileAssets","fetchedPaths","shadow","workflowAsset","published","previousPublished","canMergeFiles","planEntryReparse","sharedPaths","getReusableEntry","mergeable","_path","reusedEntries","dirtyFiles","mergeableCache","mergeableGroups","parsedByPath","parsedEntries","reusedEntry","parseFileInfo","fetchedFileMap","getFilePaths","updateStores","applyFileMetadata","metadataMap","entriesChanged","assetsChanged","parseEntryFiles","parseFiles","toFileListItem","toFileListItems","getFileList","lastConfigHash","cachedConfigHash","cachedCommitHash","gitConfigFetched","metaEntries","lastCommitHash","cachedFileEntries","fetchFileList","saveFileListMeta","metaDB","advanceRepositoryHead","restoreCachedFileData","cachedFiles","attachParsedContents","reparsedFileMap","updateCache","usedPaths","unusedPaths","savedEntries","fetchingFiles","cacheDB","readDatabaseEntries","completeMetadata","cacheArgs","metadataFetched","fetchFileMetadata","cacheFiles","cacheUpdate","whenScoped","scoped","convertKeys","convert","convertFile","convertPullRequest","scopeCommit","scopeFileFetchers","toRepoFiles","lastHash","fetchFileContents","scopeWorkflow","toRepo","fromRepo","scopeBackendService","fetchBlob","deployments","productionSHA","lastCommitPublishHint","deployPollTimedOut","forgetDeployments","resetDeployments","setLastCommitPublishHint","lastParseKey","getParseKey","resolveHead","lastCommit","accessPromise","branchPromise","lastCommitPromise","fetchedCommit","loadContents","contentFiles","finishLoad","isStale","updateStores$6","readyMessage","startCacheUpdate","fetchAndParseFiles","fetchers","incremental","initialLoad","checkAccess","databaseEntriesPromise","branchAccessPromise","finishArgs","fetchRepositoryFiles","PROGRESS_TIME_PER_FILE","startSimulatedProgress","fileCount","fetchTree","recursive","treeRef","blobs","truncated","tooBig","FETCH_DIR_SHA_QUERY","fetchDirSHA","CHUNK_SIZE","getFileContentsFragment","getFileMetadataFragment","requestBlob","fetchBlobText","parseFileContents","truncatedFiles","isTruncated","parseFileMetadata","messageBody","committedDate","fetchInChunks","stopProgress","fetchFiles","createStatusChecker","getLevel","checkStatus","isSquashMergeEnabled","deleteRemoteBranch","goneStatuses","openWorkflowPullRequest","createPullRequest","saveWorkflowBranch","recorded","updateDescription","commitToExistingBranch","commitToNewBranch","commitToNewWorkflowBranch","commitFromStart","branchExistsStatus","commitOnBranch","findOpenPullRequest","inUseMessage","createBranchGoneError","assertBranchAtHead","headSHA","updateLabelledStatus","updateForkStatus","updateLabels","updateDraftState","getParentDirs","toChangedFilesWithModes","changedFiles","statusMap","fetchFileModes","getMovedHeadMergeState","resolveMergeState","onConfiguredBranches","listChangedFiles","isPullRequestMerged","reopenPullRequest","updatePullRequestDescription","approvePullRequest","findOwnApprovals","reviews","reviewer","discardPullRequest","closeRequest","closedStatuses","applyForkPullRequestStatus","normalizedState","AUTO_MERGE_POLL","isPermanentClientError","waitForMerge","cancelSafely","failure","armed","PENDING_CHECK_STATES","BLOCKING_REVIEW_DECISIONS","MERGEABLE_STATES","MERGE_STATE_POLL","FETCH_MERGE_READINESS_QUERY","ENABLE_AUTO_MERGE_MUTATION","DISABLE_AUTO_MERGE_MUTATION","fetchMergeReadiness","isCheckingMergeability","fetchSettledMergeReadiness","isWaitingForChecks","waitForAutoMerge","autoMergeRequest","checkState","nodeId","scheduleAutoMerge","squash","latest","mergeRefusedPullRequest","refusal","parseFileNodes","changeType","fetchPullRequestFileList","FILES_CHUNK_SIZE","fetchPullRequestFiles","pullRequests","workflowRepository","FETCH_BRANCH_HEAD_QUERY","newLabels","parseAuthor","baseBranch","maintainerCanModify","getFetchForkBranchesQuery","BRANCH_PULL_REQUESTS_CHUNK_SIZE","getForkPullRequestsFragment","isForkPullRequest","pr","fetchForkBranchPullRequests","parseForkBranch","inReview","databaseId","fetchForkBranches","fetchForkBranchFileList","headOwner","fetchForkPullRequests","renamed","FETCH_PULL_REQUEST_STATE_QUERY","fetchForkRequestState","applyForkStatus","readPages","maxPages","pageResults","fetchPage","fetchPages","readNumberedPages","pageSize","getPullRequestFields","getForkPullRequestsSelection","getFetchPullRequestsQuery","withForks","toPullRequest","getLabelNames","parsePullRequest","parseForkPullRequest","fetchLabelledPullRequests","fetchPullRequests","FETCH_BRANCH_BASE_QUERY","CREATE_REF_MUTATION","getFetchOpenPullRequestsQuery","fetchOpenPullRequests","isCrossRepository","resetBranch","tryCreateRef","fetchForkMergeBase","forkOwner","forkBranch","mergeBase","createBranch","forkRepo","openPullRequest","updateStatus","approve","WITHDRAWAL_MESSAGE","REVIEWS_PER_PAGE","MAX_REVIEW_PAGES","fetchReviews","withdrawApproval","headRepository","savePullRequest","MAX_COMPARE_FILES","REST_FILE_STATUSES","workflow_default","encodedBranch","refs","initGitBackend","authRoot","authPath","api","tokenPath","ADDITIONS_AUTH_PATH","gitBackendServices","github","projectPath","graphqlApiRoot","signIn$2","signOut$3","fetchFiles$3","fetchBlob$2","commitChanges$3","triggerDeployment$1","SERVICE_CHUNK_NAMES","serviceChunks","chunkName","loadGitBackendService","services","serviceName","remoteRepository","REPOSITORY_PROPS","ROOT_DIR_HANDLE_KEY","rootDirHandleDB","assetHashDB","getRootDirHandle","forceReload","showPicker","backendName$1","checkLocalGitStatus","local_default","label$1","init$2","signIn$1","signOut$2","fetchFiles$2","commitChanges$2","SEED_LINK_SELECTOR","SEED_FETCH_CONCURRENCY","getSeedManifestURL","isDemoSite","isValidSeedPath","fetchSeedManifest","manifestURL","fetchSeedFile","writeSeedFile","repoDirHandle","seedTestRepository","storageDirHandle","repoDirName","getBackupDatabaseName","fileSystemBackendServices","getBackendService","unsupportedBackends","validBackendNames","loadBackendService","remoteName","selectBackend","getCollectionPublishModeOptions","getWorkflowStages","resolveStage","getEntryStage","getStagesOfEntry","getStageOfEntry","isStageAvailable","getNextStage","isLastStage","boardStages","workflowPageLabelKey","workflowEnabled","isWorkflowEnabled","allUnpublishedEntries","unpublishedEntries","unpublishedEntriesLoading","unpublishedEntriesLoaded","publishingBranches","workflowDataReady","getUnpublishedEntriesByCollection","filterCompanionEntries","companion","getCompanionEntries","getEditedCompanionEntries","getEditedCompanionPaths","editedEntries","companions","publishedEntry","findEditingUnpublishedEntry","getPullRequestEntries","isAddressedEntry","getUnpublishedEntry","getForkUnpublishedEntry","getUnpublishedEntryBySlug","unpublishedEntry","getUnpublishedEntryById","getUnpublishedEntryByBranch","getUnpublishedEntryByDraft","originalEntry","isOrphanedForkDraft","isWorkflowDraft","isPendingDeletion","isDraftLocked","getDeletionSelection","canMergePullRequest","isPublishVisible","canSkipReviewAlong","isPublishStage","isPublishAllowed","getPublishAction","isDirectPublishAllowed","swapUnpublishedEntries","drafts","draftMap","mergeUnpublishedEntries","swapped","swappedIn","unpublished","getPublishedVersion","hasPublishedVersion","checkPublishedVersion","isDiscardableDraft","getExistingSlugs","slugs","legacySlugLength","slugOptions","maxlength","existingSlugs","rename","filledSlug","uniqueSlug","suffixBytes","numberedSlugs","fillMediaFolderTemplate","localeFile","getEntryLocaleContext","fillInternalPathTemplate","findInEntryBaseFolders","entryFileFolder","baseFolder","getEntryRelativePath","assetFolderPath","getEntryRelativeAbsolutePath","resolvedSubPath","getEntryRelativePublicPath","findInEntryRelativeFolder","find","localPath","findLibraryOptions","libraryName","legacyOptions","siteName","siteDefaultName","mergeLibraryOptions","fieldOptions","siteOptions","resolveLibraryOptions","getPreferredLibraryNames","fieldLibraries","siteLibraries","libraries","getUploadableServiceEntries","cloudServiceEntries","upload","findPreferredLibraryName","serviceEntries","uploadRequired","preferredLibraryNames","repositoryAvailable","serviceId","getMediaLibraryOptions","RASTER_IMAGE_FORMATS","HEIC_IMAGE_TYPES","RASTER_IMAGE_TYPES","RASTER_IMAGE_EXTENSION_REGEX","VECTOR_IMAGE_FORMATS","VECTOR_IMAGE_TYPES","VECTOR_IMAGE_EXTENSION_REGEX","SUPPORTED_IMAGE_FORMATS","SUPPORTED_IMAGE_TYPES","SUPPORTED_IMAGE_TYPES_WITH_HEIC","IMAGE_FORMAT_LABELS","getAcceptedImageFormatLabels","withHeic","RASTER_IMAGE_CONVERSION_FORMATS","hasTag","getGIFColorTableSize","skipGIFSubBlocks","isAnimatedGIF","frameCount","introducer","isAnimatedWebP","isAnimatedPNG","isAnimatedImage","HEADER_LENGTH","HEIF_BRANDS","AVIF_BRANDS","startsWith","readTag","getBrands","boxSize","brands","sniffRasterImageFormat","encodingSupportMap","checkIfEncodingIsSupported","canvas","hasTransparency","exportCanvasAsBlob","supported","nativeOnly","quality","imageData","encode","IDLE_TIMEOUT","workerPromise","workerUnavailable","idleTimer","getWorkerScript","moduleURL","WorkerUnavailableError","createWorker","worker","getWorker","terminateWorker","decodeInWorker","decodeOnMainThread","decode","decodeBuffer","decodeHEIC","resolveTransformOptions","calculateResize","originalWidth","originalHeight","targetWidth","targetHeight","isSmaller","scale","newWidth","newHeight","fit","resizeCanvas","THUMBNAIL_TRANSFORM_OPTIONS","createImageSource","image","createVideoSource","video","createSource","createFallbackImageBitmap","transformImage","requestedWidth","requestedHeight","naturalWidth","naturalHeight","optimizeSVG","optimize","normalizeFileNameTemplate","getDefaultMediaLibraryOptions","fileNameTemplate","toRasterImageFormat","getRasterImageFormats","declaredFormat","canConvertHEIC","getAcceptedImageTypes","getAcceptedFileTypes","isAcceptedFile","transformFile","sourceFormat","formatTransformations","newFormat","newFileName","selectedSubfolderPath","focusedSubfolder","renamingSubfolder","deletingSubfolder","canBrowseSubfolders","getRelativePath","getSubfolderPath","resolveAssetFolderPath","knownFolder","folders","exactMatch","parentFolder","browsedDirPath","browsingCmsFolder","listSubfolders","getTakenNames","fileNames","buildFolderTree","listChildFolders","groupNamesByDir","getRepositoryFolderTree","getEntryFileNamesByDir","getConfigFileNamesByDir","getFolderNamesInDir","getNonAssetFileNamesInDir","getFolderBreadcrumbItems","subfolderNames","rootLabel","onBrowse","getOwnerFolderPathCache","getOwnerFolderPath","getSubfolderSourcePaths","ownerFolderPath","getSubfolders","getSubfolderTree","getAssetsInDir","getUploadDirPath","subfolderPath","formatSubfolderName","slugificationEnabled","validateSubfolderName","hasTags","removeSlashBeforeAtSign","replaceTags","globalMediaFolder","globalPublicFolder","replaceFolderTags","globalFolders","isPublicFolder","getCollectionBaseFolder","normalizeAssetFolder","_mediaFolder","_publicFolder","addFolderIfNeeded","iterateFiles","fileMediaFolder","filePublicFolder","inherits","handleFieldMediaFolders","fieldMediaFolders","validCollections","addAssetCollections","assetCollections","assetCollection","isAssetFolderReadonly","isAssetCollection","resolveGlobalFolders","_globalMediaFolder","_globalPublicFolder","collectCollectionAssetFolders","isGlobalFolderConfigured","collectionFiles","isRelativeFileCollectionFolder","getLocaleFolderNameMap","hasLocaleFolder","getAllAssetFolders","assetFolders","allAssetsFolder","allFolders","localeFolderNameMap","getEntryCollectionContexts","getAssetByInternalPath","getAssetKey","unsaved","replaceGlobalFolderTags","getAssetByRelativePathAndCollection","fieldFolder","folderOptions","entryContent","normalizedMediaFolder","normalizedPublicFolder","getCandidateAssetFolders","hasCollection","requireCollectionName","skipTemplateFolders","getAssetByRelativePath","findAsset","publicPathRegexCache","getPublicPathRegex","isRelativePath","getAssetByAbsolutePath","baseName","findInFolder","_collectionName","scanningFolders","foundAsset","matchingFolder","getAssetByPath","encodedPath","pathWithoutFragment","isAssetInFolder","getAssetFolderMatchKey","_hasTemplateTags","getAssetCountsByFolder","countAssetsInFolder","getAssetsByDir","getAssetsByDirName","getTakenNamesInDir","getDuplicateFiles","existingNames","filterAssets","groupAssets","SVG_NS","readAsDataURL","isFixedLength","parseViewBox","numbers","createInertSVG","isSVG","attributeNames","viewBox","PDFJS_DIST_URL","PDFJS_WORKER_URL","PDFJS_GET_DOC_OPTIONS","createLoadingOptions","pdfjs","renderPDF","loadingTask","loadingOptions","pdfPage","cachedBlobs","pendingAssetBlobs","XML_TYPE_REGEX","getDisplayBlob","createDisplayBlobURL","cacheAssetBlobURL","displayBlob","cacheAssetBlob","downloadOnce","download","downloadAssetBlob","fetchAssetBlob","readHandle","getAssetBlob","getThumbnailSourceBlob","getAssetBlobURL","thumbnailStore","pendingThumbnailBlobs","memoryThumbnailCache","getCachedThumbnail","initThumbnailStore","limitThumbnailGeneration","resolveThumbnailBlob","thumbnailBlob","hasCachedThumbnail","getAssetThumbnailURL","cacheOnly","cachedBlob","pendingRevocations","preloadedURLs","preloadedAssets","loadedAssets","flushRevocations","revokeBlobURLIfNeeded","isFirst","revokeAssetBlobURLIfNeeded","replaceTemplatePath","groupNames","groupName","newGroupName","resolvePublicFolder","getAssetPublicURL","encodingEnabled","pathOnly","publicBasePath","allowSpecial","getFolderPublicPath","preloadAssets","retained","released","getFolderKey","getRelativeKey","formatFileName","originalName","assetNamesInSameFolder","foldedNamesInSameFolder","isSameFileName","name1","name2","validateAssetName","isTaken","folderNames","filterAssetsByQuery","lowerQuery","getCredential","getListPrefix","fetchListing","credential","filterByKind","listObjects","browseObjects","listFolderObjects","searchObjects","getFileNamesInFolder","folderKey","uploadObjects","uploadedObjects","deleteObjects","replaceObject","moveObject","newPath","createFolderObject","deleteFolderObject","getRenamedPath","newName","renameObject","ownName","createObjectStorageOperations","withConfig","ObjectStorageService","libOptions","serviceLabel","serviceURL","developerURL","apiKeyURL","apiKeyPattern","resolveConfig","isConfigured","isConfigURL","operations","parseXml","nodeToObject","toArray","DEFAULT_ENDPOINT_SUFFIX","MAX_RESULTS","buildContainerUrl","accountName","endpoint","buildRequestUrl","searchParams","buildBlobRequestUrl","azureBlobStorage","publicUrl","Name","containerUrl","properties","displayKey","encodedKey","blobUrl","downloadURL","isEnabled$2","isAssetURL$2","list$5","search$4","upload$1","deleteFiles","createEmptyFolder","removeFolder","activated","consoleLoaded","dialogOpen","FRAME_ORIGIN","FRAME_SRC_PARAMS","CONFIG_PROPS","getLibraryOptions","getMergedLibraryOptions","getCloudConfig","cloudName","apiKey","isEnabled","isAssetURL","cloudinary_default","isEnabled$1","isAssetURL$1","generateAwsSignature","urlObj","amzDate","dateStamp","canonicalUri","canonicalQueryString","canonicalHeaders","signedHeaders","canonicalRequest","payloadHash","credentialScope","stringToSign","signatureHex","secretAccessKey","accessKeyId","signedRequest","extraHeaders","authorization","buildObjectUrl","bucket","forcePathStyle","isS3ObjectUrl","encodeKey","buildObjectApiUrl","getAclHeader","acl","s3Operations","Key","objects","baseUrl","fileContent","S3CompatibleService","regionalHost","objectAcl","requiredOption","awsS3","backblaze_b2_default","bunny_storage_default","JURISDICTION_INFIXES","getEndpoint","accountId","jurisdiction","cloudflare_r2_default","digitalocean_spaces_default","ENDPOINT_HOSTNAME_REGEX","parseEndpoint","neon_object_storage_default","scaleway_default","projectId","getPublicUrl","supabase_default","LEGACY_CDN_ORIGIN","PROJECT_CDN_URL_REGEX","getPublicKey","getFileKind","parseResults","cdnBase","isImage","defaultOperations","autoFilename","getKeys","secretKey","publicKey","secretKeyRequired","getRESTHeaders","getCDNOrigin","nextUrl","generateSignature","expire","allCloudStorageServices","backblazeB2","bunnyStorage","cloudflareR2","digitaloceanSpaces","neonObjectStorage","scaleway","supabase","list$4","search$3","formData","cdnOrigin","CLOUD_MEDIA_LIBRARY_NAMES","URL_REGEX","getAssetBaseURL","getMediaFieldSource","assetBaseURL","getSourceURL","getMediaFieldURL","getRichTextMediaSource","customComponentNames","componentNames","getRichTextMediaURL","COMPONENT_NAME_PREFIX_REGEX","stripComponentNamePrefix","DEFAULT_MODES","NODE_NAME_MAP","INLINE_BUTTONS","BLOCK_BUTTONS","OPTIONAL_BUTTONS","DEFAULT_BUTTONS","BUTTON_NAME_MAP","BUTTON_COMPONENTS","BUILTIN_COMPONENTS","getValueFormat","getEditorComponentNames","defaultConfig","getEditorComponentDefs","getToolbarButtons","buttonNames","resolveAllowNestedComponents","getRootFieldName","getAvailableComponentDefs","inEditorComponent","allowNestedComponents","parentComponentNames","getStaleExtraValueKeys","extraValues","isPresent","parseHTMLFragment","parseStartTag","serializeStartTag","endTag","outerHTML","isInsideTag","MEDIA_URL_ATTRIBUTES","MEDIA_TAG_NAMES","MEDIA_TAG_SELECTOR","MEDIA_TAG_NAME_PATTERN","MEDIA_TAG_PATTERN","MEDIA_TAG_REGEX","GLOBAL_MEDIA_TAG_REGEX","DEFERRED_ATTRIBUTE_PREFIX","MEDIA_QUERY_SELECTOR","getMediaElements","deferMediaURLs","parseSrcset","urlStart","srcset","descriptorEnd","stringifySrcset","mapSrcset","newCandidates","getNewURL","resolveMediaURLs","resolveURL","deferredName","updated","localName","MARKDOWN_IMAGE_REGEX","MEDIA_START_TAG_PATTERN","MARKDOWN_MEDIA_REGEX","parseMediaSource","bracketed","fragmentIndex","updateMediaElementURLs","rewriteMediaStartTag","updateMarkdownMediaURLs","newSource","updateHTMLMediaURLs","updateRichTextMediaURLs","getRichTextMediaSources","replaceRichTextMediaSources","newSources","getComparableAssetURL","createMatcher","matcher","createMediaSourceResolver","matchAssetURL","forms","getURLTargets","byURL","getMatchingTargets","whole","partial","mayReferToTargets","hasTarget","tagCount","matchField","replacing","findAssetReferences","exhaustive","every","isDone","matchArgs","onMatch","getEntriesByAssetURL","findEntriesByAssets","getEntriesByAssets","getEntriesUsingTargets","getAssetReferences","references","extractExifData","exif","DateTimeOriginal","latitude","longitude","probeSource","eventType","getInfo","getImageSourceInfo","getMediaSourceInfo","getSourceInfo","getMediaMetadata","cachedDetails","getExternalAssetDetails","getExternalAssetUsedEntries","getExternalAssetsUsedEntries","CONCURRENCY","externalAssetAvailability","checkedIds","probeURL","isMixedContent","checkExternalAssetAvailability","checkExternalAssetsAvailability","unchecked","isLinkedURL","createLinkedAsset","getFieldWidgets","collectLinkedAssets","widgets","linkedAssets","linkedFilesService","getSharedCredentials","setApiKey","isInvalidApiKey","saveApiKey","getApiKey","isSharedApiKey","getDeployHook","deployHookURL","deployHookAuthHeader","isSharedDeployHook","enabledCloudServices","getCloudService","getCloudServicePath","getExternalAssetPath","canPreviewExternalAsset","mergeUploadedExternalAssets","uploadedIds","uploaded","selectedCloudService","externalAssets","hasFolderSupport","externalFolders","selectedExternalDirPath","focusedExternalSubfolder","showNewExternalFolderDialog","renamingExternalSubfolder","deletingExternalSubfolder","externalAssetCounts","externalAssetsError","externalAssetsTruncated","selectedExternalAssets","selectedExternalAssetIdSet","focusedExternalAsset","pruneExternalAssetSelection","kept","selectedOrFocusedExternalAssets","overlaidExternalAssetId","renamingExternalAsset","externalAssetSearchTerms","getFetchOptions","password","hasAuthInfo","resetExternalAssets","browseExternalFolder","assetListSettings","defaultView","currentView","getSettingsKey","initSettings","savedView","getNameSortValue","sortAssets","_assets","showAssetOverlay","showUploadAssetsDialog","showNewSubfolderDialog","showUploadAssetsConfirmDialog","getFolderLabelByCollection","selectedFolderAssets","listedAssets","listedSubfolders","folderSummary","subfolder","getAdjacentAssets","isCurrent","canPreview","previousAssetGroups","sortConditions","filterConditions","groupConditions","sortedAssets","filteredAssets","assetGroups","listedAssetIndexMap","_backend","initSettings$2","showContentOverlay","showDuplicateToast","activeInlineEditors","translatorApiKeyDialogState","copyFromLocaleToast","listItemClipboardToast","editorFirstPane","editorSecondPane","selectAssetsView","getEntryEditorPath","pullRequestNumber","getUnpublishedEntryEditorPath","openNewTab","features","noopener","hasOverlay","selectedPageName","announcedPageStatus","mainAreaTitle","overlayTitle","parseLocation","activeTransition","transitionHolds","transitionSkipped","stopWaitingForHolds","holdViewTransition","waitForTransitionHolds","skipped","startViewTransition","updateContent","transitionType","getTransitionTypeFromHistory","oldIndex","oldURL","getTransitionTypeFromPaths","oldPath","inSameSection","routeRegex","oldPathSegmentCount","newPathSegmentCount","updateContentFromHashChange","isTrusted","goto","replaceState","notifyChange","LEGACY_ENTRY_ROUTE_REGEX","redirectLegacyEntryLink","STANDALONE_PAGE_NAMES","PAGE_SEARCH_MODES","resolveRoute","pageNames","pageName","goBack","sameDocument","returnTo","getEntryEditorBackPath","openProductionSite","displayURL","siteURL","titleOwner","Page_container_main_area","primaryToolbar","secondaryToolbar","mainContent","secondarySidebar","main","Back_button","useShortcut","onclick","Main_area","actions","h2","additions_UpdateInfobar","graphemeSegmenter","LETTER_REGEX","CJK_REGEX","getFirstLetter","getInitials","Avatar","username","brokenSrc","Panel_container","section","h3","CONFIG_SECTION","getAdminSections","getAdminSectionPath","lastAdminSectionKey","getAdminLink","sections","getAdminSectionKey","getAdminPageAnnouncement","sectionKey","isSmallScreen","IMAGE_DATA_URL_REGEX","DEFAULT_APP_LOGO_URL","appTitle","appLogoURL","appLogoType","getDataURL","transformedBlob","appIconURLs","superseded","logoURL","iconURLs","small","large","appManifestURL","manifest","getLatestVersion","packageName","compareVersions","isNewerVersion","latestVersion","isUpdateAvailable","resolvedVersion","getAuthRoot","apiRoot","MAX_DIR_LOOKUPS","COMMIT_SHA_REGEX","createCachedDirSHALookup","lookups","lookUp","getSkipCIOptions","skipCIConfigured","isPublishingCommit","listTrees","fetched","completed","getListing","fetchTreeListing","cacheable","listing","listings","currentLevel","isRelationFieldOf","getPendingEntriesByCollection","getNewPendingEntriesByCollection","getDraftValueSources","currentValues","getPendingEntryValueSources","isReferencedIn","fieldArgs","getReferencedPendingEntrySet","referenced","grow","newlyReferenced","getReferencedEditedEntries","getReferencedPendingEntries","getCodeKeys","outputCodeOnly","isCodeValueKey","formatSummary","hasSingleSubField","itemKeyPath","listFieldConfig","getUnknownTypeMessage","warnUnknownType","resolveVariableType","getTypedSubKeyPath","getLocalizedRelationValue","getLocalizedFieldValue","DUPLICATE_IF_EMPTY_FIELD_TYPES","isDuplicateIfEmptyField","getMainValueKeyPath","isFieldEmpty","findDuplicateIfEmptyField","getFieldConfig","fieldKeyPath","parentFieldConfig","followsDefaultLocale","previousValue","getListFieldInfo","hasMultiSubFields","hasVariableTypes","hasDuplicatedSubField","isPairedList","getPairedListKeyPaths","isSingleItemList","itemCount","formatObjectSummary","getListItemKey","tagListItems","assignIds","getValueOwnerField","ownerKeyPath","PAIR_KEY_PATH_REGEX","getKeyValueField","getPairsFromContent","setPairs","alignPairOrder","referenceKeys","referenceContent","orderedKeys","groupKeyPathsByParent","isRealKey","isPairOrderModified","currentValueMap","originalGroups","originalValues","keyPaths","originalKeyPaths","INTERNAL_PROP_REGEX","STATIC_DRAFT_KEYS","autoDupSuspendDepth","isAutoDuplicationEnabled","suspendAutoDuplication","release","revokeDraftFileURLs","filterRealValues","collectFieldValues","dropEmptyPlaceholders","relative","isValueMapModified","realKeyCount","originalValueMap","getComparedLocales","originalLocales","currentLocales","areValuesModified","isDraftModified","originalSlugs","currentSlugs","getDraftValues","nameTemplate","VERSION_KEY","getValueMapVersion","SUBTREE_VERSIONS_KEY","SubtreeVersion","getSubtreeVersion","versions","createValueMap","subtreeVersions","getSubtreeKeyPaths","addSubtreeVersions","subtreeKeyPath","countWrite","ownKeys","onSet","onDelete","snapshotCache","getValueMapSnapshot","valueStoreKey","snapshot$2","getValueMapSnapshots","getFieldValueMapSnapshot","ROOT_ATTRIBUTE","rootElementMap","originalValueSnapshots","getOriginalValueSnapshots","getComparedDraft","EntryDraftState","setEntryDraftContext","entryDraft","getEntryDraftContext","createEntryDraftMountContext","setEntryDraftRoot","getEntryDraftByElement","getManagedKey","getAliasesKey","getAliasKeyPaths","aliasesKey","removeAliases","normalizeSitePath","getSlugRegex","getEarlierEntryPaths","slugRegex","existingSubPaths","earlierSubPath","slugIsPath","captured","earlierSlug","getEntryKey","getDraftEntryKey","createTruncationError","apiLabel","joinTextParts","texts","isAnswer","getBearerHeaders","postJSON","errorData","errorMessage","chatCompletions","systemPrompt","maxTokens","reasoning","extraBody","responses","textItem","defaultHeaders","complete","endpoint$3","endpoint$2","model","responseFormat","endpoint$1","allAiServices","anthropic","deepseek","google","mistral","openai","createLinkedCredit","createAttributedCredit","profileURL","STOCK_CREDIT_REGEX","removeStockCredits","getSupportedLocale","supportedLocales","fetchJSON","fetchPagedResults","parsePage","hasMore","createStockFetchers","getHeaders","listURL","getListParams","listKey","getSearchParams","searchURL","searchKey","SUPPORTED_LOCALES","ENDPOINT","SEARCH_PARAMS","DESCRIPTION_REGEX","getLocale","list$3","search$2","nextPage","medium","large2x","photographer","pexels_default","LIMIT","TOTAL_PAGES","FETCH_PAGES","landscape","pw","picsum_default","pages","webformatURL","imageWidth","imageHeight","largeImageURL","previewURL","pageURL","list$1","search$1","parseResults$1","pixabay_default","CREDIT_LINK_PARAMS","thumb","regular","links","totalPages","allStockAssetProviders","downloadTrackingURL","getStockAssetMediaLibraryOptions","allProviderNames","providers","normalizeLanguage","createTranslationSystemPrompt","baseInstructions","lineBreakInstructions","responseInstructions","sourceLanguageName","targetLanguageName","createTranslationUserPrompt","parseAiTranslationResponse","translations","expectedCount","createLanguageResolver","sourceLanguage","targetLanguage","availability$1","resolveLanguageNames","createAiTranslate","sourceLangName","targetLangName","extraOptions","createAiTranslationService","anthropic_default","anthropic_exports","deepseek_default","deepseek_exports","SUPPORTED_LANGUAGES","LANGUAGE_ALIASES","scriptTag","MAX_SEGMENTS_PER_REQUEST","MAX_BYTES_PER_REQUEST","chunkTexts","google_default","resolveLanguages","allTranslationServices","google_exports","googleAi","mistral_exports","openai_exports","machineTranslationServices","translator","defaultTranslationService","getCloudStorageServiceEntries","getStockPhotoServiceEntries","getApiKeyServiceGroups","findInvalidApiKey","apiKeys","lastCheckTime","commitQueue","diffStores","entryIds","entriesBefore","assetPaths","assetsBefore","entriesAfter","assetsAfter","entryIdsAfter","assetPathsAfter","rootDirTree","isRootDirUnchanged","checkForRemoteChanges","maxAge","suspendChecksWhile","previousCommit","getEntryAssetVersion","getUsedAssetPaths","mergeWorkflowAssets","assetMap","existing","removeBranchAssets","removeWorkflowAssets","removeWorkflowAssetsAt","publishWorkflowAssets","_workflow","publishedAsset","isEntryReadonly","getReadonlyEntryLabel","isEntryEditableAlong","getEntryCollection","assignToCollection","findOtherCollectionFolder","otherFolders","getLinkingKey","findPublishedEntry","linkingKey","completeEntry","parseCompanions","isCreatable","companionCollectionName","companionFiles","findOwnEntries","vacatedPaths","renames","getDepth","movedEntry","createUnpublishedEntryProps","parsePullRequestContents","listedEntryFiles","vacatedEntryFiles","targetFiles","handOverCandidates","handedOver","handedOverEntries","handedOverFolders","remainingLocales","ownPaths","convertPullRequests","lastLoad","pendingReload","recordLoad","isWorkflowReady","backendConfig","getReadyWorkflow","startLoadingPullRequests","loadUnpublishedEntries","groupByBranch","isSameList","carryOverCompanions","carryOverEntries","carried","getHeadSHA","findUpToDateBranches","openBranches","reload","upToDate","publishing","changedBranches","assetWorkflow","reloadUnpublishedEntries","fresh","checkForWorkflowChanges","workflowMaxAge","checkOnSchedule","checkOnReturn","startRemoteChangePolling","stopRemoteChangePolling","timer$1","DEPLOY_STATE_MESSAGES","pageLiveness","MAX_CACHED_PAGES","prune","cutoff","dropped","pingURL","recheck","recheckPending","sameOrigin","resetPageLiveness","report","currentToken","runCount","cancelDeployResolution","getDeployTargets","prodSHA","prBranch","deployTargets","canResolveDeployments","showLinks","isFresh","markChecking","markLookupPending","pendingOnly","refreshProductionSHA","initDeployments","encodeMagicLinkData","decodeMagicLinkData","encodedData","mergedEntries","isBuildDone","productionBuildDone","deployingEntries","lastDone","trackDeployingEntry","resetDeployingEntries","MAGIC_LINK_REGEX","auth","magicLinkConfirmation","clearIntegrationCredentials","clearMagicLinkCredentials","magicLinkAccount","clearUserCache","clearUserCacheIfNeeded","resetError","logError","parseMagicLink","copiedPrefs","getUserCache","isUserCache","getCachedBackendName","trySelectBackend","_backendName","getBackend","confirmMagicLink","copyMagicLinkPrefs","loadRepositoryData","signInAutomatically","magicLinkUser","verified","signInManually","credentials","signInWithNewPassword","newPassword","UNSUPPORTED_FUNC_NAMES","Boolean_editor","bind_get","bind_set","Boolean_preview","deferDraftWrite","isInEditorComponent","getFieldEditorContext","setFieldEditorContext","pendingFieldUpdates","fieldUpdatePending","trackPendingFieldUpdate","awaitPendingFieldUpdates","afterPendingFieldUpdates","trackPendingWhile","getPending","$.fallback","outputKeys","codeKeyPath","langKeyPath","syncedInputValues","setInputValue","setCurrentValue","valueStore","Code_editor$1","Code_preview","HEX_COLOR_REGEX","hexToInt","formatHexAsRGB","alpha","enableAlpha","RGB_HEX_REGEX","parseColorFieldValue","getColorFieldValue","rgb","getColorFieldInputValues","Color_editor","inputAlphaValue","allowInput","Color_preview","Compute_editor","indexContent","childSegmentMap","siblings","hasChildKeys","getItemIndexes","indexListItems","itemMap","nextDotIndex","getListItemIndexes","TOKEN_REGEX","OPERAND_REGEX","FUNCTIONS","PARSED_EXPRESSION_CACHE_SIZE","parsedExpressionCache","tokenize","tagIndex","allItemsTagIndexes","parseAdditive","parseBinary","parseOperand","parseArgs","parsePrimary","parseUnary","parseMultiplicative","parseExpression","literals","normalizeValue","toOperand","evaluateAggregate","operands","evaluate","evaluateNode","evaluateExpression","generatedUuidMap","getListIndex","isUuidTag","parseUuidTags","rawLiterals","valueTemplate","firstOtherIndex","lastOtherIndex","hasUuidTag","getUuids","uuidTags","extractedUuids","generatedUuids","extractedIndex","extractable","getNumericValue","stringOutput","formatComputedValue","listItemIndexMap","expandWildcards","lastWildcardIndex","ownSegments","ownKeyPath","expand","ownIndex","pathSegment","itemIndex","getComponentValues","getFieldTagSource","usesRawValue","numeric","resolveFieldTag","sourceValueMap","sourceComponentName","rawValue","hasRawValue","sourceFieldConfig","listFormatter","getComputedValue","uuids","uuidIndex","resolvePlaceholder","fieldKeyPaths","Compute_preview","Cloudinary_panel","onInsert","outputFilenameOnly","useTransformations","resources","publicId","Asset_path","strong","$$arg0","bdi","Breadcrumb","folded","canFold","getName","measure","em","leastWidths","natural","classList","least","nav","fragment_10","text_2","text_3","Picker_breadcrumb","onNavigate","ancestorPath","Simple_image_grid_item","viewType","focusPageContainer","rememberFocus","watchFocus","focusList","focusOverlay","keepFocusIn","noCheckIcon","Subfolder_strip","onOpen","selectedPaths","wasSelected","focusScope","hadFocus","Simple_image_grid","gridId","onOpenSubfolder","selectedSubfolderPaths","onSelectSubfolder","Name_input_dialog","componentId","blockedMessage","oninput","note","submitted","p_1","Subfolder_name_dialog","nameEdited","THUMBNAIL_ROOT_MARGIN","THUMBNAIL_DWELL_TIME","lastScrollTime","trackingScroll","trackScroll","whenThumbnailShown","cancelWait","stopObserving","createPreviewLifecycle","ownedURLs","lookedUpSrc","currentAsset","destroyed","resolveTransition","cancelThumbnailWait","ownURL","releaseOwnedURL","releaseTransition","previousSrc","nextSrc","flushQueued","runQueuedFlush","requestFlushSync","Asset_preview","blurBackground","cover","checkerboard","dissolve","controls","holdTransition","mediaElement","failedSource","loadedSource","hasError","blurImageURL","resolvedSrc","mediaSrc","isThumbnail","srcRequestGuard","lifecycle","updateSrc","isLatest","requestedAsset","checkLoaded","isReady","currentSource","currentSrc","audio","img_1","getAuthKeyLabel","defaultLabel","sharedLabel","compatibleAPI","getServiceDescription","Cloud_service_auth","onAuth","serviceType","isStockAssets","authState","fragment_4","Image","Remove_button","fileSizeFormatterCache","formatSize","kb","mb","gb","tb","getFileTypeLabel","Upload_assets_preview","transformedFileMap","removable","showThumbnail","thumbnailURLs","getThumbnailURL","listedFiles","originalFile","Image$1","fragment_3","getMovableAssets","canMoveAssets","canMoveToService","canMoveToFolder","canMoveAssetsTo","canMoveExternalAssets","getMovableExternalAssets","destination","getDraggedFiles","selectedFiles","getDraggedAssets","getDraggedExternalAssets","canMoveRequestTo","sourceService","DRAGOVER_CLASS","isAssetDrag","createAssetDragSource","onDragStart","createAssetDropTarget","canDrop","onDragOver","droppable","onDragLeave","onDrop","Drop_zone","typeMismatchAlert","formatList","acceptedImageFormats","showUploadButton","showFilePreview","filterDroppedFiles","dropTarget","typeMismatch","showTypeMismatchAlertDialog","showDefaultContent","openFilePicker","updateFileList","text_4","FilePicker","_files","hasFiles","filteredFileList","Rejected_files_alert_dialog","oversizedFileNames","invalidFileNames","mismatchedFileNames","mismatched","sortServicesByName","nameA","nameB","isFolderOffered","selectFolder","getFirstDefaultLibraryName","isDefaultLibraryEnabled","assetLibraryFolderMap","getInitialLibraryName","firstDefaultLibraryName","preferredName","hasPendingFiles","externalServiceEntries","getStockAssetProviderEntries","hotlinking","getPickedFolderPublicPaths","browsingSubfolders","getUnsavedAssetSubfolderPath","targetFolderPath","getInsertedResources","resource","getSelectionWithResource","isSame","getLocationResources","enteredURL","trackInsertedExternalAssets","trackDownload","UPDATE_TOAST_DEFAULT_STATE","contentUpdatesToast","assetUpdatesToast","assetCommitToast","refreshFocusedAssets","COMMIT_CANCELLED","commitMessageRequest","lastAddition","isCommitCancelled","runCommit","getCommitMessagePromptMode","requestCommitMessage","defaultMessage","promptCommitMessage","runningMessages","runAssetCommit","outcome","createAssetMoveChange","getAssetReferenceTarget","parseField","keyPathList","createKeyPathList","mapEntryContent","getContent","extractDateTime","dateFieldName","inSlugTimeZone","fillEntryPathTemplate","pathTemplate","getPreviewPath","getEntryPreviewURL","_baseURL","previewPath","getEntryRepoBlobURL","getSitePath","getPermalinkKey","fillPermalink","permalinkKey","sitePath","refreshPermalinks","copiedContent","wildcardKeyPathRegexCache","getWildcardKeyPathRegex","INDEXED_KEY_PATH_REGEX","isArrayItemKeyPath","parentKey","sortedMap","keepArrayItem","copyProperty","unsortedMap","isTomlOutput","tomlDate","omitEmptyOptionalFields","childKeys","OPAQUE_FIELD_TYPES","isOpaqueField","copyKeyValueField","pairKeyPaths","copyArgs","copyOpaqueField","addObjectPlaceholder","copyField","isConcrete","copyWildcardField","resolvedField","concreteKeyPath","finalizeContent","removeTomlNulls","serializeContent","mappedContent","collectFieldComments","getFieldComments","getSingleFileComments","buildSingleFileContent","localeContents","nonDefaultContent","getRawJSON","createReplacer","rawJSON","formatJSON","indentStyle","indentSize","formatTOML","stringifyTOML","addYAMLComments","comments","YAML_1_1_BOOL_REGEX","YAML_1_1_NUMBER_REGEX","isAmbiguousYAMLString","formatYAML","legacyQuote","toStringOptions","FORMATTERS","formatSyntax","isFrontMatterFormat","formatFrontMatter","formatWithBuiltInFormatter","valueSources","formatEntryFile","configuredFormatter","configuredFormat","customFormat","customFormatter","hasBuiltInFormatter","formatEntryData","getSavedFileConfig","resolveCacheDB","provided","getPreviousSha","isSingleFileEntry","buildEntryFileChanges","plan","planChange","previousSha","getArrayFileCollection","groupArrayFileChanges","applyArrayFileChanges","slots","slotsByOrigin","slot","arrayOrder","reordered","arrayItem","combineArrayFileChanges","arrayFileUpdates","fileChanges","createArrayFileEntries","isInFile","previousEntries","fileSavingEntries","savingEntries","newSavingEntries","newItemCount","savingEntry","previousEntry","getCommitAuthor","userData","savedEntryIds","arrayFileEntries","arrayFilePaths","arrayFileEntrySet","excludingPaths","savedAssets","commitOptions","missedRemoteChanges","headBefore","combinedChanges","savedArrayFileEntries","savingAssets","savedAsset","updateStores$5","immutableLoaded","loadImmutable","preloadImmutable","getImmutable","assetURLUpdates","urlUpdates","waitForAssetURL","AssetProxy","#asset","ExternalAssetProxy","UnsavedAssetProxy","#file","warnedOnceMap","warningMessages","warnDeprecation","createEntryMap","otherLocales","associatedAssets","convertEntryToMap","createGetAsset","unsavedFile","referencedEntryLookupCache","getReferencedEntryLookup","lookup","getMetaDataPath","warnOnRead","notSetValue","getMetaData","metaData","refEntriesCache","legacyKeys","legacyListKeys","refCollection","refFile","flatContent","metaDataPath","legacyKey","fieldMetaData","metaDataMap","buildEntry","getPreviewAssetCache","getAssociatedPreviewAssets","buildPreviewData","fieldsMetaData","thumbnailFieldRegexCache","isThumbnailPath","getEntryThumbnail","contentKeys","_thumbnailFieldNames","loadEntryThumbnail","onLoad","entryIdsByFolderCache","getEntryIdsByFolder","getAssetsByFolder","getAssetsBelowFolder","mapEntryFolderPaths","getFolderPath","getOwnedEntryFolderPaths","getEntryFolderPaths","getAssociatedAssets","entryFolderPaths","existingPaths","entryIdsByFolder","isDescendantEntryFolder","getEntryRelativeAssetVersions","collectSharedAssets","sharedAssets","assetLists","getReferringEntryIds","referringEntries","getEntriesRelativeAssets","referringIds","getEntryRelativeAssets","SUPPORTED_EVENT_TYPES","UPDATABLE_EVENT_TYPES","callEventHooks","_login","mainLocale","updatedMap","addAlias","originalSlug","originalContent","getMovedFolders","movedFolders","oldFolderPath","newFolderPath","getPathInMovedFolder","buildEntryAssetMoveChanges","noChanges","takenPaths","moveChanges","getMovedAssetPath","movedPath","getLocaleTargets","rewriteEntryAssetReferences","targetCache","getTargets","createAssetNameTemplate","getAssetNameContext","defaultLocaleSlug","fillAssetNameTemplate","collectionFileName","getPendingFileName","getConfiguredSlugTemplate","hasLegacySlugEditorTag","getEditableStages","getSlugOptions","configuredTemplate","legacyLocalized","localized","editorOnly","editorRequired","NON_FIELD_TAGS","getLocalizingKeyPaths","hasLocalizedSlugs","getOwnFolderName","hasLocalizedFolders","getLocalizedFolderName","indexEntry","indexFileNames","localizedSubPath","getAllEntries","localizeDirPath","configuredIndexFileName","resolveBlobURLs","randomValueMaps","getRandomValues","getChosenDirPath","getSlugDirPath","ENTRY_DATE_FIELD_NAMES","getEntryDateTimeParts","getCurrentSlug","getFillSlugOptions","hasTypedSlug","editorValue","getSlugTemplate","templateOnly","isSlugAutoNumbered","getNextSlugNumber","getLocalizedSlug","_slug","localizingKeyPaths","getLocalizedSlugs","getCanonicalSlug","localizedSlugs","fillSlugOptions","getSlugs","buildPathByStructure","buildCustomEntryPath","originalSubPath","keepsOriginalPath","getKeptSubPath","createEntryPath","useCustomPath","fillTemplateIfNeeded","pathString","resolveInternalPath","resolvePublicPath","resolvedPath","resolveAssetFolderPaths","getAssetFolderPaths","createPublicURL","getVacatedAssetFolderPath","getAssetSavingInfo","assetFolderPaths","resolvedInternalPath","resolvedPublicPath","vacatedFolderPath","getNames","replaceBlobURL","savingAssetsInSameFolder","dupFile","pendingFileName","namesInSave","hasName","takenNamesInSameFolder","assetNamesMovingIn","replacedName","assetPath","savingAssetProps","publicURL","setPermalink","getSubPath","getNestedCanonicalSlug","replaceBlobURLs","_globalAssetFolder","isMirrored","replaceBlobArgs","MULTILINE_FIELD_TYPES","trimValue","normalizeFieldValue","normalizeLocaleContent","createBaseSavingEntryData","normalizeArgs","removeDisabledLocales","getArrayItemTarget","planSingleFileChange","recreate","planMultiFileChange","createSavingEntryData","localizedEntryMap","runPreSave","preparePendingEntryCommit","getDraftBaseProps","localeEntries","addSavingEntryData","draftProps","_changes","collectEntryChanges","draftBaseProps","getFallbackURL","getRenamedReference","oldName","getMoveBlockedMessage","readonlyEntries","planReferenceRewrite","usedEntries","rewriteEntryReferences","replacingTargets","updatingEntries","updatingEntryMap","getNewAssetReference","collectEntryChangesFromAssets","movingAssets","collectReferenceChanges","saveReferenceChanges","newURLs","movedAssets","notify","moveAssets","extraChanges","updateStores$4","runWithUndo","finish","getExternalChangeBlockedMessage","planExternalReferenceRewrite","moveFilesWithReferences","moves","movedAsset","isValidImage","convertHEIC","isUsableImage","processFile","slugifyFilename","maxFileSize","nameContext","preTransformFile","partitionProcessedFiles","oversized","limitFileProcessing","getInitialProcessedAssets","processedAssets","originalFiles","processedResults","externalAssetsToast","uploadingExternalAssets","getSharedMediaLibraryOptions","reportError","reportSuccess","setAssets","forgetDeletedAssets","deletedIds","updateAsset","swap","oldAsset","newAsset","pruneSelection","focusedPath","latestLoadId","fetchExternalAssetBlob","loadExternalAssets","loadId","fetchOptions","prepareExternalUploads","oversizedFiles","invalidFiles","uploadExternalAssets","originalAsset","validFiles","reportError$1","deleteExternalAssets","renameExternalAsset","renamedAsset","getExternalSubfolderAssets","getExternalFolderTree","getExternalFolderContents","createExternalFolder","renameExternalFolder","newDirPath","rebase","deleteExternalFolder","persistentCaches","getNormalizedValueCache","ACCENT_REGEX","CYRILLIC_ACCENT_REGEX","stripAccents","cyrillic","marks","ASCII_REGEX","getNormalizedValue","normalizedValueCache","cachedValue","normalizedValue","hasMatch","hasAllMatches","EXTERNAL_ASSET_SORT_KEY_TYPES","EXTERNAL_ASSET_SORT_KEYS","externalAssetSortKeys","getSortValue","sortExternalAssets","filterExternalAssets","getGroupValue","groupExternalAssets","externalAssetViewGroups","searchExternalAssets","normalizedTerms","getExternalSubfolders","getExternalAssetsInDir","getExternalFolderLabel","browsingExternalFolders","listedExternalSubfolders","sortedExternalAssets","listedExternalAssets","externalFolderSummary","browsing","externalAssetGroups","listedExternalAssetIndexMap","listedIds","External_assets_panel","breadcrumb","searchQuery","panelAssets","_kind","onSelectionChange","selectedResources","browse","createFolder","allMediaLibraryOptions","hasConfig","newFolderDialogOpen","rejectedFilesAlert","listFetchOptions","folderLabel","requestGuard","getAssets","emptyFolders","getResource","canUpload","uploadFiles","prepared","canCreateFolder","showNewFolderDialog","createNewFolder","selectedURLs","requestedSelection","pickedAssets","trackDownloads","loadAuthInfo","RejectedFilesAlertDialog","node_12","Assets_panel","emptyMessage","listedItems","filteredItems","selectedAssetKeys","assetKind","computed_const_1","Internal_assets_panel","uploadDisabled","dropZone","DropZone","Location_selector","locationOption","Selector","Selector_1","$$array_1","cloudinaryActivated","$$array_2","fieldConfigMapCache","getFieldConfigMap","previewDataCache","previewDataCacheFlushScheduled","getPreviewData","draftCache","customFieldInstances","validationCache","pendingValidations","validationSequences","getCacheKey","registerCustomFieldInstance","unregisterCustomFieldInstance","resetCustomFieldValidation","parseValidationResult","triggerCustomFieldValidation","awaitCustomFieldValidations","validateCustomField","validity","validateDateTimeField","rangeUnderflow","rangeOverflow","timeFormatter","formatTime","getFormattedDateTime","datePart","timePart","getRangeErrorMessage","limitValue","limitKey","canAddMultiValue","getFieldValidationMessages","isDatetime","parsedDateTimeConf","minlength","getPathValidationMessages","getInvalidFields","extraValueMap","validateNumberField","invalidNumber","hasNumber","validateStringField","tooShort","tooLong","VALIDATE_FIELD_FUNCTIONS","validatePattern","validation","validateScalarField","getCodeField","resolveCodeField","validities","DEFAULT_VALIDITY","finalizeValidity","finalized","validateItemCount","KEY_PATH_REGEX","validateKeyValueField","isKeyValueField","isKeyValue","LEADING_INDEX_REGEX","validateListField","getListItems","resolveMediaValue","prepareListField","skip","PREPARE_FIELD_FUNCTIONS","relaxEmptyFieldValidity","enforceRequired","getWorkflowStage","isRequiredEnforced","getOtherEntries","inFolder","getTakenSlugs","otherEntries","ownSlug","slugCanHaveSpaces","validateSlug","trimmedSlug","allowSpaces","takenSlugs","getSlugValidationMessage","isSlugEditable","slugEditor","validateSlugs","valid","isWholeSlug","editorValueIsSlug","LIST_ITEM_INDEX_REGEX","isPerEntryField","UNIQUE_FIELD_TYPES","normalizeUniqueValue","isUniqueField","isValueTaken","getAutoNowStages","autoNow","isAutoNowField","isAutoNowDue","assignAutoNowValues","valueCache","getMaxEntryNumber","assignManualSortOrder","maxOrder","nextOrder","isAutoIncrementField","getNextNumber","assignAutoIncrementValues","defaultValueMap","LIST_ITEM_SUBFIELD_REGEX","DIRECT_ITEM_SUFFIX_REGEX","recordValidationMessages","validateAnyField","mapKeyInfo","prepareField","validateFieldFn","validateField","revalidateSingleField","keyValueField","stateKeyPath","revalidateField","keyAdded","validateList","validateArgs","getConfig","validateListItself","validationMessages","validateParentField","getParentField","validateKeyPath","viaSubKey","validateValueEntry","ancestorKeyPath","ancestorConfig","pairValid","codeValid","listValid","validateItems","validateFields","valueEntries","createSyntheticDraft","buildEntryUpdateChanges","compactList","remainingValues","getFieldBlockers","dedupeBlockers","buildTargetChanges","savingTargets","getReferenceTargets","comparableURL","cutMarkup","nextBreak","blankBefore","blankAfter","MEDIA_WRAPPER_TAG_NAMES","isMediaElementEmpty","removeMediaElement","removeHTMLMedia","STICKY_LINKED_IMAGE_REGEX","getLinkedImageLength","linkedImage","removeMarkdownMedia","linkedImageLength","removeEmbeddedMedia","removeAssetReferences","updatedContent","staleListItems","richTextField","createAssetDeletionPlan","referenceTargets","entryReferences","referencesByLocale","updatedLocales","localeReferences","lastPlan","planAssetDeletion","allAssetList","deleteAssets","cascadeChanges","updateStores$3","createSubfolderFileFilter","nestedFolderPrefixes","nestedPrefix","getSubfolderAssets","getSubfolderConfigFiles","createSubfolder","configFile","renameSubfolder","deleteSubfolder","Create_subfolder_dialog","New_folder_button","floating","getSingleTagName","hasConfiguredTableColumns","classifyColumnKey","getDefaultTableColumns","excludedKeys","getColumnLabel","resolveTableColumns","classified","getTableColumns","configured","relationCellCache","getTableCellValue","locale$4","entryCache","getColumnSortKey","entryListSettings","getEntryViewTypes","pickOfferedViewType","getEntryViewType","reordering","isLargeScreen","viewBeforeReorder","getEntryOrderKey","sort","_view","View_switcher","ICONS","selectedType","isGridView","hasCompactToggle","switchView","getPendingUploadAction","pendingFileCount","fillPrefixTemplate","fillLibraryPrefix","duplicatesRequest","checkDuplicates","dupFiles","EMPTY_PATH_SEGMENT_REGEX","getAssetLibraryFolderMap","fieldAssetFolder","fileAssetFolder","collectionAssetFolder","entryAssetFolder","globalFolder","getDefaultAssetFolder","folderMap","getFieldAssetFolder","getTargetFolderPath","getUnsavedFileName","getUnsavedFileDisplayPath","getFileDisplayPath","unsavedFileName","decodedValue","isInTargetFolder","isAssetInSelectedFolder","resolveUnsavedAssetPaths","unsavedAssets","namesByDir","replacedPaths","resolvedUnsavedAssets","namesInDir","listAssets","isInSelectedFolder","uncheckedFiles","hasSameAsset","getExistingBlobURL","foundURL","convertFileItemToAsset","getUnsavedAssets","getSavedAssetsForEntry","expectedPrefix","getMismatchedResult","processResource","existingBlobURL","processedFile","libraryConfig","existingAsset","credit","NO_ASSETS","createFolderAssetListing","droppedAssets","Select_assets_dialog","elementIdPrefix","headerItems","isDefaultLibrary","rawSearchTerms","canBrowseCloudLibrary","isStockLibrary","New_folder_button$2","externalAssetsPanel","isCloudLibrary","canEnterURL","pendingFiles","pendingFilesRejected","showURLInput","enabledStockAssetProviderEntries","enabledExternalServiceEntries","selectedFolder","assetListing","browsedPath","browsedDirAssets","selectedFolderLabel","isEnabledMediaService","filledPrefix","pickedFolderPublicPaths","otherPaths","navigate","resetValues","onOk","headerExtra","footerExtra","root_7","node_13","fragment_17","consequent_13","serviceProps","root_6","ExternalAssetsPanel","consequent_14","consequent_15","consequent_16","consequent_17","text_5","Conflict_resolution_dialog","respond","footer","getMediaFieldAssetOptions","getDroppedFileDestination","uploadableEntries","processResources","getRejectedFileNames","oversizedFileName","invalidFileName","mismatchedFileName","toFieldValue","resolveSelectionResult","getCustomFieldAssetOptions","addFileToDraft","namedFile","getPickedAssetKind","getPickedBlob","resolvePickedResources","Asset_picker","assetOptions","mediaFieldConfig","pick","pickOptions","rejected","fieldStateContext","createContext","reactDom","reactDomLoaded","loadReactDom","preloadReactDom","createReactRoot","mountReactNode","detached","createReactRenderer","getContainer","PATH_MATCH_REGEX","getListItemMatcher","itemKeyPaths","listGetFieldArgs","hasItem","hasParentInLocale","forEachCopyTargetLocale","matchesListItems","copyMirroredValue","localizedValue","copyDefaultLocaleValueIfEmpty","mainKeyPath","previousMainValue","targetMainValue","follows","createProxy","draftFieldArgs","isDefaultLocaleSource","shouldAutoDuplicate","getFieldInfo","getValueMap","getMirroredField","followDefaultLocale","duplicateIfEmpty","mirroredField","getDefaultValue","dynamicValue","getDefaultValueMap","getInitialValue","useEncoding","UNIQUE_VALUE_FIELD_TYPES","getRenewedUniqueValue","getHiddenFieldDefaultValueMap","LIST_ITEM_KEY_PATH_REGEX","fillUuidValues","contentMap","getUuidField","listItemKeyPath","jsonValue","VALUE_TYPES","escapeTagOpenings","sanitizeDynamicValue","firstOption","toOptionValue","populateMissingSubfields","funcArgs","subfieldKeyPath","subfield","populateDefault","hasRequiredSingleItem","getOptionItemValueMap","getSelectDefaultValueMap","DYNAMIC_ITEM_VALUE_FUNCTIONS","getBooleanDefaultValueMap","getNumberDefaultValueMap","getRichTextDefaultValueMap","toDynamicItemValue","GET_DEFAULT_VALUE_MAP_FUNCTIONS","getBooleanFieldDefaultValueMap","getCodeFieldDefaultValueMap","getDateTimeFieldDefaultValueMap","getFileFieldDefaultValueMap","getKeyValueFieldDefaultValueMap","itemFields","getRichTextFieldDefaultValueMap","getNumberFieldDefaultValueMap","hasDynamicSubfieldValues","dynamicValues","_subField","getSelectFieldDefaultValueMap","populateDefaultValue","_fieldConfig","subfieldArgs","getDefaultValues","alignPairs","defaultPairs","localePairs","displaced","syncDuplicateKeys","alignedPairs","getDuplicateKeysFieldKeyPaths","pairKeyPath","syncAllDuplicateKeys","forEachTargetLocale","duplicated","hasTemplateDefault","hasSameObject","targetContent","defaultLocaleContent","typeKeyPath","copyDefaultLocaleValues","pickObjectValues","newContent","noI18nFieldKeys","getInitialUuidValue","toggleLocale","updateNonPrimitiveValue","updateFieldValue","WRAPPED_COMPONENT_TYPES","isReactComponent","resolveControl","customFieldType","buildControlProps","previewData","fieldId","fieldClassName","handleRef","cachedFieldClassName","getInputClassName","TextInput","Custom_editor","reactRenderer","componentInstance","assetPicker","resolvedControl","handleAddFile","handlePickFile","previousInstance","renderComponent","createElement","newRegistration","AssetPicker","getCustomFieldSummary","buildPreviewProps","preview","Custom_preview","Date_time_preview","displayValue","Date_time_editor","isInputFocused","syncedInputValue","_inputValue","handleFocus","handleBlur","File_extension_change_dialog","oldExtension","newExtension","Editable_text","initialText","canEdit","editLabel","applyDisabled","ariaErrormessage","getSelectionEnd","onApply","editButton","valueElement","isComposing","moveListItem","getMoveTarget","canMoveToEdge","parseMovePosition","getListItemAt","REORDER_CONTROL_ACTIONS","focusItemReorderControl","focusReorderControl","focusAfterRemoval","AUTO_SCROLL_THRESHOLD","AUTO_SCROLL_MAX_SPEED","autoScroll","overflowY","getAutoScrollSpeed","distanceFromTop","distanceFromBottom","stepAutoScroll","nextScrollTop","scrollTop","speed","scrollHeight","clientHeight","onAutoScrollDragOver","startAutoScroll","stopAutoScroll","Move_to_dialog","everOpened","submit","Reorder_menu_items","Reorder_controls","onGrab","onRelease","showHandle","moveToDialogOpen","showButtons","showMenu","getMediaFieldPreview","urlArgs","mediaKind","File_editor_item","groupFieldId","showExtensionChangeDialog","grabbed","isImageField","isFolder","sortable","canRename","finalName","getURLArgs","fileDisplayPath","newFile","applyNewName","updateProps","Reorder_controls$1","getFieldLocaleAccess","inOtherLocale","canTranslate","_draft","isDuplicated","isSynced","areKeysDuplicated","getCreditTargetField","isShown","splitCredits","escapeMarkdown","convertCreditLine","convertCreditToMarkdown","formatCredit","insertCredit","formatted","CAPTION_FIELD_TYPES","getCreditCaptionKeyPath","isComponentField","hasCaptionField","insertCreditCaption","Photo_credit_dialog","captionKeyPath","fieldTarget","canInsert","captionField","markdownField","fragment_5","Upload_button","replaceMode","showSelectAssetsDialog","browseButton","onPasteButtonClick","onFilePaste","clipboardItems","imageType","imageItem","updateObject","newProps","getItemList","moveListExpanderStates","newStates","itemStates","expanderStateList","updateListField","valueListRemainder","isDefaultLocale","manipulate","updateListFieldForLocales","localize","pairedItems","sourceList","getMultiValueList","moveMultiValueItem","addMultiValueItems","replaceIndex","removeMultiValueItem","currentKey","createDragSorter","grabbedIndex","drag","lastOrder","displayOrder","getItemCount","getListElement","sorter","previewOrder","getItemRect","ownEventsOnly","getItemData","File_editor","uploadButtonSnippet","onResourcesSelect","targetFolder","UploadButton","allowDrop","processing","uploadButton","itemArgs","removeItem","itemList","showRemoveButton","removeSingleFile","showPhotoCreditDialog","photoCredit","acceptedTypes","isFull","fieldContext","enabledCloudServiceEntries","resetSelection","_index","File_preview_item","File_preview","d_1","Validation_error","Add_item_button","menuId","addItem","multiValueField","labelSingular","hasMaxItems","itemLabel","descriptionId","fragment_7","getPairs","validatePairs","getKeyedRows","haveStoredPairsChanged","storedPairs","shouldStorePlaceholder","getPairsToSave","validations","keyedRows","getStoredPairs","savePairs","createKeyedRows","nextId","getNextId","initialValues","currentIds","keepIds","Key_value_editor","_keyLabel","_valueLabel","keyLabel","valueLabel","keysReadonly","rowElements","tableBody","isOnlyBlankRow","ensureBlankRow","updatePairs","updatedPairs","addPair","removePair","rowList","updateStore","storedField","root_5","thead","th_1","th_2","th_3","tbody","tr_1","td_1","td_2","td_3","d_2","Key_value_preview","List_item_menu","addPositionItems","variableTypes","insertIndex","showReorder","Expand_icon","List_toolbar","pasteButton","summaryId","Error_boundary","pendingTranslations","isTranslationPending","translation","getTurndownService","TurndownService","HTML_ENTITY_MAP","decodeHTMLEntities","dec","getListItemStates","isSameListItems","originalKeyPath","getOwnerField","canWriteInLocale","getCopyingFieldMap","targetLocaleValue","translate","updateToast","translateFields","copingFieldMap","targetValues","listItemStates","translatedValues","markdownSupported","turndownService","isDraftClosed","translatedCount","copyFields","copyFromLocale","pendingTranslation","Copy_menu_items","localeItems","otherLocale","localeLabel","languagePair","isMenuDisabled","useSubmenu","Field_editor_group","RESET_ACTIONS","LABEL_KEYS","MESSAGE_KEYS","getResetLabel","getResetConfirmation","Reset_menu_items","Translate_button","sourceDisabled","translating","isButtonDisabled","PRESERVED_FIELD_TYPES","resetContent","ownI18n","allowAdd","allowRemove","objectDefault","subFieldConfig","syncOnly","resetFieldInStore","getResetArgs","canResetField","resetField","getTargetLocales","resetAllFields","canResetEntry","copyValues","resetEntry","resolveOriginalKeyPath","originalParts","innermostIndex","originalItemKeyPath","getFieldValues","isFieldChanged","revertFields","ownField","targetKeyPath","remapPrefix","revertLocale","revertAll","getRevertedPairedListKeyPaths","revertChanges","revertsEverything","pairedKeyPath","TRANSLATABLE_FIELD_TYPES","getFieldInputLabels","allowPrefix","allowExtraLabels","beforeInputLabel","afterInputLabel","getFieldEditorFlags","readonlyOption","isCompute","subfieldsReadonly","parentReadonly","autoSet","locked","getEditorFieldConfig","inline","createResetMenuState","availability","checkAvailability","selectedAction","Field_editor","beforeInput","afterInput","writeValue","extraHint","hint","hasExtraLabels","$$d_1","$$d_2","canCopy","canRevert","isRevertDisabled","fieldLabel","pendingDeletion","draftReadonly","autoIncrement","$$d_3","canReset","resetMenu","editorFieldConfig","editorProps","Editor","editors","Editor_1","h4","node_16","node_18","node_19","bind_get_1","bind_set_1","Editor_2","node_21","ExtraHint","root_9","node_23","root_8","ExtraHint_1","Object_body","summaryContent","Object_header","expandable","centerContent","endContent","Removed_item_notice","pendingExpanderStates","flushExpanderStates","stateMap","getInitialExpanderState","currentState","isExpanded","syncExpanderStates","currentStates","pendingStates","getExpanderKeys","endingWithNumber","parentConfig","expandInvalidFields","validityMap","highlightEditorField","getLastRenderedParentField","findEditorField","previousLastRenderedField","maxAttempts","lastRenderedField","revealEditorField","expanderKeys","targetField","isOutdated","widgetWrapper","highlightPreviewTemplateField","isKeyDown","getProportionalScrollTop","scrollRange","targetScrollHeight","targetClientHeight","getFieldAlignedScrollTop","ratio","targetTop","findFieldElement","_wrapper","findLazyFieldElement","previousElement","scrollTo","getRevealingScrollTop","viewTop","viewBottom","viewHeight","always","getStickyToolbarBottom","scrollToAddedListItem","getOffset","getAssetFile","createPendingFileAdder","copies","findExisting","getFieldMediaSources","rewriteAssetReferences","rewrite","walkFieldValue","isRichText","_container","walkObject","isEntryRelativeReference","getItemSubFields","LIST_ITEM_CLIPBOARD_VERSION","removeInternalProps","createListItemClipboardData","fieldTypedKeyPath","parseListItemClipboardData","isStringOrNumber","conformNumberValue","conformPrimitiveValue","conformValue","conformObjectField","conformList","conformObject","conformed","typeFields","prepareListItemPaste","stats","missingFiles","addPendingFileOrThrow","addPendingFile","rewriteReference","isBlobURL","getFolder","lastCopied","copyListItem","readListItem","renewUniqueValue","renewed","renewUniqueValues","removeOriginalKeyPaths","getInitialListExpanderStates","minimizeCollapsed","createListItem","isDuplicate","dupIndex","sourceItem","insertListItem","removeListItem","tagItems","restoreListItem","showListItemClipboardToast","getPastedItemToast","missingFileCount","droppedCount","addRemovedItem","removedItem","removedItems","shifted","shiftRemovedItems","dropRestoredItem","getNestedExpanderStates","createListActions","addedItemIndex","latestAddedItem","withDraft","updateItems","getListState","getMutationOptions","getItem","updateExpanderStates","initializeExpanderStates","revealAddedItem","toolbarBottom","getTopToolbar","addToTop","renewedValues","resolveType","sourceItems","nestedExpanderStates","createRemovedItemsState","expectedListState","getItemKeys","byIndex","getObjectThumbnail","thumbnailFieldName","nestedFieldNames","getDraftObjectThumbnail","List_editor_complex","removedItemNotices","isLocked","restoreItem","allowDuplicate","allowReorder","singleSubFields","customSummary","synced","parentExpandedKeyPath","itemsMemo","singleItem","canRemoveItem","parentExpanded","itemExpanderStates","allSubFields","hasEditableSubFields","subI18n","isAddDisabled","showReorderControls","isReorderDisabled","topToolbar","listActions","getItemValueMap","_formatSummary","itemValueMap","getThumbnail","warnUnknownTypes","toolbarProps","displayIndex","reorderControlProps","copyItem","pasteItem","customSummaryContent","List_editor_simple","unmounted","hasMultipleItems","syncFromValue","List_editor","hasSubFields","Field_preview","showLabel","previewProps","Preview","previews","Preview_1","Subfield_previews","sectionId","single","headerId","unknownType","subFieldKeyPath","List_preview_complex","itemTypes","List_preview_simple","List_preview","Leaflet_map","mapElement","onReady","shownCoordinates","showLocation","leaflet","iconUrl","mapServices","Map_editor","geometryType","center","draw","searchResults","searching","showAlertDialog","createMapDrawController","isValidGeoJSON","geometry","setLocation","coordinates","onSearchResultSelect","lat","lon","useCurrentLocation","clearValue","Map_preview","Number_editor","inputText","Number_preview","addObjectFields","newValueMap","removeObjectFields","removedValues","restoreObjectFields","Object_editor","hideHeader","hasValues","canRestore","typeLabel","initializeExpanderState","addFields","removeFields","focusExpander","restoreFields","addTypedFields","removeTypedFields","summaryText","thumbnailSource","labelledBy","Object_preview","Disabled_locale_state","labelOptions","Parent_folder_tree_item","childItems","countSegments","getIndexEntryRank","collectFolders","ranks","getNodeLabel","childPaths","buildNodes","pruneLeaves","excludePath","getNestedTree","getMaxParentFolderDepth","ownFolderPath","baseDepth","getParentFolderTree","addFolderToTree","addSegment","nodePath","existingNode","findNestedTreeNode","getMovableFolderName","getParentFolderPickerTree","newFolderPaths","getChildFolderNames","Path_editor","canMove","ownFolderName","selectedPath","hasRoomForFolder","newFolderName","newFolderNameEdited","rootNode","localizedSelectedPath","selectedNode","selectedLabel","popupOpen","takenFolderNames","newFolderError","showNewFolderError","hasFolderChoice","selectPath","Entry_editor","showPathEditor","backupTimeout","backupDB","backupDBName","restoreCheckCount","BACKUP_TOAST_DEFAULT_STATE","restoreDialogState","backupToastState","deleteBackup","getBackup","backup","getBackupSlug","getDraftBackup","baseSubPath","isArrayItemDraft","saveBackup","createFileURLs","referencedFiles","restoreBaseEntry","restoreBackup","fileURLs","liveOrder","cancelRestoreCheck","restoreBackupIfNeeded","checkCount","doRestore","showBackupToastIfNeeded","resetBackupToastState","cancelBackup","scheduleBackup","TRUTHY_BOOLEAN_STRINGS","FALSY_BOOLEAN_STRINGS","discardConflictingValue","reconcileScalarValue","firstItemIndex","firstItem","isTrue","reconcileListValue","SCALAR_TYPES","stringifyListItems","itemIndexes","reconcileObjectValue","reconcileValue","copyFromDefaultLocale","hasSameVariableTypes","getSubFields","normalizeField","sourceContent","fillDefaults","subFieldInfo","itemFieldInfo","itemField","normalizeContent","normalizeContentMap","getSlugEditorProp","slugEditorEnabled","getSlugTargetLocales","getInitialSlugs","initialSlug","getOriginalPath","initialPath","fillDuplicatedHiddenValues","buildDraft","canShowSecondPane","enabledLocales","fillArgs","expanderStates","createDraft","hasEntrySlug","canUpdateSlug","needsSlugInput","getSlugPreviewDetails","getPreview","takenSlug","getReadonlySlugs","updateSlugs","getOwnFolderPaths","getTakenFolderNames","ownFolderPaths","otherSubPath","otherDirPath","renameEntryFolders","Slug_editor","labelId","draftSlug","templatePreview","templateSlug","shownSlug","takenTemplateSlug","editError","updateSlug","applySlug","Validation_errors_toast","onShowErrors","INVALID_SEGMENT_REGEX","isPathTaken","validatePath","patternMismatch","customError","duplicateError","validateDraft","currentValuesValid","currentValuesValidities","currentValuesMessages","extraValuesValid","extraValuesValidities","extraValuesMessages","slugsValid","slugsValidities","pathValid","pathValidities","validateEntry","revealInvalidFields","validateAndRevealErrors","awaitFieldUpdates","hasInvalidFields","countInvalidFields","entryEditorSettings","toggleEntryEditorSetting","effectStoppers","Locale_switcher","thisPane","thatPane","previewInThisPane","hasMultipleLocales","listedLocales","previewOffered","hasAnyError","useDropDown","SelectComponent","SelectButtonGroup","OptionComponent","SelectButton","SelectComponent_1","OptionComponent_1","OptionComponent_2","computeFieldCacheMap","containsComputeField","collectFromField","collectFromField$1","getIndex","collectComputeFields","collectComponentComputeFields","visitedPrefixes","isLocaleTarget","updateLocaleComputedValues","computeFields","entryValues","updateComputedValues","pendingDrafts","trackComputedValues","initEntryDraftEditor","getEntryDraft","countQuotaEntries","compareEntries","canOverwrite","compareWithStore","detectEntryConflict","describeConflict","assignSaveTimeValues","COLUMN_LABELS","STATUS_UPDATE_MESSAGES","REFRESH_MESSAGES","DELETION_MESSAGES","CANCELLATION_MESSAGES","PUBLISHING_MESSAGES","getDiscardMessages","getPublishMessages","getBoardAnnouncement","review","ready","deletion","pendingDeletions","groupEntriesByStatus","entryStages","getStage","occupied","getUnpublishedEntryLabel","getCompanionNotes","getNote","getQuickAddHost","getNestedQuickAddHost","parentDraft","getHostUnpublishedEntry","getHostCompanionEntries","hostEntry","getUnlistedEntries","getLatestEntry","compareWithLatest","canSaveAlongHost","getCreatableCollection","hasCreationRoom","companionIds","pendingCount","getPendingRefEntries","seenIds","getRefEntriesWithPending","getPendingEntrySlugs","pendingSlugs","renamedSlug","renamedLocalizedSlugs","createPendingEntry","otherPendingEntries","newPendingEntries","getEditTarget","latestEntry","buildQuickAddDraft","parentPendingEntries","isPendingEntryMoved","revertSaveTimeValues","preparedValues","addPendingEntries","getNestedPendingEntries","selectPendingEntry","isEditUnchanged","replaceEntryValues","refCollectionName","getReplacements","getValues","oldValues","oldValue","replaceValues","replacementsByField","relationField","canEditEntry","_pendingEntry","editingEntry","getEditableEntries","valueSet","optionsByValue","getEditingHostName","Quick_add_dialog","adding","showValidationToast","errorCount","showErrorToast","showMoveToast","changedSince","draftCount","startDraft","changedSinceEdited","discardDraft","Select_multiple","dropdownThreshold","updateList","addValue","removeValue","Select_single","hasEmptyOption","allOptions","Select_editor","SelectMultiple","SelectSingle","Select_1","getBulkEditRowContext","setBulkEditRowContext","getBulkEditRowValues","edits","getBulkEditRowSlug","getEditorEntryValues","bulkEditRow","Relation_editor","editorEntry","showQuickAddDialog","dialogOpened","selectFieldConfig","creatableCollection","canCreate","editableEntries","hasDialogActions","SLUG_VALUE_FIELDS","Relation_preview","refValues","INVALID_FIELD_NAME_DOC_URL","addMessage","locators","collector","warnings","locatorStr","extraMessage","extraStrKey","checkUnsupportedOptions","UNSUPPORTED_OPTIONS","VALID_NAME_REGEX","isValidName","checkName","strKeyBase","nameCounts","checkRegex","INLINE_COMPONENT_FIELD_TYPES","isInlineComponentFieldList","parseEditorComponent","formatComponentSummary","strippedTemplate","flatValues","getComponentDisplayValues","getComponentDisplayText","displayField","hasThumbnail","getComponentThumbnail","validateComponentValues","loc","deleteKeysByPrefix","deleteOwnKeysByPrefix","flattenWithPrefix","getValuesByPrefix","reconcileComponentValues","normalizedValues","Editor_component","fieldEditors","typedPrefix","observe","inlineField","$.derived_safe_equal","fieldEditor","valuesSnapshot","isNewComponent","inlineControl","componentPath","typedKeyPathPrefix","handleBlockKeyDown","previousValues","valuesFromNode","teardownState","_currentValues","attachEntryDraft","setValues","restoreValues","handleRemove","handleOk","handleCancel","brokenThumbnail","displayText","stopFollowingReadonly","localeContainer","keyPathContainer","_keyPathPrefix","fromNode","reconciledValues","draftState","node_15","FENCE_OPEN_REGEX","BACKTICKS_REGEX","BLANK_LINE_REGEX","BLOCK_TAG_REGEX","LONE_TAG_REGEX","isEscaped","matchFenceOpen","isFenceClose","getCodeRanges","ranges","textStart","addCodeSpans","runIndex","isWithinRanges","startsHTMLBlock","afterParagraph","isWithinHTMLBlock","runStart","getNoAsset","fieldListCache","getComponentFieldList","hashString","encodeImageSrc","eLink","eSrc","GLOBAL_IMAGE_OR_LINKED_IMAGE_REGEX","globalPatternCache","MAX_SUBSTITUTION_PASSES","collectStringValues","getGlobalPattern","isMatchWithinPreviewValues","regions","findOutermostMatches","codeRanges","componentDefs","createPreviewContext","addComponentPreview","baseHash","seenHashes","previousPreviewMap","toPreview","fieldProps","getAsset","previewMap","getLineEndBeforeText","getHTMLBlockEnd","previousLine","substituteMatches","addText","buildHTMLWithPreviews","replaceInstances","previewTemplate","buildMarkdownWithPreviews","pass","getInlinePreview","renderInlinePreview","Inline_pattern_component","TAG_NAME_REGEX","mountedComponents","getTagName","callWithEmptyProps","createCustomNodeClass","componentDef","htmlSupported","guessTagName","htmlTagNames","getPropsFromElement","CustomNode","DecoratorNode","serializedNode","isAddedByUser","lexicalEditor","$hasUpdateTag","selectedText","getNearestEditorFromDOMNode","activeEl","selectionRange","insertInlineComponent","replacedText","InlinePatternComponent","EditorComponent","conversionMap","prevNode","createTransformer","nonGlobalPattern","getProps","matchArray","isCustomNode","fullString","matchString","matchLines","endLineIndex","featureCacheMap","createLexicalNodeFeatures","getImageSrcFieldConfig","sortDroppedImages","srcFieldConfig","images","DATA_URL_REGEX","GENERIC_PASTED_FILE_NAME","hasImageExtension","getTimestampFileName","getRemoteImageFileName","typeExtension","findImageInHTML","getPastedImages","pastedItems","clipboardData","fileIndex","htmlIndex","getDroppedImages","droppedFiles","dataTransfer","Rich_text_editor","cleanupTimeout","processingImages","insertUploadedImages","filesRejected","_modes","_buttons","imageComponent","insertImages","isSameContent","insertImage","externalSrc","inlineImages","createImageHandler","getImages","onPaste","scheduleExtraValueCleanup","Text_editor$1","extensionsAdded","withDirAuto","Renderer","bidiRenderers","renderCode","addMarkedExtensions","jt$9","VOID_ELEMENTS","matchBlockFenceOpen","HTML_OPEN_TAG_REGEX","RAW_HTML_BLOCKS","LIST_ITEM_REGEX","htmlTagRegexCache","splitHTMLBlocks","getRawHTMLBlockEnd","splitMarkdownBlocks","htmlBlock","rawHTMLBlockEnd","inList","continuesList","nextLine","openRe","closeRe","fenceMatch","htmlOpenMatch","getLinkDefinitions","definitions","lexer","addLinkDefinitions","splitPreviewBlocks","isHTML","keyBlocks","occurrences","occurrence","previousItems","getFencedCodeLanguages","URL_ATTRIBUTE_NAMES","URL_ATTRIBUTE_REGEX","IGNORED_URL_CHARS_REGEX","isScriptURL","removeScriptURLs","Rich_text_preview","reactRoots","previewNodes","newPreviewAssets","blockItems","observerReady","highlighterVersion","assetURLVersion","requestedLanguages","doSanitize","newMap","keyedBlocks","preloadHighlighter","isOwnElement","mountReactPreview","reportLoadError","unmountRemovedRoots","notifyRemovedPreviews","refreshOnAssetURLChange","replaceMediaURLs","mutationCallback","removedElements","parseMarkdown","rawHTML","Select_preview","Character_counter","setExtraHint","getStringInputValue","getStringFieldValue","String_editor","stringFieldConfig","CharacterCounter","isYouTubeVideoURL","getYouTubeEmbedURL","Youtube_embed","embeddable","embedURL","onViolation","blockedURI","violatedDirective","SAFE_PROTOCOL_REGEX","getPreviewType","String_preview","previewType","a_1","Text_preview","Uuid_editor","Uuid_preview","BooleanEditor","CodeEditor","ColorEditor","ComputeEditor","DateTimeEditor","FileEditor","KeyValueEditor","ListEditor","MapEditor","RichTextEditor","NumberEditor","ObjectEditor","RelationEditor","SelectEditor","StringEditor","TextEditor","UuidEditor","BooleanPreview","CodePreview","ColorPreview","ComputePreview","DateTimePreview","FilePreview","KeyValuePreview","ListPreview","MapPreview","RichTextPreview","NumberPreview","ObjectPreview","RelationPreview","SelectPreview","StringPreview","TextPreview","UuidPreview","createSvelteProps","initialProps","transforms","onValueChange","updateSvelteProps","REUSABLE_BUILTIN_FIELD_TYPES","builtInFieldTypeCache","normalizedFieldConfigCache","convertFieldConfig","normalizeFieldConfig","buildEditorProps","fieldState","forID","createFieldComponent","useContext","latestProps","useRef","buildProps","useCallback","svelteProps","SvelteComponent","createBuiltInFieldType","getBuiltInFieldType","getFieldTypeDefinition","assertValid","assertOption","assertDefinition","assertNotReserved","reserved","builtin","custom","parseURLFromPage","getFieldType","getSignInOptions","isTestRepo","authMethods","giteaConfig","isGitea","additionsEnabled","backendLabel","Sign_in","showTokenDialog","configuredBackend","isDemo","testRepoUnsupported","repositoryName","showLocalBackendOption","trimmedToken","showWorkflowNote","tokenOptionHidden","oauthOptionHidden","oauthOptionDisabled","magicLinkAccountName","additions_SetupWizard","additions_SignInForm","text_7","text_6","missingBrowserFeatures","Entrance_page","unsupportedBrowser","dataFetchError","div_8","div_9","div_10","div_11","div_12","text_8","Commit_message_dialog","Backend_status_indicator","startChecking","stopChecking","Update_notification","updateAvailable","checkForUpdates","en_US_default","\"create\"","\"select\"","\"select_all\"","\"select_item\"","\"upload\"","\"download\"","\"duplicate\"","\"delete\"","\"reorder\"","\"done\"","\"save\"","\"saving\"","\"publish\"","\"publishing\"","\"rename\"","\"replace\"","\"add\"","\"expand_all\"","\"collapse_all\"","\"restore\"","\"discard\"","\"searching\"","\"no_results\"","\"global\"","\"primary\"","\"secondary\"","\"collection\"","\"folder\"","\"folders\"","\"more_folders\"","\"api_key\"","\"details\"","\"back\"","\"automatic\"","\"loading\"","\"later\"","\"slug\"","\"singleton\"","\"singletons\"","\"clipboard_error\"","\"welcome_message\"","\"powered_by\"","\"unsupported_browser_error\"","\"loading_cms_config\"","\"loading_site_data\"","\"loading_site_data_error\"","\"sign_in_with_x\"","\"sign_in_using_access_token\"","\"sign_in_using_access_token_description\"","\"sign_in_using_access_token_workflow_note\"","\"sign_in_using_access_token_link\"","\"personal_access_token\"","\"authorizing\"","\"signing_in\"","\"work_with_local_repo\"","\"work_with_local_repo_description\"","\"work_with_local_repo_description_no_repo\"","\"work_with_test_repo\"","\"start_demo\"","\"test_repo_unsupported_browser\"","\"sign_in_error\"","\"not_project_root\"","\"picker_dismissed\"","\"authentication_aborted\"","\"invalid_token\"","\"UNSUPPORTED_BACKEND\"","\"UNSUPPORTED_DOMAIN\"","\"MISCONFIGURED_CLIENT\"","\"AUTH_CODE_REQUEST_FAILED\"","\"CSRF_DETECTED\"","\"TOKEN_REQUEST_FAILED\"","\"TOKEN_REFRESH_FAILED\"","\"MALFORMED_RESPONSE\"","\"backend_unsupported_version\"","\"repository_no_access\"","\"repository_no_write_access\"","\"repository_not_found\"","\"repository_empty\"","\"branch_not_found\"","\"root_dir_not_found\"","\"unexpected_error\"","\"page_crashed\"","\"field_crashed\"","\"try_again\"","\"reload_cms\"","\"entry_parse_errors\"","\"username\"","\"password\"","\"sign_in\"","\"sign_in_with_mobile\"","\"sign_in_with_mobile_instruction\"","\"sign_in_with_link\"","\"sign_in_with_link_confirmation\"","\"signed_in_as_x\"","\"working_with_local_repo\"","\"working_with_test_repo\"","\"working_in_demo_mode\"","\"demo_welcome\"","\"title\"","\"description\"","\"reset_hint\"","\"button_label\"","\"sign_out\"","\"install_as_app\"","\"contents\"","\"assets\"","\"editorial_workflow\"","\"drafts\"","\"cms_config\"","\"menu\"","\"custom_pages\"","\"mobile_promo_title\"","\"mobile_promo_button\"","\"new_language_available\"","\"change_language\"","\"live_reload_warning\"","\"switching_language\"","\"locale_load_failed\"","\"local_git_not_committed\"","\"local_git_skip_reasons\"","\"unsupported_repository\"","\"missing_identity\"","\"locked\"","\"operation_in_progress\"","\"merge\"","\"rebase\"","\"cherry_pick\"","\"revert\"","\"am\"","\"conflict\"","\"detached_head\"","\"staged_changes\"","\"lfs\"","\"visit_live_site\"","\"switch_page\"","\"search_placeholder_contents\"","\"search_placeholder_assets\"","\"search_placeholder_all\"","\"create_entry_or_assets\"","\"publish_changes\"","\"publishing_changes\"","\"publishing_changes_failed\"","\"show_notifications\"","\"notifications\"","\"show_account_menu\"","\"account\"","\"live_site\"","\"git_repository\"","\"settings\"","\"administration\"","\"show_help_menu\"","\"help\"","\"keyboard_shortcuts\"","\"documentation\"","\"release_notes\"","\"announcements\"","\"version_x\"","\"report_issue\"","\"share_feedback\"","\"get_help\"","\"donate\"","\"join_discord\"","\"bluesky\"","\"update_available\"","\"update_now\"","\"backend_status\"","\"minor_incident\"","\"major_incident\"","\"content_library\"","\"asset_library\"","\"collections\"","\"entries\"","\"files\"","\"asset_location\"","\"repository\"","\"external\"","\"stock_photos\"","\"collection_assets\"","\"entry_list\"","\"file_list\"","\"asset_list\"","\"x_collection\"","\"x_asset_folder\"","\"viewing_collection_list\"","\"viewing_asset_folder_list\"","\"viewing_x_collection\"","\"viewing_x_asset_folder\"","\"viewing_x_external_location\"","\"viewing_admin_section_list\"","\"viewing_x_admin_section\"","\"singleton_selected_announcement\"","\"page_not_found\"","\"collection_not_found\"","\"asset_folder_not_found\"","\"file_not_found\"","\"x_of_x_selected\"","\"switch_view\"","\"table_view\"","\"list_view\"","\"grid_view\"","\"switch_to_list_view\"","\"switch_to_grid_view\"","\"sort\"","\"sorting_options\"","\"table_column_keys\"","\"dirname\"","\"filename\"","\"extension\"","\"locales\"","\"sort_keys\"","\"none\"","\"commit_author\"","\"commit_date\"","\"last_modified\"","\"size\"","\"_manual\"","\"ascending\"","\"ascending_date\"","\"descending\"","\"descending_date\"","\"ascending_number\"","\"descending_number\"","\"filter\"","\"filtering_options\"","\"group\"","\"grouping_options\"","\"all\"","\"domain\"","\"image\"","\"video\"","\"audio\"","\"document\"","\"other\"","\"show_assets\"","\"hide_assets\"","\"show_info\"","\"hide_info\"","\"all_assets\"","\"global_assets\"","\"linked_files\"","\"file_unavailable\"","\"file_unavailable_description\"","\"loading_entries\"","\"entry_not_found\"","\"creating_entries_disabled_by_admin\"","\"creating_entries_disabled_by_quota\"","\"creating_entries_nearing_quota\"","\"readonly_cms\"","\"readonly_collection\"","\"readonly_entry\"","\"readonly_asset_folder\"","\"readonly_branch\"","\"readonly_role\"","\"readonly_reference\"","\"cannot_rename_referenced_entry\"","\"cannot_move_referenced_asset\"","\"back_to_collection\"","\"collection_list\"","\"back_to_collection_list\"","\"asset_folder_list\"","\"back_to_asset_folder_list\"","\"back_to_parent_folder\"","\"search_results\"","\"search_results_for_x\"","\"viewing_entry_search_results\"","\"viewing_asset_search_results\"","\"x_entries\"","\"x_assets\"","\"no_files_found\"","\"no_entries_found\"","\"upload_assets\"","\"new_folder\"","\"new_folder_name\"","\"new_folder_create\"","\"new_folder_description\"","\"new_folder_error\"","\"empty\"","\"invalid\"","\"reserved\"","\"creating_folder\"","\"creating_folder_failed\"","\"folder_options\"","\"show_folder_options\"","\"rename_folder\"","\"delete_folder\"","\"enter_new_name_for_folder\"","\"confirm_deleting_folder\"","\"renaming_folder\"","\"renaming_folder_failed\"","\"deleting_folder\"","\"deleting_folder_failed\"","\"external_assets_truncated\"","\"edit_options\"","\"show_edit_options\"","\"copy_options\"","\"edit_asset\"","\"edit_x\"","\"wrap_long_lines\"","\"move\"","\"move_asset\"","\"move_assets_title\"","\"select_asset_move_destination\"","\"asset_move_destination\"","\"assets_already_in_folder\"","\"asset_move_conflict\"","\"moving_assets\"","\"moving_assets_failed\"","\"asset_move_cleanup_failed\"","\"cannot_change_used_external_files\"","\"rename_asset\"","\"rename_x\"","\"enter_new_name_for_asset\"","\"enter_new_name_for_asset_error\"","\"character\"","\"leading_dot\"","\"file_duplicate\"","\"folder_duplicate\"","\"file_will_be_saved_as\"","\"change_file_extension\"","\"confirm_file_extension_change\"","\"change\"","\"file_extension_change_warning\"","\"replace_asset\"","\"replace_x\"","\"replace_file\"","\"replace_image\"","\"remove_file\"","\"remove_image\"","\"click_to_browse\"","\"tap_to_browse\"","\"drop_files_or_click_to_browse\"","\"drop_files_or\"","\"drop_image_files_or\"","\"browse\"","\"paste\"","\"paste_image\"","\"no_image_in_clipboard\"","\"clipboard_access_denied\"","\"drop_files_here\"","\"unsupported_file_type\"","\"dropped_file_type_mismatch\"","\"dropped_image_type_mismatch\"","\"choose_files\"","\"delete_assets\"","\"delete_selected_assets\"","\"confirm_deleting_this_asset\"","\"confirm_deleting_selected_assets\"","\"confirm_deleting_all_assets\"","\"deleting_referenced_assets_note\"","\"cannot_delete_referenced_assets\"","\"checking_asset_references_failed\"","\"delete_entries\"","\"delete_selected_entries\"","\"confirm_deleting_this_entry\"","\"confirm_deleting_this_entry_with_assets\"","\"deleting_entry_failed\"","\"confirm_deleting_selected_entries\"","\"confirm_deleting_selected_entries_with_assets\"","\"confirm_deleting_all_entries\"","\"confirm_deleting_all_entries_with_assets\"","\"deleting_referenced_entries_note\"","\"cannot_delete_referenced_entries\"","\"reorder_entries\"","\"done_reordering_entries\"","\"cancel_reordering_entries\"","\"saving_reorder_failed\"","\"bulk_edit_entries\"","\"save_bulk_edits\"","\"cancel_bulk_edits\"","\"bulk_edit_entry\"","\"bulk_edit_table\"","\"bulk_edit_cell\"","\"bulk_edit_count\"","\"bulk_edit_invalid\"","\"saving_bulk_edits_failed\"","\"discard_bulk_edits_confirm\"","\"processing_files\"","\"uploading_files\"","\"confirm_replacing_file\"","\"confirm_uploading_files\"","\"oversized_files\"","\"warning_oversized_files\"","\"invalid_files\"","\"warning_invalid_files\"","\"warning_unsupported_files\"","\"warning_unsupported_image_files\"","\"mismatched_files\"","\"warning_mismatched_files\"","\"file_name_conflict_confirmation\"","\"file_name_conflict_confirmation_with_name\"","\"file_name_conflict_resolution\"","\"keep_both\"","\"uploading_files_progress\"","\"uploading_files_failed\"","\"deleting_assets_failed\"","\"renaming_asset_failed\"","\"saving_asset_failed\"","\"file_meta_converted_from_x\"","\"no_entries_created\"","\"create_new_entry\"","\"entry\"","\"index_file\"","\"no_files_in_collection\"","\"duplicate_entry\"","\"entry_duplicated\"","\"entry_validation_errors\"","\"show_errors\"","\"entry_saved\"","\"entry_saved_and_published\"","\"entries_deleted\"","\"assets_saved\"","\"assets_saved_and_published\"","\"asset_urls_copied\"","\"asset_paths_copied\"","\"asset_ids_copied\"","\"asset_data_copied\"","\"assets_downloaded\"","\"assets_moved\"","\"assets_renamed\"","\"assets_deleted\"","\"folder_created\"","\"folder_path\"","\"folder_contents\"","\"x_folders\"","\"folder_renamed\"","\"folder_deleted\"","\"content_editor\"","\"restore_backup_title\"","\"restore_backup_description\"","\"draft_backup_saved\"","\"draft_backup_restored\"","\"draft_backup_deleted\"","\"cancel_editing\"","\"create_entry_title\"","\"create_entry_announcement\"","\"edit_entry_announcement\"","\"edit_file_announcement\"","\"edit_singleton_announcement\"","\"save_and_publish\"","\"save_without_publishing\"","\"save_and_publish_needs_review\"","\"show_editor_options\"","\"editor_options\"","\"show_second_pane\"","\"show_preview\"","\"sync_scrolling\"","\"switch_locale\"","\"locale_content_disabled_short\"","\"locale_content_error_short\"","\"edit\"","\"preview\"","\"swap_panes\"","\"edit_x_locale\"","\"preview_x_locale\"","\"edit_content\"","\"preview_content\"","\"content_preview\"","\"show_content_options_x_locale\"","\"content_options_x_locale\"","\"show_content_options\"","\"content_options\"","\"x_field\"","\"show_field_options\"","\"field_options\"","\"unsupported_field_type_x\"","\"enable_x_locale\"","\"reenable_x_locale\"","\"disable_x_locale\"","\"locale_x_has_been_disabled\"","\"locale_x_now_disabled\"","\"view_in_repository\"","\"view_on_x\"","\"view_on_live_site\"","\"deploy_preview\"","\"view\"","\"building\"","\"build_failed\"","\"checking\"","\"check_again\"","\"awaiting\"","\"short\"","\"failed\"","\"copy_from\"","\"copy_from_x\"","\"translation_options\"","\"translate\"","\"translate_fields\"","\"translate_from\"","\"translate_from_x\"","\"revert_changes\"","\"revert_all_changes\"","\"restore_default\"","\"clear_all\"","\"confirm_reverting_changes\"","\"confirm_reverting_changes_x_locale\"","\"confirm_restoring_defaults\"","\"confirm_restoring_defaults_x_locale\"","\"confirm_clearing_fields\"","\"confirm_clearing_fields_x_locale\"","\"edit_slug\"","\"edit_slug_error\"","\"slug_numbered\"","\"entry_parent_folder\"","\"new_parent_folder\"","\"new_parent_folder_create\"","\"new_parent_folder_name\"","\"new_parent_folder_description\"","\"new_parent_folder_error\"","\"edit_path_error\"","\"recursive\"","\"required\"","\"editor\"","\"translation\"","\"started\"","\"complete\"","\"validation\"","\"value_missing\"","\"range_underflow\"","\"date\"","\"time\"","\"number\"","\"range_overflow\"","\"too_short\"","\"too_long\"","\"type_mismatch\"","\"email\"","\"value_not_unique\"","\"key_not_unique\"","\"key_numeric\"","\"invalid_value\"","\"entry_sidebar\"","\"sidebar_panels\"","\"placeholder\"","\"no_errors_found\"","\"validate\"","\"generated_on_save\"","\"unavailable\"","\"history\"","\"fetch_failed\"","\"no_history\"","\"backlinks\"","\"no_entries\"","\"title_with_count\"","\"save_progress\"","\"preparing\"","\"committing\"","\"saving_entry\"","\"save_conflict\"","\"modified_by\"","\"modified\"","\"deleted\"","\"overwrite_warning\"","\"recreate_warning\"","\"reload_warning\"","\"save_anyway\"","\"branch_moved\"","\"array_item_changed\"","\"array_file_invalid\"","\"remote_change\"","\"reload_entry\"","\"confirm_reloading_entry\"","\"viewing_x_asset_details\"","\"asset_editor\"","\"previous_asset\"","\"next_asset\"","\"preview_unavailable\"","\"public_urls\"","\"file_paths\"","\"file_ids\"","\"file_data\"","\"asset_info\"","\"select_asset_show_info\"","\"kind\"","\"dimensions\"","\"duration\"","\"used_in\"","\"created_date\"","\"location\"","\"map_lat_lng\"","\"remove_this_item\"","\"move_up\"","\"move_down\"","\"reorder_options\"","\"move_to_top\"","\"move_to_bottom\"","\"move_to\"","\"move_to_description\"","\"move_to_position\"","\"reorder_item\"","\"list_item_value\"","\"list_item_position\"","\"item_removed\"","\"add_x\"","\"list_item_options\"","\"add_item_above\"","\"add_item_below\"","\"paste_item_above\"","\"paste_item_below\"","\"paste_item_to_replace\"","\"paste_item\"","\"list_item_copied\"","\"no_list_item_to_paste\"","\"list_item_not_compatible\"","\"list_item_pasted_without_values\"","\"list_item_pasted_without_files\"","\"select_list_type\"","\"unknown_variable_type\"","\"opacity\"","\"unselected_option\"","\"relation_field\"","\"save_together_hint\"","\"add_failed\"","\"edit_entry_title\"","\"edit_together_hint\"","\"edit_failed\"","\"move_unsupported\"","\"edit_conflict\"","\"edit_deleted\"","\"select_entry_to_edit\"","\"edited_with_entry\"","\"changed_since_edit\"","\"assets_dialog\"","\"file\"","\"search_for_file\"","\"search_for_image\"","\"locations\"","\"selected_folder\"","\"selected_folders\"","\"no_subfolders\"","\"prefix_unresolved\"","\"field\"","\"invalid_key\"","\"search_fetch_failed\"","\"image_fetch_failed\"","\"available_images\"","\"available_files\"","\"enter_url\"","\"enter_file_url\"","\"enter_image_url\"","\"large_file\"","\"invalid_file\"","\"rejected_files\"","\"photo_credit\"","\"insert_to_field\"","\"copy_as_markdown\"","\"unsaved\"","\"character_counter\"","\"min_max\"","\"youtube_video_player\"","\"now\"","\"editor_components\"","\"src\"","\"alt\"","\"caption\"","\"key_value\"","\"key\"","\"value\"","\"action\"","\"empty_key\"","\"duplicate_key\"","\"find_place\"","\"use_your_location\"","\"geolocation_error_title\"","\"geolocation_error_body\"","\"geolocation_unsupported\"","\"boolean\"","\"true\"","\"false\"","\"cloud_storage\"","\"auth\"","\"key_label\"","\"initial\"","\"requested\"","\"s3\"","\"auth_key_label\"","\"cloudinary\"","\"iframe_title\"","\"activate\"","\"open_library\"","\"uploadcare\"","\"azure_blob_storage\"","\"backblaze_b2\"","\"bunny_storage\"","\"config\"","\"errors\"","\"error_locator\"","\"component\"","\"no_secure_context\"","\"insecure_urls\"","\"fetch_failed_not_ok\"","\"fetch_failed_with_manual_init\"","\"parse_failed\"","\"parse_failed_invalid_object\"","\"parse_failed_unsupported_type\"","\"no_collection\"","\"no_visible_collection\"","\"missing_backend\"","\"missing_backend_name\"","\"unsupported_known_backend\"","\"unsupported_deprecated_backend\"","\"unsupported_custom_backend\"","\"unsupported_backend_suggestion\"","\"missing_repository\"","\"invalid_repository\"","\"missing_api_root\"","\"invalid_root_dir\"","\"invalid_root_dir_branch\"","\"path_outside_root_dir\"","\"oauth_implicit_flow\"","\"github_pkce_unsupported\"","\"additions_no_base_url\"","\"oauth_no_app_id\"","\"open_authoring_no_workflow\"","\"no_auth_methods\"","\"auth_scope_no_repo\"","\"missing_media_folder\"","\"public_folder_relative_path\"","\"public_folder_absolute_url\"","\"unsupported_folder_template_tag\"","\"global_folder_template_tag\"","\"invalid_sanitize_replacement\"","\"invalid_url_option\"","\"invalid_publish_mode_stages\"","\"i18n_no_locales\"","\"i18n_invalid_default_locale\"","\"i18n_invalid_initial_locale\"","\"i18n_no_collections\"","\"invalid_transformation_key\"","\"invalid_transformation_quality\"","\"invalid_transformation_size\"","\"missing_asset_collection_name\"","\"invalid_asset_collection_name\"","\"duplicate_asset_collection_name\"","\"invalid_collection_no_options\"","\"invalid_collection_multiple_options\"","\"file_format_mismatch\"","\"front_matter_body_field_not_text\"","\"invalid_collection_data_file\"","\"unsupported_collection_data_file_option\"","\"collection_data_file_workflow\"","\"collection_data_file_slug_tag\"","\"invalid_slug_slash\"","\"invalid_identifier_field\"","\"invalid_filter_field\"","\"invalid_filter_no_condition\"","\"option_field_not_found\"","\"thumbnail_field_not_media\"","\"invalid_inline_component_fields\"","\"invalid_regex\"","\"invalid_reorder_group\"","\"invalid_bulk_edit_field\"","\"unsupported_bulk_edit_field\"","\"invalid_sortable_field\"","\"multiple_sortable_field_defaults\"","\"invalid_table_column_field\"","\"invalid_view_group_field\"","\"invalid_view_filter_field\"","\"missing_view_group_name\"","\"invalid_view_group_name\"","\"duplicate_view_group_name\"","\"missing_view_filter_name\"","\"invalid_view_filter_no_condition\"","\"invalid_view_filter_name\"","\"duplicate_view_filter_name\"","\"invalid_view_group_default\"","\"invalid_view_filter_default\"","\"missing_collection_name\"","\"invalid_collection_name\"","\"duplicate_collection_name\"","\"missing_collection_file_name\"","\"invalid_collection_file_name\"","\"duplicate_collection_file_name\"","\"collection_no_fields\"","\"collection_file_no_fields\"","\"collection_folder_i18n_required\"","\"invalid_collection_folder_locale\"","\"collection_file_i18n_required\"","\"collection_i18n_no_fields\"","\"collection_i18n_no_files\"","\"collection_file_i18n_no_fields\"","\"missing_field_name\"","\"invalid_field_name\"","\"duplicate_field_name\"","\"missing_variable_type\"","\"invalid_variable_type\"","\"duplicate_variable_type\"","\"date_field_type\"","\"hidden_field_locale_without_i18n\"","\"invalid_timezone\"","\"unsupported_deprecated_option\"","\"allow_multiple\"","\"invalid_list_field\"","\"invalid_list_variable_type\"","\"invalid_object_field\"","\"invalid_range_options\"","\"invalid_step\"","\"select_field_no_options\"","\"select_field_duplicate_option\"","\"select_field_invalid_default\"","\"list_field_no_subfields\"","\"list_field_invalid_default_object\"","\"list_field_invalid_default_item\"","\"list_field_invalid_default_key\"","\"list_field_default_missing_type\"","\"list_field_invalid_default_type\"","\"list_field_map_key_no_subfields\"","\"list_field_map_key_not_found\"","\"list_field_map_key_missing_in_type\"","\"list_field_map_key_invalid_type\"","\"list_field_map_key_multiple\"","\"list_field_map_key_option_not_string\"","\"list_field_map_key_not_required\"","\"list_field_map_key_not_localized\"","\"duplicate_if_empty_multiple\"","\"invalid_default_multiple\"","\"invalid_default_single\"","\"object_field_invalid_default_key\"","\"object_field_default_missing_type\"","\"object_field_invalid_default_type\"","\"code_field_invalid_default_object\"","\"code_field_invalid_default_key\"","\"compute_field_invalid_expression\"","\"compute_field_uuid_in_expression\"","\"number_field_default_not_integer\"","\"number_field_default_not_number\"","\"object_field_no_subfields\"","\"relation_field_invalid_collection\"","\"relation_field_invalid_collection_file\"","\"relation_field_missing_file_name\"","\"relation_field_invalid_value_field\"","\"relation_field_array_file_slug\"","\"relation_field_array_file_workflow\"","\"relation_field_invalid_display_field\"","\"relation_field_invalid_search_field\"","\"relation_field_invalid_filter_field\"","\"relation_field_invalid_sort_field\"","\"relation_field_sort_by_file_ignored\"","\"unexpected\"","\"schema_invalid_type\"","\"schema_invalid_enum\"","\"schema_invalid_const\"","\"schema_invalid_empty_value\"","\"schema_invalid_item_count\"","\"schema_invalid_value\"","\"schema_missing_option\"","\"schema_missing_one_of\"","\"schema_value_type\"","\"string\"","\"integer\"","\"array\"","\"object\"","\"null\"","\"site_library_prefix_template\"","\"unsupported_ignored_option\"","\"publish_mode_stages_ignored\"","\"inline_component_multiline_pattern\"","\"single_line_block_item\"","\"conflicting_timezone_options\"","\"localize_format_without_format\"","\"compute_field_wildcard_without_item\"","\"compute_field_self_reference\"","\"compute_field_reference_cycle\"","\"localize_format_without_i18n\"","\"localize_format_unsupported_locale\"","\"preview_path_no_date_field\"","\"preview_path_date_field_not_found\"","\"preview_path_field_not_found\"","\"missing_identifier_field\"","\"slug_i18n_ineffective\"","\"slug_template_ignored\"","\"locale_not_omitted_from_file_path\"","\"i18n_not_configured\"","\"empty_public_folder\"","\"schema_unknown_option\"","\"default_localized_without_i18n\"","\"default_localized_unknown_locale\"","\"compatibility_link\"","\"schema_tip\"","\"local_workflow\"","\"indicator\"","\"unsupported_browser\"","\"disabled\"","\"viewing_editorial_workflow\"","\"viewing_open_authoring_workflow\"","\"viewing_editorial_workflow_without_review\"","\"viewing_preview_workflow\"","\"status\"","\"draft\"","\"in_review\"","\"ready\"","\"pending_deletion\"","\"deploying\"","\"workflow\"","\"cancel_deletion\"","\"confirm_cancelling_deletion\"","\"confirm_completing_deletion\"","\"deletion_pending\"","\"changes_discarded\"","\"cancelling_deletion\"","\"deletion_cancelled\"","\"cancelling_deletion_failed\"","\"unpublished_entries\"","\"published_entries\"","\"entry_status_value\"","\"change_entry_status\"","\"changing_status\"","\"updating_status\"","\"status_updated\"","\"status_change_failed\"","\"refresh\"","\"refreshing\"","\"refreshed\"","\"refresh_failed\"","\"status_change_blocked\"","\"publish_blocked\"","\"send_for_review\"","\"confirm_sending_for_review\"","\"mark_as_ready\"","\"confirm_marking_as_ready\"","\"publish_entry\"","\"discard_changes\"","\"confirm_deleting_published_entry\"","\"confirm_deleting_unpublished_entry\"","\"confirm_discarding_entry_changes\"","\"deleting_unpublished_note_all\"","\"deleting_unpublished_note_some\"","\"confirm_publishing_entry_after_build\"","\"publishing_entry\"","\"entry_published\"","\"deleting_entry\"","\"discarding_changes\"","\"entry_deleted\"","\"publishing_entry_failed\"","\"publish_refused_other_changes\"","\"publish_refused_entry_changed\"","\"review_on_x\"","\"from_fork\"","\"fork_entry_editable\"","\"fork_entry_locked\"","\"fork_not_editable\"","\"fork_entry_gone\"","\"branch_in_use\"","\"drag_entry\"","\"deploying_deletion\"","\"companion_entries\"","\"edited_companion_entries\"","\"companion_entry\"","\"commit_message\"","\"description_replace\"","\"description_addition\"","\"message\"","\"addition\"","\"open_authoring\"","\"fork_repository\"","\"fork\"","\"confirm_forking_repository\"","\"fork_declined\"","\"fork_failed\"","\"fork_branch_missing\"","\"permission_check_failed\"","\"forking_disabled\"","\"invitation_pending\"","\"private_repo_scope_required\"","\"publish_unsupported\"","\"entry_already_published\"","\"direct_commit_unsupported\"","\"contributing_via_fork\"","\"view_fork\"","\"categories\"","\"prefs\"","\"changes\"","\"api_key_saved\"","\"api_key_removed\"","\"api_key_invalid\"","\"permission_denied\"","\"appearance\"","\"theme\"","\"select_theme\"","\"dark\"","\"light\"","\"ui_language\"","\"select_language\"","\"use_draft_backup\"","\"switch_label\"","\"close_on_save\"","\"close_with_escape\"","\"i18n\"","\"translators\"","\"default\"","\"select_service\"","\"api_keys\"","\"field_label\"","\"media\"","\"credit\"","\"no_services\"","\"ai\"","\"accessibility\"","\"underline_links\"","\"data\"","\"clear_data\"","\"file_cache\"","\"confirmation\"","\"all_data\"","\"developer\"","\"developer_mode\"","\"local_git\"","\"not_ready\"","\"deploy_hook\"","\"saved\"","\"removed\"","\"keyboard_shortcuts_\"","\"view_content_library\"","\"view_asset_library\"","\"search\"","\"create_entry\"","\"save_entry\"","\"file_type_labels\"","\"avif\"","\"bmp\"","\"gif\"","\"heic\"","\"heif\"","\"ico\"","\"jpeg\"","\"jpg\"","\"png\"","\"svg\"","\"tif\"","\"tiff\"","\"webp\"","\"avi\"","\"m4v\"","\"mov\"","\"mp4\"","\"mpeg\"","\"mpg\"","\"ogg\"","\"ogv\"","\"ts\"","\"webm\"","\"aac\"","\"mid\"","\"midi\"","\"m4a\"","\"mp3\"","\"oga\"","\"opus\"","\"wav\"","\"weba\"","\"csv\"","\"doc\"","\"docx\"","\"odp\"","\"ods\"","\"odt\"","\"pdf\"","\"ppt\"","\"pptx\"","\"rtf\"","\"xls\"","\"xlsx\"","\"html\"","\"js\"","\"json\"","\"md\"","\"toml\"","\"yaml\"","\"yml\"","\"file_size_units\"","\"b\"","\"kb\"","\"mb\"","\"gb\"","\"tb\"","DEFAULT_APP_LOCALE","APP_LOCALES","getNavigatorLocale","REMOTE_LOCALES_BASE_URL","REMOTE_LOCALE_FETCH_TIMEOUT","LOCALE_CACHE_KEY","loadedLocaleStrings","appLocaleLoading","appLocaleLoadError","appNumberFormatter","isLocaleCacheEnabled","getCachedLocaleStrings","strings","_version","cacheLocaleStrings","deleteCachedLocaleStrings","fetchLocaleStrings","loadLocaleStrings","cachedStrings","updateLocaleCache","getStoredLocale","initAppLocale","defaultLocaleStrings","defaultComponentStrings","init$4","Locale_load_error_toast","showToast","Config_panel","Sidebar","uiSettingsDB","getUISettingsDB","getSidebarWidth","saveSidebarWidth","Page_container","uiSettingsKey","primarySidebar","sidebarWidth","restoreSidebarWidth","onResize","clientWidth","Not_found","backPath","anyPage","Admin_page","panels","ConfigPanel","ADMIN_ROUTE_REGEX","$.window","Sidebar$1","Panel","Panel_1","Main_area$1","pre_1","Asset_preview_content","Cascade_delete_note","blocker","bdi_1","Delete_assets_button","planDeletion","listedCount","useButton","planFailed","buttonDescription","dialogDescription","buttonDisabled","blocked","ARROW_KEY_USER_SELECTOR","getArrowKeyDirection","canSwipeOn","Details_overlay","overflowItems","contentKey","onPrevious","onNext","touchStart","getHandler","onTouchStart","touches","onTouchEnd","changedTouches","Download_assets_button","MenuItem","downloadFiles","saveFile$1","Component_1","Copy_menu","menuItems","doCopyAction","toastKey","canCopyFileData","canCopyFileDataByName","copyFileData","Copy_assets_button","canCopyData","copyPublicURLs","copyFilePaths","copyFileIDs","hasId","Edit_options_menu","canReplace","onEdit","onRename","onReplace","extraItems","moreItems","Edit_options_button","replaceFilePicker","replaceAsset","$5","formatDuration","File_info_sections","hasDimensions","dimensions","section_1","h4_1","section_2","h4_2","section_3","h4_3","Info_panel_layout","usedEntryLink","Used_entries","usages","p_2","Info_panel","unavailable","_details","_asset","_usedEntries","showAsset","Copy_assets_button$1","Delete_assets_button$1","editOptions","Edit_options_button$1","Info_panel$1","Details_overlay$2","List_container","Listing_grid","scrollKey","scroller","Asset_list_container","onBlankClick","hasSubfolders","emptyAction","hasAssets","fragment_11","Asset_list_item","dragSource","$$node","Unavailable_badge","isLinkedFile","showDetails","updateSelection","_selected","Asset_list_item$2","Subfolder_list_item","hasCheckboxColumn","onFocus","actionsDisabled","stopPropagation","canDelete","Subfolder_list_item$2","Upload_assets_button","Asset_list","subfolderCount","Subfolder_list_item$1","renderItem","Asset_list_item$1","Upload_assets_button$1","Delete_folder_dialog","assetCount","Folder_info_panel","folderCount","Folder_info_panel$2","New_folder_dialog","Preview_asset_button","Primary_toolbar","fab","breadcrumbs","Primary_toolbar$3","New_folder_button$1","Rename_dialog","usedEntryCount","confirmationOpen","keepName","extensionChanged","selectFileName","createUsedEntriesState","onFound","renameAsset","oldId","Rename_dialog$2","Rename_folder_dialog","currentName","Secondary_sidebar","Condition_radio_items","noneLabel","Filter_menu","_label","updatedFilters","Group_menu","collapsibleGroupNames","canExpandAll","canCollapseAll","Item_selector","selectedItems","totalCount","selectedCount","anySelected","allSelected","Sort_menu","getOrderLabel","Secondary_toolbar","hasListedAssets","hasMultipleAssets","Folder_info_panel$1","Primary_toolbar$2","Secondary_toolbar$1","Asset_list$1","Secondary_sidebar$1","Rename_dialog$1","New_folder_dialog$1","Rename_folder_dialog$1","Delete_folder_dialog$1","searchMode","ROUTE_REGEX","isSearchResultsPath","isSearchRoute","ASSETS_ROUTE_REGEX","isKnownFolderPath","navigationCount","getSelectedAssetFolderLabel","getAssetFolderHistoryState","replaceShownAssetPath","leaveMovedAsset","shownPath","listPath","showAssetDetails","discardAssetsNavigation","selectCloudService","assetId","resolveIndexRoute","announceAssetFolder","resolveAssetsRoute","fullPath","cachedMetadata","defaultAssetDetails","collectMediaMetadata","getMediaMetadataOnce","getAssetDetails","blobBaseURL","getAssetUsedEntries","assetsDetailList","publicURLs","assetBlob","detailList","View_in_repository_item","createAssetDetailsState","withUsedEntries","repoBlobURL","showPreview","createdDate","text_9","section_4","h4_4","text_10","text_11","section_5","h4_5","text_12","_blob","assetsInSameFolder","assetsByFoldedName","namesInBatch","foldedFileName","replacedAsset","originalAssets","replaceDuplicates","prepareAssetChanges","saveAssets","updateStores$2","Edit_asset_dialog","saving","openedFromOverlay","initState","resetState","saveAsset","getListedAssetFolders","getAssetFolderIcon","getAssetMoveDestinations","seenPaths","rootPath","listChildren","findAssetMoveDestination","destinations","isInSameTree","isSameMoveDestination","isBelowMoveDestination","getMoveDestinationIcon","getMoveDestinationKey","Move_destination_tree_item","getAssetsUsedEntries","getAssetMoveConflicts","movingNames","conflicts","moveAssetsToFolder","deleteQuietly","readFiles","listFolder","uploadFilesWithReferences","saveOptions","uploadedAsset","uploadedAssets","reportMoved","moveAssetsToService","moveWithinService","copyFromService","moveExternalAssets","sameService","getMoveSummary","getMoveRequestUsedEntries","moveToDestination","followMovedAssets","getMoveTargetServices","buildServiceFolderTree","addFolder","createDestination","getExternalMoveDestinations","Move_dialog","externalDestinations","firstName","selectRequestedDestination","_request","_destination","browseAncestor","back","originPath","updateSearchTerms","hadTerms","resetSearchAfterLeaving","Quick_search_bar","Primary_sidebar","isSearchPage","getFolderLabel","shouldShowDivider","linkedCount","Asset_result_item","Entry_thumbnail","Entry_result_item","resultRow","Search_result_list","searchAssets","assetSearchResults","scanEntry","points","entryValueCache","searchEntries","entrySearchResults","Search_results","Search_main_area","_sortFields","Assets_page","isIndexPage","notFound","selectedAssetFolderLabel","Primary_sidebar$1","Primary_toolbar$1","Details_overlay$1","Cloudinary_iframe","mlId","Asset_updates_toast","Upload_assets_confirm_dialog","mismatchedFiles","uploadableFiles","replaceFiles","dupFileCount","Upload_assets_dialog","Backup_feedback","getPreviewTemplate","buildPreviewFrameHTML","styleURLs","Entry_preview_iframe","reactRoot","mountPlaceholder","renderReactComponent","contentDocument","contentWindow","componentProps","mountReactComponent","createRoot","reportMountError","initializeIframe","mountComponent","iframe_1","getPreviewStyleURLs","mountFieldPreview","FieldPreview","FieldWidget","import_react","createWidgetFor","createWidgetsMap","widgetFor","createWidgetsFor","ImmutableMap","fromJS","getCollectionByName","convertArgs","convertEntry","preparePreviewTemplateProps","Entry_preview","reactComponent","reactProps","scrollSource","revealGuard","eventOptions","scrollEventOptions","getViewOrigin","getViewTop","getContentTop","getThatScrollTop","createScrollSync","scrollEventTarget","previewFrame","syncScrollPosition","contentArea","thisPaneContentArea","thatPaneContentArea","thisElement","ownerDocument","thatElement","thatScrollTop","markScrollSource","revealField","originalScrollTop","frameRoot","Pane_body","syncScrolling","editLocale","scrollSync","$$args","Reset_dialog","Preview_button","refineState","liveness","getEntryPreviewLink","deployMap","compose","deploy","pollTimedOut","Preview_link_button","isDeployPreview","pingable","awaitingPreview","descriptionKey","canPing","buildFinished","LOCALE_CONTENT_KEYS","getLocaleContentLabel","getPaneStateKey","getPaneSizes","firstPane","secondPane","getRestoredPanes","editorLocale","savedPanes","showSecondPane","getDefaultPanes","currentLocale","singlePane","getPanesEditingLocale","editPane","savePaneState","panes","unwatch","lastKey","holdBack","keepWaiting","prior","reopenRecentConclusions","getTargetKey","supersede","restart","retain","retainDeployPolling","recheckDeployments","Pane_header","isLocaleEnabled","isOnlyLocale","menuButton","previewLink","hasLinkItems","paneLocale","MenuButton","Pending_edit_infobar","hostName","reloadDraft","isDraftUntouched","refreshOpenedDraft","conflict","Remote_change_infobar","dismissedFor","showReloadDialog","onReloadClick","isNullish","getContentTypedKeyPath","contentSegments","resolveRelationKeyPath","getRelationKeyPaths","valuePattern","getRelationValues","getEntryRelationValues","getReferencingRelationFields","collected","sourceCollectionName","sourceCollection","sourceFileName","getBacklinks","seenEntryIds","backlinks","sourceCollectionFile","sourceEntry","backlink","collectionNames","Backlinks_panel","groupedEntries","Panel_container$1","historyCache","fetchEntryHistory","clearEntryHistoryCache","entryId","History_panel","showMessages","commitURL","Panel_section","getSlugEditRows","getSlugEditError","Slug_update_form","getEditError","Slug_panel","canUpdate","editorLocales","readonlySlugs","getSectionLabel","getSidebarPanelTitle","getSidebarPanelLabel","badge","sidebarSheetPanel","getSidebarPanels","showSidebarPanel","Validation_panel","onSelectField","hasResults","validating","listErrors","slugValidity","pathValidity","fragment_9","fragment_13","Sidebar_panel","additions_ConversationPanel","Sidebar_sheet","closingKey","fieldToHighlight","savedKey","draftPanelKey","lastDraftId","activeKey","sidebarPanel","View_menu_items","secondPaneAllowed","secondPaneAvailable","previewShown","hasSingleLocale","getCandidateEntries","relation","excludeIds","collectCascadeTargets","getLocaleValues","getContentUpdater","getDeletedValues","removeReferences","staleKeyPaths","listKeyPaths","getBlockers","collectDeleteTargets","getDeletedVersions","EMPTY_CASCADE_DELETE_PLAN","planCascadeDelete","planCascadeDeleteOrThrow","buildCascadeDeleteChanges","Delete_entry_dialog","cascadePlan","saveEntryUpdates","withUpdatedOrder","newOrder","buildReorderChanges","orderedEntries","currentOrder","buildArrayFileReorderChanges","reorderEntries","computeRenumberedEntries","updatedEntries","buildRenumberChanges","idSet","assetPathSet","deleteEntries","renumberChanges","renumberSavingEntries","renumberedIds","cascadeSavingEntries","updateStores$1","moveSubPath","restPath","oldDir","newDir","moveEntry","newSubPath","dirMove","localeDirMove","localeDirMoves","newLocaleSubPath","updateCanonicalSlug","buildMoveChanges","originalLocalizedEntry","buildNestedMoveChanges","oldDirPath","descendants","movedEntries","createRenamedEntry","getReplacementMap","getValuesArgs","renamedEntry","replaceReferences","outdatedKeyPaths","collectRenameTargets","relations","buildCascadeChanges","readonlyTargets","REGULAR_FILE_MODES","getPathChanges","classifyPath","getUpdatedEntry","getReferencingTargets","updatedEntry","getExpectedRewrites","rewrites","getMovedAssets","addedSHAs","findUnexpectedChanges","updatedPaths","branchFiles","companionPaths","editedPaths","editedPublishedPaths","editedCompanionPaths","movedAssetPaths","movedAssetSHAs","deletedAssetPaths","pathChanges","pathChange","usedAssetPaths","isExpected","createRefusal","verifyMergeState","unexpected","fetchUnchangedPaths","checkReviewedHead","getWorkflowErrorMessage","getWorkflowService","getEventHookArgs","getCompanionHookArgs","resolveWorkflowBranch","currentBranch","currentEntry","getPreviousPaths","applyCommitToFiles","upsertUnpublishedEntry","removeUnpublishedEntry","storeUnpublishedEntry","clearUnpublishedEntry","settleAssets","removePublishedAssets","settlePublishedEntry","companionEntries","cascadedEntries","mergeCompanions","getPublishedAsset","getFileRevertChange","getReplacedAssetChanges","stillUsedPaths","saveWorkflowChanges","allCompanions","replacedAssetChanges","allChanges","reviewPullRequest","approved","updateWorkflowStatus","newPullRequest","prevStatus","pendingPublishes","mergeWorkflowEntry","hookArgs","companionHookArgs","preType","postType","mergeState","fileStatus","publishWorkflowEntry","publishReviewedEntry","reviewed","discardWorkflowEntry","getDeletionTitleChanges","getEditedCompanionRevertChanges","publishedPaths","getOtherFileRevertChanges","handledPaths","knownPaths","deleteWorkflowEntry","titleChanges","companionRevertChanges","otherRevertChanges","discardWorkflowEntries","deleteWorkflowEntries","planMap","firstEntry","firstCollection","deleteBackups","deleteOrDiscardEntries","discardDrafts","useWorkflow","getDiscardDialogStrings","publishedVersionExists","getPublishDialogStrings","Entry_removal","deleting","showDeleteDialog","showDiscardDialog","showDeleteErrorToast","deleteErrorMessage","progressMessage","discardDialogStrings","confirmDelete","confirmDiscard","runDeletion","progressKey","deleteEntry","discardChanges","Save_conflict_dialog","conflictDescription","Status_pill","Status_badge","TONES","closeWorkflowEntryEditor","handleEntryAlreadyPublished","runWorkflowEditorAction","closeOnSuccess","handleAlreadyPublished","validateWorkflowEntry","canMoveToStatus","canPublish","Entry_status_menu","updating","itemsVersion","statusName","qualifiedStatusName","changeStatus","newStatus","_status","External_review_button","Publish_entry_button","modified","showPublishDialog","dialogStrings","publishAction","publish","findFieldByName","isBulkEditableField","isBulkEditEnabled","getBulkEditableFields","hasTemplateTag","usesCurrentTime","resolveComparisonValue","today","isLocalDateTime","toDate","isNumberLike","compareValues","targetDate","targetStr","prepareConditions","comparisons","matchesConditions","refValue","parseFilterConfig","createEntryMatcher","createViewOptionsState","filterEntries","configuredFilters","optionKeys","viewFilters","parseGroupConfig","getReorderGroupingConditions","groupEntriesByComparison","viewGroups","sortedGroups","sortCondition","reorderedEntries","reorderDirty","bulkEditing","bulkEdits","bulkEditSaving","bulkEditedEntries","bulkEditErrors","isRewriting","VIEW_TIME_INTERVAL","viewTime","viewUsesTime","listedEntries","_nestedFilterPath","filterNested","newUnpublishedEntries","listedUnpublishedEntries","listedEntryCount","QUOTA_WARNING_THRESHOLD","collectionState","_selectedCollection","canWriteToBranch","canReorder","canBulkEdit","quota","sortedEntries","filteredEntries","entryGroups","shownEntries","listedEntryIndexMap","restoreView","defaultSort","defaultFilter","groupOptions","defaultGroup","setReorderMode","reorderGroup","setBulkEditMode","initSettings$1","ASSET_FIELD_TYPES","copyEntryRelativeAssets","ownsFolder","copyAsset","copyFieldAssets","findHiddenField","resetUniqueValues","baseGetFieldArgs","duplicatedHiddenKeyPaths","clearedUuidFields","orderFieldKey","hiddenFields","propagateDuplicatedValues","duplicatedHiddenFieldMap","clearedUuidFieldMap","createDuplicateDraftState","duplicatePath","newDraft","duplicateDraft","detectWorkflowConflict","buildChanges","cascadeEntries","assetMoveChanges","checkPendingEntryConflicts","remoteChecked","checkSavable","preparePendingEntries","otherSavingEntries","finishSave","pendingCollectionName","saveEntry","canDuplicateEntry","creationDisabled","getRemovalMenuItems","canDeleteEntry","isCollectionFile","getSaveFailure","getEntryToolbarState","hasPullRequest","discardsDraft","saveEntryDraftFlow","isDraftOpen","savedEntry","savedDraft","statusError","nextStage","askForReview","closeOnSave","duplicateEntryDraft","Toolbar_1","overflowButtons","showReviewDialog","reviewStage","resolveReviewPrompt","showConflictDialog","saveConflict","showErrorDialog","duplicating","entryRemoval","collectionLabelSingular","entrySummary","busy","controlsDisabled","canDuplicate","removalMenuItems","showPublishControl","directPublishBlocked","reviewDialogLabel","discardItemStrings","_goBack","isWorkflowUsed","isCloseOnSaveEnabled","fragment_8","additions_EntryViewers","consequent_18","node_24","node_26","node_27","consequent_19","consequent_20","node_29","node_30","node_31","node_32","node_33","EntryRemoval","node_34","node_35","node_36","consequent_21","Content_details_overlay","$$arg1","secondPaneContentArea","firstPaneContentArea","restoring","switching","highlightRequestGuard","firstPaneWidth","secondPaneShown","paneStateKey","collectionReadonly","forkNotice","lockKey","showReadonlyInfobar","holdsLock","$$d_4","firstPaneSize","secondPaneSize","minPaneSize","restorePanes","switchPanes","savePanes","swapPanes","markInteracted","ensureEditPaneVisible","revealRequestedField","revealRequestedFieldIfNeeded","onmessage","hold","watchEntry","additions_EntryLockInfobar","fragment_12","targetCollection","fragment_19","firstWidth","secondWidth","alternate_3","alternate_4","Bulk_edit_cell","entrySlug","isBulkEditableEntry","getBulkEditValue","entryEdits","isSameValue","setBulkEditValue","otherFieldEdits","_entryEdits","otherEntryEdits","countBulkEdits","applyBulkEdits","fillEmpty","countUniqueValues","validateBulkEdits","uniqueValueCounts","valueCounts","buildBulkEditChanges","currentEntries","saveBulkEdits","snapshotBulkEditGroups","updateBulkEditValue","Entry_bulk_edit_list","getSummary","rowIndexMap","groupLabel","Entry_list_item_cells","showCheckbox","additions_EntryActivity","Entry_list_item","Entry_reorder_list_item","canMoveUp","canMoveDown","onMoveUp","onMoveDown","Entry_reorder_list","reorderGroups","dragOrigin","draggedEntry","publishOrder","getLocalEntries","finishDrag","localEntries","accepted","Entry_table_head","availableSortKeys","Create_entry_button","optionMenu","openEditor","indexFileLabel","hasOptions","ButtonComponent","SplitButton","ButtonComponent_1","Entry_list","hasEntries","deferRows","fragment_20","File_list","statuses","Nested_tree_item","isCurrentCollection","hasCurrentDescendant","Collection_tree_item","folderItems","treeNodes","Singleton_tree_item","isLastCommitPublished","canTriggerDeployment","Publish_button","toastStatus","hide","hasAnyNestedEntries","List_mode_controls","canSave","invalidMessage","discardMessage","onExit","invalidToast","errorToast","saveButton","cancelButton","exit","Bulk_edit_controls","getArgs","$6","ListModeControls","Delete_entries_dialog","draftEntries","publishedEntries","publishedEntryAssets","deleteSelectedEntries","deleteButton","reorderButton","reorderControls","bulkEditButton","bulkEditControls","nearingQuota","deleteDisabled","ReorderControls","BulkEditControls","hasListedEntries","hasMultipleEntries","CONTENTS_ROUTE_REGEX","showNotFound","notFoundKey","clearEditor","messageKey","findRouteUnpublishedEntry","resolveCollectionIndexRoute","selectRouteCollection","resolveListingRoute","routeType","resolveFileRoute","missing","resolveEntryRoute","resolveContentsRoute","_fileMap","Contents_page","awaitingDrafts","MainContent","FileList","EntryList","MainContent_1","Translator_selector","Translator_api_key_dialog","isKeyValid","saveKey","Content_updates_toast","Entry_parse_errors_toast","showParseErrorToast","CUSTOM_PAGE_ROUTE_REGEX","selectedCustomPageId","selectedCustomPage","customPages","getCustomPageId","getCustomPagePath","openCustomPage","Custom_page","shownPage","pageComponent","CACHE_STORE_NAMES","DATABASE_NAME_REGEX","clearTestBackendFiles","clearFileCache","getDatabaseNames","deleteDatabase","clearLocalStorage","eraseAllData","canShowMobileSignInDialog","showMobileSignInDialog","setState","onboardingState","uiSettingsNoticeStorage","createOneOffNotice","storage","demoWelcomeNotice","showDemoWelcomeDialogIfNeeded","Demo_welcome_dialog","isLiveReloadedPage","Live_reload_infobar","Mobile_promo_infobar","notice","New_language_infobar","newLocale","showInfobar","showInfobarIfNeeded","longLang","shortLang","availableLocales","hideInfobar","getLocalGitReasonLabel","getLocalGitStatusLabel","Local_git_notice_toast","shownNotice","Not_found_page","getToolbarPages","assetsLink","workflowLabelKey","adminLink","Page_switcher","listedCustomPages","customLinks","Bottom_navigation$1","installPrompt","beforeInstallPromptHandler","appInstalledHandler","initAppInstallDetection","promptAppInstall","prompt","App_install_menu_item","Shortcuts_dialog","feature","kbd","Shortcuts_menu_item","Pref_switch","Accessibility_panel","Api_key_input","onchange","Api_key_section","docsURL","Ai_panel","Appearance_panel","Contents_panel","Data_panel","showClearCacheDialog","showEraseDataDialog","clearCache","eraseData","Developer_panel","deployHookInput","savedMessage","removedMessage","deployHookShared","deployHookAuthShared","h3_1","h3_2","p_3","I18n_panel","Language_panel","localizedLabel","nativeLabel","selectedLocale","switchingLocale","switchingLocaleLabel","Media_panel","AppearancePanel","LanguagePanel","ContentsPanel","I18nPanel","MediaPanel","AiPanel","AccessibilityPanel","DeveloperPanel","DataPanel","toastMessage","Settings_dialog","selectedPanel","currentPanel","Account_menu","showPrefsDialog","linkError","isLocalRepo","Account_button","hasAvatar","Create_button","entryCollections","collectionItems","assetsDisabled","allDisabled","Release_notes_menu_item","Help_menu","Help_button","Notifications_button","Site_logo","showInHeader","Global_toolbar","Menu_page","adminSections","h3_3","Mobile_sign_in_dialog","toCanvas","Search_page","Settings_page","panelKey","Deploy_status_badge","BADGES","Workflow_entry_card","deploying","onPublish","deploySHA","deployState","companionNotes","gone","deleteIcon","span_4","span_5","span_6","Workflow_page","targetEntry","busyBranches","refreshing","isBusy","targetIsDeletion","publishDialogStrings","announced","reportRequest","onSettled","_branch","reportValidationErrors","confirmPublish","header_1","header_2","Main_router","NOT_FOUND_PAGE_NAME","ContentsPage","AssetsPage","SearchPage","WorkflowPage","CustomPage","AdminPage","MenuPage","SettingsPage","SelectedPage","NotFoundPage","selectPage","route","SelectedPage_1","Fork_permission_dialog","Open_authoring_indicator","forkURL","JSON_PROTO","defaultIsMergeableObjectFactory","deepmergeConstructor","isNotPrototypeKey","cloneArray","cloneObject","cloneProtoObject","targetKeys","concatArrays","sl","propertyIsEnumerable","getSymbolsAndKeys","isMergeableObject","onlyDefinedProperties","isPrimitive","mergeArray","_deepmerge","mergeObject","sourceKeys","sourceIsArray","targetIsArray","_deepmergeAll","getFilePathMap","getCollectionFileFolder","compareFilePath","getEntryCollectionFolders","getFileCollectionFolders","getSingletonCollectionFolders","singletonCollection","getAllEntryFolders","LOAD_CONFIG_DOC_URL","SCHEMA_TIP_URL","mergeAll","deepmerge","prefetchedResponses","requestFile","requestURL","fetchFile","manualInit","prefetched","schemaMissing","showSchemaTip","getConfigPath","verifyLinksAreSecure","getConfigLinks","prefetchCmsConfig","fetchCmsConfig","UNSUPPORTED_BACKEND_SUGGESTION_URL","AUTH_DOC_URL","BACKEND_DOC_SLUGS","OPEN_AUTHORING_DOC_URL","URL_OPTIONS","INVALID_BRANCH_SEGMENT_REGEX","isValidBranchPath","parseBackendConfig","suggestion","appId","allowTokenAuth","authDocURL","URL_OPTIONS$1","UNSUPPORTED_OPTIONS$8","BODY_FIELD_TYPES","KNOWN_FORMATS","isFormatMismatch","normalizedExtension","normalizedFormat","extensionFormat","NON_TEXT_FIELD_TYPES","isNonTextField","checkBodyField","getCanonicalSlugKey","EXPLICIT_TYPE_REGEX","hasValueKey","findFields","isFirstSegment","isValueKey","valueKeyFields","hasField","getRootFields","isNonFieldSortKey","checkFieldReferences","prefixedOnly","specialTags","checkThumbnailField","checkFieldReferences$1","fieldTypes","checkDateTimeTags","checkPreviewPath","SLUG_SPECIAL_TAGS","SUMMARY_SPECIAL_TAGS","checkSummaryTemplate","checkCollectionTemplates","parseCodeFieldConfig","checkExpression","TYPE_NAME_REGEX","LIST_INDEX_REGEX","getFieldReferences","checkFieldTags","selfReference","subKeyPath","referenceCycleCacheMap","getReferenceCycles","onStack","cycles","parseComputeFieldConfig","validateTimeZone","validateTimeZoneOptions","parseLocalizeFormatOption","parseDateTimeFieldConfig","UNSUPPORTED_OPTIONS$7","normalizeTemplateTags","FOLDER_OPTIONS","FIELD_TEMPLATE_OPTIONS","VIEW_COMPARISON_OPTIONS","normalizeOptions","normalizeMediaLibraryTemplates","legacyLibrary","normalizeI18nTemplates","normalizeFieldTemplates","normalizeCollectionFileTemplates","normalizeViewTemplates","views","listName","normalizeCollectionTemplates","normalizeConfigTemplates","normalizeEditorComponentTemplates","FOLDER_TEMPLATE_TAGS","GLOBAL_FOLDER_TAGS","checkFolderTemplateTags","isGlobal","hasCloudMediaLibrary","media_library","media_libraries","parseMediaConfig","media_folder","public_folder","asset_collections","checkNameArgs","TRANSFORMATION_KEYS","parseRasterImageTransformation","parseMediaLibraries","configs","checkMultipleDefault","checkObjectDefaultKeys","checkObjectDefault","keysArgs","parseFileFieldConfig","UNSUPPORTED_OPTIONS$6","hasLocaleTag","parseHiddenFieldConfig","RANGE_OPTIONS","checkLocalizedDefault","localizedDefault","checkCommonFieldOptions","minOption","maxOption","parseCustomFieldConfig","fieldParsers","parseFieldConfig","isBuiltIn","parseFields","MAP_KEY_FIELD_TYPES","checkFieldType","OBJECT_FIELD_TYPES","checkDefaultValue","subfields","subfieldType","holdsObjects","checkMapKeyField","checkSubFields","parseListFieldConfig","checkDefaultValue$1","typedFields","newContext","INTEGER_VALUE_TYPES","FLOAT_VALUE_TYPES","isInteger","parseNumberFieldConfig","UNSUPPORTED_OPTIONS$5","parseObjectFieldConfig","hasSlugTag","checkArrayFileOptions","UNSUPPORTED_OPTIONS$4","SPECIAL_TEMPLATE_TAGS","FIELD_REFERENCE_OPTIONS","checkFieldReference","sortField","checkArrayFileValueField","checkArrayFileWorkflowRelation","parentCollection","parseRelationFieldConfig","targetFields","UNSUPPORTED_OPTIONS$3","isBlockComponent","checkSingleLineOptions","parseRichTextFieldConfig","UNSUPPORTED_OPTIONS$2","LOCALE_OPTIONS","warnDeprecatedOptions","checkLocales","hasLocalizedField","isNonEmptyArray","parseI18nConfig","checkI18nTargets","checkI18nOverrides","parseCollectionFile","previewPathDateField","parseCollectionFiles","checkBulkEditFields","bulkEdit","checkCollectionFilter","checkIdentifierField","SINGLE_FILE_STRUCTURES","checkSlugOptions","i18nConfig","checkNamedViewOptions","isNameRequired","optionType","checkViewOptions","sortableFields","columnOption","isValidStageList","parsePublishMode","UNSUPPORTED_OPTIONS$1","index_file","indexFileContext","indexFileFields","indexFields","indexSummary","hasOwnFormat","reorderGroupName","view_groups","preview_path","preview_path_date_field","parseCollection","hasDivider","hasFolder","hasFile","optionCount","parseCollections","parseSlugConfig","parseCmsConfig","countLevelsUp","lowest","getEntryDepth","checkRootDirPaths","entryFolders","entryDepth","decodeSegment","getSegments","resolvePointer","TAG_PROPERTIES","MAX_UNION_DEPTH","getLeaves","getConstValues","leaf","describeTag","leaves","optional","leafValues","getRequired","getPropertyNames","matchProperty","buildChain","discriminateByTag","tagged","rewritten","discriminateByRequired","signatures","propertyNames","fallbackIndex","prepareSchema","allowUnknownProperties","deepCompareStrict","typeofa","aIsArray","aKeys","bKeys","encodePointer","escapePointer","uriFragmentCharacter","uriPercentEncoding","uriUnreservedCharacter","normalizeURIFragment","encoded","resolveURI","baseURI","schemaArrayKeyword","schemaMapKeyword","ignoredKeyword","initialBaseURI","dereference","basePointer","schemaURI","keyBase","subSchema","DATE","DAYS","TIME","HOSTNAME","URIREF","URITEMPLATE","URL_","UUID","JSON_POINTER","JSON_POINTER_URI_FRAGMENT","RELATIVE_JSON_POINTER","EMAIL_ADDRESS","EMAIL","address","IPV6","IPV4","DURATION","bind","date_time","isLeapYear","yearPart","monthPart","dayPart","maxDay","hourPart","minutePart","secondPart","offsetSign","offsetHour","offsetMinute","full","offsetDirection","DATE_TIME_SEPARATOR","extra","NOT_URI_FRAGMENT","URI_PATTERN","Z_ANCHOR","ucs2length","charCode","decimalInteger","coefficientAndExponent","coefficient","fractionLength","isMultipleOf","divisor","instanceCoefficient","instanceExponent","divisorCoefficient","divisorExponent","exponentDifference","instanceLocation","rawInstanceType","instanceType","$type","$const","$enum","$required","$not","$anyOf","$allOf","$oneOf","$if","$then","$else","$format","$properties","$patternProperties","$additionalProperties","$unevaluatedProperties","$minProperties","$maxProperties","$propertyNames","$dependentRequired","$dependentSchemas","$dependencies","$prefixItems","$items","$additionalItems","$unevaluatedItems","$contains","$minContains","$maxContains","$minItems","$maxItems","$uniqueItems","$minimum","$maximum","$exclusiveMinimum","$exclusiveMaximum","$multipleOf","$minLength","$maxLength","$pattern","$recursiveAnchor","recursiveAnchor","$recursiveRef","refSchema","__absolute_recursive_ref__","keywordLocation","schemaLocation","shortCircuit","evaluated","$ref","__absolute_ref__","subEvaluateds","errorsLength","anyValid","subEvaluated","allValid","ifEvaluated","thenResult","elseResult","subInstancePointer","dependantKey","dependentSchema","propsOrSchema","thisEvaluated","propertySchema","length2","contained","Validator","SCHEMA_DRAFT","CONTAINER_KEYWORDS","FALSE_SCHEMA_KEYWORD","CONSTRAINT_PARAMS","resolveKeyword","location","normalizeUnit","instancePath","keyword","param","findUnknownProperties","failedLocations","compileSchema","validator","getCustomFieldSchemas","validateSchema","metaSchema","applyCustomFieldSchemas","customField","formatValue","formatType","formatOption","appendFieldName","locateError","structural","reportSchemaErrors","relevant","hasAlternatives","preparedSchemas","getConfigSchemas","configSchema","replaceRegExps","validateConfigSchema","violations","updateFolders","initCmsConfig","rawConfig","manualConfig","App","ncRoot","transitioned","documentTitle","link_1","link_2","link_3","link_4","registerCustomFormat","fromFile","toFile","registerCustomPage","resolvedURL","assertOptionalFunction","validateInlineDefinition","validateBlockDefinition","htmlOptions","registerEditorComponent","registerEventListener","eventListener","registerFieldType","isDefinition","controlOption","previewOption","typeSchema","controlComponent","previewComponent","summaryComponent","registerPreviewStyle","registerPreviewTemplate","registerStringTransformation","renderRichText","BundledReact","CMS","htm_module_default","parseStyle","addDeclaration","cssText","htm","main_default","Fragment","\"__SVELTIA_CMS_REACT__\"","sharedModules","marked","scriptElement"],"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,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,334,335,353,354,355,356,363,369,370,371,372,373,374,375,376,378,379,380,381,385,386,394,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,487,488,489,490,491,492,493,494,549,550,551,1330,1374,1375,1376,1377,1378,1379,1380,1399],"sources":["../../node_modules/.pnpm/react@19.3.1/node_modules/react/cjs/react.production.js","../../node_modules/.pnpm/react@19.3.1/node_modules/react/index.js","../../node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js","../../node_modules/.pnpm/create-react-class@15.7.0/node_modules/create-react-class/factory.js","../../node_modules/.pnpm/create-react-class@15.7.0/node_modules/create-react-class/index.js","../../node_modules/.pnpm/dompurify@3.4.18/node_modules/dompurify/dist/purify.es.mjs","../../node_modules/.pnpm/isomorphic-dompurify@4.8.0_@napi-rs+canvas@1.2.0/node_modules/isomorphic-dompurify/dist/browser.mjs","../../node_modules/.pnpm/marked@18.2.1/node_modules/marked/lib/marked.esm.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/constants.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/shared/utils.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/constants.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/warnings.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/hydration.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/reactivity/equality.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/shared/errors.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/errors.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/shared/clone.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/task.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/reactivity/status.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/shared/context.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/context.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/custom-renderer/state.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/reactivity/async.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/reactivity/deriveds.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/reactivity/batch.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/reactivity/sources.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/proxy.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/operations.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/error-handling.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/reactivity/effects.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/legacy.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/misc.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/bindings/shared.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/runtime.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/utils.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/events.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/reconciler.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/template.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/reactivity/create-subscriber.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/boundary.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/render.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/branches.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/snippet.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/index-client.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/attachments/index.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dev/css.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/await.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/if.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/key.js","../../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/shared/attributes.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/css-props.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/each.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/html.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/svelte-component.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/timing.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/loop.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/transitions.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/svelte-element.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/blocks/svelte-head.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/css.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/attachments.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/class.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/style.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/bindings/select.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/attributes.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/bindings/input.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/bindings/size.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/dom/elements/bindings/this.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/reactivity/store.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/client/reactivity/props.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/legacy/legacy-client.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/cst/names.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/data-model/from-cst.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/errors.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/data-model/parse.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/data-model/visit.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/data-model/validate.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/dir-utils.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/utils.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/number.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/currency.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/datetime.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/offset.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/percent.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/string.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/unit.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/index.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/message-value.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/fallback.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/functions/unknown.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/resolve/function-context.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/resolve/resolve-function-ref.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/resolve/resolve-expression.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/resolve/resolve-variable.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/resolve/resolve-value.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/resolve/format-markup.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/select-pattern.js","../../node_modules/.pnpm/@sveltia+i18n@1.5.0_svelte@5.59.1_@typescript-eslint+types@8.73.0_/node_modules/@sveltia/i18n/dist/index.svelte.js","../../node_modules/.pnpm/messageformat@4.1.0/node_modules/messageformat/lib/messageformat.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/init-operations.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/internal/disclose-version.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/icon/icon.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/alert/alert-content.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/alert/alert.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/alert/alert.svelte","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/events.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/value.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/typography/truncated-text.svelte","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/misc.js","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/crypto.js","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/element.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/focus.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/navigation.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/popup-position.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/popup.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/modal.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/placeholder.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/modal.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/popup.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/tooltip.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/tooltip.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/alert/infobar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/bottom-navigation/bottom-navigation.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/copy-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/floating-action-button-wrapper.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/select.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/text.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/type-ahead.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/widget.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/composite-widget.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/scroll.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/menu.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/group.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/select-button-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/select-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/split-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/checkbox/checkbox-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/label.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/checkbox/checkbox.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/divider/spacer.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/modal-close-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/dialog.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/alert-dialog.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/confirmation-dialog.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/label-above.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/emoji/caret.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/emoji/emoji.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/emoji/position.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/emoji/emoji-suggestions.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/emoji-autocomplete.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/text-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/prompt-dialog.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/divider/divider.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/drawer/drawer.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/drawer/drawer.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/file/file-picker.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid-body.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/table/table-part.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid-cell.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid-col-header.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid-head.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid-row.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/listbox/listbox.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/listbox/option-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/listbox/option.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-item.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-item-checkable.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-item-checkbox.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-item-radio.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/progressbar/progressbar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/radio/radio-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/radio/radio.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/pointer-drag.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/resizable-pane/sizing.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/resizable-pane/resizable-handle.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/resizable-pane/resizable-pane-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/resizable-pane/resizable-pane.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/scroll/infinite-scroll.svelte","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/easing/index.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/animate/index.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/search-bar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/select/combobox.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/select/select.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/select/select-tags.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/select/select-tags.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/number.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/slider/slider.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/slider/slider.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/switch/switch.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/table/table-cell.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/table/table-row.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/table/table.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tabs/tab-list.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tabs/tab-list.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tabs/tab-panel.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tabs/tab.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/toast/toast.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/code-editor.js","../../node_modules/.pnpm/lexical@0.53.0_typescript@6.0.3/node_modules/lexical/dist/Lexical.prod.js","../../node_modules/.pnpm/@lexical+selection@0.53.0_typescript@6.0.3/node_modules/@lexical/selection/dist/LexicalSelection.prod.js","../../node_modules/.pnpm/@lexical+utils@0.53.0_typescript@6.0.3/node_modules/@lexical/utils/dist/LexicalUtils.prod.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionConfig.prod.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionInitialStateExtension.prod.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionLexicalBuilder.prod.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionGetPeerDependencyFromEditor.prod.js","../../node_modules/.pnpm/@preact+signals-core@1.14.5/node_modules/@preact/signals-core/dist/signals-core.module.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionWatchedSignal.prod.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionEditorStateExtension.prod.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionNodeSelectionExtension.prod.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionHorizontalRuleExtension.prod.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionGetExtensionDependency.prod.js","../../node_modules/.pnpm/@lexical+html@0.53.0_typescript@6.0.3/node_modules/@lexical/html/dist/LexicalHtml.prod.js","../../node_modules/.pnpm/@lexical+extension@0.53.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionNamedSignals.prod.js","../../node_modules/.pnpm/@lexical+code-core@0.53.0_typescript@6.0.3/node_modules/@lexical/code-core/dist/LexicalCodeCore.prod.js","../../node_modules/.pnpm/@lexical+link@0.53.0_typescript@6.0.3/node_modules/@lexical/link/dist/LexicalLink.prod.js","../../node_modules/.pnpm/@lexical+list@0.53.0_typescript@6.0.3/node_modules/@lexical/list/dist/LexicalList.prod.js","../../node_modules/.pnpm/@lexical+clipboard@0.53.0_typescript@6.0.3/node_modules/@lexical/clipboard/dist/LexicalClipboard.prod.js","../../node_modules/.pnpm/@lexical+dragon@0.53.0_typescript@6.0.3/node_modules/@lexical/dragon/dist/LexicalDragon.prod.js","../../node_modules/.pnpm/@lexical+rich-text@0.53.0_typescript@6.0.3/node_modules/@lexical/rich-text/dist/LexicalRichText.prod.js","../../node_modules/.pnpm/@lexical+markdown@0.53.0_typescript@6.0.3/node_modules/@lexical/markdown/dist/LexicalMarkdown.prod.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/markdown/syntax.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/markdown/code-blocks.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/transformers/code.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/transformers/inline-code.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/transformers/link.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/transformers/task-list.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/constants.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/caret.js","../../node_modules/.pnpm/@lexical+history@0.53.0_typescript@6.0.3/node_modules/@lexical/history/dist/LexicalHistory.prod.js","../../node_modules/.pnpm/@lexical+table@0.53.0_typescript@6.0.3/node_modules/@lexical/table/dist/LexicalTable.prod.js","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/storage/indexed-db.js","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/storage/local-storage.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/generated.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/cache.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/loader.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/background-update.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/theme.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/engine.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/html/task-list.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/html/utils.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/html/paragraph.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/html/export.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/html/components.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/html/import-rules.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/html/unsupported.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/html/index.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/lexical.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/highlighter.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/transformers/hr.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/transformers/raw-syntax.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/block.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/table.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/markdown/code-spans.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/transformers/block-escape.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/transformers/table.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/markdown/block-structure.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/markdown/block-conversion.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/markdown/formatting.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/markdown/placeholders.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/markdown/index.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/alignment.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/selection.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/utils.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/update.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/editor-components.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/single-line.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/config.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/commands.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/guards.js","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/string.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/link.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/preload.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/transformers/formatted-code.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/import.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/conversion/paste.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/core.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/lexical-root.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/store.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/code-language-switcher.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/toolbar/toolbar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/toolbar-wrapper.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/code-editor.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/text-area.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/text-area.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/widgets/emoji-autocomplete.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/editing/raw-markdown.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/actions.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/widgets/floating-link-editor.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/menu.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/table-action-menu.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/widgets/table-cell-menu-button.svelte","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/object.js","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/array.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/source-highlight.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/button-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/align-menu-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/format-text-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/insert-horizontal-rule-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/insert-item-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/insert-link-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/insert-menu-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/number-input.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/number-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/insert-table-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/toggle-block-menu-item.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/text-editor-toolbar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/text-editor.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/color-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/date-time-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/masked-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/password-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/secret-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tree/tree-item.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/tree.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tree/tree.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/app-shell.js","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/app-shell.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/empty-state.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/visibility-observer.svelte","../../node_modules/.pnpm/@sveltia+ui@0.96.2_svelte@5.59.1_@typescript-eslint+types@8.73.0__typescript@6.0.3/node_modules/@sveltia/ui/dist/locales/en-US.yaml","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/file.js","../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js","../../src/lib/services/config/constants.js","../../src/lib/services/utils/state.svelte.js","../../src/lib/services/config/state.js","../../src/lib/services/config/index.js","../../src/lib/services/contents/collection/predicates.js","../../src/lib/services/contents/fields/index.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/reactivity/set.js","../../node_modules/.pnpm/svelte@5.59.1_@typescript-eslint+types@8.73.0/node_modules/svelte/src/reactivity/map.js","../../src/lib/services/api/registries.js","../../src/lib/services/common/template/constants.js","../../src/lib/services/common/template/tags.js","../../src/lib/services/common/template/utils.js","../../src/lib/services/contents/collection/entries/index-file.js","../../src/lib/services/contents/file/constants.js","../../src/lib/services/utils/string.js","../../src/lib/services/contents/collection/nested/index.js","../../src/lib/services/utils/cache.js","../../src/lib/services/contents/i18n/placeholder.js","../../src/lib/services/contents/i18n/index.js","../../src/lib/services/contents/file/config.js","../../src/lib/services/contents/i18n/config/constants.js","../../src/lib/services/contents/i18n/config/merge.js","../../src/lib/services/contents/i18n/config/index.js","../../src/lib/services/integrations/media-libraries/multiple.js","../../src/lib/services/contents/collection/index.js","../../node_modules/.pnpm/truncate-utf8-bytes@1.0.2/node_modules/truncate-utf8-bytes/lib/truncate.js","../../node_modules/.pnpm/utf8-byte-length@1.0.5/node_modules/utf8-byte-length/browser.js","../../node_modules/.pnpm/truncate-utf8-bytes@1.0.2/node_modules/truncate-utf8-bytes/browser.js","../../node_modules/.pnpm/sanitize-filename@1.6.5/node_modules/sanitize-filename/index.js","../../src/lib/services/utils/url.js","../../src/lib/services/utils/file.js","../../src/lib/services/contents/entry/paths.js","../../src/lib/services/assets/entry-folder.js","../../src/lib/services/assets/state.js","../../src/lib/services/assets/lookup.js","../../node_modules/.pnpm/@sveltia+utils@0.13.2/node_modules/@sveltia/utils/dist/datetime.js","../../src/lib/services/common/slug/constants.js","../../src/lib/services/api/lazy-module.js","../../src/lib/services/app/dependencies.js","../../src/lib/services/common/slug/transliterate.js","../../src/lib/services/common/slug/index.js","../../node_modules/.pnpm/character-entities-legacy@3.0.0/node_modules/character-entities-legacy/index.js","../../node_modules/.pnpm/character-reference-invalid@2.0.1/node_modules/character-reference-invalid/index.js","../../node_modules/.pnpm/is-decimal@2.0.1/node_modules/is-decimal/index.js","../../node_modules/.pnpm/is-hexadecimal@2.0.1/node_modules/is-hexadecimal/index.js","../../node_modules/.pnpm/is-alphabetical@2.0.1/node_modules/is-alphabetical/index.js","../../node_modules/.pnpm/is-alphanumerical@2.0.1/node_modules/is-alphanumerical/index.js","../../node_modules/.pnpm/decode-named-character-reference@1.3.0/node_modules/decode-named-character-reference/index.dom.js","../../node_modules/.pnpm/parse-entities@4.0.2/node_modules/parse-entities/lib/index.js","../../src/lib/services/common/template/nested.js","../../node_modules/.pnpm/dayjs@1.11.23/node_modules/dayjs/dayjs.min.js","../../node_modules/.pnpm/dayjs@1.11.23/node_modules/dayjs/plugin/customParseFormat.js","../../node_modules/.pnpm/dayjs@1.11.23/node_modules/dayjs/plugin/localizedFormat.js","../../node_modules/.pnpm/dayjs@1.11.23/node_modules/dayjs/plugin/utc.js","../../src/lib/services/contents/fields/date-time/config.js","../../src/lib/services/contents/fields/date-time/locale-loader.js","../../src/lib/services/contents/fields/date-time/locales.js","../../node_modules/.pnpm/dayjs@1.11.23/node_modules/dayjs/plugin/advancedFormat.js","../../node_modules/.pnpm/dayjs@1.11.23/node_modules/dayjs/plugin/timezone.js","../../src/lib/services/contents/fields/date-time/parse.js","../../src/lib/services/utils/markdown.js","../../src/lib/services/common/transformations.js","../../src/lib/services/contents/index.js","../../src/lib/services/contents/collection/files/index.js","../../src/lib/services/contents/collection/identifier.js","../../src/lib/services/contents/entry/key-paths.js","../../node_modules/.pnpm/flat@6.0.1/node_modules/flat/index.js","../../src/lib/services/utils/object.js","../../src/lib/services/contents/entry/subtree.js","../../src/lib/services/contents/fields/rich-text/components/inline-pattern.js","../../src/lib/services/contents/fields/internal-props.js","../../src/lib/services/contents/fields/rich-text/components/utils.js","../../src/lib/services/contents/fields/rich-text/constants.js","../../src/lib/services/contents/fields/rich-text/sanitize.js","../../src/lib/services/contents/fields/rich-text/components/definitions.js","../../src/lib/services/utils/number.js","../../src/lib/services/contents/entry/fields.js","../../src/lib/services/utils/date.js","../../src/lib/services/contents/fields/date-time/timezone.js","../../src/lib/services/contents/fields/date-time/value.js","../../src/lib/services/contents/fields/date-time/display.js","../../src/lib/services/contents/fields/number/helpers.js","../../src/lib/services/contents/collection/view/values.js","../../src/lib/services/contents/folders.js","../../src/lib/services/contents/entry/collections.js","../../src/lib/services/contents/fields/list/subfields.js","../../src/lib/services/contents/fields/list/map.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/identity.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/visit.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/doc/directives.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/doc/anchors.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/doc/applyReviver.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/toJS.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/Node.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/Alias.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/Scalar.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/doc/createNode.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/Collection.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/stringify/stringifyComment.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/stringify/foldFlowLines.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/stringify/stringifyString.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/stringify/stringify.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/stringify/stringifyPair.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/log.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/Pair.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/stringify/stringifyCollection.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/YAMLMap.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/common/map.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/nodes/YAMLSeq.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/common/seq.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/common/string.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/common/null.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/core/bool.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/stringify/stringifyNumber.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/core/float.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/core/int.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/core/schema.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/json/schema.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/tags.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/schema/Schema.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/stringify/stringifyDocument.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/doc/Document.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/errors.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/resolve-props.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/util-contains-newline.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/util-map-includes.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/resolve-block-map.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/resolve-block-seq.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/resolve-end.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/compose-collection.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/compose-scalar.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/compose-node.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/compose-doc.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/compose/composer.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/parse/cst-visit.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/parse/cst.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/parse/lexer.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/parse/line-counter.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/parse/parser.js","../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/browser/dist/public-api.js","../../src/lib/services/contents/file/state.js","../../src/lib/services/contents/file/value-sources.js","../../src/lib/services/contents/file/integers.js","../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/error.js","../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/primitive.js","../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/date.js","../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/extract.js","../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/util.js","../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/struct.js","../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/parse.js","../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/stringify.js","../../src/lib/services/contents/file/leading-comments.js","../../src/lib/services/contents/file/toml-sources.js","../../src/lib/services/contents/file/parse.js","../../src/lib/services/utils/scheduling.js","../../src/lib/services/contents/file/process.js","../../src/lib/services/utils/regex.js","../../src/lib/services/contents/collection/entries/index.js","../../src/lib/services/contents/collection/entries/reorder/config.js","../../src/lib/services/contents/collection/entries/reorder/sort.js","../../src/lib/services/contents/fields/relation/helpers/cache.js","../../src/lib/services/contents/fields/relation/helpers/field-names.js","../../src/lib/services/contents/fields/relation/helpers/templates.js","../../src/lib/services/contents/fields/relation/helpers/list-fields.js","../../src/lib/services/contents/fields/relation/helpers/options.js","../../src/lib/services/contents/fields/relation/helpers/entries.js","../../src/lib/services/contents/i18n/fields.js","../../src/lib/services/contents/i18n/shared-values.js","../../src/lib/services/contents/fields/relation/helpers/filters.js","../../src/lib/services/utils/database.js","../../src/lib/services/common/view.js","../../src/lib/services/contents/collection/view/options.js","../../src/lib/services/contents/collection/view/table-keys.js","../../src/lib/services/utils/locale.js","../../src/lib/services/contents/i18n/options.js","../../src/lib/services/contents/collection/view/sort-keys.js","../../src/lib/services/contents/collection/view/sort.js","../../src/lib/services/contents/fields/relation/helpers/sort.js","../../src/lib/services/contents/fields/relation/helpers/index.js","../../src/lib/services/contents/fields/select/helpers.js","../../src/lib/services/utils/commit-author.js","../../src/lib/services/contents/entry/values.js","../../src/lib/services/contents/entry/summary.js","../../src/lib/services/common/template/handlers.js","../../src/lib/services/common/template/replacers.js","../../src/lib/services/app/additions.js","../../src/lib/services/backends/fs/git/attributes.js","../../src/lib/services/backends/fs/git/constants.js","../../src/lib/services/backends/root-dir.js","../../src/lib/services/backends/fs/shared/handles.js","../../src/lib/services/backends/fs/git/file-system.js","../../src/lib/services/utils/bytes.js","../../src/lib/services/utils/crypto.js","../../src/lib/services/backends/fs/git/index-file.js","../../src/lib/services/backends/fs/git/objects.js","../../src/lib/services/backends/fs/git/tree.js","../../src/lib/services/backends/fs/git/repository.js","../../src/lib/services/backends/git/shared/concurrency.js","../../src/lib/services/backends/git/shared/errors.js","../../src/lib/services/user/constants.js","../../src/lib/services/user/account.svelte.js","../../src/lib/services/workflow/open-authoring.js","../../src/lib/services/backends/git/shared/commits.js","../../src/lib/services/backends/fs/git/commit.js","../../src/lib/services/backends/fs/git/index.js","../../node_modules/.pnpm/mime@4.1.2/node_modules/mime/dist/types/standard.js","../../node_modules/.pnpm/mime@4.1.2/node_modules/mime/dist/src/Mime.js","../../node_modules/.pnpm/mime@4.1.2/node_modules/mime/dist/src/index_lite.js","../../src/lib/services/utils/mime.js","../../src/lib/services/assets/kinds.js","../../src/lib/services/backends/git/shared/config.js","../../src/lib/services/assets/reserved.js","../../src/lib/services/backends/branch-access.js","../../src/lib/services/workflow/constants.js","../../src/lib/services/workflow/config.js","../../src/lib/services/workflow/branch.js","../../src/lib/services/workflow/forks.js","../../src/lib/services/config/readonly.js","../../src/lib/services/assets/folders.js","../../src/lib/services/backends/git/shared/managed-paths.js","../../src/lib/services/backends/fs/shared/scan.js","../../src/lib/services/backends/git/shared/defer.js","../../src/lib/services/backends/process.js","../../src/lib/services/utils/logging.js","../../src/lib/services/backends/fs/shared/load.js","../../src/lib/services/utils/networking.js","../../src/lib/services/user/env.svelte.js","../../src/lib/services/backends/fs/shared/save.js","../../src/lib/services/backends/git/github/api.js","../../src/lib/services/backends/git/shared/api.js","../../src/lib/services/backends/git/shared/user.js","../../src/lib/services/backends/git/github/user.js","../../src/lib/services/backends/git/gitea/constants.js","../../src/lib/services/backends/git/shared/auth.js","../../src/lib/services/backends/git/github/auth.js","../../src/lib/services/backends/commit-progress.js","../../src/lib/services/user/prefs.svelte.js","../../src/lib/services/backends/git/shared/repository.js","../../src/lib/services/backends/git/github/repository.js","../../src/lib/services/backends/git/shared/api-optional.js","../../src/lib/services/backends/git/shared/poll.js","../../src/lib/services/backends/git/shared/pull-requests.js","../../src/lib/services/workflow/labels.js","../../src/lib/services/backends/git/shared/fork.js","../../src/lib/services/backends/git/github/fork.js","../../src/lib/services/backends/git/github/git-data.js","../../src/lib/services/utils/array.js","../../src/lib/services/backends/git/github/graphql.js","../../src/lib/services/backends/git/shared/commit-split.js","../../src/lib/services/backends/git/shared/head.js","../../src/lib/services/backends/git/github/commits.js","../../src/lib/services/backends/git/shared/deployment.js","../../src/lib/services/backends/git/github/deployment.js","../../src/lib/services/backends/git/shared/reconcile.js","../../src/lib/services/backends/git/shared/reparse.js","../../src/lib/services/backends/git/shared/parse-files.js","../../src/lib/services/backends/git/shared/tree.js","../../src/lib/services/backends/git/shared/file-cache.js","../../src/lib/services/backends/git/shared/scope.js","../../src/lib/services/deployments/index.js","../../src/lib/services/backends/git/shared/fetch.js","../../src/lib/services/backends/git/shared/files.js","../../src/lib/services/backends/git/shared/progress.js","../../src/lib/services/backends/git/github/files.js","../../src/lib/services/backends/git/shared/status.js","../../src/lib/services/backends/git/github/status.js","../../src/lib/services/backends/git/shared/workflow.js","../../src/lib/services/backends/git/github/auto-merge.js","../../src/lib/services/backends/git/github/pull-requests.js","../../src/lib/services/backends/git/github/workflow-fork.js","../../src/lib/services/utils/paging.js","../../src/lib/services/backends/git/github/workflow.js","../../src/lib/services/backends/git/shared/init.js","../../src/lib/services/backends/git/github/index.js","../../src/lib/services/backends/git/services.js","../../src/lib/services/backends/fs/local.js","../../src/lib/services/backends/fs/seed.js","../../src/lib/services/backends/fs/test.js","../../src/lib/services/backends/index.js","../../src/lib/services/workflow/stages.js","../../src/lib/services/workflow/index.js","../../src/lib/services/common/template/index.js","../../src/lib/services/assets/entry-relative.js","../../src/lib/services/integrations/media-libraries/options.js","../../src/lib/services/integrations/media-libraries/index.js","../../src/lib/services/utils/media/image/index.js","../../src/lib/services/utils/media/image/animation.js","../../src/lib/services/utils/media/image/sniff.js","../../src/lib/services/utils/media/image/encode.js","../../src/lib/services/utils/media/image/heic.js","../../src/lib/services/utils/media/image/options.js","../../src/lib/services/utils/media/image/resize.js","../../src/lib/services/utils/media/image/transform.js","../../src/lib/services/integrations/media-libraries/default/index.js","../../src/lib/services/assets/subfolders.js","../../src/lib/services/config/folders/assets.js","../../src/lib/services/contents/entry/contexts.js","../../src/lib/services/assets/index.js","../../src/lib/services/assets/view/filter.js","../../src/lib/services/assets/view/group.js","../../src/lib/services/utils/media/image/svg.js","../../src/lib/services/utils/media/pdf-options.js","../../src/lib/services/utils/media/pdf.js","../../src/lib/services/assets/info.js","../../src/lib/services/integrations/media-libraries/cloud/shared/keys.js","../../src/lib/services/assets/file-name.js","../../src/lib/services/integrations/media-libraries/cloud/search.js","../../src/lib/services/integrations/media-libraries/cloud/shared/object-storage.js","../../src/lib/services/integrations/media-libraries/cloud/shared/service.js","../../src/lib/services/utils/xml.js","../../src/lib/services/integrations/media-libraries/cloud/azure-blob-storage.js","../../src/lib/services/integrations/media-libraries/cloud/cloudinary.js","../../src/lib/services/integrations/media-libraries/cloud/s3/core.js","../../src/lib/services/integrations/media-libraries/cloud/s3/service.js","../../src/lib/services/integrations/media-libraries/cloud/s3/aws-s3.js","../../src/lib/services/integrations/media-libraries/cloud/s3/backblaze-b2.js","../../src/lib/services/integrations/media-libraries/cloud/s3/bunny-storage.js","../../src/lib/services/integrations/media-libraries/cloud/s3/cloudflare-r2.js","../../src/lib/services/integrations/media-libraries/cloud/s3/digitalocean-spaces.js","../../src/lib/services/integrations/media-libraries/cloud/s3/neon-object-storage.js","../../src/lib/services/integrations/media-libraries/cloud/s3/scaleway.js","../../src/lib/services/integrations/media-libraries/cloud/s3/supabase.js","../../src/lib/services/integrations/media-libraries/cloud/uploadcare.js","../../src/lib/services/integrations/media-libraries/cloud/index.js","../../src/lib/services/assets/media-field.js","../../src/lib/services/contents/fields/rich-text/index.js","../../src/lib/services/contents/fields/rich-text/options.js","../../src/lib/services/utils/html.js","../../src/lib/services/contents/fields/rich-text/previews/media-urls.js","../../src/lib/services/contents/fields/rich-text/previews/media-sources.js","../../src/lib/services/assets/references.js","../../src/lib/services/utils/media/image/exif.js","../../src/lib/services/utils/media/index.js","../../src/lib/services/assets/external/details.js","../../src/lib/services/assets/external/availability.js","../../src/lib/services/assets/external/linked.js","../../src/lib/services/user/api-keys.js","../../src/lib/services/assets/external/index.js","../../src/lib/services/assets/view/settings.js","../../src/lib/services/assets/view/sort.js","../../src/lib/services/assets/view/index.js","../../src/lib/services/contents/editor/index.js","../../src/lib/services/contents/editor/route.js","../../src/lib/services/utils/window.js","../../src/lib/services/app/navigation.js","../../src/lib/components/common/page-container-main-area.svelte","../../src/lib/components/common/page-toolbar/back-button.svelte","../../src/lib/components/admin/main-area.svelte","../../src/lib/services/utils/name.js","../../src/lib/components/common/avatar.svelte","../../src/lib/components/contents/details/sidebar/panels/panel-container.svelte","../../src/lib/services/app/admin.js","../../src/lib/services/app/branding.js","../../src/lib/services/app/update.js","../../src/lib/services/backends/git/gitea/config.js","../../src/lib/services/backends/git/shared/dir-sha.js","../../src/lib/services/backends/git/shared/integration.js","../../src/lib/services/backends/git/shared/tree-cache.js","../../src/lib/services/contents/draft/pending-entries.js","../../src/lib/services/contents/fields/code/helpers.js","../../src/lib/services/contents/fields/object/helpers.js","../../src/lib/services/contents/fields/relation/helpers/locale.js","../../src/lib/services/contents/fields/locale.js","../../src/lib/services/contents/i18n/duplicate-if-empty.js","../../src/lib/services/contents/fields/list/helpers.js","../../src/lib/services/contents/entry/owner-field.js","../../src/lib/services/contents/fields/key-value/pairs.js","../../src/lib/services/contents/fields/key-value/order.js","../../src/lib/services/contents/draft/index.js","../../src/lib/services/contents/draft/create/versioned-map.svelte.js","../../src/lib/services/contents/draft/value-map.svelte.js","../../src/lib/services/contents/draft/state.svelte.js","../../src/lib/services/contents/entry/managed-key.js","../../src/lib/services/contents/entry/aliases.js","../../src/lib/services/contents/entry/earlier-paths.js","../../src/lib/services/contents/entry/entry-key.js","../../src/lib/services/integrations/ai/api.js","../../src/lib/services/integrations/ai/anthropic.js","../../src/lib/services/integrations/ai/deepseek.js","../../src/lib/services/integrations/ai/google.js","../../src/lib/services/integrations/ai/mistral.js","../../src/lib/services/integrations/ai/openai.js","../../src/lib/services/integrations/ai/index.js","../../src/lib/services/integrations/media-libraries/stock/credit.js","../../src/lib/services/integrations/media-libraries/stock/utils.js","../../src/lib/services/integrations/media-libraries/stock/pexels.js","../../src/lib/services/integrations/media-libraries/stock/picsum.js","../../src/lib/services/integrations/media-libraries/stock/pixabay.js","../../src/lib/services/integrations/media-libraries/stock/unsplash.js","../../src/lib/services/integrations/media-libraries/stock/index.js","../../src/lib/services/integrations/translators/ai-translation.js","../../src/lib/services/integrations/translators/anthropic.js","../../src/lib/services/integrations/translators/deepseek.js","../../src/lib/services/integrations/translators/google.js","../../src/lib/services/integrations/translators/index.js","../../src/lib/services/integrations/translators/google-ai.js","../../src/lib/services/integrations/translators/mistral.js","../../src/lib/services/integrations/translators/openai.js","../../src/lib/services/integrations/api-key-services.js","../../src/lib/services/backends/refresh.js","../../src/lib/services/workflow/assets.js","../../src/lib/services/contents/entry/readonly.js","../../src/lib/services/contents/entry/editable.js","../../src/lib/services/workflow/entries.js","../../src/lib/services/workflow/load.js","../../src/lib/services/backends/poll.js","../../src/lib/services/deployments/constants.js","../../src/lib/services/deployments/ping.js","../../src/lib/services/deployments/resolve.js","../../src/lib/services/user/magic-link.js","../../src/lib/services/workflow/deploy.js","../../src/lib/services/user/auth.svelte.js","../../src/lib/services/utils/generation.js","../../src/lib/services/api/compatibility.js","../../src/lib/components/contents/details/fields/boolean/boolean-editor.svelte","../../src/lib/components/contents/details/fields/boolean/boolean-preview.svelte","../../src/lib/services/contents/draft/update/deferred.js","../../src/lib/services/contents/editor/field-context.js","../../src/lib/services/contents/editor/pending.js","../../src/lib/services/contents/editor/pending.svelte.js","../../src/lib/components/contents/details/fields/code/code-editor.svelte","../../src/lib/components/contents/details/fields/code/code-preview.svelte","../../src/lib/services/contents/fields/color/helpers.js","../../src/lib/components/contents/details/fields/color/color-editor.svelte","../../src/lib/components/contents/details/fields/color/color-preview.svelte","../../src/lib/components/contents/details/fields/compute/compute-editor.svelte","../../src/lib/services/contents/entry/content-index.js","../../src/lib/services/contents/fields/compute/expression.js","../../src/lib/services/contents/fields/compute/helpers.js","../../src/lib/components/contents/details/fields/compute/compute-preview.svelte","../../src/lib/components/assets/browser/cloudinary-panel.svelte","../../src/lib/components/assets/browser/asset-path.svelte","../../src/lib/components/common/breadcrumb.svelte","../../src/lib/components/assets/browser/picker-breadcrumb.svelte","../../src/lib/components/assets/browser/simple-image-grid-item.svelte","../../src/lib/services/app/focus.js","../../src/lib/components/assets/browser/subfolder-strip.svelte","../../src/lib/components/assets/browser/simple-image-grid.svelte","../../src/lib/components/assets/list/name-input-dialog.svelte","../../src/lib/components/assets/list/subfolder-name-dialog.svelte","../../src/lib/services/utils/visibility.js","../../src/lib/services/assets/preview-lifecycle.js","../../src/lib/services/utils/render.js","../../src/lib/components/assets/shared/asset-preview.svelte","../../src/lib/services/integrations/service-description.js","../../src/lib/components/assets/shared/cloud-service-auth.svelte","../../src/lib/components/assets/shared/image.svelte","../../src/lib/components/common/remove-button.svelte","../../src/lib/services/assets/file-size.js","../../src/lib/services/assets/file-type.js","../../src/lib/components/assets/shared/upload-assets-preview.svelte","../../src/lib/services/assets/movable.js","../../src/lib/services/assets/drag.js","../../src/lib/components/assets/shared/drop-zone.svelte","../../src/lib/components/assets/shared/rejected-files-alert-dialog.svelte","../../src/lib/services/assets/browser/select-assets-dialog.svelte.js","../../src/lib/services/contents/collection/data/index.js","../../src/lib/services/assets/data/index.js","../../src/lib/services/backends/commit-prompt.js","../../src/lib/services/assets/data/commit.js","../../src/lib/services/assets/data/move-change.js","../../src/lib/services/assets/reference-target.js","../../src/lib/services/contents/draft/save/key-path.js","../../src/lib/services/contents/entry/locales.js","../../src/lib/services/contents/entry/index.js","../../src/lib/services/contents/entry/site-path.js","../../src/lib/services/contents/entry/permalink.js","../../src/lib/services/contents/draft/save/serialize.js","../../src/lib/services/contents/draft/save/content.js","../../src/lib/services/contents/file/format.js","../../src/lib/services/contents/draft/save/entry-file.js","../../src/lib/services/contents/file/detected-formats.js","../../src/lib/services/contents/draft/save/file-changes.js","../../src/lib/services/contents/file/array.js","../../src/lib/services/backends/save.js","../../src/lib/services/api/immutable.js","../../src/lib/services/api/asset-proxy.js","../../src/lib/services/api/external-asset-proxy.js","../../src/lib/services/api/unsaved-asset-proxy.js","../../src/lib/services/config/deprecations.js","../../src/lib/services/api/preview-data.js","../../src/lib/services/contents/entry/assets.js","../../src/lib/services/api/events.js","../../src/lib/services/contents/draft/save/aliases.js","../../src/lib/services/contents/draft/save/asset-move.js","../../src/lib/services/contents/draft/save/asset-references.js","../../src/lib/services/assets/name.js","../../src/lib/services/contents/collection/slug.js","../../src/lib/services/contents/collection/nested/i18n.js","../../src/lib/services/contents/draft/slugs.js","../../src/lib/services/contents/draft/save/entry-path.js","../../src/lib/services/contents/draft/save/assets.js","../../src/lib/services/contents/draft/save/permalink.js","../../src/lib/services/contents/draft/save/changes.js","../../src/lib/services/assets/data/move.js","../../src/lib/services/utils/undo.js","../../src/lib/services/assets/external/move.js","../../src/lib/services/utils/media/image/validate.js","../../src/lib/services/assets/process.js","../../src/lib/services/assets/external/data.js","../../src/lib/services/search/util.js","../../src/lib/services/assets/external/view.js","../../src/lib/components/assets/browser/external-assets-panel.svelte","../../src/lib/components/assets/browser/assets-panel.svelte","../../src/lib/components/assets/browser/internal-assets-panel.svelte","../../src/lib/components/assets/browser/location-selector.svelte","../../src/lib/services/contents/fields/custom/helpers.js","../../src/lib/services/contents/draft/validate/custom-fields.js","../../src/lib/services/contents/fields/date-time/validate.js","../../src/lib/services/contents/draft/validate/messages.js","../../src/lib/services/contents/fields/number/validate.js","../../src/lib/services/contents/fields/string/validate.js","../../src/lib/services/contents/draft/validate/scalar.js","../../src/lib/services/contents/fields/code/validate.js","../../src/lib/services/contents/draft/validate/validity.js","../../src/lib/services/contents/fields/key-value/validate.js","../../src/lib/services/contents/fields/list/validate.js","../../src/lib/services/contents/draft/validate/prepare.js","../../src/lib/services/contents/draft/validate/required.js","../../src/lib/services/contents/draft/validate/slugs.js","../../src/lib/services/contents/entry/per-entry.js","../../src/lib/services/contents/draft/validate/unique.js","../../src/lib/services/contents/fields/date-time/auto-now.js","../../src/lib/services/contents/draft/save/sort-order.js","../../src/lib/services/contents/fields/number/auto-increment.js","../../src/lib/services/contents/draft/validate/fields.js","../../src/lib/services/contents/entry/changes.js","../../src/lib/services/contents/entry/cascade.js","../../src/lib/services/assets/data/cascade.js","../../src/lib/services/assets/data/delete.js","../../src/lib/services/assets/data/subfolder.js","../../src/lib/components/assets/list/create-subfolder-dialog.svelte","../../src/lib/components/assets/list/new-folder-button.svelte","../../src/lib/services/contents/collection/view/table.js","../../src/lib/services/contents/collection/view/settings.js","../../src/lib/components/common/page-toolbar/view-switcher.svelte","../../src/lib/services/assets/browser/pending-uploads.js","../../src/lib/services/assets/external/prefix.js","../../src/lib/services/contents/fields/file/duplicates.svelte.js","../../src/lib/services/contents/fields/file/helpers.js","../../src/lib/services/contents/fields/file/process.js","../../src/lib/services/contents/fields/file/listing.svelte.js","../../src/lib/components/assets/browser/select-assets-dialog.svelte","../../src/lib/components/assets/shared/conflict-resolution-dialog.svelte","../../src/lib/services/contents/fields/file/resources.js","../../src/lib/services/contents/fields/custom/files.js","../../src/lib/components/contents/details/fields/custom/asset-picker.svelte","../../src/lib/services/api/field-state.js","../../src/lib/services/api/react-dom.js","../../src/lib/services/api/react-dom.svelte.js","../../src/lib/services/contents/draft/create/proxy.svelte.js","../../src/lib/services/contents/fields/hidden/defaults.js","../../src/lib/services/contents/fields/uuid/helpers.js","../../src/lib/services/contents/draft/create/unique-values.js","../../src/lib/services/contents/fields/boolean/defaults.js","../../src/lib/services/contents/fields/code/defaults.js","../../src/lib/services/contents/fields/date-time/defaults.js","../../src/lib/services/contents/fields/file/defaults.js","../../src/lib/services/contents/fields/key-value/defaults.js","../../src/lib/services/contents/fields/number/defaults.js","../../src/lib/services/contents/fields/rich-text/defaults.js","../../src/lib/services/contents/fields/select/defaults.js","../../src/lib/services/contents/fields/list/defaults.js","../../src/lib/services/contents/fields/defaults.js","../../src/lib/services/contents/fields/object/defaults.js","../../src/lib/services/contents/draft/defaults.js","../../src/lib/services/contents/fields/key-value/duplicate-keys.js","../../src/lib/services/contents/draft/update/locale.js","../../src/lib/services/contents/draft/update/index.js","../../src/lib/services/api/react.js","../../src/lib/services/contents/fields/custom/editor.js","../../src/lib/components/contents/details/fields/custom/custom-editor.svelte","../../src/lib/services/contents/fields/custom/preview.js","../../src/lib/components/contents/details/fields/custom/custom-preview.svelte","../../src/lib/components/contents/details/fields/date-time/date-time-preview.svelte","../../src/lib/components/contents/details/fields/date-time/date-time-editor.svelte","../../src/lib/components/assets/shared/file-extension-change-dialog.svelte","../../src/lib/components/common/editable-text.svelte","../../src/lib/services/utils/drag-sorting.js","../../src/lib/components/common/move-to-dialog.svelte","../../src/lib/components/common/reorder-menu-items.svelte","../../src/lib/components/common/reorder-controls.svelte","../../src/lib/services/contents/fields/file/preview.js","../../src/lib/components/contents/details/fields/file/file-editor-item.svelte","../../src/lib/services/contents/editor/locale.js","../../src/lib/services/contents/fields/file/credit.js","../../src/lib/components/contents/details/fields/file/photo-credit-dialog.svelte","../../src/lib/components/contents/details/fields/file/upload-button.svelte","../../src/lib/services/contents/draft/update/list.js","../../src/lib/services/utils/drag-sorting.svelte.js","../../src/lib/components/contents/details/fields/file/file-editor.svelte","../../src/lib/components/contents/details/fields/file/file-preview-item.svelte","../../src/lib/components/contents/details/fields/file/file-preview.svelte","../../src/lib/components/contents/details/editor/validation-error.svelte","../../src/lib/components/contents/details/fields/object/add-item-button.svelte","../../src/lib/services/contents/fields/key-value/helpers.js","../../src/lib/services/utils/keyed-rows.svelte.js","../../src/lib/components/contents/details/fields/key-value/key-value-editor.svelte","../../src/lib/components/contents/details/fields/key-value/key-value-preview.svelte","../../src/lib/components/contents/details/fields/list/list-item-menu.svelte","../../src/lib/components/common/expand-icon.svelte","../../src/lib/components/contents/details/fields/list/list-toolbar.svelte","../../src/lib/services/utils/error.js","../../src/lib/components/common/error-boundary.svelte","../../src/lib/services/contents/draft/update/copy.js","../../src/lib/components/contents/details/editor/copy-menu-items.svelte","../../src/lib/components/contents/details/editor/field-editor-group.svelte","../../src/lib/services/contents/editor/reset.js","../../src/lib/components/contents/details/editor/reset-menu-items.svelte","../../src/lib/components/contents/details/editor/translate-button.svelte","../../src/lib/services/contents/draft/update/reset.js","../../src/lib/services/contents/draft/update/revert.js","../../src/lib/services/contents/editor/field-flags.js","../../src/lib/services/contents/editor/reset-menu.svelte.js","../../src/lib/components/contents/details/editor/field-editor.svelte","../../src/lib/components/contents/details/fields/object/object-body.svelte","../../src/lib/components/contents/details/fields/object/object-header.svelte","../../src/lib/components/contents/details/fields/object/removed-item-notice.svelte","../../src/lib/services/contents/editor/fields.js","../../src/lib/services/contents/editor/scroll.js","../../src/lib/services/assets/copy.js","../../src/lib/services/contents/fields/list/clipboard/walk.js","../../src/lib/services/contents/fields/list/clipboard/data.js","../../src/lib/services/contents/fields/list/clipboard/conform.js","../../src/lib/services/contents/fields/list/clipboard/paste.js","../../src/lib/services/contents/fields/list/clipboard/store.js","../../src/lib/services/contents/fields/list/items.js","../../src/lib/services/contents/fields/list/mutations.js","../../src/lib/services/contents/fields/list/paste-toast.js","../../src/lib/services/contents/fields/list/removed-items.js","../../src/lib/services/contents/fields/list/actions.svelte.js","../../src/lib/services/contents/fields/list/removed-items-state.svelte.js","../../src/lib/services/contents/fields/object/thumbnail.js","../../src/lib/components/contents/details/fields/list/list-editor-complex.svelte","../../src/lib/components/contents/details/fields/list/list-editor-simple.svelte","../../src/lib/components/contents/details/fields/list/list-editor.svelte","../../src/lib/components/contents/details/preview/field-preview.svelte","../../src/lib/components/contents/details/fields/object/subfield-previews.svelte","../../src/lib/components/contents/details/fields/list/list-preview-complex.svelte","../../src/lib/components/contents/details/fields/list/list-preview-simple.svelte","../../src/lib/components/contents/details/fields/list/list-preview.svelte","../../src/lib/components/common/leaflet-map.svelte","../../src/lib/services/contents/fields/map/services.js","../../src/lib/components/contents/details/fields/map/map-editor.svelte","../../src/lib/components/contents/details/fields/map/map-preview.svelte","../../src/lib/components/contents/details/fields/number/number-editor.svelte","../../src/lib/components/contents/details/fields/number/number-preview.svelte","../../src/lib/services/contents/draft/update/object.js","../../src/lib/components/contents/details/fields/object/object-editor.svelte","../../src/lib/components/contents/details/fields/object/object-preview.svelte","../../src/lib/components/contents/details/disabled-locale-state.svelte","../../src/lib/components/contents/details/editor/parent-folder-tree-item.svelte","../../src/lib/services/contents/collection/nested/tree.js","../../src/lib/components/contents/details/editor/path-editor.svelte","../../src/lib/components/contents/details/editor/entry-editor.svelte","../../src/lib/services/contents/draft/backup.js","../../src/lib/services/contents/draft/create/normalize.js","../../src/lib/services/contents/draft/create/index.js","../../src/lib/services/contents/editor/slug.js","../../src/lib/components/contents/details/editor/slug-editor.svelte","../../src/lib/components/contents/details/editor/validation-errors-toast.svelte","../../src/lib/services/contents/draft/validate/path.js","../../src/lib/services/contents/draft/validate/index.js","../../src/lib/services/contents/draft/validate/reveal.js","../../src/lib/services/contents/editor/settings.js","../../src/lib/components/contents/details/locale-switcher.svelte","../../src/lib/services/contents/draft/update/compute.js","../../src/lib/services/contents/draft/update/compute-tracking.svelte.js","../../src/lib/services/contents/draft/editor.svelte.js","../../src/lib/services/contents/collection/entries/count.js","../../src/lib/services/contents/draft/save/conflict.js","../../src/lib/services/contents/draft/save/save-time.js","../../src/lib/services/workflow/board.js","../../src/lib/services/contents/fields/relation/quick-add.js","../../src/lib/components/contents/details/fields/relation/quick-add-dialog.svelte","../../src/lib/components/contents/details/fields/select/select-multiple.svelte","../../src/lib/components/contents/details/fields/select/select-single.svelte","../../src/lib/components/contents/details/fields/select/select-editor.svelte","../../src/lib/services/contents/editor/bulk-edit-row.js","../../src/lib/services/contents/editor/entry-values.js","../../src/lib/components/contents/details/fields/relation/relation-editor.svelte","../../src/lib/services/contents/fields/relation/helpers/preview.js","../../src/lib/components/contents/details/fields/relation/relation-preview.svelte","../../src/lib/services/config/parser/utils/validator.js","../../src/lib/services/config/parser/editor-components.js","../../src/lib/services/contents/fields/rich-text/components/summary.js","../../src/lib/services/contents/fields/rich-text/components/thumbnail.js","../../src/lib/services/contents/fields/rich-text/components/validate.js","../../src/lib/services/contents/fields/rich-text/components/values.js","../../src/lib/components/contents/details/fields/rich-text/editor-component.svelte","../../src/lib/services/contents/fields/rich-text/previews/syntax.js","../../src/lib/services/contents/fields/rich-text/previews/components.js","../../src/lib/services/contents/fields/rich-text/components/inline-preview.js","../../src/lib/components/contents/details/fields/rich-text/inline-pattern-component.svelte","../../src/lib/components/contents/details/fields/rich-text/custom-node.js","../../src/lib/services/contents/fields/rich-text/components/transformers.js","../../src/lib/components/contents/details/fields/rich-text/custom-node-features.js","../../src/lib/services/contents/fields/rich-text/image-uploads.js","../../src/lib/services/contents/fields/rich-text/images.js","../../src/lib/components/contents/details/fields/rich-text/rich-text-editor.svelte","../../src/lib/services/contents/fields/rich-text/previews/marked.js","../../src/lib/services/contents/fields/rich-text/previews/blocks.js","../../src/lib/services/contents/fields/rich-text/previews/script-urls.js","../../src/lib/components/contents/details/fields/rich-text/rich-text-preview.svelte","../../src/lib/components/contents/details/fields/select/select-preview.svelte","../../src/lib/components/contents/details/fields/string/character-counter.svelte","../../src/lib/services/contents/editor/extra-hint.svelte.js","../../src/lib/services/contents/fields/string/helpers.js","../../src/lib/components/contents/details/fields/string/string-editor.svelte","../../src/lib/services/utils/media/video/youtube.js","../../src/lib/components/contents/details/fields/string/youtube-embed.svelte","../../src/lib/services/contents/fields/string/preview.js","../../src/lib/components/contents/details/fields/string/string-preview.svelte","../../src/lib/components/contents/details/fields/text/text-editor.svelte","../../src/lib/components/contents/details/fields/text/text-preview.svelte","../../src/lib/components/contents/details/fields/uuid/uuid-editor.svelte","../../src/lib/components/contents/details/fields/uuid/uuid-preview.svelte","../../src/lib/components/contents/details/fields/index.js","../../src/lib/services/api/field-types.svelte.js","../../src/lib/services/api/field-types.js","../../src/lib/services/api/validate.js","../../src/lib/services/api/methods/get-field-type.js","../../src/lib/services/user/sign-in-options.js","../../src/lib/components/entrance/sign-in.svelte","../../src/lib/services/app/browser-support.js","../../src/lib/components/entrance/entrance-page.svelte","../../src/lib/components/global/commit-message-dialog.svelte","../../src/lib/components/global/infobars/backend-status-indicator.svelte","../../src/lib/components/global/infobars/update-notification.svelte","../../src/lib/locales/en-US.yaml?omit=additions","../../src/lib/services/app/i18n.js","../../src/lib/components/global/locale-load-error-toast.svelte","../../src/lib/components/admin/panels/config-panel.svelte","../../src/lib/components/admin/sidebar.svelte","../../src/lib/services/app/ui-settings.js","../../src/lib/components/common/page-container.svelte","../../src/lib/components/global/not-found.svelte","../../src/lib/components/admin/admin-page.svelte","../../src/lib/components/assets/list/text-preview.svelte","../../src/lib/components/assets/list/asset-preview-content.svelte","../../src/lib/components/common/cascade-delete-note.svelte","../../src/lib/components/assets/list/delete-assets-button.svelte","../../src/lib/services/assets/view/overlay-navigation.js","../../src/lib/components/assets/list/details-overlay.svelte","../../src/lib/components/assets/list/download-assets-button.svelte","../../src/lib/components/assets/list/copy-menu.svelte","../../src/lib/services/utils/clipboard.js","../../src/lib/components/assets/list/external/copy-assets-button.svelte","../../src/lib/components/assets/list/edit-options-menu.svelte","../../src/lib/components/assets/list/external/edit-options-button.svelte","../../src/lib/services/utils/media/video/index.js","../../src/lib/components/assets/list/file-info-sections.svelte","../../src/lib/components/assets/list/info-panel-layout.svelte","../../src/lib/components/assets/list/used-entries.svelte","../../src/lib/components/assets/list/external/info-panel.svelte","../../src/lib/components/assets/list/external/details-overlay.svelte","../../src/lib/components/common/list-container.svelte","../../src/lib/components/common/listing-grid.svelte","../../src/lib/components/assets/list/asset-list-container.svelte","../../src/lib/components/assets/list/asset-list-item.svelte","../../src/lib/components/assets/list/external/unavailable-badge.svelte","../../src/lib/components/assets/list/external/asset-list-item.svelte","../../src/lib/components/assets/list/subfolder-list-item.svelte","../../src/lib/components/assets/list/external/subfolder-list-item.svelte","../../src/lib/components/assets/list/upload-button.svelte","../../src/lib/components/assets/list/external/upload-assets-button.svelte","../../src/lib/components/assets/list/external/asset-list.svelte","../../src/lib/components/assets/list/external/delete-folder-dialog.svelte","../../src/lib/components/assets/list/folder-info-panel.svelte","../../src/lib/components/assets/list/external/folder-info-panel.svelte","../../src/lib/components/assets/list/external/new-folder-dialog.svelte","../../src/lib/components/assets/list/external/new-folder-button.svelte","../../src/lib/components/assets/list/preview-asset-button.svelte","../../src/lib/components/assets/list/primary-toolbar.svelte","../../src/lib/components/assets/list/external/primary-toolbar.svelte","../../src/lib/components/assets/list/rename-dialog.svelte","../../src/lib/services/assets/used-entries.svelte.js","../../src/lib/components/assets/list/external/rename-dialog.svelte","../../src/lib/components/assets/list/external/rename-folder-dialog.svelte","../../src/lib/components/assets/list/secondary-sidebar.svelte","../../src/lib/components/common/page-toolbar/condition-radio-items.svelte","../../src/lib/components/common/page-toolbar/filter-menu.svelte","../../src/lib/components/common/page-toolbar/group-menu.svelte","../../src/lib/components/common/page-toolbar/item-selector.svelte","../../src/lib/components/common/page-toolbar/sort-menu.svelte","../../src/lib/components/assets/list/secondary-toolbar.svelte","../../src/lib/components/assets/list/external/main-area.svelte","../../src/lib/services/search/index.js","../../src/lib/services/search/navigation.js","../../src/lib/services/assets/navigation.js","../../src/lib/components/assets/list/internal/asset-list-item.svelte","../../src/lib/components/assets/list/internal/subfolder-list-item.svelte","../../src/lib/components/assets/list/internal/upload-assets-button.svelte","../../src/lib/components/assets/list/internal/asset-list.svelte","../../src/lib/components/assets/list/internal/delete-folder-dialog.svelte","../../src/lib/services/assets/details.js","../../src/lib/components/assets/list/internal/copy-assets-button.svelte","../../src/lib/components/assets/list/internal/delete-assets-button.svelte","../../src/lib/components/common/view-in-repository-item.svelte","../../src/lib/services/assets/details-state.svelte.js","../../src/lib/components/assets/list/internal/edit-options-button.svelte","../../src/lib/components/assets/list/internal/info-panel.svelte","../../src/lib/components/assets/list/internal/details-overlay.svelte","../../src/lib/services/assets/data/create.js","../../src/lib/components/assets/list/internal/edit-asset-dialog.svelte","../../src/lib/components/assets/list/internal/folder-info-panel.svelte","../../src/lib/services/assets/view/folder-list.js","../../src/lib/services/assets/data/move-destinations.js","../../src/lib/components/assets/list/internal/move-destination-tree-item.svelte","../../src/lib/services/assets/data/move-to-folder.js","../../src/lib/services/assets/data/transfer.js","../../src/lib/services/assets/external/destinations.js","../../src/lib/components/assets/list/internal/move-dialog.svelte","../../src/lib/components/assets/list/internal/new-folder-dialog.svelte","../../src/lib/components/assets/list/internal/new-folder-button.svelte","../../src/lib/components/assets/list/internal/primary-toolbar.svelte","../../src/lib/components/assets/list/internal/rename-dialog.svelte","../../src/lib/components/assets/list/internal/rename-folder-dialog.svelte","../../src/lib/services/search/input.js","../../src/lib/components/global/toolbar/items/quick-search-bar.svelte","../../src/lib/components/assets/list/primary-sidebar.svelte","../../src/lib/components/search/asset-result-item.svelte","../../src/lib/components/contents/shared/entry-thumbnail.svelte","../../src/lib/components/search/entry-result-item.svelte","../../src/lib/components/search/search-result-list.svelte","../../src/lib/services/search/assets.js","../../src/lib/services/search/entries.js","../../src/lib/components/search/search-results.svelte","../../src/lib/components/search/search-main-area.svelte","../../src/lib/services/assets/view/sort-keys.js","../../src/lib/components/assets/assets-page.svelte","../../src/lib/components/assets/browser/cloudinary-iframe.svelte","../../src/lib/components/assets/shared/asset-updates-toast.svelte","../../src/lib/components/assets/shared/upload-assets-confirm-dialog.svelte","../../src/lib/components/assets/shared/upload-assets-dialog.svelte","../../src/lib/components/contents/details/backup-feedback.svelte","../../src/lib/services/contents/editor/preview-frame.js","../../src/lib/components/contents/details/preview/entry-preview-iframe.svelte","../../src/lib/services/contents/editor/preview-styles.js","../../src/lib/services/contents/editor/preview-templates.js","../../src/lib/components/contents/details/preview/entry-preview.svelte","../../src/lib/services/contents/editor/scroll-sync.js","../../src/lib/components/contents/details/pane-body.svelte","../../src/lib/components/contents/details/editor/reset-dialog.svelte","../../src/lib/components/contents/details/preview-button.svelte","../../src/lib/services/deployments/link.js","../../src/lib/components/contents/details/preview-link-button.svelte","../../src/lib/services/contents/editor/panes.js","../../src/lib/services/deployments/poll.js","../../src/lib/components/contents/details/pane-header.svelte","../../src/lib/components/contents/details/pending-edit-infobar.svelte","../../src/lib/services/contents/draft/reload.js","../../src/lib/components/contents/details/remote-change-infobar.svelte","../../src/lib/services/contents/entry/relations/index.js","../../src/lib/services/contents/entry/relations/backlinks.js","../../src/lib/components/contents/details/sidebar/panels/backlinks-panel.svelte","../../src/lib/services/contents/entry/history.js","../../src/lib/components/contents/details/sidebar/panels/history-panel.svelte","../../src/lib/components/contents/details/sidebar/panels/panel-section.svelte","../../src/lib/services/contents/editor/slug-form.js","../../src/lib/components/contents/details/sidebar/panels/slug-update-form.svelte","../../src/lib/components/contents/details/sidebar/panels/slug-panel.svelte","../../src/lib/services/contents/editor/sidebar.js","../../src/lib/components/contents/details/sidebar/panels/validation-panel.svelte","../../src/lib/components/contents/details/sidebar/sidebar-panel.svelte","../../src/lib/components/contents/details/sidebar/sidebar-sheet.svelte","../../src/lib/components/contents/details/sidebar/sidebar.svelte","../../src/lib/components/contents/details/editor/view-menu-items.svelte","../../src/lib/services/contents/entry/relations/cascade/index.js","../../src/lib/services/contents/entry/relations/cascade/delete.js","../../src/lib/components/contents/details/delete-entry-dialog.svelte","../../src/lib/services/contents/collection/entries/save.js","../../src/lib/services/contents/collection/entries/reorder/index.js","../../src/lib/services/contents/collection/data/delete.js","../../src/lib/services/contents/collection/nested/move.js","../../src/lib/services/contents/entry/relations/cascade/update.js","../../src/lib/services/workflow/verify.js","../../src/lib/services/workflow/save.js","../../src/lib/services/workflow/delete.js","../../src/lib/services/workflow/dialogs.js","../../src/lib/components/contents/details/entry-removal.svelte","../../src/lib/components/contents/details/save-conflict-dialog.svelte","../../src/lib/components/common/status-pill.svelte","../../src/lib/components/workflow/status-badge.svelte","../../src/lib/services/workflow/editor.js","../../src/lib/services/workflow/validate.js","../../src/lib/components/workflow/entry-status-menu.svelte","../../src/lib/components/workflow/external-review-button.svelte","../../src/lib/components/workflow/publish-entry-button.svelte","../../src/lib/services/contents/collection/entries/bulk-edit/config.js","../../src/lib/services/contents/collection/view/conditions.js","../../src/lib/services/contents/collection/view/filter.js","../../src/lib/services/contents/collection/view/group.js","../../src/lib/services/contents/collection/view/index.js","../../src/lib/services/contents/draft/create/duplicate-assets.js","../../src/lib/services/contents/draft/create/duplicate.js","../../src/lib/services/workflow/conflict.js","../../src/lib/services/contents/draft/save/index.js","../../src/lib/services/contents/editor/toolbar.js","../../src/lib/services/contents/editor/save.js","../../src/lib/components/contents/details/toolbar.svelte","../../src/lib/components/contents/details/content-details-overlay.svelte","../../src/lib/components/contents/list/bulk-edit-cell.svelte","../../src/lib/services/contents/collection/entries/bulk-edit/index.js","../../src/lib/services/contents/collection/entries/bulk-edit/session.js","../../src/lib/components/contents/list/entry-bulk-edit-list.svelte","../../src/lib/components/contents/list/entry-list-item-cells.svelte","../../src/lib/components/contents/list/entry-list-item.svelte","../../src/lib/components/contents/list/entry-reorder-list-item.svelte","../../src/lib/components/contents/list/entry-reorder-list.svelte","../../src/lib/components/contents/list/entry-table-head.svelte","../../src/lib/components/contents/toolbar/create-entry-button.svelte","../../src/lib/components/contents/list/entry-list.svelte","../../src/lib/components/contents/list/file-list.svelte","../../src/lib/components/contents/list/nested-tree-item.svelte","../../src/lib/components/contents/list/collection-tree-item.svelte","../../src/lib/components/contents/list/singleton-tree-item.svelte","../../src/lib/services/deployments/publish.js","../../src/lib/components/global/toolbar/items/publish-button.svelte","../../src/lib/components/contents/list/primary-sidebar.svelte","../../src/lib/components/contents/list/list-mode-controls.svelte","../../src/lib/components/contents/list/bulk-edit-controls.svelte","../../src/lib/components/contents/list/reorder-controls.svelte","../../src/lib/components/contents/shared/delete-entries-dialog.svelte","../../src/lib/components/contents/list/primary-toolbar.svelte","../../src/lib/components/contents/list/secondary-sidebar.svelte","../../src/lib/components/contents/list/secondary-toolbar.svelte","../../src/lib/services/contents/navigation.js","../../src/lib/components/contents/contents-page.svelte","../../src/lib/components/settings/controls/translator-selector.svelte","../../src/lib/components/contents/details/editor/translator-api-key-dialog.svelte","../../src/lib/components/contents/shared/content-updates-toast.svelte","../../src/lib/components/contents/shared/entry-parse-errors-toast.svelte","../../src/lib/services/app/custom-pages.js","../../src/lib/components/custom-pages/custom-page.svelte","../../src/lib/services/app/cache.js","../../src/lib/services/app/onboarding.js","../../src/lib/components/global/demo-welcome-dialog.svelte","../../src/lib/services/app/dev-server.js","../../src/lib/components/global/infobars/live-reload-infobar.svelte","../../src/lib/components/global/infobars/mobile-promo-infobar.svelte","../../src/lib/components/global/infobars/new-language-infobar.svelte","../../src/lib/services/backends/fs/git/messages.js","../../src/lib/components/global/local-git-notice-toast.svelte","../../src/lib/components/global/not-found-page.svelte","../../src/lib/services/app/toolbar-pages.js","../../src/lib/components/global/toolbar/items/page-switcher.svelte","../../src/lib/components/global/toolbar/bottom-navigation.svelte","../../src/lib/services/app/install.js","../../src/lib/components/global/toolbar/items/app-install-menu-item.svelte","../../src/lib/components/help/shortcuts-dialog.svelte","../../src/lib/components/help/shortcuts-menu-item.svelte","../../src/lib/components/settings/controls/pref-switch.svelte","../../src/lib/components/settings/panels/accessibility-panel.svelte","../../src/lib/components/settings/controls/api-key-input.svelte","../../src/lib/components/settings/controls/api-key-section.svelte","../../src/lib/components/settings/panels/ai-panel.svelte","../../src/lib/components/settings/panels/appearance-panel.svelte","../../src/lib/components/settings/panels/contents-panel.svelte","../../src/lib/components/settings/panels/data-panel.svelte","../../src/lib/components/settings/panels/developer-panel.svelte","../../src/lib/components/settings/panels/i18n-panel.svelte","../../src/lib/components/settings/panels/language-panel.svelte","../../src/lib/components/settings/panels/media-panel.svelte","../../src/lib/components/settings/index.js","../../src/lib/components/settings/panel-container.svelte","../../src/lib/components/settings/settings-dialog.svelte","../../src/lib/components/global/toolbar/items/account-menu.svelte","../../src/lib/components/global/toolbar/items/account-button.svelte","../../src/lib/components/global/toolbar/items/create-button.svelte","../../src/lib/components/help/release-notes-menu-item.svelte","../../src/lib/components/global/toolbar/items/help-menu.svelte","../../src/lib/components/global/toolbar/items/help-button.svelte","../../src/lib/components/global/toolbar/items/notifications-button.svelte","../../src/lib/components/global/toolbar/items/site-logo.svelte","../../src/lib/components/global/toolbar/global-toolbar.svelte","../../src/lib/components/menu/menu-page.svelte","../../src/lib/components/menu/mobile-sign-in-dialog.svelte","../../src/lib/components/search/search-page.svelte","../../src/lib/components/settings/settings-page.svelte","../../src/lib/components/workflow/deploy-status-badge.svelte","../../src/lib/components/workflow/workflow-entry-card.svelte","../../src/lib/components/workflow/workflow-page.svelte","../../src/lib/components/global/main-router.svelte","../../src/lib/components/workflow/fork-permission-dialog.svelte","../../src/lib/components/workflow/open-authoring-indicator.svelte","../../node_modules/.pnpm/@fastify+deepmerge@3.2.4/node_modules/@fastify/deepmerge/index.js","../../src/lib/services/config/folders/entries.js","../../src/lib/services/config/loader.js","../../src/lib/services/config/parser/backend.js","../../src/lib/services/config/parser/collections/format.js","../../src/lib/services/config/parser/utils/fields.js","../../src/lib/services/config/parser/utils/references.js","../../src/lib/services/config/parser/collections/preview.js","../../src/lib/services/config/parser/collections/templates.js","../../src/lib/services/config/parser/fields/code.js","../../src/lib/services/config/parser/fields/compute.js","../../src/lib/services/config/parser/fields/datetime.js","../../src/lib/services/common/template/normalize.js","../../src/lib/services/config/templates.js","../../src/lib/services/config/parser/media.js","../../src/lib/services/config/parser/media-libraries.js","../../src/lib/services/config/parser/utils/defaults.js","../../src/lib/services/config/parser/fields/file.js","../../src/lib/services/config/parser/fields/hidden.js","../../src/lib/services/config/parser/fields/common.js","../../src/lib/services/config/parser/fields/custom.js","../../src/lib/services/config/parser/fields/registry.js","../../src/lib/services/config/parser/fields/list.js","../../src/lib/services/config/parser/fields/number.js","../../src/lib/services/config/parser/fields/object.js","../../src/lib/services/config/parser/collections/array-file.js","../../src/lib/services/config/parser/fields/relation.js","../../src/lib/services/config/parser/fields/rich-text.js","../../src/lib/services/config/parser/fields/index.js","../../src/lib/services/config/parser/fields/select.js","../../src/lib/services/config/parser/i18n.js","../../src/lib/services/config/parser/collection-files/index.js","../../src/lib/services/config/parser/collections/bulk-edit.js","../../src/lib/services/config/parser/collections/filter.js","../../src/lib/services/config/parser/collections/identifier.js","../../src/lib/services/config/parser/collections/slug.js","../../src/lib/services/config/parser/collections/views.js","../../src/lib/services/config/parser/publish-mode.js","../../src/lib/services/config/parser/collections/index.js","../../src/lib/services/config/parser/slug.js","../../src/lib/services/config/parser/index.js","../../src/lib/services/config/parser/root-dir.js","../../src/lib/services/config/schema/pointer.js","../../src/lib/services/config/schema/transform.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.6/node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.6/node_modules/@cfworker/json-schema/dist/esm/pointer.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.6/node_modules/@cfworker/json-schema/dist/esm/dereference.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.6/node_modules/@cfworker/json-schema/dist/esm/format.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.6/node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.6/node_modules/@cfworker/json-schema/dist/esm/validate.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.6/node_modules/@cfworker/json-schema/dist/esm/validator.js","../../src/lib/services/config/schema/validator.js","../../src/lib/services/config/schema/custom-fields.js","../../src/lib/services/config/schema/errors.js","../../src/lib/services/config/schema/loader.js","../../src/lib/services/config/schema/index.js","../../src/lib/services/config/init.js","../../src/lib/components/app.svelte","../../src/lib/services/api/methods/init.js","../../src/lib/services/api/methods/register-custom-format.js","../../src/lib/services/api/methods/register-custom-page.js","../../src/lib/services/api/methods/register-editor-component.js","../../src/lib/services/api/methods/register-event-listener.js","../../src/lib/services/api/methods/register-field-type.js","../../src/lib/services/api/methods/register-preview-style.js","../../src/lib/services/api/methods/register-preview-template.js","../../src/lib/services/api/methods/register-string-transformation.js","../../src/lib/services/api/methods/render-rich-text.js","../../src/lib/services/api/index.js","../../node_modules/.pnpm/htm@3.1.1/node_modules/htm/dist/htm.module.js","../../src/lib/services/api/htm.js","../../src/lib/main.js"],"sourcesContent":["/**\n * @license React\n * react.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n  REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n  REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n  REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n  REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n  REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n  REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n  REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n  REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n  REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n  REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n  REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n  REACT_VIEW_TRANSITION_TYPE = Symbol.for(\"react.view_transition\"),\n  MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nfunction getIteratorFn(maybeIterable) {\n  if (null === maybeIterable || \"object\" !== typeof maybeIterable) return null;\n  maybeIterable =\n    (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) ||\n    maybeIterable[\"@@iterator\"];\n  return \"function\" === typeof maybeIterable ? maybeIterable : null;\n}\nvar ReactNoopUpdateQueue = {\n    isMounted: function () {\n      return !1;\n    },\n    enqueueForceUpdate: function () {},\n    enqueueReplaceState: function () {},\n    enqueueSetState: function () {}\n  },\n  assign = Object.assign,\n  emptyObject = {};\nfunction Component(props, context, updater) {\n  this.props = props;\n  this.context = context;\n  this.refs = emptyObject;\n  this.updater = updater || ReactNoopUpdateQueue;\n}\nComponent.prototype.isReactComponent = {};\nComponent.prototype.setState = function (partialState, callback) {\n  if (\n    \"object\" !== typeof partialState &&\n    \"function\" !== typeof partialState &&\n    null != partialState\n  )\n    throw Error(\n      \"takes an object of state variables to update or a function which returns an object of state variables.\"\n    );\n  this.updater.enqueueSetState(this, partialState, callback, \"setState\");\n};\nComponent.prototype.forceUpdate = function (callback) {\n  this.updater.enqueueForceUpdate(this, callback, \"forceUpdate\");\n};\nfunction ComponentDummy() {}\nComponentDummy.prototype = Component.prototype;\nfunction PureComponent(props, context, updater) {\n  this.props = props;\n  this.context = context;\n  this.refs = emptyObject;\n  this.updater = updater || ReactNoopUpdateQueue;\n}\nvar pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());\npureComponentPrototype.constructor = PureComponent;\nassign(pureComponentPrototype, Component.prototype);\npureComponentPrototype.isPureReactComponent = !0;\nvar isArrayImpl = Array.isArray;\nfunction noop() {}\nvar ReactSharedInternals = { H: null, A: null, T: null, S: null },\n  hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction ReactElement(type, key, props) {\n  var refProp = props.ref;\n  return {\n    $$typeof: REACT_ELEMENT_TYPE,\n    type: type,\n    key: key,\n    ref: void 0 !== refProp ? refProp : null,\n    props: props\n  };\n}\nfunction cloneAndReplaceKey(oldElement, newKey) {\n  return ReactElement(oldElement.type, newKey, oldElement.props);\n}\nfunction isValidElement(object) {\n  return (\n    \"object\" === typeof object &&\n    null !== object &&\n    object.$$typeof === REACT_ELEMENT_TYPE\n  );\n}\nfunction escape(key) {\n  var escaperLookup = { \"=\": \"=0\", \":\": \"=2\" };\n  return (\n    \"$\" +\n    key.replace(/[=:]/g, function (match) {\n      return escaperLookup[match];\n    })\n  );\n}\nvar userProvidedKeyEscapeRegex = /\\/+/g;\nfunction getElementKey(element, index) {\n  return \"object\" === typeof element && null !== element && null != element.key\n    ? escape(\"\" + element.key)\n    : index.toString(36);\n}\nfunction resolveThenable(thenable) {\n  switch (thenable.status) {\n    case \"fulfilled\":\n      return thenable.value;\n    case \"rejected\":\n      throw thenable.reason;\n    default:\n      switch (\n        (\"string\" === typeof thenable.status\n          ? thenable.then(noop, noop)\n          : ((thenable.status = \"pending\"),\n            thenable.then(\n              function (fulfilledValue) {\n                \"pending\" === thenable.status &&\n                  ((thenable.status = \"fulfilled\"),\n                  (thenable.value = fulfilledValue));\n              },\n              function (error) {\n                \"pending\" === thenable.status &&\n                  ((thenable.status = \"rejected\"), (thenable.reason = error));\n              }\n            )),\n        thenable.status)\n      ) {\n        case \"fulfilled\":\n          return thenable.value;\n        case \"rejected\":\n          throw thenable.reason;\n      }\n  }\n  throw thenable;\n}\nfunction mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {\n  var type = typeof children;\n  if (\"undefined\" === type || \"boolean\" === type) children = null;\n  var invokeCallback = !1;\n  if (null === children) invokeCallback = !0;\n  else\n    switch (type) {\n      case \"bigint\":\n      case \"string\":\n      case \"number\":\n        invokeCallback = !0;\n        break;\n      case \"object\":\n        switch (children.$$typeof) {\n          case REACT_ELEMENT_TYPE:\n          case REACT_PORTAL_TYPE:\n            invokeCallback = !0;\n            break;\n          case REACT_LAZY_TYPE:\n            return (\n              (invokeCallback = children._init),\n              mapIntoArray(\n                invokeCallback(children._payload),\n                array,\n                escapedPrefix,\n                nameSoFar,\n                callback\n              )\n            );\n        }\n    }\n  if (invokeCallback)\n    return (\n      (callback = callback(children)),\n      (invokeCallback =\n        \"\" === nameSoFar ? \".\" + getElementKey(children, 0) : nameSoFar),\n      isArrayImpl(callback)\n        ? ((escapedPrefix = \"\"),\n          null != invokeCallback &&\n            (escapedPrefix =\n              invokeCallback.replace(userProvidedKeyEscapeRegex, \"$&/\") + \"/\"),\n          mapIntoArray(callback, array, escapedPrefix, \"\", function (c) {\n            return c;\n          }))\n        : null != callback &&\n          (isValidElement(callback) &&\n            (callback = cloneAndReplaceKey(\n              callback,\n              escapedPrefix +\n                (null == callback.key ||\n                (children && children.key === callback.key)\n                  ? \"\"\n                  : (\"\" + callback.key).replace(\n                      userProvidedKeyEscapeRegex,\n                      \"$&/\"\n                    ) + \"/\") +\n                invokeCallback\n            )),\n          array.push(callback)),\n      1\n    );\n  invokeCallback = 0;\n  var nextNamePrefix = \"\" === nameSoFar ? \".\" : nameSoFar + \":\";\n  if (isArrayImpl(children))\n    for (var i = 0; i < children.length; i++)\n      (nameSoFar = children[i]),\n        (type = nextNamePrefix + getElementKey(nameSoFar, i)),\n        (invokeCallback += mapIntoArray(\n          nameSoFar,\n          array,\n          escapedPrefix,\n          type,\n          callback\n        ));\n  else if (((i = getIteratorFn(children)), \"function\" === typeof i))\n    for (\n      children = i.call(children), i = 0;\n      !(nameSoFar = children.next()).done;\n\n    )\n      (nameSoFar = nameSoFar.value),\n        (type = nextNamePrefix + getElementKey(nameSoFar, i++)),\n        (invokeCallback += mapIntoArray(\n          nameSoFar,\n          array,\n          escapedPrefix,\n          type,\n          callback\n        ));\n  else if (\"object\" === type) {\n    if (\"function\" === typeof children.then)\n      return mapIntoArray(\n        resolveThenable(children),\n        array,\n        escapedPrefix,\n        nameSoFar,\n        callback\n      );\n    array = String(children);\n    throw Error(\n      \"Objects are not valid as a React child (found: \" +\n        (\"[object Object]\" === array\n          ? \"object with keys {\" + Object.keys(children).join(\", \") + \"}\"\n          : array) +\n        \"). If you meant to render a collection of children, use an array instead.\"\n    );\n  }\n  return invokeCallback;\n}\nfunction mapChildren(children, func, context) {\n  if (null == children) return children;\n  var result = [],\n    count = 0;\n  mapIntoArray(children, result, \"\", \"\", function (child) {\n    return func.call(context, child, count++);\n  });\n  return result;\n}\nfunction lazyInitializer(payload) {\n  if (-1 === payload._status) {\n    var ctor = payload._result,\n      thenable = ctor();\n    thenable.then(\n      function (moduleObject) {\n        if (0 === payload._status || -1 === payload._status)\n          (payload._status = 1),\n            (payload._result = moduleObject),\n            void 0 === thenable.status &&\n              ((thenable.status = \"fulfilled\"),\n              (thenable.value = moduleObject));\n      },\n      function (error) {\n        if (0 === payload._status || -1 === payload._status)\n          (payload._status = 2),\n            (payload._result = error),\n            void 0 === thenable.status &&\n              ((thenable.status = \"rejected\"), (thenable.reason = error));\n      }\n    );\n    -1 === payload._status &&\n      ((payload._status = 0), (payload._result = thenable));\n  }\n  if (1 === payload._status) return payload._result.default;\n  throw payload._result;\n}\nvar reportGlobalError =\n  \"function\" === typeof reportError\n    ? reportError\n    : function (error) {\n        if (\n          \"object\" === typeof window &&\n          \"function\" === typeof window.ErrorEvent\n        ) {\n          var event = new window.ErrorEvent(\"error\", {\n            bubbles: !0,\n            cancelable: !0,\n            message:\n              \"object\" === typeof error &&\n              null !== error &&\n              \"string\" === typeof error.message\n                ? String(error.message)\n                : String(error),\n            error: error\n          });\n          if (!window.dispatchEvent(event)) return;\n        } else if (\n          \"object\" === typeof process &&\n          \"function\" === typeof process.emit\n        ) {\n          process.emit(\"uncaughtException\", error);\n          return;\n        }\n        console.error(error);\n      };\nfunction startTransition(scope) {\n  var prevTransition = ReactSharedInternals.T,\n    currentTransition = {};\n  currentTransition.types =\n    null !== prevTransition ? prevTransition.types : null;\n  ReactSharedInternals.T = currentTransition;\n  try {\n    var returnValue = scope(),\n      onStartTransitionFinish = ReactSharedInternals.S;\n    null !== onStartTransitionFinish &&\n      onStartTransitionFinish(currentTransition, returnValue);\n    \"object\" === typeof returnValue &&\n      null !== returnValue &&\n      \"function\" === typeof returnValue.then &&\n      returnValue.then(noop, reportGlobalError);\n  } catch (error) {\n    reportGlobalError(error);\n  } finally {\n    null !== prevTransition &&\n      null !== currentTransition.types &&\n      (prevTransition.types = currentTransition.types),\n      (ReactSharedInternals.T = prevTransition);\n  }\n}\nfunction addTransitionType(type) {\n  var transition = ReactSharedInternals.T;\n  if (null !== transition) {\n    var transitionTypes = transition.types;\n    null === transitionTypes\n      ? (transition.types = [type])\n      : -1 === transitionTypes.indexOf(type) && transitionTypes.push(type);\n  } else startTransition(addTransitionType.bind(null, type));\n}\nvar Children = {\n  map: mapChildren,\n  forEach: function (children, forEachFunc, forEachContext) {\n    mapChildren(\n      children,\n      function () {\n        forEachFunc.apply(this, arguments);\n      },\n      forEachContext\n    );\n  },\n  count: function (children) {\n    var n = 0;\n    mapChildren(children, function () {\n      n++;\n    });\n    return n;\n  },\n  toArray: function (children) {\n    return (\n      mapChildren(children, function (child) {\n        return child;\n      }) || []\n    );\n  },\n  only: function (children) {\n    if (!isValidElement(children))\n      throw Error(\n        \"React.Children.only expected to receive a single React element child.\"\n      );\n    return children;\n  }\n};\nexports.Activity = REACT_ACTIVITY_TYPE;\nexports.Children = Children;\nexports.Component = Component;\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.Profiler = REACT_PROFILER_TYPE;\nexports.PureComponent = PureComponent;\nexports.StrictMode = REACT_STRICT_MODE_TYPE;\nexports.Suspense = REACT_SUSPENSE_TYPE;\nexports.ViewTransition = REACT_VIEW_TRANSITION_TYPE;\nexports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE =\n  ReactSharedInternals;\nexports.__COMPILER_RUNTIME = {\n  __proto__: null,\n  c: function (size) {\n    return ReactSharedInternals.H.useMemoCache(size);\n  }\n};\nexports.addTransitionType = addTransitionType;\nexports.cache = function (fn) {\n  return function () {\n    return fn.apply(null, arguments);\n  };\n};\nexports.cacheSignal = function () {\n  return null;\n};\nexports.cloneElement = function (element, config, children) {\n  if (null === element || void 0 === element)\n    throw Error(\n      \"The argument must be a React element, but you passed \" + element + \".\"\n    );\n  var props = assign({}, element.props),\n    key = element.key;\n  if (null != config)\n    for (propName in (void 0 !== config.key && (key = \"\" + config.key), config))\n      !hasOwnProperty.call(config, propName) ||\n        \"key\" === propName ||\n        \"__self\" === propName ||\n        \"__source\" === propName ||\n        (\"ref\" === propName && void 0 === config.ref) ||\n        (props[propName] = config[propName]);\n  var propName = arguments.length - 2;\n  if (1 === propName) props.children = children;\n  else if (1 < propName) {\n    for (var childArray = Array(propName), i = 0; i < propName; i++)\n      childArray[i] = arguments[i + 2];\n    props.children = childArray;\n  }\n  return ReactElement(element.type, key, props);\n};\nexports.createContext = function (defaultValue) {\n  defaultValue = {\n    $$typeof: REACT_CONTEXT_TYPE,\n    _currentValue: defaultValue,\n    _currentValue2: defaultValue,\n    _threadCount: 0,\n    Provider: null,\n    Consumer: null\n  };\n  defaultValue.Provider = defaultValue;\n  defaultValue.Consumer = {\n    $$typeof: REACT_CONSUMER_TYPE,\n    _context: defaultValue\n  };\n  return defaultValue;\n};\nexports.createElement = function (type, config, children) {\n  var propName,\n    props = {},\n    key = null;\n  if (null != config)\n    for (propName in (void 0 !== config.key && (key = \"\" + config.key), config))\n      hasOwnProperty.call(config, propName) &&\n        \"key\" !== propName &&\n        \"__self\" !== propName &&\n        \"__source\" !== propName &&\n        (props[propName] = config[propName]);\n  var childrenLength = arguments.length - 2;\n  if (1 === childrenLength) props.children = children;\n  else if (1 < childrenLength) {\n    for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)\n      childArray[i] = arguments[i + 2];\n    props.children = childArray;\n  }\n  if (type && type.defaultProps)\n    for (propName in ((childrenLength = type.defaultProps), childrenLength))\n      void 0 === props[propName] &&\n        (props[propName] = childrenLength[propName]);\n  return ReactElement(type, key, props);\n};\nexports.createRef = function () {\n  return { current: null };\n};\nexports.forwardRef = function (render) {\n  return { $$typeof: REACT_FORWARD_REF_TYPE, render: render };\n};\nexports.isValidElement = isValidElement;\nexports.lazy = function (ctor) {\n  return {\n    $$typeof: REACT_LAZY_TYPE,\n    _payload: { _status: -1, _result: ctor },\n    _init: lazyInitializer\n  };\n};\nexports.memo = function (type, compare) {\n  return {\n    $$typeof: REACT_MEMO_TYPE,\n    type: type,\n    compare: void 0 === compare ? null : compare\n  };\n};\nexports.startTransition = startTransition;\nexports.unstable_useCacheRefresh = function () {\n  return ReactSharedInternals.H.useCacheRefresh();\n};\nexports.use = function (usable) {\n  return ReactSharedInternals.H.use(usable);\n};\nexports.useActionState = function (action, initialState, permalink) {\n  return ReactSharedInternals.H.useActionState(action, initialState, permalink);\n};\nexports.useCallback = function (callback, deps) {\n  return ReactSharedInternals.H.useCallback(callback, deps);\n};\nexports.useContext = function (Context) {\n  return ReactSharedInternals.H.useContext(Context);\n};\nexports.useDebugValue = function () {};\nexports.useDeferredValue = function (value, initialValue) {\n  return ReactSharedInternals.H.useDeferredValue(value, initialValue);\n};\nexports.useEffect = function (create, deps) {\n  return ReactSharedInternals.H.useEffect(create, deps);\n};\nexports.useEffectEvent = function (callback) {\n  return ReactSharedInternals.H.useEffectEvent(callback);\n};\nexports.useId = function () {\n  return ReactSharedInternals.H.useId();\n};\nexports.useImperativeHandle = function (ref, create, deps) {\n  return ReactSharedInternals.H.useImperativeHandle(ref, create, deps);\n};\nexports.useInsertionEffect = function (create, deps) {\n  return ReactSharedInternals.H.useInsertionEffect(create, deps);\n};\nexports.useLayoutEffect = function (create, deps) {\n  return ReactSharedInternals.H.useLayoutEffect(create, deps);\n};\nexports.useMemo = function (create, deps) {\n  return ReactSharedInternals.H.useMemo(create, deps);\n};\nexports.useOptimistic = function (passthrough, reducer) {\n  return ReactSharedInternals.H.useOptimistic(passthrough, reducer);\n};\nexports.useReducer = function (reducer, initialArg, init) {\n  return ReactSharedInternals.H.useReducer(reducer, initialArg, init);\n};\nexports.useRef = function (initialValue) {\n  return ReactSharedInternals.H.useRef(initialValue);\n};\nexports.useState = function (initialState) {\n  return ReactSharedInternals.H.useState(initialState);\n};\nexports.useSyncExternalStore = function (\n  subscribe,\n  getSnapshot,\n  getServerSnapshot\n) {\n  return ReactSharedInternals.H.useSyncExternalStore(\n    subscribe,\n    getSnapshot,\n    getServerSnapshot\n  );\n};\nexports.useTransition = function () {\n  return ReactSharedInternals.H.useTransition();\n};\nexports.version = \"19.3.1\";\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./cjs/react.production.js');\n} else {\n  module.exports = require('./cjs/react.development.js');\n}\n","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc');  // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar _assign = require('object-assign');\n\n// -- Inlined from fbjs --\n\nvar emptyObject = {};\n\nif (process.env.NODE_ENV !== 'production') {\n  Object.freeze(emptyObject);\n}\n\nvar validateFormat = function validateFormat(format) {};\n\nif (process.env.NODE_ENV !== 'production') {\n  validateFormat = function validateFormat(format) {\n    if (format === undefined) {\n      throw new Error('invariant requires an error message argument');\n    }\n  };\n}\n\nfunction _invariant(condition, format, a, b, c, d, e, f) {\n  validateFormat(format);\n\n  if (!condition) {\n    var error;\n    if (format === undefined) {\n      error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');\n    } else {\n      var args = [a, b, c, d, e, f];\n      var argIndex = 0;\n      error = new Error(format.replace(/%s/g, function () {\n        return args[argIndex++];\n      }));\n      error.name = 'Invariant Violation';\n    }\n\n    error.framesToPop = 1; // we don't care about invariant's own frame\n    throw error;\n  }\n}\n\nvar warning = function(){};\n\nif (process.env.NODE_ENV !== 'production') {\n  var printWarning = function printWarning(format) {\n    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n      args[_key - 1] = arguments[_key];\n    }\n\n    var argIndex = 0;\n    var message = 'Warning: ' + format.replace(/%s/g, function () {\n      return args[argIndex++];\n    });\n    if (typeof console !== 'undefined') {\n      console.error(message);\n    }\n    try {\n      // --- Welcome to debugging React ---\n      // This error was thrown as a convenience so that you can use this stack\n      // to find the callsite that caused this warning to fire.\n      throw new Error(message);\n    } catch (x) {}\n  };\n\n  warning = function warning(condition, format) {\n    if (format === undefined) {\n      throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');\n    }\n\n    if (format.indexOf('Failed Composite propType: ') === 0) {\n      return; // Ignore CompositeComponent proptype check.\n    }\n\n    if (!condition) {\n      for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {\n        args[_key2 - 2] = arguments[_key2];\n      }\n\n      printWarning.apply(undefined, [format].concat(args));\n    }\n  };\n}\n\n// /-- Inlined from fbjs --\n\nvar MIXINS_KEY = 'mixins';\n\n// Helper function to allow the creation of anonymous functions which do not\n// have .name set to the name of the variable being assigned to.\nfunction identity(fn) {\n  return fn;\n}\n\nvar ReactPropTypeLocationNames;\nif (process.env.NODE_ENV !== 'production') {\n  ReactPropTypeLocationNames = {\n    prop: 'prop',\n    context: 'context',\n    childContext: 'child context'\n  };\n} else {\n  ReactPropTypeLocationNames = {};\n}\n\nfunction factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) {\n  /**\n   * Policies that describe methods in `ReactClassInterface`.\n   */\n\n  var injectedMixins = [];\n\n  /**\n   * Composite components are higher-level components that compose other composite\n   * or host components.\n   *\n   * To create a new type of `ReactClass`, pass a specification of\n   * your new class to `React.createClass`. The only requirement of your class\n   * specification is that you implement a `render` method.\n   *\n   *   var MyComponent = React.createClass({\n   *     render: function() {\n   *       return <div>Hello World</div>;\n   *     }\n   *   });\n   *\n   * The class specification supports a specific protocol of methods that have\n   * special meaning (e.g. `render`). See `ReactClassInterface` for\n   * more the comprehensive protocol. Any other properties and methods in the\n   * class specification will be available on the prototype.\n   *\n   * @interface ReactClassInterface\n   * @internal\n   */\n  var ReactClassInterface = {\n    /**\n     * An array of Mixin objects to include when defining your component.\n     *\n     * @type {array}\n     * @optional\n     */\n    mixins: 'DEFINE_MANY',\n\n    /**\n     * An object containing properties and methods that should be defined on\n     * the component's constructor instead of its prototype (static methods).\n     *\n     * @type {object}\n     * @optional\n     */\n    statics: 'DEFINE_MANY',\n\n    /**\n     * Definition of prop types for this component.\n     *\n     * @type {object}\n     * @optional\n     */\n    propTypes: 'DEFINE_MANY',\n\n    /**\n     * Definition of context types for this component.\n     *\n     * @type {object}\n     * @optional\n     */\n    contextTypes: 'DEFINE_MANY',\n\n    /**\n     * Definition of context types this component sets for its children.\n     *\n     * @type {object}\n     * @optional\n     */\n    childContextTypes: 'DEFINE_MANY',\n\n    // ==== Definition methods ====\n\n    /**\n     * Invoked when the component is mounted. Values in the mapping will be set on\n     * `this.props` if that prop is not specified (i.e. using an `in` check).\n     *\n     * This method is invoked before `getInitialState` and therefore cannot rely\n     * on `this.state` or use `this.setState`.\n     *\n     * @return {object}\n     * @optional\n     */\n    getDefaultProps: 'DEFINE_MANY_MERGED',\n\n    /**\n     * Invoked once before the component is mounted. The return value will be used\n     * as the initial value of `this.state`.\n     *\n     *   getInitialState: function() {\n     *     return {\n     *       isOn: false,\n     *       fooBaz: new BazFoo()\n     *     }\n     *   }\n     *\n     * @return {object}\n     * @optional\n     */\n    getInitialState: 'DEFINE_MANY_MERGED',\n\n    /**\n     * @return {object}\n     * @optional\n     */\n    getChildContext: 'DEFINE_MANY_MERGED',\n\n    /**\n     * Uses props from `this.props` and state from `this.state` to render the\n     * structure of the component.\n     *\n     * No guarantees are made about when or how often this method is invoked, so\n     * it must not have side effects.\n     *\n     *   render: function() {\n     *     var name = this.props.name;\n     *     return <div>Hello, {name}!</div>;\n     *   }\n     *\n     * @return {ReactComponent}\n     * @required\n     */\n    render: 'DEFINE_ONCE',\n\n    // ==== Delegate methods ====\n\n    /**\n     * Invoked when the component is initially created and about to be mounted.\n     * This may have side effects, but any external subscriptions or data created\n     * by this method must be cleaned up in `componentWillUnmount`.\n     *\n     * @optional\n     */\n    componentWillMount: 'DEFINE_MANY',\n\n    /**\n     * Invoked when the component has been mounted and has a DOM representation.\n     * However, there is no guarantee that the DOM node is in the document.\n     *\n     * Use this as an opportunity to operate on the DOM when the component has\n     * been mounted (initialized and rendered) for the first time.\n     *\n     * @param {DOMElement} rootNode DOM element representing the component.\n     * @optional\n     */\n    componentDidMount: 'DEFINE_MANY',\n\n    /**\n     * Invoked before the component receives new props.\n     *\n     * Use this as an opportunity to react to a prop transition by updating the\n     * state using `this.setState`. Current props are accessed via `this.props`.\n     *\n     *   componentWillReceiveProps: function(nextProps, nextContext) {\n     *     this.setState({\n     *       likesIncreasing: nextProps.likeCount > this.props.likeCount\n     *     });\n     *   }\n     *\n     * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop\n     * transition may cause a state change, but the opposite is not true. If you\n     * need it, you are probably looking for `componentWillUpdate`.\n     *\n     * @param {object} nextProps\n     * @optional\n     */\n    componentWillReceiveProps: 'DEFINE_MANY',\n\n    /**\n     * Invoked while deciding if the component should be updated as a result of\n     * receiving new props, state and/or context.\n     *\n     * Use this as an opportunity to `return false` when you're certain that the\n     * transition to the new props/state/context will not require a component\n     * update.\n     *\n     *   shouldComponentUpdate: function(nextProps, nextState, nextContext) {\n     *     return !equal(nextProps, this.props) ||\n     *       !equal(nextState, this.state) ||\n     *       !equal(nextContext, this.context);\n     *   }\n     *\n     * @param {object} nextProps\n     * @param {?object} nextState\n     * @param {?object} nextContext\n     * @return {boolean} True if the component should update.\n     * @optional\n     */\n    shouldComponentUpdate: 'DEFINE_ONCE',\n\n    /**\n     * Invoked when the component is about to update due to a transition from\n     * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`\n     * and `nextContext`.\n     *\n     * Use this as an opportunity to perform preparation before an update occurs.\n     *\n     * NOTE: You **cannot** use `this.setState()` in this method.\n     *\n     * @param {object} nextProps\n     * @param {?object} nextState\n     * @param {?object} nextContext\n     * @param {ReactReconcileTransaction} transaction\n     * @optional\n     */\n    componentWillUpdate: 'DEFINE_MANY',\n\n    /**\n     * Invoked when the component's DOM representation has been updated.\n     *\n     * Use this as an opportunity to operate on the DOM when the component has\n     * been updated.\n     *\n     * @param {object} prevProps\n     * @param {?object} prevState\n     * @param {?object} prevContext\n     * @param {DOMElement} rootNode DOM element representing the component.\n     * @optional\n     */\n    componentDidUpdate: 'DEFINE_MANY',\n\n    /**\n     * Invoked when the component is about to be removed from its parent and have\n     * its DOM representation destroyed.\n     *\n     * Use this as an opportunity to deallocate any external resources.\n     *\n     * NOTE: There is no `componentDidUnmount` since your component will have been\n     * destroyed by that point.\n     *\n     * @optional\n     */\n    componentWillUnmount: 'DEFINE_MANY',\n\n    /**\n     * Replacement for (deprecated) `componentWillMount`.\n     *\n     * @optional\n     */\n    UNSAFE_componentWillMount: 'DEFINE_MANY',\n\n    /**\n     * Replacement for (deprecated) `componentWillReceiveProps`.\n     *\n     * @optional\n     */\n    UNSAFE_componentWillReceiveProps: 'DEFINE_MANY',\n\n    /**\n     * Replacement for (deprecated) `componentWillUpdate`.\n     *\n     * @optional\n     */\n    UNSAFE_componentWillUpdate: 'DEFINE_MANY',\n\n    // ==== Advanced methods ====\n\n    /**\n     * Updates the component's currently mounted DOM representation.\n     *\n     * By default, this implements React's rendering and reconciliation algorithm.\n     * Sophisticated clients may wish to override this.\n     *\n     * @param {ReactReconcileTransaction} transaction\n     * @internal\n     * @overridable\n     */\n    updateComponent: 'OVERRIDE_BASE'\n  };\n\n  /**\n   * Similar to ReactClassInterface but for static methods.\n   */\n  var ReactClassStaticInterface = {\n    /**\n     * This method is invoked after a component is instantiated and when it\n     * receives new props. Return an object to update state in response to\n     * prop changes. Return null to indicate no change to state.\n     *\n     * If an object is returned, its keys will be merged into the existing state.\n     *\n     * @return {object || null}\n     * @optional\n     */\n    getDerivedStateFromProps: 'DEFINE_MANY_MERGED'\n  };\n\n  /**\n   * Mapping from class specification keys to special processing functions.\n   *\n   * Although these are declared like instance properties in the specification\n   * when defining classes using `React.createClass`, they are actually static\n   * and are accessible on the constructor instead of the prototype. Despite\n   * being static, they must be defined outside of the \"statics\" key under\n   * which all other static methods are defined.\n   */\n  var RESERVED_SPEC_KEYS = {\n    displayName: function(Constructor, displayName) {\n      Constructor.displayName = displayName;\n    },\n    mixins: function(Constructor, mixins) {\n      if (mixins) {\n        for (var i = 0; i < mixins.length; i++) {\n          mixSpecIntoComponent(Constructor, mixins[i]);\n        }\n      }\n    },\n    childContextTypes: function(Constructor, childContextTypes) {\n      if (process.env.NODE_ENV !== 'production') {\n        validateTypeDef(Constructor, childContextTypes, 'childContext');\n      }\n      Constructor.childContextTypes = _assign(\n        {},\n        Constructor.childContextTypes,\n        childContextTypes\n      );\n    },\n    contextTypes: function(Constructor, contextTypes) {\n      if (process.env.NODE_ENV !== 'production') {\n        validateTypeDef(Constructor, contextTypes, 'context');\n      }\n      Constructor.contextTypes = _assign(\n        {},\n        Constructor.contextTypes,\n        contextTypes\n      );\n    },\n    /**\n     * Special case getDefaultProps which should move into statics but requires\n     * automatic merging.\n     */\n    getDefaultProps: function(Constructor, getDefaultProps) {\n      if (Constructor.getDefaultProps) {\n        Constructor.getDefaultProps = createMergedResultFunction(\n          Constructor.getDefaultProps,\n          getDefaultProps\n        );\n      } else {\n        Constructor.getDefaultProps = getDefaultProps;\n      }\n    },\n    propTypes: function(Constructor, propTypes) {\n      if (process.env.NODE_ENV !== 'production') {\n        validateTypeDef(Constructor, propTypes, 'prop');\n      }\n      Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);\n    },\n    statics: function(Constructor, statics) {\n      mixStaticSpecIntoComponent(Constructor, statics);\n    },\n    autobind: function() {}\n  };\n\n  function validateTypeDef(Constructor, typeDef, location) {\n    for (var propName in typeDef) {\n      if (typeDef.hasOwnProperty(propName)) {\n        // use a warning instead of an _invariant so components\n        // don't show up in prod but only in __DEV__\n        if (process.env.NODE_ENV !== 'production') {\n          warning(\n            typeof typeDef[propName] === 'function',\n            '%s: %s type `%s` is invalid; it must be a function, usually from ' +\n              'React.PropTypes.',\n            Constructor.displayName || 'ReactClass',\n            ReactPropTypeLocationNames[location],\n            propName\n          );\n        }\n      }\n    }\n  }\n\n  function validateMethodOverride(isAlreadyDefined, name) {\n    var specPolicy = ReactClassInterface.hasOwnProperty(name)\n      ? ReactClassInterface[name]\n      : null;\n\n    // Disallow overriding of base class methods unless explicitly allowed.\n    if (ReactClassMixin.hasOwnProperty(name)) {\n      _invariant(\n        specPolicy === 'OVERRIDE_BASE',\n        'ReactClassInterface: You are attempting to override ' +\n          '`%s` from your class specification. Ensure that your method names ' +\n          'do not overlap with React methods.',\n        name\n      );\n    }\n\n    // Disallow defining methods more than once unless explicitly allowed.\n    if (isAlreadyDefined) {\n      _invariant(\n        specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED',\n        'ReactClassInterface: You are attempting to define ' +\n          '`%s` on your component more than once. This conflict may be due ' +\n          'to a mixin.',\n        name\n      );\n    }\n  }\n\n  /**\n   * Mixin helper which handles policy validation and reserved\n   * specification keys when building React classes.\n   */\n  function mixSpecIntoComponent(Constructor, spec) {\n    if (!spec) {\n      if (process.env.NODE_ENV !== 'production') {\n        var typeofSpec = typeof spec;\n        var isMixinValid = typeofSpec === 'object' && spec !== null;\n\n        if (process.env.NODE_ENV !== 'production') {\n          warning(\n            isMixinValid,\n            \"%s: You're attempting to include a mixin that is either null \" +\n              'or not an object. Check the mixins included by the component, ' +\n              'as well as any mixins they include themselves. ' +\n              'Expected object but got %s.',\n            Constructor.displayName || 'ReactClass',\n            spec === null ? null : typeofSpec\n          );\n        }\n      }\n\n      return;\n    }\n\n    _invariant(\n      typeof spec !== 'function',\n      \"ReactClass: You're attempting to \" +\n        'use a component class or function as a mixin. Instead, just use a ' +\n        'regular object.'\n    );\n    _invariant(\n      !isValidElement(spec),\n      \"ReactClass: You're attempting to \" +\n        'use a component as a mixin. Instead, just use a regular object.'\n    );\n\n    var proto = Constructor.prototype;\n    var autoBindPairs = proto.__reactAutoBindPairs;\n\n    // By handling mixins before any other properties, we ensure the same\n    // chaining order is applied to methods with DEFINE_MANY policy, whether\n    // mixins are listed before or after these methods in the spec.\n    if (spec.hasOwnProperty(MIXINS_KEY)) {\n      RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);\n    }\n\n    for (var name in spec) {\n      if (!spec.hasOwnProperty(name)) {\n        continue;\n      }\n\n      if (name === MIXINS_KEY) {\n        // We have already handled mixins in a special case above.\n        continue;\n      }\n\n      var property = spec[name];\n      var isAlreadyDefined = proto.hasOwnProperty(name);\n      validateMethodOverride(isAlreadyDefined, name);\n\n      if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {\n        RESERVED_SPEC_KEYS[name](Constructor, property);\n      } else {\n        // Setup methods on prototype:\n        // The following member methods should not be automatically bound:\n        // 1. Expected ReactClass methods (in the \"interface\").\n        // 2. Overridden methods (that were mixed in).\n        var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);\n        var isFunction = typeof property === 'function';\n        var shouldAutoBind =\n          isFunction &&\n          !isReactClassMethod &&\n          !isAlreadyDefined &&\n          spec.autobind !== false;\n\n        if (shouldAutoBind) {\n          autoBindPairs.push(name, property);\n          proto[name] = property;\n        } else {\n          if (isAlreadyDefined) {\n            var specPolicy = ReactClassInterface[name];\n\n            // These cases should already be caught by validateMethodOverride.\n            _invariant(\n              isReactClassMethod &&\n                (specPolicy === 'DEFINE_MANY_MERGED' ||\n                  specPolicy === 'DEFINE_MANY'),\n              'ReactClass: Unexpected spec policy %s for key %s ' +\n                'when mixing in component specs.',\n              specPolicy,\n              name\n            );\n\n            // For methods which are defined more than once, call the existing\n            // methods before calling the new property, merging if appropriate.\n            if (specPolicy === 'DEFINE_MANY_MERGED') {\n              proto[name] = createMergedResultFunction(proto[name], property);\n            } else if (specPolicy === 'DEFINE_MANY') {\n              proto[name] = createChainedFunction(proto[name], property);\n            }\n          } else {\n            proto[name] = property;\n            if (process.env.NODE_ENV !== 'production') {\n              // Add verbose displayName to the function, which helps when looking\n              // at profiling tools.\n              if (typeof property === 'function' && spec.displayName) {\n                proto[name].displayName = spec.displayName + '_' + name;\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  function mixStaticSpecIntoComponent(Constructor, statics) {\n    if (!statics) {\n      return;\n    }\n\n    for (var name in statics) {\n      var property = statics[name];\n      if (!statics.hasOwnProperty(name)) {\n        continue;\n      }\n\n      var isReserved = name in RESERVED_SPEC_KEYS;\n      _invariant(\n        !isReserved,\n        'ReactClass: You are attempting to define a reserved ' +\n          'property, `%s`, that shouldn\\'t be on the \"statics\" key. Define it ' +\n          'as an instance property instead; it will still be accessible on the ' +\n          'constructor.',\n        name\n      );\n\n      var isAlreadyDefined = name in Constructor;\n      if (isAlreadyDefined) {\n        var specPolicy = ReactClassStaticInterface.hasOwnProperty(name)\n          ? ReactClassStaticInterface[name]\n          : null;\n\n        _invariant(\n          specPolicy === 'DEFINE_MANY_MERGED',\n          'ReactClass: You are attempting to define ' +\n            '`%s` on your component more than once. This conflict may be ' +\n            'due to a mixin.',\n          name\n        );\n\n        Constructor[name] = createMergedResultFunction(Constructor[name], property);\n\n        return;\n      }\n\n      Constructor[name] = property;\n    }\n  }\n\n  /**\n   * Merge two objects, but throw if both contain the same key.\n   *\n   * @param {object} one The first object, which is mutated.\n   * @param {object} two The second object\n   * @return {object} one after it has been mutated to contain everything in two.\n   */\n  function mergeIntoWithNoDuplicateKeys(one, two) {\n    _invariant(\n      one && two && typeof one === 'object' && typeof two === 'object',\n      'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'\n    );\n\n    for (var key in two) {\n      if (two.hasOwnProperty(key)) {\n        _invariant(\n          one[key] === undefined,\n          'mergeIntoWithNoDuplicateKeys(): ' +\n            'Tried to merge two objects with the same key: `%s`. This conflict ' +\n            'may be due to a mixin; in particular, this may be caused by two ' +\n            'getInitialState() or getDefaultProps() methods returning objects ' +\n            'with clashing keys.',\n          key\n        );\n        one[key] = two[key];\n      }\n    }\n    return one;\n  }\n\n  /**\n   * Creates a function that invokes two functions and merges their return values.\n   *\n   * @param {function} one Function to invoke first.\n   * @param {function} two Function to invoke second.\n   * @return {function} Function that invokes the two argument functions.\n   * @private\n   */\n  function createMergedResultFunction(one, two) {\n    return function mergedResult() {\n      var a = one.apply(this, arguments);\n      var b = two.apply(this, arguments);\n      if (a == null) {\n        return b;\n      } else if (b == null) {\n        return a;\n      }\n      var c = {};\n      mergeIntoWithNoDuplicateKeys(c, a);\n      mergeIntoWithNoDuplicateKeys(c, b);\n      return c;\n    };\n  }\n\n  /**\n   * Creates a function that invokes two functions and ignores their return vales.\n   *\n   * @param {function} one Function to invoke first.\n   * @param {function} two Function to invoke second.\n   * @return {function} Function that invokes the two argument functions.\n   * @private\n   */\n  function createChainedFunction(one, two) {\n    return function chainedFunction() {\n      one.apply(this, arguments);\n      two.apply(this, arguments);\n    };\n  }\n\n  /**\n   * Binds a method to the component.\n   *\n   * @param {object} component Component whose method is going to be bound.\n   * @param {function} method Method to be bound.\n   * @return {function} The bound method.\n   */\n  function bindAutoBindMethod(component, method) {\n    var boundMethod = method.bind(component);\n    if (process.env.NODE_ENV !== 'production') {\n      boundMethod.__reactBoundContext = component;\n      boundMethod.__reactBoundMethod = method;\n      boundMethod.__reactBoundArguments = null;\n      var componentName = component.constructor.displayName;\n      var _bind = boundMethod.bind;\n      boundMethod.bind = function(newThis) {\n        for (\n          var _len = arguments.length,\n            args = Array(_len > 1 ? _len - 1 : 0),\n            _key = 1;\n          _key < _len;\n          _key++\n        ) {\n          args[_key - 1] = arguments[_key];\n        }\n\n        // User is trying to bind() an autobound method; we effectively will\n        // ignore the value of \"this\" that the user is trying to use, so\n        // let's warn.\n        if (newThis !== component && newThis !== null) {\n          if (process.env.NODE_ENV !== 'production') {\n            warning(\n              false,\n              'bind(): React component methods may only be bound to the ' +\n                'component instance. See %s',\n              componentName\n            );\n          }\n        } else if (!args.length) {\n          if (process.env.NODE_ENV !== 'production') {\n            warning(\n              false,\n              'bind(): You are binding a component method to the component. ' +\n                'React does this for you automatically in a high-performance ' +\n                'way, so you can safely remove this call. See %s',\n              componentName\n            );\n          }\n          return boundMethod;\n        }\n        var reboundMethod = _bind.apply(boundMethod, arguments);\n        reboundMethod.__reactBoundContext = component;\n        reboundMethod.__reactBoundMethod = method;\n        reboundMethod.__reactBoundArguments = args;\n        return reboundMethod;\n      };\n    }\n    return boundMethod;\n  }\n\n  /**\n   * Binds all auto-bound methods in a component.\n   *\n   * @param {object} component Component whose method is going to be bound.\n   */\n  function bindAutoBindMethods(component) {\n    var pairs = component.__reactAutoBindPairs;\n    for (var i = 0; i < pairs.length; i += 2) {\n      var autoBindKey = pairs[i];\n      var method = pairs[i + 1];\n      component[autoBindKey] = bindAutoBindMethod(component, method);\n    }\n  }\n\n  var IsMountedPreMixin = {\n    componentDidMount: function() {\n      this.__isMounted = true;\n    }\n  };\n\n  var IsMountedPostMixin = {\n    componentWillUnmount: function() {\n      this.__isMounted = false;\n    }\n  };\n\n  /**\n   * Add more to the ReactClass base class. These are all legacy features and\n   * therefore not already part of the modern ReactComponent.\n   */\n  var ReactClassMixin = {\n    /**\n     * TODO: This will be deprecated because state should always keep a consistent\n     * type signature and the only use case for this, is to avoid that.\n     */\n    replaceState: function(newState, callback) {\n      this.updater.enqueueReplaceState(this, newState, callback);\n    },\n\n    /**\n     * Checks whether or not this composite component is mounted.\n     * @return {boolean} True if mounted, false otherwise.\n     * @protected\n     * @final\n     */\n    isMounted: function() {\n      if (process.env.NODE_ENV !== 'production') {\n        warning(\n          this.__didWarnIsMounted,\n          '%s: isMounted is deprecated. Instead, make sure to clean up ' +\n            'subscriptions and pending requests in componentWillUnmount to ' +\n            'prevent memory leaks.',\n          (this.constructor && this.constructor.displayName) ||\n            this.name ||\n            'Component'\n        );\n        this.__didWarnIsMounted = true;\n      }\n      return !!this.__isMounted;\n    }\n  };\n\n  var ReactClassComponent = function() {};\n  _assign(\n    ReactClassComponent.prototype,\n    ReactComponent.prototype,\n    ReactClassMixin\n  );\n\n  /**\n   * Creates a composite component class given a class specification.\n   * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass\n   *\n   * @param {object} spec Class specification (which must define `render`).\n   * @return {function} Component constructor function.\n   * @public\n   */\n  function createClass(spec) {\n    // To keep our warnings more understandable, we'll use a little hack here to\n    // ensure that Constructor.name !== 'Constructor'. This makes sure we don't\n    // unnecessarily identify a class without displayName as 'Constructor'.\n    var Constructor = identity(function(props, context, updater) {\n      // This constructor gets overridden by mocks. The argument is used\n      // by mocks to assert on what gets mounted.\n\n      if (process.env.NODE_ENV !== 'production') {\n        warning(\n          this instanceof Constructor,\n          'Something is calling a React component directly. Use a factory or ' +\n            'JSX instead. See: https://fb.me/react-legacyfactory'\n        );\n      }\n\n      // Wire up auto-binding\n      if (this.__reactAutoBindPairs.length) {\n        bindAutoBindMethods(this);\n      }\n\n      this.props = props;\n      this.context = context;\n      this.refs = emptyObject;\n      this.updater = updater || ReactNoopUpdateQueue;\n\n      this.state = null;\n\n      // ReactClasses doesn't have constructors. Instead, they use the\n      // getInitialState and componentWillMount methods for initialization.\n\n      var initialState = this.getInitialState ? this.getInitialState() : null;\n      if (process.env.NODE_ENV !== 'production') {\n        // We allow auto-mocks to proceed as if they're returning null.\n        if (\n          initialState === undefined &&\n          this.getInitialState._isMockFunction\n        ) {\n          // This is probably bad practice. Consider warning here and\n          // deprecating this convenience.\n          initialState = null;\n        }\n      }\n      _invariant(\n        typeof initialState === 'object' && !Array.isArray(initialState),\n        '%s.getInitialState(): must return an object or null',\n        Constructor.displayName || 'ReactCompositeComponent'\n      );\n\n      this.state = initialState;\n    });\n    Constructor.prototype = new ReactClassComponent();\n    Constructor.prototype.constructor = Constructor;\n    Constructor.prototype.__reactAutoBindPairs = [];\n\n    injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));\n\n    mixSpecIntoComponent(Constructor, IsMountedPreMixin);\n    mixSpecIntoComponent(Constructor, spec);\n    mixSpecIntoComponent(Constructor, IsMountedPostMixin);\n\n    // Initialize the defaultProps property after all mixins have been merged.\n    if (Constructor.getDefaultProps) {\n      Constructor.defaultProps = Constructor.getDefaultProps();\n    }\n\n    if (process.env.NODE_ENV !== 'production') {\n      // This is a tag to indicate that the use of these method names is ok,\n      // since it's used with createClass. If it's not, then it's likely a\n      // mistake so we'll warn you to use the static property, property\n      // initializer or constructor respectively.\n      if (Constructor.getDefaultProps) {\n        Constructor.getDefaultProps.isReactClassApproved = {};\n      }\n      if (Constructor.prototype.getInitialState) {\n        Constructor.prototype.getInitialState.isReactClassApproved = {};\n      }\n    }\n\n    _invariant(\n      Constructor.prototype.render,\n      'createClass(...): Class specification must implement a `render` method.'\n    );\n\n    if (process.env.NODE_ENV !== 'production') {\n      warning(\n        !Constructor.prototype.componentShouldUpdate,\n        '%s has a method called ' +\n          'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +\n          'The name is phrased as a question because the function is ' +\n          'expected to return a value.',\n        spec.displayName || 'A component'\n      );\n      warning(\n        !Constructor.prototype.componentWillRecieveProps,\n        '%s has a method called ' +\n          'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',\n        spec.displayName || 'A component'\n      );\n      warning(\n        !Constructor.prototype.UNSAFE_componentWillRecieveProps,\n        '%s has a method called UNSAFE_componentWillRecieveProps(). ' +\n          'Did you mean UNSAFE_componentWillReceiveProps()?',\n        spec.displayName || 'A component'\n      );\n    }\n\n    // Reduce time spent doing lookups by setting these on the prototype.\n    for (var methodName in ReactClassInterface) {\n      if (!Constructor.prototype[methodName]) {\n        Constructor.prototype[methodName] = null;\n      }\n    }\n\n    return Constructor;\n  }\n\n  return createClass;\n}\n\nmodule.exports = factory;\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar React = require('react');\nvar factory = require('./factory');\n\nif (typeof React === 'undefined') {\n  throw Error(\n    'create-react-class could not find the React object. If you are using script tags, ' +\n      'make sure that React is being loaded before create-react-class.'\n  );\n}\n\n// Hack to grab NoopUpdateQueue from isomorphic React\nvar ReactNoopUpdateQueue = new React.Component().updater;\n\nmodule.exports = factory(\n  React.Component,\n  React.isValidElement,\n  ReactNoopUpdateQueue\n);\n","/*! @license DOMPurify 3.4.18 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.18/LICENSE */\nfunction _OverloadYield(e, d) {\n\tthis.v = e, this.k = d;\n}\nfunction _arrayLikeToArray(r, a) {\n\t(null == a || a > r.length) && (a = r.length);\n\tfor (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n\treturn n;\n}\nfunction _arrayWithHoles(r) {\n\tif (Array.isArray(r)) return r;\n}\nfunction _iterableToArrayLimit(r, l) {\n\tvar t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n\tif (null != t) {\n\t\tvar e, n, i, u, a = [], f = !0, o = !1;\n\t\ttry {\n\t\t\tif (i = (t = t.call(r)).next, 0 === l) {\n\t\t\t\tif (Object(t) !== t) return;\n\t\t\t\tf = !1;\n\t\t\t} else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n\t\t} catch (r) {\n\t\t\to = !0, n = r;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tif (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;\n\t\t\t} finally {\n\t\t\t\tif (o) throw n;\n\t\t\t}\n\t\t}\n\t\treturn a;\n\t}\n}\nfunction _nonIterableRest() {\n\tthrow new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */\nfunction _slicedToArray(r, e) {\n\treturn _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();\n}\nfunction _unsupportedIterableToArray(r, a) {\n\tif (r) {\n\t\tif (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n\t\tvar t = {}.toString.call(r).slice(8, -1);\n\t\treturn \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n\t}\n}\nfunction AsyncGenerator(e) {\n\tvar t, n;\n\tfunction resume(t, n) {\n\t\ttry {\n\t\t\tvar r = e[t](n), o = r.value, u = o instanceof _OverloadYield;\n\t\t\tPromise.resolve(u ? o.v : o).then(function(n) {\n\t\t\t\tif (u) {\n\t\t\t\t\tvar i = \"return\" === t && o.k ? t : \"next\";\n\t\t\t\t\tif (!o.k || n.done) return resume(i, n);\n\t\t\t\t\tn = e[i](n).value;\n\t\t\t\t}\n\t\t\t\tsettle(!!r.done, n);\n\t\t\t}, function(e) {\n\t\t\t\tresume(\"throw\", e);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tsettle(2, e);\n\t\t}\n\t}\n\tfunction settle(e, r) {\n\t\t2 === e ? t.reject(r) : t.resolve({\n\t\t\tvalue: r,\n\t\t\tdone: e\n\t\t}), (t = t.next) ? resume(t.key, t.arg) : n = null;\n\t}\n\tthis._invoke = function(e, r) {\n\t\treturn new Promise(function(o, u) {\n\t\t\tvar i = {\n\t\t\t\tkey: e,\n\t\t\t\targ: r,\n\t\t\t\tresolve: o,\n\t\t\t\treject: u,\n\t\t\t\tnext: null\n\t\t\t};\n\t\t\tn ? n = n.next = i : (t = n = i, resume(e, r));\n\t\t});\n\t}, \"function\" != typeof e.return && (this.return = void 0);\n}\nAsyncGenerator.prototype[\"function\" == typeof Symbol && Symbol.asyncIterator || \"@@asyncIterator\"] = function() {\n\treturn this;\n}, AsyncGenerator.prototype.next = function(e) {\n\treturn this._invoke(\"next\", e);\n}, AsyncGenerator.prototype.throw = function(e) {\n\treturn this._invoke(\"throw\", e);\n}, AsyncGenerator.prototype.return = function(e) {\n\treturn this._invoke(\"return\", e);\n};\nconst entries = Object.entries;\nconst objectKeys = Object.keys;\nconst setPrototypeOf = Object.setPrototypeOf;\nconst isFrozen = Object.isFrozen;\nconst getPrototypeOf = Object.getPrototypeOf;\nconst getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nlet freeze = Object.freeze;\nlet seal = Object.seal;\nlet create = Object.create;\nlet _ref = typeof Reflect !== \"undefined\" && Reflect;\nlet apply = _ref.apply;\nlet construct = _ref.construct;\nif (!freeze) freeze = function freeze(x) {\n\treturn x;\n};\nif (!seal) seal = function seal(x) {\n\treturn x;\n};\nif (!apply) apply = function apply(func, thisArg) {\n\tfor (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) args[_key - 2] = arguments[_key];\n\treturn func.apply(thisArg, args);\n};\nif (!construct) construct = function construct(Func) {\n\tfor (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) args[_key2 - 1] = arguments[_key2];\n\treturn new Func(...args);\n};\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySlice = unapply(Array.prototype.slice);\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\nconst setCreate = unconstruct(Set);\nconst setAdd = unapply(Set.prototype.add);\nconst setHas = unapply(Set.prototype.has);\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\nconst numberToString = unapply(Number.prototype.toString);\nconst booleanToString = unapply(Boolean.prototype.toString);\nconst bigintToString = typeof BigInt === \"undefined\" ? null : unapply(BigInt.prototype.toString);\nconst symbolToString = typeof Symbol === \"undefined\" ? null : unapply(Symbol.prototype.toString);\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst objectToString = unapply(Object.prototype.toString);\nconst regExpTestRaw = RegExp.prototype.test;\nconst regExpTest = function regExpTest(regExp, value) {\n\tif (regExp instanceof RegExp) regExp.lastIndex = 0;\n\treturn apply(regExpTestRaw, regExp, [value]);\n};\nconst typeErrorCreate = unconstruct(TypeError);\n/**\n* Creates a new function that calls the given function with a specified thisArg and arguments.\n*\n* @param func - The function to be wrapped and called.\n* @returns A new function that calls the given function with a specified thisArg and arguments.\n*/\nfunction unapply(func) {\n\treturn function(thisArg) {\n\t\tfor (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) args[_key3 - 1] = arguments[_key3];\n\t\treturn apply(func, thisArg, args);\n\t};\n}\n/**\n* Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n*\n* @param func - The constructor function to be wrapped and called.\n* @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n*/\nfunction unconstruct(Func) {\n\treturn function() {\n\t\tfor (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) args[_key4] = arguments[_key4];\n\t\treturn construct(Func, args);\n\t};\n}\n/**\n* Add properties to a lookup table\n*\n* @param set - The set to which elements will be added.\n* @param array - The array containing elements to be added to the set.\n* @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n* @returns The modified set with added elements.\n*/\nfunction addToSet(set, array) {\n\tlet transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase;\n\tif (setPrototypeOf) setPrototypeOf(set, null);\n\tif (!arrayIsArray(array)) return set;\n\tlet l = array.length;\n\twhile (l--) {\n\t\tlet element = array[l];\n\t\tif (typeof element === \"string\") {\n\t\t\tconst lcElement = transformCaseFunc(element);\n\t\t\tif (lcElement !== element) {\n\t\t\t\tif (!isFrozen(array)) array[l] = lcElement;\n\t\t\t\telement = lcElement;\n\t\t\t}\n\t\t}\n\t\tset[element] = true;\n\t}\n\treturn set;\n}\n/**\n* Clean up an array to harden against CSPP\n*\n* @param array - The array to be cleaned.\n* @returns The cleaned version of the array\n*/\nfunction cleanArray(array) {\n\tfor (let index = 0; index < array.length; index++) if (!objectHasOwnProperty(array, index)) array[index] = null;\n\treturn array;\n}\n/**\n* Shallow clone an object\n*\n* @param object - The object to be cloned.\n* @returns A new object that copies the original.\n*/\nfunction clone(object) {\n\tconst newObject = create(null);\n\tfor (const _ref2 of entries(object)) {\n\t\tvar _ref3 = _slicedToArray(_ref2, 2);\n\t\tconst property = _ref3[0];\n\t\tconst value = _ref3[1];\n\t\tif (objectHasOwnProperty(object, property)) {\n\t\t\tif (arrayIsArray(value)) newObject[property] = cleanArray(value);\n\t\t\telse if (value && typeof value === \"object\" && value.constructor === Object) newObject[property] = clone(value);\n\t\t\telse newObject[property] = value;\n\t\t}\n\t}\n\treturn newObject;\n}\n/**\n* Copy a flat lookup table\n*\n* @param set - The set to copy.\n* @returns A new prototype-free set with the same entries.\n*/\nfunction cloneSet(set) {\n\tconst newSet = create(null);\n\tconst keys = objectKeys(set);\n\tlet l = keys.length;\n\twhile (l--) newSet[keys[l]] = set[keys[l]];\n\treturn newSet;\n}\n/**\n* Convert non-node values into strings without depending on direct property access.\n*\n* @param value - The value to stringify.\n* @returns A string representation of the provided value.\n*/\nfunction stringifyValue(value) {\n\tswitch (typeof value) {\n\t\tcase \"string\": return value;\n\t\tcase \"number\": return numberToString(value);\n\t\tcase \"boolean\": return booleanToString(value);\n\t\tcase \"bigint\": return bigintToString ? bigintToString(value) : \"0\";\n\t\tcase \"symbol\": return symbolToString ? symbolToString(value) : \"Symbol()\";\n\t\tcase \"undefined\": return objectToString(value);\n\t\tcase \"function\":\n\t\tcase \"object\": {\n\t\t\tif (value === null) return objectToString(value);\n\t\t\tconst valueAsRecord = value;\n\t\t\tconst valueToString = lookupGetter(valueAsRecord, \"toString\");\n\t\t\tif (typeof valueToString === \"function\") {\n\t\t\t\tconst stringified = valueToString(valueAsRecord);\n\t\t\t\treturn typeof stringified === \"string\" ? stringified : objectToString(stringified);\n\t\t\t}\n\t\t\treturn objectToString(value);\n\t\t}\n\t\tdefault: return objectToString(value);\n\t}\n}\n/**\n* This method automatically checks if the prop is function or getter and behaves accordingly.\n*\n* @param object - The object to look up the getter function in its prototype chain.\n* @param prop - The property name for which to find the getter function.\n* @returns The getter function found in the prototype chain or a fallback function.\n*/\nfunction lookupGetter(object, prop) {\n\twhile (object !== null) {\n\t\tconst desc = getOwnPropertyDescriptor(object, prop);\n\t\tif (desc) {\n\t\t\tif (desc.get) return unapply(desc.get);\n\t\t\tif (typeof desc.value === \"function\") return unapply(desc.value);\n\t\t}\n\t\tobject = getPrototypeOf(object);\n\t}\n\tfunction fallbackValue() {\n\t\treturn null;\n\t}\n\treturn fallbackValue;\n}\n/**\n* Like lookupGetter, but for accessor properties only, and returns null\n* instead of a null-returning fallback when no getter exists on the chain.\n* Lets a caller fall back to a direct property read in environments that\n* lack the getter, where a fallback returning null would be indistinguishable\n* from a legitimate null value (e.g. namespaceURI of a no-namespace element).\n*\n* @param object - The object (usually a prototype) to start the lookup at.\n* @param prop - The accessor property name.\n* @returns The unapplied getter, or null if none was found.\n*/\nfunction lookupAccessor(object, prop) {\n\twhile (object !== null) {\n\t\tconst desc = getOwnPropertyDescriptor(object, prop);\n\t\tif (desc) return desc.get ? unapply(desc.get) : null;\n\t\tobject = getPrototypeOf(object);\n\t}\n\treturn null;\n}\nfunction isRegex(value) {\n\tif (!value) return false;\n\ttry {\n\t\tregExpTest(value, \"\");\n\t\treturn true;\n\t} catch (_unused) {\n\t\treturn false;\n\t}\n}\nconst html$1 = freeze([\n\t\"a\",\n\t\"abbr\",\n\t\"acronym\",\n\t\"address\",\n\t\"area\",\n\t\"article\",\n\t\"aside\",\n\t\"audio\",\n\t\"b\",\n\t\"bdi\",\n\t\"bdo\",\n\t\"big\",\n\t\"blink\",\n\t\"blockquote\",\n\t\"body\",\n\t\"br\",\n\t\"button\",\n\t\"canvas\",\n\t\"caption\",\n\t\"center\",\n\t\"cite\",\n\t\"code\",\n\t\"col\",\n\t\"colgroup\",\n\t\"content\",\n\t\"data\",\n\t\"datalist\",\n\t\"dd\",\n\t\"decorator\",\n\t\"del\",\n\t\"details\",\n\t\"dfn\",\n\t\"dialog\",\n\t\"dir\",\n\t\"div\",\n\t\"dl\",\n\t\"dt\",\n\t\"element\",\n\t\"em\",\n\t\"fieldset\",\n\t\"figcaption\",\n\t\"figure\",\n\t\"font\",\n\t\"footer\",\n\t\"form\",\n\t\"h1\",\n\t\"h2\",\n\t\"h3\",\n\t\"h4\",\n\t\"h5\",\n\t\"h6\",\n\t\"head\",\n\t\"header\",\n\t\"hgroup\",\n\t\"hr\",\n\t\"html\",\n\t\"i\",\n\t\"img\",\n\t\"input\",\n\t\"ins\",\n\t\"kbd\",\n\t\"label\",\n\t\"legend\",\n\t\"li\",\n\t\"main\",\n\t\"map\",\n\t\"mark\",\n\t\"marquee\",\n\t\"menu\",\n\t\"menuitem\",\n\t\"meter\",\n\t\"nav\",\n\t\"nobr\",\n\t\"ol\",\n\t\"optgroup\",\n\t\"option\",\n\t\"output\",\n\t\"p\",\n\t\"picture\",\n\t\"pre\",\n\t\"progress\",\n\t\"q\",\n\t\"rp\",\n\t\"rt\",\n\t\"ruby\",\n\t\"s\",\n\t\"samp\",\n\t\"search\",\n\t\"section\",\n\t\"select\",\n\t\"shadow\",\n\t\"slot\",\n\t\"small\",\n\t\"source\",\n\t\"spacer\",\n\t\"span\",\n\t\"strike\",\n\t\"strong\",\n\t\"style\",\n\t\"sub\",\n\t\"summary\",\n\t\"sup\",\n\t\"table\",\n\t\"tbody\",\n\t\"td\",\n\t\"template\",\n\t\"textarea\",\n\t\"tfoot\",\n\t\"th\",\n\t\"thead\",\n\t\"time\",\n\t\"tr\",\n\t\"track\",\n\t\"tt\",\n\t\"u\",\n\t\"ul\",\n\t\"var\",\n\t\"video\",\n\t\"wbr\"\n]);\nconst svg$1 = freeze([\n\t\"svg\",\n\t\"a\",\n\t\"altglyph\",\n\t\"altglyphdef\",\n\t\"altglyphitem\",\n\t\"animatecolor\",\n\t\"animatemotion\",\n\t\"animatetransform\",\n\t\"circle\",\n\t\"clippath\",\n\t\"defs\",\n\t\"desc\",\n\t\"ellipse\",\n\t\"filter\",\n\t\"font\",\n\t\"g\",\n\t\"glyph\",\n\t\"glyphref\",\n\t\"hkern\",\n\t\"image\",\n\t\"line\",\n\t\"lineargradient\",\n\t\"marker\",\n\t\"mask\",\n\t\"metadata\",\n\t\"mpath\",\n\t\"path\",\n\t\"pattern\",\n\t\"polygon\",\n\t\"polyline\",\n\t\"radialgradient\",\n\t\"rect\",\n\t\"stop\",\n\t\"style\",\n\t\"switch\",\n\t\"symbol\",\n\t\"text\",\n\t\"textpath\",\n\t\"title\",\n\t\"tref\",\n\t\"tspan\",\n\t\"view\",\n\t\"vkern\"\n]);\nconst svgFilters = freeze([\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]);\nconst svgDisallowed = freeze([\n\t\"animate\",\n\t\"color-profile\",\n\t\"cursor\",\n\t\"discard\",\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\"hatch\",\n\t\"hatchpath\",\n\t\"mesh\",\n\t\"meshgradient\",\n\t\"meshpatch\",\n\t\"meshrow\",\n\t\"missing-glyph\",\n\t\"script\",\n\t\"set\",\n\t\"solidcolor\",\n\t\"unknown\",\n\t\"use\"\n]);\nconst mathMl$1 = freeze([\n\t\"math\",\n\t\"menclose\",\n\t\"merror\",\n\t\"mfenced\",\n\t\"mfrac\",\n\t\"mglyph\",\n\t\"mi\",\n\t\"mlabeledtr\",\n\t\"mmultiscripts\",\n\t\"mn\",\n\t\"mo\",\n\t\"mover\",\n\t\"mpadded\",\n\t\"mphantom\",\n\t\"mroot\",\n\t\"mrow\",\n\t\"ms\",\n\t\"mspace\",\n\t\"msqrt\",\n\t\"mstyle\",\n\t\"msub\",\n\t\"msup\",\n\t\"msubsup\",\n\t\"mtable\",\n\t\"mtd\",\n\t\"mtext\",\n\t\"mtr\",\n\t\"munder\",\n\t\"munderover\",\n\t\"mprescripts\"\n]);\nconst mathMlDisallowed = freeze([\n\t\"maction\",\n\t\"maligngroup\",\n\t\"malignmark\",\n\t\"mlongdiv\",\n\t\"mscarries\",\n\t\"mscarry\",\n\t\"msgroup\",\n\t\"mstack\",\n\t\"msline\",\n\t\"msrow\",\n\t\"semantics\",\n\t\"annotation\",\n\t\"annotation-xml\",\n\t\"mprescripts\",\n\t\"none\"\n]);\nconst text = freeze([\"#text\"]);\nconst html = freeze([\n\t\"accept\",\n\t\"action\",\n\t\"align\",\n\t\"alt\",\n\t\"autocapitalize\",\n\t\"autocomplete\",\n\t\"autopictureinpicture\",\n\t\"autoplay\",\n\t\"background\",\n\t\"bgcolor\",\n\t\"border\",\n\t\"capture\",\n\t\"cellpadding\",\n\t\"cellspacing\",\n\t\"checked\",\n\t\"cite\",\n\t\"class\",\n\t\"clear\",\n\t\"color\",\n\t\"cols\",\n\t\"colspan\",\n\t\"command\",\n\t\"commandfor\",\n\t\"controls\",\n\t\"controlslist\",\n\t\"coords\",\n\t\"crossorigin\",\n\t\"datetime\",\n\t\"decoding\",\n\t\"default\",\n\t\"dir\",\n\t\"disabled\",\n\t\"disablepictureinpicture\",\n\t\"disableremoteplayback\",\n\t\"download\",\n\t\"draggable\",\n\t\"enctype\",\n\t\"enterkeyhint\",\n\t\"exportparts\",\n\t\"face\",\n\t\"for\",\n\t\"headers\",\n\t\"height\",\n\t\"hidden\",\n\t\"high\",\n\t\"href\",\n\t\"hreflang\",\n\t\"id\",\n\t\"inert\",\n\t\"inputmode\",\n\t\"integrity\",\n\t\"ismap\",\n\t\"kind\",\n\t\"label\",\n\t\"lang\",\n\t\"list\",\n\t\"loading\",\n\t\"loop\",\n\t\"low\",\n\t\"max\",\n\t\"maxlength\",\n\t\"media\",\n\t\"method\",\n\t\"min\",\n\t\"minlength\",\n\t\"multiple\",\n\t\"muted\",\n\t\"name\",\n\t\"nonce\",\n\t\"noshade\",\n\t\"novalidate\",\n\t\"nowrap\",\n\t\"open\",\n\t\"optimum\",\n\t\"part\",\n\t\"pattern\",\n\t\"placeholder\",\n\t\"playsinline\",\n\t\"popover\",\n\t\"popovertarget\",\n\t\"popovertargetaction\",\n\t\"poster\",\n\t\"preload\",\n\t\"pubdate\",\n\t\"radiogroup\",\n\t\"readonly\",\n\t\"rel\",\n\t\"required\",\n\t\"rev\",\n\t\"reversed\",\n\t\"role\",\n\t\"rows\",\n\t\"rowspan\",\n\t\"spellcheck\",\n\t\"scope\",\n\t\"selected\",\n\t\"shape\",\n\t\"size\",\n\t\"sizes\",\n\t\"slot\",\n\t\"span\",\n\t\"srclang\",\n\t\"start\",\n\t\"src\",\n\t\"srcset\",\n\t\"step\",\n\t\"style\",\n\t\"summary\",\n\t\"tabindex\",\n\t\"title\",\n\t\"translate\",\n\t\"type\",\n\t\"usemap\",\n\t\"valign\",\n\t\"value\",\n\t\"width\",\n\t\"wrap\",\n\t\"xmlns\"\n]);\nconst svg = freeze([\n\t\"accent-height\",\n\t\"accumulate\",\n\t\"additive\",\n\t\"alignment-baseline\",\n\t\"amplitude\",\n\t\"ascent\",\n\t\"attributename\",\n\t\"attributetype\",\n\t\"azimuth\",\n\t\"basefrequency\",\n\t\"baseline-shift\",\n\t\"begin\",\n\t\"bias\",\n\t\"by\",\n\t\"class\",\n\t\"clip\",\n\t\"clippathunits\",\n\t\"clip-path\",\n\t\"clip-rule\",\n\t\"color\",\n\t\"color-interpolation\",\n\t\"color-interpolation-filters\",\n\t\"color-profile\",\n\t\"color-rendering\",\n\t\"cx\",\n\t\"cy\",\n\t\"d\",\n\t\"dx\",\n\t\"dy\",\n\t\"diffuseconstant\",\n\t\"direction\",\n\t\"display\",\n\t\"divisor\",\n\t\"dominant-baseline\",\n\t\"dur\",\n\t\"edgemode\",\n\t\"elevation\",\n\t\"end\",\n\t\"exponent\",\n\t\"fill\",\n\t\"fill-opacity\",\n\t\"fill-rule\",\n\t\"filter\",\n\t\"filterunits\",\n\t\"flood-color\",\n\t\"flood-opacity\",\n\t\"font-family\",\n\t\"font-size\",\n\t\"font-size-adjust\",\n\t\"font-stretch\",\n\t\"font-style\",\n\t\"font-variant\",\n\t\"font-weight\",\n\t\"fx\",\n\t\"fy\",\n\t\"g1\",\n\t\"g2\",\n\t\"glyph-name\",\n\t\"glyphref\",\n\t\"gradientunits\",\n\t\"gradienttransform\",\n\t\"height\",\n\t\"href\",\n\t\"id\",\n\t\"image-rendering\",\n\t\"in\",\n\t\"in2\",\n\t\"intercept\",\n\t\"k\",\n\t\"k1\",\n\t\"k2\",\n\t\"k3\",\n\t\"k4\",\n\t\"kerning\",\n\t\"keypoints\",\n\t\"keysplines\",\n\t\"keytimes\",\n\t\"lang\",\n\t\"lengthadjust\",\n\t\"letter-spacing\",\n\t\"kernelmatrix\",\n\t\"kernelunitlength\",\n\t\"lighting-color\",\n\t\"local\",\n\t\"marker-end\",\n\t\"marker-mid\",\n\t\"marker-start\",\n\t\"markerheight\",\n\t\"markerunits\",\n\t\"markerwidth\",\n\t\"maskcontentunits\",\n\t\"maskunits\",\n\t\"max\",\n\t\"mask\",\n\t\"mask-type\",\n\t\"media\",\n\t\"method\",\n\t\"mode\",\n\t\"min\",\n\t\"name\",\n\t\"numoctaves\",\n\t\"offset\",\n\t\"operator\",\n\t\"opacity\",\n\t\"order\",\n\t\"orient\",\n\t\"orientation\",\n\t\"origin\",\n\t\"overflow\",\n\t\"paint-order\",\n\t\"path\",\n\t\"pathlength\",\n\t\"patterncontentunits\",\n\t\"patterntransform\",\n\t\"patternunits\",\n\t\"pointer-events\",\n\t\"points\",\n\t\"preservealpha\",\n\t\"preserveaspectratio\",\n\t\"primitiveunits\",\n\t\"r\",\n\t\"rx\",\n\t\"ry\",\n\t\"radius\",\n\t\"refx\",\n\t\"refy\",\n\t\"repeatcount\",\n\t\"repeatdur\",\n\t\"restart\",\n\t\"result\",\n\t\"rotate\",\n\t\"scale\",\n\t\"seed\",\n\t\"shape-rendering\",\n\t\"slope\",\n\t\"specularconstant\",\n\t\"specularexponent\",\n\t\"spreadmethod\",\n\t\"startoffset\",\n\t\"stddeviation\",\n\t\"stitchtiles\",\n\t\"stop-color\",\n\t\"stop-opacity\",\n\t\"stroke-dasharray\",\n\t\"stroke-dashoffset\",\n\t\"stroke-linecap\",\n\t\"stroke-linejoin\",\n\t\"stroke-miterlimit\",\n\t\"stroke-opacity\",\n\t\"stroke\",\n\t\"stroke-width\",\n\t\"style\",\n\t\"surfacescale\",\n\t\"systemlanguage\",\n\t\"tabindex\",\n\t\"tablevalues\",\n\t\"targetx\",\n\t\"targety\",\n\t\"transform\",\n\t\"transform-origin\",\n\t\"text-anchor\",\n\t\"text-decoration\",\n\t\"text-orientation\",\n\t\"text-rendering\",\n\t\"textlength\",\n\t\"type\",\n\t\"u1\",\n\t\"u2\",\n\t\"unicode\",\n\t\"values\",\n\t\"vector-effect\",\n\t\"viewbox\",\n\t\"visibility\",\n\t\"version\",\n\t\"vert-adv-y\",\n\t\"vert-origin-x\",\n\t\"vert-origin-y\",\n\t\"width\",\n\t\"word-spacing\",\n\t\"wrap\",\n\t\"writing-mode\",\n\t\"xchannelselector\",\n\t\"ychannelselector\",\n\t\"x\",\n\t\"x1\",\n\t\"x2\",\n\t\"xmlns\",\n\t\"y\",\n\t\"y1\",\n\t\"y2\",\n\t\"z\",\n\t\"zoomandpan\"\n]);\nconst mathMl = freeze([\n\t\"accent\",\n\t\"accentunder\",\n\t\"align\",\n\t\"bevelled\",\n\t\"close\",\n\t\"columnalign\",\n\t\"columnlines\",\n\t\"columnspacing\",\n\t\"columnspan\",\n\t\"denomalign\",\n\t\"depth\",\n\t\"dir\",\n\t\"display\",\n\t\"displaystyle\",\n\t\"encoding\",\n\t\"fence\",\n\t\"frame\",\n\t\"height\",\n\t\"href\",\n\t\"id\",\n\t\"largeop\",\n\t\"length\",\n\t\"linethickness\",\n\t\"lquote\",\n\t\"lspace\",\n\t\"mathbackground\",\n\t\"mathcolor\",\n\t\"mathsize\",\n\t\"mathvariant\",\n\t\"maxsize\",\n\t\"minsize\",\n\t\"movablelimits\",\n\t\"notation\",\n\t\"numalign\",\n\t\"open\",\n\t\"rowalign\",\n\t\"rowlines\",\n\t\"rowspacing\",\n\t\"rowspan\",\n\t\"rspace\",\n\t\"rquote\",\n\t\"scriptlevel\",\n\t\"scriptminsize\",\n\t\"scriptsizemultiplier\",\n\t\"selection\",\n\t\"separator\",\n\t\"separators\",\n\t\"stretchy\",\n\t\"subscriptshift\",\n\t\"supscriptshift\",\n\t\"symmetric\",\n\t\"voffset\",\n\t\"width\",\n\t\"xmlns\"\n]);\nconst xml = freeze([\n\t\"xlink:href\",\n\t\"xml:id\",\n\t\"xlink:title\",\n\t\"xml:space\",\n\t\"xmlns:xlink\"\n]);\nconst MUSTACHE_EXPR = seal(/{{[\\w\\W]*|^[\\w\\W]*}}/g);\nconst ERB_EXPR = seal(/<%[\\w\\W]*|^[\\w\\W]*%>/g);\nconst TMPLIT_EXPR = seal(/\\${[\\w\\W]*/g);\nconst TMPL_MARKER_SERIALIZED = seal(/{{|}}|\\${|<%|%>|&lt;%|%&gt;/);\nconst DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/);\nconst ARIA_ATTR = seal(/^aria-[\\-\\w]+$/);\nconst IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i);\nconst IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nconst ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g);\nconst DOCTYPE_NAME = seal(/^html$/i);\nconst CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\nconst ELEMENT_MARKUP_PROBE = seal(/<[/\\w!]/g);\nconst COMMENT_MARKUP_PROBE = seal(/<[/\\w]/g);\nconst FALLBACK_TAG_CLOSE = seal(/<\\/no(script|embed|frames)/i);\nconst SELF_CLOSING_TAG = seal(/\\/>/i);\nconst ATTR_VALUE_BREAKOUT = seal(/((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i);\nconst LEADING_WHITESPACE = seal(/^[\\r\\n\\t ]+/);\nconst NODE_TYPE = {\n\telement: 1,\n\ttext: 3,\n\tprocessingInstruction: 7,\n\tcomment: 8,\n\tdocument: 9,\n\tdocumentFragment: 11\n};\nconst LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, [\n\t\"style\",\n\t\"script\",\n\t\"xmp\",\n\t\"iframe\",\n\t\"noembed\",\n\t\"noframes\",\n\t\"plaintext\",\n\t\"noscript\"\n]));\nconst getGlobal = function getGlobal() {\n\treturn typeof window === \"undefined\" ? null : window;\n};\n/**\n* Creates a no-op policy for internal use only.\n* Don't export this function outside this module!\n* @param trustedTypes The policy factory.\n* @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n* @return The policy created (or null, if Trusted Types\n* are not supported or creating the policy failed).\n*/\nconst _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {\n\tif (typeof trustedTypes !== \"object\" || typeof trustedTypes.createPolicy !== \"function\") return null;\n\tlet suffix = null;\n\tconst ATTR_NAME = \"data-tt-policy-suffix\";\n\tif (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) suffix = purifyHostElement.getAttribute(ATTR_NAME);\n\tconst policyName = \"dompurify\" + (suffix ? \"#\" + suffix : \"\");\n\ttry {\n\t\treturn trustedTypes.createPolicy(policyName, {\n\t\t\tcreateHTML(html) {\n\t\t\t\treturn html;\n\t\t\t},\n\t\t\tcreateScriptURL(scriptUrl) {\n\t\t\t\treturn scriptUrl;\n\t\t\t}\n\t\t});\n\t} catch (_) {\n\t\tconsole.warn(\"TrustedTypes policy \" + policyName + \" could not be created.\");\n\t\treturn null;\n\t}\n};\nconst _createHooksMap = function _createHooksMap() {\n\treturn {\n\t\tafterSanitizeAttributes: [],\n\t\tafterSanitizeElements: [],\n\t\tafterSanitizeShadowDOM: [],\n\t\tbeforeSanitizeAttributes: [],\n\t\tbeforeSanitizeElements: [],\n\t\tbeforeSanitizeShadowDOM: [],\n\t\tuponSanitizeAttribute: [],\n\t\tuponSanitizeElement: [],\n\t\tuponSanitizeShadowNode: []\n\t};\n};\n/**\n* Resolve a set-valued configuration option.\n*\n* @param cfg the cloned, prototype-free configuration object\n* @param key the configuration property to read\n* @param fallback the set to use when the option is absent or not an array\n* @param options case transform, and an optional base set to extend a copy of\n* @returns a fresh set built from cfg[key], or the fallback\n*/\nconst _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {\n\treturn objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? cloneSet(options.base) : {}, cfg[key], options.transform) : fallback;\n};\n/**\n* Resolve an object-valued configuration option.\n*\n* @param cfg the cloned, prototype-free configuration object\n* @param key the configuration property to read\n* @param fallback the read-only value to use when the option is absent\n* @returns a prototype-free clone of cfg[key], or the fallback\n*/\nconst _resolveObjectOption = function _resolveObjectOption(cfg, key, fallback) {\n\tconst value = objectHasOwnProperty(cfg, key) ? cfg[key] : void 0;\n\treturn value && typeof value === \"object\" ? clone(value) : fallback;\n};\nfunction createDOMPurify() {\n\tlet window = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();\n\tconst DOMPurify = (root) => createDOMPurify(root);\n\tDOMPurify.version = \"3.4.18\";\n\tDOMPurify.removed = [];\n\tif (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {\n\t\tDOMPurify.isSupported = false;\n\t\treturn DOMPurify;\n\t}\n\tlet document = window.document;\n\tconst originalDocument = document;\n\tconst currentScript = originalDocument.currentScript;\n\tconst HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter, DOMParser = window.DOMParser, trustedTypes = window.trustedTypes;\n\tconst ElementPrototype = Element.prototype;\n\tconst cloneNode = lookupGetter(ElementPrototype, \"cloneNode\");\n\tconst remove = lookupGetter(ElementPrototype, \"remove\");\n\tconst removeAttributeNode = lookupGetter(ElementPrototype, \"removeAttributeNode\");\n\tconst getNextSibling = lookupGetter(ElementPrototype, \"nextSibling\");\n\tconst getChildNodes = lookupGetter(ElementPrototype, \"childNodes\");\n\tconst getParentNode = lookupGetter(ElementPrototype, \"parentNode\");\n\tconst getShadowRoot = lookupGetter(ElementPrototype, \"shadowRoot\");\n\tconst getAttributes = lookupGetter(ElementPrototype, \"attributes\");\n\tconst getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, \"nodeType\") : null;\n\tconst getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, \"nodeName\") : null;\n\tconst getOwnerDocument = Node && Node.prototype ? lookupGetter(Node.prototype, \"ownerDocument\") : null;\n\tconst _readNodeType = function _readNodeType(node) {\n\t\treturn getNodeType ? getNodeType(node) : node.nodeType;\n\t};\n\tconst _readNodeName = function _readNodeName(node) {\n\t\treturn getNodeName ? getNodeName(node) : node.nodeName;\n\t};\n\tconst getNamespaceURI = lookupAccessor(ElementPrototype, \"namespaceURI\");\n\tconst _readNamespaceURI = function _readNamespaceURI(element) {\n\t\treturn getNamespaceURI ? getNamespaceURI(element) : element.namespaceURI;\n\t};\n\tif (typeof HTMLTemplateElement === \"function\") {\n\t\tconst template = document.createElement(\"template\");\n\t\tif (template.content && template.content.ownerDocument) document = template.content.ownerDocument;\n\t}\n\tlet trustedTypesPolicy;\n\tlet emptyHTML = \"\";\n\tlet defaultTrustedTypesPolicy;\n\tlet defaultTrustedTypesPolicyResolved = false;\n\tlet IN_TRUSTED_TYPES_POLICY = 0;\n\tconst _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {\n\t\tif (IN_TRUSTED_TYPES_POLICY > 0) throw typeErrorCreate(\"A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the \\\"DOMPurify and Trusted Types\\\" section of the README.\");\n\t};\n\tconst _createTrustedHTML = function _createTrustedHTML(html) {\n\t\t_assertNotInTrustedTypesPolicy();\n\t\tIN_TRUSTED_TYPES_POLICY++;\n\t\ttry {\n\t\t\treturn trustedTypesPolicy.createHTML(html);\n\t\t} finally {\n\t\t\tIN_TRUSTED_TYPES_POLICY--;\n\t\t}\n\t};\n\tconst _signOutput = function _signOutput(html) {\n\t\treturn trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(html) : html;\n\t};\n\tconst _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {\n\t\t_assertNotInTrustedTypesPolicy();\n\t\tIN_TRUSTED_TYPES_POLICY++;\n\t\ttry {\n\t\t\treturn trustedTypesPolicy.createScriptURL(scriptUrl);\n\t\t} finally {\n\t\t\tIN_TRUSTED_TYPES_POLICY--;\n\t\t}\n\t};\n\tconst _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {\n\t\tif (!defaultTrustedTypesPolicyResolved) {\n\t\t\tdefaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);\n\t\t\tdefaultTrustedTypesPolicyResolved = true;\n\t\t}\n\t\treturn defaultTrustedTypesPolicy;\n\t};\n\tconst _document = document, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName;\n\tconst importNode = originalDocument.importNode;\n\tlet hooks = _createHooksMap();\n\t/**\n\t* Expose whether this browser supports running the full DOMPurify.\n\t*/\n\tDOMPurify.isSupported = typeof entries === \"function\" && typeof getParentNode === \"function\" && implementation && implementation.createHTMLDocument !== void 0;\n\tconst MUSTACHE_EXPR$1 = MUSTACHE_EXPR, ERB_EXPR$1 = ERB_EXPR, TMPLIT_EXPR$1 = TMPLIT_EXPR, DATA_ATTR$1 = DATA_ATTR, ARIA_ATTR$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$1 = ATTR_WHITESPACE, CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;\n\tlet IS_ALLOWED_URI$1 = IS_ALLOWED_URI;\n\t/**\n\t* We consider the elements and attributes below to be safe. Ideally\n\t* don't add any new ones but feel free to remove unwanted ones.\n\t*/\n\tlet ALLOWED_TAGS = null;\n\tconst DEFAULT_ALLOWED_TAGS = addToSet({}, [\n\t\t...html$1,\n\t\t...svg$1,\n\t\t...svgFilters,\n\t\t...mathMl$1,\n\t\t...text\n\t]);\n\tlet ALLOWED_ATTR = null;\n\tconst DEFAULT_ALLOWED_ATTR = addToSet({}, [\n\t\t...html,\n\t\t...svg,\n\t\t...mathMl,\n\t\t...xml\n\t]);\n\tlet CUSTOM_ELEMENT_HANDLING = null;\n\tlet FORBID_TAGS = null;\n\tlet FORBID_ATTR = null;\n\tconst EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {\n\t\ttagCheck: {\n\t\t\twritable: true,\n\t\t\tconfigurable: false,\n\t\t\tenumerable: true,\n\t\t\tvalue: null\n\t\t},\n\t\tattributeCheck: {\n\t\t\twritable: true,\n\t\t\tconfigurable: false,\n\t\t\tenumerable: true,\n\t\t\tvalue: null\n\t\t}\n\t}));\n\tlet ALLOW_ARIA_ATTR = true;\n\tlet ALLOW_DATA_ATTR = true;\n\tlet ALLOW_UNKNOWN_PROTOCOLS = false;\n\tlet ALLOW_SELF_CLOSE_IN_ATTR = true;\n\tlet SAFE_FOR_TEMPLATES = false;\n\tlet SAFE_FOR_XML = true;\n\tlet WHOLE_DOCUMENT = false;\n\tlet SET_CONFIG = false;\n\tlet SET_CONFIG_ALLOWED_TAGS = null;\n\tlet SET_CONFIG_ALLOWED_ATTR = null;\n\tlet FORCE_BODY = false;\n\tlet RETURN_DOM = false;\n\tlet RETURN_DOM_FRAGMENT = false;\n\tlet RETURN_TRUSTED_TYPE = false;\n\tlet SANITIZE_DOM = true;\n\tlet SANITIZE_NAMED_PROPS = false;\n\tconst SANITIZE_NAMED_PROPS_PREFIX = \"user-content-\";\n\tlet KEEP_CONTENT = true;\n\tlet IN_PLACE = false;\n\tlet IN_PLACE_VISITED = null;\n\tlet USE_PROFILES = false;\n\tlet FORBID_CONTENTS = null;\n\tconst DEFAULT_FORBID_CONTENTS = addToSet({}, [\n\t\t\"annotation-xml\",\n\t\t\"audio\",\n\t\t\"colgroup\",\n\t\t\"desc\",\n\t\t\"foreignobject\",\n\t\t\"head\",\n\t\t\"iframe\",\n\t\t\"math\",\n\t\t\"mi\",\n\t\t\"mn\",\n\t\t\"mo\",\n\t\t\"ms\",\n\t\t\"mtext\",\n\t\t\"noembed\",\n\t\t\"noframes\",\n\t\t\"noscript\",\n\t\t\"plaintext\",\n\t\t\"script\",\n\t\t\"selectedcontent\",\n\t\t\"style\",\n\t\t\"svg\",\n\t\t\"template\",\n\t\t\"thead\",\n\t\t\"title\",\n\t\t\"video\",\n\t\t\"xmp\"\n\t]);\n\tlet DATA_URI_TAGS = null;\n\tconst DEFAULT_DATA_URI_TAGS = addToSet({}, [\n\t\t\"audio\",\n\t\t\"video\",\n\t\t\"img\",\n\t\t\"source\",\n\t\t\"image\",\n\t\t\"track\"\n\t]);\n\tlet URI_SAFE_ATTRIBUTES = null;\n\tconst DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [\n\t\t\"alt\",\n\t\t\"class\",\n\t\t\"for\",\n\t\t\"id\",\n\t\t\"label\",\n\t\t\"name\",\n\t\t\"pattern\",\n\t\t\"placeholder\",\n\t\t\"role\",\n\t\t\"summary\",\n\t\t\"title\",\n\t\t\"value\",\n\t\t\"style\",\n\t\t\"xmlns\"\n\t]);\n\tconst MATHML_NAMESPACE = \"http://www.w3.org/1998/Math/MathML\";\n\tconst SVG_NAMESPACE = \"http://www.w3.org/2000/svg\";\n\tconst HTML_NAMESPACE = \"http://www.w3.org/1999/xhtml\";\n\tlet NAMESPACE = HTML_NAMESPACE;\n\tlet IS_EMPTY_INPUT = false;\n\tlet ALLOWED_NAMESPACES = null;\n\tconst DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [\n\t\tMATHML_NAMESPACE,\n\t\tSVG_NAMESPACE,\n\t\tHTML_NAMESPACE\n\t], stringToString);\n\tconst DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(addToSet({}, [\n\t\t\"mi\",\n\t\t\"mo\",\n\t\t\"mn\",\n\t\t\"ms\",\n\t\t\"mtext\"\n\t]));\n\tlet MATHML_TEXT_INTEGRATION_POINTS = null;\n\tconst DEFAULT_HTML_INTEGRATION_POINTS = freeze(addToSet({}, [\"annotation-xml\"]));\n\tlet HTML_INTEGRATION_POINTS = null;\n\tconst DEFAULT_CUSTOM_ELEMENT_HANDLING = freeze(create(null));\n\tconst COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [\n\t\t\"title\",\n\t\t\"style\",\n\t\t\"font\",\n\t\t\"a\",\n\t\t\"script\"\n\t]);\n\tlet PARSER_MEDIA_TYPE = null;\n\tconst SUPPORTED_PARSER_MEDIA_TYPES = [\"application/xhtml+xml\", \"text/html\"];\n\tconst DEFAULT_PARSER_MEDIA_TYPE = \"text/html\";\n\tlet transformCaseFunc = null;\n\tlet CONFIG = null;\n\tconst formElement = document.createElement(\"form\");\n\tconst isRegexOrFunction = function isRegexOrFunction(testValue) {\n\t\treturn testValue instanceof RegExp || testValue instanceof Function;\n\t};\n\t/**\n\t* _parseConfig\n\t*\n\t* @param cfg optional config literal\n\t*/\n\tconst _parseConfig = function _parseConfig() {\n\t\tlet cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};\n\t\tif (!cfg || typeof cfg !== \"object\") cfg = {};\n\t\tcfg = clone(cfg);\n\t\tPARSER_MEDIA_TYPE = SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;\n\t\ttransformCaseFunc = PARSER_MEDIA_TYPE === \"application/xhtml+xml\" ? stringToString : stringToLowerCase;\n\t\tALLOWED_TAGS = _resolveSetOption(cfg, \"ALLOWED_TAGS\", DEFAULT_ALLOWED_TAGS, { transform: transformCaseFunc });\n\t\tALLOWED_ATTR = _resolveSetOption(cfg, \"ALLOWED_ATTR\", DEFAULT_ALLOWED_ATTR, { transform: transformCaseFunc });\n\t\tALLOWED_NAMESPACES = _resolveSetOption(cfg, \"ALLOWED_NAMESPACES\", DEFAULT_ALLOWED_NAMESPACES, { transform: stringToString });\n\t\tURI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, \"ADD_URI_SAFE_ATTR\", DEFAULT_URI_SAFE_ATTRIBUTES, {\n\t\t\ttransform: transformCaseFunc,\n\t\t\tbase: DEFAULT_URI_SAFE_ATTRIBUTES\n\t\t});\n\t\tDATA_URI_TAGS = _resolveSetOption(cfg, \"ADD_DATA_URI_TAGS\", DEFAULT_DATA_URI_TAGS, {\n\t\t\ttransform: transformCaseFunc,\n\t\t\tbase: DEFAULT_DATA_URI_TAGS\n\t\t});\n\t\tFORBID_CONTENTS = _resolveSetOption(cfg, \"FORBID_CONTENTS\", DEFAULT_FORBID_CONTENTS, { transform: transformCaseFunc });\n\t\tFORBID_TAGS = _resolveSetOption(cfg, \"FORBID_TAGS\", create(null), { transform: transformCaseFunc });\n\t\tFORBID_ATTR = _resolveSetOption(cfg, \"FORBID_ATTR\", create(null), { transform: transformCaseFunc });\n\t\tUSE_PROFILES = objectHasOwnProperty(cfg, \"USE_PROFILES\") ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === \"object\" ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;\n\t\tALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;\n\t\tALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;\n\t\tALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;\n\t\tALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false;\n\t\tSAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;\n\t\tSAFE_FOR_XML = cfg.SAFE_FOR_XML !== false;\n\t\tWHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;\n\t\tRETURN_DOM = cfg.RETURN_DOM || false;\n\t\tRETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;\n\t\tRETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;\n\t\tFORCE_BODY = cfg.FORCE_BODY || false;\n\t\tSANITIZE_DOM = cfg.SANITIZE_DOM !== false;\n\t\tSANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false;\n\t\tKEEP_CONTENT = cfg.KEEP_CONTENT !== false;\n\t\tIN_PLACE = cfg.IN_PLACE || false;\n\t\tIS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI;\n\t\tNAMESPACE = typeof cfg.NAMESPACE === \"string\" ? cfg.NAMESPACE : HTML_NAMESPACE;\n\t\tMATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(cfg, \"MATHML_TEXT_INTEGRATION_POINTS\", DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);\n\t\tHTML_INTEGRATION_POINTS = _resolveObjectOption(cfg, \"HTML_INTEGRATION_POINTS\", DEFAULT_HTML_INTEGRATION_POINTS);\n\t\tconst customElementHandling = _resolveObjectOption(cfg, \"CUSTOM_ELEMENT_HANDLING\", DEFAULT_CUSTOM_ELEMENT_HANDLING);\n\t\tCUSTOM_ELEMENT_HANDLING = create(null);\n\t\tif (objectHasOwnProperty(customElementHandling, \"tagNameCheck\") && isRegexOrFunction(customElementHandling.tagNameCheck)) CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck;\n\t\tif (objectHasOwnProperty(customElementHandling, \"attributeNameCheck\") && isRegexOrFunction(customElementHandling.attributeNameCheck)) CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck;\n\t\tif (objectHasOwnProperty(customElementHandling, \"allowCustomizedBuiltInElements\") && typeof customElementHandling.allowCustomizedBuiltInElements === \"boolean\") CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements;\n\t\tseal(CUSTOM_ELEMENT_HANDLING);\n\t\tif (SAFE_FOR_TEMPLATES) ALLOW_DATA_ATTR = false;\n\t\tif (RETURN_DOM_FRAGMENT) RETURN_DOM = true;\n\t\tif (USE_PROFILES) {\n\t\t\tif ((objectHasOwnProperty(cfg, \"ALLOWED_TAGS\") || objectHasOwnProperty(cfg, \"ALLOWED_ATTR\")) && typeof console !== \"undefined\" && typeof console.warn === \"function\") console.warn(\"DOMPurify: USE_PROFILES overrides ALLOWED_TAGS and ALLOWED_ATTR. Do not use these options together.\");\n\t\t\tALLOWED_TAGS = addToSet({}, text);\n\t\t\tALLOWED_ATTR = create(null);\n\t\t\tif (USE_PROFILES.html === true) {\n\t\t\t\taddToSet(ALLOWED_TAGS, html$1);\n\t\t\t\taddToSet(ALLOWED_ATTR, html);\n\t\t\t}\n\t\t\tif (USE_PROFILES.svg === true) {\n\t\t\t\taddToSet(ALLOWED_TAGS, svg$1);\n\t\t\t\taddToSet(ALLOWED_ATTR, svg);\n\t\t\t\taddToSet(ALLOWED_ATTR, xml);\n\t\t\t}\n\t\t\tif (USE_PROFILES.svgFilters === true) {\n\t\t\t\taddToSet(ALLOWED_TAGS, svgFilters);\n\t\t\t\taddToSet(ALLOWED_ATTR, svg);\n\t\t\t\taddToSet(ALLOWED_ATTR, xml);\n\t\t\t}\n\t\t\tif (USE_PROFILES.mathMl === true) {\n\t\t\t\taddToSet(ALLOWED_TAGS, mathMl$1);\n\t\t\t\taddToSet(ALLOWED_ATTR, mathMl);\n\t\t\t\taddToSet(ALLOWED_ATTR, xml);\n\t\t\t}\n\t\t}\n\t\tEXTRA_ELEMENT_HANDLING.tagCheck = null;\n\t\tEXTRA_ELEMENT_HANDLING.attributeCheck = null;\n\t\tif (objectHasOwnProperty(cfg, \"ADD_TAGS\")) {\n\t\t\tif (typeof cfg.ADD_TAGS === \"function\") EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n\t\t\telse if (arrayIsArray(cfg.ADD_TAGS)) {\n\t\t\t\tif (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) ALLOWED_TAGS = cloneSet(ALLOWED_TAGS);\n\t\t\t\taddToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n\t\t\t}\n\t\t}\n\t\tif (objectHasOwnProperty(cfg, \"ADD_ATTR\")) {\n\t\t\tif (typeof cfg.ADD_ATTR === \"function\") EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n\t\t\telse if (arrayIsArray(cfg.ADD_ATTR)) {\n\t\t\t\tif (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) ALLOWED_ATTR = cloneSet(ALLOWED_ATTR);\n\t\t\t\taddToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n\t\t\t}\n\t\t}\n\t\tif (objectHasOwnProperty(cfg, \"ADD_FORBID_CONTENTS\") && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {\n\t\t\tif (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) FORBID_CONTENTS = cloneSet(FORBID_CONTENTS);\n\t\t\taddToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n\t\t}\n\t\tif (KEEP_CONTENT) ALLOWED_TAGS[\"#text\"] = true;\n\t\tif (WHOLE_DOCUMENT) addToSet(ALLOWED_TAGS, [\n\t\t\t\"html\",\n\t\t\t\"head\",\n\t\t\t\"body\"\n\t\t]);\n\t\tif (ALLOWED_TAGS.table) {\n\t\t\tALLOWED_TAGS.tbody = true;\n\t\t\tdelete FORBID_TAGS.tbody;\n\t\t}\n\t\tif (cfg.TRUSTED_TYPES_POLICY) {\n\t\t\tif (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== \"function\") throw typeErrorCreate(\"TRUSTED_TYPES_POLICY configuration option must provide a \\\"createHTML\\\" hook.\");\n\t\t\tif (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== \"function\") throw typeErrorCreate(\"TRUSTED_TYPES_POLICY configuration option must provide a \\\"createScriptURL\\\" hook.\");\n\t\t\tconst previousTrustedTypesPolicy = trustedTypesPolicy;\n\t\t\ttrustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n\t\t\ttry {\n\t\t\t\temptyHTML = _createTrustedHTML(\"\");\n\t\t\t} catch (error) {\n\t\t\t\ttrustedTypesPolicy = previousTrustedTypesPolicy;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} else if (cfg.TRUSTED_TYPES_POLICY === null) {\n\t\t\ttrustedTypesPolicy = void 0;\n\t\t\temptyHTML = \"\";\n\t\t} else {\n\t\t\tif (trustedTypesPolicy === void 0) trustedTypesPolicy = _getDefaultTrustedTypesPolicy();\n\t\t\tif (trustedTypesPolicy && typeof emptyHTML === \"string\") emptyHTML = _createTrustedHTML(\"\");\n\t\t}\n\t\tCONFIG = freeze(cfg);\n\t};\n\tconst ALL_SVG_TAGS = addToSet({}, [\n\t\t...svg$1,\n\t\t...svgFilters,\n\t\t...svgDisallowed\n\t]);\n\tconst ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);\n\t/**\n\t* Namespace rules for an element in the SVG namespace.\n\t*\n\t* @param tagName the element's lowercase tag name\n\t* @param parentNamespace the (possibly simulated) parent's namespace\n\t* @param parentTagName the parent's lowercase tag name\n\t* @returns true if a spec-compliant parser could produce this element\n\t*/\n\tconst _checkSvgNamespace = function _checkSvgNamespace(tagName, parentNamespace, parentTagName) {\n\t\tif (parentNamespace === HTML_NAMESPACE) return tagName === \"svg\";\n\t\tif (parentNamespace === MATHML_NAMESPACE) return tagName === \"svg\" && (parentTagName === \"annotation-xml\" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n\t\treturn Boolean(ALL_SVG_TAGS[tagName]);\n\t};\n\t/**\n\t* Namespace rules for an element in the MathML namespace.\n\t*\n\t* @param tagName the element's lowercase tag name\n\t* @param parentNamespace the (possibly simulated) parent's namespace\n\t* @param parentTagName the parent's lowercase tag name\n\t* @returns true if a spec-compliant parser could produce this element\n\t*/\n\tconst _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parentNamespace, parentTagName) {\n\t\tif (parentNamespace === HTML_NAMESPACE) return tagName === \"math\";\n\t\tif (parentNamespace === SVG_NAMESPACE) return tagName === \"math\" && HTML_INTEGRATION_POINTS[parentTagName];\n\t\treturn Boolean(ALL_MATHML_TAGS[tagName]);\n\t};\n\t/**\n\t* Namespace rules for an element in the HTML namespace.\n\t*\n\t* @param tagName the element's lowercase tag name\n\t* @param parentNamespace the (possibly simulated) parent's namespace\n\t* @param parentTagName the parent's lowercase tag name\n\t* @returns true if a spec-compliant parser could produce this element\n\t*/\n\tconst _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parentNamespace, parentTagName) {\n\t\tif (parentNamespace === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) return false;\n\t\tif (parentNamespace === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) return false;\n\t\treturn !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);\n\t};\n\t/**\n\t* @param element a DOM element whose namespace is being checked\n\t* @returns Return false if the element has a\n\t*  namespace that a spec-compliant parser would never\n\t*  return. Return true otherwise.\n\t*/\n\tconst _checkValidNamespace = function _checkValidNamespace(element) {\n\t\tconst elementNamespace = _readNamespaceURI(element);\n\t\tconst tagName = stringToLowerCase(_readNodeName(element));\n\t\tconst parentNode = getParentNode(element);\n\t\tlet parentNamespace = NAMESPACE;\n\t\tlet parentTagName = \"template\";\n\t\tif (parentNode && _readNodeType(parentNode) === NODE_TYPE.element) {\n\t\t\tparentNamespace = _readNamespaceURI(parentNode);\n\t\t\tparentTagName = stringToLowerCase(_readNodeName(parentNode));\n\t\t}\n\t\tif (!ALLOWED_NAMESPACES[elementNamespace]) return false;\n\t\tif (elementNamespace === SVG_NAMESPACE) return _checkSvgNamespace(tagName, parentNamespace, parentTagName);\n\t\tif (elementNamespace === MATHML_NAMESPACE) return _checkMathMlNamespace(tagName, parentNamespace, parentTagName);\n\t\tif (elementNamespace === HTML_NAMESPACE) return _checkHtmlNamespace(tagName, parentNamespace, parentTagName);\n\t\treturn PARSER_MEDIA_TYPE === \"application/xhtml+xml\";\n\t};\n\t/**\n\t* _forceRemove\n\t*\n\t* @param node a DOM node\n\t*/\n\tconst _forceRemove = function _forceRemove(node) {\n\t\tarrayPush(DOMPurify.removed, { element: node });\n\t\ttry {\n\t\t\tgetParentNode(node).removeChild(node);\n\t\t} catch (_) {\n\t\t\tremove(node);\n\t\t\tif (!getParentNode(node)) throw typeErrorCreate(\"a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place\");\n\t\t}\n\t};\n\t/**\n\t* Removes an Attr node as that exact node, without book-keeping. Name-based\n\t* removal lowercases the name in HTML documents and would miss a\n\t* case-preserved one such as `ONERROR`, so it is only the fallback for\n\t* clobbered or detached nodes.\n\t*\n\t* @param element the element to strip the attribute from\n\t* @param attribute the Attr node to remove\n\t* @param name the attribute's name, for the fallback path\n\t*/\n\tconst _stripAttributeNode = function _stripAttributeNode(element, attribute, name) {\n\t\ttry {\n\t\t\tremoveAttributeNode(element, attribute);\n\t\t} catch (_) {\n\t\t\ttry {\n\t\t\t\telement.removeAttribute(name);\n\t\t\t} catch (_) {}\n\t\t}\n\t};\n\t/**\n\t* Fail-closed teardown of an in-place root: strip every disallowed attribute\n\t* in the subtree first, so nothing armed is left behind, then remove all\n\t* children and the root's own attributes.\n\t*\n\t* @param root the in-place root to empty\n\t*/\n\tconst _neutralizeRoot = function _neutralizeRoot(root) {\n\t\t_neutralizeSubtree(root);\n\t\tconst childNodes = getChildNodes(root);\n\t\tif (childNodes) arrayForEach(arraySlice(childNodes), (child) => {\n\t\t\ttry {\n\t\t\t\tremove(child);\n\t\t\t} catch (_) {}\n\t\t});\n\t\tif (_readNodeType(root) === NODE_TYPE.element) _stripAttributes(root, false);\n\t};\n\t/**\n\t* Removes an attribute, preferably as its exact Attr node: name-based\n\t* removal lowercases the name in HTML documents and misses case-preserved\n\t* names, e.g. from imported XHTML.\n\t*\n\t* @param name an Attribute name\n\t* @param element a DOM node\n\t* @param attr the exact Attr node to remove, when the caller has it\n\t*/\n\tconst _removeAttribute = function _removeAttribute(name, element, attr) {\n\t\tif (!attr) try {\n\t\t\tattr = element.getAttributeNode(name);\n\t\t} catch (_) {\n\t\t\tattr = null;\n\t\t}\n\t\tarrayPush(DOMPurify.removed, {\n\t\t\tattribute: attr || null,\n\t\t\tfrom: element\n\t\t});\n\t\tif (attr) _stripAttributeNode(element, attr, name);\n\t\telse try {\n\t\t\telement.removeAttribute(name);\n\t\t} catch (_) {}\n\t\tif (name === \"is\") {\n\t\t\tif (RETURN_DOM || RETURN_DOM_FRAGMENT) try {\n\t\t\t\t_forceRemove(element);\n\t\t\t} catch (_) {}\n\t\t\telse try {\n\t\t\t\telement.setAttribute(name, \"\");\n\t\t\t} catch (_) {}\n\t\t}\n\t};\n\t/**\n\t* Removes an element's attributes without book-keeping. Used to neutralize\n\t* nodes discarded from an in-place tree.\n\t*\n\t* @param element the element to strip\n\t* @param keepAllowed whether attributes on the allowlist stay\n\t*/\n\tconst _stripAttributes = function _stripAttributes(element, keepAllowed) {\n\t\tconst attributes = getAttributes(element);\n\t\tif (!attributes) return;\n\t\tfor (let i = attributes.length - 1; i >= 0; --i) {\n\t\t\tconst attribute = attributes[i];\n\t\t\tconst name = attribute && attribute.name;\n\t\t\tif (typeof name === \"string\" && !(keepAllowed && ALLOWED_ATTR[transformCaseFunc(name)])) _stripAttributeNode(element, attribute, name);\n\t\t}\n\t};\n\t/**\n\t* Iterative depth-first walk, so deep trees cannot overflow the call stack,\n\t* reading through the cached getters, so clobbering cannot hide children.\n\t* When `visit` returns false, the node's children are skipped. With\n\t* `intoShadow`, open shadow roots are walked after their host's children.\n\t*\n\t* @param root where to start\n\t* @param visit called for every node\n\t* @param intoShadow whether to enter open shadow roots\n\t*/\n\tconst _walkTree = function _walkTree(root, visit) {\n\t\tlet intoShadow = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;\n\t\tconst stack = [root];\n\t\twhile (stack.length > 0) {\n\t\t\tconst node = stack.pop();\n\t\t\tif (visit(node) === false) continue;\n\t\t\tif (intoShadow && _readNodeType(node) === NODE_TYPE.element) {\n\t\t\t\tconst shadowRoot = getShadowRoot(node);\n\t\t\t\tif (_isDocumentFragment(shadowRoot)) stack.push(shadowRoot);\n\t\t\t}\n\t\t\tconst childNodes = getChildNodes(node);\n\t\t\tif (childNodes) for (let i = childNodes.length - 1; i >= 0; --i) stack.push(childNodes[i]);\n\t\t}\n\t};\n\t/**\n\t* Strips disallowed attributes from every element of a discarded subtree,\n\t* so a handler that is already queued (a loading image) cannot fire.\n\t*\n\t* @param root the root of a removed subtree\n\t*/\n\tconst _neutralizeSubtree = function _neutralizeSubtree(root) {\n\t\t_walkTree(root, (node) => {\n\t\t\tif (_readNodeType(node) === NODE_TYPE.element) _stripAttributes(node, true);\n\t\t});\n\t};\n\t/**\n\t* All nodes under `root`, root first, including open shadow roots. Template\n\t* content is not entered, it is inert.\n\t*\n\t* @param root the in-place root\n\t* @return the nodes\n\t*/\n\tconst _collectLiveNodes = function _collectLiveNodes(root) {\n\t\tconst nodes = [];\n\t\t_walkTree(root, (node) => {\n\t\t\tnodes.push(node);\n\t\t}, true);\n\t\treturn nodes;\n\t};\n\t/**\n\t* Strips disallowed attributes from every element that was under the\n\t* in-place root when the call started and no longer is, whatever removed\n\t* or moved it.\n\t*\n\t* @param root the in-place root\n\t* @param before the root's nodes, collected before the walk\n\t*/\n\tconst _neutralizeEscapedElements = function _neutralizeEscapedElements(root, before) {\n\t\tconst reachable = setCreate();\n\t\tarrayForEach(_collectLiveNodes(root), (node) => {\n\t\t\tif (_readNodeType(node) === NODE_TYPE.element) setAdd(reachable, node);\n\t\t});\n\t\tarrayForEach(before, (node) => {\n\t\t\tif (_readNodeType(node) === NODE_TYPE.element && !setHas(reachable, node)) _stripAttributes(node, true);\n\t\t});\n\t};\n\t/**\n\t* Neutralizes everything that left the in-place tree during the call: what\n\t* DOMPurify removed, and what hooks or custom elements removed or moved out.\n\t*\n\t* @param root the in-place root\n\t* @param before the root's nodes, collected before the walk\n\t* @return true if the root itself was removed\n\t*/\n\tconst _neutralizeDiscarded = function _neutralizeDiscarded(root, before) {\n\t\tlet rootRemoved = false;\n\t\tarrayForEach(DOMPurify.removed, (entry) => {\n\t\t\tif (entry.element) {\n\t\t\t\trootRemoved = rootRemoved || entry.element === root;\n\t\t\t\t_neutralizeSubtree(entry.element);\n\t\t\t}\n\t\t});\n\t\t_neutralizeEscapedElements(root, before);\n\t\treturn rootRemoved;\n\t};\n\tconst MAX_UNVISITED_ROUNDS = 8;\n\t/**\n\t* The walk only moves forward, so a node moved to a position it already\n\t* passed is never visited. Give every original node that is still in the\n\t* tree but unvisited the normal treatment, hooks included. Nodes created\n\t* during the call are left alone. Fails closed if the tree keeps changing.\n\t*\n\t* @param root the in-place root\n\t* @param before the root's nodes, collected before the walk\n\t*/\n\tconst _sanitizeUnvisitedNodes = function _sanitizeUnvisitedNodes(root, before) {\n\t\tconst visited = IN_PLACE_VISITED;\n\t\tlet original = null;\n\t\tconst getOriginal = () => {\n\t\t\tif (!original) {\n\t\t\t\toriginal = setCreate();\n\t\t\t\tarrayForEach(before, (beforeNode) => {\n\t\t\t\t\tsetAdd(original, beforeNode);\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn original;\n\t\t};\n\t\tfor (let round = 0;; round++) {\n\t\t\tconst live = _collectLiveNodes(root);\n\t\t\tconst containers = [root];\n\t\t\tlet pending = false;\n\t\t\tarrayForEach(live, (node) => {\n\t\t\t\tif (_readNodeType(node) === NODE_TYPE.documentFragment) arrayPush(containers, node);\n\t\t\t\telse if (!pending && !setHas(visited, node)) pending = setHas(getOriginal(), node);\n\t\t\t});\n\t\t\tif (!pending) return;\n\t\t\tif (round >= MAX_UNVISITED_ROUNDS) throw typeErrorCreate(\"the tree kept changing during in-place sanitization; refusing to return it\");\n\t\t\tarrayForEach(containers, (container, index) => {\n\t\t\t\t_sanitizeUnvisitedIn(container, index > 0, root, getOriginal());\n\t\t\t});\n\t\t}\n\t};\n\t/**\n\t* One _sanitizeUnvisitedNodes pass over the root or an open shadow root.\n\t*\n\t* @param container the root or an open shadow root\n\t* @param inShadow whether container is a shadow root\n\t* @param root the in-place root\n\t* @param original the root's nodes collected before the walk, as a set\n\t*/\n\tconst _sanitizeUnvisitedIn = function _sanitizeUnvisitedIn(container, inShadow, root, original) {\n\t\tconst iterator = _createNodeIterator(container);\n\t\tlet node;\n\t\twhile (node = iterator.nextNode()) {\n\t\t\tif (!setHas(original, node) || setHas(IN_PLACE_VISITED, node)) continue;\n\t\t\tif (inShadow) _executeHooks(hooks.uponSanitizeShadowNode, node, null);\n\t\t\t_sanitizeNode(node, root);\n\t\t}\n\t};\n\t/**\n\t* Records that _sanitizeElements processed `node`. No-op outside IN_PLACE.\n\t*\n\t* @param node the node being processed\n\t*/\n\tconst _markVisited = function _markVisited(node) {\n\t\tif (IN_PLACE_VISITED) setAdd(IN_PLACE_VISITED, node);\n\t};\n\t/**\n\t* Patch-linkage attributes (declarative partial updates): `patchsrc`\n\t* always, `for` everywhere except on <label> and <output>. Gated on\n\t* SAFE_FOR_XML. Shared by the IN_PLACE pre-pass and _isValidAttribute.\n\t*\n\t* @param lcName the transformCaseFunc'd attribute name\n\t* @param lcTag the transformCaseFunc'd tag name of the carrying element\n\t* @return true if the attribute is patch linkage and must be dropped\n\t*/\n\tconst _isPatchLinkageAttribute = function _isPatchLinkageAttribute(lcName, lcTag) {\n\t\tif (!SAFE_FOR_XML) return false;\n\t\tif (lcName === \"patchsrc\") return true;\n\t\treturn lcName === \"for\" && lcTag !== \"label\" && lcTag !== \"output\";\n\t};\n\t/**\n\t* IN_PLACE pre-pass: sever all patch linkage before the walk, so no patch\n\t* can fire mid-walk into a part of the tree the walker already passed.\n\t* Removes range markers (processing instructions, comments with markup)\n\t* and strips linkage attributes. It cannot undo a patch that already fired.\n\t*\n\t* TODO: if the shipped feature can patch through `for` on <label>/<output>,\n\t* drop that pair here too.\n\t*\n\t* @param root the in-place root to sweep\n\t*/\n\tconst _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {\n\t\tif (!SAFE_FOR_XML) return;\n\t\t_walkTree(root, (node) => {\n\t\t\tconst nodeType = _readNodeType(node);\n\t\t\tif (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {\n\t\t\t\ttry {\n\t\t\t\t\tremove(node);\n\t\t\t\t} catch (_) {}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (nodeType === NODE_TYPE.element) {\n\t\t\t\tconst element = node;\n\t\t\t\tconst lcTag = transformCaseFunc(_readNodeName(node));\n\t\t\t\ttry {\n\t\t\t\t\tif (element.hasAttribute && element.hasAttribute(\"patchsrc\")) element.removeAttribute(\"patchsrc\");\n\t\t\t\t\tif (element.hasAttribute && element.hasAttribute(\"for\") && _isPatchLinkageAttribute(\"for\", lcTag)) element.removeAttribute(\"for\");\n\t\t\t\t} catch (_) {}\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t};\n\t/**\n\t* _initDocument\n\t*\n\t* @param dirty - a string of dirty markup\n\t* @return a DOM, filled with the dirty markup\n\t*/\n\tconst _initDocument = function _initDocument(dirty) {\n\t\tlet doc = null;\n\t\tlet leadingWhitespace = null;\n\t\tif (FORCE_BODY) dirty = \"<remove></remove>\" + dirty;\n\t\telse {\n\t\t\tconst matches = stringMatch(dirty, LEADING_WHITESPACE);\n\t\t\tleadingWhitespace = matches && matches[0];\n\t\t}\n\t\tif (PARSER_MEDIA_TYPE === \"application/xhtml+xml\" && NAMESPACE === HTML_NAMESPACE) dirty = \"<html xmlns=\\\"http://www.w3.org/1999/xhtml\\\"><head></head><body>\" + dirty + \"</body></html>\";\n\t\tconst dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;\n\t\tif (NAMESPACE === HTML_NAMESPACE) try {\n\t\t\tdoc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n\t\t} catch (_) {}\n\t\tif (!doc || !doc.documentElement) {\n\t\t\tdoc = implementation.createDocument(NAMESPACE, \"template\", null);\n\t\t\ttry {\n\t\t\t\tdoc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;\n\t\t\t} catch (_) {}\n\t\t}\n\t\tconst body = doc.body || doc.documentElement;\n\t\tif (dirty && leadingWhitespace) body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n\t\tif (NAMESPACE === HTML_NAMESPACE) return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? \"html\" : \"body\")[0];\n\t\treturn WHOLE_DOCUMENT ? doc.documentElement : body;\n\t};\n\t/**\n\t* Creates a NodeIterator over `root`. ownerDocument is read through the\n\t* cached getter: a form child named \"ownerDocument\" shadows the direct\n\t* read and would make createNodeIterator throw.\n\t*\n\t* @param root The node to start traversing on.\n\t* @param characterDataOnly whether to skip elements\n\t* @return The created NodeIterator\n\t*/\n\tconst _createNodeIterator = function _createNodeIterator(root) {\n\t\tlet characterDataOnly = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;\n\t\tconst doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;\n\t\treturn createNodeIterator.call(doc || root, root, (characterDataOnly ? 0 : NodeFilter.SHOW_ELEMENT) | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);\n\t};\n\t/**\n\t* Replace template expression syntax (mustache, ERB, template\n\t* literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub\n\t* sites. Order matters: mustache, then ERB, then template literal.\n\t*\n\t* @param value the string to scrub\n\t* @returns the scrubbed string\n\t*/\n\tconst _stripTemplateExpressions = function _stripTemplateExpressions(value) {\n\t\tvalue = stringReplace(value, MUSTACHE_EXPR$1, \" \");\n\t\tvalue = stringReplace(value, ERB_EXPR$1, \" \");\n\t\tvalue = stringReplace(value, TMPLIT_EXPR$1, \" \");\n\t\treturn value;\n\t};\n\t/**\n\t* Strips template expressions from the character data under `node`,\n\t* template contents included. Runs after the walk, since an expression can\n\t* also form when a removed element leaves two text nodes adjacent. Works on\n\t* the nodes rather than on markup, which keeps node references intact and\n\t* sees `<%` unescaped. Attribute values are handled in _sanitizeAttributes.\n\t*\n\t* @param node The root element whose character data should be scrubbed.\n\t*/\n\tconst _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {\n\t\tvar _node$querySelectorAl;\n\t\t_scrubOwnCharacterData(node);\n\t\tconst templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, \"template\");\n\t\tif (templates) arrayForEach(templates, (tmpl) => {\n\t\t\tif (_isDocumentFragment(tmpl.content)) _scrubTemplateExpressions2(tmpl.content);\n\t\t});\n\t};\n\t/**\n\t* Normalizes `node` and strips template expressions from its own character\n\t* data. Template contents and shadow roots are not entered, their own\n\t* _sanitizeShadowDOM call scrubs them.\n\t*\n\t* @param node The root whose own character data should be scrubbed.\n\t*/\n\tconst _scrubOwnCharacterData = function _scrubOwnCharacterData(node) {\n\t\tnode.normalize();\n\t\tconst walker = _createNodeIterator(node, true);\n\t\tlet currentNode = walker.nextNode();\n\t\twhile (currentNode) {\n\t\t\tcurrentNode.data = _stripTemplateExpressions(currentNode.data);\n\t\t\tcurrentNode = walker.nextNode();\n\t\t}\n\t};\n\t/**\n\t* Detects DOM clobbering on a form, the only element whose named children\n\t* shadow its own properties. Each probe compares a direct read with what\n\t* the property has to be.\n\t*\n\t* @param element element to check for clobbering attacks\n\t* @return true if clobbered, false if safe\n\t*/\n\tconst _isClobbered = function _isClobbered(element) {\n\t\tconst realTagName = getNodeName ? getNodeName(element) : null;\n\t\tif (typeof realTagName !== \"string\") return false;\n\t\tif (transformCaseFunc(realTagName) !== \"form\") return false;\n\t\treturn typeof element.nodeName !== \"string\" || typeof element.textContent !== \"string\" || typeof element.removeChild !== \"function\" || element.attributes !== getAttributes(element) || typeof element.removeAttribute !== \"function\" || typeof element.removeAttributeNode !== \"function\" || typeof element.getAttributeNode !== \"function\" || typeof element.setAttribute !== \"function\" || typeof element.namespaceURI !== \"string\" || typeof element.insertBefore !== \"function\" || typeof element.hasChildNodes !== \"function\" || element.nodeType !== getNodeType(element) || element.childNodes !== getChildNodes(element);\n\t};\n\t/**\n\t* Reads nodeType through the cached getter, so the result holds for nodes\n\t* from any realm (GHSA-4w3q-35jp-p934) and cannot be clobbered.\n\t*\n\t* @param value anything\n\t* @return the node type, or null if value is not a DOM node\n\t*/\n\tconst _nodeTypeOf = function _nodeTypeOf(value) {\n\t\tif (!getNodeType || typeof value !== \"object\" || value === null) return null;\n\t\ttry {\n\t\t\tconst nodeType = getNodeType(value);\n\t\t\treturn typeof nodeType === \"number\" ? nodeType : null;\n\t\t} catch (_) {\n\t\t\treturn null;\n\t\t}\n\t};\n\tconst _isDocumentFragment = function _isDocumentFragment(value) {\n\t\treturn _nodeTypeOf(value) === NODE_TYPE.documentFragment;\n\t};\n\tconst _isNode = function _isNode(value) {\n\t\treturn _nodeTypeOf(value) !== null;\n\t};\n\tfunction _executeHooks(hooks, currentNode, data) {\n\t\tif (hooks.length === 0) return;\n\t\tarrayForEach(hooks, (hook) => {\n\t\t\thook.call(DOMPurify, currentNode, data, CONFIG);\n\t\t});\n\t}\n\t/**\n\t* Structural-threat checks that condemn a node regardless of the\n\t* allowlists: mXSS via namespace confusion, risky CSS construction,\n\t* processing instructions, markup-bearing comments. Pure predicate;\n\t* the caller removes. Check order is load-bearing.\n\t*\n\t* @param currentNode the node to inspect\n\t* @param tagName the node's transformCaseFunc'd tag name\n\t* @param nodeType the node's type, read through the cached getter\n\t* @return true if the node must be removed\n\t*/\n\tconst _isUnsafeNode = function _isUnsafeNode(currentNode, tagName, nodeType) {\n\t\tif (SAFE_FOR_XML && nodeType === NODE_TYPE.element && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) return true;\n\t\tif (SAFE_FOR_XML && LITERAL_TEXT_ELEMENTS[tagName] && nodeType === NODE_TYPE.element && _readNamespaceURI(currentNode) === HTML_NAMESPACE && (_isNode(currentNode.firstElementChild) || typeof currentNode.textContent === \"string\" && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent))) return true;\n\t\tif (nodeType === NODE_TYPE.processingInstruction) return true;\n\t\tif (SAFE_FOR_XML && nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) return true;\n\t\treturn false;\n\t};\n\t/**\n\t* Evaluate a CUSTOM_ELEMENT_HANDLING check (a RegExp or a predicate\n\t* function, per the validation in _parseConfig) against a name.\n\t* Additional arguments are forwarded to predicate functions - the\n\t* attributeNameCheck predicate receives the tag name as its second\n\t* argument. A null/absent check never matches.\n\t*\n\t* @param check the configured tagNameCheck / attributeNameCheck value\n\t* @param name the name to test\n\t* @param args extra arguments forwarded to a predicate function\n\t* @return true if the check matches the name\n\t*/\n\tconst _matchesNameCheck = function _matchesNameCheck(check, name) {\n\t\tif (check instanceof RegExp) return regExpTest(check, name);\n\t\tif (check instanceof Function) {\n\t\t\tfor (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) args[_key - 2] = arguments[_key];\n\t\t\treturn Boolean(check(name, ...args));\n\t\t}\n\t\treturn false;\n\t};\n\t/**\n\t* Handles a node whose tag is forbidden or not allowlisted: hoists its\n\t* content per KEEP_CONTENT and removes it. The one exception is a custom\n\t* element allowed via CUSTOM_ELEMENT_HANDLING, which is kept.\n\t*\n\t* @param currentNode the disallowed node\n\t* @param tagName the node's transformCaseFunc'd tag name\n\t* @return true if the node was removed, false if kept\n\t*/\n\tconst _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName, root) {\n\t\tif (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;\n\t\tif (KEEP_CONTENT && !FORBID_CONTENTS[tagName] && !FORBID_CONTENTS[stringToLowerCase(tagName)]) {\n\t\t\tconst parentNode = getParentNode(currentNode);\n\t\t\tconst childNodes = getChildNodes(currentNode);\n\t\t\tif (childNodes && parentNode) {\n\t\t\t\tconst childCount = childNodes.length;\n\t\t\t\tfor (let i = childCount - 1; i >= 0; --i) {\n\t\t\t\t\tconst hoisted = currentNode === root ? cloneNode(childNodes[i], true) : childNodes[i];\n\t\t\t\t\tparentNode.insertBefore(hoisted, getNextSibling(currentNode));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t_forceRemove(currentNode);\n\t\treturn true;\n\t};\n\t/**\n\t* Forks an allowlist off its shared binding (the instance default or the\n\t* setConfig() capture) before a hook sees it, so a hook's widening stays\n\t* within the call. A set that is already call-local is returned as is.\n\t*\n\t* @param hookList the uponSanitize* hook array for this event\n\t* @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding\n\t* @param defaultSet the per-instance DEFAULT_ALLOWED_* constant\n\t* @param setConfigSet the captured setConfig() binding, or null\n\t* @return a call-local clone if a hook is present and set is still shared,\n\t*   else set unchanged\n\t*/\n\tconst _forkSharedAllowlist = function _forkSharedAllowlist(hookList, set, defaultSet, setConfigSet) {\n\t\tif (hookList.length === 0) return set;\n\t\treturn set === defaultSet || set === setConfigSet ? cloneSet(set) : set;\n\t};\n\t/**\n\t* A hook may have detached the node it was called for. If so, treat it as\n\t* removed and stop processing it; the walk root is exempt. On the IN_PLACE\n\t* path the detached subtree is neutralized right away.\n\t*\n\t* @param currentNode the node a hook may have detached\n\t* @param root the current walk root\n\t* @return true if the node was detached\n\t*/\n\tconst _handleHookDetachedNode = function _handleHookDetachedNode(currentNode, root) {\n\t\tif (currentNode === root || getParentNode(currentNode) !== null) return false;\n\t\tif (IN_PLACE) _neutralizeSubtree(currentNode);\n\t\treturn true;\n\t};\n\t/**\n\t* _sanitizeElements\n\t*\n\t* @protect nodeName\n\t* @protect textContent\n\t* @protect removeChild\n\t* @param currentNode to check for permission to exist\n\t* @return true if node was killed, false if left alive\n\t*/\n\tconst _sanitizeElements = function _sanitizeElements(currentNode, root) {\n\t\t_markVisited(currentNode);\n\t\t_executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n\t\tif (_handleHookDetachedNode(currentNode, root)) return true;\n\t\tif (_isClobbered(currentNode)) {\n\t\t\t_forceRemove(currentNode);\n\t\t\treturn true;\n\t\t}\n\t\tconst tagName = transformCaseFunc(_readNodeName(currentNode));\n\t\tconst nodeType = _readNodeType(currentNode);\n\t\tALLOWED_TAGS = _forkSharedAllowlist(hooks.uponSanitizeElement, ALLOWED_TAGS, DEFAULT_ALLOWED_TAGS, SET_CONFIG_ALLOWED_TAGS);\n\t\t_executeHooks(hooks.uponSanitizeElement, currentNode, {\n\t\t\ttagName,\n\t\t\tallowedTags: ALLOWED_TAGS\n\t\t});\n\t\tif (_handleHookDetachedNode(currentNode, root)) return true;\n\t\tif (_isUnsafeNode(currentNode, tagName, nodeType)) {\n\t\t\t_forceRemove(currentNode);\n\t\t\treturn true;\n\t\t}\n\t\tif (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {\n\t\t\tconst removed = _sanitizeDisallowedNode(currentNode, tagName, root);\n\t\t\tif (removed === false) {\n\t\t\t\t_executeHooks(hooks.afterSanitizeElements, currentNode, null);\n\t\t\t\tif (_handleHookDetachedNode(currentNode, root)) return true;\n\t\t\t}\n\t\t\treturn removed;\n\t\t}\n\t\tif (nodeType === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {\n\t\t\t_forceRemove(currentNode);\n\t\t\treturn true;\n\t\t}\n\t\tif ((tagName === \"noscript\" || tagName === \"noembed\" || tagName === \"noframes\") && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {\n\t\t\t_forceRemove(currentNode);\n\t\t\treturn true;\n\t\t}\n\t\tif (SAFE_FOR_TEMPLATES && nodeType === NODE_TYPE.text) {\n\t\t\tconst text = currentNode.textContent;\n\t\t\tconst content = _stripTemplateExpressions(text);\n\t\t\tif (text !== content) {\n\t\t\t\tarrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });\n\t\t\t\tcurrentNode.textContent = content;\n\t\t\t}\n\t\t}\n\t\t_executeHooks(hooks.afterSanitizeElements, currentNode, null);\n\t\treturn _handleHookDetachedNode(currentNode, root);\n\t};\n\t/**\n\t* _isValidAttribute\n\t*\n\t* @param lcTag Lowercase tag name of containing element.\n\t* @param lcName Lowercase attribute name.\n\t* @param value Attribute value.\n\t* @return Returns true if `value` is valid, otherwise false.\n\t*/\n\tconst _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n\t\tif (FORBID_ATTR[lcName]) return false;\n\t\tif (_isPatchLinkageAttribute(lcName, lcTag)) return false;\n\t\tif (SANITIZE_DOM && (lcName === \"id\" || lcName === \"name\") && (value in document || value in formElement)) return false;\n\t\tconst nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);\n\t\tif (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) return true;\n\t\tif (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) return true;\n\t\tif (!nameIsPermitted) return _isBasicCustomElement(lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName, lcTag) || lcName === \"is\" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value);\n\t\tif (URI_SAFE_ATTRIBUTES[lcName]) return true;\n\t\tconst compactValue = stringReplace(value, ATTR_WHITESPACE$1, \"\");\n\t\tif (regExpTest(IS_ALLOWED_URI$1, compactValue)) return true;\n\t\tif ((lcName === \"src\" || lcName === \"xlink:href\" || lcName === \"href\") && lcTag !== \"script\" && stringIndexOf(value, \"data:\") === 0 && DATA_URI_TAGS[lcTag]) return true;\n\t\tif (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, compactValue)) return true;\n\t\treturn !value;\n\t};\n\tconst RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, [\n\t\t\"annotation-xml\",\n\t\t\"color-profile\",\n\t\t\"font-face\",\n\t\t\"font-face-format\",\n\t\t\"font-face-name\",\n\t\t\"font-face-src\",\n\t\t\"font-face-uri\",\n\t\t\"missing-glyph\"\n\t]);\n\t/**\n\t* _isBasicCustomElement\n\t* checks if at least one dash is included in tagName, and it's not the first char\n\t* for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n\t*\n\t* @param tagName name of the tag of the node to sanitize\n\t* @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n\t*/\n\tconst _isBasicCustomElement = function _isBasicCustomElement(tagName) {\n\t\treturn !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);\n\t};\n\t/**\n\t* Wrap an attribute value in the matching Trusted Types object when\n\t* the active policy requires it. Namespaced attributes pass through\n\t* unchanged (no TT support yet, see\n\t* https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).\n\t*\n\t* @param lcTag lowercase tag name of the containing element\n\t* @param lcName lowercase attribute name\n\t* @param namespaceURI the attribute's namespace, if any\n\t* @param value the attribute value to wrap\n\t* @return the value, wrapped when Trusted Types demand it\n\t*/\n\tconst _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {\n\t\tif (trustedTypesPolicy && typeof trustedTypes === \"object\" && typeof trustedTypes.getAttributeType === \"function\" && !namespaceURI) switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n\t\t\tcase \"TrustedHTML\": return _createTrustedHTML(value);\n\t\t\tcase \"TrustedScriptURL\": return _createTrustedScriptURL(value);\n\t\t}\n\t\treturn value;\n\t};\n\t/**\n\t* Writes a changed attribute value back. If the new value clobbers, the\n\t* element is removed; if the write fails, the attribute is.\n\t*\n\t* @param currentNode the element carrying the attribute\n\t* @param name the attribute name as present on the element\n\t* @param namespaceURI the attribute's namespace, if any\n\t* @param value the new attribute value\n\t* @return true if the value was written without introducing clobbering\n\t*/\n\tconst _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {\n\t\ttry {\n\t\t\tif (namespaceURI) currentNode.setAttributeNS(namespaceURI, name, value);\n\t\t\telse currentNode.setAttribute(name, value);\n\t\t\tif (_isClobbered(currentNode)) {\n\t\t\t\t_forceRemove(currentNode);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (_) {\n\t\t\t_removeAttribute(name, currentNode);\n\t\t\treturn false;\n\t\t}\n\t};\n\t/**\n\t* Value checks that apply before a hook can force-keep an attribute. Also\n\t* used by isValidAttribute(), so it never approves a value that sanitize()\n\t* would strip.\n\t*\n\t* @param name the attribute name as found on the node (case preserved)\n\t* @param value the attribute value\n\t* @returns true if the attribute must be removed because of its value\n\t*/\n\tconst _isUnsafeAttributeValue = function _isUnsafeAttributeValue(name, value) {\n\t\tif (SAFE_FOR_XML && regExpTest(ATTR_VALUE_BREAKOUT, value)) return true;\n\t\treturn stringToLowerCase(name) === \"attributename\" && stringIndexOf(value, \"href\") !== -1;\n\t};\n\t/**\n\t* _sanitizeAttributes\n\t*\n\t* @protect attributes\n\t* @protect nodeName\n\t* @protect removeAttribute\n\t* @protect setAttribute\n\t*\n\t* @param currentNode to sanitize\n\t* @param root the current walk root\n\t*/\n\tconst _sanitizeAttributes = function _sanitizeAttributes(currentNode, root) {\n\t\t_executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n\t\tif (_handleHookDetachedNode(currentNode, root)) return;\n\t\tconst attributes = currentNode.attributes;\n\t\tif (!attributes || _isClobbered(currentNode)) return;\n\t\tALLOWED_ATTR = _forkSharedAllowlist(hooks.uponSanitizeAttribute, ALLOWED_ATTR, DEFAULT_ALLOWED_ATTR, SET_CONFIG_ALLOWED_ATTR);\n\t\tconst hookEvent = {\n\t\t\tattrName: \"\",\n\t\t\tattrValue: \"\",\n\t\t\tkeepAttr: true,\n\t\t\tallowedAttributes: ALLOWED_ATTR,\n\t\t\tforceKeepAttr: void 0\n\t\t};\n\t\tlet l = attributes.length;\n\t\tconst lcTag = transformCaseFunc(_readNodeName(currentNode));\n\t\twhile (l--) {\n\t\t\tconst attr = attributes[l];\n\t\t\tconst name = attr.name, namespaceURI = attr.namespaceURI, attrValue = attr.value;\n\t\t\tconst lcName = transformCaseFunc(name);\n\t\t\tconst initValue = attrValue;\n\t\t\tlet value = name === \"value\" ? initValue : stringTrim(initValue);\n\t\t\tlet recreatedNamedProp = false;\n\t\t\thookEvent.attrName = lcName;\n\t\t\thookEvent.attrValue = value;\n\t\t\thookEvent.keepAttr = true;\n\t\t\thookEvent.forceKeepAttr = void 0;\n\t\t\t_executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n\t\t\tvalue = hookEvent.attrValue;\n\t\t\tif (SANITIZE_NAMED_PROPS && (lcName === \"id\" || lcName === \"name\") && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {\n\t\t\t\t_removeAttribute(name, currentNode, attr);\n\t\t\t\tvalue = SANITIZE_NAMED_PROPS_PREFIX + value;\n\t\t\t\trecreatedNamedProp = true;\n\t\t\t}\n\t\t\tif (_isUnsafeAttributeValue(name, value)) {\n\t\t\t\t_removeAttribute(name, currentNode, attr);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (hookEvent.forceKeepAttr) continue;\n\t\t\tif (!hookEvent.keepAttr) {\n\t\t\t\t_removeAttribute(name, currentNode, attr);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {\n\t\t\t\t_removeAttribute(name, currentNode, attr);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (SAFE_FOR_TEMPLATES) value = _stripTemplateExpressions(value);\n\t\t\tif (!_isValidAttribute(lcTag, lcName, value)) {\n\t\t\t\t_removeAttribute(name, currentNode, attr);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);\n\t\t\tif (value !== initValue) {\n\t\t\t\tif (_setAttributeValue(currentNode, name, namespaceURI, value) && recreatedNamedProp) arrayPop(DOMPurify.removed);\n\t\t\t}\n\t\t}\n\t\t_executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n\t\t_handleHookDetachedNode(currentNode, root);\n\t};\n\t/**\n\t* Sanitizes one node: the node itself, its attributes and, for a\n\t* template, its content.\n\t*\n\t* @param node the node to sanitize\n\t* @param root the current walk root\n\t*/\n\tconst _sanitizeNode = function _sanitizeNode(node, root) {\n\t\t_sanitizeElements(node, root);\n\t\t_sanitizeAttributes(node, root);\n\t\tif (_isDocumentFragment(node.content)) _sanitizeShadowDOM2(node.content);\n\t};\n\t/**\n\t* _sanitizeShadowDOM\n\t*\n\t* @param fragment to iterate over recursively\n\t*/\n\tconst _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {\n\t\tlet shadowNode = null;\n\t\tconst shadowIterator = _createNodeIterator(fragment);\n\t\t_executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n\t\twhile (shadowNode = shadowIterator.nextNode()) {\n\t\t\t_executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n\t\t\t_sanitizeNode(shadowNode, fragment);\n\t\t\tif (_readNodeType(shadowNode) === NODE_TYPE.element) {\n\t\t\t\tconst innerSr = getShadowRoot(shadowNode);\n\t\t\t\tif (_isDocumentFragment(innerSr)) {\n\t\t\t\t\t_sanitizeAttachedShadowRoots(innerSr);\n\t\t\t\t\t_sanitizeShadowDOM2(innerSr);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (SAFE_FOR_TEMPLATES) _scrubOwnCharacterData(fragment);\n\t\t_executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n\t};\n\t/**\n\t* Sanitizes every attached shadow root under `root`, since the node\n\t* iterator does not enter shadow trees. Needed for IN_PLACE input and for\n\t* DOM input whose clonable shadow roots were copied by importNode().\n\t*\n\t* @param root the subtree root to walk for attached shadow roots\n\t*/\n\tconst _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {\n\t\tconst stack = [{\n\t\t\tnode: root,\n\t\t\tshadow: null\n\t\t}];\n\t\twhile (stack.length > 0) {\n\t\t\tconst item = stack.pop();\n\t\t\tif (item.shadow) {\n\t\t\t\t_sanitizeShadowDOM2(item.shadow);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst node = item.node;\n\t\t\tconst isElement = _readNodeType(node) === NODE_TYPE.element;\n\t\t\tconst childNodes = getChildNodes(node);\n\t\t\tif (childNodes) for (let i = childNodes.length - 1; i >= 0; --i) stack.push({\n\t\t\t\tnode: childNodes[i],\n\t\t\t\tshadow: null\n\t\t\t});\n\t\t\tif (isElement) {\n\t\t\t\tconst rootName = getNodeName ? getNodeName(node) : null;\n\t\t\t\tif (typeof rootName === \"string\" && transformCaseFunc(rootName) === \"template\") {\n\t\t\t\t\tconst content = node.content;\n\t\t\t\t\tif (_isDocumentFragment(content)) stack.push({\n\t\t\t\t\t\tnode: content,\n\t\t\t\t\t\tshadow: null\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isElement) {\n\t\t\t\tconst sr = getShadowRoot(node);\n\t\t\t\tif (_isDocumentFragment(sr)) stack.push({\n\t\t\t\t\tnode: null,\n\t\t\t\t\tshadow: sr\n\t\t\t\t}, {\n\t\t\t\t\tnode: sr,\n\t\t\t\t\tshadow: null\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n\tDOMPurify.sanitize = function(dirty) {\n\t\tlet cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};\n\t\tlet body = null;\n\t\tlet importedNode = null;\n\t\tlet currentNode = null;\n\t\tlet returnNode = null;\n\t\tIS_EMPTY_INPUT = !dirty;\n\t\tif (IS_EMPTY_INPUT) dirty = \"<!-->\";\n\t\tif (typeof dirty !== \"string\" && !_isNode(dirty)) {\n\t\t\tdirty = stringifyValue(dirty);\n\t\t\tif (typeof dirty !== \"string\") throw typeErrorCreate(\"dirty is not a string, aborting\");\n\t\t}\n\t\tif (!DOMPurify.isSupported) return dirty;\n\t\tif (SET_CONFIG) {\n\t\t\tALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;\n\t\t\tALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;\n\t\t} else _parseConfig(cfg);\n\t\tDOMPurify.removed = [];\n\t\tconst inPlace = IN_PLACE && typeof dirty !== \"string\" && _isNode(dirty);\n\t\tlet inPlaceNodes = [];\n\t\tconst outerVisited = IN_PLACE_VISITED;\n\t\tif (inPlace) {\n\t\t\t_neutralizePatchLinkage(dirty);\n\t\t\tconst nn = _readNodeName(dirty);\n\t\t\tif (typeof nn === \"string\") {\n\t\t\t\tconst tagName = transformCaseFunc(nn);\n\t\t\t\tif (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n\t\t\t\t\t_neutralizeRoot(dirty);\n\t\t\t\t\tthrow typeErrorCreate(\"root node is forbidden and cannot be sanitized in-place\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (_isClobbered(dirty)) {\n\t\t\t\t_neutralizeRoot(dirty);\n\t\t\t\tthrow typeErrorCreate(\"root node is clobbered and cannot be sanitized in-place\");\n\t\t\t}\n\t\t\tinPlaceNodes = _collectLiveNodes(dirty);\n\t\t\tIN_PLACE_VISITED = setCreate();\n\t\t} else if (_isNode(dirty)) {\n\t\t\tbody = _initDocument(\"<!---->\");\n\t\t\timportedNode = body.ownerDocument.importNode(dirty, true);\n\t\t\tif (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === \"BODY\") body = importedNode;\n\t\t\telse if (importedNode.nodeName === \"HTML\") body = importedNode;\n\t\t\telse body.appendChild(importedNode);\n\t\t\t_sanitizeAttachedShadowRoots(body);\n\t\t} else {\n\t\t\tif (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf(\"<\") === -1) return _signOutput(dirty);\n\t\t\tbody = _initDocument(dirty);\n\t\t\tif (!body) return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : \"\";\n\t\t}\n\t\tif (body && FORCE_BODY) _forceRemove(body.firstChild);\n\t\tconst walkRoot = inPlace ? dirty : body;\n\t\ttry {\n\t\t\tif (inPlace) _sanitizeAttachedShadowRoots(dirty);\n\t\t\tconst nodeIterator = _createNodeIterator(walkRoot);\n\t\t\twhile (currentNode = nodeIterator.nextNode()) _sanitizeNode(currentNode, walkRoot);\n\t\t\tif (inPlace) _sanitizeUnvisitedNodes(dirty, inPlaceNodes);\n\t\t} catch (error) {\n\t\t\tif (inPlace) {\n\t\t\t\t_neutralizeRoot(dirty);\n\t\t\t\t_neutralizeDiscarded(dirty, inPlaceNodes);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tIN_PLACE_VISITED = outerVisited;\n\t\t}\n\t\tif (inPlace) {\n\t\t\tif (_neutralizeDiscarded(dirty, inPlaceNodes)) throw typeErrorCreate(\"a node selected for removal could not be safely returned; refusing to sanitize in place\");\n\t\t\tif (SAFE_FOR_TEMPLATES) _scrubTemplateExpressions2(dirty);\n\t\t\treturn dirty;\n\t\t}\n\t\tif (RETURN_DOM) {\n\t\t\tif (SAFE_FOR_TEMPLATES) _scrubTemplateExpressions2(body);\n\t\t\tif (RETURN_DOM_FRAGMENT) {\n\t\t\t\treturnNode = createDocumentFragment.call(body.ownerDocument);\n\t\t\t\twhile (body.firstChild) returnNode.appendChild(body.firstChild);\n\t\t\t} else returnNode = body;\n\t\t\tif (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) returnNode = importNode.call(originalDocument, returnNode, true);\n\t\t\treturn returnNode;\n\t\t}\n\t\tconst serialize = () => WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n\t\tlet serializedHTML = serialize();\n\t\tif (SAFE_FOR_TEMPLATES && regExpTest(TMPL_MARKER_SERIALIZED, serializedHTML)) {\n\t\t\t_scrubOwnCharacterData(body);\n\t\t\tserializedHTML = serialize();\n\t\t}\n\t\tif (WHOLE_DOCUMENT && ALLOWED_TAGS[\"!doctype\"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) serializedHTML = \"<!DOCTYPE \" + body.ownerDocument.doctype.name + \">\\n\" + serializedHTML;\n\t\treturn _signOutput(serializedHTML);\n\t};\n\tDOMPurify.setConfig = function() {\n\t\tlet cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};\n\t\t_parseConfig(cfg);\n\t\tSET_CONFIG = true;\n\t\tSET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;\n\t\tSET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;\n\t};\n\tDOMPurify.clearConfig = function() {\n\t\tCONFIG = null;\n\t\tSET_CONFIG = false;\n\t\tSET_CONFIG_ALLOWED_TAGS = null;\n\t\tSET_CONFIG_ALLOWED_ATTR = null;\n\t\ttrustedTypesPolicy = defaultTrustedTypesPolicy;\n\t\temptyHTML = \"\";\n\t};\n\tDOMPurify.isValidAttribute = function(tag, attr, value) {\n\t\tif (!CONFIG) _parseConfig({});\n\t\tconst lcTag = transformCaseFunc(tag);\n\t\tconst lcName = transformCaseFunc(attr);\n\t\tif (typeof value === \"string\" && (_isUnsafeAttributeValue(attr, value) || !ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value))) return false;\n\t\treturn _isValidAttribute(lcTag, lcName, value);\n\t};\n\tDOMPurify.addHook = function(entryPoint, hookFunction) {\n\t\tif (typeof hookFunction !== \"function\") return;\n\t\tif (!objectHasOwnProperty(hooks, entryPoint)) return;\n\t\tarrayPush(hooks[entryPoint], hookFunction);\n\t};\n\tDOMPurify.removeHook = function(entryPoint, hookFunction) {\n\t\tif (!objectHasOwnProperty(hooks, entryPoint)) return;\n\t\tif (hookFunction !== void 0) {\n\t\t\tconst index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n\t\t\treturn index === -1 ? void 0 : arraySplice(hooks[entryPoint], index, 1)[0];\n\t\t}\n\t\treturn arrayPop(hooks[entryPoint]);\n\t};\n\tDOMPurify.removeHooks = function(entryPoint) {\n\t\tif (!objectHasOwnProperty(hooks, entryPoint)) return;\n\t\thooks[entryPoint] = [];\n\t};\n\tDOMPurify.removeAllHooks = function() {\n\t\thooks = _createHooksMap();\n\t};\n\treturn DOMPurify;\n}\nvar purify_default = createDOMPurify();\nexport { purify_default as default };\n\n//# sourceMappingURL=purify.es.mjs.map","// src/browser.ts\nimport DOMPurify from \"dompurify\";\nvar browser_default = DOMPurify;\nvar sanitize = DOMPurify.sanitize.bind(DOMPurify);\nvar isSupported = DOMPurify.isSupported;\nvar addHook = DOMPurify.addHook.bind(DOMPurify);\nvar removeHook = DOMPurify.removeHook.bind(DOMPurify);\nvar removeHooks = DOMPurify.removeHooks.bind(DOMPurify);\nvar removeAllHooks = DOMPurify.removeAllHooks.bind(DOMPurify);\nvar setConfig = DOMPurify.setConfig.bind(DOMPurify);\nvar clearConfig = DOMPurify.clearConfig.bind(DOMPurify);\nvar isValidAttribute = DOMPurify.isValidAttribute.bind(DOMPurify);\nvar version = DOMPurify.version;\nvar removed = DOMPurify.removed;\nfunction clearWindow() {\n}\nexport {\n  addHook,\n  clearConfig,\n  clearWindow,\n  browser_default as default,\n  isSupported,\n  isValidAttribute,\n  removeAllHooks,\n  removeHook,\n  removeHooks,\n  removed,\n  sanitize,\n  setConfig,\n  version\n};\n","/**\n * marked v18.2.1 - a markdown parser\n * Copyright (c) 2018-2026, MarkedJS. (MIT License)\n * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License)\n * https://github.com/markedjs/marked\n */\n\n/**\n * DO NOT EDIT THIS FILE\n * The code in this file is generated from files in ./src/\n */\n\nfunction G(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var S=G();function ue(l){S=l}var q={exec:()=>null};function D(l){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),r=e[n];return r||(r=l(n),e[n]=r),r}}function g(l,e=\"\"){let t=typeof l==\"string\"?l:l.source,n={replace:(r,s)=>{let o=typeof s==\"string\"?s:s.source;return o=o.replace(O.caret,\"$1\"),t=t.replace(r,o),n},getRegex:()=>new RegExp(t,e)};return n}var _e=((l=\"\")=>{try{return!!new RegExp(\"(?<=1)(?<!1)\"+l)}catch{return!1}})(),O={codeRemoveIndent:/^(?: {0,3}\\t| {1,4})/gm,listInterruptsParagraph:/^ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/,outputLinkReplace:/\\\\([\\[\\]])/g,indentCodeCompensation:/^(\\s+)(?:```)/,beginningSpace:/^\\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \\t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\\n/g,tabCharGlobal:/\\t/g,leadingSpaceTab:/^[ \\t]+/,multipleSpaceGlobal:/\\s+/g,blankLine:/^[ \\t]*$/,doubleBlankLine:/\\n[ \\t]*\\n[ \\t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\\n {0,3}((?:=+|-+)[ \\t]*)(?=\\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \\t]?/gm,blockquoteMarkerWhitespace:/^( {0,3}>)(\\t[ \\t]*)/gm,nestedBlockMarker:/^ {0,3}(?:(?:[*+-]|\\d{1,9}[.)])(?: |$)|> ?)/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\\[[ xX]\\][ \\t]+\\S/,listReplaceTask:/^\\[[ xX]\\][ \\t]+/,listTaskCheckbox:/\\[[ xX]\\]/,anyLine:/\\n.*\\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\\||\\| *$/g,tableRowBlankLine:/\\n[ \\t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\\s|>)/i,endPreScriptTag:/^<\\/(pre|code|kbd|script)(\\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,unicodeAlphaNumeric:/[\\p{L}\\p{N}]/u,numericCharacterReference:/&#(?:(\\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,escapeTest:/[&<>\"']/,escapeReplace:/[&<>\"']/g,escapeTestNoEncode:/[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,escapeReplaceNoEncode:/[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,caret:/(^|[^\\[])\\^/g,percentDecode:/%25/g,findPipe:/\\|/g,splitPipe:/ \\|/,slashPipe:/\\\\\\|/g,carriageReturn:/\\r\\n|\\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\\S*/,endingNewline:/\\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[\t ][^\\\\n]*)?(?:\\\\n|$))`),nextBulletRegex:D(l=>new RegExp(`^ {0,${l}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \t][^\\\\n]*)?(?:\\\\n|$))`)),hrRegex:D(l=>new RegExp(`^ {0,${l}}((?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\\\\*[ \t]*){3,})(?:\\\\n+|$)`)),fencesBeginRegex:D(l=>new RegExp(`^ {0,${l}}(?:\\`\\`\\`|~~~)`)),headingBeginRegex:D(l=>new RegExp(`^ {0,${l}}#{1,6}(?:\\\\s|$)`)),pedanticHeadingBeginRegex:D(l=>new RegExp(`^ {0,${l}}#`)),htmlBeginRegex:D(l=>new RegExp(`^ {0,${l}}(?:</?(?:${he})(?:[ \\\\t]+|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\\\s>]|$)|!--)|<\\\\?|<![A-Za-z]|<!\\\\[CDATA\\\\[)`,\"i\")),blockquoteBeginRegex:D(l=>new RegExp(`^ {0,${l}}>`)),nestedContainerMarkers:/^(?: {0,3}(?:(?:[*+-]|\\d{1,9}[.)])[ \\t]+|>[ \\t]?))+/},Ge=/^(?:[ \\t]*(?:\\n|$))+/,Ne=/^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/,Fe=/^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}(?:(?=`)\\1`*|(?=~)\\1~*) *(?=\\n|$)|$)/,V=/^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/,Qe=/^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,ce=/ {0,3}(?:[*+-]|\\d{1,9}[.)])/,he=\"address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul\",J=g(\" {0,3}(?:</?(?:tag)(?:[ \\\\t]+|\\\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\\\s>]|$)|!--)|<\\\\?|<![A-Za-z]|<!\\\\[CDATA\\\\[)\").replace(\"tag\",he).getRegex(),$e=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |fences|blockquote|heading|hr|html|table))+?)\\n {0,3}(=+|-+)[ \\t]*(?:\\n+|$)/,Le=g($e).replace(/bull/g,ce).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/).replace(/\\|table/g,\"\").replace(/html/g,J).getRegex(),We=g($e).replace(/bull/g,ce).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/).replace(/table/g,/ {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/).replace(/html/g,J).getRegex(),de=/^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \\t]+\\n)[^\\n]+)*)/,Ue=/^[^\\n]+/,ge=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\\\n]|\\n(?![ \\t]*\\n))+/,Ke=g(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<(?:\\\\.|[^\\n<>\\\\])*>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace(\"label\",ge).replace(\"title\",/(?:\"(?:\\\\[\\s\\S]|[^\"\\\\])*\"|'(?:\\\\[\\s\\S]|[^'\\\\\\n]|\\n(?!\\n))*'|\\((?:\\\\[\\s\\S]|[^()\\\\])*\\))/).getRegex(),Xe=g(/^(bull)([ \\t][^\\n]*?)?(?:\\n|$)/).replace(/bull/g,ce).getRegex(),ke=/<!--(?:-?>|[\\s\\S]*?(?:-->|$))/,Ve=g(\"^ {0,3}(?:<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n*|$)|comment[^\\\\n]*(\\\\n+|$)|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>[^\\\\n]*\\\\n*|$)|<![A-Z][\\\\s\\\\S]*?(?:>[^\\\\n]*\\\\n*|$)|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>[^\\\\n]*\\\\n*|$)|</?(tag)(?:[ \\\\t]+|\\\\n|/?>|$)[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*?[ \\\\t]*/?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|</[a-z][a-z0-9-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$))\",\"i\").replace(\"comment\",ke).replace(\"tag\",he).replace(\"attribute\",/[ \\t]+[a-zA-Z:_][\\w.:-]*(?:[ \\t]*=[ \\t]*\"[^\"\\n]*\"|[ \\t]*=[ \\t]*'[^'\\n]*'|[ \\t]*=[ \\t]*[^\\s\"'=<>`]+)?/).getRegex(),Ce=l=>g(de).replace(\"hr\",V).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\",\"\").replace(\"|table\",\"\").replace(\"blockquote\",\" {0,3}>\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*(?:\\\\n|$))|~~~)[^\\\\n]*(?:\\\\n|$)\").replace(\"list\",l).replace(\"html\",J).getRegex(),Je=Ce(/ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/),Ye=Ce(/ {0,3}(?:[*+-]|\\d{1,9}[.)])(?:[ \\t]|\\n|$)/),et=g(/^( {0,3}> ?(?:(?![ \\t]*(?:\\n|$))(paragraph)|[^\\n]*)(?:\\n|$))+/).replace(\"paragraph\",Ye).getRegex(),fe={blockquote:et,code:Ne,def:Ke,fences:Fe,heading:Qe,hr:V,html:Ve,lheading:Le,list:Xe,newline:Ge,paragraph:Je,table:q,text:Ue},Pe=g(\"^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)\").replace(\"hr\",V).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"blockquote\",\" {0,3}>\").replace(\"code\",\"(?: {4}| {0,3}\t)[^\\\\n]\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*(?:\\\\n|$))|~~~)[^\\\\n]*(?:\\\\n|$)\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)])[ \\\\t]\").replace(\"html\",J).getRegex(),tt={...fe,lheading:We,table:Pe,paragraph:g(de).replace(\"hr\",V).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\",\"\").replace(\"table\",Pe).replace(\"blockquote\",\" {0,3}>\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*(?:\\\\n|$))|~~~)[^\\\\n]*(?:\\\\n|$)\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)])[ \\\\t]+[^ \\\\t\\\\n]\").replace(\"html\",J).getRegex()},nt={...fe,html:g(`^ *(?:comment(?: *\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+?</\\\\1>(?: *\\\\n{2,}|\\\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\\\s[^'\"/>\\\\s]*)*?/?>(?: *\\\\n{2,}|\\\\s*$))`).replace(\"comment\",ke).replace(/tag/g,\"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b\").getRegex(),def:/^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,heading:/^(#{1,6})(.*)(?:\\n+|$)/,fences:q,lheading:/^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,paragraph:g(de).replace(\"hr\",V).replace(\"heading\",` *#{1,6} *[^\n]`).replace(\"|table\",\"\").replace(\"blockquote\",\" {0,3}>\").replace(\"|fences\",\"\").replace(\"|list\",\"\").replace(\"|html\",\"\").replace(\"|tag\",\"\").replace(\"lheading\",Le).getRegex()},rt=/^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,st=/^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,Ie=/^( {2,}|\\\\)\\n(?!\\s*$)[ \\t]*/,it=/^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/,L=/[\\p{P}\\p{S}]/u,N=/[\\s\\p{P}\\p{S}]/u,Y=/[^\\s\\p{P}\\p{S}]/u,ot=g(/^((?![*_])punctSpace)/,\"u\").replace(/punctSpace/g,N).getRegex(),at=/[\\p{Pi}\\p{Ps}\"']/u,Ae=/(?!~)[\\p{P}\\p{S}]/u,lt=/(?!~)[\\s\\p{P}\\p{S}]/u,ut=/(?:[^\\s\\p{P}\\p{S}]|~)/u,pt=g(/link|precode-code|html/,\"g\").replace(\"link\",/\\[(?:[^\\[\\]`]|(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/).replace(\"precode-\",_e?\"(?<!`)()\":\"(^^|[^`])\").replace(\"code\",/(?<b>`+)[^`]+\\k<b>(?!`)/).replace(\"html\",/<(?! )[^<>]*?>/).getRegex(),Ee=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/,ct=g(Ee,\"u\").replace(/punct/g,L).getRegex(),ht=g(Ee,\"u\").replace(/punct/g,Ae).getRegex(),dt=/^(?:\\*+(?:((?!\\*)(?!openQuote)punct)|([^\\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\\s_]))?/,gt=g(dt,\"u\").replace(/openQuote/g,at).replace(/punct/g,L).getRegex(),ze=\"^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)\",kt=g(ze,\"gu\").replace(/notPunctSpace/g,Y).replace(/punctSpace/g,N).replace(/punct/g,L).getRegex(),ft=g(ze,\"gu\").replace(/notPunctSpace/g,ut).replace(/punctSpace/g,lt).replace(/punct/g,Ae).getRegex(),mt=\"^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)[\\\\s](\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|(?:(?!\\\\*)punct|notPunctSpace)(\\\\*+)(?!\\\\*)(?=notPunctSpace)\",xt=g(mt,\"gu\").replace(/notPunctSpace/g,Y).replace(/punctSpace/g,N).replace(/punct/g,L).getRegex(),bt=g(\"^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)\",\"gu\").replace(/notPunctSpace/g,Y).replace(/punctSpace/g,N).replace(/punct/g,L).getRegex(),Rt=\"^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\\\s](_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)\",Tt=g(Rt,\"gu\").replace(/notPunctSpace/g,Y).replace(/punctSpace/g,N).replace(/punct/g,L).getRegex(),Ot=g(/^~~?(?:((?!~)punct)|[^\\s~])/,\"u\").replace(/punct/g,L).getRegex(),wt=\"^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)\",Pt=g(wt,\"gu\").replace(/notPunctSpace/g,Y).replace(/punctSpace/g,N).replace(/punct/g,L).getRegex(),yt=g(/\\\\(punct)/,\"gu\").replace(/punct/g,L).getRegex(),St=g(/(`+)(?:[^`]|[^`][\\s\\S]*?[^`])\\1(?!`)|`+|\\\\(punct)/,\"gu\").replace(/punct/g,L).getRegex(),_t=g(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/).replace(\"scheme\",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(\"email\",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),$t=g(ke).replace(\"(?:-->|$)\",\"-->\").getRegex(),Lt=g(\"^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\\\s*/?>|^<\\\\?[\\\\s\\\\S]*?\\\\?>|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>\").replace(\"comment\",$t).replace(\"attribute\",/\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/).getRegex(),Me=/\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]/,ie=g(/(?:\\[(?:brackets|\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/).replace(\"brackets\",Me).getRegex(),Ct=g(/^!?\\[(label)\\]\\([ \\t\\n]*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?[ \\t\\n]*\\)/).replace(\"label\",ie).replace(\"href\",/<(?:\\\\.|[^\\n<>\\\\])*>|(?!<)[^ \\t\\n\\x00-\\x1f]+|(?=\\))/).replace(\"title\",/\"(?:\\\\[\\s\\S]|[^\"\\\\])*\"|'(?:\\\\[\\s\\S]|[^'\\\\])*'|\\((?:\\\\[\\s\\S]|[^)\\\\])*\\)/).getRegex(),It=g(/^!?\\[(label)\\]\\[(ref)\\]/).replace(\"label\",ie).replace(\"ref\",ge).getRegex(),At=g(/^!?\\[(ref)\\](?:\\[\\])?/).replace(\"ref\",ge).getRegex(),ye=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\]){1,999}/,Et=g(/(?:[^\\[\\]\\\\`]*(?:\\[(?:brackets|\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\]))){0,999}?[^\\[\\]\\\\`]*?/).replace(\"brackets\",Me).getRegex(),zt=g(\"reflink|nolink(?!\\\\()\",\"g\").replace(\"reflink\",g(/^!?\\[(label)\\]\\[(ref)\\]/).replace(\"label\",Et).replace(\"ref\",ye).getRegex()).replace(\"nolink\",g(/^!?\\[(ref)\\](?:\\[\\])?/).replace(\"ref\",ye).getRegex()).getRegex(),Se=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Mt=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\\w-])/,Bt=g(/(?:mailto:email|xmpp:email(?:\\/[A-Za-z0-9@.]+)?)/).replace(/email/g,Mt).getRegex(),me={_backpedal:q,anyPunctuation:yt,anyPunctuationOutsideCode:St,autolink:_t,blockSkip:pt,br:Ie,code:st,del:q,delLDelim:q,delRDelim:q,emStrongLDelim:ct,emStrongRDelimAst:kt,emStrongRDelimUnd:bt,escape:rt,link:Ct,nolink:At,punctuation:ot,reflink:It,reflinkSearch:zt,tag:Lt,text:it,url:q},Dt={...me,emStrongLDelim:gt,emStrongRDelimAst:xt,emStrongRDelimUnd:Tt,link:g(/^!?\\[(label)\\]\\((.*?)\\)/).replace(\"label\",ie).getRegex(),reflink:g(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace(\"label\",ie).getRegex()},pe={...me,emStrongRDelimAst:ft,emStrongLDelim:ht,delLDelim:Ot,delRDelim:Pt,url:g(/^emailProtocol|^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace(\"emailProtocol\",Bt).replace(\"protocol\",Se).replace(\"email\",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,del:/^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,text:g(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|wwwStart|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@))))/).replace(\"protocol\",Se).replace(/emailProtocol/g,/(?:mailto|xmpp):/).replace(\"wwwStart\",_e?\"(?<![^\\\\s*_~(])www\\\\.\":\"www\\\\.\").getRegex()},qt={...pe,br:g(Ie).replace(\"{2,}\",\"*\").getRegex(),text:g(pe.text).replace(\"\\\\b_\",\"\\\\b_| {2,}\\\\n\").replace(/\\{2,\\}/g,\"*\").getRegex()},ee={normal:fe,gfm:tt,pedantic:nt},F={normal:me,gfm:pe,breaks:qt,pedantic:Dt};var vt={\"&\":\"&amp;\",\"<\":\"&lt;\",\">\":\"&gt;\",'\"':\"&quot;\",\"'\":\"&#39;\"},Be=l=>vt[l];function y(l,e){if(e){if(O.escapeTest.test(l))return l.replace(O.escapeReplace,Be)}else if(O.escapeTestNoEncode.test(l))return l.replace(O.escapeReplaceNoEncode,Be);return l}function De(l){return O.numericCharacterReference.test(l)?l.replace(O.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return\"&amp;\";let r=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return r===0||r>1114111||r>=55296&&r<=57343?\"\\uFFFD\":r===38?\"&amp;\":String.fromCodePoint(r)}):l}function xe(l){try{l=encodeURI(l).replace(O.percentDecode,\"%\")}catch{return null}return l}function be(l,e){let t=l.replace(O.findPipe,(s,o,i)=>{let a=!1,c=o;for(;--c>=0&&i[c]===\"\\\\\";)a=!a;return a?\"|\":\" |\"}),n=t.split(O.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push(\"\");for(;r<n.length;r++)n[r]=n[r].trim().replace(O.slashPipe,\"|\");return n}function C(l,e,t){let n=l.length;if(n===0)return\"\";let r=0;for(;r<n;){let s=l.charAt(n-r-1);if(s===e&&!t)r++;else if(s!==e&&t)r++;else break}return l.slice(0,n-r)}function Re(l){let e=l.split(`\n`),t=e.length-1;for(;t>=0&&O.blankLine.test(e[t]);)t--;return e.length-t<=2?l:e.slice(0,t+1).join(`\n`)}function W(l){return l.trim().replace(O.multipleSpaceGlobal,\" \").toLowerCase().toUpperCase().toLowerCase()}function Te(l,e){if(l.indexOf(e[0])===-1&&l.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l.length;n++)if(l[n]===\"\\\\\")n++;else if(l[n]===e[0])t++;else if(l[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}var Q=new WeakMap;function Oe(l){let e={\"*\":-1,_:-1},t=-1,n=l.length;for(let r=0;r<n;r++){let s=l[r];if(s!==\"*\"&&s!==\"_\"&&s!==\"~\")continue;let o=r===0?`\n`:l[r-1],i=r+1;for(;i<n&&l[i]===s;)i++;o!==\" \"&&o!==\"\t\"&&o!==`\n`&&o!==\"\\r\"&&o!==\"\\f\"&&(s===\"~\"?t=r:e[s]=r),r=i-1}return{maskedSrc:l,lastPossibleEmStrongCloserIndex:e,lastPossibleDelCloserIndex:t}}function qe(l,e){let t=Oe(e),n=Q.get(l);n?n.push(t):Q.set(l,[t])}function ve(l){let e=Q.get(l);e&&(e.pop(),e.length===0&&Q.delete(l))}function oe(l,e,t){let n=Q.get(l)?.at(-1);return n&&n.maskedSrc===e?n.lastPossibleEmStrongCloserIndex[t]:Oe(e).lastPossibleEmStrongCloserIndex[t]}function ae(l,e){let t=Q.get(l)?.at(-1);return t&&t.maskedSrc===e?t.lastPossibleDelCloserIndex:Oe(e).lastPossibleDelCloserIndex}function te(l,e=0){let t=e,n=\"\";for(let r of l)if(r===\"\t\"){let s=4-t%4;n+=\" \".repeat(s),t+=s}else n+=r,t++;return n}function Ht(l,e){let t=\"\";for(let n=0;n<l.length;n++){if(l[n]===\"`\"){let r=e.inline.code.exec(l.slice(n));if(r){t+=r[0],n+=r[0].length-1;continue}}if(l[n]===\"\\\\\"&&(l[n+1]===\"[\"||l[n+1]===\"]\")){t+=l[n+1],n++;continue}t+=l[n]}return t}function He(l,e,t,n,r){let s=e.href,o=e.title||null,i=Ht(l[1],r),a=l[0].charAt(0)===\"!\",c=n.state.inLink,u=n.state.linkEmitted,d=n.state.inRawBlock;n.state.inLink=!0,n.state.linkEmitted=!1;let h=n.inlineTokens(i),p=n.state.linkEmitted;if(n.state.linkEmitted=u,n.state.inLink=c,!a){if(p){n.state.inRawBlock=d;return}n.state.linkEmitted=!0}return{type:a?\"image\":\"link\",raw:t,href:s,title:o,text:i,tokens:h}}function Zt(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let r=n[1];return e.split(`\n`).map(s=>{let o=s.match(t.other.beginningSpace);if(o===null)return s;let[i]=o;return s.slice(Math.min(i.length,r.length))}).join(`\n`)}function Ze(l,e,t,n){if(!e.includes(\"<\"))return!1;for(let r=0;r<e.length;r++){if(e[r]===\"\\\\\"){r++;continue}if(e[r]===\"`\"){let i=n.inline.code.exec(e.slice(r));if(i){r+=i[0].length-1;continue}}if(e[r]!==\"<\")continue;let s=l.slice(t+r),o=n.inline.tag.exec(s)||n.inline.autolink.exec(s);if(o){if(o[0].length>e.length-r)return!0;r+=o[0].length-1}}return!1}var _=class{options;rules;lexer;constructor(e){this.options=e||S}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:\"space\",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:Re(t[0]),r=n.replace(this.rules.other.codeRemoveIndent,\"\");return{type:\"code\",raw:n,codeBlockStyle:\"indented\",text:r}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=Zt(n,t[3]||\"\",this.rules);return t[3]!==void 0&&(r===\"\"||r.endsWith(`\n`))&&(r+=`\n`),{type:\"code\",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,\"$1\"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=C(n,\"#\");(this.options.pedantic||!r||this.rules.other.endingSpaceTabChar.test(r))&&(n=r.trim())}return{type:\"heading\",raw:C(t[0],`\n`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:\"hr\",raw:C(t[0],`\n`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=C(t[0],`\n`).split(`\n`),r=\"\",s=\"\",o=[];for(;n.length>0;){let i=!1,a=[],c;for(c=0;c<n.length;c++)if(this.rules.other.blockquoteStart.test(n[c]))a.push(n[c]),i=!0;else if(!i)a.push(n[c]);else break;n=n.slice(c);let u=a.join(`\n`),d=u.replace(this.rules.other.blockquoteMarkerWhitespace,(k,m,b)=>b.startsWith(\" \")?m+\" \"+b.slice(1):m+te(b,m.length)).replace(this.rules.other.blockquoteSetextReplace,`\n    $1`).replace(this.rules.other.blockquoteSetextReplace2,\"\");r=r?`${r}\n${u}`:u,s=s?`${s}\n${d}`:d;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(d,o,!0),this.lexer.state.top=h,n.length===0)break;let p=o.at(-1);if(p?.type===\"code\"||p?.type===\"heading\"||p?.type===\"hr\"||p?.type===\"html\"||p?.type===\"table\")break;if(p?.type===\"blockquote\"){let k=p,m=n.join(`\n`),b=k.raw+`\n`+m.replace(this.rules.other.blockquoteSetextReplace2,\"\"),f=this.blockquote(b);o[o.length-1]=f;let R=b.substring(f.raw.length).replace(/^\\n/,\"\"),E=R?R.split(`\n`).length:0,T=E?n.slice(0,-E):n;if(T.length>0&&(r=`${r}\n${T.join(`\n`)}`),s=s.substring(0,s.length-k.text.length)+f.text,n=n.slice(T.length),n.length>0&&this.rules.other.blockquoteStart.test(n[0]))continue;break}else if(p?.type===\"list\"){let k=p,m=k.raw+`\n`+n.join(`\n`),b=this.list(m);o[o.length-1]=b;let f=b.raw.length>k.raw.length?m.slice(k.raw.length+1,b.raw.length).split(`\n`).length:0;if(f>0){let R=n.slice(0,f).join(`\n`);r=`${r}\n${R}`,s=`${s}\n${R}`}if(n=n.slice(f),n.length>0&&!this.rules.other.blockquoteStart.test(n[0]))break;continue}}return{type:\"blockquote\",raw:r,tokens:o,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){if(!this.options.pedantic&&this.lexer.state.lastToken?.type===\"text\"&&!this.rules.other.listInterruptsParagraph.test(e))return;let n=e,r=()=>n.length-e.length,s=t[1].trim(),o=s.length>1,i={type:\"list\",raw:\"\",ordered:o,start:o?+s.slice(0,-1):\"\",loose:!1,items:[]};s=o?`\\\\d{1,9}\\\\${s.slice(-1)}`:`\\\\${s}`,this.options.pedantic&&(s=o?s:\"[*+-]\");let a=this.rules.other.listItemRegex(s),c=!1;for(;e;){let h=!1,p=\"\";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;let k=r();e=e.substring(t[0].length);let m=t[2].split(`\n`,1)[0],b=t[1].length,f=this.options.pedantic?te(m,b):m.replace(this.rules.other.leadingSpaceTab,H=>te(H,b)),R=e.split(`\n`,1)[0],E=!f.trim(),T=0;if(this.options.pedantic?(T=2,p=f.trimStart()):E?T=b+1:(T=f.search(this.rules.other.nonSpaceChar),T=T>4?1:T,p=f.slice(T),T+=b),E&&this.rules.other.blankLine.test(R)&&(e=e.substring(R.length+1),h=!0),!h){let H=this.rules.other.nextBulletRegex(T),K=this.rules.other.hrRegex(T),re=this.rules.other.fencesBeginRegex(T),B=this.options.pedantic?this.rules.other.pedanticHeadingBeginRegex(T):this.rules.other.headingBeginRegex(T),X=this.rules.other.htmlBeginRegex(T),se=this.rules.other.blockquoteBeginRegex(T),le=!1;for(;e;){let we=e.split(`\n`,1)[0],Z;if(R=we,this.options.pedantic?(R=R.replace(this.rules.other.listReplaceNesting,\"  \"),Z=R):Z=R.replace(this.rules.other.leadingSpaceTab,$=>te($)),re.test(R)||B.test(R)||X.test(R)||se.test(R)||H.test(R)||K.test(R))break;if(Z.search(this.rules.other.nonSpaceChar)>=T||!R.trim())p+=`\n`+Z.slice(T),le=!1;else{if(E)break;let $=f;if(!this.options.pedantic&&!p.includes(`\n`)&&!f.includes(\"\t\")){let j;for(;!K.test($)&&(j=this.rules.other.nestedBlockMarker.exec($));)$=$.slice(j[0].length);if(!$.trim())break}if($.replace(this.rules.other.tabCharGlobal,\"    \").search(this.rules.other.nonSpaceChar)>=4||re.test($)||B.test($)||X.test($)||K.test($))break;if(!this.options.pedantic&&!le){let j=f.replace(this.rules.other.nestedContainerMarkers,\"\");if(this.rules.block.fences.test(j)||this.rules.block.heading.test(j)||this.rules.block.hr.test(j))break}let je=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(R)&&this.rules.block.lheading.test(`${f}\n${R}`)?`    ${Z.replace(/^ {0,3}/,\"\")}`:R;p+=`\n`+je,le=!0}E=!R.trim(),e=e.substring(we.length+1),f=Z.slice(T)}}let U=n.slice(k,r());i.loose||(c?i.loose=!0:this.rules.other.doubleBlankLine.test(U)&&(c=!0)),i.items.push({type:\"list_item\",raw:U,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]})}let u=i.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;i.raw=n.slice(0,r()).trimEnd();let d=[];for(let h of i.items)if(this.lexer.state.top=!1,d.push(this.lexer.inlineQueue.length),h.tokens=this.lexer.blockTokens(h.text,[]),!i.loose){let p=h.tokens.filter(m=>m.type===\"space\"),k=p.length>0&&p.some(m=>this.rules.other.anyLine.test(m.raw));i.loose=k}for(let h=0;h<i.items.length;h++){let p=i.items[h],k=p.tokens[0];if(p.task&&(k?.type===\"text\"||k?.type===\"paragraph\")){p.text=p.text.replace(this.rules.other.listReplaceTask,\"\"),k.raw=k.raw.replace(this.rules.other.listReplaceTask,\"\"),k.text=k.text.replace(this.rules.other.listReplaceTask,\"\");let m=this.lexer.inlineQueue;for(let f=d[h];f<m.length;f++)if(m[f].tokens===k.tokens){m[f].src=m[f].src.replace(this.rules.other.listReplaceTask,\"\");break}let b=this.rules.other.listTaskCheckbox.exec(p.raw);if(b){let f={type:\"checkbox\",raw:b[0]+\" \",checked:b[0]!==\"[ ]\"};p.checked=f.checked,i.loose?p.tokens[0]&&[\"paragraph\",\"text\"].includes(p.tokens[0].type)&&\"tokens\"in p.tokens[0]&&p.tokens[0].tokens?(p.tokens[0].raw=f.raw+p.tokens[0].raw,p.tokens[0].text=f.raw+p.tokens[0].text,p.tokens[0].tokens.unshift(f)):p.tokens.unshift({type:\"paragraph\",raw:f.raw,text:f.raw,tokens:[f]}):p.tokens.unshift(f)}}else p.task&&(p.task=!1)}if(i.loose)for(let h of i.items){h.loose=!0;for(let p of h.tokens)p.type===\"text\"&&(p.type=\"paragraph\")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){if(this.lexer.state.lastToken?.type===\"paragraph\"&&!this.rules.other.htmlBeginRegex(4).test(e))return;let n=Re(t[0]);return{type:\"html\",block:!0,raw:n,pre:t[1]===\"pre\"||t[1]===\"script\"||t[1]===\"style\",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&Te(t[2],\"()\")!==-1)return;let n=W(t[1]),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,\"$1\").replace(this.rules.inline.anyPunctuation,\"$1\"):\"\",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,\"$1\"):t[3];return{type:\"def\",tag:n,raw:C(t[0],`\n`),href:r,title:s}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=be(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,\"\").split(\"|\"),s=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,\"\").split(`\n`):[],o={type:\"table\",raw:C(t[0],`\n`),header:[],align:[],rows:[]};if(n.length===r.length){for(let i of r)this.rules.other.tableAlignRight.test(i)?o.align.push(\"right\"):this.rules.other.tableAlignCenter.test(i)?o.align.push(\"center\"):this.rules.other.tableAlignLeft.test(i)?o.align.push(\"left\"):o.align.push(null);for(let i=0;i<n.length;i++)o.header.push({text:n[i],tokens:this.lexer.inline(n[i]),header:!0,align:o.align[i]});for(let i of s)o.rows.push(be(i,o.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:\"heading\",raw:C(t[0],`\n`),depth:t[2].charAt(0)===\"=\"?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`\n`?t[1].slice(0,-1):t[1];return{type:\"paragraph\",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:\"text\",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){if(e.charCodeAt(0)!==92)return;let t=this.rules.inline.escape.exec(e);if(t)return{type:\"escape\",raw:t[0],text:t[1]}}tag(e){if(e.charCodeAt(0)!==60)return;let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:\"html\",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){if(this.lexer.state.linkParenPossible===!1)return;let t=e.charCodeAt(0);if(t!==91&&t!==33)return;let n=this.rules.inline.link.exec(e);if(n){let r=n[0].charAt(0)===\"!\"?2:1;if(!this.options.pedantic&&Ze(e,n[1],r,this.rules))return;let s=n[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let c=C(s.slice(0,-1),\"\\\\\");if((s.length-c.length)%2===0)return}else{let c=Te(n[2],\"()\");if(c===-2)return;if(c>-1){let d=(n[0].indexOf(\"!\")===0?5:4)+n[1].length+c;n[2]=n[2].substring(0,c),n[0]=n[0].substring(0,d).trim(),n[3]=\"\"}}let o=C(n[0].slice(0,-1),\"\\\\\");if((n[0].length-o.length)%2===0)return;let i=n[2],a=\"\";if(this.options.pedantic){let c=this.rules.other.pedanticHrefTitle.exec(i);c&&(i=c[1],a=c[3])}else a=n[3]?n[3].slice(1,-1):\"\";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?i=i.slice(1):i=i.slice(1,-1)),He(n,{href:i&&i.replace(this.rules.inline.anyPunctuation,\"$1\"),title:a&&a.replace(this.rules.inline.anyPunctuation,\"$1\")},n[0],this.lexer,this.rules)}}reflink(e,t){let n=e.charCodeAt(0);if(n!==91&&n!==33)return;let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let s=r[0].charAt(0)===\"!\"?2:1;if(!this.options.pedantic&&Ze(e,r[1],s,this.rules))return;let o=t[W(r[2]||r[1])];if(!o){let i=r[0].charAt(0);return{type:\"text\",raw:i,text:i}}return He(r,o,r[0],this.lexer,this.rules)}}emStrong(e,t,n=\"\"){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||!r[1]&&!r[2]&&!r[3]&&!r[4])return;let s=r[0][0],o=n===s,i=t.length-e.length,a=i;for(;!this.options.pedantic&&a>0&&t[a-1]===s;)a--;let c=[...t.slice(Math.max(0,a-2),a)].at(-1)??\"\",u=c===\"*\"||c===\"_\"||!!this.rules.inline.punctuation.exec(c);a<i&&(n=c);let d=a<i?u:n===\"*\"||n===\"_\"||!!this.rules.inline.punctuation.exec(n);if(r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;let h=r[1]||r[3]||\"\";if(!h||!n||d){let p=[...r[0]].length-1,k,m,b=p,f=0,R=i-a+p,E=!this.options.pedantic&&!!c.trim()&&(!!h||s===\"*\"&&!u);if(s!==\"*\"&&s!==\"_\")return;let T=s===\"*\"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd,U=oe(this,t,s),H=t.length-e.length+p;if(U<H)return;t=t.slice(-1*e.length+p);let K=U-H;for(T.lastIndex=0;(r=T.exec(t))!==null&&!(r.index>K);){if(k=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!k)continue;if(m=[...k].length,r[3]||r[4]){b+=m;continue}else if((r[5]||r[6]||E)&&R%3&&!((R+m)%3)){if(o&&(r[5]||r[6]))break;f+=m;continue}if(b-=m,b>0)continue;m=Math.min(m,m+b+f);let re=[...r[0]][0].length,B=e.slice(0,p+r.index+re+m);if(Math.min(p,m)%2){let se=B.slice(1,-1);return{type:\"em\",raw:B,text:se,tokens:this.lexer.inlineTokens(se)}}let X=B.slice(2,-2);return{type:\"strong\",raw:B,text:X,tokens:this.lexer.inlineTokens(X)}}}}codespan(e){if(e.charCodeAt(0)!==96)return;let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal,\" \"),r=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&s&&(n=n.substring(1,n.length-1)),{type:\"codespan\",raw:t[0],text:n}}}br(e){let t=e.charCodeAt(0);if(t!==32&&t!==92&&t!==10)return;let n=this.rules.inline.br.exec(e);if(n)return{type:\"br\",raw:n[0]}}del(e,t,n=\"\"){if(e.charCodeAt(0)!==126)return;let r=this.rules.inline.delLDelim.exec(e);if(!r)return;if(!(r[1]||\"\")||!n||this.rules.inline.punctuation.exec(n)){let o=[...r[0]].length-1,i,a,c=o,u=this.rules.inline.delRDelim,d=ae(this,t),h=t.length-e.length+o;if(d<h)return;t=t.slice(-1*e.length+o);let p=d-h;for(u.lastIndex=0;(r=u.exec(t))!==null&&!(r.index>p);){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==o))continue;if(r[3]||r[4]){c+=a;continue}if(c-=a,c>0)continue;a=Math.min(a,a+c);let k=[...r[0]][0].length,m=e.slice(0,o+r.index+k+a),b=m.slice(o,-o);return{type:\"del\",raw:m,text:b,tokens:this.lexer.inlineTokens(b)}}}}autolink(e){if(e.charCodeAt(0)!==60)return;let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]===\"@\"?(n=t[1],r=\"mailto:\"+n):(n=t[1],r=n),{type:\"link\",raw:t[0],text:n,href:r,autolink:!0,tokens:[{type:\"text\",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]===\"@\")n=t[0],r=\"mailto:\"+n;else{let s;do s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??\"\";while(s!==t[0]);n=t[0],t[1]===\"www.\"?r=\"http://\"+t[0]:r=t[0]}return{type:\"link\",raw:t[0],text:n,href:r,autolink:!0,tokens:[{type:\"text\",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:\"text\",raw:t[0],text:n?t[0]:De(t[0]),escaped:n}}}};var w=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||S,this.options.tokenizer=this.options.tokenizer||new _,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let t={other:O,block:ee.normal,inline:F.normal};this.options.pedantic?(t.block=ee.pedantic,t.inline=F.pedantic):this.options.gfm&&(t.block=ee.gfm,this.options.breaks?t.inline=F.breaks:t.inline=F.gfm),this.tokenizer.rules=t}static get rules(){return{block:ee,inline:F}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(O.carriageReturn,`\n`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.state.inRawBlock=!1,this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this;let r=this.state.lastToken;this.options.pedantic&&(e=e.replace(O.tabCharGlobal,\"    \").replace(O.spaceLine,\"\"));let s=1/0,o,i=this.options.gfm&&!this.options.pedantic&&this.tokenizer.paragraph===_.prototype.paragraph;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}this.state.lastToken=t.at(-1);let a;if(this.options.extensions?.block?.some(u=>(a=u.call({lexer:this},e,t))?(e=e.substring(a.raw.length),t.push(a),!0):!1))continue;if(a=this.tokenizer.space(e)){e=e.substring(a.raw.length);let u=t.at(-1);a.raw.length===1&&u!==void 0?u.raw+=`\n`:t.push(a);continue}if(a=this.tokenizer.code(e)){e=e.substring(a.raw.length);let u=t.at(-1);u?.type===\"paragraph\"||u?.type===\"text\"?(u.raw+=(u.raw.endsWith(`\n`)?\"\":`\n`)+a.raw,u.text+=`\n`+a.text,this.inlineQueue.at(-1).src=u.text):t.push(a);continue}if(a=this.tokenizer.fences(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.heading(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.hr(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.blockquote(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.list(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.html(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.def(e)){e=e.substring(a.raw.length);let u=t.at(-1);u?.type===\"paragraph\"||u?.type===\"text\"?(u.raw+=(u.raw.endsWith(`\n`)?\"\":`\n`)+a.raw,u.text+=`\n`+a.raw,this.inlineQueue.at(-1).src=u.text):(this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title}),t.push(a));continue}if(a=this.tokenizer.table(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.lheading(e)){e=e.substring(a.raw.length),t.push(a);continue}let c=e;if(this.options.extensions?.startBlock){let u=1/0,d=e.slice(1),h;this.options.extensions.startBlock.forEach(p=>{h=p.call({lexer:this},d),typeof h==\"number\"&&h>=0&&(u=Math.min(u,h))}),u<1/0&&u>=0&&(c=e.substring(0,u+1))}if(this.state.top&&(a=this.tokenizer.paragraph(c))){let u=t.at(-1);(n||u===o&&i)&&u?.type===\"paragraph\"?(u.raw+=(u.raw.endsWith(`\n`)?\"\":`\n`)+a.raw,u.text+=`\n`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text,o=u):(t.push(a),o=a),n=c.length!==e.length,e=e.substring(a.raw.length);continue}if(a=this.tokenizer.text(e)){e=e.substring(a.raw.length);let u=t.at(-1);u?.type===\"text\"?(u.raw+=(u.raw.endsWith(`\n`)?\"\":`\n`)+a.raw,u.text+=`\n`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):t.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,this.state.lastToken=r,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes(\"[\"))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!==\"!\")return!0;for(let n of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let r=n[0],s=r.lastIndexOf(\"[\");if(!(r.charAt(0)===\"!\"||!Object.hasOwn(this.tokens.links,W(r.slice(s+1,-1))))&&!(s>1&&this.linkInText(r.slice(1,s-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=e.includes(\")\");try{return this.#t(e,t)}finally{this.state.linkParenPossible=n}}#t(e,t){let n=e.includes(\"*\")||e.includes(\"_\")||e.includes(\"~\"),r=n||this.options.hooks?.emStrongMask||this.tokenizer.emStrong!==_.prototype.emStrong||this.tokenizer.del!==_.prototype.del?this.#r(e):e;if(!n)return this.#e(e,r,t);qe(this.tokenizer,r);try{return this.#e(e,r,t)}finally{ve(this.tokenizer)}}#e(e,t,n){let r=!1,s=\"\",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}r||(s=\"\"),r=!1;let i;if(this.options.extensions?.inline?.some(u=>(i=u.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length);let u=n.at(-1);i.type===\"text\"&&u?.type===\"text\"?(u.raw+=i.raw,u.text+=i.text):n.push(i);continue}let a=e[0];if(a===\"*\"||a===\"_\"){let u=t.length-e.length;if(oe(this.tokenizer,t,a)<=u){let h=1;for(;h<e.length&&e.charCodeAt(h)===a.charCodeAt(0);)h++;let p=e.substring(0,h),k=n.at(-1);k?.type===\"text\"&&!k.escaped?(k.raw+=p,k.text+=p):n.push({type:\"text\",raw:p,text:p,escaped:!1}),e=e.substring(h),s=a,r=!0;continue}}else if(a===\"~\"){let u=t.length-e.length;if(ae(this.tokenizer,t)<=u){let h=1;for(;h<e.length&&e.charCodeAt(h)===126;)h++;let p=e.substring(0,h),k=n.at(-1);k?.type===\"text\"&&!k.escaped?(k.raw+=p,k.text+=p):n.push({type:\"text\",raw:p,text:p,escaped:!1}),e=e.substring(h),s=a,r=!0;continue}}if(i=this.tokenizer.emStrong(e,t,s)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.del(e,t,s)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.autolink(e)){e=e.substring(i.raw.length),n.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e))){e=e.substring(i.raw.length),n.push(i);continue}let c=e;if(this.options.extensions?.startInline){let u=1/0,d=e.slice(1),h;this.options.extensions.startInline.forEach(p=>{h=p.call({lexer:this},d),typeof h==\"number\"&&h>=0&&(u=Math.min(u,h))}),u<1/0&&u>=0&&(c=e.substring(0,u+1))}if(i=this.tokenizer.inlineText(c)){e=e.substring(i.raw.length),i.raw.slice(-1)!==\"_\"&&(s=i.raw.slice(-1)),r=!0;let u=n.at(-1);u?.type===\"text\"?(u.raw+=i.raw,u.text+=i.text):n.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}#n(e){let{blockSkip:t,tag:n,autolink:r}=this.tokenizer.rules.inline,s=\"\",o=0,i;for(t.lastIndex=0;i=t.exec(e);){let a=i.index+(i[2]?i[2].length:0),c=i.index+i[0].length;if(e.charAt(a)===\"<\"){let u=e.slice(a),d=n.exec(u)||r.exec(u);if(!d){t.lastIndex=a+1;continue}c=a+d[0].length,t.lastIndex=c}s+=e.slice(o,a)+\"[\"+\"a\".repeat(c-a-2)+\"]\",o=c}return s+e.slice(o)}#r(e){let t=e;if(this.tokens.links&&e.includes(\"[\")){let n=this.tokenizer.rules.inline.reflinkSearch,r=s=>{let o=s.lastIndexOf(\"[\");if(!Object.hasOwn(this.tokens.links,W(s.slice(o+1,-1))))return s;if(o>1&&s.charAt(0)!==\"!\"){let i=s.slice(1,o-1);if(this.linkInText(i))return\"[\"+i.replace(n,r)+\"][\"+\"a\".repeat(s.length-o-2)+\"]\"}return\"[\"+\"a\".repeat(s.length-2)+\"]\"};t=t.replace(n,r)}return t=t.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(n,r,s)=>s?\"+\".repeat(n.length):r?r+n.slice(r.length,-r.length).replace(/`/g,\"+\")+r:n),t=this.#n(t),t=this.options.hooks?.emStrongMask?.call({lexer:this},t)??t,t}infiniteLoopError(e){let t=\"Infinite loop on byte: \"+e;if(this.options.silent)console.error(t);else throw new Error(t)}};var I=class{options;parser;constructor(e){this.options=e||S}space(e){return\"\"}code({text:e,lang:t,escaped:n}){let r=(t||\"\").match(O.notSpaceStart)?.[0],s=e?e.replace(O.endingNewline,\"\")+`\n`:\"\";return r?'<pre><code class=\"language-'+y(r)+'\">'+(n?s:y(s,!0))+`</code></pre>\n`:\"<pre><code>\"+(n?s:y(s,!0))+`</code></pre>\n`}blockquote({tokens:e}){return`<blockquote>\n${this.parser.parse(e)}</blockquote>\n`}html({text:e}){return e}def(e){return\"\"}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>\n`}hr(e){return`<hr>\n`}list(e){let t=e.ordered,n=e.start,r=\"\";for(let i=0;i<e.items.length;i++){let a=e.items[i];r+=this.listitem(a)}let s=t?\"ol\":\"ul\",o=t&&n!==1?' start=\"'+n+'\"':\"\";return\"<\"+s+o+`>\n`+r+\"</\"+s+`>\n`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>\n`}checkbox({checked:e}){return\"<input \"+(e?'checked=\"\" ':\"\")+'disabled=\"\" type=\"checkbox\"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>\n`}table(e){let t=\"\",n=\"\";for(let s=0;s<e.header.length;s++)n+=this.tablecell(e.header[s]);t+=this.tablerow({text:n});let r=\"\";for(let s=0;s<e.rows.length;s++){let o=e.rows[s];n=\"\";for(let i=0;i<o.length;i++)n+=this.tablecell(o[i]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>\n<thead>\n`+t+`</thead>\n`+r+`</table>\n`}tablerow({text:e}){return`<tr>\n${e}</tr>\n`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?\"th\":\"td\";return(e.align?`<${n} align=\"${e.align}\">`:`<${n}>`)+t+`</${n}>\n`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${y(e,!0)}</code>`}br(e){return\"<br>\"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:r,autolink:s}){let o=s?y(n,!0):this.parser.parseInline(r),i=xe(e);if(i===null)return o;e=y(i,s);let a='<a href=\"'+e+'\"';return t&&(a+=' title=\"'+y(t)+'\"'),a+=\">\"+o+\"</a>\",a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let s=xe(e);if(s===null)return y(n);e=s;let o=`<img src=\"${y(e)}\" alt=\"${y(n)}\"`;return t&&(o+=` title=\"${y(t)}\"`),o+=\">\",o}text(e){return\"tokens\"in e&&e.tokens?this.parser.parseInline(e.tokens):\"escaped\"in e&&e.escaped?e.text:y(e.text)}};var z=class{parser;strong({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}em({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}codespan({text:e}){return e}del({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}html({text:e}){return e}text({text:e}){return e}link({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}image({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}br(){return`\n`}checkbox({raw:e}){return e}};var P=class l{options;renderer;textRenderer;constructor(e){this.options=e||S,this.options.renderer=this.options.renderer||new I,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new z,this.textRenderer.parser=this}static parse(e,t){return new l(t).parse(e)}static parseInline(e,t){return new l(t).parseInline(e)}parse(e){this.renderer.parser=this;let t=\"\";for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let o=r,i=this.options.extensions.renderers[o.type].call({parser:this},o);if(i!==!1||![\"space\",\"hr\",\"heading\",\"code\",\"table\",\"blockquote\",\"list\",\"checkbox\",\"html\",\"def\",\"paragraph\",\"text\"].includes(o.type)){t+=i===!1?\"\":i??\"\";continue}}let s=r;switch(s.type){case\"space\":{t+=this.renderer.space(s);break}case\"hr\":{t+=this.renderer.hr(s);break}case\"heading\":{t+=this.renderer.heading(s);break}case\"code\":{t+=this.renderer.code(s);break}case\"table\":{t+=this.renderer.table(s);break}case\"blockquote\":{t+=this.renderer.blockquote(s);break}case\"list\":{t+=this.renderer.list(s);break}case\"checkbox\":{t+=this.renderer.checkbox(s);break}case\"html\":{t+=this.renderer.html(s);break}case\"def\":{t+=this.renderer.def(s);break}case\"paragraph\":{t+=this.renderer.paragraph(s);break}case\"text\":{t+=this.renderer.text(s);break}default:{let o='Token with \"'+s.type+'\" type was not found.';if(this.options.silent)return console.error(o),\"\";throw new Error(o)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=\"\";for(let r=0;r<e.length;r++){let s=e[r];if(this.options.extensions?.renderers?.[s.type]){let i=this.options.extensions.renderers[s.type].call({parser:this},s);if(i!==!1||![\"escape\",\"html\",\"link\",\"image\",\"checkbox\",\"strong\",\"em\",\"codespan\",\"br\",\"del\",\"text\"].includes(s.type)){n+=i===!1?\"\":i??\"\";continue}}let o=s;switch(o.type){case\"escape\":{n+=t.text(o);break}case\"html\":{n+=t.html(o);break}case\"link\":{n+=t.link(o);break}case\"image\":{n+=t.image(o);break}case\"checkbox\":{n+=t.checkbox(o);break}case\"strong\":{n+=t.strong(o);break}case\"em\":{n+=t.em(o);break}case\"codespan\":{n+=t.codespan(o);break}case\"br\":{n+=t.br(o);break}case\"del\":{n+=t.del(o);break}case\"text\":{n+=t.text(o);break}default:{let i='Token with \"'+o.type+'\" type was not found.';if(this.options.silent)return console.error(i),\"\";throw new Error(i)}}}return n}};var A=class{options;block;constructor(e){this.options=e||S}static passThroughHooks=new Set([\"preprocess\",\"postprocess\",\"processAllTokens\",\"emStrongMask\"]);static passThroughHooksRespectAsync=new Set([\"preprocess\",\"postprocess\",\"processAllTokens\"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?w.lex:w.lexInline}provideParser(e=this.block){return e?P.parse:P.parseInline}};function M(l,e){if(Array.isArray(e))for(let t=0;t<e.length;t++)l.push(e[t]);else l.push(e)}var ne=class{defaults=G();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=P;Renderer=I;TextRenderer=z;Lexer=w;Tokenizer=_;Hooks=A;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(M(n,t.call(this,r)),r.type){case\"table\":{let s=r;for(let o of s.header)M(n,this.walkTokens(o.tokens,t));for(let o of s.rows)for(let i of o)M(n,this.walkTokens(i.tokens,t));break}case\"list\":{let s=r;M(n,this.walkTokens(s.items,t));break}default:{let s=r;this.defaults.extensions?.childTokens?.[s.type]?this.defaults.extensions.childTokens[s.type].forEach(o=>{let i=s[o].flat(1/0);M(n,this.walkTokens(i,t))}):s.tokens&&M(n,this.walkTokens(s.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:Object.create(null),childTokens:Object.create(null)};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error(\"extension name required\");if(\"renderer\"in s){let o=t.renderers[s.name];o?t.renderers[s.name]=function(...i){let a=s.renderer.apply(this,i);return a===!1&&(a=o.apply(this,i)),a}:t.renderers[s.name]=s.renderer}if(\"tokenizer\"in s){if(!s.level||s.level!==\"block\"&&s.level!==\"inline\")throw new Error(\"extension level must be 'block' or 'inline'\");let o=t[s.level];o?o.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level===\"block\"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level===\"inline\"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}\"childTokens\"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),r.extensions=t),n.renderer){let s=this.defaults.renderer||new I(this.defaults);for(let o in n.renderer){if(!(o in s))throw new Error(`renderer '${o}' does not exist`);if([\"options\",\"parser\"].includes(o))continue;let i=o,a=n.renderer[i],c=s[i];s[i]=(...u)=>{let d=a.apply(s,u);return d===!1&&(d=c.apply(s,u)),d===!1?\"\":d??\"\"}}r.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new _(this.defaults);for(let o in n.tokenizer){if(!(o in s))throw new Error(`tokenizer '${o}' does not exist`);if([\"options\",\"rules\",\"lexer\"].includes(o))continue;let i=o,a=n.tokenizer[i],c=s[i];s[i]=(...u)=>{let d=a.apply(s,u);return d===!1&&(d=c.apply(s,u)),d}}r.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new A;for(let o in n.hooks){if(!(o in s))throw new Error(`hook '${o}' does not exist`);if([\"options\",\"block\"].includes(o))continue;let i=o,a=n.hooks[i],c=s[i];A.passThroughHooks.has(o)?s[i]=u=>{if(s.options.async&&A.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(s,u);return c.call(s,h)})();let d=a.call(s,u);return c.call(s,d)}:s[i]=(...u)=>{if(s.options.async)return(async()=>{let h=await a.apply(s,u);return h===!1&&(h=await c.apply(s,u)),h})();let d=a.apply(s,u);return d===!1&&(d=c.apply(s,u)),d}}r.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,o=n.walkTokens;r.walkTokens=function(i){let a=[];return M(a,o.call(this,i)),s&&M(a,s.call(this,i)),a}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return w.lex(e,t??this.defaults)}parser(e,t){return P.parse(e,t??this.defaults)}parseMarkdown(e){return(n,r)=>{let s={...r},o={...this.defaults,...s},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return i(new Error(\"marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.\"));if(typeof n>\"u\"||n===null)return i(new Error(\"marked(): input parameter is undefined or null\"));if(typeof n!=\"string\")return i(new Error(\"marked(): input parameter is of type \"+Object.prototype.toString.call(n)+\", string expected\"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let a=o.hooks?await o.hooks.preprocess(n):n,u=await(o.hooks?await o.hooks.provideLexer(e):e?w.lex:w.lexInline)(a,o),d=o.hooks?await o.hooks.processAllTokens(u):u;o.walkTokens&&await Promise.all(this.walkTokens(d,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?P.parse:P.parseInline)(d,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(i);try{o.hooks&&(n=o.hooks.preprocess(n));let c=(o.hooks?o.hooks.provideLexer(e):e?w.lex:w.lexInline)(n,o);o.hooks&&(c=o.hooks.processAllTokens(c)),o.walkTokens&&this.walkTokens(c,o.walkTokens);let d=(o.hooks?o.hooks.provideParser(e):e?P.parse:P.parseInline)(c,o);return o.hooks&&(d=o.hooks.postprocess(d)),d}catch(a){return i(a)}}}onError(e,t){return n=>{if(n.message+=`\nPlease report this to https://github.com/markedjs/marked.`,e){let r=\"<p>An error occurred:</p><pre>\"+y(n.message+\"\",!0)+\"</pre>\";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}};var v=new ne;function x(l,e){return v.parse(l,e)}x.options=x.setOptions=function(l){return v.setOptions(l),x.defaults=v.defaults,ue(x.defaults),x};x.getDefaults=G;x.defaults=S;function jt(...l){return v.use(...l),x.defaults=v.defaults,ue(x.defaults),x}x.use=jt;x.walkTokens=function(l,e){return v.walkTokens(l,e)};x.parseInline=v.parseInline;x.Parser=P;x.parser=P.parse;x.Renderer=I;x.TextRenderer=z;x.Lexer=w;x.lexer=w.lex;x.Tokenizer=_;x.Hooks=A;x.parse=x;var En=x.options,zn=x.setOptions,Mn=x.walkTokens,Bn=x.parseInline,Dn=x,qn=P.parse,vn=w.lex;export{A as Hooks,w as Lexer,ne as Marked,P as Parser,I as Renderer,z as TextRenderer,_ as Tokenizer,S as defaults,G as getDefaults,vn as lexer,x as marked,En as options,Dn as parse,Bn as parseInline,qn as parser,zn as setOptions,jt as use,Mn as walkTokens};\n//# sourceMappingURL=marked.esm.js.map\n","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('uninitialized');\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\nexport const ATTACHMENT_KEY = '@attach';\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 * `array.push(...items)` overflows the stack for large `items`.\n * @template T\n * @param {T[]} array\n * @param {T[]} items\n */\nexport function push_array(array, items) {\n\tfor (var i = 0; i < items.length; i++) {\n\t\tarray.push(items[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 * Set on the effect that `pause_effect` was called on, i.e. the root of a paused subtree,\n * as opposed to its descendants which are merely `INERT`. This allows `resume_effect` on\n * an ancestor to skip subtrees that were paused for their own reasons (such as a block\n * whose condition is still false) rather than resurrecting them.\n */\nexport const PAUSED = 1 << 8;\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 used for async\nexport const REACTION_IS_UPDATING = 1 << 21;\nexport const ASYNC = 1 << 22;\n\nexport const ERROR_VALUE = 1 << 23;\n\n/** A run of the reaction asked for an abort signal (see `getAbortSignal`) */\nexport const HAS_ABORT_CONTROLLER = 1 << 27;\n\n// Flags exclusive to deriveds\n/** The global state of the derived is a value that was assigned to it, rather than a run of it */\nexport const ASSIGNED = 1 << 26;\n\nexport const STATE_SYMBOL = Symbol('$state');\n/** Marks component export objects, so that `proxy(...)` leaves them untouched */\nexport const COMPONENT_SYMBOL = Symbol('component');\nexport const LEGACY_PROPS = Symbol('legacy props');\nexport const LOADING_ATTR_SYMBOL = Symbol('');\nexport const PROXY_PATH_SYMBOL = Symbol('proxy path');\nexport const ATTRIBUTES_CACHE = Symbol('attributes');\nexport const CLASS_CACHE = Symbol('class');\nexport const STYLE_CACHE = Symbol('style');\nexport const TEXT_CACHE = Symbol('text');\nexport const FORM_RESET_HANDLER = Symbol('form reset');\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\nexport const CUSTOM_RENDERER_NODE_TYPE_MAP = /** @type {const} */ ({\n\tfragment: DOCUMENT_FRAGMENT_NODE,\n\telement: ELEMENT_NODE,\n\ttext: TEXT_NODE,\n\tcomment: COMMENT_NODE\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 * 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 * 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\tHYDRATION_START_FAILED\n} from '../../../constants.js';\nimport * as w from '../warnings.js';\nimport { get_next_sibling, get_node_value, node_type, remove_node } 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_type(node) === COMMENT_NODE) {\n\t\t\tvar data = get_node_value(node) ?? '';\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// \"[?\" followed by the serialized error, for failed boundaries\n\t\t\t\tdata.startsWith(HYDRATION_START_FAILED) ||\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) remove_node(node);\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_type(node) !== COMMENT_NODE) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\treturn get_node_value(node) ?? '';\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/** @type {Equals} */\nexport function safe_equals(value) {\n\treturn !safe_not_equal(value, this.v);\n}\n","/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\nimport { DEV } from 'esm-env';\n\n/**\n * You need to specify a custom condition to use a custom renderer in a non-browser environment such as Node. Add the `svelte-custom-renderer` resolve condition (eg. run Node with `--conditions=svelte-custom-renderer`).\n * \n * If you're using a bundler, add `svelte-custom-renderer` to its list of resolve conditions instead.\n * @returns {never}\n */\nexport function custom_renderer_unavailable_on_server() {\n\tif (DEV) {\n\t\tconst error = new Error(`custom_renderer_unavailable_on_server\\nYou need to specify a custom condition to use a custom renderer in a non-browser environment such as Node. Add the \\`svelte-custom-renderer\\` resolve condition (eg. run Node with \\`--conditions=svelte-custom-renderer\\`).\n\nIf you're using a bundler, add \\`svelte-custom-renderer\\` to its list of resolve conditions instead.\\nhttps://svelte.dev/e/custom_renderer_unavailable_on_server`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/custom_renderer_unavailable_on_server`);\n\t}\n}\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 the current component or any of its ancestors\n * @returns {never}\n */\nexport function missing_context() {\n\tif (DEV) {\n\t\tconst error = new Error(`missing_context\\nContext was not set in the current component or any of its ancestors\\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 * `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 * 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 * Can only create a `$derived(...)` with an `await` expression during component initialization or in a declaration tag\n * @returns {never}\n */\nexport function async_derived_orphan() {\n\tif (DEV) {\n\t\tconst error = new Error(`async_derived_orphan\\nCan only create a \\`$derived(...)\\` with an \\`await\\` expression during component initialization or in a declaration tag\\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 * `%operation%` is not supported when rendering with a custom renderer\n * @param {string} operation\n * @returns {never}\n */\nexport function custom_renderer_unsupported_operation(operation) {\n\tif (DEV) {\n\t\tconst error = new Error(`custom_renderer_unsupported_operation\\n\\`${operation}\\` is not supported when rendering with a custom renderer\\nhttps://svelte.dev/e/custom_renderer_unsupported_operation`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/custom_renderer_unsupported_operation`);\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()` cannot be called after an `await`\n * @returns {never}\n */\nexport function get_abort_signal_after_await() {\n\tif (DEV) {\n\t\tconst error = new Error(`get_abort_signal_after_await\\n\\`getAbortSignal()\\` cannot be called after an \\`await\\`\\nhttps://svelte.dev/e/get_abort_signal_after_await`);\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_after_await`);\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 * `createRawSnippet` cannot be used with a custom renderer\n * @returns {never}\n */\nexport function invalid_snippet_in_custom_renderer() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_snippet_in_custom_renderer\\n\\`createRawSnippet\\` cannot be used with a custom renderer\\nhttps://svelte.dev/e/invalid_snippet_in_custom_renderer`);\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_in_custom_renderer`);\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 * Cannot render content belonging to %guest% inside %host%. A custom renderer must define `embed` or `host` to be combined with another renderer\n * @param {string} guest\n * @param {string} host\n * @returns {never}\n */\nexport function renderer_cannot_cross(guest, host) {\n\tif (DEV) {\n\t\tconst error = new Error(`renderer_cannot_cross\\nCannot render content belonging to ${guest} inside ${host}. A custom renderer must define \\`embed\\` or \\`host\\` to be combined with another renderer\\nhttps://svelte.dev/e/renderer_cannot_cross`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/renderer_cannot_cross`);\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 * A snippet created in a component that was compiled without `experimental.customRenderer` cannot be rendered by a custom renderer\n * @returns {never}\n */\nexport function snippet_renderer_mismatch() {\n\tif (DEV) {\n\t\tconst error = new Error(`snippet_renderer_mismatch\\nA snippet created in a component that was compiled without \\`experimental.customRenderer\\` cannot be rendered by a custom renderer\\nhttps://svelte.dev/e/snippet_renderer_mismatch`);\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_renderer_mismatch`);\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}","/** @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\t// Ensure SvelteDate snapshots are tracked\n\t\t\tvalue.getTime();\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 { 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, 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.edges === null) {\n\t\tset_signal_status(derived, CLEAN);\n\t} else {\n\t\tset_signal_status(derived, MAYBE_DIRTY);\n\t}\n}\n","import { lifecycle_outside_component, missing_context } from './errors.js';\n\n/**\n * @template T\n * @param {(key: object) => T} get_context\n * @param {(key: object, context: T) => T} set_context\n * @param {(key: object) => boolean} has_context\n * @returns {[() => T, (context: T) => T, () => boolean]}\n */\nexport function create_context(get_context, set_context, has_context) {\n\tconst key = {};\n\n\treturn [\n\t\t() => {\n\t\t\tif (!has_context(key)) {\n\t\t\t\tmissing_context();\n\t\t\t}\n\n\t\t\treturn get_context(key);\n\t\t},\n\t\t(context) => set_context(key, context),\n\t\t() => has_context(key)\n\t];\n}\n\n/**\n * @typedef {{ p: Context | null, c: Map<unknown, unknown> | null }} Context\n */\n\n/**\n * @param {Context} context\n * @returns {Map<unknown, unknown> | null}\n */\nfunction get_parent_context(context) {\n\tlet parent = context.p;\n\twhile (parent !== null && parent.c === null) {\n\t\tparent = parent.p;\n\t}\n\treturn parent?.c ?? null;\n}\n\n/**\n * @param {Context | null} context\n * @param {string} name\n * @returns {Map<unknown, unknown>}\n */\nexport function get_or_init_context_map(context, name) {\n\tif (context === null) {\n\t\tlifecycle_outside_component(name);\n\t}\n\n\treturn (context.c ??= new Map(get_parent_context(context) || undefined));\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, COMPONENT_SYMBOL } from './constants.js';\nimport { define_property } from '../shared/utils.js';\nimport { create_context, get_or_init_context_map } from '../shared/context.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, has]` triplet of functions for working with context in a type-safe way.\n *\n * `get` will throw an error if `set` has not yet been called in the current component or any of\n * its ancestors.\n *\n * @template T\n * @returns {[() => T, (context: T) => T, () => boolean]}\n * @since 5.40.0\n */\nexport function createContext() {\n\treturn /** @type {[() => T, (context: T) => T, () => boolean]} */ (\n\t\tcreate_context(getContext, setContext, hasContext)\n\t);\n}\n\n/**\n * Retrieves the context set with the specified `key` in the current component or any of its\n * ancestors. If multiple components set the same key, the value from the closest one is returned.\n * A `setContext` call in the current component is only visible to `getContext` calls that run after it.\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(component_context, '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 the component itself and all of its\n * descendants (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(component_context, '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 the current component or any of\n * its ancestors. 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(component_context, 'hasContext');\n\treturn context_map.has(key);\n}\n\n/**\n * Retrieves the whole context map that belongs to the current component, including entries\n * inherited from its ancestors. Must be called during component initialisation. Useful, for\n * example, if you 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(component_context, '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 mark_as_component(component);\n}\n\n/**\n * Add a symbol to the object (or create one if undefined) to mark it as a component so it isn't proxified.\n * @param {any} component\n */\nexport function mark_as_component(component = {}) {\n\tdefine_property(component, COMPONENT_SYMBOL, { value: true });\n\treturn component;\n}\n\n/** @returns {boolean} */\nexport function is_runes() {\n\treturn !legacy_mode_flag || (component_context !== null && component_context.l === null);\n}\n","/** @import { Renderer } from './types.js'; */\n\nimport { hydrating, set_hydrating } from '../dom/hydration.js';\n\n/**\n * @type {Renderer<any> | null}\n */\nexport let current_renderer = null;\n\n/**\n * @param {Renderer<any> | null} value\n */\nexport function set_renderer(value) {\n\tcurrent_renderer = value;\n}\n\n/** How many `push_renderer` calls haven't been matched by a `pop_renderer` yet */\nvar depth = 0;\n\n/** @type {number[]} Depths of pushes that suspended hydration, including nested hydrate calls */\nvar suspended_hydration_at = [];\n\n/**\n * Makes `value` the current renderer (`null` for the DOM), returning the previous one.\n * Every call must be matched by a call to `pop_renderer` with the returned value\n * (in a `finally` block, if anything in between can throw).\n *\n * Custom renderers never hydrate, so hydration is suspended while one is active.\n * This doesn't allocate, since it runs for every effect when custom renderers are used.\n * @param {Renderer<any> | null} value\n * @returns {Renderer<any> | null}\n */\nexport function push_renderer(value) {\n\tvar previous = current_renderer;\n\tcurrent_renderer = value;\n\tdepth += 1;\n\n\t// this is to allow hydration code to treeshake\n\tif (hydrating && value !== null) {\n\t\tset_hydrating(false);\n\t\tsuspended_hydration_at.push(depth);\n\t}\n\n\treturn previous;\n}\n\n/**\n * Restores the renderer that was current before the matching `push_renderer` call\n * @param {Renderer<any> | null} previous The value returned by `push_renderer`\n */\nexport function pop_renderer(previous) {\n\tif (suspended_hydration_at[suspended_hydration_at.length - 1] === depth) {\n\t\tsuspended_hydration_at.pop();\n\t\tset_hydrating(true);\n\t}\n\n\tdepth -= 1;\n\tcurrent_renderer = previous;\n}\n","/** @import { Effect, Source, Value } from '#client' */\n/** @import { Batch } from './batch.js' */\nimport { DESTROYED, EFFECT_TRANSPARENT, 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 { current_renderer, set_renderer } from '../custom-renderer/state.js';\nimport { custom_renderers_flag } from '../../flags/index.js';\nimport { invoke_error_boundary } from '../error-handling.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tget,\n\tset_active_effect,\n\tset_active_reaction\n} from '../runtime.js';\nimport { current_batch } from './batch.js';\nimport {\n\treactivity_loss_tracker,\n\tderived,\n\tderived_safe_equal,\n\tset_reactivity_loss_tracker,\n\tasync_expression,\n\tis_uninitialized\n} from './deriveds.js';\nimport { async_effect, block, branch } 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\tvar parent = /** @type {Effect} */ (active_effect);\n\tvar deriveds = sync.map(is_runes() ? derived : derived_safe_equal);\n\n\tif (DEV) {\n\t\tderiveds.forEach((d, i) => {\n\t\t\t// TODO this is kinda useful for debugging but a lousy implementation —\n\t\t\t// maybe the compiler could pass through the template string\n\t\t\td.label = sync[i]\n\t\t\t\t.toString()\n\t\t\t\t.replace('() => ', '')\n\t\t\t\t.replaceAll('$.eager(() => ', '$state.eager(')\n\t\t\t\t.replace(/\\$\\.get\\((.+?)\\)/g, (_, id) => id);\n\t\t});\n\t}\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 (pending.length > 0) {\n\t\tvar restore = capture();\n\t\tvar decrement_pending = increment_pending();\n\t\tvar p = pending.length === 1 ? pending[0].promise : Promise.all(pending.map((b) => b.promise));\n\n\t\tp.then(() => {\n\t\t\tif ((parent.f & DESTROYED) !== 0) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Keep the caller's context, but use the script's batch to read its first values.\n\t\t\trestore(pending[0].run.get_batch());\n\n\t\t\ttry {\n\t\t\t\trun();\n\t\t\t} catch (error) {\n\t\t\t\tinvoke_error_boundary(error, parent);\n\t\t\t}\n\n\t\t\tunset_context();\n\t\t}).finally(decrement_pending);\n\t} else {\n\t\trun();\n\t}\n\n\tfunction run() {\n\t\tif (blockers.some((b) => b.failed)) return;\n\n\t\tif (async.length === 0) {\n\t\t\tfn(deriveds);\n\t\t\treturn;\n\t\t}\n\n\t\tvar signals = async.map((fn) => async_expression(fn));\n\n\t\t/** @type {Effect | null} */\n\t\tvar effect = null;\n\n\t\tblock(() => {\n\t\t\tfor (var s of signals) {\n\t\t\t\tif (is_uninitialized(s)) {\n\t\t\t\t\tget(s);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (effect !== null) {\n\t\t\t\t/** @type {Batch} */ (current_batch).revalidate_branch(effect);\n\t\t\t} else {\n\t\t\t\teffect = branch(() => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfn([...deriveds, ...signals]);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tinvoke_error_boundary(error, parent);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}, EFFECT_TRANSPARENT);\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\tvar previous_renderer = custom_renderers_flag ? current_renderer : null;\n\n\tif (DEV) {\n\t\tvar previous_dev_stack = dev_stack;\n\t}\n\n\t/**\n\t * @param {Batch | null} [batch] the batch to continue in, if not the one that was active before\n\t */\n\treturn function restore(batch = previous_batch) {\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 (custom_renderers_flag) {\n\t\t\tset_renderer(previous_renderer);\n\t\t}\n\n\t\tif (batch !== null && (previous_effect.f & DESTROYED) === 0) {\n\t\t\t// A batch that was merged into another one continues as that one.\n\t\t\t// TODO we only need the check here because `{#await ...}` blocks\n\t\t\t// are anomalous. Once we retire them we can get rid of it\n\t\t\tmerge_target(batch).activate();\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/** `true` between a `save` thunk restoring a context and the end of that synchronous segment */\nvar restored = false;\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\t// the context restored by an earlier `save` in this expression must not\n\t// outlive the synchronous segment that is about to end at this `await`\n\tunsave();\n\tvar value = await promise;\n\n\treturn () => {\n\t\trestore();\n\t\trestored = true;\n\t\treturn value;\n\t};\n}\n\n/**\n * Unset the context if a `save` thunk restored it in the current synchronous segment,\n * so that a foreign microtask can never run inside a restored reaction context.\n * Called at every suspension point, and at the end of async expression bodies —\n * `async () => (await $.save(a))().b` becomes `async () => { try { return (await $.save(a))().b; } finally { $.unsave(); } }`\n * @template T\n * @param {T} [value]\n * @returns {T}\n */\nexport function unsave(value) {\n\tif (restored) unset_context();\n\treturn /** @type {T} */ (value);\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\tunsave();\n\tvar previous_reactivity_loss_tracker = 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_reactivity_loss_tracker) {\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_reactivity_loss_tracker);\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_reactivity_loss_tracker) {\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// eslint-disable-next-line no-useless-assignment\n\tlet invoke_return = true;\n\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\tinvoke_return = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tvar prev = reactivity_loss_tracker;\n\t\t\ttry {\n\t\t\t\tyield value;\n\t\t\t} catch (e) {\n\t\t\t\tset_reactivity_loss_tracker(prev);\n\t\t\t\t// If the yield throws, we need to call `return` but not return its value, instead rethrow\n\t\t\t\tif (iterator.return !== undefined) {\n\t\t\t\t\t(await track_reactivity_loss(iterator.return()))();\n\t\t\t\t}\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tset_reactivity_loss_tracker(prev);\n\t\t}\n\t} catch (error) {\n\t\tinvoke_return = false;\n\t\tthrow error;\n\t} finally {\n\t\t// If the iterator had an abrupt completion (break) and `return` is defined on the iterator, call it and return the value\n\t\tif (invoke_return && 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\trestored = false;\n\tset_active_effect(null);\n\tset_active_reaction(null);\n\tset_component_context(null);\n\tif (custom_renderers_flag) {\n\t\tset_renderer(null);\n\t}\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 * The script's state while a `run` step executes.\n * Async expressions set `batch` when they deliver their first value. `continued` holds callbacks\n * to run after the script resumes, and `signals` lists the expressions in creation order.\n * @type {Runner | null}\n */\nexport let current_runner = null;\n\nclass Runner {\n\t/** @type {ReturnType<typeof capture>} */\n\t#restore;\n\n\t/**\n\t * Other batches that share this run\n\t * @type {Set<Batch>}\n\t */\n\t#adopters = new Set();\n\n\t/** @type {Batch} */\n\t#batch;\n\n\t/** @type {Array<() => void>} */\n\tcontinued = [];\n\n\t/**\n\t * Async deriveds created during this run\n\t * @type {Source[]}\n\t */\n\tsignals = [];\n\n\t/** Whether the full initialization promise chain is still pending. */\n\trunning = true;\n\n\tconstructor() {\n\t\t// TODO this should be unnecessary! these should just be class initializers. but\n\t\t// something somewhere (vitest?) must be doing some transpilation that breaks classes\n\t\tthis.#batch = /** @type {Batch} */ (current_batch);\n\t\tthis.#restore = capture();\n\t}\n\n\t/** The batch to continue in, even if the original fork was discarded. */\n\tget_batch() {\n\t\tif (!merge_target(this.#batch).linked) {\n\t\t\tfor (const b of this.#adopters) {\n\t\t\t\tvar target = merge_target(b);\n\t\t\t\tif (target.linked) this.#batch = target;\n\t\t\t}\n\t\t}\n\n\t\treturn this.#batch;\n\t}\n\n\trestore() {\n\t\tthis.#restore(this.get_batch());\n\t}\n\n\t/**\n\t *\n\t * @param {Array<() => void | Promise<void>>} thunks\n\t */\n\trun(thunks) {\n\t\tvar active = /** @type {Effect} */ (active_effect);\n\n\t\tvar promise = Promise.resolve(this.#invoke(thunks[0]));\n\t\tvar blockers = [new Blocker(this, promise)];\n\n\t\tfor (const fn of thunks.slice(1)) {\n\t\t\tpromise = promise.then(() => {\n\t\t\t\tif ((active.f & DESTROYED) !== 0) {\n\t\t\t\t\tthrow STALE_REACTION;\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis.restore();\n\t\t\t\t\treturn this.#invoke(fn);\n\t\t\t\t} finally {\n\t\t\t\t\t// We gotta unset context directly in case the function returns a promise, in which case\n\t\t\t\t\t// unset_context in .finally() would be too late\n\t\t\t\t\tunset_context();\n\t\t\t\t\t// Release buffered results now that the script has used the previous step's first values.\n\t\t\t\t\tthis.#continue();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tblockers.push(new Blocker(this, promise));\n\t\t}\n\n\t\tpromise = promise\n\t\t\t.catch((error) => {\n\t\t\t\tif ((active.f & DESTROYED) === 0) {\n\t\t\t\t\tthis.restore();\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tinvoke_error_boundary(error, active);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tunset_context();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t// The last step has no following step to release its buffered results.\n\t\t\t.finally(() => this.#continue());\n\n\t\tasync_effect(() => {\n\t\t\t// Inside an effect so later adopting branches can rerun this\n\t\t\tvar batch = /** @type {Batch} */ (current_batch);\n\t\t\tthis.#adopters.add(batch);\n\t\t\tvar decrement_pending = increment_pending();\n\n\t\t\tpromise.finally(() => {\n\t\t\t\t// An adopting batch must also run effects created after it adopted the script's branch.\n\t\t\t\tvar target = merge_target(batch);\n\n\t\t\t\tif (target.linked && (active.f & DESTROYED) === 0) {\n\t\t\t\t\ttarget.revalidate_branch(active);\n\t\t\t\t}\n\n\t\t\t\tdecrement_pending();\n\n\t\t\t\tthis.running = false;\n\t\t\t});\n\t\t});\n\n\t\treturn blockers;\n\t}\n\n\t/**\n\t * Switch away from the previous batch (which is now obsolete)\n\t * to another one\n\t * @param {Batch} batch\n\t */\n\tswitch(batch) {\n\t\tthis.#batch = batch;\n\t}\n\n\t#continue() {\n\t\tfor (const fn of this.continued.splice(0)) fn();\n\t}\n\n\t/**\n\t * @param {() => void | Promise<void>} fn\n\t */\n\t#invoke(fn) {\n\t\tvar previous_runner = current_runner;\n\t\tcurrent_runner = this;\n\n\t\ttry {\n\t\t\treturn fn();\n\t\t} finally {\n\t\t\tcurrent_runner = previous_runner;\n\t\t}\n\t}\n}\n\nexport class Blocker {\n\tsettled = false;\n\tfailed = false;\n\n\t/**\n\t * @param {Runner} run\n\t * @param {Promise<any>} promise\n\t */\n\tconstructor(run, promise) {\n\t\tthis.run = run;\n\t\tthis.promise = promise\n\t\t\t.catch(() => {\n\t\t\t\tthis.failed = true;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tthis.settled = true;\n\t\t\t\tunset_context();\n\t\t\t});\n\t}\n}\n\n/**\n * @param {Array<() => void | Promise<void>>} thunks\n */\nexport function run(thunks) {\n\treturn new Runner().run(thunks);\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 * Adds pending work to the current batch, and to the boundary of the active effect. If the batch is merged\n * into another one before the work is done, it's that batch's from then on (see `Batch#merge`)\n * @returns {() => void}\n */\nexport function increment_pending() {\n\tvar effect = /** @type {Effect} */ (active_effect);\n\tvar boundary = effect.b; // undefined if called outside the render tree, e.g. a standalone $effect.root\n\tvar batch = merge_target(/** @type {Batch} */ (current_batch));\n\n\t/** The nearest boundary with a pending snippet, if there is one */\n\tvar pending = boundary;\n\n\twhile (pending && !pending.is_pending) {\n\t\tpending = pending.parent;\n\t}\n\n\tbatch.increment(effect);\n\tpending?.increment(effect, batch);\n\tboundary?.update_effect_pending(1);\n\n\treturn () => {\n\t\tmerge_target(batch).decrement(effect);\n\t\t// The boundary keeps counts under the originating batch, even if it was merged.\n\t\tpending?.decrement(effect, batch);\n\t\tboundary?.update_effect_pending(-1);\n\t};\n}\n\n/**\n * The batch that `batch` was merged into, if any (transitively), else `batch` itself\n * @param {Batch} batch\n */\nexport function merge_target(batch) {\n\twhile (batch.merged !== null) batch = batch.merged;\n\treturn batch;\n}\n","/** @import { BatchRecord, BatchValue, Derived, DerivedRecord, Effect, Reaction, Source, Value } from '#client' */\n/** @import { Batch } from './batch.js'; */\nimport { DEV } from 'esm-env';\nimport {\n\tDERIVED,\n\tDIRTY,\n\tEFFECT_PRESERVED,\n\tSTALE_REACTION,\n\tASYNC,\n\tDESTROYED,\n\tINERT,\n\tCONNECTED,\n\tASSIGNED,\n\tERROR_VALUE,\n\tHAS_ABORT_CONTROLLER\n} from '#client/constants';\nimport {\n\tactive_reaction,\n\tactive_effect,\n\tupdate_reaction,\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\tis_current,\n\tpromote_record,\n\tchanged_since,\n\tis_dirty,\n\tabort_all,\n\tabort_controller,\n\tget\n} from '../runtime.js';\nimport { equals, safe_equals } from './equality.js';\nimport * as e from '../errors.js';\nimport * as w from '../warnings.js';\nimport { async_effect, destroy_effect, destroy_effect_children, teardown } from './effects.js';\nimport { eager_effects, set_eager_effects, source } from './sources.js';\nimport { get_error, invariant } 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, view_batch, view_cache } from './batch.js';\nimport { current_runner, increment_pending, merge_target, unset_context } from './async.js';\nimport { deferred, includes, noop } from '../../shared/utils.js';\nimport { update_derived_status } from './status.js';\nimport { stringify_derived } from '../dev/debug.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\tdv: null,\n\t\tedges: 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\nexport const OBSOLETE = Symbol('obsolete');\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 * @param {(error: unknown) => void} [onready] Called when the first result is captured; receives its error, if any\n * @returns {Source<V>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function async_expression(fn, label, location, onready) {\n\tvar signal = source(/** @type {V} */ (UNINITIALIZED));\n\tsignal.f |= ASYNC;\n\n\tif (DEV) signal.label = label ?? stringify_derived(fn);\n\n\t/** @type {Set<ReturnType<typeof deferred<V>>>} */\n\tvar deferreds = new Set();\n\n\t// `run` continues in the creating batch's view; other batches' results wait until then.\n\t// A superseded or obsolete run lets another batch supply the first value.\n\tvar runner = current_runner;\n\n\t/**\n\t * The batch whose run delivers the first value (`null`: whichever comes first)\n\t * @type {Batch | null}\n\t */\n\tvar resolver = runner && current_batch;\n\n\t/**\n\t * Results buffered until the script continues; `null` disables buffering.\n\t * @type {Array<() => void> | null}\n\t */\n\tvar waiting = runner && [];\n\n\t/**\n\t * Retry buffered results, or release them once the script has continued.\n\t * @param {boolean} [continued]\n\t */\n\tfunction flush_waiting(continued = false) {\n\t\tvar fns = /** @type {Array<() => void>} */ (waiting);\n\t\twaiting = continued ? null : [];\n\t\tif (continued) resolver = null;\n\t\tfor (const fn of fns) fn();\n\t}\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\n\t\ttry {\n\t\t\tvar result = fn();\n\t\t\tif (result === UNINITIALIZED) return;\n\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\tvar promise = Promise.resolve(result);\n\t\t\t// The then getter may also call `getAbortSignal()`, so capture its signal afterwards.\n\t\t\tvar abort_signal = abort_controller?.signal;\n\n\t\t\t// We call `unset_context` to undo any `save` calls that happen inside `fn()`\n\t\t\tpromise\n\t\t\t\t.then(\n\t\t\t\t\t(value) => {\n\t\t\t\t\t\tif (!abort_signal?.aborted) d.resolve(value);\n\t\t\t\t\t},\n\t\t\t\t\t(e) => {\n\t\t\t\t\t\t// An aborted run waits for its replacement, even if the user catches the abort.\n\t\t\t\t\t\t// A script awaiting another reaction's aborted promise must release its resolver:\n\t\t\t\t\t\t// the eager merge includes the signal's owner, but not necessarily this waiter.\n\t\t\t\t\t\tif (abort_signal?.aborted || (e === STALE_REACTION && runner === null)) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\td.reject(e === STALE_REACTION ? OBSOLETE : e);\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t\t.finally(unset_context);\n\t\t} catch (error) {\n\t\t\td.reject(error);\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\t\tvar decrement_pending = increment_pending();\n\n\t\tbatch.async_deriveds.get(effect)?.reject(OBSOLETE);\n\t\tdeferreds.add(d);\n\t\tbatch.async_deriveds.set(effect, d);\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\tinvariant(view_batch === null, 'Batch is currently active');\n\n\t\t\t\treactivity_loss_tracker = null;\n\t\t\t}\n\n\t\t\tif (waiting !== null && error !== OBSOLETE) {\n\t\t\t\tresolver ??= batch;\n\n\t\t\t\tif (merge_target(batch) !== merge_target(resolver)) {\n\t\t\t\t\t// Recheck staleness after waiting: the batch may have rerun or been discarded.\n\t\t\t\t\t// Merged batches remain valid while their merge target is linked.\n\t\t\t\t\twaiting.push(() => {\n\t\t\t\t\t\tvar obsolete =\n\t\t\t\t\t\t\t(effect.f & DESTROYED) !== 0 ||\n\t\t\t\t\t\t\t(batch.linked ? batch.async_deriveds.get(effect) !== d : !merge_target(batch).linked);\n\n\t\t\t\t\t\thandler(value, obsolete ? OBSOLETE : error);\n\t\t\t\t\t});\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdecrement_pending();\n\t\t\tdeferreds.delete(d);\n\n\t\t\tif (error) {\n\t\t\t\t// If the resolver's run is obsolete, let the next result supply the first value.\n\t\t\t\t// Do the same on failure if other results are pending. Try buffered results first.\n\t\t\t\t// A rerun in the same batch keeps ownership.\n\t\t\t\tif (\n\t\t\t\t\twaiting !== null &&\n\t\t\t\t\tresolver !== null &&\n\t\t\t\t\t(deferreds.size > 0 || error === OBSOLETE) &&\n\t\t\t\t\tmerge_target(resolver) === merge_target(batch) &&\n\t\t\t\t\tmerge_target(batch).async_deriveds.get(effect) === d\n\t\t\t\t) {\n\t\t\t\t\tresolver = null;\n\t\t\t\t\tflush_waiting();\n\t\t\t\t\treturn;\n\t\t\t\t} else if (error === OBSOLETE) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar same = signal.equals(value) && !error && (signal.f & ERROR_VALUE) === 0;\n\t\t\tmerge_target(batch).capture(signal, error ?? value, same, !!error);\n\n\t\t\tif (runner !== null) {\n\t\t\t\t// Let the script consume the first value in this batch's view before releasing buffered results.\n\t\t\t\trunner.switch(batch);\n\n\t\t\t\trunner.continued.push(() => flush_waiting(true));\n\n\t\t\t\trunner = null;\n\t\t\t}\n\n\t\t\tonready?.(error);\n\t\t\tonready = undefined;\n\n\t\t\tif (DEV && location !== undefined && !signal.equals(value)) {\n\t\t\t\trecent_async_deriveds.add(signal);\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tif (recent_async_deriveds.has(signal) && (effect.f & DESTROYED) === 0) {\n\t\t\t\t\t\tw.await_waterfall(/** @type {string} */ (signal.label), location);\n\t\t\t\t\t\trecent_async_deriveds.delete(signal);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\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) {\n\t\t\td.reject(OBSOLETE);\n\t\t}\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\tif (!current_runner) {\n\t\te.async_derived_orphan();\n\t}\n\n\tconst runner = current_runner;\n\tconst batch = /** @type {Batch} */ (current_batch);\n\n\treturn new Promise((fulfil, reject) => {\n\t\tvar source = async_expression(\n\t\t\t() => {\n\t\t\t\tvar effect = /** @type {Effect} */ (active_effect);\n\t\t\t\tvar target = merge_target(/** @type {Batch} */ (current_batch));\n\n\t\t\t\tif (runner.running && target !== batch && is_uninitialized(source)) {\n\t\t\t\t\t// Check all earlier expressions: assignments can initialize them out of order.\n\t\t\t\t\tfor (var i = index - 1; i >= 0; i--) {\n\t\t\t\t\t\tvar s = runner.signals[i];\n\n\t\t\t\t\t\tif (is_uninitialized(s)) {\n\t\t\t\t\t\t\t// re-run until we have a value\n\t\t\t\t\t\t\tget(s);\n\n\t\t\t\t\t\t\tvar pending = /** @type {Batch} */ (current_batch).async_deriveds;\n\t\t\t\t\t\t\tpending.get(effect)?.reject(OBSOLETE);\n\t\t\t\t\t\t\tpending.delete(effect);\n\t\t\t\t\t\t\treturn UNINITIALIZED;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn fn();\n\t\t\t},\n\t\t\tlabel,\n\t\t\tlocation,\n\t\t\t(error) => {\n\t\t\t\tif (error === undefined) fulfil(/** @type {Source<V>} */ (source));\n\t\t\t\telse reject(error);\n\t\t\t}\n\t\t);\n\n\t\tvar index = runner.signals.push(source) - 1;\n\t});\n}\n\n/**\n * Whether the signal of an async expression has no value yet in the active view of the world\n * @param {Source} signal\n */\nexport function is_uninitialized(signal) {\n\treturn (batch_values?.get(signal) ?? signal).v === UNINITIALIZED;\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 prev_active_effect = active_effect;\n\tvar parent = derived.parent;\n\n\tif (\n\t\t!is_destroying_effect &&\n\t\tparent !== null &&\n\t\tderived.v !== UNINITIALIZED && // if it was never evaluated before, it's guaranteed to fail downstream, so we try to execute instead\n\t\t(parent.f & (DESTROYED | INERT)) !== 0\n\t) {\n\t\tw.derived_inert();\n\n\t\t// (as if it ran — it can't change anymore)\n\t\tupdate_derived_status(derived);\n\n\t\treturn derived.v;\n\t}\n\n\t// Check before pushing, so that a recursive call doesn't remove the outer evaluation from the stack.\n\tif (DEV && includes.call(stack, derived)) {\n\t\te.derived_references_self();\n\t}\n\n\tset_active_effect(parent);\n\n\tvar prev_eager_effects = eager_effects;\n\n\tif (DEV) {\n\t\tset_eager_effects(new Set());\n\t\tstack.push(derived);\n\t}\n\n\ttry {\n\t\tdestroy_derived_effects(derived);\n\t\treturn update_reaction(derived);\n\t} finally {\n\t\tset_active_effect(prev_active_effect);\n\n\t\tif (DEV) {\n\t\t\tset_eager_effects(prev_eager_effects);\n\t\t\tstack.pop();\n\t\t}\n\t}\n}\n\n/**\n * Update the global state of a derived, adopting the active batch's run if its view has\n * become the real world (e.g. because a fork was committed), or re-evaluating it otherwise.\n * `signal` can be a source, too, which is cheaper than checking first (this is called for every dependency that\n * is checked): only reactions ever get a dirty status, so `is_dirty` returns `false` for a source right away\n * @param {Value} signal\n * @returns {void}\n */\nexport function update_derived(signal) {\n\tvar derived = /** @type {Derived} */ (signal);\n\n\tif (!is_dirty(derived)) return;\n\n\tvar records = view_batch?.records;\n\tvar record = records?.get(derived);\n\n\tif (record !== undefined && is_current(record.deps, record.dv)) {\n\t\t/** @type {Map<Reaction, BatchRecord>} */ (records).delete(derived);\n\t\tpromote_record(derived, record);\n\t} else {\n\t\t// (the result is stored by `update_dependencies`)\n\t\texecute_derived(derived);\n\t}\n}\n\n/**\n * The value of `derived` as the view of the world of the active batch sees it, with its version: an\n * assigned value that holds, or a run of it whose versions are what the view holds — a record in the\n * batch, or the derived itself (i.e. its global state) — or else a new run. Results are cached for the\n * lifetime of the view (see `view_cache`), unless the derived is disconnected, in which case nothing\n * would remove them from the cache when they become stale.\n * @param {Derived} derived\n * @returns {Derived | DerivedRecord | BatchValue}\n */\nexport function get_view(derived) {\n\tvar cache = /** @type {Map<Derived, Derived | DerivedRecord | BatchValue>} */ (view_cache);\n\tvar entry = cache.get(derived);\n\n\tif (entry !== undefined) return entry;\n\n\tvar batch = /** @type {Batch} */ (view_batch);\n\n\t// What the view holds for the derived is a write to it — an assignment (in this batch, or made while it commits),\n\t// or the value from before another batch's assignment that this view undoes — or else its global state. An assigned value\n\t// holds until one of the derived's dependencies — what its run in this view (its record in the batch, if\n\t// any, else its global run) read — is written after it (see `changed_since`). The value from before an\n\t// undone assignment is only used if it was assigned, too: a computed value was computed in some other\n\t// view of the world, and may depend on writes that this view undoes\n\tvar written = /** @type {Map<Value, BatchValue>} */ (batch_values).get(derived);\n\tvar held = written ?? derived;\n\tvar assigned = written === undefined ? (derived.f & ASSIGNED) !== 0 : written.assigned;\n\tvar record = /** @type {DerivedRecord | undefined} */ (batch.get_record(derived));\n\n\tif (assigned && !changed_since((record ?? derived).deps, held.wv)) {\n\t\tentry = held;\n\t} else if (record !== undefined && is_current(record.deps, record.dv)) {\n\t\tentry = record;\n\t} else if (\n\t\twritten === undefined &&\n\t\t!assigned &&\n\t\tderived.dv !== null &&\n\t\tis_current(derived.deps, derived.dv)\n\t) {\n\t\tentry = derived;\n\t} else {\n\t\texecute_derived(derived);\n\n\t\t// the run is stored in the batch, unless it is the real-world value (see `update_record`)\n\t\tentry = /** @type {DerivedRecord | undefined} */ (batch.records?.get(derived)) ?? derived;\n\t}\n\n\tif ((derived.f & CONNECTED) !== 0) {\n\t\tcache.set(derived, entry);\n\t}\n\n\treturn entry;\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.f & HAS_ABORT_CONTROLLER) !== 0) {\n\t\t\te.teardown?.();\n\t\t\tabort_all(e);\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 (but not for teardown-only effects)\n\t\t\tif (e.fn !== null) e.teardown = noop;\n\n\t\t\tremove_reactions(e);\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 && e.fn !== null) {\n\t\t\tupdate_effect(e);\n\t\t}\n\t}\n}\n","/** @import { Fork } from 'svelte' */\n/** @import { BatchRecord, BatchValue, Derived, DerivedRecord, Effect, Reaction, Source, Value } from '#client' */\n/** @import { Boundary } from '../dom/blocks/boundary.js' */\nimport {\n\tBLOCK_EFFECT,\n\tBRANCH_EFFECT,\n\tCLEAN,\n\tDESTROYED,\n\tDIRTY,\n\tEFFECT,\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\tDESTROYING,\n\tEFFECT_OFFSCREEN,\n\tASSIGNED,\n\tASYNC,\n\tREACTION_IS_UPDATING,\n\tBOUNDARY_EFFECT\n} from '#client/constants';\nimport { async_mode_flag, custom_renderers_flag } from '../../flags/index.js';\nimport { deferred, define_property } from '../../shared/utils.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tget,\n\tincrement_write_version,\n\tis_destroying_effect,\n\tis_dirty,\n\tis_outdated,\n\tpromote_record,\n\tprune_edges,\n\tuntrack,\n\tupdate_effect,\n\twrite_version,\n\tabort_record\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 {\n\teager_effects,\n\teager_effects_deferred,\n\tflush_eager_effects,\n\tsource,\n\tupdate\n} from './sources.js';\nimport { eager_effect, teardown, unlink_effect } from './effects.js';\nimport { UNINITIALIZED } from '../../../constants.js';\nimport { set_signal_status, update_derived_status } from './status.js';\nimport { invariant } from '../../shared/dev.js';\nimport { OBSOLETE } from './deriveds.js';\nimport { is_runes } from '../context.js';\nimport { merge_target } from './async.js';\n\n/** @type {Batch | null} */\nexport let first_batch = null;\n\n/** @type {Batch | null} */\nlet last_batch = null;\n\n/** @type {Batch | null} */\nexport let current_batch = null;\n\n/**\n * The batch currently being processed (see `#process`)\n * @type {Batch | null}\n */\nexport let processing_batch = null;\n\n/**\n * @typedef {Object} TeardownContext\n * @property {Map<Value, BatchValue>} reverted_values What teardowns see instead of the values sources hold: the values\n * from before the writes that caused the teardowns (the `previous` of the batch being processed, see `flush`). For\n * block effects that re-run right away because of a user effect's writes, also the writes of the effects that ran\n * before it in the same commit, which apply (see `flush_queued_effects`)\n * @property {Map<Derived, BatchValue>} derived_cache The values of deriveds in this view (see `runtime.js#teardown_view`),\n * until it changes\n * @property {TeardownContext | null} parent The context to restore after a nested flush or eager block\n */\n\n/**\n * Effect teardowns revert the writes that caused them (see `runtime.js#teardown_view`).\n * (A teardown outside of a flush reverts nothing, but gets a context to cache its deriveds in, for as long as it\n * runs — see `execute_effect_teardown`)\n * @type {TeardownContext | null}\n */\nexport let teardown_context = null;\n\n/** @param {TeardownContext | null} context */\nexport function set_teardown_context(context) {\n\tteardown_context = context;\n}\n\n/** @param {Map<Value, BatchValue>} [values] */\nexport function push_teardown_context(values) {\n\tvar context = (teardown_context = {\n\t\treverted_values: new Map(teardown_context?.reverted_values),\n\t\tderived_cache: new Map(),\n\t\tparent: teardown_context\n\t});\n\n\tfor (const [source, value] of values ?? []) context.reverted_values.set(source, value);\n\n\treturn context;\n}\n\n/**\n * A write in a teardown remains visible after returning to an enclosing teardown view,\n * and the deriveds that teardowns evaluated may depend on it\n * @param {Value} source\n */\nexport function teardown_write(source) {\n\tfor (var context = teardown_context; context !== null; context = context.parent) {\n\t\tcontext.reverted_values.delete(source);\n\t\tcontext.derived_cache.clear();\n\t}\n}\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 — along with their\n * versions: the batch's writes, and the values from before the writes of\n * other batches, which its view of the world undoes (see `activate`).\n * `null` means that the real world (i.e. the latest values) applies.\n * Doesn't contain computed deriveds, these are in {@link view_cache}.\n * @type {Map<Value, BatchValue> | null}\n */\nexport let batch_values = null;\n\n/**\n * The values of deriveds in the active view of the world, for as long as it is active (see `get_view`):\n * a record of a run (in which case `e` tells whether its value is an error), the derived itself if its\n * global state applies, or the write to it that holds (an assignment). Exists whenever `batch_values` does\n * @type {Map<Derived, Derived | DerivedRecord | BatchValue> | null}\n */\nexport let view_cache = null;\n\n/**\n * The batch whose view of the world is active (see `activate`). Block and async\n * effects that run while it is processed, and deriveds evaluated with values\n * that are not the latest, are recorded in this batch\n * @type {Batch | null}\n */\nexport let view_batch = null;\n\n/** @type {Effect | null} */\nlet last_scheduled_effect = null;\n\n/**\n * Batches whose view of the world changed because another batch committed, and that\n * therefore need to be processed again once the current flush is done (see `#commit`)\n * @type {Set<Batch>}\n */\nvar rebases = new Set();\n\nexport let is_flushing_sync = 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;\n\n/** Sources whose DEV update counts and stack traces need resetting after the flush. @type {Set<Value>} */\nexport const source_stacks = new Set();\n\n/**\n * A set of signals we have already seen while traversing in `batch.mark`.\n * Not always set to balance the common case of sources only having a couple\n * of (transitive) dependencies (where always creating a Set would be bad for perf)\n * with the edge case of extremely deep or wide dependency arrays with cycles.\n * @type {Set<any> | null}\n */\nvar seen = null;\n/** Number of transitive dependencies, see {@link seen} for more info */\nvar count_deps = 0;\n\nlet uid = 1;\n\n/** @type {number | null} */\nlet last_processed = null;\n\nexport class Batch {\n\tid = uid++;\n\n\t/** True as soon as `#process` was called */\n\tstarted = false;\n\n\tlinked = true;\n\n\t/** @type {Batch | null} */\n\tprev = null;\n\n\t/** @type {Batch | null} */\n\tnext = null;\n\n\t/** @type {Map<Effect, ReturnType<typeof deferred<any>>>} */\n\tasync_deriveds = new Map();\n\n\t/**\n\t * The current values (and their versions) of any sources that are updated in this batch,\n\t * including deriveds that were overridden via assignment — until it commits them (see `#commit`).\n\t * Its keys are those of `this.previous`, plus the sources this batch gave their first value. `e` says whether\n\t * the value is an error\n\t * @type {Map<Value, BatchValue>}\n\t */\n\tcurrent = new Map();\n\n\t/**\n\t * The values (and their versions) of any sources that are updated in this batch _before_ those updates took place.\n\t * For a derived, `assigned` says whether its value before was assigned, too (otherwise it was computed).\n\t * A source that this batch gave its first value (e.g. an async expression that resolved for the first time) has\n\t * no entry: there's no value from before it, so other views can't undo the write, and teardowns don't revert it.\n\t * @type {Map<Value, BatchValue>}\n\t */\n\tprevious = new Map();\n\n\t/**\n\t * Results of reactions that belong to this batch rather than to the real world:\n\t * deriveds evaluated in this batch's view of the world with values that are not the\n\t * latest ones, and block/async effects that ran while this batch was processed.\n\t * Effect records become global state when the batch commits (see `promote_record`)\n\t * @type {Map<Reaction, BatchRecord> | null}\n\t */\n\trecords = null;\n\n\t/**\n\t * Earlier batches whose changes are part of this batch's view of the world, because\n\t * they intersect with it (this batch will be merged into them, see `#merge`)\n\t * @type {Batch[]}\n\t */\n\tfolded = [];\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 * Each callback maps to the writes that apply in the teardowns it causes, if it was added\n\t * while block effects re-ran eagerly (see `eager_block_writes`)\n\t * @type {Map<(batch: Batch) => void, Map<Value, BatchValue> | null>}\n\t */\n\t#commit_callbacks = new Map();\n\n\t/**\n\t * If a fork is discarded, we need to destroy any effects that are no longer needed\n\t * (see `#commit_callbacks`)\n\t * @type {Map<(batch: Batch) => void, Map<Value, BatchValue> | null>}\n\t */\n\t#discard_callbacks = new Map();\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 * 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 * Effects to (re-)validate when this batch is processed next, and their status (DIRTY or MAYBE_DIRTY):\n\t * those that were scheduled while it wasn't being processed (see {@link schedule}), and those whose run\n\t * was deferred because it has pending work (see `#defer_effects`)\n\t * @type {Map<Effect, number>}\n\t */\n\t#unprocessed = new Map();\n\n\t/**\n\t * Effects that were scheduled in this batch but not yet 'resolved' into the\n\t * root effects that need to be flushed. Resolving — the upwards traversal that\n\t * marks the path to each effect on the shared effect tree (see #resolve) — is\n\t * deferred until the batch is processed, so that the markers are created and\n\t * consumed within a single traversal. Scheduling into other batches (which can\n\t * happen concurrently, e.g. while a batch is committed) can therefore never\n\t * observe (and be confused by) this batch's markers.\n\t * May contain duplicates — deduplication happens during resolving\n\t * @type {Effect[]}\n\t */\n\t#scheduled = [];\n\n\t/**\n\t * Branches that still exist, but will be destroyed when this batch\n\t * is committed — we skip over these during `#process`\n\t * @type {Set<Effect>}\n\t */\n\t#skipped_branches = new Set();\n\n\t/**\n\t * Branches that this batch selected (see `unskip_effect`). A branch that is offscreen until\n\t * it is committed (see `EFFECT_OFFSCREEN`) only exists in the views of the batches that selected it\n\t * @type {Set<Effect>}\n\t */\n\t#unskipped_branches = new Set();\n\n\tis_fork = false;\n\n\t/**\n\t * The batch that this one was merged into, if any (see `#merge`). Its async work that is still in flight\n\t * continues as part of that one\n\t * @type {Batch | null}\n\t */\n\tmerged = null;\n\n\t/**\n\t * Batches whose runs this batch aborted. Merge into them before waiting for pending work.\n\t * Requests belong to this batch because a synchronous derived can abort outside traversal,\n\t * before an unrelated batch is processed (e.g. a fork being committed).\n\t * @type {Set<Batch>}\n\t */\n\tmerge_requests = new Set();\n\n\t#decrement_queued = false;\n\n\tconstructor() {\n\t\tif (last_batch === null) {\n\t\t\tfirst_batch = last_batch = this;\n\t\t} else {\n\t\t\tlast_batch.next = this;\n\t\t\tthis.prev = last_batch;\n\t\t}\n\n\t\tlast_batch = this;\n\t}\n\n\t#is_deferred() {\n\t\tif (this.is_fork) return true;\n\n\t\tfor (const effect of this.#pending.keys()) {\n\t\t\tif (this.is_blocked_by(effect)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Whether `effect` is a branch that this batch skips, or that only exists offscreen for other batches\n\t * @param {Effect} effect\n\t */\n\t#skips(effect) {\n\t\treturn (\n\t\t\tthis.#skipped_branches.has(effect) ||\n\t\t\t((effect.f & EFFECT_OFFSCREEN) !== 0 && !this.#unskipped_branches.has(effect))\n\t\t);\n\t}\n\n\t/**\n\t * Whether `effect` is inside a branch that this batch skips, i.e. doesn't exist in its view of the world\n\t * @param {Effect} effect\n\t */\n\tis_skipped(effect) {\n\t\tfor (var e = /** @type {Effect | null} */ (effect); e !== null; e = e.parent) {\n\t\t\tif (this.#skips(e)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Whether async work in `effect` holds up this batch — or, with `root`, the boundary whose content `root` is.\n\t * It doesn't if the effect is inside a branch that this batch skips (the branch is going to be destroyed),\n\t * or inside a boundary that is pending (which shows its pending snippet in the meantime).\n\t * Unlike a skipped branch, the content of a pending boundary does exist in the view of the batch: its\n\t * effects are still re-validated (see `#revalidate`), they just don't keep the batch from committing\n\t * @param {Effect} effect\n\t * @param {Effect | null} [root]\n\t */\n\tis_blocked_by(effect, root = null) {\n\t\tfor (var e = /** @type {Effect | null} */ (effect); e !== null && e !== root; e = e.parent) {\n\t\t\tif (this.#skips(e)) return false;\n\n\t\t\tif (\n\t\t\t\t(e.f & (BOUNDARY_EFFECT | DESTROYED)) === BOUNDARY_EFFECT &&\n\t\t\t\t/** @type {Boundary} */ (e.b).is_pending\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t */\n\tskip_effect(effect) {\n\t\tthis.#skipped_branches.add(effect);\n\t\tthis.#unskipped_branches.delete(effect);\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t */\n\tunskip_effect(effect) {\n\t\tif (\n\t\t\tthis.#skipped_branches.delete(effect) ||\n\t\t\t(!this.#unskipped_branches.has(effect) &&\n\t\t\t\t((effect.f & EFFECT_OFFSCREEN) !== 0 ||\n\t\t\t\t\tthis.folded.some((batch) => batch.#skipped_branches.has(effect))))\n\t\t) {\n\t\t\t// This batch adopts a branch that it skipped (whose effects may have been reset, see `reset_branch`),\n\t\t\t// that so far only existed offscreen (possibly for another batch, whose view of the world its\n\t\t\t// effects ran in), or that a batch whose writes are part of its view skips (and so didn't run the\n\t\t\t// effects that its writes affect, or reset them) — re-validate its effects in this batch's view\n\t\t\tthis.revalidate_branch(effect);\n\t\t}\n\n\t\tthis.#unskipped_branches.add(effect);\n\t}\n\n\t/**\n\t * Like `unskip_effect`, for a branch that was just created offscreen while this batch is processed.\n\t * Its effects ran in this batch's view of the world when they were created, so there's nothing to re-validate\n\t * TODO can we skip revalidation in `unskip_effect` in more cases, by detecting whether things changed\n\t * inside a branch while it was skipped?\n\t * @param {Effect} effect\n\t */\n\tunskip_new_effect(effect) {\n\t\tthis.#unskipped_branches.add(effect);\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t */\n\trevalidate_branch(effect) {\n\t\tfor (var e = effect.first; e !== null; e = e.next) {\n\t\t\tvar flags = e.f;\n\n\t\t\t// (branches nested inside that exist offscreen for other batches only are not adopted)\n\t\t\tif ((flags & (DESTROYED | INERT)) === 0 && !this.#skips(e)) {\n\t\t\t\tif ((flags & (BRANCH_EFFECT | ROOT_EFFECT | EAGER_EFFECT)) === 0 && e.fn !== null) {\n\t\t\t\t\tthis.schedule(e, MAYBE_DIRTY);\n\t\t\t\t}\n\n\t\t\t\tthis.revalidate_branch(e);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Convert the effects that were scheduled in this batch into the root effects\n\t * that need to be traversed, marking the path to each effect (by clearing the\n\t * `CLEAN` flag on ancestor branches) so that the traversal can find them.\n\t * This happens right before traversal rather than at scheduling time, so that\n\t * the markers left on the (shared) effect tree are created and consumed within\n\t * a single traversal — scheduling into other batches can never observe them\n\t * @returns {Effect[]}\n\t */\n\t#resolve() {\n\t\t/** @type {Effect[]} */\n\t\tvar roots = [];\n\n\t\tfor (const effect of this.#scheduled) {\n\t\t\t// skip effects that are destroyed, or that already ran (e.g. because\n\t\t\t// they were reached by the traversal that preceded a drain iteration,\n\t\t\t// or because they were scheduled twice)\n\t\t\tif ((effect.f & DESTROYED) !== 0 || (effect.f & (DIRTY | MAYBE_DIRTY)) === 0) continue;\n\n\t\t\tvar e = effect;\n\t\t\tvar covered = false;\n\n\t\t\twhile (e.parent !== null) {\n\t\t\t\te = e.parent;\n\t\t\t\tvar flags = e.f;\n\n\t\t\t\tif ((flags & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) {\n\t\t\t\t\tif ((flags & CLEAN) === 0) {\n\t\t\t\t\t\t// the path to the root was already marked, meaning the\n\t\t\t\t\t\t// root was already collected — nothing left to do\n\t\t\t\t\t\tcovered = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\te.f ^= CLEAN;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!covered) {\n\t\t\t\troots.push(e);\n\t\t\t}\n\t\t}\n\n\t\tthis.#scheduled = [];\n\n\t\treturn roots;\n\t}\n\n\t#process() {\n\t\tcurrent_batch = processing_batch = this;\n\n\t\t// A different batch view may apply, even when processing continues within the same flush.\n\t\tteardown_context?.derived_cache.clear();\n\n\t\tif (async_mode_flag && this.started && last_processed !== this.id) {\n\t\t\t// Since this batch last ran, reactions may have come to depend on its writes without it\n\t\t\t// knowing (e.g. effects created by other batches), or have run in the view of other batches.\n\t\t\t// Re-validate them in this batch's view — this only re-runs those that are out of date\n\t\t\tthis.#revalidate(this.current.keys());\n\t\t}\n\n\t\tthis.started = true;\n\t\tlast_processed = this.id;\n\n\t\t// Deferred effects are rescheduled even if the batch still has pending work, because traversing the\n\t\t// tree could make an if block that contains the last blocking pending effect falsy, causing the batch\n\t\t// to no longer be deferred. If it still is, they are deferred again\n\t\tif (this.#unprocessed.size > 0) {\n\t\t\tfor (const [e, status] of this.#unprocessed) this.#add(e, status);\n\t\t\tthis.#unprocessed.clear();\n\t\t}\n\n\t\tif (DEV) {\n\t\t\t// track all the values that were updated during this flush,\n\t\t\t// so that they can be reset afterwards\n\t\t\tfor (const value of this.current.keys()) {\n\t\t\t\tsource_stacks.add(value);\n\t\t\t}\n\t\t}\n\n\t\tthis.activate();\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/** @type {Boundary[]} */\n\t\tvar revealed_boundaries = [];\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\t// Effects can be scheduled during traversal (e.g. because a parent each/await/etc\n\t\t// block updated an internal source, or because an effect invalidated itself)\n\t\t// hence we loop until there are no more scheduled effects.\n\t\twhile (this.#scheduled.length > 0) {\n\t\t\tif (flush_count++ > 1000) {\n\t\t\t\tthis.#unlink();\n\t\t\t\tinfinite_loop_guard(); // TODO try to reset the tree here?\n\t\t\t}\n\n\t\t\tfor (const root of this.#resolve()) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.#traverse(root, effects, render_effects, revealed_boundaries);\n\t\t\t\t} catch (e) {\n\t\t\t\t\treset_branch(root, true);\n\t\t\t\t\t// If there's no async work left, this branch is now dead and needs\n\t\t\t\t\t// to be discarded to not become a zombie that is never cleaned up.\n\t\t\t\t\t// See https://github.com/sveltejs/svelte/issues/18221#issuecomment-4497918414\n\t\t\t\t\t// for a (non-minimal) reproduction that demonstrates a case where this is necessary\n\t\t\t\t\t// to not get follow-up false-positives via \"batch has scheduled roots\" invariant errors.\n\t\t\t\t\tif (!this.#is_deferred()) this.discard();\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.#scheduled.length > 0) {\n\t\t\t\t// A later traversal may discover effects before ones we already collected.\n\t\t\t\t// Recollect them together so they are flushed in tree order, rather than\n\t\t\t\t// appending earlier effects after their later siblings.\n\t\t\t\tfor (const effect of render_effects) this.#scheduled.push(effect);\n\t\t\t\tfor (const effect of effects) this.#scheduled.push(effect);\n\t\t\t\trender_effects.length = 0;\n\t\t\t\teffects.length = 0;\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\t// these were marked during traversal already (see `mark_reactions`), unless they ran since\n\t\t\t\tif ((e.f & CLEAN) === 0) batch.schedule(e, MAYBE_DIRTY);\n\t\t\t}\n\t\t}\n\n\t\tcollected_effects = null;\n\t\tlegacy_updates = null;\n\n\t\tif (this.merge_requests.size > 0) {\n\t\t\tconst sorted = Array.from(this.merge_requests, merge_target)\n\t\t\t\t.filter((batch) => batch !== this && batch.linked && !batch.is_fork)\n\t\t\t\t.sort((a, b) => a.id - b.id);\n\t\t\tthis.merge_requests.clear();\n\n\t\t\tif (sorted.length > 0) {\n\t\t\t\tthis.#defer_effects(render_effects);\n\t\t\t\tthis.#defer_effects(effects);\n\n\t\t\t\t/** @type {Batch} */\n\t\t\t\tvar target = this;\n\t\t\t\tvar i = sorted.length;\n\n\t\t\t\twhile (i--) {\n\t\t\t\t\tvar earlier = sorted[i];\n\t\t\t\t\tif (earlier === target) continue;\n\t\t\t\t\tearlier.#merge(target);\n\t\t\t\t\ttarget = earlier;\n\t\t\t\t}\n\n\t\t\t\t// Revalidate once all the writes and pending work belong to the same batch.\n\t\t\t\ttarget.#process();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// if the batch has outstanding pending work, stash effects and bail\n\t\tif (this.#is_deferred()) {\n\t\t\tthis.#defer_effects(render_effects);\n\t\t\tthis.#defer_effects(effects);\n\n\t\t\tfor (const e of this.#skipped_branches) {\n\t\t\t\treset_branch(e);\n\t\t\t}\n\n\t\t\tif (updates.length > 0) {\n\t\t\t\t/** @type {Batch} */ (/** @type {unknown} */ (current_batch)).#process();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tconst earlier_batch = this.#find_earlier_batch();\n\n\t\tif (earlier_batch) {\n\t\t\t// If this batch collected deferred effects during traversal, they still need\n\t\t\t// to run after being merged into the earlier batch.\n\t\t\tthis.#defer_effects(render_effects);\n\t\t\tthis.#defer_effects(effects);\n\t\t\tearlier_batch.#merge(this);\n\t\t\tearlier_batch.#process();\n\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const boundary of revealed_boundaries) {\n\t\t\t// A later traversal may have restored an unresolved branch since this boundary was queued.\n\t\t\tif (boundary.is_pending && boundary.is_ready(this)) {\n\t\t\t\tboundary.reveal(effects);\n\t\t\t}\n\t\t}\n\n\t\t// The results of this batch are about to become the real-world state\n\t\tthis.#release_records(true);\n\n\t\t// append/remove branches\n\t\tthis.#run_callbacks(this.#commit_callbacks);\n\n\t\tvar earlier_writes = flush_queued_effects(render_effects);\n\n\t\t// the content has been updated, and user effects are about to see it\n\t\tif (custom_renderers_flag && before_effects !== null) {\n\t\t\tbefore_effects();\n\t\t}\n\n\t\tflush_queued_effects(effects, earlier_writes);\n\n\t\tthis.#deferred?.resolve();\n\n\t\tvar next_batch = /** @type {Batch | null} */ (/** @type {unknown} */ (current_batch));\n\n\t\tif (this.#pending.size === 0 && (this.#scheduled.length === 0 || next_batch !== null)) {\n\t\t\tthis.#unlink();\n\t\t}\n\n\t\t// Order matters here - we need to commit and THEN continue flushing new batches, not the other way around,\n\t\t// else we could start flushing a new batch and then, if it has pending work, rebase it right afterwards, which is wrong.\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) {\n\t\t\tthis.commit_writes();\n\t\t}\n\n\t\tif (next_batch !== null) {\n\t\t\t// The next batch holds the writes made while this one committed, which cause the teardowns that run\n\t\t\t// when it's processed. So teardowns now revert those, and no longer this batch's: of the reverted\n\t\t\t// values, keep those that are the next batch's values from before its writes. (Writes made in teardowns\n\t\t\t// aren't among them, see `teardown_write`, so they stay visible)\n\t\t\tif (teardown_context !== null) {\n\t\t\t\tfor (const [source, snapshot] of teardown_context.reverted_values) {\n\t\t\t\t\tif (next_batch.previous.get(source)?.wv !== snapshot.wv) {\n\t\t\t\t\t\tteardown_context.reverted_values.delete(source);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnext_batch.#process();\n\t\t}\n\t}\n\n\t/**\n\t * Schedule the reactions that (transitively) depend on `sources` for re-validation in this batch.\n\t * They are marked MAYBE_DIRTY, which means that they are only re-run if the exact versions\n\t * of their dependencies differ from the ones they last saw (in this batch's view of the world)\n\t * @param {Iterable<Source>} sources\n\t */\n\t#revalidate(sources) {\n\t\t// deriveds added during iteration are visited too, so this doubles as a worklist\n\t\t/** @type {Set<Value>} */\n\t\tvar values = new Set(sources);\n\n\t\t/** @type {Set<Effect>} */\n\t\tvar effects = new Set();\n\n\t\tfor (const value of values) {\n\t\t\tvar reactions = value.reactions;\n\t\t\tif (reactions === null) continue;\n\n\t\t\tfor (const reaction of reactions) {\n\t\t\t\tvar flags = reaction.f;\n\n\t\t\t\tif ((flags & DERIVED) !== 0) {\n\t\t\t\t\tif ((flags & CLEAN) !== 0) set_signal_status(reaction, MAYBE_DIRTY);\n\t\t\t\t\tvalues.add(/** @type {Derived} */ (reaction));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tvar effect = /** @type {Effect} */ (reaction);\n\t\t\t\tif (effects.has(effect)) continue;\n\t\t\t\teffects.add(effect);\n\n\t\t\t\tif (\n\t\t\t\t\t(flags & (EAGER_EFFECT | INERT | DESTROYED)) === 0 &&\n\t\t\t\t\t// branches that this batch skips don't exist in its view of the world\n\t\t\t\t\t!this.is_skipped(effect)\n\t\t\t\t) {\n\t\t\t\t\tthis.schedule(effect, MAYBE_DIRTY);\n\t\t\t\t}\n\t\t\t}\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 * @param {Boundary[]} revealed_boundaries\n\t */\n\t#traverse(root, effects, render_effects, revealed_boundaries) {\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\t// (eager effects run in the real world, see `flush_eager_effects`, not in the view of the batch)\n\t\t\tvar skip =\n\t\t\t\tis_skippable_branch || (flags & (INERT | EAGER_EFFECT)) !== 0 || this.#skips(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\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\t// if a pending boundary is now resolved, reveal it\n\t\t\t\tif ((effect.f & (BOUNDARY_EFFECT | DESTROYED)) === BOUNDARY_EFFECT) {\n\t\t\t\t\tvar boundary = /** @type {Boundary} */ (effect.b);\n\n\t\t\t\t\tif (boundary.is_pending && boundary.is_ready(this)) {\n\t\t\t\t\t\trevealed_boundaries.push(boundary);\n\t\t\t\t\t}\n\t\t\t\t}\n\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#find_earlier_batch() {\n\t\tfor (var batch = this.prev; batch !== null; batch = batch.prev) {\n\t\t\tif (!batch.is_fork && this.#intersects(batch)) return batch;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/** @param {Batch} batch */\n\t#intersects(batch) {\n\t\tfor (const source of this.current.keys()) {\n\t\t\tif (batch.current.has(source)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Take over the writes of a later batch that depends on this one, because it finished first\n\t * or aborted one of this batch's runs.\n\t * Values it produced (async results, deriveds) remain valid; block effects select their\n\t * branches again for this batch, if needed (their selections are keyed by batch)\n\t * @param {Batch} batch\n\t */\n\t#merge(batch) {\n\t\tfor (const target of batch.merge_requests) this.merge_requests.add(target);\n\t\tbatch.merge_requests.clear();\n\n\t\tfor (const [source, entry] of batch.current) {\n\t\t\tif (!this.previous.has(source)) {\n\t\t\t\tconst previous = batch.previous.get(source);\n\t\t\t\tif (previous) this.previous.set(source, previous);\n\t\t\t}\n\n\t\t\tthis.current.set(source, entry);\n\t\t}\n\n\t\tfor (const [effect, deferred] of batch.async_deriveds) {\n\t\t\tconst d = this.async_deriveds.get(effect);\n\t\t\tif (d && d !== deferred) deferred.promise.then(d.resolve, d.reject);\n\t\t\t// The incoming run can still be pending. A subsequent replacement must reach\n\t\t\t// this deferred too, not just the older waiters to which it forwards its result.\n\t\t\tthis.async_deriveds.set(effect, deferred);\n\t\t}\n\n\t\tfor (const [reaction, record] of batch.records ?? []) {\n\t\t\tif ((reaction.f & BLOCK_EFFECT) === 0) {\n\t\t\t\tvar replaced = this.records?.get(reaction);\n\t\t\t\t(this.records ??= new Map()).set(reaction, record);\n\n\t\t\t\t// the run moves to this batch\n\t\t\t\tbatch.records?.delete(reaction);\n\n\t\t\t\t// (once it's replaced, as both batches may hold the same record, see `keep_global_run`)\n\t\t\t\tabort_record(reaction, replaced);\n\t\t\t}\n\t\t}\n\n\t\t// Clear them or else those that are still pending might get rejected on discard (after merged-into batch is done).\n\t\t// This can happen when batch Y merged into X and Y has a pending boundary and therefore still-pending async deriveds inside.\n\t\tbatch.async_deriveds.clear();\n\n\t\t// That pending work is this batch's from now on: it decrements this batch's counts (see `increment_pending`),\n\t\t// so this batch stays linked until the work is done, and receives the effects that a boundary defers until then\n\t\tif (batch.#pending.size > 0) {\n\t\t\tfor (const [effect, count] of batch.#pending) {\n\t\t\t\tthis.#pending.set(effect, (this.#pending.get(effect) ?? 0) + count);\n\t\t\t}\n\n\t\t\tbatch.#pending.clear();\n\t\t}\n\n\t\tif (batch.#unprocessed.size > 0) {\n\t\t\tfor (const [effect, status] of batch.#unprocessed) {\n\t\t\t\tthis.#add_dirty_effect(effect, status);\n\t\t\t}\n\n\t\t\tbatch.#unprocessed.clear();\n\t\t}\n\n\t\t// What the merged batch did on its own (e.g. branches it selected) is obsolete once this batch is\n\t\t// done — whether it commits or is discarded (e.g. because of an error)\n\t\tconst discard = () => batch.discard();\n\t\tthis.oncommit(discard);\n\t\tthis.ondiscard(discard);\n\t\tbatch.merged = this;\n\t\tbatch.#unlink();\n\t}\n\n\t/**\n\t * Note that `effect` needs to be (re-)validated, without downgrading a DIRTY effect to MAYBE_DIRTY\n\t * @param {Effect} effect\n\t * @param {number} status DIRTY or MAYBE_DIRTY\n\t */\n\t#add_dirty_effect(effect, status) {\n\t\tif (status === DIRTY || this.#unprocessed.get(effect) !== DIRTY) {\n\t\t\tthis.#unprocessed.set(effect, status);\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\tvar effect = effects[i];\n\t\t\tvar status = effect.f & (DIRTY | MAYBE_DIRTY);\n\n\t\t\tif (status !== 0) {\n\t\t\t\tthis.#add_dirty_effect(effect, effect.dv === null ? MAYBE_DIRTY : status);\n\n\t\t\t\t// mark as clean so they get scheduled if they depend on pending async state\n\t\t\t\tset_signal_status(effect, CLEAN);\n\t\t\t}\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 (and versions).\n\t * The source itself is only updated if this is its latest value, i.e. unless this\n\t * is a fork (whose writes only exist in its own view of the world) or a later batch\n\t * already wrote to it (e.g. because an async expression resolved in an earlier batch).\n\t * @param {Value} source\n\t * @param {any} value\n\t * @param {boolean} same whether the value equals the real one (it can, if this batch sees another one, see\n\t * `internal_set`) — in which case the source isn't updated, and the value gets the same version\n\t * @param {boolean} [error] whether the value is an error (thrown when read, see `runtime.js#get`)\n\t * @param {Effect[] | null} [updated_during_traversal]\n\t */\n\tcapture(source, value, same, error = false, updated_during_traversal = null) {\n\t\tvar previous = this.previous.get(source);\n\t\tvar later = later_writer(this, source);\n\n\t\tif (previous === undefined) {\n\t\t\t// the value before this batch's change is the one before the later batch's change, if any\n\t\t\tprevious = later?.previous.get(source);\n\n\t\t\t// (A first value has no value from before it, see `previous`. If the later batch's write is the first value,\n\t\t\t// the value before this batch's write is taken to be that one: in the views of other batches and in\n\t\t\t// teardowns, undoing this write then gives the real value, just like not undoing it would)\n\t\t\tif (previous === undefined && source.v !== UNINITIALIZED) {\n\t\t\t\tprevious = {\n\t\t\t\t\tv: source.v,\n\t\t\t\t\twv: source.wv,\n\t\t\t\t\te: (source.f & ERROR_VALUE) !== 0,\n\t\t\t\t\tassigned: (source.f & ASSIGNED) !== 0\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (previous !== undefined) this.previous.set(source, previous);\n\t\t}\n\n\t\tif (is_destroying_effect) {\n\t\t\tteardown_write(source);\n\t\t} else if (previous !== undefined) {\n\t\t\tteardown_context?.reverted_values.set(source, previous);\n\t\t\tteardown_context?.derived_cache.clear();\n\t\t}\n\n\t\t/** @type {BatchValue} */\n\t\tvar entry = {\n\t\t\tv: value,\n\t\t\twv: same ? source.wv : increment_write_version(),\n\t\t\te: error,\n\t\t\t// a write to a derived is an assignment\n\t\t\tassigned: (source.f & DERIVED) !== 0,\n\t\t\tasync: (source.f & ASYNC) !== 0\n\t\t};\n\n\t\tthis.current.set(source, entry);\n\n\t\t// The active view of the world sees writes made while it's active, even if they don't belong to the batch whose\n\t\t// view it is — e.g. those of effects that run while a batch commits, which go to a new batch. (Async results\n\t\t// are only captured while no view is active, see `async_derived`)\n\t\tbatch_values?.set(source, entry);\n\n\t\t// an assignment replaces the value of a derived that the active view of the world holds\n\t\tview_cache?.delete(/** @type {Derived} */ (source));\n\n\t\t// in order, this batch's change comes before that of the later batch, which replaces it (this happens when a\n\t\t// result arrives in a batch that committed while it was pending, see `#move_to_front`)\n\t\tif (!this.is_fork && later !== null) later.previous.set(source, entry);\n\n\t\tif (!this.is_fork && !same && later === null) {\n\t\t\tapply(source, entry);\n\t\t}\n\n\t\t// A value that equals the real one, with the same version, changes nothing that reactions\n\t\t// could read outside this batch's view — which is revalidated when the batch is processed\n\t\tif (!same) {\n\t\t\tseen = null;\n\t\t\tcount_deps = 0;\n\t\t\tthis.mark(source, DIRTY, updated_during_traversal);\n\t\t\tseen = null;\n\n\t\t\tif (eager_effects.size > 0 && !eager_effects_deferred) {\n\t\t\t\tflush_eager_effects();\n\t\t\t}\n\t\t}\n\t}\n\n\tdeactivate() {\n\t\tcurrent_batch = processing_batch = batch_values = view_cache = view_batch = null;\n\t}\n\n\tflush() {\n\t\t// flushes can be nested, e.g. if an effect calls `flushSync`\n\t\tvar context = push_teardown_context(this.previous);\n\n\t\ttry {\n\t\t\tthis.#process();\n\n\t\t\t// (the size check avoids allocating an iterator in the common case)\n\t\t\tif (rebases.size > 0) {\n\t\t\t\tfor (const batch of rebases) {\n\t\t\t\t\trebases.delete(batch);\n\n\t\t\t\t\t// the batch is processed again anyway if a flush is queued\n\t\t\t\t\tif (batch.linked && !batch.#decrement_queued) {\n\t\t\t\t\t\tbatch.#process();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\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\n\t\t\tteardown_context = context.parent;\n\t\t\tthis.deactivate();\n\n\t\t\tif (DEV) {\n\t\t\t\tfor (const source of source_stacks) {\n\t\t\t\t\tsource.updated = null;\n\t\t\t\t}\n\n\t\t\t\tsource_stacks.clear();\n\t\t\t}\n\t\t}\n\t}\n\n\tdiscard() {\n\t\tthis.#run_callbacks(this.#discard_callbacks);\n\n\t\tfor (const deferred of this.async_deriveds.values()) {\n\t\t\tdeferred.reject(OBSOLETE);\n\t\t}\n\n\t\tthis.#unlink();\n\t\tthis.#deferred?.resolve();\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, their view of the world now includes the newly committed\n\t\t// state (unless the batch in question has a more recent value for a given source),\n\t\t// so everything that depends on it needs to be re-validated in their view\n\t\tfor (let batch = first_batch; batch !== null; batch = batch.next) {\n\t\t\tif (batch === this) continue;\n\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, entry] of this.current) {\n\t\t\t\tvar own = batch.current.get(source);\n\n\t\t\t\tif (own !== undefined) {\n\t\t\t\t\tif (is_earlier && entry.v !== own.v && !own.async) {\n\t\t\t\t\t\t// bring the value up to date\n\t\t\t\t\t\tbatch.current.set(source, entry);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// same value, later batch has more recent value, or the batch's own result\n\t\t\t\t\t\t// of an async expression — 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// If not started yet or no sources to update (which is e.g. possible for the very first batch) then bail\n\t\t\tif (!batch.started || batch.current.size === 0) continue;\n\n\t\t\tvar obsolete = true;\n\n\t\t\tfor (const source of batch.current.keys()) {\n\t\t\t\tif (!this.current.has(source)) {\n\t\t\t\t\tobsolete = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (obsolete && is_earlier) {\n\t\t\t\t// this batch is now obsolete and can be discarded\n\t\t\t\tbatch.discard();\n\t\t\t} else if (sources.length > 0) {\n\t\t\t\t// The microtask queue can contain the batch already scheduled to run right\n\t\t\t\t// after this one is finished, so throwing the invariant would be wrong here.\n\t\t\t\tif (DEV && !batch.#decrement_queued) {\n\t\t\t\t\tinvariant(batch.#scheduled.length === 0, 'Batch has scheduled effects');\n\t\t\t\t}\n\n\t\t\t\t// Everything that depends on the committed values needs to be re-validated in the\n\t\t\t\t// batch's view. The batch is processed again once the current flush is done (which\n\t\t\t\t// also re-validates what depends on its own writes, as the committed batch may have\n\t\t\t\t// created reactions that read them), so that block effects select their branches\n\t\t\t\t// and async work restarts in the new view right away\n\t\t\t\tbatch.#revalidate(sources);\n\t\t\t\trebases.add(batch);\n\t\t\t}\n\t\t}\n\n\t\t// The writes are part of the real world now. A batch that is still linked (because of pending work)\n\t\t// only has writes again once that work resolves, which it then commits\n\t\tthis.current.clear();\n\t\tthis.previous.clear();\n\t}\n\n\t/**\n\t * Make this batch's writes the real world, part of every other batch's view (see `#commit`).\n\t * If it has pending work it stays linked, coming first from now on (see `#move_to_front`)\n\t */\n\tcommit_writes() {\n\t\tthis.#commit();\n\t\tif (this.linked && this.prev !== null) this.#move_to_front();\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t */\n\tincrement(effect) {\n\t\tvar count = this.#pending.get(effect) ?? 0;\n\t\tthis.#pending.set(effect, count + 1);\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t */\n\tdecrement(effect) {\n\t\tvar count = this.#pending.get(effect) ?? 0;\n\n\t\tif (count === 1) {\n\t\t\tthis.#pending.delete(effect);\n\t\t} else {\n\t\t\tthis.#pending.set(effect, count - 1);\n\t\t}\n\n\t\tif (this.#decrement_queued) return;\n\t\tthis.#decrement_queued = true;\n\n\t\tqueue_micro_task(() => {\n\t\t\tthis.#decrement_queued = false;\n\n\t\t\tif (this.linked) {\n\t\t\t\tthis.flush();\n\t\t\t}\n\t\t});\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\toncommit(fn) {\n\t\tthis.#commit_callbacks.set(fn, eager_block_writes?.size ? eager_block_writes : null);\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\tondiscard(fn) {\n\t\tthis.#discard_callbacks.set(fn, eager_block_writes?.size ? eager_block_writes : null);\n\t}\n\n\t/**\n\t * Runs the commit/discard callbacks.\n\t * A callback that was added while block effects re-ran eagerly detaches the branches that such a run\n\t * deselected (see `flush_queued_effects`). The teardowns it causes see the writes that applied in the\n\t * run's view, like they would have during the run: of the values that the current teardown context\n\t * reverts, the writes of the effects that ran before the one whose writes caused the run are restored.\n\t * Callbacks run untracked, because a batch can commit while an effect runs (e.g. one that calls `flushSync`)\n\t * @param {Map<(batch: Batch) => void, Map<Value, BatchValue> | null>} callbacks\n\t */\n\t#run_callbacks(callbacks) {\n\t\tuntrack(() => {\n\t\t\tfor (const [fn, writes] of callbacks) {\n\t\t\t\tif (writes === null) {\n\t\t\t\t\tfn(this);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tvar context = push_teardown_context();\n\n\t\t\t\tfor (const [source, write] of writes) {\n\t\t\t\t\tif (context.reverted_values.has(source)) context.reverted_values.set(source, write);\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tfn(this);\n\t\t\t\t} finally {\n\t\t\t\t\tteardown_context = context.parent;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tcallbacks.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 (processing_batch === null && !is_flushing_sync) {\n\t\t\t\tqueue_micro_task(() => {\n\t\t\t\t\tif (!batch.started) {\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\t/**\n\t * Make this the current batch, and its view of the world the active one\n\t */\n\tactivate() {\n\t\tcurrent_batch = this;\n\t\tview_batch = this;\n\n\t\t// Async continuations can create or run reactions in another batch's view without\n\t\t// processing it. The next flush must re-validate those reactions in its own view.\n\t\tif (last_processed !== this.id) last_processed = null;\n\n\t\tif (!async_mode_flag) {\n\t\t\tbatch_values = view_cache = null;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.folded = [];\n\n\t\tif (!this.is_fork && this.prev === null && this.next === null) {\n\t\t\t// this batch's view is the real world\n\t\t\tbatch_values = view_cache = 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(this.current);\n\t\tview_cache = new Map();\n\n\t\t// ...and undo changes belonging to other batches unless they intersect\n\t\tfor (let batch = first_batch; batch !== null; batch = batch.next) {\n\t\t\tif (batch === this || batch.is_fork) continue;\n\n\t\t\t// Since the latter batch merges into the earlier (if it resolves before the earlier one),\n\t\t\t// we treat the earlier values as \"already applied\". This way we don't need to rerun async\n\t\t\t// effects of the earlier batch in case they are merged.\n\t\t\t// As a result you can think of batch_values as having the latest values of all intersecting\n\t\t\t// batches up until this batch.\n\t\t\tif (batch.id < this.id && batch.#intersects(this)) {\n\t\t\t\tthis.folded.push(batch);\n\t\t\t} else {\n\t\t\t\tfor (const [source, previous] of batch.previous) {\n\t\t\t\t\t// (where the views agree on the value, the real one — and its version — applies. Not for an\n\t\t\t\t\t// assigned derived: its value before may have been computed in another view, see `get_view`)\n\t\t\t\t\tif (\n\t\t\t\t\t\t!batch_values.has(source) &&\n\t\t\t\t\t\t((source.f & DERIVED) !== 0 || !source.equals(previous.v))\n\t\t\t\t\t) {\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 * The record of `reaction` in this batch's view of the world, i.e. that of this batch\n\t * or of the (earlier) batches whose changes it includes, if any\n\t * @param {Reaction} reaction\n\t * @returns {BatchRecord | undefined}\n\t */\n\tget_record(reaction) {\n\t\tvar record = this.records?.get(reaction);\n\t\tvar i = this.folded.length;\n\n\t\twhile (record === undefined && i--) {\n\t\t\trecord = this.folded[i].records?.get(reaction);\n\t\t}\n\n\t\treturn record;\n\t}\n\n\t/**\n\t * @param {Value} signal\n\t * @param {number} status should be DIRTY or MAYBE_DIRTY\n\t * @param {Effect[] | null} [updated_during_traversal]\n\t * @returns {void}\n\t */\n\tmark(signal, status, updated_during_traversal = null) {\n\t\tvar reactions = signal.reactions;\n\t\tif (reactions === null) return;\n\n\t\tvar runes = is_runes();\n\t\tvar length = reactions.length;\n\n\t\tcount_deps += length;\n\t\t// Activate the `seen` Set if we think from the unusually high number of deps that\n\t\t// there might be cycles in the graph, to avoid repeated lookups for reactions\n\t\t// Example: https://github.com/sveltejs/svelte/issues/16658 has a graph with one source\n\t\t// reaching ~10000 distinct deriveds/effects each, resulting in 65 million walks through repeated visits.\n\t\tif (count_deps > 100000 && seen === null) seen = new Set();\n\n\t\tif (seen !== null) {\n\t\t\tif (seen.has(signal)) return;\n\t\t\tseen.add(signal);\n\t\t}\n\n\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar reaction = reactions[i];\n\t\t\tvar flags = reaction.f;\n\n\t\t\t// In legacy mode, skip the current effect to prevent infinite loops\n\t\t\tif (!runes && reaction === active_effect) continue;\n\n\t\t\tvar not_dirty = (flags & DIRTY) === 0;\n\n\t\t\tif ((flags & EAGER_EFFECT) !== 0) {\n\t\t\t\tif (!this.is_fork) {\n\t\t\t\t\t// don't set a DIRTY reaction to MAYBE_DIRTY\n\t\t\t\t\tif (not_dirty) {\n\t\t\t\t\t\tset_signal_status(reaction, status);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Eager effects need to run immediately:\n\t\t\t\t\t// - for $inspect so that the stack trace makes sense\n\t\t\t\t\t// - for $state.eager because they might be without an effect parent\n\t\t\t\t\teager_effects.add(/** @type {Effect} */ (reaction));\n\t\t\t\t}\n\t\t\t} else if ((flags & DERIVED) !== 0) {\n\t\t\t\t// don't set a DIRTY reaction to MAYBE_DIRTY\n\t\t\t\tif (not_dirty) {\n\t\t\t\t\tset_signal_status(reaction, status);\n\t\t\t\t}\n\n\t\t\t\tvar derived = /** @type {Derived} */ (reaction);\n\n\t\t\t\tview_cache?.delete(derived);\n\t\t\t\tthis.mark(derived, MAYBE_DIRTY, updated_during_traversal);\n\t\t\t} else if (not_dirty) {\n\t\t\t\tvar effect = /** @type {Effect} */ (reaction);\n\n\t\t\t\tif ((flags & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) {\n\t\t\t\t\t// these run right away to find out which branches the rest of the flush must skip\n\t\t\t\t\t// (see `flush_queued_effects`); the DOM changes when this batch commits\n\t\t\t\t\tset_signal_status(effect, status);\n\t\t\t\t\teager_block_effects.add(effect);\n\t\t\t\t}\n\n\t\t\t\tif (updated_during_traversal !== null) {\n\t\t\t\t\tset_signal_status(effect, status);\n\t\t\t\t\tupdated_during_traversal.push(effect);\n\t\t\t\t} else {\n\t\t\t\t\t// the status is applied when the batch is processed\n\t\t\t\t\tthis.schedule(effect, status);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Schedule `effect` to be (re-)validated when this batch is processed. Its status only applies right\n\t * away if this is the batch that the current flush processes (next), or if a reaction is running (which\n\t * may have read what changed). Otherwise, whether an effect is dirty depends on this batch's view of the\n\t * world, so other batches (which may be processed first) mustn't see it: it is kept with this batch until\n\t * it is processed, and then checked against the exact versions of its dependencies (i.e. MAYBE_DIRTY)\n\t * @param {Effect} effect\n\t * @param {number} status DIRTY or MAYBE_DIRTY\n\t */\n\tschedule(effect, status) {\n\t\tlast_scheduled_effect = effect;\n\n\t\t// While another batch is committed, effects that this batch's writes affect (other than the one\n\t\t// that is running, i.e. writing) wait for it to be processed, rather than running as part of that commit.\n\t\t// They may still run as part of it (for that batch's reasons) and see the write, so versions decide — unless\n\t\t// the effect is running, in which case it would record the version it didn't see (see `update_dependencies`)\n\t\tif (view_batch !== null && view_batch !== this && effect !== active_reaction) {\n\t\t\tthis.#add_dirty_effect(\n\t\t\t\teffect,\n\t\t\t\t(effect.f & REACTION_IS_UPDATING) !== 0 ? status : MAYBE_DIRTY\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (processing_batch !== this && active_reaction === null) {\n\t\t\tif (this.prev !== null || this.next !== null || this.is_fork) {\n\t\t\t\tthis.#add_dirty_effect(effect, MAYBE_DIRTY);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstatus = MAYBE_DIRTY;\n\t\t}\n\n\t\tthis.#add(effect, status);\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t * @param {number} status\n\t */\n\t#add(effect, status) {\n\t\t// don't set a DIRTY effect to MAYBE_DIRTY\n\t\tif ((effect.f & DIRTY) === 0) {\n\t\t\tset_signal_status(effect, status);\n\t\t}\n\n\t\tthis.#scheduled.push(effect);\n\t}\n\n\t/** @param {boolean} commit whether the effects' runs become global state */\n\t#release_records(commit = false) {\n\t\tvar records = this.records;\n\t\tif (records === null) return;\n\n\t\t// Release ownership before pruning. Merged runs are retained by the receiving batch\n\t\tthis.records = null;\n\t\tfor (const [reaction, record] of records) {\n\t\t\t// A derived's record is a run in this batch's view: it is only the real-world value if its\n\t\t\t// dependencies still hold what it read, which is checked where a record is promoted on read\n\t\t\t// (see `update_derived`) and cannot be checked here. So it is dropped rather than promoted,\n\t\t\t// and its edges are left for its next global run to prune (see `prune_edges`). A destroyed\n\t\t\t// reaction has nothing left to update either\n\t\t\tif ((reaction.f & (DERIVED | DESTROYED)) === 0) {\n\t\t\t\t// Keep a newer committed async run instead of promoting an outdated record.\n\t\t\t\t// Otherwise, the effect would rerun and restart its async work in every batch.\n\t\t\t\tvar replaced = (reaction.f & ASYNC) !== 0 && is_outdated(record) && !is_outdated(reaction);\n\n\t\t\t\tif (commit && !replaced) {\n\t\t\t\t\tpromote_record(reaction, record);\n\n\t\t\t\t\t// The committed run is now what applies in the view of every batch without a run of the async\n\t\t\t\t\t// effect of its own (typically because the batch committed while its run was pending, inside a\n\t\t\t\t\t// pending boundary). Their in-flight runs are superseded: their results would overwrite this one\n\t\t\t\t\t// TODO feels pretty hacky and indication of an X-Y problem: This only works because !b.records?.has(reaction)\n\t\t\t\t\t// means \"this would re-use the real world result, i.e. the one we just committed, so we can reject this old run\".\n\t\t\t\t\t// This can reject runs too early in pending batches. The superseding batch eventually settles them,\n\t\t\t\t\t// but async/if blocks inside pending boundaries should be excluded.\n\t\t\t\t\tif ((reaction.f & ASYNC) !== 0) {\n\t\t\t\t\t\tfor (let b = first_batch; b !== null; b = b.next) {\n\t\t\t\t\t\t\tif (b !== this && !b.records?.has(reaction)) {\n\t\t\t\t\t\t\t\tb.async_deriveds.get(/** @type {Effect} */ (reaction))?.reject(OBSOLETE);\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\tprune_edges(reaction);\n\t\t\t}\n\n\t\t\t// abort this run - if it was promoted to global, or another batch holds it, too, this is a noop\n\t\t\tabort_record(reaction, record);\n\t\t}\n\t}\n\n\t/**\n\t * A batch that committed while work inside a pending boundary was in flight stays linked, so that the results\n\t * arrive in it. Its writes are the real world now, part of every other batch's view, so it comes first from now\n\t * on: This ensures logic about who sees what values in intersects/merge/etc work correctly.\n\t */\n\t#move_to_front() {\n\t\tvar prev = /** @type {Batch} */ (this.prev);\n\t\tvar first = /** @type {Batch} */ (first_batch);\n\n\t\tprev.next = this.next;\n\t\tif (this.next === null) last_batch = prev;\n\t\telse this.next.prev = prev;\n\n\t\tthis.prev = null;\n\t\tthis.next = first;\n\t\tfirst.prev = first_batch = this;\n\t\tthis.id = first.id - 1;\n\t}\n\n\t#unlink() {\n\t\t// #merge calls #unlink, discard later on does it again - prevent\n\t\t// running it multiple times to not corrupt the linked list\n\t\tif (!this.linked) return;\n\n\t\tvar prev = this.prev;\n\t\tvar next = this.next;\n\n\t\tif (prev === null) {\n\t\t\tfirst_batch = next;\n\t\t} else {\n\t\t\tprev.next = next;\n\t\t}\n\n\t\tif (next === null) {\n\t\t\tlast_batch = prev;\n\t\t} else {\n\t\t\tnext.prev = prev;\n\t\t}\n\n\t\tthis.linked = false;\n\t\tthis.#release_records();\n\t}\n}\n\n// TODO Svelte@6 think about removing the callback argument.\n/**\n * Called each time a batch has updated the content, before its user effects run, if set. Custom renderers\n * use this to keep the content of crossings that share a container in the order of their host nodes\n * (see `custom-renderer/containers.js`), so that effects never see them in a stale order\n * @type {(() => void) | null}\n */\nlet before_effects = null;\n\n/**\n * @param {(() => void) | null} fn\n */\nexport function set_before_effects(fn) {\n\tbefore_effects = fn;\n}\n\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\t// e.g. flushSync during effect flushing phase - we gotta restore the view_batch afterwards in that case\n\tvar previous_view_batch = view_batch !== current_batch ? view_batch : null;\n\tis_flushing_sync = true;\n\n\ttry {\n\t\tvar result;\n\n\t\tif (fn) {\n\t\t\tflushSync(); // flush anything pending through the while loop below\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\tview_batch = previous_view_batch;\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 * While block effects re-run eagerly (see `flush_queued_effects`), the writes of the effects that ran before the one\n * whose writes caused the re-runs, which apply in their view (possibly none). `null` otherwise. The branches that\n * these runs select/unskip are only appended (and those they skip detached) when the batch with the writes commits\n * (see `should_defer_append`), and the teardowns that this causes see these writes, too (see `#run_callbacks`)\n * @type {Map<Value, BatchValue> | null}\n */\nexport let eager_block_writes = null;\n\n/**\n * An effect (as opposed to a render effect, which keeps the offscreen content up to date) inside a boundary\n * that is still pending doesn't run when the batch commits. The boundary keeps it until it is revealed,\n * and hands it to the batch that reveals it (see `Boundary#reveal`)\n * TODO I feel like there's probably a less roundabout way to achieve this\n * @param {Effect} effect\n * @returns {boolean} whether the effect was deferred\n */\nfunction defer_if_pending(effect) {\n\t// A boundary is only pending while its content is new, so an effect that\n\t// has run before can't be inside one, and we can skip the lookup\n\tif ((effect.f & (EFFECT | REACTION_RAN)) !== EFFECT) return false;\n\n\tfor (var boundary = effect.b; boundary !== null; boundary = boundary.parent) {\n\t\tif (boundary.is_pending) {\n\t\t\tboundary.defer_effect(effect);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * `earlier_writes` includes writes from the pre-effect phase. Eager block teardowns\n * revert the running effect's writes, but not these earlier writes.\n * @param {Array<Effect>} effects\n * @param {Map<Value, BatchValue> | null} [earlier_writes]\n * @returns {Map<Value, BatchValue> | null}\n */\nfunction flush_queued_effects(effects, earlier_writes = null) {\n\tvar length = effects.length;\n\tif (length === 0) return earlier_writes;\n\n\tvar i = 0;\n\n\twhile (i < length) {\n\t\tvar effect = effects[i++];\n\n\t\tif (\n\t\t\t(effect.f & (DESTROYED | INERT)) === 0 &&\n\t\t\t// don't run if already marked for destruction in the next batch\n\t\t\t// (this can happen if an effect writes a value which e.g. makes an if block falsy)\n\t\t\t!current_batch?.is_skipped(effect) &&\n\t\t\t!defer_if_pending(effect) &&\n\t\t\tis_dirty(effect)\n\t\t) {\n\t\t\teager_block_effects = new Set();\n\n\t\t\tvar version = write_version;\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.edges === 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\t// these run because of the writes of the effect, so their teardowns revert those\n\t\t\t\tvar previous_teardown_context = teardown_context;\n\n\t\t\t\t// if state was written by an effect before the one that caused the eager\n\t\t\t\t// block rerun, its writes apply in this view. Deriveds must be evaluated\n\t\t\t\t// afresh rather than reusing results cached before those writes.\n\t\t\t\tif (earlier_writes !== null) push_teardown_context(earlier_writes);\n\n\t\t\t\t// (a copy, as `earlier_writes` grows while the flush continues)\n\t\t\t\tvar previous_eager_block_writes = eager_block_writes;\n\t\t\t\teager_block_writes = new Map(earlier_writes);\n\n\t\t\t\ttry {\n\t\t\t\t\tfor (const e of eager_block_effects) {\n\t\t\t\t\t\t// Skip eager effects that have already been unmounted, or that are inside a\n\t\t\t\t\t\t// branch that an earlier eager run (e.g. of an ancestor block) skips\n\t\t\t\t\t\tif ((e.f & (DESTROYED | INERT)) !== 0 || current_batch?.is_skipped(e)) continue;\n\n\t\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\t/** @type {Effect[]} */\n\t\t\t\t\t\tconst ordered_effects = [e];\n\t\t\t\t\t\tlet ancestor = e.parent;\n\t\t\t\t\t\twhile (ancestor !== null) {\n\t\t\t\t\t\t\tif (eager_block_effects.has(ancestor)) {\n\t\t\t\t\t\t\t\teager_block_effects.delete(ancestor);\n\t\t\t\t\t\t\t\tordered_effects.push(ancestor);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tancestor = ancestor.parent;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (let j = ordered_effects.length - 1; j >= 0; j--) {\n\t\t\t\t\t\t\tconst e = ordered_effects[j];\n\t\t\t\t\t\t\t// a block run may have skipped/destroyed the branch that a later one is in\n\t\t\t\t\t\t\tif ((e.f & (DESTROYED | INERT)) !== 0 || current_batch?.is_skipped(e)) continue;\n\t\t\t\t\t\t\tupdate_effect(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\teager_block_writes = previous_eager_block_writes;\n\t\t\t\t\teager_block_effects?.clear();\n\t\t\t\t\tteardown_context = previous_teardown_context;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if the effect — or the block effects — wrote anything\n\t\t\tif (write_version !== version && current_batch !== null) {\n\t\t\t\tfor (const [value, write] of current_batch.current) {\n\t\t\t\t\tif (write.wv > version) {\n\t\t\t\t\t\t(earlier_writes ??= new Map()).set(value, write);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\teager_block_effects = null;\n\treturn earlier_writes;\n}\n\n/**\n * The next batch after `batch` that wrote `source`, if any. Its write comes after one of `batch` in order, so\n * that one isn't the real-world value. Forks are skipped: their writes only exist in their own view of the world\n * @param {Batch} batch\n * @param {Value} source\n */\nfunction later_writer(batch, source) {\n\tvar later = batch.next;\n\n\twhile (later !== null && (later.is_fork || !later.current.has(source))) {\n\t\tlater = later.next;\n\t}\n\n\treturn later;\n}\n\n/**\n * Make a write the real-world value of `source`. A write to a derived is an assignment, whose\n * value holds until one of the derived's dependencies is written after it (see `changed_since`)\n * @param {Value} source\n * @param {BatchValue} entry\n */\nfunction apply(source, entry) {\n\tsource.v = entry.v;\n\tsource.wv = entry.wv;\n\tsource.f = entry.e ? source.f | ERROR_VALUE : source.f & ~ERROR_VALUE;\n\n\tif ((source.f & DERIVED) !== 0) {\n\t\tsource.f |= ASSIGNED;\n\t\tupdate_derived_status(/** @type {Derived} */ (source));\n\t}\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/** @type {Map<Reaction, Source<number>>} */\nvar version_map = new Map();\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 initial = true;\n\tvar value = /** @type {T} */ (undefined);\n\n\tif (active_reaction === null) {\n\t\treturn fn();\n\t}\n\n\tlet parent = active_reaction;\n\n\tlet version = version_map.get(parent) ?? source(0);\n\tversion_map.set(parent, version);\n\n\tif (DEV) {\n\t\tversion.label ??= '$state.eager version';\n\t}\n\n\tteardown(() => {\n\t\tif (parent.f & DESTROYING) version_map.delete(parent);\n\t});\n\n\tget(version);\n\n\t// evaluate in the real world — including recording the versions of the dependencies,\n\t// so that the eager effect is dirty-checked correctly later (see `flush_eager_effects`)\n\tin_real_world(() => {\n\t\teager_effect(() => {\n\t\t\tif (initial) {\n\t\t\t\t// the first time this runs, we create an eager effect\n\t\t\t\t// that will run eagerly whenever the expression changes\n\t\t\t\tvalue = fn();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// the second time this effect runs, it's to schedule a\n\t\t\t// `version` update. since this will recreate the effect,\n\t\t\t// we don't need to evaluate the expression here\n\t\t\tif (eager_versions.length === 0) {\n\t\t\t\tqueue_micro_task(eager_flush);\n\t\t\t}\n\n\t\t\teager_versions.push(version);\n\t\t});\n\t});\n\n\tinitial = false;\n\n\treturn value;\n}\n\n/**\n * Run `fn` with the real world (i.e. the latest values) as the active view, regardless of which batch is active\n * @param {() => void} fn\n */\nexport function in_real_world(fn) {\n\tvar previous_batch_values = batch_values;\n\tvar previous_view_cache = view_cache;\n\tvar previous_view_batch = view_batch;\n\n\t// the real world doesn't belong to a batch, so what runs in it doesn't touch the active batch's records\n\tbatch_values = view_cache = view_batch = null;\n\n\ttry {\n\t\tfn();\n\t} finally {\n\t\tbatch_values = previous_batch_values;\n\t\tview_cache = previous_view_cache;\n\t\tview_batch = previous_view_batch;\n\t}\n}\n\n/**\n * Mark all the effects inside a skipped branch CLEAN, so that they can be correctly\n * rescheduled later (if the branch survives, its effects are re-validated, see `unskip_effect`)\n * @param {Effect} effect\n * @param {boolean} force reset even clean branches following an error\n */\nfunction reset_branch(effect, force = false) {\n\t// clean branch = nothing dirty inside, no need to traverse further\n\tif (!force && (effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) {\n\t\treturn;\n\t}\n\n\tset_signal_status(effect, CLEAN);\n\n\tvar e = effect.first;\n\twhile (e !== null) {\n\t\treset_branch(e, force);\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 (active_effect !== null || current_batch?.is_fork) {\n\t\te.fork_timing();\n\t}\n\n\tvar batch = flushSync(() => {\n\t\tvar batch = Batch.ensure();\n\t\tbatch.is_fork = true;\n\n\t\ttry {\n\t\t\tin_real_world(() => {\n\t\t\t\tbatch_values = new Map();\n\t\t\t\tview_cache = new Map();\n\t\t\t\tview_batch = batch;\n\n\t\t\t\tfn();\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tbatch.discard();\n\t\t\tbatch.deactivate();\n\t\t\tthrow error;\n\t\t}\n\n\t\treturn batch;\n\t});\n\n\tvar settled = batch.settled();\n\tvar committed = false;\n\tvar discarded = false;\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 (discarded) {\n\t\t\t\te.fork_discarded();\n\t\t\t}\n\n\t\t\tif (!batch.linked) {\n\t\t\t\t// batch was made obsolete by later changes\n\t\t\t\tcommitted = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tcommitted = true;\n\t\t\tbatch.is_fork = false;\n\n\t\t\t// Apply the changes to the real world. They keep the versions they had in the fork,\n\t\t\t// so that everything the fork computed remains valid (processing the batch\n\t\t\t// re-validates everything that depends on them, see `#process`)\n\t\t\tfor (const [source, entry] of batch.current) {\n\t\t\t\tconst later = later_writer(batch, source);\n\n\t\t\t\tif (later !== null) {\n\t\t\t\t\t// in order, the fork's write comes before the later batch's, which replaces it\n\t\t\t\t\tlater.previous.set(source, entry);\n\t\t\t\t} else {\n\t\t\t\t\tbatch.mark(source, MAYBE_DIRTY);\n\t\t\t\t\tapply(source, entry);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (eager_effects.size > 0) {\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\tif (!committed && batch.linked) {\n\t\t\t\tbatch.discard();\n\t\t\t}\n\n\t\t\tdiscarded = true;\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\tfirst_batch = last_batch = null;\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\tupdate_effect,\n\tcurrent_sources,\n\tis_dirty,\n\tuntracking,\n\tpush_reaction_value,\n\tis_destroying_effect\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\tASSIGNED,\n\tERROR_VALUE\n} from '#client/constants';\nimport * as e from '../errors.js';\nimport { legacy_mode_flag, tracing_mode_flag } from '../../flags/index.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\tlegacy_updates,\n\tin_real_world,\n\tteardown_write,\n\tsource_stacks\n} from './batch.js';\nimport { proxy } from '../proxy.js';\nimport { execute_derived } from './deriveds.js';\nimport { set_signal_status } from './status.js';\n\n/** @type {Set<Effect>} */\nexport let eager_effects = new Set();\n\n/**\n * @param {Set<any>} v\n */\nexport function set_eager_effects(v) {\n\teager_effects = v;\n}\n\nexport let 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 {Source<V>} */\n\tvar signal = {\n\t\tf: 0,\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 {Value<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 || !current_sources.has(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 {Value<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\tvar same = source.equals(value) && (source.f & ERROR_VALUE) === 0;\n\tvar entry = batch_values?.get(source);\n\n\t// A value that equals the real one may still overwrite a different value in the active view.\n\tif (!same || (entry !== undefined && (entry.e || !source.equals.call(entry, value)))) {\n\t\tvar batch = Batch.ensure();\n\n\t\t// If we are assigning to a dirty derived we eagerly execute it to track the dependencies. (Not if\n\t\t// it's assigned already: it tracks them, and its flags don't tell whether the assignment still holds,\n\t\t// which is what other views see when they undo this one — see `is_dirty`)\n\t\tif ((source.f & (DERIVED | DIRTY | ASSIGNED)) === (DERIVED | DIRTY)) {\n\t\t\texecute_derived(/** @type {Derived} */ (source));\n\t\t}\n\n\t\tbatch.capture(source, value, same, false, updated_during_traversal);\n\n\t\tif (DEV) {\n\t\t\tif (tracing_mode_flag || active_effect !== null) {\n\t\t\t\tsource.updated ??= new Map();\n\t\t\t\tsource_stacks.add(source);\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\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\t} else if (is_destroying_effect) {\n\t\t// not a change, but the teardown no longer sees a reverted value\n\t\tteardown_write(source);\n\t}\n\n\treturn value;\n}\n\nexport function flush_eager_effects() {\n\teager_effects_deferred = false;\n\n\t// eager effects run in the real world, not in the view of a batch\n\tin_real_world(run_eager_effects);\n}\n\nfunction run_eager_effects() {\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\tlet dirty;\n\n\t\ttry {\n\t\t\tdirty = is_dirty(effect);\n\t\t} catch {\n\t\t\t// Dirty-checking can evaluate derived dependencies and throw in cases where\n\t\t\t// parent effects are about to destroy this eager effect. Run the effect so\n\t\t\t// its own error handling can deal with transient failures.\n\t\t\tdirty = true;\n\t\t}\n\n\t\tif (dirty) {\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","/** @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 { COMPONENT_SYMBOL, 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, a component instance, or already a proxy, return `value`\n\tif (\n\t\ttypeof value !== 'object' ||\n\t\tvalue === null ||\n\t\tSTATE_SYMBOL in value ||\n\t\tCOMPONENT_SYMBOL in value\n\t) {\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\tthis.has?.(target, prop);\n\n\t\t\tvar descriptor = Reflect.getOwnPropertyDescriptor(target, prop);\n\t\t\tvar s = sources.get(prop);\n\n\t\t\tif (s !== undefined) {\n\t\t\t\tvar value = get(s);\n\n\t\t\t\tif (value === UNINITIALIZED) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tif (descriptor && 'value' in descriptor) {\n\t\t\t\t\tdescriptor.value = value;\n\t\t\t\t} else {\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 || active_reaction !== null) &&\n\t\t\t\t\t(!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 { Effect, TemplateNode } from '#client' */\nimport { hydrate_node, hydrating, reset, 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 {\n\tATTRIBUTES_CACHE,\n\tCLASS_CACHE,\n\tREACTION_RAN,\n\tSTYLE_CACHE,\n\tTEXT_CACHE,\n\tTEXT_NODE,\n\tCOMMENT_NODE,\n\tCUSTOM_RENDERER_NODE_TYPE_MAP\n} from '#client/constants';\nimport { eager_block_writes } from '../reactivity/batch.js';\nimport { NAMESPACE_HTML } from '../../../constants.js';\nimport { current_renderer } from '../custom-renderer/state.js';\nimport * as e from '../errors.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/** @type {any} */ (element_prototype)[CLASS_CACHE] = undefined;\n\t\t/** @type {any} */ (element_prototype)[ATTRIBUTES_CACHE] = null;\n\t\t/** @type {any} */ (element_prototype)[STYLE_CACHE] = 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/** @type {any} */ (text_prototype)[TEXT_CACHE] = 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\tif (current_renderer) return /** @type {Text} */ (current_renderer.createText(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\tif (current_renderer)\n\t\treturn /** @type {TemplateNode | null} */ (current_renderer.getFirstChild(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\tif (current_renderer)\n\t\treturn /** @type {TemplateNode | null} */ (current_renderer.getNextSibling(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 = /** @type {TemplateNode} */ (append_child(hydrate_node, create_text()));\n\t} else if (is_text && node_type(child) !== TEXT_NODE) {\n\t\tvar text = create_text();\n\t\tinsert_before(child, 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 (is_comment(first) && get_node_value(first) === '') 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 (node_type(hydrate_node) !== TEXT_NODE) {\n\t\t\tvar text = create_text();\n\n\t\t\tif (hydrate_node) insert_before(hydrate_node, 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 * `child`, for the very common case of an element with exactly one child. Resetting the\n * hydration cursor is part of the same step, so the compiler doesn't have to emit a\n * separate `reset` call for every `<p>{text}</p>` in an app.\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 only_child(node, is_text = false) {\n\tif (!hydrating) {\n\t\treturn get_first_child(node);\n\t}\n\n\tvar first = child(node, is_text);\n\treset(node);\n\n\treturn first;\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 (node_type(next_sibling) !== 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\tif (last_sibling) insert_after(last_sibling, text);\n\t\t\t} else {\n\t\t\t\tinsert_before(next_sibling, 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\tif (current_renderer) {\n\t\tvar child = current_renderer.getFirstChild(node);\n\t\twhile (child !== null) {\n\t\t\tvar next = current_renderer.getNextSibling(child);\n\t\t\tcurrent_renderer.remove(child);\n\t\t\tchild = next;\n\t\t}\n\t\treturn;\n\t}\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 && eager_block_writes === null) return false;\n\n\tvar flags = /** @type {Effect} */ (active_effect).f;\n\treturn (flags & REACTION_RAN) !== 0;\n}\n\n/**\n * Branching here is intentional and load-bearing for perf. `createElement(tag)`\n * hits a fast path in Blink that `createElementNS(NAMESPACE_HTML, tag)` doesn't,\n * and passing an explicit `undefined` as the trailing options arg measurably\n * slows both APIs. Funnelling every case through a single `createElementNS(ns,\n * tag, options)` call would be smaller but slower on the HTML path.\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\tif (current_renderer) {\n\t\treturn current_renderer.createElement(tag);\n\t}\n\n\tif (namespace == null || namespace === NAMESPACE_HTML) {\n\t\treturn /** @type {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element} */ (\n\t\t\tis ? document.createElement(tag, { is }) : document.createElement(tag)\n\t\t);\n\t}\n\n\treturn /** @type {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element} */ (\n\t\tis ? document.createElementNS(namespace, tag, { is }) : document.createElementNS(namespace, tag)\n\t);\n}\n\nexport function create_fragment() {\n\tif (current_renderer) return /** @type {DocumentFragment} */ (current_renderer.createFragment());\n\treturn document.createDocumentFragment();\n}\n\n/**\n * @param {string} data\n * @returns\n */\nexport function create_comment(data = '') {\n\tif (current_renderer) return /** @type {Comment} */ (current_renderer.createComment(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 (current_renderer) {\n\t\tcurrent_renderer.setAttribute(element, key, value);\n\t\treturn;\n\t}\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\t// if we have a renderer we will not hydrate so we can skip this\n\tif (current_renderer) return;\n\n\tif (/** @type {string} */ (text.nodeValue).length < 65536) {\n\t\treturn;\n\t}\n\n\tlet next = text.nextSibling;\n\n\twhile (next !== null && node_type(next) === 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\n/**\n * @param {TemplateNode | null} node\n * @returns {node is Comment}\n */\nfunction is_comment(node) {\n\tif (current_renderer) return !!node && node_type(node) === COMMENT_NODE;\n\treturn node instanceof Comment;\n}\n\n/**\n * @param {Node | null | undefined} node\n */\nexport function node_type(node) {\n\tif (node == null) return undefined;\n\tif (current_renderer) {\n\t\tconst type = current_renderer.getNodeType(node);\n\t\treturn CUSTOM_RENDERER_NODE_TYPE_MAP[type];\n\t}\n\treturn node.nodeType;\n}\n\n/**\n * @param {Node} node\n * @returns {string}\n */\nexport function node_name(node) {\n\tif (current_renderer) {\n\t\t// for custom renderers we don't need to return the node name since all the\n\t\t// checks that we do on specific node names are meant to be for the HTML\n\t\treturn '';\n\t}\n\treturn node.nodeName;\n}\n\n/**\n * @param {Node} node\n * @returns {TemplateNode | null}\n */\nexport function get_last_child(node) {\n\tif (current_renderer)\n\t\treturn /** @type {TemplateNode | null} */ (current_renderer.getLastChild(node));\n\treturn /** @type {TemplateNode | null} */ (node.lastChild);\n}\n\n/**\n * @param {Node} node\n * @returns {TemplateNode | null}\n */\nexport function get_parent_node(node) {\n\tif (current_renderer)\n\t\treturn /** @type {TemplateNode | null} */ (current_renderer.getParent(node));\n\treturn /** @type {TemplateNode | null} */ (node.parentNode);\n}\n\n/**\n * @param {Node} parent\n * @param {Node} child\n * @returns {Node}\n */\nexport function append_child(parent, child) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.insert(parent, child, null);\n\t\treturn child;\n\t}\n\treturn parent.appendChild(child);\n}\n\n/**\n * Insert `new_node` before `ref_node` (equivalent to `ref_node.before(new_node)`)\n * @param {ChildNode} ref_node\n * @param {Node} new_node\n */\nexport function insert_before(ref_node, new_node) {\n\tif (current_renderer) {\n\t\tvar parent = current_renderer.getParent(ref_node);\n\t\tcurrent_renderer.insert(parent, new_node, ref_node);\n\t\treturn;\n\t}\n\tref_node.before(new_node);\n}\n\n/**\n * Insert `new_node` after `ref_node` (equivalent to `ref_node.after(new_node)`)\n * @param {ChildNode} ref_node\n * @param {Node} new_node\n */\nexport function insert_after(ref_node, new_node) {\n\tif (current_renderer) {\n\t\tvar parent = current_renderer.getParent(ref_node);\n\t\tvar next = current_renderer.getNextSibling(ref_node);\n\t\tcurrent_renderer.insert(parent, new_node, next);\n\t\treturn;\n\t}\n\tref_node.after(new_node);\n}\n\n/**\n * @param {ChildNode} node\n */\nexport function remove_node(node) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.remove(node);\n\t\treturn;\n\t}\n\tnode.remove();\n}\n\n/**\n * @param {Node} parent\n * @param {ChildNode} child\n * @returns {ChildNode}\n */\nexport function remove_child(parent, child) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.remove(child);\n\t\treturn child;\n\t}\n\treturn /** @type {ChildNode} */ (parent.removeChild(child));\n}\n\n/**\n * @param {ChildNode} old_node\n * @param {Node} new_node\n */\nexport function replace_with(old_node, new_node) {\n\tif (current_renderer) {\n\t\tvar parent = current_renderer.getParent(old_node);\n\t\tcurrent_renderer.insert(parent, new_node, old_node);\n\t\tcurrent_renderer.remove(old_node);\n\t\treturn;\n\t}\n\told_node.replaceWith(new_node);\n}\n\n/**\n * @param {Node} node\n * @param {string} value\n */\nexport function set_text_content(node, value) {\n\tif (current_renderer) {\n\t\t// only used for DOM-only features (injected styles and `<script>` tags in `{@html ...}`)\n\t\te.custom_renderer_unsupported_operation('textContent');\n\t}\n\tnode.textContent = value;\n}\n\n/**\n * @param {Node} node\n * @param {string} value\n */\nexport function set_node_value(node, value) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.setText(node, value);\n\t\treturn;\n\t}\n\tnode.nodeValue = value;\n}\n\n/**\n * @param {Node} node\n * @returns {string | null}\n */\nexport function get_node_value(node) {\n\tif (current_renderer) return current_renderer.getText(node);\n\treturn node.nodeValue;\n}\n\n/**\n * Sets the `value` property on an element. For custom renderers, uses `setAttribute`.\n * @param {Element} element\n * @param {any} value\n */\nexport function set_element_value(element, value) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.setAttribute(element, 'value', value ?? '');\n\t\treturn;\n\t}\n\t// @ts-expect-error\n\telement.value = value ?? '';\n}\n\n/**\n * Sets the `checked` property on an element. For custom renderers, uses `setAttribute`.\n * @param {Element} element\n * @param {boolean} checked\n */\nexport function set_element_checked(element, checked) {\n\tif (current_renderer) {\n\t\tif (checked) {\n\t\t\tcurrent_renderer.setAttribute(element, 'checked', '');\n\t\t} else {\n\t\t\tcurrent_renderer.removeAttribute(element, 'checked');\n\t\t}\n\t\treturn;\n\t}\n\t// @ts-expect-error\n\telement.checked = checked;\n}\n\n/**\n * Sets the `defaultValue` property on an element without affecting the current `value`.\n * For custom renderers, uses `setAttribute` on `defaultvalue`.\n * @param {Element} element\n * @param {string} value\n */\nexport function set_element_default_value(element, value) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.setAttribute(element, 'defaultValue', value);\n\t\treturn;\n\t}\n\t// @ts-expect-error\n\tconst existing_value = element.value;\n\t// @ts-expect-error\n\telement.defaultValue = value;\n\t// @ts-expect-error\n\telement.value = existing_value;\n}\n\n/**\n * Sets the `defaultChecked` property on an element without affecting the current `checked` state.\n * For custom renderers, uses `setAttribute` on `defaultchecked`.\n * @param {Element} element\n * @param {boolean} checked\n */\nexport function set_element_default_checked(element, checked) {\n\tif (current_renderer) {\n\t\tif (checked) {\n\t\t\tcurrent_renderer.setAttribute(element, 'defaultChecked', '');\n\t\t} else {\n\t\t\tcurrent_renderer.removeAttribute(element, 'defaultChecked');\n\t\t}\n\t\treturn;\n\t}\n\t// @ts-expect-error\n\tconst existing_value = element.checked;\n\t// @ts-expect-error\n\telement.defaultChecked = checked;\n\t// @ts-expect-error\n\telement.checked = existing_value;\n}\n\n/**\n * @param {Element} element\n * @param {string} name\n * @returns {string | null}\n */\nexport function get_attribute(element, name) {\n\tif (current_renderer) return current_renderer.getAttribute(element, name);\n\treturn element.getAttribute(name);\n}\n\n/**\n * @param {Element} element\n * @param {string} name\n */\nexport function remove_attribute(element, name) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.removeAttribute(element, name);\n\t\treturn;\n\t}\n\telement.removeAttribute(name);\n}\n\n/**\n * @param {Element} element\n * @param {string} name\n * @returns {boolean}\n */\nexport function has_attribute(element, name) {\n\tif (current_renderer) return current_renderer.hasAttribute(element, name);\n\treturn element.hasAttribute(name);\n}\n\n/**\n * @param {Element} element\n * @param {string} value\n */\nexport function set_inner_html(element, value) {\n\tif (current_renderer) {\n\t\te.custom_renderer_unsupported_operation('innerHTML');\n\t}\n\telement.innerHTML = value;\n}\n\n/**\n * @param {Node} node\n * @param {boolean} deep\n * @returns {Node}\n */\nexport function clone_node(node, deep) {\n\tif (current_renderer) {\n\t\te.custom_renderer_unsupported_operation('cloneNode');\n\t}\n\treturn node.cloneNode(deep);\n}\n\n/**\n * @param {Node} node\n * @param {boolean} deep\n * @returns {Node}\n */\nexport function import_node(node, deep) {\n\tif (current_renderer) {\n\t\te.custom_renderer_unsupported_operation('importNode');\n\t}\n\treturn document.importNode(node, deep);\n}\n\n/**\n * @param {EventTarget} target\n * @param {string} type\n * @param {EventListenerOrEventListenerObject} handler\n * @param {boolean | AddEventListenerOptions} [options]\n */\nexport function add_event_listener(target, type, handler, options) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.addEventListener(target, type, handler, options);\n\t\treturn;\n\t}\n\ttarget.addEventListener(type, handler, options);\n}\n\n/**\n * @param {EventTarget} target\n * @param {string} type\n * @param {EventListenerOrEventListenerObject} handler\n * @param {boolean | EventListenerOptions} [options]\n */\nexport function remove_event_listener(target, type, handler, options) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.removeEventListener(target, type, handler, options);\n\t\treturn;\n\t}\n\ttarget.removeEventListener(type, handler, options);\n}\n\n/**\n * @param {EventTarget} target\n * @param {Event} event\n * @returns {boolean}\n */\nexport function dispatch_event(target, event) {\n\tif (current_renderer) {\n\t\te.custom_renderer_unsupported_operation('dispatchEvent');\n\t}\n\treturn target.dispatchEvent(event);\n}\n\n/**\n * @param {HTMLElement} element\n * @param {string} property\n * @param {string} value\n * @param {string} [priority]\n */\nexport function style_set_property(element, property, value, priority) {\n\t// custom renderers never get here: `set_style` and `css_props` set the whole attribute instead\n\telement.style.setProperty(property, value, priority);\n}\n\n/**\n * @param {HTMLElement} element\n * @param {string} property\n */\nexport function style_remove_property(element, property) {\n\t// custom renderers never get here: `set_style` and `css_props` set the whole attribute instead\n\telement.style.removeProperty(property);\n}\n\n/**\n * @param {HTMLElement} element\n * @param {string} value\n */\nexport function set_css_text(element, value) {\n\tif (current_renderer) {\n\t\tcurrent_renderer.setAttribute(element, 'style', value);\n\t\treturn;\n\t}\n\telement.style.cssText = value;\n}\n\n/**\n * @param {Element} element\n * @param {string} name\n * @param {boolean} force\n */\nexport function class_list_toggle(element, name, force) {\n\t// custom renderers never get here: `set_class` sets the whole attribute instead\n\telement.classList.toggle(name, force);\n}\n","/** @import { Effect } from '#client' */\n/** @import { Boundary } from './dom/blocks/boundary.js' */\nimport { DEV } from 'esm-env';\nimport { FILENAME, HYDRATION_ERROR } from '../../constants.js';\nimport { is_firefox } from './dom/operations.js';\nimport { BOUNDARY_EFFECT, REACTION_RAN, EFFECT, DESTROYED, DESTROYING } from './constants.js';\nimport { define_property, get_descriptor } from '../shared/utils.js';\nimport { active_effect } 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 (the error becomes their value)\n\tif (effect === null) {\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\tif (error === HYDRATION_ERROR) {\n\t\tthrow error;\n\t}\n\n\tif (effect !== null && (effect.f & DESTROYED) !== 0) {\n\t\treturn;\n\t}\n\n\twhile (effect !== null) {\n\t\t// Skip boundaries that are destroyed/destroying and cannot meaningfully handle the error.\n\t\tif ((effect.f & BOUNDARY_EFFECT) !== 0 && (effect.f & (DESTROYED | DESTROYING)) === 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 { ComponentContext, ComponentContextLegacy, Derived, Effect, TemplateNode, TransitionManager } from '#client' */\n/** @import { Blocker } from './async.js' */\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\tteardown_version,\n\tuntrack,\n\tuntracking,\n\tset_active_effect,\n\tabort_all\n} from '../runtime.js';\nimport {\n\tDIRTY,\n\tBRANCH_EFFECT,\n\tRENDER_EFFECT,\n\tEFFECT,\n\tDESTROYED,\n\tINERT,\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\tUSER_EFFECT,\n\tASYNC,\n\tCONNECTED,\n\tMANAGED_EFFECT,\n\tDESTROYING,\n\tPAUSED\n} from '#client/constants';\nimport { invoke_error_boundary } from '../error-handling.js';\nimport * as e from '../errors.js';\nimport { DEV } from 'esm-env';\nimport { define_property } from '../../shared/utils.js';\nimport { get_next_sibling, remove_node, append_child } from '../dom/operations.js';\nimport { component_context, dev_current_component_function, dev_stack } from '../context.js';\nimport { Batch, collected_effects, set_teardown_context, teardown_context } from './batch.js';\nimport { flatten } from './async.js';\nimport { set_signal_status } from './status.js';\nimport { push_renderer, current_renderer, pop_renderer } from '../custom-renderer/state.js';\nimport { custom_renderers_flag } from '../../flags/index.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\tdv: null,\n\t\tedges: 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\tr: current_renderer\n\t};\n\n\tif (DEV) {\n\t\teffect.component_function = dev_current_component_function;\n\t}\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, DIRTY);\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.edges === 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 =\n\t\t!active_reaction &&\n\t\t(flags & BRANCH_EFFECT) !== 0 &&\n\t\tcomponent_context !== null &&\n\t\t!component_context.i;\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.edges !== 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, () => {\n\t\t\tfn(...values.map(get));\n\t\t});\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\tflatten(blockers, sync, async, (values) => {\n\t\tcreate_effect(EFFECT, () => fn(...values.map(get)));\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_teardown_version = teardown_version;\n\t\tconst previous_teardown_context = teardown_context;\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} catch (error) {\n\t\t\t// Route teardown errors through the boundary system so that a live\n\t\t\t// ancestor <svelte:boundary> can handle them. Boundaries that are\n\t\t\t// themselves mid-teardown are skipped by invoke_error_boundary.\n\t\t\tinvoke_error_boundary(error, effect.parent);\n\t\t} finally {\n\t\t\tset_is_destroying_effect(previously_destroying_effect, previous_teardown_version);\n\t\t\tset_teardown_context(previous_teardown_context);\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\tabort_all(effect);\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\tvar previous_renderer = custom_renderers_flag ? push_renderer(effect.r) : null;\n\n\ttry {\n\t\tif (\n\t\t\t(remove_dom || (effect.f & HEAD_EFFECT) !== 0) &&\n\t\t\teffect.nodes !== null &&\n\t\t\teffect.nodes.end !== null\n\t\t) {\n\t\t\tremove_effect_dom(effect.nodes.start, /** @type {TemplateNode} */ (effect.nodes.end));\n\t\t\tremoved = true;\n\t\t}\n\n\t\teffect.f |= DESTROYING;\n\t\tdestroy_effect_children(effect, remove_dom && !removed);\n\t\tremove_reactions(effect);\n\n\t\tvar transitions = effect.nodes && effect.nodes.t;\n\n\t\tif (transitions !== null) {\n\t\t\tfor (const transition of transitions) {\n\t\t\t\ttransition.stop();\n\t\t\t}\n\t\t}\n\n\t\texecute_effect_teardown(effect);\n\t} finally {\n\t\t// nothing below interacts with the renderer\n\t\tif (custom_renderers_flag) pop_renderer(previous_renderer);\n\t}\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.dv =\n\t\teffect.edges =\n\t\teffect.fn =\n\t\teffect.nodes =\n\t\teffect.ac =\n\t\teffect.b =\n\t\teffect.r =\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\tremove_node(/** @type {ChildNode} */ (node));\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\teffect.f |= PAUSED;\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\n\tif (remaining > 0) {\n\t\tvar context = teardown_context;\n\n\t\tvar check = () => {\n\t\t\tif (!--remaining) {\n\t\t\t\tvar previous_context = teardown_context;\n\n\t\t\t\ttry {\n\t\t\t\t\tif (context) {\n\t\t\t\t\t\t// Other outros can share this context, and state may have changed\n\t\t\t\t\t\t// since its derived values were cached.\n\t\t\t\t\t\tcontext.derived_cache.clear();\n\t\t\t\t\t\tset_teardown_context(context);\n\t\t\t\t\t}\n\t\t\t\t\tfn();\n\t\t\t\t} finally {\n\t\t\t\t\tif (context) set_teardown_context(previous_context);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\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\teffect.f &= ~PAUSED;\n\tresume_children(effect, true);\n}\n\n/**\n * @param {Effect} effect\n * @param {boolean} local\n */\nfunction resume_children(effect, local) {\n\t// this subtree was paused for its own reasons (e.g. a block whose condition\n\t// is still false) — its controller will resume or destroy it\n\tif ((effect.f & PAUSED) !== 0) return;\n\n\tif ((effect.f & INERT) === 0) return;\n\teffect.f ^= INERT;\n\n\t// If a dependency of this effect may have 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\t// Assumption: This happens during the commit phase of the batch, causing another flush, but it's safe\n\t\tBatch.ensure().schedule(effect, MAYBE_DIRTY);\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\n/**\n * @param {Effect} effect\n * @param {DocumentFragment} fragment\n */\nexport function move_effect(effect, fragment) {\n\tif (!effect.nodes) return;\n\n\tvar previous_renderer = custom_renderers_flag ? push_renderer(effect.r) : null;\n\n\ttry {\n\t\t/** @type {TemplateNode | null} */\n\t\tvar node = effect.nodes.start;\n\t\tvar end = effect.nodes.end;\n\n\t\twhile (node !== null) {\n\t\t\t/** @type {TemplateNode | null} */\n\t\t\tvar next = node === end ? null : get_next_sibling(node);\n\n\t\t\tappend_child(fragment, node);\n\t\t\tnode = next;\n\t\t}\n\t} finally {\n\t\tif (custom_renderers_flag) pop_renderer(previous_renderer);\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 { hydrating } from '../hydration.js';\nimport { clear_text_content, get_first_child, add_event_listener } from '../operations.js';\nimport { queue_micro_task } from '../task.js';\nimport { FORM_RESET_HANDLER } from '../../constants.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\tadd_event_listener(\n\t\t\tdocument,\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/** @type {any} */ (e)[FORM_RESET_HANDLER]?.();\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 { FORM_RESET_HANDLER } from '../../../constants.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\tconst prev = /** @type {any} */ (element)[FORM_RESET_HANDLER];\n\tif (prev) {\n\t\t// special case for checkbox that can have multiple binds (group & checked)\n\t\t/** @type {any} */ (element)[FORM_RESET_HANDLER] = () => {\n\t\t\tprev();\n\t\t\ton_reset(true);\n\t\t};\n\t} else {\n\t\t/** @type {any} */ (element)[FORM_RESET_HANDLER] = () => on_reset(true);\n\t}\n\n\tadd_form_reset_listener();\n}\n","/** @import { BatchRecord, BatchValue, Derived, DerivedRecord, 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\tHAS_ABORT_CONTROLLER,\n\tMANAGED_EFFECT,\n\tREACTION_RAN,\n\tASYNC,\n\tASSIGNED\n} from './constants.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\tget_view\n} from './reactivity/deriveds.js';\nimport { async_mode_flag, tracing_mode_flag, custom_renderers_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\tfirst_batch,\n\tflushSync,\n\tpush_teardown_context,\n\tteardown_context,\n\tview_batch,\n\tview_cache\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 { merge_target } from './reactivity/async.js';\nimport * as e from './errors.js';\nimport * as w from './warnings.js';\nimport { push_renderer, pop_renderer } from './custom-renderer/state.js';\n\nexport let is_destroying_effect = false;\n\n/** The write version when the running teardown started — later writes happened in it, and aren't reverted */\nexport let teardown_version = 0;\n\n/**\n * @param {boolean} value\n * @param {number} [version]\n */\nexport function set_is_destroying_effect(value, version = write_version) {\n\tis_destroying_effect = value;\n\tteardown_version = version;\n}\n\n/**\n * The result of the latest run of a derived in a teardown, which only the teardown sees: `update_dependencies` sets\n * it — that's where the run's dependencies, which determine its version, are known — instead of storing the run, and\n * `teardown_view` takes it right after `execute_derived`\n * @type {BatchValue}\n */\nlet teardown_run = { v: undefined, wv: 0, e: false, assigned: false };\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 | Set<Value>}\n */\nexport let current_sources = null;\n\n/** @param {Value} value */\nexport function push_reaction_value(value) {\n\tif (\n\t\tactive_reaction !== null &&\n\t\t((!async_mode_flag && (active_reaction.f & REACTION_IS_UPDATING) !== 0) ||\n\t\t\t(active_reaction.f & DERIVED) !== 0)\n\t) {\n\t\t(current_sources ??= new Set()).add(value);\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 | Value[]}\n */\nexport let untracked_writes = null;\n\n/** @param {null | Value[]} 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: every new value — whether it is\n * the real-world (i.e. latest) one, or only exists within a batch — gets a new version. Versions\n * identify values, they are only ever compared for equality (except for `$inspect.trace`).\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 dependencies 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 * The version `signal` has in the active view of the world, bringing deriveds up to date\n * @param {Value} signal\n */\nexport function version_of(signal) {\n\tif (batch_values === null) {\n\t\tupdate_derived(signal);\n\t\treturn signal.wv;\n\t}\n\n\tif ((signal.f & DERIVED) !== 0) {\n\t\treturn get_view(/** @type {Derived} */ (signal)).wv;\n\t}\n\n\treturn (batch_values.get(signal) ?? signal).wv;\n}\n\n/**\n * Whether the values with the given versions are (still) what `deps` hold in the active view of the world.\n * Dependencies are checked in order and deriveds are brought up to date along the way, so that we\n * don't evaluate a derived that the reaction would no longer read (e.g. `a ? b : c` where `a` changed)\n * @param {Value[] | null} deps\n * @param {number[]} dv\n */\nexport function is_current(deps, dv) {\n\tif (deps !== null) {\n\t\tfor (var i = 0; i < dv.length; i++) {\n\t\t\tif (version_of(deps[i]) !== dv[i]) return false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n/**\n * Whether none of `deps` has been written since the version `wv` in the active view of the world, which is\n * how a value assigned to a derived (whose version is `wv`) holds: until one of the values read by the run\n * that applies in the view (see `get_view`) is written after it. Comparing versions with those the\n * dependencies had at the time of the assignment, like `is_current` does, wouldn't work: a view might undo\n * a write the assignment saw, and a committed fork might apply one it didn't see — but both writes happened\n * before the assignment, so they don't make it outdated.\n *\n * This (and its counterpart in `teardown_view`) is where versions are compared by order across views. That only works for versions of writes\n * (including assignments), which are allocated when the write happens. A derived's version is allocated when it is\n * evaluated, which can be after the assignment even if everything it read was written before it (e.g. because it is\n * evaluated lazily, or again in another view). So a derived only counts as changed if, in addition, one of the\n * values its run in the view read was written after the assignment\n * @param {Value[] | null} deps\n * @param {number} wv\n * @param {Set<Derived | DerivedRecord | BatchValue> | null} [unchanged] runs that this walk found unchanged,\n * to avoid walking a derived that is reachable by more than one path (e.g. a diamond) once per path. Only valid\n * within one top-level call: `wv` and the view are fixed, and the walk itself doesn't write anything\n */\nexport function changed_since(deps, wv, unchanged = null) {\n\tif (deps !== null) {\n\t\tfor (var i = 0; i < deps.length; i++) {\n\t\t\tvar dep = deps[i];\n\n\t\t\tif ((dep.f & DERIVED) === 0) {\n\t\t\t\tif (version_of(dep) > wv) return true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// the run of the derived that applies in the view, brought up to date — or a value assigned to it\n\t\t\t/** @type {Derived | DerivedRecord | BatchValue} */\n\t\t\tvar run = /** @type {Derived} */ (dep);\n\n\t\t\tif (batch_values === null) {\n\t\t\t\tupdate_derived(/** @type {Derived} */ (dep));\n\t\t\t} else {\n\t\t\t\trun = get_view(/** @type {Derived} */ (dep));\n\t\t\t}\n\n\t\t\t// (an equal value keeps its version, so a derived whose value didn't change since doesn't count either)\n\t\t\tif (run.wv > wv) {\n\t\t\t\tvar assigned = run === dep ? (dep.f & ASSIGNED) !== 0 : !('dv' in run);\n\n\t\t\t\tif (assigned) return true;\n\n\t\t\t\t// this run was already found to have no writes after `wv` below it\n\t\t\t\tif (unchanged === null) {\n\t\t\t\t\tunchanged = new Set();\n\t\t\t\t} else if (unchanged.has(run)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (changed_since(/** @type {DerivedRecord} */ (run).deps, wv, unchanged)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tunchanged.add(run);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * For block/async effects returns the record of the {@link view_batch} (if any), else reaction itself.\n * @param {Reaction} reaction\n * @returns {Reaction | BatchRecord}\n */\nexport function run_of(reaction) {\n\treturn (\n\t\t((reaction.f & (BLOCK_EFFECT | ASYNC)) !== 0 && view_batch?.get_record(reaction)) || reaction\n\t);\n}\n\n/**\n * Determines whether a derived or effect is dirty.\n * If it is MAYBE_DIRTY (or an assigned derived) and isn't, will set the status to CLEAN.\n * Deriveds are only checked like this in the real world — within the view of a batch,\n * see {@link get_view}. Effects are checked against the run that applies (see `run_of`).\n * @param {Reaction} reaction\n * @returns {boolean}\n */\nexport function is_dirty(reaction) {\n\tvar flags = reaction.f;\n\n\tif ((flags & (DIRTY | MAYBE_DIRTY)) === 0) {\n\t\treturn false;\n\t}\n\n\tif ((flags & ASSIGNED) !== 0) {\n\t\t// A value assigned to a derived holds until one of its dependencies is written after it, which its flags\n\t\t// can't tell: writes that don't change the real world (e.g. those of a fork) mark the derived, too\n\t\tif (changed_since(reaction.deps, reaction.wv)) return true;\n\t} else if ((flags & DIRTY) !== 0) {\n\t\treturn true;\n\t} else {\n\t\tvar run = run_of(reaction);\n\t\tvar deps = run.deps;\n\t\tvar dv = run.dv;\n\n\t\tif (dv === null) return true;\n\n\t\tif (batch_values === null) {\n\t\t\tfor (var i = 0, length = dv.length; i < length; i++) {\n\t\t\t\tvar dependency = /** @type {Value[]} */ (deps)[i];\n\n\t\t\t\tupdate_derived(dependency);\n\n\t\t\t\tif (dependency.wv !== dv[i]) return true;\n\t\t\t}\n\t\t} else if (!is_current(deps, dv)) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tif ((flags & CONNECTED) !== 0) {\n\t\tset_signal_status(reaction, CLEAN);\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 && current_sources.has(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\t/** @type {Batch} */ (current_batch).schedule(\n\t\t\t\t/** @type {Effect} */ (reaction),\n\t\t\t\troot ? DIRTY : MAYBE_DIRTY\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * The controller of the signal of the run in progress, if it asked for one (see `get_abort_signal`). Once the run is\n * done, it's stored with the run: on the reaction for its global run, or on the record a batch holds of it\n * @type {AbortController | null}\n */\nexport let abort_controller = null;\n\n/**\n * The signal of the run of `reaction` that is in progress. Its controller is stored with the run once it's done\n * (see `set_global_signal` and `update_record`) — `reaction.ac` is the previous global run's until then\n * @param {Reaction} reaction\n */\nexport function get_abort_signal(reaction) {\n\tif ((reaction.f & REACTION_IS_UPDATING) === 0) {\n\t\t// for now, disallow calling `getAbortSignal()` after an `await`. we could\n\t\t// potentially relax this restriction in future, but it adds complexity\n\t\te.get_abort_signal_after_await();\n\t}\n\n\treaction.f |= HAS_ABORT_CONTROLLER;\n\n\treturn (abort_controller ??= new AbortController()).signal;\n}\n\n/** @param {AbortController | null | undefined} controller */\nfunction abort_signal(controller) {\n\tif (controller) without_reactive_context(() => controller.abort(STALE_REACTION));\n}\n\n/**\n * Abort the signal of a record of `reaction` that a batch replaces or drops — unless another batch holds the\n * record, too (see `keep_global_run`), in which case it aborts once the last one lets go of it\n * @param {Reaction} reaction\n * @param {BatchRecord | undefined} record\n * @param {boolean} [rerun] whether `reaction` is about to run again (see `abort_replaced`). The active batch\n * and the batches that the new run supersedes still hold the record then, but don't count\n */\nexport function abort_record(reaction, record, rerun = false) {\n\tif (!record?.ac) return;\n\n\tfor (var b = first_batch; b !== null; b = b.next) {\n\t\tif (\n\t\t\tb.records?.get(reaction) === record &&\n\t\t\t!(rerun && (b === view_batch || supersedes(current_batch, b)))\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tabort_signal(record.ac);\n\trecord.ac = null;\n}\n\n/**\n * Before `reaction` runs again, abort the signals of the runs it replaces: its run in the active batch (which the\n * new run replaces either way, see `update_record`), its global run if the new run is going to replace that one,\n * and the runs of earlier batches that a run in a real batch supersedes (see `supersedes`). (Forks stay\n * independent until they're committed or discarded.) Whether a derived's run in a view replaces the global run\n * is only known once it's done (see `set_global_signal`) — unless the global run is outdated in the real world\n * anyway\n * @param {Reaction} reaction\n * @param {number} flags\n */\nfunction abort_replaced(reaction, flags) {\n\tvar batch = current_batch;\n\tvar is_derived = (flags & DERIVED) !== 0;\n\n\t// a teardown's run of a derived doesn't replace anything (see `teardown_view`)\n\tif (is_derived && is_destroying_effect) return;\n\n\tvar real = batch === null || !batch.is_fork;\n\n\tabort_record(reaction, view_batch?.records?.get(reaction), true);\n\n\tif (is_derived ? batch_values === null || (real && is_outdated(reaction)) : real) {\n\t\t// (the controller stays referenced until the new run is stored, see `keep_global_run`)\n\t\tabort_signal(reaction.ac);\n\t}\n\n\tfor (var b = first_batch; b !== null; b = b.next) {\n\t\tif (supersedes(batch, b)) abort_record(reaction, b.records?.get(reaction), true);\n\t}\n}\n\n/**\n * The run that just ended is the global state of `reaction`: its signal replaces the global run's, which aborts —\n * unless other batches took that run over, along with its signal (see `keep_global_run`)\n * @param {Reaction} reaction\n */\nfunction set_global_signal(reaction) {\n\tabort_signal(reaction.ac);\n\treaction.ac = abort_controller;\n}\n\n/**\n * Whether a run is invalid or a dependency's real-world version has changed.\n * This does not evaluate derived dependencies, which may themselves be outdated.\n * @param {Reaction | BatchRecord} run\n */\nexport function is_outdated({ deps, dv }) {\n\treturn dv === null || dv.some((version, i) => /** @type {Value[]} */ (deps)[i].wv !== version);\n}\n\n/**\n * Whether a run in `batch` supersedes the runs of batch `other`, so that their signals abort (see `abort_replaced`):\n * a run in a real batch supersedes those of earlier batches whose writes it saw — because it ran in the real world,\n * or in a view that folds them, or undoes none of their writes (e.g. because they committed, see `Batch#activate`).\n * The runs of other earlier batches read their writes, which this run didn't see, so they still apply in their\n * views. Forks stay independent until they're committed or discarded\n * @param {Batch | null} batch\n * @param {Batch} other\n */\nfunction supersedes(batch, other) {\n\treturn (\n\t\tbatch !== null &&\n\t\t!batch.is_fork &&\n\t\t!other.is_fork &&\n\t\tother.id < batch.id &&\n\t\t(batch_values === null || other.previous.size === 0 || batch.folded.includes(other))\n\t);\n}\n\n/**\n * Abort all signals of `reaction` (see `getAbortSignal`), e.g. because it's destroyed.\n * Returns whether a run had requested a signal, even if it was already aborted\n * @param {Reaction} reaction\n */\nexport function abort_all(reaction) {\n\tif ((reaction.f & HAS_ABORT_CONTROLLER) === 0) return false;\n\treaction.f ^= HAS_ABORT_CONTROLLER;\n\n\tabort_signal(reaction.ac);\n\treaction.ac = null;\n\n\tfor (var b = first_batch; b !== null; b = b.next) {\n\t\tvar record = b.records?.get(reaction);\n\n\t\tif (record?.ac) {\n\t\t\tabort_signal(record.ac);\n\t\t\trecord.ac = null;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n/**\n * Whether or not we should unconditionally record a reaction run within a batch, as opposed\n * to updating the signal directly. True for async effects, and previously-initialized\n * block effects (as long as they run during traversal, rather than on commit)\n * @param {number} flags\n */\nfunction is_recorded_effect(flags) {\n\tif (\n\t\t(flags & ASYNC) === 0 &&\n\t\t(flags & (BLOCK_EFFECT | REACTION_RAN)) !== (BLOCK_EFFECT | REACTION_RAN)\n\t) {\n\t\treturn false;\n\t}\n\n\treturn view_batch !== null && view_batch === current_batch;\n}\n\n/** @param {Reaction} reaction */\nexport function update_reaction(reaction) {\n\tconst batch = current_batch;\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\tvar previous_abort_controller = abort_controller;\n\tabort_controller = null;\n\n\tif ((flags & HAS_ABORT_CONTROLLER) !== 0) {\n\t\tabort_replaced(reaction, flags);\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\tupdate_dependencies(reaction, flags, result, false);\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\t// bail out if the effect didn't read anything\n\t\t\t(new_deps !== null || skipped_deps > 0) &&\n\t\t\t(reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0\n\t\t) {\n\t\t\tfor (var 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\treturn result;\n\t} catch (error) {\n\t\tvar value = error;\n\n\t\ttry {\n\t\t\tvalue = handle_error(error);\n\t\t} finally {\n\t\t\t// Still commit the deps read before the throw, otherwise deriveds connected by this run keep no reader\n\t\t\t// and the reaction never re-runs when they change. For a derived, the error is the value of the run\n\t\t\t// (`get` throws it) — unless an error boundary took care of it\n\t\t\tupdate_dependencies(reaction, flags, value, value === error);\n\t\t}\n\n\t\treturn value;\n\t} finally {\n\t\tvar signal = /** @type {AbortController | null} */ (abort_controller)?.signal;\n\n\t\tif (batch !== null && signal !== undefined) {\n\t\t\t// The reaction that requested the signal identifies the merge target, even if\n\t\t\t// another reaction awaits its result (e.g. `let promise = $derived(load(...))`).\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\tif (current_batch !== null) {\n\t\t\t\t\tconst target = merge_target(batch);\n\n\t\t\t\t\tif (target !== current_batch && target.linked && !target.is_fork) {\n\t\t\t\t\t\tcurrent_batch.merge_requests.add(target);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\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\tabort_controller = previous_abort_controller;\n\t}\n}\n\n/**\n * Store the result of the current run of `reaction` where it belongs — the versions of the\n * values it read and, for a derived, its value — and update the edges of the graph.\n *\n * A run belongs to the real world — and becomes the reaction's global state — unless\n * - it is a derived that read values which aren't the latest ones (it is then stored in the batch\n *   whose view of the world it ran in, see {@link get_view})\n * - it is an effect run that belongs to a batch (see {@link update_record})\n * - it is a derived evaluated in a teardown, in which case only the teardown sees it (see `teardown_view`)\n *\n * The edges of the graph (`reaction.edges` and the `reactions` of its dependencies) are a\n * superset of the dependencies of every live record, so that changes to any of them reach\n * the reaction. They are only pruned when a global run happens and no batch holds a record.\n * @param {Reaction} reaction\n * @param {number} flags the flags of the reaction before the run\n * @param {any} value the value of the run (only relevant for deriveds)\n * @param {boolean} error whether the value is an error\n */\nfunction update_dependencies(reaction, flags, value, error) {\n\tvar deps = reaction.deps;\n\tvar length = skipped_deps + (new_deps === null ? 0 : new_deps.length);\n\tvar dv = reaction.dv;\n\n\t// an effect can be destroyed while it runs, e.g. by an error boundary\n\tif ((reaction.f & DESTROYED) !== 0) {\n\t\tabort_signal(abort_controller);\n\t\treturn;\n\t}\n\n\t// ...and so can the last reaction of a derived, which aborts the derived's signals, see `remove_reaction`.\n\t// `abort_all` removed the flag that the run in progress set, so its signal is still to be aborted\n\tif (abort_controller !== null && (reaction.f & HAS_ABORT_CONTROLLER) === 0) {\n\t\tabort_signal(abort_controller);\n\t\tabort_controller = null;\n\t}\n\n\tif ((flags & DERIVED) !== 0 && is_destroying_effect) {\n\t\t// The run belongs to the teardown's view of the world (see `teardown_view`).\n\t\t// Its value can't be more recent than what it read\n\t\tvar wv = 0;\n\n\t\tfor (var j = 0; j < length; j++) {\n\t\t\tvar dep =\n\t\t\t\tj < skipped_deps\n\t\t\t\t\t? /** @type {Value[]} */ (deps)[j]\n\t\t\t\t\t: /** @type {Value[]} */ (new_deps)[j - skipped_deps];\n\n\t\t\twv = Math.max(wv, teardown_version_of(dep));\n\t\t}\n\n\t\t// TODO: the run's signal (if any) is never aborted — should we abort when the teardown's view of the\n\t\t// world is done with the run?\n\t\tteardown_run = { v: value, wv, e: error, assigned: (flags & ASSIGNED) !== 0 };\n\t\treturn;\n\t}\n\n\t// A run of a derived in the real world is its new global state. Other batches may still see the current one\n\t// (in a view, whether a derived's run is a global one is decided by `update_record`)\n\tif (\n\t\t(flags & DERIVED) !== 0 &&\n\t\tbatch_values === null &&\n\t\tfirst_batch !== null &&\n\t\tfirst_batch.next !== null\n\t) {\n\t\tkeep_global_run(/** @type {Derived} */ (reaction), flags);\n\t}\n\n\t// Fast path: the reaction read the same values as before, in the real world, and has no other edges\n\tif (\n\t\tnew_deps === null &&\n\t\tbatch_values === null &&\n\t\tdv !== null &&\n\t\tlength === deps?.length &&\n\t\treaction.edges === deps &&\n\t\t(flags & (BLOCK_EFFECT | ASYNC)) === 0\n\t) {\n\t\t// The run saw what its dependencies hold now — a write during the run after it read\n\t\t// the value marks it dirty (see `Batch#schedule`), so it doesn't take effect here\n\t\tfor (var i = 0; i < length; i++) dv[i] = deps[i].wv;\n\t\tif (dv.length !== length) dv.length = length;\n\n\t\tif ((flags & DERIVED) !== 0) set_derived_value(/** @type {Derived} */ (reaction), value, error);\n\t\tif (reaction.ac || abort_controller) set_global_signal(reaction);\n\n\t\treturn;\n\t}\n\n\tupdate_record(reaction, flags, length, value, error);\n}\n\n/**\n * Make `value` the (real-world) value of `derived` — it keeps its version if it is the same value\n * @param {Derived} derived\n * @param {any} value\n * @param {boolean} error\n */\nfunction set_derived_value(derived, value, error) {\n\t// a run replaces a value that was assigned to the derived\n\tvar flags = derived.f & ~ASSIGNED;\n\n\tif (error || (flags & ERROR_VALUE) !== 0 || !derived.equals(value)) {\n\t\tderived.v = value;\n\t\tderived.wv = increment_write_version();\n\t\tflags = error ? flags | ERROR_VALUE : flags & ~ERROR_VALUE;\n\t}\n\n\tderived.f = flags;\n\tupdate_derived_status(derived);\n}\n\n/**\n * The general case of `update_dependencies`, which\n * 1. decides where the run belongs: to the batch whose view of the world is active (as a record, see\n *    `Batch#records`), or to the real world (as the reaction's global state)\n * 2. records the versions of the values the run read (`dv`)\n * 3. updates the edges of the graph\n * 4. stores the run where it belongs\n * @param {Reaction} reaction\n * @param {number} flags the flags of the reaction before the run\n * @param {number} length the number of values the run read\n * @param {any} value the value of the run (only relevant for deriveds)\n * @param {boolean} error whether the value is an error\n */\nfunction update_record(reaction, flags, length, value, error) {\n\t// Block and async effects that run while a batch is processed produce a result for that batch (the\n\t// branch it selected, the value an async expression resolved to for it), which it keeps until it\n\t// commits. The first run of a block effect is the exception — it creates (and commits) its initial\n\t// branch. (Whether a derived's run belongs to a batch depends on what it read, see below)\n\tvar should_record = is_recorded_effect(flags);\n\n\t// A derived that has another version in the view than in the real world — because the view undoes an\n\t// assignment to it, or it was assigned in a fork — never runs for the real world (see `get_view`)\n\tif (batch_values !== null && (flags & DERIVED) !== 0) {\n\t\tvar written = batch_values.get(/** @type {Derived} */ (reaction));\n\n\t\tif (written !== undefined && written.wv !== /** @type {Derived} */ (reaction).wv) {\n\t\t\tshould_record = true;\n\t\t}\n\t}\n\n\tvar deps = reaction.deps;\n\tvar read = deps;\n\tif (new_deps !== null || skipped_deps !== deps?.length) {\n\t\tread =\n\t\t\tskipped_deps === 0\n\t\t\t\t? new_deps\n\t\t\t\t: /** @type {Value[]} */ (deps).slice(0, skipped_deps).concat(new_deps ?? []);\n\t}\n\n\t// A global run in the real world updates the versions in place. Anything else needs a new array:\n\t// a record must not share it with the global state, and a derived's run can turn out to belong\n\t// to the batch halfway through the loop\n\tvar dv = !should_record && batch_values === null && reaction.dv !== null ? reaction.dv : [];\n\n\tfor (var i = 0; i < length; i++) {\n\t\tvar dep = /** @type {Value[]} */ (read)[i];\n\t\tdv[i] = seen_version(dep);\n\n\t\t// Within a batch's view, a derived's run belongs to the batch unless everything it read is the latest\n\t\t// value: the version it saw is the real-world one, and — for a derived — that one is up to date\n\t\tif (\n\t\t\tbatch_values !== null &&\n\t\t\t(flags & DERIVED) !== 0 &&\n\t\t\t(dv[i] !== dep.wv || (dep.f & (DERIVED | CLEAN)) === DERIVED)\n\t\t) {\n\t\t\tshould_record = true;\n\t\t}\n\t}\n\n\tif (dv.length !== length) dv.length = length;\n\n\tif (!should_record && batch_values !== null && (flags & DERIVED) !== 0) {\n\t\tkeep_global_run(/** @type {Derived} */ (reaction), flags);\n\t}\n\n\t// The edges — `reaction.edges`, and `reaction` in the `reactions` of each of them — must cover what every\n\t// live run of the reaction read (its global run, and the records batches hold of it), so that a change to\n\t// any of those values reaches it. So unless this is a global run and no batch holds a record, edges are\n\t// only added (and pruned by a later global run). Their order is independent of the run's reads\n\tvar keep = should_record || has_batch_record(reaction);\n\tvar tracking = effect_tracking() && (reaction.f & CONNECTED) !== 0;\n\tvar edges = reaction.edges;\n\n\tif (keep && edges !== null) {\n\t\tif (new_deps !== null) {\n\t\t\t// the edges may be a run's `deps` as well, see `update_dependencies`\n\t\t\treaction.edges = edges = edges.slice();\n\t\t\tfor (dep of new_deps) {\n\t\t\t\tif (!includes.call(edges, dep)) {\n\t\t\t\t\tedges.push(dep);\n\t\t\t\t\tif (tracking) (dep.reactions ??= []).push(reaction);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (edges === deps) {\n\t\t\t// The edges are exactly what the previous global run read (if anything), so — as on `main` —\n\t\t\t// the values this run read again, in the same order, stay connected, and the rest is replaced\n\t\t\tif (edges !== null) {\n\t\t\t\tfor (i = skipped_deps; i < edges.length; i++) remove_reaction(reaction, edges[i]);\n\t\t\t}\n\n\t\t\tif (tracking && new_deps !== null) {\n\t\t\t\tfor (dep of new_deps) (dep.reactions ??= []).push(reaction);\n\t\t\t}\n\t\t} else {\n\t\t\t// The edges can include some that were retained for runs no batch holds anymore\n\t\t\tvar added = new Set(read);\n\t\t\tfor (dep of /** @type {Value[]} */ (edges)) {\n\t\t\t\tif (!added.delete(dep)) remove_reaction(reaction, dep);\n\t\t\t}\n\n\t\t\tif (tracking) {\n\t\t\t\tfor (dep of added) (dep.reactions ??= []).push(reaction);\n\t\t\t}\n\t\t}\n\n\t\treaction.edges = read;\n\t}\n\n\tif (should_record) {\n\t\tvar batch = /** @type {Batch} */ (view_batch);\n\n\t\t(batch.records ??= new Map()).set(\n\t\t\treaction,\n\t\t\t(flags & DERIVED) !== 0\n\t\t\t\t? {\n\t\t\t\t\t\tdeps: read,\n\t\t\t\t\t\tdv,\n\t\t\t\t\t\tv: value,\n\t\t\t\t\t\te: error,\n\t\t\t\t\t\twv: derived_version(/** @type {Derived} */ (reaction), batch, value, error),\n\t\t\t\t\t\tac: abort_controller\n\t\t\t\t\t}\n\t\t\t\t: { deps: read, dv, ac: abort_controller }\n\t\t);\n\t} else {\n\t\treaction.deps = read;\n\t\treaction.dv = dv;\n\t\tif (reaction.ac || abort_controller) set_global_signal(reaction);\n\n\t\tif ((flags & DERIVED) !== 0) {\n\t\t\tset_derived_value(/** @type {Derived} */ (reaction), value, error);\n\n\t\t\t// A record of the derived in the active batch is outdated now. (Effects never have one at this point:\n\t\t\t// their runs only become global outside of processing, on their first run, or once the batch commits,\n\t\t\t// whose records are promoted by then)\n\t\t\tview_batch?.records?.delete(reaction);\n\t\t}\n\t}\n}\n\n/**\n * A run of `derived` that becomes its global state replaces the current one, which other batches may still see:\n * their views differ from the real world, and can undo the writes that made it outdated. It is kept as a record in\n * each of them that doesn't have one, so that they don't evaluate the derived again — which would give an equal value\n * a new version, and re-run what saw the current one (restarting async work, for example). That's also the case if\n * the new value is equal, and so keeps its version: the derived itself would still run again, with whatever side\n * effects it has (like asking for a new abort signal). (Like any record, it is only used where it `is_current`)\n *\n * If the derived uses an abort signal, the kept run's may have been aborted when the derived ran again. Only the batches\n * that the new run supersedes (see `supersedes`) keep it regardless — it stays aborted for them until something it read\n * changes in their view. The others (forks, later batches) evaluate the derived again.\n *\n * A fork's run supersedes nothing, though, so the run it replaces isn't aborted: a batch may still be waiting for it.\n * Every other batch keeps it then, and the record takes over its signal, which aborts once no batch holds the record\n * anymore (see `abort_record`)\n * @param {Derived} derived\n * @param {number} flags the flags of the derived before the run\n */\nfunction keep_global_run(derived, flags) {\n\tvar dv = derived.dv;\n\n\tif (\n\t\t// no valid run, or one that doesn't depend on anything — which is only run again if it was invalidated\n\t\tdv === null ||\n\t\tdv.length === 0 ||\n\t\t// an assigned value isn't a run, see `get_view`\n\t\t(flags & ASSIGNED) !== 0\n\t) {\n\t\treturn;\n\t}\n\n\t/** @type {DerivedRecord | undefined} */\n\tvar record;\n\n\tvar ac = derived.ac;\n\n\t// whether the run's signal stays live, because a fork's view ran the derived (it's only aborted before the\n\t// derived runs again if the run was in the real world, see `abort_replaced`)\n\tvar live = ac !== null && current_batch !== null && current_batch.is_fork && !ac.signal.aborted;\n\n\tfor (var batch = first_batch; batch !== null; batch = batch.next) {\n\t\tif (\n\t\t\tbatch !== view_batch &&\n\t\t\t!batch.records?.has(derived) &&\n\t\t\t// otherwise, the run's signal was aborted when the derived ran again, or is about to be (see `set_global_signal`)\n\t\t\t(ac === null || live || supersedes(current_batch, batch))\n\t\t) {\n\t\t\t// All batches that retain this run share one record. (Its versions are copied: the\n\t\t\t// derived's next global run in the real world updates its own in place)\n\t\t\trecord ??= {\n\t\t\t\tdeps: derived.deps,\n\t\t\t\tdv: dv.slice(),\n\t\t\t\tv: derived.v,\n\t\t\t\twv: derived.wv,\n\t\t\t\te: (flags & ERROR_VALUE) !== 0\n\t\t\t};\n\t\t\t(batch.records ??= new Map()).set(derived, record);\n\t\t}\n\t}\n\n\tif (live && record !== undefined) {\n\t\t// the signal belongs to the batches that kept the run now. (If none did, `set_global_signal` aborts it)\n\t\trecord.ac = ac;\n\t\tderived.ac = null;\n\t}\n}\n\n/**\n * The version of `signal` that the current run saw. Recording it never evaluates anything: a derived that\n * isn't in the view's cache (anymore) was invalidated by a write during the run, or can't be cached —\n * the run then doesn't count as having seen its current version, just like in the real world, where\n * a derived that changes during the run gets a new version only once it is evaluated again\n * @param {Value} signal\n */\nfunction seen_version(signal) {\n\tif (batch_values === null) return signal.wv;\n\n\tif ((signal.f & DERIVED) !== 0) {\n\t\tvar cache = /** @type {Map<Derived, Derived | DerivedRecord | BatchValue>} */ (view_cache);\n\t\treturn cache.get(/** @type {Derived} */ (signal))?.wv ?? -1;\n\t}\n\n\treturn (batch_values.get(signal) ?? signal).wv;\n}\n\n/**\n * Reuse the version of an equal value in the batch's previous run, then the global value,\n * or allocate a new one. Errors always get a new version\n * @param {Derived} derived\n * @param {Batch} batch\n * @param {any} value\n * @param {boolean} error\n */\nfunction derived_version(derived, batch, value, error) {\n\tif (!error) {\n\t\tvar previous = /** @type {DerivedRecord | undefined} */ (batch.get_record(derived));\n\t\tif (previous !== undefined && !previous.e && derived.equals.call(previous, value)) {\n\t\t\treturn previous.wv;\n\t\t}\n\n\t\tif ((derived.f & ERROR_VALUE) === 0 && derived.equals(value)) return derived.wv;\n\t}\n\n\treturn increment_write_version();\n}\n\n/**\n * Make the record a batch holds of `reaction` its global state, e.g. because the batch\n * committed, which makes its results the real-world ones (for a derived, that includes its value)\n * @param {Reaction} reaction\n * @param {BatchRecord} record\n */\nexport function promote_record(reaction, record) {\n\treaction.deps = record.deps;\n\t// The global run updates its versions in place. An effect's record is dropped when it is promoted, but\n\t// other batches can still hold a derived's (see `keep_global_run`), so that one keeps its own\n\treaction.dv = (reaction.f & DERIVED) !== 0 ? record.dv.slice() : record.dv;\n\n\tif ((reaction.f & DERIVED) !== 0) {\n\t\tvar derived = /** @type {Derived} */ (reaction);\n\n\t\tderived.v = record.v;\n\t\tderived.wv = /** @type {number} */ (record.wv);\n\t\tderived.f = (record.e ? derived.f | ERROR_VALUE : derived.f & ~ERROR_VALUE) & ~ASSIGNED;\n\t\tupdate_derived_status(derived);\n\t}\n\n\t// the run's signal replaces the global run's (so that dropping the record doesn't abort it, see `Batch#release_records`)\n\tabort_signal(reaction.ac);\n\treaction.ac = record.ac ?? null;\n\trecord.ac = null;\n}\n\n/** @param {Reaction} reaction */\nfunction has_batch_record(reaction) {\n\tfor (var batch = first_batch; batch !== null; batch = batch.next) {\n\t\tif (batch.records?.has(reaction)) return true;\n\t}\n\n\treturn false;\n}\n\n/**\n * Remove the edges of an effect that only runs no batch holds anymore needed (because the batch committed and\n * its record was promoted, or because it was dropped), once no batch holds a record of it, so that its edges are\n * what its global run read again. `update_record` only prunes edges in a global run that happens while no batch\n * holds a record, which block and async effects hardly ever have: they run in batches.\n * (Not for deriveds: their edges also notify the reactions that read the value of a record that was dropped. They\n * are pruned by their next global run)\n * @param {Reaction} effect\n */\nexport function prune_edges(effect) {\n\tvar edges = effect.edges;\n\tvar deps = effect.deps;\n\n\tif (edges === deps || has_batch_record(effect)) return;\n\n\t// (the edges are a superset of `deps`, so nothing needs to be connected)\n\tfor (var dep of /** @type {Value[]} */ (edges)) {\n\t\tif (deps === null || !includes.call(deps, dep)) remove_reaction(effect, dep);\n\t}\n\n\teffect.edges = deps;\n}\n\n/**\n * Connect a reaction outside its normal dependency update, without duplicating subscriptions\n * @param {Value} signal\n * @param {Reaction} reaction\n */\nfunction add_reaction(signal, reaction) {\n\tvar reactions = (signal.reactions ??= []);\n\tif (!includes.call(reactions, reaction)) reactions.push(reaction);\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\tif ((derived.f & CONNECTED) !== 0) {\n\t\t\tderived.f ^= CONNECTED;\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 losing 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// Call abort controller, noone's listening to this derived anymore: no live run of any reaction, in any batch,\n\t\t// read it (the edges cover them all, see `Reaction#edges`). That includes the runs of it that batches hold\n\t\tif (abort_all(derived)) {\n\t\t\t// ensure it reruns right away next time instead of potentially returning a rejected promise as its value —\n\t\t\t// in the real world, and in every batch's view (which would otherwise reuse its record of the derived)\n\t\t\tset_signal_status(derived, DIRTY);\n\t\t\tderived.dv = null;\n\t\t\tfor (var b = first_batch; b !== null; b = b.next) b.records?.delete(derived);\n\t\t\tview_cache?.delete(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);\n\t}\n}\n\n/**\n * @param {Reaction} signal\n * @returns {void}\n */\nexport function remove_reactions(signal) {\n\tvar dependencies = signal.edges;\n\tif (dependencies === null) return;\n\n\tfor (var i = 0; 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\n\tactive_effect = effect;\n\n\tvar previous_renderer = custom_renderers_flag ? push_renderer(effect.r) : null;\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\n\t\t// Whether an effect is dirty is determined by the exact versions of its dependencies (see\n\t\t// `update_dependencies`) — this only marks when it last ran, which `$inspect.trace` uses\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.edges !== null) {\n\t\t\tfor (var dep of effect.edges) {\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\tactive_effect = previous_effect;\n\n\t\tif (custom_renderers_flag) pop_renderer(previous_renderer);\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/** The reaction that reads `signal` after an `await`, if any */\n\tvar late_reader = null;\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 || !current_sources.has(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\tlate_reader = active_reaction;\n\n\t\t\t\t// Late reads add an edge immediately, even if evaluating the value throws.\n\t\t\t\tvar edges = active_reaction.edges;\n\t\t\t\tif (edges === null || !includes.call(edges, signal)) {\n\t\t\t\t\tactive_reaction.edges = edges === null ? [signal] : [...edges, signal];\n\t\t\t\t}\n\n\t\t\t\tadd_reaction(signal, active_reaction);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (DEV) {\n\t\tif (\n\t\t\t!untracking &&\n\t\t\t// By checking that no batch is active we filter out false positives.\n\t\t\t// reactivity_loss_tracker is only reset after a microtask, so if a flush happens\n\t\t\t// before that, we get warnings for things we shouldn't warn on.\n\t\t\tview_batch === null &&\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) {\n\t\t// teardowns have their own view of the world; nothing read here is recorded\n\t\tvar held = teardown_view(signal);\n\n\t\tif (held !== undefined) {\n\t\t\tif (held.e) throw held.v;\n\t\t\treturn held.v;\n\t\t}\n\t}\n\n\t/**\n\t * The value (and version) as the active view of the world sees it, if it differs from the real\n\t * world — for a derived, this is the derived itself if its global state applies (see `get_view`)\n\t * @type {{ v: any, wv: number, e?: boolean } | undefined}\n\t */\n\tvar view;\n\n\tif (is_derived) {\n\t\tvar derived = /** @type {Derived} */ (signal);\n\n\t\t// connect disconnected deriveds when reading them inside a connected reaction\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(active_reaction.f & CONNECTED) !== 0;\n\n\t\tvar is_new = (derived.f & REACTION_RAN) === 0;\n\n\t\tif (should_connect) {\n\t\t\t// set the flag before the derived is (re)evaluated, so that\n\t\t\t// it is added as a reaction to its dependencies\n\t\t\tderived.f |= CONNECTED;\n\t\t}\n\n\t\tif (batch_values !== null) {\n\t\t\tview = get_view(derived);\n\t\t} else {\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} else if (batch_values !== null) {\n\t\tview = batch_values.get(signal);\n\t}\n\n\tif (late_reader !== null) {\n\t\trecord_late_read(late_reader, signal, view === undefined ? signal.wv : view.wv);\n\t}\n\n\tif (view !== undefined && view !== signal) {\n\t\tif (view.e) throw view.v;\n\t\treturn view.v;\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 * Record that `reaction` read `signal` (with the given version) after an `await`, i.e. after\n * its run — as part of the record of that run\n * @param {Reaction} reaction\n * @param {Value} signal\n * @param {number} version\n */\nfunction record_late_read(reaction, signal, version) {\n\tvar run = run_of(reaction);\n\tvar deps = run.deps;\n\n\tif (run.dv !== null && (deps === null || !includes.call(deps, signal))) {\n\t\trun.deps = deps === null ? [signal] : [...deps, signal];\n\t\trun.dv.push(version);\n\t}\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.edges === null) return;\n\n\tfor (const dep of derived.edges) {\n\t\tadd_reaction(dep, 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/**\n * The value of `signal` in the view of the world of the running teardown, if it differs from the active one:\n * teardowns revert the writes that caused them, apart from their own (see `TeardownContext`). Deriveds always\n * get one, since their runs in a teardown only belong to it, and it is cached until the view changes:\n * - a value written to the derived, while none of its dependencies is written after it (like in `get_view`)\n * - its global run, if its dependencies still have the versions that run read\n * - otherwise a new run (see `update_dependencies`), which keeps the version of the value it replaces if equal\n * @param {Value} signal\n * @returns {BatchValue | undefined}\n */\nfunction teardown_view(signal) {\n\tvar written =\n\t\tsignal.wv > teardown_version ? undefined : teardown_context?.reverted_values.get(signal);\n\n\tif ((signal.f & DERIVED) === 0) return written;\n\n\tvar derived = /** @type {Derived} */ (signal);\n\tvar cache = (teardown_context ?? push_teardown_context()).derived_cache;\n\tvar record = cache.get(derived);\n\n\tif (record !== undefined) return record;\n\n\t// A value written to the derived — reverted, or the active view's — holds if it was assigned, like in `get_view`:\n\t// the value from before an assignment may have been computed, with values that the teardown reverts\n\tvar held = written ?? batch_values?.get(derived);\n\tvar assigned = held === undefined ? (derived.f & ASSIGNED) !== 0 : held.assigned;\n\t// (the versions its global run read, if that can apply)\n\tvar dv = held === undefined && !assigned ? derived.dv : null;\n\tvar deps = derived.deps ?? [];\n\tvar holds = assigned || dv !== null;\n\tvar length = dv?.length ?? deps.length;\n\n\theld ??= {\n\t\tv: derived.v,\n\t\twv: derived.wv,\n\t\te: (derived.f & ERROR_VALUE) !== 0,\n\t\tassigned: (derived.f & ASSIGNED) !== 0\n\t};\n\n\tfor (var i = 0; holds && i < length; i++) {\n\t\tvar version = teardown_version_of(deps[i]);\n\t\tholds = dv === null ? version <= held.wv : version === dv[i];\n\t}\n\n\tif (holds) {\n\t\trecord = held;\n\t} else {\n\t\texecute_derived(derived);\n\t\trecord = teardown_run;\n\n\t\tif (held.wv < record.wv && !held.e && !record.e && derived.equals.call(held, record.v)) {\n\t\t\trecord.wv = held.wv;\n\t\t}\n\t}\n\n\tcache.set(derived, record);\n\treturn record;\n}\n\n/**\n * The version of `signal` in the view of the world of the running teardown\n * @param {Value} signal\n */\nfunction teardown_version_of(signal) {\n\treturn (teardown_view(signal) ?? batch_values?.get(signal) ?? signal).wv;\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","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\nexport const 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 { teardown } from '../../reactivity/effects.js';\nimport { array_from, define_property } from '../../../shared/utils.js';\nimport { is_passive_event } from '../../../../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';\nimport {\n\tremove_attribute,\n\tdispatch_event,\n\tadd_event_listener,\n\tremove_event_listener\n} from '../operations.js';\nimport { current_renderer } from '../../custom-renderer/state.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// The native listener boundary at which a delegated descendant stopped propagation.\nconst propagation_stopped_at = Symbol('propagation stopped at');\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\t// custom renderers safe since it immediately returns if not hydrating\n\tif (!hydrating) return;\n\n\tremove_attribute(dom, 'onload');\n\tremove_attribute(dom, '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\tdispatch_event(dom, 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// Capture whether a custom renderer is active at creation time (during mount),\n\t// since `renderer` will be null when the event actually fires\n\tvar is_custom_renderer = current_renderer != null;\n\n\t/**\n\t * @this {EventTarget}\n\t * @param  {...any} args\n\t */\n\tfunction target_handler(...args) {\n\t\tif (is_custom_renderer) {\n\t\t\t// Custom renderers don't use DOM event propagation/delegation,\n\t\t\t// so just call the handler directly\n\t\t\treturn without_reactive_context(() => {\n\t\t\t\treturn handler?.apply(this, /** @type {any} */ (args));\n\t\t\t});\n\t\t}\n\t\tvar event = /** @type {Event} */ (args[0]);\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\t// Native stopPropagation() does not stop other listeners on the same element.\n\t\t// Only skip this callback if a delegated descendant stopped before reaching it.\n\t\t// @ts-expect-error\n\t\tif (options.capture || event[propagation_stopped_at] !== dom) {\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\t!is_custom_renderer &&\n\t\t(event_name.startsWith('pointer') || event_name.startsWith('touch') || event_name === 'wheel')\n\t) {\n\t\ttarget_handler.__removed = false;\n\t\tqueue_micro_task(() => {\n\t\t\tif (!target_handler.__removed) {\n\t\t\t\tadd_event_listener(dom, event_name, target_handler, options);\n\t\t\t}\n\t\t});\n\t} else {\n\t\tadd_event_listener(dom, 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\ttarget_handler.__removed = true;\n\t\tremove_event_listener(element, 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\t// if there's a renderer we will never add to body, window or document.\n\t\tcurrent_renderer == null &&\n\t\t(dom === document.body ||\n\t\t\t// @ts-ignore\n\t\t\tdom === window ||\n\t\t\t// @ts-ignore\n\t\t\tdom === document ||\n\t\t\t// Firefox has quirky behavior, it can happen that we still get \"canplay\" events when the element is already removed\n\t\t\tdom instanceof HTMLMediaElement)\n\t) {\n\t\tteardown(() => {\n\t\t\ttarget_handler.__removed = true;\n\t\t\tremove_event_listener(dom, 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/**\n * How many delegation roots are listening to each event type on each node\n * @type {Map<EventTarget, Map<string, number>>}\n */\nconst delegated_listeners = new Map();\n\n/**\n * Makes `target` a root for delegated events: listens on `target` and on `document`\n * for every delegated event type, including types registered later, and dispatches\n * them to the handlers set with `delegated(...)`. Used for `mount`/`hydrate` targets,\n * and for DOM containers that DOM content is rendered into from a custom renderer.\n *\n * This always uses DOM methods directly (rather than renderer-aware operations),\n * since it may be torn down while a custom renderer is active.\n * @param {EventTarget} target\n * @returns {() => void} stops listening\n */\nexport function listen_to_delegated_events(target) {\n\t/** @type {Set<string>} */\n\tvar registered_events = new Set();\n\n\t/** @param {Array<string>} events */\n\tvar event_handle = (events) => {\n\t\tfor (var i = 0; i < events.length; i++) {\n\t\t\tvar event_name = events[i];\n\n\t\t\tif (registered_events.has(event_name)) continue;\n\t\t\tregistered_events.add(event_name);\n\n\t\t\tvar passive = is_passive_event(event_name);\n\n\t\t\t// Add the event listener to both the target and the document.\n\t\t\t// The target listener ensures we catch events from within in case\n\t\t\t// the outer content stops propagation of the event.\n\t\t\t//\n\t\t\t// The document listener ensures we catch events that originate from elements that were\n\t\t\t// manually moved outside of the target (e.g. via manual portals).\n\t\t\tfor (const node of [target, document]) {\n\t\t\t\tvar counts = delegated_listeners.get(node);\n\n\t\t\t\tif (counts === undefined) {\n\t\t\t\t\tcounts = new Map();\n\t\t\t\t\tdelegated_listeners.set(node, counts);\n\t\t\t\t}\n\n\t\t\t\tvar count = counts.get(event_name);\n\n\t\t\t\tif (count === undefined) {\n\t\t\t\t\tnode.addEventListener(event_name, handle_event_propagation, { passive });\n\t\t\t\t\tcounts.set(event_name, 1);\n\t\t\t\t} else {\n\t\t\t\t\tcounts.set(event_name, count + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\tevent_handle(array_from(all_registered_events));\n\troot_event_handles.add(event_handle);\n\n\treturn () => {\n\t\tfor (var event_name of registered_events) {\n\t\t\tfor (const node of [target, document]) {\n\t\t\t\tvar counts = /** @type {Map<string, number>} */ (delegated_listeners.get(node));\n\t\t\t\tvar count = /** @type {number} */ (counts.get(event_name));\n\n\t\t\t\tif (--count == 0) {\n\t\t\t\t\tnode.removeEventListener(event_name, handle_event_propagation);\n\t\t\t\t\tcounts.delete(event_name);\n\n\t\t\t\t\tif (counts.size === 0) {\n\t\t\t\t\t\tdelegated_listeners.delete(node);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcounts.set(event_name, count);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\troot_event_handles.delete(event_handle);\n\t};\n}\n\n// used to store the reference to the currently propagated event\n// to prevent garbage collection between microtasks in Firefox (<= 141)\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// whether a task is already queued to clear `last_propagated_event`\nlet last_propagated_event_clear_scheduled = false;\n\n/**\n * @this {EventTarget}\n * @param {Event} event\n * @returns {void}\n */\nexport function handle_event_propagation(event) {\n\t// this function is custom renderers safe since it's invoked in `mount`\n\tvar handler_element = this;\n\tvar was_stopped = event.cancelBubble;\n\n\t// Another listener at this boundary may already have dispatched the delegated\n\t// handler that stopped propagation. Do not dispatch it again.\n\t// @ts-expect-error\n\tif (was_stopped && event[propagation_stopped_at] === handler_element) return;\n\n\tif (!was_stopped) {\n\t\t// The same event object may be dispatched again.\n\t\t// @ts-expect-error\n\t\tdelete event[propagation_stopped_at];\n\t}\n\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// The reference is only needed while the event can still reach another\n\t// delegated root, i.e. during the current (synchronous) dispatch and its\n\t// microtask checkpoints. Clearing it in a later task preserves the\n\t// Firefox workaround while making sure the slot doesn't retain the last\n\t// event forever — through `event.target` it would otherwise keep the\n\t// entire detached subtree of whatever the user last clicked in alive\n\t// until the next delegated event happens to arrive.\n\tif (!last_propagated_event_clear_scheduled) {\n\t\tlast_propagated_event_clear_scheduled = true;\n\t\tsetTimeout(() => {\n\t\t\tlast_propagated_event_clear_scheduled = false;\n\t\t\tlast_propagated_event = null;\n\t\t});\n\t}\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 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 events 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\tif (current_target === handler_element) break;\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) {\n\t\t\t\tif (!was_stopped) {\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tevent[propagation_stopped_at] = handler_element;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpath_idx++;\n\t\t\tcurrent_target = path_idx < path.length ? /** @type {Element} */ (path[path_idx]) : null;\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, set_inner_html } 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\tset_inner_html(elem, 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 {\n\tCOMMENT_NODE,\n\tDOCUMENT_FRAGMENT_NODE,\n\tIS_XHTML,\n\tREACTION_RAN,\n\tTEXT_NODE\n} from '#client/constants';\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 { current_renderer } from '../custom-renderer/state.js';\nimport { active_effect } from '../runtime.js';\nimport { hydrate_next, hydrate_node, hydrating, set_hydrate_node } from './hydration.js';\nimport {\n\tappend_child,\n\tclone_node,\n\tcreate_comment,\n\tcreate_element,\n\tcreate_fragment,\n\tcreate_text,\n\tget_first_child,\n\tget_last_child,\n\tget_node_value,\n\timport_node,\n\tinsert_before,\n\tis_firefox,\n\tmerge_text_nodes,\n\tnode_name,\n\tnode_type,\n\treplace_with,\n\tset_attribute,\n\tset_text_content\n} from './operations.js';\nimport { create_fragment_from_html } from './reconciler.js';\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 ? import_node(node, true) : clone_node(node, 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} */ (get_last_child(clone));\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 = create_fragment();\n\t\t\t\twhile (get_first_child(root)) {\n\t\t\t\t\tappend_child(node, /** @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} */ (clone_node(node, 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} */ (get_last_child(clone));\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\tappend_child(fragment, 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\tappend_child(fragment, 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\tnode_name(element) === TEMPLATE_TAG\n\t\t\t\t\t? // this is safe for custom renderers because the name will never be `template` due to how `node_name` works\n\t\t\t\t\t\t/** @type {HTMLTemplateElement} */ (element).content\n\t\t\t\t\t: element;\n\n\t\t\tappend_child(\n\t\t\t\ttarget,\n\t\t\t\tfragment_from_tree(children, node_name(element) === 'foreignObject' ? undefined : namespace)\n\t\t\t);\n\t\t}\n\n\t\tappend_child(fragment, 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\tconst ns =\n\t\t(flags & TEMPLATE_USE_SVG) !== 0\n\t\t\t? NAMESPACE_SVG\n\t\t\t: (flags & TEMPLATE_USE_MATHML) !== 0\n\t\t\t\t? NAMESPACE_MATHML\n\t\t\t\t: undefined;\n\n\t/** The DOM template that is cloned for each instance @type {Node | undefined} */\n\tvar node;\n\n\tfunction create() {\n\t\tvar fragment = fragment_from_tree(structure, ns);\n\t\treturn is_fragment ? fragment : /** @type {TemplateNode} */ (get_first_child(fragment));\n\t}\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\t/** @type {TemplateNode} */\n\t\tvar clone;\n\n\t\tif (current_renderer !== null) {\n\t\t\t// for custom renderers we create new nodes every time rather than cloning a template.\n\t\t\t// It's a bit less efficient, but saves renderer authors from having to implement\n\t\t\t// `cloneNode`/`importNode`, which can be a pain. The nodes are not cached, since\n\t\t\t// that would keep the most recent instance alive after it is destroyed\n\t\t\tclone = /** @type {TemplateNode} */ (create());\n\t\t} else {\n\t\t\tnode ??= create();\n\t\t\tclone = /** @type {TemplateNode} */ (\n\t\t\t\tuse_import_node || is_firefox ? import_node(node, true) : clone_node(node, true)\n\t\t\t);\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} */ (get_last_child(clone));\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// this should be custom renderer safe since we never emit `with_script` in that case\n\t// scripts were SSR'd, in which case they will run\n\tif (hydrating) return node;\n\n\tconst is_fragment = node_type(node) === DOCUMENT_FRAGMENT_NODE;\n\tconst scripts =\n\t\tnode_name(node) === 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\n\t\tfor (var attribute of script.attributes) {\n\t\t\tset_attribute(clone, attribute.name, attribute.value);\n\t\t}\n\n\t\tset_text_content(clone, 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 ? get_first_child(node) === script : node === script) {\n\t\t\teffect.nodes.start = clone;\n\t\t}\n\t\tif (is_fragment ? get_last_child(node) === script : node === script) {\n\t\t\teffect.nodes.end = clone;\n\t\t}\n\n\t\treplace_with(script, 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_type(node) !== TEXT_NODE) {\n\t\t// if an {expression} is empty during SSR, we need to insert an empty text node\n\t\tinsert_before(node, (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 = create_fragment();\n\tvar start = create_comment('');\n\tvar anchor = create_text();\n\tappend_child(frag, start);\n\tappend_child(frag, 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\tinsert_before(anchor, /** @type {Node} */ (dom));\n}\n\n/**\n * Create (or hydrate) an unique UID for the component instance.\n */\nexport function props_id() {\n\tlet node_value;\n\tif (\n\t\thydrating &&\n\t\thydrate_node &&\n\t\tnode_type(hydrate_node) === COMMENT_NODE &&\n\t\t(node_value = get_node_value(hydrate_node))?.startsWith(`$`)\n\t) {\n\t\tconst id = node_value.substring(1);\n\t\thydrate_next();\n\t\treturn id;\n\t}\n\t// @ts-expect-error This way we ensure the id is unique even across Svelte runtimes\n\t(globalThis.__svelte ??= {}).uid ??= 1;\n\n\t// @ts-expect-error\n\treturn `c${globalThis.__svelte.uid++}`;\n}\n","import { get, 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\tDESTROYED,\n\tDESTROYING,\n\tDIRTY,\n\tEFFECT_PRESERVED,\n\tEFFECT_TRANSPARENT,\n\tMAYBE_DIRTY\n} from '#client/constants';\nimport {\n\tHYDRATION_ERROR,\n\tHYDRATION_START_ELSE,\n\tHYDRATION_START_FAILED\n} from '../../../../constants.js';\nimport { component_context, set_component_context } from '../../context.js';\nimport { 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\tread_hydration_instruction,\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 } 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, create_fragment, append_child, insert_before } from '../operations.js';\nimport { set_signal_status } from '../../reactivity/status.js';\nimport { push_renderer, pop_renderer } from '../../custom-renderer/state.js';\nimport { custom_renderers_flag } from '../../../flags/index.js';\n\n/**\n * @typedef {{\n * \t onerror?: ((error: unknown, reset: () => void) => void) | null;\n *   failed?: ((anchor: Node, error: () => unknown, reset: () => () => void) => void) | null;\n *   pending?: ((anchor: Node) => void) | null;\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_update_queued = false;\n\n\t/**\n\t * User effects created inside this boundary. They will run when the boundary is revealed\n\t * @type {Effect[]}\n\t */\n\t#effects = [];\n\n\t/**\n\t * Async effects that are currently in flight, grouped by the batch that started them.\n\t * A speculative fork's work must not hold up the real world's boundary.\n\t * @type {Map<Batch, Map<Effect, number>>}\n\t */\n\t#pending = new Map();\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_data = read_hydration_instruction(\n\t\t\t\t\t/** @type {TemplateNode} */ (this.#hydrate_open)\n\t\t\t\t);\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\tconst { reset, invoke_onerror } = this.#create_reset(error);\n\n\t\t// `onerror` may mutate state, which is disallowed while hydrating\n\t\tqueue_micro_task(invoke_onerror);\n\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() => reset\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Creates the `reset` function for a failed boundary, along with a function\n\t * that invokes `onerror` with it (if provided)\n\t * @param {unknown} error\n\t * @returns {{ reset: () => void, invoke_onerror: () => void }}\n\t */\n\t#create_reset(error) {\n\t\tvar did_reset = false;\n\t\tvar calling_on_error = false;\n\n\t\tconst reset = () => {\n\t\t\tif (this.#is_destroyed()) return;\n\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\tconst invoke_onerror = () => {\n\t\t\tif (this.#is_destroyed()) return;\n\n\t\t\ttry {\n\t\t\t\tcalling_on_error = true;\n\t\t\t\tthis.#props.onerror?.(error, reset);\n\t\t\t\tcalling_on_error = false;\n\t\t\t} catch (err) {\n\t\t\t\tinvoke_error_boundary(err, this.#effect && this.#effect.parent);\n\t\t\t}\n\t\t};\n\n\t\treturn { reset, invoke_onerror };\n\t}\n\n\t#is_destroyed() {\n\t\treturn (this.#effect.f & (DESTROYED | DESTROYING)) !== 0;\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\tif (this.#is_destroyed()) return;\n\n\t\t\tvar previous_renderer = custom_renderers_flag ? push_renderer(this.#effect.r) : null;\n\n\t\t\ttry {\n\t\t\t\tvar fragment = (this.#offscreen_fragment = create_fragment());\n\t\t\t\tvar anchor = create_text();\n\n\t\t\t\tappend_child(fragment, anchor);\n\n\t\t\t\tthis.#main_effect = this.#run(() => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn branch(() => this.#children(anchor));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tthis.error(error);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tinvoke_error_boundary(error, this.#effect.parent);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (this.#main_effect !== null && this.#pending.size === 0) {\n\t\t\t\t\tthis.is_pending = false;\n\t\t\t\t\tinsert_before(this.#anchor, fragment);\n\t\t\t\t\tthis.#offscreen_fragment = null;\n\n\t\t\t\t\tpause_effect(/** @type {Effect} */ (this.#pending_effect), () => {\n\t\t\t\t\t\tthis.#pending_effect = null;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tif (custom_renderers_flag) pop_renderer(previous_renderer);\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.#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.size === 0) {\n\t\t\t\tthis.is_pending = false;\n\t\t\t} else {\n\t\t\t\tconst pending = this.#props.pending;\n\n\t\t\t\tif (pending) {\n\t\t\t\t\tvar fragment = (this.#offscreen_fragment = create_fragment());\n\t\t\t\t\tmove_effect(this.#main_effect, fragment);\n\n\t\t\t\t\tthis.#pending_effect = branch(() => pending(this.#anchor));\n\t\t\t\t}\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 * Defer an effect inside a pending boundary until the boundary resolves\n\t * @param {Effect} effect\n\t */\n\tdefer_effect(effect) {\n\t\tthis.#effects.push(effect);\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\tvar previous_renderer = custom_renderers_flag ? push_renderer(this.#effect.r) : null;\n\n\t\ttry {\n\t\t\tBatch.ensure();\n\t\t\treturn fn();\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\tif (custom_renderers_flag) pop_renderer(previous_renderer);\n\t\t}\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\tis_ready(batch) {\n\t\tif (batch.is_fork && this.#pending.size > 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (const [owner, pending] of this.#pending) {\n\t\t\tif (owner.is_fork) continue;\n\n\t\t\tfor (const effect of pending.keys()) {\n\t\t\t\tif (batch.is_blocked_by(effect, this.#main_effect)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * @param {Effect[]} effects\n\t */\n\treveal(effects) {\n\t\tthis.is_pending = false;\n\n\t\t// Add any deferred effects to the batch's effect queue\n\t\tfor (const effect of this.#effects) {\n\t\t\tset_signal_status(effect, DIRTY);\n\t\t\teffects.push(effect);\n\t\t}\n\n\t\tthis.#effects.length = 0;\n\n\t\tif (this.#pending_effect) {\n\t\t\tpause_effect(this.#pending_effect, () => {\n\t\t\t\tthis.#pending_effect = null;\n\t\t\t});\n\t\t}\n\n\t\tif (this.#offscreen_fragment) {\n\t\t\tvar previous_renderer = custom_renderers_flag ? push_renderer(this.#effect.r) : null;\n\n\t\t\ttry {\n\t\t\t\tinsert_before(this.#anchor, this.#offscreen_fragment);\n\t\t\t\tthis.#offscreen_fragment = null;\n\t\t\t} finally {\n\t\t\t\tif (custom_renderers_flag) pop_renderer(previous_renderer);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t * @param {Batch} batch\n\t */\n\tincrement(effect, batch) {\n\t\tvar pending = this.#pending.get(batch);\n\n\t\tif (pending === undefined) {\n\t\t\tthis.#pending.set(batch, (pending = new Map()));\n\t\t}\n\n\t\tvar count = pending.get(effect) ?? 0;\n\t\tpending.set(effect, count + 1);\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t * @param {Batch} batch\n\t */\n\tdecrement(effect, batch) {\n\t\tvar pending = /** @type {Map<Effect, number>} */ (this.#pending.get(batch));\n\t\tvar count = /** @type {number} */ (pending.get(effect));\n\n\t\tif (count === 1) {\n\t\t\tpending.delete(effect);\n\n\t\t\tif (pending.size === 0) {\n\t\t\t\tthis.#pending.delete(batch);\n\t\t\t}\n\n\t\t\t// The remaining work may belong to speculative forks. Check again in a normal batch,\n\t\t\t// after the result's batch has flushed, so that we reveal committed content and run\n\t\t\t// deferred effects in the same view.\n\t\t\tqueue_micro_task(() => {\n\t\t\t\tif (this.is_pending && !this.#is_destroyed()) {\n\t\t\t\t\tBatch.ensure().schedule(this.#effect, MAYBE_DIRTY);\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tpending.set(effect, count - 1);\n\t\t}\n\t}\n\n\t/**\n\t * Update the source that powers `$effect.pending()` inside this boundary.\n\t * Do not call from inside the class\n\t * @param {1 | -1} d\n\t */\n\tupdate_effect_pending(d) {\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\tif (error === HYDRATION_ERROR) {\n\t\t\tthrow error;\n\t\t}\n\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.oncommit(() => {\n\t\t\t\tif (!this.#is_destroyed()) this.#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\tlet failed = this.#props.failed;\n\n\t\t/** @param {unknown} transformed_error */\n\t\tconst handle_error_result = (transformed_error) => {\n\t\t\tif (this.#is_destroyed()) return;\n\n\t\t\tconst { reset, invoke_onerror } = this.#create_reset(transformed_error);\n\n\t\t\tinvoke_onerror();\n\n\t\t\tif (failed && !this.#is_destroyed()) {\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\tif (this.#is_destroyed()) return;\n\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 { ComponentContext, Effect, EffectNodes, TemplateNode } from '#client' */\n/** @import { Component, ComponentType, SvelteComponent, MountOptions } from '../../index.js' */\n/** @import { Renderer } from './custom-renderer/types.js' */\nimport { DEV } from 'esm-env';\nimport {\n\tclear_text_content,\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tappend_child,\n\tget_parent_node,\n\tremove_child,\n\tset_node_value,\n\tget_node_value,\n\tnode_type\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, mark_as_component } from './context.js';\nimport { component_root } from './reactivity/effects.js';\nimport { hydrate_node, hydrating, set_hydrate_node, set_hydrating } from './dom/hydration.js';\nimport { listen_to_delegated_events } 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 { COMMENT_NODE, TEXT_CACHE } from './constants.js';\nimport { boundary } from './dom/blocks/boundary.js';\nimport { push_renderer, pop_renderer } from './custom-renderer/state.js';\nimport { async_mode_flag, custom_renderers_flag } from '../flags/index.js';\nimport { current_batch } from './reactivity/batch.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// prettier-ignore\n\tif (str !== (/** @type {any} */ (text)[TEXT_CACHE] ??= get_node_value(text))) {\n\t\t/** @type {any} */ (text)[TEXT_CACHE] = str;\n\t\tset_node_value(text, `${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 * @template [Renderer=undefined]\n * @param {ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>} component\n * @param {MountOptions<Props, Renderer>} 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 * @template [Renderer=undefined]\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 */\n// `Renderer` is unused, but the type parameters need to match `mount`'s,\n// otherwise a `hydrate | mount` union isn't callable\nexport function hydrate(component, options) {\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(node_type(anchor) !== COMMENT_NODE || get_node_value(anchor) !== 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\t// The server rendered the hydrated DOM with the state that hydration ran with (set before `hydrate()`,\n\t\t// or while hydrating, e.g. by lazily initialized state), so that state is the real world from now on.\n\t\t// This is what happens when mounting, too, where the batch commits right away because the root boundary\n\t\t// is pending. Otherwise, while the hydration batch waits for async work, other batches' views would undo\n\t\t// those writes — e.g. that of a pending boundary's content, which renders in a batch of its own\n\t\tif (async_mode_flag && current_batch !== null) {\n\t\t\tcurrent_batch.commit_writes();\n\t\t}\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\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/**\n * @template {Record<string, any>} Exports\n * @param {ComponentType<SvelteComponent<any>> | Component<any>} Component\n * @param {MountOptions<any, any> & { renderer?: Renderer }} options\n * @returns {Exports}\n */\nfunction _mount(Component, options) {\n\tif (custom_renderers_flag && options.renderer) {\n\t\tvar previous_renderer = push_renderer(options.renderer);\n\n\t\ttry {\n\t\t\treturn _mount_inner(Component, options);\n\t\t} finally {\n\t\t\tpop_renderer(previous_renderer);\n\t\t}\n\t}\n\n\treturn _mount_inner(Component, options);\n}\n\n/**\n * @template {Record<string, any>} Exports\n * @param {ComponentType<SvelteComponent<any>> | Component<any>} Component\n * @param {MountOptions<any, any> & { renderer?: Renderer }} options\n * @returns {Exports}\n */\nfunction _mount_inner(\n\tComponent,\n\t{ target, anchor, props = {}, events, context, intro = true, transformError, renderer }\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 =\n\t\t\tanchor ?? /** @type {Text} */ (append_child(/** @type {Node} */ (target), 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) || mark_as_component();\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\tnode_type(hydrate_node) !== COMMENT_NODE ||\n\t\t\t\t\t\tget_node_value(hydrate_node) !== 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// When mounting with a custom renderer the target isn't a DOM node; any DOM content inside it is rendered\n\t\t// into DOM containers that become delegation roots themselves (see `cross`)\n\t\tvar stop_listening = renderer\n\t\t\t? null\n\t\t\t: listen_to_delegated_events(/** @type {EventTarget} */ (target));\n\n\t\treturn () => {\n\t\t\tstop_listening?.();\n\n\t\t\tif (anchor_node !== anchor) {\n\t\t\t\tvar parent = get_parent_node(/** @type {Node} */ (anchor_node));\n\t\t\t\tif (parent) remove_child(parent, /** @type {ChildNode} */ (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\tw.lifecycle_double_unmount();\n\t}\n\n\treturn Promise.resolve();\n}\n","/** @import { Effect, TemplateNode } from '#client' */\n/** @import { Renderer } from '../../custom-renderer/types.js' */\n/** @import { Batch } from '../../reactivity/batch.js' */\nimport { 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 { EFFECT_OFFSCREEN } from '#client/constants';\nimport { hydrate_node, hydrating } from '../hydration.js';\nimport {\n\tcreate_text,\n\tshould_defer_append,\n\tcreate_fragment,\n\tappend_child,\n\tinsert_before,\n\tremove_node,\n\tget_last_child\n} from '../operations.js';\nimport { DEV } from 'esm-env';\nimport { push_renderer, current_renderer, pop_renderer } from '../../custom-renderer/state.js';\nimport { custom_renderers_flag } from '../../../flags/index.js';\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 * The renderer that was active when this BranchManager was created.\n\t * Needed so that #commit can push the correct renderer when doing DOM operations\n\t * outside of an effect context (e.g. as a batch commit callback).\n\t * @type {Renderer | null}\n\t */\n\t#renderer = null;\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\tthis.#renderer = current_renderer;\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 previous_renderer = custom_renderers_flag ? push_renderer(this.#renderer) : null;\n\n\t\ttry {\n\t\t\tvar key = /** @type {Key} */ (this.#batches.get(batch));\n\n\t\t\tvar onscreen = this.#onscreen.get(key);\n\n\t\t\tif (onscreen) {\n\t\t\t\t// effect is already in the DOM — abort any current outro\n\t\t\t\tresume_effect(onscreen);\n\t\t\t\tthis.#outroing.delete(key);\n\t\t\t} else {\n\t\t\t\t// effect is currently offscreen. put it in the DOM\n\t\t\t\tvar offscreen = this.#offscreen.get(key);\n\n\t\t\t\tif (offscreen) {\n\t\t\t\t\t// effect could have been outro'ed before through a prior batch — resume if necessary\n\t\t\t\t\tresume_effect(offscreen.effect);\n\t\t\t\t\tthis.#onscreen.set(key, offscreen.effect);\n\t\t\t\t\tthis.#offscreen.delete(key);\n\n\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\t// Tell hmr.js about the anchor it should use for updates,\n\t\t\t\t\t\t// since the initial one will be removed\n\t\t\t\t\t\t/** @type {any} */ (get_last_child(offscreen.fragment))[HMR_ANCHOR] = this.anchor;\n\t\t\t\t\t}\n\n\t\t\t\t\t// remove the anchor...\n\t\t\t\t\tremove_node(/** @type {ChildNode} */ (get_last_child(offscreen.fragment)));\n\n\t\t\t\t\t// ...and append the fragment\n\t\t\t\t\tinsert_before(this.anchor, offscreen.fragment);\n\t\t\t\t\tonscreen = offscreen.effect;\n\t\t\t\t\tonscreen.f &= ~EFFECT_OFFSCREEN;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// other batches can still commit (in any order), so their selections remain\n\t\t\tthis.#discard(batch);\n\n\t\t\t// outro/destroy all onscreen effects...\n\t\t\tfor (const [k, effect] of this.#onscreen) {\n\t\t\t\t// ...except the one that was just committed\n\t\t\t\t//    or those that are already outroing (else the transition is aborted and the effect destroyed right away)\n\t\t\t\tif (k === key || this.#outroing.has(k)) continue;\n\n\t\t\t\tconst on_destroy = () => {\n\t\t\t\t\tconst keys = Array.from(this.#batches.values());\n\n\t\t\t\t\tif (keys.includes(k)) {\n\t\t\t\t\t\t// keep the effect offscreen, as another batch will need it\n\t\t\t\t\t\tvar fragment = create_fragment();\n\t\t\t\t\t\tmove_effect(effect, fragment);\n\n\t\t\t\t\t\tappend_child(fragment, create_text()); // TODO can we avoid this?\n\n\t\t\t\t\t\tthis.#offscreen.set(k, { effect, fragment });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdestroy_effect(effect);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.#outroing.delete(k);\n\t\t\t\t\tthis.#onscreen.delete(k);\n\t\t\t\t};\n\n\t\t\t\tif (this.#transition || !onscreen) {\n\t\t\t\t\tthis.#outroing.add(k);\n\t\t\t\t\tpause_effect(effect, on_destroy, false);\n\t\t\t\t} else {\n\t\t\t\t\ton_destroy();\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tif (custom_renderers_flag) pop_renderer(previous_renderer);\n\t\t}\n\t};\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#discard = (batch) => {\n\t\tfor (const b of this.#batches.keys()) {\n\t\t\t// (batches that were merged into another one don't select anything anymore)\n\t\t\tif (b === batch || !b.linked) this.#batches.delete(b);\n\t\t}\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 = create_fragment();\n\t\t\t\tvar target = create_text();\n\n\t\t\t\tappend_child(fragment, target);\n\n\t\t\t\tvar effect = branch(() => fn(target));\n\n\t\t\t\t// until it is committed, the branch only exists for the batches that select it\n\t\t\t\teffect.f |= EFFECT_OFFSCREEN;\n\t\t\t\tbatch.unskip_new_effect(effect);\n\n\t\t\t\tthis.#offscreen.set(key, { effect, fragment });\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 { Renderer } from '../../custom-renderer/types.js' */\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\tcomponent_context,\n\tdev_current_component_function,\n\tdev_stack,\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, insert_before, node_type } from '../operations.js';\nimport { prevent_snippet_stringification } from '../../../shared/validate.js';\nimport { BranchManager } from './branches.js';\nimport { current_renderer } from '../../custom-renderer/state.js';\nimport { cross, is_crossing } from '../../custom-renderer/cross.js';\nimport { has_own_property } from '../../../shared/utils.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 * Wraps a snippet function so that it remembers which renderer it was compiled for\n * (`null` for DOM). If it is rendered by a different renderer, the snippet content\n * is rendered across a renderer boundary (see `cross`).\n * @template {(...args: any[]) => any} T\n * @param {Renderer | null} renderer\n * @param {T} fn\n * @returns {T}\n */\nexport function renderer_snippet(renderer, fn) {\n\tvar wrapped = /** @type {T} */ (\n\t\t(/** @type {TemplateNode} */ anchor, /** @type {any[]} */ ...args) => {\n\t\t\tif (is_crossing(renderer)) {\n\t\t\t\treturn cross(renderer, anchor, (anchor) => fn(anchor, ...args));\n\t\t\t}\n\n\t\t\treturn fn(anchor, ...args);\n\t\t}\n\t);\n\n\t/** @type {any} */ (wrapped).__renderer = renderer;\n\n\treturn wrapped;\n}\n\n/**\n * Validates that a snippet can be rendered by a custom renderer. Snippets compiled with\n * custom renderer support know which renderer they belong to and can cross renderer\n * boundaries; anything else (e.g. snippets from components compiled without the\n * `experimental.customRenderer` option) can only be rendered by the DOM.\n * @template {((...args: any[]) => void) | null | undefined} T\n * @param {T} fn\n * @returns {T}\n */\nexport function validate_snippet_renderer(fn) {\n\tif (fn != null && !has_own_property.call(fn, '__renderer')) {\n\t\te.snippet_renderer_mismatch();\n\t}\n\n\treturn fn;\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\tif (current_renderer != null) {\n\t\t\te.invalid_snippet_in_custom_renderer();\n\t\t}\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 || node_type(element) !== ELEMENT_NODE)) {\n\t\t\t\tw.invalid_raw_snippet_render();\n\t\t\t}\n\n\t\t\tinsert_before(anchor, element);\n\t\t}\n\n\t\tif (DEV && dev_stack !== null) {\n\t\t\t// Raw snippets have no template locations, so use the render callsite.\n\t\t\t// This also keeps the surrounding template from claiming their root.\n\t\t\t// @ts-expect-error\n\t\t\telement.__svelte_meta = {\n\t\t\t\tparent: dev_stack,\n\t\t\t\tloc: { file: dev_stack.file, line: dev_stack.line, column: dev_stack.column },\n\t\t\t\tcomponent: component_context\n\t\t\t};\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, get_abort_signal, 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 no one 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, before anything is awaited.\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 get_abort_signal(active_reaction);\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 { remove_node } from '../dom/operations.js';\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\tremove_node(style);\n\t}\n\n\tall_styles.delete(hash);\n}\n","/** @import { Effect, 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 { get_node_value, should_defer_append } from '../operations.js';\nimport { HYDRATION_START_ELSE, UNINITIALIZED } from '../../../../constants.js';\nimport { ASYNC, DESTROYED, EFFECT_PRESERVED } from '#client/constants';\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, merge_target, unset_context } from '../../reactivity/async.js';\nimport { DEV } from 'esm-env';\nimport { active_effect } from '../../runtime.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\t// like the result of an async expression, the states of a run belong to the batch\n\t// that holds them: another batch's commit doesn't overwrite them (see `BatchValue#async`)\n\tvalue.f |= ASYNC;\n\terror.f |= ASYNC;\n\n\tif (DEV) {\n\t\tvalue.label = '{#await ...} value';\n\t\terror.label = '{#await ...} error';\n\t}\n\n\tvar branches = new BranchManager(node);\n\n\t/** The latest run of the block in the real world */\n\tvar current = {};\n\n\t/**\n\t * The latest run of the block in each fork that ran it. Once the fork is committed, that's a run of the real\n\t * world (and so are its later runs), until a later run in the real world supersedes it (`null`)\n\t * @type {Map<Batch, {} | null>}\n\t */\n\tvar forks = new Map();\n\n\t/** @param {Batch} batch */\n\tvar commit = (batch) => {\n\t\tvar run = forks.get(batch);\n\t\tif (run) current = run;\n\t\tforks.delete(batch);\n\t};\n\n\t/** @param {Batch} batch */\n\tvar discard = (batch) => {\n\t\tforks.delete(batch);\n\t};\n\n\t/**\n\t * @param {{}} run\n\t * @param {Batch} batch\n\t */\n\tvar is_latest = (run, batch) => {\n\t\tif (forks.has(batch)) return forks.get(batch) === run;\n\t\tif (run !== current) return false;\n\n\t\t// a fork that was committed since supersedes it\n\t\tfor (const [b, r] of forks) {\n\t\t\tif (!b.is_fork && r !== null) return false;\n\t\t}\n\n\t\treturn true;\n\t};\n\n\t/**\n\t * The batch that the states of a run in `batch` go into, if they aren't their own batch: the fork, so that they\n\t * don't show before it's committed — and once it is, the batch it became, so that they land along with the rest\n\t * of its changes while those are pending (its later runs, too: they replace the states it holds)\n\t * @param {Batch} batch\n\t */\n\tvar owner = (batch) => {\n\t\tvar target = merge_target(batch);\n\t\treturn forks.has(batch) && target.linked ? target : null;\n\t};\n\n\tblock(() => {\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\t\tvar input = get_input();\n\t\tvar run = {};\n\n\t\t// (not the first run, which creates the block for every batch's view, see `should_defer_append`)\n\t\tvar fork = batch.is_fork && should_defer_append();\n\n\t\tif (fork || forks.has(batch)) {\n\t\t\tforks.set(batch, run);\n\t\t\tbatch.oncommit(commit);\n\t\t\tbatch.ondiscard(discard);\n\t\t}\n\n\t\tif (!fork) {\n\t\t\tfor (const b of forks.keys()) {\n\t\t\t\tif (!b.is_fork && b !== batch) forks.set(b, null);\n\t\t\t}\n\n\t\t\tcurrent = run;\n\t\t}\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 =\n\t\t\thydrating && is_promise(input) === (get_node_value(node) === 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 {(set: (source: Source, value: any) => void) => void} fn\n\t\t\t */\n\t\t\tconst resolve = (fn) => {\n\t\t\t\tif ((effect.f & DESTROYED) !== 0 || !is_latest(run, batch)) return;\n\n\t\t\t\tresolved = true;\n\n\t\t\t\tvar target = owner(batch);\n\n\t\t\t\tif (target !== null) {\n\t\t\t\t\tvar previous = current_batch;\n\t\t\t\t\trestore(target);\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfn((source, v) => /** @type {Batch} */ (target).capture(source, v, source.equals(v)));\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tunset_context(false);\n\t\t\t\t\t\ttarget.flush();\n\t\t\t\t\t\tif (previous?.linked) previous.activate();\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\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(null);\n\t\t\t\t// ...but it might still be set here. That means a `save(...)` has restored it — but that batch will\n\t\t\t\t// likely already have been committed by the time it resolves, and this resolve should be processed\n\t\t\t\t// in a separate batch. We're not using batch.deactivate()/activate() above because get_input()\n\t\t\t\t// could write to sources, which would then incorrectly create a new batch or could mess with\n\t\t\t\t// async_derived expecting a current_batch to exist.\n\t\t\t\tif (current_batch === batch) {\n\t\t\t\t\tbatch.deactivate();\n\t\t\t\t}\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\ttry {\n\t\t\t\t\tfn(internal_set);\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((set) => {\n\t\t\t\t\t\tset(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((set) => {\n\t\t\t\t\t\tset(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 e;\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\tif (owner(batch) === batch) batch.capture(value, input, value.equals(input));\n\t\t\telse internal_set(value, input);\n\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\t}, EFFECT_PRESERVED); // states are selected asynchronously: keep the effect even without dependencies\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","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\t// `''` is a present boolean attribute, as it is in markup and on the client\n\tif (value == null || (is_boolean && !value && value !== '')) 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\t// strip comments; surrounding whitespace is handled by the trims below (which is much faster than doing it through regex)\n\t\t\tvalue = String(value)\n\t\t\t\t.replaceAll(/\\/\\*.*?\\*\\//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 { render_effect } from '../../reactivity/effects.js';\nimport { hydrating, set_hydrate_node } from '../hydration.js';\nimport {\n\tget_attribute,\n\tget_first_child,\n\tremove_attribute,\n\tset_css_text,\n\tstyle_set_property,\n\tstyle_remove_property\n} from '../operations.js';\nimport { to_style } from '../../../shared/attributes.js';\nimport { custom_renderers_flag } from '../../../flags/index.js';\nimport { current_renderer } from '../../custom-renderer/state.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\tif (custom_renderers_flag && current_renderer !== null) {\n\t\t// custom renderers only deal in attributes, so set the whole `style` attribute: the\n\t\t// wrapper's own styles, followed by the custom properties\n\t\tvar base = get_attribute(element, 'style');\n\n\t\trender_effect(() => {\n\t\t\tvar style = to_style(base, get_styles());\n\n\t\t\tif (style === null) {\n\t\t\t\tremove_attribute(element, 'style');\n\t\t\t} else {\n\t\t\t\tset_css_text(/** @type {HTMLElement} */ (element), style);\n\t\t\t}\n\t\t});\n\n\t\treturn;\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 == null || value === '') {\n\t\t\t\tstyle_remove_property(/** @type {HTMLElement} */ (element), key);\n\t\t\t} else {\n\t\t\t\tstyle_set_property(/** @type {HTMLElement} */ (element), key, value);\n\t\t\t}\n\t\t}\n\t});\n}\n","/** @import { EachItem, EachOutroGroup, EachState, Effect, EffectNodes, MaybeSource, TemplateNode, TransitionManager } 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\tget_parent_node,\n\tappend_child,\n\tcreate_fragment,\n\tinsert_before,\n\tnode_type,\n\tget_node_value\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\nimport { push_renderer, current_renderer, pop_renderer } from '../../custom-renderer/state.js';\nimport { custom_renderers_flag } from '../../../flags/index.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\t// Skip the fast path when another batch is still pending on this each block:\n\t\t// that batch's keys still reference EachItems in `state.items`, which\n\t\t// `destroy_effects` needs to preserve offscreen (see #18610).\n\t\tvar fast_path =\n\t\t\ttransitions.length === 0 && controlled_anchor !== null && state.pending.size === 0;\n\n\t\tif (fast_path) {\n\t\t\tvar anchor = /** @type {Element} */ (controlled_anchor);\n\t\t\tvar parent_node = /** @type {Element} */ (get_parent_node(anchor));\n\n\t\t\tclear_text_content(parent_node);\n\t\t\tappend_child(parent_node, 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 * @returns {Set<Effect>}\n */\nfunction selected_effects(state) {\n\tvar selected = new Set();\n\t// The loop-in-a-loop isn't ideal, but we should only hit this in relatively rare cases\n\tfor (const keys of state.pending.values()) {\n\t\tfor (const key of keys) {\n\t\t\tselected.add(/** @type {EachItem} */ (state.items.get(key)).e);\n\t\t}\n\t}\n\treturn selected;\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\tvar preserved_effects = state.pending.size > 0 ? selected_effects(state) : undefined;\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 = create_fragment();\n\t\t\tmove_effect(e, fragment);\n\n\t\t\t// `reconcile` expects offscreen items to come after all onscreen items\n\t\t\tif (e !== state.effect.last) {\n\t\t\t\tlink(state, e.prev, e.next);\n\t\t\t\tlink(state, state.effect.last, e);\n\t\t\t\tlink(state, e, null);\n\t\t\t}\n\t\t} else {\n\t\t\tdestroy_effect(to_destroy[i], remove_dom);\n\t\t}\n\t}\n}\n\n/**\n * Whether the item is outroing, i.e. `pause_effects` destroys it (or keeps it offscreen) once its outro is done\n * @param {EachState} state\n * @param {Effect} effect\n */\nfunction is_outroing(state, effect) {\n\tif (state.outrogroups !== null) {\n\t\tfor (const group of state.outrogroups) {\n\t\t\tif (group.pending.has(effect) || group.done.has(effect)) return true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n// we need to handle the case of multiple renderers so we need to use a WeakMap of offscreen anchors rather than a single variable.\n// we also need the dom_weak_key since `null` is not a viable WeakKey\n/** @type {WeakMap<WeakKey, TemplateNode>} */\nvar offscreen_anchors = new WeakMap();\nvar dom_weak_key = {};\n\n/**\n * Returns an anchor node suitable for offscreen rendering.\n * When a custom renderer is active, the anchor must have a parent\n * (so that `getParent()` works), so we place the text node inside\n * a fragment. The result is cached just like the non-renderer path.\n * @returns {TemplateNode}\n */\nfunction get_offscreen_anchor() {\n\t// not doing it inline to please typescript\n\tvar cached = offscreen_anchors.get(current_renderer ?? dom_weak_key);\n\tif (cached) return cached;\n\n\tvar offscreen_anchor = create_text();\n\n\tif (current_renderer) {\n\t\tvar fragment = create_fragment();\n\t\tappend_child(fragment, offscreen_anchor);\n\t}\n\n\toffscreen_anchors.set(current_renderer ?? dom_weak_key, offscreen_anchor);\n\treturn offscreen_anchor;\n}\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\t// Capture the renderer that was active when this each block was created.\n\t// Needed so that the commit callback can push the correct renderer when doing\n\t// DOM operations outside of an effect context (e.g. as a batch commit callback).\n\tvar renderer = current_renderer;\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: /** @type {Text} */ (append_child(parent_node, 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 /** @type {V[]} */ (\n\t\t\tis_array(collection) ? collection : collection == null ? [] : array_from(collection)\n\t\t);\n\t});\n\n\tif (DEV) {\n\t\ttag(each_array, '{#each ...}');\n\t}\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\tvar previous_renderer = custom_renderers_flag ? push_renderer(renderer) : null;\n\n\t\ttry {\n\t\t\tstate.pending.delete(batch);\n\n\t\t\t// The effect doesn't necessarily re-run in a batch right before that batch commits\n\t\t\t// (its view of the collection may not have changed), so we read the collection\n\t\t\t// as the committing batch sees it rather than using the most recent block run's result\n\t\t\tvar array = get(each_array);\n\n\t\t\tstate.fallback = fallback;\n\t\t\treconcile(state, array, anchor, flags, get_key);\n\n\t\t\tif (fallback !== null) {\n\t\t\t\tif (array.length === 0) {\n\t\t\t\t\tif ((fallback.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\t\t\t\tresume_effect(fallback);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfallback.f ^= EFFECT_OFFSCREEN;\n\t\t\t\t\t\tmove(fallback, null, anchor);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpause_effect(fallback, () => {\n\t\t\t\t\t\t// TODO only null out if no pending batch needs it,\n\t\t\t\t\t\t// otherwise re-add `fallback.fragment` and move the\n\t\t\t\t\t\t// effect into it\n\t\t\t\t\t\tfallback = null;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tif (custom_renderers_flag) pop_renderer(previous_renderer);\n\t\t}\n\n\t\tdestroy_unselected();\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\tfunction discard(batch) {\n\t\tstate.pending.delete(batch);\n\n\t\tif ((state.effect.f & DESTROYED) === 0) {\n\t\t\tdestroy_unselected();\n\t\t}\n\t}\n\n\t/**\n\t * Destroys the offscreen items that no pending batch selects anymore. Offscreen items only exist\n\t * for the batches that select them: they were created in their view, or kept for them when a\n\t * commit removed them (see `destroy_effects`). A batch stops selecting an item when it's discarded,\n\t * or when its block runs again without it. `reconcile` doesn't destroy such an item if it was kept,\n\t * as kept items are paused, and it leaves paused items alone (taking them to be outroing)\n\t */\n\tfunction destroy_unselected() {\n\t\t/** @type {Set<Effect> | undefined} */\n\t\tvar selected;\n\t\tvar effect = state.effect.last;\n\n\t\t// offscreen items come after all onscreen items (see `destroy_effects`)\n\t\twhile (effect !== null) {\n\t\t\tvar prev = effect.prev;\n\n\t\t\t// (an offscreen fallback isn't paused, so the next commit shows it or destroys it, see above)\n\t\t\tif ((effect.f & BRANCH_EFFECT) !== 0 && effect !== fallback) {\n\t\t\t\tif ((effect.f & EFFECT_OFFSCREEN) === 0) break;\n\n\t\t\t\t// create lazily to save work in the common case\n\t\t\t\tselected ??= selected_effects(state);\n\n\t\t\t\tif (!selected.has(effect) && !is_outroing(state, effect)) {\n\t\t\t\t\tdestroy_effect(effect);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\teffect = prev;\n\t\t}\n\t}\n\n\tvar effect = block(() => {\n\t\tvar array = /** @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\tnode_type(hydrate_node) === COMMENT_NODE &&\n\t\t\t\tget_node_value(hydrate_node) === 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 : get_offscreen_anchor(),\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\t// until it is committed, the item only exists for the batches that select it\n\t\t\t\t\titem.e.f |= EFFECT_OFFSCREEN;\n\t\t\t\t\tif (defer) batch.unskip_new_effect(item.e);\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(get_offscreen_anchor()));\n\t\t\t\t// until it is committed, the fallback only exists for the batches that select it\n\t\t\t\tfallback.f |= EFFECT_OFFSCREEN;\n\t\t\t\tif (defer) batch.unskip_new_effect(fallback);\n\t\t\t}\n\t\t}\n\n\t\tif (defer && fallback !== null) {\n\t\t\tif (length === 0) {\n\t\t\t\tbatch.unskip_effect(fallback);\n\t\t\t} else {\n\t\t\t\tbatch.skip_effect(fallback);\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: MaybeSource<V>, index: MaybeSource<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\tinsert_before(dest, 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 { DevStackEntry, 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 { component_context, dev_current_component_function, dev_stack } from '../../context.js';\nimport {\n\tcreate_element,\n\tget_first_child,\n\tget_next_sibling,\n\tget_last_child,\n\tset_inner_html,\n\tinsert_before,\n\tnode_type,\n\tget_node_value\n} from '../operations.js';\nimport { active_effect } from '../../runtime.js';\nimport { COMMENT_NODE, ELEMENT_NODE } from '#client/constants';\n\n/**\n * @param {string | null} server_hash\n * @param {string | TrustedHTML} value\n * @param {[string, number, number] | undefined} loc\n */\nfunction check_hash(server_hash, value, loc) {\n\tif (!server_hash || server_hash === hash(String(value ?? ''))) return;\n\n\tlet location;\n\n\tif (loc) {\n\t\tlocation = `near ${loc[0]}:${loc[1]}:${loc[2]}`;\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 * Assigns the location of the `{@html ...}` tag to the top-level elements it created,\n * which also prevents the surrounding template from assigning its locations to them\n * @param {Effect} effect\n * @param {DevStackEntry | null} parent\n * @param {[string, number, number]} loc\n */\nfunction assign_locations(effect, parent, loc) {\n\tif (effect.nodes === null) return;\n\n\t/** @type {TemplateNode | null} */\n\tvar node = effect.nodes.start;\n\n\twhile (node !== null) {\n\t\tif (node_type(node) === ELEMENT_NODE) {\n\t\t\t// @ts-expect-error\n\t\t\tnode.__svelte_meta = {\n\t\t\t\tparent,\n\t\t\t\tloc: { file: loc[0], line: loc[1], column: loc[2] },\n\t\t\t\tcomponent: component_context\n\t\t\t};\n\t\t}\n\n\t\tif (node === effect.nodes.end) break;\n\t\tnode = get_next_sibling(node);\n\t}\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 * @param {[string, number, number]} [location] the filename, line and column of the tag\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\tlocation\n) {\n\tvar anchor = node;\n\tvar parent = DEV ? dev_stack : null;\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\tset_inner_html(parent_node, /** @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} */ (get_last_child(parent_node))\n\t\t\t\t);\n\n\t\t\t\tif (DEV && location) assign_locations(effect, parent, location);\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 = get_node_value(hydrate_node);\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 (next !== null && (node_type(next) !== COMMENT_NODE || get_node_value(next) !== '')) {\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(hash, value, location);\n\t\t\t}\n\n\t\t\tassign_nodes(hydrate_node, last);\n\t\t\tif (DEV && location) assign_locations(effect, parent, location);\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\tset_inner_html(wrapper, /** @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} */ (get_last_child(node))\n\t\t);\n\n\t\tif (DEV && location) assign_locations(effect, parent, location);\n\n\t\tif (svg || mathml) {\n\t\t\twhile (get_first_child(node)) {\n\t\t\t\tinsert_before(anchor, /** @type {TemplateNode} */ (get_first_child(node)));\n\t\t\t}\n\t\t} else {\n\t\t\tinsert_before(anchor, node);\n\t\t}\n\t});\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 } 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(\n\t\t\t\t\tthis.element,\n\t\t\t\t\toptions,\n\t\t\t\t\tundefined,\n\t\t\t\t\t1,\n\t\t\t\t\t() => {},\n\t\t\t\t\t() => {\n\t\t\t\t\t\tanimation?.abort();\n\t\t\t\t\t\tanimation = undefined;\n\t\t\t\t\t}\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(\n\t\t\t\telement,\n\t\t\t\tget_options(),\n\t\t\t\toutro,\n\t\t\t\t1,\n\t\t\t\t() => {\n\t\t\t\t\tdispatch_event(element, 'introstart');\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdispatch_event(element, 'introend');\n\n\t\t\t\t\t// Ensure we cancel the animation to prevent leaking\n\t\t\t\t\tintro?.abort();\n\t\t\t\t\tintro = current_options = undefined;\n\n\t\t\t\t\telement.style.overflow = overflow;\n\t\t\t\t}\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(\n\t\t\t\telement,\n\t\t\t\tget_options(),\n\t\t\t\tintro,\n\t\t\t\t0,\n\t\t\t\t() => {\n\t\t\t\t\tdispatch_event(element, 'outrostart');\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdispatch_event(element, 'outroend');\n\t\t\t\t\tfn?.();\n\t\t\t\t}\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_begin Called just before beginning the animation\n * @param {(() => void)} on_finish Called after successfully completing the animation\n * @returns {Animation}\n */\nfunction animate(element, options, counterpart, t2, on_begin, on_finish) {\n\tvar is_intro = t2 === 1;\n\tvar aborted = false;\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\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_begin, 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() ?? 1 - t2\n\t\t};\n\t}\n\n\tcounterpart?.deactivate();\n\n\tif (!options?.duration && !options?.delay) {\n\t\ton_begin();\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\t/** @type {globalThis.Animation} */\n\tvar animation;\n\n\tvar get_t = () => 1 - t2;\n\n\t// wait a microtask before applying the initial styles and creating the dummy animation,\n\t// so that transitions created in the same batch (e.g. on nested elements) all measure\n\t// the DOM first (#18421). this still happens before the next paint, so the element\n\t// won't be rendered without styles applied (#14732)\n\tqueue_micro_task(() => {\n\t\tif (aborted) return;\n\n\t\tvar keyframes = [];\n\n\t\tif (is_intro && counterpart === undefined) {\n\t\t\tif (tick) {\n\t\t\t\ttick(0, 1); // TODO put in nested effect, to avoid interleaved reads/writes?\n\t\t\t}\n\n\t\t\tif (css) {\n\t\t\t\tvar styles = css_to_keyframe(css(0, 1));\n\t\t\t\tkeyframes.push(styles, styles);\n\t\t\t}\n\t\t}\n\n\t\t// create a dummy animation that lasts as long as the delay (but with whatever devtools\n\t\t// multiplier is in effect). in the common case that it is `0`, we keep it anyway so that\n\t\t// the CSS keyframes aren't created until the DOM is updated\n\t\t//\n\t\t// fill forwards to prevent the element from rendering without styles applied\n\t\t// see https://github.com/sveltejs/svelte/issues/14732\n\t\tanimation = element.animate(keyframes, { duration: delay, fill: 'forwards' });\n\n\t\tanimation.onfinish = () => {\n\t\t\t// remove dummy animation from the stack to prevent conflict with main animation\n\t\t\tanimation.cancel();\n\n\t\t\ton_begin();\n\n\t\t\t// for bidirectional transitions, we start from the current position,\n\t\t\t// rather than doing a full intro/outro\n\t\t\tvar t1 = counterpart?.t() ?? 1 - t2;\n\t\t\tcounterpart?.abort();\n\n\t\t\tvar delta = t2 - t1;\n\t\t\tvar duration = /** @type {number} */ (options.duration) * Math.abs(delta);\n\t\t\tvar keyframes = [];\n\n\t\t\tif (duration > 0) {\n\t\t\t\t/**\n\t\t\t\t * Whether or not the CSS includes `overflow: hidden`, in which case we need to\n\t\t\t\t * add it as an inline style to work around a Safari <18 bug\n\t\t\t\t * TODO 6.0 remove this, if possible\n\t\t\t\t */\n\t\t\t\tvar needs_overflow_hidden = false;\n\n\t\t\t\tif (css) {\n\t\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\t\tfor (var i = 0; i <= n; i += 1) {\n\t\t\t\t\t\tvar t = t1 + delta * easing(i / n);\n\t\t\t\t\t\tvar styles = css_to_keyframe(css(t, 1 - t));\n\t\t\t\t\t\tkeyframes.push(styles);\n\n\t\t\t\t\t\tneeds_overflow_hidden ||= styles.overflow === 'hidden';\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (needs_overflow_hidden) {\n\t\t\t\t\t/** @type {HTMLElement} */ (element).style.overflow = 'hidden';\n\t\t\t\t}\n\n\t\t\t\tget_t = () => {\n\t\t\t\t\tvar time = /** @type {number} */ (\n\t\t\t\t\t\t/** @type {globalThis.Animation} */ (animation).currentTime\n\t\t\t\t\t);\n\n\t\t\t\t\treturn t1 + delta * easing(time / duration);\n\t\t\t\t};\n\n\t\t\t\tif (tick) {\n\t\t\t\t\tloop(() => {\n\t\t\t\t\t\tif (animation.playState !== 'running') return false;\n\n\t\t\t\t\t\tvar t = get_t();\n\t\t\t\t\t\ttick(t, 1 - t);\n\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tanimation = element.animate(keyframes, { duration, fill: 'forwards' });\n\n\t\t\tanimation.onfinish = () => {\n\t\t\t\tget_t = () => t2;\n\t\t\t\ttick?.(t2, 1 - t2);\n\t\t\t\ton_finish();\n\t\t\t};\n\t\t};\n\t});\n\n\treturn {\n\t\tabort: () => {\n\t\t\taborted = true;\n\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 {\n\tcreate_element,\n\tcreate_text,\n\tget_first_child,\n\tappend_child,\n\tcreate_comment,\n\tinsert_before,\n\tnode_type,\n\tremove_child\n} 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 && node_type(hydrate_node) === 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\tvar is_hydrating = hydrating;\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\tcomponent: component_context\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\tvar tmp_comment = null;\n\n\t\t\t\t\tif (hydrating && is_raw_text_element(next_tag)) {\n\t\t\t\t\t\t// prevent hydration glitches (code just below expects an anchor)\n\t\t\t\t\t\tappend_child(element, (tmp_comment = create_comment('')));\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: /** @type {Text} */ (append_child(element, 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\t\t\t\t\tif (tmp_comment) {\n\t\t\t\t\t\tremove_child(element, tmp_comment);\n\t\t\t\t\t}\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\t// we only move the node if we are not hydrating since a claimed element is already in place\n\t\t\t\tif (!is_hydrating) insert_before(anchor, 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';\n\nimport {\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tremove_node,\n\tappend_child,\n\tnode_type,\n\tget_node_value\n} from '../operations.js';\nimport { block, branch } from '../../reactivity/effects.js';\nimport { COMMENT_NODE, 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(node_type(head_anchor) !== COMMENT_NODE || get_node_value(head_anchor) !== 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\tremove_node(/** @type {ChildNode} */ (head_anchor)); // 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 = /** @type {Comment | Text} */ (append_child(document.head, create_text()));\n\t}\n\n\ttry {\n\t\tblock(() => {\n\t\t\tvar e = branch(() => render_fn(anchor));\n\t\t\te.f |= HEAD_EFFECT;\n\n\t\t\tif (!hydrating) {\n\t\t\t\tif (e.nodes === null) {\n\t\t\t\t\te.nodes = { start: anchor, end: anchor, a: null, t: null };\n\t\t\t\t} else {\n\t\t\t\t\te.nodes.end = anchor;\n\t\t\t\t}\n\t\t\t}\n\t\t});\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, append_child, set_text_content } from './operations.js';\nimport { active_effect } from '../runtime.js';\n\n/**\n * @param {Node} anchor\n * @param {{ hash: string, code: string }} css\n */\nexport function append_styles(anchor, css) {\n\t// Use an effect to ensure `anchor` is in the DOM, otherwise getRootNode() will yield wrong results\n\teffect(() => {\n\t\t// Bit of a hack: branches.js/each.js use offscreen fragments with temporary text nodes that will\n\t\t// never be connected to the real dom. Therefore walk up to the branch that has created the component\n\t\t// whose styles we want to append, and check its node instead. It will be connected by the time we get here.\n\t\tanchor = active_effect?.parent?.nodes?.start ?? anchor;\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 (!(/** @type {Element} */ (target).querySelector('#' + css.hash))) {\n\t\t\tconst style = create_element('style');\n\t\t\tstyle.id = css.hash;\n\t\t\tset_text_content(style, css.code);\n\n\t\t\tappend_child(target, 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 { 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","import { to_class } from '../../../shared/attributes.js';\nimport { custom_renderers_flag } from '../../../flags/index.js';\nimport { current_renderer } from '../../custom-renderer/state.js';\nimport { CLASS_CACHE } from '../../constants.js';\nimport { hydrating } from '../hydration.js';\nimport {\n\tclass_list_toggle,\n\tget_attribute,\n\tremove_attribute,\n\tset_attribute\n} from '../operations.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\tvar prev = /** @type {any} */ (dom)[CLASS_CACHE];\n\n\tif (\n\t\thydrating ||\n\t\tprev !== value ||\n\t\tprev === undefined || // for edge case of `class={undefined}`\n\t\t// custom renderers only deal in attributes, so rather than toggling individual classes\n\t\t// (which would mean editing the `class` attribute), always set the whole thing\n\t\t(custom_renderers_flag && current_renderer !== null)\n\t) {\n\t\tvar next_class_name = to_class(value, hash, next_classes);\n\n\t\tif (!hydrating || next_class_name !== get_attribute(dom, '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\tremove_attribute(dom, '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\tset_attribute(dom, 'class', next_class_name);\n\t\t\t}\n\t\t}\n\n\t\t/** @type {any} */ (dom)[CLASS_CACHE] = 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\tclass_list_toggle(/** @type {HTMLElement} */ (dom), 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 { custom_renderers_flag } from '../../../flags/index.js';\nimport { current_renderer } from '../../custom-renderer/state.js';\nimport { STYLE_CACHE } from '../../constants.js';\nimport { hydrating } from '../hydration.js';\nimport {\n\tstyle_remove_property,\n\tstyle_set_property,\n\tget_attribute,\n\tremove_attribute,\n\tset_css_text\n} from '../operations.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\tstyle_remove_property(/** @type {HTMLElement} */ (dom), key);\n\t\t\t} else {\n\t\t\t\tstyle_set_property(/** @type {HTMLElement} */ (dom), 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\tvar prev = /** @type {any} */ (dom)[STYLE_CACHE];\n\n\t// Custom renderers only deal in attributes, so rather than updating individual properties\n\t// (which would mean parsing and editing the `style` attribute), always set the whole thing\n\tif (hydrating || prev !== value || (custom_renderers_flag && current_renderer !== null)) {\n\t\tvar next_style_attr = to_style(value, next_styles);\n\n\t\tif (!hydrating || next_style_attr !== get_attribute(dom, 'style')) {\n\t\t\tif (next_style_attr == null) {\n\t\t\t\tremove_attribute(dom, 'style');\n\t\t\t} else {\n\t\t\t\tset_css_text(/** @type {HTMLElement} */ (dom), next_style_attr);\n\t\t\t}\n\t\t}\n\n\t\t/** @type {any} */ (dom)[STYLE_CACHE] = 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 { Batch } from '../../../reactivity/batch.js' */\nimport { 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 { current_batch, view_batch } from '../../../reactivity/batch.js';\nimport {\n\thas_attribute,\n\tremove_attribute,\n\tset_attribute as set_attribute_op\n} from '../../operations.js';\n\n/**\n * Sets the `selected` attribute on an option so form reset can restore it.\n * @param {HTMLOptionElement} option\n * @param {boolean} selected\n */\nexport function set_selected(option, 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 (!has_attribute(option, 'selected')) {\n\t\t\tset_attribute_op(option, 'selected', '');\n\t\t}\n\t} else {\n\t\tremove_attribute(option, 'selected');\n\t}\n}\n\n/**\n * Sets the options a form reset should restore. The first call selects\n * them if nothing has set a value, later calls leave the current selection alone.\n * @param {HTMLSelectElement} select\n * @param {any} value\n */\nexport function set_default_select_value(select, value) {\n\tvar mounting = !('__defaultValue' in select);\n\t// @ts-expect-error\n\tif (!mounting && select.__defaultValue === value) return;\n\t// @ts-expect-error\n\tselect.__defaultValue = value;\n\tapply_default_select_value(select, !mounting || '__value' in select);\n}\n\n/**\n * Marks the options matching `__defaultValue` as selected. Without `preserve`\n * a newly matching option gets selected, as an inserted `<option selected>` would.\n * @param {HTMLSelectElement} select\n * @param {boolean} preserve\n */\nfunction apply_default_select_value(select, preserve) {\n\t// @ts-expect-error\n\tvar value = select.__defaultValue;\n\tvar multiple = select.multiple;\n\tvar values = multiple ? value ?? [] : null;\n\n\tif (multiple && !is_array(values)) return;\n\n\tvar index = select.selectedIndex;\n\tvar selected = preserve && multiple ? new Set(select.selectedOptions) : null;\n\n\tfor (var option of select.options) {\n\t\tvar option_value = get_option_value(option);\n\t\tset_selected(\n\t\t\toption,\n\t\t\tmultiple ? /** @type {any[]} */ (values).includes(option_value) : is(option_value, value)\n\t\t);\n\t}\n\n\tif (!preserve) return;\n\n\tif (selected !== null) {\n\t\tfor (option of select.options) {\n\t\t\tvar was_selected = selected.has(option);\n\t\t\tif (option.selected !== was_selected) option.selected = was_selected;\n\t\t}\n\t} else if (select.selectedIndex !== index) {\n\t\tselect.selectedIndex = index;\n\t}\n}\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 * Sets up a mutation observer to sync the current selection\n * and default to the dom when the options change, for example\n * when they are inside an `#each` block. Called once per `<select>`,\n * by the compiled output or by `attribute_effect` for spreads.\n * @param {HTMLSelectElement} select\n */\nexport function init_select(select) {\n\tvar observer = new MutationObserver((entries) => {\n\t\t// Mutations related to `<selectedcontent>` can never affect the option list.\n\t\t// Reacting to them could revert a user-initiated selection change, because the\n\t\t// records are delivered as soon as any listener returns (e.g. a delegated `input`\n\t\t// handler), which can happen before the `change` handler has updated `__value`\n\t\tif (entries.every(is_selectedcontent_mutation)) return;\n\n\t\tif ('__defaultValue' in select) {\n\t\t\tapply_default_select_value(select, false);\n\t\t}\n\n\t\tif ('__value' in select) {\n\t\t\tselect_option(select, select.__value);\n\t\t}\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// 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(/** @type {Batch} */ (view_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\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\n/**\n * Returns `true` if the mutation stems from the browser mirroring the selected\n * option's content into `<selectedcontent>`, or from us replacing the\n * `<selectedcontent>` element with a clone of itself\n * @param {MutationRecord} entry\n */\nfunction is_selectedcontent_mutation(entry) {\n\tif (/** @type {Element} */ (entry.target).closest('selectedcontent') !== null) {\n\t\treturn true;\n\t}\n\n\tif (entry.type === 'childList') {\n\t\tvar nodes = [...entry.addedNodes, ...entry.removedNodes];\n\t\treturn nodes.length > 0 && nodes.every((node) => node.nodeName === 'SELECTEDCONTENT');\n\t}\n\n\treturn false;\n}\n","/** @import { Effect } from '#client' */\n/** @import { Blocker } from '../../reactivity/async.js' */\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 } from './events.js';\nimport { add_form_reset_listener, autofocus } from './misc.js';\nimport * as w from '../../warnings.js';\nimport {\n\tATTRIBUTES_CACHE,\n\tFORM_RESET_HANDLER,\n\tIS_XHTML,\n\tLOADING_ATTR_SYMBOL\n} 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 {\n\tinit_select,\n\tselect_option,\n\tset_default_select_value,\n\tset_selected\n} from './bindings/select.js';\nimport { flatten } from '../../reactivity/async.js';\nimport {\n\thas_attribute,\n\tget_attribute,\n\tremove_attribute,\n\tset_attribute as set_attribute_op,\n\tremove_event_listener,\n\tnode_name,\n\tset_element_value,\n\tset_element_checked,\n\tset_element_default_value,\n\tset_element_default_checked\n} from '../operations.js';\nimport { current_renderer } from '../../custom-renderer/state.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\t// we should be safe here from custom renderers as this only run during hydration\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 (has_attribute(input, '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 (has_attribute(input, '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/** @type {any} */ (input)[FORM_RESET_HANDLER] = 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// `progress` elements always need their value set when it's `0`\n\t\t(current_renderer == null &&\n\t\t\t/** @type {any} */ (element).value === value &&\n\t\t\t(value !== 0 || node_name(element) !== PROGRESS_TAG))\n\t) {\n\t\treturn;\n\t}\n\n\tset_element_value(element, 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\tset_element_checked(element, checked);\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\tset_element_default_checked(element, checked);\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\tset_element_default_value(element, 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] = get_attribute(element, attribute);\n\n\t\tif (\n\t\t\tattribute === 'src' ||\n\t\t\tattribute === 'srcset' ||\n\t\t\t(attribute === 'href' && node_name(element) === 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\tvar previous = attributes[attribute];\n\tif (previous === (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\tremove_attribute(element, attribute);\n\t} else if (typeof value !== 'string' && get_setters(element).has(attribute)) {\n\t\t// @ts-ignore\n\t\telement[attribute] = value;\n\t} else if (\n\t\t// while hydrating, skip a number or boolean whose string the server already rendered\n\t\t!(\n\t\t\thydrating &&\n\t\t\t(typeof value === 'number' || typeof value === 'boolean') &&\n\t\t\tprevious === String(value)\n\t\t)\n\t) {\n\t\tset_attribute_op(element, 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\t// custom renderer safe since we never emit this\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// custom renderer safe since we never emit this\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(get_attribute(node, 'is') || node_name(node)) ||\n\t\t\t// customElements may not be available in browser extension contexts\n\t\t\t!customElements ||\n\t\t\tcustomElements.get(get_attribute(node, 'is') || node_name(node).toLowerCase())\n\t\t\t\t? get_setters(node).has(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 && node_name(element) === INPUT_TAG) {\n\t\tif (!('defaultValue' in next || 'defaultChecked' in next)) {\n\t\t\tremove_input_defaults(/** @type {HTMLInputElement} */ (element));\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 = node_name(element) === OPTION_TAG;\n\tvar is_select_element = node_name(element) === SELECT_TAG;\n\n\ttry {\n\t\tfor (var key in prev) {\n\t\t\t// don't null our internal $$onX listeners\n\t\t\tif (!(key in next) && key[0] + key[1] !== '$$') {\n\t\t\t\tnext[key] = null;\n\t\t\t}\n\t\t}\n\n\t\tif (next.class) {\n\t\t\tnext.class = clsx(next.class);\n\t\t} else if (css_hash || next[CLASS]) {\n\t\t\tnext.class = null; /* force call to set_class() */\n\t\t}\n\n\t\tif (next[STYLE]) {\n\t\t\tnext.style ??= null; /* force call to set_style() */\n\t\t}\n\n\t\tvar setters = get_setters(element);\n\n\t\tif (\n\t\t\t// the following logic only makes sense in a DOM environment\n\t\t\tcurrent_renderer == null &&\n\t\t\tnode_name(element) === INPUT_TAG &&\n\t\t\t'type' in next &&\n\t\t\t('value' in next || '__value' in next)\n\t\t) {\n\t\t\tvar type = next.type;\n\n\t\t\tif (type !== current.type || (type === undefined && element.hasAttribute('type'))) {\n\t\t\t\tcurrent.type = type;\n\t\t\t\tset_attribute(element, 'type', type, skip_warning);\n\t\t\t}\n\t\t}\n\n\t\t// since key is captured we use const\n\t\tfor (const key in next) {\n\t\t\t// let instead of var because referenced in a closure\n\t\t\tlet value = next[key];\n\n\t\t\t// Up here because we want to do this for the initial value, too, even if it's undefined,\n\t\t\t// and this wouldn't be reached in case of undefined because of the equality check below\n\t\t\tif (is_option_element && key === 'value' && value == null) {\n\t\t\t\t// The <option> element is a special case because removing the value attribute means\n\t\t\t\t// the value is set to the text content of the option element, and setting the value\n\t\t\t\t// to null or undefined means the value is set to the string \"null\" or \"undefined\".\n\t\t\t\t// To align with how we handle this case in non-spread-scenarios, this logic is needed.\n\t\t\t\t// There's a super-edge-case bug here that is left in favor of smaller code size:\n\t\t\t\t// Because of the \"set missing props to null\" logic above, we can't differentiate\n\t\t\t\t// between a missing value and an explicitly set value of null or undefined. That means\n\t\t\t\t// that once set, the value attribute of an <option> element can't be removed. This is\n\t\t\t\t// a very rare edge case, and removing the attribute altogether isn't possible either\n\t\t\t\t// for the <option value={undefined}> case, so we're not losing any functionality here.\n\t\t\t\t// @ts-ignore\n\t\t\t\telement.value = element.__value = '';\n\t\t\t\tcurrent[key] = value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (key === 'class') {\n\t\t\t\tvar is_html = current_renderer == null && element.namespaceURI === NAMESPACE_HTML;\n\t\t\t\tset_class(element, is_html, value, css_hash, prev?.[CLASS], next[CLASS]);\n\t\t\t\tcurrent[key] = value;\n\t\t\t\tcurrent[CLASS] = next[CLASS];\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (key === 'style') {\n\t\t\t\tset_style(element, value, prev?.[STYLE], next[STYLE]);\n\t\t\t\tcurrent[key] = value;\n\t\t\t\tcurrent[STYLE] = next[STYLE];\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tvar prev_value = current[key];\n\n\t\t\t// Skip if value is unchanged, unless it's `undefined` and the element still has the attribute\n\t\t\tif (value === prev_value && !(value === undefined && has_attribute(element, key))) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcurrent[key] = value;\n\n\t\t\tvar prefix = key[0] + key[1]; // this is faster than key.slice(0, 2)\n\t\t\tif (prefix === '$$') continue;\n\n\t\t\tif (prefix === 'on') {\n\t\t\t\t/** @type {{ capture?: true }} */\n\t\t\t\tconst opts = {};\n\t\t\t\tconst event_handle_key = '$$' + key;\n\t\t\t\tlet event_name = key.slice(2);\n\t\t\t\tvar is_delegated = current_renderer == null && can_delegate_event(event_name);\n\n\t\t\t\tif (is_capture_event(event_name)) {\n\t\t\t\t\tevent_name = event_name.slice(0, -7);\n\t\t\t\t\topts.capture = true;\n\t\t\t\t}\n\n\t\t\t\tif (!is_delegated && prev_value) {\n\t\t\t\t\t// Listening to same event but different handler -> our handle function below takes care of this\n\t\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\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\t// https://github.com/sveltejs/svelte/issues/11903\n\t\t\t\t\tif (value != null) continue;\n\n\t\t\t\t\tremove_event_listener(element, event_name, current[event_handle_key], opts);\n\t\t\t\t\tcurrent[event_handle_key] = null;\n\t\t\t\t}\n\n\t\t\t\tif (is_delegated) {\n\t\t\t\t\tdelegated(event_name, element, value);\n\t\t\t\t\tdelegate([event_name]);\n\t\t\t\t} else if (value != null) {\n\t\t\t\t\t/**\n\t\t\t\t\t * @this {any}\n\t\t\t\t\t * @param {...any} args\n\t\t\t\t\t */\n\t\t\t\t\tfunction handle(...args) {\n\t\t\t\t\t\tcurrent[key].apply(this, args);\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent[event_handle_key] = create_event(event_name, element, handle, opts);\n\t\t\t\t}\n\t\t\t} else if (key === 'style') {\n\t\t\t\t// avoid using the setter\n\t\t\t\tset_attribute(element, key, value);\n\t\t\t} else if (key === 'autofocus') {\n\t\t\t\tif (current_renderer == null) {\n\t\t\t\t\tautofocus(/** @type {HTMLElement} */ (element), Boolean(value));\n\t\t\t\t} else {\n\t\t\t\t\t// In custom renderer mode, just set autofocus as a regular attribute\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\tset_attribute_op(element, key, value);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tremove_attribute(element, key);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (!is_custom_element && (key === '__value' || (key === 'value' && value != null))) {\n\t\t\t\t// @ts-ignore We're not running this for custom elements because __value is actually\n\t\t\t\t// how Lit stores the current value on the element, and messing with that would break things.\n\t\t\t\telement.__value = value;\n\t\t\t\t// we don't set the value if it hasn't changed. This supports invalid number inputs like `1e` because\n\t\t\t\t// 1. user types 1e\n\t\t\t\t// 2. the state is updated reading e.target.value which is ''\n\t\t\t\t// 3. the spreaded value is ''\n\t\t\t\t// 4. updating input.value would thus, clear the user value\n\t\t\t\tif (\n\t\t\t\t\tprev_value == null ||\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\telement.value !== value ||\n\t\t\t\t\t(value === 0 && element.nodeName === PROGRESS_TAG)\n\t\t\t\t) {\n\t\t\t\t\tset_element_value(element, value);\n\t\t\t\t}\n\t\t\t} else if (key === 'selected' && is_option_element) {\n\t\t\t\tset_selected(/** @type {HTMLOptionElement} */ (element), value);\n\t\t\t} else {\n\t\t\t\tvar name = key;\n\t\t\t\tif (!preserve_attribute_case) {\n\t\t\t\t\tname = normalize_attribute(name);\n\t\t\t\t}\n\n\t\t\t\tvar is_default = name === 'defaultValue' || name === 'defaultChecked';\n\n\t\t\t\t// A select's default value is represented by selected options, not a property.\n\t\t\t\tif (is_select_element && name === 'defaultValue') continue;\n\n\t\t\t\tif (value == null && !is_custom_element && !is_default) {\n\t\t\t\t\tattributes[key] = null;\n\t\t\t\t\tif ((name === 'value' || name === 'checked') && current_renderer == null) {\n\t\t\t\t\t\t// removing value/checked also removes defaultValue/defaultChecked — preserve\n\t\t\t\t\t\tlet input = /** @type {HTMLInputElement} */ (element);\n\t\t\t\t\t\tconst use_default = prev === undefined;\n\t\t\t\t\t\tif (name === 'value') {\n\t\t\t\t\t\t\tlet previous = input.defaultValue;\n\t\t\t\t\t\t\tremove_attribute(input, name);\n\t\t\t\t\t\t\tset_element_default_value(input, previous);\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tset_element_value(input, (input.__value = use_default ? previous : null));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlet previous = input.defaultChecked;\n\t\t\t\t\t\t\tremove_attribute(input, name);\n\t\t\t\t\t\t\tset_element_default_checked(input, previous);\n\t\t\t\t\t\t\tset_element_checked(input, use_default ? previous : false);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tremove_attribute(element, key);\n\t\t\t\t\t\tif (name === 'value') {\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\telement.__value = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (is_default && current_renderer != null) {\n\t\t\t\t\t// Route through the renderer-aware abstraction so custom renderers\n\t\t\t\t\t// see defaultValue/defaultChecked as proper attributes\n\t\t\t\t\tif (name === 'defaultValue') {\n\t\t\t\t\t\tset_element_default_value(element, value);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tset_element_default_checked(element, value);\n\t\t\t\t\t}\n\t\t\t\t\t// remove it from attributes's cache\n\t\t\t\t\tif (name in attributes) attributes[name] = UNINITIALIZED;\n\t\t\t\t} else if (\n\t\t\t\t\tis_default ||\n\t\t\t\t\t((is_custom_element || typeof value !== 'string') && setters.has(name))\n\t\t\t\t) {\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\telement[name] = value;\n\t\t\t\t\t// remove it from attributes's cache\n\t\t\t\t\tif (name in attributes) attributes[name] = UNINITIALIZED;\n\t\t\t\t} else if (typeof value !== 'function') {\n\t\t\t\t\tset_attribute(element, name, value, skip_warning);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tif (is_hydrating_custom_element) {\n\t\t\tset_hydrating(true);\n\t\t}\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 = node_name(element) === 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) {\n\t\t\t\tvar select = /** @type {HTMLSelectElement} */ (element);\n\n\t\t\t\tif ('defaultValue' in next) {\n\t\t\t\t\tset_default_select_value(select, next.defaultValue);\n\t\t\t\t}\n\n\t\t\t\tif ('value' in next) {\n\t\t\t\t\tselect_option(select, next.value);\n\t\t\t\t}\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\tvar attrs = /** @type {Record<string | symbol, any>} */ (prev);\n\n\t\t\t\tif ('defaultValue' in attrs) {\n\t\t\t\t\tset_default_select_value(select, attrs.defaultValue);\n\t\t\t\t}\n\n\t\t\t\tselect_option(select, attrs.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/** @type {any} */ (element)[ATTRIBUTES_CACHE] ??= {\n\t\t\t[IS_CUSTOM_ELEMENT]: node_name(element).includes('-'),\n\t\t\t[IS_HTML]: current_renderer == null && element.namespaceURI === NAMESPACE_HTML\n\t\t}\n\t);\n}\n\n/** @type {Map<string, Set<string>>} */\nvar setters_cache = new Map();\nvar empty_setters = new Set();\n\n/** @param {Element} element */\nfunction get_setters(element) {\n\t// if we have a custom renderer we just skip the check all together\n\tif (current_renderer) return empty_setters;\n\tvar cache_key = get_attribute(element, 'is') || node_name(element);\n\tvar setters = setters_cache.get(cache_key);\n\tif (setters) return setters;\n\tsetters_cache.set(cache_key, (setters = new Set()));\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 (and dangerous, like innerHTML) setters we're not interested in\n\t// Do not use constructor.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 (\n\t\t\t\tdescriptors[key].set &&\n\t\t\t\t// better safe than sorry, we don't want spread attributes to mess with HTML content\n\t\t\t\tkey !== 'innerHTML' &&\n\t\t\t\tkey !== 'textContent' &&\n\t\t\t\tkey !== 'innerText'\n\t\t\t) {\n\t\t\t\tsetters.add(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 || current_renderer != null) return;\n\tif (attribute === 'srcset' && srcset_url_equal(element, value)) return;\n\tif (src_url_equal(get_attribute(element, 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 || current_renderer != null) 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\tif (current_renderer != null) return true;\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 { 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 { current_batch, view_batch } from '../../../reactivity/batch.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// 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(/** @type {Batch} */ (view_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(\n\t\tinput,\n\t\t'change',\n\t\t() => {\n\t\t\tset(input.files);\n\t\t},\n\t\t() => {\n\t\t\t// A form reset can empty the input's `FileList` in place, which is then the very\n\t\t\t// object the binding already holds and would not be seen as a change: give the\n\t\t\t// input a new, empty one instead\n\t\t\tif (typeof DataTransfer === 'function') {\n\t\t\t\tinput.files = new DataTransfer().files;\n\t\t\t}\n\n\t\t\tset(input.files);\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\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 { 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, mark_as_component } 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(\n\telement_or_component = mark_as_component(),\n\tupdate,\n\tget_value,\n\tget_parts\n) {\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 (!is_bound_this(get_value(...parts), element_or_component)) {\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 { 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('unmounted');\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 { Derived, 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';\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: Set<string | symbol>, name?: string }>}}\n */\nconst rest_props_handler = {\n\tget(target, key) {\n\t\tif (target.exclude.has(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.has(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.has(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.has(key));\n\t}\n};\n\n/**\n * @param {Record<string, unknown>} props\n * @param {Set<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(DEV ? { props, exclude, name } : { props, exclude }, rest_props_handler);\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\tvar fallback_signal = /** @type {Derived<V> | undefined} */ (undefined);\n\n\tvar get_fallback = () => {\n\t\tif (lazy && runes) {\n\t\t\tfallback_signal ??= derived(/** @type {() => V} */ (fallback));\n\t\t\treturn get(fallback_signal);\n\t\t}\n\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 { 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\tconst render_options = {\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\tthis.#instance = options.hydrate\n\t\t\t? hydrate(options.component, render_options)\n\t\t\t: mount(options.component, render_options);\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","const bidiChars = /^[\\u061c\\u200e\\u200f\\u2066-\\u2069]+/;\nconst nameChars = /^[-.+0-9A-Z_a-z\\u{a1}-\\u{61b}\\u{61d}-\\u{167f}\\u{1681}-\\u{1fff}\\u{200b}-\\u{200d}\\u{2010}-\\u{2027}\\u{2030}-\\u{205e}\\u{2060}-\\u{2065}\\u{206a}-\\u{2fff}\\u{3001}-\\u{d7ff}\\u{e000}-\\u{fdcf}\\u{fdf0}-\\u{fffd}\\u{10000}-\\u{1fffd}\\u{20000}-\\u{2fffd}\\u{30000}-\\u{3fffd}\\u{40000}-\\u{4fffd}\\u{50000}-\\u{5fffd}\\u{60000}-\\u{6fffd}\\u{70000}-\\u{7fffd}\\u{80000}-\\u{8fffd}\\u{90000}-\\u{9fffd}\\u{a0000}-\\u{afffd}\\u{b0000}-\\u{bfffd}\\u{c0000}-\\u{cfffd}\\u{d0000}-\\u{dfffd}\\u{e0000}-\\u{efffd}\\u{f0000}-\\u{ffffd}\\u{100000}-\\u{10fffd}]+/u;\nconst notNameStart = /^[-.0-9]/;\nexport function parseNameValue(source, start) {\n    let pos = start;\n    const startBidi = source.slice(pos).match(bidiChars);\n    if (startBidi)\n        pos += startBidi[0].length;\n    const match = source.slice(pos).match(nameChars);\n    if (!match)\n        return null;\n    const name = match[0];\n    if (notNameStart.test(name))\n        return null;\n    pos += name.length;\n    const endBidi = source.slice(pos).match(bidiChars);\n    if (endBidi)\n        pos += endBidi[0].length;\n    return { value: name.normalize(), end: pos };\n}\nexport function isValidUnquotedLiteral(str) {\n    const match = str.match(nameChars);\n    return !!match && match[0].length === str.length;\n}\nexport const parseUnquotedLiteralValue = (source, start) => source.slice(start).match(nameChars)?.[0] ?? '';\n","import { MessageSyntaxError } from \"../errors.js\";\n/**\n * Shared symbol used as a key on message data model nodes\n * to reference their CST source.\n *\n * Only set on message data model nodes when parsed by {@link messageFromCST}.\n */\nexport const cstKey = Symbol.for('CST');\n/**\n * Convert a CST message structure into its data model representation.\n *\n * In the returned {@link Model.Message},\n * all nodes include a reference to their source {@link CST} node\n * as a {@link cstKey} symbol-keyed property.\n */\nexport function messageFromCST(msg) {\n    for (const error of msg.errors)\n        throw error;\n    const declarations = msg.declarations\n        ? msg.declarations.map(asDeclaration)\n        : [];\n    if (msg.type === 'select') {\n        return {\n            type: 'select',\n            declarations,\n            selectors: msg.selectors.map(sel => asValue(sel)),\n            variants: msg.variants.map(variant => ({\n                keys: variant.keys.map(key => key.type === '*' ? { type: '*', [cstKey]: key } : asValue(key)),\n                value: asPattern(variant.value),\n                [cstKey]: variant\n            })),\n            [cstKey]: msg\n        };\n    }\n    else {\n        return {\n            type: 'message',\n            declarations,\n            pattern: asPattern(msg.pattern),\n            [cstKey]: msg\n        };\n    }\n}\nfunction asDeclaration(decl) {\n    switch (decl.type) {\n        case 'input': {\n            const value = asExpression(decl.value, false);\n            if (value.arg?.type !== 'variable') {\n                const { start, end } = decl.value;\n                throw new MessageSyntaxError('parse-error', start, end);\n            }\n            return {\n                type: 'input',\n                name: value.arg.name,\n                value: value,\n                [cstKey]: decl\n            };\n        }\n        case 'local':\n            return {\n                type: 'local',\n                name: asValue(decl.target).name,\n                value: asExpression(decl.value, false),\n                [cstKey]: decl\n            };\n        default:\n            throw new MessageSyntaxError('parse-error', decl.start, decl.end);\n    }\n}\nconst asPattern = (pattern) => pattern.body.map(el => el.type === 'text' ? el.value : asExpression(el, true));\nfunction asExpression(exp, allowMarkup) {\n    if (exp.type === 'expression') {\n        if (allowMarkup && exp.markup) {\n            const cm = exp.markup;\n            const name = asName(cm.name);\n            const kind = cm.open.value === '/' ? 'close' : cm.close ? 'standalone' : 'open';\n            const markup = { type: 'markup', kind, name };\n            if (cm.options.length)\n                markup.options = asOptions(cm.options);\n            if (exp.attributes.length) {\n                markup.attributes = asAttributes(exp.attributes);\n            }\n            markup[cstKey] = exp;\n            return markup;\n        }\n        const arg = exp.arg ? asValue(exp.arg) : undefined;\n        let functionRef;\n        const ca = exp.functionRef;\n        if (ca) {\n            if (ca.type === 'function') {\n                functionRef = { type: 'function', name: asName(ca.name) };\n                if (ca.options.length)\n                    functionRef.options = asOptions(ca.options);\n            }\n            else {\n                throw new MessageSyntaxError('parse-error', exp.start, exp.end);\n            }\n        }\n        let expression = arg\n            ? { type: 'expression', arg }\n            : undefined;\n        if (functionRef) {\n            functionRef[cstKey] = ca;\n            if (expression)\n                expression.functionRef = functionRef;\n            else\n                expression = { type: 'expression', functionRef: functionRef };\n        }\n        if (expression) {\n            if (exp.attributes.length) {\n                expression.attributes = asAttributes(exp.attributes);\n            }\n            expression[cstKey] = exp;\n            return expression;\n        }\n    }\n    throw new MessageSyntaxError('parse-error', exp.start, exp.end);\n}\nfunction asOptions(options) {\n    const map = {};\n    for (const opt of options) {\n        const name = asName(opt.name);\n        if (Object.hasOwn(map, name)) {\n            throw new MessageSyntaxError('duplicate-option-name', opt.start, opt.end);\n        }\n        map[name] = asValue(opt.value);\n    }\n    return map;\n}\nfunction asAttributes(attributes) {\n    const map = {};\n    for (const attr of attributes) {\n        const name = asName(attr.name);\n        if (Object.hasOwn(map, name)) {\n            throw new MessageSyntaxError('duplicate-attribute', attr.start, attr.end);\n        }\n        map[name] = attr.value ? asValue(attr.value) : true;\n    }\n    return map;\n}\nfunction asName(id) {\n    switch (id.length) {\n        case 1:\n            return id[0].value;\n        case 3:\n            return `${id[0].value}:${id[2].value}`;\n        default:\n            throw new MessageSyntaxError('parse-error', id[0]?.start ?? -1, id.at(-1)?.end ?? -1);\n    }\n}\nfunction asValue(value) {\n    switch (value.type) {\n        case 'literal':\n            return { type: 'literal', value: value.value, [cstKey]: value };\n        case 'variable':\n            return { type: 'variable', name: value.name, [cstKey]: value };\n        default:\n            throw new MessageSyntaxError('parse-error', value.start, value.end);\n    }\n}\n","import { cstKey } from \"./data-model/from-cst.js\";\n/**\n * Base error class used by MessageFormat\n *\n * @category Errors\n */\nexport class MessageError extends Error {\n    type;\n    constructor(type, message) {\n        super(message);\n        this.type = type;\n    }\n}\n/**\n * Errors in the message syntax.\n *\n * @category Errors\n */\nexport class MessageSyntaxError extends MessageError {\n    start;\n    end;\n    /** @private */\n    constructor(type, start, end, expected) {\n        let message = expected ? `Missing ${expected}` : type;\n        if (start >= 0)\n            message += ` at ${start}`;\n        super(type, message);\n        this.start = start;\n        this.end = end ?? start + 1;\n    }\n}\n/**\n * Errors in the message data model.\n *\n * @category Errors\n */\nexport class MessageDataModelError extends MessageSyntaxError {\n    /** @private */\n    constructor(type, node) {\n        const { start, end } = node[cstKey] ?? { start: -1, end: -1 };\n        super(type, start, end);\n    }\n}\n/**\n * Message runtime resolution errors\n *\n * @category Errors\n */\nexport class MessageResolutionError extends MessageError {\n    source;\n    cause;\n    constructor(type, message, source, cause) {\n        super(type, message);\n        this.source = source;\n        if (cause !== undefined)\n            this.cause = cause;\n    }\n}\n/**\n * Message runtime resolution errors\n *\n * @category Errors\n */\nexport class MessageFunctionError extends MessageError {\n    source;\n    cause;\n    constructor(type, message) {\n        super(type, message);\n        this.source = '�';\n    }\n}\n","import { parseNameValue, parseUnquotedLiteralValue } from \"../cst/names.js\";\nimport { MessageSyntaxError } from \"../errors.js\";\nconst bidiChars = new Set('\\u061C\\u200E\\u200F\\u2066\\u2067\\u2068\\u2069');\nconst whitespaceChars = new Set('\\t\\n\\r \\u3000');\n//// Parser State ////\nlet pos;\nlet source;\n//// Utilities & Error Wrappers ////\n// These indirections allow for the function names to be mangled,\n// while keeping the error class name intact.\nconst MissingSyntax = (pos, expected) => new MessageSyntaxError('missing-syntax', pos, pos + expected.length, expected);\nconst SyntaxError = (...args) => new MessageSyntaxError(...args);\nfunction expect(searchString, consume) {\n    if (source.startsWith(searchString, pos)) {\n        if (consume)\n            pos += searchString.length;\n    }\n    else {\n        throw MissingSyntax(pos, searchString);\n    }\n}\nexport function parseMessage(source_) {\n    pos = 0;\n    source = source_;\n    const decl = declarations();\n    if (source.startsWith('.match', pos))\n        return selectMessage(decl);\n    const quoted = decl.length > 0 || source.startsWith('{{', pos);\n    if (!quoted && pos > 0)\n        pos = 0;\n    const pattern_ = pattern(quoted);\n    if (quoted) {\n        ws();\n        if (pos < source.length) {\n            throw SyntaxError('extra-content', pos, source.length);\n        }\n    }\n    return { type: 'message', declarations: decl, pattern: pattern_ };\n}\nfunction selectMessage(declarations) {\n    pos += 6; // '.match'\n    ws(true);\n    const selectors = [];\n    while (source[pos] === '$') {\n        selectors.push(variable());\n        ws(true);\n    }\n    if (selectors.length === 0)\n        throw SyntaxError('empty-token', pos);\n    const variants = [];\n    while (pos < source.length) {\n        variants.push(variant());\n        ws();\n    }\n    return { type: 'select', declarations, selectors, variants };\n}\nfunction variant() {\n    const keys = [];\n    while (pos < source.length) {\n        ws(keys.length ? '{' : false);\n        const next = source[pos];\n        if (next === '{')\n            break;\n        if (next === '*') {\n            keys.push({ type: '*' });\n            pos += 1;\n        }\n        else {\n            const key = literal(true);\n            key.value = key.value.normalize();\n            keys.push(key);\n        }\n    }\n    return { keys, value: pattern(true) };\n}\nfunction pattern(quoted) {\n    if (quoted) {\n        if (source.startsWith('{{', pos))\n            pos += 2;\n        else\n            throw MissingSyntax(pos, '{{');\n    }\n    const pattern = [];\n    loop: while (pos < source.length) {\n        switch (source[pos]) {\n            case '{': {\n                pattern.push(expression(true));\n                break;\n            }\n            case '}':\n                if (!quoted)\n                    throw SyntaxError('parse-error', pos);\n                break loop;\n            default: {\n                pattern.push(text());\n            }\n        }\n    }\n    if (quoted) {\n        if (source.startsWith('}}', pos))\n            pos += 2;\n        else\n            throw MissingSyntax(pos, '}}');\n    }\n    return pattern;\n}\nfunction declarations() {\n    const declarations = [];\n    ws();\n    loop: while (source[pos] === '.') {\n        const keyword = source.substr(pos, 6);\n        switch (keyword) {\n            case '.input':\n                declarations.push(inputDeclaration());\n                break;\n            case '.local':\n                declarations.push(localDeclaration());\n                break;\n            case '.match':\n                break loop;\n            default:\n                throw SyntaxError('parse-error', pos);\n        }\n        ws();\n    }\n    return declarations;\n}\nfunction inputDeclaration() {\n    pos += 6; // '.input'\n    ws();\n    expect('{', false);\n    const valueStart = pos;\n    const value = expression(false);\n    if (value.type === 'expression' && value.arg?.type === 'variable') {\n        // @ts-expect-error TS isn't catching that value is Expression<VariableRef>\n        return { type: 'input', name: value.arg.name, value };\n    }\n    throw SyntaxError('bad-input-expression', valueStart, pos);\n}\nfunction localDeclaration() {\n    pos += 6; // '.local'\n    ws(true);\n    expect('$', true);\n    const name_ = name();\n    ws();\n    expect('=', true);\n    ws();\n    expect('{', false);\n    const value = expression(false);\n    return { type: 'local', name: name_, value };\n}\nfunction expression(allowMarkup) {\n    const start = pos;\n    pos += 1; // '{'\n    ws();\n    const arg = value(false);\n    if (arg)\n        ws('}');\n    const sigil = source[pos];\n    let functionRef;\n    let markup;\n    switch (sigil) {\n        case '@':\n        case '}':\n            break;\n        case ':': {\n            pos += 1; // ':'\n            functionRef = { type: 'function', name: identifier() };\n            const options_ = options();\n            if (options_)\n                functionRef.options = options_;\n            break;\n        }\n        case '#':\n        case '/': {\n            if (arg || !allowMarkup)\n                throw SyntaxError('parse-error', pos);\n            pos += 1; // '#' or '/'\n            const kind = sigil === '#' ? 'open' : 'close';\n            markup = { type: 'markup', kind, name: identifier() };\n            const options_ = options();\n            if (options_)\n                markup.options = options_;\n            break;\n        }\n        default:\n            throw SyntaxError('parse-error', pos);\n    }\n    const attributes_ = attributes();\n    if (markup?.kind === 'open' && source[pos] === '/') {\n        markup.kind = 'standalone';\n        pos += 1; // '/'\n    }\n    expect('}', true);\n    if (functionRef) {\n        const exp = arg\n            ? { type: 'expression', arg, functionRef: functionRef }\n            : { type: 'expression', functionRef: functionRef };\n        if (attributes_)\n            exp.attributes = attributes_;\n        return exp;\n    }\n    if (markup) {\n        if (attributes_)\n            markup.attributes = attributes_;\n        return markup;\n    }\n    if (!arg)\n        throw SyntaxError('empty-token', start, pos);\n    return attributes_\n        ? { type: 'expression', arg, attributes: attributes_ }\n        : { type: 'expression', arg };\n}\n/** Requires and consumes leading and trailing whitespace. */\nfunction options() {\n    ws('/}');\n    const options = {};\n    let isEmpty = true;\n    while (pos < source.length) {\n        const next = source[pos];\n        if (next === '@' || next === '/' || next === '}')\n            break;\n        const start = pos;\n        const name_ = identifier();\n        if (Object.hasOwn(options, name_)) {\n            throw SyntaxError('duplicate-option-name', start, pos);\n        }\n        ws();\n        expect('=', true);\n        ws();\n        options[name_] = value(true);\n        isEmpty = false;\n        ws('/}');\n    }\n    return isEmpty ? null : options;\n}\nfunction attributes() {\n    const attributes = {};\n    let isEmpty = true;\n    while (source[pos] === '@') {\n        const start = pos;\n        pos += 1; // '@'\n        const name_ = identifier();\n        if (Object.hasOwn(attributes, name_)) {\n            throw SyntaxError('duplicate-attribute', start, pos);\n        }\n        ws('=/}');\n        if (source[pos] === '=') {\n            pos += 1; // '='\n            ws();\n            attributes[name_] = literal(true);\n            ws('/}');\n        }\n        else {\n            attributes[name_] = true;\n        }\n        isEmpty = false;\n    }\n    return isEmpty ? null : attributes;\n}\nfunction text() {\n    let value = '';\n    let i = pos;\n    loop: for (; i < source.length; ++i) {\n        switch (source[i]) {\n            case '\\\\': {\n                const esc = source[i + 1];\n                if (!'\\\\{|}'.includes(esc))\n                    throw SyntaxError('bad-escape', i, i + 2);\n                value += source.substring(pos, i) + esc;\n                i += 1;\n                pos = i + 1;\n                break;\n            }\n            case '{':\n            case '}':\n                break loop;\n        }\n    }\n    value += source.substring(pos, i);\n    pos = i;\n    return value;\n}\nfunction value(required) {\n    return source[pos] === '$' ? variable() : literal(required);\n}\nfunction variable() {\n    pos += 1; // '$'\n    return { type: 'variable', name: name() };\n}\nfunction literal(required) {\n    if (source[pos] === '|')\n        return quotedLiteral();\n    const value = parseUnquotedLiteralValue(source, pos);\n    if (!value) {\n        if (required)\n            throw SyntaxError('empty-token', pos);\n        else\n            return undefined;\n    }\n    pos += value.length;\n    return { type: 'literal', value };\n}\nfunction quotedLiteral() {\n    pos += 1; // '|'\n    let value = '';\n    for (let i = pos; i < source.length; ++i) {\n        switch (source[i]) {\n            case '\\\\': {\n                const esc = source[i + 1];\n                if (!'\\\\{|}'.includes(esc))\n                    throw SyntaxError('bad-escape', i, i + 2);\n                value += source.substring(pos, i) + esc;\n                i += 1;\n                pos = i + 1;\n                break;\n            }\n            case '|':\n                value += source.substring(pos, i);\n                pos = i + 1;\n                return { type: 'literal', value };\n        }\n    }\n    throw MissingSyntax(source.length, '|');\n}\nfunction identifier() {\n    const name_ = name();\n    if (source[pos] === ':') {\n        pos += 1;\n        return name_ + ':' + name();\n    }\n    return name_;\n}\nfunction name() {\n    const name = parseNameValue(source, pos);\n    if (!name)\n        throw SyntaxError('empty-token', pos);\n    pos = name.end;\n    return name.value;\n}\nfunction ws(req = false) {\n    let next = source[pos];\n    let hasWS = false;\n    if (req) {\n        while (bidiChars.has(next))\n            next = source[++pos];\n        while (whitespaceChars.has(next)) {\n            next = source[++pos];\n            hasWS = true;\n        }\n    }\n    while (bidiChars.has(next) || whitespaceChars.has(next))\n        next = source[++pos];\n    if (req && !hasWS && (req === true || !req.includes(source[pos]))) {\n        throw MissingSyntax(pos, \"' '\");\n    }\n}\n","/**\n * Apply visitor functions to message nodes.\n *\n * The visitors are applied in source order, starting from the root.\n * Visitors for nodes that contain other nodes may return a callback function\n * that will be called with no arguments when exiting the node.\n *\n * If set, the `node` visitor is called for all {@link Node} values\n * for which an explicit visitor is not defined.\n *\n * Many visitors will be called with additional arguments\n * identifying some of the context for the visited node.\n *\n * @category Message Data Model\n */\nexport function visit(msg, visitors) {\n    const { node, pattern } = visitors;\n    const { functionRef = node, attributes = null, declaration = node, expression = node, key = node, markup = node, options = null, value = node, variant = node } = visitors;\n    const handleOptions = (options_, context) => {\n        if (options_) {\n            const end = options?.(options_, context);\n            if (value) {\n                for (const value_ of Object.values(options_)) {\n                    value(value_, context, 'option');\n                }\n            }\n            end?.();\n        }\n    };\n    const handleAttributes = (attributes_, context) => {\n        if (attributes_) {\n            const end = attributes?.(attributes_, context);\n            if (value) {\n                for (const value_ of Object.values(attributes_)) {\n                    if (value_ !== true)\n                        value(value_, context, 'attribute');\n                }\n            }\n            end?.();\n        }\n    };\n    const handleElement = (exp, context) => {\n        if (typeof exp === 'object') {\n            let end;\n            switch (exp.type) {\n                case 'expression': {\n                    end = expression?.(exp, context);\n                    if (exp.arg)\n                        value?.(exp.arg, context, 'arg');\n                    if (exp.functionRef) {\n                        const endA = functionRef?.(exp.functionRef, context, exp.arg);\n                        handleOptions(exp.functionRef.options, context);\n                        endA?.();\n                    }\n                    handleAttributes(exp.attributes, context);\n                    break;\n                }\n                case 'markup': {\n                    end = markup?.(exp, context);\n                    handleOptions(exp.options, context);\n                    handleAttributes(exp.attributes, context);\n                    break;\n                }\n            }\n            end?.();\n        }\n    };\n    const handlePattern = (pat) => {\n        const end = pattern?.(pat);\n        for (const el of pat)\n            handleElement(el, 'placeholder');\n        end?.();\n    };\n    for (const decl of msg.declarations) {\n        const end = declaration?.(decl);\n        if (decl.value)\n            handleElement(decl.value, 'declaration');\n        end?.();\n    }\n    if (msg.type === 'message') {\n        handlePattern(msg.pattern);\n    }\n    else {\n        if (value)\n            for (const sel of msg.selectors)\n                value(sel, 'selector', 'arg');\n        for (const vari of msg.variants) {\n            const end = variant?.(vari);\n            if (key)\n                vari.keys.forEach(key);\n            handlePattern(vari.value);\n            end?.();\n        }\n    }\n}\n","import { MessageDataModelError } from \"../errors.js\";\nimport { visit } from \"./visit.js\";\n/**\n * Ensure that the `msg` data model is _valid_, calling `onError` on errors.\n * If `onError` is not defined, a {@link MessageDataModelError} will be thrown on error.\n *\n * Detects the following errors:\n *\n * - `'key-mismatch'`: **Variant Key Mismatch**<br>\n *   The number of keys on a _variant_ does not equal the number of _selectors_.\n *\n * - `'missing-fallback'`: **Missing Fallback Variant**<br>\n *   The message does not include a _variant_ with only catch-all keys.\n *\n * - `'missing-selector-annotation'`: **Missing Selector Annotation**<br>\n *   A _selector_ does not contains a _variable_ that directly or indirectly\n *   reference a _declaration_ with a _function_.\n *\n * - `'duplicate-declaration'`: **Duplicate Declaration**<br>\n *   A _variable_ appears in two _declarations_.\n *\n * - `'duplicate-variant'`: **Duplicate Variant**<br>\n *   The same list of _keys_ is used for more than one _variant_.\n *\n * @category Message Data Model\n * @returns The sets of runtime `functions` and `variables` used by the message.\n */\nexport function validate(msg, onError = (type, node) => {\n    throw new MessageDataModelError(type, node);\n}) {\n    let selectorCount = 0;\n    let missingFallback = null;\n    /** Tracks directly & indirectly annotated variables for `missing-selector-annotation` */\n    const annotated = new Set();\n    /** Tracks declared variables for `duplicate-declaration` */\n    const declared = new Set();\n    const functions = new Set();\n    const localVars = new Set();\n    const variables = new Set();\n    const variants = new Set();\n    let setArgAsDeclared = true;\n    visit(msg, {\n        declaration(decl) {\n            // Skip all ReservedStatement\n            if (!decl.name)\n                return undefined;\n            if (decl.value.functionRef ||\n                (decl.type === 'local' &&\n                    decl.value.arg?.type === 'variable' &&\n                    annotated.has(decl.value.arg.name))) {\n                annotated.add(decl.name);\n            }\n            if (decl.type === 'local')\n                localVars.add(decl.name);\n            setArgAsDeclared = decl.type === 'local';\n            return () => {\n                if (declared.has(decl.name))\n                    onError('duplicate-declaration', decl);\n                else\n                    declared.add(decl.name);\n            };\n        },\n        expression({ functionRef }) {\n            if (functionRef)\n                functions.add(functionRef.name);\n        },\n        value(value, context, position) {\n            if (value.type !== 'variable')\n                return;\n            variables.add(value.name);\n            switch (context) {\n                case 'declaration':\n                    if (position !== 'arg' || setArgAsDeclared) {\n                        declared.add(value.name);\n                    }\n                    break;\n                case 'selector':\n                    selectorCount += 1;\n                    missingFallback = value;\n                    if (!annotated.has(value.name)) {\n                        onError('missing-selector-annotation', value);\n                    }\n            }\n        },\n        variant(variant) {\n            const { keys } = variant;\n            if (keys.length !== selectorCount)\n                onError('key-mismatch', variant);\n            const strKeys = JSON.stringify(keys.map(key => (key.type === 'literal' ? key.value : 0)));\n            if (variants.has(strKeys))\n                onError('duplicate-variant', variant);\n            else\n                variants.add(strKeys);\n            missingFallback &&= keys.every(key => key.type === '*') ? null : variant;\n        }\n    });\n    if (missingFallback)\n        onError('missing-fallback', missingFallback);\n    for (const lv of localVars)\n        variables.delete(lv);\n    return { functions, variables };\n}\n","export const LRI = '\\u2066';\nexport const RLI = '\\u2067';\nexport const FSI = '\\u2068';\nexport const PDI = '\\u2069';\n// Data source: RECOMMENDED and LIMITED_USE scripts from\n// https://github.com/unicode-org/cldr/blob/1a914d1/common/properties/scriptMetadata.txt\nconst RTL = 'Adlm,Arab,Hebr,Mand,Nkoo,Rohg,Syrc,Thaa';\n/** Get a default text direction for `locale`. */\nexport function getLocaleDir(locale) {\n    if (locale) {\n        try {\n            if (typeof locale === 'string')\n                locale = new Intl.Locale(locale);\n            // @ts-expect-error -- New feature, API changed during Stage 3\n            const info = locale.getTextInfo?.() ?? locale.textInfo;\n            if (info?.direction)\n                return info.direction;\n            const script = locale.maximize().script;\n            if (script)\n                return RTL.includes(script) ? 'rtl' : 'ltr';\n        }\n        catch {\n            // Use 'auto' on error\n        }\n    }\n    return 'auto';\n}\n","/**\n * Utility function for custom functions.\n * Cast a value as a Boolean,\n * unwrapping objects using their `valueOf()` methods.\n * Also accepts `'true'` and `'false'`.\n * Throws a `RangeError` for invalid inputs.\n */\nexport function asBoolean(value) {\n    if (value && typeof value === 'object')\n        value = value.valueOf();\n    if (typeof value === 'boolean')\n        return value;\n    if (value && typeof value === 'object')\n        value = String(value);\n    if (value === 'true')\n        return true;\n    if (value === 'false')\n        return false;\n    throw new RangeError('Not a boolean');\n}\n/**\n * Utility function for custom functions.\n * Cast a value as a non-negative integer,\n * unwrapping objects using their `valueOf()` methods.\n * Also accepts JSON string reprentations of integers.\n * Throws a `RangeError` for invalid inputs.\n *\n * The default functions use this to validate _digit size options_.\n */\nexport function asPositiveInteger(value) {\n    if (value && typeof value === 'object')\n        value = value.valueOf();\n    if (value && typeof value === 'object')\n        value = String(value);\n    if (typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value)) {\n        value = Number(value);\n    }\n    if (typeof value === 'number' && value >= 0 && Number.isInteger(value)) {\n        return value;\n    }\n    throw new RangeError('Not a positive integer');\n}\n/**\n * Utility function for custom functions.\n * Cast a value as a string,\n * unwrapping objects using their `valueOf()` methods.\n * Throws a `RangeError` for invalid inputs.\n */\nexport function asString(value) {\n    if (value && typeof value === 'object')\n        value = value.valueOf();\n    if (typeof value === 'string')\n        return value;\n    if (value && typeof value === 'object')\n        return String(value);\n    throw new RangeError('Not a string');\n}\n","import { getLocaleDir } from \"../dir-utils.js\";\nimport { MessageFunctionError } from \"../errors.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\nexport function readNumericOperand(value) {\n    let options = undefined;\n    if (typeof value === 'object') {\n        const valueOf = value?.valueOf;\n        if (typeof valueOf === 'function') {\n            options = value.options;\n            value = valueOf.call(value);\n        }\n    }\n    if (typeof value === 'string') {\n        try {\n            value = JSON.parse(value);\n        }\n        catch {\n            // handled below\n        }\n    }\n    if (typeof value !== 'bigint' && typeof value !== 'number') {\n        throw new MessageFunctionError('bad-operand', 'Input is not numeric');\n    }\n    return { value, options };\n}\nexport function getMessageNumber(ctx, value, options, canSelect) {\n    let { dir, locales } = ctx;\n    // @ts-expect-error We may have been a bit naughty earlier.\n    if (options.useGrouping === 'never')\n        options.useGrouping = false;\n    if (canSelect &&\n        'select' in options &&\n        !ctx.literalOptionKeys.has('select')) {\n        ctx.onError('bad-option', 'The option select may only be set by a literal value');\n        canSelect = false;\n    }\n    let locale;\n    let nf;\n    let cat;\n    let str;\n    return {\n        type: 'number',\n        get dir() {\n            if (dir == null) {\n                locale ??= Intl.NumberFormat.supportedLocalesOf(locales, options)[0];\n                dir = getLocaleDir(locale);\n            }\n            return dir;\n        },\n        get options() {\n            return { ...options };\n        },\n        selectKey: canSelect\n            ? keys => {\n                let numVal = value;\n                if (options.style === 'percent') {\n                    if (typeof numVal === 'bigint')\n                        numVal *= 100n;\n                    else\n                        numVal *= 100;\n                }\n                const str = String(numVal);\n                if (keys.has(str))\n                    return str;\n                if (options.select === 'exact')\n                    return null;\n                const pluralOpt = options.select\n                    ? { ...options, select: undefined, type: options.select }\n                    : options;\n                // Intl.PluralRules needs a number, not bigint\n                cat ??= new Intl.PluralRules(locales, pluralOpt).select(Number(numVal));\n                return keys.has(cat) ? cat : null;\n            }\n            : undefined,\n        toParts() {\n            nf ??= new Intl.NumberFormat(locales, options);\n            const parts = nf.formatToParts(value);\n            locale ??= nf.resolvedOptions().locale;\n            dir ??= getLocaleDir(locale);\n            return dir === 'ltr' || dir === 'rtl'\n                ? [{ type: 'number', dir, locale, parts }]\n                : [{ type: 'number', locale, parts }];\n        },\n        toString() {\n            nf ??= new Intl.NumberFormat(locales, options);\n            str ??= nf.format(value);\n            return str;\n        },\n        valueOf: () => value\n    };\n}\nexport function number(ctx, exprOpt, operand) {\n    const input = readNumericOperand(operand);\n    const value = input.value;\n    const options = Object.assign({}, input.options, {\n        localeMatcher: ctx.localeMatcher,\n        style: 'decimal'\n    });\n    for (const [name, optval] of Object.entries(exprOpt)) {\n        if (optval === undefined)\n            continue;\n        try {\n            switch (name) {\n                case 'minimumIntegerDigits':\n                case 'minimumFractionDigits':\n                case 'maximumFractionDigits':\n                case 'minimumSignificantDigits':\n                case 'maximumSignificantDigits':\n                case 'roundingIncrement':\n                    // @ts-expect-error TS types don't know about roundingIncrement\n                    options[name] = asPositiveInteger(optval);\n                    break;\n                case 'roundingMode':\n                case 'roundingPriority':\n                case 'select': // Called 'type' in Intl.PluralRules\n                case 'signDisplay':\n                case 'trailingZeroDisplay':\n                case 'useGrouping':\n                    // @ts-expect-error Let Intl.NumberFormat construction fail\n                    options[name] = asString(optval);\n            }\n        }\n        catch {\n            ctx.onError('bad-option', `Value ${optval} is not valid for :number option ${name}`);\n        }\n    }\n    return getMessageNumber(ctx, value, options, true);\n}\nexport function integer(ctx, exprOpt, operand) {\n    const input = readNumericOperand(operand);\n    const value = Number.isFinite(input.value)\n        ? Math.round(input.value)\n        : input.value;\n    const options = Object.assign({}, input.options, {\n        //localeMatcher: ctx.localeMatcher,\n        maximumFractionDigits: 0,\n        minimumFractionDigits: undefined,\n        minimumSignificantDigits: undefined,\n        style: 'decimal'\n    });\n    for (const [name, optval] of Object.entries(exprOpt)) {\n        if (optval === undefined)\n            continue;\n        try {\n            switch (name) {\n                case 'minimumIntegerDigits':\n                case 'maximumSignificantDigits':\n                    options[name] = asPositiveInteger(optval);\n                    break;\n                case 'select': // Called 'type' in Intl.PluralRules\n                case 'signDisplay':\n                case 'useGrouping':\n                    // @ts-expect-error Let Intl.NumberFormat construction fail\n                    options[name] = asString(optval);\n            }\n        }\n        catch {\n            ctx.onError('bad-option', `Value ${optval} is not valid for :integer option ${name}`);\n        }\n    }\n    return getMessageNumber(ctx, value, options, true);\n}\n","import { MessageFunctionError } from \"../errors.js\";\nimport { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * `currency` accepts as input numerical values as well as\n * objects wrapping a numerical value that also include a `currency` property.\n *\n * @beta\n */\nexport function currency(ctx, exprOpt, operand) {\n    const input = readNumericOperand(operand);\n    const options = Object.assign({}, input.options, {\n        localeMatcher: ctx.localeMatcher,\n        style: 'currency'\n    });\n    for (const [name, optval] of Object.entries(exprOpt)) {\n        if (optval === undefined)\n            continue;\n        try {\n            switch (name) {\n                case 'currency':\n                case 'currencySign':\n                case 'roundingMode':\n                case 'roundingPriority':\n                case 'trailingZeroDisplay':\n                case 'useGrouping':\n                    // @ts-expect-error Let Intl.NumberFormat construction fail\n                    options[name] = asString(optval);\n                    break;\n                case 'minimumIntegerDigits':\n                case 'minimumSignificantDigits':\n                case 'maximumSignificantDigits':\n                case 'roundingIncrement':\n                    // @ts-expect-error TS types don't know about roundingIncrement\n                    options[name] = asPositiveInteger(optval);\n                    break;\n                case 'currencyDisplay': {\n                    const strval = asString(optval);\n                    if (strval === 'never') {\n                        ctx.onError('unsupported-operation', 'Currency display \"never\" is not yet supported');\n                    }\n                    else {\n                        // @ts-expect-error Let Intl.NumberFormat construction fail\n                        options[name] = strval;\n                    }\n                    break;\n                }\n                case 'fractionDigits': {\n                    const strval = asString(optval);\n                    if (strval === 'auto') {\n                        options.minimumFractionDigits = undefined;\n                        options.maximumFractionDigits = undefined;\n                    }\n                    else {\n                        const numval = asPositiveInteger(strval);\n                        options.minimumFractionDigits = numval;\n                        options.maximumFractionDigits = numval;\n                    }\n                    break;\n                }\n            }\n        }\n        catch {\n            ctx.onError('bad-option', `Value ${optval} is not valid for :currency option ${name}`);\n        }\n    }\n    if (!options.currency) {\n        throw new MessageFunctionError('bad-operand', 'A currency code is required for :currency');\n    }\n    return getMessageNumber(ctx, input.value, options, false);\n}\n","import { getLocaleDir } from \"../dir-utils.js\";\nimport { MessageFunctionError } from \"../errors.js\";\nimport { asBoolean, asString } from \"./utils.js\";\nconst dateFieldsValues = new Set([\n    'weekday',\n    'day-weekday',\n    'month-day',\n    'month-day-weekday',\n    'year-month-day',\n    'year-month-day-weekday'\n]);\nconst dateLengthValues = new Set(['long', 'medium', 'short']);\nconst timePrecisionValues = new Set(['hour', 'minute', 'second']);\nconst timeZoneStyleValues = new Set(['long', 'short']);\n/**\n * The function `:datetime` is used to format a date/time value.\n * Its formatted result will always include both the date and the time, and optionally a timezone.\n *\n * @beta\n */\nexport const datetime = (ctx, options, operand) => dateTimeImplementation('datetime', ctx, options, operand);\n/**\n * The function `:date` is used to format the date portion of date/time values.\n *\n * @beta\n */\nexport const date = (ctx, options, operand) => dateTimeImplementation('date', ctx, options, operand);\n/**\n * The function `:time` is used to format the time portion of date/time values.\n * Its formatted result will always include the time, and optionally a timezone.\n *\n * @beta\n */\nexport const time = (ctx, options, operand) => dateTimeImplementation('time', ctx, options, operand);\nfunction dateTimeImplementation(functionName, ctx, exprOpt, operand) {\n    const options = {\n        localeMatcher: ctx.localeMatcher\n    };\n    let value = operand;\n    if (typeof value === 'object' && value !== null) {\n        const opt = value.options;\n        if (opt) {\n            options.calendar = opt.calendar;\n            if (functionName !== 'date')\n                options.hour12 = opt.hour12;\n            options.timeZone = opt.timeZone;\n        }\n        if (typeof value.valueOf === 'function')\n            value = value.valueOf();\n    }\n    switch (typeof value) {\n        case 'number':\n        case 'string':\n            value = new Date(value);\n    }\n    if (!(value instanceof Date) || isNaN(value.getTime())) {\n        throw new MessageFunctionError('bad-operand', 'Input is not a valid date');\n    }\n    // Override options\n    if (exprOpt.calendar !== undefined) {\n        try {\n            options.calendar = asString(exprOpt.calendar);\n        }\n        catch {\n            ctx.onError('bad-option', `Invalid :${functionName} calendar option value`);\n        }\n    }\n    if (exprOpt.hour12 !== undefined && functionName !== 'date') {\n        try {\n            options.hour12 = asBoolean(exprOpt.hour12);\n        }\n        catch {\n            ctx.onError('bad-option', `Invalid :${functionName} hour12 option value`);\n        }\n    }\n    if (exprOpt.timeZone !== undefined) {\n        let tz;\n        try {\n            tz = asString(exprOpt.timeZone);\n        }\n        catch {\n            ctx.onError('bad-option', `Invalid :${functionName} timeZone option value`);\n        }\n        if (tz === 'input') {\n            if (options.timeZone === undefined) {\n                ctx.onError('bad-operand', `Missing input timeZone value for :${functionName}`);\n            }\n        }\n        else if (tz !== undefined) {\n            if (options.timeZone !== undefined && tz !== options.timeZone) {\n                // Use fallback value for expression\n                throw new MessageFunctionError('bad-option', 'Time zone conversion is not supported');\n            }\n            options.timeZone = tz;\n        }\n    }\n    // Date formatting options\n    if (functionName !== 'time') {\n        const dfName = functionName === 'date' ? 'fields' : 'dateFields';\n        const dlName = functionName === 'date' ? 'length' : 'dateLength';\n        const dateFieldsValue = readStringOption(ctx, exprOpt, dfName, dateFieldsValues) ??\n            'year-month-day';\n        const dateLength = readStringOption(ctx, exprOpt, dlName, dateLengthValues);\n        const dateFields = new Set(dateFieldsValue.split('-'));\n        if (dateFields.has('year'))\n            options.year = 'numeric';\n        if (dateFields.has('month')) {\n            options.month =\n                dateLength === 'long'\n                    ? 'long'\n                    : dateLength === 'short'\n                        ? 'numeric'\n                        : 'short';\n        }\n        if (dateFields.has('day'))\n            options.day = 'numeric';\n        if (dateFields.has('weekday')) {\n            options.weekday = dateLength === 'long' ? 'long' : 'short';\n        }\n    }\n    // Time formatting options\n    if (functionName !== 'date') {\n        const tpName = functionName === 'time' ? 'precision' : 'timePrecision';\n        switch (readStringOption(ctx, exprOpt, tpName, timePrecisionValues)) {\n            case 'hour':\n                options.hour = 'numeric';\n                break;\n            case 'second':\n                options.hour = 'numeric';\n                options.minute = 'numeric';\n                options.second = 'numeric';\n                break;\n            default:\n                options.hour = 'numeric';\n                options.minute = 'numeric';\n        }\n        options.timeZoneName = readStringOption(ctx, exprOpt, 'timeZoneStyle', timeZoneStyleValues);\n    }\n    // Resolved value\n    const dtf = new Intl.DateTimeFormat(ctx.locales, options);\n    let dir = ctx.dir;\n    let locale;\n    let str;\n    return {\n        type: 'datetime',\n        get dir() {\n            if (dir == null) {\n                locale ??= dtf.resolvedOptions().locale;\n                dir = getLocaleDir(locale);\n            }\n            return dir;\n        },\n        get options() {\n            return { ...options };\n        },\n        toParts() {\n            const parts = dtf.formatToParts(value);\n            locale ??= dtf.resolvedOptions().locale;\n            dir ??= getLocaleDir(locale);\n            return dir === 'ltr' || dir === 'rtl'\n                ? [{ type: 'datetime', dir, locale, parts }]\n                : [{ type: 'datetime', locale, parts }];\n        },\n        toString() {\n            str ??= dtf.format(value);\n            return str;\n        },\n        valueOf: () => value\n    };\n}\nfunction readStringOption(ctx, options, name, allowed) {\n    const value = options[name];\n    if (value !== undefined) {\n        try {\n            const str = asString(value);\n            if (allowed && !allowed.has(str))\n                throw Error();\n            return str;\n        }\n        catch {\n            ctx.onError('bad-option', `Invalid value for ${name} option`);\n        }\n    }\n    return undefined;\n}\n","import { MessageFunctionError } from \"../errors.js\";\nimport { number, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger } from \"./utils.js\";\n/**\n * `offset` accepts a numeric value as input and adds or subtracts an integer value from it\n *\n * @beta\n */\nexport function offset(ctx, exprOpt, operand) {\n    let { value, options } = readNumericOperand(operand);\n    let add;\n    try {\n        add = 'add' in exprOpt ? asPositiveInteger(exprOpt.add) : -1;\n    }\n    catch {\n        throw new MessageFunctionError('bad-option', `Value ${exprOpt.add} is not valid for :offset option add`);\n    }\n    let sub;\n    try {\n        sub = 'subtract' in exprOpt ? asPositiveInteger(exprOpt.subtract) : -1;\n    }\n    catch {\n        throw new MessageFunctionError('bad-option', `Value ${exprOpt.subtract} is not valid for :offset option subtract`);\n    }\n    if (add < 0 === sub < 0) {\n        const msg = 'Exactly one of \"add\" or \"subtract\" is required as an :offset option';\n        throw new MessageFunctionError('bad-option', msg);\n    }\n    const delta = add < 0 ? -sub : add;\n    if (typeof value === 'number')\n        value += delta;\n    else\n        value += BigInt(delta);\n    return number(ctx, {}, { valueOf: () => value, options });\n}\n","import { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * The function `:percent` is a selector and formatter for percent values.\n *\n * @beta\n */\nexport function percent(ctx, exprOpt, operand) {\n    const input = readNumericOperand(operand);\n    const options = Object.assign({}, input.options, {\n        localeMatcher: ctx.localeMatcher,\n        style: 'percent'\n    });\n    for (const [name, optval] of Object.entries(exprOpt)) {\n        if (optval === undefined)\n            continue;\n        try {\n            switch (name) {\n                case 'roundingMode':\n                case 'roundingPriority':\n                case 'signDisplay':\n                case 'trailingZeroDisplay':\n                case 'useGrouping':\n                    // @ts-expect-error Let Intl.NumberFormat construction fail\n                    options[name] = asString(optval);\n                    break;\n                case 'minimumFractionDigits':\n                case 'maximumFractionDigits':\n                case 'minimumSignificantDigits':\n                case 'maximumSignificantDigits':\n                    options[name] = asPositiveInteger(optval);\n                    break;\n            }\n        }\n        catch {\n            ctx.onError('bad-option', `Value ${optval} is not valid for :percent option ${name}`);\n        }\n    }\n    return getMessageNumber(ctx, input.value, options, true);\n}\n","export function string(ctx, _options, operand) {\n    const str = operand === undefined ? '' : String(operand);\n    const selStr = str.normalize();\n    return {\n        type: 'string',\n        dir: ctx.dir ?? 'auto',\n        selectKey: keys => (keys.has(selStr) ? selStr : null),\n        toParts() {\n            const { dir } = ctx;\n            const locale = ctx.locales[0];\n            return dir === 'ltr' || dir === 'rtl'\n                ? [{ type: 'string', dir, locale, value: str }]\n                : [{ type: 'string', locale, value: str }];\n        },\n        toString: () => str,\n        valueOf: () => str\n    };\n}\n","import { MessageError, MessageFunctionError } from \"../errors.js\";\nimport { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * `unit` accepts as input numerical values as well as\n * objects wrapping a numerical value that also include a `unit` property.\n *\n * @beta\n */\nexport function unit(ctx, exprOpt, operand) {\n    const input = readNumericOperand(operand);\n    const options = Object.assign({}, input.options, {\n        localeMatcher: ctx.localeMatcher,\n        style: 'unit'\n    });\n    for (const [name, optval] of Object.entries(exprOpt)) {\n        if (optval === undefined)\n            continue;\n        try {\n            switch (name) {\n                case 'signDisplay':\n                case 'roundingMode':\n                case 'roundingPriority':\n                case 'trailingZeroDisplay':\n                case 'unit':\n                case 'unitDisplay':\n                case 'useGrouping':\n                    // @ts-expect-error Let Intl.NumberFormat construction fail\n                    options[name] = asString(optval);\n                    break;\n                case 'minimumIntegerDigits':\n                case 'minimumFractionDigits':\n                case 'maximumFractionDigits':\n                case 'minimumSignificantDigits':\n                case 'maximumSignificantDigits':\n                case 'roundingIncrement':\n                    // @ts-expect-error TS types don't know about roundingIncrement\n                    options[name] = asPositiveInteger(optval);\n                    break;\n            }\n        }\n        catch (error) {\n            if (error instanceof MessageError) {\n                ctx.onError(error);\n            }\n            else {\n                ctx.onError('bad-option', `Value ${optval} is not valid for :currency option ${name}`);\n            }\n        }\n    }\n    if (!options.unit) {\n        throw new MessageFunctionError('bad-operand', 'A unit identifier is required for :unit');\n    }\n    return getMessageNumber(ctx, input.value, options, false);\n}\n","/**\n * Implementations for :number, :string, and other default functions,\n * along with some utilities for building custom function handlers.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const mf = new MessageFormat(locale, msgSrc, { functions: DraftFunctions });\n * ```\n *\n * @module\n */\nexport { getLocaleDir } from \"../dir-utils.js\";\nexport { asBoolean, asPositiveInteger, asString } from \"./utils.js\";\nimport { currency } from \"./currency.js\";\nimport { date, datetime, time } from \"./datetime.js\";\nimport { integer, number } from \"./number.js\";\nimport { offset } from \"./offset.js\";\nimport { percent } from \"./percent.js\";\nimport { string } from \"./string.js\";\nimport { unit } from \"./unit.js\";\n/**\n * Functions classified as REQUIRED by the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48.2 MessageFormat specification}.\n */\nexport let DefaultFunctions = {\n    /**\n     * Supports formatting as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-currency-function | :currency function}.\n     *\n     * The `operand` must be a number, BigInt, or string representing a JSON number,\n     * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n     *\n     * The `currency` option must be provided by either the operand's `options` or the `exprOpt` expression options.\n     */\n    currency,\n    /**\n     * Supports formatting and selection as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-integer-function | :integer function}.\n     *\n     * The `operand` must be a number, BigInt, or string representing a JSON number,\n     * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n     */\n    integer,\n    /**\n     * Supports formatting and selection as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-number-function | :number function}.\n     *\n     * The `operand` must be a number, BigInt, or string representing a JSON number,\n     * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n     */\n    number,\n    /**\n     * Supports formatting and selection as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-offset-function | :offset function}.\n     *\n     * The `operand` must be a number, BigInt, or string representing a JSON number,\n     * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n     */\n    offset,\n    /**\n     * Supports formatting as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-percent-function | :percent function}.\n     *\n     * The `operand` must be a number, BigInt, or string representing a JSON number,\n     * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n     */\n    percent,\n    /**\n     * Supports formatting and selection as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-string-function | :string function}.\n     *\n     * The `operand` must be a stringifiable value.\n     * An `undefined` value is resolved as an empty string.\n     */\n    string\n};\nDefaultFunctions = Object.freeze(Object.assign(Object.create(null), DefaultFunctions));\n/**\n * Functions classified as DRAFT by the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48.2 MessageFormat specification}.\n *\n * These are liable to change, and are **_not_** covered by any stability guarantee.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const mf = new MessageFormat(locale, msgsrc, { functions: DraftFunctions });\n * ```\n *\n * @beta\n */\nexport let DraftFunctions = {\n    /**\n     * Supports formatting as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-date-function | :date function}.\n     *\n     * The `operand` must be a Date, number, or string representing a date,\n     * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n     */\n    date,\n    /**\n     * Supports formatting as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-datetime-function | :datetime function}.\n     *\n     * The `operand` must be a Date, number, or string representing a date,\n     * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n     */\n    datetime,\n    /**\n     * Supports formatting as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-time-function | :time function}.\n     *\n     * The `operand` must be a Date, number, or string representing a date,\n     * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n     */\n    time,\n    /**\n     * Supports formatting as defined in LDML 48.2 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-unit-function | :unit function}.\n     *\n     * The `operand` must be a number, BigInt, or string representing a JSON number,\n     * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n     *\n     * The `unit` option must be provided by either the operand's `options` or the `exprOpt` expression options.\n     */\n    unit\n};\nDraftFunctions = Object.freeze(Object.assign(Object.create(null), DraftFunctions));\n","export const BIDI_ISOLATE = Symbol('bidi-isolate');\n","export const fallback = (source = '�') => ({\n    type: 'fallback',\n    source,\n    toParts: () => [{ type: 'fallback', source }],\n    toString: () => `{${source}}`\n});\n","export const unknown = (source, input) => ({\n    type: 'unknown',\n    source,\n    dir: 'auto',\n    toParts: () => [{ type: 'unknown', value: input }],\n    toString: () => String(input),\n    valueOf: () => input\n});\n","import { MessageFunctionError } from \"../errors.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport class MessageFunctionContext {\n    #ctx;\n    #litKeys;\n    #source;\n    dir;\n    id;\n    constructor(ctx, source, options) {\n        this.#ctx = ctx;\n        this.#source = source;\n        this.dir = undefined;\n        const dirOpt = options && Object.hasOwn(options, 'u:dir') ? options['u:dir'] : undefined;\n        if (dirOpt) {\n            const dir = String(resolveValue(ctx, dirOpt));\n            if (dir === 'ltr' || dir === 'rtl' || dir === 'auto') {\n                this.dir = dir;\n            }\n            else if (dir !== 'inherit') {\n                const error = new MessageFunctionError('bad-option', 'Unsupported value for u:dir option');\n                error.source = getValueSource(dirOpt);\n                ctx.onError(error);\n            }\n        }\n        const idOpt = options && Object.hasOwn(options, 'u:id') ? options['u:id'] : undefined;\n        this.id = idOpt ? String(resolveValue(ctx, idOpt)) : undefined;\n        if (options) {\n            this.#litKeys = new Set();\n            for (const [key, value] of Object.entries(options)) {\n                if (value.type === 'literal')\n                    this.#litKeys.add(key);\n            }\n        }\n    }\n    get literalOptionKeys() {\n        return new Set(this.#litKeys);\n    }\n    get localeMatcher() {\n        return this.#ctx.localeMatcher;\n    }\n    get locales() {\n        return this.#ctx.locales.map(String);\n    }\n    onError(error, message) {\n        let mfError;\n        if (error instanceof MessageFunctionError) {\n            mfError = error;\n        }\n        else if (typeof error === 'string' && typeof message === 'string') {\n            mfError = new MessageFunctionError(error, message);\n        }\n        else {\n            mfError = new MessageFunctionError('function-error', String(error));\n            mfError.cause = error;\n        }\n        mfError.source = this.#source;\n        this.#ctx.onError(mfError);\n    }\n}\n","import { MessageError, MessageResolutionError } from \"../errors.js\";\nimport { fallback } from \"../functions/fallback.js\";\nimport { BIDI_ISOLATE } from \"../message-value.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport function resolveFunctionRef(ctx, operand, { name, options }) {\n    const fnSource = `:${name}`;\n    const source = getValueSource(operand) ?? fnSource;\n    try {\n        const fnInput = operand ? [resolveValue(ctx, operand)] : [];\n        const rf = ctx.functions[name];\n        if (!rf) {\n            throw new MessageResolutionError('unknown-function', `Unknown function ${fnSource}`, source);\n        }\n        const msgCtx = new MessageFunctionContext(ctx, source, options);\n        const opt = resolveOptions(ctx, options);\n        const res = rf(msgCtx, opt, ...fnInput);\n        if (res === null ||\n            typeof res !== 'object' ||\n            typeof res.type !== 'string') {\n            throw new MessageResolutionError('bad-function-result', `Function ${fnSource} did not return a MessageValue`, source);\n        }\n        const override = { source };\n        if (msgCtx.dir) {\n            override.dir = msgCtx.dir;\n            override[BIDI_ISOLATE] = true;\n        }\n        if (msgCtx.id && typeof res.toParts === 'function') {\n            override.toParts = () => {\n                const parts = res.toParts();\n                for (const part of parts)\n                    part.id = msgCtx.id;\n                return parts;\n            };\n        }\n        return { ...res, ...override };\n    }\n    catch (error) {\n        ctx.onError(error instanceof MessageError\n            ? error\n            : new MessageResolutionError('bad-function-result', String(error), source, error));\n        return fallback(source);\n    }\n}\nfunction resolveOptions(ctx, options) {\n    const opt = Object.create(null);\n    if (options) {\n        for (const [name, value] of Object.entries(options)) {\n            if (!name.startsWith('u:'))\n                opt[name] = resolveValue(ctx, value);\n        }\n    }\n    return opt;\n}\n","import { string } from \"../functions/string.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { resolveFunctionRef } from \"./resolve-function-ref.js\";\nimport { resolveVariableRef } from \"./resolve-variable.js\";\nexport function resolveExpression(ctx, { arg, functionRef }) {\n    if (functionRef) {\n        return resolveFunctionRef(ctx, arg, functionRef);\n    }\n    switch (arg?.type) {\n        case 'literal': {\n            const source = `|${arg.value}|`;\n            const msgCtx = new MessageFunctionContext(ctx, source);\n            const msgStr = string(msgCtx, {}, arg.value);\n            msgStr.source = source;\n            return msgStr;\n        }\n        case 'variable':\n            return resolveVariableRef(ctx, arg);\n        default:\n            // @ts-expect-error - should never happen\n            throw new Error(`Unsupported expression: ${arg?.type}`);\n    }\n}\n","import { MessageResolutionError } from \"../errors.js\";\nimport { fallback } from \"../functions/fallback.js\";\nimport { unknown } from \"../functions/unknown.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { resolveExpression } from \"./resolve-expression.js\";\n/**\n * Declarations aren't resolved until they're requierd,\n * and their resolution order matters for variable resolution.\n * This internal class is used to store any required data,\n * and to allow for `instanceof` detection.\n *\n * @internal\n */\nexport class UnresolvedExpression {\n    expression;\n    scope;\n    constructor(expression, scope) {\n        this.expression = expression;\n        this.scope = scope;\n    }\n}\nconst isScope = (scope) => scope !== null && (typeof scope === 'object' || typeof scope === 'function');\n/**\n * Looks for the longest matching `.` delimited starting substring of name.\n * @returns `undefined` if value not found\n */\nfunction getValue(scope, name) {\n    if (isScope(scope)) {\n        if (name in scope)\n            return scope[name];\n        const parts = name.split('.');\n        for (let i = parts.length - 1; i > 0; --i) {\n            const head = parts.slice(0, i).join('.');\n            if (head in scope) {\n                const tail = parts.slice(i).join('.');\n                return getValue(scope[head], tail);\n            }\n        }\n        for (const [key, value] of Object.entries(scope)) {\n            if (key.normalize() === name)\n                return value;\n        }\n    }\n    return undefined;\n}\n/**\n * Get the raw value of a variable.\n * Resolves declarations as necessary\n *\n * @internal\n * @returns `unknown` or `any` for input values;\n *   `MessageValue` for `.input` and `.local` declaration values.\n */\nexport function lookupVariableRef(ctx, { name }) {\n    const value = getValue(ctx.scope, name);\n    if (value === undefined) {\n        const source = '$' + name;\n        const msg = `Variable not available: ${source}`;\n        ctx.onError(new MessageResolutionError('unresolved-variable', msg, source));\n    }\n    else if (value instanceof UnresolvedExpression) {\n        const local = resolveExpression(value.scope ? { ...ctx, scope: value.scope } : ctx, value.expression);\n        ctx.scope[name] = local;\n        ctx.localVars.add(local);\n        return local;\n    }\n    return value;\n}\nexport function resolveVariableRef(ctx, ref) {\n    const source = '$' + ref.name;\n    const value = lookupVariableRef(ctx, ref);\n    if (value === undefined)\n        return fallback(source);\n    let type = typeof value;\n    if (type === 'object') {\n        const mv = value;\n        if (mv.type === 'fallback')\n            return fallback(source);\n        if (ctx.localVars.has(mv)) {\n            mv.source = source;\n            return mv;\n        }\n        if (value instanceof Number)\n            type = 'number';\n        else if (value instanceof String)\n            type = 'string';\n    }\n    let msgFn;\n    switch (type) {\n        case 'bigint':\n        case 'number':\n            msgFn = ctx.functions.number;\n            break;\n        case 'string':\n            msgFn = ctx.functions.string;\n            break;\n        default:\n            return unknown(source, value);\n    }\n    const msgCtx = new MessageFunctionContext(ctx, source);\n    const mv = msgFn(msgCtx, {}, value);\n    mv.source = source;\n    return mv;\n}\n","import { lookupVariableRef } from \"./resolve-variable.js\";\nexport function resolveValue(ctx, value) {\n    switch (value.type) {\n        case 'literal':\n            return value.value;\n        case 'variable':\n            return lookupVariableRef(ctx, value);\n        default:\n            // @ts-expect-error - should never happen\n            throw new Error(`Unsupported value: ${value.type}`);\n    }\n}\nexport function getValueSource(value) {\n    switch (value?.type) {\n        case 'literal':\n            return ('|' + value.value.replaceAll('\\\\', '\\\\\\\\').replaceAll('|', '\\\\|') + '|');\n        case 'variable':\n            return '$' + value.name;\n        default:\n            return undefined;\n    }\n}\n","import { MessageFunctionError } from \"../errors.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport function formatMarkup(ctx, { kind, name, options }) {\n    const part = { type: 'markup', kind, name };\n    const entries = options ? Object.entries(options) : null;\n    if (entries?.length) {\n        part.options = {};\n        for (const [name, value] of entries) {\n            if (name === 'u:dir') {\n                const error = new MessageFunctionError('bad-option', `The option ${name} is not valid for markup`);\n                error.source = getValueSource(value);\n                ctx.onError(error);\n            }\n            else {\n                let rv = resolveValue(ctx, value);\n                if (typeof rv === 'object' && typeof rv?.valueOf === 'function') {\n                    rv = rv.valueOf();\n                }\n                if (name === 'u:id')\n                    part.id = String(rv);\n                else\n                    part.options[name] = rv;\n            }\n        }\n    }\n    return part;\n}\n","import { MessageResolutionError } from \"./errors.js\";\nimport { resolveVariableRef } from \"./resolve/resolve-variable.js\";\nexport function selectPattern(context, message) {\n    if (message.type === 'message')\n        return message.pattern;\n    // message.type === 'select'\n    const ctx = message.selectors.map(sel => {\n        const selector = resolveVariableRef(context, sel);\n        let selectKey;\n        if (typeof selector.selectKey === 'function') {\n            selectKey = selector.selectKey.bind(selector);\n        }\n        else {\n            const msg = 'Selector does not support selection';\n            context.onError(new MessageResolutionError('bad-selector', msg, selector.source));\n            selectKey = () => null;\n        }\n        return {\n            selectKey,\n            source: selector.source,\n            best: null,\n            keys: null\n        };\n    });\n    let candidates = message.variants;\n    loop: for (let i = 0; i < ctx.length; ++i) {\n        const sc = ctx[i];\n        if (!sc.keys) {\n            sc.keys = new Set();\n            for (const { keys } of candidates) {\n                const key = keys[i];\n                if (!key)\n                    break loop; // key-mismatch error\n                if (key.type !== '*')\n                    sc.keys.add(key.value);\n            }\n        }\n        try {\n            sc.best = sc.keys.size ? sc.selectKey(sc.keys) : null;\n        }\n        catch (error) {\n            const msg = 'Selection failed';\n            context.onError(new MessageResolutionError('bad-selector', msg, sc.source, error));\n            sc.selectKey = () => null;\n            sc.best = null;\n        }\n        // Leave out all candidate variants that aren't the best,\n        // or only the catchall ones, if nothing else matches.\n        candidates = candidates.filter(v => {\n            const k = v.keys[i];\n            if (k.type === '*')\n                return sc.best == null;\n            return sc.best === k.value;\n        });\n        // If we've run out of candidates,\n        // drop the previous best key of the preceding selector,\n        // reset all subsequent key sets,\n        // and restart the loop.\n        if (candidates.length === 0) {\n            if (i === 0)\n                break; // No match; should not happen\n            const prev = ctx[i - 1];\n            if (prev.best == null)\n                prev.keys?.clear();\n            else\n                prev.keys?.delete(prev.best);\n            for (let j = i; j < ctx.length; ++j)\n                ctx[j].keys = null;\n            candidates = message.variants;\n            i = -1;\n        }\n    }\n    const res = candidates[0];\n    if (!res) {\n        // This should not be possible with a valid message.\n        const msg = 'No variant was selected!?';\n        context.onError(new MessageResolutionError('no-match', msg, '.match'));\n        return [];\n    }\n    return res.value;\n}\n","import { MessageFormat } from 'messageformat';\nimport { DefaultFunctions, DraftFunctions, getLocaleDir } from 'messageformat/functions';\n\n// Polyfill\nIntl.MessageFormat ??= MessageFormat;\n\n/**\n * A date/time format preset, extending `Intl.DateTimeFormatOptions` with a `locale` override that\n * applies whenever the preset is selected.\n * @typedef {Intl.DateTimeFormatOptions & { locale?: string }} DateFormatPreset\n */\n\n/**\n * A number format preset, extending `Intl.NumberFormatOptions` with a `locale` override that\n * applies whenever the preset is selected.\n * @typedef {Intl.NumberFormatOptions & { locale?: string }} NumberFormatPreset\n */\n\n/**\n * Custom format presets. Within each group, the reserved `_default` key defines the preset used\n * when no `format` option is given, replacing the bare `Intl` defaults. It also applies to the\n * matching MF2 placeholders in messages, where it likewise replaces the options the placeholder\n * resolved. Any other key defines a named preset selectable with the `format` option.\n * @typedef {object} Formats\n * @property {Record<string, NumberFormatPreset>} [number] Custom number format presets.\n * @property {Record<string, DateFormatPreset>} [date] Custom date format presets.\n * @property {Record<string, DateFormatPreset>} [time] Custom time format presets.\n * @property {Record<string, DateFormatPreset>} [datetime] Custom date/time format presets. Used\n * only by the MF2 `:datetime` function; there is no standalone `datetime()` formatter.\n */\n\n/**\n * Per-call format overrides for the MF2 placeholders in a single message. Each entry is either the\n * name of a preset (custom or built-in) or an inline preset object.\n * @typedef {object} MessageFormats\n * @property {string | NumberFormatPreset} [number] Applied to `:number` and `:integer`.\n * @property {string | DateFormatPreset} [date] Applied to `:date`.\n * @property {string | DateFormatPreset} [time] Applied to `:time`.\n * @property {string | DateFormatPreset} [datetime] Applied to `:datetime`.\n */\n\n/**\n * A custom MF2 function handler, registered with `registerMessageFunction()` and callable from\n * messages as `:name`.\n * @callback MessageFunction\n * @param {any} context MF2 function context, carrying `locales`, `localeMatcher` and `onError`.\n * @param {Record<string, unknown>} options Options given in the message expression, e.g.\n * `weekday=long`.\n * @param {unknown} [operand] The value the function was applied to.\n * @returns {any} A message value exposing at least `toString()`.\n * @see https://messageformat.github.io/modules/messageformat_functions.html\n */\n\n/**\n * @callback MissingKeyHandler\n * @param {string} key The missing message key.\n * @param {string} locale The active locale.\n * @param {string | undefined} defaultValue The default value passed to `format()`, if any.\n * @returns {string | void} A replacement string, or `undefined` to fall through to the default.\n */\n\n/**\n * @typedef {object} MessageObject\n * @property {string} id Message key.\n * @property {Record<string, any>} [values] Variables to interpolate into the message.\n * @property {string} [locale] Locale override for this call.\n * @property {string} [default] Fallback string if the key is not found.\n * @property {MessageFormats} [formats] Format overrides for the MF2 placeholders in this message.\n */\n\n/**\n * Date/time formatting options, extending `Intl.DateTimeFormatOptions` with `locale` and `format`\n * overrides.\n * @typedef {Intl.DateTimeFormatOptions & { locale?: string, format?: string }} DateFormatOptions\n */\n\n/**\n * Number formatting options, extending `Intl.NumberFormatOptions` with `locale` and `format`\n * overrides.\n * @typedef {Intl.NumberFormatOptions & { locale?: string, format?: string }} NumberFormatOptions\n */\n\n// --- State ---\n\n/** @type {string} */\nlet _locale = $state('');\n/**\n * The locale last passed to `locale.set()`, before negotiation. Kept so the active locale can be\n * negotiated again as more locales are registered.\n */\nlet requestedLocale = '';\n/**\n * All registered locales.\n * @type {string[]}\n */\nconst locales = $state([]);\n/**\n * All registered resources.\n * @type {Record<string, Record<string, Intl.MessageFormat>>}\n */\nconst dictionary = $state({});\n/**\n * Whether locale messages are currently being loaded. Returns `true` after a locale is set but\n * before its messages are available.\n * @returns {boolean} `true` if messages are pending for the current locale, `false` otherwise.\n */\nconst isLoading = () => !!_locale && !dictionary[_locale];\n\n// --- Configuration state ---\n\n/** Locale to fall back to when the active locale has no entry for a key. */\n// eslint-disable-next-line padding-line-between-statements\nlet fallbackLocale = '';\n/**\n * Negotiated fallback locale — pre-computed from `fallbackLocale` against the registered locales.\n * Cached to avoid repeated `Intl.Locale` construction on every `format()` call.\n */\nlet _resolvedFallback = '';\n/** @type {MissingKeyHandler | undefined} */\nlet missingMessageHandler;\n/** @type {Formats} */\nlet customFormats = {};\n/**\n * Custom MF2 functions, keyed by the name used in messages. Read when a message is compiled, so\n * entries added after `addMessages()` do not apply to messages already registered.\n * @type {Record<string, MessageFunction>}\n */\nlet customFunctions = {};\n/**\n * Format overrides for the MF2 placeholders of the message currently being formatted. MF2\n * formatting is synchronous, so this is set for the duration of one {@link format} call and cleared\n * again before it returns.\n * @type {MessageFormats | undefined}\n */\nlet messageFormats;\n\n// --- Validation ---\n\n/**\n * Throw a `TypeError` if the given value is not a non-empty string.\n * @param {string} label Argument label used in the error message, e.g. `addMessages: localeCode`.\n * @param {unknown} value Value to check.\n * @throws {TypeError} If `value` is not a non-empty string.\n */\nconst assertNonEmptyString = (label, value) => {\n  if (typeof value !== 'string' || !value) {\n    throw new TypeError(`${label} must be a non-empty string (got ${JSON.stringify(value)})`);\n  }\n};\n\n/**\n * Throw a `TypeError` if the given value is not a string. Unlike {@link assertNonEmptyString}, an\n * empty string is accepted.\n * @param {string} label Argument label used in the error message.\n * @param {unknown} value Value to check.\n * @throws {TypeError} If `value` is not a string.\n */\nconst assertString = (label, value) => {\n  if (typeof value !== 'string') {\n    throw new TypeError(`${label} must be a string (got ${typeof value})`);\n  }\n};\n\n/**\n * Throw a `TypeError` if the given value is not a function.\n * @param {string} label Argument label used in the error message.\n * @param {unknown} value Value to check.\n * @throws {TypeError} If `value` is not a function.\n */\nconst assertFunction = (label, value) => {\n  if (typeof value !== 'function') {\n    throw new TypeError(`${label} must be a function (got ${typeof value})`);\n  }\n};\n\n/**\n * Throw a `TypeError` if the given value is not a `RegExp`.\n * @param {string} label Argument label used in the error message.\n * @param {unknown} value Value to check.\n * @throws {TypeError} If `value` is not a `RegExp`.\n */\nconst assertRegExp = (label, value) => {\n  if (!(value instanceof RegExp)) {\n    throw new TypeError(`${label} must be a RegExp (got ${typeof value})`);\n  }\n};\n\n// --- Messages ---\n\n/**\n * A locale tag broken down into what locale negotiation compares.\n * @typedef {object} ParsedLocaleTag\n * @property {string} language Language subtag, such as `zh`.\n * @property {string | undefined} script Script the locale is written in, such as `Hant`. It is\n * `undefined` only for a language whose script cannot be determined, such as an unassigned code.\n * @property {string | undefined} region Region subtag the tag spells out, such as `TW`. It is\n * `undefined` for a tag that names no region, such as `zh` or `zh-Hant`.\n * @property {string | undefined} preferredRegion Region to prefer when several available locales\n * match equally well: the tag’s own region, or the one CLDR considers most likely for it, so a\n * bare `en` prefers `US` and `zh-Hant` prefers `TW`.\n * @property {boolean} anyScript Whether the tag leaves the script open, which is the case when it\n * has neither a script nor a region, such as a bare `zh`.\n */\n\n/**\n * Parsed locale tags, keyed by the tag. `Intl.Locale` is not cheap to construct, and the same tags\n * are parsed over and over, every time a locale is registered or activated.\n *\n * A plain `Map` rather than a `SvelteMap`, because this is a pure cache of static `Intl` data that\n * nothing should react to.\n * @type {Map<string, ParsedLocaleTag | undefined>}\n */\n// eslint-disable-next-line svelte/prefer-svelte-reactivity\nconst parsedTags = new Map();\n\n/**\n * Parse a locale tag into the language, the script it’s written in, and the region to prefer. Both\n * are inferred from CLDR’s likely-subtags data when the tag doesn’t spell them out, so `zh-TW` is\n * parsed as Traditional Chinese and a bare `en` prefers the `US` region.\n * @param {string} tag Locale tag.\n * @returns {ParsedLocaleTag | undefined} The parsed tag, or `undefined` if it’s not a well-formed\n * BCP 47 tag.\n */\nconst parseLocaleTag = (tag) => {\n  if (!parsedTags.has(tag)) {\n    try {\n      const parsed = new Intl.Locale(tag);\n      const { language, script, region } = parsed;\n      // `maximize()` fills in whatever the tag leaves out, so it’s only needed when something is\n      // missing. It’s the expensive part of parsing, hence the cache around this whole function.\n      const maximized = script && region ? undefined : parsed.maximize();\n\n      parsedTags.set(tag, {\n        language,\n        script: script ?? maximized?.script,\n        region,\n        preferredRegion: region ?? maximized?.region,\n        // A tag with neither a script nor a region, e.g. `zh`, asks for the language in whichever\n        // script is available, unlike `zh-TW`, which asks for Traditional Chinese\n        anyScript: !script && !region,\n      });\n    } catch {\n      parsedTags.set(tag, undefined);\n    }\n  }\n\n  return parsedTags.get(tag);\n};\n\n/**\n * Negotiate the best available locale for a requested tag.\n * 1. Exact match  2. Same language and script (en-CA → en-US)  3. Original value.\n *\n * A locale written in another script is never substituted, so Simplified Chinese (`zh-CN`) is not\n * offered to a reader of Traditional Chinese (`zh-TW`), and vice versa. Regional variants sharing a\n * script still match each other, so `pt-PT` resolves to `pt-BR`. A requested tag with neither a\n * script nor a region, such as a bare `zh`, matches a locale in any script.\n *\n * Where several available locales match a request equally well, as `en-US` and `en-GB` both do for\n * a bare `en`, the tie is broken by region:\n * 1. The region CLDR considers most likely for the request, so `en` picks `en-US` and `es` picks\n * `es-ES`, rather than whichever happened to be registered first.\n * 2. The region most likely for the language alone, which differs from the above only when the\n * request names a region that isn’t available, so `en-CA` picks `en-US` over `en-GB`.\n * 3. Registration order, so an app keeps a say where `Intl` has no opinion.\n * @param {string} requested The requested locale tag.\n * @param {string[]} available List of available locale codes.\n * @returns {string} The best-matching available locale, or `requested` if no match is found.\n */\nconst negotiateLocale = (requested, available) => {\n  if (!requested || !available.length) return requested;\n  if (available.includes(requested)) return requested;\n\n  const parsedRequest = parseLocaleTag(requested);\n\n  if (!parsedRequest) return requested;\n\n  const { language, script, anyScript, preferredRegion } = parsedRequest;\n\n  const candidates = available.filter((code) => {\n    const parsed = parseLocaleTag(code);\n\n    return !!parsed && parsed.language === language && (anyScript || parsed.script === script);\n  });\n\n  // Nothing to rank: no match at all, or no ambiguity about which match to use\n  if (candidates.length < 2) return candidates[0] ?? requested;\n\n  /**\n   * Find the candidate written for the given region, if any.\n   * @param {string | undefined} region Region subtag to look for.\n   * @returns {string | undefined} Locale code, or `undefined` if no candidate names that region.\n   */\n  const findByRegion = (region) =>\n    region ? candidates.find((code) => parseLocaleTag(code)?.region === region) : undefined;\n\n  return (\n    findByRegion(preferredRegion) ??\n    // Only reached for a request naming a region of its own, whose own region didn’t match. Parsing\n    // the bare language reuses the same cache, so this costs nothing after the first lookup.\n    findByRegion(parseLocaleTag(language)?.preferredRegion) ??\n    candidates[0]\n  );\n};\n\n/**\n * Recursively flatten a nested message map into dot-separated keys. `{ field: { name: 'Name' } }` →\n * `{ 'field.name': 'Name' }` Top-level keys that already contain dots are preserved as-is.\n * @param {Record<string, any>} map Nested or flat message map to flatten.\n * @param {string} [prefix] Key prefix for recursive calls.\n * @returns {Record<string, string>} Flat map with dot-separated keys.\n */\nconst flattenMessages = (map, prefix = '') =>\n  Object.entries(map).reduce((acc, [key, value]) => {\n    const flatKey = prefix ? `${prefix}.${key}` : key;\n\n    if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n      Object.assign(acc, flattenMessages(value, flatKey));\n    } else {\n      acc[flatKey] = value;\n    }\n\n    return acc;\n  }, /** @type {Record<string, string>} */ (Object.create(null)));\n\n/**\n * Register a locale code in `locales` (if not already present) and refresh `_resolvedFallback`.\n * Shared by {@link addMessages} and {@link register}.\n * @param {string} localeCode Locale code to register.\n */\nconst registerLocaleCode = (localeCode) => {\n  if (!locales.includes(localeCode)) {\n    locales.push(localeCode);\n    _resolvedFallback = negotiateLocale(fallbackLocale, locales);\n  }\n};\n\n/**\n * Resolve a requested locale against the registered locales, falling back to `fallbackLocale` when\n * no registered locale matches (only when it actually resolved to a registered locale; otherwise\n * the original value is kept).\n * @param {string} value Requested locale.\n * @returns {string} Locale to activate.\n */\nconst resolveLocale = (value) => {\n  if (!value || !locales.length) return value;\n\n  const resolved = negotiateLocale(value, locales);\n\n  return !locales.includes(resolved) && _resolvedFallback && locales.includes(_resolvedFallback)\n    ? _resolvedFallback\n    : resolved;\n};\n\n/**\n * Re-negotiate the active locale if registering a locale changed what the one last requested with\n * `locale.set()` resolves to. That happens when it was called before the requested locale, or any\n * locale at all, was registered. Shared by {@link addMessages} and {@link register}.\n */\nconst renegotiateActiveLocale = () => {\n  if (requestedLocale && resolveLocale(requestedLocale) !== _locale) {\n    // eslint-disable-next-line no-use-before-define\n    locale.set(requestedLocale);\n  }\n};\n\n/**\n * Add new messages for a locale. Accepts flat or nested maps; nested objects are flattened to\n * dot-separated keys (`field.name`). Multiple dicts can be passed and are merged in order, matching\n * svelte-i18n’s `addMessages(locale, ...dicts)` signature.\n * @param {string} localeCode Locale.\n * @param {...Record<string, any>} maps One or more message maps (flat or nested).\n * @throws {TypeError} If `localeCode` is not a non-empty string or any map is not a plain object.\n * @see https://messageformat.github.io/modules/messageformat.html\n */\nconst addMessages = (localeCode, ...maps) => {\n  assertNonEmptyString('addMessages: localeCode', localeCode);\n\n  maps.forEach((map, i) => {\n    if (map === null || typeof map !== 'object' || Array.isArray(map)) {\n      throw new TypeError(\n        `addMessages: maps[${i}] must be a plain object (got ${Array.isArray(map) ? 'array' : typeof map})`,\n      );\n    }\n  });\n\n  registerLocaleCode(localeCode);\n  dictionary[localeCode] ??= {};\n\n  const messages = dictionary[localeCode];\n  // Custom functions come last so they can replace a built-in of the same name. Resolved once per\n  // call: `customFunctions` cannot change while the maps below are compiled.\n  // eslint-disable-next-line no-use-before-define\n  const functions = { ...MESSAGE_FUNCTIONS, ...customFunctions };\n\n  maps.forEach((map) => {\n    Object.entries(flattenMessages(map)).forEach(([key, value]) => {\n      messages[key] = new Intl.MessageFormat(localeCode, String(value), { functions });\n    });\n  });\n\n  renegotiateActiveLocale();\n};\n\n// --- Loader ---\n\n// Plain `Map`s rather than `SvelteMap`s, because these are private bookkeeping that nothing reacts\n// to; `isLoading()` reads `dictionary` instead.\n/** @type {Map<string, () => Promise<Record<string, string>>>} */\n// eslint-disable-next-line svelte/prefer-svelte-reactivity\nconst loaderQueue = new Map();\n/** @type {Map<string, Promise<void>>} */\n// eslint-disable-next-line svelte/prefer-svelte-reactivity\nconst loaderPromises = new Map();\n\n/**\n * Execute the registered loader for the given locale (or the current locale if omitted) and wait\n * until the messages are loaded. Subsequent calls for the same locale return the same promise.\n * @param {string} [localeCode] Defaults to `locale.current`.\n * @returns {Promise<void>}\n * @throws {TypeError} If `localeCode` is provided and is not a string.\n */\nconst waitLocale = (localeCode = _locale) => {\n  assertString('waitLocale: localeCode', localeCode);\n\n  if (!localeCode) return Promise.resolve();\n\n  let promise = loaderPromises.get(localeCode);\n\n  if (!promise) {\n    const loader = loaderQueue.get(localeCode);\n\n    promise = loader\n      ? Promise.resolve(loader()).then(\n          (map) => {\n            addMessages(localeCode, map);\n          },\n          () => {\n            loaderPromises.delete(localeCode);\n\n            // If the failed `locale` is still the active one and has no `dictionary` entry, fall\n            // back so that `isLoading()` does not remain `true` forever. Going through\n            // `locale.set()` also triggers the fallback locale’s own loader and updates\n            // `<html lang>`.\n            if (\n              _locale === localeCode &&\n              !dictionary[localeCode] &&\n              _resolvedFallback &&\n              _resolvedFallback !== localeCode\n            ) {\n              // eslint-disable-next-line no-use-before-define\n              return locale.set(_resolvedFallback);\n            }\n\n            return undefined;\n          },\n        )\n      : Promise.resolve();\n\n    loaderPromises.set(localeCode, promise);\n  }\n\n  return promise;\n};\n\n// --- Locale ---\n\n/**\n * Whether the given locale (or the current locale if omitted) is written right-to-left. Reactive:\n * re-evaluates automatically whenever the locale changes.\n *\n * `getLocaleDir()` reads `Intl.Locale`’s `getTextInfo()`/`textInfo` when available (Chrome/Safari),\n * falls back to the maximized script subtag (Firefox), and returns `'auto'` for an empty or invalid\n * tag.\n * @param {string} [localeCode] Locale to check. Defaults to the active locale.\n * @returns {boolean} `true` if the locale is RTL, `false` otherwise.\n */\nconst isRTL = (localeCode = _locale) => getLocaleDir(localeCode) === 'rtl';\n\n/**\n * Current locale.\n */\nconst locale = {\n  /**\n   * Returns the current locale code.\n   * @returns {string} The active locale code.\n   */\n  get current() {\n    return _locale;\n  },\n  /**\n   * Set the current locale. Negotiates against registered locales (e.g. En-CA → en-US), updates\n   * `<html lang>` / `<html dir>`, and auto-triggers any registered loader.\n   * @param {string} value The locale to set.\n   * @returns {Promise<void>}\n   * @throws {TypeError} If `value` is not a string.\n   */\n  set(value) {\n    assertString('locale.set: value', value);\n\n    requestedLocale = value;\n\n    const resolved = resolveLocale(value);\n\n    _locale = resolved;\n\n    if (typeof document !== 'undefined' && resolved) {\n      document.documentElement.lang = resolved;\n\n      const dir = getLocaleDir(resolved);\n\n      // `auto` means the direction could not be determined, e.g. `resolved` is not a valid BCP 47\n      // tag; leave the attribute alone in that case\n      if (dir !== 'auto') {\n        document.documentElement.dir = dir;\n      }\n    }\n\n    return waitLocale(resolved);\n  },\n};\n\n/**\n * Register a custom MF2 function, callable from messages as `:name`. Registering an existing name,\n * including a built-in like `date`, replaces it.\n *\n * Messages are compiled by {@link addMessages}, which captures the functions available at that\n * moment, so **all functions must be registered before the messages that use them are added**. A\n * message referencing an unregistered function formats as a fallback such as `{$value}`.\n * @param {string} name Function name, without the leading colon.\n * @param {MessageFunction} fn Function handler.\n * @throws {TypeError} If `name` is not a non-empty string or `fn` is not a function.\n * @see https://messageformat.github.io/modules/messageformat_functions.html\n */\nconst registerMessageFunction = (name, fn) => {\n  assertNonEmptyString('registerMessageFunction: name', name);\n  assertFunction('registerMessageFunction: fn', fn);\n\n  customFunctions[name] = fn;\n};\n\n/**\n * Register an async loader for a locale. The loader is called the first time\n * `waitLocale(localeCode)` is invoked for that locale.\n * @param {string} localeCode Locale.\n * @param {() => Promise<Record<string, string>>} loader Function returning a message map.\n * @throws {TypeError} If `localeCode` is not a non-empty string or `loader` is not a function.\n */\nconst register = (localeCode, loader) => {\n  assertNonEmptyString('register: localeCode', localeCode);\n  assertFunction('register: loader', loader);\n\n  loaderQueue.set(localeCode, loader);\n  // Invalidate any cached promise so the new loader is picked up on next waitLocale call.\n  loaderPromises.delete(localeCode);\n\n  registerLocaleCode(localeCode);\n  renegotiateActiveLocale();\n};\n\n/**\n * Get the user’s preferred locale from the browser. The browser’s preferred languages are tried in\n * order and negotiated against the registered locales, so a language further down the list wins\n * when the ones before it are unavailable — including when the first one is only unavailable in the\n * script it asks for, as for a reader of Traditional Chinese who also accepts Japanese.\n *\n * The first preferred language is returned as is when no locale is registered yet, or when none of\n * them matches; {@link locale.set} negotiates again and applies the fallback locale in that case.\n * @returns {string | undefined} A locale code, or `undefined` in non-browser environments.\n */\nconst getLocaleFromNavigator = () => {\n  if (typeof navigator === 'undefined') return undefined;\n\n  const languages = navigator.languages?.length ? navigator.languages : [navigator.language];\n\n  return (\n    languages\n      .map((lang) => negotiateLocale(lang, locales))\n      .find((code) => locales.includes(code)) ?? languages[0]\n  );\n};\n\n/**\n * Shared implementation for {@link getLocaleFromHostname} and {@link getLocaleFromPathname}.\n * @param {'hostname' | 'pathname'} part Part of `window.location` to match against.\n * @param {string} label Argument label used in the error message.\n * @param {RegExp} pattern Pattern with a capture group for the locale code.\n * @returns {string | undefined} The matched locale code, or `undefined` if not in a browser or no\n * match.\n * @throws {TypeError} If `pattern` is not a `RegExp`.\n */\nconst getLocaleFromLocation = (part, label, pattern) => {\n  assertRegExp(label, pattern);\n\n  return typeof window === 'undefined' || !window.location\n    ? undefined\n    : window.location[part].match(pattern)?.[1];\n};\n\n/**\n * Shared implementation for {@link getLocaleFromQueryString} and {@link getLocaleFromHash}.\n * @param {'search' | 'hash'} part Part of `window.location` to parse as a query string.\n * @param {string} label Argument label used in the error message.\n * @param {string} key The key to read.\n * @returns {string | undefined} The parameter value, or `undefined` if not in a browser or not\n * found.\n * @throws {TypeError} If `key` is not a non-empty string.\n */\nconst getLocaleFromLocationParams = (part, label, key) => {\n  assertNonEmptyString(label, key);\n\n  if (typeof window === 'undefined' || !window.location) return undefined;\n\n  // The hash may carry a leading `#`, which is not part of the query string.\n  const query = part === 'hash' ? window.location.hash.replace(/^#/, '') : window.location.search;\n\n  return new URLSearchParams(query).get(key) ?? undefined;\n};\n\n/**\n * Get the locale from a pattern matched against `window.location.hostname`.\n * @param {RegExp} hostnamePattern Pattern with a capture group for the locale code.\n * @returns {string | undefined} The matched locale code, or `undefined` if not in a browser or no\n * match.\n * @throws {TypeError} If `hostnamePattern` is not a `RegExp`.\n */\nconst getLocaleFromHostname = (hostnamePattern) =>\n  getLocaleFromLocation('hostname', 'getLocaleFromHostname: hostnamePattern', hostnamePattern);\n\n/**\n * Get the locale from a pattern matched against `window.location.pathname`.\n * @param {RegExp} pathnamePattern Pattern with a capture group for the locale code.\n * @returns {string | undefined} The matched locale code, or `undefined` if not in a browser or no\n * match.\n * @throws {TypeError} If `pathnamePattern` is not a `RegExp`.\n */\nconst getLocaleFromPathname = (pathnamePattern) =>\n  getLocaleFromLocation('pathname', 'getLocaleFromPathname: pathnamePattern', pathnamePattern);\n\n/**\n * Get the locale from a URL query string parameter.\n * @param {string} queryKey The query string key to read.\n * @returns {string | undefined} The query parameter value, or `undefined` if not in a browser or\n * not found.\n * @throws {TypeError} If `queryKey` is not a non-empty string.\n */\nconst getLocaleFromQueryString = (queryKey) =>\n  getLocaleFromLocationParams('search', 'getLocaleFromQueryString: queryKey', queryKey);\n\n/**\n * Get the locale from a `key=value` pair in `window.location.hash`.\n * @param {string} hashKey The key to look for in the hash.\n * @returns {string | undefined} The hash parameter value, or `undefined` if not in a browser or not\n * found.\n * @throws {TypeError} If `hashKey` is not a non-empty string.\n */\nconst getLocaleFromHash = (hashKey) =>\n  getLocaleFromLocationParams('hash', 'getLocaleFromHash: hashKey', hashKey);\n\n// --- Configuration ---\n\n/**\n * Initialize the locales.\n * @param {object} args Arguments.\n * @param {string} args.fallbackLocale Locale to be used for fallback.\n * @param {string} [args.initialLocale] Locale to be used for the initial selection.\n * @param {Formats} [args.formats] Custom named formats. The reserved `_default` key in each group\n * defines the preset used when a `number()`, `date()` or `time()` call passes no `format` option,\n * and for the matching MF2 placeholders in messages. A preset may carry a `locale` to format in a\n * locale other than the active one.\n * @param {MissingKeyHandler} [args.handleMissingMessage] Called when a message key is not found.\n * May return a string to use as a fallback.\n * @throws {TypeError} If `args.fallbackLocale` is not a string, `args.initialLocale` is not a\n * string, or `args.handleMissingMessage` is not a function.\n */\nconst init = (args) => {\n  if (!args || typeof args.fallbackLocale !== 'string') {\n    throw new TypeError(\n      `init: fallbackLocale must be a string (got ${JSON.stringify(args?.fallbackLocale)})`,\n    );\n  }\n\n  if (args.initialLocale !== undefined) {\n    assertString('init: initialLocale', args.initialLocale);\n  }\n\n  if (args.handleMissingMessage !== undefined) {\n    assertFunction('init: handleMissingMessage', args.handleMissingMessage);\n  }\n\n  fallbackLocale = args.fallbackLocale;\n  _resolvedFallback = negotiateLocale(fallbackLocale, locales);\n  missingMessageHandler = args.handleMissingMessage;\n  customFormats = args.formats ?? {};\n  if (args.initialLocale) locale.set(args.initialLocale);\n};\n\n// --- Formatting ---\n\n/**\n * Get a compiled message. Only the dictionary’s own keys are considered, so a key such as\n * `constructor` or `toString` is not resolved to an `Object.prototype` member.\n * @param {string} localeCode Locale.\n * @param {string} key Message key.\n * @returns {Intl.MessageFormat | undefined} The message, or `undefined` if not found.\n */\nconst getMessage = (localeCode, key) => {\n  const messages = dictionary[localeCode];\n\n  return messages && Object.hasOwn(messages, key) ? messages[key] : undefined;\n};\n\n/**\n * Get the locales to look a message up in, in order of preference: the active locale (or the given\n * override), then the fallback locale if it differs.\n * @param {string} [localeOverride] Locale override for this call.\n * @returns {string[]} One or two locale codes.\n */\nconst getLookupLocales = (localeOverride) => {\n  const active = localeOverride ?? _locale;\n\n  return active !== _resolvedFallback ? [active, _resolvedFallback] : [active];\n};\n\n/**\n * Format a message by key.\n *\n * Supports two call signatures (matching svelte-i18n):\n * - `format(id, options?)` — key as first argument\n * - `format({ id, values, locale, default })` — options object only.\n * @param {string | MessageObject} key Message key, or an object with `id` and options.\n * @param {{ values?: Record<string, any>, locale?: string, default?: string,\n * formats?: MessageFormats }} [options] Formatting options when `key` is a string.\n * @returns {string} The formatted message string.\n * @throws {TypeError} If `key` is `null` or `undefined`.\n */\nconst format = (\n  key,\n  { values = {}, locale: localeOverride, default: defaultString, formats } = {},\n) => {\n  if (key === null || key === undefined) {\n    throw new TypeError(\n      `format: key must be a string or message object (got ${JSON.stringify(key)})`,\n    );\n  }\n\n  if (typeof key === 'object') {\n    const { id, ...options } = key;\n\n    return format(id, options);\n  }\n\n  const lookupLocales = getLookupLocales(localeOverride);\n  const [active] = lookupLocales;\n\n  // Stop at the first locale that has the message, so the fallback dictionary is read (and tracked\n  // as a reactive dependency) only when needed\n  const message = lookupLocales.reduce(\n    (/** @type {Intl.MessageFormat | undefined} */ found, code) => found ?? getMessage(code, key),\n    undefined,\n  );\n\n  messageFormats = formats;\n\n  /** @type {string | undefined} */\n  let result;\n\n  try {\n    result = message?.format(values);\n  } finally {\n    messageFormats = undefined;\n  }\n\n  if (result !== undefined) return result;\n\n  if (missingMessageHandler) {\n    const handled = missingMessageHandler(key, active, defaultString);\n\n    if (handled !== undefined) return handled;\n  }\n\n  return defaultString ?? key;\n};\n\n/**\n * Return a nested object of formatted strings for all keys under the given prefix. Equivalent to\n * svelte-i18n’s `$json()`. Useful for iterating over a group of messages.\n * @param {string} prefix Key prefix (e.g. `'nav'` matches `nav.home`, `nav.about`, …).\n * @param {{ locale?: string }} [options] Lookup options.\n * @returns {Record<string, string> | undefined} Object mapping suffix keys to formatted strings, or\n * `undefined` if no keys match the prefix.\n * @throws {TypeError} If `prefix` is not a non-empty string.\n */\nconst json = (prefix, { locale: localeOverride } = {}) => {\n  assertNonEmptyString('json: prefix', prefix);\n\n  const pfx = `${prefix}.`;\n  const result = /** @type {Record<string, string>} */ ({});\n\n  /**\n   * Format every message under the prefix into `result`, keyed by the suffix.\n   * @param {Record<string, Intl.MessageFormat>} messages Messages for one locale.\n   */\n  const collect = (messages) => {\n    Object.entries(messages).forEach(([key, mf]) => {\n      if (key.startsWith(pfx)) {\n        result[key.slice(pfx.length)] = mf.format({});\n      }\n    });\n  };\n\n  // Start with fallback entries, then overlay active so per-key fallback works.\n  getLookupLocales(localeOverride)\n    .reverse()\n    .forEach((code) => collect(dictionary[code] ?? {}));\n\n  return Object.keys(result).length ? result : undefined;\n};\n\n// --- Date, time & number ---\n\n/** Reserved preset name defining the options used when no `format` option is given. */\nconst DEFAULT_FORMAT_KEY = '_default';\n\n// Built-in named formats matching svelte-i18n defaults\n/** @type {Record<string, DateFormatPreset>} */\nconst BUILT_IN_DATE_FORMATS = {\n  short: { month: 'numeric', day: 'numeric', year: '2-digit' },\n  medium: { month: 'short', day: 'numeric', year: 'numeric' },\n  long: { month: 'long', day: 'numeric', year: 'numeric' },\n  full: { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' },\n};\n\n/** @type {Record<string, DateFormatPreset>} */\nconst BUILT_IN_TIME_FORMATS = {\n  short: { hour: 'numeric', minute: 'numeric' },\n  medium: { hour: 'numeric', minute: 'numeric', second: 'numeric' },\n  long: { hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' },\n  full: { hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' },\n};\n\n/** @type {Record<string, NumberFormatPreset>} */\nconst BUILT_IN_NUMBER_FORMATS = {\n  currency: { style: 'currency' },\n  percent: { style: 'percent' },\n  scientific: { notation: 'scientific' },\n  engineering: { notation: 'engineering' },\n  compactLong: { notation: 'compact', compactDisplay: 'long' },\n  compactShort: { notation: 'compact', compactDisplay: 'short' },\n};\n\n/**\n * Built-in presets by kind. `datetime` has no built-ins; its names resolve from `formats.datetime`.\n * @type {Record<string, Record<string, DateFormatPreset | NumberFormatPreset>>}\n */\nconst BUILT_IN_FORMATS = {\n  date: BUILT_IN_DATE_FORMATS,\n  time: BUILT_IN_TIME_FORMATS,\n  number: BUILT_IN_NUMBER_FORMATS,\n};\n\n/**\n * Look up a named preset for the given kind: a custom preset defined in `init({ formats })` first,\n * then a built-in one.\n * @param {string} kind One of `number`, `date`, `time` or `datetime`.\n * @param {string} name Preset name.\n * @returns {DateFormatPreset | NumberFormatPreset | undefined} The preset, or `undefined` if no\n * preset of that name exists for the kind.\n */\nconst getNamedPreset = (kind, name) =>\n  customFormats[/** @type {keyof Formats} */ (kind)]?.[name] ?? BUILT_IN_FORMATS[kind]?.[name];\n\n/**\n * Look up the group’s `_default` preset defined in `init({ formats })`.\n * @param {string} kind One of `number`, `date`, `time` or `datetime`.\n * @returns {DateFormatPreset | NumberFormatPreset | undefined} The preset, or `undefined` if none\n * is defined for the kind.\n */\nconst getDefaultPreset = (kind) =>\n  customFormats[/** @type {keyof Formats} */ (kind)]?.[DEFAULT_FORMAT_KEY];\n\n/**\n * Resolve the preset for a standalone {@link date}, {@link time} or {@link number} call: the named\n * preset requested with the `format` option, falling back to the group’s `_default` preset.\n * @param {'number' | 'date' | 'time'} kind One of `number`, `date` or `time`.\n * @param {string} [name] Preset name from the `format` option, if any.\n * @returns {DateFormatPreset | NumberFormatPreset} The preset, or an empty object if neither the\n * call nor `init({ formats })` provides one.\n */\nconst getCallPreset = (kind, name) =>\n  (name ? getNamedPreset(kind, name) : undefined) ?? getDefaultPreset(kind) ?? {};\n\n/**\n * Resolve the preset that should override an MF2 function, preferring an override passed to the\n * current {@link format} call and falling back to the group’s `_default` preset.\n * @param {string} kind One of `number`, `date`, `time` or `datetime`.\n * @returns {DateFormatPreset | NumberFormatPreset | undefined} The preset, or `undefined` when\n * neither the call nor `init({ formats })` provides one for the kind.\n */\nconst getMessagePreset = (kind) => {\n  const spec = messageFormats?.[/** @type {keyof MessageFormats} */ (kind)];\n  const preset = typeof spec === 'string' ? getNamedPreset(kind, spec) : spec;\n\n  return preset ?? getDefaultPreset(kind);\n};\n\n/**\n * Build a replacement for an MF2 message value that formats through `formatter`. Spreading the\n * original keeps its `selectKey`, so `:number` continues to work as a plural selector.\n * @param {any} mv The message value returned by the wrapped MF2 function.\n * @param {Intl.DateTimeFormat | Intl.NumberFormat} formatter Formatter built from the preset.\n * @param {string} [presetLocale] Locale carried by the preset, if any.\n * @returns {any} The replacement message value.\n */\nconst overrideMessageValue = (mv, formatter, presetLocale) => {\n  const value = mv.valueOf();\n\n  return {\n    // The spread carries over `selectKey` and `valueOf`, so `:number` keeps working as a plural\n    // selector and the value stays usable as an operand for another function.\n    ...mv,\n    // `MessageFormat.format()` reads `dir` to pick the bidi isolate character, so it has to follow\n    // the preset locale. `toParts()` keeps the original formatter, but it is reachable only through\n    // `formatToParts()`, which this library does not expose.\n    dir: presetLocale ? getLocaleDir(presetLocale) : mv.dir,\n    /**\n     * Format the value through the preset.\n     * @returns {string} The formatted string.\n     */\n    toString: () => formatter.format(value),\n  };\n};\n\n/**\n * Wrap an MF2 function so a preset selected for the current {@link format} call replaces the\n * options it resolved.\n * @param {any} fn The MF2 function to wrap.\n * @param {'number' | 'date' | 'time' | 'datetime'} kind Format kind to look up.\n * @param {typeof Intl.DateTimeFormat | typeof Intl.NumberFormat} Formatter Formatter to build from\n * the preset.\n * @returns {any} The wrapped function.\n */\nconst wrapMessageFunction =\n  (fn, kind, Formatter) =>\n  /**\n   * Apply the preset selected for the current {@link format} call to the wrapped function’s result.\n   * @param {any} ctx MF2 function context.\n   * @param {any} options Options resolved by the wrapped function.\n   * @param {any} operand The operand passed to the function.\n   * @returns {any} The message value, with any preset applied.\n   */\n  (ctx, options, operand) => {\n    const mv = fn(ctx, options, operand);\n    const preset = getMessagePreset(kind);\n\n    if (!preset) return mv;\n\n    const { locale: presetLocale, ...rest } = preset;\n\n    return overrideMessageValue(\n      mv,\n      new /** @type {any} */ (Formatter)(presetLocale ?? ctx.locales, rest),\n      presetLocale,\n    );\n  };\n\n/**\n * MF2 functions used to compile messages. `:number` and `:integer` come from `DefaultFunctions`;\n * `DraftFunctions` does not define them, and the `functions` option is layered over the defaults,\n * so wrapping the wrong source would shadow them with `undefined`. `:integer` looks up the\n * `number` presets, like `Intl.MessageFormat` itself.\n */\nconst MESSAGE_FUNCTIONS = {\n  ...DraftFunctions,\n  date: wrapMessageFunction(DraftFunctions.date, 'date', Intl.DateTimeFormat),\n  time: wrapMessageFunction(DraftFunctions.time, 'time', Intl.DateTimeFormat),\n  datetime: wrapMessageFunction(DraftFunctions.datetime, 'datetime', Intl.DateTimeFormat),\n  number: wrapMessageFunction(DefaultFunctions.number, 'number', Intl.NumberFormat),\n  integer: wrapMessageFunction(DefaultFunctions.integer, 'number', Intl.NumberFormat),\n};\n\n/**\n * Shared implementation for {@link date}, {@link time} and {@link number}: format a value with the\n * preset selected by the `format` option, overlaid with any other options given.\n * @param {typeof Intl.DateTimeFormat | typeof Intl.NumberFormat} Formatter Formatter to use.\n * @param {'number' | 'date' | 'time'} kind Format kind to look up.\n * @param {any} value The value to format.\n * @param {DateFormatOptions | NumberFormatOptions} options Formatting options.\n * @returns {string} The formatted string.\n */\nconst formatStandaloneValue = (Formatter, kind, value, options) => {\n  const { locale: loc, format: fmt, ...rest } = options;\n  const { locale: presetLocale, ...named } = getCallPreset(kind, fmt);\n  // An empty `_locale` (none set yet) is not a valid tag; use the runtime default instead\n  const localeCode = loc ?? presetLocale ?? (_locale || undefined);\n\n  return new /** @type {any} */ (Formatter)(localeCode, { ...named, ...rest }).format(value);\n};\n\n/**\n * Shared implementation for {@link date} and {@link time}.\n * @param {'date' | 'time'} kind `'date'` or `'time'`, selects the format table and error label.\n * @param {Date} value The date to format.\n * @param {DateFormatOptions} [options] Formatting options.\n * @returns {string} The formatted string.\n * @throws {TypeError} If `value` is not a `Date` instance.\n */\nconst formatDateTimeValue = (kind, value, options = {}) => {\n  if (!(value instanceof Date)) {\n    throw new TypeError(`${kind}: value must be a Date instance (got ${typeof value})`);\n  }\n\n  return formatStandaloneValue(Intl.DateTimeFormat, kind, value, options);\n};\n\n/**\n * Format a date value as a localized date string.\n * @param {Date} value The date to format.\n * @param {DateFormatOptions} [options] Formatting options.\n * @returns {string} The formatted date string.\n * @throws {TypeError} If `value` is not a `Date` instance.\n */\nconst date = (value, options = {}) => formatDateTimeValue('date', value, options);\n/**\n * Format a date value as a localized time string.\n * @param {Date} value The date to format.\n * @param {DateFormatOptions} [options] Formatting options.\n * @returns {string} The formatted time string.\n * @throws {TypeError} If `value` is not a `Date` instance.\n */\nconst time = (value, options = {}) => formatDateTimeValue('time', value, options);\n\n/**\n * Format a number as a localized string.\n * @param {number | bigint} value The number to format.\n * @param {NumberFormatOptions} [options] Formatting options.\n * @returns {string} The formatted number string.\n * @throws {TypeError} If `value` is not a number or bigint.\n */\nconst number = (value, options = {}) => {\n  if (typeof value !== 'number' && typeof value !== 'bigint') {\n    throw new TypeError(`number: value must be a number or bigint (got ${typeof value})`);\n  }\n\n  return formatStandaloneValue(Intl.NumberFormat, 'number', value, options);\n};\n\n/**\n * Reset all internal state. Intended **only** for use in tests.\n * @internal\n */\nconst _reset = () => {\n  _locale = '';\n  requestedLocale = '';\n  locales.splice(0);\n  Object.keys(dictionary).forEach((k) => delete dictionary[k]);\n  loaderQueue.clear();\n  loaderPromises.clear();\n  fallbackLocale = '';\n  _resolvedFallback = '';\n  missingMessageHandler = undefined;\n  customFormats = {};\n  customFunctions = {};\n  messageFormats = undefined;\n};\n\n// Export all public API as named exports, and also alias `format` as `_` and `t` for convenience.\n// We cannot use `export const` syntax for each symbol because the TypeScript conversion fails to\n// export the comments with the functions.\nexport {\n  format as _,\n  _reset,\n  addMessages,\n  date,\n  dictionary,\n  format,\n  getLocaleFromHash,\n  getLocaleFromHostname,\n  getLocaleFromNavigator,\n  getLocaleFromPathname,\n  getLocaleFromQueryString,\n  init,\n  isLoading,\n  isRTL,\n  json,\n  locale,\n  locales,\n  number,\n  register,\n  registerMessageFunction,\n  format as t,\n  time,\n  waitLocale,\n};\n","import { parseMessage } from \"./data-model/parse.js\";\nimport { validate } from \"./data-model/validate.js\";\nimport { FSI, LRI, PDI, RLI, getLocaleDir } from \"./dir-utils.js\";\nimport { MessageFunctionError } from \"./errors.js\";\nimport { DefaultFunctions } from \"./functions/index.js\";\nimport { BIDI_ISOLATE } from \"./message-value.js\";\nimport { formatMarkup } from \"./resolve/format-markup.js\";\nimport { resolveExpression } from \"./resolve/resolve-expression.js\";\nimport { UnresolvedExpression } from \"./resolve/resolve-variable.js\";\nimport { selectPattern } from \"./select-pattern.js\";\n/**\n * A message formatter for that implements the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48.2 MessageFormat}\n * specification as well as the {@link https://github.com/tc39/proposal-intl-messageformat/ | TC39 Intl.MessageFormat proposal}.\n *\n * @category Formatting\n * @typeParam T - The `type` used by custom message functions, if any.\n *   These extend the {@link DefaultFunctions | default functions}.\n * @typeParam P - The formatted-parts `type` used by any custom message values.\n */\nexport class MessageFormat {\n    #bidiIsolation;\n    #dir;\n    #localeMatcher;\n    #locales;\n    #message;\n    #functions;\n    constructor(locales, source, options) {\n        this.#bidiIsolation = options?.bidiIsolation !== 'none';\n        this.#localeMatcher = options?.localeMatcher ?? 'best fit';\n        this.#locales = Array.isArray(locales)\n            ? locales.map(lc => new Intl.Locale(lc))\n            : locales\n                ? [new Intl.Locale(locales)]\n                : [];\n        this.#dir = options?.dir ?? getLocaleDir(this.#locales[0]);\n        this.#message = typeof source === 'string' ? parseMessage(source) : source;\n        validate(this.#message);\n        this.#functions = options?.functions\n            ? Object.assign(Object.create(null), DefaultFunctions, options.functions)\n            : DefaultFunctions;\n    }\n    /**\n     * Format a message to a string.\n     *\n     * ```js\n     * import { MessageFormat } from 'messageformat';\n     * import { DraftFunctions } from 'messageformat/functions';\n     *\n     * const msg = 'Hello {$user.name}, today is {$date :date style=long}';\n     * const mf = new MessageFormat('en', msg, { functions: DraftFunctions });\n     * mf.format({ user: { name: 'Kat' }, date: new Date('2025-03-01') });\n     * ```\n     *\n     * ```js\n     * 'Hello Kat, today is March 1, 2025'\n     * ```\n     *\n     * @param msgParams - Values that may be referenced by `$`-prefixed variable references.\n     *   To refer to an inner property of an object value,\n     *   use `.` as a separator; in case of conflict, the longest starting substring wins.\n     * @param onError - Called in case of error.\n     *   If not set, errors are by default logged as warnings.\n     */\n    format(msgParams, onError) {\n        const ctx = this.#createContext(msgParams, onError);\n        let res = '';\n        for (const elem of selectPattern(ctx, this.#message)) {\n            if (typeof elem === 'string') {\n                res += elem;\n            }\n            else if (elem.type === 'markup') {\n                // Handle errors, but discard results\n                formatMarkup(ctx, elem);\n            }\n            else {\n                let mv;\n                try {\n                    mv = resolveExpression(ctx, elem);\n                    if (typeof mv.toString === 'function') {\n                        if (this.#bidiIsolation &&\n                            (this.#dir !== 'ltr' || mv.dir !== 'ltr' || mv[BIDI_ISOLATE])) {\n                            const pre = mv.dir === 'ltr' ? LRI : mv.dir === 'rtl' ? RLI : FSI;\n                            res += pre + mv.toString() + PDI;\n                        }\n                        else {\n                            res += mv.toString();\n                        }\n                    }\n                    else {\n                        const error = new MessageFunctionError('not-formattable', 'Message part is not formattable');\n                        error.source = mv.source;\n                        throw error;\n                    }\n                }\n                catch (error) {\n                    ctx.onError(error);\n                    const errStr = `{${mv?.source ?? '�'}}`;\n                    res += this.#bidiIsolation ? FSI + errStr + PDI : errStr;\n                }\n            }\n        }\n        return res;\n    }\n    /**\n     * Format a message to a sequence of parts.\n     *\n     * ```js\n     * import { MessageFormat } from 'messageformat';\n     * import { DraftFunctions } from 'messageformat/functions';\n     *\n     * const msg = 'Hello {$user.name}, today is {$date :date style=long}';\n     * const mf = new MessageFormat('en', msg, { functions: DraftFunctions });\n     * mf.formatToParts({ user: { name: 'Kat' }, date: new Date('2025-03-01') });\n     * ```\n     *\n     * ```js\n     * [\n     *   { type: 'text', value: 'Hello ' },\n     *   { type: 'bidiIsolation', value: '\\u2068' },\n     *   { type: 'string', locale: 'en', value: 'Kat' },\n     *   { type: 'bidiIsolation', value: '\\u2069' },\n     *   { type: 'text', value: ', today is ' },\n     *   {\n     *     type: 'datetime',\n     *     dir: 'ltr',\n     *     locale: 'en',\n     *     parts: [\n     *       { type: 'month', value: 'March' },\n     *       { type: 'literal', value: ' ' },\n     *       { type: 'day', value: '1' },\n     *       { type: 'literal', value: ', ' },\n     *       { type: 'year', value: '2025' }\n     *     ]\n     *   }\n     * ]\n     * ```\n     *\n     * @param msgParams - Values that may be referenced by `$`-prefixed variable references.\n     *   To refer to an inner property of an object value,\n     *   use `.` as a separator; in case of conflict, the longest starting substring wins.\n     * @param onError - Called in case of error.\n     *   If not set, errors are by default logged as warnings.\n     */\n    formatToParts(msgParams, onError) {\n        const ctx = this.#createContext(msgParams, onError);\n        const parts = [];\n        for (const elem of selectPattern(ctx, this.#message)) {\n            if (typeof elem === 'string') {\n                parts.push({ type: 'text', value: elem });\n            }\n            else if (elem.type === 'markup') {\n                parts.push(formatMarkup(ctx, elem));\n            }\n            else {\n                let mv;\n                try {\n                    mv = resolveExpression(ctx, elem);\n                    if (typeof mv.toParts === 'function') {\n                        // Let's presume that parts that look like MessageNumberPart or MessageStringPart are such.\n                        const mp = mv.toParts();\n                        if (this.#bidiIsolation &&\n                            (this.#dir !== 'ltr' || mv.dir !== 'ltr' || mv[BIDI_ISOLATE])) {\n                            const pre = mv.dir === 'ltr' ? LRI : mv.dir === 'rtl' ? RLI : FSI;\n                            parts.push({ type: 'bidiIsolation', value: pre }, ...mp, {\n                                type: 'bidiIsolation',\n                                value: PDI\n                            });\n                        }\n                        else {\n                            parts.push(...mp);\n                        }\n                    }\n                    else {\n                        const error = new MessageFunctionError('not-formattable', 'Message part is not formattable');\n                        error.source = mv.source;\n                        throw error;\n                    }\n                }\n                catch (error) {\n                    ctx.onError(error);\n                    const fb = {\n                        type: 'fallback',\n                        source: mv?.source ?? '�'\n                    };\n                    if (this.#bidiIsolation) {\n                        parts.push({ type: 'bidiIsolation', value: FSI }, fb, {\n                            type: 'bidiIsolation',\n                            value: PDI\n                        });\n                    }\n                    else {\n                        parts.push(fb);\n                    }\n                }\n            }\n        }\n        return parts;\n    }\n    #createContext(msgParams, onError = (error) => {\n        // Emit warning for errors by default\n        try {\n            process.emitWarning(error);\n        }\n        catch {\n            console.warn(error);\n        }\n    }) {\n        const scope = { ...msgParams };\n        for (const decl of this.#message.declarations) {\n            scope[decl.name] = new UnresolvedExpression(decl.value, decl.type === 'input' ? (msgParams ?? {}) : undefined);\n        }\n        const ctx = {\n            onError,\n            localeMatcher: this.#localeMatcher,\n            locales: this.#locales,\n            localVars: new WeakSet(),\n            functions: this.#functions,\n            scope\n        };\n        return ctx;\n    }\n}\n","import { init_operations } from './client/dom/operations.js';\n\ninit_operations();\n","import { PUBLIC_VERSION } from '../version.js';\n\nif (typeof window !== 'undefined') {\n\t// @ts-expect-error\n\t((globalThis.__svelte ??= {}).v ??= new Set()).add(PUBLIC_VERSION);\n}\n","<!--\n  @component\n  A Material Symbols icon.\n  @see https://developers.google.com/fonts/docs/material_symbols\n-->\n<script>\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the `span` element.\n   * @property {string} [name] Icon name, e.g. `search`, `expand_more`, `close`, etc.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    name,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<span\n  {...restProps}\n  class=\"sui icon material-symbols-outlined {className}\"\n  aria-hidden={!('aria-label' in restProps)}\n>\n  {name}\n</span>\n\n<style>.icon.small-arrow {\n  overflow: hidden;\n  width: 12px;\n  text-indent: -6px;\n}</style>\n","<!--\n  @component\n  The content shared by `<Alert>` and `<Infobar>`: the status icon, the status spelled out off\n  screen, and the message. Internal; not exported.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import Icon from '../icon/icon.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { AlertStatus } from './alert.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {AlertStatus} status Alert status.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {Snippet} [icon] Icon slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    status,\n    children = undefined,\n    icon = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<!--\n  The colour and icon tell sighted users how serious the message is; the icon is hidden from\n  assistive technology, so the status is also spelled out for screen readers, off screen.\n-->\n{#if icon}\n  {@render icon()}\n{:else}\n  <Icon name={status === 'success' ? 'check_circle' : status} />\n{/if}\n<span class=\"status-label\">{_(`_sui.alert.${status}`)}</span>\n{@render children?.()}\n\n<style>.status-label {\n  position: absolute;\n  overflow: hidden;\n  clip-path: inset(50%);\n  width: 1px;\n  height: 1px;\n  white-space: nowrap;\n}</style>\n","/**\n * @typedef {'error' | 'warning' | 'info' | 'success'} AlertStatus\n */\n\n/**\n * Get the ARIA role for an alert status. Errors and warnings are `alert` and interrupt; information\n * and success are `status` and wait.\n * @param {AlertStatus} status Alert status.\n * @returns {'alert' | 'status'} Role.\n */\nexport const getAlertRole = (status) =>\n  status === 'error' || status === 'warning' ? 'alert' : 'status';\n\n/**\n * Get the ARIA live region politeness for an alert role, unless one is given explicitly.\n * @param {'alert' | 'status'} role Role from {@link getAlertRole}.\n * @param {'off' | 'polite' | 'assertive'} [ariaLive] Explicit politeness, if any.\n * @returns {'off' | 'polite' | 'assertive'} Politeness.\n */\nexport const getAlertAriaLive = (role, ariaLive) =>\n  ariaLive ?? (role === 'alert' ? 'assertive' : 'polite');\n","<!--\n  @component\n  Inline alert message.\n  @see https://w3c.github.io/aria/#alert\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/alert/\n-->\n<script>\n  import AlertContent from './alert-content.svelte';\n  import { getAlertAriaLive, getAlertRole } from './alert.js';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'error' | 'warning' | 'info' | 'success'} status Alert status. Errors and warnings\n   * are `role=\"alert\"` and interrupt; information and success are `role=\"status\"` and wait.\n   * @property {'off' | 'polite' | 'assertive'} [ariaLive] ARIA live region politeness. Defaults to\n   * `assertive` for an alert and `polite` for a status.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {Snippet} [icon] Icon slot content.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    status,\n    ariaLive = undefined,\n    children,\n    icon,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const role = $derived(getAlertRole(status));\n</script>\n\n<div {...restProps} {role} class=\"sui alert {status}\" aria-live={getAlertAriaLive(role, ariaLive)}>\n  <AlertContent {status} {children} {icon} />\n</div>\n\n<style>.alert {\n  display: flex;\n  align-items: center;\n  gap: var(--gap, 8px);\n  padding: var(--padding, 8px);\n  border-width: var(--border-width, var(--sui-control-medium-border-width));\n  border-style: var(--border-style, solid);\n  border-radius: var(--border-radius, var(--sui-control-medium-border-radius));\n  font-size: var(--font-size, var(--sui-font-size-default));\n}\n.alert.error {\n  border-color: var(--sui-error-border-color);\n  color: var(--sui-error-foreground-color);\n  background-color: var(--sui-error-background-color);\n}\n.alert.warning {\n  border-color: var(--sui-warning-border-color);\n  color: var(--sui-warning-foreground-color);\n  background-color: var(--sui-warning-background-color);\n}\n.alert.info {\n  border-color: var(--sui-info-border-color);\n  color: var(--sui-info-foreground-color);\n  background-color: var(--sui-info-background-color);\n}\n.alert.success {\n  border-color: var(--sui-success-border-color);\n  color: var(--sui-success-foreground-color);\n  background-color: var(--sui-success-background-color);\n}</style>\n","/**\n * @import { Attachment } from 'svelte/attachments';\n */\n\n/** @type {boolean | undefined} */\nlet _isMac;\n\n/**\n * Check if the user agent is macOS.\n * @returns {boolean} Result.\n */\nconst isMac = () => {\n  _isMac ??=\n    /** @type {any} */ (navigator).userAgentData?.platform === 'macOS' ||\n    navigator.platform.startsWith('Mac');\n\n  return _isMac;\n};\n\nconst MODIFIER_KEYS = new Set(['Ctrl', 'Meta', 'Alt', 'Shift']);\n/**\n * `KeyboardEvent.key` values produced by the modifier keys themselves.\n */\nconst MODIFIER_EVENT_KEYS = new Set(['Control', 'Meta', 'Alt', 'Shift']);\n\n/**\n * Shortcut tokens that correspond to a physical, layout- and modifier-stable `KeyboardEvent.code`\n * value. Matching against `code` (rather than `key`) for these avoids two problems:\n *\n * 1. `event.key` for the Space bar is a single space character (`' '`), which is awkward to write\n * in a shortcut string — the conventional token is `Space`.\n * 2. `event.key` changes when Shift (or Alt/Option on macOS) is held: `Shift+1` produces `'!'` on\n * US layout, `Alt+E` on macOS produces `'´'`, etc. Comparing against `code` keeps shortcuts like\n * `Ctrl+Shift+1` or `Alt+ArrowUp` working as authored.\n */\nconst PHYSICAL_TOKENS = new Set([\n  'Space',\n  'Enter',\n  'Escape',\n  'Tab',\n  'Backspace',\n  'Delete',\n  'Insert',\n  'Home',\n  'End',\n  'PageUp',\n  'PageDown',\n  'ArrowUp',\n  'ArrowDown',\n  'ArrowLeft',\n  'ArrowRight',\n  // Function keys F1–F24\n  ...Array.from({ length: 24 }, (_, i) => `F${i + 1}`),\n]);\n\n/**\n * Create a function that determines whether a single (non-modifier) shortcut token matches a\n * `KeyboardEvent`. The token is classified once here, at parse time, rather than on every\n * keystroke.\n *\n * Letters are compared against `event.key` (layout-aware: a Dvorak user pressing the physical\n * QWERTY-`S` key produces `key: 'o'`, which should match `Ctrl+O`, not `Ctrl+S`), falling back to\n * `event.code` when `key` is a non-ASCII character or dead key (non-Latin layouts, `Alt+E` on\n * macOS). Bare digits are compared against `event.code` (layout- and modifier-stable, so `Shift+1`\n * matches even though `event.key` becomes `'!'`). Named keys and function keys are compared against\n * either, so their numeric keypad equivalents match too. Other characters fall back to\n * `event.key`.\n * @param {string} token A single key token from a shortcut string, e.g. `S`, `Space`, `1`, `/`.\n * @returns {(event: KeyboardEvent) => boolean} Function that checks whether the token matches the\n * event.\n */\nconst createTokenMatcher = (token) => {\n  // Bare digit: match the physical digit row regardless of Shift (`Shift+1` vs `!`).\n  if (/^\\d$/.test(token)) {\n    const digitCode = `Digit${token}`;\n\n    return ({ code }) => code === digitCode;\n  }\n\n  // Named keys (Space, Enter, arrows, F-keys, …): match the stable `code`, or `key`, which\n  // modifiers don’t change for these. The numeric keypad has its own `code` values, e.g.\n  // `NumpadEnter` for Enter, and `Numpad8` for ArrowUp with NumLock off, so only `key` matches.\n  if (PHYSICAL_TOKENS.has(token)) {\n    const namedKey = token === 'Space' ? ' ' : token;\n\n    return ({ key, code }) => code === token || key === namedKey;\n  }\n\n  const lowerToken = token.toLowerCase();\n\n  // Letter: prefer `event.key` so the user's active Latin layout (Dvorak, AZERTY, …) is respected.\n  // When `key` is a non-ASCII character or a dead key, the layout is non-Latin (`ы` on Russian) or\n  // Alt changed the character (`Alt+E` → `´` on macOS), so fall back to the physical `code`. ASCII\n  // punctuation (`.` on Dvorak’s `KeyE`), IME `Process` keys and AltGr characters (`ą` on Polish,\n  // reported as Ctrl+Alt on Windows) must not fall back, or ordinary typing would hit shortcuts.\n  // macOS has no AltGr key, but browsers report Option as AltGraph there, so it’s only checked on\n  // other platforms; otherwise `Alt+E` or `Meta+Alt+V` would never match.\n  if (/^[a-z]$/i.test(token)) {\n    const letterCode = `Key${token.toUpperCase()}`;\n\n    return (event) => {\n      const { key, code } = event;\n\n      const useCode =\n        (key === 'Dead' || (key.length === 1 && key.charCodeAt(0) > 0x7f)) &&\n        (isMac() || !event.getModifierState?.('AltGraph'));\n\n      return useCode ? code === letterCode : lowerToken === key.toLowerCase();\n    };\n  }\n\n  // Everything else (punctuation): compare case-insensitively against `event.key`.\n  return ({ key }) => lowerToken === key.toLowerCase();\n};\n\n/**\n * A shortcut string parsed into the exact modifier state it requires plus its non-modifier tokens.\n * @typedef {object} ParsedShortcut\n * @property {boolean} ctrl Whether Ctrl must be held.\n * @property {boolean} meta Whether Meta must be held.\n * @property {boolean} alt Whether Alt must be held.\n * @property {boolean} shift Whether Shift must be held.\n * @property {((event: KeyboardEvent) => boolean)[]} matchers Matchers for the non-modifier key\n * tokens, e.g. `S`. Empty for a modifier-only shortcut like `Shift`.\n */\n\n/**\n * Replace the `Accel` alias with the platform’s primary modifier.\n * @param {string} shortcuts Keyboard shortcuts, possibly containing `Accel`.\n * @returns {string} Resolved shortcuts.\n */\nconst resolveAccel = (shortcuts) => shortcuts.replace(/\\bAccel\\b/g, isMac() ? 'Meta' : 'Ctrl');\n/**\n * Cache of parsed shortcut strings. Shortcut matching runs on every keystroke, so the string\n * splitting, `Accel` substitution and token classification happen once per unique shortcut string\n * rather than per event.\n * Keyed by the raw (unresolved) string; {@link isMac} is stable for the lifetime of the module, so\n * the resolved result is stable too.\n * @type {Map<string, ParsedShortcut[]>}\n */\nconst parsedShortcutCache = new Map();\n\n/**\n * Parse a shortcut string into a list of {@link ParsedShortcut} objects, one per space-separated\n * alternative.\n * @param {string} shortcuts Keyboard shortcuts like `A`, `Ctrl+S`, `Accel+Space`, `Shift+1`.\n * @returns {ParsedShortcut[]} Parsed shortcuts.\n */\nconst parseShortcuts = (shortcuts) => {\n  let parsed = parsedShortcutCache.get(shortcuts);\n\n  if (!parsed) {\n    parsed = resolveAccel(shortcuts)\n      .trim()\n      .split(/\\s+/)\n      .filter(Boolean)\n      .map((shortcut) => {\n        // Accept `Control`, as written in `aria-keyshortcuts`, as an alias of `Ctrl`\n        const keys = shortcut.split('+').map((key) => (key === 'Control' ? 'Ctrl' : key));\n\n        return {\n          ctrl: keys.includes('Ctrl'),\n          meta: keys.includes('Meta'),\n          alt: keys.includes('Alt'),\n          shift: keys.includes('Shift'),\n          matchers: keys.filter((key) => !MODIFIER_KEYS.has(key)).map(createTokenMatcher),\n        };\n      });\n\n    parsedShortcutCache.set(shortcuts, parsed);\n  }\n\n  return parsed;\n};\n\n/**\n * Whether the event matches any of the given pre-parsed shortcuts. The modifier state must match\n * exactly: every modifier the shortcut requires has to be held, and no others.\n * @param {KeyboardEvent} event `keydown` or `keypress` event.\n * @param {ParsedShortcut[]} parsedShortcuts Pre-parsed shortcuts.\n * @returns {boolean} Result.\n */\nconst matchesParsedShortcuts = (event, parsedShortcuts) => {\n  const { ctrlKey, metaKey, altKey, shiftKey, key, code } = event;\n\n  // Both `key` and `code` can be empty in edge cases (e.g. dead keys mid-composition).\n  if (!key && !code) {\n    return false;\n  }\n\n  // A key pressed while composing text with an IME belongs to the IME, e.g. Escape to cancel a\n  // conversion or Enter to commit it. Safari fires that `keydown` right after `compositionend`,\n  // with `isComposing` already `false`, so only its `keyCode` of `229` gives it away\n  if (event.isComposing || event.keyCode === 229) {\n    return false;\n  }\n\n  return parsedShortcuts.some(\n    ({ ctrl, meta, alt, shift, matchers }) =>\n      ctrl === ctrlKey &&\n      meta === metaKey &&\n      alt === altKey &&\n      shift === shiftKey &&\n      // A modifier-only shortcut like `Shift` must not match every key pressed with that modifier\n      (matchers.length\n        ? matchers.every((matches) => matches(event))\n        : MODIFIER_EVENT_KEYS.has(key)),\n  );\n};\n\n/**\n * Whether the event matches the given keyboard shortcuts.\n *\n * Uses a hybrid of `KeyboardEvent.key` and `KeyboardEvent.code` so shortcuts work correctly on\n * non-QWERTY layouts (Dvorak, AZERTY, Colemak, …) *and* with modifiers like Shift or Alt that\n * otherwise change `event.key` (`Shift+1` → `'!'`, `Alt+E` on macOS → `'´'`, etc.). See\n * {@link createTokenMatcher} for the matching rules.\n * @param {KeyboardEvent} event `keydown` or `keypress` event.\n * @param {string} shortcuts Keyboard shortcuts like `A`, `Ctrl+S`, `Accel+Space`, `Shift+1`.\n * @returns {boolean} Result.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values\n * @see https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_code_values\n * @see https://w3c.github.io/aria/#aria-keyshortcuts\n */\nconst matchesShortcuts = (event, shortcuts) =>\n  matchesParsedShortcuts(event, parseShortcuts(shortcuts));\n\n/**\n * Shortcuts registered by a single attachment.\n * @typedef {object} ShortcutRegistration\n * @property {ParsedShortcut[]} parsedShortcuts Pre-parsed shortcuts.\n * @property {string} label Shortcuts in the `aria-keyshortcuts` syntax.\n */\n\n/**\n * Elements with active shortcuts, mapped to the registrations of every attachment on them, as an\n * element can have more than one. A single shared `keydown` listener serves every registered\n * element, instead of adding one global listener per element.\n * @type {Map<HTMLInputElement | HTMLButtonElement, ShortcutRegistration[]>}\n */\nconst shortcutTargets = new Map();\n\n/**\n * Activate the element if the shortcut applies to it. Only called once the event is already known\n * to match, since the geometry checks here force a synchronous layout.\n * @param {HTMLInputElement | HTMLButtonElement} element Registered element.\n * @param {KeyboardEvent} event `keydown` event.\n */\nconst activateElement = (element, event) => {\n  const { disabled } = element;\n\n  // `getClientRects()` is empty for `display: none` elements. Unlike `offsetParent`, it still\n  // returns rects for `position: fixed` elements.\n  if (!element.getClientRects().length) {\n    return;\n  }\n\n  const { top, left } = element.getBoundingClientRect();\n\n  if (disabled) {\n    // Make sure `elementsFromPoint()` works as expected\n    element.style.setProperty('pointer-events', 'auto');\n  }\n\n  // Check if the element is clickable (not behind a modal dialog)\n  const isClickable = document.elementsFromPoint(left + 4, top + 4).includes(element);\n\n  if (disabled) {\n    element.style.removeProperty('pointer-events');\n  }\n\n  if (!isClickable) {\n    return;\n  }\n\n  event.preventDefault();\n\n  if (!disabled) {\n    element.focus();\n    element.click();\n  }\n};\n\n/**\n * `<input>` types that don’t take typed text, where the Option key on macOS doesn’t produce a\n * character.\n */\nconst NON_TEXT_INPUT_TYPES = new Set([\n  'button',\n  'checkbox',\n  'color',\n  'file',\n  'hidden',\n  'image',\n  'radio',\n  'range',\n  'reset',\n  'submit',\n]);\n\n/**\n * Whether the given event target takes typed text: a text field, a `<textarea>` or an editable\n * element.\n * @param {EventTarget | null | undefined} target Event target.\n * @returns {boolean} Result.\n */\nconst isTextEntryTarget = (target) =>\n  target instanceof HTMLElement &&\n  (target.isContentEditable ||\n    target instanceof HTMLTextAreaElement ||\n    (target instanceof HTMLInputElement && !NON_TEXT_INPUT_TYPES.has(target.type)));\n\n/**\n * Whether the `keydown` event is a text editing action rather than a shortcut. On macOS, the\n * Option key held without Command or Control is a text editing modifier in a text field: it types\n * a character, like `@` with Option+2 on Swedish, Finnish and Norwegian layouts, or `¡` and `™` on\n * the US layout, and it moves the caret or deletes by word with the arrow keys and Backspace. A\n * shortcut like `Alt+2` or `Alt+ArrowUp` must not take the key there.\n * @param {KeyboardEvent} event `keydown` event.\n * @returns {boolean} Result.\n */\nconst isTextEditingWithOption = (event) =>\n  isMac() &&\n  event.altKey &&\n  !event.ctrlKey &&\n  !event.metaKey &&\n  // `target` is the shadow host for an event from within a shadow tree, so take the original one\n  isTextEntryTarget(event.composedPath()[0]);\n\n/**\n * Shared `keydown` handler. The shortcut comparison runs first for every registered element because\n * it is pure string/boolean work; the layout-forcing geometry checks in {@link activateElement} are\n * reached only once a shortcut actually matches. This keeps ordinary typing free of reflows.\n * @param {KeyboardEvent} event `keydown` event.\n */\nconst handleKeyDown = (event) => {\n  if (isTextEditingWithOption(event)) {\n    return;\n  }\n\n  // Go through a copy, as `Map#forEach` would also visit an element registered by another one’s\n  // click handler, activating it with the same key press\n  [...shortcutTargets.keys()].forEach((element) => {\n    // Skip an element unregistered on the way\n    const registrations = shortcutTargets.get(element);\n\n    if (\n      registrations?.some(({ parsedShortcuts }) => matchesParsedShortcuts(event, parsedShortcuts))\n    ) {\n      activateElement(element, event);\n    }\n  });\n};\n\n/**\n * Set or remove the `aria-keyshortcuts` attribute to reflect every registration on the element.\n * @param {HTMLInputElement | HTMLButtonElement} element Registered element.\n * @param {ShortcutRegistration[]} registrations Registrations on the element.\n */\nconst updateShortcutsAttribute = (element, registrations) => {\n  if (registrations.length) {\n    element.setAttribute(\n      'aria-keyshortcuts',\n      [...new Set(registrations.flatMap(({ label }) => label.split(' ')))].join(' '),\n    );\n  } else {\n    element.removeAttribute('aria-keyshortcuts');\n  }\n};\n\n/**\n * Activate keyboard shortcuts.\n * @param {string} [shortcuts] Keyboard shortcuts like `A` or `Accel+S` to focus and click the text\n * field or button. Multiple shortcuts can be defined space-separated. The `Accel` modifier will be\n * replaced with `Ctrl` on Windows/Linux and `Command` on macOS.\n * @returns {Attachment<HTMLInputElement | HTMLButtonElement>} Svelte attachment to deactivate the\n * shortcuts.\n */\nconst activateKeyShortcuts = (shortcuts = '') => {\n  // ARIA takes modifier names from `KeyboardEvent.key` values, where Ctrl is `Control`\n  const label = resolveAccel(shortcuts)\n    .trim()\n    .replace(/\\s+/g, ' ')\n    .replace(/\\bCtrl\\b/g, 'Control');\n\n  if (!label) {\n    // Return a no-op attachment so the return value always matches the `Attachment` shape (a\n    // function that takes an element and returns a cleanup function).\n    return () => () => {};\n  }\n\n  // Parse the raw string so the cache entry is shared with `matchesShortcuts()` calls\n  const parsedShortcuts = parseShortcuts(shortcuts);\n\n  return (element) => {\n    if (!shortcutTargets.size) {\n      globalThis.addEventListener('keydown', handleKeyDown, { capture: true });\n    }\n\n    // A new object per attachment, so the cleanup removes only its own registration\n    /** @type {ShortcutRegistration} */\n    const registration = { parsedShortcuts, label };\n    const registrations = shortcutTargets.get(element) ?? [];\n\n    registrations.push(registration);\n    shortcutTargets.set(element, registrations);\n    updateShortcutsAttribute(element, registrations);\n\n    return () => {\n      const index = registrations.indexOf(registration);\n\n      // Run only once\n      if (index === -1) {\n        return;\n      }\n\n      registrations.splice(index, 1);\n      updateShortcutsAttribute(element, registrations);\n\n      if (!registrations.length) {\n        shortcutTargets.delete(element);\n      }\n\n      if (!shortcutTargets.size) {\n        globalThis.removeEventListener('keydown', handleKeyDown, { capture: true });\n      }\n    };\n  };\n};\n\nexport { activateKeyShortcuts, isMac, matchesShortcuts };\n","/**\n * Conversion of the values held by buttons and other items: a value is stored in the `data-value`\n * attribute along with its type in the `data-type` attribute, so it can be cast back to the\n * original type when the item is selected.\n */\n\n/**\n * Get the data type of a value, to be stored in the `data-type` attribute. `null` gets its own type\n * because `typeof null` is `object`, and the `data-value` attribute is omitted for `null`.\n * @param {any} value Value.\n * @returns {string} Data type, e.g. `string`, `number`, `boolean` or `null`.\n */\nexport const getValueType = (value) => (value === null ? 'null' : typeof value);\n\n/**\n * Cast a value read from the `data-value` attribute back to its original type.\n * @param {string | undefined} value Attribute value, or `undefined` if the attribute is omitted.\n * @param {string} type Data type stored in the `data-type` attribute.\n * @returns {any} Cast value. Any other type than `number`, `boolean`, `null` and `string` is\n * returned as is.\n */\nexport const castValue = (value, type) => {\n  if (type === 'number') {\n    const number = Number(value);\n\n    return Number.isNaN(number) ? null : number;\n  }\n\n  if (type === 'boolean') {\n    return value === 'true';\n  }\n\n  if (type === 'null') {\n    return null;\n  }\n\n  if (type === 'string') {\n    return value ? String(value) : '';\n  }\n\n  return value;\n};\n","<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {number} [lines] Number of lines.\n   * @property {Snippet} [children] Primary slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    lines = 1,\n    children = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<span\n  role=\"none\"\n  class=\"sui truncated-text\"\n  style:-webkit-line-clamp={lines}\n  style:line-clamp={lines}\n>\n  {@render children?.()}\n</span>\n\n<style>.truncated-text {\n  display: -webkit-box;\n  -webkit-box-orient: vertical;\n  overflow: hidden;\n  white-space: normal;\n  overflow-wrap: anywhere;\n}</style>\n","/**\n * Return a simple `Promise` to resolve in the given time, making it easier to wait for a bit in the\n * code, particularly while making sequential HTTP requests.\n * @param {number} [ms] Milliseconds to wait.\n * @returns {Promise<void>} Nothing.\n */\nconst sleep = (ms = 0) =>\n  new Promise((resolve) => {\n    globalThis.setTimeout(() => {\n      resolve(undefined);\n    }, ms);\n  });\n\nexport { sleep };\n","/**\n * Regular expression that matches a UUID.\n */\nconst uuidPattern = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;\n\n/**\n * Generate a v4 UUID or its shortened version.\n * @param {'short' | 'shorter' | number} [length] Length.\n * @returns {string} UUID like `10f95178-c983-4cfe-91d6-4e62c8c7e582`.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID\n */\nconst generateUUID = (length) => {\n  const uuid = globalThis.crypto.randomUUID();\n\n  // Last 12 characters\n  if (length === 'short') {\n    return /** @type {string} */ (uuid.split('-').pop());\n  }\n\n  // First 8 characters\n  if (length === 'shorter') {\n    return /** @type {string} */ (uuid.split('-').shift());\n  }\n\n  // First X characters but without hyphens\n  if (typeof length === 'number') {\n    return uuid.split('-').join('').slice(0, length);\n  }\n\n  return uuid;\n};\n\n/**\n * RFC 4648 Base32 alphabet, lowercased.\n */\nconst base32Alphabet = 'abcdefghijklmnopqrstuvwxyz234567';\n\n/* eslint-disable no-bitwise */\n/**\n * Encode the given bytes as a lowercase RFC 4648 Base32 string without padding.\n * @param {Uint8Array} bytes Bytes to encode.\n * @returns {string} Encoded string.\n */\nconst encodeBase32 = (bytes) => {\n  let output = '';\n  let buffer = 0;\n  let bits = 0;\n\n  bytes.forEach((byte) => {\n    buffer = (buffer << 8) | byte;\n    bits += 8;\n\n    while (bits >= 5) {\n      bits -= 5;\n      output += base32Alphabet[(buffer >>> bits) & 31];\n    }\n  });\n\n  // Always true for 16-byte UUID input, which leaves 3 bits over\n  /* v8 ignore else */\n  if (bits > 0) {\n    output += base32Alphabet[(buffer << (5 - bits)) & 31];\n  }\n\n  return output;\n};\n/* eslint-enable no-bitwise */\n\n/**\n * Generate a random ID.\n * @returns {string} Generated 26-character string.\n */\nconst generateRandomId = () => encodeBase32(Uint8Array.fromHex(generateUUID().replaceAll('-', '')));\n\n/**\n * Get the SHA hash of the given file or text.\n * @param {File | Blob | ArrayBuffer | ArrayBufferView | string} input File or text.\n * @param {object} [options] Options.\n * @param {'SHA-1' | 'SHA-256' | 'SHA-512'} [options.algorithm] Digest algorithm. Default: SHA-1.\n * @param {'hex' | 'binary'} [options.format] Hash format. Default: hex.\n * @returns {Promise<string>} Hash.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest\n */\nconst getHash = async (input, { algorithm = 'SHA-1', format = 'hex' } = {}) => {\n  /** @type {BufferSource} */\n  let data;\n\n  // `digest()` accepts any `BufferSource`, so views are passed as-is. Slicing `view.buffer` would\n  // copy the whole payload first, doubling peak memory for large inputs.\n  if (typeof input === 'string') {\n    data = new TextEncoder().encode(input);\n  } else if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) {\n    data = /** @type {BufferSource} */ (input);\n  } else if (input && typeof (/** @type {any} */ (input).arrayBuffer) === 'function') {\n    // Blob or File\n    data = await /** @type {Blob} */ (input).arrayBuffer();\n  } else {\n    throw new Error('Unsupported input type for getHash');\n  }\n\n  const digest = await globalThis.crypto.subtle.digest(algorithm, data);\n\n  if (format === 'binary') {\n    return Array.from(new Uint8Array(digest), (b) => String.fromCharCode(b)).join('');\n  }\n\n  return new Uint8Array(digest).toHex();\n};\n\nexport { generateRandomId, generateUUID, getHash, uuidPattern };\n","import { generateUUID } from './crypto.js';\n\n/** @type {WeakMap<HTMLElement, () => void>} */\nconst visibilityResolvers = new WeakMap();\n/** @type {IntersectionObserver | undefined} */\nlet sharedVisibilityObserver;\n/**\n * Get a random ID that can be used for elements.\n * @param {string} [prefix] Prefix to be added to the ID, e.g. `popup`.\n * @param {number} [length] Number of characters to be used in the ID.\n * @returns {string} Generated ID.\n */\nconst generateElementId = (prefix = 'e', length = 7) => [prefix, generateUUID(length)].join('-');\n\n/**\n * Remove the visibility resolver for the given element and stop observing it.\n * @param {HTMLElement} element Element to remove the resolver for.\n */\nconst removeVisibilityResolver = (element) => {\n  visibilityResolvers.delete(element);\n  sharedVisibilityObserver?.unobserve(element);\n};\n\n/**\n * Create or reuse a shared observer to avoid registering one IntersectionObserver per element. This\n * keeps large lists responsive because we only create a single observer for all visibility checks\n * instead of hundreds of short-lived observers.\n * @returns {IntersectionObserver | undefined} Shared observer instance.\n */\nconst getSharedVisibilityObserver = () => {\n  if (!('IntersectionObserver' in globalThis)) {\n    return undefined;\n  }\n\n  if (sharedVisibilityObserver) {\n    return sharedVisibilityObserver;\n  }\n\n  sharedVisibilityObserver = new IntersectionObserver((entries) => {\n    entries.forEach(({ isIntersecting, target }) => {\n      if (!isIntersecting || !(target instanceof HTMLElement)) {\n        return;\n      }\n\n      const resolve = visibilityResolvers.get(target);\n\n      if (resolve) {\n        resolve();\n        removeVisibilityResolver(target);\n      }\n    });\n  });\n\n  return sharedVisibilityObserver;\n};\n\n/**\n * @typedef {object} VisibilityOptions\n * @property {string} [rootMargin] Margin around the viewport within which an element counts as\n * visible, in the syntax of the CSS `margin` property, e.g. `200px 0px` to start loading an image\n * just before it scrolls into view. Defaults to `0px`.\n */\n\n/**\n * @typedef {object} SharedVisibilityObserver\n * @property {IntersectionObserver} observer Observer.\n * @property {Map<Element, Set<(visible: boolean) => void>>} listeners Functions to call when the\n * visibility of an observed element changes.\n * @property {Map<Element, boolean>} states Whether each observed element was visible when the\n * observer last reported it, so a listener added later is told without waiting for a change.\n */\n\n/**\n * Observers shared by every element observed with the same root margin through\n * {@link observeVisibility}, keyed by that margin.\n * @type {Map<string, SharedVisibilityObserver>}\n */\nconst sharedVisibilityObservers = new Map();\n\n/**\n * Create or reuse the observer shared by every element observed with the given root margin.\n * @param {string} rootMargin Root margin.\n * @returns {SharedVisibilityObserver | undefined} Shared observer, or `undefined` if\n * `IntersectionObserver` is not available.\n */\nconst getMarginVisibilityObserver = (rootMargin) => {\n  if (!('IntersectionObserver' in globalThis)) {\n    return undefined;\n  }\n\n  let shared = sharedVisibilityObservers.get(rootMargin);\n\n  if (!shared) {\n    /** @type {SharedVisibilityObserver['listeners']} */\n    const listeners = new Map();\n    /** @type {SharedVisibilityObserver['states']} */\n    const states = new Map();\n\n    const observer = new IntersectionObserver(\n      (entries) => {\n        entries.forEach(({ isIntersecting, target }) => {\n          const elementListeners = listeners.get(target);\n\n          // A late entry for an element that is no longer observed is ignored\n          if (elementListeners) {\n            states.set(target, isIntersecting);\n\n            // Go through a copy, as a listener can add or remove others. One added on the way is\n            // told in a microtask instead, and one removed on the way isn’t told at all\n            [...elementListeners].forEach((listener) => {\n              if (elementListeners.has(listener)) {\n                listener(isIntersecting);\n              }\n            });\n          }\n        });\n      },\n      { rootMargin },\n    );\n\n    shared = { observer, listeners, states };\n    sharedVisibilityObservers.set(rootMargin, shared);\n  }\n\n  return shared;\n};\n\n/**\n * Observe whether the given element is in or near the viewport. Unlike a check with\n * `getBoundingClientRect()`, this never forces a layout: the observer reports the element’s state\n * asynchronously, first right after it’s observed, then whenever it changes. That matters in a long\n * list, where a synchronous check for every row being rendered would lay out the page each time.\n * The flip side is that, unlike with {@link waitForVisibility}, an element already in view is only\n * reported once the next frame has been laid out. A listener added to an element that is observed\n * already is told the last reported state in a microtask, as the observer itself won’t report it\n * again until it changes.\n * @param {Element} element Element to observe.\n * @param {(visible: boolean) => void} listener Function called with whether the element is visible.\n * @param {VisibilityOptions} [options] Options.\n * @returns {() => void} Function to stop observing. If `IntersectionObserver` is not available,\n * the listener is never called.\n */\nconst observeVisibility = (element, listener, { rootMargin = '0px' } = {}) => {\n  const shared = getMarginVisibilityObserver(rootMargin);\n\n  if (!shared) {\n    return () => {};\n  }\n\n  const { observer, listeners, states } = shared;\n  const elementListeners = listeners.get(element) ?? new Set();\n\n  if (!elementListeners.size) {\n    listeners.set(element, elementListeners);\n    observer.observe(element);\n  } else if (states.has(element) && !elementListeners.has(listener)) {\n    // The element is observed already, and its state has been reported, which the observer won’t\n    // do again until it changes. Tell the new listener in a microtask, like the observer, rather\n    // than before this function has returned\n    queueMicrotask(() => {\n      if (elementListeners.has(listener) && listeners.get(element) === elementListeners) {\n        listener(/** @type {boolean} */ (states.get(element)));\n      }\n    });\n  }\n\n  elementListeners.add(listener);\n\n  return () => {\n    elementListeners.delete(listener);\n\n    if (!elementListeners.size && listeners.get(element) === elementListeners) {\n      listeners.delete(element);\n      states.delete(element);\n      observer.unobserve(element);\n    }\n  };\n};\n\n/**\n * Call a function once the given element has stayed in or near the viewport for a moment. An\n * element that only passes through the viewport, as the rows do while a long list is scrolled\n * quickly, doesn’t count, so the work it would start isn’t queued ahead of what the user stops at.\n * @param {Element} element Element to observe.\n * @param {() => void} callback Function to call. If `IntersectionObserver` is not available, it’s\n * called in a microtask, so it’s never called before this function has returned.\n * @param {VisibilityOptions & { delay?: number }} [options] Options. `delay` is how long the\n * element has to stay visible, in milliseconds. Defaults to 100.\n * @returns {() => void} Function to cancel the call if it hasn’t been made yet.\n */\nconst whenSteadilyVisible = (element, callback, { delay = 100, ...options } = {}) => {\n  if (!('IntersectionObserver' in globalThis)) {\n    let cancelled = false;\n\n    queueMicrotask(() => {\n      if (!cancelled) {\n        callback();\n      }\n    });\n\n    return () => {\n      cancelled = true;\n    };\n  }\n\n  /** @type {ReturnType<typeof setTimeout> | undefined} */\n  let timer;\n\n  const stop = observeVisibility(\n    element,\n    (visible) => {\n      clearTimeout(timer);\n\n      if (visible) {\n        timer = setTimeout(() => {\n          stop();\n          callback();\n        }, delay);\n      }\n    },\n    options,\n  );\n\n  return () => {\n    clearTimeout(timer);\n    stop();\n  };\n};\n\n/**\n * Check whether the element is already visible in the viewport.\n * @param {HTMLElement} element Element to check.\n * @returns {boolean} Whether the element is visible.\n */\nconst isVisible = (element) => {\n  const { top, left, bottom, right } = element.getBoundingClientRect();\n  const { innerHeight, innerWidth } = globalThis;\n\n  return bottom > 0 && right > 0 && top < innerHeight && left < innerWidth;\n};\n\n/**\n * Schedule a callback to run on the next animation frame or a short timeout fallback.\n * @param {() => void} callback Callback to schedule.\n */\nconst scheduleVisibilityCheck = (callback) => {\n  if ('requestAnimationFrame' in globalThis) {\n    globalThis.requestAnimationFrame(callback);\n\n    return;\n  }\n\n  globalThis.setTimeout(callback, 16);\n};\n\n/**\n * Wait until the given element enters the viewport.\n * @param {HTMLElement} element Element to observe.\n * @returns {void | Promise<void>} Promise to be resolved when the element becomes visible. If\n * `IntersectionObserver` is not available, `undefined` will be returned instead.\n */\nconst waitForVisibility = (element) => {\n  const observer = getSharedVisibilityObserver();\n\n  if (!observer) {\n    return undefined;\n  }\n\n  if (isVisible(element)) {\n    return Promise.resolve(undefined);\n  }\n\n  return new Promise((resolve) => {\n    const previousResolve = visibilityResolvers.get(element);\n\n    // Keep any pending resolver for the same element so that earlier callers are resolved too,\n    // instead of being overwritten and left pending forever.\n    visibilityResolvers.set(\n      element,\n      previousResolve\n        ? () => {\n            previousResolve();\n            resolve();\n          }\n        : resolve,\n    );\n\n    scheduleVisibilityCheck(() => {\n      // Don’t start observing if the resolver was removed in the meantime; nothing would ever\n      // unobserve the element after that.\n      if (visibilityResolvers.has(element)) {\n        observer.observe(element);\n      }\n    });\n  });\n};\n\nexport {\n  generateElementId,\n  isVisible,\n  observeVisibility,\n  removeVisibilityResolver,\n  waitForVisibility,\n  whenSteadilyVisible,\n};\n","/**\n * Focus management shared by the composite widgets and the overlays.\n */\n\n/**\n * Selector for the elements that can hold focus.\n */\nconst FOCUSABLE_SELECTOR = 'a[href], button, input, select, textarea, summary, [tabindex]';\n\n/**\n * Move focus to the tab stop next to the given element in document order. Positive `tabindex`\n * values, which reorder the sequence, are not accounted for; they’re discouraged and absent from\n * this library.\n *\n * The candidates are narrowed by attribute alone before any of them is measured, and the measuring\n * — `getClientRects()`, which forces the browser to lay the page out — then walks outward from the\n * element and stops at the first candidate that is actually rendered. Measuring every focusable\n * element in the document up front is what a menu sitting on a large page cannot afford.\n * @internal\n * @param {HTMLElement} element Element to start from.\n * @param {boolean} backwards Whether to move to the previous tab stop rather than the next.\n */\nexport const focusAdjacentTabStop = (element, backwards) => {\n  const candidates = /** @type {HTMLElement[]} */ ([\n    ...document.querySelectorAll(FOCUSABLE_SELECTOR),\n  ]).filter(\n    (candidate) =>\n      candidate === element ||\n      (candidate.tabIndex >= 0 &&\n        !candidate.matches(':disabled, [aria-disabled=\"true\"], [hidden], [inert], [inert] *')),\n  );\n\n  const index = candidates.indexOf(element);\n\n  if (index === -1) {\n    return;\n  }\n\n  const step = backwards ? -1 : 1;\n\n  for (let i = index + step; i >= 0 && i < candidates.length; i += step) {\n    if (candidates[i].getClientRects().length) {\n      candidates[i].focus();\n\n      return;\n    }\n  }\n};\n\n/**\n * Move focus back to the given element once an overlay has closed — but only if focus is still\n * inside the overlay, or nowhere because the overlay took it down with itself. If it has already\n * moved on — the user tabbed out of a menu, say — pulling it back would undo what they just did.\n * @internal\n * @param {HTMLElement} element Element to move focus to, typically the one that opened the overlay.\n * @param {HTMLElement | null | undefined} container Overlay element.\n */\nexport const restoreFocus = (element, container) => {\n  const { activeElement } = document;\n\n  if (!element.isConnected) {\n    return;\n  }\n\n  if (!activeElement || activeElement === document.body || container?.contains(activeElement)) {\n    element.focus();\n  }\n};\n","/**\n * Arrow key navigation shared by the composite widgets. These functions only map a key and the\n * current position to a new position; finding the members and moving focus is up to the caller.\n */\n\n/**\n * CSS selector matching the members that are disabled or hidden, which are left out of navigation.\n */\nexport const INACTIVE_MEMBER_SELECTOR = '[aria-disabled=\"true\"], [aria-hidden=\"true\"]';\n\n/**\n * Check whether any modifier key — Shift, Alt, Control or Meta — is held down with a key press.\n * @param {KeyboardEvent} event `keydown` event.\n * @returns {boolean} Result.\n */\nexport const hasModifier = ({ shiftKey, altKey, ctrlKey, metaKey }) =>\n  shiftKey || altKey || ctrlKey || metaKey;\n\n/**\n * Get the arrow keys that move to the previous and next member along the given orientation. In a\n * right-to-left layout, the inline arrows are mirrored: ArrowLeft moves forward, ArrowRight back.\n * @param {string} orientation `horizontal` or `vertical`.\n * @param {boolean} rtl Whether the layout runs right to left.\n * @returns {{ prevKey: string, nextKey: string }} Keys.\n */\nexport const getArrowKeys = (orientation, rtl) => {\n  if (orientation === 'horizontal') {\n    return rtl\n      ? { prevKey: 'ArrowRight', nextKey: 'ArrowLeft' }\n      : { prevKey: 'ArrowLeft', nextKey: 'ArrowRight' };\n  }\n\n  return { prevKey: 'ArrowUp', nextKey: 'ArrowDown' };\n};\n\n/**\n * Get the index to move to in a list when an arrow key is pressed. The movement wraps around at\n * either end, and with nothing current yet, the previous key starts from the last member and the\n * next key from the first one.\n * @param {object} args Arguments.\n * @param {string} args.key Pressed key.\n * @param {number} args.index Index of the current member, or `-1` if there’s none.\n * @param {number} args.count Number of members.\n * @param {string} args.prevKey Key that moves to the previous member.\n * @param {string} args.nextKey Key that moves to the next member.\n * @returns {number} Index of the member to move to, or `-1` if the key doesn’t move.\n */\nexport const getLinearTargetIndex = ({ key, index, count, prevKey, nextKey }) => {\n  if (key === prevKey) {\n    return index > 0 ? index - 1 : count - 1;\n  }\n\n  if (key === nextKey) {\n    return index < count - 1 ? index + 1 : 0;\n  }\n\n  return -1;\n};\n\n/**\n * Get the index to move to in a grid layout when an arrow key is pressed. The vertical arrows move\n * by a visual row and the inline arrows by a single member, and none of them wraps around. With\n * nothing current yet, the arrows start from either end, as in a list.\n * @param {object} args Arguments.\n * @param {string} args.key Pressed key.\n * @param {number} args.index Index of the current member, or `-1` if there’s none.\n * @param {number} args.count Number of members.\n * @param {number} args.columnCount Number of members per visual row.\n * @param {string} args.prevKey Inline key that moves to the previous member.\n * @param {string} args.nextKey Inline key that moves to the next member.\n * @returns {number} Index of the member to move to, or `-1` if the key doesn’t move.\n */\nexport const getGridTargetIndex = ({ key, index, count, columnCount, prevKey, nextKey }) => {\n  const lastIndex = count - 1;\n  const backward = key === 'ArrowUp' || key === prevKey;\n  const forward = key === 'ArrowDown' || key === nextKey;\n\n  if (index === -1) {\n    if (forward) {\n      return 0;\n    }\n\n    return backward ? lastIndex : -1;\n  }\n\n  if (backward && index > 0) {\n    // Up by a row, stopping at the first member\n    return key === 'ArrowUp' ? Math.max(index - columnCount, 0) : index - 1;\n  }\n\n  if (forward && index < lastIndex) {\n    // Down by a row; a partial last row still gets reached\n    return key === 'ArrowDown' ? Math.min(index + columnCount, lastIndex) : index + 1;\n  }\n\n  return -1;\n};\n","/**\n * Pure helpers that work out where a popup goes and how large it can be, given the anchor’s rect\n * and the viewport size. They don’t touch the DOM, so they can be tested on their own.\n */\n\n/**\n * @import { PopupPosition } from '../typedefs.js';\n */\n\n/**\n * @typedef {object} PopupStyle\n * @property {string | undefined} inset The `inset` CSS property.\n * @property {number | undefined} zIndex The `z-index` CSS property.\n * @property {string | undefined} minWidth The `min-width` CSS property.\n * @property {string | undefined} maxWidth The `max-width` CSS property.\n * @property {string | undefined} height The `max-height` CSS property.\n */\n\n/**\n * @typedef {object} ViewportSize\n * @property {number} width Viewport width.\n * @property {number} height Viewport height.\n */\n\n/**\n * @typedef {object} ClippedRect\n * @property {number} top Top edge.\n * @property {number} left Left edge.\n * @property {number} right Right edge.\n * @property {number} bottom Bottom edge.\n * @property {number} width Width.\n * @property {number} height Height.\n */\n\n/**\n * Mirror a popup position for an RTL document, so `-left` becomes `-right`, `left-` becomes\n * `right-` and vice versa. The positions are written for LTR documents.\n * @internal\n * @param {PopupPosition} position Original position.\n * @returns {PopupPosition} Mirrored position.\n * @todo Rename `PopupPosition` enums to be direction-agnostic.\n */\nexport const mirrorPosition = (position) => {\n  let mirrored = position;\n\n  if (mirrored.endsWith('-left')) {\n    mirrored = /** @type {PopupPosition} */ (mirrored.replace('-left', '-right'));\n  } else if (mirrored.endsWith('-right')) {\n    mirrored = /** @type {PopupPosition} */ (mirrored.replace('-right', '-left'));\n  }\n\n  if (mirrored.startsWith('left-')) {\n    mirrored = /** @type {PopupPosition} */ (mirrored.replace('left-', 'right-'));\n  } else if (mirrored.startsWith('right-')) {\n    mirrored = /** @type {PopupPosition} */ (mirrored.replace('right-', 'left-'));\n  }\n\n  return mirrored;\n};\n\n/**\n * Clip the anchor’s rect to the viewport, mirroring what `IntersectionObserver` used to report as\n * `intersectionRect`.\n * @internal\n * @param {{ top: number, left: number, right: number, bottom: number }} anchorRect Anchor’s\n * bounding rect.\n * @param {ViewportSize} viewport Viewport size.\n * @returns {ClippedRect} Clipped rect.\n */\nexport const clipRect = (anchorRect, viewport) => {\n  const top = Math.max(anchorRect.top, 0);\n  const left = Math.max(anchorRect.left, 0);\n  const right = Math.min(anchorRect.right, viewport.width);\n  const bottom = Math.min(anchorRect.bottom, viewport.height);\n\n  return {\n    top,\n    left,\n    right,\n    bottom,\n    width: Math.max(0, right - left),\n    height: Math.max(0, bottom - top),\n  };\n};\n\n/**\n * Move a popup to the opposite side of its anchor when the content doesn’t fit on the current side\n * and the opposite side has more room. When the content doesn’t fit, the popup is also capped by\n * the room on the side it ends up on, so it scrolls instead of running past the viewport.\n * @internal\n * @param {object} args Arguments.\n * @param {PopupPosition} args.position Current position.\n * @param {string} args.from Part of the position denoting the current side, e.g. `bottom-`.\n * @param {string} args.to Part of the position denoting the opposite side, e.g. `top-`.\n * @param {number} args.size Content size along the axis.\n * @param {number} args.room Room on the current side.\n * @param {number} args.otherRoom Room on the opposite side.\n * @returns {{ position: PopupPosition, cap: number | undefined }} New position, and the size limit\n * if the content doesn’t fit, `undefined` otherwise.\n */\nexport const flip = ({ position, from, to, size, room, otherRoom }) => {\n  if (size <= room) {\n    return { position, cap: undefined };\n  }\n\n  if (otherRoom > room) {\n    return { position: /** @type {PopupPosition} */ (position.replace(from, to)), cap: otherRoom };\n  }\n\n  return { position, cap: room };\n};\n\n/**\n * Apply {@link flip} to whichever of the two opposite sides the position is on, if any.\n * @internal\n * @param {object} args Arguments.\n * @param {PopupPosition} args.position Current position.\n * @param {[string, string]} args.sides Parts of the position denoting the two sides, either both\n * prefixes like `bottom-` or both suffixes like `-left`.\n * @param {number} args.size Content size along the axis.\n * @param {[number, number]} args.rooms Room on each side, in the same order as `sides`.\n * @returns {{ position: PopupPosition, cap: number | undefined }} New position, and the size limit\n * if the content doesn’t fit, `undefined` otherwise or if the position is on neither side.\n */\nexport const flipEither = ({ position, sides, size, rooms }) => {\n  /**\n   * Check if the position is on the given side.\n   * @param {string} side Prefix or suffix.\n   * @returns {boolean} Result.\n   */\n  const isOn = (side) => (side.endsWith('-') ? position.startsWith(side) : position.endsWith(side));\n  const [sideA, sideB] = sides;\n  const [roomA, roomB] = rooms;\n\n  if (isOn(sideA)) {\n    return flip({ position, from: sideA, to: sideB, size, room: roomA, otherRoom: roomB });\n  }\n\n  if (isOn(sideB)) {\n    return flip({ position, from: sideB, to: sideA, size, room: roomB, otherRoom: roomA });\n  }\n\n  return { position, cap: undefined };\n};\n\n/**\n * Calculate the popup’s inset and size from the anchor’s rect, the viewport size and the content’s\n * natural size. The position may be altered if the space is limited.\n * @internal\n * @param {object} args Arguments.\n * @param {PopupPosition} args.position Preferred position, already mirrored for RTL if needed.\n * @param {{ top: number, left: number, right: number, bottom: number }} args.anchorRect Anchor’s\n * bounding rect.\n * @param {ViewportSize} args.viewport Viewport size.\n * @param {number} args.contentWidth Content’s natural width.\n * @param {number} args.contentHeight Content’s natural height.\n * @returns {PopupStyle} Popup style.\n */\nexport const calculatePopupStyle = ({\n  position: preferredPosition,\n  anchorRect,\n  viewport,\n  contentWidth,\n  contentHeight,\n}) => {\n  const rect = clipRect(anchorRect, viewport);\n  const topMargin = rect.top - 8;\n  const bottomMargin = viewport.height - rect.bottom - 8;\n  // A popup that opens beside its anchor is aligned with one of the anchor’s edges and extends\n  // across it, so its room is measured from that edge, not from the opposite one a dropdown\n  // hangs off\n  const leftMargin = rect.left - 8;\n  const rightMargin = viewport.width - rect.right - 8;\n  const downwardMargin = viewport.height - rect.top - 8;\n  const upwardMargin = rect.bottom - 8;\n  let position = preferredPosition;\n  /** @type {number | undefined} */\n  let height;\n\n  /**\n   * Apply {@link flipEither} vertically, keeping any height limit already set if the content fits.\n   * @param {[string, string]} sides Parts of the position denoting the two sides.\n   * @param {[number, number]} rooms Room on each side.\n   */\n  const flipVertically = (sides, rooms) => {\n    const result = flipEither({ position, sides, size: contentHeight, rooms });\n\n    position = result.position;\n    height = result.cap ?? height;\n  };\n\n  // Alter the position if the space is limited\n  flipVertically(['bottom-', 'top-'], [bottomMargin, topMargin]);\n\n  // Only a popup that opens beside its anchor carries a `-top`/`-bottom` suffix, and it grows\n  // away from the edge it’s aligned with: down from the anchor’s top, or up from its bottom. It\n  // gets the same treatment as the dropdown above — align with the other edge when the content\n  // doesn’t fit and that edge has more room, and cap it either way, so a long submenu scrolls\n  // instead of running past the viewport\n  flipVertically(['-top', '-bottom'], [downwardMargin, upwardMargin]);\n\n  // If the popup overflows the viewport, align it with the anchor’s other edge, but only when that\n  // side has more room. Checking each side on its own would flip a popup that fits neither way\n  // over and straight back, leaving it on whichever side was checked last\n  ({ position } = flipEither({\n    position,\n    sides: ['-left', '-right'],\n    size: contentWidth,\n    rooms: [viewport.width - rect.left - 8, rect.right - 8],\n  }));\n\n  // The two checks above align a dropdown that opens below or above its anchor, so neither\n  // covers a popup that opens beside one — a submenu — running off the edge it opens towards.\n  // That gets the same treatment as the vertical flip above: switch to the other side, but only\n  // when it has more room, so a submenu with nowhere to go stays where the caller put it. The\n  // width isn’t capped here; that’s done with `maxWidth` below.\n  ({ position } = flipEither({\n    position,\n    sides: ['right-', 'left-'],\n    size: contentWidth,\n    rooms: [rightMargin, leftMargin],\n  }));\n\n  const top = position.startsWith('bottom-')\n    ? `${Math.round(rect.bottom)}px`\n    : position.endsWith('-top')\n      ? `${Math.round(rect.top)}px`\n      : 'auto';\n\n  const right = position.startsWith('left-')\n    ? `${Math.round(viewport.width - rect.left)}px`\n    : position.endsWith('-right')\n      ? `${Math.round(viewport.width - rect.right)}px`\n      : 'auto';\n\n  const bottom = position.startsWith('top-')\n    ? `${Math.round(viewport.height - rect.top)}px`\n    : position.endsWith('-bottom')\n      ? `${Math.round(viewport.height - rect.bottom)}px`\n      : 'auto';\n\n  const left = position.startsWith('right-')\n    ? `${Math.round(rect.right)}px`\n    : position.endsWith('-left')\n      ? `${Math.round(rect.left)}px`\n      : 'auto';\n\n  return {\n    inset: [top, right, bottom, left].join(' '),\n    zIndex: 1000,\n    minWidth: `${Math.round(rect.width)}px`,\n    // A popup opening beside the anchor is capped by the room on that side, not by the width the\n    // anchor’s own edges leave, which is what the two dropdown cases below measure\n    maxWidth: position.startsWith('right-')\n      ? `${Math.round(rightMargin)}px`\n      : position.startsWith('left-')\n        ? `${Math.round(leftMargin)}px`\n        : position.endsWith('-left')\n          ? `${Math.round(viewport.width - rect.left - 8)}px`\n          : `${Math.round(rect.right - 8)}px`,\n    // `undefined` removes the `max-height` the popup is given, letting it take its natural size\n    // again. `auto` would look equivalent but isn’t a valid `max-height`, so the browser would\n    // drop it and leave whatever limit was applied last in place.\n    height: height ? `${Math.round(height)}px` : undefined,\n  };\n};\n\n/**\n * Check if two objects have the same keys with strictly equal values.\n * @internal\n * @param {Record<string, any>} a One object.\n * @param {Record<string, any>} b Another object.\n * @returns {boolean} Whether the objects are shallowly equal.\n */\nexport const isShallowEqual = (a, b) => {\n  const keys = Object.keys(a);\n\n  return (\n    keys.length === Object.keys(b).length &&\n    keys.every((key) => Object.hasOwn(b, key) && a[key] === b[key])\n  );\n};\n","import { isRTL } from '@sveltia/i18n';\nimport { generateElementId } from '@sveltia/utils/element';\nimport { sleep } from '@sveltia/utils/misc';\nimport { on } from 'svelte/events';\nimport { restoreFocus } from './focus.js';\nimport { hasModifier } from './navigation.js';\nimport { calculatePopupStyle, isShallowEqual, mirrorPosition } from './popup-position.js';\n\n/**\n * @import { PopupPosition } from '../typedefs.js';\n * @import { PopupStyle } from './popup-position.js';\n */\n\n/**\n * Implement the popup handler.\n */\nclass Popup {\n  #open = $state(false);\n\n  /**\n   * Whether the popup is open.\n   * @returns {boolean} `true` if the popup is open.\n   */\n  get open() {\n    return this.#open;\n  }\n\n  /**\n   * Open or close the popup, running side effects synchronously.\n   * @param {boolean} value `true` to open, `false` to close.\n   */\n  set open(value) {\n    this.#open = value;\n\n    if (value) {\n      this.checkPosition();\n    } else if (this.anchorElement.getAttribute('aria-expanded') === 'true') {\n      // Wait for the popup to close before focusing the anchor, otherwise the focus will be lost\n      window.requestAnimationFrame(() => {\n        restoreFocus(this.anchorElement, this.popupElement);\n      });\n    }\n\n    this.anchorElement.setAttribute('aria-expanded', String(value));\n  }\n\n  style = $state(\n    /** @type {PopupStyle} */\n    ({\n      inset: undefined,\n      zIndex: undefined,\n      minWidth: undefined,\n      maxWidth: undefined,\n      height: undefined,\n    }),\n  );\n\n  /**\n   * A reference to the `<dialog>` element used for the popup, which also serves as the backdrop.\n   * This is `undefined` while the element is not in the DOM tree, which is the case for a closed\n   * popup that doesn’t keep its content.\n   * @type {HTMLDialogElement | undefined}\n   */\n  popupElement = undefined;\n\n  /**\n   * A reference to the element holding the popup content. Unlike {@link popupElement}, which a\n   * nested popup shares with its parent, this element belongs to this popup alone, so it’s the one\n   * that carries the {@link id} and that the anchor’s `aria-controls` points at.\n   * @type {HTMLElement | undefined}\n   */\n  contentElement = undefined;\n\n  /**\n   * Whether the {@link popupElement} is shared with a parent popup, as a submenu’s is.\n   * @type {boolean}\n   */\n  nested = false;\n\n  /**\n   * Controller whose signal removes the event listeners added to the current {@link popupElement}.\n   * @type {AbortController | undefined}\n   */\n  #popupListeners = undefined;\n\n  /**\n   * Controller whose signal removes the event listeners added to the {@link anchorElement}, which\n   * may outlive this instance.\n   * @type {AbortController}\n   */\n  #anchorListeners = new AbortController();\n\n  /**\n   * Whether the {@link anchorElement} is a text field, which keeps its clicks and its Enter and\n   * Space keys.\n   * @type {boolean}\n   */\n  #anchorIsTextField = false;\n\n  /**\n   * ID of the animation frame requested to recalculate the position after a resize.\n   * @type {number}\n   */\n  _rafId = 0;\n\n  /**\n   * Initialize a new `Popup` instance. Note that the `popupElement` is optional, because the\n   * element is typically mounted only while the popup is open. Use {@link attachPopupElement} to\n   * provide it later.\n   * @param {HTMLElement} anchorElement Element that triggers the popup, typically a `<button>`.\n   * @param {HTMLDialogElement | undefined} popupElement `<dialog>` element to be used for the\n   * popup, if it’s already in the DOM tree.\n   * @param {PopupPosition} position Where to show the popup content.\n   * @param {HTMLElement} [positionBaseElement] The base element of the `position`. If omitted, this\n   * will be the `anchorElement`.\n   */\n  constructor(anchorElement, popupElement, position, positionBaseElement) {\n    this.anchorElement = anchorElement;\n    this.position = position;\n    this.positionBaseElement = positionBaseElement ?? anchorElement;\n    this.id = generateElementId('popup');\n\n    this.anchorElement.setAttribute('aria-expanded', 'false');\n\n    // A text field, such as the input of an editable combobox, needs its clicks to place the caret\n    // and its Enter and Space keys to type, so it’s not toggled by them. Its consumer provides a\n    // separate control, typically an expand button, while the arrow keys still open the popup.\n    this.#anchorIsTextField = anchorElement.matches('input, textarea, [contenteditable=\"true\"]');\n\n    const { signal } = this.#anchorListeners;\n\n    on(anchorElement, 'click', (event) => this.#onAnchorClick(event), { signal });\n    on(anchorElement, 'keydown', (event) => this.#onAnchorKeyDown(event), { signal });\n    on(anchorElement, 'transitionstart', () => this.#onAnchorTransitionStart(), { signal });\n\n    // A busy browser can report several changes at once, oldest first, so only the last entry tells\n    // whether the anchor is visible now\n    this.intersectionObserver = new IntersectionObserver((entries) => {\n      if (!entries.at(-1)?.isIntersecting && this.open) {\n        this.hideImmediately();\n      }\n    });\n    this.intersectionObserver.observe(this.anchorElement);\n\n    // Update the popup width when the base element is resized\n    this.resizeObserver = new ResizeObserver(() => {\n      cancelAnimationFrame(this._rafId);\n      this._rafId = requestAnimationFrame(() => this.checkPosition());\n    });\n    this.resizeObserver.observe(this.positionBaseElement);\n\n    // Recalculate the position when the viewport is resized. This is needed in addition to the\n    // `ResizeObserver` above, which only reacts to the anchor’s own size changing, not to it\n    // simply moving — which happens, for example, when a dialog containing the anchor is\n    // re-centered as the viewport is resized. This deliberately avoids the `resize` event on\n    // `window`, which isn’t guaranteed to fire for every layout-affecting viewport change across\n    // browsers; observing this popup’s own `<dialog>` element instead is reliable, because that\n    // element is always sized to exactly `100dvw` × `100dvh` (see `Modal.svelte`), so its box\n    // changes precisely when the viewport does — independent of the host app’s own CSS, unlike\n    // watching `document.body` or `document.documentElement` would be.\n    this.viewportResizeObserver = new ResizeObserver(() => {\n      if (this.open) {\n        this.checkPosition();\n      }\n    });\n\n    if (popupElement) {\n      this.attachPopupElement(popupElement);\n    }\n  }\n\n  /**\n   * Attach the `<dialog>` element used for the popup. This is called every time the element is\n   * mounted, which happens on each open.\n   * @param {HTMLDialogElement} popupElement `<dialog>` element to be used for the popup. A nested\n   * popup shares this with its parent, so it must not be labelled as belonging to this popup.\n   * @param {HTMLElement} [contentElement] Element holding this popup’s content. When omitted, the\n   * `popupElement` is assumed to hold the content on its own.\n   * @param {object} [options] Options.\n   * @param {boolean} [options.nested] Whether the `popupElement` is shared with a parent popup.\n   */\n  attachPopupElement(popupElement, contentElement, { nested = false } = {}) {\n    if (this.popupElement === popupElement && this.contentElement === contentElement) {\n      return;\n    }\n\n    this.detachPopupElement();\n    this.popupElement = popupElement;\n    this.contentElement = contentElement;\n    this.nested = nested;\n    this.viewportResizeObserver.observe(popupElement);\n\n    // Identify the popup by the element that actually holds its content. Labelling the `<dialog>`\n    // would be wrong for a nested popup, which shares its parent’s: it would overwrite the parent’s\n    // own `id` and leave the anchor pointing at the parent instead of the submenu.\n    const identifiedElement = contentElement ?? popupElement;\n\n    identifiedElement.id = this.id;\n    this.anchorElement.setAttribute('aria-controls', this.id);\n\n    this.#popupListeners = new AbortController();\n\n    const { signal } = this.#popupListeners;\n\n    on(popupElement, 'click', (event) => this.#onPopupClick(event), { signal });\n    on(popupElement, 'keydown', (event) => this.#onPopupKeyDown(event), { signal });\n  }\n\n  /**\n   * Handle the `click` event on the anchor: toggle the popup.\n   * @param {MouseEvent} event `click` event.\n   */\n  #onAnchorClick(event) {\n    if (!this.#anchorIsTextField && !this.isDisabled && !this.isReadOnly) {\n      // A menu item’s submenu may already have been opened by hovering, which also happens right\n      // before a tap on a touch screen, so a pointer click only opens it rather than toggling it\n      // closed. A scripted click, which has no `detail`, still toggles it: that’s how the keyboard\n      // navigation closes a submenu.\n      this.open =\n        event.detail && this.anchorElement.matches('[role=\"menuitem\"]') ? true : !this.open;\n    }\n  }\n\n  /**\n   * Handle the `keydown` event on the anchor: toggle the popup with Enter or Space, and open it\n   * with the arrow keys.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  #onAnchorKeyDown(event) {\n    const { key, ctrlKey, metaKey, shiftKey, altKey } = event;\n    const { anchorElement } = this;\n\n    if (this.isDisabled || this.isReadOnly) {\n      return;\n    }\n\n    if (!this.#anchorIsTextField && ['Enter', ' '].includes(key) && !hasModifier(event)) {\n      event.preventDefault();\n      event.stopPropagation();\n      this.open = !this.open;\n\n      return;\n    }\n\n    // The arrow keys open a listbox or menu, the way they do a native `<select>`; Alt+Down is the\n    // combobox convention (APG Select-Only Combobox, Menu Button). They never close one: inside the\n    // popup they belong to the list. A menu item that opens a submenu is left alone: there the\n    // arrows move through the parent menu, and the submenu opens with the inline arrow.\n    if (\n      ['ArrowDown', 'ArrowUp'].includes(key) &&\n      !(shiftKey || ctrlKey || metaKey) &&\n      (!altKey || key === 'ArrowDown') &&\n      ['listbox', 'menu'].includes(anchorElement.getAttribute('aria-haspopup') ?? '') &&\n      !anchorElement.matches('[role^=\"menuitem\"]') &&\n      !this.open\n    ) {\n      event.preventDefault();\n      event.stopPropagation();\n      this.open = true;\n    }\n  }\n\n  /**\n   * Handle the `transitionstart` event on the anchor: hide the popup right away when the anchor is\n   * being hidden.\n   */\n  #onAnchorTransitionStart() {\n    if (this.anchorElement.closest('.hiding, .hidden, [hidden]')) {\n      this.hideImmediately();\n    }\n  }\n\n  /**\n   * Handle the `click` event on the popup: close it when the backdrop, a menu item or an option is\n   * clicked.\n   * @param {MouseEvent} event `click` event.\n   */\n  #onPopupClick(event) {\n    event.stopPropagation();\n\n    // eslint-disable-next-line prefer-destructuring\n    const target = /** @type {HTMLElement} */ (event.target);\n\n    if (\n      this.open &&\n      (target === this.popupElement || target.matches('[role^=\"menuitem\"], [role=\"option\"]'))\n    ) {\n      this.open = false;\n    }\n  }\n\n  /**\n   * Handle the `keydown` event on the popup: close it with Escape.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  #onPopupKeyDown(event) {\n    if (event.key === 'Escape' && !hasModifier(event)) {\n      event.preventDefault();\n      event.stopPropagation();\n      this.open = false;\n    }\n  }\n\n  /**\n   * Detach the `<dialog>` element, typically because it’s being unmounted. The anchor’s\n   * `aria-controls` attribute is removed as well, since the content is leaving the DOM tree.\n   */\n  detachPopupElement() {\n    this.#popupListeners?.abort();\n    this.#popupListeners = undefined;\n\n    if (this.popupElement) {\n      this.viewportResizeObserver.unobserve(this.popupElement);\n    }\n\n    // The content is leaving the DOM tree, so the anchor must stop referencing it. Only clear a\n    // reference this popup owns; the consumer may have pointed the anchor somewhere else.\n    if (this.anchorElement.getAttribute('aria-controls') === this.id) {\n      this.anchorElement.removeAttribute('aria-controls');\n    }\n\n    this.popupElement = undefined;\n    this.contentElement = undefined;\n  }\n\n  /**\n   * Whether the anchor element is disabled.\n   * @type {boolean}\n   */\n  get isDisabled() {\n    return this.anchorElement.matches('[aria-disabled=\"true\"]');\n  }\n\n  /**\n   * Whether the anchor element is read-only.\n   * @type {boolean}\n   */\n  get isReadOnly() {\n    return this.anchorElement.matches('[aria-readonly=\"true\"]');\n  }\n\n  /**\n   * Check the position of the anchor element and, if the popup is mounted, recalculate and apply\n   * its inset and size. This is a no-op while the popup element is not in the DOM tree; the caller\n   * is expected to call this again once the element is attached.\n   *\n   * This measures the anchor synchronously with `getBoundingClientRect()` rather than reacting to\n   * an `IntersectionObserver`, whose delivery isn’t guaranteed to be timely or frame-aligned the\n   * way `ResizeObserver`’s is: a stale computation could arrive after a fresher one and silently\n   * overwrite it, occasionally leaving the popup mispositioned after a resize.\n   */\n  checkPosition() {\n    if (!this.popupElement) {\n      return;\n    }\n\n    // Use the tracked content element rather than searching the popup element, which for a nested\n    // popup is the shared parent `<dialog>` and would yield the parent’s content\n    const content = /** @type {HTMLElement | null} */ (\n      this.contentElement ?? this.popupElement?.querySelector('.content') ?? null\n    );\n\n    // The content is not in the DOM tree yet; `checkPosition()` will be called again once the\n    // popup element is attached\n    if (!content) {\n      return;\n    }\n\n    // Measure the content at its natural size, with any limit previously applied here taken off\n    // first. A popup that delegates its scrolling to a child — the combobox hands it to the option\n    // list, so the filter stays put — reports a `scrollHeight` no larger than the `max-height` it’s\n    // already capped at, and the same goes for `scrollWidth` against `max-width`. Measuring those\n    // clipped values would make the cap stick: once the popup had shrunk to fit a small viewport,\n    // it could never grow back when the viewport did. The properties are put back synchronously,\n    // before the browser can paint, so nothing flickers.\n    const anchorRect = this.positionBaseElement.getBoundingClientRect();\n    const { maxHeight: appliedMaxHeight, maxWidth: appliedMaxWidth } = content.style;\n\n    content.style.maxHeight = '';\n    content.style.maxWidth = '';\n\n    const { scrollHeight: contentHeight, scrollWidth: contentWidth } = content;\n\n    content.style.maxHeight = appliedMaxHeight;\n    content.style.maxWidth = appliedMaxWidth;\n\n    const style = calculatePopupStyle({\n      // Normalize RTL-friendly positions to LTR for LTR documents\n      position: isRTL() ? mirrorPosition(this.position) : this.position,\n      anchorRect,\n      viewport: { width: window.innerWidth, height: window.innerHeight },\n      contentWidth,\n      contentHeight,\n    });\n\n    if (!isShallowEqual(style, this.style)) {\n      this.style = style;\n    }\n  }\n\n  /**\n   * Hide the popup immediately (when the anchor is being hidden).\n   */\n  async hideImmediately() {\n    // A submenu only hides its own content, not the `<dialog>` it shares with its parent menu,\n    // which would make the whole menu blink and drop the focus in it\n    const element = this.nested ? this.contentElement : this.popupElement;\n\n    if (element) {\n      element.hidden = true;\n    }\n\n    this.open = false;\n    await sleep(50);\n\n    // The element may have been unmounted in the meantime\n    if (element?.isConnected) {\n      element.hidden = false;\n    }\n  }\n\n  /**\n   * Dispose of the popup, disconnecting observers and canceling pending work.\n   */\n  destroy() {\n    this.detachPopupElement();\n    this.#anchorListeners.abort();\n    this.intersectionObserver?.disconnect();\n    this.resizeObserver?.disconnect();\n    this.viewportResizeObserver?.disconnect();\n\n    if (this._rafId) {\n      cancelAnimationFrame(this._rafId);\n    }\n  }\n}\n\n/**\n * Activate a new popup.\n * @param {ConstructorParameters<typeof Popup>} args Arguments passed to the `Popup` constructor.\n * @returns {Popup} New popup.\n */\nexport const activatePopup = (...args) => new Popup(...args);\n","/**\n * Helpers behind `<Modal>`, kept apart from the component so they can be tested on their own.\n */\n\n/**\n * Get the longest time from a computed CSS time list, such as `transition-duration`.\n * @param {string} value Comma-separated CSS time values in seconds, e.g. `0.4s, 0.15s`.\n * @returns {number} Time in milliseconds, `0` if the list is empty or holds no valid time.\n */\nexport const getLongestTime = (value) =>\n  Math.max(0, ...value.split(',').map((time) => Number.parseFloat(time) || 0)) * 1000;\n\n/**\n * Get how long the closing or opening transition of a `<dialog>` can take, so a fallback timer can\n * be set in case `transitionend` is never fired, for example when the transition is removed by the\n * consumer’s CSS or the element is not rendered at all.\n * @param {{ transitionDuration: string, transitionDelay: string }} style Computed style of the\n * element.\n * @returns {number} Time in milliseconds, with a small margin added.\n */\nexport const getTransitionTimeout = ({ transitionDuration, transitionDelay }) =>\n  getLongestTime(transitionDuration) + getLongestTime(transitionDelay) + 100;\n\n/**\n * The modal `<dialog>` elements shown by `<Modal>`, in the order they were opened, the topmost\n * last. The elements are placed in the document in the order the components are mounted, which\n * tells nothing about which one is on top, so others like `<Toast>` can look here instead.\n * @type {HTMLDialogElement[]}\n */\nexport const openModalDialogs = [];\n\n/**\n * Remove the given `<dialog>` element from {@link openModalDialogs}.\n * @param {HTMLDialogElement | undefined} dialog Element.\n */\nexport const forgetModalDialog = (dialog) => {\n  const index = dialog ? openModalDialogs.indexOf(dialog) : -1;\n\n  if (index > -1) {\n    openModalDialogs.splice(index, 1);\n  }\n};\n\n/**\n * Add the given `<dialog>` element to {@link openModalDialogs} as the topmost one, moving it there\n * if it’s already in the list.\n * @param {HTMLDialogElement} dialog Element.\n */\nexport const rememberModalDialog = (dialog) => {\n  forgetModalDialog(dialog);\n  openModalDialogs.push(dialog);\n};\n","<!--\n  @component\n  @see https://github.com/sveltejs/svelte/issues/3088\n-->\n<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Snippet} [children] Primary slot content.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    children,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n{@render children?.()}\n","<!--\n  @component\n  A generic modal top-layer helper based on the HTML `<dialog>` element.\n-->\n<script module>\n  /**\n   * Context key used by a modal to keep the modal it’s rendered within mounted.\n   * @type {symbol}\n   */\n  const RETAINER_KEY = Symbol('sui-modal-retainer');\n</script>\n\n<script>\n  import {\n    getAllContexts,\n    getContext,\n    mount,\n    onMount,\n    setContext,\n    tick,\n    unmount,\n    untrack,\n  } from 'svelte';\n  // Aliased, since the component has a `restoreFocus` prop of its own\n  import { restoreFocus as returnFocus } from '../../services/focus.js';\n  import { forgetModalDialog, getTransitionTimeout, rememberModalDialog } from './modal.js';\n  import Placeholder from './placeholder.svelte';\n\n  /**\n   * @import { ModalProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ModalProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    dialog: boundDialog = $bindable(),\n    class: className,\n    role = 'dialog',\n    modal = true,\n    showBackdrop = false,\n    lightDismiss = false,\n    escapeDismiss = true,\n    keepContent = false,\n    restoreFocus = true,\n    children,\n    extraContent,\n    onOpening,\n    onOpen,\n    onClosing,\n    onOk,\n    onCancel,\n    onClose,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * A reference to the `<dialog>` element. This is kept apart from the bindable `dialog` prop: when\n   * the consumer doesn’t bind that prop, Svelte discards the value assigned to it locally as soon\n   * as any of the props spread onto this component changes, such as the labelling attributes of a\n   * `<Dialog>` whose title has been updated, which would leave the modal unable to open or close.\n   * @type {HTMLDialogElement | undefined}\n   */\n  let dialog = $state.raw();\n\n  /**\n   * Focus the `<dialog>` element. It has `tabindex=\"-1\"`, so it can receive focus programmatically,\n   * allowing assistive technology to announce the modal’s label and description.\n   */\n  export const focus = () => {\n    dialog?.focus();\n  };\n\n  /**\n   * Show the `<dialog>` element, as a modal unless {@link modal} is disabled. A non-modal dialog\n   * leaves the rest of the page usable: it isn’t put in the top layer and doesn’t make the page\n   * `inert`.\n   */\n  const showDialog = () => {\n    if (modal) {\n      dialog?.showModal();\n\n      if (dialog) {\n        rememberModalDialog(dialog);\n      }\n    } else {\n      dialog?.show();\n    }\n  };\n\n  /**\n   * Close the modal.\n   * @param {string} returnValue Return value to be used for `<dialog>`.\n   */\n  export const close = (returnValue) => {\n    if (!dialog) {\n      return;\n    }\n\n    dialog.returnValue = returnValue;\n    open = false;\n  };\n\n  let setOpenClass = $state(false);\n  let setActiveClass = $state(false);\n  /**\n   * Whether the modal is being displayed. This is enabled just before the opening transition\n   * starts, and disabled right after the closing transition is complete.\n   * @type {boolean}\n   */\n  let visible = $state(false);\n\n  /**\n   * The number of descendant modals that are currently being displayed. A popup’s content is\n   * unmounted as soon as the popup closes, which would also destroy any modal declared alongside\n   * it, such as a dialog opened from a menu item. Because the menu item inevitably goes away with\n   * the menu, the dialog has to outlive it, so the content is held until the dialog is done with.\n   * @type {number}\n   */\n  let retainCount = $state(0);\n\n  /**\n   * The retainer of the modal this modal is rendered within, if any. This has to be read before the\n   * `setContext()` call below, which would otherwise shadow it with this modal’s own retainer.\n   * @type {{ retain: () => void, release: () => void } | undefined}\n   */\n  const parentRetainer = getContext(RETAINER_KEY);\n\n  // This has to be set before `getAllContexts()` below, so the content, which is rendered in a\n  // separate component tree, can reach it. The counter is updated within `untrack()`, because\n  // incrementing it reads it first, which would otherwise make it a dependency of the calling\n  // descendant’s effect and send that effect into an endless retain/release loop.\n  setContext(RETAINER_KEY, {\n    /**\n     * Keep this modal mounted on behalf of a descendant modal.\n     */\n    retain: () => {\n      untrack(() => {\n        retainCount += 1;\n      });\n    },\n    /**\n     * Release a hold previously acquired with `retain`.\n     */\n    release: () => {\n      untrack(() => {\n        retainCount -= 1;\n      });\n    },\n  });\n\n  /**\n   * Whether the `<dialog>` element is in the DOM tree. Unless {@link keepContent} is enabled, the\n   * element is mounted on demand, and unmounted once the closing transition is complete.\n   * @type {boolean}\n   */\n  const mounted = $derived(keepContent || visible || retainCount > 0);\n\n  /**\n   * Whether the modal has been requested to open. Unlike the {@link open} prop, this is a plain\n   * variable updated synchronously at the very beginning of `openDialog`/`closeDialog`, so either\n   * of them can bail out early when the requested state is already in effect.\n   * @type {boolean}\n   */\n  let requestedOpen = false;\n\n  /**\n   * Monotonically increasing counter used to detect stale async operations. Incremented at the\n   * start of each `openDialog`/`closeDialog` call; any suspended continuation that finds its\n   * captured value no longer matches the current counter knows it has been superseded and exits\n   * without mutating state.\n   * @type {number}\n   */\n  let generation = 0;\n\n  /**\n   * The element that had the focus just before the modal was opened. The focus is moved back to it\n   * once the modal is closed.\n   * @type {HTMLElement | undefined}\n   */\n  let lastActiveElement;\n\n  /**\n   * The element the last `pointerdown` event in the modal was fired on. A click that lands on the\n   * backdrop only dismisses the modal if the pointer was also pressed there, so selecting text in\n   * the content by dragging and releasing the pointer over the backdrop doesn’t close it.\n   * @type {EventTarget | null | undefined}\n   */\n  let pointerDownTarget;\n\n  /**\n   * Timer used to defer the focus restoration in {@link moveFocusBack}.\n   * @type {number | undefined}\n   */\n  let restoreFocusTimer;\n\n  /**\n   * Move the focus back to the element that had it before the modal was opened. This is done\n   * manually rather than relying on the browser’s own focus restoration, because the modal is\n   * closed while `<body>` is `inert`, which prevents the focus from being restored.\n   */\n  const moveFocusBack = () => {\n    const element = lastActiveElement;\n\n    lastActiveElement = undefined;\n\n    if (!restoreFocus || !element) {\n      return;\n    }\n\n    // Wait for the current task to finish before moving the focus. The modal is typically closed\n    // from within an event handler, and the event that triggered it is still being processed:\n    // Firefox dispatches `keypress` to whatever holds the focus at that point, so restoring it\n    // synchronously would let the Enter key that submitted the modal activate the button that\n    // opened it, immediately reopening the modal.\n    restoreFocusTimer = window.setTimeout(() => {\n      returnFocus(element, dialog);\n    });\n  };\n\n  /**\n   * Resolve once the transition is complete.\n   * @returns {Promise<void>} Nothing.\n   */\n  const waitForTransition = async () => {\n    // Let the CSS class change be applied first, so the duration below is read from the new state\n    await tick();\n\n    if (!dialog) {\n      return;\n    }\n\n    // Fall back to a timer, so the modal is never stuck half-open (and, more importantly, never\n    // left mounted) in case `transitionend` is never fired, e.g. when the transition is removed by\n    // the consumer’s CSS or the element is not rendered at all\n    const timeout = getTransitionTimeout(getComputedStyle(dialog));\n    const controller = new AbortController();\n    const { signal } = controller;\n\n    dialog.addEventListener(\n      'transitionend',\n      (event) => {\n        if (event.target === dialog) {\n          controller.abort();\n        }\n      },\n      { signal },\n    );\n\n    const timer = window.setTimeout(() => controller.abort(), timeout);\n\n    await new Promise((resolve) => {\n      signal.addEventListener('abort', () => resolve(undefined));\n    });\n\n    window.clearTimeout(timer);\n  };\n\n  /**\n   * Show the modal.\n   */\n  const openDialog = async () => {\n    // Only called when the `open` prop changes, so it can’t be requested twice in a row\n    /* v8 ignore next */\n    if (requestedOpen) {\n      return;\n    }\n\n    requestedOpen = true;\n    generation += 1;\n\n    const gen = generation;\n    const { activeElement } = document;\n\n    // Cancel a pending restoration from a previous close, which would otherwise pull the focus out\n    // of the modal that’s being opened right now\n    window.clearTimeout(restoreFocusTimer);\n    lastActiveElement = activeElement instanceof HTMLElement ? activeElement : undefined;\n\n    onOpening?.(new CustomEvent('Opening'));\n    visible = true;\n    // Wait for the `<dialog>` element to be added to the DOM tree\n    await tick();\n\n    if (gen !== generation || !dialog || dialog.open) return;\n\n    // Clear the return value left by a close that has been cut short by this reopening, so it isn’t\n    // taken for the return value of the next close. A finished close clears it itself.\n    dialog.returnValue = '';\n    showDialog();\n    onOpen?.(new CustomEvent('Open'));\n    // Force a style recalculation, so the browser has a state to transition from. This is required\n    // because the element may have just been added to the DOM tree.\n    dialog.getBoundingClientRect();\n    setOpenClass = true;\n    // Wait for the `inert` attribute to be removed, then move the focus into the modal. The\n    // browser’s own dialog focusing steps don’t do this, because the element is still `inert` when\n    // `showModal()` is called above, leaving the focus on `<body>`. A component using this modal,\n    // such as `<Dialog>`, may then move the focus to a specific control, like an input field.\n    await tick();\n\n    // The focus is on `<body>` at this point, because the element was still `inert` when shown\n    /* v8 ignore next */\n    if (gen !== generation || !dialog) return;\n\n    /* v8 ignore else */\n    if (!dialog.contains(document.activeElement)) {\n      focus();\n    }\n\n    await waitForTransition();\n    if (gen !== generation) return;\n    setActiveClass = true;\n  };\n\n  /**\n   * Hide the modal.\n   */\n  const closeDialog = async () => {\n    if (!requestedOpen) {\n      return;\n    }\n\n    requestedOpen = false;\n    generation += 1;\n\n    const gen = generation;\n    const wasOpen = setOpenClass;\n    // The element is mounted by the time a close can be requested; see `openDialog()` above\n    /* v8 ignore next */\n    const returnValue = dialog?.returnValue ?? '';\n\n    onClosing?.(new CustomEvent('Closing'));\n\n    if (dialog?.open) {\n      // Prevent a button behind the `<dialog>` from being clicked erroneously (Svelte bug)\n      document.body.inert = true;\n      dialog.close();\n      document.body.inert = false;\n    }\n\n    moveFocusBack();\n    setActiveClass = false;\n    setOpenClass = false;\n\n    // Only wait for the closing transition if the dialog was visually open (i.e. the `.open` CSS\n    // class was set). If the dialog was closed before the opening transition even started, there is\n    // no CSS transition in progress and `transitionend` will never fire.\n    if (wasOpen) {\n      await waitForTransition();\n    }\n\n    if (gen !== generation) return;\n\n    // Unmount the `<dialog>` element unless `keepContent` is enabled\n    visible = false;\n\n    if (returnValue === 'ok') {\n      onOk?.(new CustomEvent('Ok'));\n    }\n\n    if (returnValue === 'cancel') {\n      onCancel?.(new CustomEvent('Cancel'));\n    }\n\n    onClose?.(new CustomEvent('Close', { detail: { returnValue } }));\n\n    if (dialog) {\n      dialog.returnValue = '';\n    }\n  };\n\n  /**\n   * The context available to this component. The `<dialog>` element is rendered in a separate\n   * component tree created with `mount()`, which would otherwise start with an empty context, so\n   * this is forwarded to keep `getContext()` working for the modal content.\n   * @type {Map<any, any>}\n   */\n  const context = getAllContexts();\n\n  onMount(() => {\n    const placeholder = mount(Placeholder, {\n      target: document.querySelector('.sui.app-shell') ?? document.body,\n      // eslint-disable-next-line no-use-before-define\n      props: { children: dialogSnippet },\n      context,\n    });\n\n    // onUnmount\n    return () => {\n      window.clearTimeout(restoreFocusTimer);\n      dialog?.close();\n      forgetModalDialog(dialog);\n      unmount(placeholder);\n    };\n  });\n\n  // This must be declared after `onMount()` above, because effects run in declaration order, and\n  // `openDialog()` expects the placeholder holding the `<dialog>` element to be already mounted\n  $effect(() => {\n    if (open) {\n      openDialog();\n    } else {\n      closeDialog();\n    }\n  });\n\n  // Hold the enclosing modal, if any, for as long as this one is on screen. `visible` is used\n  // rather than `mounted`, so a `keepContent` modal doesn’t pin its ancestor forever\n  $effect(() => {\n    if (!visible) {\n      return undefined;\n    }\n\n    parentRetainer?.retain();\n\n    return () => {\n      parentRetainer?.release();\n    };\n  });\n</script>\n\n{#snippet dialogSnippet()}\n  {#if mounted}\n    <dialog\n      bind:this={\n        () => dialog,\n        (element) => {\n          dialog = element;\n          boundDialog = element;\n        }\n      }\n      tabindex=\"-1\"\n      {...restProps}\n      inert={!setOpenClass}\n      {role}\n      class=\"sui modal {className}\"\n      class:backdrop={showBackdrop}\n      class:non-modal={!modal}\n      class:open={setOpenClass}\n      class:active={setActiveClass}\n      onpointerdown={({ target }) => {\n        pointerDownTarget = target;\n      }}\n      onclick={({ target }) => {\n        const downTarget = pointerDownTarget;\n\n        pointerDownTarget = undefined;\n\n        // A click with no `pointerdown` before it, like one dispatched by a script, is taken as is\n        if (downTarget && downTarget !== dialog) {\n          return;\n        }\n\n        if (lightDismiss && /** @type {HTMLElement | undefined} */ (target)?.matches('dialog')) {\n          close('cancel');\n        }\n      }}\n      onkeydown={(event) => {\n        // A non-modal dialog gets no `cancel` event from the browser when Escape is pressed, so the\n        // key is handled here instead, as long as the focus is within the dialog. Escape that\n        // cancels an IME composition is left to the input method, as the browser does for a modal\n        if (modal || event.key !== 'Escape' || event.isComposing || event.defaultPrevented) {\n          return;\n        }\n\n        event.preventDefault();\n\n        if (escapeDismiss) {\n          close('cancel');\n        }\n      }}\n      oncancel={(event) => {\n        event.preventDefault();\n\n        // Escape key is pressed\n        if (escapeDismiss) {\n          close('cancel');\n        }\n      }}\n      onclose={() => {\n        if (!dialog?.open) {\n          forgetModalDialog(dialog);\n        }\n\n        // Closed by `closeDialog()` or on unmount, or already shown again by `openDialog()`\n        if (!requestedOpen || !dialog?.isConnected || dialog.open) {\n          return;\n        }\n\n        // The browser has closed the dialog on its own. The `cancel` event can’t always be\n        // prevented: Chrome makes it non-cancelable when Escape is pressed again without any user\n        // activation in between. Show the dialog again if it shouldn’t be dismissed with Escape,\n        // otherwise bring the state in line, so the usual closing steps run.\n        if (!escapeDismiss) {\n          showDialog();\n        } else {\n          open = false;\n        }\n      }}\n    >\n      {@render extraContent?.()}\n      {@render children?.()}\n    </dialog>\n  {/if}\n{/snippet}\n\n<style>dialog {\n  position: fixed;\n  inset: 0;\n  z-index: 9999999;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  overflow: hidden;\n  outline: 0;\n  margin: 0;\n  border: 0;\n  padding: 0;\n  width: 100dvw;\n  max-width: 100dvw;\n  height: 100dvh;\n  max-height: 100dvh;\n  color: var(--sui-primary-foreground-color);\n  background: transparent;\n  -webkit-user-select: none;\n  user-select: none;\n  touch-action: none;\n  pointer-events: all;\n  cursor: default;\n}\ndialog::backdrop {\n  background: transparent;\n}\ndialog.backdrop {\n  background-color: var(--sui-popup-backdrop-color);\n}\ndialog.non-modal {\n  pointer-events: none;\n}\ndialog.non-modal.active > :global(*) {\n  pointer-events: auto;\n}\ndialog.open {\n  transition-duration: 50ms;\n  opacity: 1;\n}\ndialog:not(.open) {\n  transition-duration: 400ms;\n  opacity: 0;\n}\ndialog[hidden] {\n  transition-duration: 1ms !important;\n}\ndialog:not(.active) {\n  pointer-events: none !important;\n}\ndialog:not(.active) :global(*) {\n  transition-duration: 0ms !important;\n  pointer-events: none !important;\n}</style>\n","<!--\n  @component\n  Generic popup helper.\n-->\n<script>\n  import { sleep } from '@sveltia/utils/misc';\n  import { onMount, tick } from 'svelte';\n  import { activatePopup } from '../../services/popup.svelte.js';\n  import Modal from './modal.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ModalProps, PopupPosition } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the content element.\n   * @property {boolean} [open] Whether to open the popup.\n   * @property {boolean} [hovered] Whether the content is hovered.\n   * @property {HTMLElement} [anchor] A reference to the anchor element that opens the popup.\n   * Typically a `<button>`.\n   * @property {HTMLElement} [content] A reference to the content element.\n   * @property {PopupPosition} [position] Where to show the popup.\n   * @property {HTMLElement} [positionBaseElement] The base element of {@link position}. If omitted,\n   * this will be {@link anchor}.\n   * @property {HTMLDialogElement} [parentDialogElement] A reference to a dialog element that is\n   * already displayed. This should be provided for a nested popup.\n   * @property {boolean} [touchOptimized] Whether to show the popup at the center of the screen on\n   * mobile/tablet and ignore the defined dropdown `position`.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {Snippet} [extraContent] Extra slot content.\n   * @property {(event: CustomEvent) => void} [onOpen] Custom `Open` event handler.\n   */\n\n  /**\n   * @type {ModalProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    hovered = $bindable(false),\n    content: boundContent = $bindable(),\n    class: className,\n    showBackdrop = undefined,\n    anchor,\n    position = 'bottom-left',\n    positionBaseElement = undefined,\n    parentDialogElement = undefined,\n    touchOptimized = false,\n    children,\n    onOpen,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * A reference to the content element. It’s kept apart from the bindable `content` prop, which\n   * Svelte resets whenever the props spread onto this component change, unless the consumer binds\n   * it.\n   * @type {HTMLElement | undefined}\n   */\n  let content = $state.raw();\n\n  /**\n   * A reference to the `<dialog>` element. This is only available while the popup is open, because\n   * the element is mounted on demand.\n   * @type {HTMLDialogElement | undefined}\n   */\n  let dialogElement = $state();\n  /**\n   * Whether the touch is enabled on the user device.\n   * @type {boolean}\n   */\n  let touchEnabled = $state(false);\n  /**\n   * The type of the content displayed in the popup, defined with the `aria-haspopup` attribute on\n   * the anchor element.\n   * @type {string | undefined}\n   * @see https://w3c.github.io/aria/#aria-haspopup\n   */\n  let contentType = $state();\n  /**\n   * @type {ReturnType<typeof activatePopup> | undefined}\n   */\n  let popupInstance = $state();\n  let hoveredTimeout = 0;\n\n  /**\n   * Move the focus into the content. A composite widget keeps exactly one of its items in the tab\n   * order and takes its own root out of it, so the item is what should receive focus. Falling back\n   * to any focusable element covers the popups that hold plain content.\n   * @param {object} [options] Options.\n   * @param {boolean} [options.tabStopOnly] Whether to only focus an element in the tab order,\n   * without falling back to any other element.\n   * @returns {boolean} Whether an element has taken the focus.\n   */\n  const focusContent = ({ tabStopOnly = false } = {}) => {\n    /* v8 ignore next 3 -- the callers check the content first */\n    if (!content) {\n      return false;\n    }\n\n    const candidates = /** @type {HTMLElement[]} */ ([\n      ...content.querySelectorAll('[tabindex=\"0\"]:not([aria-disabled=\"true\"])'),\n      ...(tabStopOnly ? [] : content.querySelectorAll('[tabindex]:not([aria-disabled=\"true\"])')),\n    ]);\n\n    // Skip an element that can’t take the focus, e.g. a hidden one\n    const focused = candidates.some((element) => {\n      element.focus();\n\n      return document.activeElement === element;\n    });\n\n    if (!focused && !tabStopOnly) {\n      content.tabIndex = -1;\n      content.focus();\n    }\n\n    return focused;\n  };\n\n  // Keep the `open` prop and the instance in sync both ways. The instance opens the popup when\n  // the anchor is activated, and closes it when the backdrop or an item is clicked, or Escape is\n  // pressed; the prop is what a consumer such as `<Combobox>` or `<MenuItem>` toggles from its own\n  // controls. The instance has to follow the prop as well, because it’s the instance that handles\n  // the dismissal, and it ignores a popup it doesn’t know to be open.\n  $effect(() => {\n    if (popupInstance) {\n      open = popupInstance.open;\n    }\n  });\n\n  $effect(() => {\n    if (popupInstance && popupInstance.open !== open) {\n      popupInstance.open = open;\n    }\n  });\n\n  $effect(() => {\n    if (parentDialogElement && !dialogElement && content) {\n      dialogElement = parentDialogElement;\n      dialogElement.append(content);\n    }\n  });\n\n  // The instance must be created as soon as the anchor is available, without waiting for the\n  // `<dialog>` element, because it’s the instance that listens to the anchor and opens the popup —\n  // and therefore causes the element to be mounted in the first place\n  $effect(() => {\n    if (anchor && !popupInstance) {\n      popupInstance = activatePopup(anchor, undefined, position, positionBaseElement);\n      contentType = anchor.getAttribute('aria-haspopup') ?? undefined;\n    }\n  });\n\n  // Attach the `<dialog>` element to the instance whenever it’s mounted, and detach it when it’s\n  // unmounted, which happens on every close. The content element is passed alongside it, because\n  // a nested popup shares the `<dialog>` with its parent and only the content is its own.\n  $effect(() => {\n    if (popupInstance && dialogElement && content) {\n      popupInstance.attachPopupElement(dialogElement, content, { nested: !!parentDialogElement });\n\n      return () => {\n        popupInstance?.detachPopupElement();\n      };\n    }\n\n    return undefined;\n  });\n\n  // The position can only be calculated once the content is in the DOM tree, so it has to be\n  // (re)checked here rather than in the instance’s `open` setter, which runs before the mount\n  $effect(() => {\n    if (open && dialogElement) {\n      popupInstance?.checkPosition();\n    }\n  });\n\n  const touch = $derived(touchOptimized && touchEnabled);\n\n  onMount(() => {\n    touchEnabled = globalThis.matchMedia('(pointer: coarse)').matches;\n\n    return () => {\n      popupInstance?.destroy?.();\n      globalThis.clearTimeout(hoveredTimeout);\n    };\n  });\n</script>\n\n{#snippet contentWrapper()}\n  <div\n    bind:this={\n      () => content,\n      (el) => {\n        content = el;\n        boundContent = el;\n      }\n    }\n    hidden={!open}\n    role=\"none\"\n    class=\"content {className} {contentType}\"\n    class:touch\n    class:nested={!!parentDialogElement}\n    style:inset={popupInstance?.style.inset}\n    style:z-index={popupInstance?.style.zIndex}\n    style:min-width={popupInstance?.style.minWidth}\n    style:max-width={popupInstance?.style.maxWidth}\n    style:max-height={popupInstance?.style.height}\n    style:visibility={popupInstance?.style.inset ? undefined : 'hidden'}\n    onmouseenter={() => {\n      hovered = true;\n\n      if (parentDialogElement) {\n        window.clearTimeout(hoveredTimeout);\n      }\n    }}\n    onmouseleave={() => {\n      hovered = false;\n\n      if (parentDialogElement) {\n        hoveredTimeout = window.setTimeout(() => {\n          open = false;\n        }, 200);\n      }\n    }}\n  >\n    {@render children?.()}\n  </div>\n{/snippet}\n\n{#if parentDialogElement}\n  {@render contentWrapper()}\n{:else}\n  <Modal\n    {...restProps}\n    bind:dialog={dialogElement}\n    role=\"none\"\n    class=\"popup\"\n    bind:open\n    showBackdrop={showBackdrop ?? touch}\n    lightDismiss={true}\n    onOpen={async (event) => {\n      onOpen?.(event);\n\n      // Move the focus into the content as soon as it’s rendered, if it holds a control that’s\n      // already in the tab order, like the search box of a dropdown list: a key typed right after\n      // the popup opens would otherwise be lost\n      await tick();\n\n      if (!content || focusContent({ tabStopOnly: true })) {\n        return;\n      }\n\n      // Otherwise wait for a composite widget, such as a menu, to put one of its items in the tab\n      // order, which it does a moment later\n      await sleep(100);\n\n      // Leave the focus alone if the user has already moved it within the content\n      if (content && !content.contains(document.activeElement)) {\n        focusContent();\n      }\n    }}\n  >\n    {@render contentWrapper()}\n  </Modal>\n{/if}\n\n<style>.content {\n  position: absolute;\n  overflow-y: auto;\n  outline-width: 0 !important;\n  width: auto;\n  transition-property: opacity, transform;\n  color: var(--sui-primary-foreground-color);\n  background-color: var(--sui-secondary-background-color-translucent);\n  box-shadow: 0 8px 16px var(--sui-popup-shadow-color);\n  -webkit-backdrop-filter: blur(16px);\n  backdrop-filter: blur(16px);\n}\n.content.menu {\n  border-width: var(--sui-menu-border-width, 1px);\n  border-style: var(--sui-menu-border-style, solid);\n  border-color: var(--sui-menu-border-color, var(--sui-secondary-border-color));\n  border-radius: var(--sui-menu-border-radius, 4px);\n  padding: var(--sui-menu-padding, 4px);\n}\n.content.menu :global(.sui.menu) {\n  border-width: 0;\n  border-radius: 0;\n  padding: 0;\n  background-color: transparent;\n}\n.content.listbox {\n  border-width: var(--sui-listbox-border-width, 1px);\n  border-style: var(--sui-listbox-border-style, solid);\n  border-color: var(--sui-listbox-border-color, var(--sui-secondary-border-color));\n  border-radius: var(--sui-listbox-border-radius, 4px);\n  padding: var(--sui-listbox-padding, 4px);\n}\n.content.listbox :global(.sui.listbox) {\n  border-width: 0;\n  border-radius: 0;\n  padding: 0;\n  background-color: transparent;\n}\n.content.tree {\n  border-width: var(--sui-tree-border-width, 1px);\n  border-style: var(--sui-tree-border-style, solid);\n  border-color: var(--sui-tree-border-color, var(--sui-secondary-border-color));\n  border-radius: var(--sui-tree-border-radius, 4px);\n  padding: var(--sui-tree-padding, 4px);\n}\n.content.tree :global(.sui.tree) {\n  margin: 0;\n  border-width: 0;\n  border-radius: 0;\n  padding: 0;\n  background-color: transparent;\n}\n.content.combobox {\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n.content.touch {\n  position: static;\n  border-width: 0 !important;\n  border-radius: 4px !important;\n  padding: 8px;\n  min-width: 320px !important;\n  max-width: calc(100dvw - 32px) !important;\n  max-height: calc(100dvh - 32px) !important;\n}\n:global(dialog.open) .content.touch {\n  transform: scale(100%) !important;\n}\n:global(dialog:not(.open)) .content.touch {\n  transform: scale(90%);\n}\n.content.touch.combobox :global(.sui.listbox) {\n  gap: 4px;\n  padding: 8px 4px !important;\n}\n:global(dialog.open) .content {\n  transition-duration: 50ms;\n  opacity: 1;\n  transform: translateY(2px);\n}\n:global(dialog:not(.open)) .content {\n  transition-duration: 300ms;\n  opacity: 0;\n  transform: translateY(-8px);\n}\n.content.nested.menu {\n  margin-block: calc(-1 * (var(--sui-menu-border-width, 1px) + var(--sui-menu-padding, 4px)));\n}\n:global(dialog.open) .content.nested.menu {\n  transform: none;\n}</style>\n","/**\n * Pure helpers for `<Tooltip>`, which don’t touch the DOM, so they can be tested on their own.\n */\n\n/**\n * Space kept between a tooltip and its anchor, and between a tooltip and the viewport edges.\n */\nexport const TOOLTIP_GAP = 6;\n\n/**\n * @typedef {'auto' | 'top' | 'bottom' | 'left' | 'right'} TooltipPosition\n */\n\n/**\n * Sides opposite each other, which a tooltip moves to when its own side has no room.\n * @type {Record<'top' | 'bottom' | 'left' | 'right', 'top' | 'bottom' | 'left' | 'right'>}\n */\nconst OPPOSITE_SIDES = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' };\n/**\n * Keep a value between a minimum and a maximum, favouring the minimum when they cross.\n * @param {number} value Value.\n * @param {number} min Minimum.\n * @param {number} max Maximum.\n * @returns {number} Result.\n */\nconst clamp = (value, min, max) => Math.max(min, Math.min(value, max));\n\n/**\n * Work out where a tooltip goes: on the given side of its anchor, centred on it, or on the opposite\n * side when there’s no room on the given one and more on the other, and moved along the side as\n * needed to stay within the viewport. `auto` is below the anchor.\n * @param {object} args Arguments.\n * @param {{ top: number, right: number, bottom: number, left: number, width: number,\n * height: number }} args.anchorRect Anchor’s rect, as `getBoundingClientRect()` returns it.\n * @param {{ width: number, height: number }} args.viewport Viewport size.\n * @param {{ width: number, height: number }} args.size Tooltip’s size.\n * @param {TooltipPosition} [args.position] Preferred side. Default: `auto`.\n * @param {boolean} [args.rtl] Whether the anchor is in a right-to-left context, which swaps `left`\n * and `right`, like the popup positions.\n * @returns {{ top: number, left: number, placement: 'top' | 'bottom' | 'left' | 'right' }}\n * Position of the tooltip’s top-left corner in the viewport, and which side of the anchor it’s on.\n */\nexport const getTooltipPosition = ({\n  anchorRect,\n  viewport,\n  size,\n  position = 'auto',\n  rtl = false,\n}) => {\n  const rooms = {\n    top: anchorRect.top - TOOLTIP_GAP * 2,\n    bottom: viewport.height - anchorRect.bottom - TOOLTIP_GAP * 2,\n    left: anchorRect.left - TOOLTIP_GAP * 2,\n    right: viewport.width - anchorRect.right - TOOLTIP_GAP * 2,\n  };\n\n  const side = position === 'auto' ? 'bottom' : position;\n  const preferred = rtl && (side === 'left' || side === 'right') ? OPPOSITE_SIDES[side] : side;\n  const opposite = OPPOSITE_SIDES[preferred];\n  const needed = preferred === 'top' || preferred === 'bottom' ? size.height : size.width;\n\n  const placement =\n    needed > rooms[preferred] && rooms[opposite] > rooms[preferred] ? opposite : preferred;\n\n  const centredLeft = anchorRect.left + anchorRect.width / 2 - size.width / 2;\n  const centredTop = anchorRect.top + anchorRect.height / 2 - size.height / 2;\n  const maxLeft = viewport.width - size.width - TOOLTIP_GAP;\n  const maxTop = viewport.height - size.height - TOOLTIP_GAP;\n\n  if (placement === 'top' || placement === 'bottom') {\n    return {\n      top:\n        placement === 'bottom'\n          ? anchorRect.bottom + TOOLTIP_GAP\n          : anchorRect.top - TOOLTIP_GAP - size.height,\n      left: clamp(centredLeft, TOOLTIP_GAP, maxLeft),\n      placement,\n    };\n  }\n\n  return {\n    top: clamp(centredTop, TOOLTIP_GAP, maxTop),\n    left:\n      placement === 'right'\n        ? anchorRect.right + TOOLTIP_GAP\n        : anchorRect.left - TOOLTIP_GAP - size.width,\n    placement,\n  };\n};\n\n/**\n * Add or remove an ID in a space-separated ID list, such as the `aria-describedby` attribute,\n * keeping any other IDs the consumer has set.\n * @param {string | null} list Current list.\n * @param {string} id ID.\n * @param {boolean} include Whether the ID should be in the list.\n * @returns {string | null} New list, or `null` if it ends up empty.\n */\nexport const toggleIdInList = (list, id, include) => {\n  const ids = (list ?? '').split(/\\s+/).filter((item) => item && item !== id);\n\n  if (include) {\n    ids.push(id);\n  }\n\n  return ids.length ? ids.join(' ') : null;\n};\n\n/**\n * Get the text of an element as a screen reader would read it, leaving out the parts hidden with\n * `aria-hidden`, such as the name of an icon drawn with a ligature font.\n * @param {Element} element Element.\n * @returns {string} Text, with its white space collapsed.\n */\nexport const getAccessibleText = (element) => {\n  /**\n   * Collect the text of a node.\n   * @param {Node} node Node.\n   * @returns {string} Text.\n   */\n  const collect = (node) => {\n    if (node.nodeType === Node.TEXT_NODE) {\n      return node.textContent ?? '';\n    }\n\n    if (\n      node.nodeType !== Node.ELEMENT_NODE ||\n      /** @type {Element} */ (node).getAttribute('aria-hidden') === 'true'\n    ) {\n      return '';\n    }\n\n    // The text nodes carry the real white space, so nothing is added between the parts\n    return [...node.childNodes].map(collect).join('');\n  };\n\n  return collect(element).replace(/\\s+/g, ' ').trim();\n};\n","<!--\n  @component\n  A tooltip for a button or another focusable element: a short text shown next to it while the\n  pointer rests on it or the keyboard focus is on it, hidden again with the Escape key. It lives in\n  the top layer through the Popover API, so a dialog or a scrolling container can’t clip it.\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/tooltip/\n  @see https://www.w3.org/WAI/WCAG22/Understanding/content-on-hover-or-focus.html\n-->\n<script>\n  import { untrack } from 'svelte';\n  import { getAccessibleText, getTooltipPosition, toggleIdInList } from '../../services/tooltip.js';\n\n  /**\n   * @import { TooltipPosition } from '../../services/tooltip.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {HTMLElement | undefined} anchor Element the tooltip belongs to.\n   * @property {string} text Text to show.\n   * @property {TooltipPosition} [position] Side of the anchor to show the tooltip on. Default:\n   * `auto`, which is below it. The tooltip moves to the opposite side when there’s no room, and\n   * `left` and `right` are swapped in a right-to-left context, like the popup positions.\n   * @property {boolean} [open] Whether to show the tooltip regardless of the pointer and focus, for\n   * instance to confirm an action for a moment.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    anchor,\n    text,\n    position = 'auto',\n    open = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * How long the pointer has to rest on the anchor before the tooltip shows, in milliseconds.\n   */\n  const SHOW_DELAY = 500;\n  /**\n   * How long the tooltip stays after the pointer leaves the anchor, in milliseconds, so the pointer\n   * can move onto the tooltip without it disappearing.\n   */\n  const HIDE_DELAY = 100;\n\n  const id = $props.id();\n\n  /** @type {HTMLElement | undefined} */\n  let element = $state();\n  let hovered = $state(false);\n  let focused = $state(false);\n  /** Whether the Escape key has dismissed the tooltip, until the pointer or focus comes back. */\n  let dismissed = $state(false);\n  let top = $state(0);\n  let left = $state(0);\n  /** @type {'top' | 'bottom' | 'left' | 'right'} */\n  let placement = $state('bottom');\n  let timer = 0;\n\n  const visible = $derived(!!text && (open || ((hovered || focused) && !dismissed)));\n\n  /**\n   * Run a function after a delay, replacing any pending one.\n   * @param {() => void} fn Function.\n   * @param {number} delay Delay in milliseconds.\n   */\n  const schedule = (fn, delay) => {\n    clearTimeout(timer);\n    timer = /** @type {number} */ (/** @type {unknown} */ (setTimeout(fn, delay)));\n  };\n\n  /**\n   * Handle the pointer entering the anchor or the tooltip. Touch is left out, as a tap would show\n   * the tooltip on top of what the tap does.\n   * @param {PointerEvent} event `pointerenter` event.\n   * @param {number} delay Delay in milliseconds.\n   */\n  const onPointerEnter = (event, delay) => {\n    if (event.pointerType !== 'touch') {\n      dismissed = false;\n      schedule(() => {\n        hovered = true;\n      }, delay);\n    }\n  };\n\n  /**\n   * Handle the pointer leaving the anchor or the tooltip.\n   */\n  const onPointerLeave = () => {\n    schedule(() => {\n      hovered = false;\n    }, HIDE_DELAY);\n  };\n\n  /**\n   * Place the tooltip next to the anchor.\n   */\n  const updatePosition = () => {\n    /* v8 ignore next 3 -- only called while both are rendered */\n    if (!anchor || !element) {\n      return;\n    }\n\n    ({ top, left, placement } = getTooltipPosition({\n      anchorRect: anchor.getBoundingClientRect(),\n      viewport: { width: window.innerWidth, height: window.innerHeight },\n      size: { width: element.offsetWidth, height: element.offsetHeight },\n      position,\n      rtl: anchor.matches(':dir(rtl)'),\n    }));\n  };\n\n  /**\n   * Handle the pointer entering the anchor, after the usual delay.\n   * @param {Event} event `pointerenter` event.\n   */\n  const onAnchorPointerEnter = (event) => {\n    onPointerEnter(/** @type {PointerEvent} */ (event), SHOW_DELAY);\n  };\n\n  /**\n   * Show the tooltip when the anchor gets the keyboard focus. A click focuses a button too, but the\n   * pointer covers that case.\n   * @param {Event} event `focusin` event.\n   */\n  const onFocusIn = (event) => {\n    focused = /** @type {HTMLElement} */ (event.currentTarget).matches(':focus-visible');\n\n    // A click, which also focuses the button, keeps the tooltip dismissed\n    if (focused) {\n      dismissed = false;\n    }\n  };\n\n  /**\n   * Hide the tooltip when the anchor is pressed, as it would cover what the press opens, such as a\n   * menu, until the pointer comes back. A tooltip forced open, like a copy confirmation, still\n   * shows.\n   */\n  const onPointerDown = () => {\n    clearTimeout(timer);\n    dismissed = true;\n  };\n\n  /**\n   * Hide the tooltip when the anchor loses the focus. Removing a focused anchor fires the event at\n   * once, while the block that removes it is still running, where Svelte forbids a state change\n   * unless it’s untracked.\n   */\n  const onFocusOut = () => {\n    untrack(() => {\n      focused = false;\n    });\n  };\n\n  // Follow the anchor’s pointer and focus events\n  $effect(() => {\n    /* v8 ignore next 3 -- the anchor is bound before the effects run */\n    if (!anchor) {\n      return undefined;\n    }\n\n    const target = anchor;\n\n    /** @type {[string, EventListener][]} */\n    const listeners = [\n      ['pointerenter', onAnchorPointerEnter],\n      ['pointerleave', onPointerLeave],\n      ['pointerdown', onPointerDown],\n      ['focusin', onFocusIn],\n      ['focusout', onFocusOut],\n    ];\n\n    listeners.forEach(([type, listener]) => target.addEventListener(type, listener));\n\n    return () => {\n      clearTimeout(timer);\n      listeners.forEach(([type, listener]) => target.removeEventListener(type, listener));\n    };\n  });\n\n  /**\n   * Add the tooltip to the IDs in the anchor’s `aria-describedby`, or take it out, keeping any\n   * other IDs set on the anchor.\n   * @param {HTMLElement} target Anchor.\n   * @param {boolean} include Whether the tooltip should describe the anchor.\n   */\n  const setDescribedBy = (target, include) => {\n    const list = toggleIdInList(target.getAttribute('aria-describedby'), id, include);\n\n    if (list) {\n      target.setAttribute('aria-describedby', list);\n    } else {\n      target.removeAttribute('aria-describedby');\n    }\n  };\n\n  // Describe the anchor with the tooltip, unless the tooltip only repeats its name, which would be\n  // read out twice, as it is for an icon button whose tooltip shows its label\n  $effect(() => {\n    /* v8 ignore next 3 -- the anchor is bound before the effects run */\n    if (!anchor) {\n      return undefined;\n    }\n\n    const target = anchor;\n    const name = target.getAttribute('aria-label') ?? getAccessibleText(target);\n\n    setDescribedBy(target, !!text && text !== name);\n\n    return () => {\n      setDescribedBy(target, false);\n    };\n  });\n\n  // Show and place the tooltip, and keep it next to the anchor while it’s shown\n  $effect(() => {\n    /* v8 ignore next 3 -- the element is rendered with the component */\n    if (!element?.showPopover) {\n      return undefined;\n    }\n\n    const popover = element;\n\n    if (!visible) {\n      if (popover.matches(':popover-open')) {\n        popover.hidePopover();\n      }\n\n      return undefined;\n    }\n\n    if (!popover.matches(':popover-open')) {\n      popover.showPopover();\n    }\n\n    updatePosition();\n\n    /**\n     * Dismiss the tooltip with the Escape key, without moving the focus. The key is used up, so it\n     * doesn’t also close a dialog or a popup the anchor is in; the next press does. A tooltip\n     * forced open, like a copy confirmation, goes away on its own instead.\n     * @param {KeyboardEvent} event `keydown` event.\n     */\n    const onKeyDown = (event) => {\n      if (event.key === 'Escape' && !open) {\n        event.preventDefault();\n        event.stopPropagation();\n        dismissed = true;\n      }\n    };\n\n    // Its size changes with its text, e.g. from a label to “Copied”, so it’s centred again\n    const resizeObserver = new ResizeObserver(updatePosition);\n\n    resizeObserver.observe(popover);\n    window.addEventListener('scroll', updatePosition, { capture: true, passive: true });\n    window.addEventListener('resize', updatePosition, { passive: true });\n    window.addEventListener('keydown', onKeyDown, { capture: true });\n\n    return () => {\n      resizeObserver.disconnect();\n      window.removeEventListener('scroll', updatePosition, { capture: true });\n      window.removeEventListener('resize', updatePosition);\n      window.removeEventListener('keydown', onKeyDown, { capture: true });\n    };\n  });\n</script>\n\n<div\n  bind:this={element}\n  {id}\n  role=\"tooltip\"\n  popover=\"manual\"\n  class=\"sui tooltip {placement}\"\n  style:top=\"{top}px\"\n  style:left=\"{left}px\"\n  onpointerenter={(event) => onPointerEnter(event, 0)}\n  onpointerleave={onPointerLeave}\n>\n  {text}\n</div>\n\n<style>.tooltip {\n  position: fixed;\n  inset: auto;\n  margin: 0;\n  padding: 4px 8px;\n  max-width: min(320px, 100vw - 12px);\n  font-family: var(--sui-font-family-default);\n  font-size: var(--sui-font-size-small);\n  font-weight: var(--sui-font-weight-normal, normal);\n  line-height: var(--sui-line-height-compact, 1.4);\n  text-align: center;\n  overflow-wrap: anywhere;\n  white-space: normal;\n  color: var(--sui-primary-foreground-color);\n  background-color: var(--sui-secondary-background-color-translucent);\n  box-shadow: 0 8px 16px var(--sui-popup-shadow-color);\n  -webkit-backdrop-filter: blur(16px);\n  backdrop-filter: blur(16px);\n  border-width: var(--sui-tooltip-border-width, 1px);\n  border-style: var(--sui-tooltip-border-style, solid);\n  border-color: var(--sui-tooltip-border-color, var(--sui-secondary-border-color));\n  border-radius: var(--sui-tooltip-border-radius, 4px);\n  box-shadow: 0 2px 6px var(--sui-tooltip-shadow-color, hsl(var(--sui-shadow-color)/20%));\n}</style>\n","<!--\n  @component\n  A generic button widget based on the HTML `<button>` element.\n  @see https://w3c.github.io/aria/#button\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/button/\n-->\n<script>\n  import { activateKeyShortcuts } from '@sveltia/utils/events';\n  import { getValueType } from '../../services/value.js';\n  import TruncatedText from '../typography/truncated-text.svelte';\n  import Popup from '../util/popup.svelte';\n  import Tooltip from '../util/tooltip.svelte';\n\n  /**\n   * @import { ButtonProps, CommonEventHandlers } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ButtonProps & CommonEventHandlers & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    element: boundElement = $bindable(),\n    class: className = '',\n    type = 'button',\n    role = 'button',\n    name = undefined,\n    value = undefined,\n    // svelte-ignore state_referenced_locally\n    valueType = getValueType(value),\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    pressed = undefined,\n    keyShortcuts = undefined,\n    label = '',\n    labelDir = undefined,\n    lines = 1,\n    variant = undefined,\n    size = 'medium',\n    iconic = false,\n    pill = false,\n    flex = false,\n    popupPosition = 'bottom-left',\n    showPopupBackdrop = false,\n    tooltip = undefined,\n    tooltipPosition = 'auto',\n    children,\n    startIcon,\n    endIcon,\n    popup,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * A reference to the `<button>` element. It’s kept apart from the bindable `element` prop, which\n   * Svelte resets whenever the props spread onto this component change, unless the consumer binds\n   * it.\n   * @type {HTMLButtonElement | undefined}\n   */\n  let element = $state.raw();\n</script>\n\n{#snippet labelText()}\n  <span role=\"none\" class=\"label\" dir={labelDir}>\n    <TruncatedText {lines}>\n      {label}\n    </TruncatedText>\n  </span>\n{/snippet}\n\n<!--\n  `aria-readonly` is only rendered when it applies: the attribute isn’t supported on the `button`\n  role (or `option`, `tab` and `menuitem`, which also wrap this component), and Svelte would\n  otherwise serialize `false` as the literal string \"false\".\n\n  The key shortcut handler is attached only when there are shortcuts to bind. A falsy value counts\n  as no attachment at all, which saves an effect per button — and both `<Option>` and `<MenuItem>`\n  wrap one, so a long list would otherwise pay for an effect per item that has nothing to do.\n-->\n<button\n  bind:this={\n    () => element,\n    (el) => {\n      element = el;\n      boundElement = el;\n    }\n  }\n  {...restProps}\n  class={['sui', 'button', variant, size, className]}\n  class:iconic\n  class:pill\n  class:flex\n  {type}\n  {name}\n  {value}\n  {hidden}\n  {disabled}\n  {role}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-readonly={readonly || undefined}\n  aria-pressed={pressed}\n  data-type={valueType}\n  data-name={name}\n  data-label={label}\n  data-value={value}\n  {@attach keyShortcuts && activateKeyShortcuts(keyShortcuts)}\n>\n  {@render startIcon?.()}\n  {#if variant === 'link'}\n    {#if label}\n      {@render labelText()}\n    {:else}\n      <span role=\"none\" class=\"label\">\n        {@render children?.()}\n      </span>\n    {/if}\n  {:else}\n    {#if label}\n      {@render labelText()}\n    {/if}\n    {@render children?.()}\n  {/if}\n  {@render endIcon?.()}\n</button>\n\n{#if tooltip}\n  <Tooltip anchor={element} text={tooltip} position={tooltipPosition} />\n{/if}\n\n{#if popup}\n  <Popup\n    anchor={element}\n    position={popupPosition}\n    showBackdrop={showPopupBackdrop}\n    touchOptimized={true}\n  >\n    {@render popup()}\n  </Popup>\n{/if}\n\n<style>button {\n  flex: none;\n  display: inline-flex;\n  align-items: center;\n  gap: 4px;\n  margin: var(--sui-focus-ring-width);\n  border-width: 0;\n  border-style: solid;\n  border-color: transparent;\n  padding: 0;\n  color: var(--sui-control-foreground-color, inherit);\n  background-color: transparent;\n  box-shadow: none;\n  font-family: var(--sui-control-font-family);\n  font-size: var(--sui-control-font-size);\n  line-height: var(--sui-control-line-height);\n  font-weight: var(--sui-font-weight-normal, normal);\n  text-align: start;\n  cursor: pointer;\n  transition: all 200ms;\n}\nbutton[hidden] {\n  display: none !important;\n}\nbutton:not(:disabled):focus-visible {\n  z-index: 1;\n}\nbutton:is(.primary, .secondary, .tertiary, .ghost) {\n  justify-content: center;\n  border-width: 1px;\n}\nbutton:is(.primary, .secondary, .tertiary, .ghost) .label:only-child {\n  padding: 0 4px;\n}\nbutton.primary {\n  border-width: var(--sui-button-primary-border-width, 1px);\n  border-style: var(--sui-button-primary-border-style, solid);\n  border-color: var(--sui-button-primary-border-color, var(--sui-primary-accent-color));\n  color: var(--sui-button-primary-foreground-color, var(--sui-primary-accent-color-inverted));\n  background-color: var(--sui-button-primary-background-color, var(--sui-primary-accent-color));\n  font-weight: var(--sui-button-primary-font-weight, var(--sui-font-weight-normal, normal));\n}\nbutton.primary:is(:hover, :focus-visible, [aria-expanded=true]) {\n  color: var(--sui-button-primary-foreground-color-focus, var(--sui-button-primary-foreground-color, var(--sui-primary-accent-color-inverted)));\n  background-color: var(--sui-button-primary-background-color-focus, var(--sui-primary-accent-color-light));\n}\nbutton.primary:active {\n  color: var(--sui-button-primary-foreground-color-active, var(--sui-button-primary-foreground-color, var(--sui-primary-accent-color-inverted)));\n  background-color: var(--sui-button-primary-background-color-active, var(--sui-primary-accent-color-dark));\n}\nbutton.secondary {\n  border-width: var(--sui-button-secondary-border-width, 1px);\n  border-style: var(--sui-button-secondary-border-style, solid);\n  border-color: var(--sui-button-secondary-border-color, var(--sui-primary-accent-color));\n  color: var(--sui-button-secondary-foreground-color, var(--sui-primary-accent-color-text));\n  background-color: var(--sui-button-secondary-background-color, var(--sui-button-background-color));\n  font-weight: var(--sui-button-secondary-font-weight, var(--sui-font-weight-normal, normal));\n}\nbutton.secondary:is(:hover, :focus-visible, [aria-expanded=true]) {\n  color: var(--sui-button-secondary-foreground-color-focus, var(--sui-button-secondary-foreground-color, var(--sui-primary-accent-color-text)));\n  background-color: var(--sui-button-secondary-background-color-focus, var(--sui-hover-background-color));\n}\nbutton.secondary:active {\n  color: var(--sui-button-secondary-foreground-color-active, var(--sui-button-secondary-foreground-color, var(--sui-primary-accent-color-text)));\n  background-color: var(--sui-button-secondary-background-color-active, var(--sui-active-background-color));\n}\nbutton.secondary[aria-pressed=true] {\n  color: var(--sui-button-secondary-foreground-color-pressed);\n  background-color: var(--sui-button-secondary-background-color-pressed, var(--sui-primary-accent-color));\n}\nbutton.tertiary {\n  border-width: var(--sui-button-tertiary-border-width, 1px);\n  border-style: var(--sui-button-tertiary-border-style, solid);\n  border-color: var(--sui-button-tertiary-border-color, var(--sui-button-border-color));\n  color: var(--sui-button-tertiary-foreground-color, var(--sui-highlight-foreground-color));\n  background-color: var(--sui-button-tertiary-background-color, var(--sui-button-background-color));\n  font-weight: var(--sui-button-tertiary-font-weight, var(--sui-font-weight-normal, normal));\n}\nbutton.tertiary:is(:hover, :focus-visible, [aria-expanded=true]) {\n  color: var(--sui-button-tertiary-foreground-color-focus, var(--sui-button-tertiary-foreground-color, var(--sui-highlight-foreground-color)));\n  background-color: var(--sui-button-tertiary-background-color-focus, var(--sui-hover-background-color));\n}\nbutton.tertiary:active {\n  color: var(--sui-button-tertiary-foreground-color-active, var(--sui-button-tertiary-foreground-color, var(--sui-highlight-foreground-color)));\n  background-color: var(--sui-button-tertiary-background-color-active, var(--sui-active-background-color));\n}\nbutton.tertiary[aria-pressed=true] {\n  color: var(--sui-button-tertiary-foreground-color-pressed);\n  background-color: var(--sui-button-tertiary-background-color-pressed, var(--sui-selected-background-color));\n}\nbutton.ghost {\n  font-weight: var(--sui-button-ghost-font-weight, var(--sui-font-weight-normal, normal));\n}\nbutton.ghost:is(:hover, :focus-visible, [aria-expanded=true]) {\n  color: var(--sui-button-ghost-foreground-color-focus);\n  background-color: var(--sui-button-ghost-background-color-focus, var(--sui-hover-background-color));\n}\nbutton.ghost:active {\n  color: var(--sui-button-ghost-foreground-color-active);\n  background-color: var(--sui-button-ghost-background-color-active, var(--sui-active-background-color));\n}\nbutton.ghost[aria-pressed=true] {\n  color: var(--sui-button-ghost-foreground-color-pressed);\n  background-color: var(--sui-button-ghost-background-color-pressed, var(--sui-selected-background-color));\n}\nbutton.link {\n  margin: 0;\n  padding: 0 !important;\n  height: auto !important;\n  color: var(--sui-button-link-foreground-color, var(--sui-primary-accent-color-text));\n}\nbutton.link:hover .label {\n  outline: none !important;\n  text-decoration: underline;\n}\nbutton.link .label {\n  padding: 0;\n  line-height: var(--sui-line-height-compact);\n  text-decoration: var(--sui-button-link-text-decoration, none);\n  text-underline-offset: 2px;\n  white-space: normal;\n}\n:global(:is(:root, :host)[data-underline-links='true']) button.link .label {\n  text-decoration: underline;\n}\nbutton.small {\n  border-radius: var(--sui-button-small-border-radius);\n  padding: var(--sui-button-small-padding);\n  height: var(--sui-button-small-height);\n  font-size: var(--sui-button-small-font-size, var(--sui-font-size-small));\n}\nbutton.small :global(.icon) {\n  font-size: var(--sui-font-size-large);\n}\nbutton.medium {\n  border-radius: var(--sui-button-medium-border-radius);\n  padding: var(--sui-button-medium-padding);\n  height: var(--sui-button-medium-height);\n  font-size: var(--sui-button-medium-font-size, var(--sui-font-size-default));\n}\nbutton.large {\n  border-radius: var(--sui-button-large-border-radius);\n  padding: var(--sui-button-large-padding);\n  height: var(--sui-button-large-height);\n  font-size: var(--sui-button-large-font-size, var(--sui-font-size-large));\n}\nbutton.pill {\n  border-radius: 80px;\n  padding: var(--sui-button-medium-pill-padding, 0 12px);\n}\nbutton.flex:not([hidden]) {\n  display: inline-flex;\n  flex: auto;\n  width: -moz-available;\n  width: -webkit-fill-available;\n  width: stretch;\n}\nbutton.iconic {\n  justify-content: center;\n  padding: 0;\n  aspect-ratio: 1/1;\n}\nbutton.danger {\n  background-color: var(--sui-error-background-color);\n}\nbutton .label {\n  padding: 0 4px;\n}\nbutton > :global(*) {\n  pointer-events: none;\n}</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import AlertContent from './alert-content.svelte';\n  import { getAlertAriaLive, getAlertRole } from './alert.js';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [show] Whether to show the infobar.\n   * @property {boolean} [dismissible] Whether to show the close button.\n   * @property {'error' | 'warning' | 'info' | 'success'} [status] Information status. Errors and\n   * warnings are `role=\"alert\"` and interrupt; information and success are `role=\"status\"` and\n   * wait.\n   * @property {'off' | 'polite' | 'assertive'} [ariaLive] ARIA live region politeness. Defaults to\n   * `assertive` for an alert and `polite` for a status.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {Snippet} [icon] Icon slot content.\n   * @property {() => void} [onDismiss] Callback invoked when the close button is clicked.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    show = $bindable(true),\n    dismissible = true,\n    status = 'info',\n    ariaLive = undefined,\n    children = undefined,\n    icon = undefined,\n    onDismiss,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const role = $derived(getAlertRole(status));\n</script>\n\n{#if show}\n  <div role=\"none\" class={['infobar', status]}>\n    <div {role} class=\"message\" aria-live={getAlertAriaLive(role, ariaLive)}>\n      <AlertContent {status} {children} {icon} />\n    </div>\n    {#if dismissible}\n      <div role=\"none\">\n        <Button\n          iconic\n          size=\"small\"\n          variant=\"ghost\"\n          aria-label={_('_sui.dismiss')}\n          onclick={() => {\n            show = false;\n            onDismiss?.();\n          }}\n        >\n          <Icon name=\"close\" />\n        </Button>\n      </div>\n    {/if}\n  </div>\n{/if}\n\n<style>.infobar {\n  flex: none;\n  display: flex;\n  align-items: center;\n  gap: var(--sui-infobar-gap, 8px);\n  border-width: var(--sui-infobar-border-width, 0 0 1px);\n  border-style: var(--sui-infobar-border-style, solid);\n  padding: var(--sui-infobar-padding, 0);\n  min-height: var(--sui-infobar-min-height, 32px);\n  font-size: var(--sui-infobar-font-size, var(--sui-font-size-small));\n}\n.infobar.info {\n  border-color: var(--sui-info-border-color);\n  color: var(--sui-info-foreground-color);\n  background-color: var(--sui-info-background-color);\n}\n.infobar.warning {\n  border-color: var(--sui-warning-border-color);\n  color: var(--sui-warning-foreground-color);\n  background-color: var(--sui-warning-background-color);\n}\n.infobar.error {\n  border-color: var(--sui-error-border-color);\n  color: var(--sui-error-foreground-color);\n  background-color: var(--sui-error-background-color);\n}\n.infobar.success {\n  border-color: var(--sui-success-border-color);\n  color: var(--sui-success-foreground-color);\n  background-color: var(--sui-success-background-color);\n}\n\n.message {\n  flex: auto;\n  display: flex;\n  align-items: center;\n  justify-content: var(--sui-infobar-message-justify-content, start);\n  gap: var(--sui-infobar-message-gap, 6px);\n  padding: var(--sui-infobar-message-padding, 6px);\n}\n.message :global(button) {\n  font-size: inherit !important;\n}\n.message :global(.icon) {\n  font-size: 16px; /* !hardcoded */\n}</style>\n","<script>\n  /**\n   * @import { ContainerProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [title] Text label displayed above the group items.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    children,\n    ...rest\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div role=\"none\" class=\"sui bottom-navigation {className}\" {...rest}>\n  {@render children?.()}\n</div>\n\n<style>.bottom-navigation {\n  height: var(--sui-bottom-navigation-height, var(--sui-primary-toolbar-size));\n  border-top-width: var(--sui-bottom-navigation-border-width, 1px);\n  border-top-style: var(--sui-bottom-navigation-border-style, solid);\n  border-top-color: var(--sui-bottom-navigation-border-color, var(--sui-secondary-border-color));\n}\n.bottom-navigation:is([inert], [hidden]) {\n  display: none;\n}\n.bottom-navigation :global(.buttons) {\n  flex: auto;\n  display: flex;\n  align-items: center;\n  justify-content: space-evenly;\n}</style>\n","<!--\n  @component\n  An icon button that copies the given text to the clipboard. Its tooltip shows its label. Once the\n  text is copied, the button shows a check mark and the tooltip says “Copied” for a moment, which\n  screen readers announce too.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { tick } from 'svelte';\n  import Icon from '../icon/icon.svelte';\n  import Tooltip from '../util/tooltip.svelte';\n  import Button from './button.svelte';\n\n  /**\n   * @import { ButtonProps, CommonEventHandlers } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} text Text to copy.\n   * @property {string} [ariaLabel] Accessible label, also shown in the tooltip, such as “Copy the\n   * URL”. Default: “Copy”.\n   * @property {(event: CustomEvent<{ text: string }>) => void} [onCopy] Called once the text has\n   * been copied.\n   * @property {(event: CustomEvent<{ error: unknown }>) => void} [onError] Called when the\n   * clipboard refuses the text, such as when the browser denies the permission. The button then\n   * stays as it was.\n   */\n\n  /**\n   * @type {Omit<ButtonProps, 'label' | 'iconic' | 'value' | 'tooltip'> & CommonEventHandlers &\n   * Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    text,\n    ariaLabel = undefined,\n    variant = 'ghost',\n    tooltipPosition = 'auto',\n    disabled = false,\n    onCopy,\n    onError,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * How long the button shows “Copied”, in milliseconds.\n   */\n  const COPIED_DURATION = 2000;\n\n  let copied = $state(false);\n  /** @type {HTMLButtonElement | undefined} */\n  let buttonElement = $state();\n\n  const label = $derived(ariaLabel ?? _('_sui.copy_button.copy'));\n  let timer = 0;\n\n  $effect(() => () => {\n    clearTimeout(timer);\n  });\n\n  /**\n   * Copy the text, and show that it’s been copied for a moment.\n   */\n  const copy = async () => {\n    try {\n      await navigator.clipboard.writeText(text);\n    } catch (error) {\n      onError?.(new CustomEvent('Error', { detail: { error } }));\n\n      return;\n    }\n\n    // Reset first, so a second copy is announced as well\n    copied = false;\n    await tick();\n    copied = true;\n    clearTimeout(timer);\n    timer = /** @type {number} */ (\n      /** @type {unknown} */ (\n        setTimeout(() => {\n          copied = false;\n        }, COPIED_DURATION)\n      )\n    );\n    onCopy?.(new CustomEvent('Copy', { detail: { text } }));\n  };\n</script>\n\n<Button\n  {...restProps}\n  bind:element={buttonElement}\n  {variant}\n  {disabled}\n  iconic\n  aria-label={label}\n  onclick={copy}\n>\n  {#snippet startIcon()}\n    <Icon name={copied ? 'check' : 'content_copy'} />\n  {/snippet}\n</Button>\n<Tooltip\n  anchor={buttonElement}\n  text={copied ? _('_sui.copy_button.copied') : label}\n  position={tooltipPosition}\n  open={copied}\n/>\n<!-- A tooltip isn’t announced when it appears, so the outcome is announced separately -->\n<span role=\"status\" class=\"sui copy-button-status\">\n  {copied ? _('_sui.copy_button.copied') : ''}\n</span>\n\n<style>.copy-button-status {\n  position: absolute;\n  overflow: hidden;\n  clip-path: inset(50%);\n  width: 1px;\n  height: 1px;\n  white-space: nowrap;\n}</style>\n","<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Snippet} [children] Slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    children = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div role=\"none\" class=\"sui floating-action-button-wrapper\">\n  {@render children?.()}\n</div>\n\n<style>.floating-action-button-wrapper {\n  display: contents;\n}\n@media (width < 768px) {\n  .floating-action-button-wrapper {\n    display: block;\n    position: fixed;\n    inset-inline-end: 16px;\n    inset-block-end: 72px;\n    z-index: 100;\n  }\n  .floating-action-button-wrapper :global(button) {\n    border-radius: 50%;\n    height: 56px;\n    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.4);\n  }\n  .floating-action-button-wrapper :global(button) :global(.icon) {\n    font-size: 32px;\n  }\n}</style>\n","import { getContext, setContext } from 'svelte';\nimport { castValue } from './value.js';\n\n/**\n * @import { OptionEntry, SelectedItemDetail } from '../typedefs.js';\n */\n\n/**\n * Context key for {@link OptionRegistry}.\n */\nconst CONTEXT_KEY = Symbol('sui-option-registry');\n\n/**\n * Reactive registry of the `<Option>`s declared within a `<Combobox>`.\n *\n * The options only render their DOM while the dropdown is expanded, so a collapsed combobox can’t\n * look them up with `querySelector`. Each `<Option>` instead registers a live view of its own props\n * here, which lets the combobox resolve the current label and the initially selected value without\n * keeping the option elements in the DOM tree.\n *\n * The order of the registered options is not significant. Svelte still renders the options itself,\n * in declaration order, so nothing here has to reproduce that order.\n */\nexport class OptionRegistry {\n  /**\n   * Whether the dropdown is expanded, meaning the options should render their DOM.\n   * @type {boolean}\n   */\n  expanded = $state(false);\n\n  /**\n   * Registered options. This is a plain set rather than a state, so that registering an option\n   * doesn’t copy the whole list, which would make mounting many options quadratic. The entries,\n   * which expose their properties as getters onto the `<Option>`’s props, are not wrapped in a\n   * reactive proxy either. Changes are signalled through {@link #version}.\n   * @type {Set<OptionEntry>}\n   */\n  // eslint-disable-next-line svelte/prefer-svelte-reactivity -- Signalled manually, see above\n  #entrySet = new Set();\n\n  /**\n   * Incremented whenever an option is registered or unregistered, to notify the readers.\n   * @type {number}\n   */\n  #version = $state(0);\n\n  /**\n   * Array snapshot of {@link #entrySet}, rebuilt lazily after a change.\n   * @type {OptionEntry[]}\n   */\n  #snapshot = [];\n\n  /**\n   * Value of {@link #version} when {@link #snapshot} was last rebuilt.\n   * @type {number}\n   */\n  #snapshotVersion = -1;\n\n  /**\n   * Registered options, in registration order. The returned array must not be mutated.\n   * @returns {OptionEntry[]} Entries.\n   */\n  get #entries() {\n    // Reading `#version` also subscribes the caller to changes\n    if (this.#snapshotVersion !== this.#version) {\n      this.#snapshot = [...this.#entrySet];\n      this.#snapshotVersion = this.#version;\n    }\n\n    return this.#snapshot;\n  }\n\n  /**\n   * Number of registered options.\n   * @returns {number} Count.\n   */\n  get count() {\n    return this.#entries.length;\n  }\n\n  /**\n   * Registered options, in registration order.\n   * @returns {OptionEntry[]} Entries.\n   */\n  get entries() {\n    return this.#entries;\n  }\n\n  /**\n   * The option that is currently marked as selected, if any.\n   * @returns {OptionEntry | undefined} Matching option.\n   */\n  get selectedEntry() {\n    return this.#entries.find((entry) => entry.selected);\n  }\n\n  /**\n   * Register an option.\n   * @param {OptionEntry} entry Live view of the option’s props.\n   * @returns {() => void} Function to unregister the option.\n   */\n  register(entry) {\n    this.#entrySet.add(entry);\n    this.#version += 1;\n\n    return () => {\n      this.#entrySet.delete(entry);\n      this.#version += 1;\n    };\n  }\n\n  /**\n   * Find the option with the given value.\n   * @param {any} value Value to look for.\n   * @returns {OptionEntry | undefined} Matching option.\n   */\n  find(value) {\n    return this.#entries.find((entry) => entry.value === value);\n  }\n\n  /**\n   * Mark the option with the given value as the only selected one.\n   * @param {any} value Value to select.\n   */\n  selectOnly(value) {\n    this.#entries.forEach((entry) => {\n      const selected = entry.value === value;\n\n      if (entry.selected !== selected) {\n        entry.selected = selected;\n      }\n    });\n  }\n}\n\n/**\n * Create an option registry and provide it to the descendant `<Option>`s.\n * @returns {OptionRegistry} New registry.\n */\nexport const createOptionRegistry = () => setContext(CONTEXT_KEY, new OptionRegistry());\n\n/**\n * Get the option registry provided by an ancestor `<Combobox>`.\n * @returns {OptionRegistry | undefined} Registry, or `undefined` when the `<Option>` is used\n * standalone within a `<Listbox>`.\n */\nexport const getOptionRegistry = () => getContext(CONTEXT_KEY);\n\n/**\n * Get the detail of the selected element.\n * @param {HTMLElement} target Element to get the detail from.\n * @returns {SelectedItemDetail} Detail of the selected element.\n */\nexport const getSelectedItemDetail = (target) => {\n  const { type = 'string', name, label } = target.dataset;\n  const value = castValue(target.dataset.value, type);\n\n  return { target, type, name, label, value };\n};\n","/**\n * Text normalization shared by search filtering and type-ahead.\n */\n\n/**\n * Diacritic characters regex for normalization. We use a regex instead of `Intl` APIs for better\n * performance, since `transliterate` is slow and we only need basic normalization.\n */\nconst DIACRITIC_RE = /\\p{Diacritic}/gu;\n\n/**\n * Fold the given string for comparison: strip diacritics and convert to lower case, keeping\n * whitespace as is.\n * @internal\n * @param {string} value Original value.\n * @returns {string} Folded value.\n */\nexport const fold = (value) => value.normalize('NFD').replace(DIACRITIC_RE, '').toLocaleLowerCase();\n\n/**\n * Normalize the given string for search value comparison. Since `transliterate` is slow, we only\n * apply basic normalization.\n * @internal\n * @param {string} value Original value.\n * @returns {string} Normalized value.\n * @todo Move this to `@sveltia/utils`.\n */\nexport const normalize = (value) => fold(value.trim());\n\n/**\n * Get the visible label of a member of a composite widget, as used for type-ahead: the `data-label`\n * attribute, or else the text of its `.label` element rather than the whole text, which would take\n * in icon ligature names.\n * @internal\n * @param {HTMLElement} element Member element.\n * @param {object} [options] Options.\n * @param {boolean} [options.textFallback] Whether to fall back to the element’s whole text when it\n * has neither. A tree item holds its child items, whose text must not be taken for its own, so the\n * tree turns this off.\n * @returns {string} Label, which is empty if none is found.\n */\nexport const getItemLabel = (element, { textFallback = true } = {}) =>\n  element.dataset.label ??\n  element.querySelector('.label')?.textContent ??\n  (textFallback ? (element.textContent ?? '') : '');\n","/**\n * Type-ahead support shared by the composite widgets: the collapsed select-only combobox, and the\n * listbox and menu groups.\n */\n\nimport { fold, normalize } from './text.js';\n\n/**\n * How long, in milliseconds, successive keystrokes keep adding up to one type-ahead prefix.\n */\nexport const TYPE_AHEAD_TIMEOUT = 500;\n\n/**\n * Check whether a key press types a character that type-ahead goes by: a single printable\n * character other than whitespace, typed with Shift at most. A shortcut, with Alt, Control or Meta\n * held down, is left alone, and so is Space, which selects. Callers that ignore Shift as well check\n * for it themselves beforehand.\n * @param {KeyboardEvent} event `keydown` event.\n * @returns {boolean} Result.\n */\nexport const isPrintableKey = ({ key, altKey, ctrlKey, metaKey }) =>\n  key.length === 1 && !!key.trim() && !altKey && !ctrlKey && !metaKey;\n\n/**\n * Find the item that a type-ahead prefix lands on, the way a native `<select>` does. A single\n * character moves to the next item after the current one whose label starts with it, wrapping\n * around, and a repeated character (“aa”, …) keeps cycling through those. A longer prefix refines\n * the match from the current item, which is where the first character landed.\n * @param {string[]} labels Normalized item labels, in order.\n * @param {string} prefix Normalized prefix typed so far.\n * @param {number} currentIndex Index of the current item, or `-1` if there is none.\n * @returns {number} Index of the matching item, or `-1` if nothing matches.\n */\nexport const findTypeAheadMatch = (labels, prefix, currentIndex) => {\n  if (!prefix) {\n    return -1;\n  }\n\n  const cycling = prefix.length > 1 && [...prefix].every((char) => char === prefix[0]);\n  const needle = cycling ? prefix[0] : prefix;\n  // A single or repeated character is a request to move on, so the search starts after the current\n  // item; a longer prefix is refining what the first character found, so it starts there\n  const start = prefix.length === 1 || cycling ? currentIndex + 1 : Math.max(currentIndex, 0);\n  const { length } = labels;\n\n  for (let i = 0; i < length; i += 1) {\n    const index = (start + i) % length;\n\n    if (labels[index].startsWith(needle)) {\n      return index;\n    }\n  }\n\n  return -1;\n};\n\n/**\n * Keystroke buffer behind type-ahead: printable keys typed in quick succession make up a prefix,\n * which is dropped again after a short pause.\n */\nexport class TypeAhead {\n  /** @type {string} */\n  #prefix = '';\n\n  /** @type {number} */\n  #timer = 0;\n\n  /**\n   * Add a keystroke to the prefix.\n   * @param {string} key Printable key.\n   * @returns {string} Current prefix.\n   */\n  push(key) {\n    globalThis.clearTimeout(this.#timer);\n    this.#prefix += fold(key);\n    this.#timer = /** @type {number} */ (\n      /** @type {unknown} */ (\n        globalThis.setTimeout(() => {\n          this.#prefix = '';\n        }, TYPE_AHEAD_TIMEOUT)\n      )\n    );\n\n    return this.#prefix;\n  }\n\n  /**\n   * Add a keystroke to the prefix, and find the item it lands on. See {@link findTypeAheadMatch}.\n   * @param {string[]} labels Item labels, in order. They’re normalized here.\n   * @param {string} key Printable key.\n   * @param {number} currentIndex Index of the current item, or `-1` if there is none.\n   * @returns {number} Index of the matching item, or `-1` if nothing matches.\n   */\n  match(labels, key, currentIndex) {\n    return findTypeAheadMatch(labels.map(normalize), this.push(key), currentIndex);\n  }\n\n  /**\n   * Drop the prefix.\n   */\n  reset() {\n    globalThis.clearTimeout(this.#timer);\n    this.#prefix = '';\n  }\n}\n","/**\n * Activation scaffolding shared by the composite widgets, `Group` and `Tree`, which set up their\n * members only once the child components have had a chance to mount.\n */\n\nimport { sleep } from '@sveltia/utils/misc';\n\n/**\n * @typedef {object} ActivatableWidget\n * @property {() => void} activate Set up the members, unless they already are.\n */\n\n/**\n * Create an event listener that activates the widget before handing the event on, so an event\n * that comes before the delayed activation is not lost.\n * @template {Event} E\n * @param {ActivatableWidget} widget Widget.\n * @param {(event: E) => void} handler Function that handles the event.\n * @returns {(event: E) => void} Event listener.\n */\nexport const activateBefore = (widget, handler) => (event) => {\n  widget.activate();\n  handler(event);\n};\n\n/**\n * Activate the widget after a short delay, giving the relevant components time to mount, unless\n * the widget has been destroyed in the meantime.\n * @param {ActivatableWidget} widget Widget.\n * @param {() => boolean} isDestroyed Function that tells whether the widget has been destroyed.\n */\nexport const activateLater = async (widget, isDestroyed) => {\n  await sleep(100);\n\n  // The widget may have been unmounted in the meantime\n  if (!isDestroyed()) {\n    widget.activate();\n  }\n};\n","/**\n * Base class shared by the composite widgets, `Group` and `Tree`, along with the attachment factory\n * that mounts them.\n */\n\nimport { untrack } from 'svelte';\nimport { getSelectedItemDetail } from './select.svelte.js';\nimport { TypeAhead } from './type-ahead.js';\nimport { activateBefore, activateLater } from './widget.js';\n\n/**\n * @import { Attachment } from 'svelte/attachments';\n */\n\n/**\n * Lifecycle shared by the composite widgets: the `Initializing` and `Initialized` events, the\n * delayed activation that gives the child components time to mount, the event listeners that\n * activate the widget before handling an event that comes first, and the clean-up.\n */\nexport class CompositeWidget {\n  /**\n   * Whether {@link activate} has run. Until then, members are left as they are rendered.\n   * @type {boolean}\n   */\n  activated = false;\n\n  /**\n   * Whether {@link destroy} has run, so a pending {@link activate} must not run.\n   * @type {boolean}\n   */\n  destroyed = false;\n\n  /**\n   * Keystroke buffer for type-ahead.\n   * @type {TypeAhead}\n   */\n  typeAheadBuffer = new TypeAhead();\n\n  /**\n   * Controller whose signal removes every listener added with {@link listen} once aborted.\n   * @type {AbortController}\n   */\n  #controller = new AbortController();\n\n  /**\n   * Initialize a new `CompositeWidget` instance, and schedule its activation.\n   * @param {HTMLElement} parent Widget root element.\n   */\n  constructor(parent) {\n    parent.dispatchEvent(new CustomEvent('Initializing'));\n\n    this.parent = parent;\n\n    // Wait a bit before the relevant components, including the `aria-controls` targets, are\n    // mounted. If the widget is unmounted in the meantime, nothing is set up.\n    activateLater(this, () => this.destroyed);\n  }\n\n  /**\n   * Listen to an event on the widget root until {@link destroy} is called. The widget is activated\n   * before the event is handled, so an event that comes before the delayed activation isn’t lost.\n   * @template {keyof HTMLElementEventMap} K\n   * @param {K} type Event type.\n   * @param {(event: HTMLElementEventMap[K]) => void} handler Event handler.\n   */\n  listen(type, handler) {\n    this.parent.addEventListener(type, activateBefore(this, handler), {\n      signal: this.#controller.signal,\n    });\n  }\n\n  /**\n   * Activate the members, unless they already are.\n   */\n  activate() {\n    if (this.activated) {\n      return;\n    }\n\n    this.activated = true;\n    this.setUp();\n    this.parent.dispatchEvent(new CustomEvent('Initialized'));\n  }\n\n  /**\n   * Set up the members on activation. To be implemented by the subclass.\n   */\n  setUp() {}\n\n  /**\n   * Called whenever the params passed to the attachment are updated. To be implemented by the\n   * subclass.\n   * @param {Record<string, any>} _params Updated params.\n   */\n  // eslint-disable-next-line no-unused-vars\n  onUpdate(_params) {}\n\n  /**\n   * Whether the widget is disabled.\n   * @type {boolean}\n   */\n  get isDisabled() {\n    return this.parent.matches('[aria-disabled=\"true\"]');\n  }\n\n  /**\n   * Whether the widget is read-only.\n   * @type {boolean}\n   */\n  get isReadOnly() {\n    return this.parent.matches('[aria-readonly=\"true\"]');\n  }\n\n  /**\n   * Notify a change of the selection on the widget root.\n   * @param {HTMLElement} item Member that triggered the change.\n   */\n  dispatchChange(item) {\n    this.parent.dispatchEvent(new CustomEvent('Change', { detail: getSelectedItemDetail(item) }));\n  }\n\n  /**\n   * Clean up event listeners.\n   */\n  destroy() {\n    this.destroyed = true;\n    this.#controller.abort();\n    this.typeAheadBuffer.reset();\n  }\n}\n\n/**\n * Create an attachment factory for the given composite widget class.\n * @template {CompositeWidget} W\n * @param {new (parent: HTMLElement, params?: any) => W} Widget Widget class.\n * @returns {(paramsOrGetter?: object | (() => object)) => Attachment} Function that takes a params\n * object, or a getter function for reactive params, and returns an attachment.\n */\nexport const createWidgetAttachment = (Widget) => (paramsOrGetter) => (parent) => {\n  const isGetter = typeof paramsOrGetter === 'function';\n  // Read the params without tracking them: attachments run in an effect, so a tracked read would\n  // destroy and recreate the whole widget whenever they change, e.g. on every search keystroke.\n  // Changes are handled by `onUpdate()` below instead.\n  const initialParams = isGetter ? untrack(() => paramsOrGetter()) : paramsOrGetter;\n  const widget = new Widget(/** @type {HTMLElement} */ (parent), initialParams);\n\n  /* v8 ignore next 4 */\n  if (isGetter) {\n    $effect(() => {\n      widget.onUpdate(paramsOrGetter());\n    });\n  }\n\n  return () => {\n    widget.destroy();\n  };\n};\n","/**\n * Scrolling helpers shared by the composite widgets.\n */\n\n/**\n * Scroll the given element into view if needed, by as little as possible. Falls back to the legacy\n * boolean argument on a browser that rejects the options object.\n * @internal\n * @param {HTMLElement} element Element to be scrolled into view.\n */\nexport const scrollIntoViewIfNeeded = (element) => {\n  try {\n    element.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'auto' });\n  } catch {\n    element.scrollIntoView(true);\n  }\n};\n","/**\n * Menu behavior on top of the `Group` composite widget: leaving a menu with Tab, and stepping into\n * and out of submenus with the inline arrows and Escape, per the ARIA Menu pattern.\n * @see https://www.w3.org/WAI/ARIA/apg/patterns/menubar/\n */\n\nimport { isRTL } from '@sveltia/i18n';\nimport { sleep } from '@sveltia/utils/misc';\nimport { focusAdjacentTabStop } from './focus.js';\nimport { getArrowKeys, hasModifier, INACTIVE_MEMBER_SELECTOR } from './navigation.js';\n\n/**\n * @import { Group } from './group.svelte.js';\n */\n\n/**\n * Find the element that opens the menu the given element belongs to. A menu lives outside its\n * opener in the DOM tree, so the link runs the other way: the opener points at the menu’s container\n * with `aria-controls`.\n * @internal\n * @param {HTMLElement} element Element within the menu.\n * @returns {HTMLElement | null} Menu button or parent menu item, if any.\n */\nexport const getMenuOpener = (element) => {\n  /** @type {HTMLElement | null} */\n  let current = element;\n\n  while (current) {\n    if (current.id) {\n      const opener = /** @type {HTMLElement | null} */ (\n        document.querySelector(`[aria-haspopup=\"menu\"][aria-controls=\"${CSS.escape(current.id)}\"]`)\n      );\n\n      if (opener) {\n        return opener;\n      }\n    }\n\n    current = current.parentElement;\n  }\n\n  return null;\n};\n\n/**\n * Find the menu item that opens the given menu, when it’s a submenu. A menu button is deliberately\n * excluded, because closing a top-level menu is not what “back to the parent item” means.\n * @internal\n * @param {HTMLElement} menu Menu element.\n * @returns {HTMLElement | null} Parent menu item, if any.\n */\nexport const getParentMenuItem = (menu) => {\n  const opener = getMenuOpener(menu);\n\n  return opener?.matches('[role^=\"menuitem\"]') ? opener : null;\n};\n\n/**\n * Close the given menu along with every menu above it.\n * @internal\n * @param {HTMLElement} menu Menu element.\n * @returns {HTMLElement | null} The element that opens the outermost menu, so the caller can hand\n * focus back to it.\n */\nexport const closeMenuChain = (menu) => {\n  /** @type {HTMLElement | null} */\n  let opener = getMenuOpener(menu);\n  /** @type {HTMLElement | null} */\n  let outermost = null;\n\n  // Bounded, so a malformed `aria-controls` cycle can’t hang the page\n  for (let i = 0; i < 10 && opener; i += 1) {\n    outermost = opener;\n\n    if (opener.getAttribute('aria-expanded') === 'true') {\n      opener.click();\n    }\n\n    const parentMenu = /** @type {HTMLElement | null} */ (\n      opener.closest('[role=\"menu\"], [role=\"menubar\"]')\n    );\n\n    opener = parentMenu ? getMenuOpener(parentMenu) : null;\n  }\n\n  return outermost;\n};\n\n/**\n * Leave the menu the way Tab should: close it along with every menu above it, then carry focus on\n * to whatever follows the outermost opener. The browser can’t be left to do this itself, because a\n * modal `<dialog>` confines Tab to its own contents.\n * @internal\n * @param {HTMLElement} menu Menu element.\n * @param {boolean} backwards Whether to move to the previous tab stop instead, as Shift+Tab.\n */\nexport const leaveMenu = async (menu, backwards) => {\n  const opener = closeMenuChain(menu);\n\n  if (!opener) {\n    return;\n  }\n\n  // Somewhere to stand while the menu is torn down, and the fallback if there’s nothing beyond\n  opener.focus();\n  await sleep(50);\n  focusAdjacentTabStop(opener, backwards);\n};\n\n/**\n * Open the submenu of the given menu item if needed, and move focus onto its first item.\n * @internal\n * @param {HTMLElement} item Menu item with `aria-haspopup=\"menu\"`.\n * @param {string} selector CSS selector matching the menu items.\n */\nexport const enterSubmenu = async (item, selector) => {\n  const submenuId = item.getAttribute('aria-controls');\n\n  if (!submenuId) {\n    return;\n  }\n\n  if (item.getAttribute('aria-expanded') !== 'true') {\n    item.click();\n  }\n\n  const submenu = document.getElementById(submenuId);\n\n  // The submenu is revealed and positioned asynchronously, and an element that is still hidden or\n  // invisible cannot take focus, so keep trying for a few frames\n  for (let i = 0; i < 20; i += 1) {\n    const first = /** @type {HTMLElement | undefined} */ (\n      [...(submenu?.querySelectorAll(selector) ?? [])].find(\n        (element) => !element.matches(INACTIVE_MEMBER_SELECTOR),\n      )\n    );\n\n    first?.focus();\n\n    if (first && document.activeElement === first) {\n      return;\n    }\n\n    // eslint-disable-next-line no-await-in-loop\n    await sleep(20);\n  }\n};\n\n/**\n * Close a submenu and move focus back onto the menu item that opens it.\n * @internal\n * @param {HTMLElement} item Menu item with `aria-haspopup=\"menu\"`.\n */\nexport const leaveSubmenu = (item) => {\n  if (item.getAttribute('aria-expanded') === 'true') {\n    item.click();\n  }\n\n  item.focus();\n};\n\n/**\n * Handle the keys that only a menu responds to: Tab, which leaves the menu entirely rather than\n * stepping through it, Escape, which dismisses just a submenu, and the inline arrows, which step\n * into a submenu and back out again. Called by the group before its own handling, once it has left\n * the keys pressed in a text field to that field.\n * @internal\n * @param {Group} group Menu or menubar group.\n * @param {KeyboardEvent} event `keydown` event.\n * @param {HTMLElement | undefined} currentTarget Member the key was pressed on, if any.\n * @returns {boolean} Whether the key has been dealt with, so the group must leave it alone.\n */\nexport const handleMenuKey = (group, event, currentTarget) => {\n  const { key, ctrlKey, metaKey, shiftKey, altKey } = event;\n  const { parent } = group;\n\n  // Shift is allowed through here, unlike the keys below, because Shift+Tab leaves the menu just\n  // the same. A menu rendered inline, with no opener to return to, leaves Tab to the browser to\n  // move focus on as usual.\n  if (key === 'Tab' && !ctrlKey && !metaKey && !altKey) {\n    if (getMenuOpener(parent)) {\n      event.preventDefault();\n      leaveMenu(parent, shiftKey);\n    }\n\n    return true;\n  }\n\n  if (hasModifier(event)) {\n    return false;\n  }\n\n  // Escape in a submenu dismisses just that submenu. Propagation is stopped so the popup, whose own\n  // Escape handler sits on the `<dialog>` this submenu shares with its parent, doesn’t go on to\n  // close the whole stack.\n  if (key === 'Escape') {\n    const parentMenuItem = getParentMenuItem(parent);\n\n    if (parentMenuItem) {\n      event.preventDefault();\n      event.stopPropagation();\n      leaveSubmenu(parentMenuItem);\n\n      return true;\n    }\n\n    return false;\n  }\n\n  // Submenu traversal. In a vertical menu the inline arrows are free, so they step into a submenu\n  // and back out again, as the Menu pattern expects. Mirrored for RTL.\n  if (group.orientation !== 'vertical') {\n    return false;\n  }\n\n  const { prevKey: outOfSubmenuKey, nextKey: intoSubmenuKey } = getArrowKeys('horizontal', isRTL());\n\n  if (key === intoSubmenuKey && currentTarget?.getAttribute('aria-haspopup') === 'menu') {\n    event.preventDefault();\n    enterSubmenu(currentTarget, group.selector);\n\n    return true;\n  }\n\n  if (key === outOfSubmenuKey) {\n    const parentMenuItem = getParentMenuItem(parent);\n\n    if (parentMenuItem) {\n      event.preventDefault();\n      leaveSubmenu(parentMenuItem);\n\n      return true;\n    }\n  }\n\n  return false;\n};\n","import { isRTL } from '@sveltia/i18n';\nimport { generateElementId } from '@sveltia/utils/element';\nimport { CompositeWidget, createWidgetAttachment } from './composite-widget.svelte.js';\nimport { scrollIntoViewIfNeeded } from './scroll.js';\nimport { getItemLabel, normalize } from './text.js';\nimport { isPrintableKey } from './type-ahead.js';\nimport { handleMenuKey } from './menu.js';\nimport {\n  getArrowKeys,\n  getGridTargetIndex,\n  getLinearTargetIndex,\n  hasModifier,\n  INACTIVE_MEMBER_SELECTOR,\n} from './navigation.js';\n\n/**\n * Set an element’s `tabindex` attribute, leaving the DOM alone if it already holds that value.\n * @param {HTMLElement} element Element.\n * @param {number} tabIndex New value.\n */\nconst setTabIndex = (element, tabIndex) => {\n  if (element.getAttribute('tabindex') !== String(tabIndex)) {\n    element.tabIndex = tabIndex;\n  }\n};\n\n/**\n * @type {{ [role: string]: {\n * orientation: 'vertical' | 'horizontal',\n * childRoles: string[],\n * childSelectedAttr: 'aria-selected' | 'aria-checked',\n * focusChild: boolean\n * selectFirst: boolean\n * controlsPanel: boolean\n * rovingTabStop: 'selected' | 'first'\n * } }}\n */\nconst config = {\n  grid: {\n    orientation: 'vertical',\n    childRoles: ['row'],\n    childSelectedAttr: 'aria-selected',\n    focusChild: true,\n    // Rows are data, not a choice the widget has to make on the user’s behalf: nothing is\n    // selected until the user selects it. The first row is only the tab stop.\n    selectFirst: false,\n    controlsPanel: false,\n    rovingTabStop: 'selected',\n  },\n  listbox: {\n    orientation: 'vertical',\n    childRoles: ['option'],\n    childSelectedAttr: 'aria-selected',\n    focusChild: false,\n    selectFirst: false,\n    controlsPanel: false,\n    rovingTabStop: 'selected',\n  },\n  menu: {\n    orientation: 'vertical',\n    childRoles: ['menuitem', 'menuitemcheckbox', 'menuitemradio'],\n    childSelectedAttr: 'aria-checked',\n    focusChild: true,\n    selectFirst: false,\n    controlsPanel: false,\n    rovingTabStop: 'first',\n  },\n  menubar: {\n    orientation: 'horizontal',\n    childRoles: ['menuitem', 'menuitemcheckbox', 'menuitemradio'],\n    childSelectedAttr: 'aria-checked',\n    focusChild: true,\n    selectFirst: false,\n    controlsPanel: false,\n    rovingTabStop: 'first',\n  },\n  radiogroup: {\n    orientation: 'horizontal',\n    childRoles: ['radio'],\n    childSelectedAttr: 'aria-checked',\n    focusChild: true,\n    selectFirst: false,\n    controlsPanel: false,\n    rovingTabStop: 'selected',\n  },\n  tablist: {\n    orientation: 'horizontal',\n    childRoles: ['tab'],\n    childSelectedAttr: 'aria-selected',\n    focusChild: true,\n    selectFirst: true,\n    controlsPanel: true,\n    rovingTabStop: 'selected',\n  },\n};\n\n/**\n * Check whether the given member can hold a selected state. A plain menu item is an action, not a\n * choice, so it has no checked state, and a member marked with `data-selectable=\"false\"`, such as\n * the caption row of a collapsible row group in a grid, can be focused but not selected.\n * @internal\n * @param {HTMLElement} element Member element.\n * @param {string | null} [role] The member’s role, if already read.\n * @returns {boolean} Result.\n */\nconst isSelectable = (element, role = element.getAttribute('role')) =>\n  role !== 'menuitem' && element.dataset.selectable !== 'false';\n\n/**\n * Move the cursor of a composite widget that keeps focus on itself, such as a listbox, onto the\n * given member: mark the member with the `focused` class, taking it off any other, and point the\n * widget’s `aria-activedescendant` at it.\n * @param {HTMLElement} parent Widget root element.\n * @param {HTMLElement} element Member element.\n */\nexport const setFocusedMember = (parent, element) => {\n  parent.querySelectorAll('.focused').forEach((member) => {\n    if (member !== element) {\n      member.classList.remove('focused');\n    }\n  });\n\n  element.classList.add('focused');\n  parent.setAttribute('aria-activedescendant', element.id);\n};\n\n/**\n * Implement keyboard and mouse interactions for a grouping composite widget.\n */\nexport class Group extends CompositeWidget {\n  /**\n   * Observer of the members’ selected state, for the widgets whose panels or tab stop follow it.\n   * @type {MutationObserver | undefined}\n   */\n  selectionObserver = undefined;\n\n  /**\n   * Timer for the pending {@link scrollIntoViewLater} call, if any.\n   * @type {ReturnType<typeof setTimeout> | undefined}\n   */\n  #scrollTimer = undefined;\n\n  /**\n   * Memoized member lists, discarded whenever the widget’s subtree changes. See {@link #members}.\n   * @type {{ all: HTMLElement[], active: HTMLElement[] } | undefined}\n   */\n  #memberCache = undefined;\n\n  /**\n   * Normalized search value of each member, kept alongside the raw value it was derived from so it\n   * can be reused until the member’s label actually changes. Filtering runs over every member on\n   * every keystroke, and `normalize()` is not free — it decomposes the string and strips the\n   * diacritics.\n   * @type {WeakMap<HTMLElement, { raw: string, normalized: string }>}\n   */\n  #searchValueCache = new WeakMap();\n\n  /**\n   * Hidden state each member was last told about, so the filter can skip the members whose state\n   * hasn’t moved. The DOM is deliberately not consulted for this: the listener updates a component,\n   * which renders asynchronously, so two keystrokes within a frame would read a stale attribute.\n   * @type {WeakMap<HTMLElement, boolean>}\n   */\n  #hiddenState = new WeakMap();\n\n  /**\n   * Whether {@link selectTarget} is clicking a radio button to have its component check it, so the\n   * click that comes back to {@link onClick} is not handled as a second selection.\n   * @type {boolean}\n   */\n  #clickingRadio = false;\n\n  /**\n   * Get the normalized value a member is searched by, computing it only when the underlying raw\n   * value has changed since the last call.\n   * @param {HTMLElement} member Member element.\n   * @returns {string} Normalized search value.\n   */\n  #getNormalizedSearchValue(member) {\n    const raw = member.dataset.searchValue ?? getItemLabel(member);\n    const cached = this.#searchValueCache.get(member);\n\n    if (cached?.raw === raw) {\n      return cached.normalized;\n    }\n\n    const normalized = normalize(raw);\n\n    this.#searchValueCache.set(member, { raw, normalized });\n\n    return normalized;\n  }\n\n  /**\n   * Get the panel a member controls, if the group owns such panels. See {@link controlsPanel}.\n   * @param {HTMLElement} member Member element.\n   * @returns {HTMLElement | null} The member’s `aria-controls` target, or `null` if there’s none\n   * or the group doesn’t own its members’ targets.\n   */\n  #getControlTarget(member) {\n    const controlTargetId = this.controlsPanel ? member.getAttribute('aria-controls') : null;\n\n    // Looked up by ID rather than with a selector, which would throw on an ID that isn’t a valid\n    // CSS identifier, such as one starting with a digit\n    return controlTargetId ? document.getElementById(controlTargetId) : null;\n  }\n\n  /**\n   * Show or hide a panel controlled by a member, both to the user and to assistive technology.\n   * @param {HTMLElement} panel Panel element.\n   * @param {boolean} shown Whether the panel is to be shown.\n   */\n  #setPanelShown(panel, shown) {\n    panel.inert = !shown;\n    panel.setAttribute('aria-hidden', String(!shown));\n  }\n\n  /**\n   * Initialize a new `Group` instance.\n   * @param {HTMLElement} parent Parent element.\n   * @param {object} [options] Options.\n   * @param {boolean} [options.clickToSelect] Whether to select an item by clicking on it.\n   */\n  constructor(parent, { clickToSelect = true } = {}) {\n    super(parent);\n\n    this.role = /** @type {string} */ (parent.getAttribute('role'));\n    this.multi = this.parent.getAttribute('aria-multiselectable') === 'true';\n    this.id = generateElementId(this.role);\n    this.parentGroupSelector = `[role=\"group\"], [role=\"${this.role}\"]`;\n    this.clickToSelect = clickToSelect;\n\n    const {\n      orientation,\n      childRoles,\n      childSelectedAttr,\n      focusChild,\n      selectFirst,\n      controlsPanel,\n      rovingTabStop,\n    } = config[this.role];\n\n    this.orientation = this.grid\n      ? 'horizontal'\n      : (this.parent.getAttribute('aria-orientation') ?? orientation);\n    this.childRoles = childRoles;\n    this.childSelectedAttr = childSelectedAttr;\n    this.childSelectedProp = childSelectedAttr.replace('aria-', '');\n    this.focusChild = focusChild;\n    this.selectFirst = selectFirst;\n    /**\n     * Whether a member’s `aria-controls` target is a panel this group owns, as with a tab and its\n     * tabpanel. Only then may the group hide the target when the member isn’t selected. Elsewhere\n     * `aria-controls` means something quite different — on a menu item it points at the submenu the\n     * item opens, and on a toolbar button at the region it acts on — and hiding those would break\n     * the very widget the member controls.\n     * @type {boolean}\n     */\n    this.controlsPanel = controlsPanel;\n    /**\n     * Which member holds the group’s single tab stop. `selected` suits widgets where one member is\n     * the natural entry point, such as the checked radio or the current tab. `first` suits menus,\n     * where any number of items can be checked at once, so the checked state says nothing about\n     * where the keyboard should land.\n     * @type {'selected' | 'first'}\n     */\n    this.rovingTabStop = rovingTabStop;\n\n    this.parent.tabIndex = focusChild ? -1 : 0;\n\n    // The members can be added, removed, disabled or hidden at any time, which is what invalidates\n    // the cached lists. Only the attributes that decide membership are watched, so the group’s own\n    // writes — the selected state and the roving `tabindex` — don’t needlessly discard the cache.\n    this.observer = new globalThis.MutationObserver((records) => {\n      if (!this.#affectsMembers(records)) {\n        return;\n      }\n\n      this.#memberCache = undefined;\n\n      // Members rendered after activation — rows that arrive with the data, say — start out with\n      // whatever `tabindex` their component gives them, so the roving tab stop has to be redone\n      // for them to become a single stop\n      if (this.activated && records.some(({ type }) => type === 'childList')) {\n        this.updateTabStop();\n      }\n    });\n\n    this.observer.observe(parent, {\n      childList: true,\n      subtree: true,\n      attributes: true,\n      attributeFilter: ['aria-disabled', 'aria-hidden'],\n    });\n\n    // A member can also be selected from code, as when a `<Tab>`’s `selected` prop changes. The\n    // group’s own writes are already in sync, so this only matters for the ones made elsewhere: the\n    // panels and the roving tab stop have to follow the new selection.\n    if (controlsPanel || (focusChild && rovingTabStop === 'selected')) {\n      this.selectionObserver = new globalThis.MutationObserver(() => {\n        if (this.activated) {\n          this.syncSelection();\n        }\n      });\n\n      this.selectionObserver.observe(parent, {\n        subtree: true,\n        attributes: true,\n        attributeFilter: [childSelectedAttr],\n      });\n    }\n\n    // Listen right away: a click or a key press that comes before the activation below activates\n    // the members first, rather than being lost\n    this.listen('click', (event) => this.onClick(event));\n    this.listen('keydown', (event) => this.onKeyDown(event));\n  }\n\n  /**\n   * Set up the members on activation.\n   * @override\n   */\n  setUp() {\n    const { allMembers, selected: defaultSelected } = this;\n\n    allMembers.forEach((element, index) => {\n      // Select the first one if no member has the `selected` attribute\n      const isSelected =\n        element.getAttribute(this.childSelectedAttr) === 'true' ||\n        (defaultSelected ? element === defaultSelected : this.selectFirst && index === 0);\n\n      const controlTarget = this.#getControlTarget(element);\n\n      element.id ||= `${this.id}-item-${index + 1}`;\n\n      if (isSelectable(element)) {\n        element.setAttribute(this.childSelectedAttr, String(isSelected));\n      }\n\n      if (controlTarget) {\n        controlTarget.setAttribute('aria-labelledby', element.id);\n        this.#setPanelShown(controlTarget, isSelected);\n\n        if (isSelected) {\n          globalThis.setTimeout(() => {\n            scrollIntoViewIfNeeded(controlTarget);\n          }, 300);\n        }\n      }\n    });\n\n    this.updateTabStop();\n  }\n\n  /**\n   * Put exactly one member in the tab sequence, as a composite widget should. Giving every checked\n   * member `tabindex=\"0\"` would scatter tab stops through the widget — a menu with two checked\n   * items would take three tab presses to step over.\n   */\n  updateTabStop() {\n    const { allMembers, activeMembers } = this;\n\n    // When the group element itself takes focus, as a listbox does, no member is a tab stop\n    if (!this.focusChild) {\n      allMembers.forEach((element) => {\n        element.tabIndex = -1;\n      });\n\n      return;\n    }\n\n    // The stop stays where the user is. This runs again whenever the subtree changes, so a member\n    // the user has moved to must not be handed back to the selected or first one just because a\n    // cell re-rendered or a row arrived. Only when there is no single stop — at activation, where\n    // every member may render as one, or after new members have — is one picked.\n    const { activeElement } = document;\n\n    const focused = activeMembers.find(\n      (element) => element === activeElement || element.contains(activeElement),\n    );\n\n    const holders = activeMembers.filter((element) => element.getAttribute('tabindex') === '0');\n\n    const tabStop =\n      focused ??\n      (holders.length === 1\n        ? holders[0]\n        : ((this.rovingTabStop === 'selected' ? this.selected : undefined) ??\n          // The first member not marked as unselectable, so a grid’s header row or a row group\n          // caption isn’t where the user lands when they tab into it. A plain menu item can’t be\n          // selected either, but it’s still where a menu starts\n          activeMembers.find((element) => element.dataset.selectable !== 'false') ??\n          activeMembers[0]));\n\n    allMembers.forEach((element) => {\n      // Only touch the DOM when it changes; this runs on every mutation of a large widget. The\n      // attribute is what’s compared: a `<button>` reports a `tabIndex` of 0 without one, and the\n      // popup looks the tab stop up by attribute.\n      setTabIndex(element, element === tabStop ? 0 : -1);\n    });\n  }\n\n  /**\n   * Bring the panels and the roving tab stop in line with the members’ selected state, after it has\n   * been changed from outside the group.\n   */\n  syncSelection() {\n    const { allMembers, parent } = this;\n\n    if (this.controlsPanel) {\n      allMembers.forEach((element) => {\n        const controlTarget = this.#getControlTarget(element);\n\n        if (controlTarget) {\n          this.#setPanelShown(\n            controlTarget,\n            element.getAttribute(this.childSelectedAttr) === 'true',\n          );\n        }\n      });\n    }\n\n    // The tab stop moves to the newly selected member, unless the user is in the widget, in which\n    // case it stays where they are\n    if (this.focusChild && !parent.contains(document.activeElement)) {\n      const { selected } = this;\n\n      if (selected) {\n        allMembers.forEach((element) => {\n          setTabIndex(element, element === selected ? 0 : -1);\n        });\n      }\n    }\n  }\n\n  /**\n   * Count the columns of a grid layout from where the members sit, rather than from their widths:\n   * a row of a data grid spans the full width, a tile in a grid listbox doesn’t, and a header row\n   * may have no box at all.\n   * @returns {number} Number of members per visual row, at least 1.\n   */\n  get columnCount() {\n    // Members without a layout box don’t occupy a column\n    const laidOut = this.allMembers.filter((member) => member.getClientRects().length);\n    const firstTop = laidOut[0]?.getBoundingClientRect().top;\n\n    const count = laidOut.findIndex(\n      (member) => Math.abs(member.getBoundingClientRect().top - firstTop) > 1,\n    );\n\n    // Everything on one visual row when nothing wraps\n    return Math.max(1, count === -1 ? laidOut.length : count);\n  }\n\n  /**\n   * CSS selector to retrieve the members.\n   * @type {string}\n   */\n  get selector() {\n    return this.childRoles.map((role) => `[role=\"${role}\"]`).join(',');\n  }\n\n  /**\n   * The member lists, recomputed only once the widget’s subtree has actually changed. A single\n   * arrow key reaches these several times over, and a composite widget can hold thousands of\n   * members, so the `querySelectorAll` and the `matches()` per member that back them are far too\n   * expensive to repeat on every read.\n   *\n   * The observer’s pending records are drained here rather than left to its callback, which runs a\n   * microtask later — too late for a read that happens synchronously after a mutation, as when a\n   * key is dispatched right after the members are swapped out.\n   * @type {{ all: HTMLElement[], active: HTMLElement[] }}\n   */\n  get #members() {\n    if (this.#affectsMembers(this.observer.takeRecords())) {\n      this.#memberCache = undefined;\n    }\n\n    if (!this.#memberCache) {\n      const all = /** @type {HTMLElement[]} */ ([...this.parent.querySelectorAll(this.selector)]);\n\n      this.#memberCache = {\n        all,\n        active: all.filter((element) => !element.matches(INACTIVE_MEMBER_SELECTOR)),\n      };\n    }\n\n    return this.#memberCache;\n  }\n\n  /**\n   * Check whether any of the given mutations adds, removes, disables or hides a member. The subtree\n   * is observed as a whole, so most changes happen inside a member — a cell rendering its content,\n   * an image arriving — and leave the member lists as they were. Recomputing the lists, and the\n   * roving tab stop with them, on each of those would cost a query over every member of a widget\n   * that can hold thousands.\n   * @param {MutationRecord[]} records Mutations.\n   * @returns {boolean} Whether the member lists may have changed.\n   */\n  #affectsMembers(records) {\n    const { selector } = this;\n\n    /**\n     * Check whether the given node is a member or holds one.\n     * @param {Node} node Node.\n     * @returns {boolean} Result.\n     */\n    const hasMember = (node) =>\n      node instanceof Element && (node.matches(selector) || !!node.querySelector(selector));\n\n    return records.some(({ type, target, addedNodes, removedNodes }) =>\n      type === 'attributes'\n        ? target instanceof Element && target.matches(selector)\n        : [...addedNodes].some(hasMember) || [...removedNodes].some(hasMember),\n    );\n  }\n\n  /**\n   * List of all the members.\n   * @type {HTMLElement[]}\n   */\n  get allMembers() {\n    return this.#members.all;\n  }\n\n  /**\n   * List of the enabled and visible members.\n   * @type {HTMLElement[]}\n   */\n  get activeMembers() {\n    return this.#members.active;\n  }\n\n  /**\n   * Get the currently selected member.\n   * @type {HTMLElement | undefined}\n   */\n  get selected() {\n    return this.activeMembers.find(\n      (element) => element.getAttribute(this.childSelectedAttr) === 'true',\n    );\n  }\n\n  /**\n   * Whether the widget is displayed in grid mode.\n   * @type {boolean}\n   */\n  get grid() {\n    return this.role === 'grid' || (this.role === 'listbox' && this.parent.matches('.grid'));\n  }\n\n  /**\n   * Set a member’s selected state and tell its component about the change.\n   * @param {HTMLElement} element Member element.\n   * @param {boolean} selected Whether the member is selected.\n   */\n  #setMemberSelected(element, selected) {\n    element.setAttribute(this.childSelectedAttr, String(selected));\n    element.dispatchEvent(\n      new CustomEvent('Change', { detail: { [this.childSelectedProp]: selected } }),\n    );\n  }\n\n  /**\n   * Click a radio button, so its component checks itself and updates its bound group. The click\n   * bubbles back up to the group, which must not take it as another selection.\n   * @param {HTMLElement} element Radio button.\n   */\n  #clickRadio(element) {\n    this.#clickingRadio = true;\n\n    try {\n      element.click();\n    } finally {\n      this.#clickingRadio = false;\n    }\n  }\n\n  /**\n   * Apply a selection made on the target to one of the members taking part in it: activate a plain\n   * menu item, toggle a member of a multi-select group, or check or uncheck a member of a\n   * single-select group.\n   * @param {MouseEvent | KeyboardEvent} event Triggered event.\n   * @param {HTMLElement} element Member element.\n   * @param {object} context Selection context.\n   * @param {string | null} context.role The member’s role.\n   * @param {boolean} context.isTarget Whether the member is the target.\n   * @param {boolean} context.targetSelectable Whether the target can hold a selected state.\n   * @param {boolean} context.selecting Whether the event is a click or Space, which selects, rather\n   * than a key that merely moves.\n   * @returns {boolean} Whether the member’s selection changed, or an action was taken on it.\n   */\n  #applySelection(event, element, { role, isTarget, targetSelectable, selecting }) {\n    const isMenuItemRadio = role === 'menuitemradio';\n    const selectable = isSelectable(element, role);\n    const multiSelect = selectable && (role === 'menuitemcheckbox' || this.multi);\n    const singleSelect = selectable && targetSelectable && (isMenuItemRadio || !multiSelect);\n    const isSelected = element.getAttribute(this.childSelectedAttr) === 'true';\n    let changed = false;\n\n    // A plain menu item is activated, never checked, and only by a click or Space: the arrow\n    // keys merely move to it\n    if (role === 'menuitem' && isTarget && selecting) {\n      changed = true;\n      element.dispatchEvent(new CustomEvent('Select'));\n    }\n\n    if (multiSelect && isTarget && selecting) {\n      changed = true;\n      this.#setMemberSelected(element, !isSelected);\n\n      if (!isSelected) {\n        element.dispatchEvent(new CustomEvent('Select'));\n      }\n    }\n\n    if (singleSelect && isSelected !== isTarget && (isMenuItemRadio ? selecting : true)) {\n      changed = true;\n      this.#setMemberSelected(element, isTarget);\n\n      if (isTarget) {\n        if (event.type === 'keydown' && role === 'radio') {\n          this.#clickRadio(element);\n        }\n\n        element.dispatchEvent(new CustomEvent('Select'));\n      }\n    }\n\n    return changed;\n  }\n\n  /**\n   * Move the cursor onto the target, or off any other member taking part in a selection: the\n   * focused state where the group itself holds focus, the panel the member controls, and the\n   * group’s active descendant.\n   * @param {HTMLElement} element Member element.\n   * @param {boolean} isTarget Whether the member is the target.\n   * @param {HTMLElement[]} scrollTargets Elements to be scrolled into view, which the target and\n   * its panel are added to.\n   */\n  #moveCursor(element, isTarget, scrollTargets) {\n    const controlTarget = this.#getControlTarget(element);\n\n    if (controlTarget) {\n      this.#setPanelShown(controlTarget, isTarget);\n\n      if (isTarget) {\n        scrollTargets.push(controlTarget);\n      }\n    }\n\n    if (!isTarget) {\n      return;\n    }\n\n    if (this.focusChild) {\n      this.parent.setAttribute('aria-activedescendant', element.id);\n    } else {\n      setFocusedMember(this.parent, element);\n      element.dispatchEvent(new CustomEvent('Focus'));\n    }\n\n    scrollTargets.push(element);\n  }\n\n  /**\n   * Move the roving tab stop and the focus onto the target.\n   * @param {HTMLElement[]} affected Members that took part in the selection.\n   * @param {HTMLElement} newTarget Target element.\n   * @param {boolean} targetAffected Whether the target itself took part, meaning it’s the one to\n   * receive focus.\n   */\n  #moveFocus(affected, newTarget, targetAffected) {\n    // Done right away rather than on the next frame: a key that repeats, or a second press before\n    // the frame, has to start from the member that was just reached, which it reads from the focus\n    affected.forEach((element) => {\n      setTabIndex(element, element === newTarget ? 0 : -1);\n    });\n\n    if (targetAffected) {\n      newTarget.focus();\n      newTarget.dispatchEvent(new CustomEvent('Focus'));\n    }\n  }\n\n  /**\n   * Select (and move focus to) the given target.\n   * @param {(MouseEvent | KeyboardEvent)} event Triggered event.\n   * @param {HTMLElement} newTarget Target element.\n   */\n  selectTarget(event, newTarget) {\n    if (this.isDisabled || this.isReadOnly) {\n      event.preventDefault();\n\n      return;\n    }\n\n    const targetRole = newTarget.getAttribute('role');\n    const targetParent = newTarget.closest(this.parentGroupSelector);\n    // Moving to a member that can’t be selected, such as a plain menu item, leaves the selection\n    // as it is, rather than clearing it as moving to another member of a single-select group does\n    const targetSelectable = isSelectable(newTarget, targetRole);\n\n    // A click or Space selects; the arrow keys and the like merely move\n    const selecting =\n      event.type === 'click' ||\n      (event.type === 'keydown' && /** @type {KeyboardEvent} */ (event).key === ' ');\n\n    /**\n     * Members that took part in this selection, and whose roving `tabindex` therefore has to be\n     * updated. The ones skipped below belong to another menu group and are left alone.\n     * @type {HTMLElement[]}\n     */\n    const affected = [];\n    /**\n     * Whether the target itself took part, meaning it’s the one to receive focus.\n     * @type {boolean}\n     */\n    let targetAffected = false;\n    /**\n     * Elements to be scrolled into view: the target and the panel it controls, if any.\n     * @type {HTMLElement[]}\n     */\n    const scrollTargets = [];\n    /**\n     * Whether the selection changed, or an action was taken on a menu item, which is what the\n     * group’s own `Change` event reports. Moving the cursor alone, or selecting the member that is\n     * already selected, changes nothing.\n     * @type {boolean}\n     */\n    let changed = false;\n\n    this.activeMembers.forEach((element) => {\n      // Reading the role once and comparing it is markedly cheaper than putting every member\n      // through the selector engine three times over\n      const role = element.getAttribute('role');\n\n      if (\n        (role === 'menuitemcheckbox' || role === 'menuitemradio') &&\n        (role !== targetRole || element.closest(this.parentGroupSelector) !== targetParent)\n      ) {\n        return;\n      }\n\n      const isTarget = element === newTarget;\n\n      affected.push(element);\n      targetAffected ||= isTarget;\n\n      if (this.#applySelection(event, element, { role, isTarget, targetSelectable, selecting })) {\n        changed = true;\n      }\n\n      this.#moveCursor(element, isTarget, scrollTargets);\n    });\n\n    if (scrollTargets.length) {\n      this.scrollIntoViewLater(scrollTargets);\n    }\n\n    if (this.focusChild) {\n      this.#moveFocus(affected, newTarget, targetAffected);\n    }\n\n    if (changed) {\n      this.dispatchChange(newTarget);\n    }\n  }\n\n  /**\n   * Scroll the given elements into view after a short delay, replacing any pending scroll, so a\n   * key held down doesn’t queue a scroll for every member it passes and jump back to an old one.\n   * @param {HTMLElement[]} elements Elements to scroll into view.\n   */\n  scrollIntoViewLater(elements) {\n    globalThis.clearTimeout(this.#scrollTimer);\n\n    this.#scrollTimer = globalThis.setTimeout(() => {\n      this.#scrollTimer = undefined;\n\n      elements.forEach(scrollIntoViewIfNeeded);\n    }, 300);\n  }\n\n  /**\n   * Handle the `click` event on the widget.\n   * @param {MouseEvent} event `click` event.\n   */\n  onClick(event) {\n    // eslint-disable-next-line prefer-destructuring\n    const target = /** @type {HTMLElement} */ (event.target);\n\n    const newTarget = target.matches(this.selector)\n      ? target\n      : /** @type {HTMLElement | null} */ (target.closest(this.selector));\n\n    if (!newTarget || event.button !== 0 || !this.clickToSelect || this.#clickingRadio) {\n      return;\n    }\n\n    this.selectTarget(event, newTarget);\n\n    // Where the group itself holds focus, as a listbox does, a click still lands it on the member\n    // clicked. Take it back, so the keys keep moving the cursor from the group and the focus ring\n    // follows the cursor rather than staying on the clicked member. A pointer-driven focus doesn’t\n    // match `:focus-visible`, so no ring appears on the click itself.\n    if (\n      !this.focusChild &&\n      document.activeElement !== this.parent &&\n      newTarget.contains(document.activeElement)\n    ) {\n      this.parent.focus({ preventScroll: true });\n    }\n  }\n\n  /**\n   * Handle the `keydown` event on the widget.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  onKeyDown(event) {\n    const { key } = event;\n    const isMenu = this.childRoles.includes('menuitem');\n    // eslint-disable-next-line prefer-destructuring\n    const target = /** @type {HTMLElement} */ (event.target);\n\n    // A field the user is typing in keeps its keys: the caret moves, the text changes. Escape and\n    // Tab still reach the group, so a menu holding a field can be left the usual ways.\n    if (\n      target !== this.parent &&\n      target.matches('input, textarea, select, [contenteditable]:not([contenteditable=\"false\"])') &&\n      key !== 'Escape' &&\n      key !== 'Tab'\n    ) {\n      return;\n    }\n\n    const currentTarget = this.#getCurrentTarget(target);\n\n    if (isMenu && handleMenuKey(this, event, currentTarget)) {\n      return;\n    }\n\n    if (hasModifier(event)) {\n      return;\n    }\n\n    const { activeMembers } = this;\n\n    if (['Enter', ' ', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(key)) {\n      event.preventDefault();\n    }\n\n    // Home, End and type-ahead only apply to keystrokes on the group itself or on a member. A text\n    // field nested in a menu, say, keeps them for its own caret and content.\n    const fromMember = target === this.parent || target.matches(this.selector);\n\n    // Home and End jump to the ends of the group, in any layout\n    if (key === 'Home' || key === 'End') {\n      if (!fromMember) {\n        return;\n      }\n\n      event.preventDefault();\n\n      const newTarget = activeMembers[key === 'Home' ? 0 : activeMembers.length - 1];\n\n      if (newTarget && newTarget !== currentTarget) {\n        this.selectTarget(event, newTarget);\n      }\n\n      return;\n    }\n\n    // Type-ahead: a printable character moves to the next member whose label starts with what has\n    // been typed so far, as in a native `<select>` and per the Listbox and Menu patterns. This goes\n    // by the visible label, not the search value, which may hold synonyms for filtering — and by\n    // the label element rather than the whole text, which would take in icon ligature names.\n    if (isPrintableKey(event) && fromMember && (this.role === 'listbox' || isMenu)) {\n      // Swallow the key whether or not it matches, as a native `<select>` does. Left to the\n      // browser, a printable key on a non-editable element starts Firefox’s find-as-you-type.\n      event.preventDefault();\n\n      const newTarget = this.#getTypeAheadTarget(key, currentTarget);\n\n      if (newTarget && newTarget !== currentTarget) {\n        this.selectTarget(event, newTarget);\n      }\n\n      return;\n    }\n\n    if (key === 'Enter') {\n      currentTarget?.click(); // Also close the popup if needed\n\n      return;\n    }\n\n    if (key === ' ') {\n      if (currentTarget) {\n        this.selectTarget(event, currentTarget);\n      }\n\n      return;\n    }\n\n    const newTarget = this.#getArrowTarget(key, currentTarget, isRTL());\n\n    if (newTarget && newTarget !== currentTarget) {\n      this.selectTarget(event, newTarget);\n    }\n  }\n\n  /**\n   * Get the member a key press moves from: the member with the cursor where the group itself holds\n   * focus, otherwise the member the key was pressed on.\n   * @param {HTMLElement} target Element the key was pressed on.\n   * @returns {HTMLElement | undefined} Current member, if any.\n   */\n  #getCurrentTarget(target) {\n    if (!this.focusChild) {\n      return this.activeMembers.find((member) => member.matches('.focused'));\n    }\n\n    // A key pressed on a control inside a member, such as a checkbox in a grid row, moves from\n    // that member\n    const member = /** @type {HTMLElement | null} */ (target.closest(this.selector));\n\n    return member && this.parent.contains(member) ? member : undefined;\n  }\n\n  /**\n   * Get the next member whose label starts with what has been typed so far, including the given\n   * key.\n   * @param {string} key Printable key.\n   * @param {HTMLElement | undefined} currentTarget Current member, if any.\n   * @returns {HTMLElement | undefined} Matching member, if any.\n   */\n  #getTypeAheadTarget(key, currentTarget) {\n    const { activeMembers } = this;\n\n    const index = this.typeAheadBuffer.match(\n      activeMembers.map((member) => getItemLabel(member)),\n      key,\n      currentTarget ? activeMembers.indexOf(currentTarget) : -1,\n    );\n\n    return index === -1 ? undefined : activeMembers[index];\n  }\n\n  /**\n   * Get the member an arrow key moves to.\n   * @param {string} key Pressed key.\n   * @param {HTMLElement | undefined} currentTarget Current member, if any.\n   * @param {boolean} rtl Whether the layout runs right to left.\n   * @returns {HTMLElement | undefined} Member to move to, if any.\n   */\n  #getArrowTarget(key, currentTarget, rtl) {\n    const { allMembers, activeMembers } = this;\n\n    if (!this.grid) {\n      const index = currentTarget ? activeMembers.indexOf(currentTarget) : -1;\n      const count = activeMembers.length;\n\n      // A radio group moves with all four arrows whatever its orientation, as native radio buttons\n      // do and as the Radio Group pattern expects: Down and Right go to the next radio, Up and Left\n      // to the previous one, with the inline arrows mirrored for RTL.\n      if (this.role === 'radiogroup') {\n        const inlineIndex = getLinearTargetIndex({\n          key,\n          index,\n          count,\n          ...getArrowKeys('horizontal', rtl),\n        });\n\n        return activeMembers[\n          inlineIndex === -1\n            ? getLinearTargetIndex({ key, index, count, ...getArrowKeys('vertical', rtl) })\n            : inlineIndex\n        ];\n      }\n\n      const keys = getArrowKeys(this.orientation, rtl);\n\n      return activeMembers[getLinearTargetIndex({ key, index, count, ...keys })];\n    }\n\n    const { columnCount } = this;\n    // Members filtered out by a search take no cell in the layout, so they’re left out of the index\n    // the same way they’re left out of the column count. A disabled member still takes its cell,\n    // and stays in.\n    const members = allMembers.filter((member) => member.getAttribute('aria-hidden') !== 'true');\n    const index = currentTarget ? members.indexOf(currentTarget) : -1;\n    // With nothing focused yet, the arrows start from either end of the active members\n    const list = index === -1 ? activeMembers : members;\n    const keys = getArrowKeys('horizontal', rtl);\n    let targetIndex = index;\n    /** @type {HTMLElement | undefined} */\n    let newTarget;\n\n    // Step over a disabled member in the same direction: the inline arrows on to the next member,\n    // the vertical arrows on to the next row in the same column. Each step moves further along or\n    // returns `-1`, so this ends at the edge of the grid at the latest.\n    do {\n      targetIndex = getGridTargetIndex({\n        key,\n        index: targetIndex,\n        count: list.length,\n        columnCount,\n        ...keys,\n      });\n      newTarget = list[targetIndex];\n    } while (newTarget?.matches('[aria-disabled=\"true\"]'));\n\n    return newTarget;\n  }\n\n  /**\n   * Clean up event listeners and observers.\n   * @override\n   */\n  destroy() {\n    super.destroy();\n    globalThis.clearTimeout(this.#scrollTimer);\n    this.observer.disconnect();\n    this.selectionObserver?.disconnect();\n  }\n\n  /**\n   * Called whenever the params are updated. Apply `clickToSelect` if given, and filter the items\n   * based on the search terms if given.\n   * @override\n   * @param {object} params Updated params.\n   * @param {string} [params.searchTerms] Search terms.\n   * @param {boolean} [params.clickToSelect] Whether to select an item by clicking on it.\n   */\n  onUpdate(params) {\n    const { searchTerms } = params;\n\n    if ('clickToSelect' in params) {\n      this.clickToSelect = params.clickToSelect ?? true;\n    }\n\n    // Only a filterable widget, such as a listbox, passes search terms\n    if (typeof searchTerms !== 'string') {\n      return;\n    }\n\n    const terms = normalize(searchTerms);\n    const _terms = terms ? terms.split(/\\s+/) : [];\n    const { allMembers, parent } = this;\n\n    const matched = allMembers\n      .map((member) => {\n        const searchValue = this.#getNormalizedSearchValue(member);\n        const hidden = !_terms.every((term) => searchValue.includes(term));\n\n        // Only report an actual change. Every keystroke runs this over every member, and the\n        // listener on the other end drives a component update\n        if (this.#hiddenState.get(member) !== hidden) {\n          this.#hiddenState.set(member, hidden);\n          member.dispatchEvent(new CustomEvent('Toggle', { detail: { hidden } }));\n        }\n\n        return hidden;\n      })\n      .filter((hidden) => !hidden).length;\n\n    parent.dispatchEvent(\n      new CustomEvent('Filter', { detail: { matched, total: allMembers.length } }),\n    );\n  }\n}\n\n/**\n * Activate a new group. Takes a params object, or a getter function for reactive params, and\n * returns an attachment.\n */\nexport const activateGroup = createWidgetAttachment(Group);\n","<!--\n  @component\n  A variant of `<RadioGroup>`, looking like normal buttons.\n  @see https://w3c.github.io/aria/#radiogroup\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/radio/\n-->\n<script>\n  import { activateGroup } from '../../services/group.svelte.js';\n\n  /**\n   * @import { ContainerProps, FormFieldStateProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & FormFieldStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    ariaLabel = undefined,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div\n  {...restProps}\n  role=\"radiogroup\"\n  class=\"sui select-button-group {className}\"\n  {hidden}\n  tabindex=\"-1\"\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-readonly={readonly}\n  aria-required={required}\n  aria-invalid={invalid}\n  aria-label={ariaLabel}\n  {@attach activateGroup()}\n>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    {@render children?.()}\n  </div>\n</div>\n\n<style>.select-button-group {\n  flex: none;\n  display: inline-flex;\n  align-items: center;\n  margin: var(--sui-focus-ring-width);\n}\n.select-button-group:focus-visible {\n  outline-width: 0 !important;\n}\n.select-button-group :global(button) {\n  margin: 0 !important;\n  border-radius: 0 !important;\n  color: var(--sui-primary-foreground-color);\n}\n.select-button-group :global(button:first-child) {\n  border-start-start-radius: 4px !important;\n  border-end-start-radius: 4px !important;\n}\n.select-button-group :global(button:not(:first-child)) {\n  border-inline-start-width: 0;\n}\n.select-button-group :global(button:last-child) {\n  border-start-end-radius: 4px !important;\n  border-end-end-radius: 4px !important;\n}\n.select-button-group :global(button[aria-checked=true]) {\n  color: var(--sui-highlight-foreground-color);\n  background-color: var(--sui-selected-background-color);\n}\n.select-button-group[aria-invalid=true] :global(button) {\n  border-color: var(--sui-error-border-color);\n}\n.select-button-group[aria-disabled=false] :global(button[aria-disabled='true']) {\n  filter: grayscale(0) opacity(1);\n}\n.select-button-group[aria-disabled=false] :global(button[aria-disabled='true']) :global(*) {\n  filter: grayscale(1) opacity(var(--sui-disabled-opacity, 0.35));\n}\n.select-button-group[aria-readonly=true] :global(button) {\n  pointer-events: none;\n}\n\n.inner {\n  display: contents;\n}</style>\n","<!--\n  @component\n  A variant of `<Radio>`, looking like a normal button.\n  @see https://w3c.github.io/aria/#radio\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/radio/\n-->\n<script>\n  import Button from './button.svelte';\n\n  /**\n   * @import { ButtonProps, CommonEventHandlers } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [selected] Whether to select the widget. An alias of the `aria-checked`\n   * attribute. Because the UI is a button, we expose `selected` instead of `checked`.\n   */\n\n  /**\n   * @type {ButtonProps & CommonEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    selected = $bindable(false),\n    class: className,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<Button\n  {...restProps}\n  role=\"radio\"\n  class=\"sui select-button {className}\"\n  aria-checked={selected}\n  onChange={(event) => {\n    // The radio group reports the state as `checked`, after the `aria-checked` attribute it manages\n    selected = event.detail.checked;\n    onChange?.(event);\n  }}\n></Button>\n","<!--\n  @component\n  A button to open a `<Menu>` widget.\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/\n-->\n<script>\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import Popup from '../util/popup.svelte';\n\n  /**\n   * @import { ButtonProps, CommonEventHandlers } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {HTMLElement} [popupPositionBaseElement] The base element of {@link popupPosition}.\n   * If omitted, this will be the button itself.\n   */\n\n  /**\n   * @type {ButtonProps & CommonEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    popupPosition = 'bottom-left',\n    popupPositionBaseElement = undefined,\n    showPopupBackdrop = false,\n    label = '',\n    variant = undefined,\n    size = 'medium',\n    iconic = false,\n    children: _children,\n    startIcon: _startIcon,\n    endIcon: _endIcon,\n    popup,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Reference to the `<button>` element.\n   * @type {HTMLButtonElement | undefined}\n   */\n  let buttonElement = $state();\n\n  /**\n   * Move focus to the `<button>` element.\n   */\n  export const focus = () => {\n    buttonElement?.focus();\n  };\n</script>\n\n<Button\n  {...restProps}\n  bind:element={buttonElement}\n  class=\"sui menu-button {className}\"\n  {hidden}\n  {disabled}\n  {label}\n  {variant}\n  {size}\n  {iconic}\n  aria-haspopup=\"menu\"\n>\n  {#snippet startIcon()}\n    {@render _startIcon?.()}\n  {/snippet}\n  <!-- eslint-disable-next-line svelte/no-useless-children-snippet -->\n  {#snippet children()}\n    {@render _children?.()}\n  {/snippet}\n  {#snippet endIcon()}\n    {#if _endIcon}\n      {@render _endIcon()}\n    {:else if iconic}\n      <Icon name=\"more_vert\" />\n    {:else}\n      <Icon name=\"arrow_drop_down\" class=\"small-arrow\" />\n    {/if}\n  {/snippet}\n</Button>\n\n<Popup\n  anchor={buttonElement}\n  position={popupPosition}\n  positionBaseElement={popupPositionBaseElement}\n  showBackdrop={showPopupBackdrop}\n>\n  {@render popup?.()}\n</Popup>\n","<!--\n  @component\n  A combination of a normal `<Button>` (default action) and an arrow-only `<MenuButton>` (different\n  actions). For example, Microsoft Word has the Paste button along with the Keep Source Formatting,\n  Match Formatting and Keep Text Only options.\n  @see https://www.google.com/search?q=split+button&tbm=isch\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import Icon from '../icon/icon.svelte';\n  import MenuButton from '../menu/menu-button.svelte';\n  import Button from './button.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ButtonProps, CommonEventHandlers, PopupPosition } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {PopupPosition} [popupPosition] Where to show the dropdown menu.\n   * @property {boolean} [showPopupBackdrop] Whether to show the backdrop for the popup.\n   * @property {Snippet} [chevronIcon] Chevron slot content.\n   * @property {Snippet} [popup] Popup slot content.\n   */\n\n  /**\n   * @type {ButtonProps & CommonEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    hidden = false,\n    disabled = false,\n    label = '',\n    variant = undefined,\n    size = 'medium',\n    popupPosition = 'bottom-left',\n    showPopupBackdrop = false,\n    chevronIcon,\n    popup: _popup,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * @type {HTMLElement | undefined}\n   */\n  let wrapper = $state();\n</script>\n\n<div\n  bind:this={wrapper}\n  role=\"group\"\n  class=\"sui split-button\"\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-label={_('_sui.split_button.x_options', { values: { name: label } })}\n>\n  <Button {...restProps} {hidden} {disabled} {label} {variant} {size}></Button>\n  <MenuButton\n    iconic\n    {hidden}\n    {disabled}\n    {variant}\n    {size}\n    aria-label={_('_sui.split_button.more_options')}\n    {popupPosition}\n    popupPositionBaseElement={wrapper}\n    {showPopupBackdrop}\n  >\n    {#snippet endIcon()}\n      {#if chevronIcon}\n        {@render chevronIcon()}\n      {:else}\n        <Icon name=\"arrow_drop_down\" class=\"small-arrow\" />\n      {/if}\n    {/snippet}\n    {#snippet popup()}\n      {@render _popup?.()}\n    {/snippet}\n  </MenuButton>\n</div>\n\n<style>.split-button {\n  flex: none;\n  display: inline-flex;\n  margin: var(--sui-focus-ring-width);\n}\n.split-button :global(button) {\n  margin: 0;\n}\n.split-button :global(button.menu-button) {\n  border-inline-start-width: 0;\n  border-start-start-radius: 0;\n  border-end-start-radius: 0;\n  aspect-ratio: 3/4;\n}\n.split-button :global(button:not(.menu-button)) {\n  border-start-end-radius: 0;\n  border-end-end-radius: 0;\n}</style>\n","<!--\n  @component\n  The layout container of `<Checkbox>`es.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  /**\n   * @import { ContainerProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'horizontal'|'vertical'} [orientation] Orientation of the widget.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    orientation = 'horizontal',\n    ariaLabel = undefined,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div\n  {...restProps}\n  role=\"group\"\n  class={['sui', 'checkbox-group', className, orientation]}\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-roledescription={_('_sui.role_descriptions.checkbox_group')}\n  aria-label={ariaLabel}\n>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    {@render children?.()}\n  </div>\n</div>\n\n<style>.checkbox-group {\n  display: inline-flex;\n}\n.checkbox-group.horizontal {\n  gap: 8px;\n  align-items: center;\n  flex-wrap: wrap;\n}\n.checkbox-group.vertical {\n  gap: 4px;\n  flex-direction: column;\n}\n@media (pointer: coarse) {\n  .checkbox-group.vertical {\n    gap: 8px;\n  }\n}\n\n.inner {\n  display: contents;\n}</style>\n","/**\n * Get the labelling attributes of the `<button>` in a `<Checkbox>` or `<Radio>`. An accessible name\n * given as a prop or as a plain `aria-label` attribute takes the place of the visible label, which\n * the button otherwise points at — but only when there is one to point at.\n * @param {object} args Arguments.\n * @param {string} args.id Component ID. The visible label has the `${id}-label` ID.\n * @param {string | undefined} args.ariaLabel Accessible name, if any.\n * @param {boolean} args.hasVisibleLabel Whether the component has a visible label.\n * @returns {{ 'aria-label': string | undefined, 'aria-labelledby': string | undefined }}\n * Attributes.\n */\nexport const getToggleLabelAttrs = ({ id, ariaLabel, hasVisibleLabel }) => ({\n  'aria-label': ariaLabel || undefined,\n  'aria-labelledby': !ariaLabel && hasVisibleLabel ? `${id}-label` : undefined,\n});\n\n/**\n * Get the labelling attributes of the `<dialog>` in a `<Dialog>` or `<Drawer>`. The built-in header\n * renders the title in an element the dialog can point at; with a custom header the title is only\n * text, so it becomes `aria-label` unless the consumer names the labelling element.\n * @param {object} args Arguments.\n * @param {string} args.id Component ID. The title has the `${id}-title` ID.\n * @param {string | undefined} args.title Title, if any.\n * @param {string | undefined} args.ariaLabelledby ID of the labelling element named by the\n * consumer, if any.\n * @param {boolean} args.hasCustomHeader Whether the component has a custom header.\n * @returns {{ 'aria-label': string | undefined, 'aria-labelledby': string | undefined }}\n * Attributes.\n */\nexport const getModalLabelAttrs = ({ id, title, ariaLabelledby, hasCustomHeader }) => {\n  const labelledby = ariaLabelledby ?? (!hasCustomHeader && title ? `${id}-title` : undefined);\n\n  return {\n    'aria-label': labelledby ? undefined : title || undefined,\n    'aria-labelledby': labelledby,\n  };\n};\n\n/**\n * Get the accessible name of a component, given as the `ariaLabel` prop or as a plain `aria-label`\n * attribute, which wrapper components pass through as is. An empty name counts as none, so it\n * doesn’t hide the other one, and isn’t rendered as an empty attribute.\n * @param {object} args Arguments.\n * @param {string | undefined} args.ariaLabel The `ariaLabel` prop.\n * @param {Record<string, any>} args.props Other props, which may hold the `aria-label` attribute.\n * @returns {string | undefined} Accessible name, if any.\n */\nexport const getAccessibleName = ({ ariaLabel, props }) =>\n  ariaLabel || props['aria-label'] || undefined;\n\n/**\n * Get the text of the label shown above a field with the `showLabelAbove` option, for a component\n * that renders the label itself rather than leaving it to an embedded `<TextInput>` or `<Select>`:\n * the field’s accessible name.\n * @param {object} args Arguments.\n * @param {boolean} args.showLabelAbove Whether to show the label above the field.\n * @param {Record<string, any>} args.props Props that hold the accessible name, if any.\n * @returns {string | undefined} Label text, or `undefined` if there’s no label to show.\n */\nexport const getLabelAboveText = ({ showLabelAbove, props }) =>\n  showLabelAbove ? getAccessibleName({ ariaLabel: props.ariaLabel, props }) : undefined;\n","<!--\n  @component\n  The equivalent of the HTML `<input type=\"checkbox\">` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox\n  @see https://w3c.github.io/aria/#checkbox\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/\n-->\n<script>\n  import { getAccessibleName, getToggleLabelAttrs } from '../../services/label.js';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ButtonProps, CommonEventHandlers } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [required] Whether to mark the widget required. An alias of the\n   * `aria-required` attribute.\n   * @property {boolean} [invalid] Whether to mark the widget invalid. An alias of the\n   * `aria-invalid` attribute.\n   * @property {boolean | 'mixed'} [checked] Whether to check the widget. An alias of the\n   * `aria-checked` attribute.\n   * @property {string} [label] Text label displayed next to the checkbox.\n   * @property {string} [ariaLabel] `aria-label` attribute.\n   * @property {Snippet} [checkIcon] Check icon slot content.\n   * @property {string[]} [group] The two-way bound variable to manage the state of a group of\n   * checkboxes. It works in the same way as the [`<input\n   * bind:group>`](https://svelte.dev/docs/svelte/bind#input-bind:group) of Svelte.\n   */\n\n  /**\n   * @type {ButtonProps & CommonEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    checked = $bindable(false),\n    class: className,\n    name = undefined,\n    value = undefined,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    label = undefined,\n    ariaLabel = undefined,\n    group = $bindable(),\n    onChange,\n    children,\n    checkIcon,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n\n  /**\n   * Reference to the `<button>` element.\n   * @type {HTMLButtonElement | undefined}\n   */\n  let buttonElement = $state();\n\n  const hasVisibleLabel = $derived(!!(children || label));\n  const labelAttrs = $derived(\n    getToggleLabelAttrs({\n      id,\n      ariaLabel: getAccessibleName({ ariaLabel, props: restProps }),\n      hasVisibleLabel,\n    }),\n  );\n  const indeterminate = $derived(checked === 'mixed');\n\n  // Sync `checked` with `group` and `value`\n  $effect(() => {\n    if (Array.isArray(group)) {\n      if (group.includes(value)) {\n        if (checked !== true) {\n          checked = true;\n        }\n      } else if (checked !== false) {\n        checked = false;\n      }\n    }\n  });\n</script>\n\n<div\n  role=\"none\"\n  class=\"sui checkbox {className}\"\n  class:checked\n  class:indeterminate\n  class:disabled\n  class:readonly\n  {hidden}\n  onclick={(event) => {\n    event.preventDefault();\n    event.stopPropagation();\n\n    // The button handles its own clicks, and doesn’t let them reach here\n    /* v8 ignore else */\n    if (!(/** @type {HTMLElement} */ (event.target).matches('button'))) {\n      buttonElement?.click();\n    }\n  }}\n>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    <Button\n      {...restProps}\n      bind:element={buttonElement}\n      role=\"checkbox\"\n      {id}\n      {name}\n      {value}\n      {hidden}\n      {disabled}\n      {readonly}\n      aria-required={required}\n      aria-invalid={invalid}\n      aria-checked={checked}\n      {...labelAttrs}\n      onclick={(event) => {\n        event.preventDefault();\n        event.stopPropagation();\n\n        if (disabled || readonly) {\n          return;\n        }\n\n        checked = indeterminate ? true : !checked;\n\n        // The effect above keeps `checked` in step with the group, so a newly checked box is never\n        // in the group already, and a newly unchecked one is never missing from it\n        if (Array.isArray(group)) {\n          if (checked) {\n            /* v8 ignore else */\n            if (!group.includes(value)) {\n              group = [...group, value];\n            }\n          } else /* v8 ignore else */ if (group.includes(value)) {\n            group = group.filter((v) => v !== value);\n          }\n        }\n\n        onChange?.(new CustomEvent('Change', { detail: { checked } }));\n      }}\n    >\n      {#snippet startIcon()}\n        {#if checkIcon}\n          {@render checkIcon()}\n        {:else if indeterminate}\n          <Icon name=\"remove\" />\n        {:else if checked}\n          <Icon name=\"check\" />\n        {/if}\n      {/snippet}\n    </Button>\n    {#if hasVisibleLabel}\n      <label id=\"{id}-label\">\n        {#if children}\n          {@render children()}\n        {:else}\n          {label}\n        {/if}\n      </label>\n    {/if}\n  </div>\n</div>\n\n<style>.checkbox {\n  display: inline-flex;\n  align-items: center;\n  gap: 8px;\n  margin: var(--sui-focus-ring-width);\n  min-width: 24px;\n  min-height: 24px;\n  color: var(--sui-control-foreground-color);\n  font-family: var(--sui-control-font-family);\n  font-size: var(--sui-control-font-size);\n  line-height: var(--sui-control-line-height);\n  cursor: pointer;\n  -webkit-user-select: none;\n  user-select: none;\n}\n.checkbox:hover :global(button) {\n  background-color: var(--sui-hover-background-color);\n}\n.checkbox:hover :global(button[aria-checked=true]) {\n  background-color: var(--sui-primary-accent-color-light);\n}\n.checkbox:active :global(button) {\n  background-color: var(--sui-active-background-color);\n}\n.checkbox:active :global(button[aria-checked=true]) {\n  background-color: var(--sui-primary-accent-color-dark);\n}\n.checkbox :global(button) {\n  flex: none;\n  align-items: center;\n  justify-content: center;\n  overflow: hidden;\n  margin: 0 !important;\n  border-width: var(--sui-checkbox-border-width, 1.5px);\n  border-color: var(--sui-checkbox-border-color);\n  border-radius: var(--sui-checkbox-border-radius);\n  padding: 0;\n  width: var(--sui-checkbox-height);\n  height: var(--sui-checkbox-height);\n  color: var(--sui-primary-accent-text-color);\n  background-color: var(--sui-checkbox-background-color);\n  transition: all 200ms;\n}\n.checkbox :global(button[aria-checked=true]) {\n  border-color: var(--sui-checkbox-border-color-checked, var(--sui-primary-accent-color));\n  color: var(--sui-checkbox-foreground-color-checked, var(--sui-primary-accent-color-inverted));\n  background-color: var(--sui-checkbox-background-color-checked, var(--sui-primary-accent-color));\n}\n.checkbox :global(button[aria-invalid=true]) {\n  border-color: var(--sui-error-border-color);\n  color: var(--sui-error-foreground-color);\n}\n.checkbox :global(button[aria-checked=true][aria-invalid=true]) {\n  background-color: var(--sui-checkbox-background-color);\n}\n.checkbox :global(button) :global(.icon) {\n  font-size: calc(var(--sui-checkbox-height) - 2px);\n}\n.checkbox label {\n  cursor: inherit;\n}\n.checkbox.readonly {\n  cursor: default;\n}\n.checkbox.readonly :global(button), .checkbox.readonly:is(:hover, :active) :global(button) {\n  background-color: var(--sui-checkbox-background-color);\n}\n.checkbox.readonly :global(button[aria-checked='true']:not([aria-invalid='true'])), .checkbox.readonly:is(:hover, :active) :global(button[aria-checked='true']:not([aria-invalid='true'])) {\n  border-color: var(--sui-readonly-accent-color);\n  color: var(--sui-readonly-accent-color-inverted);\n  background-color: var(--sui-readonly-accent-color);\n}\n\n.inner {\n  display: contents;\n}</style>\n","<!--\n  @component\n  A content divider with no line. It can be flexible.\n-->\n<script>\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [flex] Whether to make the spacer flexible.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    flex = false,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div {...restProps} role=\"none\" class=\"sui spacer {className}\" class:flex></div>\n\n<style>.spacer.flex:not([hidden]) {\n  display: block;\n  flex: auto;\n}\n.spacer:not(.flex) {\n  width: 8px;\n  height: 8px;\n}</style>\n","<!--\n  @component\n  The Close button shared by `<Dialog>` and `<Drawer>`. Internal; not exported.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the button.\n   * @property {string} controls ID of the dialog or drawer the button closes.\n   * @property {Snippet} [closeIcon] Custom icon, used instead of the default one.\n   * @property {() => void} onClose Callback invoked when the button is clicked.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    class: className = undefined,\n    controls,\n    closeIcon = undefined,\n    onClose,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<Button\n  variant=\"ghost\"\n  iconic\n  class={className}\n  aria-label={_('_sui.close')}\n  aria-controls={controls}\n  onclick={() => {\n    onClose();\n  }}\n>\n  {#snippet startIcon()}\n    {#if closeIcon}\n      {@render closeIcon()}\n    {:else}\n      <Icon name=\"close\" />\n    {/if}\n  {/snippet}\n</Button>\n","<!--\n  @component\n  A feedback dialog widget based on the HTML `<dialog>` element.\n  @see https://w3c.github.io/aria/#dialog\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/\n-->\n<script module>\n  /**\n   * Keep the distance a dialog is dragged within the room it has on either side.\n   * @param {number} distance Distance moved.\n   * @param {number} before Room on the left or top.\n   * @param {number} after Room on the right or bottom.\n   * @returns {number} Clamped distance.\n   */\n  const clamp = (distance, before, after) =>\n    Math.min(Math.max(distance, -before), Math.max(after, 0));\n</script>\n\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { sleep } from '@sveltia/utils/misc';\n  import { getModalLabelAttrs } from '../../services/label.js';\n  import Button from '../button/button.svelte';\n  import Spacer from '../divider/spacer.svelte';\n  import Modal from '../util/modal.svelte';\n  import ModalCloseButton from './modal-close-button.svelte';\n\n  /**\n   * @import { DialogProps, ModalProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ModalProps & DialogProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    value = $bindable(''),\n    title,\n    ariaLabelledby = undefined,\n    role = 'dialog',\n    size = 'medium',\n    modal = true,\n    showBackdrop = undefined,\n    movable = false,\n    class: className,\n    showClose = false,\n    showOk = true,\n    showCancel = true,\n    okLabel = '',\n    okShortcuts = undefined,\n    okDisabled = false,\n    cancelLabel = '',\n    cancelShortcuts = undefined,\n    cancelDisabled = false,\n    focusInput = true,\n    onBeforeOk = undefined,\n    children,\n    header,\n    headerExtra,\n    footer,\n    footerExtra,\n    closeIcon,\n    input: _input,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * The ID of the dialog.\n   * @type {string}\n   */\n  const id = $props.id();\n\n  /**\n   * Labelling attributes for the `<dialog>`, giving it an accessible name.\n   */\n  const labelAttrs = $derived(\n    getModalLabelAttrs({ id, title, ariaLabelledby, hasCustomHeader: !!header }),\n  );\n  /**\n   * A reference to the modal component.\n   * @type {Modal | undefined}\n   */\n  let modalComponent = $state();\n  /**\n   * Whether {@link onBeforeOk} is running, during which the OK button is disabled.\n   */\n  let okBusy = $state(false);\n\n  /**\n   * Close the dialog with the OK button, unless {@link onBeforeOk} says to keep it open because the\n   * request it sends has failed, so the user can correct what they entered.\n   */\n  const confirm = async () => {\n    if (onBeforeOk) {\n      okBusy = true;\n\n      try {\n        if ((await onBeforeOk()) === false) {\n          return;\n        }\n      } catch {\n        return;\n      } finally {\n        okBusy = false;\n      }\n    }\n\n    modalComponent?.close('ok');\n  };\n  /**\n   * @type {HTMLElement | undefined}\n   */\n  let content = $state();\n\n  /**\n   * How far the user has moved the dialog from the center of the viewport by dragging its header.\n   * @type {{ x: number, y: number }}\n   */\n  let offset = $state({ x: 0, y: 0 });\n  /**\n   * Where the current drag started, if the user is dragging the header.\n   * @type {{ pointerId: number, x: number, y: number, offset: { x: number, y: number }, rect:\n   * DOMRect } | undefined}\n   */\n  let dragStart;\n\n  /**\n   * Move the dialog back to the center of the viewport, ending a drag if any.\n   */\n  const recenter = () => {\n    offset = { x: 0, y: 0 };\n    dragStart = undefined;\n  };\n\n  $effect(() => {\n    if (!open) {\n      return undefined;\n    }\n\n    // Start from the center whenever the dialog is opened again\n    recenter();\n\n    if (!movable) {\n      return undefined;\n    }\n\n    // A moved dialog could end up outside a smaller viewport, so bring it back to the center\n    window.addEventListener('resize', recenter);\n\n    return () => {\n      window.removeEventListener('resize', recenter);\n    };\n  });\n\n  /**\n   * Start moving the dialog when the header is pressed, unless a button or another control in the\n   * header is. Only bound when the dialog is {@link movable}.\n   * @param {PointerEvent} event `pointerdown` event.\n   */\n  const onHeaderPointerDown = (event) => {\n    const { button, pointerId, clientX, clientY, currentTarget, target } = event;\n    const headerElement = /** @type {HTMLElement} */ (currentTarget);\n\n    // Look for the control within the header only: the `<dialog>` around it has `tabindex` as well\n    const control = /** @type {HTMLElement} */ (target).closest(\n      'button, input, select, textarea, a, [tabindex]',\n    );\n\n    if (button !== 0 || (control && headerElement.contains(control))) {\n      return;\n    }\n\n    event.preventDefault();\n    headerElement.setPointerCapture(pointerId);\n    dragStart = {\n      pointerId,\n      x: clientX,\n      y: clientY,\n      offset: { ...offset },\n      // The header is rendered within the content\n      rect: /** @type {HTMLElement} */ (content).getBoundingClientRect(),\n    };\n  };\n\n  /**\n   * Move the dialog along with the pointer, keeping it within the viewport.\n   * @param {PointerEvent} event `pointermove` event.\n   */\n  const onHeaderPointerMove = ({ pointerId, buttons, clientX, clientY }) => {\n    if (!dragStart || dragStart.pointerId !== pointerId) {\n      return;\n    }\n\n    // The drag can end without a `pointerup` reaching the header, e.g. when the dialog is closed\n    // halfway, so a move without the primary button pressed ends it. The primary button is the\n    // lowest bit of `buttons`\n    if (buttons % 2 === 0) {\n      dragStart = undefined;\n\n      return;\n    }\n\n    const { x, y, offset: startOffset, rect } = dragStart;\n\n    offset = {\n      x: startOffset.x + clamp(clientX - x, rect.left, window.innerWidth - rect.right),\n      y: startOffset.y + clamp(clientY - y, rect.top, window.innerHeight - rect.bottom),\n    };\n  };\n\n  /**\n   * Stop moving the dialog.\n   * @param {PointerEvent} event `pointerup` or `pointercancel` event.\n   */\n  const onHeaderPointerUp = ({ pointerId }) => {\n    if (dragStart?.pointerId === pointerId) {\n      dragStart = undefined;\n    }\n  };\n\n  /**\n   * Event handlers that let the user move the dialog by dragging its header.\n   */\n  const dragHandlers = {\n    onpointerdown: onHeaderPointerDown,\n    onpointermove: onHeaderPointerMove,\n    onpointerup: onHeaderPointerUp,\n    onpointercancel: onHeaderPointerUp,\n  };\n\n  $effect(() => {\n    if (open && content) {\n      let cancelled = false;\n\n      (async () => {\n        await sleep(50);\n\n        // Leave the focus alone if it has already moved into the content in the meantime, e.g. the\n        // user has clicked an input field or started typing in it, or the content has taken the\n        // focus on its own. Moving it now would pull it away, and selecting the input value would\n        // cause the next keystrokes to replace it.\n        if (cancelled || content?.contains(document.activeElement)) {\n          return;\n        }\n\n        // A read-only or disabled field can’t be edited, so the first one that can is focused,\n        // e.g. the name rather than a username that can’t be changed. A field that can’t take the\n        // focus, like a hidden one, is skipped too: the first candidate the focus lands on wins\n        const candidates = focusInput\n          ? /** @type {(HTMLInputElement | HTMLButtonElement)[]} */ ([\n              ...(content?.querySelectorAll(\n                'input:not([type=\"hidden\"], [readonly], :disabled), button.primary',\n              ) ?? []),\n            ])\n          : [];\n\n        const target = candidates.find((candidate) => {\n          candidate.focus();\n\n          return document.activeElement === candidate;\n        });\n\n        if (target instanceof HTMLInputElement) {\n          target.select();\n        }\n\n        if (!target) {\n          // Fall back to the `<dialog>` element itself, so the focus is never left outside the\n          // modal, e.g. when the dialog has no input field or primary button\n          modalComponent?.focus();\n        }\n      })();\n\n      return () => {\n        cancelled = true;\n      };\n    }\n\n    return undefined;\n  });\n</script>\n\n<Modal\n  bind:this={modalComponent}\n  {...restProps}\n  {role}\n  {id}\n  class=\"dialog\"\n  {...labelAttrs}\n  aria-describedby=\"{id}-body\"\n  bind:open\n  {modal}\n  showBackdrop={showBackdrop ?? modal}\n>\n  <div\n    bind:this={content}\n    role=\"none\"\n    class={['content', className, size]}\n    style:translate={movable ? `${offset.x}px ${offset.y}px` : undefined}\n  >\n    {#if title || showClose || header || headerExtra}\n      <div role=\"none\" class=\"header\" class:movable {...movable ? dragHandlers : {}}>\n        {#if header}\n          {@render header()}\n        {:else}\n          <div role=\"none\" id=\"{id}-title\" class=\"title\">\n            {title}\n          </div>\n          <Spacer flex={true} />\n          {@render headerExtra?.()}\n          {#if showClose}\n            <ModalCloseButton\n              controls={id}\n              {closeIcon}\n              onClose={() => {\n                modalComponent?.close('close');\n              }}\n            />\n          {/if}\n        {/if}\n      </div>\n    {/if}\n    <div role=\"none\" id=\"{id}-body\" class=\"body\">\n      {@render children?.()}\n    </div>\n    {#if showOk || showCancel || footer || footerExtra}\n      <div role=\"none\" class=\"footer\">\n        {#if footer}\n          {@render footer?.()}\n        {:else}\n          {@render footerExtra?.()}\n          <Spacer flex={true} />\n          {#if showOk}\n            <Button\n              variant=\"primary\"\n              label={okLabel || _('_sui.ok')}\n              keyShortcuts={okShortcuts}\n              disabled={okDisabled || okBusy}\n              onclick={confirm}\n            />\n          {/if}\n          {#if showCancel}\n            <Button\n              variant=\"secondary\"\n              label={cancelLabel || _('_sui.cancel')}\n              keyShortcuts={cancelShortcuts}\n              disabled={cancelDisabled}\n              onclick={() => {\n                modalComponent?.close('cancel');\n              }}\n            />\n          {/if}\n        {/if}\n      </div>\n    {/if}\n  </div>\n</Modal>\n\n<style>.content {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n  border-width: var(--sui-dialog-content-border-width, var(--sui-modal-border-width, 0));\n  border-style: solid;\n  border-color: var(--sui-dialog-content-border-color, var(--sui-primary-border-color));\n  border-radius: var(--sui-dialog-content-border-radius, 4px);\n  max-width: calc(100dvw - var(--sui-dialog-content-margin, 16px) * 2);\n  background-color: var(--sui-dialog-content-background-color, var(--sui-secondary-background-color-translucent));\n  box-shadow: var(--sui-dialog-content-box-shadow, 0 8px 16px var(--sui-popup-shadow-color));\n  -webkit-backdrop-filter: var(--sui-dialog-content-backdrop-filter, blur(16px));\n  backdrop-filter: var(--sui-dialog-content-backdrop-filter, blur(16px));\n  transition-property: transform;\n}\n:global(dialog.open) .content {\n  transition-duration: 150ms;\n  transform: scale(100%);\n}\n:global(dialog:not(.open)) .content {\n  transition-duration: 300ms;\n  transform: scale(90%);\n}\n.content.x-small {\n  width: var(--sui-dialog-x-small-content-width, var(--sui-dialog-content-width, 300px));\n  max-height: var(--sui-dialog-x-small-content-max-height, var(--sui-dialog-content-max-height, 300px));\n  --sui-textbox-singleline-min-width: 0;\n}\n@media (max-height: 300px) {\n  .content.x-small {\n    max-height: calc(100dvh - 32px);\n  }\n}\n.content.small {\n  width: var(--sui-dialog-small-content-width, var(--sui-dialog-content-width, 400px));\n  max-height: var(--sui-dialog-small-content-max-height, var(--sui-dialog-content-max-height, 400px));\n}\n@media (max-height: 400px) {\n  .content.small {\n    max-height: calc(100dvh - 32px);\n  }\n}\n.content.medium {\n  width: var(--sui-dialog-medium-content-width, var(--sui-dialog-content-width, 600px));\n  max-height: var(--sui-dialog-medium-content-max-height, var(--sui-dialog-content-max-height, 600px));\n}\n@media (max-height: 600px) {\n  .content.medium {\n    max-height: calc(100dvh - 32px);\n  }\n}\n.content.large {\n  width: var(--sui-dialog-large-content-width, var(--sui-dialog-content-width, 800px));\n  max-height: var(--sui-dialog-large-content-max-height, var(--sui-dialog-content-max-height, 800px));\n}\n@media (max-height: 800px) {\n  .content.large {\n    max-height: calc(100dvh - 32px);\n  }\n}\n.content.x-large {\n  width: var(--sui-dialog-x-large-content-width, var(--sui-dialog-content-width, 1000px));\n  max-height: var(--sui-dialog-x-large-content-max-height, var(--sui-dialog-content-max-height, 1000px));\n}\n@media (max-height: 1000px) {\n  .content.x-large {\n    max-height: calc(100dvh - 32px);\n  }\n}\n\n:is(.header, .footer) {\n  display: flex;\n  align-items: center;\n  gap: 4px;\n}\n\n.header {\n  box-sizing: content-box;\n  margin: var(--sui-dialog-header-margin, 0 16px);\n  border-width: var(--sui-dialog-header-border-width, 0 0 1px);\n  border-color: var(--sui-dialog-header-border-color, var(--sui-secondary-border-color));\n  padding: var(--sui-dialog-header-padding, 16px 8px);\n  height: var(--sui-dialog-header-height, 32px);\n}\n.header.movable {\n  cursor: move;\n}\n.header .title {\n  font-size: var(--sui-font-size-large);\n  font-weight: var(--sui-font-weight-bold);\n}\n\n.footer {\n  margin: var(--sui-dialog-footer-margin, 0 24px 24px);\n}\n@media (width < 768px) {\n  .footer {\n    margin: var(--sui-dialog-footer-margin, 0 16px 16px);\n  }\n}\n\n.body {\n  overflow: auto;\n  padding: var(--sui-dialog-body-padding, var(--sui-dialog-body-margin, 24px 24px));\n  white-space: normal;\n  line-height: var(--sui-line-height-compact);\n}\n@media (width < 768px) {\n  .body {\n    padding: var(--sui-dialog-body-padding, var(--sui-dialog-body-margin, 16px 16px));\n  }\n}</style>\n","<!--\n  @component\n  A modal alert dialog. It only shows the OK button, just like `window.alert()`.\n  @see https://w3c.github.io/aria/#alertdialog\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/\n  @see https://developer.mozilla.org/en-US/docs/Web/API/Window/alert\n-->\n<script>\n  import Dialog from './dialog.svelte';\n\n  /**\n   * @import { DialogProps, ModalProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ModalProps & DialogProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<Dialog {...restProps} bind:open role=\"alertdialog\" showCancel={false}></Dialog>\n","<!--\n  @component\n  A modal confirmation dialog. It shows the OK and Cancel buttons, just like `window.confirm()`.\n  @see https://w3c.github.io/aria/#alertdialog\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/\n  @see https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm\n-->\n<script>\n  import Dialog from './dialog.svelte';\n\n  /**\n   * @import { DialogProps, ModalProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ModalProps & DialogProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<Dialog {...restProps} bind:open role=\"alertdialog\"></Dialog>\n","<!--\n  @component\n  Internal: the visible label of a field with the `showLabelAbove` option, on a line of its own at\n  the start of the field’s wrapper. The field keeps its `aria-label`, so this is only what a sighted\n  user sees, and what they can click to focus the field.\n-->\n<script>\n  /**\n   * @typedef {object} Props\n   * @property {string} label Label text.\n   * @property {string} [for] ID of the field, when it’s a labelable element, such as an `<input>`.\n   * @property {() => HTMLElement | null | undefined} [getTarget] Element to focus on a click,\n   * when the field isn’t a labelable element, such as a `role=\"combobox\"` or `role=\"slider\"`\n   * `<div>`. It’s left alone while it’s disabled, as a native field would be.\n   * @property {string} [id] The `id` attribute, for a wrapper to point `aria-labelledby` at.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    label,\n    for: htmlFor = undefined,\n    getTarget = undefined,\n    id = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<!--\n  A click on a label already focuses a labelable field, which leaves the keyboard to reach the other\n  fields directly, so this click handler needs no keyboard equivalent\n-->\n<!--\n  svelte-ignore a11y_click_events_have_key_events,\n  a11y_no_noninteractive_element_interactions\n-->\n<label\n  for={htmlFor}\n  {id}\n  class=\"sui label-above\"\n  onclick={() => {\n    const target = getTarget?.();\n\n    if (target && target.getAttribute('aria-disabled') !== 'true') {\n      target.focus();\n    }\n  }}\n>\n  {label}\n</label>\n\n<style>.label-above {\n  display: block;\n  flex: 0 0 100%;\n  grid-column: 1/-1;\n  margin-block-end: 4px;\n  color: var(--sui-secondary-foreground-color);\n  font-size: var(--sui-font-size-small);\n  font-weight: var(--sui-font-weight-bold, bold);\n}</style>\n","/**\n * @import { EmojiAnchorRect } from '../../typedefs.js';\n */\n\n/**\n * CSS properties copied from the field onto the mirror element, so the mirror wraps and spaces the\n * text exactly as the field does. Anything that affects the position of a character has to be here.\n */\nconst MIRROR_STYLE_PROPERTIES = [\n  'boxSizing',\n  'width',\n  'borderTopWidth',\n  'borderRightWidth',\n  'borderBottomWidth',\n  'borderLeftWidth',\n  'paddingTop',\n  'paddingRight',\n  'paddingBottom',\n  'paddingLeft',\n  'fontFamily',\n  'fontSize',\n  'fontStretch',\n  'fontStyle',\n  'fontVariant',\n  'fontWeight',\n  'letterSpacing',\n  'lineHeight',\n  'tabSize',\n  'textAlign',\n  'textIndent',\n  'textTransform',\n  'wordBreak',\n  'wordSpacing',\n  'overflowWrap',\n  'direction',\n];\n\n/**\n * Get the viewport-relative bounds of a range of characters within a text field.\n *\n * An `<input>` or `<textarea>` gives no way to ask where a character sits, so the field is\n * replicated with a hidden element carrying the same text and the same typography, and the range is\n * measured there. Only the offset within the mirror is used, which is then applied to the field’s\n * own position, so neither element has to be positioned relative to the other.\n * @param {HTMLInputElement | HTMLTextAreaElement} element Text field.\n * @param {number} start Index of the first character.\n * @param {number} end Index just past the last character.\n * @returns {EmojiAnchorRect | undefined} Bounds, or `undefined` if the field isn’t laid out.\n * @see https://github.com/component/textarea-caret-position\n */\nexport const getFieldCaretRect = (element, start, end) => {\n  const fieldRect = element.getBoundingClientRect();\n\n  // The field is hidden or detached, so there is nothing to anchor to\n  if (!fieldRect.width && !fieldRect.height) {\n    return undefined;\n  }\n\n  const style = globalThis.getComputedStyle(element);\n  const singleLine = element.tagName === 'INPUT';\n  const mirror = document.createElement('div');\n  const marker = document.createElement('span');\n\n  MIRROR_STYLE_PROPERTIES.forEach((property) => {\n    /** @type {Record<string, any>} */ (mirror.style)[property] =\n      /** @type {Record<string, any>} */ (style)[property];\n  });\n\n  Object.assign(mirror.style, {\n    position: 'absolute',\n    top: '0',\n    left: '0',\n    height: 'auto',\n    minHeight: '0',\n    maxHeight: 'none',\n    overflow: 'hidden',\n    visibility: 'hidden',\n    pointerEvents: 'none',\n    // A single-line field never wraps, however long the value is\n    whiteSpace: singleLine ? 'pre' : 'pre-wrap',\n  });\n\n  mirror.setAttribute('aria-hidden', 'true');\n  mirror.textContent = element.value.slice(0, start);\n  // A zero-width space keeps the marker measurable when the range is empty\n  marker.textContent = element.value.slice(start, end) || '\\u200B';\n  mirror.append(marker);\n  document.body.append(mirror);\n\n  const mirrorRect = mirror.getBoundingClientRect();\n  const markerRects = marker.getClientRects();\n  // A wrapped range spans several lines; the last one is where the caret is\n  const markerRect = markerRects[markerRects.length - 1] ?? marker.getBoundingClientRect();\n  const offsetTop = markerRect.top - mirrorRect.top;\n  const offsetLeft = markerRect.left - mirrorRect.left;\n  const offsetRight = markerRect.right - mirrorRect.left;\n  const height = markerRect.height || Number.parseFloat(style.lineHeight) || 0;\n\n  mirror.remove();\n\n  const top = fieldRect.top + offsetTop - element.scrollTop;\n  const left = fieldRect.left + offsetLeft - element.scrollLeft;\n  const right = fieldRect.left + offsetRight - element.scrollLeft;\n\n  return { top, bottom: top + height, left, right };\n};\n","import { EMOJI_DATA } from './generated.js';\n\n/**\n * @import { EmojiEntry } from '../../typedefs.js';\n */\n\n/**\n * Regular expression that matches an emoji shortcode being typed at the end of a line, like `:smi`.\n * The colon must be at the beginning of the text or preceded by a whitespace or an opening bracket,\n * so a colon in the middle of a word, as in `https://` or `12:34`, doesn’t trigger the suggestions.\n * The query is bounded to keep a runaway line from being searched for, at a length that still\n * accommodates the longest published shortcode.\n */\nexport const EMOJI_TRIGGER_REGEX = /(?<=^|[\\s([{\"'«])(?::)(?<query>[a-zA-Z0-9_+-]{1,64})$/;\n\n/**\n * Maximum number of emoji suggestions offered, matching what Discord shows. The dropdown displays\n * five at a time and scrolls through the rest, so this only bounds how far a query can be explored\n * — a single letter otherwise matches over a thousand emojis, all rendered on every keystroke.\n */\nexport const MAX_EMOJI_SUGGESTIONS = 50;\n\n/**\n * Separator between the words of a shortcode. Most use an underscore, as in `party_popper`, but the\n * flags and the compound people use a hyphen, as in `flag-ca` and `man-woman-girl`.\n */\nconst WORD_SEPARATOR_REGEX = /[-_]/;\n/**\n * Emoji list, parsed out of the data the first time it’s searched. This is `undefined` until then,\n * so a page that never sees a shortcode never pays for it.\n * @type {EmojiEntry[] | undefined}\n */\nlet emojiList;\n\n/**\n * Convert the generated emoji data into a searchable list.\n * @internal\n * @param {string} data Emoji data, one line per emoji. See `generated.js` for the format.\n * @returns {EmojiEntry[]} Emoji list.\n */\nexport const parseEmojiData = (data) =>\n  data.split('\\n').map((line) => {\n    const [emoji, shortcodes, keywords = ''] = line.split('\\t');\n    const [name, ...otherShortcodes] = shortcodes.split(' ');\n\n    return {\n      emoji,\n      name,\n      // The alternative shortcodes come first, because they’re what the user might type, while the\n      // keywords merely describe the emoji\n      aliases: [...otherShortcodes, ...(keywords ? keywords.split(' ') : [])],\n    };\n  });\n\n/**\n * Rank given when there is no match at all. Higher than any real rank, so an unmatched emoji sorts\n * last and the ranks can still be compared arithmetically.\n */\nexport const NO_EMOJI_MATCH = 9;\n\n/**\n * Get how well an emoji’s canonical shortcode matches the given query. A lower rank means a better\n * match.\n *\n * A match has to start at a word boundary. The shortcode is matched word by word rather than only\n * as a whole, so a partly typed `:polar` reaches `polar_bear` just as `:polar_bear` does, and the\n * whole shortcode is tested as well, so a query spanning a word boundary like `:polar_b` still\n * matches. What this rules out is a match starting mid-word, which is nearly always coincidental:\n * `:age` would otherwise turn up `mage`, `bagel`, `baggage`, `pager` and `package`.\n * @internal\n * @param {string} name Canonical shortcode.\n * @param {string} query Lower-cased search query without the leading colon.\n * @returns {number} Rank, or {@link NO_EMOJI_MATCH}.\n */\nexport const getEmojiNameMatchRank = (name, query) => {\n  const words = name.split(WORD_SEPARATOR_REGEX);\n\n  if (name === query) {\n    return 0;\n  }\n\n  // What the shortcode leads with is what the emoji mostly is, so `heart_eyes` is a better `:heart`\n  // match than `sparkling_heart`, where the word merely turns up along the way. The whole leading\n  // word has to match: `japanese_castle` is not what `:japan` is after, nor `crystal_ball` `:cry`.\n  if (name.startsWith(query) && WORD_SEPARATOR_REGEX.test(name.charAt(query.length))) {\n    return 1;\n  }\n\n  if (words.includes(query)) {\n    return 2;\n  }\n\n  // The whole shortcode is tested too, so a query spanning a word boundary like `:polar_b` matches\n  if (name.startsWith(query) || words.some((word) => word.startsWith(query))) {\n    return 4;\n  }\n\n  return NO_EMOJI_MATCH;\n};\n\n/**\n * Get how well an emoji’s alternative shortcodes and keywords match the given query. A lower rank\n * means a better match. The ranks interleave with {@link getEmojiNameMatchRank}’s: an exact keyword\n * sits between a whole word of the shortcode and a partial one.\n * @internal\n * @param {string[]} aliases Lower-cased alternative shortcodes and keywords.\n * @param {string} query Lower-cased search query without the leading colon.\n * @returns {number} Rank, or {@link NO_EMOJI_MATCH}.\n */\nexport const getEmojiAliasMatchRank = (aliases, query) => {\n  if (aliases.includes(query)) {\n    return 3;\n  }\n\n  if (aliases.some((alias) => alias.startsWith(query))) {\n    return 5;\n  }\n\n  return NO_EMOJI_MATCH;\n};\n\n/**\n * Get how well an emoji matches the given query, as the best of its shortcode and keyword ranks\n * plus the shortcode rank on its own.\n *\n * The shortcode rank is kept so it can break ties, because the shortcode is what the emoji is\n * called while the keywords are merely associated with it. Many emojis share a keyword — `canada`\n * belongs to 🇨🇦 and 🍁 alike — and the one that also carries the query in its shortcode,\n * `flag-ca`, is the one the user is after.\n * @internal\n * @param {EmojiEntry} entry Emoji entry.\n * @param {string} query Lower-cased search query without the leading colon.\n * @returns {{ rank: number, nameRank: number }} Best rank and shortcode rank, either of which is\n * {@link NO_EMOJI_MATCH} when there is nothing to match.\n */\nexport const getEmojiMatchRank = ({ name, aliases }, query) => {\n  const nameRank = getEmojiNameMatchRank(name, query);\n  const aliasRank = getEmojiAliasMatchRank(aliases, query);\n\n  return { rank: Math.min(nameRank, aliasRank), nameRank };\n};\n\n/**\n * Get how central a match is to the emoji, to separate emojis that match equally well. A lower\n * number means the query is more of what the emoji is about.\n *\n * For a shortcode match, that’s how much of the shortcode the query accounts for: `red_heart` is\n * more of a `:heart` than `smiling_face_with_heart_eyes` is. For a keyword match, it’s how early\n * the keyword comes — the alternative shortcodes are listed first, then the words of the Unicode\n * name in the order it spells them out, which is roughly most to least defining.\n * @internal\n * @param {EmojiEntry} entry Emoji entry.\n * @param {string} query Lower-cased search query without the leading colon.\n * @returns {number} Centrality, comparable only between equally ranked emojis.\n */\nconst getMatchCentrality = ({ name, aliases }, query) => {\n  if (getEmojiNameMatchRank(name, query) < NO_EMOJI_MATCH) {\n    return name.split(WORD_SEPARATOR_REGEX).length;\n  }\n\n  const index = aliases.findIndex((alias) => alias === query || alias.startsWith(query));\n\n  return (index > -1 ? index : aliases.length) * 100 + aliases.length;\n};\n\n/**\n * Search the emoji list for the given query.\n * @param {string} query Search query without the leading colon, e.g. `smi`.\n * @returns {EmojiEntry[]} Matching emojis, best match first, capped at\n * {@link MAX_EMOJI_SUGGESTIONS}.\n */\nexport const searchEmojis = (query) => {\n  const normalizedQuery = query.toLowerCase();\n\n  if (!normalizedQuery) {\n    return [];\n  }\n\n  emojiList ??= parseEmojiData(EMOJI_DATA);\n\n  return (\n    emojiList\n      .map((entry) => {\n        const { rank, nameRank } = getEmojiMatchRank(entry, normalizedQuery);\n\n        return { entry, rank, nameRank, centrality: getMatchCentrality(entry, normalizedQuery) };\n      })\n      .filter(({ rank }) => rank < NO_EMOJI_MATCH)\n      // Equally ranked emojis are settled by the shortcode, then by how central the match is to the\n      // emoji, then by the published order, which is the Unicode order — `Array.prototype.sort()`\n      // is stable. That last resort roughly groups the like with the like, so a tie between two\n      // country flags or two smileys at least comes out in a familiar order.\n      .sort((a, b) => a.rank - b.rank || a.nameRank - b.nameRank || a.centrality - b.centrality)\n      .slice(0, MAX_EMOJI_SUGGESTIONS)\n      .map(({ entry }) => entry)\n  );\n};\n\n/**\n * Get the text to insert in place of a shortcode.\n *\n * A space follows the emoji, so the user can carry straight on typing the next word, the way it\n * works on GitHub, Slack and Discord. It’s left out when the caret is already followed by\n * whitespace, which would otherwise leave a double space behind.\n * @param {string} emoji Emoji character.\n * @param {string} textAfterCaret Text between the caret and the end of the line.\n * @returns {string} Text to insert.\n */\nexport const getEmojiInsertText = (emoji, textAfterCaret) =>\n  /^\\s/.test(textAfterCaret) ? emoji : `${emoji} `;\n\n/**\n * Detect an emoji shortcode being typed right before the caret.\n * @param {string} textBeforeCaret Text between the beginning of the current text node and the\n * caret.\n * @returns {string | undefined} Query without the leading colon, or `undefined` if there is no\n * shortcode.\n */\nexport const detectEmojiTrigger = (textBeforeCaret) =>\n  textBeforeCaret.match(EMOJI_TRIGGER_REGEX)?.groups?.query;\n","/**\n * Placement of the `<EmojiSuggestions>` dropdown, kept apart from the component so it can be\n * tested against arbitrary viewports.\n */\n\n/**\n * @import { EmojiAnchorRect } from '../../typedefs.js';\n */\n\n/**\n * Width of the dropdown, also enforced in the component’s stylesheet.\n */\nexport const LIST_WIDTH = 280;\n/**\n * Gap between the dropdown and the caret, and the minimum margin to the viewport edges.\n */\nexport const LIST_OFFSET = 4;\nexport const VIEWPORT_MARGIN = 8;\n\n/**\n * @typedef {object} SuggestionListPosition\n * @property {string | undefined} top CSS `top`, when the list hangs below the caret.\n * @property {string | undefined} bottom CSS `bottom`, when the list is flipped above the caret.\n * @property {string} left CSS `left`.\n * @property {string} maxHeight CSS `max-height`.\n */\n\n/**\n * Work out where to place the dropdown: below the caret by default, flipped above it when there\n * is more room there and not enough below, and clamped to the viewport horizontally.\n *\n * The dropdown grows away from the start of the line, so it follows the reading direction rather\n * than reaching back across the text: in a right-to-left layout it hangs from the shortcode’s\n * right edge and extends leftwards, mirroring what `activatePopup()` does for anchored popups.\n * @param {object} options Options.\n * @param {EmojiAnchorRect} options.anchorRect Viewport-relative bounds of the shortcode being\n * typed.\n * @param {number} options.listMaxHeight The height the list would like to have, in pixels.\n * @param {{ width: number, height: number }} options.viewport Size of the viewport in pixels.\n * @param {boolean} options.rtl Whether the layout is right-to-left.\n * @param {number} [options.listWidth] Width of the dropdown in pixels, for another popup placed\n * the same way.\n * @returns {SuggestionListPosition} Position.\n */\nexport const getSuggestionListPosition = ({\n  anchorRect,\n  listMaxHeight,\n  viewport,\n  rtl,\n  listWidth = LIST_WIDTH,\n}) => {\n  const { width: innerWidth, height: innerHeight } = viewport;\n  const spaceBelow = innerHeight - anchorRect.bottom;\n  const spaceAbove = anchorRect.top;\n  const flipped = spaceBelow < listMaxHeight + VIEWPORT_MARGIN && spaceAbove > spaceBelow;\n  const anchorLeft = rtl ? anchorRect.right - listWidth : anchorRect.left;\n\n  return {\n    top: flipped ? undefined : `${Math.round(anchorRect.bottom + LIST_OFFSET)}px`,\n    bottom: flipped ? `${Math.round(innerHeight - anchorRect.top + LIST_OFFSET)}px` : undefined,\n    left: `${Math.round(\n      Math.max(VIEWPORT_MARGIN, Math.min(anchorLeft, innerWidth - listWidth - VIEWPORT_MARGIN)),\n    )}px`,\n    maxHeight: `${Math.round(\n      Math.min(listMaxHeight, (flipped ? spaceAbove : spaceBelow) - LIST_OFFSET - VIEWPORT_MARGIN),\n    )}px`,\n  };\n};\n","<!--\n  @component\n  The dropdown shown while an emoji shortcode is being typed, along with the state behind it. This\n  knows nothing about where the text is being typed; a host component detects the shortcode, feeds\n  it in with {@link update} and applies the chosen emoji through the `onSelect` callback.\n\n  The list is rendered in the top layer with the Popover API, so it’s never clipped by whatever\n  contains the field, and it never takes the focus, so the user can keep typing to narrow down the\n  suggestions.\n  @see https://developer.mozilla.org/en-US/docs/Web/API/Popover_API\n-->\n<script>\n  import { _, isRTL } from '@sveltia/i18n';\n  import { onMount, untrack } from 'svelte';\n  import { searchEmojis } from './emoji.js';\n  import { getSuggestionListPosition } from './position.js';\n\n  /**\n   * @import { EmojiAnchorRect, EmojiEntry, EmojiTrigger } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {(trigger: EmojiTrigger) => EmojiAnchorRect | undefined} getAnchorRect Get the\n   * viewport-relative bounds of the shortcode being typed, which the dropdown is anchored to.\n   * @property {(entry: EmojiEntry, trigger: EmojiTrigger) => void} onSelect Called with the emoji\n   * the user picked and the shortcode it should replace.\n   * @property {HTMLElement} [ariaOwner] The element holding the caret, which is labelled with the\n   * highlighted suggestion because the focus never moves to the dropdown.\n   */\n\n  /**\n   * @type {Props}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    getAnchorRect,\n    onSelect,\n    ariaOwner = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * How many suggestions are visible at once. The rest are reached by scrolling.\n   */\n  const VISIBLE_ROWS = 5;\n  /**\n   * Height to assume until a row has been measured, so the first open is positioned sensibly.\n   */\n  const FALLBACK_MAX_HEIGHT = 180;\n\n  const listId = $props.id();\n\n  /**\n   * The shortcode currently being typed, if any.\n   * @type {EmojiTrigger | undefined}\n   */\n  let trigger = $state();\n  /**\n   * Emojis matching the {@link trigger}’s query.\n   * @type {EmojiEntry[]}\n   */\n  let candidates = $state([]);\n  /**\n   * Index of the highlighted candidate.\n   * @type {number}\n   */\n  let selectedIndex = $state(0);\n  /**\n   * Viewport-relative bounds of the shortcode being typed.\n   * @type {EmojiAnchorRect | undefined}\n   */\n  let anchorRect = $state();\n  /**\n   * A reference to the dropdown element, which is only mounted while suggestions are shown.\n   * @type {HTMLElement | undefined}\n   */\n  let listElement = $state();\n  /**\n   * Identifier of the shortcode the user has dismissed with the Escape key, so the suggestions\n   * don’t come back while they keep typing it.\n   * @type {string | undefined}\n   */\n  let dismissedShortcodeId = $state();\n\n  const open = $derived(!!trigger && !!candidates.length);\n\n  /**\n   * Height of one suggestion, measured rather than assumed so the dropdown still shows exactly\n   * {@link VISIBLE_ROWS} of them whatever the theme makes a row.\n   * @type {number}\n   */\n  let rowHeight = $state(0);\n  /**\n   * The dropdown’s own vertical padding and border, which sit outside the rows. `box-sizing` is\n   * `border-box`, so `max-height` has to cover them for the rows to get their full share.\n   * @type {number}\n   */\n  let listChrome = $state(0);\n\n  const listMaxHeight = $derived(\n    rowHeight ? rowHeight * VISIBLE_ROWS + listChrome : FALLBACK_MAX_HEIGHT,\n  );\n\n  /**\n   * Position of the dropdown, flipped above the caret and clamped to the viewport as needed.\n   */\n  const position = $derived(\n    anchorRect\n      ? getSuggestionListPosition({\n          anchorRect,\n          listMaxHeight,\n          viewport: { width: window.innerWidth, height: window.innerHeight },\n          rtl: isRTL(),\n        })\n      : undefined,\n  );\n\n  /**\n   * Whether any suggestions are currently shown.\n   * @returns {boolean} Result.\n   */\n  export const isOpen = () => open;\n\n  /**\n   * Close the list and forget the current shortcode.\n   * @param {boolean} [dismissed] Whether the user has dismissed the list, in which case it stays\n   * closed until they move on to another shortcode.\n   */\n  export const close = (dismissed = false) => {\n    // The state is reset within `untrack()`, because a host closes the list when its field loses\n    // the focus, and the browser fires that `blur` synchronously while it removes the field from\n    // the DOM — which is to say, in the middle of Svelte rendering the block the field lives in,\n    // where a plain assignment would be reported as an unsafe mutation. The same goes for a host\n    // closing the list from an effect teardown. Not tracking the reads is what’s wanted anyway:\n    // whatever happens to be rendering has no business depending on this state.\n    untrack(() => {\n      dismissedShortcodeId = dismissed && trigger ? trigger.id : undefined;\n      trigger = undefined;\n      candidates = [];\n      selectedIndex = 0;\n      anchorRect = undefined;\n    });\n  };\n\n  /**\n   * Feed the shortcode being typed into the list, or nothing to close it.\n   * @param {EmojiTrigger} [newTrigger] Shortcode state.\n   */\n  export const update = (newTrigger) => {\n    if (!newTrigger) {\n      if (trigger || dismissedShortcodeId) {\n        close();\n      }\n\n      return;\n    }\n\n    // The user has dismissed this very shortcode with the Escape key\n    if (dismissedShortcodeId === newTrigger.id) {\n      return;\n    }\n\n    const { id, query } = newTrigger;\n\n    dismissedShortcodeId = undefined;\n    anchorRect = getAnchorRect(newTrigger);\n\n    // The caret may have moved without the query changing, e.g. with an undo; keep the existing\n    // suggestions in that case, so the highlighted item doesn’t jump back to the top\n    if (trigger?.id === id && trigger.query === query) {\n      trigger = newTrigger;\n\n      return;\n    }\n\n    trigger = newTrigger;\n    candidates = searchEmojis(query);\n    selectedIndex = 0;\n  };\n\n  /**\n   * Move the highlight by the given amount, wrapping around at both ends.\n   * @param {number} delta Number of items to move.\n   */\n  export const moveSelection = (delta) => {\n    const { length } = candidates;\n\n    if (length) {\n      selectedIndex = (selectedIndex + delta + length) % length;\n    }\n  };\n\n  /**\n   * Apply the highlighted suggestion and close the list.\n   */\n  export const selectHighlighted = () => {\n    const entry = candidates[selectedIndex];\n\n    if (entry && trigger) {\n      onSelect(entry, trigger);\n    }\n\n    close();\n  };\n\n  /**\n   * Handle a `keydown` event on the field the list is attached to.\n   * @param {KeyboardEvent} event `keydown` event.\n   * @returns {boolean} `true` if the list consumed the event, in which case the field should\n   * ignore it.\n   */\n  export const handleKeyDown = (event) => {\n    const { key, altKey, ctrlKey, metaKey, shiftKey } = event;\n\n    if (!open || altKey || ctrlKey || metaKey) {\n      return false;\n    }\n\n    if (key === 'ArrowDown' || key === 'ArrowUp') {\n      moveSelection(key === 'ArrowDown' ? 1 : -1);\n    } else if ((key === 'Enter' || key === 'Tab') && !shiftKey) {\n      selectHighlighted();\n    } else if (key === 'Escape') {\n      close(true);\n    } else {\n      return false;\n    }\n\n    event.preventDefault();\n\n    return true;\n  };\n\n  // Move the dropdown to the top layer, so it’s not clipped by anything around the field, then\n  // measure a row. The measurement has to happen after the popover is shown, because until then the\n  // element isn’t rendered at all and everything measures zero. A row’s height comes from the\n  // theme’s control height plus its padding, so it’s read back rather than assumed.\n  $effect(() => {\n    void candidates;\n\n    if (!listElement) {\n      return;\n    }\n\n    if (!listElement.matches(':popover-open')) {\n      listElement.showPopover?.();\n    }\n\n    const row = listElement.querySelector('.option');\n\n    // The list is only mounted while there are candidates, so there is always a row\n    /* v8 ignore else */\n    if (row) {\n      const { paddingTop, paddingBottom, borderTopWidth, borderBottomWidth } =\n        getComputedStyle(listElement);\n\n      rowHeight = row.getBoundingClientRect().height;\n      listChrome =\n        Number.parseFloat(paddingTop) +\n        Number.parseFloat(paddingBottom) +\n        Number.parseFloat(borderTopWidth) +\n        Number.parseFloat(borderBottomWidth);\n    }\n  });\n\n  // Advertise that typing here can bring up predictions, for as long as the autocomplete is\n  // attached. `aria-autocomplete` applies to a textbox as much as to a combobox, so the field keeps\n  // whatever role it already had rather than being relabelled — a rich text editor is not a\n  // combobox, and neither is a comment field. `list` says the predictions appear in a popup rather\n  // than being completed inline.\n  // @see https://w3c.github.io/aria/#aria-autocomplete\n  $effect(() => {\n    if (!ariaOwner) {\n      return undefined;\n    }\n\n    const owner = ariaOwner;\n\n    owner.setAttribute('aria-autocomplete', 'list');\n    owner.setAttribute('aria-haspopup', 'listbox');\n\n    return () => {\n      owner.removeAttribute('aria-autocomplete');\n      owner.removeAttribute('aria-haspopup');\n    };\n  });\n\n  // Point at the highlighted suggestion, given the focus stays in the field. The list is only in\n  // the DOM while open, so it can only be referenced while it is. There is deliberately no\n  // `aria-expanded`, which a textbox doesn’t support; the active descendant appearing and\n  // disappearing is what conveys the list opening and closing.\n  $effect(() => {\n    if (!ariaOwner) {\n      return undefined;\n    }\n\n    const owner = ariaOwner;\n\n    if (open) {\n      owner.setAttribute('aria-controls', listId);\n      owner.setAttribute('aria-activedescendant', `${listId}-option-${selectedIndex}`);\n    } else {\n      owner.removeAttribute('aria-controls');\n      owner.removeAttribute('aria-activedescendant');\n    }\n\n    return () => {\n      owner.removeAttribute('aria-controls');\n      owner.removeAttribute('aria-activedescendant');\n    };\n  });\n\n  // Keep the highlighted suggestion visible while the user arrows through a long list. The scroll\n  // has to be instant: an inherited `scroll-behavior: smooth` otherwise animates it, and the\n  // animation never lands while the list is in the top layer, leaving the highlight off screen.\n  $effect(() => {\n    void selectedIndex;\n\n    listElement\n      ?.querySelector('[aria-selected=\"true\"]')\n      ?.scrollIntoView({ block: 'nearest', behavior: 'instant' });\n  });\n\n  onMount(() => {\n    /**\n     * Follow the caret when the page or an ancestor is scrolled or the window is resized.\n     */\n    const reposition = () => {\n      if (trigger) {\n        anchorRect = getAnchorRect(trigger);\n      }\n    };\n\n    /**\n     * Dismiss the list when the user presses somewhere else on the page.\n     *\n     * The popover is `manual` rather than `auto`, so the platform’s own light dismiss is off: an\n     * `auto` popover also closes itself on Escape, which would fight the Escape handling here, and\n     * it would close on a press inside the field the list belongs to, where the caret moving is\n     * what should decide. This covers the one behavior worth borrowing.\n     * @param {PointerEvent} event `pointerdown` event.\n     */\n    const onPointerDown = ({ target }) => {\n      const node = /** @type {Node} */ (target);\n\n      // A press on the list is a choice, not a dismissal, and this runs before the option’s own\n      // handler; a press in the field is left to the caret to sort out\n      if (!open || listElement?.contains(node) || ariaOwner?.contains(node)) {\n        return;\n      }\n\n      close();\n    };\n\n    window.addEventListener('scroll', reposition, { capture: true, passive: true });\n    window.addEventListener('resize', reposition, { passive: true });\n    document.addEventListener('pointerdown', onPointerDown, { capture: true });\n\n    return () => {\n      window.removeEventListener('scroll', reposition, { capture: true });\n      window.removeEventListener('resize', reposition);\n      document.removeEventListener('pointerdown', onPointerDown, { capture: true });\n    };\n  });\n</script>\n\n{#if open && position}\n  <div\n    bind:this={listElement}\n    id={listId}\n    role=\"listbox\"\n    class=\"sui emoji-suggestions\"\n    aria-label={_('_sui.emoji_suggestions')}\n    popover=\"manual\"\n    style:top={position.top}\n    style:bottom={position.bottom}\n    style:left={position.left}\n    style:max-height={position.maxHeight}\n  >\n    {#each candidates as entry, index (entry.emoji)}\n      <div\n        id={`${listId}-option-${index}`}\n        role=\"option\"\n        class=\"option\"\n        tabindex=\"-1\"\n        aria-selected={index === selectedIndex}\n        onmouseenter={() => {\n          selectedIndex = index;\n        }}\n        onmousedown={(event) => {\n          // Keep the focus and the caret where they are, so the shortcode can be replaced\n          event.preventDefault();\n          selectedIndex = index;\n          selectHighlighted();\n        }}\n      >\n        <span role=\"none\" class=\"emoji\">{entry.emoji}</span>\n        <span role=\"none\" class=\"name\">{`:${entry.name}:`}</span>\n      </div>\n    {/each}\n  </div>\n{/if}\n\n<style>.emoji-suggestions {\n  position: fixed;\n  inset: auto;\n  z-index: 1000;\n  display: flex;\n  flex-direction: column;\n  overflow-y: auto;\n  margin: 0;\n  padding: var(--sui-listbox-padding, 4px);\n  width: 280px;\n  font-family: var(--sui-control-font-family);\n  font-size: var(--sui-control-font-size);\n  line-height: var(--sui-control-line-height);\n  -webkit-user-select: none;\n  user-select: none;\n  border-width: var(--sui-listbox-border-width, 1px);\n  border-style: var(--sui-listbox-border-style, solid);\n  border-color: var(--sui-listbox-border-color, var(--sui-secondary-border-color));\n  border-radius: var(--sui-listbox-border-radius, 4px);\n  color: var(--sui-primary-foreground-color);\n  background-color: var(--sui-secondary-background-color-translucent);\n  box-shadow: 0 8px 16px var(--sui-popup-shadow-color);\n  -webkit-backdrop-filter: blur(16px);\n  backdrop-filter: blur(16px);\n}\n\n.option {\n  flex: none;\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  border-radius: var(--sui-option-border-radius);\n  padding: var(--sui-option-padding);\n  min-height: var(--sui-option-height);\n  cursor: default;\n}\n.option[aria-selected=true] {\n  color: var(--sui-highlight-foreground-color);\n  background-color: var(--sui-hover-background-color);\n}\n.option .emoji {\n  flex: none;\n  width: 1.5em;\n  font-size: var(--sui-font-size-large);\n  text-align: center;\n}\n.option .name {\n  flex: auto;\n  overflow: hidden;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n}</style>\n","<!--\n  @component\n  Emoji autocomplete for a plain `<input>` or `<textarea>`. Typing a colon followed by one or more\n  characters, like `:smi`, brings up a list of matching emojis that can be inserted with a click or\n  the Enter key, the same way it works on GitHub, Slack and other apps. This wires the field up to\n  `<EmojiSuggestions>`, which owns the dropdown itself.\n-->\n<script>\n  import { getFieldCaretRect } from '../emoji/caret.js';\n  import { detectEmojiTrigger, getEmojiInsertText } from '../emoji/emoji.js';\n  import EmojiSuggestions from '../emoji/emoji-suggestions.svelte';\n\n  /**\n   * @import { EmojiEntry, EmojiTrigger } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {HTMLInputElement | HTMLTextAreaElement} [element] The field to attach the\n   * suggestions to.\n   */\n\n  /**\n   * A shortcode within a text field, identified by where its colon is, which doesn’t change as the\n   * query grows.\n   * @typedef {EmojiTrigger & { start: number, end: number }} FieldEmojiTrigger\n   */\n\n  /**\n   * @type {Props}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    element = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * A reference to the dropdown.\n   * @type {ReturnType<typeof EmojiSuggestions> | undefined}\n   */\n  let list = $state();\n\n  /**\n   * Look for a shortcode being typed right before the caret.\n   * @returns {FieldEmojiTrigger | undefined} Shortcode state, if any.\n   */\n  const findTrigger = () => {\n    if (!element || element.disabled || element.readOnly) {\n      return undefined;\n    }\n\n    const { value, selectionStart, selectionEnd } = element;\n\n    // Only suggest at a plain caret, not while a range is selected\n    if (selectionStart === null || selectionStart !== selectionEnd) {\n      return undefined;\n    }\n\n    const query = detectEmojiTrigger(value.slice(0, selectionStart));\n\n    if (query === undefined) {\n      return undefined;\n    }\n\n    const start = selectionStart - query.length - 1;\n\n    return { id: String(start), query, start, end: selectionStart };\n  };\n\n  /**\n   * Get the viewport-relative bounds of the shortcode being typed.\n   * @param {EmojiTrigger} trigger Shortcode state.\n   * @returns {ReturnType<typeof getFieldCaretRect>} Bounds, or `undefined` if they can’t be\n   * determined.\n   */\n  const getAnchorRect = (trigger) => {\n    const { start, end } = /** @type {FieldEmojiTrigger} */ (trigger);\n\n    // The trigger was found in the field, so the field is there\n    /* v8 ignore next */\n    return element ? getFieldCaretRect(element, start, end) : undefined;\n  };\n\n  /**\n   * Replace the shortcode being typed with the given emoji.\n   * @param {EmojiEntry} entry Emoji to insert.\n   * @param {EmojiTrigger} trigger Shortcode to replace.\n   */\n  const insertEmoji = (entry, trigger) => {\n    const { query, start, end } = /** @type {FieldEmojiTrigger} */ (trigger);\n\n    // Make sure the shortcode is still where it was when the suggestions appeared\n    if (!element || element.value.slice(start, end) !== `:${query}`) {\n      return;\n    }\n\n    const text = getEmojiInsertText(entry.emoji, element.value.slice(end));\n\n    element.focus();\n    element.setSelectionRange(start, end);\n\n    // `execCommand()` is deprecated but remains the only way to edit a field without wiping its\n    // native undo history, so it’s tried first and `setRangeText()` covers the fallback\n    let inserted = false;\n\n    try {\n      inserted = document.execCommand('insertText', false, text);\n    } catch {\n      inserted = false;\n    }\n\n    if (!inserted) {\n      element.setRangeText(text, start, end, 'end');\n      // Let Svelte bindings and consumer handlers know the value changed\n      element.dispatchEvent(new Event('input', { bubbles: true }));\n    }\n  };\n\n  // Kept out of the effect: in SSR output, esrap moves the comments of the dropped effect onto\n  // the next node, where this cast comment wraps a shorthand prop in parentheses, which is invalid\n  /**\n   * Give the list first refusal on the keys it drives. Anything it doesn’t take is left to the\n   * field, and the `keyup` listener below picks up wherever the caret ends up.\n   * @param {Event} event `keydown` event.\n   */\n  const onKeyDown = (event) => {\n    list?.handleKeyDown(/** @type {KeyboardEvent} */ (event));\n  };\n\n  $effect(() => {\n    if (!element || !list) {\n      return undefined;\n    }\n\n    const field = element;\n\n    /**\n     * Re-examine the text around the caret.\n     */\n    const refresh = () => {\n      list?.update(findTrigger());\n    };\n\n    /**\n     * Close the list when the field loses the focus.\n     */\n    const onBlur = () => {\n      list?.close();\n    };\n\n    field.addEventListener('keydown', onKeyDown);\n    field.addEventListener('keyup', refresh);\n    field.addEventListener('input', refresh);\n    field.addEventListener('mouseup', refresh);\n    field.addEventListener('blur', onBlur);\n\n    return () => {\n      field.removeEventListener('keydown', onKeyDown);\n      field.removeEventListener('keyup', refresh);\n      field.removeEventListener('input', refresh);\n      field.removeEventListener('mouseup', refresh);\n      field.removeEventListener('blur', onBlur);\n      list?.close();\n    };\n  });\n</script>\n\n<EmojiSuggestions bind:this={list} {getAnchorRect} onSelect={insertEmoji} ariaOwner={element} />\n","<!--\n  @component\n  A generic, single-line text field. The equivalent of the HTML `<input type=\"text\">` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/text\n  @see https://w3c.github.io/aria/#textbox\n-->\n<script>\n  import { activateKeyShortcuts } from '@sveltia/utils/events';\n  import { getAccessibleName } from '../../services/label.js';\n  import TruncatedText from '../typography/truncated-text.svelte';\n  import LabelAbove from '../util/label-above.svelte';\n  import EmojiAutocomplete from './emoji-autocomplete.svelte';\n\n  /**\n   * @import {\n   * CommonEventHandlers,\n   * InputEventHandlers,\n   * LabelAboveProps,\n   * TextInputProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [value] Input value.\n   * @property {boolean} [useEmojiAutocomplete] Whether to autocomplete emojis when the user\n   * types a shortcode, like `:smi`.\n   */\n\n  /**\n   * @type {LabelAboveProps & TextInputProps & CommonEventHandlers & InputEventHandlers & Props &\n   * Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    element: boundElement = $bindable(),\n    role = 'textbox',\n    keyShortcuts = undefined,\n    dir = undefined,\n    name = undefined,\n    showInlineLabel = false,\n    showLabelAbove = false,\n    inputmode = 'text',\n    flex = false,\n    monospace = false,\n    debounce = false,\n    useEmojiAutocomplete = false,\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    ariaLabel = undefined,\n    children,\n    oninput,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * A reference to the `<input>` element. It’s kept apart from the bindable `element` prop, which\n   * Svelte resets whenever the props spread onto this component change, unless the consumer binds\n   * it.\n   * @type {HTMLInputElement | undefined}\n   */\n  let element = $state.raw();\n\n  const id = $props.id();\n  /** ID of the `<input>` element, which the label above it points to. */\n  const inputId = $derived(restProps.id ?? `${id}-input`);\n  const timeout = $derived(typeof debounce === 'number' ? debounce : 300);\n  /**\n   * Accessible label, whether given as the `ariaLabel` prop or as a plain `aria-label` attribute,\n   * which the wrapper components such as `<SearchBar>` and `<NumberInput>` pass through as is.\n   * @type {string | undefined}\n   */\n  const label = $derived(getAccessibleName({ ariaLabel, props: restProps }));\n  /** Label shown above the field with `showLabelAbove`, in place of the inline one. */\n  const labelAbove = $derived(showLabelAbove ? label : undefined);\n\n  let debounceTimer = 0;\n\n  $effect(() => () => {\n    clearTimeout(debounceTimer);\n  });\n\n  /**\n   * Update the `value` and call the `oninput` callback.\n   * @param {InputEvent} event The `input` event object.\n   */\n  const fireInput = (event) => {\n    value = element?.value;\n    oninput?.(event);\n  };\n\n  /**\n   * Handle the `input` event. If `debounce` is `true`, the event will be debounced by 300ms. We use\n   * `oninputcapture` to ensure that the event is fired before any `oninput` handlers on parent\n   * elements, including the Lexical editor.\n   * @param {Event} event The `input` event object.\n   */\n  const handleInput = (event) => {\n    const inputEvent = /** @type {InputEvent} */ (event);\n\n    if (debounce) {\n      clearTimeout(debounceTimer);\n      debounceTimer = /** @type {number} */ (\n        /** @type {unknown} */ (\n          setTimeout(() => {\n            fireInput(inputEvent);\n          }, timeout)\n        )\n      );\n    } else {\n      fireInput(inputEvent);\n    }\n  };\n</script>\n\n<div\n  role=\"none\"\n  class=\"sui text-input {className}\"\n  class:flex\n  class:monospace\n  class:disabled\n  class:readonly\n  class:has-label-above={!!labelAbove}\n  {hidden}\n>\n  {#if labelAbove}\n    <LabelAbove label={labelAbove} for={inputId} />\n  {/if}\n  <input\n    bind:this={\n      () => element,\n      (el) => {\n        element = el;\n        boundElement = el;\n      }\n    }\n    type=\"text\"\n    {...restProps}\n    id={inputId}\n    {value}\n    {role}\n    {dir}\n    {name}\n    tabindex={disabled ? -1 : 0}\n    disabled={disabled || undefined}\n    readonly={readonly || undefined}\n    {inputmode}\n    aria-label={label}\n    aria-hidden={hidden}\n    aria-disabled={disabled}\n    aria-readonly={readonly}\n    aria-required={required}\n    aria-invalid={invalid}\n    oninputcapture={handleInput}\n    {@attach activateKeyShortcuts(keyShortcuts)}\n  />\n  {#if useEmojiAutocomplete && !disabled && !readonly}\n    <EmojiAutocomplete {element} />\n  {/if}\n  {#if label && showInlineLabel && !labelAbove}\n    <span id=\"{id}-label\" class=\"label\" class:hidden={!!value} aria-hidden=\"true\">\n      <TruncatedText>\n        {label}\n      </TruncatedText>\n    </span>\n  {/if}\n</div>\n\n<style>.text-input {\n  display: inline-flex;\n  align-items: center;\n  position: relative;\n  margin: var(--sui-focus-ring-width);\n  min-width: var(--sui-textbox-singleline-min-width);\n}\n.text-input.flex:not([hidden]) {\n  display: inline-flex;\n  width: -moz-available;\n  width: -webkit-fill-available;\n  width: stretch;\n  min-width: 0;\n}\n.text-input.has-label-above {\n  flex-wrap: wrap;\n}\n.text-input.monospace {\n  --sui-textbox-font-family: var(--sui-font-family-monospace, monospace);\n}\n.text-input.monospace input::placeholder {\n  font-family: var(--sui-control-font-family);\n}\n\ninput:is(:-webkit-autofill, :-webkit-autofill:focus) {\n  transition: background-color 0s 600000s, color 0s 600000s;\n}\n\ninput {\n  display: inline-block;\n  flex: auto;\n  min-width: 0;\n  height: var(--sui-textbox-height);\n  border-width: var(--sui-textbox-border-width, 1px);\n  border-color: var(--sui-textbox-border-color);\n  border-radius: var(--sui-textbox-border-radius);\n  padding: var(--sui-textbox-singleline-padding);\n  color: var(--sui-textbox-foreground-color);\n  background-color: var(--sui-textbox-background-color);\n  font-family: var(--sui-textbox-font-family);\n  font-size: var(--sui-textbox-font-size);\n  line-height: var(--sui-textbox-singleline-line-height);\n  font-weight: var(--sui-textbox-font-weight, var(--sui-font-weight-normal, normal));\n  letter-spacing: var(--sui-textbox-letter-spacing, normal);\n  transition: all 200ms;\n  text-align: var(--sui-textbox-text-align, start);\n  text-indent: var(--sui-textbox-text-indent, 0);\n  text-transform: var(--sui-textbox-text-transform, none);\n  word-spacing: var(--sui-word-spacing-normal, normal);\n}\ninput:focus {\n  color: var(--sui-textbox-foreground-color-focus, var(--sui-textbox-foreground-color));\n  background-color: var(--sui-textbox-background-color-focus, var(--sui-textbox-background-color));\n}\ninput[aria-invalid=true] {\n  border-color: var(--sui-error-border-color);\n}\ninput:read-only {\n  color: var(--sui-secondary-foreground-color);\n  border-color: var(--sui-textbox-border-color) !important;\n}\ninput:is(:disabled, :read-only) {\n  background-color: var(--sui-disabled-background-color);\n}\ninput ~ :global(button) {\n  flex: none;\n  margin-inline-start: -1px;\n  border-width: 1px;\n  border-color: var(--sui-textbox-border-color);\n  height: var(--sui-textbox-height);\n  aspect-ratio: 1/1;\n}\ninput ~ :global(button:last-child) {\n  border-start-start-radius: 0;\n  border-start-end-radius: 4px;\n  border-end-end-radius: 4px;\n  border-end-start-radius: 0;\n}\ninput ~ :global(button) :global(.icon) {\n  font-size: var(--sui-font-size-xx-large);\n}\n\n.label {\n  position: absolute;\n  inset: var(--sui-textbox-singleline-padding);\n  z-index: 2;\n  display: flex;\n  align-items: center;\n  justify-content: var(--sui-textbox-placeholder-text-align, var(--sui-textbox-text-align, start));\n  pointer-events: none;\n}\n.label.hidden {\n  opacity: 0;\n}\n\ninput:focus + .label {\n  opacity: 0;\n}\n\ninput::placeholder,\n.label {\n  color: var(--sui-textbox-placeholder-foreground-color, var(--sui-textbox-foreground-color));\n  opacity: var(--sui-textbox-placeholder-opacity, 0.5);\n  font-family: var(--sui-textbox-placeholder-font-family, var(--sui-textbox-font-family));\n  font-size: var(--sui-textbox-placeholder-font-size, var(--sui-textbox-font-size));\n  line-height: var(--sui-textbox-placeholder-singleline-line-height, var(--sui-textbox-singleline-line-height));\n  font-weight: var(--sui-textbox-placeholder-font-weight, var(--sui-textbox-font-weight, var(--sui-font-weight-normal, normal)));\n  text-align: var(--sui-textbox-placeholder-text-align, var(--sui-textbox-text-align, start));\n  text-indent: var(--sui-textbox-placeholder-text-indent, var(--sui-textbox-text-indent, 0));\n  letter-spacing: var(--sui-textbox-placeholder-letter-spacing, var(--sui-textbox-letter-spacing, normal));\n}</style>\n","<!--\n  @component\n  A modal prompt dialog. It shows the OK and Cancel buttons as well as a textbox, just like\n  `window.prompt()`.\n  @see https://w3c.github.io/aria/#alertdialog\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/\n  @see https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt\n-->\n<script>\n  import TextInput from '../text-field/text-input.svelte';\n  import Dialog from './dialog.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import {\n   * CommonEventHandlers,\n   * DialogProps,\n   * InputEventHandlers,\n   * ModalProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [value] Value entered on the textbox.\n   * @property {object} [textboxAttrs] Extra attributes for the `<TextInput>`. The text box is\n   * labelled by the dialog `title` unless an `aria-label` or `aria-labelledby` is given here.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {Snippet} [input] Input slot content.\n   */\n\n  /**\n   * @type {ModalProps & DialogProps & CommonEventHandlers & InputEventHandlers &\n   * Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    value = $bindable(''),\n    title,\n    textboxAttrs = {},\n    children,\n    input,\n    onkeydown,\n    onkeyup,\n    onkeypress,\n    oninput,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<!--\n  The built-in text box is the point of the dialog, so it takes the dialog title as its name unless\n  the consumer labels it; the dialog itself is still named by the title as usual.\n-->\n<Dialog {...restProps} {title} bind:open role=\"alertdialog\">\n  {@render children?.()}\n  <div class=\"input-outer\">\n    {#if input}\n      {@render input()}\n    {:else}\n      <TextInput\n        dir=\"auto\"\n        bind:value\n        flex\n        autofocus\n        aria-label={'aria-labelledby' in textboxAttrs ? undefined : title}\n        {...textboxAttrs}\n        {onkeydown}\n        {onkeyup}\n        {onkeypress}\n        {oninput}\n      />\n    {/if}\n  </div>\n</Dialog>\n\n<style>.input-outer {\n  margin: 12px 0 0;\n}</style>\n","<!--\n  @component\n  A content divider with a visible vertical/horizontal line.\n  @see https://w3c.github.io/aria/#separator\n-->\n<script>\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [hidden] Whether to hide the widget. An alias of the `aria-hidden`\n   * attribute.\n   * @property {'horizontal'|'vertical'} [orientation] Orientation of the widget. An alias of the\n   * `aria-orientation` attribute.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    orientation = 'horizontal',\n    ariaLabel = undefined,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div\n  {...restProps}\n  role=\"separator\"\n  class=\"sui divider {className}\"\n  {hidden}\n  aria-hidden={hidden}\n  aria-orientation={orientation}\n  aria-label={ariaLabel}\n></div>\n\n<style>.divider {\n  flex: none;\n  background-color: var(--sui-secondary-border-color);\n}\n.divider[aria-orientation=horizontal] {\n  margin: 8px 0;\n  width: 100%;\n  height: 1px;\n}\n.divider[aria-orientation=vertical] {\n  margin: 0 8px;\n  width: 1px;\n  height: 100%;\n}</style>\n","/**\n * Geometry behind the swipe-to-dismiss gesture of `<Drawer>`, kept apart from the component so the\n * calculations can be tested without a rendered drawer.\n */\n\n/**\n * @typedef {object} SwipeSample\n * @property {number} offset Distance the drawer has been dragged towards its edge, in pixels.\n * @property {number} time Time of the sample in milliseconds, such as an event’s\n * `timeStamp`.\n */\n\n/**\n * @typedef {object} SwipeState\n * @property {number} pointerId ID of the pointer dragging the drawer.\n * @property {'X' | 'Y'} axis Axis along which the drawer is dragged.\n * @property {1 | -1} sign Sign of the direction towards the edge. See {@link getSwipeDirection}.\n * @property {number} start Position along the axis where the drag has started, in pixels.\n * @property {SwipeSample[]} samples Recent samples. See {@link addSwipeSample}.\n */\n\n/**\n * Portion of the drawer’s size it has to be dragged by to be dismissed on release.\n */\nexport const SWIPE_DISMISS_DISTANCE_RATIO = 0.3;\n\n/**\n * Speed in pixels per millisecond towards the edge at which a release dismisses the drawer, however\n * short the drag, so a quick flick is enough.\n */\nexport const SWIPE_DISMISS_VELOCITY = 0.5;\n\n/**\n * Distance in pixels a flick has to cover to dismiss the drawer, so a finger that rolls a little\n * while tapping the header doesn’t count as one.\n */\nexport const SWIPE_FLICK_MIN_DISTANCE = 16;\n\n/**\n * Time window in milliseconds over which the speed of a drag is measured when it’s released.\n */\nexport const SWIPE_VELOCITY_WINDOW = 100;\n\n/**\n * Get the axis along which the drawer is swiped away, and the sign of the physical direction\n * towards the edge it’s attached to.\n * @param {'top' | 'right' | 'bottom' | 'left'} position Position of the drawer.\n * @param {boolean} rtl Whether the layout is right-to-left, which mirrors the `left` and `right`\n * positions: they’re logical, like the `inset-inline` properties they’re laid out with.\n * @returns {{ axis: 'X' | 'Y', sign: 1 | -1 }} Axis, named as in `translateX()` and\n * `translateY()`, and sign.\n */\nexport const getSwipeDirection = (position, rtl) => {\n  if (position === 'top' || position === 'bottom') {\n    return { axis: 'Y', sign: position === 'bottom' ? 1 : -1 };\n  }\n\n  return { axis: 'X', sign: (position === 'right') !== rtl ? 1 : -1 };\n};\n\n/**\n * Get the distance the drawer has been dragged towards its edge. A drag the other way is ignored:\n * the drawer can’t be pulled out further than it’s open.\n * @param {number} delta Physical distance the pointer has moved along the axis, in pixels.\n * @param {1 | -1} sign Sign of the direction towards the edge. See {@link getSwipeDirection}.\n * @returns {number} Offset in pixels, `0` or more.\n */\nexport const getSwipeOffset = (delta, sign) => Math.max(0, delta * sign);\n\n/**\n * Add a sample to the list the speed of a drag is measured with, dropping the ones that have left\n * the measuring window.\n * @param {SwipeSample[]} samples Previous samples, oldest first.\n * @param {SwipeSample} sample New sample.\n * @returns {SwipeSample[]} Samples within {@link SWIPE_VELOCITY_WINDOW}, oldest first.\n */\nexport const addSwipeSample = (samples, sample) => [\n  ...samples.filter(({ time }) => sample.time - time <= SWIPE_VELOCITY_WINDOW),\n  sample,\n];\n\n/**\n * Get the speed of a drag towards the edge.\n * @param {SwipeSample[]} samples Recent samples, oldest first. See {@link addSwipeSample}.\n * @returns {number} Speed in pixels per millisecond, negative if the drag was heading back.\n */\nexport const getSwipeVelocity = (samples) => {\n  const first = samples[0];\n  const last = samples[samples.length - 1];\n\n  if (!first || !last || last.time <= first.time) {\n    return 0;\n  }\n\n  return (last.offset - first.offset) / (last.time - first.time);\n};\n\n/**\n * Check whether a drag that has just been released should dismiss the drawer: it has been dragged\n * far enough, or flicked towards its edge.\n * @param {object} args Arguments.\n * @param {number} args.offset Distance the drawer has been dragged towards its edge, in pixels.\n * @param {number} args.size Size of the drawer along the axis, in pixels.\n * @param {number} args.velocity Speed of the drag towards the edge, in pixels per millisecond.\n * @returns {boolean} Result.\n */\nexport const shouldDismissSwipe = ({ offset, size, velocity }) =>\n  offset > 0 &&\n  (offset >= size * SWIPE_DISMISS_DISTANCE_RATIO ||\n    (offset >= SWIPE_FLICK_MIN_DISTANCE && velocity >= SWIPE_DISMISS_VELOCITY));\n","<!--\n  @component\n  A generic drawer widget based on the HTML `<dialog>` element.\n  @see https://w3c.github.io/aria/#dialog\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/\n-->\n<script>\n  import { untrack } from 'svelte';\n  import { getModalLabelAttrs } from '../../services/label.js';\n  import Spacer from '../divider/spacer.svelte';\n  import ModalCloseButton from '../dialog/modal-close-button.svelte';\n  import Modal from '../util/modal.svelte';\n  import {\n    addSwipeSample,\n    getSwipeDirection,\n    getSwipeOffset,\n    getSwipeVelocity,\n    shouldDismissSwipe,\n  } from './drawer.js';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ModalLabelProps, ModalProps } from '../../typedefs.js';\n   * @import { SwipeState } from './drawer.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the content element.\n   * @property {boolean} [open] Whether to open the drawer.\n   * @property {'top' | 'right' | 'bottom' | 'left'} [position] Position of the drawer.\n   * @property {'small' | 'medium' | 'large' | 'x-large' | 'full'} [size] Width or height of the\n   * drawer.\n   * @property {'inside' | 'outside' | false} [showClose] Whether to show the Close button.\n   * @property {boolean} [swipeDismiss] Whether the drawer can be dismissed by dragging it towards\n   * the edge it’s attached to, as a bottom sheet on a mobile device is. The drag starts from the\n   * header, or from a grab handle shown on a top or bottom drawer; the main content and the footer\n   * are left alone, so they can be scrolled and interacted with. The Close button and the Escape\n   * key still work, as the gesture isn’t available to everyone.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {Snippet} [header] Header slot content.\n   * @property {Snippet} [headerExtra] Header extra slot content.\n   * @property {Snippet} [footer] Footer slot content.\n   * @property {Snippet} [closeIcon] Close icon slot content.\n   * @property {Snippet} [extraContent] Extra content slot content.\n   */\n\n  /**\n   * @type {ModalProps & ModalLabelProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    class: className,\n    title = '',\n    ariaLabelledby = undefined,\n    position = 'right',\n    size = 'small',\n    showClose = 'outside',\n    swipeDismiss = false,\n    children,\n    header,\n    headerExtra,\n    footer,\n    closeIcon,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Elements a drag can’t start from: the parts of the drawer that can scroll or hold text to\n   * select, and anything interactive.\n   */\n  const EXCLUDED_SWIPE_TARGETS = [\n    '.main',\n    '.footer',\n    '.extra-control',\n    'a',\n    'button',\n    'input',\n    'select',\n    'textarea',\n    '[contenteditable]',\n    '[tabindex]',\n  ].join(', ');\n\n  /**\n   * The ID of the drawer.\n   * @type {string}\n   */\n  const id = $props.id();\n\n  /**\n   * A reference to the modal component.\n   * @type {Modal | undefined}\n   */\n  let modal = $state();\n\n  const orientation = $derived(\n    position === 'right' || position === 'left' ? 'vertical' : 'horizontal',\n  );\n\n  /**\n   * A reference to the content element.\n   * @type {HTMLElement | undefined}\n   */\n  let content = $state();\n  /**\n   * The drag in progress, if any. The object is replaced rather than updated, except for the\n   * samples, which only feed the speed calculation on release, so nothing needs to track them.\n   * @type {SwipeState | undefined}\n   */\n  let swipe = $state.raw();\n  /**\n   * Distance the drawer has been dragged towards its edge, in pixels.\n   * @type {number}\n   */\n  let swipeOffset = $state(0);\n\n  /**\n   * Handle the `pointerdown` event on the content, starting a drag from anywhere but the main\n   * content, the footer and the controls.\n   * @param {PointerEvent} event `pointerdown` event.\n   */\n  const onPointerDown = (event) => {\n    const { button, isPrimary, pointerId, target, clientX, clientY } = event;\n\n    if (!swipeDismiss || !content || swipe || button !== 0 || !isPrimary) {\n      return;\n    }\n\n    // The dialog around the content is focusable too, so only look inside the content\n    const excluded = /** @type {Element} */ (target).closest(EXCLUDED_SWIPE_TARGETS);\n\n    if (excluded && content.contains(excluded)) {\n      return;\n    }\n\n    const { axis, sign } = getSwipeDirection(position, content.matches(':dir(rtl)'));\n\n    swipe = { pointerId, axis, sign, start: axis === 'Y' ? clientY : clientX, samples: [] };\n    swipeOffset = 0;\n    content.setPointerCapture(pointerId);\n  };\n\n  /**\n   * Handle the `pointermove` event on the content while dragging.\n   * @param {PointerEvent} event `pointermove` event.\n   */\n  const onPointerMove = (event) => {\n    const { pointerId, clientX, clientY, timeStamp } = event;\n\n    if (!swipe || pointerId !== swipe.pointerId) {\n      return;\n    }\n\n    swipeOffset = getSwipeOffset(\n      (swipe.axis === 'Y' ? clientY : clientX) - swipe.start,\n      swipe.sign,\n    );\n    swipe.samples = addSwipeSample(swipe.samples, { offset: swipeOffset, time: timeStamp });\n  };\n\n  /**\n   * Handle the `pointerup` and `pointercancel` events on the content, ending the drag. The drawer\n   * is dismissed if it has been dragged far enough or flicked, or goes back into place otherwise.\n   * Either way, the transition picks up from where the drag has left the drawer.\n   * @param {PointerEvent} event `pointerup` or `pointercancel` event.\n   */\n  const onPointerUp = (event) => {\n    if (!swipe || !content || event.pointerId !== swipe.pointerId) {\n      return;\n    }\n\n    const { width, height } = content.getBoundingClientRect();\n    // The pointer may have been held still since it last moved, which ends any flick\n    const samples = addSwipeSample(swipe.samples, { offset: swipeOffset, time: event.timeStamp });\n\n    const dismiss =\n      event.type === 'pointerup' &&\n      shouldDismissSwipe({\n        offset: swipeOffset,\n        size: swipe.axis === 'Y' ? height : width,\n        velocity: getSwipeVelocity(samples),\n      });\n\n    swipe = undefined;\n    swipeOffset = 0;\n\n    if (dismiss) {\n      modal?.close('close');\n    }\n  };\n\n  $effect(() => {\n    if (!open) {\n      // The drawer can be closed in the middle of a drag, e.g. with the Escape key, and should\n      // then slide away rather than stay where the drag has left it\n      untrack(() => {\n        swipe = undefined;\n        swipeOffset = 0;\n      });\n    }\n  });\n\n  /**\n   * Labelling attributes for the `<dialog>`, giving it an accessible name.\n   */\n  const labelAttrs = $derived(\n    getModalLabelAttrs({ id, title, ariaLabelledby, hasCustomHeader: !!header }),\n  );\n</script>\n\n{#snippet closeButton()}\n  <ModalCloseButton\n    class=\"close\"\n    controls={id}\n    {closeIcon}\n    onClose={() => {\n      modal?.close('close');\n    }}\n  />\n{/snippet}\n\n<Modal bind:this={modal} {...restProps} bind:open {id} class=\"drawer\" {...labelAttrs} showBackdrop>\n  <div\n    bind:this={content}\n    role=\"none\"\n    class={[\n      'content',\n      className,\n      size,\n      position,\n      orientation,\n      { 'swipe-dismiss': swipeDismiss, swiping: !!swipe },\n    ]}\n    style:transform={swipe ? `translate${swipe.axis}(${swipe.sign * swipeOffset}px)` : undefined}\n    style:transition-duration={swipe ? '0s' : undefined}\n    onpointerdown={onPointerDown}\n    onpointermove={onPointerMove}\n    onpointerup={onPointerUp}\n    onpointercancel={onPointerUp}\n  >\n    {#if swipeDismiss && position === 'bottom'}\n      <div role=\"none\" class=\"handle\"></div>\n    {/if}\n    <div role=\"none\" class=\"extra-control\">\n      {#if showClose === 'outside'}\n        {@render closeButton()}\n      {/if}\n    </div>\n    {#if title || showClose === 'inside' || header || headerExtra}\n      {#if header}\n        {@render header()}\n      {:else}\n        <div role=\"none\" class=\"header\">\n          <div role=\"none\" id=\"{id}-title\" class=\"title\">\n            {title}\n          </div>\n          <Spacer flex={true} />\n          {@render headerExtra?.()}\n          {#if showClose === 'inside'}\n            {@render closeButton()}\n          {/if}\n        </div>\n      {/if}\n    {/if}\n    <div role=\"none\" class=\"main\">\n      {@render children?.()}\n    </div>\n    {#if footer}\n      <div role=\"none\" class=\"footer\">\n        {@render footer?.()}\n      </div>\n    {/if}\n    {#if swipeDismiss && position === 'top'}\n      <div role=\"none\" class=\"handle\"></div>\n    {/if}\n  </div>\n</Modal>\n\n<style>.content {\n  position: absolute;\n  display: flex;\n  flex-direction: column;\n  max-width: 100dvw;\n  max-height: 100dvh;\n  border-width: var(--sui-drawer-content-border-width, var(--sui-modal-border-width, 0));\n  border-style: solid;\n  border-color: var(--sui-drawer-content-border-color, var(--sui-primary-border-color));\n  background-color: var(--sui-secondary-background-color-translucent);\n  box-shadow: 0 8px 16px var(--sui-popup-shadow-color);\n  -webkit-backdrop-filter: blur(16px);\n  backdrop-filter: blur(16px);\n  transition-property: transform;\n}\n.content .extra-control {\n  position: absolute;\n}\n.content .extra-control :global(button.close) {\n  margin: 8px;\n}\n:global(dialog.open) .content {\n  transition-duration: 150ms;\n  transform: translateX(0%);\n}\n:global(dialog:not(.open)) .content {\n  transition-duration: 300ms;\n}\n.content.right {\n  inset-block: var(--sui-drawer-right-content-inset-block, 0);\n  inset-inline: var(--sui-drawer-right-content-inset-inline, auto 0);\n  border-start-start-radius: var(--sui-drawer-right-content-border-start-start-radius, var(--sui-drawer-content-border-start-start-radius, 4px));\n  border-start-end-radius: var(--sui-drawer-right-content-border-start-end-radius, var(--sui-drawer-content-border-start-end-radius, 0));\n  border-end-end-radius: var(--sui-drawer-right-content-border-end-end-radius, var(--sui-drawer-content-border-end-end-radius, 0));\n  border-end-start-radius: var(--sui-drawer-right-content-border-end-start-radius, var(--sui-drawer-content-border-end-start-radius, 4px));\n}\n.content.right.full {\n  border-radius: var(--sui-drawer-right-full-content-border-radius, var(--sui-drawer-right-content-border-radius, 0));\n}\n.content.right .extra-control {\n  inset-block-start: 0;\n  inset-inline-end: 100%;\n}\n:global(dialog:not(.open)) .content.right:dir(ltr) {\n  transform: translateX(105%);\n}\n:global(dialog:not(.open)) .content.right:dir(rtl) {\n  transform: translateX(-105%);\n}\n.content.left {\n  inset-block: var(--sui-drawer-left-content-inset-block, 0);\n  inset-inline: var(--sui-drawer-left-content-inset-inline, 0 auto);\n  border-start-start-radius: var(--sui-drawer-left-content-border-start-start-radius, var(--sui-drawer-content-border-start-start-radius, 0));\n  border-start-end-radius: var(--sui-drawer-left-content-border-start-end-radius, var(--sui-drawer-content-border-start-end-radius, 4px));\n  border-end-end-radius: var(--sui-drawer-left-content-border-end-end-radius, var(--sui-drawer-content-border-end-end-radius, 4px));\n  border-end-start-radius: var(--sui-drawer-left-content-border-end-start-radius, var(--sui-drawer-content-border-end-start-radius, 0));\n}\n.content.left.full {\n  border-radius: var(--sui-drawer-left-full-content-border-radius, var(--sui-drawer-left-content-border-radius, 0));\n}\n.content.left .extra-control {\n  inset-block-start: 0;\n  inset-inline-start: 100%;\n}\n:global(dialog:not(.open)) .content.left:dir(ltr) {\n  transform: translateX(-105%);\n}\n:global(dialog:not(.open)) .content.left:dir(rtl) {\n  transform: translateX(105%);\n}\n:global(dialog.open) .content.vertical {\n  transform: translateX(0%);\n}\n.content.vertical.small {\n  width: var(--sui-drawer-vertical-small-width, var(--sui-drawer-vertical-width, 400px));\n  max-width: var(--sui-drawer-vertical-small-max-width, var(--sui-drawer-vertical-max-width, calc(100dvw - 56px)));\n  height: var(--sui-drawer-vertical-small-height, var(--sui-drawer-vertical-height, 100dvh));\n}\n.content.vertical.medium {\n  width: var(--sui-drawer-vertical-medium-width, var(--sui-drawer-vertical-width, 600px));\n  max-width: var(--sui-drawer-vertical-medium-max-width, var(--sui-drawer-vertical-max-width, calc(100dvw - 56px)));\n  height: var(--sui-drawer-vertical-medium-height, var(--sui-drawer-vertical-height, 100dvh));\n}\n.content.vertical.large {\n  width: var(--sui-drawer-vertical-large-width, var(--sui-drawer-vertical-width, 800px));\n  max-width: var(--sui-drawer-vertical-large-max-width, var(--sui-drawer-vertical-max-width, calc(100dvw - 56px)));\n  height: var(--sui-drawer-vertical-large-height, var(--sui-drawer-vertical-height, 100dvh));\n}\n.content.vertical.x-large {\n  width: var(--sui-drawer-vertical-x-large-width, var(--sui-drawer-vertical-width, 1000px));\n  max-width: var(--sui-drawer-vertical-x-large-max-width, var(--sui-drawer-vertical-max-width, calc(100dvw - 56px)));\n  height: var(--sui-drawer-vertical-x-large-height, var(--sui-drawer-vertical-height, 100dvh));\n}\n.content.vertical.full {\n  width: 100dvw;\n  max-width: 100dvw;\n  height: 100dvh;\n}\n.content.top {\n  inset-block-start: var(--sui-drawer-top-content-inset-block, 0);\n  inset-inline: var(--sui-drawer-top-content-inset-inline, 0 0);\n  border-start-start-radius: var(--sui-drawer-top-content-border-start-start-radius, var(--sui-drawer-content-border-start-start-radius, 0));\n  border-start-end-radius: var(--sui-drawer-top-content-border-start-end-radius, var(--sui-drawer-content-border-start-end-radius, 0));\n  border-end-end-radius: var(--sui-drawer-top-content-border-end-end-radius, var(--sui-drawer-content-border-end-end-radius, 4px));\n  border-end-start-radius: var(--sui-drawer-top-content-border-end-start-radius, var(--sui-drawer-content-border-end-start-radius, 4px));\n}\n.content.top.full {\n  border-radius: var(--sui-drawer-top-full-content-border-radius, var(--sui-drawer-top-content-border-radius, 0));\n}\n.content.top .extra-control {\n  inset-block-start: 100%;\n  inset-inline-end: 0;\n}\n:global(dialog:not(.open)) .content.top {\n  transform: translateY(-105%);\n}\n.content.bottom {\n  inset-block: var(--sui-drawer-bottom-content-inset-block, auto 0);\n  inset-inline: var(--sui-drawer-bottom-content-inset-inline, 0);\n  border-start-start-radius: var(--sui-drawer-bottom-content-border-start-start-radius, var(--sui-drawer-content-border-start-start-radius, 4px));\n  border-start-end-radius: var(--sui-drawer-bottom-content-border-start-end-radius, var(--sui-drawer-content-border-start-end-radius, 4px));\n  border-end-end-radius: var(--sui-drawer-bottom-content-border-end-end-radius, var(--sui-drawer-content-border-end-end-radius, 0));\n  border-end-start-radius: var(--sui-drawer-bottom-content-border-end-start-radius, var(--sui-drawer-content-border-end-start-radius, 0));\n}\n.content.bottom.full {\n  border-radius: var(--sui-drawer-bottom-full-content-border-radius, var(--sui-drawer-bottom-content-border-radius, 0));\n}\n.content.bottom .extra-control {\n  inset-block-end: 100%;\n  inset-inline-end: 0;\n}\n:global(dialog:not(.open)) .content.bottom {\n  transform: translateY(105%);\n}\n:global(dialog.open) .content.horizontal {\n  transform: translateY(0%);\n}\n.content.horizontal.small {\n  width: var(--sui-drawer-horizontal-small-width, var(--sui-drawer-horizontal-width, 100dvw));\n  height: var(--sui-drawer-horizontal-small-height, var(--sui-drawer-horizontal-height, 400px));\n  max-height: var(--sui-drawer-horizontal-small-max-height, var(--sui-drawer-horizontal-max-height, calc(100dvh - 56px)));\n}\n.content.horizontal.medium {\n  width: var(--sui-drawer-horizontal-medium-width, var(--sui-drawer-horizontal-width, 100dvw));\n  height: var(--sui-drawer-horizontal-medium-height, var(--sui-drawer-horizontal-height, 600px));\n  max-height: var(--sui-drawer-horizontal-medium-max-height, var(--sui-drawer-horizontal-max-height, calc(100dvh - 56px)));\n}\n.content.horizontal.large {\n  width: var(--sui-drawer-horizontal-large-width, var(--sui-drawer-horizontal-width, 100dvw));\n  height: var(--sui-drawer-horizontal-large-height, var(--sui-drawer-horizontal-height, 800px));\n  max-height: var(--sui-drawer-horizontal-large-max-height, var(--sui-drawer-horizontal-max-height, calc(100dvh - 56px)));\n}\n.content.horizontal.x-large {\n  width: var(--sui-drawer-horizontal-x-large-width, var(--sui-drawer-horizontal-width, 100dvw));\n  height: var(--sui-drawer-horizontal-x-large-height, var(--sui-drawer-horizontal-height, 1000px));\n  max-height: var(--sui-drawer-horizontal-x-large-max-height, var(--sui-drawer-horizontal-max-height, calc(100dvh - 56px)));\n}\n.content.horizontal.full {\n  width: 100dvw;\n  height: 100dvh;\n  max-height: 100dvh;\n}\n\n.content.swipe-dismiss > :global(:not(.main, .footer, .extra-control)) {\n  touch-action: none;\n  user-select: none;\n}\n.content.swipe-dismiss.swiping, .content.swipe-dismiss.swiping .handle {\n  cursor: grabbing;\n}\n\n.handle {\n  flex: none;\n  display: flex;\n  justify-content: center;\n  padding: 8px 0;\n  cursor: grab;\n}\n.handle::before {\n  content: \"\";\n  border-radius: 2px;\n  width: 32px;\n  height: 4px;\n  background-color: var(--sui-drawer-handle-color, var(--sui-secondary-foreground-color));\n  opacity: 0.5;\n}\n\n:is(.header, .footer) {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n.header {\n  flex-direction: var(--sui-drawer-header-flex-direction, row);\n  box-sizing: content-box;\n  margin: var(--sui-drawer-header-margin, 0 16px);\n  border-width: var(--sui-drawer-header-border-width, 0 0 1px);\n  border-color: var(--sui-drawer-header-border-color, var(--sui-secondary-border-color));\n  padding: var(--sui-drawer-header-padding, 16px 8px);\n  height: var(--sui-drawer-header-height, 32px);\n}\n.header .title {\n  font-size: var(--sui-font-size-large);\n  font-weight: var(--sui-font-weight-bold);\n}\n\n.footer {\n  margin: 0 24px 24px;\n}\n\n.main {\n  flex: auto;\n  overflow: auto;\n  padding: var(--sui-drawer-main-padding, 24px);\n  white-space: normal;\n}</style>\n","<script>\n  /**\n   * @typedef {object} Props\n   * @property {string} [accept] The `accept` attribute for the `<input type=\"file\">`.\n   * @property {boolean} [multiple] Whether to accept multiple files.\n   * @property {(detail: { files: File[], file: File }) => void} [onSelect] Custom `select` event\n   * handler. Since `multiple` could be false, we pass both `file` and `files` with the arguments.\n   * @property {() => void} [onCancel] `cancel` event handler.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    accept = undefined,\n    multiple = false,\n    onSelect = undefined,\n    onCancel = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {HTMLInputElement | undefined} */\n  let filePicker = $state();\n\n  /**\n   * Show the browser’s file picker dialog.\n   */\n  export const open = () => {\n    filePicker?.click();\n  };\n</script>\n\n<input\n  class=\"sui file-picker\"\n  type=\"file\"\n  hidden\n  {accept}\n  {multiple}\n  bind:this={filePicker}\n  onchange={({ target }) => {\n    const input = /** @type {HTMLInputElement} */ (target);\n    const files = [.../** @type {FileList} */ (input.files)];\n\n    // Clear the selection, so picking the same file again still fires the `change` event\n    input.value = '';\n    onSelect?.({ files, file: files[0] });\n  }}\n  oncancel={(event) => {\n    event.stopPropagation();\n    onCancel?.();\n  }}\n/>\n","<!--\n  @component\n  The interactive version of `<TableBody>`. A labelled row group can be made collapsible, in which\n  case the caption doubles as an expander button that shows or hides the rows.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody\n  @see https://w3c.github.io/aria/#rowgroup\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/\n-->\n<script>\n  import { _, isRTL } from '@sveltia/i18n';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { Attachment } from 'svelte/attachments';\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [label] Display label for the row group.\n   * @property {boolean} [collapsible] Whether the rows can be hidden with an expander in the\n   * caption. Requires `label`.\n   * @property {boolean} [expanded] Whether the rows are shown. Only applies when `collapsible`. An\n   * alias of the `aria-expanded` attribute on the expander button.\n   * @property {Snippet} [chevronIcon] Chevron slot content for the expander.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler, called with\n   * the new `expanded` state in `detail` when the expander is toggled.\n   */\n\n  /**\n   * @type {ContainerProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    expanded = $bindable(true),\n    class: className,\n    label = '',\n    collapsible = false,\n    children,\n    chevronIcon,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n  const hasExpander = $derived(collapsible && !!label);\n\n  /**\n   * Toggle the `expanded` state and notify the consumer.\n   */\n  const toggle = () => {\n    expanded = !expanded;\n    onChange?.(new CustomEvent('Change', { detail: { expanded } }));\n  };\n\n  /**\n   * Toggle the expander when the caption row itself is clicked. The `Grid` treats the caption as a\n   * row: the arrow keys land on it, and Enter clicks it, so this is how a keyboard user who has\n   * moved to the caption toggles the group. A click bubbling up from the button is left alone, as\n   * the button has toggled the group already.\n   * @type {Attachment}\n   */\n  const handleCaptionClick = (element) => {\n    /**\n     * Handle the `click` event on the caption row.\n     * @param {Event} event `click` event.\n     */\n    const listener = (event) => {\n      if (hasExpander && event.target === element) {\n        toggle();\n      }\n    };\n\n    element.addEventListener('click', listener);\n\n    return () => {\n      element.removeEventListener('click', listener);\n    };\n  };\n</script>\n\n<div\n  {...restProps}\n  role=\"rowgroup\"\n  class=\"sui grid-body row-group {className}\"\n  aria-labelledby={label ? `${id}-label` : undefined}\n  aria-roledescription={_('_sui.role_descriptions.grid_body')}\n>\n  {#if label}\n    <!--\n      The caption is a row the keyboard can land on, but not one that can be selected: clicking or\n      pressing Enter on it toggles the group instead\n    -->\n    <div role=\"row\" class=\"row-group-caption\" data-selectable=\"false\" {@attach handleCaptionClick}>\n      <!-- We need `colspan` here but cannot place `<th>` under `<div>`, so use a hack -->\n      <svelte:element this={'th'} role=\"columnheader\" id=\"{id}-label\" colspan=\"9999\">\n        {#if hasExpander}\n          <!--\n            The button is not a tab stop: the grid has a single one, and a keyboard user reaches\n            the caption row with the arrow keys and toggles it with Enter\n          -->\n          <Button class=\"expander\" {label} tabindex=\"-1\" aria-expanded={expanded} onclick={toggle}>\n            {#snippet startIcon()}\n              <span role=\"none\" class=\"chevron\">\n                {#if chevronIcon}\n                  {@render chevronIcon()}\n                {:else}\n                  <Icon name={isRTL() ? 'chevron_left' : 'chevron_right'} />\n                {/if}\n              </span>\n            {/snippet}\n          </Button>\n        {:else}\n          {label}\n        {/if}\n      </svelte:element>\n    </div>\n  {/if}\n  {#if !hasExpander || expanded}\n    {@render children?.()}\n  {/if}\n</div>\n\n<style>[role=rowgroup] {\n  display: table-row-group;\n}\n\n[role=row] {\n  display: table-row;\n}\n\n[role=columnheader] {\n  display: table-cell;\n  padding: 8px;\n  color: var(--sui-secondary-foreground-color);\n  background-color: var(--sui-secondary-background-color);\n  font-size: var(--sui-font-size-default);\n  text-align: start;\n}\n[role=columnheader]:has(> :global(.expander)) {\n  padding: 0;\n}\n[role=columnheader] :global(.expander) {\n  justify-content: flex-start;\n  margin: 0;\n  border-radius: 0;\n  padding: 4px 8px 4px 4px;\n  width: 100%;\n  height: auto;\n  color: inherit;\n  font-size: inherit;\n  text-align: start;\n}\n\n.chevron {\n  flex: none;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  transition: transform 200ms;\n}\n:global(.expander[aria-expanded='true']) > .chevron:dir(ltr) {\n  transform: rotate(90deg);\n}\n:global(.expander[aria-expanded='true']) > .chevron:dir(rtl) {\n  transform: rotate(-90deg);\n}</style>\n","<!--\n  @component\n  The row group, row or cell behind the leaf components of `<Table>` and `<Grid>`, which only differ\n  in their role, class name and `display`. Internal; not exported.\n-->\n<script>\n  /**\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {'head' | 'foot' | 'row' | 'col-header' | 'row-header' | 'cell'} PartName\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} role The `role` attribute on the wrapper element.\n   * @property {`table-${PartName}` | `grid-${PartName}`} kind The component class name, which also\n   * determines the `display` style.\n   */\n\n  /**\n   * @type {ContainerProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    role,\n    kind,\n    class: className,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div {...restProps} {role} class=\"sui {kind} {className}\">\n  {@render children?.()}\n</div>\n\n<style>.table-head,\n.grid-head {\n  display: table-header-group;\n}\n\n.table-foot,\n.grid-foot {\n  display: table-footer-group;\n}\n\n.table-row,\n.grid-row {\n  display: table-row;\n  height: var(--sui-primary-row-height);\n}\n\n.table-col-header,\n.grid-col-header,\n.table-cell,\n.grid-cell {\n  display: table-cell;\n}\n\n.table-row-header,\n.grid-row-header {\n  display: table-cell;\n  height: var(--sui-secondary-row-height);\n}</style>\n","<!--\n  @component\n  The interactive version of `<TableCell>`.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td\n  @see https://w3c.github.io/aria/#gridcell\n-->\n<script>\n  import TablePart from '../table/table-part.svelte';\n\n  /**\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ContainerProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<TablePart {...restProps} role=\"gridcell\" kind=\"grid-cell\" />\n","<!--\n  @component\n  The interactive version of `<TableColHeader>`. With `sortOrder` set, the header becomes sortable:\n  its content is wrapped in a button that indicates the current order and requests a new one.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th\n  @see https://w3c.github.io/aria/#columnheader\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/table/examples/sortable-table/\n-->\n<script>\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import TablePart from '../table/table-part.svelte';\n\n  /**\n   * @import { Attachment } from 'svelte/attachments';\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'ascending' | 'descending' | 'none'} [sortOrder] The order the column is sorted in,\n   * or `none` if it can be sorted but currently isn’t. An alias of the `aria-sort` attribute, which\n   * is only set on the sorted column, as the sortable table pattern recommends. When set, the\n   * content is rendered in a button that requests a new order with `onSort`; the button covers the\n   * whole cell, padding included. Leave it out for a header that can’t be sorted.\n   * @property {(event: CustomEvent<{ sortOrder: 'ascending' | 'descending' }>) => void} [onSort]\n   * Custom `Sort` event handler, called when the sort button is clicked. `detail.sortOrder` is the\n   * suggested next order: `descending` if the column is currently sorted in ascending order,\n   * otherwise `ascending`. The consumer sorts the rows and updates `sortOrder` accordingly.\n   */\n\n  /**\n   * @type {ContainerProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    sortOrder = undefined,\n    children,\n    onSort,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Keep the sort button’s clicks and activation keys from the `<Grid>`, which would otherwise\n   * select or focus the header row, or prevent the key’s default action, and call `onSort` instead.\n   * A click also focuses the button, as it does in browsers other than Safari.\n   * Native listeners are used because the grid listens on its own element, which a delegated Svelte\n   * event handler would only reach after the grid has handled the event. The arrow keys are left\n   * alone, so they still move from the header row to the data rows.\n   * @type {Attachment}\n   */\n  const handleSortButton = (element) => {\n    /**\n     * Handle the `click` event on the button.\n     * @param {Event} event `click` event.\n     */\n    const onClick = (event) => {\n      event.stopPropagation();\n      // Safari doesn’t focus a button on click, but moves the focus to the closest focusable\n      // ancestor instead, which is the header row\n      /** @type {HTMLElement} */ (element).focus();\n      onSort?.(\n        new CustomEvent('Sort', {\n          detail: { sortOrder: sortOrder === 'ascending' ? 'descending' : 'ascending' },\n        }),\n      );\n    };\n\n    /**\n     * Handle the `keydown` event on the button.\n     * @param {Event} event `keydown` event.\n     */\n    const onKeyDown = (event) => {\n      const { key } = /** @type {KeyboardEvent} */ (event);\n\n      if (key === 'Enter' || key === ' ') {\n        event.stopPropagation();\n      }\n    };\n\n    element.addEventListener('click', onClick);\n    element.addEventListener('keydown', onKeyDown);\n\n    return () => {\n      element.removeEventListener('click', onClick);\n      element.removeEventListener('keydown', onKeyDown);\n    };\n  };\n</script>\n\n{#if sortOrder === undefined}\n  <TablePart {...restProps} role=\"columnheader\" kind=\"grid-col-header\" class={className}>\n    {@render children?.()}\n  </TablePart>\n{:else}\n  <TablePart\n    {...restProps}\n    role=\"columnheader\"\n    kind=\"grid-col-header\"\n    class={className ? `sortable ${className}` : 'sortable'}\n    aria-sort={sortOrder === 'none' ? undefined : sortOrder}\n  >\n    <Button class=\"sort-button\" {@attach handleSortButton}>\n      {@render children?.()}\n      {#snippet endIcon()}\n        <Icon\n          class=\"sort-icon {sortOrder}\"\n          name={sortOrder === 'descending' ? 'arrow_downward' : 'arrow_upward'}\n        />\n      {/snippet}\n    </Button>\n  </TablePart>\n{/if}\n\n<style>:global(:where(.sui.grid-col-header.sortable)) {\n  position: relative;\n}\n:global(.sui.grid-col-header.sortable) > :global(.sui.button.sort-button) {\n  justify-content: flex-start;\n  margin: 0;\n  border-radius: 0;\n  padding: 0;\n  width: 100%;\n  height: auto;\n  color: inherit;\n  font: inherit;\n  text-align: start;\n}\n:global(.sui.grid-col-header.sortable) > :global(.sui.button.sort-button::after) {\n  position: absolute;\n  inset: 0;\n  content: \"\";\n}\n:global(.sui.grid-col-header.sortable) > :global(.sui.button.sort-button) :global(.sort-icon) {\n  flex: none;\n  font-size: 16px;\n  transition: opacity 200ms;\n}\n:global(.sui.grid-col-header.sortable) > :global(.sui.button.sort-button) :global(.sort-icon.none) {\n  opacity: 0;\n}\n:global(.sui.grid-col-header.sortable) > :global(.sui.button.sort-button:is(:hover, :focus-visible)) :global(.sort-icon.none) {\n  opacity: 0.4;\n}\n@media (hover: none) {\n  :global(.sui.grid-col-header.sortable) > :global(.sui.button.sort-button) :global(.sort-icon.none) {\n    opacity: 0.4;\n  }\n}</style>\n","<!--\n  @component\n  The interactive version of `<TableHead>`.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead\n  @see https://w3c.github.io/aria/#rowgroup\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { setContext } from 'svelte';\n  import TablePart from '../table/table-part.svelte';\n  import { UNSELECTABLE_ROWS_KEY } from './grid.js';\n\n  /**\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ContainerProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  // Tell the `<GridRow>`s inside that they are header rows, which can be focused but not selected\n  setContext(UNSELECTABLE_ROWS_KEY, true);\n</script>\n\n<TablePart\n  {...restProps}\n  role=\"rowgroup\"\n  kind=\"grid-head\"\n  aria-roledescription={_('_sui.role_descriptions.grid_head')}\n/>\n","<!--\n  @component\n  The interactive version of `<TableRow>`.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr\n  @see https://w3c.github.io/aria/#row\n-->\n<script>\n  import { getContext } from 'svelte';\n  import TablePart from '../table/table-part.svelte';\n  import { UNSELECTABLE_ROWS_KEY } from './grid.js';\n\n  /**\n   * @import { Attachment } from 'svelte/attachments';\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [selected] Whether to select the widget. An alias of the `aria-selected`\n   * attribute. Ignored on a header or footer row inside `<GridHead>` or `<GridFoot>`, which can\n   * never be selected.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   * @property {(event: CustomEvent) => void} [onSelect] Custom `Select` event handler.\n   */\n\n  /**\n   * @type {ContainerProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    selected = false,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Whether the row is a header or footer row inside `<GridHead>` or `<GridFoot>`. The grid’s arrow\n   * keys still land on it, but it can’t be selected, so it has no `aria-selected` state, even one\n   * passed as an attribute, and is marked for the group service to leave out of the selection.\n   */\n  const isUnselectableRow = getContext(UNSELECTABLE_ROWS_KEY) === true;\n\n  const attributes = $derived.by(() => {\n    if (!isUnselectableRow) {\n      return { ...restProps, 'aria-selected': selected };\n    }\n\n    const { 'aria-selected': _ariaSelected, ...rest } = restProps;\n\n    return { ...rest, 'data-selectable': 'false' };\n  });\n\n  /**\n   * Move the focus from a header row to the first sort button in it when the row is activated,\n   * which the grid does by clicking the focused row on Enter. The arrow keys move from row to row,\n   * so this is how a keyboard user gets from the header row to the sort buttons, and on from there\n   * with Tab. A click on a cell is left alone, as the button covers its sortable cell.\n   * @type {Attachment}\n   */\n  const focusSortButton = (element) => {\n    /**\n     * Handle the `click` event on the row.\n     * @param {Event} event `click` event.\n     */\n    const listener = (event) => {\n      const button = /** @type {HTMLElement | null} */ (element.querySelector('.sort-button'));\n\n      if (event.target === element && button) {\n        // The grid would otherwise move the focus back to the row it has just clicked\n        event.stopPropagation();\n        button.focus();\n      }\n    };\n\n    element.addEventListener('click', listener);\n\n    return () => {\n      element.removeEventListener('click', listener);\n    };\n  };\n</script>\n\n{#if isUnselectableRow}\n  <TablePart {...attributes} role=\"row\" kind=\"grid-row\" tabindex=\"0\" {@attach focusSortButton} />\n{:else}\n  <TablePart {...attributes} role=\"row\" kind=\"grid-row\" tabindex=\"0\" />\n{/if}\n","<!--\n  @component\n  The interactive version of `<Table>`.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table\n  @see https://w3c.github.io/aria/#grid\n-->\n<script>\n  import { setContext } from 'svelte';\n  import { activateGroup } from '../../services/group.svelte.js';\n  import { UNSELECTABLE_ROWS_KEY } from './grid.js';\n\n  /**\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [multiple] Whether to allow selecting more than one `<GridRow>` and/or\n   * `<GridCell>`. An alias of the `aria-multiselectable` attribute.\n   * @property {boolean} [clickToSelect] Whether to select a row by clicking on it.\n   * @property {HTMLElement} [element] A reference to the wrapper element.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {ContainerProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    element = $bindable(),\n    class: className,\n    multiple = false,\n    clickToSelect = true,\n    ariaLabel = undefined,\n    children,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  // A grid nested in a header or footer cell of another grid has data rows of its own, so the\n  // outer grid’s `<GridHead>` or `<GridFoot>` doesn’t make them unselectable\n  setContext(UNSELECTABLE_ROWS_KEY, false);\n</script>\n\n<div\n  bind:this={element}\n  {...restProps}\n  role=\"grid\"\n  class=\"sui grid {className}\"\n  aria-multiselectable={multiple}\n  aria-label={ariaLabel}\n  onChange={(/** @type {CustomEvent} */ event) => {\n    onChange?.(event);\n  }}\n  {@attach activateGroup(() => ({ clickToSelect }))}\n>\n  {@render children?.()}\n</div>\n\n<style>.grid {\n  display: table;\n  margin: var(--sui-focus-ring-width);\n  width: calc(100% - var(--sui-focus-ring-width) * 2);\n}\n.grid.data {\n  border-collapse: collapse;\n}\n.grid.data :global(:is(.grid-col-header, .grid-row-header, .grid-cell)) {\n  border: 1px solid var(--sui-secondary-border-color);\n  padding: 8px 8px;\n}</style>\n","<!--\n  @component\n  A list widget with selectable options. The equivalent of the HTML `<select multiple>` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select\n  @see https://w3c.github.io/aria/#listbox\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/listbox/\n-->\n<script>\n  import { activateGroup } from '../../services/group.svelte.js';\n\n  /**\n   * @import {\n   * ButtonProps,\n   * CommonEventHandlers,\n   * ContainerProps,\n   * FormFieldStateProps,\n   * WidgetStateProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [multiple] Whether to allow selecting more than one `<Option>`. An alias of\n   * the `aria-multiselectable` attribute.\n   * @property {string} [searchTerms] Search terms to be used to filter the items.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   * @property {(event: CustomEvent) => void} [onFilter] Custom `Filter` event handler.\n   */\n\n  /**\n   * @type {CommonEventHandlers & ContainerProps & WidgetStateProps & FormFieldStateProps & Props &\n   * Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    multiple = false,\n    searchTerms = '',\n    ariaLabel = undefined,\n    children,\n    onChange,\n    onFilter,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * @type {boolean}\n   */\n  let filtered = $state(false);\n\n  /**\n   * Handle the `Change` event from the group. The group only selects among the options that are\n   * shown, so an option hidden by the search terms keeps its selection. In a single-select listbox,\n   * that has to be cleared once another option is selected, or two would be selected once the\n   * filter is lifted.\n   * @param {CustomEvent} event The `Change` event.\n   */\n  const _onChange = (event) => {\n    const { currentTarget, target } = event;\n\n    // Only the listbox’s own event, not one dispatched on an option and bubbling up\n    if (!multiple && target === currentTarget) {\n      /** @type {HTMLElement} */ (currentTarget)\n        .querySelectorAll('[role=\"option\"][aria-hidden=\"true\"][aria-selected=\"true\"]')\n        .forEach((option) => {\n          option.setAttribute('aria-selected', 'false');\n          option.dispatchEvent(new CustomEvent('Change', { detail: { selected: false } }));\n        });\n    }\n\n    onChange?.(event);\n  };\n</script>\n\n<div\n  {...restProps}\n  role=\"listbox\"\n  class=\"sui listbox {className}\"\n  class:filtered\n  tabindex={disabled ? -1 : 0}\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-readonly={readonly}\n  aria-required={required}\n  aria-invalid={invalid}\n  aria-multiselectable={multiple}\n  aria-label={ariaLabel}\n  onChange={_onChange}\n  onFilter={(/** @type {CustomEvent} */ event) => {\n    const {\n      detail: { matched, total },\n    } = event;\n\n    filtered = matched !== total;\n    onFilter?.(event);\n  }}\n  {@attach activateGroup(() => ({ searchTerms }))}\n>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    {@render children?.()}\n  </div>\n</div>\n\n<style>[role=listbox] {\n  display: flex;\n  flex-direction: column;\n  margin: var(--sui-focus-ring-width);\n  border-width: var(--sui-listbox-border-width, 1px);\n  border-style: var(--sui-listbox-border-style, solid);\n  border-color: var(--sui-listbox-border-color, var(--sui-secondary-border-color));\n  border-radius: var(--sui-listbox-border-radius, 4px);\n  padding: var(--sui-listbox-padding, 4px);\n  min-width: var(--sui-listbox-min-width, calc(var(--sui-option-height) * 5));\n  color: var(--sui-listbox-foreground-color);\n  background-color: var(--sui-listbox-background-color);\n  font-family: var(--sui-control-font-family);\n  font-size: var(--sui-control-font-size);\n  line-height: var(--sui-control-line-height);\n}\n[role=listbox] :global([role=separator]) {\n  margin: 4px 0;\n  background-color: var(--sui-control-border-color);\n}\n[role=listbox][aria-invalid=true] {\n  border-color: var(--sui-error-border-color);\n}\n[role=listbox].tabs {\n  padding: 0;\n  border-block-start-width: 0;\n  border-block-end-width: 0;\n  border-inline-end-width: 1px;\n  border-inline-start-width: 0;\n  border-color: var(--sui-control-border-color);\n}\n[role=listbox].tabs :global(.option) :global(button) {\n  justify-content: flex-start;\n  border-width: 0;\n  border-inline-end-width: 2px;\n  border-color: transparent;\n  padding: 0 12px;\n  border-start-end-radius: 0;\n  border-end-end-radius: 0;\n  height: var(--sui-tab-medium-height);\n}\n[role=listbox].tabs :global(.option) :global(button[aria-selected=true]) {\n  border-color: var(--sui-primary-accent-color-light);\n}\n[role=listbox].tabs :global(.option) :global(button) :global(.icon) {\n  display: none;\n}\n[role=listbox].tabs[aria-readonly=true] :global(.option button[aria-selected='true']) {\n  border-color: var(--sui-readonly-accent-color);\n}\n[role=listbox].in-combobox:focus-visible, [role=listbox]:focus-visible:has(:global(.focused)) {\n  outline-color: transparent;\n}\n[role=listbox].filtered :global([role=separator]) {\n  display: none;\n}\n\n.inner {\n  display: contents;\n}</style>\n","<!--\n  @component\n  A group within a `<Listbox>`. The equivalent of the HTML `<optgroup>` element. It can contain one\n  or more `<Option>`s.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup\n  @see https://w3c.github.io/aria/#listbox\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/listbox/examples/listbox-grouped/\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import TruncatedText from '../typography/truncated-text.svelte';\n\n  /**\n   * @import { ContainerProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [label] The group’s label to be displayed above the child `<Option>`s.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    label = '',\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n</script>\n\n<div\n  {...restProps}\n  role=\"group\"\n  {id}\n  class=\"sui option-group {className}\"\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-labelledby=\"{id}-label\"\n  aria-roledescription={_('_sui.role_descriptions.option_group')}\n>\n  <div role=\"none\" id=\"{id}-label\" class=\"label\">\n    <TruncatedText>\n      {label}\n    </TruncatedText>\n  </div>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    {@render children?.()}\n  </div>\n</div>\n\n<style>.option-group:not(:first-child) {\n  margin: 12px 0 0;\n}\n\n.label {\n  margin: 8px;\n  color: var(--sui-secondary-foreground-color);\n  font-size: var(--sui-font-size-small);\n}\n\n.inner {\n  display: contents;\n}</style>\n","<!--\n  @component\n  An option within the `<Listbox>` widget. The equivalent of the HTML `<option>` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option\n  @see https://w3c.github.io/aria/#option\n-->\n<script>\n  import { onDestroy } from 'svelte';\n  import { getOptionRegistry } from '../../services/select.svelte.js';\n  import { getValueType } from '../../services/value.js';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ButtonProps, CommonEventHandlers } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [selected] Whether to select the widget. An alias of the `aria-selected`\n   * attribute.\n   * @property {string} label Text label displayed on the item.\n   * @property {string} [searchValue] The value to be searched.\n   * @property {boolean} [wrap] Whether to wrap a long label.\n   * @property {Snippet} [checkIcon] Check icon slot content.\n   */\n\n  /**\n   * @type {ButtonProps & CommonEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    selected = $bindable(false),\n    hidden = $bindable(false),\n    class: className,\n    disabled = false,\n    label,\n    value: _value = undefined,\n    searchValue: _searchValue = undefined,\n    wrap = false,\n    children,\n    checkIcon,\n    startIcon: _startIcon,\n    onChange,\n    onToggle,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Fallback `id`, so the option can always be referenced by `aria-activedescendant`. `<Group>`\n   * assigns one to each member as it activates, but within a `<Combobox>` that happens while the\n   * dropdown is still collapsed and no option has rendered yet.\n   */\n  const fallbackId = $props.id();\n\n  // The label is the default, followed when it changes, like on a locale switch. A prop fallback\n  // would only take its first value\n  const value = $derived(_value === undefined ? label : _value);\n  const searchValue = $derived(_searchValue === undefined ? label : _searchValue);\n\n  /**\n   * The registry provided by an ancestor `<Combobox>`. This is `undefined` when the option is used\n   * standalone within a `<Listbox>`, in which case it always renders itself.\n   */\n  const registry = getOptionRegistry();\n\n  if (registry) {\n    // Expose the props as accessors, so the combobox always reads the current values\n    const unregister = registry.register({\n      /**\n       * Get the option’s value.\n       * @returns {any} Value.\n       */\n      get value() {\n        return value;\n      },\n      /**\n       * Get the option’s text label.\n       * @returns {string} Label.\n       */\n      get label() {\n        return label;\n      },\n      /**\n       * Get the option’s name.\n       * @returns {string | undefined} Name.\n       */\n      get name() {\n        return restProps.name;\n      },\n      /**\n       * Get the data type of the option’s value.\n       * @returns {string} Type.\n       */\n      get type() {\n        return restProps.valueType ?? getValueType(value);\n      },\n      /**\n       * Get whether the option is selected.\n       * @returns {boolean} Result.\n       */\n      get selected() {\n        return selected;\n      },\n      /**\n       * Select or deselect the option.\n       * @param {boolean} newValue `true` to select.\n       */\n      set selected(newValue) {\n        selected = newValue;\n      },\n      /**\n       * Get whether the option is disabled.\n       * @returns {boolean} Result.\n       */\n      get disabled() {\n        return disabled;\n      },\n    });\n\n    onDestroy(unregister);\n  }\n\n  /**\n   * Whether to render the option. Within a `<Combobox>`, the options are only rendered while the\n   * dropdown is expanded; the registration above is what keeps the collapsed combobox working.\n   * @type {boolean}\n   */\n  const rendered = $derived(!registry || registry.expanded);\n</script>\n\n{#if rendered}\n  <div role=\"none\" class=\"sui option {className}\" class:wrap {hidden}>\n    <Button\n      {...restProps}\n      role=\"option\"\n      id={restProps.id ?? fallbackId}\n      tabindex=\"-1\"\n      aria-selected={selected}\n      {label}\n      {value}\n      {hidden}\n      {disabled}\n      data-search-value={searchValue}\n      onChange={(event) => {\n        selected = event.detail.selected;\n        onChange?.(event);\n      }}\n      onToggle={(event) => {\n        // Being filtered out doesn’t change the selection, which comes back with the option. A\n        // single-select `<Listbox>` deselects it once another option is selected instead.\n        hidden = event.detail.hidden;\n        onToggle?.(event);\n      }}\n    >\n      {#if selected}\n        {#if checkIcon}\n          {@render checkIcon()}\n        {:else}\n          <Icon class=\"check\" name=\"check\" />\n        {/if}\n      {/if}\n      {#snippet startIcon()}\n        {@render _startIcon?.()}\n      {/snippet}\n      {@render children?.()}\n    </Button>\n  </div>\n{/if}\n\n<style>.option {\n  display: contents;\n}\n.option:focus-visible {\n  outline-width: 0 !important;\n}\n.option.wrap :global(button) {\n  white-space: normal;\n}\n.option :global(button) {\n  flex: none;\n  display: flex;\n  gap: 4px;\n  margin: 0 !important;\n  border-radius: var(--sui-option-border-radius);\n  padding: var(--sui-option-padding);\n  width: 100%;\n  height: auto;\n  min-height: var(--sui-option-height);\n}\n.option :global(button:active) {\n  background-color: var(--sui-active-background-color);\n}\n.option :global(button[aria-selected=true]) :global(.icon.check) {\n  color: var(--sui-primary-accent-color-text);\n}\n.option :global(button) :global(*) {\n  flex: none;\n}\n.option :global(button) :global(.label) {\n  flex: auto;\n}\n.option :global(:is(.focused, button:hover)) {\n  color: var(--sui-highlight-foreground-color);\n  background-color: var(--sui-hover-background-color);\n}\n.option :global(.icon.check) {\n  margin: -2px;\n}\n\n:global([role='listbox']:focus-visible) .option :global(.focused) {\n  outline-color: var(--sui-focus-ring-color);\n  outline-offset: calc(var(--sui-focus-ring-width) * -1);\n}\n\n:global([role='listbox'][aria-readonly='true']) .option :global(button) {\n  cursor: default;\n}\n:global([role='listbox'][aria-readonly='true']) .option :global(button:not(.focused):is(:hover, :active)) {\n  color: var(--sui-control-foreground-color);\n  background-color: transparent;\n}\n:global([role='listbox'][aria-readonly='true']) .option :global(button[aria-selected=true]) :global(.icon.check) {\n  color: var(--sui-readonly-accent-color);\n}</style>\n","<!--\n  @component\n  A menu widget.\n  @see https://w3c.github.io/aria/#menu\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/menubar/\n-->\n<script>\n  import { activateGroup } from '../../services/group.svelte.js';\n\n  /**\n   * @import { ContainerProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    ariaLabel = undefined,\n    children,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div\n  {...restProps}\n  role=\"menu\"\n  class=\"sui menu {className}\"\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-label={ariaLabel}\n  onChange={(/** @type {CustomEvent} */ event) => {\n    onChange?.(event);\n  }}\n  {@attach activateGroup()}\n>\n  {@render children?.()}\n</div>\n\n<style>.menu {\n  display: flex;\n  flex-direction: column;\n  margin: 0;\n  border-width: var(--sui-menu-border-width, 1px);\n  border-style: var(--sui-menu-border-style, solid);\n  border-color: var(--sui-menu-border-color, var(--sui-secondary-border-color));\n  border-radius: var(--sui-menu-border-radius, 4px);\n  padding: var(--sui-menu-padding, 4px);\n}\n.menu :global([role=separator]) {\n  margin: var(--sui-menu-divider-margin, 4px);\n  width: auto;\n  background-color: var(--sui-menu-divider-color, var(--sui-control-border-color));\n}</style>\n","<!--\n  @component\n  A menu item widget.\n  @see https://w3c.github.io/aria/#menuitem\n-->\n<script>\n  import { isRTL } from '@sveltia/i18n';\n  import { onMount } from 'svelte';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import Popup from '../util/popup.svelte';\n  import Menu from './menu.svelte';\n\n  /**\n   * @import {\n   * ButtonProps,\n   * CommonEventHandlers,\n   * MenuItemProps,\n   * PopupPosition,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {PopupPosition} [popupPosition] Where to show the dropdown menu.\n   */\n\n  /**\n   * @type {ButtonProps & MenuItemProps & CommonEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    role = 'menuitem',\n    hidden = false,\n    disabled = false,\n    label = '',\n    labelDir = undefined,\n    // The popup flips to the other side by itself when the submenu wouldn’t fit on this one\n    popupPosition = 'right-top',\n    children: _children,\n    startIcon: _startIcon,\n    endIcon: _endIcon,\n    chevronIcon,\n    items,\n    onmouseenter,\n    onmouseleave,\n    onclick,\n    onChange,\n    onSelect,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  let isPopupOpen = $state(false);\n  let isPopupHovered = $state(false);\n  /** @type {number | undefined} */\n  let hoverTimer;\n\n  /**\n   * Reference to the `<button>` element.\n   * @type {HTMLButtonElement | undefined}\n   */\n  let buttonElement = $state();\n\n  /**\n   * Reference to the `<dialog>` element the menu is in, if any.\n   * @type {HTMLDialogElement | undefined}\n   */\n  let dialogElement = $state();\n\n  const hasItems = $derived(role === 'menuitem' && !!items);\n\n  /**\n   * Open or close the submenu after a short delay, cancelling any pending change, so that quickly\n   * moving the pointer in and out doesn’t leave a stale timer to act on the state later.\n   * @param {() => void} callback Function to run after the delay.\n   */\n  const scheduleHoverChange = (callback) => {\n    window.clearTimeout(hoverTimer);\n    hoverTimer = window.setTimeout(callback, 200);\n  };\n\n  onMount(() => {\n    dialogElement = buttonElement?.closest('dialog') ?? undefined;\n\n    return () => {\n      window.clearTimeout(hoverTimer);\n    };\n  });\n</script>\n\n<div role=\"none\" class=\"sui menuitem {className}\" {hidden}>\n  <Button\n    bind:element={buttonElement}\n    {...restProps}\n    {role}\n    {hidden}\n    {disabled}\n    aria-haspopup={hasItems ? 'menu' : undefined}\n    aria-expanded={hasItems ? isPopupOpen : undefined}\n    onmouseenter={(event) => {\n      if (hasItems) {\n        scheduleHoverChange(() => {\n          isPopupOpen = true;\n        });\n      }\n\n      onmouseenter?.(event);\n    }}\n    onmouseleave={(event) => {\n      if (hasItems) {\n        scheduleHoverChange(() => {\n          if (!isPopupHovered) {\n            isPopupOpen = false;\n          }\n        });\n      }\n\n      onmouseleave?.(event);\n    }}\n    onclick={(event) => {\n      if (hasItems) {\n        event.preventDefault();\n        event.stopPropagation();\n        window.clearTimeout(hoverTimer);\n        // A pointer click opens rather than toggles, as the hover may have opened the submenu\n        // already; on a touch screen, the emulated `mouseenter` comes right before the `click`. A\n        // scripted click still toggles it, which is how the keyboard navigation closes it.\n        isPopupOpen = event.detail ? true : !isPopupOpen;\n      }\n\n      onclick?.(event);\n    }}\n    {onChange}\n    {onSelect}\n  >\n    {#snippet startIcon()}\n      {@render _startIcon?.()}\n    {/snippet}\n    <!-- eslint-disable-next-line svelte/no-useless-children-snippet -->\n    {#snippet children()}\n      <div role=\"none\" class=\"content\" class:label={!!label} dir={label ? labelDir : undefined}>\n        {#if label}\n          {label}\n        {:else}\n          {@render _children?.()}\n        {/if}\n      </div>\n      {#if hasItems}\n        <span role=\"none\" class=\"icon-outer\">\n          {#if chevronIcon}\n            {@render chevronIcon()}\n          {:else}\n            <Icon name={isRTL() ? 'chevron_left' : 'chevron_right'} />\n          {/if}\n        </span>\n      {/if}\n    {/snippet}\n    {#snippet endIcon()}\n      {@render _endIcon?.()}\n    {/snippet}\n  </Button>\n  <!--\n    A menu in a popup shares its `<dialog>` with the submenu, while a menu placed directly on the\n    page leaves the submenu to open its own\n  -->\n  {#if hasItems && buttonElement}\n    <Popup\n      anchor={buttonElement}\n      parentDialogElement={dialogElement}\n      position={popupPosition}\n      bind:open={isPopupOpen}\n      bind:hovered={isPopupHovered}\n    >\n      <Menu>\n        {@render items?.()}\n      </Menu>\n    </Popup>\n  {/if}\n</div>\n\n<style>.menuitem {\n  position: relative;\n}\n.menuitem :global(button) {\n  display: flex;\n  gap: var(--sui-menuitem-gap, 4px);\n  align-items: var(--sui-menuitem-align-items, center);\n  border-radius: var(--sui-menuitem-border-radius, var(--sui-option-border-radius, 4px));\n  margin: 0 !important;\n  padding: var(--sui-menuitem-padding, 0 16px);\n  width: 100%;\n  min-width: var(--sui-menuitem-min-width, 160px);\n  height: var(--sui-menuitem-height, var(--sui-option-height));\n  color: var(--sui-menuitem-foreground-color, var(--sui-control-foreground-color, inherit));\n  background-color: var(--sui-menuitem-background-color, transparent);\n  font-size: var(--sui-menuitem-font-size, var(--sui-option-font-size));\n  font-weight: var(--sui-menuitem-font-weight, var(--sui-option-font-weight, var(--sui-font-weight-normal, normal)));\n}\n.menuitem :global(button[aria-checked=true]) :global(.icon) {\n  color: var(--sui-primary-accent-color-text);\n}\n.menuitem :global(button:hover) {\n  color: var(--sui-highlight-foreground-color);\n  background-color: var(--sui-hover-background-color);\n}\n.menuitem :global(button:active) {\n  background-color: var(--sui-active-background-color);\n}\n\n.content {\n  flex: auto;\n}\n\n.icon-outer {\n  flex: none;\n  width: 24px;\n  height: 24px;\n}</style>\n","<!--\n  @component\n  The checkable menu item behind `<MenuItemCheckbox>` and `<MenuItemRadio>`, which only differ in\n  their role. Internal; not exported.\n  @see https://w3c.github.io/aria/#menuitemcheckbox\n  @see https://w3c.github.io/aria/#menuitemradio\n-->\n<script>\n  import Icon from '../icon/icon.svelte';\n  import MenuItem from './menu-item.svelte';\n\n  /**\n   * @import { ButtonProps, CommonEventHandlers, MenuItemProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'menuitemcheckbox' | 'menuitemradio'} role The `role` attribute on the item.\n   */\n\n  /**\n   * @type {ButtonProps & MenuItemProps & CommonEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    role,\n    checked = $bindable(),\n    class: className,\n    hidden = false,\n    disabled = false,\n    label = '',\n    children: _children,\n    startIcon: _startIcon,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * The class name for the role, e.g. `menu-item-checkbox`.\n   */\n  const roleClass = $derived(role === 'menuitemradio' ? 'menu-item-radio' : 'menu-item-checkbox');\n</script>\n\n<MenuItem\n  {...restProps}\n  {role}\n  class=\"sui {roleClass} {className}\"\n  {label}\n  {hidden}\n  {disabled}\n  aria-checked={checked}\n  onChange={(event) => {\n    // Update the state first, so the handler sees the new value through a bound `checked`\n    checked = event.detail.checked;\n    onChange?.(event);\n  }}\n>\n  {#snippet startIcon()}\n    {@render _startIcon?.()}\n  {/snippet}\n  <!-- eslint-disable-next-line svelte/no-useless-children-snippet -->\n  {#snippet children()}\n    {@render _children?.()}\n  {/snippet}\n  {#snippet endIcon()}\n    {#if checked}\n      <Icon name=\"check\" />\n    {/if}\n  {/snippet}\n</MenuItem>\n","<!--\n  @component\n  A menu item widget with a checkbox.\n  @see https://w3c.github.io/aria/#menuitemcheckbox\n-->\n<script>\n  import MenuItemCheckable from './menu-item-checkable.svelte';\n\n  /**\n   * @import { ButtonProps, CommonEventHandlers, MenuItemProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ButtonProps & MenuItemProps & CommonEventHandlers & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    checked = $bindable(),\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<MenuItemCheckable {...restProps} bind:checked role=\"menuitemcheckbox\" />\n","<!--\n  @component\n  A menu item widget with a radio. Only one item can be selected within the parent `<Menu>` or\n  `<MenuItemGroup>` component.\n  @see https://w3c.github.io/aria/#menuitemradio\n-->\n<script>\n  import MenuItemCheckable from './menu-item-checkable.svelte';\n\n  /**\n   * @import { ButtonProps, CommonEventHandlers, MenuItemProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ButtonProps & MenuItemProps & CommonEventHandlers & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    checked = $bindable(),\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<MenuItemCheckable {...restProps} bind:checked role=\"menuitemradio\" />\n","<!--\n  @component\n  A progressbar widget.\n  @see https://w3c.github.io/aria/#progressbar\n-->\n<script>\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {number} now The `aria-valuenow` attribute on the wrapper element.\n   * @property {number} [min] The `aria-valuemin` attribute on the wrapper element.\n   * @property {number} [max] The `aria-valuemax` attribute on the wrapper element.\n   * @property {string} [text] The `aria-valuetext` attribute on the wrapper element.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    now = 0,\n    min = 0,\n    max = 100,\n    text,\n    ariaLabel = undefined,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** Position of `now` within the range, as a percentage, clamped to the range. */\n  const percentage = $derived(\n    max > min ? Math.min(Math.max(((now - min) / (max - min)) * 100, 0), 100) : 0,\n  );\n</script>\n\n<div\n  {...restProps}\n  role=\"progressbar\"\n  class=\"sui progressbar {className}\"\n  aria-valuenow={now}\n  aria-valuemin={min}\n  aria-valuemax={max}\n  aria-valuetext={text}\n  aria-label={ariaLabel}\n>\n  <div role=\"none\" style:width={`${percentage}%`}></div>\n</div>\n\n<style>.progressbar {\n  overflow: hidden;\n  border-width: var(--sui-progressbar-border-width, 1px);\n  border-style: var(--sui-progressbar-border-style, solid);\n  border-color: var(--sui-progressbar-border-color, var(--sui-control-border-color));\n  border-radius: var(--sui-progressbar-border-radius, 16px);\n  width: var(--sui-progressbar-width, 240px);\n  height: var(--sui-progressbar-height, 10px);\n  background-color: var(--sui-progressbar-background-color, var(--sui-secondary-background-color));\n}\n.progressbar div {\n  height: 100%;\n  background-color: var(--sui-progressbar-foreground-color, var(--sui-primary-accent-color-light));\n  transition: width 250ms;\n}</style>\n","<!--\n  @component\n  The container of `<Radio>`s.\n  @see https://w3c.github.io/aria/#radiogroup\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/radio/\n-->\n<script>\n  import { activateGroup } from '../../services/group.svelte.js';\n\n  /**\n   * @import { ContainerProps, FormFieldStateProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'horizontal'|'vertical'} [orientation] Orientation of the widget. An alias of the\n   * `aria-orientation` attribute.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & FormFieldStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    orientation = 'horizontal',\n    ariaLabel = undefined,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div\n  {...restProps}\n  role=\"radiogroup\"\n  class={['sui', 'radio-group', className, orientation]}\n  tabindex=\"-1\"\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-readonly={readonly}\n  aria-required={required}\n  aria-invalid={invalid}\n  aria-orientation={orientation}\n  aria-label={ariaLabel}\n  {@attach activateGroup()}\n>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    {@render children?.()}\n  </div>\n</div>\n\n<style>.radio-group {\n  display: inline-flex;\n}\n.radio-group:focus-visible {\n  outline-width: 0 !important;\n}\n.radio-group.horizontal {\n  gap: 8px;\n  align-items: center;\n  flex-wrap: wrap;\n}\n.radio-group.vertical {\n  gap: 4px;\n  flex-direction: column;\n}\n@media (pointer: coarse) {\n  .radio-group.vertical {\n    gap: 8px;\n  }\n}\n.radio-group[aria-invalid=true] :global(button) {\n  border-color: var(--sui-error-border-color);\n}\n.radio-group[aria-invalid=true] :global(button[aria-checked=true]) {\n  border-color: var(--sui-error-border-color);\n}\n.radio-group[aria-invalid=true] :global(button[aria-checked=true]::before) {\n  background-color: var(--sui-error-border-color);\n}\n\n.inner {\n  display: contents;\n}</style>\n","<!--\n  @component\n  The equivalent of the HTML `<input type=\"radio\">` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio\n  @see https://w3c.github.io/aria/#radio\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/radio/\n-->\n<script>\n  import { untrack } from 'svelte';\n  import { getAccessibleName, getToggleLabelAttrs } from '../../services/label.js';\n  import Button from '../button/button.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ContainerProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [checked] Whether to check the widget. An alias of the `aria-checked`\n   * attribute.\n   * @property {string} [name] The `data-name` attribute on the `<button>` element.\n   * @property {any} [value] The `data-value` attribute on the `<button>` element.\n   * @property {string} [valueType] Data type of the `value`. Typically `string`, `number`,\n   * `boolean` or `null`. Default: auto detect.\n   * @property {string} [label] Text label displayed next to the radio button.\n   * @property {string} [ariaLabel] `aria-label` attribute on the `<button>` element, for a radio\n   * button without a visible label.\n   * @property {any} [group] The two-way bound variable to manage the state of a group of radio\n   * buttons. It works in the same way as the [`<input\n   * bind:group>`](https://svelte.dev/docs/svelte/bind#input-bind:group) of Svelte: it can hold any\n   * type of value, including `undefined` before a choice is made.\n   * @property {Snippet} [default] Default slot content.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   * @property {(event: CustomEvent) => void} [onSelect] Custom `Select` event handler.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    checked = false,\n    class: className,\n    hidden = false,\n    disabled = false,\n    name = undefined,\n    value = undefined,\n    valueType = undefined,\n    label = undefined,\n    ariaLabel = undefined,\n    group = $bindable(),\n    children,\n    onChange,\n    onSelect,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n\n  /**\n   * Reference to the `<button>` element.\n   * @type {HTMLButtonElement | undefined}\n   */\n  let buttonElement = $state();\n\n  const labelAttrs = $derived(\n    getToggleLabelAttrs({\n      id,\n      ariaLabel: getAccessibleName({ ariaLabel, props: restProps }),\n      hasVisibleLabel: !!(children || label),\n    }),\n  );\n\n  /**\n   * Check if the radio button belongs to a read-only `<RadioGroup>`.\n   * @returns {boolean} Result.\n   */\n  const isGroupReadOnly = () =>\n    !!buttonElement?.closest('[role=\"radiogroup\"]')?.matches('[aria-readonly=\"true\"]');\n\n  // Sync `checked` with `group` and `value`. An unbound `group` and a bound one that’s still\n  // `undefined` read the same, so leave `checked` alone until there’s a choice. Only a change to\n  // `group` or `value` triggers the sync, not one to `checked`: without a bound `group`, the one\n  // set on a click stays local to this radio button, and must not check it again when the group\n  // unchecks it as the arrow keys move.\n  $effect(() => {\n    const isChecked = group !== undefined && group === value;\n\n    untrack(() => {\n      if (group !== undefined && checked !== isChecked) {\n        checked = isChecked;\n      }\n    });\n  });\n</script>\n\n<!--\n  `restProps`, including any `aria-*` attribute, go on the `<button>`: ARIA ignores them on the\n  presentational wrapper.\n-->\n<span\n  role=\"none\"\n  class=\"sui radio {className}\"\n  class:disabled\n  {hidden}\n  onclick={(event) => {\n    if (!(/** @type {HTMLElement} */ (event.target).matches('button'))) {\n      buttonElement?.click();\n    }\n  }}\n>\n  <Button\n    {...restProps}\n    bind:element={buttonElement}\n    role=\"radio\"\n    {id}\n    {hidden}\n    {disabled}\n    {name}\n    {value}\n    {valueType}\n    aria-checked={checked}\n    {...labelAttrs}\n    onclick={(event) => {\n      event.preventDefault();\n\n      // A read-only group turns the selection down too, but only once this handler has run, so it\n      // has to be checked here as well\n      if (disabled || checked || isGroupReadOnly()) {\n        return;\n      }\n\n      checked = true;\n      group = value;\n    }}\n    onChange={(/** @type {CustomEvent} */ event) => {\n      // The group checks and unchecks the radio buttons by itself, as the arrow keys move, so keep\n      // the state in step; otherwise a radio button unchecked that way would still think it’s\n      // checked and ignore the next click\n      checked = event.detail.checked;\n\n      if (checked) {\n        group = value;\n      }\n\n      onChange?.(event);\n    }}\n    {onSelect}\n  />\n  {#if children || label}\n    <label id=\"{id}-label\">\n      {#if children}\n        {@render children?.()}\n      {:else}\n        {label}\n      {/if}\n    </label>\n  {/if}\n</span>\n\n<style>.radio {\n  display: inline-flex;\n  align-items: center;\n  gap: 8px;\n  margin: var(--sui-focus-ring-width);\n  min-width: 24px;\n  min-height: 24px;\n  color: var(--sui-control-foreground-color);\n  font-family: var(--sui-control-font-family);\n  font-size: var(--sui-control-font-size);\n  line-height: var(--sui-control-line-height);\n  cursor: pointer;\n  -webkit-user-select: none;\n  user-select: none;\n}\n.radio:hover :global(button) {\n  background-color: var(--sui-hover-background-color);\n}\n.radio:hover :global(button[aria-checked=true]) {\n  border-color: var(--sui-primary-accent-color-light);\n  color: var(--sui-primary-accent-color-text);\n}\n.radio:hover :global(button[aria-checked=true]::before) {\n  background-color: var(--sui-primary-accent-color-light);\n}\n.radio:active :global(button) {\n  background-color: var(--sui-active-background-color);\n}\n.radio:active :global(button[aria-checked=true]) {\n  border-color: var(--sui-primary-accent-color-dark);\n  color: var(--sui-primary-accent-color-dark);\n}\n.radio :global(button) {\n  flex: none;\n  justify-content: center;\n  overflow: hidden;\n  margin: 0 !important;\n  border-width: 1.5px;\n  border-color: var(--sui-checkbox-border-color);\n  border-radius: var(--sui-checkbox-height);\n  padding: 0;\n  width: var(--sui-checkbox-height);\n  height: var(--sui-checkbox-height);\n  background-color: var(--sui-checkbox-background-color);\n  transition: all 200ms;\n}\n.radio :global(button::before) {\n  content: \"\";\n  border-radius: var(--sui-checkbox-height);\n  width: calc(var(--sui-checkbox-height) - 7px);\n  height: calc(var(--sui-checkbox-height) - 7px);\n  background-color: var(--sui-primary-accent-color);\n  opacity: 0;\n  transition: all 200ms;\n  will-change: opacity;\n}\n.radio :global(button[aria-checked=true]) {\n  border-color: var(--sui-primary-accent-color);\n}\n.radio :global(button[aria-checked=true]::before) {\n  opacity: 1;\n}\n.radio label {\n  cursor: inherit;\n}\n\n:global([role='radiogroup'][aria-readonly='true']) .radio {\n  cursor: default;\n}\n:global([role='radiogroup'][aria-readonly='true']) .radio :global(button), :global([role='radiogroup'][aria-readonly='true']) .radio:is(:hover, :active) :global(button) {\n  background-color: var(--sui-checkbox-background-color);\n}\n:global([role='radiogroup'][aria-readonly='true']) .radio :global(button[aria-checked='true']), :global([role='radiogroup'][aria-readonly='true']) .radio:is(:hover, :active) :global(button[aria-checked='true']) {\n  border-color: var(--sui-readonly-accent-color);\n}\n:global([role='radiogroup'][aria-readonly='true']) .radio :global(button[aria-checked='true']::before), :global([role='radiogroup'][aria-readonly='true']) .radio:is(:hover, :active) :global(button[aria-checked='true']::before) {\n  background-color: var(--sui-readonly-accent-color);\n}</style>\n","/**\n * Pointer drag lifecycle shared by the widgets that can be dragged, such as `<ResizableHandle>` and\n * `<Slider>`.\n */\n\n/**\n * @typedef {object} PointerDragHandlers\n * @property {(event: PointerEvent) => void} [onMove] Called with each `pointermove` event of the\n * dragging pointer while the drag goes on.\n * @property {(event: PointerEvent) => void} [onEnd] Called once when the drag ends, with the\n * `pointerup` or `pointercancel` event, or with the `pointermove` event of a mouse that no longer\n * has the primary button held down.\n */\n\n/**\n * Start dragging with the pointer that has just been pressed. The pointer is captured by the given\n * element, and its moves and release are followed on the `document` until the drag ends. Events of\n * other pointers are ignored.\n * @internal\n * @param {HTMLElement} element Element to capture the pointer.\n * @param {PointerEvent} event `pointerdown` event that starts the drag.\n * @param {PointerDragHandlers} handlers Event handlers.\n * @returns {() => void} Function to stop following the pointer without calling `onEnd`, for example\n * when the element is removed in the middle of a drag. It does nothing once the drag has ended.\n */\nexport const startPointerDrag = (element, { pointerId }, { onMove, onEnd }) => {\n  /**\n   * Stop following the pointer, and release it.\n   */\n  const stop = () => {\n    // eslint-disable-next-line no-use-before-define\n    document.removeEventListener('pointermove', onPointerMove);\n    // eslint-disable-next-line no-use-before-define\n    document.removeEventListener('pointerup', onPointerUp);\n    // eslint-disable-next-line no-use-before-define\n    document.removeEventListener('pointercancel', onPointerUp);\n\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  };\n\n  /**\n   * End the drag.\n   * @param {PointerEvent} event Event that ends the drag.\n   */\n  const end = (event) => {\n    stop();\n    onEnd?.(event);\n  };\n\n  /**\n   * Handle the `pointermove` event fired anywhere on the page.\n   * @param {PointerEvent} event `pointermove` event.\n   */\n  const onPointerMove = (event) => {\n    if (event.pointerId !== pointerId) {\n      return;\n    }\n\n    // The `pointerup` event may never come, for example when a context menu opened during the drag\n    // swallowed it, so a mouse moved without the primary button held down ends the drag instead of\n    // carrying on. The primary button is the lowest bit of `buttons`.\n    if (event.pointerType === 'mouse' && event.buttons % 2 === 0) {\n      end(event);\n\n      return;\n    }\n\n    onMove?.(event);\n  };\n\n  /**\n   * Handle the `pointerup` and `pointercancel` events fired anywhere on the page.\n   * @param {PointerEvent} event `pointerup` or `pointercancel` event.\n   */\n  const onPointerUp = (event) => {\n    if (event.pointerId === pointerId) {\n      end(event);\n    }\n  };\n\n  element.setPointerCapture(pointerId);\n  document.addEventListener('pointermove', onPointerMove);\n  document.addEventListener('pointerup', onPointerUp);\n  document.addEventListener('pointercancel', onPointerUp);\n\n  return stop;\n};\n","/**\n * Size arithmetic behind `<ResizablePaneGroup>` and `<ResizableHandle>`, kept apart from the\n * components so the conversions and clamping can be tested without laying anything out. Every\n * size here is a percentage of the pane group unless stated otherwise.\n */\n\nimport { getArrowKeys } from '../../services/navigation.js';\n\n/**\n * @import { ResizablePaneSize } from '../../typedefs.js';\n */\n\n/**\n * @typedef {object} SizeEnvironment\n * @property {number} containerSize Size of the pane group in pixels along its direction, or `0`\n * if it hasn’t been laid out yet.\n * @property {number} viewportWidth Width of the viewport in pixels.\n * @property {number} viewportHeight Height of the viewport in pixels.\n */\n\n/**\n * @typedef {object} PaneConstraints\n * @property {number} minSize Minimum size.\n * @property {number} maxSize Maximum size, never below `minSize`.\n */\n\n/**\n * Resolve a size given as a percentage number or a CSS length string to a percentage.\n * @param {ResizablePaneSize | undefined} value Size as a percentage number, or a CSS size string\n * such as `240px`, `20%` or `20dvw`.\n * @param {number} fallback Percentage to return when the value can’t be resolved.\n * @param {SizeEnvironment} env Sizes the lengths are relative to. A length other than a percentage\n * can’t be resolved while the container has no size.\n * @returns {number} Size in percentage points.\n */\nexport const resolveToPercent = (value, fallback, env) => {\n  if (typeof value === 'number') {\n    return value;\n  }\n\n  if (!value || typeof value !== 'string') {\n    return fallback;\n  }\n\n  const trimmed = value.trim();\n  const matchedPercent = trimmed.match(/^(-?\\d+(?:\\.\\d+)?)%$/);\n\n  if (matchedPercent) {\n    return Number(matchedPercent[1]);\n  }\n\n  const { containerSize } = env;\n\n  if (!containerSize) {\n    return fallback;\n  }\n\n  const matchedPx = trimmed.match(/^(-?\\d+(?:\\.\\d+)?)px$/i);\n\n  if (matchedPx) {\n    return (Number(matchedPx[1]) / containerSize) * 100;\n  }\n\n  const matchedViewport = trimmed.match(/^(-?\\d+(?:\\.\\d+)?)(dvw|vw|dvh|vh)$/i);\n\n  if (matchedViewport) {\n    const viewportValue = Number(matchedViewport[1]);\n    const unit = matchedViewport[2].toLowerCase();\n    const viewportSize = unit.endsWith('w') ? env.viewportWidth : env.viewportHeight;\n    const pixels = (viewportValue / 100) * viewportSize;\n\n    return (pixels / containerSize) * 100;\n  }\n\n  return fallback;\n};\n\n/**\n * Resolve a pane’s default size to a percentage.\n * @param {{ defaultSize?: ResizablePaneSize }} paneDef Pane definition.\n * @param {SizeEnvironment} env Sizes the lengths are relative to.\n * @returns {number} Size in percentage points, or `NaN` if the pane has no default size, or it\n * can’t be resolved.\n */\nexport const resolveDefaultSize = ({ defaultSize }, env) =>\n  defaultSize === undefined ? NaN : resolveToPercent(defaultSize, NaN, env);\n\n/**\n * Resolve a pane’s size constraints to percentages, clamped to the `0`–`100` range, with the\n * maximum never below the minimum.\n * @param {{ minSize: ResizablePaneSize, maxSize: ResizablePaneSize } | undefined} paneDef Pane\n * definition, or `undefined` for a pane that hasn’t registered, which is unconstrained.\n * @param {SizeEnvironment} env Sizes the lengths are relative to.\n * @returns {PaneConstraints} Constraints.\n */\nexport const resolvePaneConstraints = (paneDef, env) => {\n  if (!paneDef) {\n    return { minSize: 0, maxSize: 100 };\n  }\n\n  const minSize = Math.max(0, resolveToPercent(paneDef.minSize, 0, env));\n  const maxSize = Math.min(100, resolveToPercent(paneDef.maxSize, 100, env));\n\n  return {\n    minSize,\n    maxSize: Math.max(minSize, maxSize),\n  };\n};\n\n/**\n * Spread an amount over some of the panes, as far as their constraints allow. A positive amount\n * grows the panes and a negative one shrinks them.\n * @param {number[]} sizes Size of each pane, updated in place.\n * @param {PaneConstraints[]} constraints Constraints of each pane.\n * @param {number[]} indexes Indexes of the panes to spread the amount over.\n * @param {number} amount Amount to spread.\n * @returns {number} What is left of the amount once the panes are full or empty.\n */\nconst spreadSize = (sizes, constraints, indexes, amount) => {\n  let remaining = amount;\n  let adjustable = indexes;\n\n  // Each round either uses up the amount or fills at least one pane, so the loop is bounded\n  while (adjustable.length && Math.abs(remaining) > 1e-9) {\n    const share = remaining / adjustable.length;\n\n    const moved = adjustable.map((i) => {\n      const { minSize, maxSize } = constraints[i];\n      const size = Math.min(maxSize, Math.max(minSize, sizes[i] + share));\n      const diff = size - sizes[i];\n\n      sizes[i] = size;\n\n      return diff;\n    });\n\n    remaining -= moved.reduce((sum, diff) => sum + diff, 0);\n    adjustable = adjustable.filter((i) =>\n      share > 0 ? sizes[i] < constraints[i].maxSize : sizes[i] > constraints[i].minSize,\n    );\n  }\n\n  return remaining;\n};\n\n/**\n * Work out the initial size of each pane. Panes with a default size get it; the others share\n * whatever is left of the group equally. When constraints are given, each size is then brought\n * within its pane’s constraints, and whatever that frees up or takes away is made up by the other\n * panes, those without a default size first, so the total stays the same where possible.\n * @param {number[]} resolvedDefaults Each pane’s default size as a percentage, or `NaN` for a pane\n * that has none, or whose default couldn’t be resolved.\n * @param {PaneConstraints[]} [constraints] Constraints of each pane.\n * @returns {number[]} Size of each pane.\n */\nexport const getInitialSizes = (resolvedDefaults, constraints) => {\n  const specified = resolvedDefaults.filter((v) => !Number.isNaN(v));\n  const totalSpecified = specified.reduce((sum, v) => sum + v, 0);\n  const unspecifiedCount = resolvedDefaults.length - specified.length;\n  const remaining = Math.max(0, 100 - totalSpecified);\n  const defaultSize = unspecifiedCount > 0 ? remaining / unspecifiedCount : 0;\n  const sizes = resolvedDefaults.map((v) => (Number.isNaN(v) ? defaultSize : v));\n\n  if (!constraints) {\n    return sizes;\n  }\n\n  const total = sizes.reduce((sum, v) => sum + v, 0);\n  const allConstraints = sizes.map((_v, i) => constraints[i] ?? { minSize: 0, maxSize: 100 });\n\n  const fitted = sizes.map((v, i) =>\n    Math.min(allConstraints[i].maxSize, Math.max(allConstraints[i].minSize, v)),\n  );\n\n  const indexes = sizes.map((_v, i) => i);\n  const unspecified = indexes.filter((i) => Number.isNaN(resolvedDefaults[i]));\n  const excess = total - fitted.reduce((sum, v) => sum + v, 0);\n\n  spreadSize(\n    fitted,\n    allConstraints,\n    indexes,\n    spreadSize(fitted, allConstraints, unspecified, excess),\n  );\n\n  return fitted;\n};\n\n/**\n * Get the size wanted for a pane shown after the initial layout: its default size, or an equal\n * share of the group if it has none, within its constraints.\n * @param {object} args Arguments.\n * @param {number} args.defaultSize Default size of the pane, or `NaN` if it has none.\n * @param {PaneConstraints} args.constraints Constraints of the pane.\n * @param {number} args.paneCount Number of panes in the group, including the new one.\n * @returns {number} Size.\n */\nexport const getNewPaneSize = ({ defaultSize, constraints: { minSize, maxSize }, paneCount }) =>\n  Math.min(Math.max(Number.isNaN(defaultSize) ? 100 / paneCount : defaultSize, minSize), maxSize);\n\n/**\n * Sort items, such as panes or handles, in the order of their keys in the given list, which is\n * usually the order of the elements in the DOM. Items whose key isn’t in the list go last, in their\n * current order.\n * @template T, K\n * @param {T[]} items Items to sort. The array is left as is.\n * @param {K[]} order Keys in the order wanted.\n * @param {(item: T) => K} getKey Function to get the key of an item.\n * @returns {T[]} Sorted copy of the items.\n */\nexport const sortByDomOrder = (items, order, getKey) => {\n  /**\n   * Get the position of the given item in the list, or the end if it isn’t in it.\n   * @param {T} item Item.\n   * @returns {number} Position.\n   */\n  const getPosition = (item) => {\n    const position = order.indexOf(getKey(item));\n\n    return position === -1 ? Infinity : position;\n  };\n\n  return items.toSorted((a, b) => getPosition(a) - getPosition(b));\n};\n\n/**\n * Clamp the delta a handle is moved by, so neither of the two panes around it leaves its size\n * constraints. A positive delta grows the pane before the handle at the expense of the one after\n * it, and a negative delta does the opposite.\n * @param {number} deltaPercent Requested delta.\n * @param {object} panes The panes around the handle.\n * @param {number} panes.sizeBefore Current size of the pane before the handle.\n * @param {number} panes.sizeAfter Current size of the pane after the handle.\n * @param {PaneConstraints} panes.constraintsBefore Constraints of the pane before the handle.\n * @param {PaneConstraints} panes.constraintsAfter Constraints of the pane after the handle.\n * @returns {number} Delta both panes can accommodate.\n */\nexport const clampResizeDelta = (\n  deltaPercent,\n  { sizeBefore, sizeAfter, constraintsBefore, constraintsAfter },\n) => {\n  // Never below zero, so a pane that is already out of its constraints can’t make the handle move\n  // the wrong way\n  const canGrow = Math.max(\n    0,\n    Math.min(constraintsBefore.maxSize - sizeBefore, sizeAfter - constraintsAfter.minSize),\n  );\n\n  const canShrink = Math.max(\n    0,\n    Math.min(sizeBefore - constraintsBefore.minSize, constraintsAfter.maxSize - sizeAfter),\n  );\n\n  return deltaPercent > 0 ? Math.min(deltaPercent, canGrow) : -Math.min(-deltaPercent, canShrink);\n};\n\n/**\n * Get the range a handle can move the pane before it in, as only the space between the panes on\n * either side of the handle can be moved, and only as far as both panes’ constraints allow.\n * @param {object} panes The panes around the handle.\n * @param {number} panes.sizeBefore Current size of the pane before the handle.\n * @param {number} panes.sizeAfter Current size of the pane after the handle.\n * @param {PaneConstraints} panes.constraintsBefore Constraints of the pane before the handle.\n * @param {PaneConstraints} panes.constraintsAfter Constraints of the pane after the handle.\n * @returns {{ min: number, max: number }} Minimum and maximum size of the pane before the handle.\n */\nexport const getHandleRange = ({ sizeBefore, sizeAfter, constraintsBefore, constraintsAfter }) => {\n  const pairSize = sizeBefore + sizeAfter;\n\n  return {\n    min: Math.max(constraintsBefore.minSize, pairSize - constraintsAfter.maxSize),\n    max: Math.min(constraintsBefore.maxSize, pairSize - constraintsAfter.minSize),\n  };\n};\n\n/**\n * Convert the distance a handle has been dragged to a delta for the pane before it.\n * @param {object} args Arguments.\n * @param {number} args.delta Distance in pixels along the group’s direction, from the top or the\n * physical left.\n * @param {number} args.containerSize Space the panes share in pixels. Must not be `0`.\n * @param {boolean} args.isHorizontal Whether the panes are laid out horizontally.\n * @param {boolean} args.rtl Whether the layout is right-to-left, in which case a horizontal drag\n * to the left grows the pane before the handle.\n * @returns {number} Delta in percentage points.\n */\nexport const pixelDeltaToPercent = ({ delta, containerSize, isHorizontal, rtl }) => {\n  const percentDelta = (delta / containerSize) * 100;\n\n  return isHorizontal && rtl ? -percentDelta : percentDelta;\n};\n\n/**\n * Give the given space to the given panes, the first one first, then to the others, as far as\n * their maximum sizes allow, or take it from them with a negative amount, as far as their minimum\n * sizes allow. The sizes are updated in place.\n * @param {number[]} sizes Pane sizes in percentages.\n * @param {object} args Arguments.\n * @param {number[]} args.neighbors Indexes of the panes to give the space to first.\n * @param {number} args.amount Space in percentage points.\n * @param {number} [args.exclude] Index of a pane to leave alone.\n * @param {(index: number) => PaneConstraints} args.getConstraints Function to get the constraints\n * of a pane.\n * @returns {number} Space that couldn’t be given or taken.\n */\nexport const shareSpaceAmongPanes = (sizes, { neighbors, amount, exclude, getConstraints }) => {\n  let rest = amount;\n\n  [...neighbors, ...sizes.map((_size, index) => index)].forEach((neighbor) => {\n    if (Math.abs(rest) < 0.001 || neighbor === exclude || sizes[neighbor] === undefined) {\n      return;\n    }\n\n    const { minSize, maxSize } = getConstraints(neighbor);\n    const size = Math.min(Math.max(sizes[neighbor] + rest, minSize), maxSize);\n\n    rest -= size - sizes[neighbor];\n    sizes[neighbor] = size;\n  });\n\n  return rest;\n};\n\n/**\n * Interpret a key pressed on a resize handle. Arrow keys move the handle by 1%, or 10% with Shift.\n * Enter collapses or restores the pane before the handle. Home and End move it to its minimum and\n * maximum; the delta for those is oversized, and gets clamped by {@link clampResizeDelta}.\n * @param {object} options Options.\n * @param {string} options.key The key pressed.\n * @param {boolean} options.shiftKey Whether Shift was held.\n * @param {boolean} options.isHorizontal Whether the panes are laid out horizontally, in which case\n * the handle moves left and right.\n * @param {boolean} options.rtl Whether the layout is right-to-left, which swaps the horizontal\n * arrow keys.\n * @returns {{ type: 'toggle' } | { type: 'resize', delta: number } | undefined} What to do, or\n * `undefined` if the key has no meaning here.\n */\nexport const getHandleKeyAction = ({ key, shiftKey, isHorizontal, rtl }) => {\n  if (key === 'Enter') {\n    return { type: 'toggle' };\n  }\n\n  if (key === 'Home') {\n    return { type: 'resize', delta: -100 };\n  }\n\n  if (key === 'End') {\n    return { type: 'resize', delta: 100 };\n  }\n\n  const step = shiftKey ? 10 : 1;\n  const { prevKey, nextKey } = getArrowKeys(isHorizontal ? 'horizontal' : 'vertical', rtl);\n\n  if (key === prevKey) {\n    return { type: 'resize', delta: -step };\n  }\n\n  if (key === nextKey) {\n    return { type: 'resize', delta: step };\n  }\n\n  return undefined;\n};\n","<!--\n  @component\n  A draggable handle for resizing adjacent panes within a `<ResizablePaneGroup>`.\n  @see https://w3c.github.io/aria/#separator\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/\n-->\n<script>\n  import { isRTL } from '@sveltia/i18n';\n  import { getContext, onDestroy } from 'svelte';\n  import { startPointerDrag } from '../../services/pointer-drag.js';\n  import { getHandleKeyAction, getHandleRange, pixelDeltaToPercent } from './sizing.js';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { PaneGroupContext } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [disabled] Whether to disable the handle.\n   * @property {boolean} [showHandleBar] Whether to show the handle bar.\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   * @property {Snippet} [children] Custom handle content. If omitted, a default visual indicator is\n   * rendered.\n   * @property {() => void} [onResizeStart] Called when a resize interaction begins (pointer down or\n   * first keyboard step).\n   * @property {() => void} [onResizeEnd] Called when a resize interaction ends (pointer up/cancel\n   * or handle blur).\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    disabled = false,\n    showHandleBar = false,\n    class: className,\n    ariaLabel = undefined,\n    children,\n    onResizeStart,\n    onResizeEnd,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {PaneGroupContext} */\n  const ctx = getContext('paneGroup');\n\n  if (!ctx) {\n    throw new Error('<ResizableHandle> must be used inside a <ResizablePaneGroup>');\n  }\n\n  /**\n   * A reference to the handle element.\n   * @type {HTMLElement | undefined}\n   */\n  let element = $state();\n\n  const handle = ctx.registerHandle(() => element);\n  // The handles are counted in the order they are in the group, which changes as panes are shown\n  // and hidden\n  const handleIndex = $derived(handle.index);\n\n  onDestroy(() => {\n    handle.unregister();\n  });\n  const isHorizontal = $derived(ctx.direction === 'horizontal');\n  const sizes = $derived(ctx.sizes);\n  // The value reported via aria-valuenow is the size of the pane immediately before this handle\n  const currentPaneSize = $derived(sizes[handleIndex] ?? 0);\n  // The handle only moves space between the panes either side of it, so its range is bound by\n  // what those two panes can take\n  const range = $derived(\n    getHandleRange({\n      sizeBefore: currentPaneSize,\n      sizeAfter: sizes[handleIndex + 1] ?? 0,\n      constraintsBefore: ctx.getPaneConstraints(handleIndex),\n      constraintsAfter: ctx.getPaneConstraints(handleIndex + 1),\n    }),\n  );\n\n  let dragging = $state(false);\n  /**\n   * Pointer position along the group’s direction when the drag began.\n   */\n  let startScreenPos = 0;\n  /**\n   * Size of the pane before the handle when the drag began. Each move sets the pane to this plus\n   * the distance from where the drag began, rather than adding the latest step to the current\n   * size, so the handle stays under the pointer after it has been held back at a limit.\n   */\n  let startPaneSize = 0;\n  /**\n   * Function to stop following the pointer in the middle of a drag.\n   * @type {(() => void) | undefined}\n   */\n  let stopDrag;\n  /**\n   * Whether the handle is being resized via keyboard (at least one step fired).\n   */\n  let keyResizing = $state(false);\n\n  /**\n   * The space the panes share in pixels, used for px→% conversion. Measured once when a drag\n   * begins rather than on every pointer move: measuring forces the browser to lay the page out,\n   * which is the last thing wanted in the middle of a drag, and the group cannot change size while\n   * the pointer holding it is down.\n   * @type {number}\n   */\n  let containerSize = 0;\n\n  /**\n   * Handle pointer move events while dragging.\n   * @param {PointerEvent} event `pointermove` event.\n   */\n  const onPointerMove = (event) => {\n    if (disabled) return;\n\n    event.preventDefault();\n    event.stopPropagation();\n\n    const { screenX, screenY } = event;\n    const screenPos = isHorizontal ? screenX : screenY;\n\n    // A group that has no size, because it isn’t laid out, can’t be resized\n    /* v8 ignore next */\n    if (!containerSize) return;\n\n    const percentDelta = pixelDeltaToPercent({\n      delta: screenPos - startScreenPos,\n      containerSize,\n      isHorizontal,\n      rtl: isRTL(),\n    });\n\n    ctx.resize(handleIndex, startPaneSize + percentDelta - (sizes[handleIndex] ?? 0));\n  };\n\n  /**\n   * Handle the end of a drag.\n   */\n  const onDragEnd = () => {\n    dragging = false;\n    stopDrag = undefined;\n\n    onResizeEnd?.();\n  };\n\n  /**\n   * Handle pointer down events on the handle.\n   * @param {PointerEvent} event `pointerdown` event.\n   */\n  const onPointerDown = (event) => {\n    // Only the primary button resizes; the others are left to open a context menu and the like\n    if (disabled || event.button !== 0) return;\n\n    event.preventDefault();\n    event.stopPropagation();\n\n    const { screenX, screenY } = event;\n\n    // A pointer pressed while another one is dragging takes over\n    stopDrag?.();\n    dragging = true;\n    startScreenPos = isHorizontal ? screenX : screenY;\n    startPaneSize = sizes[handleIndex] ?? 0;\n    containerSize = ctx.measurePaneSpace();\n    stopDrag = startPointerDrag(/** @type {HTMLElement} */ (element), event, {\n      onMove: onPointerMove,\n      onEnd: onDragEnd,\n    });\n\n    onResizeStart?.();\n  };\n\n  /**\n   * Handle keyboard events for accessibility. Arrow keys move the handle by 1%; Shift+Arrow moves\n   * by 10%. Enter collapses/restores the primary pane. Home/End jump to min/max.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  const onKeyDown = (event) => {\n    if (disabled) return;\n\n    const { key, shiftKey } = event;\n    const action = getHandleKeyAction({ key, shiftKey, isHorizontal, rtl: isRTL() });\n\n    if (!action) return;\n\n    event.preventDefault();\n    event.stopPropagation();\n\n    if (action.type === 'toggle') {\n      ctx.toggleCollapse(handleIndex);\n\n      return;\n    }\n\n    // Home and End send an oversized delta, which gets clamped to the min/max internally\n    if (key !== 'Home' && key !== 'End' && !keyResizing) {\n      keyResizing = true;\n      onResizeStart?.();\n    }\n\n    ctx.resize(handleIndex, action.delta);\n  };\n\n  /**\n   * Handle blur to signal keyboard resize end.\n   */\n  const onBlur = () => {\n    if (keyResizing) {\n      keyResizing = false;\n      onResizeEnd?.();\n    }\n  };\n\n  $effect(() => () => {\n    // Stop listening if the handle is removed in the middle of a drag\n    stopDrag?.();\n  });\n</script>\n\n<!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n<div\n  bind:this={element}\n  {...restProps}\n  role=\"separator\"\n  tabindex={disabled ? -1 : 0}\n  aria-orientation={isHorizontal ? 'vertical' : 'horizontal'}\n  aria-valuenow={Math.round(currentPaneSize)}\n  aria-valuemin={range.min}\n  aria-valuemax={range.max}\n  aria-controls={ctx.paneDefs[handleIndex]?.id}\n  aria-disabled={disabled || undefined}\n  aria-label={ariaLabel}\n  class=\"sui resizable-handle {className}\"\n  class:horizontal={isHorizontal}\n  class:vertical={!isHorizontal}\n  class:disabled\n  class:dragging\n  onpointerdown={onPointerDown}\n  onkeydown={onKeyDown}\n  onblur={onBlur}\n>\n  {#if children}\n    {@render children()}\n  {:else if showHandleBar}\n    <div role=\"none\" class=\"handle-bar\"></div>\n  {/if}\n</div>\n\n<style>.resizable-handle {\n  position: relative;\n  flex: 0 0 auto;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  touch-action: none;\n  outline-offset: 0;\n  background-color: transparent;\n  transition: background-color 200ms;\n}\n.resizable-handle:focus-visible, .resizable-handle:hover, .resizable-handle.dragging {\n  outline: none;\n  z-index: 1;\n  background-color: var(--sui-primary-accent-color-translucent-light);\n}\n.resizable-handle:focus-visible .handle-bar, .resizable-handle:hover .handle-bar, .resizable-handle.dragging .handle-bar {\n  background-color: var(--sui-primary-accent-color);\n}\n.resizable-handle.disabled {\n  pointer-events: none;\n  opacity: 0.4;\n}\n.resizable-handle::before {\n  content: \"\";\n  position: absolute;\n  inset: 0;\n  z-index: 1;\n}\n.resizable-handle.horizontal {\n  width: var(--sui-resizable-handle-size, 4px);\n  height: 100%;\n  cursor: col-resize;\n}\n.resizable-handle.horizontal::before {\n  inset-inline: calc((var(--sui-resizable-handle-size, 4px) - 24px) / 2);\n}\n.resizable-handle.horizontal .handle-bar {\n  width: 2px;\n  height: 40%;\n  min-height: 20px;\n}\n.resizable-handle.vertical {\n  width: 100%;\n  height: var(--sui-resizable-handle-size, 4px);\n  cursor: row-resize;\n}\n.resizable-handle.vertical::before {\n  inset-block: calc((var(--sui-resizable-handle-size, 4px) - 24px) / 2);\n}\n.resizable-handle.vertical .handle-bar {\n  height: 2px;\n  width: 40%;\n  min-width: 20px;\n}\n.resizable-handle .handle-bar {\n  border-radius: 1px;\n  background-color: hsl(var(--sui-border-color-1-hsl));\n  transition: background-color 200ms;\n}</style>\n","<!--\n  @component\n  Container for resizable panes. Panes must be separated by `<ResizableHandle>` components.\n  @see https://w3c.github.io/aria/#separator\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/\n-->\n<script>\n  import { setContext } from 'svelte';\n  import {\n    clampResizeDelta,\n    getInitialSizes,\n    getNewPaneSize,\n    resolveDefaultSize,\n    resolvePaneConstraints,\n    shareSpaceAmongPanes,\n    sortByDomOrder,\n  } from './sizing.js';\n\n  /**\n   * @import { ContainerProps, PaneGroupContext, ResizablePaneSize } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'horizontal' | 'vertical'} [direction] Layout direction of the panes.\n   * @property {(detail: { sizes: number[] }) => void} [onResize] `resize` event handler, called\n   * whenever the pane sizes change.\n   */\n\n  /**\n   * @typedef {{\n   * id: string,\n   * defaultSize: ResizablePaneSize | undefined,\n   * minSize: ResizablePaneSize,\n   * maxSize: ResizablePaneSize,\n   * }} PaneDef\n   */\n\n  /**\n   * @type {ContainerProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    direction = 'horizontal',\n    class: className,\n    children,\n    onResize,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * `ResizablePane` definitions in the order of the panes in the group. Child `<ResizablePane>`\n   * components register in the order they’re mounted, which is only the order in the group the\n   * first time; one shown later with `{#if}` comes last until {@link syncOrder} puts it in place.\n   * @type {PaneDef[]}\n   */\n  let _paneDefs = $state.raw([]);\n\n  /**\n   * Functions to get the `<ResizableHandle>` elements, in the order of the handles in the group.\n   * @type {(() => HTMLElement | undefined)[]}\n   */\n  let _handles = $state.raw([]);\n\n  /** @type {HTMLDivElement | undefined} */\n  let element = $state();\n\n  /**\n   * Current pane sizes as percentages.\n   * @type {number[]}\n   */\n  const sizes = $state([]);\n\n  /**\n   * Per-handle saved sizes before collapse, for Enter key restore, along with the size the collapse\n   * left the pane at. That isn’t always `minSize`, as the pane after the handle may reach its\n   * `maxSize` first.\n   * @type {({ size: number, collapsedSize: number } | undefined)[]}\n   */\n  const _savedSizes = $state([]);\n\n  /**\n   * Measure the space the panes share: the group’s size along its direction, less the handles\n   * between them. Every pane size is a percentage of this, so the panes and handles together fill\n   * the group exactly. Were the percentages of the whole group, the handles would push the last\n   * pane past the edge; the overflow is hidden, but the group could still be scrolled by that much\n   * whenever something inside is scrolled into view, and everything would shift out of place.\n   * @returns {number} Space in pixels, or `0` if the group isn’t laid out.\n   */\n  const measurePaneSpace = () => {\n    if (!element) {\n      return 0;\n    }\n\n    const isHorizontal = direction === 'horizontal';\n    const groupSize = isHorizontal ? element.clientWidth : element.clientHeight;\n\n    const handleSize = [...element.querySelectorAll(':scope > .resizable-handle')].reduce(\n      (total, handle) =>\n        total +\n        (isHorizontal\n          ? /** @type {HTMLElement} */ (handle).offsetWidth\n          : /** @type {HTMLElement} */ (handle).offsetHeight),\n      0,\n    );\n\n    return Math.max(groupSize - handleSize, 0);\n  };\n\n  /**\n   * Get the sizes the pane lengths are relative to.\n   * @returns {import('./sizing.js').SizeEnvironment} Environment.\n   */\n  const getSizeEnvironment = () => ({\n    containerSize: measurePaneSpace(),\n    viewportWidth: window.innerWidth,\n    viewportHeight: window.innerHeight,\n  });\n\n  /**\n   * Get pane constraints converted to percentages for the current container size.\n   * @param {number} paneIndex Pane index.\n   * @returns {{ minSize: number, maxSize: number }} Min/max in percentages.\n   */\n  const getPaneConstraints = (paneIndex) =>\n    resolvePaneConstraints(_paneDefs[paneIndex], getSizeEnvironment());\n\n  /**\n   * The sizes last reported with `onResize`, to report a change only once.\n   */\n  let reportedSizes = '';\n\n  /**\n   * Get the current sizes rounded to one decimal place, as they are reported.\n   * @returns {number[]} Rounded sizes.\n   */\n  const roundSizes = () => sizes.map((size) => Number(size.toFixed(1)));\n\n  /**\n   * Initialize pane sizes from `defaultSize` props. Called once all panes have registered. Panes\n   * without `defaultSize` share the remaining space equally, and every size is kept within its\n   * pane’s `minSize` and `maxSize`.\n   */\n  const initSizes = () => {\n    // Only called once panes have registered; see the effect below\n    /* v8 ignore next */\n    if (!_paneDefs.length) return;\n\n    const env = getSizeEnvironment();\n    // Resolve each pane’s defaultSize to a percentage (NaN if unspecified or unresolvable)\n    const resolvedDefaults = _paneDefs.map((p) => resolveDefaultSize(p, env));\n    const constraints = _paneDefs.map((p) => resolvePaneConstraints(p, env));\n\n    sizes.splice(0, sizes.length, ...getInitialSizes(resolvedDefaults, constraints));\n    // The initial sizes aren’t reported, only the changes from them\n    reportedSizes = roundSizes().join();\n  };\n\n  /**\n   * Call `onResize` with the current sizes, if they’ve changed since the last call.\n   */\n  const reportSizes = () => {\n    const rounded = roundSizes();\n    const key = rounded.join();\n\n    if (key !== reportedSizes) {\n      reportedSizes = key;\n      onResize?.({ sizes: rounded });\n    }\n  };\n\n  /**\n   * Resize panes around a handle by the given delta (percentage points).\n   * @param {number} handleIndex Index of the resize handle.\n   * @param {number} deltaPercent Size delta in percentage points.\n   */\n  const resize = (handleIndex, deltaPercent) => {\n    const beforeIdx = handleIndex;\n    const afterIdx = handleIndex + 1;\n\n    if (beforeIdx < 0 || afterIdx >= sizes.length) return;\n\n    const prevBefore = sizes[beforeIdx];\n    const prevAfter = sizes[afterIdx];\n\n    // Clamp delta so neither pane exceeds its min/max constraints\n    const delta = clampResizeDelta(deltaPercent, {\n      sizeBefore: prevBefore,\n      sizeAfter: prevAfter,\n      constraintsBefore: getPaneConstraints(beforeIdx),\n      constraintsAfter: getPaneConstraints(afterIdx),\n    });\n\n    sizes[beforeIdx] = prevBefore + delta;\n    sizes[afterIdx] = prevAfter - delta;\n\n    reportSizes();\n  };\n\n  /**\n   * Toggle collapse of the primary pane (before the given handle). If the pane hasn’t been\n   * collapsed, it’s shrunk to `minSize`, or as far as the pane after the handle allows; if it’s\n   * still at the size the collapse left it, the previous size is restored.\n   * @param {number} handleIndex Index of the resize handle.\n   */\n  const toggleCollapse = (handleIndex) => {\n    const { minSize: minBefore } = getPaneConstraints(handleIndex);\n    const saved = _savedSizes[handleIndex];\n\n    // The saved size is only restored while the pane is still collapsed; once it has been resized\n    // since, it’s collapsed again from where it is\n    if (saved && Math.abs(sizes[handleIndex] - saved.collapsedSize) < 0.1) {\n      _savedSizes[handleIndex] = undefined;\n      resize(handleIndex, saved.size - sizes[handleIndex]);\n    } else {\n      const size = sizes[handleIndex];\n\n      resize(handleIndex, -(size - minBefore));\n      _savedSizes[handleIndex] = { size, collapsedSize: sizes[handleIndex] };\n    }\n  };\n\n  /**\n   * Give the given space to the given panes, then to the others, or take it from them with a\n   * negative amount; see {@link shareSpaceAmongPanes}.\n   * @param {number[]} neighbors Indexes of the panes to give the space to first.\n   * @param {number} amount Space in percentage points.\n   * @param {number} [exclude] Index of a pane to leave alone.\n   * @returns {number} Space that couldn’t be given or taken.\n   */\n  const shareSpace = (neighbors, amount, exclude) =>\n    shareSpaceAmongPanes(sizes, { neighbors, amount, exclude, getConstraints: getPaneConstraints });\n\n  /**\n   * Put the panes and handles in the order they are in the group, and size a pane shown after the\n   * initial layout, taking its space from the panes next to it.\n   */\n  const syncOrder = () => {\n    // Only called once the group is mounted\n    /* v8 ignore next */\n    if (!element || !sizes.length) return;\n\n    const paneIds = [...element.querySelectorAll(':scope > .resizable-pane')].map(({ id }) => id);\n    const defs = sortByDomOrder(_paneDefs, paneIds, (def) => def.id);\n    const newSizes = defs.map((def) => sizes[_paneDefs.indexOf(def)]);\n    const isReordered = defs.some((def, index) => def !== _paneDefs[index]);\n\n    if (isReordered) {\n      _paneDefs = defs;\n      sizes.splice(0, sizes.length, ...newSizes);\n      _savedSizes.length = 0;\n    }\n\n    /**\n     * Sizes the lengths are relative to, measured once for all the new panes, and only if there\n     * are any, as measuring makes the browser lay out the page.\n     * @type {import('./sizing.js').SizeEnvironment | undefined}\n     */\n    let env;\n\n    sizes.forEach((size, index) => {\n      if (!Number.isNaN(size)) {\n        return;\n      }\n\n      env ??= getSizeEnvironment();\n\n      const def = _paneDefs[index];\n\n      const wanted = getNewPaneSize({\n        defaultSize: resolveDefaultSize(def, env),\n        constraints: resolvePaneConstraints(def, env),\n        paneCount: sizes.length,\n      });\n\n      sizes[index] = 0;\n      sizes[index] = wanted + shareSpace([index - 1, index + 1], -wanted, index);\n    });\n\n    const handleElements = [...element.querySelectorAll(':scope > .resizable-handle')];\n    const handles = sortByDomOrder(_handles, handleElements, (getElement) => getElement());\n\n    if (handles.some((handle, index) => handle !== _handles[index])) {\n      _handles = handles;\n      _savedSizes.length = 0;\n    }\n\n    // Reported here rather than as a pane leaves, which also happens when the whole group is\n    // removed: this observer callback doesn’t run then, as the observer is disconnected first\n    if (!sizes.some((size) => Number.isNaN(size))) {\n      reportSizes();\n    }\n  };\n\n  setContext(\n    'paneGroup',\n    /* eslint-disable jsdoc/require-jsdoc */\n    /** @type {PaneGroupContext} */ ({\n      get direction() {\n        return direction;\n      },\n      sizes,\n      registerPane: (def) => {\n        _paneDefs = [..._paneDefs, def];\n\n        // A pane shown after the initial layout is sized once it’s in place; see `syncOrder()`\n        if (sizes.length) {\n          sizes.push(NaN);\n        }\n\n        return {\n          get index() {\n            return _paneDefs.indexOf(def);\n          },\n          unregister: () => {\n            const index = _paneDefs.indexOf(def);\n\n            if (index === -1) {\n              return;\n            }\n\n            _paneDefs = _paneDefs.toSpliced(index, 1);\n\n            // Its space goes to the panes next to it\n            if (sizes.length) {\n              const [size] = sizes.splice(index, 1);\n\n              _savedSizes.length = 0;\n\n              if (sizes.length && !Number.isNaN(size)) {\n                shareSpace([index - 1, index], size);\n              }\n            }\n          },\n        };\n      },\n      registerHandle: (getElement) => {\n        _handles = [..._handles, getElement];\n\n        return {\n          get index() {\n            return _handles.indexOf(getElement);\n          },\n          unregister: () => {\n            _handles = _handles.filter((handle) => handle !== getElement);\n            _savedSizes.length = 0;\n          },\n        };\n      },\n      resize,\n      toggleCollapse,\n      getPaneConstraints,\n      measurePaneSpace,\n      get paneDefs() {\n        return _paneDefs;\n      },\n    }),\n    /* eslint-enable jsdoc/require-jsdoc */\n  );\n\n  $effect(() => {\n    if (_paneDefs.length && !sizes.length) {\n      initSizes();\n    }\n  });\n\n  // Panes and handles can be shown and hidden after the initial layout, with `{#if}` for example\n  $effect(() => {\n    if (!element) {\n      return undefined;\n    }\n\n    const observer = new MutationObserver(() => syncOrder());\n\n    observer.observe(element, { childList: true });\n\n    return () => {\n      observer.disconnect();\n    };\n  });\n</script>\n\n<div\n  bind:this={element}\n  {...restProps}\n  role=\"none\"\n  class={['sui', 'resizable-pane-group', direction, className]}\n  data-direction={direction}\n>\n  {@render children?.()}\n</div>\n\n<style>.resizable-pane-group {\n  display: flex;\n  overflow: hidden;\n}\n.resizable-pane-group.horizontal {\n  flex-direction: row;\n  width: 100%;\n  height: 100%;\n}\n.resizable-pane-group.vertical {\n  flex-direction: column;\n  width: 100%;\n  height: 100%;\n}</style>\n","<!--\n  @component\n  A resizable pane within a `<ResizablePaneGroup>`. Must be a direct child of\n  `<ResizablePaneGroup>`.\n-->\n<script>\n  import { getContext, onDestroy, untrack } from 'svelte';\n\n  /**\n   * @import { ContainerProps, PaneGroupContext, ResizablePaneSize } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ResizablePaneSize} [defaultSize] Default size. Numbers are percentages (0-100) of\n   * the space the panes share, which is the group less its handles; strings can be any CSS\n   * length/percentage such as `240px`, `20%` or `20dvw`. Panes without `defaultSize` share the\n   * remaining space equally.\n   * @property {ResizablePaneSize} [minSize] Minimum size. Numbers are percentages, strings are CSS\n   * lengths. Defaults to `0`.\n   * @property {ResizablePaneSize} [maxSize] Maximum size. Numbers are percentages, strings are CSS\n   * lengths. Defaults to `100`.\n   * @property {(detail: { size: number }) => void} [onResize] Called whenever this pane’s size (in\n   * percent) changes.\n   */\n\n  /**\n   * @type {ContainerProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    defaultSize = undefined,\n    minSize = 0,\n    maxSize = 100,\n    class: className,\n    children,\n    onResize,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n\n  /** @type {PaneGroupContext} */\n  const ctx = getContext('paneGroup');\n\n  if (!ctx) {\n    throw new Error('<ResizablePane> must be used inside a <ResizablePaneGroup>');\n  }\n\n  // The sizes are read when they’re needed, so a change to them is followed\n  /* eslint-disable jsdoc/require-jsdoc */\n  const pane = ctx.registerPane({\n    id,\n    get defaultSize() {\n      return defaultSize;\n    },\n    get minSize() {\n      return minSize;\n    },\n    get maxSize() {\n      return maxSize;\n    },\n  });\n  /* eslint-enable jsdoc/require-jsdoc */\n\n  const direction = $derived(ctx.direction);\n  const size = $derived(ctx.sizes[pane.index]);\n  /**\n   * The size as a flex basis. The percentages are of the space the panes share rather than of the\n   * group, while a flex basis is a percentage of the group, so the panes are made shrinkable: the\n   * handles then take their room from the panes in proportion to their sizes, which works out to\n   * exactly the intended percentages, and the group is never overflowed.\n   */\n  const sizeStyle = $derived.by(() => {\n    // A pane shown after the initial layout has no size until it’s in place\n    if (size !== undefined && !Number.isNaN(size)) {\n      return `${size}%`;\n    }\n\n    if (typeof defaultSize === 'number') {\n      return `${defaultSize}%`;\n    }\n\n    return defaultSize ?? '0%';\n  });\n\n  // Leave the group when removed, giving the space to the panes next to it\n  onDestroy(() => {\n    pane.unregister();\n  });\n\n  $effect(() => {\n    if (size !== undefined && !Number.isNaN(size)) {\n      untrack(() => onResize?.({ size: Number(size.toFixed(1)) }));\n    }\n  });\n</script>\n\n<div\n  {...restProps}\n  {id}\n  role=\"none\"\n  class=\"sui resizable-pane {className}\"\n  style:flex-basis={sizeStyle}\n  style:flex-grow=\"0\"\n  style:flex-shrink=\"1\"\n  style:overflow-x={direction === 'horizontal' ? 'auto' : undefined}\n  style:overflow-y={direction === 'vertical' ? 'auto' : undefined}\n>\n  {@render children?.()}\n</div>\n","<!--\n  @component Enable infinite scroll for list items for better rendering performance.\n  @see https://svelte.dev/docs/svelte/v5-migration-guide#Snippets-instead-of-slots-Passing-data-back-up\n-->\n<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {any[]} items Item list.\n   * @property {string} itemKey Item key used for the `each` loop.\n   * @property {number} [itemChunkSize] Number of items to be loaded at once. Defaults to 25.\n   * @property {Snippet<[any, number]>} renderItem Snippet to render each item. The snippet receives\n   * the item and its index as parameters.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    items,\n    itemKey,\n    itemChunkSize = 25,\n    renderItem,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {number} */\n  // svelte-ignore state_referenced_locally\n  let loadedItemSize = $state(itemChunkSize);\n\n  /** @type {HTMLElement | undefined} */\n  let spinner = $state(undefined);\n\n  const loading = $derived(items.length > loadedItemSize);\n\n  /**\n   * The scroll container found for the spinner. Looking it up reads the computed style and the\n   * scroll size of every ancestor, which forces a layout each time a chunk has been rendered.\n   * @type {HTMLElement | null}\n   */\n  let scrollContainer = null;\n\n  /**\n   * Whether {@link scrollContainer} is final: the nearest ancestor that can scroll, or the document\n   * if none can. The list only grows from then on, so a container that scrolls keeps doing so.\n   * Until then, a nearer one, like a pane the first chunk didn’t fill or one that was hidden, may\n   * start scrolling, and an outer container kept instead would miss the margin that loads the next\n   * chunk ahead of the view, so it’s looked up again for each chunk.\n   */\n  let isScrollContainerFinal = false;\n\n  /**\n   * Find the nearest ancestor of the given element that scrolls vertically. An ancestor that can\n   * scroll but whose content fits, like one growing with the list or a horizontal scroller, doesn’t\n   * clip the element, and as the observer’s root it would let every chunk load at once. The heights\n   * are rounded separately, so a 1px difference doesn’t count as scrolling.\n   * @param {HTMLElement} element Element.\n   * @returns {HTMLElement | null} Scroll container, or `null` if the document itself scrolls.\n   */\n  const getScrollContainer = (element) => {\n    if (isScrollContainerFinal) {\n      return scrollContainer;\n    }\n\n    /** @type {HTMLElement | null} */\n    let nearest = null;\n\n    scrollContainer = null;\n\n    for (let parent = element.parentElement; parent; parent = parent.parentElement) {\n      if (/^(auto|scroll)$/.test(getComputedStyle(parent).overflowY)) {\n        nearest ??= parent;\n\n        if (parent.scrollHeight - parent.clientHeight > 1) {\n          scrollContainer = parent;\n          break;\n        }\n      }\n    }\n\n    isScrollContainerFinal = scrollContainer === nearest;\n\n    return scrollContainer;\n  };\n\n  // Observe the spinner anew once each chunk is rendered: the observer only reports changes, so a\n  // spinner that stays in view because the chunk didn’t fill the viewport would stall the loading.\n  // Observing an element always reports its current state first. The observer is created here\n  // rather than when the component is set up, since `IntersectionObserver` doesn’t exist during\n  // server-side rendering, and it’s disconnected before the next chunk and on unmount.\n  // The next chunk starts loading while the spinner is still a little below the visible area, so\n  // the scrolling doesn’t stop at the end of each chunk. The margin only applies to the observer’s\n  // root, which has to be the scroll container: the viewport margin wouldn’t reveal a spinner\n  // clipped by a scrolling ancestor.\n  $effect(() => {\n    void loadedItemSize;\n\n    if (!spinner) {\n      return undefined;\n    }\n\n    const observer = new IntersectionObserver(\n      (entries) => {\n        // A busy browser can report several changes at once, oldest first, so only the last entry\n        // tells whether the spinner is near the view now\n        if (entries.at(-1)?.isIntersecting && loading) {\n          loadedItemSize += itemChunkSize;\n        }\n      },\n      { root: getScrollContainer(spinner), rootMargin: '0px 0px 500px 0px' },\n    );\n\n    observer.observe(spinner);\n\n    return () => {\n      observer.disconnect();\n    };\n  });\n</script>\n\n{#each items.slice(0, loadedItemSize) as item, index (item[itemKey] ?? index)}\n  {@render renderItem(item, index)}\n{/each}\n\n{#if loading}\n  <div role=\"none\" class=\"spinner\" bind:this={spinner}></div>\n{/if}\n\n<style>\n  .spinner {\n    height: 1px;\n  }\n\n</style>\n","/*\nAdapted from https://github.com/mattdesl\nDistributed under MIT License https://github.com/mattdesl/eases/blob/master/LICENSE.md\n*/\n\n/**\n * Returns value as is.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function linear(t) {\n\treturn t;\n}\n\n/**\n * Rebound effect on start and end of value range.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function backInOut(t) {\n\tconst s = 1.70158 * 1.525;\n\tif ((t *= 2) < 1) return 0.5 * (t * t * ((s + 1) * t - s));\n\treturn 0.5 * ((t -= 2) * t * ((s + 1) * t + s) + 2);\n}\n\n/**\n * Rebound effect on start.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function backIn(t) {\n\tconst s = 1.70158;\n\treturn t * t * ((s + 1) * t - s);\n}\n\n/**\n * Rebound effect on end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function backOut(t) {\n\tconst s = 1.70158;\n\treturn --t * t * ((s + 1) * t + s) + 1;\n}\n\n/**\n * Bounce effect on end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function bounceOut(t) {\n\tconst a = 4.0 / 11.0;\n\tconst b = 8.0 / 11.0;\n\tconst c = 9.0 / 10.0;\n\tconst ca = 4356.0 / 361.0;\n\tconst cb = 35442.0 / 1805.0;\n\tconst cc = 16061.0 / 1805.0;\n\tconst t2 = t * t;\n\treturn t < a\n\t\t? 7.5625 * t2\n\t\t: t < b\n\t\t\t? 9.075 * t2 - 9.9 * t + 3.4\n\t\t\t: t < c\n\t\t\t\t? ca * t2 - cb * t + cc\n\t\t\t\t: 10.8 * t * t - 20.52 * t + 10.72;\n}\n\n/**\n * Bounce effect on start and end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function bounceInOut(t) {\n\treturn t < 0.5 ? 0.5 * (1.0 - bounceOut(1.0 - t * 2.0)) : 0.5 * bounceOut(t * 2.0 - 1.0) + 0.5;\n}\n\n/**\n * Bounce effect on start.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function bounceIn(t) {\n\treturn 1.0 - bounceOut(1.0 - t);\n}\n\n/**\n * Circular effect, accelerate on start, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function circInOut(t) {\n\tif ((t *= 2) < 1) return -0.5 * (Math.sqrt(1 - t * t) - 1);\n\treturn 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);\n}\n\n/**\n * Circular effect, accelerate on start.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function circIn(t) {\n\treturn 1.0 - Math.sqrt(1.0 - t * t);\n}\n\n/**\n * Circular effect, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function circOut(t) {\n\treturn Math.sqrt(1 - --t * t);\n}\n\n/**\n * Cubic scaling, accelerate on start, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function cubicInOut(t) {\n\treturn t < 0.5 ? 4.0 * t * t * t : 0.5 * Math.pow(2.0 * t - 2.0, 3.0) + 1.0;\n}\n\n/**\n * Cubic scaling, accelerate on start\n *\n * @param {number} t\n * @returns {number}\n */\nexport function cubicIn(t) {\n\treturn t * t * t;\n}\n\n/**\n * Cubic scaling, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function cubicOut(t) {\n\tconst f = t - 1.0;\n\treturn f * f * f + 1.0;\n}\n\n/**\n * Elastic effect on start and end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function elasticInOut(t) {\n\treturn t < 0.5\n\t\t? 0.5 * Math.sin(((+13.0 * Math.PI) / 2) * 2.0 * t) * Math.pow(2.0, 10.0 * (2.0 * t - 1.0))\n\t\t: 0.5 *\n\t\t\t\tMath.sin(((-13.0 * Math.PI) / 2) * (2.0 * t - 1.0 + 1.0)) *\n\t\t\t\tMath.pow(2.0, -10.0 * (2.0 * t - 1.0)) +\n\t\t\t\t1.0;\n}\n\n/**\n * Elastic effect on start.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function elasticIn(t) {\n\treturn Math.sin((13.0 * t * Math.PI) / 2) * Math.pow(2.0, 10.0 * (t - 1.0));\n}\n\n/**\n * Elastic effect on end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function elasticOut(t) {\n\treturn Math.sin((-13.0 * (t + 1.0) * Math.PI) / 2) * Math.pow(2.0, -10.0 * t) + 1.0;\n}\n\n/**\n * Exponential effect on start and end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function expoInOut(t) {\n\treturn t === 0.0 || t === 1.0\n\t\t? t\n\t\t: t < 0.5\n\t\t\t? +0.5 * Math.pow(2.0, 20.0 * t - 10.0)\n\t\t\t: -0.5 * Math.pow(2.0, 10.0 - t * 20.0) + 1.0;\n}\n\n/**\n * Exponential effect on start.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function expoIn(t) {\n\treturn t === 0.0 ? t : Math.pow(2.0, 10.0 * (t - 1.0));\n}\n\n/**\n * Exponential effect on end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function expoOut(t) {\n\treturn t === 1.0 ? t : 1.0 - Math.pow(2.0, -10.0 * t);\n}\n\n/**\n * Quadratic scaling, accelerate on start, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function quadInOut(t) {\n\tt /= 0.5;\n\tif (t < 1) return 0.5 * t * t;\n\tt--;\n\treturn -0.5 * (t * (t - 2) - 1);\n}\n\n/**\n * Quadratic scaling, accelerate on start.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function quadIn(t) {\n\treturn t * t;\n}\n\n/**\n * Quadratic scaling, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function quadOut(t) {\n\treturn -t * (t - 2.0);\n}\n\n/**\n * Quartic scaling, accelerate on start, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function quartInOut(t) {\n\treturn t < 0.5 ? +8.0 * Math.pow(t, 4.0) : -8.0 * Math.pow(t - 1.0, 4.0) + 1.0;\n}\n\n/**\n * Quartic scaling, accelerate on start.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function quartIn(t) {\n\treturn Math.pow(t, 4.0);\n}\n\n/**\n * Quartic scaling, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function quartOut(t) {\n\treturn Math.pow(t - 1.0, 3.0) * (1.0 - t) + 1.0;\n}\n\n/**\n * Quintic scaling, accelerate on start, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function quintInOut(t) {\n\tif ((t *= 2) < 1) return 0.5 * t * t * t * t * t;\n\treturn 0.5 * ((t -= 2) * t * t * t * t + 2);\n}\n\n/**\n * Quintic scaling, accelerate on start.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function quintIn(t) {\n\treturn t * t * t * t * t;\n}\n\n/**\n * Quintic scaling, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function quintOut(t) {\n\treturn --t * t * t * t * t + 1;\n}\n\n/**\n * Sinusoidal effect, accelerate on start, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function sineInOut(t) {\n\treturn -0.5 * (Math.cos(Math.PI * t) - 1);\n}\n\n/**\n * Sinusoidal effect, accelerate on start.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function sineIn(t) {\n\tconst v = Math.cos(t * Math.PI * 0.5);\n\tif (Math.abs(v) < 1e-14) return 1;\n\telse return 1 - v;\n}\n\n/**\n * Sinusoidal effect, decelerate towards end.\n *\n * @param {number} t\n * @returns {number}\n */\nexport function sineOut(t) {\n\treturn Math.sin((t * Math.PI) / 2);\n}\n","/** @import { FlipParams, AnimationConfig } from './public.js' */\nimport { cubicOut } from '../easing/index.js';\n\n/**\n * The flip function calculates the start and end position of an element and animates between them, translating the x and y values.\n * `flip` stands for [First, Last, Invert, Play](https://aerotwist.com/blog/flip-your-animations/).\n *\n * @param {Element} node\n * @param {{ from: DOMRect; to: DOMRect }} fromTo\n * @param {FlipParams} params\n * @returns {AnimationConfig}\n */\nexport function flip(node, { from, to }, params = {}) {\n\tvar { delay = 0, duration = (d) => Math.sqrt(d) * 120, easing = cubicOut } = params;\n\n\tvar style = getComputedStyle(node);\n\n\t// find the transform origin, expressed as a pair of values between 0 and 1\n\tvar transform = style.transform === 'none' ? '' : style.transform;\n\tvar [ox, oy] = style.transformOrigin.split(' ').map(parseFloat);\n\tox /= node.clientWidth;\n\toy /= node.clientHeight;\n\n\t// calculate effect of parent transforms and zoom\n\tvar zoom = get_zoom(node); // https://drafts.csswg.org/css-viewport/#effective-zoom\n\tvar sx = node.clientWidth / to.width / zoom;\n\tvar sy = node.clientHeight / to.height / zoom;\n\n\t// find the starting position of the transform origin\n\tvar fx = from.left + from.width * ox;\n\tvar fy = from.top + from.height * oy;\n\n\t// find the ending position of the transform origin\n\tvar tx = to.left + to.width * ox;\n\tvar ty = to.top + to.height * oy;\n\n\t// find the translation at the start of the transform\n\tvar dx = (fx - tx) * sx;\n\tvar dy = (fy - ty) * sy;\n\n\t// find the relative scale at the start of the transform\n\tvar dsx = from.width / to.width;\n\tvar dsy = from.height / to.height;\n\n\treturn {\n\t\tdelay,\n\t\tduration: typeof duration === 'function' ? duration(Math.sqrt(dx * dx + dy * dy)) : duration,\n\t\teasing,\n\t\tcss: (t, u) => {\n\t\t\tvar x = u * dx;\n\t\t\tvar y = u * dy;\n\t\t\tvar sx = t + u * dsx;\n\t\t\tvar sy = t + u * dsy;\n\n\t\t\treturn `transform: ${transform} translate(${x}px, ${y}px) scale(${sx}, ${sy});`;\n\t\t}\n\t};\n}\n\n/**\n * @param {Element} element\n */\nfunction get_zoom(element) {\n\tif ('currentCSSZoom' in element) {\n\t\treturn /** @type {number} */ (element.currentCSSZoom);\n\t}\n\n\t/** @type {Element | null} */\n\tvar current = element;\n\tvar zoom = 1;\n\n\twhile (current !== null) {\n\t\tzoom *= +getComputedStyle(current).zoom;\n\t\tcurrent = /** @type {Element | null} */ (current.parentElement);\n\t}\n\n\treturn zoom;\n}\n","<!--\n  @component\n  The equivalent of the HTML `<input type=\"search\">` element. It comes with a magnifier icon and\n  clear button.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search\n  @see https://w3c.github.io/aria/#search\n-->\n\n<script>\n  import { _ } from '@sveltia/i18n';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import TextInput from './text-input.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { CommonEventHandlers, InputEventHandlers, TextInputProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [value] Input value.\n   * @property {Snippet} [searchIcon] Search icon slot content.\n   * @property {Snippet} [closeIcon] Close icon slot content.\n   * @property {() => void} [onClear] Callback invoked when the clear button is clicked.\n   */\n\n  /**\n   * @type {TextInputProps & CommonEventHandlers & InputEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    flex = false,\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    // Not supported, as the search icon takes the place of a label, but kept out of `restProps` so\n    // the inner `<TextInput>` doesn’t show one inside the search bar\n    showLabelAbove,\n    children,\n    searchIcon,\n    closeIcon,\n    onClear,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n\n  /**\n   * Reference to the `<input>` element.\n   * @type {HTMLInputElement | undefined}\n   */\n  let inputElement = $state();\n\n  /**\n   * Move focus to the `<input>` element.\n   */\n  export const focus = () => {\n    inputElement?.focus();\n  };\n</script>\n\n<div\n  role={hidden ? undefined : 'none'}\n  class=\"sui search-bar {className}\"\n  class:flex\n  class:disabled\n  class:readonly\n  {hidden}\n  aria-hidden={hidden}\n>\n  <span role=\"none\">\n    {#if searchIcon}\n      {@render searchIcon()}\n    {:else}\n      <Icon name=\"search\" />\n    {/if}\n  </span>\n  <TextInput\n    dir=\"auto\"\n    bind:element={inputElement}\n    {...restProps}\n    role=\"searchbox\"\n    {id}\n    bind:value\n    {flex}\n    {hidden}\n    {disabled}\n    {readonly}\n    {required}\n    {invalid}\n    inputmode=\"search\"\n  />\n  {#if value}\n    <Button\n      iconic\n      disabled={disabled || readonly}\n      aria-label={_('_sui.clear')}\n      aria-controls={id}\n      onclick={() => {\n        value = '';\n        inputElement?.focus();\n        onClear?.();\n      }}\n    >\n      {#snippet startIcon()}\n        {#if closeIcon}\n          {@render closeIcon()}\n        {:else}\n          <Icon name=\"close\" />\n        {/if}\n      {/snippet}\n    </Button>\n  {/if}\n</div>\n\n<style>.search-bar {\n  display: inline-flex;\n  align-items: center;\n  position: relative;\n  margin: var(--sui-focus-ring-width);\n  min-width: var(--sui-textbox-singleline-min-width);\n}\n.search-bar.flex:not([hidden]) {\n  display: inline-flex;\n  width: -moz-available;\n  width: -webkit-fill-available;\n  width: stretch;\n  min-width: 0;\n}\n.search-bar > span {\n  position: absolute;\n  inset-block: 0;\n  inset-inline-start: 0;\n  inset-inline-end: auto;\n  z-index: 2;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: var(--sui-button-medium-height);\n  height: var(--sui-button-medium-height);\n}\n.search-bar :global(.icon) {\n  font-size: calc(var(--sui-textbox-height) * 0.6);\n  opacity: 0.5;\n}\n.search-bar > :global(button) {\n  position: absolute;\n  inset-block: 0;\n  inset-inline-start: auto;\n  inset-inline-end: 0;\n  z-index: 2;\n  margin: 0 !important;\n  height: var(--sui-button-medium-height);\n}\n.search-bar :global(.label) {\n  --sui-textbox-singleline-padding: 0 36px;\n}\n.search-bar :global(.text-input) {\n  flex: auto;\n  margin: 0 !important;\n  width: 0;\n  min-width: 0 !important;\n}\n.search-bar :global(input) {\n  z-index: 1;\n  padding: 0 var(--sui-button-medium-height) !important;\n  width: 100%;\n}\n\n.search-bar:dir(rtl) {\n  --sui-textbox-text-align: right;\n}</style>\n","<!--\n  @component\n  A variant of the `<Select>` widget with an auto-complete text input field.\n  @see https://w3c.github.io/aria/#combobox\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/combobox/\n  @todo Add DOM API compatibility.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { onMount } from 'svelte';\n  import { setFocusedMember } from '../../services/group.svelte.js';\n  import { getAccessibleName } from '../../services/label.js';\n  import { createOptionRegistry, getSelectedItemDetail } from '../../services/select.svelte.js';\n  import { isPrintableKey, TypeAhead } from '../../services/type-ahead.js';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import Listbox from '../listbox/listbox.svelte';\n  import SearchBar from '../text-field/search-bar.svelte';\n  import TextInput from '../text-field/text-input.svelte';\n  import TruncatedText from '../typography/truncated-text.svelte';\n  import LabelAbove from '../util/label-above.svelte';\n  import Popup from '../util/popup.svelte';\n\n  /**\n   * @import {\n   * ComboboxProps,\n   * LabelAboveProps,\n   * OptionEntry,\n   * TextInputProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {LabelAboveProps & ComboboxProps & TextInputProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    editable = true,\n    position = 'bottom-left',\n    filterThreshold = 5,\n    selectOnTypeAhead = true,\n    ariaLabel = undefined,\n    showLabelAbove = false,\n    children,\n    chevronIcon,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n  let isPopupOpen = $state(false);\n\n  /** @type {HTMLElement | undefined} */\n  let comboboxElement = $state();\n  /** @type {HTMLInputElement | undefined} */\n  let inputElement = $state();\n  /** @type {HTMLElement | undefined} */\n  let popupContent = $state();\n  /**\n   * Wrapper holding the options while the dropdown is collapsed.\n   * @type {HTMLElement | undefined}\n   */\n  let idleHost = $state();\n  /**\n   * Wrapper holding the options, moved between {@link idleHost} and {@link listboxSlot}.\n   * @type {HTMLElement | undefined}\n   */\n  let optionHost = $state();\n  /**\n   * Where the options go while the dropdown is expanded.\n   * @type {HTMLElement | undefined}\n   */\n  let listboxSlot = $state();\n  /** @type {boolean} */\n  let showFilter = $state(false);\n  /** @type {string} */\n  let searchTerms = $state('');\n  /**\n   * Characters typed on the collapsed combobox that opened the dropdown, to be carried over to the\n   * filter once it’s shown. See {@link selectOnTypeAhead}.\n   * @type {string}\n   */\n  let pendingSearchTerms = '';\n  /**\n   * Number of options matching the current search terms, as last reported by the listbox.\n   * @type {number}\n   */\n  let matchedOptions = $state(0);\n\n  /**\n   * Whether to keep the option list free of the “no matching options” notice. That notice is about\n   * filtering, so it’s only meaningful once search terms have been entered — the listbox also\n   * reports zero matches while the options are unrendered, which says nothing about the filter.\n   * @type {boolean}\n   */\n  const hasMatchingOptions = $derived(!searchTerms || matchedOptions > 0);\n  /**\n   * @type {HTMLElement}\n   */\n  /**\n   * Accessible name, given as the `ariaLabel` prop or as a plain `aria-label` attribute. It’s set\n   * after the props are spread, so it has to cover both, or the attribute would be overwritten.\n   */\n  const accessibleName = $derived(getAccessibleName({ ariaLabel, props: restProps }));\n  const labelAbove = $derived(showLabelAbove ? accessibleName : undefined);\n  const anchor = $derived(/** @type {HTMLElement} */ (comboboxElement ?? inputElement));\n\n  /**\n   * The options declared as `<Option>` children. They only render while the dropdown is expanded,\n   * so the label and the initial value below are resolved through the registry rather than the DOM\n   * tree.\n   */\n  const registry = createOptionRegistry();\n\n  /**\n   * Label of the option matching the {@link value}. A value that matches no option, including\n   * `undefined`, gives an empty label.\n   */\n  const label = $derived(registry.find(value)?.label ?? '');\n\n  /**\n   * Raise a `Change` event for an option known only through its registry entry. There is no option\n   * element to report while the dropdown is collapsed.\n   * @param {OptionEntry} entry Selected option’s entry.\n   */\n  const dispatchEntryChange = ({ type, name, label: entryLabel, value: entryValue }) => {\n    onChange?.(\n      new CustomEvent('Change', {\n        detail: { target: undefined, type, name, label: entryLabel, value: entryValue },\n      }),\n    );\n  };\n\n  /**\n   * Update the {@link value} whenever an option is selected.\n   * @param {HTMLButtonElement} target Selected option.\n   */\n  const _onSelect = (target) => {\n    const detail = getSelectedItemDetail(target);\n\n    value = detail.value;\n    onChange?.(new CustomEvent('Change', { detail }));\n  };\n\n  /**\n   * Update the {@link value} as the user types in the editable combobox. The text is a free-form\n   * value, so the `Change` event carries the text itself rather than an option.\n   * @param {Event} event The `input` event.\n   */\n  const onTextInput = (event) => {\n    const { target } = /** @type {Event & { target: HTMLInputElement }} */ (event);\n\n    value = target.value;\n    restProps.oninput?.(event);\n    onChange?.(\n      new CustomEvent('Change', {\n        detail: { target, type: 'string', name: undefined, label: target.value, value },\n      }),\n    );\n  };\n\n  /**\n   * Keystroke buffer for type-ahead on the collapsed select.\n   */\n  const typeAhead = new TypeAhead();\n\n  /**\n   * Type-ahead on the collapsed, select-only combobox: a printable character picks the next option\n   * whose label starts with what has been typed, without expanding the dropdown — the way a native\n   * `<select>` behaves and the Select-Only Combobox pattern expects. There is no option element to\n   * report while the dropdown is collapsed, so the `Change` event carries the registry entry.\n   *\n   * With `selectOnTypeAhead` disabled, as in `<SelectTags>` where every change commits a tag, a\n   * printable character opens the dropdown instead, and goes into the filter if it’s shown, so the\n   * user can narrow down the options before picking one.\n   * @param {KeyboardEvent} event The `keydown` event.\n   */\n  const onComboboxKeyDown = (event) => {\n    const { key } = event;\n\n    if (disabled || readonly || isPopupOpen || !isPrintableKey(event)) {\n      return;\n    }\n\n    // Swallow the key whether or not it matches, as a native `<select>` does. Left to the browser,\n    // a printable key on a non-editable element starts Firefox’s find-as-you-type.\n    event.preventDefault();\n\n    if (!selectOnTypeAhead) {\n      pendingSearchTerms = key;\n      isPopupOpen = true;\n\n      return;\n    }\n\n    const entries = registry.entries.filter((entry) => !entry.disabled);\n\n    const index = typeAhead.match(\n      entries.map((entry) => entry.label ?? ''),\n      key,\n      entries.findIndex((entry) => entry.value === value),\n    );\n\n    if (index === -1) {\n      return;\n    }\n\n    const entry = entries[index];\n\n    if (entry.value === value) {\n      return;\n    }\n\n    value = entry.value;\n    dispatchEntryChange(entry);\n  };\n\n  /**\n   * The `<Listbox>` rendered for this combobox. It’s reached through {@link optionHost}, which owns\n   * it wherever the options currently live, rather than through the popup, which only holds it\n   * while the dropdown is expanded.\n   * @returns {HTMLElement | null | undefined} Listbox element.\n   */\n  const getListbox = () => optionHost?.querySelector('[role=\"listbox\"]');\n\n  /**\n   * Make the selected option the starting point of the expanded dropdown: scroll it into view, and\n   * mark it as the focused member so the arrow keys carry on from there. A long option list is\n   * scrollable, and the dropdown would otherwise open at the top with the current selection nowhere\n   * to be seen — and the first arrow key would jump back up to the first option.\n   */\n  const revealSelectedOption = () => {\n    const listbox = getListbox();\n\n    const option = /** @type {HTMLElement | null | undefined} */ (\n      listbox?.querySelector('[role=\"option\"][aria-selected=\"true\"]')\n    );\n\n    if (!listbox || !option) {\n      return;\n    }\n\n    // `<Group>` tracks the focused member with this class, and moves it on from there\n    setFocusedMember(listbox, option);\n\n    option.scrollIntoView(true);\n  };\n\n  // Let the options know whether they should render themselves\n  $effect(() => {\n    registry.expanded = isPopupOpen;\n  });\n\n  // Reveal the selected option once the dropdown is expanded. The options are rendered and moved\n  // into the popup by the effects around this one, and the popup is then measured against the space\n  // below the anchor to get its height, so there is nothing to scroll until all of that has\n  // settled. The popup moves focus onto its first tab stop 100ms in, which scrolls that element\n  // into view in turn, so this has to come after it rather than be undone by it.\n  $effect(() => {\n    if (!isPopupOpen) {\n      return undefined;\n    }\n\n    const timer = globalThis.setTimeout(revealSelectedOption, 150);\n\n    return () => {\n      globalThis.clearTimeout(timer);\n      // The options are unmounted along with the popup, so the listbox is about to be pointing at\n      // an element that no longer exists\n      getListbox()?.removeAttribute('aria-activedescendant');\n    };\n  });\n\n  // Move the options into the popup while it’s expanded, and back out before it’s unmounted. Only\n  // the wrapper is moved, never its children, so Svelte keeps full ownership of the subtree.\n  $effect(() => {\n    // The host is bound before any effect runs\n    /* v8 ignore next */\n    if (!optionHost) {\n      return;\n    }\n\n    const parent = isPopupOpen ? listboxSlot : idleHost;\n\n    if (parent && optionHost.parentElement !== parent) {\n      parent.append(optionHost);\n    }\n  });\n\n  // Derive the initial value from the `<Option>` that is marked as selected in the markup. This has\n  // to be a one-off read rather than an effect on `registry.selectedEntry`: where the markup marks\n  // nothing as selected, the first entry to become selected is the one the user picks, and\n  // reporting that here would raise a second `Change` for a single choice. The options register\n  // during their own initialization, so they are all present by the time this runs.\n  onMount(() => {\n    const entry = registry.selectedEntry;\n\n    if (!entry) {\n      return;\n    }\n\n    value = entry.value;\n\n    // There is no element to report while the dropdown has never been expanded\n    dispatchEntryChange(entry);\n  });\n\n  // Mark the option matching the value as selected. A value that matches no option, including\n  // `undefined`, deselects every option, so the previous option doesn’t stay selected.\n  $effect(() => {\n    registry.selectOnly(value);\n  });\n</script>\n\n<!--\n  `aria-controls` is deliberately absent from the `role=\"combobox\"` element below: the popup is\n  only in the DOM tree while it’s expanded, and a reference to a missing element is worse than no\n  reference at all. The popup service adds it on open and removes it on close.\n-->\n<div\n  role=\"none\"\n  class=\"sui combobox {className}\"\n  class:editable\n  class:has-label-above={!!labelAbove}\n  {hidden}\n>\n  {#if labelAbove}\n    <!-- A non-editable combobox is a `<div>`, which a label can’t point to -->\n    <LabelAbove\n      label={labelAbove}\n      for={editable ? id : undefined}\n      getTarget={editable ? undefined : () => comboboxElement}\n    />\n  {/if}\n  {#if !editable}\n    <div\n      bind:this={comboboxElement}\n      {...restProps}\n      role=\"combobox\"\n      {id}\n      class:selected={value !== undefined}\n      tabindex={disabled ? -1 : 0}\n      aria-expanded={isPopupOpen}\n      aria-hidden={hidden}\n      aria-disabled={disabled}\n      aria-readonly={readonly}\n      aria-required={required}\n      aria-invalid={invalid}\n      aria-haspopup=\"listbox\"\n      aria-label={accessibleName}\n      onkeydown={onComboboxKeyDown}\n    >\n      <div role=\"none\" class=\"label\">\n        <TruncatedText>\n          {value !== undefined ? label : _('_sui.combobox.select_an_option')}\n        </TruncatedText>\n      </div>\n    </div>\n  {:else}\n    <TextInput\n      {...restProps}\n      dir=\"auto\"\n      bind:element={inputElement}\n      role=\"combobox\"\n      {id}\n      value={value === undefined ? '' : String(value)}\n      {hidden}\n      {disabled}\n      {readonly}\n      {required}\n      {invalid}\n      aria-expanded={isPopupOpen}\n      aria-haspopup=\"listbox\"\n      ariaLabel={accessibleName}\n      oninput={onTextInput}\n    />\n  {/if}\n  <Button\n    variant=\"ghost\"\n    iconic\n    {hidden}\n    {disabled}\n    tabindex={!editable || readonly || disabled ? -1 : 0}\n    aria-label={isPopupOpen ? _('_sui.collapse') : _('_sui.expand')}\n    aria-controls={isPopupOpen ? `${id}-popup` : undefined}\n    aria-expanded={isPopupOpen}\n    onclick={(event) => {\n      event.preventDefault();\n      event.stopPropagation();\n\n      if (!disabled && !readonly) {\n        isPopupOpen = !isPopupOpen;\n      }\n    }}\n  >\n    {#snippet startIcon()}\n      {#if chevronIcon}\n        {@render chevronIcon()}\n      {:else}\n        <Icon name=\"expand_more\" />\n      {/if}\n    {/snippet}\n  </Button>\n</div>\n<!--\n  The `<Option>`s have to stay instantiated while the dropdown is collapsed, so that the registry\n  above can resolve the current label. They render no DOM of their own in that state, so this host\n  is empty apart from any other markup the consumer interleaved, such as a `<Divider>`. It’s moved\n  into the popup when the dropdown expands, which keeps a single set of component instances and lets\n  Svelte own the rendering order.\n-->\n<div bind:this={idleHost} role=\"none\" class=\"idle-host\" hidden>\n  <div bind:this={optionHost} role=\"none\" class=\"option-host\">\n    <Listbox\n      id=\"{id}-listbox\"\n      class=\"in-combobox\"\n      {searchTerms}\n      onclick={(event) => {\n        if (/** @type {HTMLElement} */ (event.target).matches('[role=\"option\"]')) {\n          _onSelect(/** @type {HTMLButtonElement} */ (event.target));\n        }\n      }}\n      onFilter={(event) => {\n        matchedOptions = /** @type {CustomEvent} */ (event).detail.matched;\n      }}\n    >\n      {@render children?.()}\n    </Listbox>\n  </div>\n</div>\n<Popup\n  bind:content={popupContent}\n  id=\"{id}-popup\"\n  class=\"combobox\"\n  {anchor}\n  {position}\n  touchOptimized={true}\n  bind:open={isPopupOpen}\n  onOpen={() => {\n    showFilter = filterThreshold === -1 ? false : registry.count > filterThreshold;\n    searchTerms = showFilter ? pendingSearchTerms : '';\n    pendingSearchTerms = '';\n  }}\n>\n  <div role=\"none\" class=\"combobox-inner\">\n    {#if showFilter}\n      <SearchBar\n        flex\n        aria-label={_('_sui.combobox.filter_options')}\n        aria-controls=\"{id}-listbox\"\n        bind:value={searchTerms}\n        onkeydown={(event) => {\n          if (['ArrowUp', 'ArrowDown', 'Enter'].includes(event.key)) {\n            event.preventDefault();\n            popupContent\n              ?.querySelector('.sui.listbox')\n              ?.dispatchEvent(new KeyboardEvent('keydown', event));\n          }\n        }}\n      />\n    {/if}\n    <div bind:this={listboxSlot} role=\"none\" class=\"listbox-slot\"></div>\n    {#if !hasMatchingOptions}\n      <div role=\"status\" class=\"no-options\">\n        {_('_sui.combobox.no_matching_options')}\n      </div>\n    {/if}\n  </div>\n</Popup>\n\n<style>:is(.option-host, .listbox-slot) {\n  display: contents;\n}\n\n.combobox {\n  margin: var(--sui-focus-ring-width);\n  display: flex;\n  align-items: center;\n  position: relative;\n  min-width: var(--sui-combobox-min-width, calc(var(--sui-option-height) * 5));\n}\n.combobox.has-label-above {\n  flex-wrap: wrap;\n}\n.combobox.has-label-above > :global(button) {\n  inset-block: auto 0;\n}\n.combobox div[role=combobox] {\n  display: flex;\n  align-items: center;\n  border-width: 1px;\n  border-color: var(--sui-control-border-color);\n  border-radius: var(--sui-textbox-border-radius);\n  padding-block: 0;\n  padding-inline-start: calc(var(--sui-textbox-height) / 4);\n  padding-inline-end: var(--sui-textbox-height);\n  width: 100%;\n  height: var(--sui-textbox-height);\n  color: var(--sui-control-foreground-color);\n  background-color: var(--sui-disabled-background-color);\n  font-family: var(--sui-control-font-family);\n  font-size: var(--sui-control-font-size);\n  line-height: var(--sui-control-line-height);\n  -webkit-user-select: none;\n  user-select: none;\n  cursor: pointer;\n  transition: all 200ms;\n}\n.combobox div[role=combobox]:not(.selected) {\n  font-style: italic;\n}\n.combobox div[role=combobox]:is(:hover, :focus) {\n  background-color: var(--sui-hover-background-color);\n}\n.combobox div[role=combobox][aria-readonly=true] {\n  cursor: default;\n}\n.combobox div[role=combobox][aria-readonly=true]:is(:hover, :focus):not(:focus-visible) {\n  background-color: var(--sui-disabled-background-color);\n}\n.combobox div[role=combobox][aria-invalid=true] {\n  border-color: var(--sui-error-border-color);\n}\n.combobox div[role=combobox] .label {\n  width: 100%;\n}\n.combobox :global(.icon) {\n  font-size: var(--sui-font-size-xx-large);\n  opacity: 0.5;\n}\n.combobox > :global(button) {\n  position: absolute;\n  inset-block-start: 0;\n  inset-inline-end: 0;\n  z-index: 1;\n  margin: 0 !important;\n  border-start-start-radius: 0;\n  border-end-start-radius: 0;\n  background-color: transparent !important;\n}\n.combobox > :global(button[tabindex=\"-1\"]) {\n  pointer-events: none;\n}\n.combobox :global(.text-input) {\n  margin: 0 !important;\n  width: 100% !important;\n}\n.combobox :global(input) {\n  padding-block: 0;\n  padding-inline: 8px 32px;\n  width: 0;\n}\n\n.combobox-inner {\n  flex: auto;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n.combobox-inner :global(.sui.search-bar) {\n  flex: none;\n  margin-bottom: calc(8px - var(--sui-focus-ring-width));\n}\n.combobox-inner :global(.sui.listbox) {\n  flex: auto;\n  overflow-y: auto;\n}\n.combobox-inner .no-options {\n  flex: none;\n  display: flex;\n  align-items: center;\n  padding: var(--sui-option-padding);\n  height: var(--sui-option-height);\n  color: var(--sui-tertiary-foreground-color);\n}</style>\n","<!--\n  @component\n  A select-only variant of `<Combobox>`. The equivalent of the HTML `<select>` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select\n  @see https://w3c.github.io/aria/#combobox\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/\n-->\n<script>\n  import Combobox from './combobox.svelte';\n\n  /**\n   * @import { ComboboxProps, LabelAboveProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {LabelAboveProps & ComboboxProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    class: className,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<Combobox {...restProps} bind:value class=\"sui select {className}\" editable={false} />\n","/**\n * Reordering logic behind `<SelectTags>`, kept apart from the component so it can be tested\n * without dragging anything.\n */\n\n/**\n * Move an item within a list.\n * @template T\n * @param {T[]} list List.\n * @param {number} from Index of the item to move.\n * @param {number} to Index the item should end up at.\n * @returns {T[]} A new list with the item moved, or the same list if `from` and `to` are equal.\n */\nexport const moveItem = (list, from, to) => {\n  if (from === to) {\n    return list;\n  }\n\n  const newList = [...list];\n  const [item] = newList.splice(from, 1);\n\n  newList.splice(to, 0, item);\n\n  return newList;\n};\n\n/**\n * Get the index a tag should move to when a key is pressed on it. The arrow keys swap it with a\n * neighbor, following the visual direction of the list, and Home/End move it to either end.\n * @param {object} options Options.\n * @param {string} options.key The key pressed.\n * @param {number} options.index Index of the tag.\n * @param {number} options.length Number of tags.\n * @param {boolean} options.rtl Whether the layout is right-to-left, in which case the arrow keys\n * are swapped.\n * @returns {number} Target index, or `-1` if the key doesn’t move the tag, including when it’s\n * already at the end the key would move it to.\n */\nexport const getKeyboardMoveTarget = ({ key, index, length, rtl }) => {\n  const prevKey = rtl ? 'ArrowRight' : 'ArrowLeft';\n  const nextKey = rtl ? 'ArrowLeft' : 'ArrowRight';\n\n  if (key === prevKey && index > 0) {\n    return index - 1;\n  }\n\n  if (key === nextKey && index < length - 1) {\n    return index + 1;\n  }\n\n  if (key === 'Home' && index > 0) {\n    return 0;\n  }\n\n  if (key === 'End' && index < length - 1) {\n    return length - 1;\n  }\n\n  return -1;\n};\n\n/**\n * Get where a dragged tag would be inserted when the pointer is over another tag: before it when\n * the pointer is in the half nearer to the start of the list, after it otherwise.\n * @param {object} options Options.\n * @param {number} options.index Index of the tag under the pointer.\n * @param {number} options.clientX Horizontal position of the pointer.\n * @param {{ left: number, width: number }} options.rect Bounds of the tag under the pointer.\n * @param {boolean} options.rtl Whether the layout is right-to-left, in which case the start of the\n * list is on the right.\n * @returns {number} Insertion index: the dragged tag would be placed before the tag at this index,\n * so `length` means after the last one.\n */\nexport const getDropIndex = ({ index, clientX, rect, rtl }) => {\n  const inFirstHalf = clientX < rect.left + rect.width / 2;\n\n  return inFirstHalf !== rtl ? index : index + 1;\n};\n\n/**\n * Turn an insertion index into the index the dragged tag ends up at once it’s been taken out of\n * the list.\n * @param {number} fromIndex Index of the dragged tag.\n * @param {number} dropIndex Insertion index, as returned by {@link getDropIndex}.\n * @returns {number | undefined} Destination index for {@link moveItem}, or `undefined` if the\n * drop leaves the order unchanged, which is the case when the tag is dropped on either side of\n * its own position.\n */\nexport const getDropTarget = (fromIndex, dropIndex) => {\n  if (dropIndex === fromIndex || dropIndex === fromIndex + 1) {\n    return undefined;\n  }\n\n  return dropIndex > fromIndex ? dropIndex - 1 : dropIndex;\n};\n","<script>\n  import { _, isRTL } from '@sveltia/i18n';\n  import { tick } from 'svelte';\n  import { flip } from 'svelte/animate';\n  import { getLabelAboveText } from '../../services/label.js';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import Option from '../listbox/option.svelte';\n  import LabelAbove from '../util/label-above.svelte';\n  import Select from './select.svelte';\n  import { getDropIndex, getDropTarget, getKeyboardMoveTarget, moveItem } from './select-tags.js';\n\n  /**\n   * @import {\n   * ContainerProps,\n   * FormFieldStateProps,\n   * LabelAboveProps,\n   * WidgetStateProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {{ label: string, value: any, searchValue?: string }[]} options Available options.\n   * @property {string[]} [values] Selected option values.\n   * @property {number} [max] Maximum number of selectable options.\n   * @property {(event: CustomEvent<{ value: string }>) => void} [onAddValue] Custom `AddValue`\n   * event handler.\n   * @property {(event: CustomEvent<{ value: string }>) => void} [onRemoveValue] Custom\n   * `RemoveValue` event handler.\n   * @property {(event: CustomEvent<{ values: string[] }>) => void} [onReorder] Custom `Reorder`\n   * event handler fired when the order of selected values changes.\n   */\n\n  /**\n   * @type {LabelAboveProps & ContainerProps & WidgetStateProps & FormFieldStateProps & Props &\n   * Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    values = $bindable([]),\n    options,\n    max = undefined,\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    showLabelAbove = false,\n    children,\n    onAddValue,\n    onRemoveValue,\n    onReorder,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {Map<any, { label: string, value: any, searchValue?: string }>} */\n  const optionMap = $derived(new Map(options.map((o) => [o.value, o])));\n  /**\n   * The selected values as a set, so the option list below can test membership in constant time.\n   * Calling `values.includes()` once per option instead makes rendering the list quadratic in the\n   * number of options and selected tags.\n   * @type {Set<any>}\n   */\n  const selectedValues = $derived(new Set(values));\n  /**\n   * Whether any option is left to pick. This can’t be told by comparing the number of selected\n   * values with the number of options, as the values may include entries missing from the options.\n   * @type {boolean}\n   */\n  const hasUnselectedOptions = $derived(options.some(({ value }) => !selectedValues.has(value)));\n\n  /**\n   * Reference to the wrapper element.\n   * @type {HTMLElement | undefined}\n   */\n  let wrapperElement = $state();\n\n  /**\n   * Label shown above the widget with `showLabelAbove`. It’s rendered here rather than by the\n   * `<Select>`, so it sits above the tags as well.\n   */\n  const labelAbove = $derived(getLabelAboveText({ showLabelAbove, props: restProps }));\n\n  /**\n   * @type {string | undefined}\n   */\n  let selectedValue = $state();\n\n  /**\n   * Index of the tag currently being dragged.\n   * @type {number | undefined}\n   */\n  let dragIndex = $state();\n\n  /**\n   * Insertion position during drag: the dragged item will be placed *before* this index (0 = before\n   * first, values.length = after last).\n   * @type {number | undefined}\n   */\n  let dropIndex = $state();\n\n  /**\n   * Move a selected value from one position to another and dispatch the `Reorder` event.\n   * @param {number} from Source index.\n   * @param {number} to Destination index.\n   */\n  const moveValue = (from, to) => {\n    // The callers only ask for actual moves\n    /* v8 ignore next */\n    if (from === to) return;\n\n    const newValues = moveItem(values, from, to);\n\n    values = newValues;\n    onReorder?.(new CustomEvent('Reorder', { detail: { values: newValues } }));\n  };\n\n  /**\n   * Move a value and focus the tag at the destination index.\n   * @param {number} from Source index.\n   * @param {number} to Destination index.\n   */\n  const moveAndFocus = async (from, to) => {\n    moveValue(from, to);\n    await tick();\n\n    /** @type {HTMLElement} */ (\n      wrapperElement?.querySelectorAll('.label[tabindex]')?.[to]\n    )?.focus();\n  };\n</script>\n\n<div\n  role=\"none\"\n  class=\"sui select-tags {className}\"\n  class:disabled={disabled || readonly}\n  {hidden}\n  bind:this={wrapperElement}\n>\n  {#if labelAbove}\n    <!-- The select is a `<div>`, which a label can’t point to, and goes once `max` is reached -->\n    <LabelAbove\n      label={labelAbove}\n      getTarget={() => wrapperElement?.querySelector('[role=\"combobox\"]')}\n    />\n  {/if}\n  <!--\n    The tags follow the APG layout grid pattern rather than a listbox: a listbox may only hold\n    options, and each tag also carries its Remove button. Each tag is a row whose first cell, the\n    label, is the focusable part that the arrow keys reorder.\n    @see https://www.w3.org/WAI/ARIA/apg/patterns/grid/examples/layout-grids/\n  -->\n  <span role=\"grid\" aria-label={_('_sui.select_tags.selected_options')}>\n    {#each values as value, index (value)}\n      {@const option = optionMap.get(value)}\n      {@const label = option?.label || option?.value || value}\n      <!--\n        The drag handlers are the pointer path only; the keyboard path is the focusable label cell\n        below, so the row itself stays out of the tab order\n      -->\n      <!-- svelte-ignore a11y_interactive_supports_focus -->\n      <span\n        role=\"row\"\n        draggable={!disabled && !readonly}\n        class:drag-source={dragIndex === index}\n        class:drop-before={dropIndex === index && dragIndex !== index && dragIndex !== index - 1}\n        class:drop-after={dropIndex === values.length &&\n          index === values.length - 1 &&\n          dragIndex !== values.length - 1}\n        ondragstart={(event) => {\n          dragIndex = index;\n\n          if (event.dataTransfer) {\n            event.dataTransfer.setData('text/plain', label);\n            event.dataTransfer.effectAllowed = 'move';\n          }\n        }}\n        ondragover={(event) => {\n          event.preventDefault();\n\n          if (event.dataTransfer) {\n            event.dataTransfer.dropEffect = 'move';\n          }\n\n          dropIndex = getDropIndex({\n            index,\n            clientX: event.clientX,\n            rect: event.currentTarget.getBoundingClientRect(),\n            rtl: isRTL(),\n          });\n        }}\n        ondrop={async (event) => {\n          event.preventDefault();\n\n          const fromIndex = dragIndex;\n          const toIndex = dropIndex;\n\n          dragIndex = undefined;\n          dropIndex = undefined;\n\n          if (fromIndex === undefined || toIndex === undefined) {\n            return;\n          }\n\n          const target = getDropTarget(fromIndex, toIndex);\n\n          if (target !== undefined) {\n            await moveAndFocus(fromIndex, target);\n          }\n        }}\n        ondragend={() => {\n          dragIndex = undefined;\n          dropIndex = undefined;\n        }}\n        animate:flip={{ duration: 200 }}\n      >\n        <span\n          class=\"label\"\n          role=\"gridcell\"\n          tabindex={disabled || readonly ? undefined : 0}\n          onkeydown={async (event) => {\n            const targetIndex = getKeyboardMoveTarget({\n              key: event.key,\n              index,\n              length: values.length,\n              rtl: isRTL(),\n            });\n\n            if (targetIndex === -1) return;\n\n            event.preventDefault();\n            await moveAndFocus(index, targetIndex);\n          }}\n        >\n          {label}\n        </span>\n        {#if option}\n          <span role=\"gridcell\">\n            <Button\n              iconic\n              size=\"small\"\n              disabled={disabled || readonly}\n              aria-label={_('_sui.select_tags.remove_x', { values: { name: label } })}\n              onclick={() => {\n                values = values.filter((v) => v !== value);\n                onRemoveValue?.(new CustomEvent('RemoveValue', { detail: { value } }));\n              }}\n            >\n              {#snippet startIcon()}\n                <Icon name=\"close\" />\n              {/snippet}\n            </Button>\n          </span>\n        {/if}\n      </span>\n    {/each}\n  </span>\n  {#if (typeof max !== 'number' || values.length < max) && hasUnselectedOptions}\n    <Select\n      {...restProps}\n      bind:value={selectedValue}\n      disabled={disabled || readonly}\n      {readonly}\n      {required}\n      {invalid}\n      selectOnTypeAhead={false}\n      onChange={() => {\n        // The select only reports a change once an option has been picked. Check for `undefined`\n        // rather than a falsy value, as `null`, `false`, `0` and an empty string are valid values\n        /* v8 ignore else */\n        if (selectedValue !== undefined) {\n          values = [...values, selectedValue];\n          onAddValue?.(new CustomEvent('AddValue', { detail: { value: selectedValue } }));\n          // Reset the combobox\n          selectedValue = undefined;\n        }\n      }}\n    >\n      {#each options as { label, value, searchValue } (value)}\n        {#if !selectedValues.has(value)}\n          <Option {label} {value} {searchValue} />\n        {/if}\n      {/each}\n    </Select>\n  {/if}\n</div>\n\n<style>.select-tags {\n  display: flex;\n  flex-wrap: wrap;\n  align-items: center;\n}\n.select-tags.disabled {\n  pointer-events: none;\n}\n.select-tags.disabled > * {\n  opacity: 0.5;\n}\n.select-tags span[role=grid] {\n  display: contents;\n}\n.select-tags span[draggable] {\n  display: inline-flex;\n  align-items: center;\n  position: relative;\n  margin: var(--sui-focus-ring-width);\n  padding: 0;\n  padding-inline-start: 8px;\n  border-radius: var(--sui-control-medium-border-radius);\n  background-color: var(--sui-secondary-background-color);\n  cursor: grab;\n  outline: none;\n}\n.select-tags span[draggable]:focus-within {\n  outline: var(--sui-focus-ring-width) solid var(--sui-focus-ring-color);\n}\n.select-tags span[draggable].drag-source {\n  opacity: 0.4;\n  cursor: grabbing;\n}\n.select-tags span[draggable].drop-before::before, .select-tags span[draggable].drop-after::after {\n  content: \"\";\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  margin-inline-start: -1px;\n  border-radius: 1px;\n  width: 4px;\n  background-color: var(--sui-primary-accent-color);\n  pointer-events: none;\n}\n.select-tags span[draggable].drop-before::before {\n  inset-inline-start: calc(-1 * var(--sui-focus-ring-width) - 1px);\n}\n.select-tags span[draggable].drop-after::after {\n  inset-inline-end: calc(-1 * var(--sui-focus-ring-width) - 1px);\n}\n.select-tags span[draggable] .label {\n  outline: none;\n}\n.select-tags span[draggable] span[role=gridcell]:not(.label) {\n  display: contents;\n}\n.select-tags span[draggable] :global(button) {\n  outline-offset: -2px;\n}\n.select-tags span[draggable] :global(.icon) {\n  font-size: var(--sui-font-size-large);\n}</style>\n","/**\n * Number helpers shared by the components that step through a range of numbers, like\n * `<NumberInput>` and `<Slider>`.\n */\n\n/**\n * Get the step to use, falling back to `1` for a value that isn’t a positive number, like `0`,\n * `null` or `NaN`, which would leave the spin buttons and the arrow keys with nowhere to go.\n * @param {number | null | undefined} step Step value.\n * @returns {number} Positive step.\n */\nexport const normalizeStep = (step) =>\n  typeof step === 'number' && Number.isFinite(step) && step > 0 ? step : 1;\n\n/**\n * Count the fraction digits of a number, including one written in exponent notation, such as\n * `1e-7`, so a value stepped by `0.1` can be rounded to `0.3` rather than `0.30000000000000004`.\n * @param {number} num Number.\n * @returns {number} Number of fraction digits, `0` for an integer.\n */\nexport const getMaximumFractionDigits = (num) => {\n  // A small number like `0.0000001` is stringified in exponent notation as `1e-7`\n  const [mantissa, exponent = '0'] = String(num).toLowerCase().split('e');\n  const digits = (mantissa.split('.')[1]?.length ?? 0) - Number(exponent);\n\n  return Math.max(digits, 0);\n};\n","import { getArrowKeys } from '../../services/navigation.js';\nimport { getMaximumFractionDigits, normalizeStep } from '../../services/number.js';\n\n/**\n * Geometry and keyboard logic behind `<Slider>`, kept apart from the component so the value\n * calculations can be tested without a rendered track.\n */\n\n/**\n * Get the values a thumb can take and where each of them sits along the track.\n * @param {object} options Options.\n * @param {number} options.min Minimum value.\n * @param {number} options.max Maximum value.\n * @param {number} options.step Distance between two values. `1` is used instead if it isn’t a\n * positive number.\n * @param {number} options.barWidth Width of the track in pixels.\n * @returns {{ valueList: number[], positionList: number[] }} Values from `min` to `max` in `step`\n * increments, and the matching pixel offsets from the logical start of the track.\n */\nexport const getSliderSteps = ({ min, max, step: _step, barWidth }) => {\n  // Fall back to `1` for a step that isn’t a positive number: `0` would make the step count\n  // infinite, while a negative step would leave no values at all\n  const step = normalizeStep(_step);\n  const stepRatio = (max - min) / step;\n  // Tolerate floating point errors, e.g. `0.3 / 0.1` is `2.9999999999999996`, which would otherwise\n  // drop the maximum\n  const stepCount = Math.floor(stepRatio + 1e-9) + 1;\n  const stepWidth = barWidth / stepRatio;\n  const emptyArray = Array.from({ length: stepCount });\n\n  // Round the values to the precision of the minimum and the step, e.g. `3 * 0.1` is\n  // `0.30000000000000004`, which would otherwise never match the `0.3` value. `toFixed()` accepts\n  // up to 100 digits\n  const decimals = Math.min(\n    Math.max(getMaximumFractionDigits(min), getMaximumFractionDigits(step)),\n    100,\n  );\n\n  return {\n    valueList: emptyArray.map((_, index) => Number((index * step + min).toFixed(decimals))),\n    positionList: emptyArray.map((_, index) => index * stepWidth),\n  };\n};\n\n/**\n * Convert a physical pointer position into a logical one along the track. The logical position\n * always runs from the minimum value at `0` to the maximum at `barWidth`, so in a right-to-left\n * layout, where the minimum sits on the right, the axis is mirrored. The result is clamped to the\n * track, so a fast drag that overshoots the edge still resolves to the nearest valid position\n * instead of dropping the update.\n * @param {number} physicalX Position in pixels from the left edge of the track.\n * @param {number} barWidth Width of the track in pixels.\n * @param {boolean} rtl Whether the layout is right-to-left.\n * @returns {number} Logical position in pixels.\n */\nexport const toLogicalX = (physicalX, barWidth, rtl) =>\n  Math.min(barWidth, Math.max(0, rtl ? barWidth - physicalX : physicalX));\n\n/**\n * Find the step closest to the given position along the track.\n * @param {number[]} positionList Pixel offset of each step, in ascending order.\n * @param {number} logicalX Logical position in pixels.\n * @returns {number} Index of the nearest step, or `-1` if there are no steps.\n */\nexport const findNearestStepIndex = (positionList, logicalX) => {\n  const fromIndex = positionList.findLastIndex((s) => s <= logicalX);\n  const toIndex = positionList.findIndex((s) => logicalX <= s);\n\n  if (fromIndex === -1) {\n    return toIndex;\n  }\n\n  if (toIndex === -1) {\n    return fromIndex;\n  }\n\n  const fromDiff = Math.abs(positionList[fromIndex] - logicalX);\n  const toDiff = Math.abs(positionList[toIndex] - logicalX);\n\n  return fromDiff < toDiff ? fromIndex : toIndex;\n};\n\n/**\n * Get the direction an arrow key moves the thumb in. The vertical keys don’t depend on the layout,\n * while the horizontal ones follow the visual direction of the track, so in a right-to-left layout\n * `ArrowLeft` increases the value.\n * @param {string} key The key pressed.\n * @param {boolean} rtl Whether the layout is right-to-left.\n * @returns {1 | -1 | 0} `1` to increase, `-1` to decrease, `0` if the key doesn’t move the thumb.\n */\nexport const getSliderKeyDirection = (key, rtl) => {\n  // Only the horizontal keys are mirrored; `ArrowUp` increases the value, unlike in a list\n  const { prevKey, nextKey } = getArrowKeys('horizontal', rtl);\n\n  if (key === 'ArrowUp' || key === nextKey) {\n    return 1;\n  }\n\n  if (key === 'ArrowDown' || key === prevKey) {\n    return -1;\n  }\n\n  return 0;\n};\n\n/**\n * Get the step index a key moves the thumb to, per the APG Slider pattern: the arrow keys move by\n * one step, Page Up/Down by a tenth of the range, and Home/End jump to either end.\n * @param {object} options Options.\n * @param {string} options.key The key pressed.\n * @param {boolean} options.rtl Whether the layout is right-to-left.\n * @param {number} options.currentIndex Index of the current step.\n * @param {number} options.length Number of steps.\n * @returns {number} Target index, clamped to the range, or `-1` if the key doesn’t move the thumb\n * or the thumb is already where the key would take it.\n */\nexport const getSliderKeyTargetIndex = ({ key, rtl, currentIndex, length }) => {\n  const lastIndex = length - 1;\n  const page = Math.max(1, Math.round(length / 10));\n  /** @type {number} */\n  let index;\n\n  if (key === 'Home') {\n    index = 0;\n  } else if (key === 'End') {\n    index = lastIndex;\n  } else if (key === 'PageUp') {\n    index = currentIndex + page;\n  } else if (key === 'PageDown') {\n    index = currentIndex - page;\n  } else {\n    const direction = getSliderKeyDirection(key, rtl);\n\n    if (!direction) {\n      return -1;\n    }\n\n    index = currentIndex + direction;\n  }\n\n  index = Math.min(lastIndex, Math.max(0, index));\n\n  return index === currentIndex ? -1 : index;\n};\n\n/**\n * Clamp the step a thumb of a multi-thumb slider moves to, so it stops one step short of the other\n * thumb instead of crossing or landing on it. A move that overshoots, like Home on the second thumb\n * or a fast drag past the other thumb, still brings the thumb as close as it can get.\n * @param {object} options Options.\n * @param {number} options.valueIndex Index of the thumb being moved, `0` or `1`.\n * @param {number} options.index Index of the step the thumb would move to.\n * @param {number[]} options.positionList Pixel offset of each step, in ascending order.\n * @param {number[]} options.sliderPositions Current position of each thumb, in pixels.\n * @returns {number} Index of the step the thumb can move to, or `-1` if there’s no room for it.\n */\nexport const clampThumbIndex = ({ valueIndex, index, positionList, sliderPositions }) => {\n  const otherIndex = findNearestStepIndex(positionList, sliderPositions[valueIndex === 0 ? 1 : 0]);\n\n  const clampedIndex =\n    valueIndex === 0 ? Math.min(index, otherIndex - 1) : Math.max(index, otherIndex + 1);\n\n  return clampedIndex < 0 || clampedIndex >= positionList.length ? -1 : clampedIndex;\n};\n\n/**\n * Get the step index a key press starts from. A value that sits between two steps, such as `55`\n * with a step of `10`, has no index of its own, so it starts from the step below when the key\n * increases the value and from the step above when it decreases it. That way the first press\n * moves the thumb to the adjacent step in the direction of the key.\n * @param {object} options Options.\n * @param {number[]} options.valueList Values of each step, in ascending order.\n * @param {number} options.value Current value.\n * @param {boolean} options.decreasing Whether the key decreases the value.\n * @returns {number} Index of the current step. It can be `-1` or `valueList.length` for a value\n * below the minimum or above the maximum, so any move brings it back into the range.\n */\nexport const getSliderCurrentIndex = ({ valueList, value, decreasing }) => {\n  const index = valueList.indexOf(value);\n\n  if (index !== -1) {\n    return index;\n  }\n\n  if (decreasing) {\n    const upperIndex = valueList.findIndex((v) => v > value);\n\n    return upperIndex === -1 ? valueList.length : upperIndex;\n  }\n\n  return valueList.findLastIndex((v) => v < value);\n};\n\n/**\n * Find the thumb of a multi-thumb slider closest to the given position, so a click on the track\n * moves that one. When both thumbs sit at the same spot, the second one is picked for a position\n * after it and the first one otherwise, so the click never has to cross the other thumb.\n * @param {number[]} sliderPositions Current position of each thumb, in pixels.\n * @param {number} logicalX Logical position in pixels.\n * @returns {number} Index of the nearest thumb, `0` or `1`.\n */\nexport const getNearestThumbIndex = (sliderPositions, logicalX) => {\n  const [position0, position1] = sliderPositions;\n  const diff0 = Math.abs(position0 - logicalX);\n  const diff1 = Math.abs(position1 - logicalX);\n\n  if (diff0 === diff1) {\n    return logicalX > position1 ? 1 : 0;\n  }\n\n  return diff1 < diff0 ? 1 : 0;\n};\n","<!--\n  @component\n  The equivalent of the HTML `<input type=\"range\">` element, but it comes with the multi-thumb\n  support.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range\n  @see https://w3c.github.io/aria/#slider\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/slider/\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/slider-multithumb/\n-->\n<script>\n  import { isRTL } from '@sveltia/i18n';\n  import { onMount, untrack } from 'svelte';\n  import { hasModifier } from '../../services/navigation.js';\n  import { startPointerDrag } from '../../services/pointer-drag.js';\n  import LabelAbove from '../util/label-above.svelte';\n  import {\n    clampThumbIndex,\n    findNearestStepIndex,\n    getNearestThumbIndex,\n    getSliderCurrentIndex,\n    getSliderKeyDirection,\n    getSliderKeyTargetIndex,\n    getSliderSteps,\n    toLogicalX,\n  } from './slider.js';\n\n  /**\n   * @import { ContainerProps, LabelAboveProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {number} [value] Current value.\n   * @property {number} [min] Minimum allowed value. An alias of the `aria-valuemin` attribute.\n   * @property {number} [max] Maximum allowed value. An alias of the `aria-valuemax` attribute.\n   * @property {string} [sliderLabel] `aria-label` on the slider. With `showLabelAbove`, it’s also\n   * shown above the slider, where it names a multi-thumb slider’s pair of thumbs as a group.\n   * @property {string} [ariaLabelledby] `aria-labelledby` on a single-thumb slider, for a visible\n   * label elsewhere on the page.\n   * @property {[number, number]} [values] Value list for a multi-thumb slider.\n   * @property {[string, string]} [sliderLabels] `aria-label` on a multi-thumb slider.\n   * @property {number} [step] Step option like `<input type=\"range\">`.\n   * @property {(string[] | number[])} [optionLabels] Visible labels on the slider. When there is\n   * one per step, the current one is also read out as the value (`aria-valuetext`).\n   * @property {boolean} [flex] Make the text input container flexible.\n   * @property {boolean} [readonly] Whether to make the widget read-only. An alias of the\n   * `aria-readonly` attribute.\n   * @property {boolean} [invalid] Whether to mark the widget invalid. An alias of the\n   * `aria-invalid` attribute.\n   * @property {(detail: { values?: number[], value?: number }) => void} [onChange] `change` event\n   * handler.\n   */\n\n  /**\n   * @type {LabelAboveProps & ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(0),\n    min = 0,\n    max = 100,\n    sliderLabel = '',\n    ariaLabelledby = undefined,\n    values = $bindable(undefined),\n    sliderLabels = undefined,\n    step = 1,\n    optionLabels = [],\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    invalid = false,\n    showLabelAbove = false,\n    children,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const multiThumb = $derived(Array.isArray(values));\n  const uid = $props.id();\n  const labelAbove = $derived(showLabelAbove ? sliderLabel : '');\n\n  /** @type {HTMLElement | undefined} */\n  let base = $state();\n  let barWidth = $state(0);\n  /** @type {number[]} */\n  let positionList = $state([]);\n  /** @type {number[]} */\n  let valueList = $state([]);\n\n  /**\n   * Get the text read out for a value, when the visible option labels line up with the steps.\n   * @param {number | undefined} _value Value.\n   * @returns {string | undefined} Matching label, if any.\n   */\n  const getValueText = (_value) => {\n    if (optionLabels.length !== valueList.length || _value === undefined) {\n      return undefined;\n    }\n\n    const index = valueList.indexOf(_value);\n\n    return index === -1 ? undefined : String(optionLabels[index]);\n  };\n  let startX = $state(0);\n  let startScreenX = $state(0);\n  // eslint-disable-next-line prefer-const\n  let sliderPositions = $state([0, 0]);\n  let targetValueIndex = $state(0);\n  /**\n   * Function to stop following the pointer in the middle of a drag.\n   * @type {(() => void) | undefined}\n   */\n  let stopDrag;\n\n  /**\n   * Set the value of a thumb, and fire the `change` event if it’s actually changed. This is only\n   * called for user actions, so the event doesn’t fire when the slider is mounted or resized.\n   * @param {number} valueIndex Index in the {@link values} array, `0` for a single-thumb slider.\n   * @param {number} newValue New value.\n   */\n  const setValue = (valueIndex, newValue) => {\n    const _values = /** @type {[number, number]} */ (values);\n\n    if ((multiThumb ? _values[valueIndex] : value) === newValue) {\n      return;\n    }\n\n    if (multiThumb) {\n      _values[valueIndex] = newValue;\n      values = [..._values];\n      onChange?.({ values });\n    } else {\n      value = newValue;\n      onChange?.({ value });\n    }\n  };\n\n  /**\n   * Move a thumb with mouse.\n   * @param {number} physicalX Physical X position in pixels from the left edge.\n   */\n  const moveThumb = (physicalX) => {\n    let index = findNearestStepIndex(positionList, toLogicalX(physicalX, barWidth, isRTL()));\n\n    // Stop at the other thumb rather than ignoring the move, so a fast drag past it still brings\n    // the thumb as close as it can get\n    if (multiThumb) {\n      index = clampThumbIndex({\n        valueIndex: targetValueIndex,\n        index,\n        positionList,\n        sliderPositions,\n      });\n    }\n\n    if (index === -1) {\n      return;\n    }\n\n    setValue(targetValueIndex, valueList[index]);\n  };\n\n  /**\n   * Handle the `keydown` event fired on the slider.\n   * @param {KeyboardEvent} event `keydown` event.\n   * @param {number} [valueIndex] Index in the {@link values} array to be used to get/set the value.\n   */\n  const onKeyDown = (event, valueIndex = 0) => {\n    const { key } = event;\n\n    if (disabled || readonly || hasModifier(event)) {\n      return;\n    }\n\n    const _value = multiThumb ? /** @type {[number, number]} */ (values)[valueIndex] : value;\n    const rtl = isRTL();\n\n    let index = getSliderKeyTargetIndex({\n      key,\n      rtl,\n      currentIndex: getSliderCurrentIndex({\n        valueList,\n        value: _value,\n        decreasing: key === 'PageDown' || getSliderKeyDirection(key, rtl) === -1,\n      }),\n      length: valueList.length,\n    });\n\n    if (index === -1) {\n      // Still swallow the key if it’s one of the slider’s, so Home/End don’t scroll the page\n      if (['Home', 'End', 'PageUp', 'PageDown'].includes(key)) {\n        event.preventDefault();\n      }\n\n      return;\n    }\n\n    event.preventDefault();\n    event.stopPropagation();\n\n    if (multiThumb) {\n      const targetValue = valueList[index];\n\n      // Stop at the other thumb rather than ignoring the key, so Home, End and the Page keys still\n      // bring the thumb as close as it can get\n      index = clampThumbIndex({ valueIndex, index, positionList, sliderPositions });\n\n      // Don’t move the thumb at all if the clamped step lies the other way, which can happen when\n      // the value sits between two steps\n      if (\n        index === -1 ||\n        Math.sign(valueList[index] - _value) !== Math.sign(targetValue - _value)\n      ) {\n        return;\n      }\n    }\n\n    setValue(valueIndex, valueList[index]);\n  };\n\n  /**\n   * Handle the `pointermove` event fired anywhere on the page while dragging.\n   * @param {PointerEvent} event `pointermove` event.\n   */\n  const onPointerMove = (event) => {\n    if (disabled || readonly) {\n      return;\n    }\n\n    event.preventDefault();\n    event.stopPropagation();\n\n    const screenDiff = event.screenX - startScreenX;\n    // Calculate new physical position from left edge\n    const physicalX = startX + screenDiff;\n\n    moveThumb(physicalX);\n  };\n\n  /**\n   * Handle the end of a drag.\n   * @param {PointerEvent} event `pointerup` or `pointercancel` event, or `pointermove` event of a\n   * mouse that no longer has the primary button held down.\n   */\n  const onDragEnd = (event) => {\n    stopDrag = undefined;\n\n    if (disabled || readonly) {\n      return;\n    }\n\n    event.stopPropagation();\n\n    // Handle a click on the bars, but not a drag ended by a mouse moved without the button held\n    if (\n      event.type !== 'pointermove' &&\n      /** @type {HTMLElement} */ (event.target).matches('.base-bar, .slider-bar')\n    ) {\n      const rect = /** @type {HTMLElement} */ (base).getBoundingClientRect();\n      // Get physical X position from left edge\n      const physicalX = event.clientX - rect.left;\n\n      moveThumb(physicalX);\n    }\n\n    // Reset everything\n    startX = 0;\n    startScreenX = 0;\n    targetValueIndex = 0;\n  };\n\n  /**\n   * Handle the `pointerdown` event fired on the slider.\n   * @param {PointerEvent} event `pointerdown` event.\n   * @param {number} [valueIndex] Index in the {@link values} array to be used to get/set the value.\n   * Omitted when the track is pressed, so the thumb nearest to the pointer is used.\n   */\n  const onPointerDown = (event, valueIndex) => {\n    if (disabled || readonly) {\n      return;\n    }\n\n    event.preventDefault();\n    event.stopPropagation();\n\n    const { clientX, screenX, target } = event;\n    const rect = /** @type {HTMLElement} */ (base).getBoundingClientRect();\n\n    // A pointer pressed while another one is dragging takes over\n    stopDrag?.();\n    // Store physical X position from left edge (same in LTR and RTL)\n    startX = clientX - rect.left;\n    startScreenX = screenX;\n    targetValueIndex =\n      valueIndex ??\n      (multiThumb\n        ? getNearestThumbIndex(sliderPositions, toLogicalX(startX, barWidth, isRTL()))\n        : 0);\n    stopDrag = startPointerDrag(/** @type {HTMLElement} */ (target), event, {\n      onMove: onPointerMove,\n      onEnd: onDragEnd,\n    });\n  };\n\n  /**\n   * Get the thumb position for a value. A value that doesn’t sit on a step, such as `55` with a\n   * step of `10`, is kept as is until the user moves the thumb, but drawn at the nearest step.\n   * @param {number} _value Value.\n   * @returns {number} Position in pixels.\n   */\n  const getPosition = (_value) => positionList[findNearestStepIndex(valueList, _value)] ?? 0;\n\n  /**\n   * Update the thumb positions when the value or the track is changed.\n   */\n  const updatePositions = () => {\n    if (multiThumb) {\n      const [value0, value1] = /** @type {[number, number]} */ (values);\n\n      sliderPositions[0] = getPosition(value0);\n      sliderPositions[1] = getPosition(value1);\n    } else {\n      sliderPositions[0] = getPosition(value);\n    }\n  };\n\n  /**\n   * Initialize the variables.\n   */\n  const init = () => {\n    // Only called once mounted, when the track is bound\n    /* v8 ignore next */\n    if (!base) {\n      return;\n    }\n\n    barWidth = base.clientWidth;\n    ({ valueList, positionList } = getSliderSteps({ min, max, step, barWidth }));\n    updatePositions();\n  };\n\n  onMount(() => {\n    const observer = new ResizeObserver(() => init());\n    const query = globalThis.matchMedia('(pointer: coarse)');\n\n    observer.observe(/** @type {HTMLElement} */ (base));\n    query.addEventListener('change', init);\n    init();\n\n    return () => {\n      observer.disconnect();\n      query.removeEventListener('change', init);\n      // Stop listening if the slider is removed in the middle of a drag\n      stopDrag?.();\n    };\n  });\n\n  $effect(() => {\n    void value;\n    void values;\n    updatePositions();\n  });\n\n  // The steps are worked out from the range, so they have to follow a change to it, or the keys,\n  // the thumbs and the drag would keep using the old range\n  $effect(() => {\n    void min;\n    void max;\n    void step;\n    untrack(init);\n  });\n</script>\n\n<svelte:body\n  onclick={() => {\n    stopDrag?.();\n    stopDrag = undefined;\n  }}\n/>\n\n<!-- A multi-thumb slider’s label above names the pair of thumbs, which have labels of their own -->\n<div\n  {...restProps}\n  role={labelAbove && multiThumb ? 'group' : 'none'}\n  aria-labelledby={labelAbove && multiThumb ? `${uid}-label` : undefined}\n  class=\"sui slider {className}\"\n  class:disabled\n  class:readonly\n  class:invalid\n  {hidden}\n>\n  {#if labelAbove}\n    <!-- A thumb is a `<div>`, which a label can’t point to -->\n    <LabelAbove\n      id=\"{uid}-label\"\n      label={labelAbove}\n      getTarget={() => base?.querySelector('[role=\"slider\"]')}\n    />\n  {/if}\n  <div bind:this={base} role=\"none\" class=\"base\" onpointerdown={(event) => onPointerDown(event)}>\n    <div role=\"none\" class=\"base-bar\"></div>\n    <div\n      class=\"slider-bar\"\n      style:inset-inline-start={`${multiThumb ? sliderPositions[0] : 0}px`}\n      style:width={`${multiThumb ? sliderPositions[1] - sliderPositions[0] : sliderPositions[0]}px`}\n    ></div>\n    <div\n      role=\"slider\"\n      tabindex={disabled ? -1 : 0}\n      aria-label={(multiThumb ? sliderLabels?.[0] : sliderLabel) || undefined}\n      aria-labelledby={multiThumb ? undefined : ariaLabelledby}\n      aria-hidden={hidden}\n      aria-disabled={disabled}\n      aria-readonly={readonly}\n      aria-invalid={invalid}\n      aria-valuemin={min}\n      aria-valuemax={max}\n      aria-valuenow={multiThumb ? values?.[0] : value}\n      aria-valuetext={getValueText(multiThumb ? values?.[0] : value)}\n      style:inset-inline-start={`${sliderPositions[0]}px`}\n      onpointerdown={(event) => onPointerDown(event, 0)}\n      onkeydown={(event) => onKeyDown(event, 0)}\n    ></div>\n    {#if multiThumb}\n      <div\n        role=\"slider\"\n        tabindex={disabled ? -1 : 0}\n        aria-label={sliderLabels?.[1] || undefined}\n        aria-hidden={hidden}\n        aria-disabled={disabled}\n        aria-readonly={readonly}\n        aria-invalid={invalid}\n        aria-valuemin={min}\n        aria-valuemax={max}\n        aria-valuenow={values?.[1]}\n        aria-valuetext={getValueText(values?.[1])}\n        style:inset-inline-start={`${sliderPositions[1]}px`}\n        onpointerdown={(event) => onPointerDown(event, 1)}\n        onkeydown={(event) => onKeyDown(event, 1)}\n      ></div>\n    {/if}\n    {#if optionLabels.length}\n      {#each optionLabels as label, index (`${index}-${label}`)}\n        <span\n          role=\"none\"\n          class=\"label\"\n          style:inset-inline-start=\"{(barWidth / (optionLabels.length - 1)) * index}px\"\n        >\n          {label}\n        </span>\n      {/each}\n    {/if}\n  </div>\n</div>\n\n<style>.slider {\n  position: relative;\n  display: inline-block;\n  margin: var(--sui-focus-ring-width);\n  padding: 4px 6px;\n  touch-action: none;\n}\n.slider:hover:where(:not(:has(:global(.label-above:hover)))) .base-bar {\n  background-color: var(--sui-hover-background-color);\n}\n.slider:active:where(:not(:has(:global(.label-above:active)))) .base-bar {\n  background-color: var(--sui-active-background-color);\n}\n.slider.readonly .base-bar, .slider.readonly:is(:hover, :active) .base-bar {\n  background-color: var(--sui-slider-background-color, var(--sui-secondary-background-color));\n}\n.slider.readonly .base,\n.slider.readonly [role=slider] {\n  cursor: default;\n}\n.slider.readonly:not(.invalid) .slider-bar {\n  background-color: var(--sui-readonly-accent-color);\n}\n.slider.readonly:not(.invalid) [role=slider] {\n  border-color: var(--sui-readonly-accent-color);\n}\n\n.base {\n  position: relative;\n  width: var(--sui-slider-base-width, 240px);\n  height: calc(var(--sui-checkbox-height) / 2);\n  cursor: pointer;\n}\n\n.base-bar {\n  border-width: 1px;\n  border-style: solid;\n  border-color: var(--sui-control-border-color);\n  border-radius: var(--sui-checkbox-height);\n  background-color: var(--sui-slider-background-color, var(--sui-secondary-background-color));\n  transition: all 200ms;\n  width: 100%;\n  height: 100%;\n}\n\n.slider-bar {\n  position: absolute;\n  top: 0;\n  height: calc(var(--sui-checkbox-height) / 2);\n  border-radius: var(--sui-checkbox-height);\n  background-color: var(--sui-primary-accent-color-light);\n}\n.invalid .slider-bar {\n  background-color: var(--sui-error-border-color);\n}\n\n[role=slider] {\n  position: absolute;\n  top: 0;\n  border: 3px solid var(--sui-primary-accent-color-light);\n  border-radius: var(--sui-checkbox-height);\n  width: calc(var(--sui-checkbox-height) - 2px);\n  height: calc(var(--sui-checkbox-height) - 2px);\n  background-color: var(--sui-primary-accent-color-inverted);\n  cursor: pointer;\n}\n[role=slider]::before {\n  content: \"\";\n  position: absolute;\n  inset: -4px;\n  border-radius: inherit;\n}\n[role=slider]:dir(ltr) {\n  transform: translate(calc((var(--sui-checkbox-height) / 2 - 1px) * -1), calc((var(--sui-checkbox-height) / 4 - 1px) * -1));\n}\n[role=slider]:dir(rtl) {\n  transform: translate(calc(var(--sui-checkbox-height) / 2 - 1px), calc((var(--sui-checkbox-height) / 4 - 1px) * -1));\n}\n.invalid [role=slider] {\n  border-color: var(--sui-error-border-color);\n}\n\n.label {\n  position: absolute;\n  top: calc(var(--sui-checkbox-height) / 2 + 8px);\n  font-size: var(--sui-font-size-x-small);\n}\n.label:dir(ltr) {\n  transform: translateX(-50%);\n}\n.label:dir(rtl) {\n  transform: translateX(50%);\n}</style>\n","<!--\n  @component\n  A variant of `<Checkbox>`, looking like a switch that can be often seen on mobile apps.\n  @see https://w3c.github.io/aria/#switch\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/switch/\n-->\n<script>\n  /**\n   * @import { ContainerProps, FormFieldStateProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [label] Text label displayed next to the switch.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & FormFieldStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    checked = $bindable(false),\n    label = undefined,\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    ariaLabel = undefined,\n    children,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<button\n  {...restProps}\n  role=\"switch\"\n  class=\"sui switch {className}\"\n  type=\"button\"\n  {hidden}\n  disabled={disabled || undefined}\n  aria-checked={checked}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-readonly={readonly}\n  aria-required={required}\n  aria-invalid={invalid}\n  aria-label={ariaLabel}\n  onclick={() => {\n    if (!disabled && !readonly) {\n      checked = !checked;\n      onChange?.(new CustomEvent('Change', { detail: { checked } }));\n    }\n  }}\n>\n  <span role=\"none\"></span>\n  {#if label}\n    {label}\n  {:else}\n    {@render children?.()}\n  {/if}\n</button>\n\n<style>button {\n  display: inline-flex;\n  align-items: center;\n  gap: 8px;\n  margin: var(--sui-focus-ring-width);\n  border-width: 0;\n  border-style: solid;\n  border-color: transparent;\n  padding: 0;\n  color: var(--sui-control-foreground-color);\n  background-color: transparent;\n  box-shadow: none;\n  font-family: var(--sui-control-font-family);\n  font-size: var(--sui-control-font-size);\n  line-height: var(--sui-control-line-height);\n  font-weight: var(--sui-font-weight-normal, normal);\n  text-align: start;\n  cursor: pointer;\n  -webkit-user-select: none;\n  user-select: none;\n}\nbutton[aria-invalid=true] span {\n  background-color: var(--sui-error-border-color) !important;\n}\nbutton:hover[aria-checked=false] span {\n  background-color: var(--sui-hover-background-color);\n}\nbutton:hover[aria-checked=true] span {\n  background-color: var(--sui-primary-accent-color-light);\n}\nbutton:active[aria-checked=false] span {\n  background-color: var(--sui-active-background-color);\n}\nbutton:active[aria-checked=true] span {\n  background-color: var(--sui-primary-accent-color-dark);\n}\nbutton:focus-visible {\n  outline: 0;\n}\nbutton:focus-visible span {\n  outline-color: var(--sui-focus-ring-color);\n}\nbutton[aria-checked=true] span {\n  background-color: var(--sui-primary-accent-color);\n  border-color: transparent;\n}\nbutton[aria-checked=true] span::before {\n  --translateX: var(--sui-checkbox-height) * 2 - var(--sui-checkbox-height);\n  border-color: var(--sui-primary-accent-color);\n  background-color: var(--sui-primary-accent-color-inverted);\n}\nbutton[aria-checked=true] span:dir(ltr)::before {\n  transform: translateX(calc(var(--translateX)));\n}\nbutton[aria-checked=true] span:dir(rtl)::before {\n  transform: translateX(calc((var(--translateX)) * -1));\n}\nbutton[aria-readonly=true] {\n  cursor: default;\n}\nbutton[aria-readonly=true][aria-checked=false] span, button[aria-readonly=true]:is(:hover, :active)[aria-checked=false] span {\n  background-color: var(--sui-control-background-color);\n}\nbutton[aria-readonly=true][aria-checked=true] span, button[aria-readonly=true]:is(:hover, :active)[aria-checked=true] span {\n  background-color: var(--sui-readonly-accent-color);\n}\nbutton[aria-readonly=true][aria-checked=true] span::before, button[aria-readonly=true]:is(:hover, :active)[aria-checked=true] span::before {\n  border-color: var(--sui-readonly-accent-color);\n  background-color: var(--sui-readonly-accent-color-inverted);\n}\n\nspan {\n  position: relative;\n  width: calc(var(--sui-checkbox-height) * 2);\n  height: var(--sui-checkbox-height);\n  padding: 0 2px;\n  display: inline-flex;\n  align-items: center;\n  border-width: 1.5px;\n  border-style: solid;\n  border-color: var(--sui-checkbox-border-color);\n  border-radius: var(--sui-checkbox-height);\n  background-color: var(--sui-control-background-color);\n  transition: all 200ms;\n}\nspan::before {\n  display: inline-block;\n  width: calc(var(--sui-checkbox-height) - 6px);\n  height: calc(var(--sui-checkbox-height) - 6px);\n  border-radius: var(--sui-checkbox-height);\n  background-color: var(--sui-checkbox-border-color);\n  transition: all 200ms;\n  content: \"\";\n}</style>\n","<!--\n  @component\n  The equivalent of the HTML `<td>` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td\n  @see https://w3c.github.io/aria/#cell\n-->\n<script>\n  import TablePart from './table-part.svelte';\n\n  /**\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ContainerProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<TablePart {...restProps} role=\"cell\" kind=\"table-cell\" />\n","<!--\n  @component\n  The equivalent of the HTML `<tr>` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr\n  @see https://w3c.github.io/aria/#row\n-->\n<script>\n  import TablePart from './table-part.svelte';\n\n  /**\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ContainerProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<TablePart {...restProps} role=\"row\" kind=\"table-row\" />\n","<!--\n  @component\n  The equivalent of the HTML `<table>` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table\n  @see https://w3c.github.io/aria/#table\n-->\n<script>\n  /**\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   */\n\n  /**\n   * @type {ContainerProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    ariaLabel = undefined,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div {...restProps} role=\"table\" class=\"sui table {className}\" aria-label={ariaLabel}>\n  {@render children?.()}\n</div>\n\n<style>.table {\n  display: table;\n  margin: var(--sui-focus-ring-width);\n  width: calc(100% - var(--sui-focus-ring-width) * 2);\n}\n.table.data {\n  border-collapse: collapse;\n}\n.table.data :global(:is(.table-col-header, .table-row-header, .table-cell)) {\n  border: 1px solid var(--sui-secondary-border-color);\n  padding: 8px 8px;\n}</style>\n","/**\n * Helpers behind `<TabList>`, kept apart from the component so they can be tested on their own.\n */\n\n/**\n * Get the inline style placing the selection indicator over the given tab.\n * @param {{ offsetTop: number, offsetLeft: number, offsetWidth: number, offsetHeight: number }}\n * tab The selected tab’s offset box, relative to the tab list.\n * @returns {string} CSS declarations for the indicator.\n */\nexport const getIndicatorStyle = ({ offsetTop, offsetLeft, offsetWidth, offsetHeight }) =>\n  Object.entries({\n    top: offsetTop,\n    left: offsetLeft,\n    width: offsetWidth,\n    height: offsetHeight,\n  })\n    .map(([key, value]) => `${key}: ${value}px`)\n    .join('; ');\n","<!--\n  @component\n  A tab list widget.\n  @see https://w3c.github.io/aria/#tablist\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/tabs/\n-->\n<script>\n  import { onMount } from 'svelte';\n  import { activateGroup } from '../../services/group.svelte.js';\n  import { getIndicatorStyle } from './tab-list.js';\n\n  /**\n   * @import { ContainerProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'horizontal' | 'vertical'} [orientation] Orientation of the widget. An alias of the\n   * `aria-orientation` attribute.\n   * @property {string} [name] The `data-name` attribute on the wrapper element.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    orientation = 'horizontal',\n    name = undefined,\n    ariaLabel = undefined,\n    children,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * A reference to the wrapper element.\n   * @type {HTMLElement | undefined}\n   */\n  let wrapper = $state();\n  /**\n   * The indicator’s CSS style.\n   * @type {string | undefined}\n   */\n  let indicatorStyle = $state();\n\n  /**\n   * Update the indicator position.\n   */\n  const updateIndicator = () => {\n    globalThis.requestAnimationFrame(() => {\n      const selected = /** @type {HTMLElement | null} */ (\n        wrapper?.querySelector('[role=\"tab\"][aria-selected=\"true\"]')\n      );\n\n      indicatorStyle = selected ? getIndicatorStyle(selected) : undefined;\n    });\n  };\n\n  onMount(() => {\n    const observer = new ResizeObserver(() => {\n      updateIndicator();\n    });\n\n    // A tab can also be selected from code through its `selected` prop, which doesn’t go through\n    // the `Change` event below\n    const selectionObserver = new MutationObserver(() => {\n      updateIndicator();\n    });\n\n    observer.observe(/** @type {HTMLElement} */ (wrapper));\n    selectionObserver.observe(/** @type {HTMLElement} */ (wrapper), {\n      subtree: true,\n      attributes: true,\n      attributeFilter: ['aria-selected'],\n    });\n\n    return () => {\n      observer.disconnect();\n      selectionObserver.disconnect();\n    };\n  });\n</script>\n\n<div\n  bind:this={wrapper}\n  {...restProps}\n  role=\"tablist\"\n  class=\"sui tab-list {className}\"\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-orientation={orientation}\n  aria-label={ariaLabel}\n  data-name={name || undefined}\n  onInitialized={() => {\n    updateIndicator();\n  }}\n  onChange={(/** @type {CustomEvent} */ event) => {\n    updateIndicator();\n    onChange?.(event);\n  }}\n  {@attach activateGroup()}\n>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    {@render children?.()}\n  </div>\n  <div role=\"none\" class=\"indicator\" style={indicatorStyle}></div>\n</div>\n\n<style>.tab-list {\n  flex: none;\n  position: relative;\n  display: flex;\n  align-items: center;\n  margin: var(--sui-tab-list-margin, var(--sui-focus-ring-width));\n  border-color: var(--sui-tab-list-border-color, var(--sui-control-border-color));\n  border-radius: var(--sui-tab-list-border-radius, 0);\n  background-color: var(--sui-tab-list-background-color, transparent);\n}\n.tab-list[aria-orientation=horizontal] {\n  gap: var(--sui-horizontal-tab-list-gap, var(--sui-tab-list-gap, 8px));\n  margin-block: var(--sui-horizontal-tab-list-margin-block, 0 32px);\n  margin-inline: var(--sui-horizontal-tab-list-margin-inline, 0);\n  border-block-width: var(--sui-horizontal-tab-list-border-block-width, 0 1px);\n  border-inline-width: var(--sui-horizontal-tab-list-border-inline-width, 0 0);\n  padding: var(--sui-horizontal-tab-list-padding, var(--sui-tab-list-padding, 0 16px));\n}\n.tab-list[aria-orientation=horizontal] :global(button) {\n  width: var(--sui-horizontal-tab-width, var(--sui-tab-width, auto));\n  height: var(--sui-horizontal-tab-height, var(--sui-tab-height, 100%));\n  justify-content: var(--sui-horizontal-tab-justify-content, center);\n}\n.tab-list[aria-orientation=horizontal] .indicator {\n  border-block-width: var(--sui-horizontal-tab-list-indicator-border-block-width, 0 2px);\n  border-inline-width: var(--sui-horizontal-tab-list-indicator-border-inline-width, 0 0);\n}\n.tab-list[aria-orientation=vertical] {\n  gap: var(--sui-vertical-tab-list-gap, var(--sui-tab-list-gap, 8px));\n  flex-direction: column;\n  margin-block: var(--sui-vertical-tab-list-margin-block, 0);\n  margin-inline: var(--sui-vertical-tab-list-margin-inline, 0 32px);\n  border-block-width: var(--sui-vertical-tab-list-border-block-width, 0 0);\n  border-inline-width: var(--sui-vertical-tab-list-border-inline-width, 0 1px);\n  padding: var(--sui-vertical-tab-list-padding, var(--sui-tab-list-padding, 8px 0));\n  width: var(--sui-vertical-tab-list-width, auto);\n}\n.tab-list[aria-orientation=vertical] :global(button) {\n  justify-content: var(--sui-vertical-tab-justify-content, flex-start);\n  padding-inline-end: 32px;\n  width: var(--sui-vertical-tab-width, var(--sui-tab-width, 100%));\n  height: var(--sui-vertical-tab-height, var(--sui-tab-height, auto));\n}\n.tab-list[aria-orientation=vertical] .indicator {\n  border-block-width: var(--sui-vertical-tab-list-indicator-border-block-width, 0 0);\n  border-inline-width: var(--sui-vertical-tab-list-indicator-border-inline-width, 0 2px);\n}\n.tab-list :global(button) {\n  position: relative;\n  z-index: 1;\n  border-color: transparent;\n  margin: 0 !important;\n  border-radius: var(--sui-tab-border-radius, 0);\n  font-family: var(--sui-tab-font-family, var(--sui-control-font-family, inherit));\n  font-size: var(--sui-tab-font-size, var(--sui-control-font-size, inherit));\n  font-weight: var(--sui-tab-font-weight, var(--sui-control-font-weight, var(--sui-font-weight-normal, normal)));\n}\n\n.inner {\n  display: contents;\n}\n\n.indicator {\n  position: absolute;\n  z-index: 0;\n  inset: auto;\n  border-radius: var(--sui-tab-list-indicator-border-radius, 0);\n  border-color: var(--sui-tab-list-indicator-border-color, var(--sui-primary-accent-color-light));\n  background-color: var(--sui-tab-list-indicator-background-color, transparent);\n  box-shadow: var(--sui-tab-list-indicator-box-shadow, none);\n  pointer-events: none;\n  transition: var(--sui-tab-list-indicator-transition, all 200ms);\n}</style>\n","<!--\n  @component\n  A tab content panel.\n  @see https://w3c.github.io/aria/#tabpanel\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/tabs/\n-->\n<script>\n  /**\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {ContainerProps & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div {...restProps} role=\"tabpanel\" class=\"sui tab-panel {className}\">\n  {@render children?.()}\n</div>\n\n<style>.tab-panel {\n  flex: auto;\n  transition: all 200ms;\n}\n.tab-panel[aria-hidden=true], .tab-panel:not([aria-hidden]) {\n  display: none;\n}</style>\n","<!--\n  @component\n  A tab widget.\n  @see https://w3c.github.io/aria/#tab\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/tabs/\n-->\n<script>\n  import Button from '../button/button.svelte';\n\n  /**\n   * @import { ButtonProps, CommonEventHandlers } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [selected] Whether to select the widget. An alias of the `aria-selected`\n   * attribute.\n   */\n\n  /**\n   * @type {ButtonProps & CommonEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    selected = false,\n    children: _children,\n    startIcon: _startIcon,\n    endIcon: _endIcon,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<Button\n  {...restProps}\n  role=\"tab\"\n  class=\"sui tab {className}\"\n  {hidden}\n  {disabled}\n  aria-selected={selected}\n>\n  {#snippet startIcon()}\n    {@render _startIcon?.()}\n  {/snippet}\n  <!-- eslint-disable-next-line svelte/no-useless-children-snippet -->\n  {#snippet children()}\n    {@render _children?.()}\n  {/snippet}\n  {#snippet endIcon()}\n    {@render _endIcon?.()}\n  {/snippet}\n</Button>\n","<!--\n  @component\n  Toast/snackbar notification. Use the Popover API if possible to acquire a non-modal top layer.\n  @see https://w3c.github.io/aria/#alert\n  @see https://developer.chrome.com/blog/introducing-popover-api/\n  @see https://github.com/whatwg/html/issues/9936\n-->\n<script module>\n  import { openModalDialogs } from '../util/modal.js';\n\n  /**\n   * Modal dialogs currently open, the topmost last. While a modal dialog is open, the rest of the\n   * document is inert, including a popover stacked on top of the dialog, so the toast base has to\n   * live inside the topmost dialog to stay interactive and be announced by screen readers.\n   * @type {HTMLDialogElement[]}\n   */\n  const modals = [];\n\n  /**\n   * Get the element the toast base should be placed in.\n   * @returns {HTMLElement} Topmost modal dialog, the app shell, or the `<body>`.\n   */\n  const getHost = () => {\n    // Drop the dialogs that have been closed or removed without us noticing\n    modals.splice(\n      0,\n      modals.length,\n      ...modals.filter((dialog) => dialog.isConnected && dialog.matches(':modal')),\n    );\n\n    return modals.at(-1) ?? document.querySelector('.sui.app-shell') ?? document.body;\n  };\n\n  /**\n   * Move the toast base to the top of the top layer if it has any toast, or close it otherwise.\n   * It has to be reopened, because a modal dialog opened after the base is stacked on top of it.\n   * @param {HTMLElement} base Toast base.\n   */\n  const raiseBase = (base) => {\n    // Skip if the browser doesn’t support the Popover API\n    /* v8 ignore next */\n    if (!base.showPopover) {\n      return;\n    }\n\n    if (base.matches(':popover-open')) {\n      base.hidePopover();\n    }\n\n    if (base.querySelector('.toast')) {\n      base.showPopover();\n    }\n  };\n\n  /**\n   * Move the toast base to the host returned by {@link getHost}, if it’s not there yet. Use\n   * `moveBefore()` where supported, so the base stays open and the focus stays in a toast.\n   * @param {HTMLElement} base Toast base.\n   * @returns {boolean} Whether the base has been moved.\n   */\n  const moveBase = (base) => {\n    const host = getHost();\n\n    if (base.parentElement === host) {\n      return false;\n    }\n\n    const { moveBefore } = /** @type {any} */ (host);\n\n    if (typeof moveBefore === 'function' && base.isConnected) {\n      moveBefore.call(host, base, null);\n    } else {\n      host.appendChild(base);\n    }\n\n    return true;\n  };\n\n  /**\n   * Get the lane in the toast base for the toasts at the given position, creating it if needed.\n   * The toasts at the same position are stacked in their lane rather than laid on top of each\n   * other.\n   * @param {HTMLElement} base Toast base.\n   * @param {string} position Toast position, e.g. `bottom-right`.\n   * @returns {HTMLElement} Lane.\n   */\n  const getLane = (base, position) => {\n    let lane = /** @type {HTMLElement[]} */ ([...base.children]).find(\n      (child) => child.dataset.position === position,\n    );\n\n    if (!lane) {\n      lane = document.createElement('div');\n      lane.setAttribute('role', 'none');\n      lane.className = `toast-lane ${position}`;\n      lane.dataset.position = position;\n      base.appendChild(lane);\n    }\n\n    return lane;\n  };\n\n  /**\n   * Toast base shared by all the toasts. It’s created by the first toast mounted and removed with\n   * the last one unmounted, rather than rendered by a component, so it doesn’t go away with the\n   * toast that happened to create it.\n   * @type {HTMLElement | undefined}\n   */\n  let base;\n  /**\n   * Number of the toasts currently mounted.\n   */\n  let mountCount = 0;\n\n  /**\n   * Move the base into a modal dialog that has just been opened.\n   * @param {Event} event `toggle` event.\n   */\n  const onToggle = (event) => {\n    const { target, newState } = /** @type {ToggleEvent} */ (event);\n\n    if (\n      base &&\n      target instanceof HTMLDialogElement &&\n      newState === 'open' &&\n      target.matches(':modal') &&\n      !modals.includes(target)\n    ) {\n      modals.push(target);\n      moveBase(base);\n      raiseBase(base);\n    }\n  };\n\n  /**\n   * Move the base out of a modal dialog that is being closed, before the dialog is possibly\n   * removed from the DOM tree along with the base. `beforetoggle` is fired synchronously when the\n   * dialog is closed; `close` is a fallback for browsers that don’t fire it on a dialog.\n   * @param {Event} event `beforetoggle` or `close` event.\n   */\n  const onClose = (event) => {\n    const { target } = event;\n\n    if (\n      !base ||\n      !(target instanceof HTMLDialogElement) ||\n      (event.type === 'beforetoggle' && /** @type {ToggleEvent} */ (event).newState !== 'closed')\n    ) {\n      return;\n    }\n\n    const index = modals.indexOf(target);\n\n    if (index > -1) {\n      modals.splice(index, 1);\n    }\n\n    if (target.contains(base) && moveBase(base) && !base.matches(':popover-open')) {\n      raiseBase(base);\n    }\n  };\n\n  /**\n   * Get the toast base, creating it if needed, and start keeping it in the topmost modal dialog.\n   * Call {@link releaseBase} once done.\n   * @returns {HTMLElement} Toast base.\n   */\n  const acquireBase = () => {\n    mountCount += 1;\n\n    if (!base) {\n      base = document.createElement('div');\n      base.setAttribute('role', 'none');\n      base.className = 'sui toast-base enabled';\n      base.popover = 'manual';\n\n      // The dialogs are in the document in no particular order, so put those shown by `<Modal>` in\n      // the order they were opened, on top of any others\n      const dialogs = [...document.querySelectorAll(/** @type {'dialog'} */ ('dialog:modal'))];\n\n      modals.push(\n        ...dialogs.filter((dialog) => !openModalDialogs.includes(dialog)),\n        ...openModalDialogs.filter((dialog) => dialogs.includes(dialog)),\n      );\n\n      // These events don’t bubble, so listen in the capture phase\n      document.addEventListener('toggle', onToggle, true);\n      document.addEventListener('beforetoggle', onClose, true);\n      document.addEventListener('close', onClose, true);\n    }\n\n    moveBase(base);\n\n    return base;\n  };\n\n  /**\n   * Release the toast base, removing it once no toast uses it.\n   */\n  const releaseBase = () => {\n    mountCount -= 1;\n\n    if (mountCount > 0 || !base) {\n      return;\n    }\n\n    document.removeEventListener('toggle', onToggle, true);\n    document.removeEventListener('beforetoggle', onClose, true);\n    document.removeEventListener('close', onClose, true);\n    base.remove();\n    base = undefined;\n    modals.length = 0;\n  };\n</script>\n\n<script>\n  import { onMount } from 'svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ToastPosition } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string | number} [id] The toast ID. If updated, the timer that hides\n   * the toast will be reset, meaning the same toast can be displayed for a longer period of time.\n   * @property {boolean} [show] Whether to show the toast.\n   * @property {number} [duration] Duration to automatically hide the toast. Use `0` or `Infinity`\n   * to hide it manually from the consumer. The countdown is held while the pointer is over the\n   * toast or the focus is inside it, and starts over once it leaves.\n   * @property {ToastPosition} [position] Position of the toast.\n   * @property {Snippet} [children] Primary slot content.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    show = $bindable(false),\n    id = undefined,\n    duration = 5000,\n    position = 'auto',\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * @type {HTMLElement | undefined}\n   */\n  let popover = $state();\n  /**\n   * @type {HTMLElement | undefined}\n   */\n  let toast = $state();\n  /**\n   * Whether the pointer is over the toast.\n   * @type {boolean}\n   */\n  let hovered = $state(false);\n  /**\n   * Whether the focus is inside the toast.\n   * @type {boolean}\n   */\n  let focused = $state(false);\n  /**\n   * Whether the pointer is over the toast or the focus is inside it. The auto-hide countdown is\n   * held while it is, so a toast with a control in it can’t vanish from under the user (WCAG\n   * 2.2.1). Both are tracked apart, so the pointer leaving doesn’t release the hold of the focus,\n   * or the other way around.\n   */\n  const held = $derived(hovered || focused);\n  /**\n   * Whether the content is in the DOM tree. It lags behind {@link show} on the way out, so the\n   * toast can fade before the content goes. On the way in, the content is inserted rather than\n   * unhidden: a live region is only announced when its content arrives.\n   * @type {boolean}\n   */\n  let rendered = $state(false);\n\n  /**\n   * The longest delay `setTimeout()` accepts, in milliseconds.\n   */\n  const MAX_TIMEOUT = 2_147_483_647;\n\n  onMount(() => {\n    popover = acquireBase();\n\n    return () => {\n      // eslint-disable-next-line svelte/no-dom-manipulating\n      toast?.remove();\n      releaseBase();\n    };\n  });\n\n  onMount(() => {\n    if (position !== 'auto') {\n      return undefined;\n    }\n\n    const mql = globalThis.matchMedia('(width < 1024px)');\n\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    const setMode = () => {\n      // In the RTL layout, a `bottom-right`-positioned toast is actually displayed in the\n      // bottom-left corner thanks to the `inset-inline-start/end` CSS properties\n      position = mql.matches ? 'bottom-center' : 'bottom-right';\n    };\n\n    setMode();\n    mql.addEventListener('change', setMode);\n\n    return () => {\n      mql.removeEventListener('change', setMode);\n    };\n  });\n\n  $effect(() => {\n    // Both are in place by the time the effect first runs; see `onMount()` above\n    /* v8 ignore next */\n    if (!popover || !toast) {\n      return;\n    }\n\n    // Keep the toast out of the base while it’s hidden, so faded-out toasts don’t pile up there\n    if (!rendered) {\n      // eslint-disable-next-line svelte/no-dom-manipulating\n      toast.remove();\n      // A detached element gets no `pointerleave` or `focusout`, so release the hold here, or the\n      // countdown would never start the next time the toast is shown\n      hovered = false;\n      focused = false;\n\n      // Close the base once the last toast is gone\n      if (!popover.querySelector('.toast') && popover.matches(':popover-open')) {\n        popover.hidePopover();\n      }\n\n      return;\n    }\n\n    // Make sure the base is in the topmost modal dialog, in case a dialog event has been missed\n    moveBase(popover);\n\n    // The newest toast goes next to the edge of the screen: last at the bottom, first at the top\n    const lane = getLane(popover, position);\n\n    if (position.startsWith('top-')) {\n      lane.prepend(toast);\n    } else {\n      lane.append(toast);\n    }\n\n    raiseBase(popover);\n  });\n\n  $effect(() => {\n    if (show) {\n      rendered = true;\n\n      return undefined;\n    }\n\n    // Matches the opacity transition below\n    const timer = globalThis.setTimeout(() => {\n      rendered = false;\n    }, 250);\n\n    return () => {\n      globalThis.clearTimeout(timer);\n    };\n  });\n\n  $effect(() => {\n    void id;\n    void show;\n    void duration;\n    void held;\n\n    // An infinite duration keeps the toast like `0` does: `setTimeout()` would take it as `0` and\n    // hide the toast at once\n    if (!show || !duration || !Number.isFinite(duration) || held) {\n      return undefined;\n    }\n\n    // `setTimeout()` fires at once when the delay is longer than its 32-bit maximum (about 24.8\n    // days), so cap it there\n    const timer = globalThis.setTimeout(\n      () => {\n        show = false;\n      },\n      Math.min(duration, MAX_TIMEOUT),\n    );\n\n    // Stop the countdown when any of the above changes, so the previous timer can’t fire, or when\n    // the toast is destroyed, or it would still hide the toast later\n    return () => {\n      globalThis.clearTimeout(timer);\n    };\n  });\n</script>\n\n<div\n  {...restProps}\n  bind:this={toast}\n  class={['sui', 'toast', position]}\n  aria-hidden={!show}\n  onpointerenter={() => {\n    hovered = true;\n  }}\n  onpointerleave={() => {\n    hovered = false;\n  }}\n  onfocusin={() => {\n    focused = true;\n  }}\n  onfocusout={(event) => {\n    focused = !!event.relatedTarget && !!toast?.contains(/** @type {Node} */ (event.relatedTarget));\n  }}\n>\n  {#if rendered}\n    {@render children?.()}\n  {/if}\n</div>\n\n<style>:global(.sui.toast-base) {\n  position: fixed;\n  inset: 16px;\n  z-index: 99999;\n  overflow: visible;\n  margin: 0;\n  border: 0;\n  padding: 0;\n  width: auto;\n  height: auto;\n  background-color: transparent;\n  font-family: var(--sui-font-family-default);\n  font-size: var(--sui-font-size-default);\n  font-weight: var(--sui-font-weight-normal, normal);\n  text-align: center;\n  pointer-events: none;\n  -webkit-user-select: none;\n  user-select: none;\n}\n\n:global(body:has(.sui.bottom-navigation:not([inert]:not([hidden])))) :global(.toast-base) {\n  bottom: calc(var(--sui-bottom-navigation-height) + 16px);\n}\n\n:global(.sui.toast-base) > :global(.toast-lane) {\n  position: absolute;\n  display: flex;\n  flex-direction: column;\n  margin-block: -4px;\n  max-width: 100%;\n}\n:global(.sui.toast-base) > :global(.toast-lane.top-left), :global(.sui.toast-base) > :global(.toast-lane.top-center), :global(.sui.toast-base) > :global(.toast-lane.top-right) {\n  inset-block-start: 0;\n}\n:global(.sui.toast-base) > :global(.toast-lane.bottom-left), :global(.sui.toast-base) > :global(.toast-lane.bottom-center), :global(.sui.toast-base) > :global(.toast-lane.bottom-right) {\n  inset-block-end: 0;\n}\n:global(.sui.toast-base) > :global(.toast-lane.top-left), :global(.sui.toast-base) > :global(.toast-lane.bottom-left) {\n  inset-inline-start: 0;\n  align-items: flex-start;\n}\n:global(.sui.toast-base) > :global(.toast-lane.top-center), :global(.sui.toast-base) > :global(.toast-lane.bottom-center) {\n  inset-inline: 0;\n  align-items: center;\n}\n:global(.sui.toast-base) > :global(.toast-lane.top-right), :global(.sui.toast-base) > :global(.toast-lane.bottom-right) {\n  inset-inline-end: 0;\n  align-items: flex-end;\n}\n\n.toast {\n  margin-block: 4px;\n  width: max-content;\n  max-width: 80dvw;\n  height: auto;\n  overflow: clip;\n  opacity: 1;\n  transition-duration: 250ms;\n  will-change: opacity;\n}\n@starting-style {\n  .toast {\n    opacity: 0;\n  }\n}\n.toast {\n  pointer-events: auto;\n}\n.toast[aria-hidden=true] {\n  display: block;\n  opacity: 0;\n  pointer-events: none;\n}\n@supports (interpolate-size: allow-keywords) {\n  .toast {\n    interpolate-size: allow-keywords;\n  }\n  @starting-style {\n    .toast {\n      margin-block: 0;\n      height: 0;\n    }\n  }\n  .toast[aria-hidden=true] {\n    margin-block: 0;\n    height: 0;\n  }\n}\n.toast:has(:global(.alert)) {\n  filter: drop-shadow(0 8px 8px var(--sui-popup-shadow-color));\n}</style>\n","/**\n * Conversion between the code and language a `<CodeEditor>` exposes and the Markdown fenced code\n * block the underlying editor works with.\n */\n\n/**\n * Wrap code in a Markdown fenced code block. Like Lexical, the fence is made longer than any\n * backtick run in the code, so a fence line within the code, like a fenced code block in Markdown,\n * doesn’t close the block.\n * @param {string} lang Language identifier, placed after the opening fence.\n * @param {string} code Code. If empty, the block has no content line at all.\n * @returns {string} Fenced code block.\n */\nexport const toCodeBlock = (lang, code) => {\n  // Not `Math.max(...runs)`, which would exceed the maximum number of arguments with many runs\n  const longestRun = (code.match(/`+/g) ?? []).reduce((max, run) => Math.max(max, run.length), 2);\n  const fence = '`'.repeat(longestRun + 1);\n\n  return code ? `${fence}${lang}\\n${code}\\n${fence}` : `${fence}${lang}\\n${fence}`;\n};\n\n/**\n * Take a Markdown fenced code block apart. The fence can be longer than three backticks, as Lexical\n * makes it when the code contains a fence line, and the closing fence has to be as long.\n * @param {string} markdown Fenced code block, as produced by {@link toCodeBlock}.\n * @returns {{ lang: string, code: string }} Language identifier, `plain` if the fence has none,\n * and the code, empty if the block has no content or `markdown` is not a code block at all.\n */\nexport const parseCodeBlock = (markdown) => {\n  const { lang = 'plain', code = '' } =\n    markdown.match(/^(?<fence>`{3,})(?<lang>[^\\s`]+)?\\n(?:(?<code>.*)\\n)?\\k<fence>(?!`)/s)\n      ?.groups ?? {};\n\n  return { lang, code };\n};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nfunction t(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),o=new URLSearchParams;o.append(\"code\",t);for(const t of e)o.append(\"v\",t);return n.search=o.toString(),new Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function e(e,...n){throw t(e,...n)}function n(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),o=new URLSearchParams;o.append(\"code\",t);for(const t of e)o.append(\"v\",t);n.search=o.toString(),console.warn(`Minified Lexical warning #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function o(){return\"undefined\"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement}const r=/* @__PURE__ */o();function i(){return r&&\"documentMode\"in document?document.documentMode:null}const s=/* @__PURE__ */i();function l(t){return r&&t.test(navigator.platform)}function c(t){return r&&t.test(navigator.userAgent)}const a=/* @__PURE__ */l(/Mac|iPod|iPhone|iPad/),u=/* @__PURE__ */c(/^(?!.*Seamonkey)(?=.*Firefox).*/i);function f(){return!(!r||!(\"InputEvent\"in window)||s)&&\"getTargetRanges\"in new window.InputEvent(\"input\")}const d=/* @__PURE__ */f();function h(){return r&&!window.MSStream&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||/Macintosh/.test(navigator.userAgent)&&navigator.maxTouchPoints>1)}const g=/* @__PURE__ */h(),_=/* @__PURE__ */c(/Android/),p=/* @__PURE__ */c(/Version\\/[\\d.]+.*Safari/)&&!_,y=/* @__PURE__ */c(/^(?=.*Chrome).*/i),m=r&&_&&y,x=/* @__PURE__ */c(/AppleWebKit\\/[\\d.]+/)&&a&&!y,v=1,S=2,C=4,b=8,k=16,T=32,N=64,w=128;function E(){return 2047}const A=/* @__PURE__ */E(),O=p||g||x?\"\\xa0\":\"\\u200b\",M=\"\\n\\n\",D=u?\"\\xa0\":O,P=\"\\u0591-\\u07ff\\ufb1d-\\ufdfd\\ufe70-\\ufefc\",F=\"A-Za-z\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02b8\\u0300-\\u0590\\u0800-\\u1fff\\u200e\\u2c00-\\ufb1c\\ufe00-\\ufe6f\\ufefd-\\uffff\";function I(t,e){return new RegExp(\"^[^\"+t+\"]*[\"+e+\"]\")}const L=/* @__PURE__ */I(F,P),K=/* @__PURE__ */I(P,F),z={bold:1,capitalize:1024,code:16,highlight:128,italic:2,lowercase:256,strikethrough:4,subscript:32,superscript:64,underline:8,uppercase:512},B={directionless:1,unmergeable:2},R={center:2,end:6,justify:4,left:1,right:3,start:5};function W(t){const e={};for(const n of Object.keys(t))e[t[n]]=n;return e}const j=/* @__PURE__ */W(R),$={normal:0,segmented:2,token:1},U=/* @__PURE__ */W($),J=\"$\",V=Symbol.for(\"@lexical/ctrlOrOtherKey\"),H=\"$config\";\n/*@__INLINE__*/\nfunction q(t){return()=>{}}function Y(t){return{type:t}}const X=/* @__PURE__ */Y(\"SELECTION_CHANGE_COMMAND\"),G=/* @__PURE__ */Y(\"SELECTION_INSERT_CLIPBOARD_NODES_COMMAND\"),Q=/* @__PURE__ */Y(\"CLICK_COMMAND\"),Z=/* @__PURE__ */Y(\"BEFORE_INPUT_COMMAND\"),tt=/* @__PURE__ */Y(\"INPUT_COMMAND\"),et=/* @__PURE__ */Y(\"COMPOSITION_START_COMMAND\"),nt=/* @__PURE__ */Y(\"COMPOSITION_END_COMMAND\"),ot=/* @__PURE__ */Y(\"DELETE_CHARACTER_COMMAND\"),rt=/* @__PURE__ */Y(\"INSERT_LINE_BREAK_COMMAND\"),it=/* @__PURE__ */Y(\"INSERT_PARAGRAPH_COMMAND\"),st=/* @__PURE__ */Y(\"CONTROLLED_TEXT_INSERTION_COMMAND\"),lt=/* @__PURE__ */Y(\"PASTE_COMMAND\"),ct=/* @__PURE__ */Y(\"REMOVE_TEXT_COMMAND\"),at=/* @__PURE__ */Y(\"DELETE_WORD_COMMAND\"),ut=/* @__PURE__ */Y(\"DELETE_LINE_COMMAND\"),ft=/* @__PURE__ */Y(\"FORMAT_TEXT_COMMAND\"),dt=/* @__PURE__ */Y(\"SET_TEXT_FORMAT_COMMAND\"),ht=/* @__PURE__ */Y(\"UNDO_COMMAND\"),gt=/* @__PURE__ */Y(\"REDO_COMMAND\"),_t=/* @__PURE__ */Y(\"KEYDOWN_COMMAND\"),pt=/* @__PURE__ */Y(\"KEY_ARROW_RIGHT_COMMAND\"),yt=/* @__PURE__ */Y(\"MOVE_TO_END\"),mt=/* @__PURE__ */Y(\"KEY_ARROW_LEFT_COMMAND\"),xt=/* @__PURE__ */Y(\"MOVE_TO_START\"),vt=/* @__PURE__ */Y(\"KEY_ARROW_UP_COMMAND\"),St=/* @__PURE__ */Y(\"KEY_ARROW_DOWN_COMMAND\"),Ct=/* @__PURE__ */Y(\"KEY_ENTER_COMMAND\"),bt=/* @__PURE__ */Y(\"KEY_SPACE_COMMAND\"),kt=/* @__PURE__ */Y(\"KEY_BACKSPACE_COMMAND\"),Tt=/* @__PURE__ */Y(\"KEY_ESCAPE_COMMAND\"),Nt=/* @__PURE__ */Y(\"KEY_DELETE_COMMAND\"),wt=/* @__PURE__ */Y(\"KEY_TAB_COMMAND\"),Et=/* @__PURE__ */Y(\"INSERT_TAB_COMMAND\"),At=/* @__PURE__ */Y(\"INDENT_CONTENT_COMMAND\"),Ot=/* @__PURE__ */Y(\"OUTDENT_CONTENT_COMMAND\"),Mt=/* @__PURE__ */Y(\"DROP_COMMAND\"),Dt=/* @__PURE__ */Y(\"FORMAT_ELEMENT_COMMAND\"),Pt=/* @__PURE__ */Y(\"DRAGSTART_COMMAND\"),Ft=/* @__PURE__ */Y(\"DRAGOVER_COMMAND\"),It=/* @__PURE__ */Y(\"DRAGEND_COMMAND\"),Lt=/* @__PURE__ */Y(\"COPY_COMMAND\"),Kt=/* @__PURE__ */Y(\"CUT_COMMAND\"),zt=/* @__PURE__ */Y(\"SELECT_ALL_COMMAND\"),Bt=/* @__PURE__ */Y(\"CLEAR_EDITOR_COMMAND\"),Rt=/* @__PURE__ */Y(\"CLEAR_HISTORY_COMMAND\"),Wt=/* @__PURE__ */Y(\"CAN_REDO_COMMAND\"),jt=/* @__PURE__ */Y(\"CAN_UNDO_COMMAND\"),$t=/* @__PURE__ */Y(\"FOCUS_COMMAND\"),Ut=/* @__PURE__ */Y(\"BLUR_COMMAND\"),Jt=/* @__PURE__ */Y(\"KEY_MODIFIER_COMMAND\");function Vt(t,e){return{...e,[V]:t}}const Ht=/* @__PURE__ */Vt(\"metaKey\",{ctrlKey:!a,metaKey:a}),qt=/* @__PURE__ */Vt(\"altKey\",{altKey:a,ctrlKey:!a}),Yt=[[\"altKey\",1],[\"ctrlKey\",2],[\"metaKey\",4],[\"shiftKey\",8]];function Xt(t,e,n){const o=t.get(e);o?o.push(n):t.set(e,[n])}class Gt{byKey=(()=>new Map)();byCode=(()=>new Map)();add(t){const{key:n,modifiers:o={}}=t;n.length>0||e(399);const r=n.toLowerCase();for(const e of function(t){let e=[0];for(const[n,o]of Yt){const r=t[n]||!1;\"any\"===r?e=e.concat(e.map(t=>t|o)):r&&(e=e.map(t=>t|o))}return e}(o))Xt(this.byKey,`${e}:${r}`,t),1===n.length&&(/[0-9]/.test(n)?Xt(this.byCode,`${e}:Digit${n}`,t):/[a-z]/.test(r)&&Xt(this.byCode,`${e}:Key${r.toUpperCase()}`,t));return this}matches(t){const e=t.key;if(!e)return[];const n=function(t){let e=0;for(const[n,o]of Yt)t[n]&&(e|=o);return e}(t),o=this.byKey.get(`${n}:${e.toLowerCase()}`),r=o?o.slice():[];if(this.byCode.size>0&&!(1===e.length&&e.charCodeAt(0)<=127)){const e=this.byCode.get(`${n}:${t.code}`);e&&r.push(...e)}return r}match(t){return this.matches(t)[0]}}function Qt(t){const e=new Gt;for(const n of t)e.add(n);return e}function Zt(t){const e=new Map;return{dispose(){for(const t of e.values())t.dispose();e.clear()},register(n,o){let r=e.get(n);void 0===r&&(r={dispose:t(n,o),holders:new Set},e.set(n,r));const i=()=>{const t=e.get(n);t&&t.holders.delete(i)&&0===t.holders.size&&(e.delete(n),t.dispose())};return r.holders.add(i),i}}}function te(){let t;try{t=\"0.53.0+prod.esm\"}catch{}return t??'\"<unknown>+source\"'}const ee=/* @__PURE__ */te();class ne{_front=(()=>new Set)();_back=(()=>new Set)();_cache;get size(){return this._front.size+this._back.size}addBack(t){return delete this._cache,this._front.has(t)||this._back.add(t),this}addFront(t){return delete this._cache,this._back.has(t)||this._front.add(t),this}delete(t){return delete this._cache,this._front.delete(t)||this._back.delete(t)}toArray(){const t=Array.from(this._front).reverse();for(const e of this._back)t.push(e);return t}toReadonlyArray(){return this._cache=this._cache||this.toArray(),this._cache}[Symbol.iterator](){return this.toReadonlyArray()[Symbol.iterator]()}}const oe=null;function re(t,e=1e3){return t instanceof ie?t.clone():t.size<e?new Map(t):(new ie).init(new Map(t),void 0,t.size)}class ie{_mutable=!1;_old=void 0;_nursery=void 0;_size=0;clone(){return this._mutable=!1,(new ie).init(this._old,this._nursery,this._size)}init(t,e,n){return this._old=t,this._nursery=e,this._size=n,this}get size(){return this._size}has(t){return void 0!==this.get(t)}getWithTombstone(t){const e=this._nursery&&this._nursery.get(t);return void 0!==e?e:this._old&&this._old.get(t)}get(t){const e=this.getWithTombstone(t);return e===oe?void 0:e}shouldCompact(){return void 0!==this._nursery&&2*this._nursery.size>this._size}getNursery(){return this._mutable&&this._nursery||(this.compact(),this._nursery=new Map(this._nursery),this._mutable=!0),this._nursery}compact(t=!1){if(this._nursery&&this._nursery.size>0&&(t||this.shouldCompact())){const t=new Map(this._old);for(const[e,n]of this._nursery)n!==oe?t.set(e,n):t.delete(e);this._old=t,this._nursery=void 0}return this._mutable=!1,this}set(t,e){const n=this.getWithTombstone(t);if(n===e)return this;const o=this.getNursery();return n!==oe&&void 0!==n||(this._size++,n===oe&&o.delete(t)),o.set(t,e),this}delete(t){const e=this.has(t);return e&&(this.getNursery().set(t,oe),this._size--),e}getOrInsert(t,e){const n=this.get(t);return void 0!==n?n:(this.set(t,e),e)}getOrInsertComputed(t,e){const n=this.get(t);if(void 0!==n)return n;const o=e(t);return this.set(t,o),o}clear(){this._mutable=!1,this._old=void 0,this._nursery=void 0,this._size=0}*keys(){for(const t of this.entries())yield t[0]}*values(){for(const t of this.entries())yield t[1]}*entries(){const t=this._nursery,e=this._old;if(t){if(e)for(const n of e){const e=n[0],o=t.get(e);o!==oe&&(void 0!==o&&(n[1]=o),yield n)}for(const n of t)n[1]===oe||e&&e.has(n[0])||(yield n)}else e&&(yield*e)}forEach(t,e){void 0!==e&&(t=t.bind(e));for(const[e,n]of this.entries())t(n,e,this)}get[Symbol.toStringTag](){return\"GenMap\"}[Symbol.iterator](){return this.entries()}}let se=!1;function le(t,n,...o){const r=se;let i;try{se=t,i=n()}finally{se=r}var s;return null===(s=i)||\"object\"!=typeof s&&\"function\"!=typeof s||\"function\"!=typeof s.then||e(421),i}function ce(){return se}function ae(t){const n=t.exportJSON(se),o=t.constructor;return n.type!==o.getType()&&e(130,o.name),ni(t)&&!Array.isArray(n.children)&&e(59,o.name),n}function ue(){return mc()._blockCursorElement}function fe(t){return null!==t&&1===t.nodeType&&t.hasAttribute(\"data-lexical-slot\")}const de=x||g||p;function he(){const t=Yl().createElement(\"img\");t.setAttribute(\"data-lexical-decorator-boundary\",\"true\"),t.alt=\"\";for(const[e,n]of[[\"position\",\"absolute\"],[\"width\",\"0px\"],[\"height\",\"0px\"],[\"border\",\"0px\"],[\"margin\",\"0px\"],[\"padding\",\"0px\"]])t.style.setProperty(e,n,\"important\");return t}function ge(t){return null!==t&&1===t.nodeType&&t.hasAttribute(\"data-lexical-decorator-boundary\")}class _e{element;before;after;constructor(t,e,n){this.element=t,this.before=e||null,this.after=n||null}withBefore(t){return new _e(this.element,t,this.after)}withAfter(t){return new _e(this.element,this.before,t)}withElement(t){return this.element===t?this:new _e(t,this.before,this.after)}insertChild(t){const n=this.getInsertionAnchor();return null!==n&&n.parentElement!==this.element&&e(357),this.element.insertBefore(t,n),this}removeChild(t){return t.parentElement!==this.element&&e(358),this.element.removeChild(t),this}replaceChild(t,n){return n.parentElement!==this.element&&e(359),this.element.replaceChild(t,n),this}getFirstChild(){const t=this.getFirstChildAnchor(),e=t?t.nextSibling:this.element.firstChild;return e===this.getInsertionAnchor()?null:e}getFirstChildAnchor(){return this.after}resolveLeafPosition(t,e,n){if(this.element===t)return e===t&&0===n?\"before\":\"after\";const o=pe(t,this.element);if(null===o)return\"after\";const r=Array.prototype.indexOf.call(t.childNodes,o);if(r<0)return\"after\";if(e===t)return n<=r?\"before\":\"after\";const i=pe(t,e);if(null===i)return\"after\";const s=Array.prototype.indexOf.call(t.childNodes,i);return s>=0&&s<=r?\"before\":\"after\"}getInsertionAnchor(){return this.before}}function pe(t,e){let n=e;for(;null!==n&&n.parentNode!==t;)n=n.parentNode;return n}class ye extends _e{withBefore(t){return new ye(this.element,t,this.after)}withAfter(t){return new ye(this.element,this.before,t)}withElement(t){return this.element===t?this:new ye(t,this.before,this.after)}getInsertionAnchor(){return super.getInsertionAnchor()||this.getManagedLineBreak()||this.getDecoratorBoundaryAnchor(\"trailing\")}getFirstChildAnchor(){let t=super.getFirstChildAnchor(),e=t?t.nextSibling:this.element.firstChild;for(;fe(e);)t=e,e=e.nextSibling;ge(e)&&(t=e,e=e.nextSibling);const n=t?t.nextSibling:this.element.firstChild;return null!==n&&n===ue()?n:t}getDecoratorBoundaryAnchor(t){let e;if(\"leading\"===t){const t=super.getFirstChildAnchor();for(e=t?t.nextSibling:this.element.firstChild;fe(e);)e=e.nextSibling}else e=this.before?this.before.previousSibling:this.element.lastChild,null!==e&&e===ue()&&(e=e.previousSibling);return ge(e)?e:null}setDecoratorBoundaryAnchor(t,e){const n=this.getDecoratorBoundaryAnchor(t);if(e!==(null!==n))if(null!==n)this.element.removeChild(n);else if(\"leading\"===t){const t=this.getFirstChildAnchor();this.element.insertBefore(he(),t?t.nextSibling:this.element.firstChild)}else this.element.insertBefore(he(),this.before)}getManagedLineBreak(){return this.element.__lexicalLineBreak||null}setManagedLineBreak(t){const e=this.element,n=null===this.after?e.firstChild:this.after.nextSibling,o=\"empty\"===t&&fe(n)?null:t;if(e.__lexicalLastChildKind!==o)if(e.__lexicalLastChildKind=o,null===o)this.removeManagedLineBreak();else{const t=\"decorator\"===o&&de;this.insertManagedLineBreak(t)}}removeManagedLineBreak(){const t=this.element,e=this.getManagedLineBreak();if(e){e.remove();for(const e of t.querySelectorAll(\":scope > [data-lexical-managed-linebreak]\"))e.remove();t.__lexicalLineBreak=void 0}}insertManagedLineBreak(t){const e=this.element,n=this.getManagedLineBreak();if(n){const o=t?n.nextSibling:n;if(o&&o===e.querySelector(\":scope > br[data-lexical-managed-linebreak]\"))return;this.removeManagedLineBreak()}const o=this.before||this.getDecoratorBoundaryAnchor(\"trailing\"),r=Yl().createElement(\"br\");if(r.setAttribute(\"data-lexical-managed-linebreak\",\"true\"),e.insertBefore(r,o),t){const t=Yl().createElement(\"img\");t.setAttribute(\"data-lexical-managed-linebreak\",\"true\"),t.style.setProperty(\"display\",\"inline\",\"important\"),t.style.setProperty(\"border\",\"0px\",\"important\"),t.style.setProperty(\"margin\",\"0px\",\"important\"),t.alt=\"\",e.insertBefore(t,r),e.__lexicalLineBreak=t}else e.__lexicalLineBreak=r}getFirstChildOffset(){const t=this.getFirstChild(),e=this.getInsertionAnchor();let n=0;for(let o=this.element.firstChild;null!==o&&o!==t&&o!==e;o=o.nextSibling)n++;return n}resolveChildIndex(t,e,n,o){if(n===this.element){const e=this.getFirstChildOffset(),n=ue(),r=this.element.childNodes,i=Math.min(o,r.length);let s=0;for(let t=e;t<i;t++)r[t]!==n&&s++;return[t,Math.min(s,t.getChildrenSize())]}const r=me(e,n);r.push(o);const i=me(e,this.element);let s=t.getIndexWithinParent();for(let t=0;t<i.length;t++){const e=r[t],n=i[t];if(void 0===e||e<n)break;if(e>n){s+=1;break}}return[t.getParentOrThrow(),s]}}function me(t,n){const o=[];let r=n;for(;r!==t&&null!==r;r=r.parentNode){let t=0;for(let e=r.previousSibling;null!==e;e=e.previousSibling)t++;o.push(t)}return r!==t&&e(225),o.reverse()}let xe=!1,ve=0;function Se(){ve=performance.now()}function Ce(t){return uc(t)&&t.hasAttribute(\"data-lexical-managed-linebreak\")}function be(t,e,n){const o=jl(Ml(n)),r=o&&Ql(o,n._rootElement);let i=null,s=null;null!==r&&r.anchorNode===t&&(i=r.anchorOffset,s=r.focusOffset);const l=t.nodeValue;null!==l&&rl(e,l,i,s,!1)}function ke(t,e,n){if(Xf(t)){const e=t.anchor.getNode();if(e.is(n)&&t.format!==e.getFormat())return!1}return ws(e)&&n.isAttached()}function Te(t,e,n){for(let o=t;o&&!Fc(o);o=Cl(o)){const t=js(o,e);if(void 0!==t){const e=Bs(t,n);if(e)return ii(e)||!uc(o)?void 0:[o,e]}}}function Ne(t,e,n,o){xe=!0;const r=null===t._inputState.unprocessedBeforeInputData&&performance.now()-ve>100;try{Wu(t,()=>{const i=Od()||function(t){return t.read(\"latest\",()=>{const t=Od();return null!==t?t.clone():null})}(t),s=new Map,l=t._editorState,c=t._blockCursorElement;let a=!1,f=\"\";for(const n of e){const e=n.type,d=n.target,h=Te(d,t,l);if(!h)continue;const[g,_]=h;if(\"characterData\"===e)o?Mi(_)&&_.isAttached()&&_.markDirty():r&&Mi(_)&&ws(d)&&ke(i,d,_)&&be(d,_,t);else{a=!0;for(const e of n.addedNodes){const n=js(e,t);if(e!==c&&e.parentNode===d&&(n?t.getElementByKey(n)!==e:!(t._slotsUsed&&uc(e)&&e.hasAttribute(\"data-lexical-slot\")||Fc(e)))){if(u){const t=(uc(e)?e.innerText:null)||e.nodeValue;t&&(f+=t)}d.removeChild(e)}}for(const t of n.removedNodes){const e=c===t;if(e||ge(t)||Ce(t)){const e=n.nextSibling,o=n.previousSibling;d.insertBefore(t,e&&e.parentNode!==d?o?o.parentNode===d?o.nextSibling:null:d.firstChild:e)}e||s.set(g,_)}}}for(const[e,n]of s)n.reconcileObservedMutation(e,t);const d=n.takeRecords();for(const e of d)for(const n of e.addedNodes)\"BR\"!==n.nodeName||js(n,t)||Ce(n)||n.remove();n.takeRecords(),null!==i&&(a&&Ys(i),u&&xl(t)&&i.insertRawText(f))})}finally{xe=!1}}function we(t,e,n){const o=t._observer;if(null!==o){const r=o.takeRecords();(!n||r.length>0)&&Ne(t,r,o,e)}}function Ee(t){!function(t){Ml(t).addEventListener(\"textInput\",Se,!0)}(t),t._observer=new MutationObserver((e,n)=>{Ne(t,e,n)})}function Ae(t,e,n){const{isEqual:o}=t;return e===n||void 0!==o&&o(e,n)}function Oe(t,e){return Ae(t,e,t.defaultValue)}function Me(t){return\"object\"==typeof t&&null!==t}function De(t,n){const o=Ke(t,n).getter;return Me(o)&&void 0!==o.getterTable||e(405,n),Le(o.getterTable)}function Pe(t,n){const o=Ke(t,n).setter;return Me(o)&&void 0!==o.setterTable||e(406,n),Le(o.setterTable)}function Fe(t,n,o){let{meta:r}=Ke(t,n);for(let t=0;;)if(\"aliased\"===r.kind){if(t===o)return Le(r.aliases);t++,r=r.inner.meta}else\"nullable\"===r.kind||\"optional\"===r.kind?r=r.inner.meta:\"array\"===r.kind?r=r.item.meta:e(407,n,String(o))}function Ie(t,n){const o=Ke(t,n),{setter:r}=o;Me(r)&&void 0!==r.setterTable||e(408,n);const i=String(o.defaultValue);return Ge(r.setterTable,i)||e(409,n,i),r.setterTable[i]}function Le(t){return Object.assign(Object.create(null),t)}function Ke(t,n){const o=t.get(n);return void 0===o&&e(410,n),o}function ze(t,e,n,o,r){void 0!==r&&Be.add(r);const i=void 0===n,s=i?t(void 0):n;return i&&$e(s),Object.assign(t,{accepts:r,defaultValue:s,isEqual:o,meta:e})}const Be=new WeakSet;function Re(t){const{accepts:e}=t;return void 0===e||Be.has(e)?void 0:e}const We=new WeakSet;function je(t){return null!==t&&\"object\"==typeof t&&We.add(t),t}function $e(t){if(null!==t&&\"object\"==typeof t&&!Object.isFrozen(t)&&!We.has(t)){Object.freeze(t);for(const e of Object.values(t))$e(e)}}function Ue(t){const{isEqual:e}=t;return void 0===e?void 0:(t,n)=>null==t||null==n?t===n:e(t,n)}function Je(t,e){return n=>e(n)||Ve(t,n)}function Ve(t,e){const{accepts:n}=t;return void 0!==n?n.call(t,e):void 0!==function(t,e){const{accepts:n}=t;if(void 0!==n)return Ve(t,e)?{parsed:t(e)}:void 0;const o=t(e);return Oe(t,o)&&e!==t.defaultValue?void 0:{parsed:o}}(t,e)}const He=new WeakMap;function qe(t){const e=He.get(t);if(void 0!==e)return e;const n=function(t){const e=t.meta;if(null==e)return!1;if(void 0!==Re(t))return!1;switch(e.kind){case\"raw\":return!0;case\"union\":return null!=e.members&&e.members.length>0&&e.members.every(t=>qe(t));case\"nullable\":case\"optional\":case\"transform\":case\"aliased\":return null!=e.inner&&qe(e.inner);default:return!1}}(t);return He.set(t,n),n}function Ye(t,e){const n=t.meta;if(null==n)return Ve(t,e)?1:4;const o=Re(t),r=void 0!==o;if(r&&!o.call(t,e))return 4;const i=function(t,e,n,o){switch(e.kind){case\"raw\":return o?1:2;case\"array\":{if(!Array.isArray(n))return 4;if(null==e.item)return 1;let t=1;for(let o=0;o<n.length;o++)if(void 0!==n[o]){const r=Ye(e.item,n[o]);r>t&&(t=r)}return t>=3?3:t}case\"object\":{const t=e.fields;if(!Qe(n))return 4;if(null==t)return 1;if(!o&&Ze(n,t))return 4;let r=1;for(const e of Object.keys(n))if(Ge(t,e)){const o=Ye(t[e],n[e]);o>r&&(r=o)}return r>=3?3:r}case\"union\":return null==e.members?1:Xe(e.members,n).fit;case\"aliased\":case\"nullable\":case\"optional\":case\"transform\":return(\"aliased\"===e.kind?\"string\"==typeof n&&null!=e.aliases&&Ge(e.aliases,n):\"nullable\"===e.kind?null==n:\"optional\"===e.kind&&void 0===n)||null==e.inner?1:Ye(e.inner,n);default:return o||Ve(t,n)?1:4}}(t,n,e,r);return r&&4===i?3:i}function Xe(t,e){let n,o=4,r=4;for(let i=0;i<t.length;i++){const s=t[i],l=Ye(s,e),c=l<3&&qe(s)?3:l;if(c<o&&(n=s,o=c,r=l,1===c))break}return{fit:r,member:n}}function Ge(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Qe(t){if(!function(t){return function(t){return\"object\"==typeof t&&null!==t}(t)&&!Array.isArray(t)}(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}function Ze(t,e){for(const n of Object.keys(t))if(!Ge(e,n))return!0;return!1}function tn(t=\"\"){return ze(e=>\"string\"==typeof e?e:t,{kind:\"string\"},void 0,void 0,t=>\"string\"==typeof t)}const en=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function nn(t=0,e={}){const{integer:n,clamp:o}=e,r=n&&void 0!==e.min?Math.ceil(e.min):e.min,i=n&&void 0!==e.max?Math.floor(e.max):e.max,s=t=>\"string\"==typeof t&&en.test(t)?Number(t):t,l=t=>\"number\"==typeof t&&Number.isFinite(t)&&(!n||Number.isInteger(t)),c=t=>l(t)&&(void 0===r||t>=r)&&(void 0===i||t<=i);return ze(e=>{const n=s(e);return o&&l(n)?void 0!==r&&n<r?r:void 0!==i&&n>i?i:n:c(n)?n:t},{clamp:o,integer:n,kind:\"number\",max:i,min:r},void 0,void 0,t=>o?l(s(t)):c(s(t)))}function on(t=!1){return ze(e=>\"boolean\"==typeof e?e:t,{kind:\"boolean\"},void 0,void 0,t=>\"boolean\"==typeof t)}function rn(t,...e){const n=je(0!==e.length?e[0]:t[0]),o=new Set(t);return ze(t=>void 0!==t&&o.has(t)?t:n,{kind:\"enum\",values:t},n,void 0,t=>o.has(t)&&(void 0!==t||void 0===n))}function sn(t,e={}){const{defaultAsNull:n}=e;return ze(e=>{if(null==e)return null;const o=t(e);return n&&Oe(t,o)?null:o},{defaultAsNull:n,inner:t,kind:\"nullable\"},void 0,Ue(t),Je(t,t=>null==t))}function ln(t,e={}){const{omitDefault:n}=e;return ze(e=>{if(void 0===e)return;const o=t(e);return n&&Oe(t,o)?void 0:o},{inner:t,kind:\"optional\",omitDefault:n},void 0,Ue(t),Je(t,t=>void 0===t))}function cn(t,e){if(t===e)return!0;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!cn(t[n],e[n]))return!1;return!0}if(!Qe(t)||!Qe(e))return!1;const n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(n=>Ge(e,n)&&cn(t[n],e[n]))}function an(t,...e){const n=0!==e.length?je(e[0]):t[0].defaultValue;return ze(e=>{if(void 0===e)return n;const o=(e=>{const n=function(t,e){return Xe(t,e).member}(t,e);return void 0===n?void 0:{member:n,parsed:n(e)}})(e);return void 0===o?n:o.parsed},{kind:\"union\",members:t},n,cn,e=>(void 0!==e||void 0===n)&&t.some(t=>Ve(t,e)))}function un(){return t=>function(t){return{meta:{fields:t,kind:\"node\"}}}(t)}function fn(t,e){const n=t=>\"string\"==typeof t&&Ge(e,t);return ze(o=>n(o)?e[o]:t(o),{aliases:e,inner:t,kind:\"aliased\"},t.defaultValue,t.isEqual,e=>n(e)||Ve(t,e))}function dn(t,e,n={}){return ze(n=>e(t(n)),{inner:t,kind:\"transform\"},je(e(t.defaultValue)),n.isEqual,e=>Ve(t,e))}function hn(){return ze(t=>void 0===t?void 0:t,{kind:\"raw\"},void 0,void 0,()=>!0)}function gn(t){return ze(e=>{if(!Array.isArray(e))return[];const n=new Array(e.length);for(let o=0;o<e.length;o++)n[o]=t(e[o]);return n},{item:t,kind:\"array\"},void 0,(e,n)=>{if(!Array.isArray(e)||!Array.isArray(n)||e.length!==n.length)return!1;for(let o=0;o<e.length;o++)if(!Ae(t,e[o],n[o]))return!1;return!0},t=>Array.isArray(t))}function _n(t){return ze(e=>{if(!Array.isArray(e))return Object.freeze([]);if(Object.isFrozen(e)&&function(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(\"string\"!=typeof o||n>0&&!(e[n-1]<o)||!Ve(t,o)||t(o)!==o)return!1}return!0}(t,e))return e;const n=[];for(let o=0;o<e.length;o++){const r=e[o];void 0!==r&&Ve(t,r)&&n.push(t(r))}n.sort();const o=[];for(let t=0;t<n.length;t++)0!==t&&n[t]===n[t-1]||o.push(n[t]);return Object.freeze(o)},{item:t,kind:\"set\"},void 0,pn,t=>Array.isArray(t))}function pn(t,e){if(t===e)return!0;if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function yn(t){const e=function(t,e){const n=Object.entries(e);return ze(t=>{const e=null!==t&&\"object\"==typeof t?t:{},o={};for(let t=0;t<n.length;t++){const[r,i]=n[t];o[r]=i(e[r])}return o},{fields:e,kind:\"object\"},void 0,(t,o)=>Qe(t)&&Qe(o)&&!Ze(t,e)&&!Ze(o,e)&&n.every(([e,n])=>Ae(n,t[e],o[e])),t=>Qe(t)&&!Ze(t,e))}(0,t);return e}function mn(t,e){return vn(0,t,{getter:{field:e.field,getterTable:e.getterTable,method:e.getter,when:e.when},setter:{field:e.field,method:e.setter,setterTable:e.setterTable}},!0===e.derived)}function xn(t,e){return vn(0,t,{getter:e.getter,setter:e.setter},!0===e.derived)}function vn(t,e,n,o=!1){return Object.assign(t=>e(t),{accepts:e.accepts,defaultValue:e.defaultValue,...o?{derived:!0}:{},getter:n.getter,isEqual:e.isEqual,meta:e.meta,setter:n.setter})}const Sn=\"direct\",Cn=\"latest\";class bn{key;parse;unparse;isEqual;defaultValue;resetOnCopyNode;derived;schema;constructor(t,e){this.key=t,this.derived=!0===e.derived;const n=\"meta\"in(o=e.parse)&&\"object\"==typeof o.meta&&null!==o.meta&&\"kind\"in o.meta&&\"string\"==typeof o.meta.kind&&\"defaultValue\"in o?e.parse:void 0;var o;this.schema=n,this.parse=e.parse.bind(e),this.unparse=(e.unparse||In).bind(e),this.isEqual=e.isEqual?e.isEqual.bind(e):void 0!==n&&void 0!==n.isEqual?(t,e)=>Ae(n,t,e):Object.is,this.defaultValue=void 0!==n?n.defaultValue:this.parse(void 0),this.resetOnCopyNode=e.resetOnCopyNode||!1}}function kn(t,e){return new bn(t,e)}function Tn(t,e,n=Cn){const o=(n===Cn?t.getLatest():t).__state;return o?o.getValue(e):e.defaultValue}function Nn(t,e,n){const o=Tn(t,n,Sn),r=Tn(e,n,Sn);return n.isEqual(o,r)?null:[o,r]}function wn(t,e,n){let o;if(xu(),\"function\"==typeof n){const r=t.getLatest(),i=Tn(r,e);if(o=En(e,n(i)),e.isEqual(i,o))return r}else o=En(e,n);const r=t.getWritable();return Dn(r).updateFromKnown(e,o),r}function En(t,e){const{schema:n}=t;return void 0!==n&&\"set\"===n.meta.kind?t.parse(e):e}function An(t){const e=new Map,n=new Set;for(const{ownNodeConfig:o}of da(\"function\"==typeof t?t:t.replace))if(o&&o.stateConfigs)for(const t of o.stateConfigs){let o;\"stateConfig\"in t?(o=t.stateConfig,t.flat&&n.add(o.key)):o=t,e.set(o.key,o)}return{flatKeys:n,sharedConfigMap:e}}const On=new Set([\"__proto__\",\"constructor\",\"prototype\"]);class Mn{node;knownState;unknownState;sharedNodeState;size;constructor(t,e,n=void 0,o=new Map,r=void 0){this.node=t,this.sharedNodeState=e,this.unknownState=n,this.knownState=o;const{sharedConfigMap:i}=this.sharedNodeState,s=void 0!==r?r:function(t,e,n){let o=n.size;if(e)for(const r in e){const e=t.get(r);e&&n.has(e)||o++}return o}(i,n,o);this.size=s}getValue(t){const e=this.knownState.get(t);if(void 0!==e)return e;this.sharedNodeState.sharedConfigMap.set(t.key,t);let n=t.defaultValue;if(this.unknownState&&t.key in this.unknownState){const e=this.unknownState[t.key];void 0!==e&&(n=t.parse(e)),this.knownState.set(t,n)}return n}getInternalState(){return[this.unknownState,this.knownState]}toJSON(){const t={...this.unknownState},e={};for(const[e,n]of this.knownState)e.isEqual(n,e.defaultValue)?delete t[e.key]:t[e.key]=e.unparse(n);for(const n of this.sharedNodeState.flatKeys)n in t&&(e[n]=t[n],delete t[n]);return Fn(t)&&(e[J]=t),e}getWritable(t){if(this.node===t)return this;const{sharedNodeState:e,unknownState:n}=this,o=new Map(this.knownState);return new Mn(t,e,function(t,e,n){let o;if(n)for(const[r,i]of Object.entries(n)){if(On.has(r))continue;const n=t.get(r);n?e.has(n)||e.set(n,n.parse(i)):(o=o||{},o[r]=i)}return o}(e.sharedConfigMap,o,n),o,this.size)}resetOnCopyNode(){for(const t of this.knownState.keys())t.resetOnCopyNode&&this.knownState.set(t,t.defaultValue);return this}updateFromKnown(t,e){const n=t.key;this.sharedNodeState.sharedConfigMap.set(n,t);const{knownState:o,unknownState:r}=this;r&&n in r?(delete r[n],this.unknownState=Fn(r)):o.has(t)||this.size++,o.set(t,e)}updateFromUnknown(t,e){if(On.has(t))return;const n=this.sharedNodeState.sharedConfigMap.get(t);n?this.updateFromKnown(n,n.parse(e)):(this.unknownState=this.unknownState||{},t in this.unknownState||this.size++,this.unknownState[t]=e)}updateFromJSON(t){const{knownState:e}=this;for(const t of e.keys())e.set(t,t.defaultValue);if(this.size=e.size,this.unknownState=void 0,t)for(const[e,n]of Object.entries(t))this.updateFromUnknown(e,n)}}function Dn(t){const e=t.getWritable(),n=e.__state?e.__state.getWritable(e):new Mn(e,function(t){return t.__state?t.__state.sharedNodeState:gs(mc(),t.getType()).sharedNodeState}(e));return e.__state=n,n}function Pn(t,e){const n=t.getWritable(),o=e[J];return(n.__state||o)&&Dn(t).updateFromJSON(o),n}function Fn(t){if(t)for(const e in t)return t}function In(t){return t}function Ln(t,e,n){for(const[o,r]of e.knownState){if(t.has(o.key))continue;t.add(o.key);const e=n?n.getValue(o):o.defaultValue;if(e!==r&&!o.isEqual(e,r))return!0}return!1}function Kn(t,e,n){const{unknownState:o}=e,r=n?n.unknownState:void 0;if(o)for(const[e,n]of Object.entries(o))if(!t.has(e)&&(t.add(e),n!==(r?r[e]:void 0)))return!0;return!1}function zn(t,e){const n=t.__state;return n&&n.node===t?n.getWritable(e):n}function Bn(t){return!ci(t)&&t.getTextContent!==ei.prototype.getTextContent}const Rn=Symbol.for(\"@lexical/CachedTextSize\");function Wn(t,n){return ro.read(()=>{let o=0,r=t;for(let t=0;t<n&&null!==r;t++){const i=oo.get(r);if(void 0===i&&e(345,r),ni(i)){const s=io.get(r);if(void 0!==s&&ni(s)&&s.__parent!==i.__parent)o+=i.getTextContentSize();else{const t=so.get(r),n=t&&t.__lexicalTextContent;\"string\"!=typeof n&&e(346,i.getType()),o+=n.length}t<n-1&&!i.isInline()&&(o+=2)}else if(bo(i).size>0)o+=i.getTextContentSize();else{const t=i[Rn];void 0===t&&e(347,i.getType(),r),o+=t}r=i.__next}return o},{editor:Jn})}function jn(t){ni(t)||bo(t).size>0||void 0===t[Rn]&&(t[Rn]=Mi(t)?t.__text.length:t.getTextContentSize())}const $n=4;let Un,Jn,Vn,Hn=\"\",qn=null,Yn=null,Xn=null;function Gn(){return{firstTextKey:Xn,format:qn,style:Yn}}function Qn(t){null!==t.firstTextKey&&(qn=t.format,Yn=t.style,Xn=t.firstTextKey)}function Zn(t){if(null!==Xn)return;const n=t.__lexicalFirstTextKey;if(void 0===n&&e(348),null===n)return;const o=io.get(n);Mi(o)&&(qn=o.getFormat(),Yn=o.getStyle(),Xn=n)}let to,eo,no,oo,ro,io,so,lo,co,ao,uo=!1,fo=!1;function ho(t,e){const n=oo.get(t),o=io.has(t);if(null!==e){const n=zo(t);n.parentNode===e&&e.removeChild(n)}if(!o){if(Jn._keyToDOMMap.delete(t),ni(n)){const t=pa(n,oo);go(t,0,t.length-1,null)}if(void 0!==n){for(const t of bo(n).values()){const e=To(t);ho(t,null),null!==e&&e.remove()}_l(co,Vn,to,n,\"destroyed\")}}}function go(t,e,n,o){for(let r=e;r<=n;++r){const e=t[r];void 0!==e&&ho(e,o)}}function _o(t,e){t.setProperty(\"text-align\",e)}const po=\"40px\";function yo(t,e){const n=Un.theme.indent;if(\"string\"==typeof n){const o=t.classList.contains(n);e>0&&!o?t.classList.add(n):e<1&&o&&t.classList.remove(n)}t.style.setProperty(\"padding-inline-start\",0===e?\"\":`calc(${e} * var(--lexical-indent-base-value, ${po}))`),hl(t,\"class\"),hl(t,\"style\")}function mo(t,e){const n=t.style;0===e?_o(n,\"\"):1===e?_o(n,\"left\"):2===e?_o(n,\"center\"):3===e?_o(n,\"right\"):4===e?_o(n,\"justify\"):5===e?_o(n,\"start\"):6===e&&_o(n,\"end\"),hl(t,\"style\")}function xo(t,e){const n=function(t){const e=t.__dir;if(null!==e)return e;if(ci(t))return null;const n=t.getParent();return null===n||Il(n)&&null===n.__dir?\"auto\":null}(e);null!==n?t.dir=n:t.removeAttribute(\"dir\")}function vo(t){const e=Yl().createElement(\"div\");return e.setAttribute(\"data-lexical-slot\",t),e.style.display=\"none\",e}function So(t,e,n){e||\"false\"===t.contentEditable?Ic(n,Jn):n.removeAttribute(\"contenteditable\")}function Co(t,e,n){const o=Hn,r=Gn();Hn=\"\";let i=\"\";const s=ii(t);for(const[o,r]of n){const n=vo(o);So(e,s,n),e.appendChild(n),Hn=\"\";const l=Gn();wo(r,vc(t,n,Jn)),Qn(l),ko(t,o,e,n),i+=Hn}return Qn(r),Hn=o,i}function bo(t){return rh(t)&&null!==t.__slots?t.__slots:oh}function ko(t,e,n,o){const r=ao.$getSlotTargetElement(t,e,n,Jn);null!==r&&(o.parentElement!==r&&r.appendChild(o),o.style.display=\"\")}function To(t){const e=so.get(t);return void 0!==e?e.parentElement:null}function No(t,e,n){const o=bo(t),r=bo(e);for(const[t,e]of o)if(!r.has(t)){const t=To(e);ho(e,null),null!==t&&t.remove()}const i=Hn,s=Gn();let l=\"\",c=null;const a=ii(e);for(const[t,i]of r){const r=o.get(t);let s=void 0!==r?To(r):null;Hn=\"\";const u=Gn();if(null===s){s=vo(t);let o=null;for(const t of n.children)if(!t.hasAttribute(\"data-lexical-slot\")){o=t;break}n.insertBefore(s,o),wo(i,vc(e,s,Jn))}else r===i?Po(i,s):(void 0!==r&&ho(r,s),wo(i,vc(e,s,Jn)));if(Qn(u),So(n,a,s),ko(e,t,n,s),l+=Hn,s.parentElement===n){const t=null===c?n.firstChild:c.nextSibling;t!==s&&n.insertBefore(s,t),c=s}}return Qn(s),Hn=i,l}function wo(t,n){const o=io.get(t);if(void 0===o&&e(60),null!==n){const e=oo.get(t);if(void 0!==e){const r=so.get(t);if(void 0!==r){const i=ih(e)?e.__slotHost:null,s=ih(o)?o.__slotHost:null,l=e.__parent!==o.__parent||i!==s,c=null!==s&&r.parentElement!==n.element;if(l||c)return n.insertChild(r),Po(t,n.element)}}}const r=ao.$createDOM(o,Jn);if(function(t,e,n){const o=n._keyToDOMMap;Ws(e,n,t),o.set(t,e)}(t,r,Jn),Mi(o)?r.setAttribute(\"data-lexical-text\",\"true\"):ii(o)&&(r.setAttribute(\"data-lexical-decorator\",\"true\"),Pc(r,{captureSelection:!0})),ni(o)){const t=Hn,e=o.__indent,n=o.__size;xo(r,o),0!==e&&yo(r,e);const i=bo(o),s=i.size>0?Co(o,r,i):\"\";if(0===n)r.__lexicalTextContent=s,r.__lexicalFirstTextKey=null,Hn+=s,i.size>0&&(r.__lexicalSlotTextLength=s.length);else{const e=n-1;if(Eo(pa(o,io),o,0,e,vc(o,r,Jn)),\"\"!==s){const e=r.__lexicalTextContent||\"\";r.__lexicalTextContent=s+e,Hn=t+s+e}i.size>0&&(r.__lexicalSlotTextLength=s.length)}if(Bn(o)){const e=o.getTextContent();r.__lexicalTextContent=e,Hn=t+e}const l=o.__format;0!==l&&mo(r,l),o.isInline()||(Mo(0,o,r),Oo(o,r))}else{const e=o.getTextContent();if(ii(o)){const e=o.decorate(Jn,Un);null!==e&&Fo(t,e),r.contentEditable=\"false\";const n=bo(o);n.size>0&&Co(o,r,n)}Hn+=e}return null!==n&&n.insertChild(r),ao.$decorateDOM(o,null,r,Jn),jn(o),_l(co,Vn,to,o,\"created\"),r}function Eo(t,n,o,r,i){const s=Hn,l=Gn();Hn=\"\",qn=null,Yn=null,Xn=null;let c=o;for(;c<=r;++c){const e=Gn();wo(t[c],i);const n=io.get(t[c]);null!==n&&Mi(n)?null===qn&&(qn=n.getFormat(),Yn=n.getStyle(),Xn=n.__key):ni(n)&&c<r&&!n.isInline()&&(Hn+=M),Qn(e)}const a=Jn._keyToDOMMap.get(n.__key);void 0===a&&e(349,n.__key),a.__lexicalTextContent=Hn,a.__lexicalFirstTextKey=Xn,Hn=s+Hn,Qn(l)}function Ao(t){return ii(t)&&!t.isInline()}function Oo(t,e,n=vc(t,e,Jn)){n.setDecoratorBoundaryAnchor(\"leading\",Ao(t.getFirstChild())),n.setDecoratorBoundaryAnchor(\"trailing\",Ao(t.getLastChild()))}function Mo(t,e,n){const o=vc(e,n,Jn),r=function(t,e){if(t){const n=t.__last;if(n){const t=e.get(n);if(t)return Ba(t)?\"line-break\":ii(t)&&t.isInline()?\"decorator\":null}return\"empty\"}return null}(e,io);o.setManagedLineBreak(r)}function Do(t,e,n){const o=e.__lexicalFirstTextKey;if(null!=o){const e=t.__key;let r=o;for(;null!==r;){const t=io.get(r);if(void 0===t){r=null;break}if(t.__parent===e)break;r=t.__parent}if(null!==r&&!n.has(r)){const t=io.get(o);if(Mi(t))return qn=t.getFormat(),void(Yn=t.getStyle())}}e.__lexicalFirstTextKey=Xn}function Po(t,n){const o=oo.get(t);let r=io.get(t);void 0!==o&&void 0!==r||e(61);const i=uo||no.has(t)||eo.has(t),s=Sl(Jn,t);if(o===r&&!i){let t;if(ni(o)){const n=s.__lexicalTextContent;\"string\"!=typeof n&&e(355,o.getType()),t=n,Zn(s)}else t=o.getTextContent();return Hn+=t,s}if(o!==r&&i&&_l(co,Vn,to,r,\"updated\"),ao.$updateDOM(r,o,s,Jn)){const o=wo(t,null);return null===n&&e(62),n.replaceChild(o,s),ho(t,null),o}if(ni(o)){ni(r)||e(334,t);const n=r.__indent;(uo||n!==o.__indent)&&yo(s,n);const l=r.__format;(uo||l!==o.__format)&&mo(s,l);const c=i&&(bo(r).size>0||bo(o).size>0)?No(o,r,s):\"\";if(i){const t=Hn;if(function(t,n,o){var r;qn=null,Yn=null,Xn=null,function(t,n,o){const r=Hn,i=t.__size,s=n.__size;Hn=\"\";const l=o.element,c=Jn._keyToDOMMap.get(n.__key);void 0===c&&e(351,n.__key);const a=s-i;if(!uo&&Math.abs(a)<=1&&i>=$n&&t.__first===n.__first&&(0!==a||!Jn._cloneNotNeeded.has(t.__key))){const i=c.__lexicalTextContent,u=lo.get(t.__key);if(!uo&&!Bn(n)&&\"string\"==typeof i&&void 0!==u){const s=function(t,e){const n=e.size;if(0===n||n>=t.__size)return null;let o=t.__last,r=null,i=0;for(;null!==o&&i<n;){if(!e.has(o))return null;r=o;const t=io.get(o);if(void 0===t)return null;o=t.__prev,i++}return i!==n||null!==o&&e.has(o)?null:r}(n,u);if(null!==s){const f=u.size;if(0===a){const t=Wn(s,f);let o=s,a=0;for(;null!==o&&a<f;){const t=io.get(o);if(void 0===t)break;const e=Gn();Po(o,l),Mi(t)&&null===qn&&(qn=t.getFormat(),Yn=t.getStyle(),Xn=t.__key),Qn(e),o=t.__next,a++}let d=\"\";for(o=s,a=0;null!==o&&a<f;){const t=io.get(o);if(void 0===t)break;let n;if(ni(t)){const r=Jn._keyToDOMMap.get(o),i=r&&r.__lexicalTextContent;\"string\"!=typeof i&&e(352,t.getType()),n=i}else n=t.getTextContent();d+=n,a<f-1&&ni(t)&&!t.isInline()&&(d+=M),o=t.__next,a++}const h=c.__lexicalSlotTextLength||0,g=h>0?i.slice(h):i,_=g.slice(0,g.length-t)+d;return c.__lexicalTextContent=_,Hn=r+_,void Do(n,c,u)}if(function(t,n,o,r,i,s,l,c){if(1!==c&&-1!==c)return!1;if(l!==(1===c?2:1))return!1;const a=l-c;let u=t.__last;for(let t=0;t<a-1;t++){if(null===u)return!1;const t=oo.get(u);if(void 0===t)return!1;u=t.__prev}if(null===u)return!1;const f=io.get(s),d=oo.get(u);if(void 0===f||void 0===d)return!1;if(f.__prev!==d.__prev)return!1;const h=[];let g=s;for(let t=0;t<l;t++){if(null===g)return!1;h.push(g);const t=io.get(g);g=t?t.__next:null}const _=[];g=u;for(let t=0;t<a;t++){if(null===g)return!1;_.push(g);const t=oo.get(g);g=t?t.__next:null}const p=new Set(_),y=new Set(h),m=[];let x=0,v=0;for(;x<a&&v<l;)if(h[v]===_[x])m.push({key:h[v],kind:\"reconcile\"}),x++,v++;else if(y.has(_[x])){if(p.has(h[v]))return!1;m.push({key:h[v],kind:\"create\",nextIndex:v}),v++}else m.push({key:_[x],kind:\"destroy\"}),x++;for(;x<a;)m.push({key:_[x++],kind:\"destroy\"});for(;v<l;)m.push({key:h[v],kind:\"create\",nextIndex:v}),v++;const S=Wn(u,a);for(const t of m){const e=Gn();if(\"reconcile\"===t.kind)Po(t.key,o.element);else if(\"destroy\"===t.kind)ho(t.key,o.element);else{let e=null;for(let n=t.nextIndex+1;n<l;n++){const t=Jn._keyToDOMMap.get(h[n]);if(void 0!==t){e=t;break}}wo(t.key,o.withBefore(e??o.before))}if(\"destroy\"!==t.kind){const e=io.get(t.key);e&&Mi(e)&&null===qn&&(qn=e.getFormat(),Yn=e.getStyle(),Xn=e.__key)}Qn(e)}let C=\"\";for(let t=0;t<l;t++){const n=io.get(h[t]);if(void 0===n)return!1;let o;if(ni(n)){const r=Jn._keyToDOMMap.get(h[t]),i=r&&r.__lexicalTextContent;\"string\"!=typeof i&&e(350,n.getType()),o=i}else o=n.getTextContent();C+=o,t<l-1&&ni(n)&&!n.isInline()&&(C+=M)}const b=r.__lexicalSlotTextLength||0,k=b>0?i.slice(b):i;return r.__lexicalTextContent=k.slice(0,k.length-S)+C,!0}(t,0,o,c,i,s,f,a)){const t=c.__lexicalTextContent;return\"string\"!=typeof t&&e(353),Hn=r+t,void Do(n,c,u)}}}if(0===a){let n=t.__first,o=0;for(;null!==n;){const t=io.get(n);if(void 0===t)break;const r=uo||no.has(n)||eo.has(n),i=Gn();if(r)Po(n,l);else{let o,r;if(ni(t)){r=so.get(n);const i=r&&r.__lexicalTextContent;\"string\"!=typeof i&&e(354,t.getType()),o=i}else o=t.getTextContent();Hn+=o,void 0!==r&&Zn(r)}Mi(t)?null===qn&&(qn=t.getFormat(),Yn=t.getStyle(),Xn=t.__key):ni(t)&&o<s-1&&!t.isInline()&&(Hn+=M),Qn(i),n=t.__next,o++}return c.__lexicalTextContent=Hn,c.__lexicalFirstTextKey=Xn,void(Hn=r+Hn)}}if(1===i&&1===s){const e=t.__first,r=n.__first;if(e===r)Po(e,l);else{const t=zo(e),n=wo(r,null);try{t.parentNode===l?l.replaceChild(n,t):o.insertChild(n)}catch(o){if(\"object\"==typeof o&&null!=o){const i=`${o.toString()} Parent: ${l.tagName}, new child: {tag: ${n.tagName} key: ${r}}, old child: {tag: ${t.tagName}, key: ${e}}.`;throw new Error(i)}throw o}ho(e,null)}const i=io.get(r);Mi(i)&&null===qn&&(qn=i.getFormat(),Yn=i.getStyle(),Xn=i.__key)}else{const r=pa(t,oo),c=pa(n,io);if(r.length!==i&&e(227),c.length!==s&&e(228),0===i)0!==s&&Eo(c,n,0,s-1,o);else if(0===s){if(0!==i){const t=null==o.after&&null==o.before&&0===bo(n).size&&null==o.element.__lexicalLineBreak;go(r,0,i-1,t?null:l),t&&(l.textContent=\"\")}}else!function(t,e,n,o,r,i){const s=o-1,l=r-1;let c,a,u=i.getFirstChild(),f=0,d=0;for(;f<=s&&d<=l;){const t=e[f],o=n[d],r=Gn();if(t===o)u=Io(Po(o,i.element)),f++,d++;else{if(void 0===a&&(a=Lo(n,d)),void 0===c)c=Lo(e,f);else if(!c.has(t)){f++,Qn(r);continue}if(!a.has(t)){const e=zo(t);e.parentNode===i.element&&(u=Io(e)),ho(t,i.element),f++,c.delete(t),Qn(r);continue}if(c.has(o)){const t=Sl(Jn,o);t!==u&&i.withBefore(u??i.before).insertChild(t),u=Io(Po(o,i.element)),f++,d++}else wo(o,i.withBefore(u??i.before)),d++}const s=io.get(o);null!==s&&Mi(s)?null===qn&&(qn=s.getFormat(),Yn=s.getStyle(),Xn=s.__key):ni(s)&&d<=l&&!s.isInline()&&(Hn+=M),Qn(r)}const h=f>s,g=d>l;if(h&&!g){const e=n[l+1],o=void 0===e?null:Jn.getElementByKey(e);Eo(n,t,d,l,i.withBefore(o??i.before))}else g&&!h&&go(e,f,s,i.element)}(n,r,c,i,s,o)}c.__lexicalTextContent=Hn,c.__lexicalFirstTextKey=Xn,Hn=r+Hn}(t,n,vc(n,o,Jn)),Il(n)||(r=n,null==qn||qn===r.__textFormat||fo||r.setTextFormat(qn),function(t){null==Yn||Yn===t.__textStyle||fo||t.setTextStyle(Yn)}(n))}(o,r,s),r.isInline()||(ci(r)||Mo(0,r,s),Oo(r,s)),\"\"!==c){const e=s.__lexicalTextContent||\"\";s.__lexicalTextContent=c+e,Hn=t+c+e,s.__lexicalSlotTextLength=c.length}else(bo(r).size>0||bo(o).size>0)&&(s.__lexicalSlotTextLength=0);if(Bn(r)){const e=r.getTextContent();s.__lexicalTextContent=e,Hn=t+e}}else{const t=s.__lexicalTextContent;\"string\"!=typeof t&&e(356,o.getType()),Hn+=t,Zn(s)}if((uo||r.__dir!==o.__dir||r.__parent!==o.__parent)&&(xo(s,r),ci(r)&&!uo))for(const t of r.getChildren())ni(t)&&xo(Sl(Jn,t.getKey()),t)}else{const e=r.getTextContent();if(ii(r)){const e=r.decorate(Jn,Un);null!==e&&Fo(t,e),i&&(bo(r).size>0||bo(o).size>0)&&No(o,r,s)}Hn+=e}if(!fo&&ci(r)){const t=r.getLatest();if(t.__cachedText!==Hn){const e=t.getWritable();e.__cachedText=Hn,r=e}}return ao.$decorateDOM(r,o,s,Jn),jn(r),s}function Fo(t,e){let n=Jn._pendingDecorators;const o=Jn._decorators;if(null===n){if(o[t]===e)return;n=Us(Jn)}n[t]=e}function Io(t){let e=t.nextSibling;return null!==e&&e===Jn._blockCursorElement&&(e=e.nextSibling),e}function Lo(t,e){const n=new Set;for(let o=e;o<t.length;o++)n.add(t[o]);return n}function Ko(t,e,n,o,r,i){Hn=\"\",qn=null,Yn=null,Xn=null,uo=2===o,Jn=n,Un=n._config,ao=n._config.dom||nu,Vn=n._nodes,to=Jn._listeners.mutation,eo=r,no=i,oo=t._nodeMap,ro=t,io=e._nodeMap,fo=e._readOnly,so=re(n._keyToDOMMap),lo=function(){const t=new Map,e=e=>{for(const n of e){const e=io.get(n);if(void 0===e)continue;const o=e.__parent;if(null===o)continue;let r=t.get(o);void 0===r&&(r=new Set,t.set(o,r)),r.add(n)}};return e(eo.keys()),e(no),t}();const s=new Map;return co=s,Po(\"root\",null),Jn=void 0,Vn=void 0,eo=void 0,no=void 0,oo=void 0,ro=void 0,io=void 0,Un=void 0,so=void 0,lo=void 0,co=void 0,ao=nu,s}function zo(t){const n=so.get(t);return void 0===n&&e(75,t),n}function Bo(t,n,o){xu();const r=t.__key,i=t.getParent();if(null===i)return void(null!==sh(t)&&e(367,r,String(sh(t))));const s=function(t){const e=Od();if(!Xf(e)||!ni(t))return e;const{anchor:n,focus:o}=e,r=n.getNode(),i=o.getNode();return Al(r,t)&&n.set(t.__key,0,\"element\"),Al(i,t)&&o.set(t.__key,0,\"element\"),e}(t);let l=!1;if(Xf(s)&&n){const e=s.anchor,n=s.focus;e.key===r&&(Fd(e,t,i,t.getPreviousSibling(),t.getNextSibling()),l=!0),n.key===r&&(Fd(n,t,i,t.getPreviousSibling(),t.getNextSibling()),l=!0)}else Qf(s)&&n&&t.isSelected()&&t.selectPrevious();Zd(t.getWritable(),n&&!l&&Xf(s)?s:null),o||Il(i)||i.canBeEmpty()||!i.isEmpty()||Bo(i,n),n&&s&&ci(i)&&i.isEmpty()&&i.selectEnd()}function Ro(t){return t}const Wo=Symbol.for(\"ephemeral\");function jo(t){return t[Wo]||!1}const $o={configurable:!0,enumerable:!1,value:void 0,writable:!0};class Uo{__type;__key;__parent;__prev;__next;__state;static getType(){const{ownNodeType:t}=ra(this);return void 0===t&&e(64,this.name),t}static clone(t){e(65,this.name)}$config(){return{}}config(t,e){const n=e.extends||ya(this.constructor);return Object.assign(e,{extends:n}),\"string\"==typeof t&&Object.assign(e,{type:t}),{[t]:e}}afterCloneFrom(t){this.__key===t.__key?(this.__parent=t.__parent,this.__next=t.__next,this.__prev=t.__prev,this.__state=t.__state):t.__state&&(this.__state=t.__state.getWritable(this))}resetOnCopyNodeFrom(t){this.__state&&(this.__state=this.__state.getWritable(this).resetOnCopyNode())}static importDOM;constructor(t){this.__type=this.constructor.getType(),this.__parent=null,this.__prev=null,this.__next=null,Object.defineProperty(this,\"__state\",$o),Object.defineProperty(this,Rn,$o),Ds(this,t)}getType(){return this.__type}isInline(){e(137,this.constructor.name)}isAttached(){let t=this.__key;for(;null!==t;){if(\"root\"===t)return!0;const e=Bs(t);if(null===e)break;t=null!==e.__parent?e.__parent:sh(e)}return!1}isSelected(t){const e=t||Od();if(null==e)return!1;const n=e.getNodes().some(t=>t.__key===this.__key);if(Mi(this))return n;if(Xf(e)&&\"element\"===e.anchor.type&&\"element\"===e.focus.type){if(e.isCollapsed())return!1;const t=this.getParent();if(ii(this)&&this.isInline()&&t){const n=e.isBackward()?e.focus:e.anchor;if(t.is(n.getNode())&&n.offset===t.getChildrenSize()&&this.is(t.getLastChild()))return!1}}return n}getKey(){return this.__key}getIndexWithinParent(){const t=this.getParent();if(null===t)return-1;let e=t.getFirstChild(),n=0;for(;null!==e;){if(this.is(e))return n;n++,e=e.getNextSibling()}return-1}getParent(){const t=this.getLatest().__parent;return null===t?null:Bs(t)}getParentOrThrow(){const t=this.getParent();return null===t&&e(66,this.__key),t}getTopLevelElement(){let t=this;for(;null!==t;){const n=t.getParent();if(Il(n)||null!==sh(t))return ni(t)||t===this&&ii(t)||e(194),t;t=n}return null}getTopLevelElementOrThrow(){const t=this.getTopLevelElement();return null===t&&e(67,this.__key),t}getParents(){const t=[];let e=this.getParent();for(;null!==e;)t.push(e),e=e.getParent();return t}getParentKeys(){const t=[];let e=this.getParent();for(;null!==e;)t.push(e.__key),e=e.getParent();return t}getPreviousSibling(){const t=this.getLatest().__prev;return null===t?null:Bs(t)}getPreviousSiblings(){return nh(this.getPreviousSibling(),\"previous\").reverse()}getNextSibling(){const t=this.getLatest().__next;return null===t?null:Bs(t)}getNextSiblings(){return nh(this.getNextSibling(),\"next\")}is(t){return null!=t&&this.__key===t.__key}isBefore(t){const n=cg(this,t);return null!==n&&(\"descendant\"===n.type||(\"branch\"===n.type?-1===ig(n):(\"same\"!==n.type&&\"ancestor\"!==n.type&&e(279),!1)))}isParentOf(t){return Al(t,this)}getNodesBetween(t){const e=this.isBefore(t),n=[];let o=this,r=!0,i=0;for(;null!==o&&((r||0===i)&&n.push(o),!o.is(t));){!r&&i>0&&i--;const t=r&&ni(o)?e?o.getFirstChild():o.getLastChild():null;null!==t&&i++;const n=t||(e?o.getNextSibling():o.getPreviousSibling());r=null!==n,o=n||o.getParent()}return e?n:n.reverse()}isDirty(){const t=bu()._dirtyLeaves;return null!==t&&t.has(this.__key)}getLatest(){if(jo(this))return this;const t=Bs(this.__key);return null===t&&e(442,this.__key,this.__type),t}getWritable(){if(jo(this))return this;xu();const t=Su(),n=bu(),o=this.__key,r=n._cloneNotNeeded,i=r.get(o),s=t._selection;if(null!==s&&s.setCachedNodes(null),void 0!==i)return Is(i),i;const l=t._nodeMap,c=l.get(o);void 0===c&&e(442,o,this.__type);const a=Ec(c);return r.set(o,a),l.set(o,a),Is(a),a}getTextContent(){return vh(this)}getTextContentSize(){return this.getTextContent().length}createDOM(t,n){e(70)}updateDOM(t,n,o){e(71)}getDOMSlot(t){return new _e(t)}exportDOM(t){return{element:xc(t).$createDOM(this,t)}}exportJSON(t=!1){const e=function(t,e){const n=Rc(Bc(t.constructor)),{generated:o,isCompactDefault:r}=n,i=null===o?void 0:e?o.exportCompactJSON:o.exportJSON;return void 0===i?function(t,e,n){const o=n?{type:t.__type}:{};return ni(t)&&(o.children=[]),function(t,e,n,o){for(let r=0;r<e.length;r++){const i=e[r];if(o&&i.derived)continue;let s;if(\"ownField\"===i.kind){const e=Zc(t)[i.field];s=void 0===i.getterTable?e:Ge(i.getterTable,e)?i.getterTable[e]:void 0}else s=i.getter.call(t);\"ownField\"===i.kind&&void 0!==i.when&&(!ta(i,s)&&i.when.call(t)||(s=void 0)),o&&ta(i,s)||(n[i.key]=s)}}(t,e,o,n),n||(o.type=t.__type,o.version=1),o}(t,n.getters,e):e?i(t,r):i(t)}(this,t),n=this.__state?this.__state.toJSON():void 0;return void 0!==n&&Object.assign(e,n),e}static importJSON(t){e(18,this.name)}updateFromJSON(t){return oa(Pn(this,t),t)}static transform(){return null}remove(t){Bo(this,!0,t)}replace(t,n){xu();let o=Od();null!==o&&(o=o.clone()),zl(this,t);const r=this.getLatest(),i=this.__key,s=lh(r);null!==s&&e(400,i,r.getType(),s.getKey(),s.getType());const l=t.__key,c=t.getWritable(),a=this.getParentOrThrow().getWritable(),u=a.__size,f=c.getParent();Zd(c,Xf(o)?o:null);const d=r.getPreviousSibling(),h=r.getNextSibling();Bo(r,!1,!0),Gd(a,c,d&&d.getWritable(),h&&h.getWritable()),a.__size=null!==f&&f.is(a)?u-1:u;let g=0;if(n&&(ni(this)&&ni(c)||e(139),g=c.getChildrenSize(),c.splice(g,0,this.getChildren())),Xf(o)){Ys(o);for(const t of[o.anchor,o.focus])t.key===i&&(n&&\"element\"===t.type?t.set(c.__key,g+t.offset,\"element\"):Uf(t,c))}return Ks()===i&&Ls(l),c}insertAfter(t,e=!0){return th(this,\"next\",t,e)}insertBefore(t,e=!0){return th(this,\"previous\",t,e)}isParentRequired(){return!1}createParentElementNode(){return os()}selectStart(){return this.selectPrevious()}selectEnd(){return this.selectNext(0,0)}selectPrevious(t,e){return eh(Rh(this,\"previous\"),t,e)}selectNext(t,e){return eh(Rh(this,\"next\"),t,e)}markDirty(){this.getWritable()}reconcileObservedMutation(t,e){this.markDirty()}}function Jo(t){return t instanceof Uo}function Vo(t,e){const n=t.__mode,o=t.__format,r=t.__style,i=e.__mode,s=e.__format,l=e.__style,c=t.__state,a=e.__state;return(null===n||n===i)&&(null===o||o===s)&&(null===r||r===l)&&(null===t.__state||c===a||function(t,e){if(t===e)return!0;const n=new Set;return!(t&&Ln(n,t,e)||e&&Ln(n,e,t)||t&&Kn(n,t,e)||e&&Kn(n,e,t))}(c,a))}function Ho(t,e){const n=t.mergeWithSibling(e),o=bu()._normalizedNodes;return o.add(t.__key),o.add(e.__key),n}function qo(t){let e,n,o=t;if(!zs(o))if(\"\"!==o.__text||!o.isSimpleText()||o.isUnmergeable()){for(;null!==(e=o.getPreviousSibling())&&Mi(e)&&e.isSimpleText()&&!e.isUnmergeable()&&!zs(e);){if(\"\"!==e.__text){if(Vo(e,o)){o=Ho(e,o);break}break}e.remove()}for(;null!==(n=o.getNextSibling())&&Mi(n)&&n.isSimpleText()&&!n.isUnmergeable()&&!zs(n);){if(\"\"!==n.__text){if(Vo(o,n)){o=Ho(o,n);break}break}n.remove()}}else o.remove()}function Yo(t){return Xo(t.anchor),Xo(t.focus),t}function Xo(t){for(;\"element\"===t.type;){const e=t.getNode(),n=t.offset;let o,r;if(n===e.getChildrenSize()?(o=e.getChildAtIndex(n-1),r=!0):(o=e.getChildAtIndex(n),r=!1),Mi(o)){t.set(o.__key,r?o.getTextContentSize():0,\"text\",!0);break}if(!ni(o))break;t.set(o.__key,r?o.getChildrenSize():0,\"element\",!0)}}const Go=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function Qo(t,e){if(\"number\"==typeof t)return Number.isFinite(t)?t:e;if(\"string\"!=typeof t||!Go.test(t))return e;const n=Number(t);return Number.isFinite(n)?n:e}function Zo(t,e,n,o,r){const i=Qo(t,e);return i>=n&&i<=o&&Number.isInteger(i)?i:e}const tr=t=>{const e=De(t,\"format\"),n=Pe(t,\"format\"),o=Ie(t,\"format\");return{exportJSON:function(t){const n=t.__textFormat,o=t.__textStyle,r=(0!==n||\"\"!==o)&&t.shouldSerializeTextStyles();return{children:[],direction:t.__dir,format:e[t.__format],indent:t.__indent,textFormat:0!==n&&r?n:void 0,textStyle:\"\"!==o&&r?o:void 0,type:t.__type,version:1}},exportCompactJSON:function(t){const n=t.__textFormat,o=t.__textStyle,r=(0!==n||\"\"!==o)&&t.shouldSerializeTextStyles(),i={type:t.__type,children:[]},s=t.__dir;null!=s&&(i.direction=s);const l=e[t.__format];void 0!==l&&\"\"!==l&&(i.format=l);const c=t.__indent;return void 0!==c&&0!==c&&(i.indent=c),void 0!==n&&0!==n&&r&&(i.textFormat=n),void 0!==o&&\"\"!==o&&r&&(i.textStyle=o),i},updateFromJSON:function(t,e){const r=e.direction;t.__dir=null===r||\"ltr\"===r||\"rtl\"===r?r:null;const i=e.format;t.__format=\"string\"==typeof i&&i in n?n[i]:o,t.__indent=Zo(e.indent,0,0,Infinity),t.__textFormat=Qo(e.textFormat,0);const s=e.textStyle;return t.__textStyle=\"string\"==typeof s?s:\"\",t}}};function er(t,e){t.__detail=e.__detail,t.__format=e.__format,t.__mode=e.__mode,t.__style=e.__style,t.__text=e.__text}const nr=t=>{const e=De(t,\"mode\"),n=Fe(t,\"detail\",0),o=Fe(t,\"format\",0),r=Pe(t,\"mode\"),i=Ie(t,\"mode\");return{exportJSON:function(t){return{detail:t.__detail,format:t.__format,mode:e[t.__mode],style:t.__style,text:t.__text,type:t.__type,version:1}},exportCompactJSON:function(t){const n={type:t.__type},o=t.__detail;void 0!==o&&0!==o&&(n.detail=o);const r=t.__format;void 0!==r&&0!==r&&(n.format=r);const i=e[t.__mode];void 0!==i&&\"normal\"!==i&&(n.mode=i);const s=t.__style;void 0!==s&&\"\"!==s&&(n.style=s);const l=t.__text;return void 0!==l&&\"\"!==l&&(n.text=l),n},updateFromJSON:function(t,e){const s=e.detail;t.__detail=\"string\"==typeof s&&s in n?n[s]:Qo(s,0);const l=e.format;t.__format=\"string\"==typeof l&&l in o?o[l]:Qo(l,0);const c=e.mode;t.__mode=\"string\"==typeof c&&c in r?r[c]:i;const a=e.style;t.__style=\"string\"==typeof a?a:\"\";const u=e.text;return t.__text=\"string\"==typeof u?u:\"\",t},afterCloneFrom:er}},or=t=>{const e=De(t,\"format\"),n=Pe(t,\"format\"),o=Ie(t,\"format\");return{exportJSON:function(t){const n=t.__textFormat,o=t.__textStyle,r=(0!==n||\"\"!==o)&&t.shouldSerializeTextStyles();return{children:[],direction:t.__dir,format:e[t.__format],indent:t.__indent,textFormat:0!==n&&r?n:void 0,textStyle:\"\"!==o&&r?o:void 0,type:t.__type,version:1}},exportCompactJSON:function(t){const n=t.__textFormat,o=t.__textStyle,r=(0!==n||\"\"!==o)&&t.shouldSerializeTextStyles(),i={type:t.__type,children:[]},s=t.__dir;null!=s&&(i.direction=s);const l=e[t.__format];void 0!==l&&\"\"!==l&&(i.format=l);const c=t.__indent;return void 0!==c&&0!==c&&(i.indent=c),void 0!==n&&0!==n&&r&&(i.textFormat=n),void 0!==o&&\"\"!==o&&r&&(i.textStyle=o),i},updateFromJSON:function(t,e){const r=e.direction;t.__dir=null===r||\"ltr\"===r||\"rtl\"===r?r:null;const i=e.format;t.__format=\"string\"==typeof i&&i in n?n[i]:o,t.__indent=Zo(e.indent,0,0,Infinity),t.__textFormat=Qo(e.textFormat,0);const s=e.textStyle;return t.__textStyle=\"string\"==typeof s?s:\"\",t}}},rr=()=>({exportJSON:function(t){return{type:t.__type,version:1}},exportCompactJSON:function(t){return{type:t.__type}}}),ir=t=>{const e=De(t,\"mode\"),n=Fe(t,\"format\",0);return{exportJSON:function(t){return{detail:t.__detail,mode:e[t.__mode],text:t.__text,format:t.__format,style:t.__style,type:t.__type,version:1}},exportCompactJSON:function(t){const e={type:t.__type},n=t.__format;void 0!==n&&0!==n&&(e.format=n);const o=t.__style;return void 0!==o&&\"\"!==o&&(e.style=o),e},updateFromJSON:function(t,e){const o=e.format;t.__format=\"string\"==typeof o&&o in n?n[o]:Qo(o,0);const r=e.style;return t.__style=\"string\"==typeof r?r:\"\",t}}},sr=/* @__PURE__ */new WeakMap;function lr(t,e){for(let n=t;null!==n&&n!==e;n=Object.getPrototypeOf(n)){const e=n.prototype;if(void 0!==e&&Object.prototype.hasOwnProperty.call(e,\"isInline\")&&\"function\"==typeof e.isInline&&!la(e.isInline))try{const e=t.prototype.isInline.call(Object.create(t.prototype));return\"boolean\"==typeof e?e:null}catch(t){return null}}}function cr(t){for(const{ownNodeConfig:e}of da(t))if(e&&void 0!==e.children)return e.children}function ar(t){let e=sr.get(t);if(void 0===e){const n={},o={};let r=!1;for(const{klass:e,ownNodeConfig:i}of da(t))i&&(void 0===o.inline&&void 0!==i.inline&&(n.inline=i.inline,o.inline=e),void 0===o.children&&void 0!==i.children&&(n.children=i.children,o.children=e),r||void 0===i.mergeAdjacent||(r=!0,!1!==i.mergeAdjacent&&(n.mergeAdjacent=i.mergeAdjacent,o.mergeAdjacent=e)));const i=function(t){const e=new Set,n=Yc(t);for(const t of Object.keys(n))!0===n[t].derived&&e.add(t);for(const{ownNodeConfig:n}of da(t)){const t=n&&n.stateConfigs;if(t)for(const n of t){const t=n instanceof bn?n:n.stateConfig;t.derived&&e.add(t.key)}}return e}(t);void 0!==o.inline&&o.inline!==t&&void 0!==lr(t,o.inline)&&lr(t,o.inline)!==n.inline&&(delete n.inline,delete o.inline),void 0===o.mergeAdjacent||o.mergeAdjacent===t||null===function(t,e,n){const o=Yc(t);for(const t of e.by)if(\"string\"==typeof t){if(!(t in o))return{entry:t,reason:\"unknown\"};if(n.has(t))return{entry:t,reason:\"derived\"}}else if(t.derived)return{entry:String(t.key),reason:\"derived-state\"};return null}(t,n.mergeAdjacent,i)&&null===function(t,e){if(!Array.isArray(e)||e.includes(\"inline\"))return null;for(const n of e){if(\"inline\"===n)continue;const e=cr(n);if(!(\"inline\"===e||Array.isArray(e)&&e.includes(\"inline\")&&e.every(e=>\"inline\"===e||e===t||t.prototype instanceof e)))return n}return null}(t,n.children)||(delete n.mergeAdjacent,delete o.mergeAdjacent),e=Object.freeze({...n,declaredBy:Object.freeze(o),derived:i,derivedNames:i}),sr.set(t,e)}return e}function ur(t){const{derivedNames:e,...n}=ar(t);return Object.freeze({...n,derived:new Set(e)})}const fr=/* @__PURE__ */new WeakMap;function dr(t){return function(t){let e=fr.get(t);if(void 0===e){e=!1;for(const{ownNodeConfig:n,ownNodeType:o}of da(t))if(void 0!==n&&\"overflow\"===o&&n.extends===ei){e=!0;break}fr.set(t,e)}return e}(t.constructor)}function hr(t){if(Mi(t)||Ba(t)||dr(t))return!0;try{return t.isInline()}catch(t){return!0}}function gr(t){return Mi(t)||Ba(t)||ii(t)&&hr(t)}function _r(t,e){if(dr(e))return!0;if(\"inline\"===t)return hr(e);if(\"block\"===t)return!hr(e);if(hr(e))return t.includes(\"inline\");for(const n of t)if(\"inline\"!==n&&e instanceof n)return!0;return!1}function pr(t){return Il(t)?\"block\":ar(t.constructor).children}function yr(t,e){return rs(e)&&!e.isShadowRoot()&&e.getChildren().every(e=>_r(t,e))}function mr(t,e){const n=[];for(let o=t;null!==o;o=ni(o)?e?o.getLastChild():o.getFirstChild():null)n.push(o.getKey());return n}function xr(t){if(\"text\"===t.type)return{offset:t.offset,text:t.key};const e=t.getNode();if(!ni(e))return null;const n=Math.min(t.offset,e.getChildrenSize()),o=n>0?e.getChildAtIndex(n-1):null,r=e.getChildAtIndex(n);if(null!==o&&gr(o))return{after:!0,keys:[o.getKey()]};if(null!==r&&gr(r))return{after:!1,keys:[r.getKey()]};let i=o,s=r;const l=pr(e);if(\"inline\"===l||Array.isArray(l)&&l.includes(\"inline\")){for(;null!==i&&vr(i);)i=i.getPreviousSibling();for(;null!==s&&vr(s);)s=s.getNextSibling();null===i&&null===s&&(i=o,s=r)}return null!==i&&gr(i)?{after:!0,keys:[i.getKey()]}:null!==s&&gr(s)?{after:!1,keys:[s.getKey()]}:null!==s?{after:!1,keys:mr(s,!1)}:null!==i?{after:!0,keys:mr(i,!0)}:{inside:e.getKey()}}function vr(t){if(!ni(t)||rs(t)||hr(t))return!1;const e=t=>t.getChildren().some(t=>!ni(t)||e(t));return!e(t)}class Sr{path=(()=>new Set)();pathByParent=(()=>new Map)();touched=(()=>new Set)();substitutes=(()=>new Map)();written=(()=>new Set)();changed=!1;full=!1;wrapsAll=(()=>new Set)();addPath(t){const e=t.getKey();this.path.add(e);const n=t.getLatest().__parent;if(null!==n){let t=this.pathByParent.get(n);void 0===t&&(t=new Set,this.pathByParent.set(n,t)),t.add(e)}}$children(t){if(this.full)return t.getChildren();const e=t.getKey(),n=this.pathByParent.get(e);if(void 0===n)return[];const o=this.childrenCache.get(e);if(void 0!==o&&o.size===n.size)return o.nodes;const r=[];for(const t of n){const n=Bs(t);null!==n&&n.getLatest().__parent===e&&r.push(n)}return this.childrenCache.set(e,{nodes:r,size:n.size}),r}childrenCache=(()=>new Map)();addPathChain(t){for(let e=t;null!==e;e=e.getParent()){const t=e.getLatest().__parent,n=null===t?void 0:this.pathByParent.get(t);if(void 0!==n&&n.has(e.getKey()))return;this.addPath(e)}}repath(){for(const[t,e]of Array.from(this.pathByParent)){const n=Bs(t);if(null===n||!n.isAttached()){this.pathByParent.delete(t);for(const t of e){const e=Bs(t);null!==e&&e.isAttached()&&this.addPathChain(e)}}}}movePath(t,e){const n=this.pathByParent.get(t);if(void 0!==n){this.pathByParent.delete(t);for(const t of n){const e=Bs(t);null!==e&&this.addPath(e)}}this.addPath(e)}$resolve(t,e=0){if(\"text\"in t){const e=Bs(t.text);return null!==e&&e.isAttached()?[t.text,t.offset,\"text\"]:null}if(\"inside\"in t){const n=Bs(t.inside);if(null!==n&&n.isAttached())return[t.inside,0,\"element\"];const o=this.substitutes.get(t.inside);return void 0!==o&&e<16?this.$resolve(o,e+1):null}const{keys:n,after:o}=t;for(let t=n.length-1;t>=0;t--){const r=Bs(n[t]);if(null===r||!r.isAttached()||null===r.getParent()){const o=this.substitutes.get(n[t]);if(void 0!==o&&e<16)return this.$resolve(o,e+1);continue}let i=r;for(let e=0;e<t;e++){const t=i.getParent();if(null===t||Il(t)||null!==(o?i.getNextSibling():i.getPreviousSibling()))break;i=t}return Mi(i)?[i.getKey(),o?i.getTextContentSize():0,\"text\"]:[i.getParentOrThrow().getKey(),i.getIndexWithinParent()+(o?1:0),\"element\"]}return null}}function Cr(t,e){e.length>0&&ei.prototype.splice.call(t,t.getChildrenSize(),0,e)}function br(t){Bo(t,!1,!0)}function kr(t,e){if(t.constructor!==e.constructor||!ni(t)||!ni(e))return!1;const n=t.constructor,o=ar(n),r=o.mergeAdjacent;if(void 0===r||o.declaredBy.mergeAdjacent!==n)return!1;let i,s;for(const n of r.by)if(\"string\"==typeof n){i=i||t.exportJSON(),s=s||e.exportJSON();const o=i[n],r=s[n];if(o!==r&&JSON.stringify(o)!==JSON.stringify(r))return!1}else if(!n.isEqual(Tn(t,n),Tn(e,n)))return!1;return!0}function Tr(t,e,n){const o=t.getLastChild(),r=e.getFirstChild();if(n.substitutes.set(e.getKey(),null!==o?{after:!0,keys:mr(o,!0)}:{inside:t.getKey()}),Cr(t,e.getChildren()),br(e),n.movePath(e.getKey(),t),n.changed=!0,n.written.add(t.getKey()),null===o||null===r)return;if(ni(o)&&kr(o,r))return void Tr(o,r,n);const i=t.INTERNAL_$afterStructureMerge;\"function\"==typeof i&&(i.call(t,o,r),n.full||n.repath())}function Nr(t,e){let n=t;for(let t=n.getPreviousSibling();null!==t&&kr(t,n);t=n.getPreviousSibling())n=t;for(let t=n.getNextSibling();null!==t&&kr(n,t);t=n.getNextSibling())Tr(n,t,e);return n}function wr(t,e,n=!1){if(n||e.full)for(let n=t.getFirstChild();null!==n;)n=Nr(n,e).getNextSibling();else for(const n of e.$children(t)){const o=n.constructor;ar(o).declaredBy.mergeAdjacent===o&&n.getLatest().__parent===t.getKey()&&Nr(n,e)}}function Er(t,e,n){n.changed=!0;for(const e of t.getChildren())br(e);const o=[],r=[],i=[];let s=!1;for(const n of e){if(\"lifted\"in n){o.push(n.lifted);continue}if(!n.hadChildren)continue;let e;if(s){e=Ll(t);const n=e.INTERNAL_$afterStructureSplit;\"function\"==typeof n&&n.call(e,t,i)}else s=!0,e=t;Cr(e,n.content),n.holder=e,i.push(...n.content),o.push(e),r.push(e)}const l=t.getParentOrThrow();n.written.add(l.getKey());const c=o.indexOf(t);let a=t;for(let t=c-1;t>=0;t--)th(a,\"previous\",o[t],!1),a=o[t];a=t;for(let t=c+1;t<o.length;t++)th(a,\"next\",o[t],!1),a=o[t];for(const t of o)n.addPath(t),n.touched.add(t.getKey());return-1===c&&(o.length>0&&n.substitutes.set(t.getKey(),{after:!1,keys:mr(o[0],!1)}),br(t)),r}function Ar(t,e,n){const o=t.isInline();return n.map(t=>_r(e,t)?\"keep\":!o&&yr(e,t)?\"join\":hr(t)?\"keep\":\"lift\")}function Or(t,e){const n=t[0],o=void 0===n?void 0:cr(n);return e.map(e=>_r(t,e)?\"keep\":void 0===n||void 0!==o&&!_r(o,e)?void 0!==n&&void 0!==o&&yr(o,e)?\"flatten\":hr(e)?\"keep\":\"lift\":\"wrap\")}function Mr(t,e,n){const o=[];let r=[];const i=()=>{if(r.length>0){const t=Ll(e);th(r[0],\"previous\",t,!1),Cr(t,r),o.push(t),r=[]}};for(const o of t.getChildren())!hr(o)||dr(o)?(i(),ni(o)&&Mr(o,e,n)):r.push(o);if(i(),0===o.length)return;n.changed=!0,n.written.add(t.getKey());const s=pr(t);void 0!==s&&o.some(t=>!_r(s,t))&&Lr(t,s,!0,n)}function Dr(t,e){const n=t=>null!==t&&!_r(\"block\",t);if(!n(t))return;let o=t;for(let t=o.getPreviousSibling();n(t);t=o.getPreviousSibling())o=t;const r=[o];for(let t=o.getNextSibling();n(t);t=t.getNextSibling())r.push(t);const i=o.createParentElementNode();th(o,\"previous\",i,!1),Cr(i,r),e.changed=!0,e.written.add(i.getKey()),e.addPath(i),e.touched.add(i.getKey())}const Pr=/* @__PURE__ */new WeakMap;function Fr(t){let e=Ir.get(t);if(void 0===e){const n=t.prototype;e=n.isShadowRoot!==ei.prototype.isShadowRoot||n.isInline!==ei.prototype.isInline&&!la(n.isInline),Ir.set(t,e)}return e}const Ir=/* @__PURE__ */new WeakMap;function Lr(t,e,n,o){if(\"block\"===e&&n&&!$r(t))return null;const r=t.getKey(),i=n?t.getChildren():o.$children(t).filter(t=>t.getLatest().__parent===r);if(\"block\"===e){for(const t of i)t.getLatest().__parent===r&&Dr(t,o);return null}return\"inline\"===e||e.includes(\"inline\")?Ar(t,e,i).every(t=>\"keep\"===t)?null:function(t,e,n){const o=t.isInline(),r=t.getChildren(),i=Ar(t,e,r);if(i.every(t=>\"keep\"===t))return[t];const s=[],l=[];let c={content:[],hadChildren:!1,holder:null},a=\"none\";for(let e=0;e<r.length;e++){const u=r[e],f=i[e];if(\"lift\"===f){o&&ni(u)&&Mr(u,t,n),s.push(c,{lifted:u}),c={content:[],hadChildren:!1,holder:null},a=\"none\";continue}if(c.hadChildren=!0,\"join\"===f){\"inline\"!==a&&\"line\"!==a||c.content.push(za());const t=u.getChildren();0===t.length&&l.push({at:c.content.length,paragraph:u,segment:c}),c.content.push(...t),a=\"line\";continue}const d=hr(u)?\"inline\":\"block\";\"inline\"===d&&\"line\"===a&&c.content.push(za()),c.content.push(u),a=d}s.push(c);const u=Er(t,s,n);for(const{paragraph:e,segment:o,at:r}of l){const i=r>0?o.content[r-1]:void 0,s=o.content[r];n.substitutes.set(e.getKey(),void 0!==i?{after:!0,keys:mr(i,!0)}:void 0!==s?{after:!1,keys:mr(s,!1)}:{inside:(o.holder||t).getKey()})}return u}(t,e,o):Or(e,i).every(t=>\"keep\"===t)?null:function(t,e,n){const o=e[0],r=t.getChildren(),i=Or(e,r);if(i.every(t=>\"keep\"===t))return[t];const s=[];let l={content:[],hadChildren:!1,holder:null};for(let t=0;t<r.length;t++){const e=r[t],c=i[t];if(\"lift\"!==c)if(l.hadChildren=!0,\"keep\"===c)l.content.push(e);else if(\"flatten\"===c){const t=ga(o);Cr(t,e.getChildren()),n.substitutes.set(e.getKey(),{inside:t.getKey()}),l.content.push(t)}else{const n=[e];for(;hr(e)&&t+1<r.length&&\"wrap\"===i[t+1]&&hr(r[t+1]);)n.push(r[++t]);const s=ga(o);Cr(s,n),l.content.push(s)}else s.push(l,{lifted:e}),l={content:[],hadChildren:!1,holder:null}}return s.push(l),Er(t,s,n)}(t,e,o)}function Kr(t,e){const n=pr(t),o=void 0!==n&&(function(t,e){if(ci(t)||!Fr(t.constructor))return e.full;const n=t.getLatest(),o=(Il(t)?1:0)+(hr(t)?2:0);let r=Pr.get(n);if(void 0===r){const e=mc().getEditorState()._nodeMap.get(t.getKey());r=void 0===e?void 0:Pr.get(e)}return Pr.set(n,o),e.full||r!==o}(t,e)||\"block\"===n&&e.wrapsAll.has(t.getKey()));if(!e.full&&!e.pathByParent.has(t.getKey())){if(t.isEmpty()&&!Il(t)&&zr(t))return Br(t,e),!0;if(!o)return!1}wr(t,e);let r=!1;for(const n of e.$children(t))ni(n)&&n.getLatest().__parent===t.getKey()&&Kr(n,e)&&(r=!0);if(t.isEmpty()&&!Il(t)&&(zr(t)||r&&!t.canBeEmpty()))return Br(t,e),!0;const i=void 0===n?null:Lr(t,n,o,e);if(null===i)wr(t,e);else for(const t of i)wr(t,e,!0);return!1}function zr(t){return dr(t)||hr(t)&&!t.canBeEmpty()}function Br(t,e){const n=t.getPreviousSibling(),o=t.getNextSibling(),r=t.getParentOrThrow();e.substitutes.set(t.getKey(),null!==n?{after:!0,keys:mr(n,!0)}:null!==o?{after:!1,keys:mr(o,!1)}:{inside:r.getKey()}),br(t);for(const t of[n,o])null!==t&&(e.addPath(t),e.touched.add(t.getKey()));e.changed=!0,e.written.add(r.getKey())}const Rr=/* @__PURE__ */new WeakMap;function Wr(t,e){if(void 0===e||!ni(t))return!1;const n=t.constructor;if(e.constructor!==n||!function(t){let e=Rr.get(t);return void 0===e&&(e=!Fr(t)&&ar(t).declaredBy.mergeAdjacent!==t,Rr.set(t,e)),e}(n))return!1;const o=t,r=e;return r.__parent===o.__parent&&r.__prev===o.__prev&&r.__next===o.__next&&r.__first===o.__first&&r.__last===o.__last&&r.__size===o.__size}function jr(t){if(!ni(t))return!1;try{return!t.isInline()}catch(t){return!1}}function $r(t){for(let e=t.getFirstChild();null!==e;e=e.getNextSibling())if(!jr(e)&&!_r(\"block\",e))return!0;return!1}function Ur(t,e){const n=Od(),o=Xf(n)?[n.anchor,n.focus].map(t=>({anchor:xr(t),point:t})):[];e(t);for(const e of t.written){const t=Bs(e);if(null!==t&&t.isAttached())for(let e=t;null!==e&&!ci(e);e=e.getParent())e.markDirty()}if(t.changed)for(const{point:e,anchor:n}of o){const o=n&&t.$resolve(n);o&&e.set(o[0],o[1],o[2])}}function Jr(t){if(!ni(t)||!t.isAttached())return;const e=new Sr;e.full=!0;const n=t.getParent();Ur(e,()=>{if(null===n||Il(t))return void Kr(t,e);const o=n.getKey();e.touched.add(t.getKey()),Kr(t,e);for(const t of Array.from(e.touched)){const n=Bs(t);null!==n&&n.getLatest().__parent===o&&Nr(n,e)}})}let Vr;function Hr(t){const e=Vr||(Vr=new WeakMap);let n=e.get(t);if(void 0===n){const o=[],r=new Set,i=t=>{const e=t.__key;o.push(e),r.add(e)},s=new WeakSet([t.getEditorState()]);let l=!0;const c=()=>{const t=l;l=!1,function(t,e,n){const o=Hs();if(0===t.length&&!e&&!$r(o))return;const r=new Sr;r.full=e;const i=o.getKey();r.wrapsAll.add(i),r.path.add(i);const s=n?mc().getEditorState()._nodeMap:null,l=[];for(const n of e?[]:t){l.length=0;let t=!1;const e=Bs(n);if(ni(e)&&e.isShadowRoot()&&r.wrapsAll.add(n),null===s||null===e||!Wr(e,s.get(n))){for(let n=e;null!==n;n=n.getParent()){if(r.path.has(n.getKey())){t=!0;break}l.push(n)}if(t)for(const t of l)r.addPath(t)}}t.length=0,(r.path.size>1||e||$r(o))&&Ur(r,()=>{Kr(o,r)})}(o,t,!s.has(mc().getEditorState()))},a=t.registerUpdateListener(({editorState:t,dirtyElements:e,dirtyLeaves:n})=>{const o=t._nodeMap,i=t=>!r.has(t)&&o.has(t);let l=!0;for(const[t,n]of e)if(n&&\"root\"!==t&&i(t)){l=!1;break}if(l)for(const t of n)if(i(t)){l=!1;break}r.clear(),l||s.add(t)}),u=[],f=[];for(const[e,{klass:n,transforms:o}]of t._nodes){const t=\"root\"===e?c:i;o.add(t),u.push([o,t]),(n.prototype instanceof ei||n.prototype instanceof ri)&&f.push(e)}n={dispose:()=>{a();for(const[t,e]of u)t.delete(e)},refs:0},e.set(t,n),Vs(t,f)}n.refs++;let o=!1;const r=n;return()=>{o||(o=!0,0===--r.refs&&(r.dispose(),e.delete(t)))}}function qr(t){return void 0!==Vr&&Vr.has(t)}function Yr(){return{...j,0:\"\"}}function Xr(){return{...R,\"\":0}}const Gr=/* @__PURE__ */Yr(),Qr=/* @__PURE__ */Xr(),Zr=/* @__PURE__ */un()({direction:/* @__PURE__ */mn(/* @__PURE__ */rn([null,\"ltr\",\"rtl\"]),{field:\"__dir\"}),format:/* @__PURE__ */mn(/* @__PURE__ */rn([\"\",\"left\",\"start\",\"center\",\"right\",\"end\",\"justify\"]),{field:\"__format\",getter:\"getFormatType\",getterTable:Gr,setter:\"setFormat\",setterTable:Qr}),indent:/* @__PURE__ */mn(/* @__PURE__ */nn(0,{integer:!0,min:0}),{field:\"__indent\"}),textFormat:/* @__PURE__ */xn(/* @__PURE__ */nn(),{getter:{field:\"__textFormat\",method:\"getSerializedTextFormat\",when:\"shouldSerializeTextStyles\"},setter:{field:\"__textFormat\"}}),textStyle:/* @__PURE__ */xn(/* @__PURE__ */tn(),{getter:{field:\"__textStyle\",method:\"getSerializedTextStyle\",when:\"shouldSerializeTextStyles\"},setter:{field:\"__textStyle\"}})});function ti(t){if(Il(t)&&!qr(bu())){let e=null;for(const n of t.getChildren())e=n.isInline()?(e||n.replace(n.createParentElementNode())).append(n):null}}class ei extends Uo{__first;__last;__size;__format;__style;__indent;__dir;__textFormat;__textStyle;__slotHost;__slots;$config(){return this.config(Symbol.for(\"ElementNode\"),{$transform:ti,extends:Uo,generated:tr,json:Zr})}constructor(t){super(t),this.__first=null,this.__last=null,this.__size=0,this.__format=0,this.__style=\"\",this.__indent=0,this.__dir=null,this.__textFormat=0,this.__textStyle=\"\",this.__slotHost=null,this.__slots=null}afterCloneFrom(t){super.afterCloneFrom(t),this.__key===t.__key&&(this.__first=t.__first,this.__last=t.__last,this.__size=t.__size,this.__slotHost=t.__slotHost,null!==this.__slotHost&&null!==this.__parent&&e(384,this.__key,String(this.__slotHost),String(this.__parent)),this.__slots=t.__slots),this.__style=t.__style,function(t,e){t.__dir=e.__dir,t.__format=e.__format,t.__indent=e.__indent,t.__textFormat=e.__textFormat,t.__textStyle=e.__textStyle}(this,t)}getFormat(){return this.getLatest().__format}getFormatType(){const t=this.getFormat();return j[t]||\"\"}getStyle(){return this.getLatest().__style}getIndent(){return this.getLatest().__indent}getChildren(){return nh(this.getFirstChild(),\"next\")}getChildrenKeys(){const t=[];let e=this.getFirstChild();for(;null!==e;)t.push(e.__key),e=e.getNextSibling();return t}getChildrenSize(){return this.getLatest().__size}isEmpty(){return 0===this.getChildrenSize()&&0===dh(this).length}isDirty(){const t=bu()._dirtyElements;return null!==t&&t.has(this.__key)}isLastChild(){const t=this.getLatest(),e=this.getParentOrThrow().getLastChild();return null!==e&&e.is(t)}getAllTextNodes(){const t=[];for(const e of dh(this)){const n=hh(this,e);if(ni(n))for(const e of n.getAllTextNodes())t.push(e)}let e=this.getFirstChild();for(;null!==e;){if(Mi(e)&&t.push(e),ni(e))for(const n of e.getAllTextNodes())t.push(n);e=e.getNextSibling()}return t}getFirstDescendant(){let t=this.getFirstChild();for(;ni(t);){const e=t.getFirstChild();if(null===e)break;t=e}return t}getLastDescendant(){let t=this.getLastChild();for(;ni(t);){const e=t.getLastChild();if(null===e)break;t=e}return t}getDescendantByIndex(t){const e=t>=this.getChildrenSize(),n=e?this.getLastChild():this.getChildAtIndex(t);return ni(n)&&(e?n.getLastDescendant():n.getFirstDescendant())||n}getFirstChild(){const t=this.getLatest().__first;return null===t?null:Bs(t)}getFirstChildOrThrow(){const t=this.getFirstChild();return null===t&&e(45,this.__key),t}getLastChild(){const t=this.getLatest().__last;return null===t?null:Bs(t)}getLastChildOrThrow(){const t=this.getLastChild();return null===t&&e(96,this.__key),t}getChildAtIndex(t){const e=this.getChildrenSize();let n,o;if(t<e/2){for(n=this.getFirstChild(),o=0;null!==n&&o<=t;){if(o===t)return n;n=n.getNextSibling(),o++}return null}for(n=this.getLastChild(),o=e-1;null!==n&&o>=t;){if(o===t)return n;n=n.getPreviousSibling(),o--}return null}getTextContent(){let t=vh(this);const e=this.getChildren(),n=e.length;for(let o=0;o<n;o++){const r=e[o];t+=r.getTextContent(),ni(r)&&o!==n-1&&!r.isInline()&&(t+=M)}return t}getTextContentSize(){let t=function(t){let e=0;for(const n of fh(t).values()){const t=Bs(n);null!==t&&(e+=t.getTextContentSize())}return e}(this);const e=this.getChildren(),n=e.length;for(let o=0;o<n;o++){const r=e[o];t+=r.getTextContentSize(),ni(r)&&o!==n-1&&!r.isInline()&&(t+=2)}return t}getDirection(){return this.getLatest().__dir}getTextFormat(){return this.getLatest().__textFormat}hasFormat(t){if(\"\"!==t){const e=R[t];return 0!==(this.getFormat()&e)}return!1}hasTextFormat(t){const e=z[t];return 0!==(this.getTextFormat()&e)}getFormatFlags(t,e){return Os(this.getLatest().__textFormat,t,e)}getTextStyle(){return this.getLatest().__textStyle}select(t,e){xu();const n=Od();let o=t,r=e;const i=this.getChildrenSize();if(!this.canBeEmpty())if(0===t&&0===e){const t=this.getFirstChild();if(Mi(t)||ni(t))return t.select(0,0)}else if(!(void 0!==t&&t!==i||void 0!==e&&e!==i)){const t=this.getLastChild();if(Mi(t)||ni(t))return t.select()}void 0===o&&(o=i),void 0===r&&(r=i);const s=this.__key;return Xf(n)?(n.anchor.set(s,o,\"element\"),n.focus.set(s,r,\"element\"),n.dirty=!0,n):bd(s,o,s,r,\"element\",\"element\")}selectStart(){const t=this.getFirstDescendant();return t?t.selectStart():this.select()}selectEnd(){const t=this.getLastDescendant();return t?t.selectEnd():this.select()}clear(){const t=this.getWritable();return this.getChildren().forEach(t=>t.remove()),t}append(...t){return this.splice(this.getChildrenSize(),0,t)}setDirection(t){const e=this.getWritable();return e.__dir=t,e}setFormat(t){const e=this.getWritable();return e.__format=\"\"!==t&&R[t]||0,e}setStyle(t){const e=this.getWritable();return e.__style=t||\"\",e}setTextFormat(t){const e=this.getWritable();return e.__textFormat=t,e}setTextStyle(t){const e=this.getWritable();return e.__textStyle=t,e}setIndent(t){const e=this.getWritable();return e.__indent=t,e}splice(t,n,o){jo(this)&&e(324,this.__key,this.__type);const r=this.getChildrenSize(),i=this.getWritable();t+n<=r||e(226,String(t),String(n),String(r));for(const t of o);const s=i.__key,l=[];let c=[],a=this.getChildAtIndex(t+n),u=null,f=r-n+o.length;if(0!==t)if(t===r)u=this.getLastChild();else{const e=this.getChildAtIndex(t);null!==e&&(u=e.getPreviousSibling())}n>0&&(c=function(t,n,o,r){const i=[];let s=n;for(let t=0;t<o;t++){null===s&&e(100);const t=s.getNextSibling();i.push(s.getWritable()),s=t}return Yd(t,r&&r.getWritable(),s&&s.getWritable()),t.__size-=i.length,i.map(t=>(Xd(t),t.__prev=null,t.__next=null,t.__parent=null,t.__key))}(i,null===u?this.getFirstChild():u.getNextSibling(),n,u));let d=o.length>0&&null!==u?u.getWritable():null;for(const t of o){null!==d&&t.is(d)&&(u=d.getPreviousSibling(),d=u&&u.getWritable()),null!==a&&t.is(a)&&(a=a.getNextSibling());const n=t.getWritable();n.__parent===s&&f--,Qd(n);const o=t.__key;Gd(i,n,d,a&&a.getWritable()),t.__key===s&&e(76),l.push(o),d=n}if(i.__size=f,c.length){const t=Od();if(Xf(t)){const e=new Set(c),n=new Set(l);for(const o of[t.anchor,t.focus])oi(o,e,n)&&Fd(o,o.getNode(),this,u,a);0!==f||this.canBeEmpty()||Il(this)||this.remove()}}return i}getDOMSlot(t){return new ye(t)}exportDOM(t){const{element:e}=super.exportDOM(t);if(uc(e)){const t=this.getIndent();t>0&&(e.style.paddingInlineStart=40*t+\"px\",e.setAttribute(\"data-lexical-indent\",String(t)));const n=this.getDirection();n&&(e.dir=n)}return{element:e}}shouldSerializeTextStyles(){if(Il(this))return!1;for(let t=this.getFirstChild();null!==t;t=t.getNextSibling())if(Mi(t))return!1;return!0}getSerializedTextFormat(){const t=this.getTextFormat();return 0!==t&&this.shouldSerializeTextStyles()?t:void 0}getSerializedTextStyle(){const t=this.getTextStyle();return\"\"!==t&&this.shouldSerializeTextStyles()?t:void 0}insertNewAfter(t,e){return null}canIndent(){return!0}collapseAtStart(t){return!1}excludeFromCopy(t){return!1}canReplaceWith(t){return!0}canInsertAfter(t){return!0}canBeEmpty(){return!0}canInsertTextBefore(){return!0}canInsertTextAfter(){return!0}isInline(){return!1}isShadowRoot(){return!1}canMergeWith(t){return!1}extractWithChild(t,e,n){return!1}canMergeWhenEmpty(){return!1}reconcileObservedMutation(t,e){e.read(\"latest\",()=>{let n=vc(this,t,e);const o=n.element;n.after&&n.after.parentNode!==o&&(n=n.withAfter(null)),n.before&&n.before.parentNode!==o&&(n=n.withBefore(null));const r=n.getManagedLineBreak();r&&n.insertManagedLineBreak(\"IMG\"===r.nodeName);let i=n.getFirstChild();for(const t of this.getChildrenKeys()){const r=e.getElementByKey(t);if(!r)continue;let s,l=i;for(;l&&!(s=js(l,e))&&Fc(l);)l=l.nextSibling;l!==r&&o.insertBefore(r,s?l:i||n.getInsertionAnchor()),i=r.nextSibling}Oo(this,t,n)})}}function ni(t){return t instanceof ei}function oi(t,e,n){let o=t.getNode();for(;o;){const t=o.__key;if(e.has(t)&&!n.has(t))return!0;o=o.getParent()}return!1}class ri extends Uo{__slotHost;__slots;constructor(t){super(t),this.__slotHost=null,this.__slots=null}afterCloneFrom(t){super.afterCloneFrom(t),this.__key===t.__key&&(this.__slotHost=t.__slotHost,null!==this.__slotHost&&null!==this.__parent&&e(383,this.__key,String(this.__slotHost),String(this.__parent)),this.__slots=t.__slots)}decorate(t,e){return null}isIsolated(){return!1}isInline(){return!0}isKeyboardSelectable(){return!0}}function ii(t){return t instanceof ri}function si(t){const e=t.getLatest().__cachedText;return null===e||!mu()&&0!==bu()._dirtyType?null:e}class li extends ei{__cachedText;$config(){return this.config(\"root\",{extends:ei})}constructor(){super(\"root\"),this.__cachedText=null}getTopLevelElementOrThrow(){e(51)}getTextContent(){const t=si(this);return null!==t?t:super.getTextContent()}getTextContentSize(){const t=si(this);return null!==t?t.length:super.getTextContentSize()}remove(){e(52)}replace(t){e(53)}insertBefore(t){e(54)}insertAfter(t){e(55)}updateDOM(t,e){return!1}splice(t,n,o){for(const t of o)ni(t)||ii(t)||e(282);return super.splice(t,n,o)}static importJSON(t){return Hs().updateFromJSON(t)}collapseAtStart(){return!0}}function ci(t){return t instanceof li}function ai(t){const e={};if(!t)return e;let n=\"\",o=\"\",r=null,i=!1,s=!1,l=!1,c=0;const a=t.length;let u=-1;for(let f=0;f<a;f++){const a=t[f];if(i)\"*\"===a&&\"/\"===t[f+1]&&(i=!1,f++);else if(s)-1===u&&(u=f),s=!1;else if(null===r)if(\"/\"!==a||\"*\"!==t[f+1])if('\"'!==a&&\"'\"!==a)if(\"(\"!==a)if(\")\"!==a)if(l||\":\"!==a||0!==c){if(\";\"===a&&0===c){-1!==u&&(l?o+=t.slice(u,f):n+=t.slice(u,f),u=-1);const r=n.trim(),i=o.trim();\"\"!==r&&\"\"!==i&&(e[r]=i),n=\"\",o=\"\",l=!1;continue}-1===u&&(u=f)}else-1!==u&&(n+=t.slice(u,f),u=-1),l=!0;else-1===u&&(u=f),c=Math.max(0,c-1);else-1===u&&(u=f),c++;else-1===u&&(u=f),r=a;else-1!==u&&(l?o+=t.slice(u,f):n+=t.slice(u,f),u=-1),i=!0,f++;else-1===u&&(u=f),\"\\\\\"===a?s=!0:a===r&&(r=null)}-1!==u&&(l?o+=t.slice(u,a):n+=t.slice(u,a));const f=n.trim(),d=o.trim();return\"\"!==f&&\"\"!==d&&(e[f]=d),e}function ui(t,e,n){const o=n.trimEnd(),r=o.length-10;r>=0&&\"!important\"===o.slice(r).toLowerCase()?t.setProperty(e,o.slice(0,r).trim(),\"important\"):t.setProperty(e,n,\"\")}function fi(t,e){for(const n in e){const o=e[n];null==o?t.removeProperty(n):ui(t,n,o)}}function di(t,e,n=\"\"){if(e===n)return;const o=ai(n),r=ai(e);for(const e in r)delete o[e],ui(t,e,r[e]);for(const e in o)t.removeProperty(e)}const hi=/* @__PURE__ */un()({detail:/* @__PURE__ */mn(/* @__PURE__ */fn(/* @__PURE__ */nn(),B),{field:\"__detail\"}),format:/* @__PURE__ */mn(/* @__PURE__ */fn(/* @__PURE__ */nn(),z),{field:\"__format\"}),mode:/* @__PURE__ */mn(/* @__PURE__ */rn([\"normal\",\"token\",\"segmented\"]),{field:\"__mode\",getterTable:U,setterTable:$}),style:/* @__PURE__ */mn(/* @__PURE__ */tn(),{field:\"__style\"}),text:/* @__PURE__ */mn(/* @__PURE__ */tn(),{field:\"__text\",getter:\"getTextContent\",setter:\"setTextContent\"})});function gi(t,e){return 16&e?\"code\":128&e?\"mark\":32&e?\"sub\":64&e?\"sup\":null}function _i(t,e){return 1&e?\"strong\":2&e?\"em\":\"span\"}function pi(t,e,n,o,r){const i=o.classList;let s=gl(r,\"base\");void 0!==s&&i.add(...s),s=gl(r,\"underlineStrikethrough\");let l=!1;const c=8&e&&4&e;void 0!==s&&(8&n&&4&n?(l=!0,c||i.add(...s)):c&&i.remove(...s));for(const t in z){const o=z[t];if(s=gl(r,t),void 0!==s)if(n&o){if(l&&(\"underline\"===t||\"strikethrough\"===t)){e&o&&i.remove(...s);continue}(0===(e&o)||c&&\"underline\"===t||\"strikethrough\"===t)&&i.add(...s)}else e&o&&i.remove(...s)}hl(o,\"class\")}function yi(t,e,n){const o=n.isComposing(),r=t+(o?O:\"\"),i=mc(),s=xc(i).$getDOMSlot(n,e,i),l=s.getFirstChild();if(null===l||l.nodeType!==Node.TEXT_NODE)return void s.insertChild(Yl().createTextNode(r));const c=l,a=c.nodeValue;if(a!==r)if(o||u||y){const[t,e,n]=function(t,e){const n=t.length,o=e.length;let r=0,i=0;for(;r<n&&r<o&&t[r]===e[r];)r++;for(;i+r<n&&i+r<o&&t[n-i-1]===e[o-i-1];)i++;return[r,n-r-i,e.slice(r,o-i)]}(a,r);c.replaceData(t,e,n)}else c.nodeValue=r}function mi(t,e,n,o,r,i){yi(r,t,e);const s=i.theme.text;void 0!==s&&pi(0,0,o,t,s)}function xi(t,e){const n=Yl().createElement(e);return n.appendChild(t),n}function vi(t){return null!=t&&!0===t.__isInlineFormattable}class Si extends Uo{__text;__format;__style;__mode;__detail;get __isInlineFormattable(){return!0}$config(){return this.config(\"text\",{extends:Uo,generated:nr,importDOM:{\"#text\":()=>({conversion:Ni,priority:0}),b:()=>({conversion:bi,priority:0}),code:()=>({conversion:Ai,priority:0}),em:()=>({conversion:Ai,priority:0}),i:()=>({conversion:Ai,priority:0}),mark:()=>({conversion:Ai,priority:0}),s:()=>({conversion:Ai,priority:0}),span:()=>({conversion:Ci,priority:0}),strong:()=>({conversion:Ai,priority:0}),sub:()=>({conversion:Ai,priority:0}),sup:()=>({conversion:Ai,priority:0}),u:()=>({conversion:Ai,priority:0})},json:hi})}constructor(t=\"\",e){super(e),this.__text=t,this.__format=0,this.__style=\"\",this.__mode=0,this.__detail=0}getFormat(){return this.getLatest().__format}getDetail(){return this.getLatest().__detail}getMode(){const t=this.getLatest();return U[t.__mode]}getStyle(){return this.getLatest().__style}isToken(){return 1===this.getLatest().__mode}isComposing(){return this.__key===Ks()}isSegmented(){return 2===this.getLatest().__mode}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(t){const e=z[t];return 0!==(this.getFormat()&e)}isSimpleText(){const t=this.getLatest();return\"text\"===t.__type&&0===t.__mode}getTextContent(){return this.getLatest().__text}getFormatFlags(t,e){return Os(this.getLatest().__format,t,e)}canHaveFormat(){return!0}isInline(){return!0}createDOM(t,e){const n=this.__format,o=gi(0,n),r=_i(0,n),i=null===o?r:o,s=Yl().createElement(i);let l=s;this.hasFormat(\"code\")&&s.setAttribute(\"spellcheck\",\"false\"),null!==o&&(l=Yl().createElement(r),s.appendChild(l)),mi(l,this,0,n,this.__text,t);const c=this.__style;return\"\"!==c&&di(s.style,c),s}updateDOM(t,n,o){const r=this.__text,i=t.__format,s=this.__format,l=gi(0,i),c=gi(0,s),a=_i(0,i),u=_i(0,s);if((null===l?a:l)!==(null===c?u:c))return!0;if(l===c&&a!==u){const t=n.firstChild;null==t&&e(48);const i=Yl().createElement(u);return mi(i,this,0,s,r,o),n.replaceChild(i,t),!1}let f=n;null!==c&&null!==l&&(f=n.firstChild,null==f&&e(49)),yi(r,f,this);const d=o.theme.text;void 0!==d&&i!==s&&pi(0,i,s,f,d);const h=t.__style,g=this.__style;return h!==g&&(di(n.style,g,h),hl(n,\"style\")),!1}exportDOM(t){let{element:n}=super.exportDOM(t);return uc(n)||e(132),n.style.whiteSpace=\"pre-wrap\",this.hasFormat(\"lowercase\")?n.style.textTransform=\"lowercase\":this.hasFormat(\"uppercase\")?n.style.textTransform=\"uppercase\":this.hasFormat(\"capitalize\")&&(n.style.textTransform=\"capitalize\"),this.hasFormat(\"bold\")&&(n=xi(n,\"b\")),this.hasFormat(\"italic\")&&(n=xi(n,\"i\")),this.hasFormat(\"strikethrough\")&&(n=xi(n,\"s\")),this.hasFormat(\"underline\")&&(n=xi(n,\"u\")),{element:n}}selectionTransform(t,e){}setFormat(t){const e=this.getWritable();return e.__format=\"string\"==typeof t?z[t]:t,e}setDetail(t){const e=this.getWritable();return e.__detail=\"string\"==typeof t?B[t]:t,e}setStyle(t){const e=this.getWritable();return e.__style=t,e}toggleFormat(t){const e=Os(this.getFormat(),t,null);return this.setFormat(e)}toggleDirectionless(){const t=this.getWritable();return t.__detail^=1,t}toggleUnmergeable(){const t=this.getWritable();return t.__detail^=2,t}setMode(t){const e=$[t];if(this.getLatest().__mode===e)return this;const n=this.getWritable();return n.__mode=e,n}setTextContent(t){if(this.getLatest().__text===t)return this;const e=this.getWritable();return e.__text=t,e}select(t,e){xu();let n=t,o=e;const r=Od(),i=this.getTextContent(),s=this.__key;if(\"string\"==typeof i){const t=i.length;void 0===n&&(n=t),void 0===o&&(o=t)}else n=0,o=0;if(!Xf(r))return bd(s,n,s,o,\"text\",\"text\");{const t=Ks();t!==r.anchor.key&&t!==r.focus.key||Ls(s),r.setTextNodeRange(this,n,this,o)}return r}selectStart(){return this.select(0,0)}selectEnd(){const t=this.getTextContentSize();return this.select(t,t)}spliceText(t,e,n,o){const r=this.getWritable(),i=r.__text,s=n.length;let l=t;l<0&&(l=s+l,l<0&&(l=0));const c=Od();if(o&&Xf(c)){const e=t+s;c.setTextNodeRange(r,e,r,e)}const a=i.slice(0,l)+n+i.slice(l+e);return r.__text=a,r}canInsertTextBefore(){return!0}canInsertTextAfter(){return!0}splitText(...t){xu();const e=this.getLatest(),n=e.getTextContent();if(\"\"===n)return[];const o=e.__key,r=Ks(),i=n.length;t.sort((t,e)=>t-e),t.push(i);const s=[],l=t.length;for(let e=0,o=0;e<i&&o<=l;o++){const r=t[o];r>e&&(s.push(n.slice(e,r)),e=r)}const c=s.length;if(1===c)return[e];const a=s[0],u=e.getParent();let f;const d=e.getFormat(),h=e.getStyle(),g=e.__detail;let _=!1,p=null,y=null;const m=Od();if(Xf(m)){const[t,e]=m.isBackward()?[m.focus,m.anchor]:[m.anchor,m.focus];\"text\"===t.type&&t.key===o&&(p=t),\"text\"===e.type&&e.key===o&&(y=e)}e.isSegmented()?(f=Oi(a),f.__format=d,f.__style=h,f.__detail=g,f.__state=zn(e,f),_=!0):f=e.setTextContent(a);const x=[f];for(let t=1;t<c;t++){const n=Oi(s[t]);n.__format=d,n.__style=h,n.__detail=g,n.__state=zn(e,n);const i=n.__key;r===o&&Ls(i),x.push(n)}const v=p?p.offset:null,S=y?y.offset:null;let C=0;for(const t of x){if(!p&&!y)break;const e=C+t.getTextContentSize();if(null!==p&&null!==v&&v<=e&&v>=C&&(p.set(t.getKey(),v-C,\"text\"),v<e&&(p=null)),null!==y&&null!==S&&S<=e&&S>=C){y.set(t.getKey(),S-C,\"text\");break}C=e}if(null!==u){!function(t){const e=t.getPreviousSibling(),n=t.getNextSibling();null!==e&&Is(e),null!==n&&Is(n)}(this);const t=u.getWritable(),e=this.getIndexWithinParent();_?(t.splice(e,0,x),this.remove()):t.splice(e,1,x),Xf(m)&&Pd(m,u,e,c-1)}return x}mergeWithSibling(t){const n=t===this.getPreviousSibling();n||t===this.getNextSibling()||e(50);const o=this.__key,r=t.__key,i=this.__text,s=i.length;Ks()===r&&Ls(o);const l=Od();if(Xf(l)){const e=l.anchor,i=l.focus;null!==e&&e.key===r&&Id(e,n,o,t,s),null!==i&&i.key===r&&Id(i,n,o,t,s)}const c=t.__text,a=n?c+i:i+c;this.setTextContent(a);const u=this.getWritable();return t.remove(),u}isTextEntity(){return!1}}function Ci(t){return{forChild:Di(t.style),node:null}}function bi(t){const e=t,n=\"normal\"===e.style.fontWeight;return{forChild:Di(e.style,n?void 0:\"bold\"),node:null}}const ki=new WeakMap;function Ti(t){if(!uc(t))return!1;if(\"PRE\"===t.nodeName)return!0;const e=t.style.whiteSpace;return\"string\"==typeof e&&e.startsWith(\"pre\")}function Ni(t){const n=t;null===t.parentElement&&e(129);let o=n.textContent||\"\";if(null!==function(t){let e,n=t.parentNode;const o=[t];for(;null!==n&&void 0===(e=ki.get(n))&&!Ti(n);)o.push(n),n=n.parentNode;const r=void 0===e?n:e;for(let t=0;t<o.length;t++)ki.set(o[t],r);return r}(n))return{node:Wd(o)};if(o=o.replace(/\\r/g,\"\").replace(/[ \\t\\n]+/g,\" \"),\"\"===o)return{node:null};if(\" \"===o[0]){let t=n,e=!0;for(;null!==t&&null!==(t=wi(t,!1));){const n=t.textContent||\"\";if(n.length>0){/[ \\t\\n]$/.test(n)&&(o=o.slice(1)),e=!1;break}}e&&(o=o.slice(1))}if(\" \"===o[o.length-1]){let t=n,e=!0;for(;null!==t&&null!==(t=wi(t,!0));)if((t.textContent||\"\").replace(/^( |\\t|\\r?\\n)+/,\"\").length>0){e=!1;break}e&&(o=o.slice(0,o.length-1))}return\"\"===o?{node:null}:{node:Oi(o)}}function wi(t,e){let n=t;for(;;){let t;for(;null===(t=e?n.nextSibling:n.previousSibling);){const t=n.parentElement;if(null===t)return null;n=t}if(n=t,uc(n)){const t=n.style.display;if(\"\"===t&&!gc(n)||\"\"!==t&&!t.startsWith(\"inline\"))return null}let o=n;for(;null!==(o=e?n.firstChild:n.lastChild);)n=o;if(ws(n))return n;if(\"BR\"===n.nodeName)return null}}const Ei={code:\"code\",em:\"italic\",i:\"italic\",mark:\"highlight\",s:\"strikethrough\",strong:\"bold\",sub:\"subscript\",sup:\"superscript\",u:\"underline\"};function Ai(t){const e=Ei[t.nodeName.toLowerCase()];return void 0===e?{node:null}:{forChild:Di(t.style,e),node:null}}function Oi(t=\"\"){return Kl(new Si(t))}function Mi(t){return t instanceof Si}function Di(t,e){const n=t.fontWeight,o=t.textDecoration.split(\" \"),r=\"700\"===n||\"bold\"===n,i=o.includes(\"line-through\"),s=\"italic\"===t.fontStyle,l=o.includes(\"underline\"),c=t.verticalAlign,a=t.textTransform;return t=>Mi(t)||vi(t)?(r&&!t.hasFormat(\"bold\")&&t.toggleFormat(\"bold\"),i&&!t.hasFormat(\"strikethrough\")&&t.toggleFormat(\"strikethrough\"),s&&!t.hasFormat(\"italic\")&&t.toggleFormat(\"italic\"),l&&!t.hasFormat(\"underline\")&&t.toggleFormat(\"underline\"),\"sub\"!==c||t.hasFormat(\"subscript\")||t.toggleFormat(\"subscript\"),\"super\"!==c||t.hasFormat(\"superscript\")||t.toggleFormat(\"superscript\"),\"lowercase\"!==a&&\"uppercase\"!==a&&\"capitalize\"!==a||t.hasFormat(a)||t.toggleFormat(a),e&&!t.hasFormat(e)&&t.toggleFormat(e),t):t}function Pi(t,n){const{type:o,key:r,offset:i}=t,s=Bl(t.key);return\"text\"===o?(Mi(s)||e(266,s.getType(),r),Wh(s,n,i)):(ni(s)||e(267,s.getType(),r),Vi(s,t.offset,n))}function Fi(t,n){const{origin:o,direction:r}=n,i=\"next\"===r;Ph(n)?t.set(o.getKey(),n.offset,\"text\"):Ih(n)?Mi(o)?t.set(o.getKey(),jh(o,r),\"text\"):t.set(o.getParentOrThrow().getKey(),o.getIndexWithinParent()+(i?1:0),\"element\"):(Lh(n)&&ni(o)||e(268),t.set(o.getKey(),i?0:o.getChildrenSize(),\"element\"))}function Ii(t){const e=Od(),n=Xf(e)?e:kd();return Li(n,t),Ys(n),n}function Li(t,e){Fi(t.anchor,e.anchor),Fi(t.focus,e.focus)}function Ki(t){const{anchor:e,focus:n}=t,o=Pi(e,\"next\"),r=Pi(n,\"next\"),i=ng(o,r)<=0?\"next\":\"previous\";return tg(Gh(o,i),Gh(r,i))}function zi(t){const{direction:e,origin:n}=t,o=Rh(n,Ah(e)).getNodeAtCaret();return o?Rh(o,e):Uh(n.getParentOrThrow(),e)}function Bi(t,e=\"root\"){const n=[t];for(let o=Lh(t)?t.getParentCaret(e):t.getSiblingCaret();null!==o;o=o.getParentCaret(e))n.push(zi(o));return n}function Ri(t){return!!t&&t.origin.isAttached()}function Wi(t,n=\"removeEmptySlices\"){if(t.isCollapsed())return t;const o=\"root\",r=\"next\";let i=n;const s=Ji(t,r);let l=s.anchor.origin;for(;null!==l&&!Il(l);)l=l.getParent();const c=ni(l)?l.getFirstChild():null,a=Bi(s.anchor,o),u=Bi(s.focus.getFlipped(),o),f=new Set,d=[];for(const t of s.iterNodeCarets(o))if(Lh(t))f.add(t.origin.getKey());else if(Ih(t)){const{origin:e}=t;ni(e)&&!f.has(e.getKey())||d.push(e)}const h=new Set;for(const t of d){const e=t.getParent();null===e||f.has(e.getKey())||h.add(e),Ps(t)}for(const t of h)!t.canBeEmpty()&&!Il(t)&&t.isEmpty()&&t.isAttached()&&t.remove();for(const t of s.getTextSlices()){if(!t)continue;const{origin:e}=t.caret,n=e.getTextContentSize(),o=zi(Rh(e,r)),s=e.getMode();if(Math.abs(t.distance)===n&&\"removeEmptySlices\"===i||\"token\"===s&&0!==t.distance)o.remove();else if(0!==t.distance){i=\"removeEmptySlices\";let e=t.removeTextSlice();const n=t.caret.origin;if(\"segmented\"===s){const t=e.origin,n=Oi(t.getTextContent()).setStyle(t.getStyle()).setFormat(t.getFormat());o.replaceOrInsert(n),e=Wh(n,r,e.offset)}n.is(a[0].origin)&&(a[0]=e),n.is(u[0].origin)&&(u[0]=e.getFlipped())}}const g=ji(a),_=ji(u),p=function(t,e,n){const o=t&&t.getParentAtCaret(),r=e&&e.getParentAtCaret(),i=o&&r&&cg(o,r);if(!i||\"branch\"!==i.type)return null;const s=(t,e)=>{let o;for(let r=t;r&&!r.is(i.commonAncestor);r=r.getParent()){if(Il(r))return;e&&!n.has(r.__key)||!yc(r)||(o=r)}return o},l=s(o,!1),c=l&&s(r,!0);return l&&c&&0===dh(c).length?[l,c]:null}(g,_,f);if(p){const[t,e]=p;Uh(t,\"previous\").splice(0,e.getChildren());let n=e.getParent();for(e.remove(!0);n&&n.isEmpty();){const t=n;n=n.getParent(),t.remove(!0)}}else if(_){const t=function(t){if(Lh(t)){const e=t.origin;if(yc(e))return e}else{const e=t.getParentAtCaret();if(e&&yc(e))return e}return null}(_),e=t&&t.getParent(),n=t&&t.getParents().findLast(Fl);if(t&&e&&!ci(e)&&t.isEmpty()&&f.has(t.getKey())&&0===dh(t).length&&(!n||f.has(n.getKey()))){t.remove(!0);let n=e;for(;n&&!ci(n)&&n.isEmpty();){const t=n.getParent();if(t&&ci(t)&&t.getChildrenSize()<=1&&n.canBeEmpty())break;const e=n;n=t,e.remove(!0)}}}null!==qs(l,c)||null===l||l.isAttached()||qs(Hs(),null);const y=ji([g,_,...a,...u]);if(y)return Zh(Gh(y,t.direction));e(269,JSON.stringify(a.map(t=>t.origin.__key)))}function ji(t){const e=t.find(Ri);return e&&$i(e)}function $i(t){const e=function(t){let e=t;for(;Lh(e);){const t=Vh(e);if(!Lh(t))break;e=t}return e}(t.getLatest()),{direction:n}=e;if(Mi(e.origin))return Ph(e)?e:Wh(e.origin,n,n);const o=e.getAdjacentCaret();return Ih(o)&&Mi(o.origin)?Wh(o.origin,n,Ah(n)):e}function Ui(t){return Ph(t)&&t.offset!==jh(t.origin,t.direction)}function Ji(t,e){return t.direction===e?t:tg(Gh(t.focus,e),Gh(t.anchor,e))}function Vi(t,e,n){const o=t.getChildrenSize(),r=(e>0?Math.min(Math.ceil(e),o):0)-(\"next\"===n?1:0),i=r<0||r>=o?null:t.getChildAtIndex(r);return null===i?Uh(t,n):Rh(i,n)}function Hi(t,e=\"root\"){let n=0,o=t,r=Vh(o);for(;null===r;){if(n--,r=o.getParentCaret(e),!r)return null;o=r,r=Vh(o)}return r&&[r,n]}function qi(t){const{origin:n,offset:o,direction:r}=t;if(o===jh(n,r))return t.getSiblingCaret();if(o===jh(n,Ah(r)))return zi(t.getSiblingCaret());const[i]=n.splitText(o);return Mi(i)||e(281),Gh(Rh(i,\"next\"),r)}function Yi(t,e){for(const n of t)if(null!==n&&n.caret.origin.is(e))return n}function Xi(t,e=null){const{origin:n}=t.caret,[o,r]=t.getSliceIndices();if(o===r)return null;if(0===o&&r===n.getTextContentSize())return n;const i=n.getParent(),s=e&&i&&Dd(e,i)?n.getIndexWithinParent():-1,l=e?[e.anchor,e.focus].map(t=>[t,t.key===n.__key&&\"text\"===t.type?t.offset-o:null!==i&&t.key===i.__key&&t.offset===s?0:null]):[],c=n.splitText(o,r),a=c[0===o?0:1];i&&e&&e!==Od()&&Pd(e,i,s,c.length-1);for(const[t,e]of l)null!==e&&t.set(a.__key,e,\"text\");return a}function Gi(t,e){return!0}function Qi(t,{$copyElementNode:e=Ll,$splitTextPointCaretNext:n=qi,rootMode:o=\"shadowRoot\",$shouldSplit:r=Gi,removeEmptyDestination:i=!1}={}){if(Ph(t))return n(t);const s=t.getParentCaret(o);if(s){const{origin:n}=s;if(Lh(t)){const t=zi(s);if(i&&n.isEmpty())return n.remove(),t;if(!n.canBeEmpty()||!r(n,\"first\"))return t}const o=nh((l=t).getNodeAtCaret(),l.direction);(o.length>0||!i&&n.canBeEmpty()&&r(n,\"last\"))&&s.insert(e(n).splice(0,0,o))}var l;return s}function Zi(t,n,o){let r=Gh(n,\"next\");Ph(r)&&(0===r.offset?r=Rh(r.origin,\"previous\").getFlipped():r.offset===r.origin.getTextContentSize()&&(r=Rh(r.origin,\"next\"))),r.origin.is(t)&&(Ih(r)||e(342,t.getKey(),t.getType()),r=zi(r)),(t.is(r.getNodeAtCaret())||t.is(r.getFlipped().getNodeAtCaret()))&&t.remove(!0);for(let t=r;t;t=Qi(t,o))r=t;return Ph(r)&&e(283),r.insert(t.isInline()?os().append(t):t),Gh(Rh(t.getLatest(),\"next\"),n.direction)}function ts(t,e){const n=Ji(Xf(e)?Ki(e):e,\"next\"),o=ah(n.anchor.origin),r=ah(t.getLatest());if(null===o?null!==r:!o.is(r))return!1;const i=$i(Uh(t,\"next\")),s=Gh($i(Uh(t,\"previous\")),\"next\");return ng(n.anchor,i)<=0&&ng(n.focus,s)>=0}class es extends ei{$config(){return this.config(\"paragraph\",{children:\"inline\",extends:ei,generated:or,importDOM:{p:()=>({conversion:ns,priority:0})}})}createDOM(t){const e=Yl().createElement(\"p\"),n=gl(t.theme,\"paragraph\");return void 0!==n&&e.classList.add(...n),e}updateDOM(t,e,n){return!1}exportDOM(t){const{element:e}=super.exportDOM(t);if(uc(e)){this.isEmpty()&&e.append(Yl().createElement(\"br\"));const t=this.getFormatType();t&&(e.style.textAlign=t)}return{element:e}}exportJSON(t=!1){const e=super.exportJSON(t);if(void 0===e.textFormat||void 0===e.textStyle){const n=this.getChildren().find(Mi),o=n?n.getFormat():this.getTextFormat(),r=n?n.getStyle():this.getTextStyle();t&&0===o||(e.textFormat=o),t&&\"\"===r||(e.textStyle=r)}return e}extractWithChild(t,e,n){if(!Xf(e))return!1;if(\"\"===this.getFormatType()&&0===this.getIndent()&&\"\"===this.getStyle())return!1;if(ts(this,e)){const t=this.getTextContent();return\"\"!==t&&e.getTextContent()===t}return!1}insertNewAfter(t,e){const n=os();n.setTextFormat(t.format),n.setTextStyle(t.style);const o=this.getDirection();return n.setDirection(o),n.setFormat(this.getFormatType()),n.setStyle(this.getStyle()),this.insertAfter(n,e),n}collapseAtStart(){if(this.getChildren().every(t=>Mi(t)&&!/\\S/.test(t.getTextContent()))){if(null!==this.getNextSibling())return this.selectNext(),this.remove(),!0;if(null!==this.getPreviousSibling())return this.selectPrevious(),this.remove(),!0}return!1}}function ns(t){const e=os();if(Dc(e,t),Oc(t,e),\"\"===e.getFormatType()){const n=t.getAttribute(\"align\");n&&n&&n in R&&e.setFormat(n)}return Mc(e,t),{node:e}}function os(){return Kl(new es)}function rs(t){return t instanceof es}const is=/* @__PURE__ */un()({detail:/* @__PURE__ */xn(/* @__PURE__ */nn(2),{getter:{field:\"__detail\"},setter:null}),mode:/* @__PURE__ */xn(/* @__PURE__ */rn([\"normal\"]),{getter:{field:\"__mode\",getterTable:{0:\"normal\"}},setter:null}),text:/* @__PURE__ */xn(/* @__PURE__ */tn(\"\\t\"),{getter:{field:\"__text\",method:\"getTextContent\"},setter:null})});class ss extends Si{$config(){return this.config(\"tab\",{extends:Si,generated:ir,json:is})}constructor(t=void 0){super(\"\\t\",t),this.__detail=2}createDOM(t){const e=super.createDOM(t),n=gl(t.theme,\"tab\");return void 0!==n&&e.classList.add(...n),e}setTextContent(t){return super.setTextContent(\"\\t\")}spliceText(t,n,o,r){return\"\"===o&&0===n||\"\\t\"===o&&1===n||e(286),this}setDetail(t){return 2!==t&&e(127),this}setMode(t){return\"normal\"!==t&&e(128),this}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}}function ls(){return Kl(new ss)}function cs(t){return t instanceof ss}let as=null;function us(t){as=t}const fs=Symbol(\"INTERNAL_SKIP_AFTER_CLONE_FROM\");let ds=1;function hs(){ds=1}function gs(t,n){const o=_s(t,n);return void 0===o&&e(30,n),o}function _s(t,e){return t._nodes.get(e)}const ps=\"function\"==typeof queueMicrotask?queueMicrotask:t=>{Promise.resolve().then(t)};function ys(t,e){const n=void 0!==e?e:(()=>{const e=t.getRootNode();return Es(e)||Ul(e)?rc(e):null})();if(!uc(n))return!1;if(n.hasAttribute(\"data-lexical-slot\"))return!1;const o=$s(n),r=n.nodeName;return Jo(o)&&(\"INPUT\"===r||\"TEXTAREA\"===r||\"true\"===n.contentEditable&&null==bs(n))}function ms(t){const e=null===t?null:ic(t);return fc(e)&&ys(e)}const xs=ys;function vs(t,e,n){const o=t.getRootElement();if(!o)return!1;try{if(!e||!o.contains(e)||!o.contains(n))return!1}catch(t){return!1}return Cs(e)===t&&t.read(\"latest\",()=>!ys(e))}function Ss(t){return t instanceof su}function Cs(t){let e=t;for(;null!=e;){const t=bs(e);if(Ss(t))return t;e=Cl(e)}return null}function bs(t){return t?t.__lexicalEditor:null}function ks(t){return L.test(t)?\"rtl\":K.test(t)?\"ltr\":null}function Ts(t){return cs(t)||t.isToken()}function Ns(t){return Ts(t)||t.isSegmented()}function ws(t){return fc(t)&&3===t.nodeType}function Es(t){return fc(t)&&9===t.nodeType}function As(t){let e=t;for(;null!=e;){if(ws(e))return e;e=e.firstChild}return null}function Os(t,e,n){const o=z[e];if(null!==n&&(t&o)===(n&o))return t;let r=t^o;return\"subscript\"===e?r&=~z.superscript:\"superscript\"===e?r&=~z.subscript:\"lowercase\"===e?(r&=~z.uppercase,r&=~z.capitalize):\"uppercase\"===e?(r&=~z.lowercase,r&=~z.capitalize):\"capitalize\"===e&&(r&=~z.lowercase,r&=~z.uppercase),r}function Ms(t){return Mi(t)||Ba(t)||ii(t)}function Ds(t,e){const n=function(){const t=as;return as=null,t}();if(null!=(e=e||n&&n.__key))return void(t.__key=e);xu(),vu();const o=bu(),r=Su(),i=\"\"+ds++;r._nodeMap.set(i,t),ni(t)?o._dirtyElements.set(i,!0):o._dirtyLeaves.add(i),o._cloneNotNeeded.set(i,t),0===o._dirtyType&&(o._dirtyType=1),t.__key=i}function Ps(t){Qd(null===t.getParent()?t:t.getWritable())}const Fs=Ps;function Is(t){vu(),jo(t)&&e(323,t.__key,t.__type);const n=null!==t.__parent?t.__parent:ih(t)?t.__slotHost:null,o=Su(),r=bu(),i=o._nodeMap,s=r._dirtyElements;null!==n&&function(t,e,n){let o=t;for(;null!==o;){if(n.has(o))return;const t=e.get(o);if(void 0===t)break;n.set(o,!1),o=null!==t.__parent?t.__parent:ih(t)?t.__slotHost:null}}(n,i,s);const l=t.__key;0===r._dirtyType&&(r._dirtyType=1),ni(t)?s.set(l,!0):r._dirtyLeaves.add(l)}function Ls(t){xu();const e=bu(),n=e._compositionKey;if(t!==n){if(e._compositionKey=t,null!==n){const t=Bs(n);null!==t&&t.getWritable()}if(null!==t){const e=Bs(t);null!==e&&e.getWritable()}}}function Ks(){return mu()?null:bu()._compositionKey}function zs(t){return!g&&(p||x)&&\"\"===t.__text&&t.__key===bu()._compositionKey}function Bs(t,e){const n=(e||Su())._nodeMap.get(t);return void 0===n?null:n}function Rs(t,e){const n=js(t,bu());return void 0!==n?Bs(n,e):null}function Ws(t,e,n){t[`__lexicalKey_${e._key}`]=n}function js(t,e){return t[`__lexicalKey_${e._key}`]}function $s(t,e){let n=t;for(;null!=n;){const t=Rs(n,e);if(null!==t)return t;n=Cl(n)}return null}function Us(t){const e=t._decorators,n=Object.assign({},e);return t._pendingDecorators=n,n}function Js(t){return t.read(()=>Hs().getTextContent())}function Vs(t,e){const n=wc(t.getEditorState()),o=[];for(const t of e){const e=n.get(t);e&&o.push(e)}0!==o.length&&t.update(()=>{for(const t of o)for(const e of t.keys()){const t=Bs(e);t&&t.markDirty()}},null===t._pendingEditorState?{tag:Ta}:void 0)}function Hs(){return Su()._nodeMap.get(\"root\")}function qs(t,e){if(!(Il(t)&&t.isAttached()&&(ci(t)?0===t.getChildrenSize():t.isEmpty())&&(ci(t)||null!==e&&yc(e))))return null;const n=os();return t.append(n),n}function Ys(t){xu();const e=Su();null!==t&&(t.dirty=!0,t.setCachedNodes(null),Xf(t)&&bu()._slotsUsed&&xd(t)),e._selection=t}function Xs(t){xu(),we(bu(),t)}function Gs(t){const e=function(t,e){let n=t;for(;null!=n;){const t=js(n,e);if(void 0!==t)return t;n=Cl(n)}return null}(t,bu());return null===e?null:Bs(e)}function Qs(t){return/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g.test(t)}function Zs(t){const e=[];for(let n=t;null!==n;n=n._parentEditor)e.push(n);return e}let tl=0;function el(){return r?Math.random().toString(36).replace(/[^a-z]+/g,\"\").substring(0,5):`s${(++tl).toString(36)}`}function nl(t){return ws(t)?t.nodeValue:null}function ol(t,e,n){const o=jl(Ml(e));if(null===o)return;const r=Ql(o,e._rootElement),i=r.anchorNode;let{anchorOffset:s,focusOffset:l}=r;if(null!==i){let e=nl(i);const o=$s(i);if(null!==e&&Mi(o)){if((e===O||e===D)&&n){const t=n.length;e=n,s=t,l=t}null!==e&&rl(o,e,s,l,t)}}}function rl(t,e,n,o,r){let i=t;if(i.isAttached()&&(r||!i.isDirty())){const s=i.isComposing(),l=!g&&(p||x);if(i.isToken()&&s)return;let c=e;if((s||r)&&(!e.endsWith(O)||l&&e===i.getTextContent()||(c=e.slice(0,-O.length)),r&&!l)){const t=D;let e;for(;-1!==(e=c.indexOf(t));)c=c.slice(0,e)+c.slice(e+t.length),null!==n&&n>e&&(n=Math.max(e,n-t.length)),null!==o&&o>e&&(o=Math.max(e,o-t.length))}const a=i.getTextContent();if(r||c!==a){const e=Od();if(\"\"===c){if(s&&!r&&l)return void il(i,\"\",e);if(Ls(null),p||g||x)i.remove();else{const t=bu();il(i,\"\",e),setTimeout(()=>{t.update(()=>{i.isAttached()&&\"\"===i.getTextContent()&&i.remove()})},20)}return}const a=i.getParent(),u=Md(),f=i.getTextContentSize(),d=Ks(),h=i.getKey();if(i.isToken()&&!s||null!==d&&h===d&&!s||Xf(u)&&(null!==a&&!a.canInsertTextBefore()&&0===u.anchor.offset||u.anchor.key===t.__key&&0===u.anchor.offset&&!i.canInsertTextBefore()&&!s||u.focus.key===t.__key&&u.focus.offset===f&&!i.canInsertTextAfter()&&!s))return void i.markDirty();if(!Xf(e)||null===n||null===o)return void il(i,c,e);if(e.setTextNodeRange(i,n,i,o),i.isSegmented()){const t=Oi(i.getTextContent());i.replace(t),i=t}il(i,c,e)}}}function il(t,e,n){if(t.setTextContent(e),Xf(n)){const e=t.getKey();let o=!1;for(const r of[\"anchor\",\"focus\"]){const i=n[r];\"text\"===i.type&&i.key===e&&(i.offset=jh(t,i.offset,\"clamp\"),o=!0)}o&&(n._cachedNodes=null,n._cachedIsBackward=null)}}function sl(t,e){const n=t[V];return n&&e!==a?{...t,ctrlKey:t[n],[n]:t.ctrlKey}:t}function ll(t,e,n){const o=e[n]||!1;return\"any\"===o||o===t[n]}function cl(t,e){return ll(t,e,\"altKey\")&&ll(t,e,\"ctrlKey\")&&ll(t,e,\"shiftKey\")&&ll(t,e,\"metaKey\")}function al(t,e,n){if(!cl(t,n))return!1;if(t.key.toLowerCase()===e.toLowerCase())return!0;if(e.length>1)return!1;if(1===t.key.length&&t.key.charCodeAt(0)<=127)return!1;if(t.code.startsWith(\"Digit\")&&/^\\d$/.test(e))return t.code===`Digit${e}`;const o=\"Key\"+e.toUpperCase();return t.code===o}function ul(t){let e=t;for(;null!==e;){const t=e.getParent();if(null===t)return null;if(ci(t))return e;e=t}return null}function fl(t,e){const{anchor:n,focus:o}=t,r=n.key,i=n.offset,s=n.type,l=o.key,c=o.offset,a=o.type;if(Yo(t),!ci(e))return t;const u=ul(n.getNode());return ni(u)&&u.isShadowRoot()&&u.is(ul(o.getNode()))&&(n.set(r,i,s),o.set(l,c,a)),t}function dl(t){const e=Hs();if(Xf(t)){const e=t.anchor,n=t.focus,o=e.getNode();if(ci(o))return e.set(o.getKey(),0,\"element\"),n.set(o.getKey(),o.getChildrenSize(),\"element\"),fl(t,o),t;const r=o.getTopLevelElementOrThrow(),i=r.getParent();return null===i?(ni(r)&&(e.set(r.getKey(),0,\"element\"),n.set(r.getKey(),r.getChildrenSize(),\"element\"),fl(t,r)),t):(e.set(i.getKey(),0,\"element\"),n.set(i.getKey(),i.getChildrenSize(),\"element\"),fl(t,i),t)}{const t=e.select(0,e.getChildrenSize());return Ys(fl(t,e)),t}}function hl(t,e){\"\"===t.getAttribute(e)&&t.removeAttribute(e)}function gl(t,e){void 0===t.__lexicalClassNameCache&&(t.__lexicalClassNameCache={});const n=t.__lexicalClassNameCache,o=n[e];if(void 0!==o)return o;const r=t[e];if(\"string\"==typeof r){const t=gg(r);return n[e]=t,t}return r}function _l(t,n,o,r,i){if(0===o.size)return;const s=r.__type,l=r.__key,c=n.get(s);void 0===c&&e(33,s);const a=c.klass;let u=t.get(a);void 0===u&&(u=new Map,t.set(a,u));const f=u.get(l),d=\"destroyed\"===f&&\"created\"===i;(void 0===f||d)&&u.set(l,d?\"updated\":i)}function pl(t){const e=t.getType(),n=Su();if(n._readOnly){const t=wc(n).get(e);return t?Array.from(t.values()):[]}const o=n._nodeMap,r=[];for(const[,n]of o)n instanceof t&&n.__type===e&&n.isAttached()&&r.push(n);return r}function yl(t,e,n){const o=t.getParent();let r=n,i=t;return null!==o&&(e&&0===n?(r=i.getIndexWithinParent(),i=o):e||n!==i.getChildrenSize()||(r=i.getIndexWithinParent()+1,i=o)),i.getChildAtIndex(e?r-1:r)}function ml(t,e){const n=t.offset;if(\"element\"===t.type)return yl(t.getNode(),e,n);{const o=t.getNode();if(e&&0===n||!e&&n===o.getTextContentSize()){const t=e?o.getPreviousSibling():o.getNextSibling();return null===t?yl(o.getParentOrThrow(),e,o.getIndexWithinParent()+(e?0:1)):t}}return null}function xl(t){const e=Ml(t).event,n=e&&e.inputType;return\"insertFromPaste\"===n||\"insertFromPasteAsQuotation\"===n}function vl(t,e,...n){return Lu(t,e,n[0],t)}function Sl(t,n){const o=t._keyToDOMMap.get(n);return void 0===o&&e(75,n),o}function Cl(t){const e=t.assignedSlot||t.parentElement;if(null!==e)return e;const n=t.parentNode;return Ul(n)?n.host:null}function bl(t){return Es(t)?t:uc(t)?t.ownerDocument:null}function kl(t,e){const n=parseFloat(t);return isFinite(n)?t.endsWith(\"%\")?n*e/100:n:0}function Tl(t,e,n,o){const r=e.clientWidth,i=e.scrollWidth-r;if(i<=0)return 0;const s=t.getComputedStyle(e);if(\"auto\"!==s.overflowX&&\"scroll\"!==s.overflowX)return 0;const l=e.getBoundingClientRect(),c=e.offsetWidth,a=c>0&&Math.abs(l.width-c)>1?l.width/c:1,u=\"rtl\"===s.direction,f=l.left+e.clientLeft*a,d=f+kl(s.scrollPaddingLeft,r)*a,h=f+(r-kl(s.scrollPaddingRight,r))*a;let g=n,_=Math.max(o,n+1);_-g>h-d&&(u?g=_-1:_=g+1);let p=0;if(g<d?p=g-d:_>h&&(p=_-h),0===p)return 0;const y=e.scrollLeft,m=y+p/a,x=p>0?Math.ceil(m):Math.floor(m);let v=u?Math.min(0,Math.max(-i,x)):Math.max(0,Math.min(i,x));const S=y*a;return Math.abs(v)<Math.abs(y)&&g+S>=d&&_+S<=h&&(v=0),v===y?0:(e.scrollLeft=v,(e.scrollLeft-y)*a)}function Nl(t){return bu()._updateTags.has(t)}function wl(t){xu(),bu()._updateTags.add(t)}function El(t){xu(),bu()._deferred.push(t)}function Al(t,e){let n=t.getParent();for(;null!==n;){if(n.is(e))return!0;n=n.getParent()}return!1}function Ol(t){const e=bl(t);return e?e.defaultView:null}function Ml(t){const n=t._window;return null===n&&e(78),n}function Dl(t){return ni(t)&&t.isInline()||ii(t)&&t.isInline()}function Pl(t){let e=t.getLatest();for(;null!==e;){if(null!==sh(e)&&ni(e))return e;const t=e.getParentOrThrow();if(Il(t))return t;e=t}return e}function Fl(t){return ni(t)&&t.isShadowRoot()}function Il(t){return ci(t)||Fl(t)}function Ll(t,e=!1){const n=t.constructor.clone(t,fs);return Ds(n,null),n.afterCloneFrom(t),e||n.resetOnCopyNodeFrom(t),n}function Kl(t){const n=bu(),o=t.getType(),r=_s(n,o);void 0===r&&e(200,t.constructor.name,o);const{replace:i,replaceWithKlass:s}=r;if(null!==i){const n=i(t),r=n.constructor;return null!==s?n instanceof s||e(201,s.name,s.getType(),r.name,r.getType(),t.constructor.name,o):n instanceof t.constructor&&r!==t.constructor||e(202,r.name,r.getType(),t.constructor.name,o),n.__key===t.__key&&e(203,t.constructor.name,o,r.name,r.getType()),n}return t}function zl(t,n){!ci(t.getParent())||ni(n)||ii(n)||e(99)}function Bl(t){const n=Bs(t);return null===n&&e(63,t),n}function Rl(t){if(!t||t.isInline())return!1;if(ii(t))return!0;if(ni(t)){if(t.isShadowRoot()){const e=t.getParent();return!(ni(e)&&e.isShadowRoot())}return!t.canBeEmpty()}return!1}function Wl(t,e,n){n.style.removeProperty(\"caret-color\"),e._blockCursorElement=null;const o=t.parentElement;null!==o&&o.removeChild(t)}function jl(t){return r?(t||window).getSelection():null}function $l(t){const e=Ol(t);return e?e.getSelection():null}function Ul(t){return dc(t)&&\"host\"in t}const Jl=[];function Vl(t){const e=t.getRootNode();if(e===t||!Ul(e))return Jl;const n=[e];let o=e.host;for(;;){const t=o.getRootNode();if(t===o||!Ul(t))break;n.push(t),o=t.host}return n}function*Hl(t){const e=[t];let n;for(;n=e.pop();){yield*n.querySelectorAll('[data-lexical-editor=\"true\"]');const t=(Es(n)?n:n.ownerDocument).createTreeWalker(n,NodeFilter.SHOW_ELEMENT);let o;for(;o=t.nextNode();)o.shadowRoot&&e.push(o.shadowRoot)}}function ql(t){return null!==t?t.ownerDocument:document}function Yl(){const t=Nu();return ql(null!==t?t._rootElement:null)}function Xl(t,e){if(null===e||\"function\"!=typeof t.getComposedRanges)return null;const n=Vl(e);if(0===n.length)return null;const o=t.getComposedRanges;try{const e=o.call(t,{shadowRoots:n})[0];if(void 0!==e)return e}catch(t){}try{const e=o.apply(t,n)[0];if(void 0!==e)return e}catch(t){}return null}function Gl(t,e){const n=Xl(t,e);if(null!==n){const t=tc(n);if(null!==t)return t}return t.rangeCount>0?t.getRangeAt(0):null}function Ql(t,e){const n=Xl(t,e);return null===n?t:ec(n,nc(t))}function Zl(t,e){const n=Xl(t,e);if(null===n)return{points:t,range:t.rangeCount>0?t.getRangeAt(0):null};const o=tc(n)??(t.rangeCount>0?t.getRangeAt(0):null);return{points:ec(n,nc(t)),range:o}}function tc(t){const e=t.startContainer.ownerDocument;if(null===e)return null;const n=e.createRange();try{return n.setStart(t.startContainer,t.startOffset),n.setEnd(t.endContainer,t.endOffset),n}catch(t){return null}}function ec(t,e){const{startContainer:n,startOffset:o,endContainer:r,endOffset:i}=t;return\"backward\"===e?{anchorNode:r,anchorOffset:i,direction:e,focusNode:n,focusOffset:o}:{anchorNode:n,anchorOffset:o,direction:e,focusNode:r,focusOffset:i}}function nc(t){return t.direction}function oc(t){const e=t.getRootNode();return Es(e)||Ul(e)?e.activeElement:null}function rc(t){let e=t.activeElement;for(;null!==e&&null!==e.shadowRoot;){const t=e.shadowRoot.activeElement;if(null===t)break;e=t}return e}function ic(t){const e=t.target;if(null!==e&&uc(e)&&null!==e.shadowRoot&&\"function\"==typeof t.composedPath){const e=t.composedPath();if(e.length>0)return e[0]}return e}function sc(t,n){let o=t.getChildAtIndex(n);null==o&&(o=t),Il(t)&&e(102);const r=t=>{const n=t.getParentOrThrow(),i=Il(n),s=t!==o||i?Ll(t):t;if(i)return ni(t)&&ni(s)||e(133),t.insertAfter(s),[t,s,s];{const[e,o,i]=r(n),l=t.getNextSiblings();return i.append(s,...l),[e,o,s]}},[i,s]=r(o);return[i,s]}function lc(t){return uc(t)&&\"A\"===t.tagName}function cc(t){return uc(t)&&\"TR\"===t.tagName}function ac(t){return uc(t)&&(\"TD\"===t.tagName||\"TH\"===t.tagName)}function uc(t){return fc(t)&&1===t.nodeType}function fc(t){return\"object\"==typeof t&&null!==t&&\"nodeType\"in t&&\"number\"==typeof t.nodeType}function dc(t){return fc(t)&&11===t.nodeType}const hc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|mark|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var|#text)$/i;function gc(t){return!(!uc(t)||!t.style.display.startsWith(\"inline\"))||hc.test(t.nodeName)}const _c=/^(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|td|tfoot|ul|video)$/i;function pc(t){return(!uc(t)||!t.style.display.startsWith(\"inline\"))&&_c.test(t.nodeName)}function yc(t){if(ii(t)&&!t.isInline())return!0;if(!ni(t)||Il(t))return!1;const e=t.getFirstChild(),n=null===e||Ba(e)||Mi(e)||e.isInline();return!t.isInline()&&!1!==t.canBeEmpty()&&n}function mc(){return bu()}function xc(t=mc()){return t._config.dom||nu}function vc(t,n,o=mc()){const r=xc(o).$getDOMSlot(t,n,o);return ni(t)&&(bc(r)||e(344,t.getKey(),t.getType())),r}function Sc(t,e,n,o){const r=t.read(\"latest\",()=>{const o=Bs(e);return null!==o?function(t,e,n=mc()){const o=hh(t,e);if(null===o)return null;const r=n.getElementByKey(o.getKey());return null!==r?r.parentElement:null}(o,n,t):null});return null!==r&&(r.parentElement!==o&&o.appendChild(r),r.style.display=\"\"),r}function Cc(t,e,n){n.style.display=\"none\";const o=t.getElementByKey(e);null!==o&&n.parentElement!==o&&o.insertBefore(n,o.firstChild)}function bc(t){return t instanceof ye}function kc(t,e,n=mc()){return As(vc(t,e,n).element)}const Tc=new WeakMap,Nc=new Map;function wc(t){if(!t._readOnly&&t.isEmpty())return Nc;t._readOnly||e(192);let n=Tc.get(t);return n||(n=function(t){const e=new Map;for(const[n,o]of t._nodeMap){const t=o.__type;let r=e.get(t);r||(r=new Map,e.set(t,r)),r.set(n,o)}return e}(t),Tc.set(t,n)),n}function Ec(t){const e=t.constructor.clone(t,fs);return e.afterCloneFrom(t),e}function Ac(t){return(e=Ec(t))[Wo]=!0,e;var e}function Oc(t,e){const n=t.getAttribute(\"data-lexical-indent\");if(null!==n){const t=parseInt(n,10);if(Number.isFinite(t)&&t>=0)return void e.setIndent(t)}const o=parseInt(t.style.paddingInlineStart,10)||0,r=Math.round(o/40);e.setIndent(r)}function Mc(t,e){const n=e.getAttribute(\"dir\");return\"ltr\"===n||\"rtl\"===n?t.setDirection(n):t}function Dc(t,e){const n=e.style.textAlign;return n&&n in R?t.setFormat(n):t}function Pc(t,e){t.__lexicalUnmanaged=!0,e&&void 0!==e.captureSelection&&(t.__lexicalCapturedSelection=e.captureSelection)}function Fc(t){return!0===t.__lexicalUnmanaged}function Ic(t,e=mc()){const n=e.isEditable();t.contentEditable=n?\"true\":\"false\",n?t.__lexicalEditor=e:delete t.__lexicalEditor}function Lc(t,e){let n=t;for(;null!=n;){if(!0===n.__lexicalCapturedSelection)return!0;if(uc(n)&&n.hasAttribute(\"data-lexical-slot\"))return!1;if(void 0!==js(n,e))return!1;n=Cl(n)}return!1}function Kc(t,e){return Ge(t,e)&&t[e]!==Uo[e]}const zc=new WeakMap;function Bc(t){const n=zc.get(t);return void 0!==n?n:function(t){const n=null!=t.prototype&&H in t.prototype?t.prototype[H]():void 0,o=function(t){if(!(t===Uo||t.prototype instanceof Uo)){let n=\"<unknown>\",o=\"<unknown>\";try{n=t.getType()}catch(t){}try{su.version&&(o=JSON.parse(su.version))}catch(t){}e(290,t.name,n,o)}return t===ri||t===ei||t===Uo}(t),r=!o&&Kc(t,\"getType\")?t.getType:void 0,i=r&&!(Wc in r)?r.call(t):void 0;let s,l=i;if(n)if(i)s=n[i];else{for(const[t,e]of Object.entries(n))l=t,s=e;if(!s)for(const t of Object.getOwnPropertySymbols(n)){const e=n[t];if(e){s=e;break}}}const c={compiled:void 0,composed:void 0,config:{declaresOwnConfig:Ge(t.prototype,H),klass:t,ownNodeConfig:s,ownNodeType:l},ownFieldsValidated:!1};zc.set(t,c);try{const n=function(t){const n=t.prototype,o=new Map,{fieldsBaseFirst:r}=qc(t);for(const[i,s]of r){const r=Qc(t,i,s);if(null===r)continue;if(Me(r)){const n=r.field;if(\"__proto__\"===n&&e(430,t.name,i),void 0!==r.setterTable){const{setterTable:n}=r,{meta:o}=s;for(const r of\"enum\"===o.kind?o.values:[s.defaultValue])Ge(n,String(r))||e(431,t.name,i,JSON.stringify(r))}o.set(i,{field:n,key:i,kind:\"ownField\",schema:s,setterTable:r.setterTable});continue}const l=n[r];\"function\"!=typeof l&&e(432,t.name,i,r),o.set(i,{key:i,kind:\"field\",schema:s,setter:l})}return 0===o.size?jc:[...o.values()]}(t),r=function(t){const n=t.prototype,o=new Map;for(const[r,i]of qc(t).fieldsDerivedFirst){const s=Gc(t,r,i);if(null===s)continue;if(Me(s)){const l=s.field;\"__proto__\"===l&&e(426,t.name,r);const c=s.when;let a;if(void 0!==c){const o=n[c];\"function\"!=typeof o&&e(427,t.name,r,c),a=o}o.set(r,{defaultValue:i.defaultValue,derived:null===i.setter,field:l,getterTable:s.getterTable,isEqual:i.isEqual,key:r,kind:\"ownField\",schema:i,when:a});continue}const l=n[s];\"function\"!=typeof l&&e(428,t.name,r,s),o.set(r,{defaultValue:i.defaultValue,derived:null===i.setter,getter:l,isEqual:i.isEqual,key:r,kind:\"method\",schema:i})}return 0===o.size?Xc:[...o.values()]}(t),i=qc(t),a=function(t,e,n){let o,r=t;for(const{klass:e,ownNodeConfig:n}of da(t))n&&void 0!==n.generated&&(void 0===o?(o=n.generated,r=e):n.generated===o&&(r=e));return void 0===o?null:r===t||function(t,e){if(t.getters.length!==e.getters.length||t.setters.length!==e.setters.length)return!1;for(let n=0;n<t.getters.length;n++){const o=t.getters[n],r=e.getters[n];if(o.kind!==r.kind||o.key!==r.key||o.schema!==r.schema||o.derived!==r.derived||o.isEqual!==r.isEqual||!Object.is(o.defaultValue,r.defaultValue)||\"ownField\"===o.kind&&\"ownField\"===r.kind&&(o.field!==r.field||void 0===o.getterTable!=(void 0===r.getterTable)))return!1}for(let n=0;n<t.setters.length;n++){const o=t.setters[n],r=e.setters[n];if(o.kind!==r.kind||o.key!==r.key||o.schema!==r.schema||\"ownField\"===o.kind&&\"ownField\"===r.kind&&(o.field!==r.field||void 0===o.setterTable!=(void 0===r.setterTable)))return!1}return!0}(n,Rc(Bc(r)))?o:null}(t,0,{getters:r,setters:n});c.compiled={flatStates:i.flatStates,generated:null===a?null:a(i.fields),getters:r,isCompactDefault:ea(r),setters:n},function(t,e,n,o){if(!e&&n){if(!Kc(t,\"getType\")){const e=t,o=function(){return this!==e?Uo.getType.call(this):n};o[Wc]=!0,t.getType=o}if(Kc(t,\"clone\")||(t.clone=(e,n)=>{us(e);const o=new t;return n!==fs&&o.afterCloneFrom(e),o}),Kc(t,\"importJSON\")||(t.importJSON=o&&o.$importJSON||function(t){return e=>{const n=ga(t);return n.updateFromJSON===Uo.prototype.updateFromJSON?function(t,e){return oa(t.__state||void 0!==e[J]?Pn(t,e):t,e)}(n,e):n.updateFromJSON(e)}}(t)),!Kc(t,\"importDOM\")&&o){const{importDOM:e}=o;e&&(t.importDOM=()=>e)}const e=t.prototype;Ge(e,\"getTextContent\")&&!Ge(e,\"getTextContentSize\")&&(t.prototype.getTextContentSize=Uo.prototype.getTextContentSize)}}(t,o,l,s),function(t){for(const{klass:e,ownNodeConfig:n}of da(t)){const t=e.prototype;if(Ge(t,\"afterCloneFrom\"))continue;const o=fa(e);if(0===o.length)continue;const r=Object.getPrototypeOf(t),i=n&&void 0!==n.generated?Rc(Bc(e)).generated:null,s=null!==i&&i.afterCloneFrom||((t,e)=>{const n=t,r=e;for(let t=0;t<o.length;t++){const e=o[t];n[e]=r[e]}});t.afterCloneFrom=function(t){r.afterCloneFrom.call(this,t),s(this,t)},t.afterCloneFrom[aa]=!0}}(t),function(t,e){e&&void 0!==e.inline&&Ge(t.prototype,H)&&!Object.prototype.hasOwnProperty.call(t.prototype,\"isInline\")&&Object.defineProperty(t.prototype,\"isInline\",{configurable:!0,value:e.inline?ia:sa,writable:!0})}(t,s)}catch(e){throw zc.delete(t),e}return c}(t)}function Rc(t){const{compiled:n}=t;return void 0===n&&e(422,t.config.klass.name),n}const Wc=Symbol(\"lexical.synthesizedGetType\"),jc=[];function $c(t,e,n,o){const r=void 0===n.method?o:n.method,i=qc(t).declaredBy.get(e);if(void 0===i)return n;const s=t.prototype,l=i.prototype;return Uc(s,l,r)&&Uc(s,l,o)?n:r}function Uc(t,e,n){return t[n]===e[n]}function Jc(t){return`set${t.charAt(0).toUpperCase()}${t.slice(1)}`}function Vc(t){return`get${t.charAt(0).toUpperCase()}${t.slice(1)}`}const Hc={declaredBy:new Map,fields:new Map,fieldsBaseFirst:[],fieldsDerivedFirst:[],flatStates:[]};function qc(t){const e=Bc(t);return void 0===e.composed&&(e.composed=function(t){const e=[],n=[],o=[];for(const{klass:r,ownNodeConfig:i}of da(t)){const t=i&&i.json;n.push(r),e.push(t&&\"node\"===t.meta.kind?Object.entries(t.meta.fields):[]);const s=[];if(i&&i.stateConfigs)for(const t of i.stateConfigs)\"stateConfig\"in t&&t.flat&&s.push(t.stateConfig);o.push(s)}const r=new Map;for(let t=0;t<e.length;t++)for(const[n,o]of e[t])r.has(n)||r.set(n,o);const i=new Map,s=new Map,l=new Map;for(let t=e.length-1;t>=0;t--){for(const[o,l]of e[t]){const e=r.get(o);void 0===e||i.has(o)||i.set(o,e),void 0===e||l!==e||s.has(o)||s.set(o,n[t])}for(const e of o[t])l.has(e.key)||l.set(e.key,e)}return 0===r.size&&0===l.size?Hc:{declaredBy:s,fields:i,fieldsBaseFirst:[...i],fieldsDerivedFirst:[...r],flatStates:[...l.values()]}}(t)),e.composed}function Yc(t){const{fieldsDerivedFirst:e,flatStates:n}=qc(t),o={};for(const t of n)t.schema&&(o[t.key]=t.schema);for(const[t,n]of e)o[t]=n;return o}const Xc=[];function Gc(t,e,n){const o=n.getter;if(null===o)return null;const r=void 0===o?Vc(e):o;return Me(r)?$c(t,e,r,Vc(e)):r}function Qc(t,e,n){const o=n.setter;if(null===o)return null;const r=void 0===o?Jc(e):o;return Me(r)?$c(t,e,r,Jc(e)):r}function Zc(t){return t}function ta(t,e){const{defaultValue:n,isEqual:o}=t;return void 0===e||e===n||void 0!==o&&o(e,n)}function ea(t){let e;return(n,o)=>{void 0===e&&(e=new Map(t.map(t=>[t.key,t])));const r=e.get(n);return void 0!==r&&ta(r,o)}}function na(t){const{setterTable:e,schema:n}=t,{defaultValue:o}=n;return void 0===e?o:e[String(o)]}function oa(t,e){const n=Bc(t.constructor),{flatStates:o,generated:r,setters:i}=Rc(n),s=function(t,e,n){let o=t;for(let t=0;t<n.length;t++){const r=n[t],i=e[r.key];if(void 0!==i){const t=r.parse(i);o=wn(o,r,()=>t)}}return o}(t,e,o);return null!==r&&void 0!==r.updateFromJSON?r.updateFromJSON(s,e):function(t,e,n){for(let o=0;o<n.length;o++){const r=n[o],i=r.schema(e[r.key]);\"ownField\"===r.kind?Zc(t)[r.field]=void 0===r.setterTable?i:Ge(r.setterTable,i)?r.setterTable[i]:na(r):r.setter.call(t,i)}return t}(s,e,i)}function ra(t){return Bc(t).config}function ia(){return!0}function sa(){return!1}function la(t){return t===ia||t===sa}function ca(t){const e=[];for(const n of[t.getter,t.setter])Me(n)&&\"__proto__\"!==n.field&&!e.includes(n.field)&&e.push(n.field);return e}const aa=\"__lexicalSynthesizedAfterCloneFrom\";function ua(t){const{declaredBy:e,fieldsBaseFirst:n}=qc(t),o=[];for(const[r,i]of n)if(e.get(r)===t)for(const t of ca(i))o.includes(t)||o.push(t);return o}function fa(t){const e=ua(t);if(0===e.length)return e;const n=new Set;for(const{klass:e}of da(t))if(e!==t)for(const t of ua(e))n.add(t);return 0===n.size?e:e.filter(t=>!n.has(t))}function*da(t){for(let e=t;e&&(e===Uo||Jo(e.prototype));){const t=ra(e),n=t.declaresOwnConfig;yield n?t:{...t,ownNodeConfig:void 0},e=n&&t.ownNodeConfig&&t.ownNodeConfig.extends||ya(e)}}function ha(t){const e=new Map,n=new Map;for(const o of t){const{ownNodeType:t}=ra(o);t&&(n.set(t,o),e.set(t,new Set))}for(const[t,o]of n)for(const{ownNodeType:n}of da(o)){const o=n&&e.get(n);o&&o.add(t)}return e}function ga(t){const e=mc();xu();const n=e.resolveRegisteredNodeAfterReplacements(e.getRegisteredNode(t)),o=new n.klass;return null===n.replace?o:Kl(o)}const _a=(t,e)=>{let n=t;for(;null!=n&&!ci(n);){if(e(n))return n;n=n.getParent()}return null};function pa(t,n){const o=[];let r=t.__first;for(;null!==r;){const t=null===n?Bs(r):n.get(r);null==t&&e(174),o.push(r),r=t.__next}return o}function ya(t){const e=Object.getPrototypeOf(t);if(\"function\"==typeof e&&e!==Function.prototype)return e;const n=t.prototype&&Object.getPrototypeOf(t.prototype);return n?n.constructor:null}function ma(t){return new Ca(re(t._nodeMap),null,t._slotsUsed)}function xa(){return new Ca(new Map([[\"root\",new li]]),null,!1)}function va(t){const n=t.constructor,o=ae(t);if(ni(t)){const e=o.children,n=t.getChildren();for(let t=0;t<n.length;t++)e.push(va(n[t]))}const r=dh(t);if(r.length>0){const i={};for(const o of r){const r=hh(t,o);null===r&&e(366,n.name,o),i[o]=va(r)}o.$slots=i}return o}function Sa(t){return t instanceof Ca}class Ca{_nodeMap;_movedNodes;_selection;_flushSync;_readOnly;_parsed;_slotsUsed;constructor(t,e=null,n=!1){this._nodeMap=t,this._movedNodes=null,this._selection=e||null,this._flushSync=!1,this._readOnly=!1,this._parsed=!1,this._slotsUsed=n}isEmpty(){return this._nodeMap.size<=1&&null===this._selection}read(t,e){return Du(e&&e.editor||null,this,t)}clone(t){const e=new Ca(this._nodeMap,void 0===t?this._selection:t,this._slotsUsed);return e._readOnly=!0,e._parsed=this._parsed,e}toJSON(t){return le(\"boolean\"==typeof t&&t,()=>Du(null,this,()=>({root:va(Hs())})))}}const ba=\"historic\",ka=\"history-push\",Ta=\"history-merge\",Na=\"paste\",wa=\"cut\",Ea=\"collaboration\",Aa=\"skip-collab\",Oa=\"skip-scroll-into-view\",Ma=\"skip-dom-selection\",Da=\"skip-selection-focus\",Pa=\"composition-start\",Fa=\"composition-end\";class Ia extends ei{$config(){return this.config(\"artificial\",{extends:ei})}createDOM(t){return Yl().createElement(\"div\")}}class La extends Uo{$config(){return this.config(\"linebreak\",{extends:Uo,generated:rr,importDOM:{br:t=>Ra(t)||Wa(t)?null:{conversion:Ka,priority:0}}})}getTextContent(){return\"\\n\"}createDOM(){return Yl().createElement(\"br\")}updateDOM(){return!1}isInline(){return!0}}function Ka(t){return{node:za()}}function za(){return Kl(new La)}function Ba(t){return t instanceof La}function Ra(t){const e=t.parentElement;if(null!==e&&pc(e)){const n=e.firstChild;if(n===t||n.nextSibling===t&&ja(n)){const n=e.lastChild;if(n===t||n.previousSibling===t&&ja(n))return!0}}return!1}function Wa(t){const e=t.parentElement;if(null!==e&&pc(e)){const n=e.firstChild;if(n===t||n.nextSibling===t&&ja(n))return!1;const o=e.lastChild;if(o===t||o.previousSibling===t&&ja(o))return!0}return!1}function ja(t){return ws(t)&&/^( |\\t|\\r?\\n)+$/.test(t.textContent||\"\")}function $a(t){console.warn(t)}const Ua=0,Ja=1,Va=2,Ha=3,qa=4,Ya=-8,Xa=-7,Ga=-6,Qa=-5,Za=-4;function tu(t,e,n,o,r){const i=t._keyToDOMMap;i.clear(),t._editorState=xa(),t._pendingEditorState=o,t._compositionKey=null,t._dirtyType=0,t._cloneNotNeeded.clear(),t._dirtyLeaves=new Set,t._dirtyElements.clear(),t._normalizedNodes=new Set,r&&r.preserveUpdateQueue||(t._updateTags=new Set,t._updates=[],t._cascadeCount=0),t._blockCursorElement=null,null!==t._inputState.handledSelectionCommandTimeoutId&&clearTimeout(t._inputState.handledSelectionCommandTimeoutId),null!==e&&lf(t,e),t._inputState={collapsedSelectionFormat:{format:0,key:\"root\",offset:0,style:\"\",timeStamp:0},composedSegmentedKey:null,compositionPhase:\"idle\",hadOrphanedCompositionEvents:!1,handledSelectionCommandTimeoutId:null,isInsertLineBreak:!1,isInsertTextAfterHandledSelectionCommand:!1,isSelectionChangeFromDOMUpdate:!1,isSelectionChangeFromMouseDown:!1,isShiftKeyDown:!1,lastBeforeInputInsertTextTimeStamp:0,lastKeyCode:null,lastKeyDownTimeStamp:0,lastPointerType:\"\",mouseDrag:null,postDeleteSelectionToRestore:null,savedInputMode:void 0,selectionChangeFromDOMUpdatePoints:null,unprocessedBeforeInputData:null};const s=t._observer;null!==s&&(s.disconnect(),t._observer=null),null!==e&&(e.textContent=\"\",function(t,e){delete t[`__lexicalKey_${e._key}`]}(e,t)),null!==n&&(n.textContent=\"\",i.set(\"root\",n),Ws(n,t,\"root\"))}function eu(t){const e=new Set,n=new Set;for(const{klass:o,ownNodeConfig:r}of da(t)){const t=o.transform;if(!n.has(t)){n.add(t);const r=o.transform();r&&e.add(r)}if(r){const t=r.$transform;t&&e.add(t)}}return e}const nu={$createDOM:(t,e)=>t.createDOM(e._config,e),$decorateDOM:(t,e,n,o)=>{},$exportDOM:(t,e)=>{const n=_s(e,t.getType());return n&&void 0!==n.exportDOM?n.exportDOM(e,t):t.exportDOM(e)},$extractWithChild:(t,e,n,o,r)=>ni(t)&&t.extractWithChild(e,n,o),$getDOMSlot:(t,e,n)=>t.getDOMSlot(e),$getSlotTargetElement:(t,e,n,o)=>null,$shouldExclude:(t,e,n)=>ni(t)&&t.excludeFromCopy(\"html\"),$shouldInclude:(t,e,n)=>!e||t.isSelected(e),$updateDOM:(t,e,n,o)=>t.updateDOM(e,n,o._config)};function ou(t){const n=t||{},o=Nu(),r=n.theme||{},i=void 0===t?o:n.parentEditor||null,s=n.disableEvents||!1,l=xa(),c=n.namespace||(null!==i?i._config.namespace:el()),a=n.editorState,u=[li,Si,La,ss,es,Ia,...n.nodes||[]],{onError:f,onWarn:d,html:h}=n,g=void 0===n.editable||n.editable;let _;if(void 0===t&&null!==o)_=o._nodes;else{_=new Map;for(let t=0;t<u.length;t++){let o=u[t],r=null,i=null;if(o&&\"object\"==typeof o){const t=o;o=t.replace,r=t.with,i=t.withKlass||null}if(\"function\"!=typeof o||!o.prototype||!(o===Uo||o.prototype instanceof Uo)){let r=\"<unknown>\";try{r=JSON.parse(ee)}catch{}e(365,String(t-u.length+(n.nodes?n.nodes.length:0)),\"function\"==typeof o?`${o.name}${\"function\"==typeof o.getType?` (type ${String(o.getType())})`:\"\"}`:String(o),String(r))}ra(o);const s=o.getType(),l=eu(o);_.set(s,{exportDOM:h&&h.export?h.export.get(o):void 0,klass:o,replace:r,replaceWithKlass:i,sharedNodeState:An(u[t]),transforms:l})}}const p=new su(l,i,_,{disableEvents:s,dom:{...nu,...t&&t.dom},namespace:c,theme:r},f||console.error,d||$a,function(t,e){const n=new Map,o=new Set,r=t=>{Object.keys(t).forEach(e=>{let o=n.get(e);void 0===o&&(o=[],n.set(e,o)),o.push(t[e])})};return t.forEach(t=>{const e=t.klass.importDOM;if(null==e||o.has(e))return;o.add(e);const n=e.call(t.klass);null!==n&&r(n)}),e&&r(e),n}(_,h?h.import:void 0),g,t);return void 0!==a&&(p._pendingEditorState=a,p._dirtyType=2),function(t){t.registerCommand(Z,yf,0),t.registerCommand(tt,xf,0),t.registerCommand(et,Sf,0),t.registerCommand(nt,Cf,0),t.registerCommand(_t,Pf,0)}(p),p}function ru(t,e){const n=t.get(e);t.delete(e),n&&n()}function iu(t,e,n){return t.set(e,n),ru.bind(null,t,e)}class su{static version=(()=>ee)();_headless;_recordNodeMoves;_parentEditor;_rootElement;_editorState;_pendingEditorState;_compositionKey;_deferred;_keyToDOMMap;_updates;_updating;_cascadeCount;_listeners;_commands;_nodes;_decorators;_pendingDecorators;_config;_dirtyType;_cloneNotNeeded;_dirtyLeaves;_dirtyElements;_normalizedNodes;_updateTags;_observer;_key;_onError;_onWarn;_htmlConversions;_window;_editable;_blockCursorElement;_slotsUsed;_keyDownShortcuts;_inputState;_lastNotifiedSelection;_createEditorArgs;constructor(t,e,n,o,r,i,s,l,c){this._createEditorArgs=c,this._parentEditor=e,this._rootElement=null,this._editorState=t,this._pendingEditorState=null,this._compositionKey=null,this._deferred=[],this._keyToDOMMap=new ie,this._updates=[],this._updating=!1,this._cascadeCount=0,this._listeners={decorator:new Map,editable:new Map,mutation:new Map,root:new Map,textcontent:new Map,update:new Map},this._commands=new Map,this._config=o,this._nodes=n,this._decorators={},this._pendingDecorators=null,this._dirtyType=0,this._cloneNotNeeded=new Map,this._dirtyLeaves=new Set,this._dirtyElements=new Map,this._normalizedNodes=new Set,this._updateTags=new Set,this._observer=null,this._key=el(),this._onError=r,this._onWarn=i,this._htmlConversions=s,this._editable=l,this._headless=null!==e&&e._headless,this._recordNodeMoves=!1,this._window=null,this._blockCursorElement=null,this._slotsUsed=!1,this._keyDownShortcuts=null,this._inputState={collapsedSelectionFormat:{format:0,key:\"root\",offset:0,style:\"\",timeStamp:0},composedSegmentedKey:null,compositionPhase:\"idle\",hadOrphanedCompositionEvents:!1,handledSelectionCommandTimeoutId:null,isInsertLineBreak:!1,isInsertTextAfterHandledSelectionCommand:!1,isSelectionChangeFromDOMUpdate:!1,isSelectionChangeFromMouseDown:!1,isShiftKeyDown:!1,lastBeforeInputInsertTextTimeStamp:0,lastKeyCode:null,lastKeyDownTimeStamp:0,lastPointerType:\"\",mouseDrag:null,postDeleteSelectionToRestore:null,savedInputMode:void 0,selectionChangeFromDOMUpdatePoints:null,unprocessedBeforeInputData:null},this._lastNotifiedSelection=null}isComposing(){return null!=this._compositionKey}registerUpdateListener(t){return iu(this._listeners.update,t)}registerEditableListener(t){return iu(this._listeners.editable,t)}registerDecoratorListener(t){return iu(this._listeners.decorator,t)}registerTextContentListener(t){return iu(this._listeners.textcontent,t)}registerRootListener(t){const e=this._listeners.root;return ju(iu(e,t,t(this._rootElement,null)||void 0),()=>function(t,e,n){const o=t.get(e);o&&o(),t.set(e,e(...n)||void 0)}(e,t,[null,this._rootElement]))}registerCommand(t,n,o){void 0===o&&e(35);const r=this._commands;r.has(t)||r.set(t,[new ne,new ne,new ne,new ne,new ne]);const i=r.get(t);void 0===i&&e(36,String(t));const s=function(t){return 7&t}(o),l=i[s];return s!==o?l.addFront(n):l.addBack(n),()=>{l.delete(n),i.every(t=>0===t.size)&&r.delete(t)}}registerMutationListener(t,e,n){const o=this.resolveRegisteredNodeAfterReplacements(this.getRegisteredNode(t)).klass,r=this._listeners.mutation;let i=r.get(e);void 0===i&&(i=new Set,r.set(e,i)),i.add(o);const s=n&&n.skipInitialization;return void 0!==s&&s||this.initializeMutationListener(e,o),()=>{i.delete(o),0===i.size&&r.delete(e)}}getRegisteredNode(t){const n=this._nodes.get(t.getType());return void 0===n&&e(37,t.name),n}resolveRegisteredNodeAfterReplacements(t){for(;t.replaceWithKlass;)t=this.getRegisteredNode(t.replaceWithKlass);return t}initializeMutationListener(t,e){const n=this._editorState,o=wc(n).get(e.getType());if(!o)return;const r=new Map;for(const t of o.keys())r.set(t,\"created\");r.size>0&&t(r,{dirtyLeaves:new Set,prevEditorState:n,updateTags:new Set([\"registerMutationListener\"])})}registerNodeTransformToKlass(t,e){const n=this.getRegisteredNode(t);return n.transforms.add(e),n}registerNodeTransform(t,e){const n=this.registerNodeTransformToKlass(t,e),o=[n],r=n.replaceWithKlass;if(null!=r){const t=this.registerNodeTransformToKlass(r,e);o.push(t)}return Vs(this,o.map(t=>t.klass.getType())),()=>{o.forEach(t=>t.transforms.delete(e))}}hasNode(t){return this._nodes.has(t.getType())}hasNodes(t){return t.every(this.hasNode.bind(this))}dispatchCommand(t,...e){return vl(this,t,...e)}getDecorators(){return this._decorators}getRootElement(){return this._rootElement}getKey(){return this._key}setRootElement(t){const n=this._rootElement;if(t!==n){const o=gl(this._config.theme,\"root\"),r=this._pendingEditorState||this._editorState;if(this._rootElement=t,tu(this,n,t,r,{preserveUpdateQueue:!0}),null!==n&&(this._config.disableEvents||function(t){const n=Vu.get(t);if(void 0===n)return void Rf();const o=Hu.get(n);if(void 0===o)return void Rf();Vu.delete(t);const r=bs(t);Ss(r)?(function(t){if(null!==t._parentEditor){const e=Zs(t),n=e[e.length-1]._key;Lf.get(n)===t&&Lf.delete(n)}else Lf.delete(t._key)}(r),o.editors.delete(r),o.hasShadowEditor=void 0,t.__lexicalEditor=null):r&&e(198);const i=Ff(t);for(let t=0;t<i.length;t++)i[t]();t.__lexicalEventHandles=[]}(n),null!=o&&n.classList.remove(...o)),null!==t){const e=Ol(t),n=t.style;n.userSelect=\"text\",n.whiteSpace=\"pre-wrap\",n.wordBreak=\"break-word\",t.setAttribute(\"data-lexical-editor\",\"true\"),this._window=e,this._dirtyType=2,Ee(this),this._updateTags.add(Ta),Pu(this),this._config.disableEvents||function(t,e){const n=t.ownerDocument;Vu.set(t,n);let o=Hu.get(n);void 0===o&&(o={editors:new Set,hasShadowEditor:void 0},Hu.set(n,o)),o.editors.add(e),o.hasShadowEditor=void 0,t.__lexicalEditor=e;const r=Ff(t);r.push(qu.register(n));const i={blur:Ut,click:ef,compositionend:Tf,compositionstart:vf,copy:Lt,cut:Kt,dragend:It,dragover:Ft,dragstart:Pt,drop:Mt,focus:$t,input:mf,keydown:Nf,paste:lt,pointerdown:cf,...d&&{beforeinput:pf},...g&&{keyup:wf,mousedown:rf}};for(const[n,o]of Object.entries(i)){const i=r=>{Bf(r)||(zf(r),\"blur\"===n&&(lf(e,t),e._inputState.isShiftKeyDown=!1,e._inputState.isInsertLineBreak=!1),(e.isEditable()||\"click\"===n||\"copy\"===n)&&(\"function\"==typeof o?o(r,e):vl(e,o,r)))};r.push($u(t,n,i))}let s;const l=()=>{e._inputState.mouseDrag=null},c=n=>{const r=e._inputState,i=r.mouseDrag;if(s&&s.defaultPrevented&&!n.buttons&&(r.isSelectionChangeFromMouseDown=!1),!i||\"mouse\"!==n.pointerType)return;const c=\"pointerup\"===n.type;if(\"pointercancel\"===n.type||!c&&1!==n.buttons)return l();r.mouseDrag=c?null:n,Wu(e,()=>{const s=jl(Ml(e));if(\"mousedown\"!==i.type){const o=c&&s&&Xf(Od())&&Ed(Md(),s,e,new Event(\"selectionchange\"));return o&&Ys(o),uf(e,n,c&&s?Ql(s,t).focusNode:null)}const a=Nd(s,e);if(i.defaultPrevented||!i.shiftKey&&a&&!a.isCollapsed())l();else if(s&&r.isSelectionChangeFromMouseDown){If(e,s,new Event(\"selectionchange\"),o),uf(e,i,Ql(s,t).focusNode);const n=Od();Xf(n)&&n.isCollapsed()&&!n.is(Md())&&tf(e,n)}})};r.push(Uu(n,{pointercancel:c,pointermove:c,pointerup:c},!0),$u(Ml(e),\"blur\",l),e.registerEditableListener(l),Uu(t,{contextmenu:l,dragstart:l,keydown:t=>t.getModifierState&&t.getModifierState(t.key)||l(),mousedown:t=>{const n=e._inputState;n.mouseDrag=0!==t.button||1!==t.detail||t.defaultPrevented||\"mouse\"!==n.lastPointerType||!e.isEditable()||e.isComposing()||Lc(ic(t),e)?null:t}}),$u(t,\"pointerdown\",t=>{s=t,e._inputState.lastPointerType=t.pointerType},!0)),g&&r.push(function(t,e){let n=null;const o={capture:!0,passive:!0};return ju($u(t,\"touchstart\",t=>{const e=1===t.touches.length?t.touches[0]:null;n=e?{x:e.clientX,y:e.clientY}:null},o),$u(t,\"touchend\",t=>{const o=t.changedTouches[0];null!==n&&o&&0===t.touches.length&&Math.abs(o.clientX-n.x)<=nf&&Math.abs(o.clientY-n.y)<=nf&&e(t),n=null},o))}(t,n=>function(t,e,n){void 0!==e._inputState.savedInputMode&&(sf(t,e,n)||(rc(n.ownerDocument)===n&&n.blur(),lf(e,n)))}(n,e,t)))}(t,this),null!=o&&t.classList.add(...o)}else this._window=null,this._updateTags.add(Ta),Pu(this);Fu(\"root\",this,!1,t,n)}}getElementByKey(t){return this._keyToDOMMap.get(t)||null}getEditorState(){return this._editorState}setEditorState(t,e){const o=t.isEmpty();let r=t;r._readOnly&&(r=ma(t),r._selection=t._selection?t._selection.clone():null),we(this);const i=this._pendingEditorState,s=void 0!==e?e.tag:null;null===i||i.isEmpty()||(null!=s&&this._updateTags.add(s),Pu(this)),this._pendingEditorState=r,this._dirtyType=2,this._dirtyElements.set(\"root\",!1),this._compositionKey=null,this._slotsUsed=this._slotsUsed||t._slotsUsed,Wu(this,()=>{if(s&&this._updateTags.add(s),o&&(n(38),Hs().append(os())),t._parsed)for(const[t,e]of r._nodeMap.entries())ni(e)?this._dirtyElements.set(t,!0):this._dirtyLeaves.add(t)},{discrete:!this._updating||void 0})}parseEditorState(t,e){return function(t,e,n){const o=xa(),r=cu,i=uu,s=au,l=e._dirtyElements,c=e._dirtyLeaves,a=e._cloneNotNeeded,u=e._dirtyType;e._dirtyElements=new Map,e._dirtyLeaves=new Set,e._cloneNotNeeded=new Map,e._dirtyType=0,cu=o,uu=!1,au=e,us(null);try{const r=e._nodes;Mu(t.root,r),n&&n(),o._readOnly=!0,o._parsed=!0}catch(t){t instanceof Error&&e._onError(t)}finally{e._dirtyElements=l,e._dirtyLeaves=c,e._cloneNotNeeded=a,e._dirtyType=u,cu=r,uu=i,au=s}return o}(\"string\"==typeof t?JSON.parse(t):t,this,e)}read(...t){const[e,n]=1===t.length?[\"force-commit\",t[0]]:t;return\"force-commit\"===e&&(_u.has(this)||Pu(this)),(\"pending\"===e?this._pendingEditorState||this._editorState:this.getEditorState()).read(n,{editor:this})}update(t,e){!function(t,e,n){t._updating?t._updates.push([e,n]):Ru(t,e,n)}(this,t,e)}focus(t,e={}){const n=this._rootElement;null!==n&&(n.setAttribute(\"autocapitalize\",\"off\"),Wu(this,()=>{const o=Od(),r=Hs();null!==o?o.dirty||Ys(o.clone()):0!==r.getChildrenSize()&&(\"rootStart\"===e.defaultSelection?r.selectStart():r.selectEnd()),wl(\"focus\"),El(()=>{n.removeAttribute(\"autocapitalize\"),t&&t()})}),null===this._pendingEditorState&&n.removeAttribute(\"autocapitalize\"))}blur(){const t=this._rootElement;null!==t&&t.blur();const e=jl(this._window);null!==e&&e.removeAllRanges()}isEditable(){return this._editable}setEditable(t){this._editable!==t&&(this._editable=t,Fu(\"editable\",this,!0,t),this._slotsUsed&&this.update(()=>ku()))}toJSON(){return{editorState:this._editorState.toJSON(ce())}}}function lu(t,e,n,o,r,i){if(ni(t)){let s=t.__first;for(;null!==s;){const t=o.get(s);if(void 0===t)break;const l=ni(t);t.__parent!==e||l&&i.has(s)||((l||rh(t)&&null!==t.__slots)&&lu(t,s,n,o,r,i),n.has(s)||i.delete(s),r.push(s)),s=t.__next}}for(const s of rh(t)&&null!==t.__slots?t.__slots.values():[]){const t=o.get(s);void 0!==t&&ih(t)&&t.__slotHost===e&&((ni(t)||rh(t)&&null!==t.__slots)&&lu(t,s,n,o,r,i),n.has(s)||i.delete(s),r.push(s))}}let cu=null,au=null,uu=!1,fu=!1,du=!1;const hu=new Set,gu=new Set,_u=new Set;let pu=0;const yu={characterData:!0,childList:!0,subtree:!0};function mu(){return uu||null!==cu&&cu._readOnly}function xu(){uu&&e(13)}function vu(){pu>99&&e(14)}function Su(){return null===cu&&e(195,Tu()),cu}function Cu(t){null!==Su()&&null===au&&(au=t),au!==t&&n(378)}function bu(){return null===au&&e(337,Tu()),au}function ku(){bu()._dirtyType=2}function Tu(){let t=0;const e=new Set,n=su.version;if(\"undefined\"!=typeof window)for(const o of Hl(document)){const r=bs(o);if(Ss(r))t++;else if(r){let t=String(r.constructor.version||\"<0.17.1\");t===n&&(t+=\" (separately built, likely a bundler configuration issue)\"),e.add(t)}}let o=` Detected on the page: ${t} compatible editor(s) with version ${n}`;return e.size&&(o+=` and incompatible editors with versions ${Array.from(e).join(\", \")}`),o}function Nu(){return au}function wu(t,e,n){const o=e.__type,r=gs(t,o);let i=n.get(o);void 0===i&&(i=Array.from(r.transforms),n.set(o,i));const s=i.length;for(let t=0;t<s&&(i[t](e),e.isAttached());t++);}function Eu(t,e){return void 0!==t&&t.__key!==e&&t.isAttached()}function Au(t,e){if(!e)return;const n=t._updateTags;let o=e;Array.isArray(e)||(o=[e]);for(const t of o)n.add(t)}function Ou(t){return Mu(t,bu()._nodes)}function Mu(t,n){const o=t.type,r=n.get(o);void 0===r&&e(17,o);const i=r.klass;t.type!==i.getType()&&e(18,i.name);const s=i.importJSON(t),l=t.children;if(ni(s)&&Array.isArray(l))for(let t=0;t<l.length;t++){const e=Mu(l[t],n);s.append(e)}const c=t.$slots;if(c){rh(s)||e(379,i.name);for(const t in c)Ch(s,t,Mu(c[t],n))}return s}function Du(t,e,n){const o=cu,r=uu,i=au;cu=e,uu=!0,au=t;try{return n()}finally{cu=o,uu=r,au=i}}function Pu(e,n){null!==e._pendingEditorState&&au!==e&&we(e,!1,!0);const o=du;du=!0;try{const o=function(t){if(gu.has(t))return!1;gu.add(t);try{for(let e=0;null!==t._pendingEditorState;e++){const n=t._pendingEditorState._selection,o=t._rootElement;if(!Iu(t,n))return!1;const r=(null===n||Xf(n))&&(t._headless||null===o||!o.isConnected);if(r||100===e)return t._lastNotifiedSelection=null===n?null:n.clone(),!r;Ru(t,()=>t.dispatchCommand(X),void 0,!0)}return!1}finally{gu.delete(t)}}(e);!function(e,n){const o=e._pendingEditorState,r=e._rootElement,i=e._headless||null===r;if(null===o)return void(!e._updating&&e._deferred.length>0&&Ku(e,e._deferred));const s=e._editorState,l=s._selection,c=o._selection,a=0!==e._dirtyType,u=cu,f=uu,d=au,h=e._updating,g=e._observer;let _=null;if(e._pendingEditorState=null,e._editorState=o,!i&&a&&null!==g){au=e,cu=o,uu=!1,e._updating=!0;try{const t=e._dirtyType,n=e._dirtyElements,r=e._dirtyLeaves;g.disconnect(),_=Ko(s,o,e,t,n,r)}catch(t){if(t instanceof Error&&e._onError(t),fu)throw t;return tu(e,null,r,o),Ee(e),e._dirtyType=2,fu=!0,Pu(e,s),void(fu=!1)}finally{g.observe(r,yu),e._updating=h,cu=u,uu=f,au=d}}o._readOnly||(o._readOnly=!0);const p=e._dirtyLeaves,y=e._dirtyElements,m=e._normalizedNodes,x=e._updateTags;a&&(e._dirtyType=0,e._cloneNotNeeded.clear(),e._dirtyLeaves=new Set,e._dirtyElements=new Map,e._normalizedNodes=new Set),e._updateTags=new Set;const v=e._deferred;h||(e._deferred=[]),function(t,e){const n=t._decorators;let o=t._pendingDecorators||n;const r=e._nodeMap;let i;for(i in o)r.has(i)||(o===n&&(o=Us(t)),delete o[i])}(e,o);const S=i?null:jl(Ml(e));if(e._editable&&null!==S&&(a||null===c||c.dirty||!c.is(l))&&null!==r&&!x.has(Ma)){au=e,cu=o;try{if(null!==g&&g.disconnect(),a||null===c||c.dirty){const t=e._blockCursorElement;null!==t&&Wl(t,e,r),zd(l,c,e,S,x,r)}!function(t,e,n){let o=t._blockCursorElement;if(Xf(n)&&n.isCollapsed()&&\"element\"===n.anchor.type&&e.contains(oc(e))){const r=n.anchor,i=r.getNode(),s=r.offset;let l=!1,c=null;if(s===i.getChildrenSize())Rl(i.getChildAtIndex(s-1))&&(l=!0);else{const e=i.getChildAtIndex(s);null!==e&&Rl(e)&&(l=!0,c=t.getElementByKey(e.__key))}if(l){const n=vc(i,t.getElementByKey(i.__key),t).element;return null===o&&(t._blockCursorElement=o=function(t){const e=t.theme,n=Yl().createElement(\"div\");n.contentEditable=\"false\",n.setAttribute(\"data-lexical-cursor\",\"true\");let o=e.blockCursor;if(void 0!==o){if(\"string\"==typeof o){const t=gg(o);o=e.blockCursor=t}void 0!==o&&n.classList.add(...o)}return n}(t._config)),e.style.caretColor=\"transparent\",void(null===c?n.appendChild(o):n.insertBefore(o,c))}}null!==o&&Wl(o,t,e)}(e,r,c)}finally{null!==g&&g.observe(r,yu),au=d,cu=u}}const C=_u.has(e);_u.add(e);try{null!==_&&function(t,e,n,o,r){const i=Array.from(t._listeners.mutation),s=i.length;for(let t=0;t<s;t++){const[s,l]=i[t];for(const t of l){const i=e.get(t);void 0!==i&&s(i,{dirtyLeaves:o,prevEditorState:r,updateTags:n})}}}(e,_,x,p,s);const t=e._pendingDecorators;null!==t&&(e._decorators=t,e._pendingDecorators=null,Fu(\"decorator\",e,!0,t)),function(t,e,n){const o=Js(e),r=Js(n);o!==r&&Fu(\"textcontent\",t,!0,r)}(e,n||s,o),Fu(\"update\",e,!0,{dirtyElements:y,dirtyLeaves:p,editorState:o,mutatedNodes:_,normalizedNodes:m,prevEditorState:n||s,tags:x})}finally{C||_u.delete(e)}h||Ku(e,v),function(e){const n=e._updates;if(0===n.length)return void(e._cascadeCount=0);if(function(t){hu.has(t)||(hu.add(t),setTimeout(()=>{hu.delete(t),t._cascadeCount=0},0))}(e),e._cascadeCount++>99)return e._updates=[],e._cascadeCount=0,void e._onWarn(t(437,e._config.namespace));const o=n.shift();if(o){const[t,n]=o;Ru(e,t,n)}}(e)}(e,n),o&&e._onWarn(t(436))}finally{du=o}}function Fu(t,e,n,...o){const r=e._updating;e._updating=n;try{const n=e._listeners[t],r=Array.from(n);for(const[t,e]of r){e&&e();const r=t(...o),i=\"function\"==typeof r?r:void 0;n.has(t)?n.set(t,i):i&&i()}}finally{e._updating=r}}function Iu(t,e){const n=t._lastNotifiedSelection;return null===e?null!==n:!e.is(n)}function Lu(t,e,n,o){const r=Zs(t);let i;if(!du)for(let t=0;t<r.length;t++)r[t]._updating||(r[t]._cascadeCount=0);if(e===X){if(au!==t||uu){let r=!1;return Wu(t,()=>{r=Lu(t,e,n,o)}),r}const r=Su()._selection;t._lastNotifiedSelection=null===r?null:r.clone()}for(let t=4;t>=0;t--)for(let s=0;s<r.length;s++){const l=r[s];if(s>0&&l._updating){i=l;break}const c=l._commands.get(e);if(void 0!==c){const e=c[t];if(e.size>0){let t=!1;if(Wu(l,()=>{for(const r of e)if(r(n,o))return void(t=!0)}),t)return t}}}return i&&i.update(()=>{Lu(i,e,n,o)}),!1}function Ku(t,e){if(t._deferred===e&&(t._deferred=[]),0!==e.length){const n=t._updating;t._updating=!0;try{for(let t=0;t<e.length;t++)e[t]()}finally{t._updating=n}}}function zu(t,n){const o=t._updates;let r=n||!1;for(;0!==o.length;){const n=o.shift();if(n){const[o,i]=n,s=t._pendingEditorState;let l;void 0!==i&&(l=i.onUpdate,i.skipTransforms&&(r=!0),i.discrete&&(null===s&&e(191),s._flushSync=!0),l&&t._deferred.push(l),Au(t,i.tag)),null==s?Ru(t,o,i):o()}}return r}function Bu(){const t=Su();xu(),t._flushSync=!0}function Ru(t,n,o,r=!1){const i=t._updateTags;let s,l=!1,c=!1;void 0!==o&&(s=o.onUpdate,Au(t,o.tag),l=o.skipTransforms||!1,c=o.discrete||!1),s&&t._deferred.push(s);const a=t._editorState;let u=t._pendingEditorState,f=!1;(null===u||u._readOnly)&&(u=t._pendingEditorState=ma(u||a),f=!0),u._flushSync=c;const d=cu,h=uu,g=au,_=t._updating,p=t._lastNotifiedSelection;cu=u,uu=!1,t._updating=!0,au=t;const y=t._headless||null===t.getRootElement();us(null);try{f&&(y?null!==a._selection&&(u._selection=a._selection.clone()):u._selection=function(t,e){const n=t.getEditorState()._selection,o=jl(Ml(t));return Xf(n)||null==n?Ed(n,o,t,e):n.clone()}(t,o&&o.event||null));const r=t._compositionKey;n(),l=zu(t,l),function(t,e){const n=e.getEditorState()._selection,o=t._selection;if(Xf(o)){const t=o.anchor,e=o.focus;let r;if(\"text\"===t.type&&(r=t.getNode(),r.selectionTransform(n,o)),\"text\"===e.type){const t=e.getNode();r!==t&&t.selectionTransform(n,o)}}}(u,t),0!==t._dirtyType&&(l?function(t,e){const n=e._dirtyLeaves,o=t._nodeMap;for(const t of n){const e=o.get(t);Mi(e)&&e.isAttached()&&e.isSimpleText()&&!e.isUnmergeable()&&qo(e)}}(u,t):function(t,e){const n=e._dirtyLeaves,o=e._dirtyElements,r=t._nodeMap,i=Ks(),s=new Map;let l=n,c=l.size,a=o,u=a.size;for(;c>0||u>0;){if(c>0){e._dirtyLeaves=new Set;for(const t of l){const o=r.get(t);Mi(o)&&o.isAttached()&&o.isSimpleText()&&!o.isUnmergeable()&&qo(o),void 0!==o&&Eu(o,i)&&wu(e,o,s),n.add(t)}if(l=e._dirtyLeaves,c=l.size,c>0){pu++;continue}}e._dirtyLeaves=new Set,e._dirtyElements=new Map,a.delete(\"root\")&&a.set(\"root\",!0);for(const t of a){const n=t[0],l=t[1];if(o.set(n,l),!l)continue;const c=r.get(n);void 0!==c&&Eu(c,i)&&wu(e,c,s)}l=e._dirtyLeaves,c=l.size,a=e._dirtyElements,u=a.size,pu++}e._dirtyLeaves=n,e._dirtyElements=o}(u,t),zu(t),function(t,e,n,o){const r=t._nodeMap,i=e._nodeMap,s=[];for(const[t]of o){const e=i.get(t);void 0!==e&&(e.isAttached()||(ni(e)&&lu(e,t,r,i,s,o),r.has(t)||o.delete(t),s.push(t)))}for(const t of n){const e=i.get(t);void 0===e||e.isAttached()||(rh(e)&&null!==e.__slots&&lu(e,t,r,i,s,n),r.has(t)||n.delete(t),s.push(t))}const l=bu(),c=l._cloneNotNeeded;for(const t of s)i.delete(t),c.delete(t);const a=l._compositionKey;null===a||i.has(a)||(l._compositionKey=null)}(a,u,t._dirtyLeaves,t._dirtyElements)),r!==t._compositionKey&&(u._flushSync=!0);const i=u._selection;if(Xf(i)){t._slotsUsed&&xd(i);const n=u._nodeMap,o=i.anchor.key,r=i.focus.key;void 0!==n.get(o)&&void 0!==n.get(r)||e(19)}else Qf(i)&&0===i._nodes.size&&(u._selection=null)}catch(e){e instanceof Error&&t._onError(e),t._pendingEditorState=a;const n=a._selection;return t._lastNotifiedSelection=null===n?null:n.clone(),t._dirtyType=2,t._cloneNotNeeded.clear(),t._dirtyLeaves=new Set,t._dirtyElements.clear(),void Pu(t)}finally{cu=d,uu=h,au=g,t._updating=_,pu=0}if(r)return;const m=0!==t._dirtyType||t._deferred.length>0||function(t,e){const n=e.getEditorState()._selection,o=t._selection;if(null!==o){if(o.dirty||!o.is(n))return!0}else if(null!==n)return!0;return!1}(u,t);m?u._flushSync?(u._flushSync=!1,Pu(t)):f&&ps(()=>{Pu(t)}):(u._flushSync=!1,f&&(i.clear(),t._deferred=[],t._pendingEditorState=null,t._lastNotifiedSelection=p))}function Wu(t,e,n){au===t&&void 0===n?mu()?Ru(t,e,n):e():Ru(t,e,n)}function ju(...t){return()=>{for(let e=t.length-1;e>=0;e--)t[e]();t.length=0}}function $u(t,e,n,o){return t.addEventListener(e,n,o),t.removeEventListener.bind(t,e,n,o)}function Uu(t,e,n){return ju(...Object.entries(e).map(([e,o])=>$u(t,e,o,n)))}const Ju=30,Vu=new WeakMap,Hu=new WeakMap,qu=/* @__PURE__ */Zt(t=>(t.addEventListener(\"selectionchange\",Kf),()=>t.removeEventListener(\"selectionchange\",Kf)));function Yu(t,e,n,o,r,i){const s=t.anchor,l=t.focus,c=s.getNode(),a=bu();let u;if(void 0!==i)u=i;else{const t=jl(Ml(a));u=null!==t?Ql(t,a._rootElement):null}const f=null!==u?u.anchorNode:null,h=s.key,g=a.getElementByKey(h),_=n.length;return h!==l.key||!Mi(c)||(!r&&(!d||a._inputState.lastBeforeInputInsertTextTimeStamp<o+50)||c.isDirty()&&_<2||Qs(n))&&s.offset!==l.offset&&!c.isComposing()||Ns(c)||c.isDirty()&&_>1||(r||!d)&&null!==g&&!c.isComposing()&&f!==kc(c,g,a)||null!==u&&null!==e&&(!e.collapsed||e.startContainer!==u.anchorNode||e.startOffset!==u.anchorOffset)||!c.isComposing()&&(c.getFormat()!==t.format||c.getStyle()!==t.style)||function(t,e){if(e.isSegmented())return!0;if(!t.isCollapsed())return!1;const n=t.anchor.offset,o=e.getParentOrThrow(),r=Ts(e);return 0===n?!e.canInsertTextBefore()||!o.canInsertTextBefore()&&!e.isComposing()||r||function(t){const e=t.getPreviousSibling();return(Mi(e)||ni(e)&&e.isInline())&&!e.canInsertTextAfter()}(e):n===e.getTextContentSize()&&(!e.canInsertTextAfter()||!o.canInsertTextAfter()&&!e.isComposing()||r)}(t,c)}function Xu(t,e){return ws(t)&&null!==t.nodeValue&&0!==e&&e!==t.nodeValue.length}function Gu(t,e,n){const{anchorNode:o,anchorOffset:r,focusNode:i,focusOffset:s}=Ql(t,e._rootElement),l=e._inputState;if(l.isSelectionChangeFromDOMUpdate){l.isSelectionChangeFromDOMUpdate=!1;const t=l.selectionChangeFromDOMUpdatePoints;if(l.selectionChangeFromDOMUpdatePoints=null,Xu(o,r)&&Xu(i,s)&&!l.postDeleteSelectionToRestore&&(null===t||t.anchorNode===o&&t.anchorOffset===r&&t.focusNode===i&&t.focusOffset===s))return}Wu(e,()=>{if(!n)return void Ys(null);if(!vs(e,o,i))return;const c=l.mouseDrag;!c||\"mousedown\"===c.type&&c.defaultPrevented||uf(e,c,i);const a=af.has(c);let u=Od();if(l.postDeleteSelectionToRestore&&Xf(u)&&u.isCollapsed()){const t=u.anchor,e=l.postDeleteSelectionToRestore.anchor;(t.key===e.key&&t.offset===e.offset+1||1===t.offset&&e.getNode().is(t.getNode().getPreviousSibling()))&&(u=l.postDeleteSelectionToRestore.clone(),Ys(u))}if(l.postDeleteSelectionToRestore=null,Xf(u)){const n=u.anchor;if(u.isCollapsed())\"Range\"===t.type&&o===i&&(u.dirty=!0),tf(e,u);else{const t=n.key,e=u.focus,o=e.key,i=u.getNodes(),l=i.length,c=u.isBackward(),[f,d]=a?[n.offset,e.offset]:[r,s],h=c?d:f,g=c?f:d,_=c?o:t,p=c?t:o;let y=A,m=!1;for(let t=0;t<l;t++){const e=i[t],n=e.getTextContentSize();if(Mi(e)&&0!==n&&!(0===t&&e.__key===_&&h===n||t===l-1&&e.__key===p&&0===g)&&(m=!0,y&=e.getFormat(),0===y))break}u.format=m?y:0}}!function(t,e,n=!1){(n||Iu(t,e))&&t.dispatchCommand(X)}(e,u,null!==u&&(u.dirty&&!a||!Xf(u)))})}function Qu(t,e,n){t.format===e&&t.style===n||(t.format=e,t.style=n,t.dirty=!0)}function Zu(t,e){Qu(t,e.getFormat(),e.getStyle())}function tf(t,n){const o=n.anchor,r=o.getNode(),i=Ml(t).event,s=i?i.timeStamp:performance.now(),{format:l,style:c,offset:a,key:u,timeStamp:f}=t._inputState.collapsedSelectionFormat;s<f+200&&o.offset===a&&o.key===u?Qu(n,l,c):\"text\"===o.type?(Mi(r)||e(141),Zu(n,r)):(t.isComposing()||\"\"!==Hs().getTextContent())&&(ni(r)||e(259),r.isEmpty()?Ad(n,\"\"):Qu(n,n.format,\"\"))}function ef(t,e){Wu(e,()=>{const n=Od(),o=jl(Ml(e)),r=Md();if(o)if(Xf(n)){const t=n.anchor,e=t.getNode();\"element\"===t.type&&0===t.offset&&n.isCollapsed()&&!ci(e)&&1===Hs().getChildrenSize()&&e.getTopLevelElementOrThrow().isEmpty()&&null!==r&&n.is(r)&&(o.removeAllRanges(),n.dirty=!0)}else if(\"touch\"===t.pointerType||\"pen\"===t.pointerType||g&&\"mouse\"!==e._inputState.lastPointerType){const n=Ql(o,e._rootElement).anchorNode;(uc(n)||ws(n))&&Ys(Ed(r,o,e,t))}if(u&&null!==o&&0===o.rangeCount){const n=e._rootElement;if(null!==n&&t.target===n){const i=t.clientY;let s=n.childNodes.length;for(let t=0;t<n.childNodes.length;t++){const e=n.childNodes[t];if(uc(e)){const n=e.getBoundingClientRect();if(i<=(n.top+n.bottom)/2){s=t;break}}}o.setBaseAndExtent(n,s,n,s);const l=Ed(r,o,e,t);null!==l?Ys(l):o.removeAllRanges()}}vl(e,Q,t)})}const nf=10,of='input:not(:disabled),textarea:not(:disabled),select:not(:disabled),button:not(:disabled),a[href],area[href],label,summary,iframe,object,embed,audio[controls],video[controls],[tabindex],[contenteditable]:not([contenteditable=\"false\"])';function rf(t,e){const n=e.getRootElement();null!==n&&(sf(t,e,n)?(t.preventDefault(),rc(n.ownerDocument)!==n&&(void 0===e._inputState.savedInputMode&&(e._inputState.savedInputMode=n.getAttribute(\"inputmode\")),n.setAttribute(\"inputmode\",\"none\"),n.focus({preventScroll:!0}))):lf(e,n))}function sf(t,e,n){if(\"mouse\"===e._inputState.lastPointerType)return!1;const o=ic(t);if(!fc(o))return!1;let r=!1;for(let t=o;null!==t;t=Cl(t)){if(t===n)return r;if(1===t.nodeType){const e=t;if(e.matches(of))return!1;\"true\"===e.getAttribute(\"data-lexical-decorator\")&&(r=!0)}}return!1}function lf(t,e){const n=t._inputState.savedInputMode;void 0!==n&&(t._inputState.savedInputMode=void 0,null===n?e.removeAttribute(\"inputmode\"):e.setAttribute(\"inputmode\",n))}function cf(t,e){const n=ic(t),o=t.pointerType;fc(n)&&\"touch\"!==o&&\"pen\"!==o&&0===t.button&&Wu(e,()=>{Lc(n,e)||(e._inputState.isSelectionChangeFromMouseDown=!0)})}const af=new WeakSet;function uf(t,e,n=null){const o=Od(),r=o&&o.clone();!function(t,e,n){const o=Md(),r=\"mousedown\"===e.type,i=r&&!e.shiftKey,s=n&&$s(n);ii(s)&&(r?i&&s.isInline()&&s.selectPrevious():Xf(o)&&Ys(o.clone()));const l=Od(),c=l||(i?kd():Xf(o)?o.clone():null),a=t.getRootElement(),u=a&&a.getRootNode();if(!Xf(c)||i&&!c.isCollapsed()||!Es(u)&&!Ul(u))return;const{anchor:f,focus:d}=c;if(!r&&Xf(o)){const{key:t,offset:e,type:n}=o.anchor;f.set(t,e,n,!0)}const{clientX:h,clientY:g}=e,_=u.elementFromPoint&&u.elementFromPoint(h,g),p=_&&$s(_),y=(t,e)=>ni(t)?\"next\"===e?t.getLastDescendant():t.getFirstDescendant():t,m=[null],x=ni(p)&&!p.isInline()&&(ci(p)?_a(d.getNode(),Cd):p);for(const t of x?Uh(x,\"next\"):[])m.push(Rh(t.origin,\"previous\"),t);const v=Ml(t),S=v.document.createRange();let C=null;for(const e of m){const n=e?y(e.origin,e.direction):p;if(!ii(n)||!n.isInline()||n===C)continue;const o=t.getElementByKey(n.getKey());if(!o)continue;S.selectNodeContents(o);const r=S.getBoundingClientRect(),s=o.getBoundingClientRect(),{bottom:a,left:u,right:_,top:m}=r.height>s.height?r:s;if(e&&(g<m||g>a)){C=n;continue}const x=\"rtl\"===v.getComputedStyle(Cl(o)||o).direction,b=2*h>u+_!==x,k=b?\"next\":\"previous\",T=e&&e.getNodeAtCaret(),N=T&&t.getElementByKey(T.getKey()),w=N?N.getClientRects():[],E=w[b?0:w.length-1];if(!e||e.direction===k&&\"none\"===v.getComputedStyle(o).cssFloat&&(!T||Ba(T)||E&&(b===x?2*E.right>u+_:2*E.left<u+_))){if(!n.is(y(ml(d,b),k))){const t=Rh(n,k);Fi(d,t),i&&Fi(f,t)}return void(l||Ys(c))}}if(ii(s)&&!r){const e=v.document,n=e.caretPositionFromPoint&&e.caretPositionFromPoint(h,g,{shadowRoots:Ul(u)?[u]:[]}),o=n&&gd(n.offsetNode,n.offset,null,t);if(o){const[{key:t,offset:e,type:n}]=o;d.set(t,e,n)}}}(t,e,n);const i=Od(),s=t._inputState.mouseDrag;s&&i&&!i.is(r)&&af.add(s),\"mousedown\"===e.type&&Xf(i)&&Ad(i,Xf(r)?r.anchor.key:\"\")}function ff(t){if(!t.getTargetRanges)return null;const e=t.getTargetRanges();return 0===e.length?null:e[0]}function df(t){const{lastKeyCode:e}=bu()._inputState;if(null==t||t.length<=1||null==e)return;const n=1===e.length?e:\"Enter\"===e?\"\\n\":\"Tab\"===e?\"\\t\":null;if(!n)return;const o=Od();if(!Xf(o)||!o.isCollapsed())return;const r=o.anchor.getNode();if(!Mi(r))return;const{offset:i}=o.anchor;if(r.getTextContentSize()===i){const t=r.getNextSibling();if(\"\\n\"===n){if(g)return;if(Ba(t))t.selectEnd();else if(!t){const t=_a(r,Cd),e=t&&t.getNextSibling();ni(e)&&e.selectStart()}}else\"\\t\"===n?cs(t)&&t.selectEnd():Mi(t)&&t.getTextContent()[0]===n&&t.select(1,1)}else r.getTextContent()[i]===n&&r.select(i+1,i+1)}function hf(t){t.isInsertTextAfterHandledSelectionCommand=!1,null!==t.handledSelectionCommandTimeoutId&&(clearTimeout(t.handledSelectionCommandTimeoutId),t.handledSelectionCommandTimeoutId=null)}function gf(t){a&&!g&&y&&(hf(t),t.isInsertTextAfterHandledSelectionCommand=!0,t.handledSelectionCommandTimeoutId=setTimeout(()=>hf(t),0))}function _f(t,e){const n=ic(t);if(uc(n)&&Lc(n,e))return!0;const o=e.getRootElement();if(null===o)return!1;const r=rc(o.ownerDocument);return null!==r&&o.contains(r)&&(Lc(r,e)||ys(o,r))}function pf(t,e){const n=t.inputType;\"deleteCompositionText\"===n||u&&xl(e)||\"insertCompositionText\"!==n&&Wu(e,()=>{_f(t,e)||vl(e,Z,t)},{event:t})}function yf(t){const n=t.inputType,o=ff(t),r=bu(),i=r._inputState,s=Od();if(\"insertText\"===n&&t.data&&i.isInsertTextAfterHandledSelectionCommand){if(hf(i),t.preventDefault(),Xf(s)&&!s.isCollapsed()){const t=s.isBackward()?s.anchor:s.focus;s.anchor.set(t.key,t.offset,t.type),s.focus.set(t.key,t.offset,t.type)}return!0}if(\"deleteContentBackward\"===n){if(null===s){const t=Md();if(!Xf(t))return!0;Ys(t.clone())}if(Xf(s)){const n=s.anchor.key===s.focus.key;if(function(t,e){return\"MediaLast\"===t.lastKeyCode&&e<t.lastKeyDownTimeStamp+Ju}(i,t.timeStamp)&&r.isComposing()&&n){if(Ls(null),i.lastKeyDownTimeStamp=0,setTimeout(()=>{Wu(r,()=>{Ls(null)})},Ju),Xf(s)){const t=s.anchor.getNode();t.markDirty(),Mi(t)||e(142),Zu(s,t)}}else{if(Ls(null),g&&null!==o&&!o.collapsed&&(s.applyDOMRange(o),!s.isCollapsed()))return t.preventDefault(),s.removeText(),!0;t.preventDefault();const e=s.anchor.getNode(),l=e.getTextContent(),c=e.canInsertTextAfter(),a=0===s.anchor.offset&&s.focus.offset===l.length;let u=m&&n&&!a&&c;if(u&&s.isCollapsed()&&(u=!ii(ml(s.anchor,!0))),!u){vl(r,ot,!0);const t=Od();m&&Xf(t)&&t.isCollapsed()&&(i.postDeleteSelectionToRestore=t,setTimeout(()=>i.postDeleteSelectionToRestore=null))}}return!0}}if(!Xf(s))return\"historyUndo\"!==n&&\"historyRedo\"!==n||(t.preventDefault(),vl(r,\"historyUndo\"===n?ht:gt)),!0;const l=t.data;null!==i.unprocessedBeforeInputData&&ol(!1,r,i.unprocessedBeforeInputData);let c=!1;if((!s.dirty||null!==i.unprocessedBeforeInputData)&&s.isCollapsed()&&!ci(s.anchor.getNode())&&null!==o){const{key:t,offset:e,type:i}=s.anchor,l=r._slotsUsed&&pd(s.anchor);s.applyDOMRange(o);const a=n.endsWith(\"Forward\");if(!1!==l&&(a||n.endsWith(\"Backward\"))){const o=jf(t,e,i),{anchor:r,focus:u}=s,f=!md(pd(r),l)||!md(pd(u),l),d=!f&&null!==l&&(a?r.isBefore(o)||u.isBefore(o):o.isBefore(r)||o.isBefore(u));(f||d)&&(r.set(t,e,i),u.set(t,e,i),c=d&&\"deleteContentForward\"===n)}}i.unprocessedBeforeInputData=null;const a=s.anchor,u=s.focus,f=a.getNode(),d=u.getNode();if(\"insertText\"===n||\"insertTranspose\"===n){if(\"\\n\"===l)t.preventDefault(),vl(r,rt,!1);else if(l===M)t.preventDefault(),vl(r,it);else if(null==l&&t.dataTransfer){const e=t.dataTransfer.getData(\"text/plain\");t.preventDefault(),s.insertRawText(e)}else null!=l&&Yu(s,o,l,t.timeStamp,!0)?(t.preventDefault(),vl(r,st,l),df(l)):i.unprocessedBeforeInputData=l;return i.lastBeforeInputInsertTextTimeStamp=t.timeStamp,!0}switch(t.preventDefault(),n){case\"insertFromYank\":case\"insertFromDrop\":case\"insertReplacementText\":vl(r,st,t),df((t.dataTransfer?t.dataTransfer.getData(\"text/plain\"):null)??t.data);break;case\"insertFromComposition\":{i.compositionPhase=\"idle\";const e=i.hadOrphanedCompositionEvents;i.hadOrphanedCompositionEvents=!1;const n=r._compositionKey;Ls(null),e||vl(r,st,t),bf(n);break}case\"insertLineBreak\":Ls(null),i.isInsertLineBreak=!1,vl(r,rt,!1);break;case\"insertParagraph\":Ls(null),i.isInsertLineBreak?(i.isInsertLineBreak=!1,vl(r,rt,!1)):vl(r,it);break;case\"insertFromPaste\":case\"insertFromPasteAsQuotation\":vl(r,lt,t);break;case\"deleteByComposition\":(function(t,e){return t!==e||ni(t)||ni(e)||!Ts(t)||!Ts(e)})(f,d)&&vl(r,ct,t);break;case\"deleteByDrag\":wl(Da),vl(r,ct,t);break;case\"deleteByCut\":vl(r,ct,t);break;case\"deleteContent\":vl(r,ot,!1);break;case\"deleteWordBackward\":vl(r,at,!0);break;case\"deleteWordForward\":vl(r,at,!1);break;case\"deleteHardLineBackward\":case\"deleteSoftLineBackward\":vl(r,ut,!0);break;case\"deleteContentForward\":case\"deleteHardLineForward\":case\"deleteSoftLineForward\":vl(r,c?ot:ut,!1);break;case\"formatStrikeThrough\":vl(r,ft,\"strikethrough\");break;case\"formatBold\":vl(r,ft,\"bold\");break;case\"formatItalic\":vl(r,ft,\"italic\");break;case\"formatUnderline\":vl(r,ft,\"underline\");break;case\"historyUndo\":vl(r,ht);break;case\"historyRedo\":vl(r,gt)}return!0}function mf(t,e){t.stopPropagation();const n=e._inputState;hf(n),Wu(e,()=>{_f(t,e)||e.dispatchCommand(tt,t)},{event:t}),n.unprocessedBeforeInputData=null}function xf(t){const e=bu(),n=e._inputState,o=Od(),r=t.data,i=ff(t);let s=!1,l=!1;if(null!=r&&Xf(o)){const c=jl(Ml(e)),a=null!==c?Ql(c,e._rootElement):null,f=\"insertCompositionText\"===t.inputType&&\"ending-firefox\"!==n.compositionPhase&&!e.isComposing();f&&(n.hadOrphanedCompositionEvents=!0);const h=o.anchor.getNode(),g=\"insertCompositionText\"===t.inputType&&\"ending-firefox\"!==n.compositionPhase&&e.isComposing()&&Mi(h)&&Ns(h);if(!f&&!g&&Yu(o,i,r,t.timeStamp,!1,a)){if(s=!0,\"ending-firefox\"===n.compositionPhase){const t=kf(e,r);if(n.compositionPhase=\"idle\",t)return wl(Fa),Xs(),!0}const i=o.anchor.getNode();if(null===c||null===a)return!0;const f=o.isBackward(),h=f?o.anchor.offset:o.focus.offset,g=f?o.focus.offset:o.anchor.offset;d&&!o.isCollapsed()&&Mi(i)&&null!==a.anchorNode&&i.getTextContent().slice(0,h)+r+i.getTextContent().slice(h+g)===nl(a.anchorNode)||(vl(e,st,r),l=\"insertText\"===t.inputType);const _=r.length;u&&_>1&&\"insertCompositionText\"===t.inputType&&!e.isComposing()&&(o.anchor.offset-=_,o._cachedNodes=null,o._cachedIsBackward=null),m&&e.isComposing()&&(n.lastKeyDownTimeStamp=0,Ls(null))}}return s||(ol(!1,e,null!==r?r:void 0),\"ending-firefox\"===n.compositionPhase&&(kf(e,r||void 0),wl(Fa),n.compositionPhase=\"idle\")),Xs(l),!0}function vf(t,e){vl(e,et,t)}function Sf(t){const e=bu(),n=e._inputState,o=Od();if(Xf(o)&&!e.isComposing()){n.compositionPhase=\"composing\",n.hadOrphanedCompositionEvents=!1;const r=o.anchor,i=o.anchor.getNode();if(Ls(r.key),wl(Pa),t.timeStamp<n.lastKeyDownTimeStamp+Ju||\"element\"===r.type||!o.isCollapsed()||!m&&(i.getFormat()!==o.format||Mi(i)&&i.getStyle()!==o.style)||Mi(i)&&(Ns(i)||0===r.offset&&!i.canInsertTextBefore()||r.offset===i.getTextContentSize()&&!i.canInsertTextAfter())){g||!p&&!x?vl(e,st,D):function(t){Vf(t,\"\",!0)}(o);const t=Od();Xf(t)&&Ls(t.anchor.key)}}return!0}function Cf(t){const e=bu();return e._inputState.compositionPhase=\"idle\",kf(e,t.data),wl(Fa),!0}function bf(t){const e=bu()._inputState,n=e.composedSegmentedKey;if(e.composedSegmentedKey=null,null===t||t!==n)return;const o=Bs(t);if(!Mi(o)||\"text\"===o.getType()||Ns(o)||!o.isAttached())return;const r=Od(),i=Xf(r)&&r.anchor.key===t?r.anchor.offset:null,s=Oi(o.getTextContent());if(s.setFormat(o.getFormat()),s.setStyle(o.getStyle()),o.replace(s),null!==i){const t=Math.min(i,s.getTextContentSize());s.select(t,t)}}function kf(t,e){const n=t._compositionKey;if(Ls(null),null!==n&&null!=e){if(\"\"===e){const e=Bs(n),o=t.getElementByKey(n),r=null!==o&&Mi(e)?kc(e,o,t):null;if(null!==r&&null!==r.nodeValue&&Mi(e)){const n=jl(Ml(t)),o=n&&Ql(n,t._rootElement);let i=null,s=null;null!==o&&o.anchorNode===r&&(i=o.anchorOffset,s=o.focusOffset),rl(e,r.nodeValue,i,s,!0)}return bf(n),!1}if(\"\\n\"===e[e.length-1]){const e=Od();if(Xf(e)||Qf(e)){if(Xf(e)){const t=e.focus;e.anchor.set(t.key,t.offset,t.type)}return vl(t,Ct,null),bf(n),!1}}const o=Bs(n);if(null!==o&&Mi(o)&&Ns(o)){o.markDirty();const t=Od(),r=o.getTextContentSize(),i=Xf(t)&&t.anchor.key===n?t.anchor.offset:r;return o.select(i,i).insertText(e),!0}}return ol(!0,t,e),bf(n),!1}function Tf(t,e){const n=e._inputState;u?n.compositionPhase=\"ending-firefox\":(\"\"===t.data||g||!p&&!x)&&vl(e,nt,t)}function Nf(t,e){const n=e._inputState;g&&(n.isShiftKeyDown=\"Shift\"===t.key||n.isShiftKeyDown&&t.shiftKey&&\"CapsLock\"!==t.key),n.lastKeyDownTimeStamp=t.timeStamp,n.lastKeyCode=t.key,\"Backspace\"!==t.key&&hf(n),e.isComposing()||!g&&(p||x)&&229===t.keyCode||vl(e,_t,t)}function wf(t,e){t.shiftKey&&\"CapsLock\"!==t.key||(e._inputState.isShiftKeyDown=!1)}const Ef={altKey:\"any\",ctrlKey:\"any\",metaKey:\"any\",shiftKey:\"any\"},Af={ctrlKey:!0},Of={metaKey:!0},Mf={shiftKey:\"any\"},Df={altKey:\"any\",shiftKey:\"any\"};function Pf(t){const e=bu();if(null==t.key)return!0;let n=e._keyDownShortcuts;null===n&&(n=Qt(function(){const t=(t,e,n)=>({key:t,modifiers:e,onMatch:(t,e)=>{vl(e,n,t)}}),e=(t,e,n,o)=>({key:t,modifiers:e,onMatch:(t,e)=>{t.preventDefault(),vl(e,n,o)}}),n=(t,e)=>({key:\"Enter\",modifiers:t,onMatch:(t,n)=>{const o=n._inputState;o.isInsertLineBreak=e&&(!g||o.isShiftKeyDown),vl(n,Ct,t),t.defaultPrevented&&(o.isInsertLineBreak=!1)}}),o=(t,e)=>({key:t,modifiers:Ht,onMatch:(t,n)=>{const o=n._editorState._selection;null===o||Xf(o)||ms(t)||(t.preventDefault(),vl(n,e,t))}});return[t(\"ArrowRight\",Mf,pt),t(\"ArrowLeft\",Mf,mt),t(\"ArrowUp\",Df,vt),t(\"ArrowDown\",Df,St),n({...Ef,shiftKey:!0},!0),n({...Ef,shiftKey:!1},!1),t(\" \",Ef,bt),{key:\"Backspace\",modifiers:Mf,onMatch:(t,e)=>{vl(e,kt,t)&&gf(e._inputState)}},t(\"Escape\",Ef,Tt),t(\"Delete\",{},Nt),e(\"Backspace\",qt,at,!0),e(\"Delete\",qt,at,!1),e(\"b\",Ht,ft,\"bold\"),e(\"u\",Ht,ft,\"underline\"),e(\"i\",Ht,ft,\"italic\"),t(\"Tab\",Mf,wt),e(\"z\",Ht,ht,void 0),e(\"z\",{...Ht,shiftKey:!0},gt,void 0),...a?[{key:\"o\",modifiers:Af,onMatch:(t,e)=>{t.preventDefault(),vl(e,rt,!0)}},t(\"ArrowLeft\",{metaKey:!0,...Mf},xt),t(\"ArrowRight\",{metaKey:!0,...Mf},yt),e(\"h\",Af,ot,!0),e(\"d\",Af,ot,!1),e(\"Backspace\",Of,ut,!0),e(\"Delete\",Of,ut,!1),e(\"k\",Af,ut,!1)]:[t(\"Home\",Mf,xt),t(\"End\",Mf,yt),e(\"y\",Af,gt,void 0)],{key:\"a\",modifiers:Ht,onMatch:(t,e)=>{t.preventDefault(),vl(e,zt,t)&&gf(e._inputState)}},o(\"c\",Lt),o(\"x\",Kt)]}()),e._keyDownShortcuts=n);const o=n.match(t);return o&&o.onMatch(t,e),function(t){return t.ctrlKey||t.shiftKey||t.altKey||t.metaKey}(t)&&e.dispatchCommand(Jt,t),!0}function Ff(t){let e=t.__lexicalEventHandles;return void 0===e&&(e=[],t.__lexicalEventHandles=e),e}function If(t,e,n,o){if(void 0!==o)for(const t of o.editors)t._inputState.isSelectionChangeFromMouseDown=!1;const r=Ql(e,t._rootElement).anchorNode;(uc(r)||ws(r))&&Ys(Ed(Md(),e,t,n))}const Lf=new Map;function Kf(t){const e=t.target;if(uc(e)&&(\"INPUT\"===e.nodeName||\"TEXTAREA\"===e.nodeName))return;const n=$l(e);if(null===n)return;const o=bl(e);let r=null;const i=null!==o?Hu.get(o):void 0;if(null!==o){if(void 0!==i){const t=i.editors;let e=i.hasShadowEditor;if(void 0===e){e=!1;for(const n of t)if(null!==n._rootElement&&Ul(n._rootElement.getRootNode())){e=!0;break}i.hasShadowEditor=e}if(e){let e=null;for(const o of t){const t=o._rootElement;if(null===t)continue;const i=Ql(n,t).anchorNode;if(null!==i&&Cs(i)===o){if(Ul(t.getRootNode())){r=o;break}null===e&&(e=o)}}null===r&&null!==e&&(r=e)}else{const t=n.anchorNode;null===t||uc(t)&&null!==t.shadowRoot||(r=Cs(t))}}if(null===r){const t=rc(o);r=null!==t?Cs(t):null}}if(null===r)return;r._inputState.isSelectionChangeFromMouseDown&&Wu(r,()=>If(r,n,t,i));const s=Zs(r),l=s[s.length-1],c=l._key,a=Lf.get(c),u=a||l;u!==r&&Gu(n,u,!1),Gu(n,r,!0),r!==l?Lf.set(c,r):a&&Lf.delete(c)}function zf(t){t._lexicalHandled=!0}function Bf(t){return!0===t._lexicalHandled}const Rf=/* @__PURE__ */q();class Wf{key;offset;type;_selection;constructor(t,e,n){this._selection=null,this.key=t,this.offset=e,this.type=n}is(t){return this.key===t.key&&this.offset===t.offset&&this.type===t.type}isBefore(t){return this.key===t.key?this.offset<t.offset:ng($i(Pi(this,\"next\")),$i(Pi(t,\"next\")))<0}getNode(){const t=Bs(this.key);return null===t&&e(20),t}set(t,e,n,o){const r=this._selection,i=this.key;o&&this.key===t&&this.offset===e&&this.type===n||(this.key=t,this.offset=e,this.type=n,mu()||(Ks()===i&&Ls(t),null!==r&&(r.setCachedNodes(null),Xf(r)&&(r._cachedIsBackward=null),r.dirty=!0)))}}function jf(t,e,n){return new Wf(t,e,n)}function $f(t,e){let n=e.__key,o=t.offset,r=\"element\";if(Mi(e)){r=\"text\";const t=e.getTextContentSize();o>t&&(o=t)}else if(!ni(e)){const t=e.getNextSibling();if(Mi(t))n=t.__key,o=0,r=\"text\";else{const t=e.getParent();t&&(n=t.__key,o=e.getIndexWithinParent()+1)}}t.set(n,o,r)}function Uf(t,e){if(ni(e)){const n=e.getLastDescendant();ni(n)||Mi(n)?$f(t,n):$f(t,e)}else $f(t,e)}function Jf(t,e,n,o){const r=t.getNode(),i=r.getChildAtIndex(t.offset),s=Oi();if(s.setFormat(n),s.setStyle(o),rs(i))i.splice(0,0,[s]);else if(null!==i){const t=Il(r)?os().append(s):s;i.insertBefore(t)}else if(Il(r)){const t=r.getLastChild();ni(t)&&!t.isInline()&&t.isEmpty()?t.append(s):r.append(os().append(s))}else r.append(s);t.is(e)&&e.set(s.__key,0,\"text\"),t.set(s.__key,0,\"text\")}function Vf(t,n,o){let r=t.format,i=t.style;if(!t.isCollapsed()){const e=(t.focus.isBefore(t.anchor)?t.focus:t.anchor).getNode();if(Mi(e)&&(r=e.getFormat(),i=e.getStyle()),t.removeText(),t.format=r,t.style=i,\"\"===n&&!o)return;if(null===Ks())return\"element\"===t.anchor.type&&Jf(t.anchor,t.focus,r,i),void Hf(t,n,r,i)}\"element\"===t.anchor.type&&Jf(t.anchor,t.focus,r,i);const s=t.anchor.getNode();Mi(s)||e(398);const l=t.anchor.offset,c=s.getParentOrThrow(),a=s.getTextContentSize();if(Ns(s)||0===l&&(!s.canInsertTextBefore()||!c.canInsertTextBefore()&&!s.__prev)||l===a&&(!s.canInsertTextAfter()||!c.canInsertTextAfter()&&!s.__next)){if(s.isSegmented()&&0!==l&&l!==a){if(null!==Ks())s.setMode(\"normal\").setFormat(r).setStyle(i),bu()._inputState.composedSegmentedKey=s.getKey();else{const e=Oi(s.getTextContent());e.setFormat(r),e.setStyle(i);const n=Od()===t;s.replace(e),t.setTextNodeRange(e,l,e,l),n&&Od()!==t&&Ys(t)}return void((\"\"!==n||o)&&Vf(t,n,o))}if(\"\"===n&&!o)return;if(0===l||l===a){const e=0===l,a=e?\"previous\":\"next\",u=Rh(s,a).getNodeAtCaret();let f;Mi(u)&&(e?u.canInsertTextAfter():u.canInsertTextBefore())&&!Ns(u)?f=u:(f=Oi().setFormat(r).setStyle(i),Rh((e?c.canInsertTextBefore():c.canInsertTextAfter())?s:c,a).insert(f));const d=e?void 0:0;return f.select(d,d),void Vf(t,n,o)}const e=Oi(n);return e.setFormat(r),e.setStyle(i),s.replace(e),void e.select()}if(\"\"===n&&!o)return;const u=c.isInline()&&0===l&&!s.__prev,f=c.isInline()&&l===a&&!s.__next,d=s.getFormat()!==r||s.getStyle()!==i;if(u||f||d){if(\"\"!==s.getTextContent()||u||f)return void Hf(t,n,r,i);s.setFormat(r),s.setStyle(i)}s.spliceText(l,0,n,!0),s.isComposing()&&\"text\"===t.anchor.type&&t.anchor.set(t.anchor.key,t.anchor.offset-n.length,t.anchor.type)}function Hf(t,n,o,r){const i=t.anchor.getNode();Mi(i)||e(398);const s=t.anchor.offset,l=Oi(n).setFormat(o).setStyle(r),c=i.getParentOrThrow(),a=0===s,u=a||s===i.getTextContentSize();if(u&&c.isInline()&&!(a?i.__prev:i.__next))Rh(c,a?\"previous\":\"next\").insert(l);else{const t=u?i:i.splitText(s)[0];a?t.insertBefore(l,!1):t.insertAfter(l,!1)}\"\"===i.getTextContent()&&i.isAttached()&&i.remove(),l.selectEnd(),l.isComposing()&&\"text\"===t.anchor.type&&t.anchor.set(t.anchor.key,t.anchor.offset-n.length,t.anchor.type)}class qf{_nodes;_cachedNodes;dirty;constructor(t){this._cachedNodes=null,this._nodes=t,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(t){this._cachedNodes=t}is(t){if(!Qf(t))return!1;const e=this._nodes,n=t._nodes;return e.size===n.size&&Array.from(e).every(t=>n.has(t))}isCollapsed(){return!1}isBackward(){return!1}getStartEndPoints(){return null}add(t){this.dirty=!0,this._nodes.add(t),this._cachedNodes=null}delete(t){this.dirty=!0,this._nodes.delete(t),this._cachedNodes=null}clear(){this.dirty=!0,this._nodes.clear(),this._cachedNodes=null}has(t){return this._nodes.has(t)}clone(){return new qf(new Set(this._nodes))}extract(){return this.getNodes()}insertRawText(t){}insertText(){}insertNodes(t){const e=this.getNodes().filter(t=>null===sh(t)),n=e.length;if(0===n)return;const o=e[n-1];let r;if(Mi(o))r=o.select();else{const t=o.getIndexWithinParent()+1;r=o.getParentOrThrow().select(t,t)}r.insertNodes(t);for(let t=0;t<n;t++)e[t].remove()}getNodes(){const t=this._cachedNodes;if(null!==t)return t;const e=this._nodes,n=[];for(const t of e){const e=Bs(t);null!==e&&n.push(e)}return mu()||(this._cachedNodes=n),n}getTextContent(){const t=this.getNodes();let e=\"\";for(let n=0;n<t.length;n++)e+=t[n].getTextContent();return e}deleteNodes(){const t=this.getNodes().filter(t=>null===sh(t));if((Od()||Md())===this&&t[0]){const e=Rh(t[0],\"next\");Ii(tg(e,e))}for(const e of t)e.remove();Yf()}}function Yf(){const t=Hs();if(0===t.getChildrenSize()&&null===uh(Od())){const e=os();t.append(e),e.select()}}function Xf(t){return t instanceof Gf}class Gf{format;style;anchor;focus;_cachedNodes;_cachedIsBackward;dirty;constructor(t,e,n,o){this.anchor=t,this.focus=e,t._selection=this,e._selection=this,this._cachedNodes=null,this._cachedIsBackward=null,this.format=n,this.style=o,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(t){this._cachedNodes=t}is(t){return!!Xf(t)&&this.anchor.is(t.anchor)&&this.focus.is(t.focus)&&this.format===t.format&&this.style===t.style}isCollapsed(){return this.anchor.is(this.focus)}getNodes(){const t=this._cachedNodes;if(null!==t)return t;const e=function(t){const e=[],[n,o]=t.getTextSlices();n&&e.push(n.caret.origin);const r=new Set;let i=0;for(const n of t)if(Lh(n)){const{origin:t}=n;0===e.length?r.add(t):(i++,e.push(t))}else{const{origin:t}=n;ni(t)&&0!==i?i--:e.push(t)}if(o&&e.push(o.caret.origin),Ih(t.focus)&&ni(t.focus.origin)&&null===t.focus.getNodeAtCaret())for(let n=Uh(t.focus.origin,\"previous\");Lh(n)&&r.has(n.origin)&&!n.origin.isEmpty()&&n.origin.is(e[e.length-1]);n=Vh(n))r.delete(n.origin),e.pop();for(;e.length>1;){const t=e[e.length-1];if(!ni(t)||i>0||t.isEmpty()||r.has(t))break;e.pop()}if(0===e.length&&t.isCollapsed()){const n=$i(t.anchor),o=$i(t.anchor.getFlipped()),r=t=>Ph(t)?t.origin:t.getNodeAtCaret(),i=r(n)||r(o)||(t.anchor.getNodeAtCaret()?n.origin:o.origin);e.push(i)}return e}(Ji(Ki(this),\"next\"));return mu()||(this._cachedNodes=e),e}setTextNodeRange(t,e,n,o){return this.anchor.set(t.__key,e,\"text\"),this.focus.set(n.__key,o,\"text\"),this}getTextContent(){if(this.isCollapsed())return\"\";const t=this.getNodes(),e=Ki(this).getTextSlices();let n=\"\",o=!0;for(let r=0;r<t.length;r++){const i=t[r];if(ni(i)&&!i.isInline()){o||(n+=\"\\n\");let t=\"\";for(const e of dh(i)){const n=hh(i,e);null!==n&&(t+=n.getTextContent())}\"\"!==t?(n+=t,o=!1):o=!i.isEmpty()}else if(o=!1,Mi(i)){const t=Yi(e,i);n+=t?t.getTextContent():i.getTextContent()}else(ii(i)||Ba(i))&&(n+=i.getTextContent())}return n}applyDOMRange(t){const e=bu(),n=e.getEditorState()._selection,o=Sd(t.startContainer,t.startOffset,t.endContainer,t.endOffset,e,n);if(null===o)return;const[r,i,s]=o;this.anchor.set(r.key,r.offset,r.type,!0),this.focus.set(i.key,i.offset,i.type,!0),s&&(this.dirty=!0),Yo(this)}clone(){const t=this.anchor,e=this.focus;return new Gf(jf(t.key,t.offset,t.type),jf(e.key,e.offset,e.type),this.format,this.style)}toggleFormat(t){this.format=Os(this.format,t,null),this.dirty=!0}setFormat(t){this.format=t,this.dirty=!0}setStyle(t){this.style=t,this.dirty=!0}hasFormat(t){const e=z[t];return 0!==(this.format&e)}insertRawText(t){this.insertNodes(Wd(t))}insertText(t){Vf(this,t,!1)}removeText(){const t=Od()===this,e=this.anchor.key;Li(this,Wi(Ki(this))),this.isCollapsed()&&Ad(this,e),t&&Od()!==this&&Ys(this)}formatText(t,e=null){nd(this,t,e)}insertNodes(t){if(0===t.length)return;this.isCollapsed()||this.removeText();const n=this.anchor.getNode();if(\"element\"===this.anchor.type&&ni(n)&&n.isShadowRoot()&&null!==sh(n)){let o=n.getFirstChild()??n.append(os()).getFirstChild();if(null!==o&&!ni(o)){const t=os();o.insertBefore(t),o=t}if(null!==o){o.selectStart();const n=Od();return Xf(n)||e(369),n.insertNodes(t)}}if(\"element\"===this.anchor.type&&Il(n)){const e=Hd(t),o=e.getLastDescendant();return n.splice(this.anchor.offset,0,e.getChildren()),void(null!==o&&o.selectEnd())}const o=this.isBackward()?this.focus:this.anchor;let r=o.getNode(),i=_a(r,yc);const s=t[t.length-1];if(ni(i)&&\"__language\"in i){if(\"__language\"in t[0])this.insertText(t[0].getTextContent());else{const[,e]=Ud(this);i.splice(e,0,t),s.selectEnd()}return}if(!t.some(t=>(ni(t)||ii(t))&&!t.isInline())){ni(i)||e(211,r.constructor.name,r.getType());const[n,o]=Ud(this,!0);return(ni(n)?n:i).splice(o,0,t),void s.selectEnd()}if(null===i){const e=Hd(t),n=e.getLastDescendant();let o=Pi(this.anchor,\"next\");for(const t of e.getChildren())o=Zi(t,o);return void(null!==n&&n.selectEnd())}if(ni(i)&&(null!==sh(i)||!i.isParentRequired()&&!Il(i.getParentOrThrow()))){const[,e]=Ud(this),n=$d(t);i.splice(e,0,n);const o=n[n.length-1];return void(void 0!==o?o.selectEnd():i.select(e,e))}const l=Hd(t),c=l.getLastDescendant(),a=l.getChildren(),u=function(t){const e=function(t){const e=t.getNode();if(t.offset>0)return\"element\"===t.type&&ni(e)?e.getChildAtIndex(t.offset-1):null;for(let t=e;null!==t&&!yc(t)&&!Il(t);t=t.getParent()){const e=t.getPreviousSibling();if(null!==e)return e}return null}(t);return Ba(e)&&Ba(e.getPreviousSibling())}(o),f=ni(i)&&i.isEmpty()?null:this.insertParagraph();f&&!i.isAttached()&&(r=this.anchor.getNode(),i=_a(r,yc));const d=a[a.length-1];let h=a[0];var g;g=h,u||!ni(g)||!yc(g)||g.isEmpty()||!ni(i)||i.isEmpty()&&!i.canMergeWhenEmpty()||(ni(i)||e(211,r.constructor.name,r.getType()),i.append(...h.getChildren()),h=a[1]),h&&(null===i&&e(212,r.constructor.name,r.getType()),function(t,n){const o=n.getParentOrThrow().getLastChild();let r=n;const i=[n];for(;r!==o;)r.getNextSibling()||e(140),r=r.getNextSibling(),i.push(r);let s=t;for(const t of i)s=s.insertAfter(t)}(i,h));const _=_a(c,yc),p=c.selectEnd();f&&(ni(_)&&(f.canMergeWhenEmpty()||yc(d))?(_.append(...f.getChildren()),f.remove()):f.isEmpty()&&f.remove()),ni(i)&&i.isEmpty()&&i.remove();const y=ni(i)?i.getLastChild():null;Ba(y)&&_!==i&&y.remove();const m=$i(Pi(p.anchor,\"next\"));Fi(p.anchor,m),Fi(p.focus,m)}insertParagraph(){this.isCollapsed()||this.removeText();const t=this.anchor.getNode();if(\"element\"===this.anchor.type&&Il(t)){const e=os();return t.splice(this.anchor.offset,0,[e]),e.select(),e}const[,n]=Ud(this),o=_a(this.anchor.getNode(),yc);if(null!==o&&null!==sh(o))return null;ni(o)||e(213);const r=o.getChildAtIndex(n),i=r?[r,...r.getNextSiblings()]:[],s=o.insertNewAfter(this,!1);return s?(s.append(...i),s.selectStart(),s):null}insertLineBreak(t){const e=za();if(this.insertNodes([e]),t){const t=e.getParentOrThrow(),n=e.getIndexWithinParent();t.select(n,n)}}extract(){const t=this.getNodes();if(this.isCollapsed())return[...t];const e=this.isBackward(),n=Ki(this).getTextSlices(),o=[];for(const e of t){const t=Yi(n,e),r=t?Xi(t,this):e;null!==r&&o.push(r)}if(1===t.length&&1===o.length&&Mi(o[0])){const t=o[0],[n,r]=e?[this.focus,this.anchor]:[this.anchor,this.focus];n.set(t.getKey(),0,\"text\"),r.set(t.getKey(),t.getTextContentSize(),\"text\")}return o}modify(t,e,n){if(qd(this,t,e,n))return;const o=\"move\"===t,r=bu(),i=jl(Ml(r));if(!i)return;const s=r._blockCursorElement,l=r._rootElement,c=this.focus.getNode();null===l||null===s||!ni(c)||c.isInline()||c.canBeEmpty()||Wl(s,r,l);const a=Sl(r,this.focus.key);let u=a;if(\"text\"===this.focus.type&&(u=Mi(c)?kc(c,a,r):null),this.dirty){const t=Sl(r,this.anchor.key);let e=t;if(\"text\"===this.anchor.type){const n=this.anchor.getNode();e=Mi(n)?kc(n,t,r):null}e&&u&&Ld(i,e,this.anchor.offset,u,this.focus.offset)}if(\"character\"===n&&Mi(c)&&c.isUnmergeable()&&(e?0===this.focus.offset:this.focus.offset===c.getTextContentSize())){const t=Rh(c,e?\"previous\":\"next\").getNodeAtCaret();if(Mi(t)){if(!o){const n=t.getTextContentSize();return e?this.focus.set(t.__key,n-1,\"text\"):this.focus.set(t.__key,1,\"text\"),void(this.dirty=!0)}{const n=r.getElementByKey(t.getKey()),o=n?kc(t,n,r):null;if(o){const t=e?o.length:0;Ld(i,o,t,o,t)}}}}if(ld(i,t,e?\"backward\":\"forward\",n,l),i.rangeCount>0){const t=Xl(i,r._rootElement),n=t||i.getRangeAt(0),s=this.anchor.getNode(),l=ci(s)?s:Pl(s);this.applyDOMRange(n),this.dirty=!0,o||(cd(this,e,l),(t?\"backward\"!==i.direction:i.anchorNode===n.startContainer&&i.anchorOffset===n.startOffset)||sd(this))}\"lineboundary\"===n&&qd(this,t,e,n,\"decorators\")}forwardDeletion(t,e,n){if(!n&&(\"element\"===t.type&&ni(e)&&t.offset===e.getChildrenSize()||\"text\"===t.type&&t.offset===e.getTextContentSize())){const t=e.getParent(),n=e.getNextSibling()||(null===t?null:t.getNextSibling());if(ni(n)&&n.isShadowRoot())return!0}return!1}deleteCharacter(t){const e=this.isCollapsed();if(this.isCollapsed()){const e=this.anchor;let n=e.getNode();if(this.forwardDeletion(e,n,t)){const t=ni(n)?n.getNextSibling():null;if(!(ni(n)&&n.isEmpty()&&ni(t)&&t.isShadowRoot()))return}const o=Pi(e,t?\"previous\":\"next\"),r=Qh(o);if(r.getTextSlices().every(t=>null===t||0===t.distance)){if(\"element\"===e.type){const t=o.getNodeAtCaret();if(ni(t)&&Rl(t)){const e=t.getParent();t.remove();const n=qs(e,t);return void(null!==n&&n.selectStart())}}let t={type:\"initial\"};for(const e of r.iterNodeCarets(\"shadowRoot\"))if(Lh(e))if(e.origin.isInline());else{if(e.origin.isShadowRoot()){if(\"merge-block\"===t.type)break;if(ni(r.anchor.origin)&&r.anchor.origin.isEmpty()){const t=$i(e);Li(this,tg(t,t)),r.anchor.origin.remove()}return}\"merge-next-block\"!==t.type&&\"merge-block\"!==t.type||(t={block:t.block,caret:e,type:\"merge-block\"})}else{if(\"merge-block\"===t.type)break;if(Ih(e)){if(ni(e.origin)){if(e.origin.isInline()){if(!e.origin.isParentOf(r.anchor.origin))break}else t={block:e.origin,type:\"merge-next-block\"};continue}if(ii(e.origin)){if(e.origin.isIsolated());else if(\"merge-next-block\"===t.type&&(e.origin.isKeyboardSelectable()||!e.origin.isInline())&&ni(r.anchor.origin)&&r.anchor.origin.isEmpty()){r.anchor.origin.remove();const t=Td();t.add(e.origin.getKey()),Ys(t)}else{const t=e.origin,n=t.getParent();t.remove();const o=qs(n,t);null!==o&&o.selectStart()}return}if(Ba(e.origin))return void e.origin.remove();break}}if(\"merge-block\"===t.type){const{caret:e,block:n}=t;if(dh(n).length>0)return;return e.origin.isEmpty()&&!n.isEmpty()&&e.origin.getParent()===n.getParent()?void e.origin.remove(!0):(Li(this,tg(!e.origin.isEmpty()&&n.isEmpty()?zi(Rh(n,e.direction)):r.anchor,e)),this.removeText())}for(let t=e.getNode();null!==t;){if(null!==sh(t))return;if(ni(t)&&t.isShadowRoot())break;t=t.getParent()}}const i=this.focus;if(ad(this,t,\"character\"),this.isCollapsed()){if(t&&0===e.offset&&function(t,e){for(let n=e;n;n=n.getParent()){if(ni(n)){if(n.collapseAtStart(t))return!0;if(Il(n))break}if(n.getPreviousSibling())break}return!1}(this,e.getNode()))return}else{const o=\"text\"===i.type?i.getNode():null;if(n=\"text\"===e.type?e.getNode():null,null!==o&&o.isSegmented()){const e=i.offset,r=o.getTextContentSize();if(o.is(n)||t&&e!==r||!t&&0!==e)return void hd(o,t,e)}else if(null!==n&&n.isSegmented()){const r=e.offset,i=n.getTextContentSize();if(n.is(o)||t&&0!==r||!t&&r!==i)return void hd(n,t,r)}!function(t,e){const n=t.anchor,o=t.focus,r=n.getNode();if(r===o.getNode()&&\"text\"===n.type&&\"text\"===o.type){const t=n.offset,s=o.offset,l=t<s,c=l?t:s,a=l?s:t,u=a-1;c!==u&&!Qs(i=r.getTextContent().slice(c,a))&&!dd(i)&&(e?o.set(o.key,u,o.type):n.set(n.key,u,n.type))}var i}(this,t)}}e||id(this),this.removeText(),t&&!e&&this.isCollapsed()&&\"element\"===this.anchor.type&&0===this.anchor.offset&&Yf()}deleteLine(t){Zf(this,t,\"lineboundary\")}deleteWord(t){Zf(this,t,\"word\")}isBackward(){const t=this._cachedIsBackward;if(null!==t)return t;const e=this.focus.isBefore(this.anchor);return mu()||(this._cachedIsBackward=e),e}getStartEndPoints(){return[this.anchor,this.focus]}}function Qf(t){return t instanceof qf}function Zf(t,e,n){const o=t.isCollapsed(),{anchor:r,focus:i}=t;let s=!1;if(o){if(\"word\"===n&&t.forwardDeletion(r,r.getNode(),e))return;s=ad(t,e,n),\"lineboundary\"===n&&function(t){for(const e of Ki(t).iterNodeCarets(\"shadowRoot\"))if(Ih(e)&&Ba(e.origin))return void Fi(t.focus,zi(e))}(t)}\"lineboundary\"!==n||t.isCollapsed()||_a(r.getNode(),yc)===_a(i.getNode(),yc)||i.set(r.key,r.offset,r.type),t.isCollapsed()?s||t.deleteCharacter(e):(o||id(t),t.removeText())}function td(t,e){if(Qf(t)){for(const n of t.getNodes())vi(n)&&n.setFormat(e(n.getFormat()));return}const n=t.isCollapsed()?[]:t.getNodes(),o=n.length?Ki(t).getTextSlices():[];let r,i,s,l=!1,c=0;for(const a of n)if(Mi(a)){r&&i&&(r.set(i.__key,0,\"text\"),r=void 0);const n=Yi(o,a);if(!l&&n&&0===n.distance){const e=t.isBackward()?t.focus:t.anchor;\"text\"===e.type&&e.key===a.__key&&(r=e)}if(l=!0,n&&0===n.distance)continue;const u=e(a.getFormat()),f=r?a.getTextContentSize():0,d=n&&!Ns(a)?Xi(n,t):a;null!==d&&(d.setFormat(u),void 0===s&&(s=u,i=d,r&&d.getTextContentSize()!==f&&(r.set(d.__key,0,\"text\"),r=void 0)),c=u)}else ni(a)?a.setTextFormat(e(a.getTextFormat())):vi(a)&&a.setFormat(e(a.getFormat()));l?void 0!==s&&(t.format=s|c):(t.setFormat(e(t.format)),Ls(null))}function ed(t,e){const n=[];for(const[t,o]of Object.entries(e))\"boolean\"==typeof o&&n.push([t,o]);0!==n.length&&td(t,t=>{for(const[e,o]of n)t=Os(t,e,o?z[e]:0);return t})}function nd(t,e,n=null){const o=null===n&&Xf(t)?Os(t.format,e,null):n;td(t,t=>Os(t,e,o))}function od(t){const e=t.offset;if(\"text\"===t.type)return e;const n=t.getNode();return e===n.getChildrenSize()?n.getTextContent().length:0}function rd(t){const e=t.getStartEndPoints();if(null===e)return[0,0];const[n,o]=e;return\"element\"===n.type&&\"element\"===o.type&&n.key===o.key&&n.offset===o.offset?[0,0]:[od(n),od(o)]}function id(t){const e=Hs();!e.isEmpty()&&ts(e,t)&&(t.anchor.set(e.getKey(),0,\"element\"),t.focus.set(e.getKey(),e.getChildrenSize(),\"element\"))}function sd(t){const e=t.focus,n=t.anchor,o=n.key,r=n.offset,i=n.type;n.set(e.key,e.offset,e.type,!0),e.set(o,r,i,!0)}function ld(t,e,n,o,r){const i=\"character\"===o?Ql(t,r):null,s=i&&i.focusNode,l=i?i.focusOffset:0;if(t.modify(e,n,o),null===i||!function(t,e,n){return null!==t&&3===t.nodeType&&(\"backward\"===n?e>0:\"forward\"===n&&e<t.length)}(s,l,n))return;const c=Ql(t,r);c.focusNode===s&&c.focusOffset===l&&t.modify(e,n,o)}function cd(t,e,n){const o=t.getNodes(),r=o.filter(t=>Al(t,n));if(0===r.length||r.length===o.length)return!1;const i=e?r[0]:r[r.length-1],s=ni(i)?i:i.getParentOrThrow();return e?s.selectStart():s.selectEnd(),!0}function ad(t,e,n){if(qd(t,\"extend\",e,n))return!1;const o=bu(),r=jl(Ml(o));if(!r||\"function\"!=typeof r.modify)return!1;const i=o._blockCursorElement,s=o._rootElement,l=t.anchor,c=t.focus.getNode();null===s||null===i||!ni(c)||c.isInline()||c.canBeEmpty()||Wl(i,o,s);const a=t=>{const e=t.getNode(),n=o.getElementByKey(t.key);return null!==n&&\"text\"===t.type&&Mi(e)?kc(e,n,o):n},u=l.getNode(),f=a(l);if(null===f)return!1;const d=l.offset,h=t.isCollapsed(),g=t.focus,_=h?f:a(g);if(null===_)return!1;const p=g.offset;if(Ld(r,_,p,_,p),ld(r,\"move\",e?\"backward\":\"forward\",n,s),0===r.rangeCount)return!1;const y=Xl(r,s)||r.getRangeAt(0);let m=y.startContainer,x=y.startOffset;if(\"lineboundary\"===n&&ws(m)&&Cs(m)===o){const t=Gs(m);if(ii(t)&&t.isInline()&&!t.isIsolated()){const n=o.getElementByKey(t.getKey());null!==n&&n.contains(m)&&(m=n,x=e?0:n.childNodes.length)}}if(h&&\"character\"===n&&\"text\"===l.type&&Mi(u)&&u.isUnmergeable()&&d===(e?0:u.getTextContentSize())){const n=Rh(u,e?\"previous\":\"next\").getNodeAtCaret();if(Mi(n)){const o=e?n.getTextContentSize()-1:1;return t.focus.set(n.__key,o,\"text\"),t.dirty=!0,!1}}if(h&&\"character\"===n&&\"text\"===l.type){const n=e?0:u.getTextContentSize(),o=m===f?x:d!==n?n:-1;if(o>=0)return o!==d&&(t.focus.set(l.key,o,\"text\"),t.dirty=!0),!1}const v=o._slotsUsed&&$s(m),S=v?ah(u):null,C=v?ah(v):null;if(v&&!md(C,S)&&ud(t.focus,u,S,C,\"deletion\",()=>!e))return!0;const[b,k,T,N]=e?[m,x,f,d]:[f,d,m,x],w=ci(u)?u:Pl(u);return t.applyDOMRange({collapsed:!1,endContainer:T,endOffset:N,startContainer:b,startOffset:k}),t.dirty=!0,!cd(t,e,w)&&e&&sd(t),!1}function ud(t,e,n,o,r,i){const s=o&&function(t,e){for(let n=lh(t);null!==n;){const t=ah(n);if(md(t,e))return null!==t||n.isAttached()?n:null;n=t&&lh(t)}return null}(o,n);if(null===s&&null===n)return!1;const l=i(),c=s&&s.getParent();let a,u;if(null===s||null===c||null!==e&&(s.is(e)||s.isParentOf(e))){const e=s||n;if(!ni(e))return null!==e&&function(t,e,n){ni(e)?t.set(e.getKey(),n?e.getChildrenSize():0,\"element\"):t.set(e.getKey(),n?e.getTextContentSize():0,\"text\")}(t,e,l),!0;a=e,u=l?e.getChildrenSize():0}else a=c,u=s.getIndexWithinParent()+(l===(\"selection\"===r)?1:0);return\"deletion\"===r?function(t,e,n,o){for(;;){const r=e.getChildAtIndex(o?n:n-1);if(Mi(r))return void t.set(r.getKey(),o?0:r.getTextContentSize(),\"text\");if(!ni(r)||Il(r))break;e=r,n=o?0:r.getChildrenSize()}t.set(e.getKey(),n,\"element\")}(t,a,u,!l):t.set(a.getKey(),u,\"element\"),!0}function fd(){try{const t=new RegExp(\"\\\\p{Emoji}\",\"u\"),e=t.test.bind(t);if(e(\"\\u2764\\ufe0f\")&&e(\"#\\ufe0f\\u20e3\")&&e(\"\\u{1f44d}\"))return e}catch(t){}return()=>!1}const dd=/* @__PURE__ */fd();function hd(t,e,n){const o=t,r=o.getTextContent().split(/(?=\\s)/g),i=r.length;let s=0,l=0;for(let t=0;t<i;t++){const o=t===i-1;if(l=s,s+=r[t].length,e&&s===n||s>n||o){r.splice(t,1),o&&(l=void 0);break}}const c=r.join(\"\").trim();\"\"===c?o.remove():(o.setTextContent(c),o.select(l,l))}function gd(t,n,o,r){let i,s=n,l=!1;if(uc(t)){let c=!1;const a=t.childNodes,u=a.length,f=r._blockCursorElement;s===u&&u>0&&(c=!0,s=u-1),void 0!==js(t,r)||Lc(t,r)||(l=!0);let d=a[s],h=!1;if(d===f)d=a[s+1],h=!0;else if(null!==f){const e=f.parentNode;t===e&&n>Array.prototype.indexOf.call(e.children,f)&&s--}if(i=Gs(d),Mi(i))s=jh(i,c?\"next\":\"previous\");else{let a=Gs(t);if(null===a)return null;if(ni(a)){const l=r.getElementByKey(a.getKey());null===l&&e(214);const u=vc(a,l,r);[a,s]=u.resolveChildIndex(a,l,t,n),ni(a)||e(215),c&&s>=a.getChildrenSize()&&(s=Math.max(0,a.getChildrenSize()-1));let f=a.getChildAtIndex(s);if(ni(f)&&function(t,e,n){const o=t.getParent();return null===n||null===o||!o.canBeEmpty()||o!==n.getNode()}(f,0,o)){const t=c?f.getLastDescendant():f.getFirstDescendant();null===t?a=f:(f=t,a=ni(f)?f:f.getParentOrThrow()),s=0}Mi(f)?(i=f,a=null,s=jh(f,c?\"next\":\"previous\")):f!==a&&c&&!h&&(ni(a)||e(216),s=Math.min(a.getChildrenSize(),s+1))}else{const e=lh(a),o=null!==e?e:a,i=o.getIndexWithinParent(),l=r.getElementByKey(a.getKey());let c=\"after\";if(null!==l&&Gs(t)===a){const e=vc(a,l,r);e.element!==l?c=e.resolveLeafPosition(l,t,n):0===n&&ii(a)&&(c=\"before\")}s=\"before\"===c?i:i+1,a=o.getParentOrThrow()}if(ni(a))return[jf(a.__key,s,\"element\"),l]}}else i=Gs(t);return Mi(i)?[jf(i.__key,jh(i,s,\"clamp\"),\"text\"),l]:null}function _d(t,e,n){const o=t.getNode();if(zs(o))return;const r=0===t.offset;if(!r&&t.offset!==o.getTextContent().length)return;const i=r?\"previous\":\"next\",s=Rh(o,i).getNodeAtCaret();if(r===e||!ni(s)||!s.isInline()||r&&n){if(r&&!e)Mi(s)&&!o.isUnmergeable()&&t.set(s.__key,s.getTextContent().length,\"text\");else if(null===s&&(n||!r&&e)){const e=o.getParent();if(ni(e)&&e.isInline()&&(r||!e.canInsertTextAfter()&&e.getTextContentSize()>1)){const n=Rh(e,i).getNodeAtCaret();Mi(n)&&t.set(n.__key,r?n.getTextContent().length:0,\"text\")}}}else t.set(s.__key,r?s.getChildrenSize():0,\"element\")}function pd(t){const e=Bs(t.key);return null===e?null:ah(e)}function yd(t,e,n){const o=pd(t),r=pd(e);return!md(o,r)&&ud(e,Bs(t.key),o,r,\"selection\",n)}function md(t,e){return null===t?null===e:t.is(e)}function xd(t){const e=yd(t.anchor,t.focus,()=>1!==function(t,e){const n=function(t,e){const n=new Map;for(let e=null,o=t;null!==o;e=o,o=og(o))n.set(o.getKey(),e);for(let t=null,o=e;null!==o;t=o,o=og(o)){const e=n.get(o.getKey());if(void 0===e)continue;const r=o.getLatest();return null===e?null===t?{commonAncestor:r,type:\"same\"}:{b:t,commonAncestor:r,type:\"ancestor\"}:null===t?{a:e,commonAncestor:r,type:\"descendant\"}:{a:e,b:t,commonAncestor:r,type:\"branch\"}}return null}(t.origin,e.origin);if(null===n)return null;switch(n.type){case\"same\":return rg(t,e);case\"ancestor\":return\"child\"===t.type&&null===sh(n.b)?-1:1;case\"descendant\":return\"child\"===e.type&&null===sh(n.a)?1:-1;case\"branch\":{const t=sh(n.a)&&n.a.getKey(),e=sh(n.b)&&n.b.getKey();if(t&&e)for(const o of fh(n.commonAncestor).values())if(o===t||o===e)return o===t?-1:1;return t?-1:e?1:n.a.isBefore(n.b)?-1:1}}}(Pi(t.anchor,\"next\"),Pi(t.focus,\"next\")));return e&&(t.dirty=!0),e}function vd(t,e){let n=e;for(;null!==n&&n.parentNode!==t;)n=n.parentNode;let o=0;for(let t=n&&n.previousSibling;t;t=t.previousSibling)o++;return o}function Sd(t,e,n,o,r,i){if(null===t||null===n||!vs(r,t,n))return null;const s=gd(t,e,Xf(i)?i.anchor:null,r);if(null===s)return null;const l=gd(n,o,Xf(i)?i.focus:null,r);if(null===l)return null;const[c,a]=s,[u,f]=l;if(\"element\"===c.type&&\"element\"===u.type){const e=Gs(t),o=Gs(n);if(ii(e)&&ii(o))return null}const d=r._slotsUsed&&yd(c,u,()=>function(t,e,n,o){if(t===n)return o>=e;const r=t.compareDocumentPosition(n);return r&Node.DOCUMENT_POSITION_CONTAINED_BY?vd(t,n)>=e:r&Node.DOCUMENT_POSITION_CONTAINS?o>vd(n,t):0!==(r&Node.DOCUMENT_POSITION_FOLLOWING)}(t,e,n,o));return function(t,e){if(\"text\"===t.type&&\"text\"===e.type){const n=t.isBefore(e),o=t.is(e);_d(t,n,o),_d(e,!n,o),o&&e.set(t.key,t.offset,t.type)}}(c,u),[c,u,a||f||d]}function Cd(t){return ni(t)&&!t.isInline()}function bd(t,e,n,o,r,i){const s=Su(),l=new Gf(jf(t,e,r),jf(n,o,i),0,\"\");return l.dirty=!0,s._selection=l,l}function kd(){const t=jf(\"root\",0,\"element\"),e=jf(\"root\",0,\"element\");return new Gf(t,e,0,\"\")}function Td(){return new qf(new Set)}function Nd(t,e){return Ed(null,t,e,null)}const wd=/* @__PURE__ */new Set([\" \",\"ArrowDown\",\"ArrowLeft\",\"ArrowRight\",\"ArrowUp\",\"Backspace\",\"Delete\",\"End\",\"Enter\",\"Home\",\"Tab\"]);function Ed(t,e,n,o){const r=n._window;if(null===r)return null;const i=o||r.event,s=i?i.type:void 0,l=\"selectionchange\"===s,c=\"keydown\"===s&&i,a=c&&ic(c),u=c&&(c.ctrlKey||c.metaKey||wd.has(c.key))&&fc(a)&&Cs(a)===n,f=!xe&&(l||u||\"beforeinput\"===s||\"compositionstart\"===s||\"compositionend\"===s||\"click\"===s&&i&&3===i.detail||\"drop\"===s||void 0===s);let d,h,g,_;if(Xf(t)&&!f)return t.clone();{if(null===e)return null;const o=Ql(e,n._rootElement);if(d=o.anchorNode,h=o.focusNode,g=o.anchorOffset,_=o.focusOffset,(l||u||void 0===s)&&Xf(t)&&!vs(n,d,h))return t.clone()}const p=Sd(d,g,h,_,n,t);if(null===p)return null;const[y,m,x]=p,v=Xf(t)?t:null,S=new Gf(y,m,v?v.format:0,v?v.style:\"\");return v&&Ad(S,v.anchor.key),S.dirty=x,S}function Ad(t,e){const n=t.anchor;if(n.key===e)return;const o=n.getNode();let r=0,i=\"\";Mi(o)?(r=o.getFormat(),i=o.getStyle()):ni(o)&&(r=o.getTextFormat(),i=o.getTextStyle()),t.format===r&&t.style===i||(t.format=r,t.style=i,t.dirty=!0)}function Od(){return Su()._selection}function Md(){return bu()._editorState._selection}function Dd(t,e){const n=e.__key;return t.anchor.key===n||t.focus.key===n}function Pd(t,e,n,o=1){if(Dd(t,e))for(const r of[t.anchor,t.focus]){r.key===e.__key&&(n<=r.offset&&o>0||n<r.offset&&o<0)&&r.set(e.__key,Math.max(0,r.offset+o),\"element\");const t=r.getNode();if(ni(t)){const e=t.getChildrenSize(),n=r.offset>=e,o=t.getChildAtIndex(n?e-1:r.offset);Mi(o)&&r.set(o.__key,n?o.getTextContentSize():0,\"text\")}}}function Fd(t,e,n,o,r){const i=o||r;if(Mi(i)||ni(i)){const e=Mi(i);t.set(i.__key,null===o?0:e?i.getTextContentSize():i.getChildrenSize(),e?\"text\":\"element\")}else{const o=e.getIndexWithinParent();t.set(n.__key,-1===o?n.getChildrenSize():o,\"element\")}}function Id(t,e,n,o,r){\"text\"===t.type?t.set(n,t.offset+(e?0:r),\"text\"):t.offset>o.getIndexWithinParent()&&t.set(t.key,t.offset-1,\"element\")}function Ld(t,e,n,o,r){try{t.setBaseAndExtent(e,n,o,r)}catch(t){}}function Kd(t,e,n){const o=Sl(t,e.getKey());if(ni(e)){const r=vc(e,o,t);return[r.element,n+r.getFirstChildOffset()]}return[o,n]}function zd(t,e,n,o,r,i){const s=i.getRootNode(),l=Es(s)||Ul(s)?rc(s):null;if(r.has(Ea)&&l!==i||null!==l&&ys(l,l))return;const c=Ql(o,i);let a;if(!Xf(e))return void(null!==t&&vs(n,c.anchorNode,c.focusNode)&&o.removeAllRanges());const f=e.anchor,d=e.focus,h=f.getNode(),g=d.getNode(),[_,p]=Kd(n,h,f.offset),[y,m]=Kd(n,g,d.offset),x=e.format,v=e.style,S=e.isCollapsed();let C=_,b=y,k=!1;if(\"text\"===f.type?(C=Mi(h)?kc(h,_,n):null,k=h.getFormat()!==x||h.getStyle()!==v):Xf(t)&&\"text\"===t.anchor.type&&(k=!0),\"text\"===d.type&&(b=Mi(g)?kc(g,y,n):null),null===C||null===b)return;const T=S&&Mi(g)&&zs(g)&&ws(b)&&b.nodeValue===O?O.length:m;if(S&&(null===t||k||Xf(t)&&(t.format!==x||t.style!==v))&&function(t,e,n,o,r,i){t._inputState.collapsedSelectionFormat={format:e,key:r,offset:o,style:n,timeStamp:i}}(n,x,v,f.offset,f.key,performance.now()),(\"Range\"!==o.type||!S)&&c.anchorOffset===p&&c.focusOffset===T&&c.anchorNode===C&&c.focusNode===b){if(null===l||!i.contains(l)){const t=null!==l?Cs(l):null;null!==t&&t!==n||r.has(Da)||i.focus({preventScroll:!0})}if(\"element\"!==f.type)return}if(Ld(o,C,p,b,T),u&&e.isCollapsed()&&null!==i&&!r.has(Da)){const t=oc(i);if(null===t||!i.contains(t)){const t=rc(i.ownerDocument),e=null!==t?Cs(t):null;null!==e&&e!==n||i.focus({preventScroll:!0})}}if(!r.has(Oa)&&e.isCollapsed()&&null!==i&&i===oc(i)){const t=Xf(e)&&\"element\"===e.anchor.type?function(t,e,n){const o=e.childNodes[n];if(!uc(o))return o||null;const r=js(o,t),i=void 0!==r?Bs(r):null;return null===i||ni(i)?o:vc(i,o,t).element}(n,C,p):(void 0===a&&(a=Gl(o,i)),a);if(null!==t){let e;if(ws(t)){const n=t.ownerDocument.createRange();n.selectNode(t),e=n.getBoundingClientRect()}else e=uc(t)?t.getBoundingClientRect():function(t){const e=t.getBoundingClientRect(),{startContainer:n,startOffset:o}=t;if(!t.collapsed||0!==e.width||0!==e.height||!ws(n)||0===n.length)return e;const r=t.cloneRange();return o>0?r.setStart(n,o-1):r.setEnd(n,1),r.getBoundingClientRect()}(t);!function(t,e,n,o=null){const r=bl(n),i=Ol(r);if(null===r||null===i)return;const s=n.getBoundingClientRect();if(e.bottom<s.top)return;if(null!==o&&e.height>0){let{left:t,right:r}=e,s=uc(o)?o:Cl(o);for(;null!==s&&n.contains(s);){const e=Tl(i,s,t,r);t-=e,r-=e,s=s===n?null:Cl(s)}}let{top:l,bottom:c}=e,a=0,u=0,f=n;for(;null!==f;){const e=f===r.body;if(e){const e=i.visualViewport;if(e){const t=e.offsetTop;a=t,u=t+e.height}else a=0,u=Ml(t).innerHeight;const n=i.getComputedStyle(r.documentElement),o=parseFloat(n.scrollPaddingTop),s=parseFloat(n.scrollPaddingBottom);isFinite(o)&&(a+=o),isFinite(s)&&(u-=s)}else{const t=f===n?s:f.getBoundingClientRect();a=t.top,u=t.bottom}let o=0;if(l<a?o=-(a-l):c>u&&(o=c-u),0!==o)if(e)i.scrollBy(0,o);else{const t=f.scrollTop;f.scrollTop+=o;const e=f.scrollTop-t;l-=e,c-=e}if(e)break;f=Cl(f)}}(n,e,i,C)}}!function(t,e,n,o,r){const i=t._inputState;i.isSelectionChangeFromDOMUpdate=!0,i.selectionChangeFromDOMUpdatePoints=void 0!==e&&void 0!==n&&void 0!==o&&void 0!==r?{anchorNode:e,anchorOffset:n,focusNode:o,focusOffset:r}:null}(n,C,p,b,T)}function Bd(t){let e=Od()||Md();null===e&&(e=Hs().selectEnd()),e.insertNodes(t)}function Rd(t,e){for(const n of t.split(/(\\r?\\n|\\t)/))\"\\n\"===n||\"\\r\\n\"===n?e.linebreak():\"\\t\"===n?e.tab():\"\"!==n&&e.text(n)}function Wd(t){const e=[];return Rd(t,{linebreak:()=>e.push(za()),tab:()=>e.push(ls()),text:t=>e.push(Oi(t))}),e}function jd(){const t=Od();return null===t?\"\":t.getTextContent()}function $d(t){const e=[];for(const n of t)Ba(n)||(!ni(n)&&!ii(n)||n.isInline()?e.push(n):ni(n)&&e.push(...$d(n.getChildren())));return e}function Ud(t,n=!1){let o=t;t.isCollapsed()||o.removeText();const r=Od();Xf(r)&&(o=r),Xf(o)||e(161);const i=o.anchor;let s=i.getNode(),l=i.offset;for(;!yc(s)&&null===sh(s);){const t=s;if([s,l]=Jd(s,l,n),t.is(s))break}return[s,l]}function Jd(t,e,n=!1){const o=t.getParent();if(!o){const t=os();return Hs().append(t),t.select(),[Hs(),0]}if(Mi(t)){const n=t.splitText(e);if(0===n.length)return[o,t.getIndexWithinParent()];const r=0===e?0:1;return[o,n[0].getIndexWithinParent()+r]}if(!ni(t)||0===e)return[o,t.getIndexWithinParent()];const r=t.getChildAtIndex(e);if(r){const o=new Gf(jf(t.__key,e,\"element\"),jf(t.__key,e,\"element\"),0,\"\"),i=t.insertNewAfter(o);if(i)i.append(r,...r.getNextSiblings());else if(n)return[t,e]}return[o,t.getIndexWithinParent()+1]}function Vd(t){return Ba(t)||Dl(t)||Mi(t)||t.isParentRequired()}function Hd(t){const e=os();let n=null;for(let o=0;o<t.length;o++){const r=t[o];if(Vd(r)){if(null===n){n=r.createParentElementNode(),e.append(n);const i=t[o+1];if(Ba(r)&&(void 0===i||!Vd(i)))continue}n.append(r)}else e.append(r),n=null}return e}function qd(t,e,n,o,r=\"decorators-and-blocks\"){if(\"move\"===e&&\"character\"===o&&!t.isCollapsed()){const[e,o]=n===t.isBackward()?[t.focus,t.anchor]:[t.anchor,t.focus];return o.set(e.key,e.offset,e.type),!0}const i=Pi(t.focus,n?\"previous\":\"next\"),s=\"lineboundary\"===o,l=\"move\"===e;let c=i,a=\"decorators-and-blocks\"===r,u=!1;if(!Ui(c)){for(const t of c){a=!1;const{origin:e}=t;if(ii(e)){if(e.isIsolated()){u=!0;break}if(c=t,s&&e.isInline())continue}break}if(u)return!0;if(a)for(const t of Qh(i).iterNodeCarets(\"extend\"===e?\"shadowRoot\":\"root\")){if(Lh(t))t.origin.isInline()||(c=t);else{if(ni(t.origin))continue;ii(t.origin)&&!t.origin.isInline()&&(c=t)}break}}if(c===i)return!1;if(l&&!s&&ii(c.origin)&&c.origin.isKeyboardSelectable()){const t=Td();return t.add(c.origin.getKey()),Ys(t),!0}return c=$i(c),l&&Fi(t.anchor,c),Fi(t.focus,c),a||!s}function Yd(t,e,n){const o=null===e?null:e.__key,r=null===n?null:n.__key;null===e?t.__first=r:e.__next=r,null===n?t.__last=o:n.__prev=o}function Xd(t){const e=bu();if(!e._recordNodeMoves)return;const n=e._editorState._nodeMap;if(n.has(t.__key)){const e=Su(),o=e._movedNodes||=new WeakMap;let r=o.get(n);void 0===r&&(r=new Set,o.set(n,r)),r.add(t.__key)}}function Gd(t,e,n,o){const r=e.__key;null===n?t.__first=r:n.__next=r,null===o?t.__last=r:o.__prev=r,e.__prev=null===n?null:n.__key,e.__next=null===o?null:o.__key,e.__parent=t.__key}function Qd(t){null!==sh(t)&&e(380,t.__key,String(sh(t)));const n=t.getParent();if(null!==n){const e=n.getWritable();Xd(t);const o=t.getPreviousSibling(),r=t.getNextSibling();Yd(e,o&&o.getWritable(),r&&r.getWritable()),t.__prev=null,t.__next=null,t.__parent=null,e.__size--}}function Zd(t,e){const n=e&&t.getParent(),o=e&&n&&Dd(e,n)?t.getIndexWithinParent():-1,r=e&&n&&-1!==o?[e.anchor,e.focus].filter(t=>\"element\"===t.type&&t.key===n.__key&&t.offset===o+1):null;return e&&n&&-1!==o&&e.isBackward(),Qd(t),e&&n&&-1!==o&&Pd(e,n,o,-1),e&&(e._cachedIsBackward=null),r}function th(t,e,n,o){xu();const r=\"next\"===e;zl(t,n);const i=t.getWritable(),s=n.getWritable();t.getParentOrThrow();const l=Od(),c=o&&Xf(l)?l:null,a=Zd(s,c),u=t.getParentOrThrow().getWritable(),f=c&&(r&&null!==a&&a.length>0||Dd(c,u))?t.getIndexWithinParent()+(r?1:0):-1,d=r?t.getNextSibling():t.getPreviousSibling(),h=d&&d.getWritable();if(Gd(u,s,r?i:h,r?h:i),u.__size++,c&&-1!==f&&(Pd(c,u,f),r&&null!==a))for(const t of a)t.set(u.__key,f+1,\"element\");return n}function eh(t,e,n){xu();const{origin:o,direction:r}=t,i=\"next\"===r,s=lh(o);if(null!==s)return i?s.selectNext(e,n):s.selectPrevious(e,n);const l=t.getNodeAtCaret(),c=o.getParentOrThrow();if(null===l)return i?c.select():c.select(0,0);if(ni(l))return i?l.select(0,0):l.select();if(Mi(l))return l.select(e,n);const a=l.getIndexWithinParent()+(i?0:1);return c.select(a,a)}function nh(t,e){const n=[];for(let o=t;null!==o;o=\"next\"===e?o.getNextSibling():o.getPreviousSibling())n.push(o);return n}const oh=new Map;function rh(t){return ni(t)||ii(t)}function ih(t){return ni(t)||ii(t)}function sh(t){const e=t.getLatest();return ih(e)?e.__slotHost:null}function lh(t){const n=sh(t);if(null===n)return null;const o=Bs(n);return ni(o)||ii(o)||e(370),o}function ch(t){const e=lh(t);if(null===e)return null;const n=t.getLatest().__key;for(const[t,o]of fh(e))if(o===n)return t;return null}function ah(t){let e=t.getLatest();for(;null!==e;){if(null!==sh(e))return e;e=e.getParent()}return null}function uh(t){if(null===t)return null;const e=Xf(t)?t.anchor.getNode():t.getNodes()[0]??null;return null===e?null:ah(e)}function fh(t){const e=t.getLatest();return rh(e)&&null!==e.__slots?e.__slots:oh}function dh(t){return Array.from(fh(t).keys())}function hh(t,e){const n=fh(t).get(e);return void 0===n?null:Bs(n)}const gh=[\"__proto__\",\"constructor\",\"prototype\"],_h=Symbol(\"slotMapOwner\");function ph(t){let e=t.__slots;return null!==e&&e[_h]===t||(e=new Map(e),e[_h]=t,t.__slots=e),e}const yh=new WeakMap,mh=[];function xh(t){for(const{ownNodeConfig:e}of da(t)){const t=e&&e.slots;if(t)return t}return mh}function vh(t){let e=\"\";for(const n of fh(t).values()){const t=Bs(n);null!==t&&(e+=t.getTextContent())}return e}function Sh(t,e,n){const o=n.get(t),r=n.get(e);return void 0!==o?void 0!==r?o-r:-1:void 0!==r?1:t<e?-1:t>e?1:0}function Ch(t,n,o){\"__proto__\"!==n&&\"constructor\"!==n&&\"prototype\"!==n||e(373,n);const r=t.getLatest();if(null!==r.__slots&&r.__slots.get(n)===o.getLatest().__key)return r;(!ni(o)&&!ii(o)||o.isInline())&&e(374,o.__key);const i=t.getWritable(),s=ph(i),l=s.get(n);void 0!==l&&kh(l);const c=o.getWritable(),a=lh(c);if(null!==a){const t=ch(c);null!==t&&ph(a.getWritable()).delete(t),c.__slotHost=null}return Qd(c),c.__slotHost=i.__key,s.set(n,c.__key),function(t){const n=t.__slots;if(null===n||n.size<2)return;const o=function(t){let n=yh.get(t);if(void 0===n){const o=xh(t),r=new Map;for(const n of o)gh.includes(n)&&e(371,t.name,n),r.has(n)&&e(372,t.name,n),r.set(n,r.size);n=r,yh.set(t,n)}return n}(t.constructor);let r=null,i=!0;for(const t of n.keys()){if(null!==r&&Sh(r,t,o)>0){i=!1;break}r=t}if(i)return;const s=Array.from(n).sort(([t],[e])=>Sh(t,e,o));n.clear();for(const[t,e]of s)n.set(t,e)}(i),bu()._slotsUsed=!0,Su()._slotsUsed=!0,i}function bh(t,e){const n=t.getWritable();if(null===n.__slots)return n;const o=n.__slots.get(e);return void 0!==o&&(kh(o),ph(n).delete(e)),n}function kh(t){const n=Bs(t);if(null===n)return;const o=n.getWritable();ih(o)||e(377,t),o.__slotHost=null,o.remove()}const Th={next:\"previous\",previous:\"next\"};class Nh{origin;constructor(t){this.origin=t}[Symbol.iterator](){return eg({hasNext:Ih,initial:this.getAdjacentCaret(),map:t=>t,step:t=>t.getAdjacentCaret()})}getAdjacentCaret(){return Rh(this.getNodeAtCaret(),this.direction)}getSiblingCaret(){return Rh(this.origin,this.direction)}remove(){const t=this.getNodeAtCaret();return t&&t.remove(),this}replaceOrInsert(t,e){const n=this.getNodeAtCaret();return t.is(this.origin)||t.is(n)||(null===n?this.insert(t):n.replace(t,e)),this}splice(t,n,o=\"next\"){const r=o===this.direction?n:Array.from(n).reverse();let i=this;const s=this.getParentAtCaret(),l=new Map;for(let e=i.getAdjacentCaret();null!==e&&l.size<t;e=e.getAdjacentCaret()){const t=e.origin.getWritable();l.set(t.getKey(),t)}for(const t of r){if(l.size>0){const n=i.getNodeAtCaret();if(n)if(l.delete(n.getKey()),l.delete(t.getKey()),n.is(t)||i.origin.is(t));else{const e=t.getParent();e&&e.is(s)&&t.remove(),n.replace(t)}else null===n&&e(263,Array.from(l).join(\" \"))}else i.insert(t);i=Rh(t,this.direction)}for(const t of l.values())t.remove();return this}}class wh extends Nh{type=\"child\";getLatest(){const t=this.origin.getLatest();return t===this.origin?this:Uh(t,this.direction)}getParentCaret(t=\"root\"){return Rh(Oh(this.getParentAtCaret(),t),this.direction)}getFlipped(){const t=Ah(this.direction);return Rh(this.getNodeAtCaret(),t)||Uh(this.origin,t)}getParentAtCaret(){return this.origin}getChildCaret(){return this}isSameNodeCaret(t){return t instanceof wh&&this.direction===t.direction&&this.origin.is(t.origin)}isSamePointCaret(t){return this.isSameNodeCaret(t)}}const Eh={root:ci,shadowRoot:Il};function Ah(t){return Th[t]}function Oh(t,e=\"root\"){return null===t||Eh[e](t)?null:null===sh(t)?t:null}class Mh extends Nh{type=\"sibling\";getLatest(){const t=this.origin.getLatest();return t===this.origin?this:Rh(t,this.direction)}getSiblingCaret(){return this}getParentAtCaret(){return this.origin.getParent()}getChildCaret(){return ni(this.origin)?Uh(this.origin,this.direction):null}getParentCaret(t=\"root\"){return Rh(Oh(this.getParentAtCaret(),t),this.direction)}getFlipped(){const t=Ah(this.direction);return Rh(this.getNodeAtCaret(),t)||Uh(this.origin.getParentOrThrow(),t)}isSamePointCaret(t){return t instanceof Mh&&this.direction===t.direction&&this.origin.is(t.origin)}isSameNodeCaret(t){return(t instanceof Mh||t instanceof Dh)&&this.direction===t.direction&&this.origin.is(t.origin)}}class Dh extends Nh{type=\"text\";offset;constructor(t,e){super(t),this.offset=e}getLatest(){const t=this.origin.getLatest();return t===this.origin?this:Wh(t,this.direction,this.offset)}getParentAtCaret(){return this.origin.getParent()}getChildCaret(){return null}getParentCaret(t=\"root\"){return Rh(Oh(this.getParentAtCaret(),t),this.direction)}getFlipped(){return Wh(this.origin,Ah(this.direction),this.offset)}isSamePointCaret(t){return t instanceof Dh&&this.direction===t.direction&&this.origin.is(t.origin)&&this.offset===t.offset}isSameNodeCaret(t){return(t instanceof Mh||t instanceof Dh)&&this.direction===t.direction&&this.origin.is(t.origin)}getSiblingCaret(){return Rh(this.origin,this.direction)}}function Ph(t){return t instanceof Dh}function Fh(t){return t instanceof Nh}function Ih(t){return t instanceof Mh}function Lh(t){return t instanceof wh}const Kh={next:class extends Dh{direction=\"next\";getNodeAtCaret(){return this.origin.getNextSibling()}insert(t){return this.origin.insertAfter(t),this}},previous:class extends Dh{direction=\"previous\";getNodeAtCaret(){return this.origin.getPreviousSibling()}insert(t){return this.origin.insertBefore(t),this}}},zh={next:class extends Mh{direction=\"next\";getNodeAtCaret(){return this.origin.getNextSibling()}insert(t){return this.origin.insertAfter(t),this}},previous:class extends Mh{direction=\"previous\";getNodeAtCaret(){return this.origin.getPreviousSibling()}insert(t){return this.origin.insertBefore(t),this}}},Bh={next:class extends wh{direction=\"next\";getNodeAtCaret(){return this.origin.getFirstChild()}insert(t){return this.origin.splice(0,0,[t]),this}},previous:class extends wh{direction=\"previous\";getNodeAtCaret(){return this.origin.getLastChild()}insert(t){return this.origin.splice(this.origin.getChildrenSize(),0,[t]),this}}};function Rh(t,e){return t?new zh[e](t):null}function Wh(t,e,n){return t?new Kh[e](t,jh(t,n)):null}function jh(t,e,o=\"error\"){const r=t.getTextContentSize();let i=\"next\"===e?r:\"previous\"===e?0:e;return(i<0||i>r)&&(\"clamp\"!==o&&n(284,String(e),String(r),t.getKey()),i=i<0?0:r),i}function $h(t,e){return new qh(t,e)}function Uh(t,e){return ni(t)?new Bh[e](t):null}function Jh(t){return t&&t.getChildCaret()||t}function Vh(t){return t&&Jh(t.getAdjacentCaret())}class Hh{type=\"node-caret-range\";direction;anchor;focus;constructor(t,e,n){this.anchor=t,this.focus=e,this.direction=n}getLatest(){const t=this.anchor.getLatest(),e=this.focus.getLatest();return t===this.anchor&&e===this.focus?this:new Hh(t,e,this.direction)}isCollapsed(){return this.anchor.isSamePointCaret(this.focus)}getTextSlices(){const t=this.anchor.getLatest(),e=this.focus.getLatest();return Ph(t)&&Ph(e)&&t.isSameNodeCaret(e)?[$h(t,e.offset-t.offset),null]:[Ph(t)?Yh(t,\"anchor\"):null,Ph(e)?Yh(e,\"focus\"):null]}iterNodeCarets(t=\"root\"){const e=Ph(this.anchor)?this.anchor.getSiblingCaret():this.anchor.getLatest(),n=this.focus.getLatest(),o=Ph(n),r=e=>e.isSameNodeCaret(n)?null:Vh(e)||e.getParentCaret(t);return eg({hasNext:t=>null!==t&&!(o&&n.isSameNodeCaret(t)),initial:e.isSameNodeCaret(n)?null:r(e),map:t=>t,step:r})}[Symbol.iterator](){return this.iterNodeCarets(\"root\")}}class qh{type=\"slice\";caret;distance;constructor(t,e){this.caret=t,this.distance=e}getSliceIndices(){const{distance:t,caret:{offset:e}}=this,n=e+t;return n<e?[n,e]:[e,n]}getTextContent(){const[t,e]=this.getSliceIndices();return this.caret.origin.getTextContent().slice(t,e)}getTextContentSize(){return Math.abs(this.distance)}removeTextSlice(){const{caret:{origin:t,direction:e}}=this,[n,o]=this.getSliceIndices(),r=t.getTextContent();return Wh(t.setTextContent(r.slice(0,n)+r.slice(o)),e,n)}}function Yh(t,e){const{direction:n,origin:o}=t;return $h(t,jh(o,\"focus\"===e?Ah(n):n)-t.offset)}function Xh(t){return t instanceof qh}function Gh(t,e){return t.direction===e?t:t.getFlipped()}function Qh(t){return tg(t,Gh(Uh(Hs(),Ah(t.direction)),t.direction))}function Zh(t){return tg(t,t)}function tg(t,n){return t.direction!==n.direction&&e(265),new Hh(t,n,t.direction)}function eg(t){const{initial:e,hasNext:n,step:o,map:r}=t;let i=e;return{[Symbol.iterator](){return this},next(){if(!n(i))return{done:!0,value:void 0};const t={done:!1,value:r(i)};return i=o(i),t}}}function ng(t,n){const o=cg(t.origin,n.origin);switch(null===o&&e(275,t.origin.getKey(),n.origin.getKey()),o.type){case\"same\":return rg(t,n);case\"ancestor\":return\"child\"===t.type?-1:1;case\"descendant\":return\"child\"===n.type?1:-1;case\"branch\":return ig(o)}}function og(t){return t.getParent()||lh(t)}function rg(t,e){const n=\"text\"===t.type,o=\"text\"===e.type;return n&&o?function(t,e){return Math.sign(t-e)}(t.offset,e.offset):t.type===e.type?0:n?-1:o?1:\"child\"===t.type?-1:1}function ig(t){const{a:e,b:n}=t,o=e.__key,r=n.__key;let i=e,s=n;for(;i&&s;i=i.getNextSibling(),s=s.getNextSibling()){if(i.__key===r)return-1;if(s.__key===o)return 1}return null===i?1:-1}function sg(t,e){return e.is(t)}function lg(t){return ni(t)?[t.getLatest(),null]:[t.getParent(),t.getLatest()]}function cg(t,n){if(t.is(n))return{commonAncestor:t,type:\"same\"};const o=new Map;for(let[e,n]=lg(t);e;n=e,e=e.getParent())o.set(e,n);for(let[r,i]=lg(n);r;i=r,r=r.getParent()){const s=o.get(r);if(void 0!==s)return null===s?(sg(t,r)||e(276),{commonAncestor:r,type:\"ancestor\"}):null===i?(sg(n,r)||e(277),{commonAncestor:r,type:\"descendant\"}):((ni(s)||sg(t,s))&&(ni(i)||sg(n,i))&&r.is(s.getParent())&&r.is(i.getParent())||e(278),{a:s,b:i,commonAncestor:r,type:\"branch\"})}return null}function ag(t){return t}function ug(...t){return t}function fg(...t){return t}function dg(t){return t}function hg(t,e){if(!e||t===e)return t;for(const n in e)if(t[n]!==e[n])return{...t,...e};return t}function gg(...t){const e=[];for(const n of t)if(n&&\"string\"==typeof n)for(const[t]of n.matchAll(/\\S+/g))e.push(t);return e}function _g(t,...e){const n=gg(...e);n.length>0&&t.classList.add(...n)}function pg(t,...e){const n=gg(...e);n.length>0&&t.classList.remove(...n)}export{wl as $addUpdateTag,Kl as $applyNodeReplacement,Cu as $assumeActiveEditor,Pi as $caretFromPoint,Ki as $caretRangeFromSelection,Ec as $cloneWithProperties,Ac as $cloneWithPropertiesEphemeral,ng as $comparePointCaretNext,Ll as $copyNode,ga as $create,pa as $createChildrenArray,za as $createLineBreakNode,Td as $createNodeSelection,os as $createParagraphNode,jf as $createPoint,kd as $createRangeSelection,Nd as $createRangeSelectionFromDom,ls as $createTabNode,Oi as $createTextNode,ae as $exportNodeJSON,Qh as $extendCaretToRange,_a as $findMatchingParent,Bu as $flushSyncAfterUpdate,nd as $formatText,ku as $fullReconcile,Wd as $generateNodesFromRawText,Vh as $getAdjacentChildCaret,ml as $getAdjacentNode,Hi as $getAdjacentSiblingOrParentSiblingCaret,Gh as $getCaretInDirection,tg as $getCaretRange,Ji as $getCaretRangeInDirection,rd as $getCharacterOffsets,Uh as $getChildCaret,Vi as $getChildCaretAtIndex,Jh as $getChildCaretOrSelf,Zh as $getCollapsedCaretRange,cg as $getCommonAncestor,ig as $getCommonAncestorResultBranchOrder,vc as $getDOMSlot,kc as $getDOMTextNode,Yl as $getDocument,mc as $getEditor,xc as $getEditorDOMRenderConfig,Kd as $getElementAndOffsetForPoint,$s as $getNearestNodeFromDOMNode,Pl as $getNearestRootOrShadowRoot,Bs as $getNodeByKey,Bl as $getNodeByKeyOrThrow,Rs as $getNodeFromDOMNode,Md as $getPreviousSelection,Hs as $getRoot,Od as $getSelection,uh as $getSelectionSlotFrame,Rh as $getSiblingCaret,hh as $getSlot,ah as $getSlotFrame,lh as $getSlotHost,ch as $getSlotNameWithinHost,dh as $getSlotNames,Tn as $getState,Nn as $getStateChange,jd as $getTextContent,jh as $getTextNodeOffset,Wh as $getTextPointCaret,$h as $getTextPointCaretSlice,Yi as $getTextPointCaretSliceForNode,Dn as $getWritableNodeState,Al as $hasAncestor,Nl as $hasUpdateTag,Zi as $insertNodeToNearestRootAtCaret,Bd as $insertNodes,Cd as $isBlockElementNode,ts as $isBlockFullySelected,Lh as $isChildCaret,ce as $isCompactExport,ii as $isDecoratorNode,Sa as $isEditorState,bc as $isElementDOMSlot,ni as $isElementNode,ms as $isEventFromEmbeddedInput,Ui as $isExtendableTextPointCaret,Dl as $isInlineElementOrDecoratorNode,vi as $isInlineFormattable,Ms as $isLeafNode,Jo as $isLexicalNode,Ba as $isLineBreakNode,Fh as $isNodeCaret,Qf as $isNodeSelection,rs as $isParagraphNode,Xf as $isRangeSelection,ci as $isRootNode,Il as $isRootOrShadowRoot,ys as $isSelectionCapturedInDecoratorInput,Fl as $isShadowRootNode,Ih as $isSiblingCaret,ih as $isSlotChild,rh as $isSlotHost,cs as $isTabNode,Mi as $isTextNode,Ph as $isTextPointCaret,Xh as $isTextPointCaretSlice,Ns as $isTokenOrSegmented,Ts as $isTokenOrTab,Ic as $markSlotEditable,Rl as $needsBlockCursorBeside,pl as $nodesOfType,$i as $normalizeCaret,Yo as $normalizeSelection__EXPERIMENTAL,El as $onUpdate,Ou as $parseSerializedNode,Ps as $removeFromParent,bh as $removeSlot,Wi as $removeTextFromCaretRange,zi as $rewindSiblingCaret,dl as $selectAll,Ls as $setCompositionKey,Mc as $setDirectionFromDOM,Dc as $setFormatFromDOM,Fi as $setPointFromCaret,Ys as $setSelection,Ii as $setSelectionFromCaretRange,Ch as $setSlot,wn as $setState,ed as $setTextFormat,Qi as $splitAtPointCaretNext,sc as $splitNode,Xi as $splitTextPointCaretSlice,zd as $updateDOMSelection,Li as $updateRangeSelectionFromCaretRange,le as $withCompactExport,Ia as ArtificialNode__DO_NOT_USE,Z as BEFORE_INPUT_COMMAND,Ut as BLUR_COMMAND,Wt as CAN_REDO_COMMAND,jt as CAN_UNDO_COMMAND,d as CAN_USE_BEFORE_INPUT,r as CAN_USE_DOM,Bt as CLEAR_EDITOR_COMMAND,Rt as CLEAR_HISTORY_COMMAND,Q as CLICK_COMMAND,Ea as COLLABORATION_TAG,Za as COMMAND_PRIORITY_BEFORE_CRITICAL,Ya as COMMAND_PRIORITY_BEFORE_EDITOR,Qa as COMMAND_PRIORITY_BEFORE_HIGH,Xa as COMMAND_PRIORITY_BEFORE_LOW,Ga as COMMAND_PRIORITY_BEFORE_NORMAL,qa as COMMAND_PRIORITY_CRITICAL,Ua as COMMAND_PRIORITY_EDITOR,Ha as COMMAND_PRIORITY_HIGH,Ja as COMMAND_PRIORITY_LOW,Va as COMMAND_PRIORITY_NORMAL,nt as COMPOSITION_END_COMMAND,Fa as COMPOSITION_END_TAG,et as COMPOSITION_START_COMMAND,Pa as COMPOSITION_START_TAG,st as CONTROLLED_TEXT_INSERTION_COMMAND,qt as CONTROL_OR_ALT,Ht as CONTROL_OR_META,V as CONTROL_OR_OTHER_KEY,Lt as COPY_COMMAND,Kt as CUT_COMMAND,wa as CUT_TAG,nu as DEFAULT_EDITOR_DOM_CONFIG,ot as DELETE_CHARACTER_COMMAND,ut as DELETE_LINE_COMMAND,at as DELETE_WORD_COMMAND,It as DRAGEND_COMMAND,Ft as DRAGOVER_COMMAND,Pt as DRAGSTART_COMMAND,Mt as DROP_COMMAND,ri as DecoratorNode,ei as ElementNode,$t as FOCUS_COMMAND,Dt as FORMAT_ELEMENT_COMMAND,ft as FORMAT_TEXT_COMMAND,ba as HISTORIC_TAG,Ta as HISTORY_MERGE_TAG,ka as HISTORY_PUSH_TAG,At as INDENT_CONTENT_COMMAND,tt as INPUT_COMMAND,rt as INSERT_LINE_BREAK_COMMAND,it as INSERT_PARAGRAPH_COMMAND,Et as INSERT_TAB_COMMAND,id as INTERNAL_$expandSelectionToWholeDocument,yc as INTERNAL_$isBlock,Jr as INTERNAL_$normalizeNodeStructure,qr as INTERNAL_isNodeStructureEnforced,Hr as INTERNAL_registerNodeStructure,A as IS_ALL_FORMATTING,_ as IS_ANDROID,m as IS_ANDROID_CHROME,a as IS_APPLE,x as IS_APPLE_WEBKIT,v as IS_BOLD,y as IS_CHROME,k as IS_CODE,u as IS_FIREFOX,w as IS_HIGHLIGHT,g as IS_IOS,S as IS_ITALIC,p as IS_SAFARI,C as IS_STRIKETHROUGH,T as IS_SUBSCRIPT,N as IS_SUPERSCRIPT,b as IS_UNDERLINE,St as KEY_ARROW_DOWN_COMMAND,mt as KEY_ARROW_LEFT_COMMAND,pt as KEY_ARROW_RIGHT_COMMAND,vt as KEY_ARROW_UP_COMMAND,kt as KEY_BACKSPACE_COMMAND,Nt as KEY_DELETE_COMMAND,_t as KEY_DOWN_COMMAND,Ct as KEY_ENTER_COMMAND,Tt as KEY_ESCAPE_COMMAND,Jt as KEY_MODIFIER_COMMAND,bt as KEY_SPACE_COMMAND,wt as KEY_TAB_COMMAND,La as LineBreakNode,yt as MOVE_TO_END,xt as MOVE_TO_START,Sn as NODE_STATE_DIRECT,J as NODE_STATE_KEY,Cn as NODE_STATE_LATEST,Ot as OUTDENT_CONTENT_COMMAND,lt as PASTE_COMMAND,Na as PASTE_TAG,es as ParagraphNode,gt as REDO_COMMAND,ct as REMOVE_TEXT_COMMAND,li as RootNode,X as SELECTION_CHANGE_COMMAND,G as SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,zt as SELECT_ALL_COMMAND,dt as SET_TEXT_FORMAT_COMMAND,Aa as SKIP_COLLAB_TAG,Ma as SKIP_DOM_SELECTION_TAG,Oa as SKIP_SCROLL_INTO_VIEW_TAG,Da as SKIP_SELECTION_FOCUS_TAG,z as TEXT_TYPE_TO_FORMAT,ss as TabNode,Si as TextNode,ht as UNDO_COMMAND,_g as addClassNamesToElement,Fe as aliasTableOf,fn as aliasedValue,_n as arraySetValue,gn as arrayValue,on as booleanValue,Ro as buildImportMap,Qt as compileKeyboardShortcuts,ug as configExtension,Y as createCommand,ou as createEditor,Zt as createRefCountedRegistry,An as createSharedNodeState,kn as createState,fg as declarePeerDependency,Re as declaredAccepts,ag as defineExtension,rn as enumValue,Hl as findAllLexicalElementsDeep,Ah as flipDirection,oc as getActiveElement,rc as getActiveElementDeep,ic as getComposedEventTarget,Yc as getComposedSchemaFields,Xl as getComposedStaticRange,bl as getDOMOwnerDocument,jl as getDOMSelection,$l as getDOMSelectionFromTarget,Ql as getDOMSelectionPoints,Gl as getDOMSelectionRange,Zl as getDOMSelectionRangeAndPoints,Vl as getDOMShadowRoots,As as getDOMTextNode,ur as getDeclaredNodeStructure,xh as getDeclaredSlots,bs as getEditorPropertyFromDOMNode,Cs as getNearestEditorFromDOMNode,Cl as getParentElement,_s as getRegisteredNode,gs as getRegisteredNodeOrThrow,ha as getRegisteredSubtypeMap,ql as getRootOwnerDocument,ra as getStaticNodeConfig,ai as getStyleObjectFromCSS,ks as getTextDirection,eu as getTransformSetFromKlass,De as getterTableOf,pc as isBlockDomNode,mu as isCurrentlyReadOnlyMode,Lc as isDOMCapturingSelection,Es as isDOMDocumentNode,fc as isDOMNode,Ul as isDOMShadowRoot,ws as isDOMTextNode,Fc as isDOMUnmanaged,dc as isDocumentFragment,al as isExactShortcutMatch,lc as isHTMLAnchorElement,uc as isHTMLElement,ac as isHTMLTableCellElement,cc as isHTMLTableRowElement,gc as isInlineDomNode,Wa as isLastChildInBlockNode,Ss as isLexicalEditor,cl as isModifierMatch,Ra as isOnlyChildInBlockNode,Me as isSchemaField,xs as isSelectionCapturedInDecoratorInput,vs as isSelectionWithinEditor,da as iterStaticNodeConfigChain,sl as keyboardEventMaskForPlatform,eg as makeStepwiseIterator,ju as mergeRegister,Sc as mountSlotContainer,un as nodeSchema,gg as normalizeClassNames,sn as nullable,nn as numberValue,yn as objectValue,ln as optional,hn as rawValue,$u as registerEventListener,Uu as registerEventListeners,pg as removeClassNamesFromElement,Fs as removeFromParent,hs as resetRandomKey,dg as safeCast,di as setDOMStyleFromCSS,fi as setDOMStyleObject,Pc as setDOMUnmanaged,Oc as setNodeIndentFromDOM,Ie as setterDefaultOf,Pe as setterTableOf,hg as shallowMergeConfig,zf as stopLexicalPropagation,tn as stringValue,Os as toggleTextFormatType,Rd as tokenizeRawText,dn as transformValue,an as unionValue,Cc as unmountSlotContainer,xn as withAccessors,mn as withField};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{getRootOwnerDocument as e,$getEditor as t,$isRootNode as n,$isTextNode as o,getDOMTextNode as l,$getElementAndOffsetForPoint as r,$getSelection as i,$isElementNode as s,$isRangeSelection as c,$isTokenOrSegmented as f,$getTextPointCaretSliceForNode as u,$caretRangeFromSelection as g,$cloneWithPropertiesEphemeral as a,$getNodeByKey as d,$getPreviousSelection as p,$createTextNode as h,$splitTextPointCaretSlice as y,getStyleObjectFromCSS as m,$caretFromPoint as S,$isExtendableTextPointCaret as x,$findMatchingParent as C,INTERNAL_$isBlock as N,flipDirection as v,$getSlotHost as T,$isTextPointCaret as w,$isTabNode as P,$extendCaretToRange as k,$isChildCaret as K,$isDecoratorNode as I,$getSlotFrame as b,$isRootOrShadowRoot as E,$hasAncestor as F,$isLeafNode as B,$setSelection as A}from\"lexical\";export{$cloneWithProperties,$selectAll}from\"lexical\";function z(e,...t){throw function(e,...t){const n=new URL(\"https://lexical.dev/docs/error\"),o=new URLSearchParams;o.append(\"code\",e);for(const e of t)o.append(\"v\",e);return n.search=o.toString(),new Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(e,...t)}\n/*@__INLINE__*/function R(e){return()=>{}}function _(e,t,n){const i=e.getElementByKey(t.getKey());if(null===i||o(t))return[l(i),n];const s=i.parentNode;return s&&\"BR\"===i.nodeName?[s,Array.from(s.childNodes).indexOf(i)]:e.read(\"latest\",()=>r(e,t,n))}function O(t,n,o,l,r){const i=e(t.getRootElement()).createRange(),[s,c]=_(t,n,o),[f,u]=_(t,l,r);let g=u;if(null===s||null===f)return null;const a=s.firstChild;s===f&&null!=a&&\"BR\"===a.nodeName&&0===c&&0===g&&(g=1);try{i.setStart(s,c),i.setEnd(f,g)}catch(e){return null}return!i.collapsed||c===g&&n.is(l)||(i.setStart(f,g),i.setEnd(s,c)),i}function L(e,t){const n=e.getRootElement();if(null===n)return[];const o=n.getBoundingClientRect(),l=getComputedStyle(n),r=parseFloat(l.paddingLeft)+parseFloat(l.paddingRight),i=Array.from(t.getClientRects());let s,c=i.length;i.sort((e,t)=>{const n=e.top-t.top;return Math.abs(n)<=3?e.left-t.left:n});for(let e=0;e<c;e++){const t=i[e],n=s&&s.top<=t.top&&s.bottom>=t.bottom&&s.left<=t.left&&s.right>=t.right,l=t.width+r===o.width;n||l?(i.splice(e--,1),c--):s=t}return i}function $(e){let t=\"\";for(const n in e)n&&(t+=`${n}: ${e[n]};`);return t}function M(e){const n=t().getElementByKey(e.getKey());if(null===n)return null;const o=n.ownerDocument.defaultView;return null===o?null:o.getComputedStyle(n)}function D(e){const t=n(e)?e:e.getParent();return t&&M(t)}function U(e){const t=D(e);return null!==t&&\"rtl\"===t.direction}function j(e,t,n=\"self\"){const o=e.getStartEndPoints();if(null!==o&&t.isSelected(e)&&!f(t)){const[l,r]=e.isBackward()?[o[1],o[0]]:o,i=!c(e)||\"element\"!==l.type&&\"element\"!==r.type?void 0:u(g(e).getTextSlices(),t),[s,f]=i?i.getSliceIndices():[t.__key===l.key?l.offset:0,t.__key===r.key?r.offset:void 0],d=t.__text.slice(s,f);d!==t.__text&&(\"clone\"===n&&(t=a(t)),t.__text=d)}return t}function H(e){if(\"text\"===e.type)return e.offset===e.getNode().getTextContentSize();const t=e.getNode();return s(t)||z(177),e.offset===t.getChildrenSize()}function V(e,t,l){let r=t.getNode(),i=l;if(s(r)){const e=r.getDescendantByIndex(t.offset);null!==e&&(r=e)}for(;i>0&&null!==r;){if(s(r)){const e=r.getLastDescendant();null!==e&&(r=e)}let l=r.getPreviousSibling(),f=0;if(null===l){let e=r.getParentOrThrow(),t=e.getPreviousSibling();for(;null===t;){if(e=e.getParent(),null===e){l=null;break}t=e.getPreviousSibling()}null!==e&&(f=e.isInline()?0:2,l=t)}let u=r.getTextContent();\"\"===u&&s(r)&&!r.isInline()&&(u=\"\\n\\n\");const g=u.length;if(!o(r)||i>=g){const e=r.getParent();r.remove(),null==e||0!==e.getChildrenSize()||n(e)||e.remove(),i-=g+f,r=l}else{const n=r.getKey(),l=e.read(\"latest\",()=>{const e=d(n);return o(e)&&e.isSimpleText()?e.getTextContent():null}),s=g-i,f=u.slice(0,s);if(null!==l&&l!==u){const e=p();let t=r;if(r.isSimpleText())r.setTextContent(l);else{const e=h(l);r.replace(e),t=e}if(c(e)&&e.isCollapsed()){const n=e.anchor.offset;t.select(n,n)}}else if(r.isSimpleText()){const e=t.key===n;let o=t.offset;o<i&&(o=g);const l=e?o-i:0,c=e?o:s;if(e&&0===l){const[e]=r.splitText(l,c);e.remove()}else{const[,e]=r.splitText(l,c);e.remove()}}else{const e=h(f);r.replace(e)}i=0}}}const W=/* @__PURE__ */R();function q(e,t){(c(e)?e.isCollapsed():o(e)||s(e))||z(280);const n=m(c(e)?e.style:o(e)?e.getStyle():e.getTextStyle()),l=$(Object.entries(t).reduce((t,[o,l])=>(\"function\"==typeof l?t[o]=l(n[o],e):null===l?delete t[o]:t[o]=l,t),{...n}));c(e)||o(e)?e.setStyle(l):e.setTextStyle(l)}function G(e,t){const n=new Set;if(c(e)&&e.isCollapsed()){q(e,t);const o=e.anchor.getNode();s(o)&&o.isEmpty()&&(n.add(o.getKey()),q(o,t))}Q(e,e=>{q(e,t)});const o=e.getNodes();if(o.length>0)for(const e of o){if(!s(e)||!e.canBeEmpty()||0!==e.getChildrenSize())continue;const o=e.getKey();n.has(o)||(n.add(o),q(e,t))}}function J(e){Q(i(),e)}function Q(e,t){if(!e)return;const n=c(e)?g(e).getTextSlices():[];for(const l of e.getNodes()){if(!o(l)||!l.canHaveFormat())continue;const r=u(n,l);(r?0!==r.distance:0!==l.getTextContentSize())&&t(r&&!f(l)?y(r,c(e)?e:null):l)}c(e)&&\"text\"===e.anchor.type&&\"text\"===e.focus.type&&e.anchor.key===e.focus.key&&X(e)}function X(e){if(e.isBackward()){const{anchor:t,focus:n}=e,{key:o,offset:l,type:r}=t;t.set(n.key,n.offset,n.type),n.set(o,l,r)}}function Y(e,t){const n=e.getFormatType(),o=e.getIndent();n!==t.getFormatType()&&t.setFormat(n),o!==t.getIndent()&&t.setIndent(o)}function Z(e,t,n){let o=S(e,n);if(x(o))return!1;for(;o;o=o.getParentCaret()){const e=o.getParentAtCaret();if(!e||o.getNodeAtCaret())return!1;if(t.is(e))return!0}return!1}function ee(e,t,n=Y){if(!e)return;const o=e.getStartEndPoints();let l=!1,r=null;const i=new Map;if(o){const[t,n]=o,c=C(t.getNode(),N);r=C(n.getNode(),N);const f=e.isBackward()?\"previous\":\"next\";l=s(r)&&!r.is(c)&&function(e,t,n){const o=e.getNode();return(!s(o)||!o.isEmpty())&&Z(e,t,n)}(n,r,v(f)),s(c)&&i.set(c.getKey(),c),s(r)&&!l&&i.set(r.getKey(),r)}for(const t of e.getNodes())if(s(t)&&N(t)){if(l&&t.is(r))continue;i.set(t.getKey(),t)}else if(!o){const e=C(t,N);s(e)&&i.set(e.getKey(),e)}for(const e of i.values()){if(null!==T(e))continue;const o=t();n(e,o),e.replace(o,!0)}}function te(e){return e.getNode().isAttached()}function ne(e){let t=e;for(;null!==t&&!E(t);){const e=t.getLatest(),n=t.getParent();0===e.getChildrenSize()&&t.remove(!0),t=n}}function oe(e,t,n=null){const o=e.getStartEndPoints(),l=o?o[0]:null,r=e.getNodes(),i=r.length;if(null!==l){const e=b(l.getNode());if(null!==e&&!E(e))return}if(null!==l&&(0===i||1===i&&\"element\"===l.type&&0===l.getNode().getChildrenSize())){const e=\"text\"===l.type?l.getNode().getParentOrThrow():l.getNode(),o=e.getChildren();let r=t();return r.setFormat(e.getFormatType()),r.setIndent(e.getIndent()),o.forEach(e=>r.append(e)),n&&(r=n.append(r)),void e.replace(r)}let s=null,c=[];for(let o=0;o<i;o++){const l=r[o];E(l)?(le(e,c,c.length,t,n),c=[],s=l):null===s||null!==s&&F(l,s)?c.push(l):(le(e,c,c.length,t,n),c=[l])}le(e,c,c.length,t,n)}function le(e,t,n,o,l=null){if(0===t.length)return;const r=t[0],i=new Map,f=[],u=s(r)?r:r.getParentOrThrow();let g=u.isInline()?u.getParentOrThrow():u,a=!1;for(;null!==g;){const e=g.getPreviousSibling();if(null!==e){g=e,a=!0;break}if(g=g.getParentOrThrow(),E(g))break}const d=new Set;for(let e=0;e<n;e++){const n=t[e];s(n)&&0===n.getChildrenSize()&&d.add(n.getKey())}const h=new Set;for(let e=0;e<n;e++){const n=t[e];let l=n.getParent();if(null!==l&&l.isInline()&&(l=l.getParent()),null!==l&&B(n)&&!h.has(n.getKey())){const e=l.getKey();if(void 0===i.get(e)){const t=o();t.setFormat(l.getFormatType()),t.setIndent(l.getIndent()),f.push(t),i.set(e,t);const n=l.getChildren();t.splice(t.getChildrenSize(),0,n);for(const e of n)if(h.add(e.getKey()),s(e))for(const t of e.getChildrenKeys())h.add(t);ne(l)}}else if(d.has(n.getKey())){s(n)||z(179);const e=o();e.setFormat(n.getFormatType()),e.setIndent(n.getIndent()),f.push(e),n.remove(!0)}}if(null!==l)for(let e=0;e<f.length;e++){const t=f[e];l.append(t)}let y=null;if(E(g))if(a)if(null!==l)g.insertAfter(l);else for(let e=f.length-1;e>=0;e--){const t=f[e];g.insertAfter(t)}else{const e=g,t=e.getFirstChild();if(s(t)&&(g=t),null===t)if(l)e.append(l);else for(let t=0;t<f.length;t++){const n=f[t];e.append(n),y=n}else if(null!==l)t.insertBefore(l);else for(let e=0;e<f.length;e++){const n=f[e];t.insertBefore(n),y=n}}else if(l)g.insertAfter(l);else for(let e=f.length-1;e>=0;e--){const t=f[e];g.insertAfter(t),y=t}const m=p();c(m)&&te(m.anchor)&&te(m.focus)?A(m.clone()):null!==y?y.selectEnd():e.dirty=!0}function re(e){const t=ie(e);return null!==t&&\"vertical-rl\"===t.writingMode}function ie(e){const t=e.anchor.getNode();return s(t)?M(t):D(t)}function se(e,t){let n=re(e)?!t:t;fe(e)&&(n=!n);const l=S(e.focus,n?\"previous\":\"next\");if(x(l))return!1;if(w(l)&&!P(l.origin)&&l.origin.isUnmergeable()){const e=l.getNodeAtCaret();if(o(e)&&!P(e))return!0}for(const e of k(l)){if(K(e))return!e.origin.isInline();if(!s(e.origin)){if(I(e.origin))return!0;break}}return!1}function ce(e,t,n,o){e.modify(t?\"extend\":\"move\",n,o)}function fe(e){const t=ie(e);return null!==t&&\"rtl\"===t.direction}function ue(e,t,n){const o=fe(e);let l;l=re(e)||o?!n:n,ce(e,t,l,\"character\")}function ge(e,t,n){const o=e.getStyle(),l=m(o);return null!==l&&l[t]||n}function ae(e,t,n=\"\"){let l=null;const r=e.getNodes();let i,s;if(c(e)){if(e.isCollapsed()&&\"\"!==e.style){const n=m(e.style);if(null!==n&&t in n)return n[t]}const{anchor:n,focus:l}=e,r=e.isBackward(),c=r?l.getNode():n.getNode(),f=r?n.getNode():l.getNode(),u=r?l.offset:n.offset,g=r?n.offset:l.offset;o(c)&&u===c.getTextContentSize()&&(i=c),0===g&&(s=f)}for(let e=0;e<r.length;e++){const c=r[e];if(o(c)&&!c.is(0===e?i:s)){const e=ge(c,t,n);if(null===l)l=e;else if(l!==e){l=\"\";break}}}return null===l?n:l}const de=m,pe=V;export{W as $addNodeStyle,Y as $copyBlockFormatIndent,X as $ensureForwardRangeSelection,J as $forEachSelectedTextNode,M as $getComputedStyleForElement,D as $getComputedStyleForParent,ae as $getSelectionStyleValueForProperty,Z as $isAtEdgeOfElement,H as $isAtNodeEnd,fe as $isParentElementRTL,U as $isParentRTL,ce as $moveCaretSelection,ue as $moveCharacter,G as $patchStyleText,ee as $setBlocksType,se as $shouldOverrideDefaultCharacterSelection,j as $sliceSelectedTextNodeContent,V as $trimTextContentFromAnchor,oe as $wrapNodes,O as createDOMRange,L as createRectsFromDOMRange,$ as getCSSFromStyleObject,de as getStyleObjectFromCSS,pe as trimTextContentFromAnchor};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{createRectsFromDOMRange as t,$isAtEdgeOfElement as e}from\"@lexical/selection\";import{getRootOwnerDocument as n,isHTMLElement as o,mergeRegister as r,$getSelection as i,$isRangeSelection as l,$isElementNode as s,$isTextNode as u,$getDOMTextNode as c,getDOMTextNode as f,$getDOMSlot as d,registerEventListener as a,getDOMSelectionPoints as g,getParentElement as p,$isSlotHost as h,$getSlotNames as m,$getSlot as y,$getChildCaret as v,$getSlotHost as w,$findMatchingParent as E,$getChildCaretOrSelf as S,$getSiblingCaret as C,$getAdjacentSiblingOrParentSiblingCaret as b,$caretRangeFromSelection as x,$getCaretRangeInDirection as N,$removeTextFromCaretRange as A,$isTextPointCaret as R,$splitAtPointCaretNext as _,$setSelectionFromCaretRange as I,$getCaretRange as P,$getPreviousSelection as D,$caretFromPoint as L,$getRoot as M,$createParagraphNode as B,$insertNodeToNearestRootAtCaret as O,$getAdjacentChildCaret as T,$isChildCaret as F,$normalizeCaret as $,$getCollapsedCaretRange as K,$cloneWithProperties as k,$fullReconcile as H,$setSelection as U,$rewindSiblingCaret as j,makeStepwiseIterator as z,$isSiblingCaret as V,$isExtendableTextPointCaret as W,$getState as X,$setState as G,IS_FIREFOX as Y,CAN_USE_DOM as q}from\"lexical\";export{$findMatchingParent,$getAdjacentSiblingOrParentSiblingCaret,$insertNodeToNearestRootAtCaret,$isBlockFullySelected,$splitNode,CAN_USE_BEFORE_INPUT,CAN_USE_DOM,IS_ANDROID,IS_ANDROID_CHROME,IS_APPLE,IS_APPLE_WEBKIT,IS_CHROME,IS_FIREFOX,IS_IOS,IS_SAFARI,addClassNamesToElement,isBlockDomNode,isHTMLAnchorElement,isHTMLElement,isInlineDomNode,mergeRegister,removeClassNamesFromElement}from\"lexical\";function J(t,...e){throw function(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),o=new URLSearchParams;o.append(\"code\",t);for(const t of e)o.append(\"v\",t);return n.search=o.toString(),new Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(t,...e)}function Q(t){const e=(t,e)=>e.left>=t.left-1&&e.top>=t.top-1&&e.right<=t.right+1&&e.bottom<=t.bottom+1,n=[];for(const o of Array.from(t))if(!(o.width<.5||o.height<.5||n.some(t=>e(o,t)))){for(let t=n.length-1;t>=0;t--)e(n[t],o)&&n.splice(t,1);n.push(o)}return n}function Z(t){return`${t}px`}const tt={attributes:!0,characterData:!0,childList:!0,subtree:!0};function et(e,r,i){let l=null,s=null,u=null,c=[];const f=n(e.getRootElement()).createElement(\"div\");function d(){null===l&&J(182),null===s&&J(183);const{left:o,top:u}=s.getBoundingClientRect(),d=function(t){const e=[];for(const n of t)n.width<.5||n.height<.5||e.some(t=>Math.abs(t.left-n.left)<=1&&Math.abs(t.top-n.top)<=1&&Math.abs(t.right-n.right)<=1&&Math.abs(t.bottom-n.bottom)<=1)||e.push(n);return e}(t(e,r));var a,g;f.parentNode!==s&&(g=f,(a=s).insertBefore(g,a.firstChild));let p=!1;for(let t=0;t<d.length;t++){const e=d[t],r=c[t]||n(l).createElement(\"div\"),i=r.style;\"absolute\"!==i.position&&(i.position=\"absolute\",p=!0);const s=Z(e.left-o);i.left!==s&&(i.left=s,p=!0);const a=Z(e.top-u);i.top!==a&&(r.style.top=a,p=!0);const g=Z(e.width);i.width!==g&&(r.style.width=g,p=!0);const h=Z(e.height);i.height!==h&&(r.style.height=h,p=!0),r.parentNode!==f&&(f.append(r),p=!0),c[t]=r}for(;c.length>d.length;){const t=c.pop();null!=t&&(t.remove(),p=!0)}p&&i(c)}function a(){s=null,l=null,null!==u&&u.disconnect(),u=null,f.remove();for(const t of c)t.remove();c=[]}function g(){const t=e.getRootElement();if(null===t)return a();const n=t.parentElement;if(!o(n))return a();a(),l=t,s=n,u=new MutationObserver(t=>{const n=e.getRootElement(),o=n&&n.parentElement;if(n!==l||o!==s)return g();for(const e of t)if(!f.contains(e.target))return d()}),u.observe(n,tt),d()}f.style.position=\"relative\";const p=e.registerRootListener(()=>(g(),a));return()=>{p(),a()}}function nt(t,e,n,o){if(\"text\"!==e.type&&s(n)){const r=d(n,o,t);return[r.element,r.getFirstChildOffset()+e.offset]}return[(u(n)?c(n,o,t):f(o))||o,e.offset]}function ot(t){for(const e of t){const t=e.style;\"Highlight\"!==t.background&&(t.background=\"Highlight\"),\"HighlightText\"!==t.color&&(t.color=\"HighlightText\"),t.marginTop!==Z(-1.5)&&(t.marginTop=Z(-1.5)),t.paddingTop!==Z(4)&&(t.paddingTop=Z(4)),t.paddingBottom!==Z(0)&&(t.paddingBottom=Z(0))}}function rt(t,e=ot){let n=null,o=null,s=null,u=null,c=null,f=null,d=()=>{};function a(r){r.read(()=>{const r=i();if(!l(r))return n=null,s=null,u=null,f=null,d(),void(d=()=>{});const[a,g]=function(t){const e=t.getStartEndPoints();return t.isBackward()?[e[1],e[0]]:e}(r),p=a.getNode(),h=p.getKey(),m=a.offset,y=g.getNode(),v=y.getKey(),w=g.offset,E=t.getElementByKey(h),S=t.getElementByKey(v),C=null===n||E!==o||m!==s||h!==n.getKey(),b=null===u||S!==c||w!==f||v!==u.getKey();if((C||b)&&null!==E&&null!==S){const n=function(t,e,n,o,r,i,l){const s=(t._window?t._window.document:document).createRange();return s.setStart(...nt(t,e,n,o)),s.setEnd(...nt(t,r,i,l)),s}(t,a,p,E,g,y,S);d(),d=et(t,n,e)}n=p,o=E,s=m,u=y,c=S,f=w},{editor:t})}return a(t.getEditorState()),r(t.registerUpdateListener(({editorState:t})=>a(t)),()=>{d()})}function it(t,e){let n=null;const o=()=>{const o=t.getRootElement(),r=null!==o?o.ownerDocument.defaultView:null,i=null!==r?r.getSelection():null,l=null!==i?g(i,o).anchorNode:null;null!==l&&null!==o&&o.contains(l)?null!==n&&(n(),n=null):null===n&&(n=rt(t,e))};return t.registerRootListener(t=>{if(t){const e=t.ownerDocument,i=r(a(e,\"selectionchange\",o),()=>{null!==n&&n()});return o(),i}})}function lt(t,e){const n=t.ownerDocument,o=n.defaultView||window;let r=o.getComputedStyle(t);const i=\"absolute\"===r.position,l=e?/(auto|scroll|hidden)/:/(auto|scroll)/;if(\"fixed\"===r.position)return n.body;for(let e=t;e=p(e);)if(r=o.getComputedStyle(e),(!i||\"static\"!==r.position)&&l.test(r.overflow+r.overflowY+r.overflowX))return e;return n.body}function st(t,e){for(const n of e)if(t.type.startsWith(n))return!0;return!1}function ut(t,e){const n=t[Symbol.iterator]();return new Promise((t,o)=>{const r=[],i=()=>{const{done:l,value:s}=n.next();if(l)return t(r);const u=new FileReader;u.addEventListener(\"error\",o),u.addEventListener(\"load\",()=>{const t=u.result;\"string\"==typeof t&&r.push({file:s,result:t}),i()}),st(s,e)?u.readAsDataURL(s):i()};i()})}function ct(t,e){return Array.from(at(t,e))}function ft(t){return t?t.getAdjacentCaret():null}function dt(t,e){return Array.from(St(t,e))}function at(t,e){return yt(\"next\",t,e)}function gt(t,e){return Array.from(pt(t,e))}function*pt(t,e){for(const n of yt(\"next\",t,e)){yield n;const{node:t,depth:o}=n;if(h(t)&&!t.is(e))for(const e of m(t)){const n=y(t,e);null!==n&&(yield*ht(n,o+1))}}}function*ht(t,e){yield{depth:e,node:t};const n=e+1;if(h(t))for(const e of m(t)){const o=y(t,e);null!==o&&(yield*ht(o,n))}if(s(t))for(const e of t.getChildren())yield*ht(e,n)}function mt(t,e){const n=b(C(t,e));return n&&n[0]}function yt(t,e,n){const o=M(),r=e||o,i=s(r)?v(r,t):C(r,t),l=wt(r),u=n?T(S(C(n,t)))||mt(n,t):mt(r,t);let c=l;return z({hasNext:t=>null!==t,initial:i,map:t=>({depth:c,node:t.origin}),step:t=>{if(t.isSameNodeCaret(u))return null;F(t)&&c++;const e=b(t);return!e||e[0].isSameNodeCaret(u)?null:(c+=e[1],e[0])}})}function vt(t){const e=b(C(t,\"next\"));return e&&[e[0].origin,e[1]]}function wt(t){let e=-1;for(let n=t;null!==n;n=n.getParent()??w(n))e++;return e}function Et(t){const e=S(C(t,\"previous\")),n=b(e,\"root\");return n&&n[0].origin}function St(t,e){return yt(\"previous\",t,e)}function Ct(t,e){return Array.from(bt(t,e))}function*bt(t,e){const n=[];for(const o of yt(\"previous\",t,e)){for(;n.length>0&&o.depth<=n[n.length-1].depth;){const t=n.pop();yield*xt(t.node,t.depth+1)}yield o;const{node:t,depth:r}=o;h(t)&&m(t).length>0&&!t.is(e)&&n.push({depth:r,node:t})}for(;n.length>0;){const t=n.pop();yield*xt(t.node,t.depth+1)}}function*xt(t,e){const n=m(t);for(let o=n.length-1;o>=0;o--){const r=y(t,n[o]);null!==r&&(yield*Nt(r,e))}}function*Nt(t,e){yield{depth:e,node:t};const n=e+1;if(s(t)){const e=t.getChildren();for(let t=e.length-1;t>=0;t--)yield*Nt(e[t],n)}h(t)&&(yield*xt(t,n))}function At(t,e){let n=t;for(;null!=n;){if(n instanceof e)return n;n=n.getParent()}return null}function Rt(t){const e=E(t,t=>s(t)&&!t.isInline());return s(e)||J(4,t.__key),e}function _t(t,e,n,o){const r=t=>t instanceof e;return t.registerNodeTransform(e,t=>{const e=(t=>{const e=t.getChildren();for(let t=0;t<e.length;t++){const n=e[t];if(r(n))return null}let n=t,o=t;for(;null!==n;)if(o=n,n=n.getParent(),r(n))return{child:o,parent:n};return null})(t);if(null!==e){const{child:r,parent:i}=e;if(r.is(t)){o(i,t);const e=r.getNextSiblings(),l=e.length;if(i.insertAfter(r),0!==l){const t=n(i);r.insertAfter(t);for(let n=0;n<l;n++)t.append(e[n])}i.canBeEmpty()||0!==i.getChildrenSize()||i.remove()}}})}function It(t,e){const n=new Map,o=t._pendingEditorState;for(const[t,o]of e._nodeMap)n.set(t,k(o));o&&(o._nodeMap=n),H();const r=e._selection;U(null===r?null:r.clone())}function Pt(t){const e=i()||D();let n;if(l(e))n=L(e.focus,\"next\");else{if(null!=e){const t=e.getNodes(),o=t[t.length-1];o&&(n=C(o,\"next\"))}n=n||v(M(),\"previous\").getFlipped().insert(B())}const o=O(t,n,W(r=n)||null!==b(R(r)?r.getSiblingCaret():r,\"shadowRoot\")?{$shouldSplit:(t,e)=>\"last\"!==e}:void 0);var r;const s=T(o),u=F(s)?$(s):o;return I(K(u)),t.getLatest()}function Dt(t){const e=i();if(!l(e))return void(e&&e.insertNodes([t]));const n=x(e);let o=N(A(n),\"next\").anchor;if(R(o)){const t=_(o);if(!t)return;o=t}const r=o.getFlipped();r.insert(t),I(P(r,r))}function Lt(t,e){const n=e();return t.replace(n),n.append(t),n}function Mt(t,e){if(null==t)return!1;const n=Object.getPrototypeOf(t);return null!=n&&null!=n.constructor&&n.constructor.name===e.name}function Bt(t){let e=null;if(Mt(t,DragEvent)?e=t.dataTransfer:Mt(t,ClipboardEvent)&&(e=t.clipboardData),null===e)return[!1,[],!1];const n=e.types,o=n.includes(\"Files\"),r=n.includes(\"text/html\")||n.includes(\"text/plain\");return[o,Array.from(e.files),r]}function Ot(t,e){const n=[];for(let o=0;o<t.length;o++){const r=e(t[o]);null!==r&&n.push(r)}return n}function Tt(t){const e=i();if(!l(e))return!1;const n=new Set,o=e.getNodes();for(let e=0;e<o.length;e++){const r=o[e],i=r.getKey();if(n.has(i))continue;const l=E(r,t=>s(t)&&!t.isInline());if(null===l)continue;const u=l.getKey();l.canIndent()&&!n.has(u)&&(n.add(u),t(l))}return n.size>0}function Ft(t,e){v(t,\"next\").insert(e)}let $t=!(Y||!q)&&void 0;function Kt(t,e=!1){let n=1;if(function(){if(void 0===$t){const t=document.createElement(\"div\");t.style.position=\"absolute\",t.style.opacity=\"0\",t.style.width=\"100px\",t.style.left=\"-1000px\",document.body.appendChild(t);const e=t.getBoundingClientRect();t.style.setProperty(\"zoom\",\"2\"),$t=t.getBoundingClientRect().width===e.width,document.body.removeChild(t)}return $t}()||e){const e=t&&t.ownerDocument.defaultView||window;for(;t;)n*=Number(e.getComputedStyle(t).getPropertyValue(\"zoom\")),t=p(t)}return n}function kt(t){return null!==t._parentEditor}function Ht(t,e){return Ut(t,e,null)}function Ut(t,e,n){let o=!1;for(const r of Vt(t))e(r)?null!==n&&n(r):(o=!0,s(r)&&Ut(r,e,n||(t=>r.insertAfter(t))),r.remove());return o}function jt(t,e){const n=[],o=Array.from(t).reverse();for(let t=o.pop();void 0!==t;t=o.pop())if(e(t))n.push(t);else if(s(t))for(const e of Vt(t))o.push(e);return n}function zt(t){return Wt(v(t,\"next\"))}function Vt(t){return Wt(v(t,\"previous\"))}function Wt(t){return z({hasNext:V,initial:t.getAdjacentCaret(),map:t=>t.origin.getLatest(),step:t=>t.getAdjacentCaret()})}function Xt(t){j(C(t,\"next\")).splice(1,t.getChildren())}function Gt(t){const e=e=>X(e,t),n=(e,n)=>G(e,t,n);return{$get:e,$set:n,accessors:[e,n],makeGetterMethod:()=>function(){return e(this)},makeSetterMethod:()=>function(t){return n(this,t)},stateConfig:t}}function Yt(t,e){const n=i();if(l(n)&&n.isCollapsed()){const o=E(n.anchor.getNode(),t);if(o){const t=o.getParent();if(null!==t&&t.getFirstChild()===o&&Jt(n.anchor,o))return o.insertBefore(B()).selectEnd(),e&&e.preventDefault(),!0}}return!1}function qt(t,e){const n=i();if(l(n)&&n.isCollapsed()){const o=E(n.anchor.getNode(),t);if(o){const t=o.getParent();if(null!==t&&t.getLastChild()===o&&Qt(n.anchor,o))return o.insertAfter(B()).selectEnd(),e&&e.preventDefault(),!0}}return!1}function Jt(t,n){return e(t,n,\"previous\")}function Qt(t,n){return e(t,n,\"next\")}export{jt as $descendantsMatching,ct as $dfs,at as $dfsIterator,gt as $dfsWithSlots,pt as $dfsWithSlotsIterator,Ot as $filter,zt as $firstToLastIterator,ft as $getAdjacentCaret,wt as $getDepth,Rt as $getNearestBlockElementAncestorOrThrow,At as $getNearestNodeOfType,Et as $getNextRightPreorderNode,vt as $getNextSiblingOrParentSibling,Tt as $handleIndentAndOutdent,Ft as $insertFirst,Dt as $insertNodeIntoLeaf,Pt as $insertNodeToNearestRoot,Qt as $isAtEndOfNode,Jt as $isAtStartOfNode,kt as $isEditorIsNestedEditor,Vt as $lastToFirstIterator,qt as $onEscapeDown,Yt as $onEscapeUp,It as $restoreEditorState,dt as $reverseDfs,St as $reverseDfsIterator,Ct as $reverseDfsWithSlots,bt as $reverseDfsWithSlotsIterator,Ht as $unwrapAndFilterDescendants,Xt as $unwrapNode,Lt as $wrapNodeInElement,Kt as calculateZoomLevel,Q as dedupeSelectionRects,Bt as eventFiles,lt as getScrollParent,st as isMimeType,Gt as makeStateWrapper,rt as markSelection,ut as mediaFileReader,Mt as objectKlassEquals,et as positionNodeOnRange,_t as registerNestedElementResolver,it as selectionAlwaysOnDisplay};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{getStaticNodeConfig as e}from\"lexical\";function n(n){const t=new Set,c=new Set;for(const f of o(n)){const n=\"function\"==typeof f?f:f.replace;e(n),t.add(n.getType()),c.add(n)}return{nodes:c,types:t}}function o(e){return(\"function\"==typeof e.nodes?e.nodes():e.nodes)||[]}export{n as getKnownTypesAndNodes,o as getNodeConfig};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{RootNode as t,TextNode as i,LineBreakNode as e,TabNode as n,ParagraphNode as o,HISTORY_MERGE_TAG as a,$isEditorState as s,$getRoot as p,$createParagraphNode as r}from\"lexical\";const d={tag:a};function l(){const t=p();t.isEmpty()&&t.append(r())}const c={config:{setOptions:d,updateOptions:d},init:({$initialEditorState:t=l})=>({$initialEditorState:t,initialized:!1}),afterRegistration(t,{updateOptions:i,setOptions:e},n){const o=n.getInitResult();if(!o.initialized){o.initialized=!0;const{$initialEditorState:n}=o;if(s(n))t.setEditorState(n,e);else if(\"function\"==typeof n)t.update(()=>{n(t)},i);else if(n&&(\"string\"==typeof n||\"object\"==typeof n)){const i=t.parseEditorState(n);t.setEditorState(i,e)}}return()=>{}},name:\"@lexical/extension/InitialState\",nodes:[t,i,e,n,o]};export{c as InitialStateExtension};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{shallowMergeConfig as t,createEditor as e,mergeRegister as n}from\"lexical\";import{getNodeConfig as i}from\"@lexical/extension/config\";import{InitialStateExtension as s}from\"@lexical/extension/InitialStateExtension\";function o(t,...e){throw function(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),i=new URLSearchParams;i.append(\"code\",t);for(const t of e)i.append(\"v\",t);return n.search=i.toString(),new Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(t,...e)}function r(){let t;try{t=\"0.53.0+prod.esm\"}catch{}return t??'\"<unknown>+source\"'}const a=/* @__PURE__ */r(),c=new Set([\"__proto__\",\"constructor\",\"prototype\"]);function d(t,e){if(t&&e&&!Array.isArray(e)&&\"object\"==typeof t&&\"object\"==typeof e){const n=t,i=e;for(const t in i)!c.has(t)&&Object.prototype.hasOwnProperty.call(i,t)&&(n[t]=d(n[t],i[t]));return t}return e}function g(t){return 0===t.id}function h(t){return 2===t.id}const f=new Set;class u{builder;configs;_dependency;_peerNameSet;extension;state;_signal;constructor(t,e){this.builder=t,this.extension=e,this.configs=new Set,this.state={id:0}}mergeConfigs(){let e=this.extension.config||{};const n=this.extension.mergeConfig?this.extension.mergeConfig.bind(this.extension):t;for(const t of this.configs)e=n(e,t);return e}init(t){const e=this.state;h(e)||o(306,String(e.id));const n={getDependency:this.getInitDependency.bind(this),getDirectDependentNames:this.getDirectDependentNames.bind(this),getPeer:this.getInitPeer.bind(this),getPeerNameSet:this.getPeerNameSet.bind(this)},i={...n,getDependency:this.getDependency.bind(this),getInitResult:this.getInitResult.bind(this),getPeer:this.getPeer.bind(this)},s=function(t,e,n){return Object.assign(t,{config:e,id:3,registerState:n})}(e,this.mergeConfigs(),n);let r;this.state=s,this.extension.init&&(r=this.extension.init(t,s.config,n)),this.state=function(t,e,n){return Object.assign(t,{id:4,initResult:e,registerState:n})}(s,r,i)}build(t){const e=this.state;let n;4!==e.id&&o(307,String(e.id),String(5)),this.extension.build&&(n=this.extension.build(t,e.config,e.registerState));const i={...e.registerState,getOutput:()=>n,getSignal:this.getSignal.bind(this)};this.state=function(t,e,n){return Object.assign(t,{id:5,output:e,registerState:n})}(e,n,i)}register(t,e){this._signal=e;const n=this.state;5!==n.id&&o(308,String(n.id),String(5));const i=this.extension.register&&this.extension.register(t,n.config,n.registerState);return this.state=function(t){return Object.assign(t,{id:6})}(n),()=>{const t=this.state;7!==t.id&&o(309,String(n.id),String(7)),this.state=function(t){return Object.assign(t,{id:5})}(t),i&&i()}}afterRegistration(t){const e=this.state;let n;return 6!==e.id&&o(310,String(e.id),String(6)),this.extension.afterRegistration&&(n=this.extension.afterRegistration(t,e.config,e.registerState)),this.state=function(t){return Object.assign(t,{id:7})}(e),n}getSignal(){return void 0===this._signal&&o(311),this._signal}getInitResult(){void 0===this.extension.init&&o(312,this.extension.name);const t=this.state;return function(t){return t.id>=4}(t)||o(313,String(t.id),String(4)),t.initResult}getInitPeer(t){const e=this.builder.extensionNameMap.get(t);return e?e.getExtensionInitDependency():void 0}getExtensionInitDependency(){const t=this.state;return function(t){return t.id>=3}(t)||o(314,String(t.id),String(3)),{config:t.config}}getPeer(t){const e=this.builder.extensionNameMap.get(t);return e?e.getExtensionDependency():void 0}getInitDependency(t){const e=this.builder.getExtensionRep(t);return void 0===e&&o(315,this.extension.name,t.name),e.getExtensionInitDependency()}getDependency(t){const e=this.builder.getExtensionRep(t);return void 0===e&&o(315,this.extension.name,t.name),e.getExtensionDependency()}getState(){const t=this.state;return function(t){return t.id>=7}(t)||o(316,String(t.id),String(7)),t}getDirectDependentNames(){return this.builder.incomingEdges.get(this.extension.name)||f}getPeerNameSet(){let t=this._peerNameSet;return t||(t=new Set((this.extension.peerDependencies||[]).map(([t])=>t)),this._peerNameSet=t),t}getExtensionDependency(){if(!this._dependency){const t=this.state;(function(t){return t.id>=5})(t)||o(317,this.extension.name),this._dependency={config:t.config,init:t.initResult,output:t.output}}return this._dependency}}const p=Symbol.for(\"@lexical/extension/LexicalBuilder\");function l(...t){return b.fromExtensions(t).buildEditor()}function m(){}function x(t){throw t}function E(t){return Array.isArray(t)?t:[t]}const S=a;class b{roots;extensionNameMap;outgoingConfigEdges;incomingEdges;conflicts;_sortedExtensionReps;PACKAGE_VERSION;constructor(t){this.outgoingConfigEdges=new Map,this.incomingEdges=new Map,this.extensionNameMap=new Map,this.conflicts=new Map,this.PACKAGE_VERSION=S,this.roots=t;for(const e of t)this.addExtension(e)}static fromExtensions(t){const e=[E(s)];for(const n of t)e.push(E(n));return new b(e)}static maybeFromEditor(t){const e=t[p];return e&&(e.PACKAGE_VERSION!==S&&o(292,e.PACKAGE_VERSION,S),e instanceof b||o(293)),e}static fromEditor(t){const e=b.maybeFromEditor(t);return void 0===e&&o(294),e}constructEditor(){const{$initialEditorState:t,onError:n,onWarn:i,...s}=this.buildCreateEditorArgs(),o=Object.assign(e({...s,...n?{onError:t=>{n(t,o)}}:{},...i?{onWarn:t=>{i(t,o)}}:{}}),{[p]:this});for(const t of this.sortedExtensionReps())t.build(o);return o}buildEditor(){let t=m;function e(){try{t()}finally{t=m}}const i=Object.assign(this.constructEditor(),{dispose:e,[Symbol.dispose]:e});return t=n(this.registerEditor(i),()=>i.setRootElement(null)),i}hasExtensionByName(t){return this.extensionNameMap.has(t)}getExtensionRep(t){const e=this.extensionNameMap.get(t.name);if(e)return e.extension!==t&&o(295,t.name),e}addEdge(t,e,n){const i=this.outgoingConfigEdges.get(t);if(i){const t=i.get(e);t?t.push(...n):i.set(e,n)}else this.outgoingConfigEdges.set(t,new Map([[e,n]]));const s=this.incomingEdges.get(e);s?s.add(t):this.incomingEdges.set(e,new Set([t]))}addExtension(t){void 0!==this._sortedExtensionReps&&o(296);const e=E(t),[n]=e;\"string\"!=typeof n.name&&o(297,typeof n.name);let i=this.extensionNameMap.get(n.name);if(void 0!==i&&i.extension!==n&&o(298,n.name),!i){i=new u(this,n),this.extensionNameMap.set(n.name,i);const t=this.conflicts.get(n.name);\"string\"==typeof t&&o(299,n.name,t);for(const t of n.conflictsWith||[])this.extensionNameMap.has(t)&&o(299,n.name,t),this.conflicts.set(t,n.name);for(const t of n.dependencies||[]){const e=E(t);this.addEdge(n.name,e[0].name,e.slice(1)),this.addExtension(e)}for(const[t,e]of n.peerDependencies||[])this.addEdge(n.name,t,e?[e]:[])}}sortedExtensionReps(){if(this._sortedExtensionReps)return this._sortedExtensionReps;const t=[],e=(n,i)=>{let s=n.state;if(h(s))return;const r=n.extension.name;var a;g(s)||o(300,r,i||\"[unknown]\"),g(a=s)||o(304,String(a.id),String(0)),s=Object.assign(a,{id:1}),n.state=s;const c=this.outgoingConfigEdges.get(r);if(c)for(const t of c.keys()){const n=this.extensionNameMap.get(t);n&&e(n,r)}s=function(t){return function(t){return 1===t.id}(t)||o(305,String(t.id),String(1)),Object.assign(t,{id:2})}(s),n.state=s,t.push(n)};for(const t of this.extensionNameMap.values())g(t.state)&&e(t);for(const e of t)for(const[t,n]of this.outgoingConfigEdges.get(e.extension.name)||[])if(n.length>0){const e=this.extensionNameMap.get(t);if(e)for(const t of n)e.configs.add(t)}for(const[t,...e]of this.roots)if(e.length>0){const n=this.extensionNameMap.get(t.name);void 0===n&&o(301,t.name);for(const t of e)n.configs.add(t)}return this._sortedExtensionReps=t,this._sortedExtensionReps}registerEditor(t){const e=this.sortedExtensionReps(),i=new AbortController,s=[()=>i.abort()],o=i.signal;for(const n of e){const e=n.register(t,o);e&&s.push(e)}for(const n of e){const e=n.afterRegistration(t);e&&s.push(e)}return n(...s)}buildCreateEditorArgs(){const t={},e=new Set,n=new Map,s=new Map,r={},a={},c=this.sortedExtensionReps();for(const g of c){const{extension:c}=g;if(void 0!==c.onError&&(t.onError=c.onError),void 0!==c.onWarn&&(t.onWarn=c.onWarn),void 0!==c.disableEvents&&(t.disableEvents=c.disableEvents),void 0!==c.parentEditor&&(t.parentEditor=c.parentEditor),void 0!==c.editable&&(t.editable=c.editable),void 0!==c.namespace&&(t.namespace=c.namespace),void 0!==c.$initialEditorState&&(t.$initialEditorState=c.$initialEditorState),c.nodes)for(const t of i(c)){if(\"function\"!=typeof t){const e=n.get(t.replace);e&&o(302,c.name,t.replace.name,e.extension.name),n.set(t.replace,g)}e.add(t)}if(c.html){if(c.html.export)for(const[t,e]of c.html.export.entries())s.set(t,e);c.html.import&&Object.assign(r,c.html.import)}c.theme&&d(a,c.theme)}Object.keys(a).length>0&&(t.theme=a),e.size&&(t.nodes=Array.from(e));const g=Object.keys(r).length>0,h=s.size>0;(g||h)&&(t.html={},g&&(t.html.import=r),h&&(t.html.export=s));for(const e of c)e.init(t);return t.onError||(t.onError=x),t}}export{b as LexicalBuilder,l as buildEditorFromExtensions,p as builderSymbol};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{LexicalBuilder as e}from\"@lexical/extension/LexicalBuilder\";function n(n,r){const o=e.maybeFromEditor(n);if(!o)return;const t=o.extensionNameMap.get(r);return t?t.getExtensionDependency():void 0}function r(e,r){const o=n(e,r);return void 0===o&&function(e,...n){throw function(e,...n){const r=new URL(\"https://lexical.dev/docs/error\"),o=new URLSearchParams;o.append(\"code\",e);for(const e of n)o.append(\"v\",e);return r.search=o.toString(),new Error(`Minified Lexical error #${e}; visit ${r.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(e,...n)}(291,r),o}export{n as getPeerDependencyFromEditor,r as getPeerDependencyFromEditorOrThrow};\n","var i=Symbol.for(\"preact-signals\");function t(){if(!(v>1)){var i,t=!1;!function(){var i=c;c=void 0;while(void 0!==i){var t=i.S;if(t.v===i.v)for(var r=t.t;void 0!==r;r=r.x)if(r.i===i.i)r.i=t.i;i=i.o}}();while(void 0!==h){var r=h;h=void 0;s++;while(void 0!==r){var n=r.u;r.u=void 0;r.f&=-3;if(!(8&r.f)&&w(r))try{r.c()}catch(r){if(!t){i=r;t=!0}}r=n}}s=0;v--;if(t)throw i}else v--}function r(i){if(v>0)return i();u=++e;v++;try{return i()}finally{t()}}var n,o=void 0;function f(i){var t=o,r=n;o=void 0;n=void 0;try{return i()}finally{o=t;n=r}}var h=void 0,v=0,s=0,e=0,u=0,c=void 0,a=0;function d(i){if(void 0!==o){var t=i.n;if(void 0===t||t.t!==o){t={i:0,S:i,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:t};if(void 0!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=o.s;t.n=void 0;o.s.n=t;o.s=t}return t}}}function l(i,t){this.v=i;this.i=0;this.n=void 0;this.t=void 0;this.l=0;this.W=null==t?void 0:t.watched;this.Z=null==t?void 0:t.unwatched;this.name=null==t?void 0:t.name}l.prototype.brand=i;l.prototype.h=function(){return!0};l.prototype.S=function(i){var t=this,r=this.t;if(r!==i&&void 0===i.e){i.x=r;this.t=i;if(void 0!==r)r.e=i;else f(function(){var i;null==(i=t.W)||i.call(t)})}};l.prototype.U=function(i){var t=this;if(void 0!==this.t){var r=i.e,n=i.x;if(void 0!==r){r.x=n;i.e=void 0}if(void 0!==n){n.e=r;i.x=void 0}if(i===this.t){this.t=n;if(void 0===n)f(function(){var i;null==(i=t.Z)||i.call(t)})}}};l.prototype.subscribe=function(i){var t=this;return x(function(){var r=t.value;f(function(){return i(r)})},{name:\"sub\"})};l.prototype.valueOf=function(){return this.value};l.prototype.toString=function(){return this.value+\"\"};l.prototype.toJSON=function(){return this.value};l.prototype.peek=function(){var i=this;return f(function(){return i.value})};Object.defineProperty(l.prototype,\"value\",{get:function(){var i=d(this);if(void 0!==i)i.i=this.i;return this.v},set:function(i){if(i!==this.v){if(s>100)throw new Error(\"Cycle detected\");!function(i){if(0!==v&&0===s)if(i.l!==u){i.l=u;c={S:i,v:i.v,i:i.i,o:c}}}(this);this.v=i;this.i++;a++;v++;try{for(var r=this.t;void 0!==r;r=r.x)r.t.N()}finally{t()}}}});function y(i,t){return new l(i,t)}function w(i){for(var t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function b(i){for(var t=i.s;void 0!==t;t=t.n){var r=t.S.n;if(void 0!==r)t.r=r;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break}}}function _(i){var t=i.s,r=void 0;while(void 0!==t){var n=t.p;if(-1===t.i){t.S.U(t);if(void 0!==n)n.n=t.n;if(void 0!==t.n)t.n.p=n}else r=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=n}i.s=r}function j(i,t){l.call(this,void 0,t);this.x=i;this.s=void 0;this.g=a-1;this.f=4}j.prototype=new l;j.prototype.h=function(){this.f&=-3;if(1&this.f)return!1;if(32==(36&this.f))return!0;this.f&=-5;if(this.g===a)return!0;this.g=a;this.f|=1;if(this.i>0&&!w(this)){this.f&=-2;return!0}var i=o;try{b(this);o=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++}}catch(i){this.v=i;this.f|=16;this.i++}o=i;_(this);this.f&=-2;return!0};j.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t)}l.prototype.S.call(this,i)};j.prototype.U=function(i){if(void 0!==this.t){l.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t)}}};j.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N()}};Object.defineProperty(j.prototype,\"value\",{get:function(){if(1&this.f)throw new Error(\"Cycle detected\");var i=d(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v}});function O(i,t){return new j(i,t)}function p(i){var r=i.j;i.j=void 0;if(\"function\"==typeof r){v++;var n=o;o=void 0;try{r()}catch(t){i.f&=-2;i.f|=8;g(i);throw t}finally{o=n;t()}}}function g(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;p(i)}function S(i){if(o!==this)throw new Error(\"Out-of-order effect\");_(this);o=i;this.f&=-2;try{if(8&this.f)g(this)}finally{t()}}function m(i,t){this.x=i;this.j=void 0;this.s=void 0;this.u=void 0;this.f=32;this.name=null==t?void 0:t.name;if(n)n.push(this)}m.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if(\"function\"==typeof t)this.j=t}finally{i()}};m.prototype.S=function(){if(1&this.f)throw new Error(\"Cycle detected\");this.f|=1;this.f&=-9;p(this);b(this);v++;var i=o;o=this;return S.bind(this,i)};m.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.u=h;h=this}};m.prototype.d=function(){this.f|=8;if(!(1&this.f))g(this)};m.prototype.dispose=function(){this.d()};function x(i,t){var r=new m(i,t);try{r.c()}catch(i){r.d();throw i}var n=r.d.bind(r);n[Symbol.dispose]=n;return n}function E(i){return function(){var t=arguments,n=this;return r(function(){return f(function(){return i.apply(n,[].slice.call(t))})})}}function C(){var i=n;n=[];return function(){var t=n;if(n&&i)i=i.concat(n);n=i;return t}}var k=function(i,t){t.push(i);for(var r=\"[object Object]\"===Object.prototype.toString.call(i),n=Object.create(null),o=i;o&&o!==Object.prototype;o=r&&Object.getPrototypeOf(o)){var f=Object.getOwnPropertyDescriptors(o);for(var h in f)if(!n[h]){n[h]=!0;var v=f[h].value;if(\"function\"==typeof v){if(\"constructor\"!==h)i[h]=E(v)}else if(o===i&&\"object\"==typeof v&&null!==v&&!(\"brand\"in v)&&t.indexOf(v)<0)k(v,t)}}};function T(i){return function(){var t,o,f=C();try{o=i.apply(void 0,[].slice.call(arguments))}catch(i){var h=n;n=void 0;if(h)try{r(function(){for(var i=0;i<h.length;i++)try{h[i].dispose()}catch(i){}})}catch(i){}throw i}finally{t=f()}k(o,[]);o[Symbol.dispose]=E(function(){if(t)for(var i=0;i<t.length;i++)t[i].dispose();t=void 0});return o}}export{j as Computed,m as Effect,l as Signal,E as action,r as batch,O as computed,T as createModel,x as effect,y as signal,f as untracked};//# sourceMappingURL=signals-core.module.js.map\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{signal as t}from\"@lexical/extension/signals\";function e(e,i){let n;return t(e(),{unwatched(){n&&(n(),n=void 0)},watched(){this.value=e(),n=i(this)}})}export{e as watchedSignal};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{watchedSignal as e}from\"@lexical/extension/watchedSignal\";const t={build:t=>e(()=>t.getEditorState(),e=>t.registerUpdateListener(t=>{e.value=t.editorState})),name:\"@lexical/extension/EditorState\"};export{t as EditorStateExtension};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{$getSelection as e,$getNodeByKey as t}from\"lexical\";import{EditorStateExtension as n}from\"@lexical/extension/EditorStateExtension\";import{signal as o,effect as i,computed as s}from\"@lexical/extension/signals\";import{watchedSignal as a}from\"@lexical/extension/watchedSignal\";const c=new Set,d={build(d,l,r){const u=r.getDependency(n).output,p=o({watchedNodeKeys:new Map}),x=a(()=>{},()=>i(()=>{const n=x.peek(),{watchedNodeKeys:o}=p.value;let i,s=!1;u.value.read(()=>{if(e())for(const[e,a]of o.entries()){if(0===a.size){o.delete(e);continue}const c=t(e),d=c&&c.isSelected()||!1;s=s||d!==(!!n&&n.has(e)),d&&(i=i||new Set,i.add(e))}}),!s&&i&&n&&i.size===n.size||(x.value=i)}));return{watchNodeKey:function(e){const t=s(()=>(x.value||c).has(e)),{watchedNodeKeys:n}=p.peek();let o=n.get(e);const i=void 0!==o;return o=o||new Set,o.add(t),i||(n.set(e,o),p.value={watchedNodeKeys:n}),t}}},dependencies:[n],name:\"@lexical/extension/NodeSelection\"};export{d as NodeSelectionExtension};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{$insertNodeToNearestRoot as e}from\"@lexical/utils\";import{createCommand as t,DecoratorNode as n,$getDocument as o,addClassNamesToElement as r,$create as i,mergeRegister as s,$getSelection as l,$isRangeSelection as c,COMMAND_PRIORITY_EDITOR as d,CLICK_COMMAND as u,isDOMNode as a,$getNodeFromDOMNode as m,COMMAND_PRIORITY_LOW as f,removeClassNamesFromElement as g,$isNodeSelection as x,$createNodeSelection as p,$setSelection as h}from\"lexical\";import{EditorStateExtension as S}from\"@lexical/extension/EditorStateExtension\";import{NodeSelectionExtension as N}from\"@lexical/extension/NodeSelectionExtension\";import{signal as y,batch as E,effect as M}from\"@lexical/extension/signals\";const v=/* @__PURE__ */t(\"INSERT_HORIZONTAL_RULE_COMMAND\");class O extends n{$config(){return this.config(\"horizontalrule\",{extends:n,importDOM:{hr:()=>({conversion:D,priority:0})}})}exportDOM(){return{element:o().createElement(\"hr\")}}createDOM(e){const t=o().createElement(\"hr\");return r(t,e.theme.hr),t}getTextContent(){return\"\\n\"}isInline(){return!1}updateDOM(){return!1}}function D(){return{node:C()}}function C(){return i(O)}function K(e){return e instanceof O}const R={dependencies:[S,N],name:\"@lexical/extension/HorizontalRule\",nodes:()=>[O],register(t,n,o){const{watchNodeKey:i}=o.getDependency(N).output,S=y({nodeSelections:new Map}),D=t._config.theme.hrSelected??\"selected\";return s(t.registerCommand(v,t=>{const n=l();if(!c(n))return!1;if(null!==n.focus.getNode()){const t=C();e(t)}return!0},d),t.registerCommand(u,e=>{if(a(e.target)){const t=m(e.target);if(K(t))return function(e,t=!1){const n=l(),o=e.isSelected(),r=e.getKey();let i;t&&x(n)?i=n:(i=p(),h(i)),o?i.delete(r):i.add(r)}(t,e.shiftKey),!0}return!1},f),t.registerMutationListener(O,(e,n)=>{E(()=>{let n=!1;const{nodeSelections:o}=S.peek();for(const[r,s]of e.entries())if(\"destroyed\"===s)o.delete(r),n=!0;else{const e=o.get(r),s=t.getElementByKey(r);e?e.domNode.value=s:(n=!0,o.set(r,{domNode:y(s),selectedSignal:i(r)}))}n&&(S.value={nodeSelections:o})})}),M(()=>{const e=[];for(const{domNode:t,selectedSignal:n}of S.value.nodeSelections.values())e.push(M(()=>{const e=t.value;e&&(n.value?r(e,D):g(e,D))}));return s(...e)}))}};export{C as $createHorizontalRuleNode,K as $isHorizontalRuleNode,R as HorizontalRuleExtension,O as HorizontalRuleNode,v as INSERT_HORIZONTAL_RULE_COMMAND};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{$getEditor as e}from\"lexical\";import{getExtensionDependencyFromEditor as n}from\"@lexical/extension/getExtensionDependencyFromEditor\";import{getPeerDependencyFromEditor as t}from\"@lexical/extension/getPeerDependencyFromEditor\";function o(t){return n(e(),t)}function r(e){return o(e).output}function i(n){return t(e(),n)}export{o as $getExtensionDependency,r as $getExtensionOutput,i as $getPeerDependency};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{$sliceSelectedTextNodeContent as t}from\"@lexical/selection\";import{isDOMDocumentNode as e,isHTMLElement as n,$getEditor as o,createState as r,$getEditorDOMRenderConfig as s,isDOMTextNode as i,isBlockDomNode as c,isInlineDomNode as l,$isElementNode as u,$isBlockElementNode as f,$isDecoratorNode as a,$isLineBreakNode as p,$createParagraphNode as d,$setFormatFromDOM as h,setNodeIndentFromDOM as m,$setDirectionFromDOM as g,$generateNodesFromRawText as y,$createTextNode as x,isOnlyChildInBlockNode as S,isLastChildInBlockNode as $,$createLineBreakNode as v,$isTextNode as C,IS_BOLD as b,IS_ITALIC as k,IS_UNDERLINE as w,IS_STRIKETHROUGH as D,TEXT_TYPE_TO_FORMAT as O,IS_SUBSCRIPT as A,IS_SUPERSCRIPT as M,IS_HIGHLIGHT as E,IS_CODE as N,shallowMergeConfig as I,DEFAULT_EDITOR_DOM_CONFIG as W,getRegisteredSubtypeMap as R,$isLexicalNode as T,iterStaticNodeConfigChain as F,$fullReconcile as z,RootNode as P,$getDocument as j,$getRoot as _,$getSelectionSlotFrame as L,$assumeActiveEditor as B,$isNodeSelection as U,isDocumentFragment as V,$isRootOrShadowRoot as q,ArtificialNode__DO_NOT_USE as G}from\"lexical\";import{objectKlassEquals as H}from\"@lexical/utils\";import{getPeerDependencyFromEditor as J}from\"@lexical/extension/getPeerDependencyFromEditor\";import{getKnownTypesAndNodes as Q}from\"@lexical/extension/config\";import{HorizontalRuleNode as K,$createHorizontalRuleNode as Y}from\"@lexical/extension/HorizontalRuleExtension\";import{$getExtensionOutput as Z}from\"@lexical/extension/getExtensionDependency\";function X(t,...e){throw function(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),o=new URLSearchParams;o.append(\"code\",t);for(const t of e)o.append(\"v\",t);return n.search=o.toString(),new Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(t,...e)}const tt=(t,e,n)=>{et(t),n()};function et(t){if(!e(t))return;const o=t;if(null===o.querySelector(\"style\"))return;const r=new Map;function s(t){let e=r.get(t);if(void 0===e){e=new Set;for(let n=0;n<t.style.length;n++)e.add(t.style[n]);r.set(t,e)}return e}try{for(const t of Array.from(o.styleSheets)){let e;try{e=t.cssRules}catch{continue}for(const t of Array.from(e)){if(!H(t,CSSStyleRule))continue;let e;try{e=o.querySelectorAll(t.selectorText)}catch{continue}for(const o of Array.from(e)){if(!n(o))continue;const e=s(o);for(let n=0;n<t.style.length;n++){const r=t.style[n];e.has(r)||o.style.setProperty(r,t.style.getPropertyValue(r),t.style.getPropertyPriority(r))}}}}}catch{}}let nt;function ot(t,e){const{key:n}=e;return t&&n in t?t[n]:e.defaultValue}function rt(t){return nt&&nt.editor===t?nt:void 0}function st(t,e){const n=rt(e);return n&&n[t]}function it(t,e){if(\"cfg\"in e){const{cfg:n,updater:o}=e;return[n,o(ot(t,n))]}return e}function ct(t,e){let n=e;for(const o of t){const[t,r]=it(n,o),s=t.key;if(n===e&&ot(n,t)===r)continue;const i=n===e||void 0===n?lt(e):n;i[s]=r,n=i}return n}function lt(t){return Object.create(t||null)}function ut(t,e){return[t,e]}function ft(t,e){return{cfg:t,updater:e}}function at(t,e,n,r=o()){const s=nt,i=rt(r);try{return nt={...i,editor:r,[t]:e},n()}finally{nt=s}}function pt(t,e=()=>{}){return(n,r=o())=>o=>{const s=rt(r),i=s&&s[t],c=ct(n,i||e(r));return c&&c!==i?at(t,c,o,r):o()}}function dt(t,e,n,o){return Object.assign(r(Symbol(e),{isEqual:o,parse:n}),{[t]:!0})}const ht=\"@lexical/html/DOM\",mt=Symbol.for(\"@lexical/html/DOMExportContext\"),gt=\"@lexical/html/DOMImport\",yt=Symbol.for(\"@lexical/html/DOMImportContext\"),xt=()=>!0;function St(t,e,n){return dt(mt,t,e,n)}const $t=/* @__PURE__ */St(\"root\",Boolean),vt=/* @__PURE__ */St(\"isExport\",Boolean);function Ct(t){const e=J(t,ht);return e?e.output.defaults:void 0}function bt(t,e=o()){return ot(function(t){return st(mt,t)||Ct(t)}(e),t)}function kt(t){const e=J(t,ht);return e?e.output.runtime:void 0}function wt(t,e,n=o()){const r=kt(n);r&&r.setContextValue(t,e)}function Dt(t,e,n=o()){const r=kt(n);r&&r.setContextValue(t,e(ot(r.editorContext,t)))}function Ot(t=o()){const e=kt(t);return e?e.getSessionConfig():s(t)}const At=/* @__PURE__ */pt(mt,Ct),Mt=Symbol.for(\"@lexical/html/SelectorImpl\");function Et(t,e){const o={kind:\"element\",predicate:(r=e,0===r.length?n:1===r.length?r[0]:(t,e)=>{for(const n of r)if(!n(t,e))return!1;return!0}),tags:t};var r;const s=n=>Et(t,[...e,n]);return{[Mt]:o,attr:(t,e,n)=>s(Wt(t,e,n)),classAll:(...t)=>s(It(t)),classAny:(...t)=>s(function(t){const e=Nt(t);return 0===e.length?()=>!1:t=>{if(!n(t))return!1;const o=t.classList;for(const t of e)if(o.contains(t))return!0;return!1}}(t)),styleAny:(t,e,o)=>s(function(t,e,o){if(\"string\"==typeof e)return o=>n(o)&&o.style.getPropertyValue(t)===e;if(e instanceof RegExp){const r=o&&o.capture,s=e;return(e,o)=>{if(!n(e))return!1;const i=e.style.getPropertyValue(t);if(!i)return!1;const c=i.match(s);return null!==c&&(void 0!==r&&(o[r]=c),!0)}}X(362,JSON.stringify(t))}(t,e,o))}}function Nt(t){const e=[];for(const n of t)n&&e.push(n);return e}function It(t){const e=Nt(t);return 0===e.length?()=>!0:t=>{if(!n(t))return!1;const o=t.classList;for(const t of e)if(!o.contains(t))return!1;return!0}}function Wt(t,e,o){if(!0===e)return e=>n(e)&&e.hasAttribute(t);if(\"string\"==typeof e)return o=>n(o)&&o.getAttribute(t)===e;if(e instanceof RegExp){const r=o&&o.capture,s=e;return(e,o)=>{if(!n(e))return!1;const i=e.getAttribute(t);if(null==i)return!1;const c=i.match(s);return null!==c&&(void 0!==r&&(o[r]=c),!0)}}X(361,JSON.stringify(t))}function Rt(t){return{[Mt]:t}}const Tt=/* @__PURE__ */Rt({kind:\"text\",predicate:i,tags:new Set}),Ft=/* @__PURE__ */Rt({kind:\"comment\",predicate:t=>8===t.nodeType,tags:new Set});function zt(){return Et(new Set,[])}function Pt(){return Ft}function jt(...t){t.length>0||X(363);const e=new Set;for(const n of t)e.add(n.toUpperCase());return Et(e,[])}function _t(){return Tt}const Lt={any:zt,comment:Pt,tag:jt,text:_t};function Bt(t,e){return n(t)&&t.nodeName===e.toUpperCase()}const Ut=/[A-Za-z0-9_-]/;class Vt{constructor(t,e){this.source=t,this.pos=e}peek(t=0){return this.source[this.pos+t]||\"\"}consume(){return this.source[this.pos++]||\"\"}eof(){return this.pos>=this.source.length}skipWhitespace(){for(;!this.eof()&&/\\s/.test(this.peek());)this.pos++}readIdent(){const t=this.pos;for(;!this.eof()&&Ut.test(this.peek());)this.pos++;return this.source.slice(t,this.pos)}readQuoted(){const t=this.consume();this.assert('\"'===t||\"'\"===t,\"expected quote\");const e=this.pos;for(;!this.eof()&&this.peek()!==t;)\"\\\\\"===this.peek()?this.pos+=2:this.pos++;this.assert(!this.eof(),\"unterminated string\");const n=this.source.slice(e,this.pos);return this.pos++,n.replace(/\\\\(.)/g,\"$1\")}assert(t,e){t||X(364,String(this.pos+1),e,this.source)}}function qt(t){const e=new Set,n=[],o=[];let r=!1;if(t.skipWhitespace(),\"*\"===t.peek())t.consume(),r=!0;else if(Ut.test(t.peek())){const n=t.readIdent();n&&e.add(n.toUpperCase())}for(;!t.eof();){const e=t.peek();if(\".\"===e){t.consume();const e=t.readIdent();t.assert(\"\"!==e,'expected class name after \".\"'),o.push(e)}else if(\"#\"===e){t.consume();const e=t.readIdent();t.assert(\"\"!==e,'expected id after \"#\"'),n.push(Wt(\"id\",e))}else{if(\"[\"!==e)break;{t.consume(),t.skipWhitespace();const e=t.readIdent();t.assert(\"\"!==e,'expected attribute name after \"[\"'),t.skipWhitespace();let o=!0;if(\"=\"===t.peek()){t.consume(),t.skipWhitespace();const e=t.peek();'\"'===e||\"'\"===e?o=t.readQuoted():(o=t.readIdent(),t.assert(\"\"!==o,\"expected attribute value\")),t.skipWhitespace()}t.assert(\"]\"===t.peek(),'expected \"]\"'),t.consume(),n.push(Wt(e,o))}}}return o.length>0&&n.push(It(o)),t.assert(r||e.size>0||n.length>0,\"expected a selector\"),{predicates:n,tags:e}}function Gt(t){const e=new Vt(t,0),n=[];for(;n.push(qt(e)),e.skipWhitespace(),!e.eof();)e.assert(\",\"===e.peek(),'expected \",\" (selector lists are the only supported combinator)'),e.consume(),e.skipWhitespace();if(1===n.length)return Et(n[0].tags,n[0].predicates);const o=new Set;if(n.every(t=>t.tags.size>0))for(const t of n)for(const e of t.tags)o.add(e);return Et(o,[(t,e)=>{for(const o of n){const n=t.nodeName;if(o.tags.size>0&&!o.tags.has(n))continue;let r=!0;for(const n of o.predicates)if(!n(t,e)){r=!1;break}if(r)return!0}return!1}])}function Ht(t,e,n){return dt(yt,t,e,n)}const Jt=/* @__PURE__ */Ht(\"importSource\",()=>\"unknown\"),Qt=/* @__PURE__ */Ht(\"importSourceDataTransfer\",()=>null),Kt=/* @__PURE__ */Ht(\"textFormat\",()=>0),Yt=/* @__PURE__ */Ht(\"textStyle\",()=>({}));function Zt(t){if(!n(t))return!1;if(\"PRE\"===t.nodeName)return!0;const e=t.style.whiteSpace;return\"string\"==typeof e&&e.startsWith(\"pre\")}function Xt(t){if(i(t))return!0;if(!n(t))return!1;const e=t.style.display;return e?e.startsWith(\"inline\"):!c(t)&&l(t)}const te=/* @__PURE__ */Ht(\"whitespaceConfig\",()=>({isInline:Xt,preservesWhitespace:Zt})),ee=/* @__PURE__ */Ht(\"importOverlays\",()=>[]);class ne{constructor(t){this.record=t}get(t){return ot(this.record,t)}set(t,e){this.record[t.key]=e}update(t,e){this.record[t.key]=e(ot(this.record,t))}has(t){return Object.prototype.hasOwnProperty.call(this.record,t.key)}}function oe(t){const e=J(t,gt);return e?e.output.defaults:void 0}function re(t,e=o()){return ot(function(t){return st(yt,t)||oe(t)}(e),t)}const se=/* @__PURE__ */pt(yt,oe);function ie(t){return f(t)||a(t)&&!t.isInline()}function ce(t,e){const n=[];let o=[];const r=()=>{0!==o.length&&(n.push(e().splice(0,0,o)),o=[])};for(const s of t)if(ie(s)){if(r(),u(s)){const t=ce(s.getChildren(),e);s.splice(0,s.getChildrenSize(),t)}n.push(s)}else o.push(s);return r(),n}function le(t,e){if(!n(e))return t;const o=e.style.textAlign;if(!ge(o))return t;for(const e of t)f(e)&&\"\"===e.getFormatType()&&e.setFormat(o);return t}function ue(t,e,o){1===t.length&&p(t[0])&&(t=[]);const r=d();if(n(o)){const t=o.style.textAlign;ge(t)&&r.setFormat(t)}return[r.splice(0,0,t)]}const fe={$accepts:ie,$packageRun:ue,name:\"BlockSchema\"},ae={$accepts:t=>!ie(t),name:\"InlineSchema\"},pe={$accepts:ie,$packageRun:t=>t,name:\"NestedBlockSchema\"},de={$accepts:ie,$packageRun:ue,name:\"RootSchema\"},he=Lt,me=new Set([\"center\",\"end\",\"justify\",\"left\",\"right\",\"start\"]);function ge(t){return me.has(t)}const ye={B:{fontWeight:\"bold\"},EM:{fontStyle:\"italic\"},I:{fontStyle:\"italic\"},S:{textDecoration:\"line-through\"},STRONG:{fontWeight:\"bold\"},SUB:{verticalAlign:\"sub\"},SUP:{verticalAlign:\"super\"},U:{textDecoration:\"underline\"}},xe={CODE:N,MARK:E},Se=new Set([\"font-weight\",\"font-style\",\"text-decoration\",\"text-transform\",\"vertical-align\"]),$e={$import:(t,e)=>{const n=t.get(Kt),o=ye[e.nodeName],r=function(t){return{fontStyle:t.style.fontStyle,fontWeight:t.style.fontWeight,textDecoration:t.style.textDecoration,textTransform:t.style.textTransform,verticalAlign:t.style.verticalAlign}}(e);var s,i;let c=n&~(l=function(t){let e=0,n=0;const{fontWeight:o,fontStyle:r,textDecoration:s,textTransform:i,verticalAlign:c}=t;if(\"700\"===o||\"bold\"===o?e|=b:\"normal\"!==o&&\"400\"!==o||(n|=b),\"italic\"===r?e|=k:\"normal\"===r&&(n|=k),s){const t=s.split(\" \");t.includes(\"underline\")&&(e|=w),t.includes(\"line-through\")&&(e|=D),t.includes(\"none\")&&(n|=w|D)}return\"lowercase\"===i?(e|=O.lowercase,n|=O.uppercase|O.capitalize):\"uppercase\"===i?(e|=O.uppercase,n|=O.lowercase|O.capitalize):\"capitalize\"===i?(e|=O.capitalize,n|=O.lowercase|O.uppercase):\"none\"===i&&(n|=O.lowercase|O.uppercase|O.capitalize),\"sub\"===c?(e|=A,n|=M):\"super\"===c?(e|=M,n|=A):\"baseline\"===c&&(n|=A|M),{clear:n,set:e}}(o?(s=o,{fontStyle:(i=r).fontStyle||s.fontStyle,fontWeight:i.fontWeight||s.fontWeight,textDecoration:i.textDecoration||s.textDecoration,textTransform:i.textTransform||s.textTransform,verticalAlign:i.verticalAlign||s.verticalAlign}):r)).clear|l.set;var l;const u=xe[e.nodeName];return u&&(c|=u),c===n?t.$importChildren(e):t.$importChildren(e,{context:[ut(Kt,c)]})},match:/* @__PURE__ */he.tag(\"b\",\"strong\",\"em\",\"i\",\"code\",\"mark\",\"s\",\"sub\",\"sup\",\"u\",\"span\"),name:\"@lexical/html/inline-format\"};function ve(t,e,n){let o=t;for(;;){let t=null;for(;null===(t=e?o.nextSibling:o.previousSibling);){const t=o.parentNode;if(null===t)return null;o=t}if(o=t,!n.isInline(o))return null;let r=o;for(;null!==(r=e?o.firstChild:o.lastChild);)o=r;if(i(o))return o;if(\"BR\"===o.nodeName)return null}}function Ce(t,e){return 0!==e&&C(t)?t.setFormat(e):t}function be(t,e){if(C(t)){const n=function(t){let e=\"\";for(const n in t)Se.has(n)||(e+=`${n}: ${t[n]}; `);return e.trimEnd()}(e);\"\"!==n&&t.setStyle(n)}return t}const ke={$import:(t,e)=>{const n=t.get(Kt),o=t.get(Yt),r=t.get(te);if(function(t,e){let n=t.parentNode;for(;null!==n;){if(e.preservesWhitespace(n))return!0;n=n.parentNode}return!1}(e,r)){const t=y(e.textContent||\"\");for(const e of t)Ce(e,n),be(e,o);return t}const s=function(t,e){let n=(t.textContent||\"\").replace(/\\r/g,\"\").replace(/[ \\t\\n]+/g,\" \");if(0===n.length)return\"\";if(\" \"===n[0]){let o=t,r=!0;for(;null!==o&&null!==(o=ve(o,!1,e));){const t=o.textContent||\"\";if(t.length>0){/[ \\t\\n]$/.test(t)&&(n=n.slice(1)),r=!1;break}}r&&(n=n.slice(1))}if(n.length>0&&\" \"===n[n.length-1]){let o=t,r=!0;for(;null!==o&&null!==(o=ve(o,!0,e));)if((o.textContent||\"\").replace(/^( |\\t|\\r?\\n)+/,\"\").length>0){r=!1;break}r&&(n=n.slice(0,-1))}return n}(e,r);if(\"\"===s)return[];const i=x(s);return Ce(i,n),be(i,o),[i]},match:/* @__PURE__ */he.text(),name:\"@lexical/html/#text\"},we={$import:()=>[],match:/* @__PURE__ */he.tag(\"script\",\"style\"),name:\"@lexical/html/script-style-ignore\"},De={$import:(t,e)=>S(e)||$(e)?[]:[v()],match:/* @__PURE__ */he.tag(\"br\"),name:\"@lexical/html/br\"},Oe={$import:(t,e)=>{const n=d();if(h(n,e),m(e,n),\"\"===n.getFormatType()){const t=e.getAttribute(\"align\");t&&ge(t)&&n.setFormat(t)}return g(n,e),[n.splice(0,0,t.$importChildren(e))]},match:/* @__PURE__ */he.tag(\"p\"),name:\"@lexical/html/p\"},Ae={$import:(t,e,n)=>o().hasNode(K)?[Y()]:n(),match:/* @__PURE__ */he.tag(\"hr\"),name:\"@lexical/html/hr\"},Me=[we,Oe,Ae,{$import:(t,e,n)=>c(e)?le(t.$importChildren(e,{schema:fe}),e):n(),match:/* @__PURE__ */he.any(),name:\"@lexical/html/transparent-block\"},ke,De,$e];function Ee(t,e){const n=[];let o=0,r=0;for(;o<t.length&&r<e.length;)t[o]<=e[r]?n.push(t[o++]):n.push(e[r++]);for(;o<t.length;)n.push(t[o++]);for(;r<e.length;)n.push(e[r++]);return n}function Ne(t){const e=[],n=new Map,o=[],r=[],s=[],i=new Set;t.forEach((t,c)=>{const l=function(t){const e=t[Mt];return void 0===e&&X(360),e}(t.match),u=t.name||function(t,e){if(\"text\"===t.kind)return`#text@${e}`;if(\"comment\"===t.kind)return`#comment@${e}`;if(0===t.tags.size)return`*@${e}`;return`${Array.from(t.tags).join(\",\").toLowerCase()}@${e}`}(l,c);if(t.name&&i.add(t.name),e.push({$import:t.$import,name:u,predicate:l.predicate}),\"text\"===l.kind)r.push(c);else if(\"comment\"===l.kind)s.push(c);else if(0===l.tags.size)o.push(c);else for(const t of l.tags){let e=n.get(t);e||(e=[],n.set(t,e)),e.push(c)}});const c=new Map;if(0===o.length)for(const[t,e]of n)c.set(t,e);else for(const[t,e]of n)c.set(t,Ee(e,o));return{byTag:c,commentIndices:s,rules:e,textIndices:r,wildcardIndices:o}}function Ie(t,e){return i(e)?t.textIndices:8===e.nodeType?t.commentIndices:n(e)?t.byTag.get(e.nodeName)||t.wildcardIndices:We}const We=/* @__PURE__ */Object.freeze([]);function Re(t){const e=[];for(const n of t)if(Te(n))for(const t of n.rules)e.push(t);else e.push(n);return e}function Te(t){return\"object\"==typeof t&&null!==t&&\"__type\"in t&&\"CompiledOverlayRules\"===t.__type}function Fe(t){const e=Re(t);return{__type:\"CompiledOverlayRules\",dispatch:Ne(e),rules:e}}const ze=/* @__PURE__ */Object.freeze({});function Pe(t,e){const n={$importChildren:(e,n)=>function(t,e,n){const o=n&&n.rules?n.rules.dispatch:void 0;o&&t.overlays.push(o);try{const o=()=>je(t,e,n);return n&&n.context?se(n.context,t.editor)(o):o()}finally{o&&t.overlays.pop()}}(t,e,n),$importOne:(e,n)=>_e(t,e,n),captures:e,get:e=>re(e,t.editor),session:t.session};return n}function je(t,e,n){const o=n&&n.$onChild,r=[];for(const n of Array.from(e.childNodes)){const e=_e(t,n,void 0);for(const t of e){const e=o?o(t):t;null!=e&&r.push(e)}}const s=n&&n.$after?n.$after(r):r,i=n&&n.schema;return i?function(t,e,n,o){const r=[];let s=null;const i=()=>{if(null===s)return;const e=s;if(s=null,t.$packageRun){const s=t.$packageRun(e,n,o);if(s.length>0){for(const t of s)r.push(t);return}}if(\"hoist\"===t.onReject)for(const t of e)r.push(t)};for(const o of e)t.$accepts(o,n)?(i(),r.push(o)):(null===s&&(s=[]),s.push(o));return i(),t.$finalize?t.$finalize(r,n):r}(i,s,null,e):s}function _e(t,e,n){const o=()=>function(t,e){const n=function(t,e){const n=[];for(let o=t.overlays.length-1;o>=0;o--){const r=t.overlays[o],s=Ie(r,e);s.length>0&&n.push({dispatch:r,indices:s})}const o=Ie(t.dispatch,e);return o.length>0&&n.push({dispatch:t.dispatch,indices:o}),n}(t,e);if(0===n.length)return Le(t,e);let o=0,r=0;const s=()=>{for(;o<n.length;){const{dispatch:i,indices:c}=n[o];for(;r<c.length;){const n=c[r++],o=i.rules[n],l={};if(o.predicate(e,l)){const n=Pe(t,0===Object.keys(l).length?ze:l);try{return o.$import(n,e,s)}catch(t){throw t}}}o++,r=0}return Le(t,e)};return s()}(t,e);return n&&n.context?se(n.context,t.editor)(o):o()}function Le(t,e){if(0===e.childNodes.length)return[];const n=[];for(const o of Array.from(e.childNodes)){const e=_e(t,o,void 0);for(const t of e)n.push(t)}return n}const Be={$import:(t,e)=>t.$importChildren(e),match:/* @__PURE__ */Lt.any(),name:\"@lexical/html/default-hoist\"},Ue={build(t,n){const o=Ne(Re(n.rules)),r=ct(n.contextDefaults,void 0),s=n.preprocess;return{$generateNodesFromDOM:(n,i)=>{const c=st(yt,t)||r,l=i&&i.context?ct(i.context,c):c,u=void 0!==l&&l!==c?l:Object.create(c||null),f=new ne(u),a={session:f};return function(t,e,n){let o=t.length-1;const r=()=>{for(;o>=0;)return void(0,t[o--])(e,n,r)};r()}(i&&i.preprocess?[...s,...i.preprocess]:s,n,a),at(yt,u,()=>function(t,n,o,r){return je({dispatch:t,editor:n,overlays:r.get(ee).map(t=>t.dispatch),session:r},e(o)?o.body:o,{schema:de})}(o,t,n,f),t)},defaults:r}},config:{contextDefaults:[],preprocess:[tt],rules:[Be]},mergeConfig:(t,e)=>I(t,{...e,...e.contextDefaults&&{contextDefaults:[...t.contextDefaults,...e.contextDefaults]},...e.preprocess&&{preprocess:[...t.preprocess,...e.preprocess]},...e.rules&&{rules:[...e.rules,...t.rules]}}),name:gt};function Ve(t,e){return Z(Ue).$generateNodesFromDOM(t,e)}const qe={dependencies:[[Ue,{rules:Me}]],name:\"@lexical/html/CoreImport\"};function Ge(t){return t}const He=[Ae],Je={any:zt,comment:Pt,css:Gt,tag:jt,text:_t};function Qe(t,e,n){return{...e,...n,nodes:t}}function Ke(t){return e=>e instanceof t}function Ye(t,{nodes:e}){if(\"*\"===e)return xt;let n={};const o=[];for(const r of e)if(\"getType\"in r){const e=r.getType();if(n){const o=t.get(e);void 0===o&&X(339,r.name,e);for(const t of o)n[t]=!0}o.push(Ke(r))}else n=void 0,o.push(r);return n||(1===o.length?o[0]:t=>{for(const e of o)if(e(t))return!0;return!1})}function Ze(t){return(e,n,o)=>t(e,o)}function Xe(t){return(e,n,o,r)=>t(e,n,r)}function tn(t){return(e,n,o,r,s)=>t(e,n,o,s)}function en(t){return(e,n,o,r,s,i)=>t(e,n,o,r,i)}function nn(t,e){return(n,o)=>{const r=()=>t(n,o),s=e(n);return s?s(n,r,o):r()}}function on(t,e){return(n,o,r)=>{const s=()=>t(n,o,r),i=e(n);return i?i(n,o,s,r):s()}}const rn=on,sn=Xe;function cn(t,e){return(n,o,r,s)=>{const i=()=>t(n,o,r,s),c=e(n);return c?c(n,o,r,i,s):i()}}function ln(t,e){return(n,o,r,s,i)=>{const c=()=>t(n,o,r,s,i),l=e(n);return l?l(n,o,r,s,c,i):c()}}function un(t,e){return(n,o,r,s)=>{t(n,o,r,s);const i=e(n);i&&i(n,o,r,s)}}function fn(t,e,n,o,r){let s=n[e];for(const n of t[e])if(\"function\"==typeof n[0]){const[t,e]=n;s=o(s,n=>t(n)&&e||void 0)}else{const t=n[1],e={};for(const n in t){const r=t[n];r&&(e[n]=r.reduce((t,e)=>o(t,()=>e),s))}s=o(s,t=>{const n=e[t.getType()];return n&&r(n)})}n[e]=s}function an(t,e,n,o){if(!o)return;const r=t[e];if(\"function\"==typeof n)r.push([n,o]);else{const t=r[r.length-1];let e;t&&\"types\"===t[0]?e=t[1]:(e={},r.push([\"types\",e]));for(const t in n){const n=e[t]||[];e[t]=n,n.push(o)}}}function pn(t){return\"*\"===t.nodes}function dn(t){return t}function hn(t,{overrides:e}){const n=function(t,e){const n=R(Q(t).nodes),o={$createDOM:[],$decorateDOM:[],$exportDOM:[],$extractWithChild:[],$getDOMSlot:[],$getSlotTargetElement:[],$shouldExclude:[],$shouldInclude:[],$updateDOM:[]};for(const t of function(t){const e=[],n=[],o=[];for(const r of t)if(pn(r))e.push(r);else if(Array.isArray(r.nodes))for(const t of r.nodes)T(t.prototype)?o.push(1===r.nodes.length?r:{...r,nodes:[t]}):n.push(1===r.nodes.length?r:{...r,nodes:[t]});const r=new Map,s=t=>{let e=r.get(t);if(void 0===e){e=-1;for(const n of F(t))e++;r.set(t,e)}return e};return o.sort((t,e)=>s(t.nodes[0])-s(e.nodes[0])),[...o,...n,...e]}(e)){const e=Ye(n,t);for(const n in o)an(o,n,e,t[n])}return o}(t,e),o={...W,...t.dom};return fn(n,\"$createDOM\",o,nn,Ze),fn(n,\"$exportDOM\",o,nn,Ze),fn(n,\"$extractWithChild\",o,ln,en),fn(n,\"$getDOMSlot\",o,rn,sn),fn(n,\"$shouldExclude\",o,on,Xe),fn(n,\"$shouldInclude\",o,on,Xe),fn(n,\"$getSlotTargetElement\",o,cn,tn),fn(n,\"$updateDOM\",o,cn,tn),fn(n,\"$decorateDOM\",o,un,dn),o}function mn(t){return{get:e=>ot(t,e)}}function gn(t){const e=Object.create(null);return ct(t,e)||e}function yn(t,e){const n=mn(e);return t.filter(t=>!(t.disabledForEditor&&t.disabledForEditor(n)))}function xn(t){if(\"*\"===t.nodes)return()=>!0;const e=t.nodes.map(t=>{const e=t;return T(e.prototype)?t=>t instanceof e:t});return t=>e.some(e=>e(t))}class Sn{editor;initialEditorConfig;overrides;editorContext;hasSessionGates;installed;sessionCache=(()=>new Map)();constructor(t,e,n,o){this.editor=t,this.initialEditorConfig=e,this.overrides=n,this.editorContext=o,this.installed=yn(n,o),this.hasSessionGates=n.some(t=>t.disabledForSession)}setContextValue(t,e){const n=this.installed;this.editorContext[t.key]=e;const o=yn(this.overrides,this.editorContext);if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(n,o))return;const r=function(t,e){const n=new Set(t),o=new Set(e),r=[];for(const e of t)o.has(e)||r.push(e);for(const t of e)n.has(t)||r.push(t);return r}(n,o);this.installed=o,this.sessionCache.clear();const s=hn(this.initialEditorConfig,{overrides:o});this.editor._config.dom=s;const i=function(t){const e=[];for(const n of t)(n.$createDOM||n.$getDOMSlot||n.$decorateDOM)&&e.push(xn(n));return 0===e.length?null:t=>e.some(e=>e(t))}(r);if(!i)return;const c=s.$updateDOM;s.$updateDOM=(t,e,n,o)=>!!i(t)||c(t,e,n,o),this.editor.update(z,{discrete:!0}),s.$updateDOM=c}getSessionConfig(){const t=this.editor._config.dom||W;if(!this.hasSessionGates)return t;const e=mn(st(mt,this.editor)||this.editorContext),n=[],o=[];if(this.installed.forEach((t,r)=>{t.disabledForSession&&t.disabledForSession(e)?n.push(String(r)):o.push(t)}),0===n.length)return t;const r=n.join(\",\");let s=this.sessionCache.get(r);return s||(s=hn(this.initialEditorConfig,{overrides:o}),this.sessionCache.set(r,s)),s}}const $n={build(t,e,n){const{initialEditorConfig:o}=n.getInitResult(),r=gn(e.contextDefaults);return{defaults:r,runtime:new Sn(t,o,e.overrides,r)}},config:{contextDefaults:[],overrides:[]},html:{export:new Map([[P,()=>{const t=j().createElement(\"div\");return t.role=\"textbox\",{element:t}}]])},init(t,e){const n={dom:t.dom,nodes:t.nodes},o=gn(e.contextDefaults),r=yn(e.overrides,o);return t.dom=hn(t,{overrides:r}),{initialEditorConfig:n}},mergeConfig(t,e){const n=I(t,e);for(const o of[\"overrides\",\"contextDefaults\"])e[o]&&(n[o]=[...t[o],...e[o]]);return n},name:ht},vn=new Set([\"STYLE\",\"SCRIPT\"]);function Cn(t,n){et(n);const o=e(n)?n.body.childNodes:n.childNodes,r=[],s=[];for(const e of o)if(!vn.has(e.nodeName)){const n=An(e,t,s,!1);if(null!==n)for(const t of n)r.push(t)}return function(t){for(const e of t)e.getParent()&&e.getNextSibling()instanceof G&&e.insertAfter(v());for(const e of t){const t=e.getParent();t&&t.splice(e.getIndexWithinParent(),1,e.getChildren())}}(s),r}function bn(t,e=null,n=o()){return At([ut(vt,!0)],n)(()=>{const o=_(),r=Ot(n),s=L(e),i=t.append.bind(t);for(const t of(u(s)?s:o).getChildren())Dn(n,t,i,e,r);return t})}function kn(t,e=_()){const n=o();return At([ut(vt,!0),ut($t,!0)],n)(()=>{const o=Ot(n),r=t.append.bind(t);return Dn(n,e,r,null,o),t})}function wn(t,e=null){return(\"undefined\"==typeof document||\"undefined\"==typeof window&&void 0===global.window)&&X(338),B(t),bn(j().createElement(\"div\"),e,t).innerHTML}function Dn(e,o,r,i=null,l=s(e)){let f=l.$shouldInclude(o,i,e);const a=l.$shouldExclude(o,i,e);let d=o;null!==i&&C(o)&&(d=t(i,o,\"clone\"));const h=l.$exportDOM(d,e),{element:m,after:g,append:y,$getChildNodes:x}=h;if(!m)return!1;const S=j().createDocumentFragment(),$=x?x():u(d)?d.getChildren():[],v=f&&U(i)&&u(o)?null:i,b=S.append.bind(S);let k=null;for(const t of $){const n=Dn(e,t,b,v,l);n&&(k=t),!f&&n&&l.$extractWithChild(o,t,i,\"html\",e)&&(f=!0)}if(f&&!a){if((n(m)||V(m))&&(y?y(S):m.append(S),function(t,e){const o=t.lastChild;if(p(e)&&n(t)&&c(t)&&null!==o&&\"BR\"===o.nodeName){const e=j().createElement(\"br\");e.setAttribute(\"data-lexical-managed-linebreak\",\"true\"),t.append(e)}}(m,k)),V(m)){if(g){const t=g.call(d,m);t&&m.replaceChildren(t)}r(m)}else if(r(m),g){const t=g.call(d,m);t&&m.replaceWith(t)}}else r(S);return f}function On(t,e,n,o=null){return Dn(t,e,n.append.bind(n),o,Ot(t))}function An(t,e,n,o,r=new Map,s){const i=[];if(vn.has(t.nodeName))return i;let a=null;const p=function(t,e){const{nodeName:n}=t,o=e._htmlConversions.get(n.toLowerCase());let r=null;if(void 0!==o)for(const e of o){const n=e(t);null!==n&&(null===r||(r.priority||0)<=(n.priority||0))&&(r=n)}return null!==r?r.conversion:null}(t,e),h=p?p(t):null;let m=null;if(null!==h){m=h.after;const e=h.node;if(a=Array.isArray(e)?e[e.length-1]:e,null!==a){for(const[,t]of r)if(a=t(a,s),!a)break;a&&i.push(...Array.isArray(e)?e:[a])}null!=h.forChild&&r.set(t.nodeName,h.forChild)}const g=t.childNodes;let y=[];const x=(null==a||!q(a))&&(null!=a&&f(a)||o);for(let t=0;t<g.length;t++)y.push(...An(g[t],e,n,x,new Map(r),a));if(null!=m&&(y=m(y)),c(t)&&(y=function(t,e,n){const o=t.style.textAlign,r=[];let s=[];for(let t=0;t<e.length;t++){const i=e[t];if(f(i))o&&!i.getFormat()&&i.setFormat(o),r.push(i);else if(s.push(i),t===e.length-1||t<e.length-1&&f(e[t+1])){const t=n();t.setFormat(o),t.append(...s),r.push(t),s=[]}}return r}(t,y,x?()=>{const t=new G;return n.push(t),t}:d)),null==a)if(y.length>0)for(const t of y)i.push(t);else c(t)&&function(t){return null!=t.nextSibling&&null!=t.previousSibling&&(l(t.nextSibling)&&l(t.previousSibling))}(t)&&i.push(v());else u(a)&&a.append(...y);return i}export{On as $appendNodeToHTML,ce as $distributeInlineWrapper,bn as $generateDOMFromNodes,kn as $generateDOMFromRoot,wn as $generateHtmlFromNodes,Cn as $generateNodesFromDOM,Ve as $generateNodesFromDOMViaExtension,re as $getImportContextValue,bt as $getRenderContextValue,Ot as $getSessionDOMRenderConfig,tt as $inlineStylesFromStyleSheets,ie as $isBlockLevel,le as $propagateTextAlignToBlockChildren,wt as $setRenderContextValue,Dt as $updateRenderContextValue,se as $withImportContext,At as $withRenderContext,fe as BlockSchema,qe as CoreImportExtension,Me as CoreImportRules,Ue as DOMImportExtension,$n as DOMRenderExtension,He as HorizontalRuleImportRules,ee as ImportOverlays,Jt as ImportSource,Qt as ImportSourceDataTransfer,Kt as ImportTextFormat,Yt as ImportTextStyle,te as ImportWhitespaceConfig,ae as InlineSchema,pe as NestedBlockSchema,vt as RenderContextExport,$t as RenderContextRoot,de as RootSchema,ft as contextUpdater,ut as contextValue,Ht as createImportState,St as createRenderState,Xt as defaultIsInline,Zt as defaultPreservesWhitespace,Ge as defineImportRule,Fe as defineOverlayRules,Qe as domOverride,Bt as isElementOfTag,Gt as parseSelector,Je as sel};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{signal as n}from\"@lexical/extension/signals\";function o(o,t={}){const i={};for(const r in o){const s=t[r],c=n(void 0===s?o[r]:s);i[r]=c}return i}export{o as namedSignals};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{sel as t,ImportOverlays as e,$isBlockLevel as n,defineOverlayRules as r,CoreImportExtension as i,DOMImportExtension as o}from\"@lexical/html\";import{getTextDirection as s,$isElementNode as l,$isTabNode as u,$isLineBreakNode as c,tokenizeRawText as a,$createTabNode as g,$createLineBreakNode as f,$getSiblingCaret as h,getterTableOf as d,setterTableOf as p,setterDefaultOf as m,aliasTableOf as _,$create as x,ElementNode as y,$getDocument as S,addClassNamesToElement as b,setDOMStyleFromCSS as v,$getEditor as C,$isTextNode as T,$createParagraphNode as N,nodeSchema as A,withAccessors as P,optional as w,stringValue as F,nullable as O,isHTMLElement as D,$applyNodeReplacement as E,TextNode as L,removeClassNamesFromElement as $,isDOMDocumentNode as B,isDOMTextNode as H,mergeRegister as k,KEY_ENTER_COMMAND as z,$getSelection as M,$isRangeSelection as K,COMMAND_PRIORITY_LOW as j,TabNode as I,$getNodeByKey as R,KEY_ARROW_DOWN_COMMAND as W,KEY_ARROW_RIGHT_COMMAND as J,KEY_ARROW_UP_COMMAND as q,KEY_ARROW_LEFT_COMMAND as U,KEY_TAB_COMMAND as V,INSERT_TAB_COMMAND as G,$insertNodes as Q,INDENT_CONTENT_COMMAND as X,OUTDENT_CONTENT_COMMAND as Y,MOVE_TO_START as Z,MOVE_TO_END as tt,$createPoint as et,$setSelectionFromCaretRange as nt,$getCaretRangeInDirection as rt,$getCaretRange as it,$getTextPointCaret as ot,$normalizeCaret as st}from\"lexical\";import{getPeerDependencyFromEditor as lt}from\"@lexical/extension/getPeerDependencyFromEditor\";import{effect as ut}from\"@lexical/extension/signals\";import{namedSignals as ct}from\"@lexical/extension/namedSignals\";import{$onEscapeDown as at,$onEscapeUp as gt}from\"@lexical/utils\";\n/*@__INLINE__*/function ft(t){return()=>{}}function ht(t,...e){throw function(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),r=new URLSearchParams;r.append(\"code\",t);for(const t of e)r.append(\"v\",t);return n.search=r.toString(),new Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(t,...e)}function dt(t,e){let n=t;for(let r=h(t,e);r&&(Gt(r.origin)||u(r.origin));r=r.getAdjacentCaret())n=r.origin;return n}function pt(t){return dt(t,\"previous\")}function mt(t){return dt(t,\"next\")}function _t(t){const e=pt(t),n=mt(t);let r=e;for(;null!==r;){if(Gt(r)){const t=s(r.getTextContent());if(null!==t)return t}if(r===n)break;r=r.getNextSibling()}const i=e.getParent();if(l(i)){const t=i.getDirection();if(\"ltr\"===t||\"rtl\"===t)return t}return null}function xt(t,e){let n=null,r=null,i=t,o=e,s=t.getTextContent();for(;;){if(0===o){const t=i.getPreviousSibling();if(null===t){i=null;break}if(Gt(t)||u(t)||c(t)||ht(167),i=t,c(i)){n={node:i,offset:1};break}o=Math.max(0,i.getTextContentSize()-1),s=i.getTextContent()}else o--;const t=s[o];Gt(i)&&\" \"!==t&&(r={node:i,offset:o})}if(null!==r)return r;let l=null;if(e<t.getTextContentSize())Gt(t)&&(l=t.getTextContent()[e]);else{const e=t.getNextSibling();Gt(e)&&(l=e.getTextContent()[0])}if(null!==l&&\" \"!==l)return n;{const r=function(t,e){let n=t,r=e,i=t.getTextContent(),o=t.getTextContentSize();for(;;){if(!Gt(n)||r===o){if(n=n.getNextSibling(),null===n||c(n))return null;Gt(n)&&(r=0,i=n.getTextContent(),o=n.getTextContentSize())}if(Gt(n)){if(\" \"!==i[r])return{node:n,offset:r};r++}}}(t,e);return null!==r?r:n}}function yt(t){const e=mt(t);return c(e)&&ht(168),e}function St(t){const e=[];return a(t,{linebreak:()=>e.push(f()),tab:()=>e.push(g()),text:t=>e.push(Vt(t))}),e}function bt(t,e,n){if(!Number.isInteger(e)||e<=0)return!1;const r=t.getTextContent(),i=/^ +/.exec(r);if(!i)return!1;const o=Math.min(e,i[0].length),s=t.getKey(),l=n.anchor.key===s&&\"text\"===n.anchor.type?n.anchor.offset:null,u=n.focus.key===s&&\"text\"===n.focus.type?n.focus.offset:null;return t.spliceText(0,o,\"\"),null!==l&&n.anchor.set(s,Math.max(0,l-o),\"text\"),null!==u&&n.focus.set(s,Math.max(0,u-o),\"text\"),!0}const vt=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function Ct(t,e){if(\"number\"==typeof t)return Number.isFinite(t)?t:e;if(\"string\"!=typeof t||!vt.test(t))return e;const n=Number(t);return Number.isFinite(n)?n:e}const Tt=t=>{const e=d(t,\"format\"),n=p(t,\"format\"),r=m(t,\"format\");return{exportJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles();return{children:[],language:t.__language,theme:t.__theme,direction:t.__dir,format:e[t.__format],indent:t.__indent,textFormat:0!==n&&i?n:void 0,textStyle:\"\"!==r&&i?r:void 0,type:t.__type,version:1}},exportCompactJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles(),o={type:t.__type,children:[]},s=t.__language;void 0!==s&&(o.language=s);const l=t.__theme;void 0!==l&&(o.theme=l);const u=t.__dir;null!=u&&(o.direction=u);const c=e[t.__format];void 0!==c&&\"\"!==c&&(o.format=c);const a=t.__indent;return void 0!==a&&0!==a&&(o.indent=a),void 0!==n&&0!==n&&i&&(o.textFormat=n),void 0!==r&&\"\"!==r&&i&&(o.textStyle=r),o},updateFromJSON:function(t,e){const i=e.direction;t.__dir=null===i||\"ltr\"===i||\"rtl\"===i?i:null;const o=e.format;t.__format=\"string\"==typeof o&&o in n?n[o]:r,t.__indent=function(t){const e=Ct(t,0);return e>=0&&e<=Infinity&&Number.isInteger(e)?e:0}(e.indent),t.__textFormat=Ct(e.textFormat,0);const s=e.textStyle;t.__textStyle=\"string\"==typeof s?s:\"\";const l=e.language;t.setLanguage(null==l||\"string\"==typeof l?l:\"\");const u=e.theme;return t.setTheme(void 0===u?void 0:\"string\"==typeof u?u:\"\"),t}}};function Nt(t,e){t.__highlightType=e.__highlightType}const At=t=>{const e=d(t,\"mode\"),n=_(t,\"detail\",0),r=_(t,\"format\",0),i=p(t,\"mode\"),o=m(t,\"mode\");return{exportJSON:function(t){return{highlightType:t.__highlightType,detail:t.__detail,format:t.__format,mode:e[t.__mode],style:t.__style,text:t.__text,type:t.__type,version:1}},exportCompactJSON:function(t){const n={type:t.__type},r=t.__highlightType;void 0!==r&&(n.highlightType=r);const i=t.__detail;void 0!==i&&0!==i&&(n.detail=i);const o=t.__format;void 0!==o&&0!==o&&(n.format=o);const s=e[t.__mode];void 0!==s&&\"normal\"!==s&&(n.mode=s);const l=t.__style;void 0!==l&&\"\"!==l&&(n.style=l);const u=t.__text;return void 0!==u&&\"\"!==u&&(n.text=u),n},updateFromJSON:function(t,e){const s=e.detail;t.__detail=\"string\"==typeof s&&s in n?n[s]:Ct(s,0);const l=e.format;t.setFormat(\"string\"==typeof l&&l in r?r[l]:Ct(l,0));const u=e.mode;t.__mode=\"string\"==typeof u&&u in i?i[u]:o;const c=e.style;t.__style=\"string\"==typeof c?c:\"\";const a=e.text;t.__text=\"string\"==typeof a?a:\"\";const g=e.highlightType;return t.setHighlightType(null==g||\"string\"==typeof g?g:\"\"),t},afterCloneFrom:Nt}},Pt=/* @__PURE__ */A()({language:/* @__PURE__ */P(/* @__PURE__ */w(/* @__PURE__ */O(/* @__PURE__ */F())),{getter:{field:\"__language\"}}),theme:/* @__PURE__ */P(/* @__PURE__ */w(/* @__PURE__ */F()),{getter:{field:\"__theme\"}})}),wt=\"javascript\",Ft=()=>wt;function Ot(t,e){for(const n of t.childNodes){if(D(n)&&n.tagName===e)return!0;if(Ot(n,e))return!0}return!1}const Dt=\"data-language\",Et=\"data-highlight-language\",Lt=\"data-theme\",$t=/* @__PURE__ */ft();class Bt extends y{__language;__theme;__isSyntaxHighlightSupported;$config(){return this.config(\"code\",{children:\"inline\",extends:y,generated:Tt,importDOM:{code:t=>null!=t.textContent&&(/\\r?\\n/.test(t.textContent)||Ot(t,\"BR\"))?{conversion:zt,priority:1}:null,div:()=>({conversion:Mt,priority:1}),pre:()=>({conversion:zt,priority:0}),table:t=>Rt(t)?{conversion:Kt,priority:3}:null,td:t=>{const e=t,n=e.closest(\"table\");return e.classList.contains(\"js-file-line\")||n&&Rt(n)?{conversion:jt,priority:3}:null},tr:t=>{const e=t.closest(\"table\");return e&&Rt(e)?{conversion:jt,priority:3}:null}},json:Pt})}constructor(t=void 0,e){super(e),this.__language=t||void 0,this.__isSyntaxHighlightSupported=!1,this.__theme=void 0}afterCloneFrom(t){super.afterCloneFrom(t),function(t,e){t.__language=e.__language,t.__theme=e.__theme}(this,t),this.__isSyntaxHighlightSupported=t.__isSyntaxHighlightSupported}createDOM(t){const e=S().createElement(\"code\");b(e,t.theme.code),e.setAttribute(\"spellcheck\",\"false\");const n=this.getLanguage();n&&(e.setAttribute(Dt,n),this.getIsSyntaxHighlightSupported()&&e.setAttribute(Et,n));const r=this.getTheme();r&&e.setAttribute(Lt,r);const i=this.getStyle();return i&&v(e.style,i),e}updateDOM(t,e,n){const r=this.__language,i=t.__language;r?r!==i&&e.setAttribute(Dt,r):i&&e.removeAttribute(Dt);const o=this.__isSyntaxHighlightSupported;t.__isSyntaxHighlightSupported&&i?o&&r?r!==i&&e.setAttribute(Et,r):e.removeAttribute(Et):o&&r&&e.setAttribute(Et,r);const s=this.__theme,l=t.__theme;s?s!==l&&e.setAttribute(Lt,s):l&&e.removeAttribute(Lt);const u=this.__style,c=t.__style;return u!==c&&v(e.style,u,c),!1}exportDOM(t){const e=S().createElement(\"pre\");b(e,t._config.theme.code),e.setAttribute(\"spellcheck\",\"false\");const n=this.getLanguage();n&&(e.setAttribute(Dt,n),this.getIsSyntaxHighlightSupported()&&e.setAttribute(Et,n));const r=this.getTheme();r&&e.setAttribute(Lt,r);const i=this.getStyle();return i&&v(e.style,i),{element:e}}insertNewAfter(t,e=!0){if(!lt(C(),\"@lexical/code\")){$t();const e=Wt(t);if(e)return e}const{anchor:n,focus:r}=t,i=(n.isBefore(r)?n:r).getNode();if(T(i)){let t=pt(i);const e=[];for(;;)if(u(t))e.push(g()),t=t.getNextSibling();else{if(!Gt(t))break;{let n=0;const r=t.getTextContent(),i=t.getTextContentSize();for(;n<i&&\" \"===r[n];)n++;if(0!==n&&e.push(Vt(\" \".repeat(n))),n!==i)break;t=t.getNextSibling()}}const r=i.splitText(n.offset)[0],o=0===n.offset?0:1,s=r.getIndexWithinParent()+o,l=i.getParentOrThrow(),c=[f(),...e];l.splice(s,0,c);const a=e[e.length-1];a?a.select():0===n.offset?r.selectPrevious():r.getNextSibling().selectNext(0,0)}if(kt(i)){const{offset:e}=t.anchor;i.splice(e,0,[f()]),i.select(e+1,e+1)}return null}canIndent(){return!1}collapseAtStart(){const t=N();return this.getChildren().forEach(e=>t.append(e)),this.replace(t),!0}setLanguage(t){const e=this.getWritable();return e.__language=t||void 0,e}getLanguage(){return this.getLatest().__language}setIsSyntaxHighlightSupported(t){const e=this.getWritable();return e.__isSyntaxHighlightSupported=t,e}getIsSyntaxHighlightSupported(){return this.getLatest().__isSyntaxHighlightSupported}setTheme(t){const e=this.getWritable();return e.__theme=t||void 0,e}getTheme(){return this.getLatest().__theme}}function Ht(t,e){return x(Bt).setLanguage(t).setTheme(e)}function kt(t){return t instanceof Bt}function zt(t){return{node:Ht(t.getAttribute(Dt),t.getAttribute(Lt))}}function Mt(t){const e=t,n=It(e);return n||function(t){let e=t.parentElement;for(;null!==e;){if(It(e))return!0;e=e.parentElement}return!1}(e)?{node:n?Ht():null}:{node:null}}function Kt(){return{node:Ht()}}function jt(){return{node:null}}function It(t){return null!==t.style.fontFamily.match(\"monospace\")}function Rt(t){return t.classList.contains(\"js-file-line-container\")}function Wt(t){const{anchor:e}=t;if(t.isCollapsed()&&\"element\"===e.type){const t=e.getNode();if(kt(t)){const n=t.getChildrenSize();if(n>=2&&e.offset===n){const e=t.getLastChild();if(c(e)&&c(e.getPreviousSibling())){const e=N();return t.splice(n-2,2,[]).insertAfter(e,!1),e.select(),e}}}}return null}const Jt=/* @__PURE__ */A()({highlightType:/* @__PURE__ */P(/* @__PURE__ */w(/* @__PURE__ */O(/* @__PURE__ */F())),{getter:{field:\"__highlightType\"}})});class qt extends L{__highlightType;constructor(t=\"\",e,n){super(t,n),this.__highlightType=e}$config(){return this.config(\"code-highlight\",{extends:L,generated:At,json:Jt})}getHighlightType(){return this.getLatest().__highlightType}setHighlightType(t){const e=this.getWritable();return e.__highlightType=t||void 0,e}canHaveFormat(){return!1}createDOM(t){const e=super.createDOM(t),n=Ut(t.theme,this.__highlightType);return b(e,n),e}updateDOM(t,e,n){const r=super.updateDOM(t,e,n),i=Ut(n.theme,t.__highlightType),o=Ut(n.theme,this.__highlightType);return i!==o&&(i&&$(e,i),o&&b(e,o)),r}setFormat(t){return this}isParentRequired(){return!0}createParentElementNode(){return Ht()}}function Ut(t,e){return e&&t&&t.codeHighlight&&t.codeHighlight[e]}function Vt(t=\"\",e){return E(new qt(t,e))}function Gt(t){return t instanceof qt}const Qt=\"data-language\",Xt=\"data-theme\";function Yt(t){const e=[];let r=!1;for(let i=0;i<t.length;i++){const o=t[i],s=n(o);i>0&&(s||r)&&e.push(\"\\n\"),e.push(o.getTextContent()),r=s}return St(e.join(\"\"))}function Zt(t){return null!==t.style.fontFamily.match(\"monospace\")}function te(t){let e=t.parentElement;for(;null!==e;){if(Zt(e))return!0;e=e.parentElement}return!1}const ee=/* @__PURE__ */r([{$import:(t,e)=>t.$importChildren(e),match:/* @__PURE__ */t.tag(\"tr\",\"td\"),name:\"@lexical/code/github-code-table/unwrap\"}]),ne={$import:(t,e)=>[Ht(e.getAttribute(Qt),e.getAttribute(Xt)).splice(0,0,Yt(t.$importChildren(e)))],match:/* @__PURE__ */t.tag(\"pre\"),name:\"@lexical/code/pre\"},re={$import:(t,e,n)=>{const r=e.textContent||\"\";return/\\r?\\n/.test(r)||null!==e.querySelector(\"br\")?[Ht(e.getAttribute(Qt),e.getAttribute(Xt)).splice(0,0,Yt(t.$importChildren(e)))]:n()},match:/* @__PURE__ */t.tag(\"code\"),name:\"@lexical/code/code-multiline\"};function ie(t){if(!D(t))return!1;const e=t.style.fontFamily,n=t.style.whiteSpace;return\"string\"==typeof e&&/monospace/i.test(e)&&\"string\"==typeof n&&n.startsWith(\"pre\")}function oe(t){let e=!1;const n=[];let r=\"\",i=!1;const o=()=>{i&&(n.push(r),r=\"\",i=!1)};for(const s of Array.from(t.childNodes))if(D(s))\"DIV\"===s.tagName?(o(),n.push(s.textContent||\"\"),e=!0):\"BR\"===s.tagName?(o(),n.push(\"\"),e=!0):(r+=s.textContent||\"\",i=!0);else if(H(s)){const t=s.textContent||\"\";t.length>0&&(r+=t,i=!0)}return o(),e?n:null}function se(t){for(const e of Array.from(t.children)){if(D(e)&&ie(e)){if(null!==oe(e))return!0;const t=e.nextElementSibling;if(t&&ie(t))return!0;continue}if(se(e))return!0}return!1}const le=/* @__PURE__ */r([{$import:(t,e,n)=>{if(!ie(e)||te(e))return n();const r=oe(e);return null===r||0===r.length?n():[Ht().splice(0,0,St(r.join(\"\\n\")))]},match:/* @__PURE__ */t.tag(\"div\"),name:\"@lexical/code/vscode-wrapper\"},{$import:(t,e,n)=>{if(!ie(e)||te(e))return n();const r=e.previousElementSibling;if(r&&ie(r))return[];const i=[];let o=e;for(;o&&ie(o);)i.push(\"BR\"===o.tagName?\"\":o.textContent||\"\"),o=o.nextElementSibling;return i.length<2?n():[Ht().splice(0,0,St(i.join(\"\\n\")))]},match:/* @__PURE__ */t.tag(\"div\",\"br\"),name:\"@lexical/code/vscode-line-run\"}]),ue={$import:(t,e,n)=>Zt(e)?[Ht().splice(0,0,Yt(t.$importChildren(e)))]:n(),match:/* @__PURE__ */t.tag(\"div\"),name:\"@lexical/code/div\"},ce=[{$import:(t,e)=>[Ht().splice(0,0,Yt(t.$importChildren(e,{rules:ee})))],match:/* @__PURE__ */t.tag(\"table\").classAll(\"js-file-line-container\"),name:\"@lexical/code/github-code-table\"},{$import:(t,e)=>t.$importChildren(e),match:/* @__PURE__ */t.tag(\"td\").classAll(\"js-file-line\"),name:\"@lexical/code/github-code-cell-by-class\"},re,ne,ue],ae={dependencies:[i,[o,{preprocess:[(t,n,r)=>{se(B(t)?t.body:t)&&n.session.update(e,t=>[...t,le]),r()}],rules:ce}]],name:\"@lexical/code\",nodes:()=>[Bt,qt],register:t=>k(t.registerCommand(z,t=>{const e=M();return!(!K(e)||!Wt(e)||(null!==t&&t.preventDefault(),0))},j),t.registerNodeTransform(I,t=>{0!==t.getFormat()&&kt(t.getParent())&&t.setFormat(0)}))};function ge(t){const e=C().getElementByKey(t.getKey());if(null===e)return;const n=t.getChildren(),r=n.length;if(r===e.__cachedChildrenLength)return;e.__cachedChildrenLength=r;let i=\"1\",o=1;for(let t=0;t<r;t++)c(n[t])&&(i+=\"\\n\"+ ++o);e.setAttribute(\"data-gutter\",i)}function fe(t){return t._headless?()=>{}:t.registerMutationListener(Bt,e=>{t.read(\"latest\",()=>{for(const[t,n]of e)if(\"destroyed\"!==n){const e=R(t);null!==e&&ge(e)}})},{skipInitialization:!1})}function he(t){if(!K(t))return!1;const e=t.anchor.getNode(),n=kt(e)?e:e.getParent(),r=t.focus.getNode(),i=kt(r)?r:r.getParent();return kt(n)&&n.is(i)}function de(t){const e=t.getNodes(),n=[];if(1===e.length&&kt(e[0]))return n;let r=[];for(let t=0;t<e.length;t++){const i=e[t];Gt(i)||u(i)||c(i)||ht(169),c(i)?r.length>0&&(n.push(r),r=[]):r.push(i)}if(r.length>0){const e=t.isBackward()?t.anchor:t.focus,i=et(r[0].getKey(),0,\"text\");e.is(i)||n.push(r)}return n}function pe(t,e){const n=M();if(!K(n)||!he(n))return!1;const r=de(n),i=r.length;if(0===i&&n.isCollapsed())return t===X?n.insertNodes([g()]):function(t,e){const n=t.anchor.getNode();if(!Gt(n)&&!u(n))return;const r=pt(n);u(r)?r.remove():void 0!==e&&Gt(r)&&bt(r,e,t)}(n,e),!0;if(0===i&&t===X&&\"\\n\"===n.getTextContent()){const t=g(),e=f(),r=n.isBackward()?\"previous\":\"next\";return n.insertNodes([t,e]),nt(rt(it(ot(t,\"next\",0),st(h(e,\"next\"))),r)),!0}for(let o=0;o<i;o++){const i=r[o];if(i.length>0){let r=i[0];if(0===o&&(r=pt(r)),t===X){const t=g();if(r.insertBefore(t),0===o){const e=n.isBackward()?\"focus\":\"anchor\",i=et(r.getKey(),0,\"text\");n[e].is(i)&&n[e].set(t.getKey(),0,\"text\")}}else u(r)?r.remove():void 0!==e&&Gt(r)&&bt(r,e,n)}}return!0}function me(t,e){const n=M();if(!K(n))return!1;const{anchor:r,focus:i}=n,o=r.offset,s=i.offset,l=r.getNode(),a=i.getNode(),g=t===q;if(!he(n)||!Gt(l)&&!u(l)||!Gt(a)&&!u(a))return!1;if(!e.altKey){if(n.isCollapsed()){const t=l.getParentOrThrow();if(g&&0===o&&null===l.getPreviousSibling()){if(null===t.getPreviousSibling())return t.selectPrevious(),e.preventDefault(),!1}else if(!g&&o===l.getTextContentSize()&&null===l.getNextSibling()&&null===t.getNextSibling())return t.selectNext(),e.preventDefault(),!1}return!1}let f,h;if(l.isBefore(a)?(f=pt(l),h=mt(a)):(f=pt(a),h=mt(l)),null==f||null==h)return!1;const d=f.getNodesBetween(h);for(let t=0;t<d.length;t++){const e=d[t];if(!Gt(e)&&!u(e)&&!c(e))return!1}e.preventDefault(),e.stopPropagation();const p=g?f.getPreviousSibling():h.getNextSibling();if(!c(p))return!0;const m=g?p.getPreviousSibling():p.getNextSibling();if(null==m)return!0;const _=c(m),x=_||!Gt(m)&&!u(m)?null:g?pt(m):mt(m);let y=null!=x?x:m;return p.remove(),d.forEach(t=>t.remove()),_?(d.forEach(t=>{y.insertAfter(t),y=t}),y.insertAfter(p)):t===q?(d.forEach(t=>y.insertBefore(t)),y.insertBefore(p)):(y.insertAfter(p),y=p,d.forEach(t=>{y.insertAfter(t),y=t})),n.setTextNodeRange(l,o,a,s),!0}function _e(t,e){const n=M();if(!K(n))return!1;const{anchor:r,focus:i}=n,o=r.getNode(),s=i.getNode(),l=t===Z;if(!he(n)||!Gt(o)&&!u(o)||!Gt(s)&&!u(s))return!1;const a=s,g=\"rtl\"===_t(a)?!l:l,f=r.key,h=r.offset,d=r.type;if(g){const t=xt(a,i.offset);if(null!==t){const{node:e,offset:r}=t;c(e)?e.selectNext(0,0):n.setTextNodeRange(e,r,e,r)}else a.getParentOrThrow().selectStart()}else yt(a).select();return e.shiftKey&&n.anchor.set(f,h,d),e.preventDefault(),e.stopPropagation(),!0}function xe(t,e,n){return k(...n?[t.registerCommand(W,t=>!t.altKey&&at(kt,t),j),t.registerCommand(J,t=>at(kt,t),j),t.registerCommand(q,t=>!t.altKey&&gt(kt,t),j),t.registerCommand(U,t=>gt(kt,t),j)]:[],t.registerCommand(V,e=>{const n=function(t){const e=M();if(!K(e)||!he(e))return null;const n=t?Y:X,r=t?Y:G,i=e.anchor,o=e.focus;if(i.is(o))return r;const s=de(e);if(1!==s.length)return n;const l=s[0];let u,c;0===l.length&&ht(285),e.isBackward()?(u=o,c=i):(u=i,c=o);const a=pt(l[0]),g=mt(l[0]),f=et(a.getKey(),0,\"text\"),h=et(g.getKey(),g.getTextContentSize(),\"text\");return u.isBefore(f)||h.isBefore(c)?n:f.isBefore(u)||c.isBefore(h)?r:n}(e.shiftKey);return null!==n&&(e.preventDefault(),t.dispatchCommand(n),!0)},j),t.registerCommand(G,()=>!!he(M())&&(Q([g()]),!0),j),t.registerCommand(X,()=>pe(X),j),t.registerCommand(Y,()=>pe(Y,e),j),t.registerCommand(q,t=>{const e=M();if(!K(e))return!1;const{anchor:n}=e,r=n.getNode();if(!he(e))return!1;const i=r.getParent();return e.isCollapsed()&&0===n.offset&&null===r.getPreviousSibling()&&kt(i)&&null===i.getPreviousSibling()?(t.preventDefault(),!0):me(q,t)},j),t.registerCommand(W,t=>{const e=M();if(!K(e))return!1;const{anchor:n}=e,r=n.getNode();return!!he(e)&&(e.isCollapsed()&&n.offset===r.getTextContentSize()&&null===r.getNextSibling()&&kt(r.getParentOrThrow())&&null===r.getParentOrThrow().getNextSibling()?(t.preventDefault(),!0):me(W,t))},j),t.registerCommand(Z,t=>_e(Z,t),j),t.registerCommand(tt,t=>_e(tt,t),j))}const ye={build:(t,e)=>ct(e),config:{disabled:!1,escapeWithArrows:!1,tabSize:void 0},dependencies:[ae],name:\"@lexical/code-indent\",register:(t,e,n)=>{const r=n.getOutput();return ut(()=>{if(!r.disabled.value)return xe(t,r.tabSize.value,r.escapeWithArrows.value)})}};export{Vt as $createCodeHighlightNode,Ht as $createCodeNode,_t as $getCodeLineDirection,yt as $getEndOfCodeInLine,pt as $getFirstCodeNodeOfLine,mt as $getLastCodeNodeOfLine,xt as $getStartOfCodeInLine,Gt as $isCodeHighlightNode,kt as $isCodeNode,bt as $outdentLeadingSpaces,St as $plainifyCodeContent,ae as CodeExtension,qt as CodeHighlightNode,ce as CodeImportRules,ye as CodeIndentExtension,Bt as CodeNode,wt as DEFAULT_CODE_LANGUAGE,Ft as getDefaultCodeLanguage,fe as registerCodeGutter,xe as registerCodeIndentation};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{AriaLiveRegionExtension as t}from\"@lexical/a11y\";import{effect as e,signal as n}from\"@lexical/extension/signals\";import{namedSignals as r}from\"@lexical/extension/namedSignals\";import{getterTableOf as i,setterTableOf as l,setterDefaultOf as o,ElementNode as s,$getDocument as u,addClassNamesToElement as a,isHTMLAnchorElement as c,$copyNode as g,$isRangeSelection as f,$applyNodeReplacement as d,createCommand as _,$getSelection as h,$isNodeSelection as p,$findMatchingParent as m,nodeSchema as x,withField as y,stringValue as v,nullable as k,booleanValue as b,$normalizeSelection__EXPERIMENTAL as U,$setSelection as S,INTERNAL_isNodeStructureEnforced as T,$getEditor as L,$getChildCaret as C,$isElementNode as A,$insertNodeToNearestRootAtCaret as N,$rewindSiblingCaret as R,$caretFromPoint as P,getDeclaredNodeStructure as w,$normalizeCaret as O,$isSiblingCaret as I,$setPointFromCaret as F,shallowMergeConfig as D,mergeRegister as M,COMMAND_PRIORITY_EDITOR as E,PASTE_COMMAND as W,$isTextNode as z,COMMAND_PRIORITY_LOW as $,registerEventListeners as j,isDOMNode as B,getNearestEditorFromDOMNode as K,$getNearestNodeFromDOMNode as J,TextNode as Z,$isLineBreakNode as H,$createTextNode as G}from\"lexical\";import{sel as q,$distributeInlineWrapper as Q,CoreImportExtension as V,DOMImportExtension as X}from\"@lexical/html\";import{objectKlassEquals as Y}from\"@lexical/utils\";const tt=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function et(t,e){if(\"number\"==typeof t)return Number.isFinite(t)?t:e;if(\"string\"!=typeof t||!tt.test(t))return e;const n=Number(t);return Number.isFinite(n)?n:e}function nt(t,e,n,r,i){const l=et(t,e);return l>=n&&l<=r&&Number.isInteger(l)?l:e}function rt(t,e){t.__rel=e.__rel,t.__target=e.__target,t.__title=e.__title,t.__url=e.__url}const it=t=>{const e=i(t,\"format\"),n=l(t,\"format\"),r=o(t,\"format\");return{exportJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles();return{children:[],rel:t.__rel,target:t.__target,title:t.__title,url:t.__url,direction:t.__dir,format:e[t.__format],indent:t.__indent,textFormat:0!==n&&i?n:void 0,textStyle:\"\"!==r&&i?r:void 0,type:t.__type,version:1}},exportCompactJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles(),l={type:t.__type,children:[]},o=t.__rel;null!=o&&(l.rel=o);const s=t.__target;null!=s&&(l.target=s);const u=t.__title;null!=u&&(l.title=u);const a=t.__url;void 0!==a&&\"\"!==a&&(l.url=a);const c=t.__dir;null!=c&&(l.direction=c);const g=e[t.__format];void 0!==g&&\"\"!==g&&(l.format=g);const f=t.__indent;return void 0!==f&&0!==f&&(l.indent=f),void 0!==n&&0!==n&&i&&(l.textFormat=n),void 0!==r&&\"\"!==r&&i&&(l.textStyle=r),l},updateFromJSON:function(t,e){const i=e.direction;t.__dir=null===i||\"ltr\"===i||\"rtl\"===i?i:null;const l=e.format;t.__format=\"string\"==typeof l&&l in n?n[l]:r,t.__indent=nt(e.indent,0,0,Infinity),t.__textFormat=et(e.textFormat,0);const o=e.textStyle;t.__textStyle=\"string\"==typeof o?o:\"\";const s=e.rel;t.__rel=\"string\"==typeof s&&\"\"!==s?s:null;const u=e.target;t.__target=\"string\"==typeof u&&\"\"!==u?u:null;const a=e.title;t.__title=\"string\"==typeof a&&\"\"!==a?a:null;const c=e.url;return t.__url=\"string\"==typeof c?c:\"\",t},afterCloneFrom:rt}};function lt(t,e){t.__isUnlinked=e.__isUnlinked}const ot=t=>{const e=i(t,\"format\"),n=l(t,\"format\"),r=o(t,\"format\");return{exportJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles();return{children:[],isUnlinked:t.__isUnlinked,rel:t.__rel,target:t.__target,title:t.__title,url:t.__url,direction:t.__dir,format:e[t.__format],indent:t.__indent,textFormat:0!==n&&i?n:void 0,textStyle:\"\"!==r&&i?r:void 0,type:t.__type,version:1}},exportCompactJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles(),l={type:t.__type,children:[]},o=t.__isUnlinked;void 0!==o&&!1!==o&&(l.isUnlinked=o);const s=t.__rel;null!=s&&(l.rel=s);const u=t.__target;null!=u&&(l.target=u);const a=t.__title;null!=a&&(l.title=a);const c=t.__url;void 0!==c&&\"\"!==c&&(l.url=c);const g=t.__dir;null!=g&&(l.direction=g);const f=e[t.__format];void 0!==f&&\"\"!==f&&(l.format=f);const d=t.__indent;return void 0!==d&&0!==d&&(l.indent=d),void 0!==n&&0!==n&&i&&(l.textFormat=n),void 0!==r&&\"\"!==r&&i&&(l.textStyle=r),l},updateFromJSON:function(t,e){const i=e.direction;t.__dir=null===i||\"ltr\"===i||\"rtl\"===i?i:null;const l=e.format;t.__format=\"string\"==typeof l&&l in n?n[l]:r,t.__indent=nt(e.indent,0,0,Infinity),t.__textFormat=et(e.textFormat,0);const o=e.textStyle;t.__textStyle=\"string\"==typeof o?o:\"\";const s=e.rel;t.__rel=\"string\"==typeof s&&\"\"!==s?s:null;const u=e.target;t.__target=\"string\"==typeof u&&\"\"!==u?u:null;const a=e.title;t.__title=\"string\"==typeof a&&\"\"!==a?a:null;const c=e.url;t.__url=\"string\"==typeof c?c:\"\";const g=e.isUnlinked;return t.__isUnlinked=\"boolean\"==typeof g&&g,t},afterCloneFrom:lt}},st=new Set([\"http:\",\"https:\",\"mailto:\",\"sms:\",\"tel:\"]),ut=/* @__PURE__ */x()({rel:/* @__PURE__ */y(/* @__PURE__ */k(/* @__PURE__ */v(),{defaultAsNull:!0}),{field:\"__rel\"}),target:/* @__PURE__ */y(/* @__PURE__ */k(/* @__PURE__ */v(),{defaultAsNull:!0}),{field:\"__target\"}),title:/* @__PURE__ */y(/* @__PURE__ */k(/* @__PURE__ */v(),{defaultAsNull:!0}),{field:\"__title\"}),url:/* @__PURE__ */y(/* @__PURE__ */v(),{field:\"__url\",getter:\"getURL\",setter:\"setURL\"})});class at extends s{__url;__target;__rel;__title;$config(){return this.config(\"link\",{children:\"inline\",extends:s,generated:it,importDOM:{a:()=>({conversion:_t,priority:1})},inline:!0,json:ut,mergeAdjacent:{by:[\"url\",\"target\",\"rel\",\"title\"]}})}constructor(t=\"\",e={},n){super(n);const{target:r=null,rel:i=null,title:l=null}=e;this.__url=t,this.__target=r,this.__rel=i,this.__title=l}createDOM(t){const e=u().createElement(\"a\");return this.updateLinkDOM(null,e,t),a(e,t.theme.link),e}updateLinkDOM(t,e,n){if(c(e)){t&&t.__url===this.__url||(e.href=this.sanitizeUrl(this.__url));for(const n of[\"target\",\"rel\",\"title\"]){const r=`__${n}`,i=this[r];t&&t[r]===i||(i?e[n]=i:e.removeAttribute(n))}}}updateDOM(t,e,n){return this.updateLinkDOM(t,e,n),!1}sanitizeUrl(t){const e=t;t=Tt(t);try{const e=new URL(Tt(t));if(!st.has(e.protocol))return\"about:blank\"}catch{const t=e.replace(/[\\u0000-\\u001F\\u007F\\s]/g,\"\").match(/^([a-z][a-z0-9+.-]*):/i);if(null!=t&&!st.has(`${t[1].toLowerCase()}:`))return\"about:blank\"}return t}getURL(){return this.getLatest().__url}setURL(t){const e=this.getWritable();return e.__url=t,e}getTarget(){return this.getLatest().__target}setTarget(t){const e=this.getWritable();return e.__target=t,e}getRel(){return this.getLatest().__rel}setRel(t){const e=this.getWritable();return e.__rel=t,e}getTitle(){return this.getLatest().__title}setTitle(t){const e=this.getWritable();return e.__title=t,e}insertNewAfter(t,e=!0){const n=g(this);return this.insertAfter(n,e),n}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}canBeEmpty(){return!1}isInline(){return!0}extractWithChild(t,e,n){if(!f(e))return!1;const r=e.anchor.getNode(),i=e.focus.getNode();return(this.is(r)||this.isParentOf(r))&&(this.is(i)||this.isParentOf(i))&&e.getTextContent().length>0}isEmailURI(){return this.getURL().startsWith(\"mailto:\")}isWebSiteURI(){const t=this.getURL();return t.startsWith(\"https://\")||t.startsWith(\"http://\")}shouldMergeAdjacentLink(t){return this.getType()===t.getType()&&this.getURL()===t.getURL()&&this.getTarget()===t.getTarget()&&this.getRel()===t.getRel()&&this.getTitle()===t.getTitle()}}function ct(t){const e=P(t,\"next\");return[e,e.getFlipped()]}function gt(t,e){for(const n of e)if(n.origin.isAttached()){const e=O(n);return void F(t,e)}}function ft(t,e){const n=t.constructor;return e.constructor===n&&T(L())&&w(n).declaredBy.mergeAdjacent===n}function dt(t){const e=h();let n=null,r=null;function i(){f(e)&&(gt(e.anchor,n),gt(e.focus,r),U(e))}f(e)&&(n=ct(e.anchor),r=ct(e.focus));let l=!1;const o=!T(L());for(const e of o?C(t,\"next\"):[]){const n=e.origin;if(A(n)&&!n.isInline()){const r=n.getChildren();if(r.length>0){const e=g(t);e.append(...r),n.append(e),l=!0}N(n,R(e),{$shouldSplit:()=>!1})}}function s(t,e,n){const[r,i]=t,l=t=>I(t)&&t.origin.is(e);if(!l(r)&&!l(i))return t;const o=O(C(n,\"next\"));return[o,o.getFlipped()]}if(t.isAttached()){const e=t.getPreviousSibling();if(pt(e)&&!ft(e,t)&&e.shouldMergeAdjacentLink(t))return n&&(n=s(n,e,t)),r&&(r=s(r,e,t)),e.append(...t.getChildren()),t.remove(),void i();const o=t.getNextSibling();pt(o)&&!ft(t,o)&&t.shouldMergeAdjacentLink(o)&&(n&&(n=s(n,t,o)),r&&(r=s(r,t,o)),t.append(...o.getChildren()),o.remove(),l=!0)}if(l){if(!t.canBeEmpty()&&t.isEmpty()){const e=t.getParent();t.remove(),e&&e.isEmpty()&&e.remove()}i()}}function _t(t){let e=null;if(c(t)){const n=t.textContent;(null!==n&&\"\"!==n||t.children.length>0)&&(e=ht(t.getAttribute(\"href\")||\"\",{rel:t.getAttribute(\"rel\"),target:t.getAttribute(\"target\"),title:t.getAttribute(\"title\")}))}return{node:e}}function ht(t=\"\",e){return d(new at(t,e))}function pt(t){return t instanceof at}const mt=/* @__PURE__ */x()({isUnlinked:/* @__PURE__ */y(/* @__PURE__ */b(),{field:\"__isUnlinked\"})});class xt extends at{__isUnlinked;constructor(t=\"\",e={},n){super(t,e,n),this.__isUnlinked=void 0!==e.isUnlinked&&null!==e.isUnlinked&&e.isUnlinked}$config(){return this.config(\"autolink\",{extends:at,generated:ot,json:mt,mergeAdjacent:!1})}shouldMergeAdjacentLink(t){return!1}getIsUnlinked(){return this.getLatest().__isUnlinked}setIsUnlinked(t){const e=this.getWritable();return e.__isUnlinked=t,e}createDOM(t){return this.__isUnlinked?u().createElement(\"span\"):super.createDOM(t)}updateDOM(t,e,n){return super.updateDOM(t,e,n)||t.__isUnlinked!==this.__isUnlinked}}function yt(t=\"\",e){return d(new xt(t,e))}function vt(t){return t instanceof xt}const kt=/* @__PURE__ */_(\"TOGGLE_LINK_COMMAND\");function bt(t,e){if(\"element\"===t.type){const n=t.getNode();return A(n)||function(t,...e){throw function(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),r=new URLSearchParams;r.append(\"code\",t);for(const t of e)r.append(\"v\",t);return n.search=r.toString(),new Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(t,...e)}(252),n.getChildren()[t.offset+e]||null}return null}function Ut(t,e={}){let n;if(t&&\"object\"==typeof t){const{url:r,...i}=t;n=r,e={...i,...e}}else n=t;const{target:r,title:i}=e,l=void 0===e.rel?\"noreferrer\":e.rel,o=h();if(null===o||!f(o)&&!p(o))return;if(p(o)){const t=o.getNodes();if(0===t.length)return;return void t.forEach(t=>{if(null===n){const e=m(t,t=>!vt(t)&&pt(t));e&&(e.insertBefore(t),0===e.getChildren().length&&e.remove())}else{const e=m(t,t=>!vt(t)&&pt(t));if(e)e.setURL(n),void 0!==r&&e.setTarget(r),void 0!==l&&e.setRel(l),void 0!==i&&e.setTitle(i);else{const e=ht(n,{rel:l,target:r,title:i});t.insertBefore(e),e.append(t)}}})}if(o.isCollapsed()&&null===n)for(const t of o.getNodes()){const e=m(t,t=>!vt(t)&&pt(t));return void(null!==e&&(e.getParentOrThrow().splice(e.getIndexWithinParent(),0,e.getChildren()),e.remove()))}const s=o.extract();if(null===n){const t=new Set;return void s.forEach(e=>{const n=m(e,t=>!vt(t)&&pt(t));if(null!==n){const e=n.getKey();if(t.has(e))return;!function(t,e){const n=new Set(e.filter(e=>t.isParentOf(e)).map(t=>t.getKey())),r=t.getChildren(),i=r=>n.has(r.getKey())||A(r)&&e.some(e=>t.isParentOf(e)&&r.isParentOf(e)),l=r.filter(i);if(0===l.length&&r.length>0)return;if(l.length===r.length)return r.forEach(e=>t.insertBefore(e)),void t.remove();const o=r.findIndex(i),s=r.findLastIndex(i),u=0===o,a=s===r.length-1;if(u)l.forEach(e=>t.insertBefore(e));else if(a)for(let e=l.length-1;e>=0;e--)t.insertAfter(l[e]);else{for(let e=l.length-1;e>=0;e--)t.insertAfter(l[e]);const e=r.slice(s+1);if(e.length>0){const n=g(t);l[l.length-1].insertAfter(n),e.forEach(t=>n.append(t))}}}(n,s),t.add(e)}})}const u=new Set,a=t=>{u.has(t.getKey())||(u.add(t.getKey()),t.setURL(n),void 0!==r&&t.setTarget(r),void 0!==l&&t.setRel(l),void 0!==i&&t.setTitle(i))};if(1===s.length){const t=s[0],e=m(t,pt);if(null!==e)return a(e)}!function(t){const e=h();if(!f(e))return t();const n=U(e),r=n.isBackward(),i=bt(n.anchor,r?-1:0),l=bt(n.focus,r?0:-1);t();if(i||l){const t=h();if(f(t)){const e=t.clone();if(i){const t=i.getParent();t&&e.anchor.set(t.getKey(),i.getIndexWithinParent()+(r?1:0),\"element\")}if(l){const t=l.getParent();t&&e.focus.set(t.getKey(),l.getIndexWithinParent()+(r?0:1),\"element\")}S(U(e))}}}(()=>{let t=null;for(const e of s){if(!e.isAttached())continue;const o=m(e,pt);if(o){a(o);continue}if(A(e)){if(!e.isInline())continue;if(pt(e)){if(!(vt(e)||null!==t&&t.getParentOrThrow().isParentOf(e))){a(e),t=e;continue}for(const t of e.getChildren())e.insertBefore(t);e.remove();continue}}const s=e.getPreviousSibling();pt(s)&&s.is(t)?s.append(e):(t=ht(n,{rel:l,target:r,title:i}),e.insertAfter(t),t.append(e))}})}const St=/^\\+?[0-9\\s()-]{5,}$/;function Tt(t){return t.match(/^[a-z][a-z0-9+.-]*:/i)||t.match(/^[/#.]/)?t:t.includes(\"@\")?`mailto:${t}`:St.test(t)?`tel:${t}`:`https://${t}`}const Lt={build:(t,e)=>r(e),config:{created:\"Link\",createdMany:\"%s links\",destroyed:\"Link removed\",destroyedMany:\"%s links removed\",disabled:!1},dependencies:[t],name:\"@lexical/link/AutoLinkAnnounce\",register(n,r,i){const{created:l,createdMany:o,destroyed:s,destroyedMany:u,disabled:a}=i.getOutput(),{announce:c}=i.getDependency(t).output;return e(()=>a.value?void 0:n.registerMutationListener(xt,t=>{let e=0,n=0;for(const[,r]of t)\"created\"===r?e++:\"destroyed\"===r&&n++;e>0&&0===n?c(1===e?l.peek():o.peek().replace(\"%s\",String(e))):n>0&&0===e&&c(1===n?s.peek():u.peek().replace(\"%s\",String(n)))},{skipInitialization:!0}))}},Ct=[{$import:(t,e)=>{if(!e.textContent&&0===e.children.length)return[];const n=e.getAttribute(\"href\")||\"\",r={rel:e.getAttribute(\"rel\"),target:e.getAttribute(\"target\"),title:e.getAttribute(\"title\")};return Q(t.$importChildren(e),()=>ht(n,r))},match:/* @__PURE__ */q.tag(\"a\"),name:\"@lexical/link/a\"}];function At(t,n){return M(t.registerNodeTransform(at,dt),t.registerCommand(kt,t=>{const e=n.validateUrl.peek(),r=n.attributes.peek();if(null===t)return Ut(null),!0;if(\"string\"==typeof t)return!(void 0!==e&&!e(t)||(Ut(t,r),0));{const{url:n,...i}=t;return!(void 0!==e&&!e(n)||(Ut(n,{...r,...i}),0))}},E),e(()=>{const e=n.validateUrl.value;if(!e)return;const r=n.attributes.value;return t.registerCommand(W,n=>{const i=h();if(!f(i)||i.isCollapsed()||!Y(n,ClipboardEvent))return!1;if(null===n.clipboardData)return!1;const l=n.clipboardData.getData(\"text\");return!!e(l)&&(!i.getNodes().some(t=>A(t)||z(t)&&!t.isSimpleText())&&(t.dispatchCommand(kt,{...r,url:l}),n.preventDefault(),!0))},$)}))}const Nt={build:(t,e,n)=>r(e),config:{attributes:void 0,validateUrl:void 0},dependencies:[V,[X,{rules:Ct}]],mergeConfig(t,e){const n=D(t,e);return t.attributes&&(n.attributes=D(t.attributes,n.attributes)),n},name:\"@lexical/link/Link\",nodes:()=>[at],register:(t,e,n)=>At(t,n.getOutput())};function Rt(){return window}function Pt(t,e,r={}){const i=e.getWindow??n(Rt),l=n=>{const r=1===n.button;if(\"auxclick\"===n.type&&!r)return;const l=n.target;if(!B(l))return;const o=K(l);if(o!==t)return;let s=null,u=null,a=!1;if(o.update(()=>{const t=J(l);if(null!==t){const n=m(t,A);if(!e.disabled.peek())if(pt(n))a=vt(n)&&n.getIsUnlinked(),s=n.sanitizeUrl(n.getURL()),u=n.getTarget();else{const t=function(t,e){let n=t;for(;null!=n;){if(e(n))return n;n=n.parentNode}return null}(l,c);null!==t&&(s=t.href,u=t.target)}}}),null===s||\"\"===s||a)return;const g=t.read(\"latest\",h);if(f(g)&&!g.isCollapsed())return void n.preventDefault();const d=e.newTab.peek()||r||n.metaKey||n.ctrlKey||\"_blank\"===u,_=i.peek()(t);null!==_&&(_.open(s,...d?[\"_blank\",\"noopener\"]:[\"_self\"]),n.preventDefault())};return t.registerRootListener(t=>{if(t)return j(t,{auxclick:l,click:l},r)})}const wt={build:(t,e,n)=>r(e),config:{disabled:!1,getWindow:Rt,newTab:!1},dependencies:[Nt],name:\"@lexical/link/ClickableLink\",register:(t,e,n)=>Pt(t,n.getOutput())};function Ot(t,e=t=>t){return n=>{const r=t.exec(n);return null===r?null:{index:r.index,length:r[0].length,text:r[0],url:e(r[0])}}}const It=/((https?:\\/\\/(www\\.)?)|(www\\.))[-\\p{L}\\p{N}@:%._+~#=]{1,256}\\.[\\p{L}\\p{N}]{1,6}(?:[-\\p{L}\\p{N}()@:%_+.~#?&//=]*[\\p{L}\\p{N}()@_~#?&//=])?/u,Ft=t=>{const e=It.exec(t);if(null===e)return null;let n=e[0],r=0;for(const t of n)\"(\"===t?r++:\")\"===t&&r--;for(;r<0&&n.endsWith(\")\");)n=n.slice(0,-1),r++;return{index:e.index,length:n.length,text:n,url:n.startsWith(\"http\")?n:`https://${n}`}},Dt=/* @__PURE__ */Ot(/(([^<>()[\\]\\\\.,;:\\s@\"]{1,64}(\\.[^<>()[\\]\\\\.,;:\\s@\"]{1,64}){0,63})|(\".{1,255}\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]{1,63}\\.){1,127}[a-zA-Z]{2,63}))/,t=>`mailto:${t}`);function Mt(t,e){for(let n=0;n<e.length;n++){const r=e[n](t);if(r)return r}return null}const Et=/[.,;\\s]/;function Wt(t,e){return e.test(t)}function zt(t,e){return Wt(t[t.length-1],e)}function $t(t,e){return Wt(t[0],e)}function jt(t,e){let n=t.getPreviousSibling();return A(n)&&(n=n.getLastDescendant()),null===n||H(n)||z(n)&&zt(n.getTextContent(),e)}function Bt(t,e){let n=t.getNextSibling();return A(n)&&(n=n.getFirstDescendant()),null===n||H(n)||z(n)&&$t(n.getTextContent(),e)}function Kt(t,e,n,r,i){return!!(t>0?Wt(r[t-1],n):jt(i[0],n))&&(e<r.length?Wt(r[e],n):Bt(i[i.length-1],n))}function Jt(t,e,n){const r=[],i=[],l=[];let o=0,s=0;const u=[...t];for(;u.length>0;){const t=u[0],a=t.getTextContent().length,c=s;s+a<=e?(r.push(t),o+=a):c>=n?l.push(t):i.push(t),s+=a,u.shift()}return[o,r,i,l]}function Zt(t,e,n,r){const i=yt(r.url,r.attributes);if(1===t.length){let l,o=t[0];0===e?[l,o]=o.splitText(n):[,l,o]=o.splitText(e,n);const s=G(r.text);return s.setFormat(l.getFormat()),s.setDetail(l.getDetail()),s.setStyle(l.getStyle()),i.append(s),l.replace(i),o}if(t.length>1){const r=t[0];let l,o=r.getTextContent().length;0===e?l=r:[,l]=r.splitText(e);const s=[];let u;for(let e=1;e<t.length;e++){const r=t[e],i=r.getTextContent().length,l=o;if(l<n)if(o+i<=n)s.push(r);else{const[t,e]=r.splitText(n-l);s.push(t),u=e}o+=i}const a=h(),c=a?a.getNodes().find(z):void 0,g=G(l.getTextContent());return g.setFormat(l.getFormat()),g.setDetail(l.getDetail()),g.setStyle(l.getStyle()),i.append(g,...s),c&&c===l&&(f(a)?g.select(a.anchor.offset,a.focus.offset):p(a)&&g.select(0,g.getTextContent().length)),l.replace(i),u}}function Ht(t,e,n,r){const i=t.getChildren(),l=i.length;for(let e=0;e<l;e++){const r=i[e];if(!z(r)||!r.isSimpleText())return Gt(t),void n(null,t.getURL())}const o=t.getTextContent(),s=Mt(o,e);if(null===s||s.text!==o)return Gt(t),void n(null,t.getURL());if(!jt(t,r)||!Bt(t,r))return Gt(t),void n(null,t.getURL());const u=t.getURL();u!==s.url&&(t.setURL(s.url),n(s.url,u)),s.attributes&&(t.getRel()!==s.attributes.rel&&t.setRel(s.attributes.rel||null),t.getTarget()!==s.attributes.target&&t.setTarget(s.attributes.target||null),t.getTitle()!==s.attributes.title&&t.setTitle(s.attributes.title||null))}function Gt(t){const e=t.getChildren();for(let n=e.length-1;n>=0;n--)t.insertAfter(e[n]);return t.remove(),e.map(t=>t.getLatest())}const qt={changeHandlers:[],excludeParents:[],matchers:[],separatorRegex:Et};function Qt(t,e=qt){const{matchers:n,changeHandlers:r,excludeParents:i,separatorRegex:l=Et}=e,o=(t,e)=>{for(const n of r)n(t,e)};return M(t.registerNodeTransform(Z,t=>{const e=t.getParentOrThrow(),r=t.getPreviousSibling();if(vt(e))Ht(e,n,o,l);else if(!pt(e)&&!i.some(t=>t(e))){if(t.isSimpleText()&&($t(t.getTextContent(),l)||!vt(r))){const e=function(t){const e=[t];let n=t.getNextSibling();for(;null!==n&&z(n)&&n.isSimpleText()&&(e.push(n),!/[\\s]/.test(n.getTextContent()));)n=n.getNextSibling();return e}(t);!function(t,e,n,r){for(const e of t){const t=e.getParent();if(vt(t)&&!t.getIsUnlinked())return}let i=[...t];const l=i.map(t=>t.getTextContent()).join(\"\");let o,s=l,u=0;for(;(o=Mt(s,e))&&null!==o;){const t=o.index,e=t+o.length;if(Kt(u+t,u+e,r,l,i)){const[r,,l,a]=Jt(i,u+t,u+e);let c=!1;for(const t of l){const e=t.getParent();if(vt(e)&&!e.getIsUnlinked()){c=!0;break}}if(c){u+=e,s=s.substring(e);continue}const g=Zt(l,u+t-r,u+e-r,o);i=g?[g,...a]:a,n(o.url,null),u=0}else u+=e;s=s.substring(e)}}(e,n,o,l)}!function(t,e,n,r){const i=t.getParent(),l=t.getPreviousSibling(),o=t.getNextSibling(),s=t.getTextContent();if(!vt(i)||i.getIsUnlinked()){if(vt(l)&&!l.getIsUnlinked()&&l.is(t.getPreviousSibling())&&t.getParent()===l.getParent()){if(!$t(s,r))return Gt(l),void n(null,l.getURL());if(u=s,l.isEmailURI()?/^\\.[a-zA-Z]{2,}/.test(u):/^\\.[a-zA-Z0-9]{1,}/.test(u)){const i=l.getTextContent()+s,o=Mt(i,e);null!==o&&o.text===i&&(l.append(t),Ht(l,e,n,r),n(null,l.getURL()))}}var u;!vt(o)||o.getIsUnlinked()||zt(s,r)||o.is(t.getNextSibling())&&t.getParent()===o.getParent()&&(Gt(o),n(null,o.getURL()))}}(t,n,o,l)}}),t.registerCommand(kt,t=>{const e=h();return!(null!==t||!f(e))&&(e.extract().forEach(t=>{const e=t.getParent();vt(e)&&(e.setIsUnlinked(!e.getIsUnlinked()),e.markDirty())}),!1)},$))}const Vt={config:qt,dependencies:[Lt,Nt],mergeConfig(t,e){const n=D(t,e);for(const r of[\"matchers\",\"changeHandlers\",\"excludeParents\"]){const i=e[r];Array.isArray(i)&&(n[r]=[...t[r],...i])}return n},name:\"@lexical/link/AutoLink\",nodes:[xt],register:Qt};export{yt as $createAutoLinkNode,ht as $createLinkNode,vt as $isAutoLinkNode,pt as $isLinkNode,Ut as $toggleLink,Lt as AutoLinkAnnounceExtension,Vt as AutoLinkExtension,xt as AutoLinkNode,wt as ClickableLinkExtension,Nt as LinkExtension,Ct as LinkImportRules,at as LinkNode,kt as TOGGLE_LINK_COMMAND,Dt as autoLinkEmailMatcher,Ft as autoLinkUrlMatcher,Ot as createLinkMatcherWithRegExp,Tt as formatUrl,Qt as registerAutoLink,Pt as registerClickableLink,At as registerLink};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{$getNearestNodeOfType as t,calculateZoomLevel as e}from\"@lexical/utils\";import{$getSelection as n,$isRangeSelection as r,$isTextNode as i,$isRootOrShadowRoot as s,$createParagraphNode as o,$copyNode as l,$isElementNode as c,$getSlotHost as a,$isLeafNode as u,$setPointFromCaret as f,$normalizeCaret as g,$getChildCaretAtIndex as d,ElementNode as h,getterTableOf as p,setterTableOf as m,setterDefaultOf as _,aliasTableOf as y,$applyNodeReplacement as C,buildImportMap as S,$getDocument as v,isHTMLElement as x,nodeSchema as b,withAccessors as k,enumValue as T,withField as L,numberValue as N,aliasedValue as F,$setDirectionFromDOM as P,INTERNAL_isNodeStructureEnforced as A,$getEditor as I,getDeclaredNodeStructure as E,normalizeClassNames as O,removeClassNamesFromElement as M,addClassNamesToElement as w,$getSiblingCaret as D,$insertNodeToNearestRootAtCaret as $,$rewindSiblingCaret as R,setDOMStyleFromCSS as K,$isParagraphNode as W,optional as z,booleanValue as B,$setFormatFromDOM as U,getStyleObjectFromCSS as q,createCommand as j,mergeRegister as V,COMMAND_PRIORITY_LOW as J,KEY_ARROW_DOWN_COMMAND as H,KEY_ARROW_UP_COMMAND as X,KEY_ESCAPE_COMMAND as G,KEY_SPACE_COMMAND as Z,$getNearestNodeFromDOMNode as Q,KEY_ARROW_LEFT_COMMAND as Y,$findMatchingParent as tt,getActiveElement as et,registerEventListeners as nt,IS_FIREFOX as rt,registerEventListener as it,getNearestEditorFromDOMNode as st,$addUpdateTag as ot,SKIP_SELECTION_FOCUS_TAG as lt,SKIP_DOM_SELECTION_TAG as ct,$createLineBreakNode as at,$getNodeByKey as ut,INSERT_PARAGRAPH_COMMAND as ft,KEY_BACKSPACE_COMMAND as gt,COMMAND_PRIORITY_BEFORE_EDITOR as dt,TextNode as ht}from\"lexical\";import{effect as pt}from\"@lexical/extension/signals\";import{namedSignals as mt}from\"@lexical/extension/namedSignals\";import{sel as _t,isElementOfTag as yt,$propagateTextAlignToBlockChildren as Ct,$isBlockLevel as St,CoreImportExtension as vt,DOMImportExtension as xt,ImportOverlays as bt,defineOverlayRules as kt,createImportState as Tt,InlineSchema as Lt}from\"@lexical/html\";function Nt(t,...e){throw function(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),r=new URLSearchParams;r.append(\"code\",t);for(const t of e)r.append(\"v\",t);return n.search=r.toString(),new Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(t,...e)}function Ft(t){let e=1,n=t.getParent();for(;null!=n;){if(fe(n)){const t=n.getParent();if(ie(t)){e++,n=t.getParent();continue}Nt(40)}return e}return e}function Pt(t){const e=t.getParent();ie(e)||Nt(40);let n=e,r=e;for(;null!==r;)r=r.getParent(),ie(r)&&(n=r);return n}function At(t){let e=[];const n=t.getChildren().filter(fe);for(let t=0;t<n.length;t++){const r=n[t],i=r.getFirstChild();ie(i)?e=e.concat(At(i)):e.push(r)}return e}function It(t){return fe(t)&&ie(t.getFirstChild())}function Et(t,e){return e.getValue()}function Ot(t,e){return fe(t)&&(0===e.length||1===e.length&&t.is(e[0])&&0===t.getChildrenSize())}function Mt(t,e){return ie(t)?l(t).setListType(e):re(e)}function wt(t){const e=n();if(null!==e){let n=e.getNodes();if(r(e)){const[r]=e.getStartEndPoints(),i=r.getNode(),l=i.getParent();if(s(i)){const t=i.getFirstChild();if(t)n=t.selectStart().getNodes();else{const t=o();i.append(t),n=t.select().getNodes()}}else if(Ot(i,n)){if(s(l)){const e=re(t);i.replace(e);const n=ue();c(i)&&(n.setFormat(i.getFormatType()),n.setIndent(i.getIndent())),e.append(n)}else if(fe(i)){const e=i.getParentOrThrow();if(null===a(e)){const n=Mt(e,t);Dt(n,e.getChildren()),e.replace(n)}}return}}const i=new Set;for(let e=0;e<n.length;e++){const r=n[e];if(c(r)&&r.isEmpty()&&!fe(r)&&null===a(r)&&!i.has(r.getKey())){$t(r,t);continue}let o=u(r)?r.getParent():fe(r)&&r.isEmpty()?r:null;for(;null!=o;){const e=o.getKey();if(ie(o)){if(!i.has(e)&&null===a(o)){const n=Mt(o,t);Dt(n,o.getChildren()),o.replace(n),i.add(e)}break}{const n=o.getParent();if(s(n)&&!i.has(e)){i.add(e),$t(o,t);break}o=n}}}}}function Dt(t,e){t.splice(t.getChildrenSize(),0,e)}function $t(t,e){if(ie(t))return t;const i=t.getPreviousSibling(),s=t.getNextSibling(),o=ue();let l;if(Dt(o,t.getChildren()),ie(i)&&e===i.getListType())i.append(o),ie(s)&&e===s.getListType()&&(Dt(i,s.getChildren()),s.remove()),l=i;else if(ie(s)&&e===s.getListType())s.getFirstChildOrThrow().insertBefore(o),l=s;else{const n=re(e);n.append(o),t.replace(n),l=n}o.setFormat(t.getFormatType()),o.setIndent(t.getIndent());const c=n();return r(c)&&(l.getKey()===c.anchor.key&&c.anchor.set(o.getKey(),c.anchor.offset,\"element\"),l.getKey()===c.focus.key&&c.focus.set(o.getKey(),c.focus.offset,\"element\")),t.remove(),l}function Rt(t,e){Kt(t,e,!1)}function Kt(t,e,n){Wt(t.getLastChild(),e.getFirstChild(),n);const r=e.getChildren();r.length>0&&t.append(...r),e.remove()}function Wt(t,e,n=!1){if(t&&e&&It(t)&&It(e)&&(!n||1===t.getChildrenSize()&&1===e.getChildrenSize())&&t.getFirstChild().getListType()===e.getFirstChild().getListType()){if(Kt(t.getFirstChild(),e.getFirstChild(),n),!n)return void e.remove();h.prototype.remove.call(e)}}function zt(){const e=n();if(r(e)){const n=new Set,r=e.getNodes(),i=e.anchor.getNode();if(Ot(i,r))n.add(Pt(i));else for(let e=0;e<r.length;e++){const i=r[e];if(u(i)){const e=t(i,oe);null!=e&&n.add(Pt(e))}}for(const t of n){if(null!==a(t))continue;let n=t;const r=At(t);for(const t of r){const r=o().setTextStyle(e.style).setTextFormat(e.format);r.setFormat(t.getFormatType()).setIndent(t.getIndent()).setDirection(t.getDirection()).setStyle(t.getStyle()),Dt(r,t.getChildren()),n.insertAfter(r),n=r,t.__key===e.anchor.key&&f(e.anchor,g(d(r,e.anchor.offset,\"next\"))),t.__key===e.focus.key&&f(e.focus,g(d(r,e.focus.offset,\"next\"))),t.remove()}t.remove()}}}function Bt(t){const e=\"check\"!==t.getListType();let n=t.getStart();for(const r of t.getChildren())fe(r)&&(r.getValue()!==n&&r.setValue(n),e&&null!=r.getLatest().__checked&&r.setChecked(void 0),ie(r.getFirstChild())||n++)}function Ut(t){const e=new Set;if(It(t)||e.has(t.getKey()))return;const n=t.getParent(),r=t.getNextSibling(),i=t.getPreviousSibling();if(It(r)&&It(i)){const n=i.getFirstChild();if(ie(n)){n.append(t);const i=r.getFirstChild();ie(i)&&n.getListType()===i.getListType()&&(Dt(n,i.getChildren()),r.remove(),e.add(r.getKey()))}}else if(It(r)){const e=r.getFirstChild();if(ie(e)){const n=e.getFirstChild();null!==n&&n.insertBefore(t)}}else if(It(i)){const e=i.getFirstChild();ie(e)&&e.append(t)}else if(ie(n)){const e=l(t),s=l(n);e.append(s),s.append(t),i?i.insertAfter(e):r?r.insertBefore(e):n.append(e)}}function qt(t){if(It(t))return;const e=t.getParent(),n=e?e.getParent():void 0;if(ie(n?n.getParent():void 0)&&fe(n)&&ie(e)){const r=e?e.getFirstChild():void 0,i=e?e.getLastChild():void 0;if(t.is(r))n.insertBefore(t),e.isEmpty()&&n.remove();else if(t.is(i))n.insertAfter(t),e.isEmpty()&&n.remove();else{const r=l(t),i=l(e);r.append(i),t.getPreviousSiblings().forEach(t=>i.append(t));const s=l(t),o=l(e);s.append(o),Dt(o,t.getNextSiblings()),n.insertBefore(r),n.insertAfter(s),n.replace(t)}}}function jt(t=!1){const e=n();if(!r(e)||!e.isCollapsed())return!1;const c=e.anchor.getNode();let a=null;if(fe(c)&&0===c.getChildrenSize())a=c;else if(i(c)){const t=c.getParent();fe(t)&&t.getChildren().every(t=>i(t)&&\"\"===t.getTextContent().trim())&&(a=t)}if(null===a)return!1;const u=Pt(a),f=a.getParent();ie(f)||Nt(40);const g=f.getParent();let d;if(s(g))d=o(),u.insertAfter(d);else{if(!fe(g))return!1;d=l(g),g.insertAfter(d)}d.setTextStyle(e.style).setTextFormat(e.format).select();const h=a.getNextSiblings();if(h.length>0){const e=t?Et(0,a):1,n=l(f).setStart(e);if(fe(d)){const t=l(d);t.append(n),d.insertAfter(t)}else d.insertAfter(n);n.append(...h)}return function(t){let e=t;for(;null==e.getNextSibling()&&null==e.getPreviousSibling();){const t=e.getParent();if(null==t||!fe(t)&&!ie(t))break;e=t}e.remove()}(a),!0}const Vt=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function Jt(t,e){if(\"number\"==typeof t)return Number.isFinite(t)?t:e;if(\"string\"!=typeof t||!Vt.test(t))return e;const n=Number(t);return Number.isFinite(n)?n:e}function Ht(t,e){t.__listType=e.__listType,t.__start=e.__start,t.__tag=e.__tag}const Xt=t=>{const e=p(t,\"format\"),n=m(t,\"format\"),r=_(t,\"format\"),i=y(t,\"listType\",0);return{exportJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles();return{children:[],listType:t.__listType,start:t.__start,tag:t.__tag,direction:t.__dir,format:e[t.__format],indent:t.__indent,textFormat:0!==n&&i?n:void 0,textStyle:\"\"!==r&&i?r:void 0,type:t.__type,version:1}},exportCompactJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles(),s={type:t.__type,children:[]},o=t.__listType;void 0!==o&&\"number\"!==o&&(s.listType=o);const l=t.__start;void 0!==l&&1!==l&&(s.start=l);const c=t.__dir;null!=c&&(s.direction=c);const a=e[t.__format];void 0!==a&&\"\"!==a&&(s.format=a);const u=t.__indent;return void 0!==u&&0!==u&&(s.indent=u),void 0!==n&&0!==n&&i&&(s.textFormat=n),void 0!==r&&\"\"!==r&&i&&(s.textStyle=r),s},updateFromJSON:function(t,e){const s=e.direction;t.__dir=null===s||\"ltr\"===s||\"rtl\"===s?s:null;const o=e.format;t.__format=\"string\"==typeof o&&o in n?n[o]:r,t.__indent=function(t){const e=Jt(t,0);return e>=0&&e<=Infinity&&Number.isInteger(e)?e:0}(e.indent),t.__textFormat=Jt(e.textFormat,0);const l=e.textStyle;t.__textStyle=\"string\"==typeof l?l:\"\";const c=e.listType;return t.setListType(\"string\"==typeof c&&c in i?i[c]:\"number\"===c||\"bullet\"===c||\"check\"===c?c:\"number\"),t.__start=Jt(e.start,1),t},afterCloneFrom:Ht}};function Gt(t,e){t.__checked=e.__checked,t.__value=e.__value}const Zt=t=>{const e=p(t,\"format\"),n=m(t,\"format\"),r=_(t,\"format\");return{exportJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles();return{children:[],checked:t.getChecked(),indent:t.getIndent(),value:t.__value,direction:t.__dir,format:e[t.__format],textFormat:0!==n&&i?n:void 0,textStyle:\"\"!==r&&i?r:void 0,type:t.__type,version:1}},exportCompactJSON:function(t){const n=t.__textFormat,r=t.__textStyle,i=(0!==n||\"\"!==r)&&t.shouldSerializeTextStyles(),s={type:t.__type,children:[]},o=t.getChecked();void 0!==o&&(s.checked=o);const l=t.getIndent();void 0!==l&&0!==l&&(s.indent=l);const c=t.__value;void 0!==c&&1!==c&&(s.value=c);const a=t.__dir;null!=a&&(s.direction=a);const u=e[t.__format];return void 0!==u&&\"\"!==u&&(s.format=u),void 0!==n&&0!==n&&i&&(s.textFormat=n),void 0!==r&&\"\"!==r&&i&&(s.textStyle=r),s},updateFromJSON:function(t,e){const i=e.direction;t.__dir=null===i||\"ltr\"===i||\"rtl\"===i?i:null;const s=e.format;t.__format=\"string\"==typeof s&&s in n?n[s]:r,t.setIndent(function(t){const e=Jt(t,NaN);return Number.isFinite(e)&&Number.isInteger(e)?e<0?0:e>128?128:e:0}(e.indent)),t.__textFormat=Jt(e.textFormat,0);const o=e.textStyle;t.__textStyle=\"string\"==typeof o?o:\"\";const l=e.checked;return t.__checked=void 0===l?void 0:\"boolean\"==typeof l&&l,t.__value=Jt(e.value,1),t},afterCloneFrom:Gt}},Qt={ol:\"number\",ul:\"bullet\"},Yt=/* @__PURE__ */b()({listType:/* @__PURE__ */k(/* @__PURE__ */F(/* @__PURE__ */T([\"number\",\"bullet\",\"check\"]),Qt),{getter:{field:\"__listType\"}}),start:/* @__PURE__ */L(/* @__PURE__ */N(1),{field:\"__start\"}),tag:/* @__PURE__ */k(/* @__PURE__ */T([\"ul\",\"ol\"]),{getter:{field:\"__tag\"},setter:null})});class te extends h{__tag;__start;__listType;$config(){return this.config(\"list\",{$transform:t=>{(function(t){const e=t.constructor,n=t.getNextSibling();return null!==n&&n.constructor===e&&A(I())&&E(e).declaredBy.mergeAdjacent===e})(t)||function(t){const e=t.getNextSibling();ie(e)&&t.getListType()===e.getListType()&&Rt(t,e)}(t),Bt(t)},children:[oe],extends:h,generated:Xt,importDOM:S({ol:()=>({conversion:ne,priority:0}),ul:()=>({conversion:ne,priority:0})}),json:Yt,mergeAdjacent:{by:[\"listType\"]}})}constructor(t=\"number\",e=1,n){super(n);const r=Qt[t]||t;this.__listType=r,this.__tag=\"number\"===r?\"ol\":\"ul\",this.__start=e}getTag(){return this.getLatest().__tag}setListType(t){const e=this.getWritable();return e.__listType=t,e.__tag=\"number\"===t?\"ol\":\"ul\",e}getListType(){return this.getLatest().__listType}getStart(){return this.getLatest().__start}setStart(t){const e=this.getWritable();return e.__start=t,e}createDOM(t,e){const n=this.__tag,r=v().createElement(n);return 1!==this.__start&&r.setAttribute(\"start\",String(this.__start)),r.__lexicalListType=this.__listType,ee(r,t.theme,this),r}updateDOM(t,e,n){return t.__tag!==this.__tag||t.__listType!==this.__listType||(ee(e,n.theme,this),t.__start!==this.__start&&e.setAttribute(\"start\",String(this.__start)),!1)}exportDOM(t){const e=this.createDOM(t._config,t);if(x(e)){1!==this.__start&&e.setAttribute(\"start\",String(this.__start)),\"check\"===this.__listType&&e.setAttribute(\"__lexicalListType\",\"check\");const t=this.getDirection();t&&(e.dir=t)}return{element:e}}canBeEmpty(){return!1}INTERNAL_$afterStructureMerge(t,e){Wt(t,e,!0)}INTERNAL_$afterStructureSplit(t,e){if(\"number\"===this.getListType()){let n=t.getStart();for(const t of e)fe(t)&&!ie(t.getFirstChild())&&n++;this.setStart(n)}}canIndent(){return!1}splice(t,e,n){let r=n;for(let t=0;t<n.length;t++){const e=n[t];if(!fe(e)){r===n&&(r=[...n]);const i=this.createListItemNode();!c(e)||ie(e)||e.isInline()?i.append(e):i.append(...e.getChildren()),r[t]=i}}return super.splice(t,e,r)}extractWithChild(t){return fe(t)}createListItemNode(){return ue()}}function ee(t,e,n){const r=[],i=[],s=e.list;if(void 0!==s){const t=s[`${n.__tag}Depth`]||[],e=Ft(n)-1,o=e%t.length,l=t[o],c=s[n.__tag];let a;const u=s.nested,f=s.checklist;if(void 0!==u&&u.list&&(a=u.list),void 0!==c&&r.push(c),void 0!==f&&\"check\"===n.__listType&&r.push(f),void 0!==l){r.push(...O(l));for(let e=0;e<t.length;e++)e!==o&&i.push(...O(t[e]))}if(void 0!==a){const t=O(a);e>1?r.push(...t):i.push(...t)}}i.length>0&&M(t,...i),r.length>0&&w(t,...r)}function ne(t){let e;if(function(t){return x(t)&&\"ol\"===t.nodeName.toLowerCase()}(t)){const n=t.start;e=re(\"number\",n)}else e=function(t){if(\"check\"===t.getAttribute(\"__lexicallisttype\")||t.classList.contains(\"contains-task-list\")||\"1\"===t.getAttribute(\"data-is-checklist\"))return!0;for(const e of t.childNodes)if(x(e)&&e.hasAttribute(\"aria-checked\"))return!0;return!1}(t)?re(\"check\"):re(\"bullet\");return P(e,t),{after:t=>function(t,e){const n=e.createListItemNode.bind(e),r=[];for(let e=0;e<t.length;e++){const i=t[e];if(fe(i)){r.push(i);const t=i.getChildren();t.length>1&&t.forEach(t=>{ie(t)&&r.push(n().append(t))})}else r.push(n().append(i))}return r}(t,e),node:e}}function re(t=\"number\",e=1){return C(new te(t,e))}function ie(t){return t instanceof te}const se=/* @__PURE__ */b()({checked:/* @__PURE__ */k(/* @__PURE__ */z(/* @__PURE__ */B()),{setter:{field:\"__checked\"}}),indent:/* @__PURE__ */k(/* @__PURE__ */N(0,{clamp:!0,integer:!0,max:128,min:0}),{derived:!0}),value:/* @__PURE__ */L(/* @__PURE__ */N(1),{derived:!0,field:\"__value\"})});class oe extends h{__value;__checked;$config(){return this.config(\"listitem\",{$transform:t=>{const e=t.getParent();if(ie(e))\"check\"!==e.getListType()&&null!=t.getChecked()&&t.setChecked(void 0);else if(e){const i=t.createParentElementNode();ie(i)||Nt(340);const o=[t];for(const e of[\"previous\",\"next\"]){o.reverse();for(const{origin:n}of D(t,e)){if(!fe(n))break;o.push(n)}}const l=A(I()),c=l?function(t,e){const i=n();if(!r(i))return null;const s=t.getKey(),o=e[0].getIndexWithinParent(),l=[i.anchor,i.focus].filter(t=>\"element\"===t.type&&t.key===s).map(t=>({offset:t.offset,point:t}));return 0===l.length?null:t=>{for(const{point:t,offset:n}of l)if(n<=o)t.set(s,n,\"element\");else if(n<o+e.length){const r=e[n-o-1];t.set(r.getKey(),r.getChildrenSize(),\"element\")}else t.set(s,n-e.length+1,\"element\")}}(e,o):null;if(t.insertBefore(i),i.splice(0,0,o),null!==c&&c(i),l)for(let t=e;null!==t&&!s(t);t=t.getParent())t.markDirty();s(e)||l||($(i,R(D(i,\"next\")),{$shouldSplit:()=>!1,removeEmptyDestination:!0}),e.isEmpty()&&e.isAttached()&&e.remove())}},children:[\"inline\",te],extends:h,generated:Zt,importDOM:S({li:()=>({conversion:le,priority:0})}),json:se})}constructor(t=1,e=void 0,n){super(n),this.__value=void 0===t?1:t,this.__checked=e}createDOM(t){const e=v().createElement(\"li\");return this.updateListItemDOM(null,e,t),e}updateListItemDOM(t,e,n){!function(t,e){const n=e.getParent();!ie(n)||\"check\"!==n.getListType()||ie(e.getFirstChild())?(t.removeAttribute(\"role\"),t.removeAttribute(\"tabIndex\"),t.removeAttribute(\"aria-checked\")):(t.setAttribute(\"role\",\"checkbox\"),t.setAttribute(\"tabIndex\",\"-1\"),t.setAttribute(\"aria-checked\",e.getChecked()?\"true\":\"false\"))}(e,this),e.value=this.__value,function(t,e,n){const r=e.list;if(!r)return;const i=r.listitem,s=r.nested&&r.nested.listitem,o=n.getParent(),l=ie(o)&&\"check\"===o.getListType(),c=n.getChecked(),a=n.getChildren().some(t=>ie(t)),u=[];void 0!==r.listitemChecked&&u.push(r.listitemChecked),void 0!==r.listitemUnchecked&&u.push(r.listitemUnchecked),void 0!==s&&u.push(...O(s)),u.length>0&&M(t,...u);const f=[];if(void 0!==i&&f.push(...O(i)),l){const t=c?r.listitemChecked:r.listitemUnchecked;void 0!==t&&f.push(t)}void 0!==s&&a&&f.push(...O(s)),f.length>0&&w(t,...f)}(e,n.theme,this);const r=t?t.__style:\"\",i=this.__style;r!==i&&K(e.style,i,r),function(t,e,n){const r=e.__textStyle,i=n?n.__textStyle:\"\";if(null!==n&&i===r)return;const s=q(r);for(const e in s)t.style.setProperty(`--listitem-marker-${e}`,s[e]);if(\"\"!==i)for(const e in q(i))e in s||t.style.removeProperty(`--listitem-marker-${e}`)}(e,this,t)}updateDOM(t,e,n){const r=e;return this.updateListItemDOM(t,r,n),!1}exportDOM(t){const e=this.createDOM(t._config),n=this.getFormatType();n&&(e.style.textAlign=n);const r=this.getDirection();return r&&(e.dir=r),It(this)?{after(t){if(x(t)){const e=t.previousElementSibling;if(x(e)&&\"LI\"===e.nodeName){for(;t.firstChild;)e.append(t.firstChild);t.remove()}}return t},element:e}:{element:e}}append(...t){for(let e=0;e<t.length;e++){const n=t[e];if(c(n)&&this.canMergeWith(n)){const t=n.getChildren();this.append(...t),n.remove()}else super.append(n)}return this}replace(t,e){if(fe(t))return super.replace(t);this.setIndent(0);const i=this.getParentOrThrow();if(!ie(i))return t;if(i.__first===this.getKey())i.insertBefore(t);else if(i.__last===this.getKey())i.insertAfter(t);else{const e=l(i);let n=this.getNextSibling();for(;n;){const t=n;n=n.getNextSibling(),e.append(t)}i.insertAfter(t),t.insertAfter(e)}const s=this.__key;let o=0;if(e&&(c(t)||Nt(139),o=t.getChildrenSize(),t.splice(o,0,this.getChildren())),e&&c(t)){const e=n();if(r(e))for(const n of e.getStartEndPoints())n.key===s&&\"element\"===n.type&&n.set(t.getKey(),o+n.offset,\"element\")}return this.remove(),0===i.getChildrenSize()&&i.remove(),t}insertAfter(t,e=!0){const n=this.getParentOrThrow();if(ie(n)||Nt(39),fe(t))return super.insertAfter(t,e);const r=this.getNextSiblings();if(n.insertAfter(t,e),0!==r.length){const i=l(n),s=r[0];\"number\"===i.getListType()&&fe(s)&&i.setStart(Et(0,s)),r.forEach(t=>i.append(t)),t.insertAfter(i,e)}return t}remove(t){const e=this.getPreviousSibling(),n=this.getNextSibling();super.remove(t),e&&n&&It(e)&&It(n)&&e.getFirstChild().getListType()===n.getFirstChild().getListType()&&(Rt(e.getFirstChild(),n.getFirstChild()),n.remove())}resetOnCopyNodeFrom(t){super.resetOnCopyNodeFrom(t),t.getChecked()&&this.setChecked(!1)}insertNewAfter(t,e=!0){const n=l(this);return this.insertAfter(n,e),n}collapseAtStart(t){if(It(this))return!1;const e=this.getParentOrThrow();if(fe(e.getParentOrThrow()))return qt(this),!0;const n=o().append(...this.getChildren()),r=this.getNextSiblings();if(r.length>0){const t=l(e);t.append(...r),e.insertAfter(t)}return e.insertAfter(n),this.remove(),0===e.getChildrenSize()&&e.remove(),n.selectStart(),!0}getValue(){return this.getLatest().__value}setValue(t){const e=this.getWritable();return e.__value=t,e}getChecked(){const t=this.getLatest();let e;const n=this.getParent();return ie(n)&&(e=n.getListType()),\"check\"===e?Boolean(t.__checked):void 0}setChecked(t){const e=this.getWritable();return e.__checked=t,e}toggleChecked(){const t=this.getWritable();return t.setChecked(!t.__checked)}getIndent(){const t=this.getParent();if(null===t||!this.isAttached())return this.getLatest().__indent;let e=t.getParentOrThrow(),n=0;for(;fe(e);)e=e.getParentOrThrow().getParentOrThrow(),n++;return n}setIndent(t){\"number\"!=typeof t&&Nt(117),(t=Math.floor(t))>=0||Nt(199);const e=t;let n=this.getIndent();for(;n!==e;)n<e?(Ut(this),n++):(qt(this),n--);return this}canInsertAfter(t){return fe(t)}canReplaceWith(t){return fe(t)}canMergeWith(t){return fe(t)||W(t)}extractWithChild(t,e){if(!r(e))return!1;const n=e.anchor.getNode(),i=e.focus.getNode();return this.isParentOf(n)&&this.isParentOf(i)&&this.getTextContent().length===e.getTextContent().length}isParentRequired(){return!0}createParentElementNode(){return re(\"bullet\")}canMergeWhenEmpty(){return!0}}function le(t){if(t.classList.contains(\"task-list-item\"))for(const e of t.children)if(\"INPUT\"===e.tagName)return ce(e);if(t.classList.contains(\"joplin-checkbox\"))for(const e of t.children)if(e.classList.contains(\"checkbox-wrapper\")&&e.children.length>0&&\"INPUT\"===e.children[0].tagName)return ce(e.children[0]);const e=t.getAttribute(\"aria-checked\"),n=ue(\"true\"===e||\"false\"!==e&&void 0);return U(n,t),{after:ae.bind(null,n),node:P(n,t)}}function ce(t){if(\"checkbox\"!==t.getAttribute(\"type\"))return{node:null};const e=ue(t.hasAttribute(\"checked\"));return{after:ae.bind(null,e),node:e}}function ae(t,e){const n=e[0];return 1===e.length&&W(n)&&!t.getFormatType()&&n.getFormatType()?(t.setFormat(n.getFormatType()),n.getChildren()):e}function ue(t){return C(new oe(void 0,t))}function fe(t){return t instanceof oe}const ge=new Set([\" \",\"Alt\",\"ArrowDown\",\"ArrowLeft\",\"ArrowUp\",\"CapsLock\",\"Control\",\"Escape\",\"Meta\",\"Shift\"]),de=/* @__PURE__ */j(\"INSERT_CHECK_LIST_COMMAND\");function he(t,e){const i=e&&e.disableTakeFocusOnClick||!1,s=\"boolean\"==typeof i?()=>i:i.peek.bind(i),o=t=>{const e=t.target;if(!x(e))return!1;const n=e.__lexicalCheckListLastHandled;return void 0!==n&&t.timeStamp-n<500};let l=\"none\";const a=t=>{l=function(t,e){let n=!1;return pe(t,()=>{n=!0,t.preventDefault(),e&&t.stopPropagation()}),n}(t,s())?\"checkMark\":\"content\"},u=()=>{\"content\"===l&&_e(t),l=\"none\"};return V(t.registerCommand(de,()=>(wt(\"check\"),!0),J),t.registerCommand(H,e=>Se(e,t,!1),J),t.registerCommand(X,e=>Se(e,t,!0),J),t.registerCommand(G,()=>{if(null!=Ce(t)){const e=t.getRootElement();return null!=e&&e.focus(),!0}return!1},J),t.registerCommand(Z,e=>{const n=Ce(t);return!(null==n||!t.isEditable()||(t.update(()=>{const t=Q(n);fe(t)&&(e.preventDefault(),t.toggleChecked())}),0))},J),t.registerCommand(Y,e=>null!==Ce(t)?(_e(t),!1):t.read(\"latest\",()=>{const i=n();if(r(i)&&i.isCollapsed()){const{anchor:n}=i,r=\"element\"===n.type;if(r||0===n.offset){const i=n.getNode(),s=tt(i,t=>c(t)&&!t.isInline());if(fe(s)){const n=s.getParent();if(ie(n)&&\"check\"===n.getListType()&&(r||s.getFirstDescendant()===i)){const n=t.getElementByKey(s.__key);if(null!=n&&et(n)!==n)return n.focus(),e.preventDefault(),!0}}}}return!1}),J),t.registerRootListener(e=>{if(null!==e)return V(nt(e,{click:t=>{u(),(t=>{o(t)||me(t,s())})(t)},pointerup:t=>{u(),(t=>{\"touch\"===t.pointerType&&(o(t)||((t=>{const e=t.target;x(e)&&(e.__lexicalCheckListLastHandled=t.timeStamp)})(t),me(t,s())))})(t)}}),nt(e,{beforeinput:()=>_e(t),focusin:()=>{rt&&\"content\"===l&&_e(t)},keydown:e=>{ge.has(e.key)||_e(t)},mousedown:a,pointerdown:a},{capture:!0}),it(e,\"touchstart\",a,{capture:!0,passive:!1}))}))}function pe(t,n){const r=t.target;if(!x(r))return;const i=r.firstChild;if(x(i)&&(\"UL\"===i.tagName||\"OL\"===i.tagName))return;const s=r.parentNode;if(!s||\"check\"!==s.__lexicalListType)return;let o=null,l=null;if(\"clientX\"in t)o=t.clientX;else if(\"touches\"in t){const e=t.touches;e.length>0&&(o=e[0].clientX,l=\"touch\")}if(null==o)return;const c=r.getBoundingClientRect(),a=o/e(r),u=r.ownerDocument.defaultView,f=u?u.getComputedStyle(r,\"::before\"):{width:\"0px\"},g=parseFloat(f.width),d=\"touch\"===l||\"pointerType\"in t&&\"touch\"===t.pointerType?32:0;(\"rtl\"===r.dir?a<c.right+d&&a>c.right-g-d:a>c.left-d&&a<c.left+g+d)&&n()}function me(t,e){pe(t,()=>{if(x(t.target)){const n=t.target,r=st(n);null!=r&&r.isEditable()&&r.update(()=>{const t=Q(n);fe(t)&&(e?(ot(lt),ot(ct)):n.focus(),t.toggleChecked())})}})}function _e(t){const e=t.getRootElement(),n=e?et(e):null;null!==e&&x(n)&&ye(n)&&e.focus({preventScroll:!0})}function ye(t){const e=t.parentNode;return\"LI\"===t.tagName&&null!=e&&\"check\"===e.__lexicalListType}function Ce(t){const e=t.getRootElement(),n=e?et(e):null;return x(n)&&ye(n)?n:null}function Se(t,e,n){const r=Ce(e);if(null!=r){let i=null;e.update(()=>{const s=Q(r);if(!fe(s))return;const o=function(t,e){let n=e?t.getPreviousSibling():t.getNextSibling(),r=t;for(;null==n&&fe(r);)r=r.getParentOrThrow().getParent(),null!=r&&(n=e?r.getPreviousSibling():r.getNextSibling());for(;fe(n);){const t=e?n.getLastChild():n.getFirstChild();if(!ie(t))return n;n=e?t.getLastChild():t.getFirstChild()}return null}(s,n);null!=o&&(o.selectStart(),null!=e.getElementByKey(o.__key)&&(t.preventDefault(),i=o.__key))},{onUpdate:()=>{const t=null===i?null:e.getElementByKey(i);null!=t&&t.focus()}})}return!1}function ve(t,e){const n=[];for(const r of t)if(fe(r)){n.push(r);const t=r.getChildren();if(t.length>1)for(const r of t)ie(r)&&n.push(e.createListItemNode().append(r))}else n.push(e.createListItemNode().append(r));return n}const xe={$import:(t,e)=>{let n;var r;return n=yt(e,\"ol\")?re(\"number\",e.start):(r=e).matches('[__lexicallisttype=\"check\"], .contains-task-list, [data-is-checklist=\"1\"]')||null!==r.querySelector(\":scope > [aria-checked]\")?re(\"check\"):re(\"bullet\"),P(n,e),[n.splice(0,0,Ct(ve(t.$importChildren(e),n),e))]},match:/* @__PURE__ */_t.tag(\"ol\",\"ul\"),name:\"@lexical/list/list\"};function be(t,e){if(1!==e.length)return e;const n=e[0];return W(n)&&!t.getFormatType()&&n.getFormatType()?(t.setFormat(n.getFormatType()),n.getChildren()):e}function ke(t){const e=t=>St(t)&&!ie(t);if(!t.some(e))return t;const n=[];let r=[];const i=()=>{r.length>0&&(n.push({lifted:!1,nodes:r}),r=[])},s=A(I());for(const o of t)e(o)?(i(),n.push(c(o)?{lifted:!1,nodes:o.getChildren()}:{lifted:s,nodes:[o]})):r.push(o);i();const o=[];for(let t=0;t<n.length;t++)o.length>0&&!n[t-1].lifted&&!n[t].lifted&&o.push(at()),o.push(...n[t].nodes);return o}const Te={$import:(t,e)=>{const n=e.getAttribute(\"aria-checked\"),r=ue(\"true\"===n||\"false\"!==n&&void 0);return U(r,e),P(r,e),[r.splice(0,0,ke(be(r,t.$importChildren(e))))]},match:/* @__PURE__ */_t.tag(\"li\"),name:\"@lexical/list/li\"};function Le(t,e,n){const r=yt(n,\"input\")?n:n.querySelector('input[type=\"checkbox\"]');if(!r||\"checkbox\"!==r.getAttribute(\"type\"))return[];const i=ue(r.hasAttribute(\"checked\"));return U(i,e),P(i,e),[i.splice(0,0,ke(be(i,t.$importChildren(e))))]}const Ne={$accepts:t=>fe(t)||ie(t),$packageRun:t=>[ue().splice(0,0,t)],name:\"ListSchema\"},Fe=[{$import:(t,e,n)=>{const r=e.querySelector(':scope > input[type=\"checkbox\"]');return r?Le(t,e,r):n()},match:/* @__PURE__ */_t.tag(\"li\").classAll(\"task-list-item\"),name:\"@lexical/list/li-task-list-item\"},{$import:(t,e,n)=>{const r=e.querySelector(\":scope > .checkbox-wrapper\");if(!r)return n();const i=r.querySelector(':scope > input[type=\"checkbox\"]');return i?Le(t,e,i):n()},match:/* @__PURE__ */_t.tag(\"li\").classAll(\"joplin-checkbox\"),name:\"@lexical/list/li-joplin-checkbox\"},xe,Te],Pe=/* @__PURE__ */j(\"UPDATE_LIST_START_COMMAND\"),Ae=/* @__PURE__ */j(\"INSERT_UNORDERED_LIST_COMMAND\"),Ie=/* @__PURE__ */j(\"INSERT_ORDERED_LIST_COMMAND\"),Ee=/* @__PURE__ */j(\"REMOVE_LIST_COMMAND\");function Oe(t,e){return V(t.registerCommand(Ie,()=>(wt(\"number\"),!0),J),t.registerCommand(Pe,t=>{const{listNodeKey:e,newStart:n}=t,r=ut(e);return!!ie(r)&&(\"number\"===r.getListType()&&(r.setStart(n),Bt(r)),!0)},J),t.registerCommand(Ae,()=>(wt(\"bullet\"),!0),J),t.registerCommand(Ee,()=>(zt(),!0),J),t.registerCommand(ft,()=>jt(!(!e||!e.restoreNumbering)),J),t.registerCommand(gt,t=>{const e=n();if(!r(e)||!e.isCollapsed())return!1;const{anchor:i}=e;if(0!==i.offset)return!1;let s=i.getNode();for(;!fe(s);){if(null!==s.getPreviousSibling())return!1;const t=s.getParent();if(null===t)return!1;s=t}return!(!fe(s)||!s.collapseAtStart(e)||(t.preventDefault(),0))},dt),t.registerNodeTransform(oe,t=>{const e=t.getFirstChild();if(e){if(i(e)){const n=e.getStyle(),r=e.getFormat();t.getTextStyle()!==n&&t.setTextStyle(n),t.getTextFormat()!==r&&t.setTextFormat(r)}}else{const e=n();r(e)&&(e.style!==t.getTextStyle()||e.format!==t.getTextFormat())&&e.isCollapsed()&&t.is(e.anchor.getNode())&&t.setTextStyle(e.style).setTextFormat(e.format)}}),t.registerNodeTransform(ht,t=>{const e=t.getParent();if(fe(e)&&t.is(e.getFirstChild())){const n=t.getStyle(),r=t.getFormat();n===e.getTextStyle()&&r===e.getTextFormat()||e.setTextStyle(n).setTextFormat(r)}}))}function Me(t){const e=t=>{const e=t.getParent();if(ie(t.getFirstChild())||!ie(e))return;const n=tt(t,t=>fe(t)&&ie(t.getParent())&&fe(t.getPreviousSibling()));if(null===n&&t.getIndent()>0)t.setIndent(0);else if(fe(n)){const r=n.getPreviousSibling();if(fe(r)){const n=function(t){let e=t,n=e.getFirstChild();for(;ie(n);){const t=n.getLastChild();if(!fe(t))break;e=t,n=e.getFirstChild()}return e}(r),i=n.getParent();if(ie(i)){const n=Ft(i);n+1<Ft(e)&&t.setIndent(n)}}}};return t.registerNodeTransform(te,t=>{const n=[t];for(;n.length>0;){const t=n.shift();if(ie(t))for(const r of t.getChildren())if(fe(r)){e(r);const t=r.getFirstChild();ie(t)&&n.push(t)}}})}const we={build:(t,e,n)=>mt(e),config:{hasStrictIndent:!1,shouldPreserveNumbering:!1},dependencies:[vt,[xt,{rules:Fe}]],name:\"@lexical/list/List\",nodes:()=>[te,oe],register(t,e,n){const r=n.getOutput();return V(pt(()=>Oe(t,{restoreNumbering:r.shouldPreserveNumbering.value})),pt(()=>r.hasStrictIndent.value?Me(t):void 0))}},De={build:(t,e)=>mt(e),config:{disableTakeFocusOnClick:!1},dependencies:[we],name:\"@lexical/list/CheckList\",register:(t,e,n)=>he(t,n.getOutput())},$e=/^MsoListParagraph(CxSp(First|Middle|Last))?$/,Re=/^[A-Za-z0-9]+[.)]/,Ke=/Microsoft Word/i,We=\"data-mso-list\";function ze(t){const e=(t.getAttribute(We)||\"\").match(/level(\\d+)/);return e?parseInt(e[1],10):1}function Be(t){return t.querySelector(`span[${We}=\"Ignore\"]`)}function Ue(t){const e=Be(t);return e?(e.textContent||\"\").trim():\"\"}function qe(t){return Re.test(t)?\"number\":\"bullet\"}function je(t){const e=Be(t);if(!e)return;let n=e;for(;n.parentElement&&n.parentElement!==t&&\"SPAN\"===n.parentElement.nodeName;)n=n.parentElement;n.remove()}function Ve(t){return x(t)&&$e.test(t.className)}function Je(t,e){const n=re(qe(e[0].marker)),r=[{level:e[0].level,list:n}];for(const n of e){for(;r.length>1&&r[r.length-1].level>n.level;)r.pop();if(n.level>r[r.length-1].level){const t=re(qe(n.marker));r[r.length-1].list.append(ue().append(t)),r.push({level:n.level,list:t})}je(n.el),r[r.length-1].list.append(ue().splice(0,0,t.$importChildren(n.el,{schema:Lt})))}return n}const He=/* @__PURE__ */Tt(\"@lexical/list/word-consumed-list-items\",()=>null),Xe={$import:(t,e)=>{let n=t.session.get(He);if(null===n&&(n=new WeakSet,t.session.set(He,n)),n.has(e))return[];const r=[];let i=e;for(;i&&Ve(i)&&(n.add(i),r.push({el:i,level:ze(i),marker:Ue(i)}),!i.classList.contains(\"MsoListParagraphCxSpLast\")&&\"MsoListParagraph\"!==i.className);)i=i.nextElementSibling;return[Je(t,r)]},match:/* @__PURE__ */_t.tag(\"p\").classAny(\"MsoListParagraph\",\"MsoListParagraphCxSpFirst\",\"MsoListParagraphCxSpMiddle\",\"MsoListParagraphCxSpLast\"),name:\"@lexical/list/word-list-paragraph\"},Ge=/* @__PURE__ */kt([{$import:()=>[],match:/* @__PURE__ */_t.tag(\"o:p\"),name:\"@lexical/list/word-o-p\"},Xe]),Ze={dependencies:[we,[xt,{preprocess:[(t,e,n)=>{const r=t.querySelector('meta[name=\"Generator\"]');if(r&&Ke.test(r.getAttribute(\"content\")||\"\")){for(const e of Array.from(t.querySelectorAll('[style*=\"mso-list\"]'))){const t=q(e.getAttribute(\"style\")||\"\")[\"mso-list\"];t&&e.setAttribute(We,t)}e.session.update(bt,t=>[...t,Ge])}n()}]}]],name:\"@lexical/list/WordListImport\"};export{ue as $createListItemNode,re as $createListNode,Ft as $getListDepth,jt as $handleListInsertParagraph,wt as $insertList,fe as $isListItemNode,ie as $isListNode,zt as $removeList,De as CheckListExtension,de as INSERT_CHECK_LIST_COMMAND,Ie as INSERT_ORDERED_LIST_COMMAND,Ae as INSERT_UNORDERED_LIST_COMMAND,we as ListExtension,Fe as ListImportRules,oe as ListItemNode,te as ListNode,Ne as ListSchema,Ee as REMOVE_LIST_COMMAND,Pe as UPDATE_LIST_START_COMMAND,Ze as WordListImportExtension,he as registerCheckList,Oe as registerList,Me as registerListStrictIndentTransform};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{getRootOwnerDocument as t,getDOMShadowRoots as e,isDOMShadowRoot as n,getParentElement as o,$getEditor as r,shallowMergeConfig as i,$isRangeSelection as l,$getSelection as c,$setSelection as s,tokenizeRawText as u,$createTabNode as f,$getRoot as a,$getSelectionSlotFrame as p,$isElementNode as d,$parseSerializedNode as m,SELECTION_INSERT_CLIPBOARD_NODES_COMMAND as g,getDOMSelection as y,COPY_COMMAND as x,COMMAND_PRIORITY_CRITICAL as h,$isTextNode as T,$exportNodeJSON as C,$isNodeSelection as b,$getSlotNames as w,$getSlot as M,$normalizeCaret as v,$isTextPointCaret as $,$splitAtPointCaretNext as D,$setSelectionFromCaretRange as P,$getCollapsedCaretRange as N,$caretFromPoint as S,$getCaretRange as R,$getChildCaret as F,getDOMSelectionPoints as E,isSelectionWithinEditor as O,$getNearestNodeFromDOMNode as I,$getTextPointCaret as K,$getDOMSlot as A,$getChildCaretAtIndex as j,$getCaretRangeInDirection as k,$caretRangeFromSelection as L,$comparePointCaretNext as _,findAllLexicalElementsDeep as J,getEditorPropertyFromDOMNode as W,isLexicalEditor as B,isHTMLElement as H,$rewindSiblingCaret as z,$isChildCaret as U,$getSiblingCaret as X}from\"lexical\";import{getPeerDependencyFromEditor as G}from\"@lexical/extension/getPeerDependencyFromEditor\";import{CoreImportExtension as Y,$generateNodesFromDOMViaExtension as q,contextValue as Q,ImportSource as V,ImportSourceDataTransfer as Z,$generateNodesFromDOM as tt,$generateHtmlFromNodes as et}from\"@lexical/html\";import{$sliceSelectedTextNodeContent as nt}from\"@lexical/selection\";import{objectKlassEquals as ot}from\"@lexical/utils\";import{$getPeerDependency as rt}from\"@lexical/extension/getExtensionDependency\";function it(r,i,l=null){const c=t(l),s=l?e(l):[],u=null!==l&&s.length>0;if(u&&\"function\"==typeof c.caretPositionFromPoint){const t=c.caretPositionFromPoint(r,i,{shadowRoots:s});if(null!==t&&function(t,e){for(let n=t;null!==n;){if(n===e)return!0;n=o(n)}return!1}(t.offsetNode,l))return{node:t.offsetNode,offset:t.offset}}if(u){const t=l.getRootNode();if(n(t)){const e=t.elementFromPoint(r,i);if(null!==e&&l.contains(e)){const t=function(t,e,n,o){const r=o.createRange(),i=t=>e<t.top?t.top-e:e>t.bottom?e-t.bottom:0,l=e=>t<e.left?e.left-t:t>e.right?t-e.right:0,c=o.createTreeWalker(n,NodeFilter.SHOW_TEXT);let s=null,u=Infinity,f=Infinity;for(let t=c.nextNode();t;t=c.nextNode()){r.selectNodeContents(t);for(const e of r.getClientRects()){const n=i(e),o=l(e);(n<u||n===u&&o<f)&&(u=n,f=o,s=t)}}if(null===s)return null;let a=0,p=Infinity,d=Infinity;for(let e=0;e<=s.length;e++){r.setStart(s,e),r.collapse(!0);const n=r.getBoundingClientRect(),o=i(n),l=Math.abs(t-n.left);(o<p||o===p&&l<d)&&(p=o,d=l,a=e)}return{node:s,offset:a}}(r,i,e,c);if(null!==t)return t}}}if(\"function\"==typeof c.caretRangeFromPoint){const t=c.caretRangeFromPoint(r,i);return null===t?null:{node:t.startContainer,offset:t.startOffset}}if(\"function\"==typeof c.caretPositionFromPoint){const t=c.caretPositionFromPoint(r,i);return null===t?null:{node:t.offsetNode,offset:t.offset}}return null}function lt(t,...e){throw function(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),o=new URLSearchParams;o.append(\"code\",t);for(const t of e)o.append(\"v\",t);return n.search=o.toString(),new Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(t,...e)}const ct={\"application/x-lexical-editor\":0,\"text/html\":10,\"text/plain\":20,\"text/uri-list\":30};function st(t){return window.trustedTypes&&window.trustedTypes.createPolicy?window.trustedTypes.createPolicy(\"lexical\",{createHTML:t=>t}).createHTML(t):t}const ut=(t,e)=>{if(!l(e))return e.insertRawText(t),!0;e!==c()&&s(e);const n=t=>{const e=c();l(e)&&t(e)};return u(t,{linebreak:()=>n(t=>t.insertParagraph()),tab:()=>n(t=>t.insertNodes([f()])),text:t=>n(e=>e.insertText(t))}),!0},ft={\"application/x-lexical-editor\":[(t,e,n)=>{try{const n=r(),o=JSON.parse(t);if(o&&o.namespace===n._config.namespace&&Array.isArray(o.nodes))return Dt(n,St(o.nodes),e),!0}catch(t){console.error(t)}return n()}],\"text/html\":[(t,e,n)=>{try{const n=r(),o=(new DOMParser).parseFromString(st(t),\"text/html\");return Dt(n,tt(n,o),e),!0}catch(t){return console.error(t),n()}}],\"text/plain\":[ut],\"text/uri-list\":[ut]};function at(t,e,n,o){if(!t)return!1;const r=(e,n,i)=>!!t[e]&&t[e](n,i,(t=n,o=i)=>r(e-1,t,o),o);return r(t.length-1,e,n)}function pt(t,e,n){const o=e.getData(\"text/plain\");for(const r of function(t){return Object.keys(t.$importMimeType).filter(e=>void 0!==t.$importMimeType[e]).sort((e,n)=>{const o=t.priority[e],r=t.priority[n];return void 0===o&&void 0===r?e<n?-1:e>n?1:0:void 0===o?1:void 0===r?-1:o-r})}(t)){const i=e.getData(r);if(i&&(\"text/html\"!==r||i!==o)&&at(t.$importMimeType[r],i,n,e))return!0}return!1}const dt={$importMimeType:ft,$insertDataTransfer:(t,e)=>pt({$importMimeType:ft,priority:ct},t,e),priority:ct},mt={build:(t,e)=>({$importMimeType:e.$importMimeType,$insertDataTransfer:(t,n)=>pt(e,t,n),priority:e.priority}),config:{$importMimeType:ft,priority:ct},mergeConfig(t,e){const n=i(t,e);if(e.$importMimeType){const o={...t.$importMimeType};for(const[t,n]of Object.entries(e.$importMimeType))if(n){const e=o[t];o[t]=e?[...e,...n]:n}n.$importMimeType=o}return e.priority&&(n.priority={...t.priority,...e.priority}),n},name:\"@lexical/clipboard/Import\"},gt={dependencies:[Y,[mt,{$importMimeType:{\"text/html\":[(t,e,n,o)=>{const i=(new DOMParser).parseFromString(st(t),\"text/html\"),l=q(i,{context:[Q(V,\"paste\"),Q(Z,o)]});return Dt(r(),l,e),!0}]}}]],name:\"@lexical/clipboard/DOMImport\"};function yt(t,e=c()){return null==e&&lt(166),l(e)&&e.isCollapsed()||0===e.getNodes().length?\"\":et(t,e)}function xt(t,e=c()){return null==e&&lt(166),l(e)&&e.isCollapsed()||0===e.getNodes().length?null:JSON.stringify(Nt(t,e))}function ht(t,e){const n=t.getData(\"text/plain\")||t.getData(\"text/uri-list\");null!=n&&e.insertRawText(n)}function Tt(t,e,n){(function(){const t=rt(mt.name);return t?t.output:dt})().$insertDataTransfer(t,e)}const Ct=\"application/x-lexical-drag\";function bt(t,e){const n={editorKey:e.getKey()};t.setData(Ct,JSON.stringify(n))}function wt(t){let e=t;if($(e))if(0===e.offset)e=z(e.getSiblingCaret());else{if(e.offset!==e.origin.getTextContentSize())return e;e=e.getSiblingCaret()}for(;;){const t=e.getParentAtCaret();if(null===t||!t.isInline()||t.isShadowRoot())return e;if(U(e))e=z(X(t,\"next\"));else{if(null!==e.getNodeAtCaret())return e;e=X(t,\"next\")}}}function Mt(t,e,n){const o=t.dataTransfer;if(null===o)return!1;const r=function(t){const e=t.getData(Ct);if(!e)return null;let n;try{n=JSON.parse(e)}catch{return null}return null!==(o=n)&&\"object\"==typeof o&&\"editorKey\"in o&&\"string\"==typeof o.editorKey?n:null;var o}(o);if(null===r)return!1;const i=function(t,e){const n=it(t.clientX,t.clientY,e.getRootElement());if(null===n)return null;const o=I(n.node);if(null===o)return null;if(T(o))return K(o,\"next\",n.offset);const r=o.getParent();if(d(o)){const t=e.getElementByKey(o.getKey());if(null===t)return null;const i=A(o,t,e);return n.node===i.element||r?j(...i.resolveChildIndex(o,t,n.node,n.offset),\"next\"):null}return r&&j(r,o.getIndexWithinParent()+1,\"next\")}(t,e);if(null===i)return!1;const s=r.editorKey===e.getKey(),u=c();if(s){if(!l(u)||u.isCollapsed())return!1;if(function(t,e){const{anchor:n,focus:o}=k(L(e),\"next\"),r=wt(t);return _(wt(n),r)<=0&&_(r,wt(o))<=0}(i,u))return t.preventDefault(),!0}const f=v(i),a=$(f)?D(f):f;if(null===a)return!1;const p=a.getFlipped();s&&l(u)&&u.removeText();const m=a.origin.isAttached()?a:p;if(m.origin.isAttached()||lt(438),n(o,P(N(m)),e),!s){const t=e.getRootElement(),n=t?t.ownerDocument:null,o=n?function(t,e){for(const n of J(e)){const e=W(n);if(B(e)&&e.getKey()===t&&H(n))return n}return null}(r.editorKey,n):null;null!==o&&o.dispatchEvent(new InputEvent(\"beforeinput\",{bubbles:!0,cancelable:!0,inputType:\"deleteByDrag\"}))}return t.preventDefault(),!0}function vt(t,e){return Mt(t,e,Tt)}function $t(t,e){return Mt(t,e,(t,e)=>ht(t,e))}function Dt(t,e,n){t.dispatchCommand(g,{nodes:e,selection:n})||(n.insertNodes(e),function(t){if(l(t)&&t.isCollapsed()){const e=t.anchor;let n=null;const o=S(e,\"previous\");if(o)if($(o))n=o.origin;else{const t=R(o,F(a(),\"next\").getFlipped());for(const e of t){if(T(e.origin)){n=e.origin;break}if(d(e.origin)&&!e.origin.isInline())break}}if(n&&T(n)){const e=n.getFormat(),o=n.getStyle();t.format===e&&t.style===o||(t.format=e,t.style=o,t.dirty=!0)}}}(n))}function Pt(t,e,n,o=[]){let r=null===e||n.isSelected(e);const i=d(n)&&n.excludeFromCopy(\"clone\");let l=n;null!==e&&T(l)&&(l=nt(e,l,\"clone\"));const c=C(l),s=d(l)?l.getChildren():[],u=c.children||[];T(l)&&0===l.getTextContentSize()&&(r=!1);const f=r&&b(e)&&d(n)?null:e;for(let o=0;o<s.length;o++){const i=s[o],l=Pt(t,f,i,u);!r&&d(n)&&l&&n.extractWithChild(i,e,\"clone\")&&(r=!0)}if(r&&!i){const e=w(l);if(e.length>0){const n={};for(const o of e){const e=M(l,o);null===e&&lt(366,l.constructor.name,o);const r=[];Pt(t,null,e,r),(1!==r.length||d(e)&&e.excludeFromCopy(\"clone\"))&&lt(435,o,l.constructor.name,String(r.length)),n[o]=r[0]}c.$slots=n}}if(r&&!i)o.push(c);else for(let t=0;t<u.length;t++)o.push(u[t]);return r}function Nt(t,e){const n=[],o=a(),r=p(e),i=(d(r)?r:o).getChildren();for(let o=0;o<i.length;o++)Pt(t,e,i[o],n);return{namespace:t._config.namespace,nodes:n}}function St(t){const e=[];for(const n of t)e.push(m(n));return e}let Rt=null;async function Ft(t,e,n){if(null!==Rt)return!1;if(null!==e)return new Promise((o,r)=>{t.update(()=>{o(Et(t,e,n))})});const o=t.getRootElement(),r=t._window||window,i=r.document,l=y(r);if(null===o||null===l)return!1;const c=i.createElement(\"span\");c.style.position=\"fixed\",c.style.top=\"-1000px\",c.append(i.createTextNode(\"#\")),o.append(c);const s=i.createRange();return s.setStart(c,0),s.setEnd(c,1),l.removeAllRanges(),l.addRange(s),new Promise((e,o)=>{const l=t.registerCommand(x,o=>(ot(o,ClipboardEvent)&&(l(),null!==Rt&&(r.clearTimeout(Rt),Rt=null),e(Et(t,o,n))),!0),h);Rt=r.setTimeout(()=>{l(),Rt=null,e(!1)},50),i.execCommand(\"copy\"),c.remove()})}function Et(t,e,n){if(void 0===n){const e=y(t._window),o=c();if(!o||o.isCollapsed())return!1;if(!e)return!1;const r=E(e,t.getRootElement()),i=r.anchorNode,l=r.focusNode;if(null!==i&&null!==l&&!O(t,i,l))return!1;n=It(o)}e.preventDefault();const o=e.clipboardData;return null!==o&&(Kt(o,n),!0)}const Ot=[[\"text/html\",yt],[\"application/x-lexical-editor\",xt]];function It(t=c()){return function(t,e){const n={\"text/plain\":\"\"};for(const[o,r]of Object.entries(t))if(r){const t=kt(r,e);null!==t&&(n[o]=t)}return n}(At(),t)}function Kt(t,e){for(const[n]of Ot)void 0===e[n]&&t.setData(n,\"\");for(const n in e){const o=e[n];void 0!==o&&t.setData(n,o)}}function At(t=r()){const e=G(t,_t.name);return e?e.output:jt}const jt={\"application/x-lexical-editor\":[(t,e)=>t?xt(r(),t):e()],\"text/html\":[(t,e)=>t?yt(r(),t):e()],\"text/plain\":[(t,e)=>t?t.getTextContent():e()]};function kt(t,e){const n=o=>t[o]?t[o](e,n.bind(null,o-1)):null;return n(t.length-1)}function Lt(t,e=c()){return kt(At()[t]||[],e)}const _t={build:(t,e,n)=>e.$exportMimeType,config:{$exportMimeType:jt},mergeConfig(t,e){const n=i(t,e);if(e.$exportMimeType){const o={...t.$exportMimeType};for(const[t,n]of Object.entries(e.$exportMimeType))if(n){const e=o[t];o[t]=e?[...e,...n]:n}n.$exportMimeType=o}return n},name:\"@lexical/clipboard/GetClipboardData\"};export{Lt as $exportMimeTypeFromSelection,Nt as $generateJSONFromSelectedNodes,St as $generateNodesFromSerializedNodes,It as $getClipboardDataFromSelection,yt as $getHtmlContent,xt as $getLexicalContent,$t as $handlePlainTextDrop,vt as $handleRichTextDrop,ht as $insertDataTransferForPlainText,Tt as $insertDataTransferForRichText,Dt as $insertGeneratedNodes,bt as $writeDragSourceToDataTransfer,gt as ClipboardDOMImportExtension,mt as ClipboardImportExtension,ft as DEFAULT_IMPORT_MIME_TYPE,ct as DEFAULT_IMPORT_MIME_TYPE_PRIORITY,_t as GetClipboardDataExtension,it as caretFromPoint,Ft as copyToClipboard,Kt as setLexicalClipboardDataTransfer};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{effect as e}from\"@lexical/extension/signals\";import{namedSignals as t}from\"@lexical/extension/namedSignals\";import{watchedSignal as n}from\"@lexical/extension/watchedSignal\";import{$getSelection as i,$isRangeSelection as o,$isTextNode as s,getEditorPropertyFromDOMNode as r,getActiveElementDeep as l,isLexicalEditor as a}from\"lexical\";const d={bold:\"bold\",italic:\"italic\",strikeThrough:\"strikethrough\",subscript:\"subscript\",superscript:\"superscript\",underline:\"underline\"},c=Symbol.for(\"@lexical/dragon/WindowState\");function u(e=function(){return\"undefined\"!=typeof window?window:void 0}()){return e?f(e,Symbol(\"@lexical/dragon/globalInstall\"),void 0):()=>{}}function f(e,t,n){const i=function(e){let t=e[c];return void 0===t&&(t={dispose:()=>{},editors:new Map,installs:new Set},e[c]=t),t}(e);if(0===i.installs.size){const t=x.bind(e);e.addEventListener(\"message\",t,!0),i.dispose=()=>{e.removeEventListener(\"message\",t,!0)}}if(i.installs.add(t),n){const e=i.editors.get(n)||new Set;e.add(t),i.editors.set(n,e)}return g.bind(null,e,i,t,n)}function g(e,t,n,i){if(i){const e=t.editors.get(i);e&&e.delete(n)&&0===e.size&&t.editors.delete(i)}t.installs.delete(n)&&0===t.installs.size&&(t.dispose(),delete e[c])}function p(e){return e&&e.ownerDocument.defaultView}function m(t){const i=n(()=>p(t.getRootElement()),e=>t.registerRootListener(t=>{e.value=p(t)}));return e(()=>{const e=i.value;if(e)return f(e,Symbol(\"@lexical/dragon/editorInstall\"),t)})}function x(e){if(e.origin!==this.location.origin)return;const t=function(e){const t=e[c];if(void 0===t)return null;const n=r(l(e.document));return a(n)&&t.editors.has(n)?n:null}(this);if(null===t)return;const n=e.data;if(\"string\"==typeof n){let r;try{r=JSON.parse(n)}catch(e){return}if(r&&\"nuanria_messaging\"===r.protocol&&\"request\"===r.type){const n=r.payload;if(n&&\"makeChanges\"===n.functionId){const r=n.args;if(Array.isArray(r)){const[n,l,a,c,u,f]=r;if(![n,l,c,u].every(Number.isFinite)||\"string\"!=typeof a&&-1!==a)return;t.update(()=>{const t=i();if(o(t)){const i=t.anchor;let o=i.getNode(),r=0,g=0;if(s(o)&&n>=0&&l>=0&&(r=n,g=n+l,t.setTextNodeRange(o,r,o,g)),\"string\"!=typeof a||r===g&&\"\"===a||(t.insertRawText(a),o=i.getNode()),s(o)){const e=o.getTextContentSize();r=Math.min(Math.max(c,0),e),g=c<0||u<0?r:Math.min(c+u,e),t.setTextNodeRange(o,r,o,g)}if(\"string\"==typeof f&&u>0&&!t.isCollapsed()){const e=d[f];void 0!==e&&t.formatText(e)}e.stopImmediatePropagation()}})}}}}}const y={build:(e,n,i)=>t(n),config:{disabled:\"undefined\"==typeof window},name:\"@lexical/dragon\",register:(t,n,i)=>e(()=>i.getOutput().disabled.value?void 0:m(t))};export{y as DragonExtension,u as installDragonSupport,m as registerDragonSupport};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{$insertDataTransferForRichText as e,caretFromPoint as t,$handleRichTextDrop as n,setLexicalClipboardDataTransfer as r,$getClipboardDataFromSelection as o,$writeDragSourceToDataTransfer as i,copyToClipboard as s}from\"@lexical/clipboard\";import{effect as l,signal as a}from\"@lexical/extension/signals\";import{$isParentRTL as c,$shouldOverrideDefaultCharacterSelection as u,$moveCharacter as f}from\"@lexical/selection\";import{$isAtEndOfNode as d,$isAtStartOfNode as g,$handleIndentAndOutdent as m,eventFiles as p,objectKlassEquals as h,$getNearestBlockElementAncestorOrThrow as y}from\"@lexical/utils\";export{eventFiles}from\"@lexical/utils\";import{getterTableOf as x,setterTableOf as _,setterDefaultOf as C,$getNodeByKey as v,setNodeIndentFromDOM as S,$setFormatFromDOM as D,$setDirectionFromDOM as N,isHTMLElement as b,shallowMergeConfig as F,$applyNodeReplacement as T,createCommand as E,ElementNode as K,$getDocument as w,addClassNamesToElement as k,$createParagraphNode as I,$getState as O,$setState as A,createState as z,booleanValue as R,mergeRegister as P,CLICK_COMMAND as M,$getSelection as $,$isNodeSelection as L,$isRangeSelection as B,COMMAND_PRIORITY_EDITOR as q,DELETE_CHARACTER_COMMAND as J,DELETE_WORD_COMMAND as W,DELETE_LINE_COMMAND as H,CONTROLLED_TEXT_INSERTION_COMMAND as j,REMOVE_TEXT_COMMAND as V,FORMAT_TEXT_COMMAND as X,$formatText as Y,SET_TEXT_FORMAT_COMMAND as G,$setTextFormat as Q,FORMAT_ELEMENT_COMMAND as U,$findMatchingParent as Z,$isElementNode as ee,INSERT_LINE_BREAK_COMMAND as te,INSERT_PARAGRAPH_COMMAND as ne,INSERT_TAB_COMMAND as re,$createTabNode as oe,$insertNodes as ie,INDENT_CONTENT_COMMAND as se,OUTDENT_CONTENT_COMMAND as le,KEY_ARROW_UP_COMMAND as ae,KEY_ARROW_DOWN_COMMAND as ce,KEY_ARROW_LEFT_COMMAND as ue,KEY_ARROW_RIGHT_COMMAND as fe,KEY_BACKSPACE_COMMAND as de,IS_IOS as ge,CAN_USE_BEFORE_INPUT as me,KEY_DELETE_COMMAND as pe,KEY_ENTER_COMMAND as he,$isDecoratorNode as ye,IS_SAFARI as xe,IS_APPLE_WEBKIT as _e,KEY_ESCAPE_COMMAND as Ce,DROP_COMMAND as ve,$getNearestNodeFromDOMNode as Se,$createRangeSelection as De,$isTextNode as Ne,$normalizeSelection__EXPERIMENTAL as be,$setSelection as Fe,DRAGSTART_COMMAND as Te,DRAGOVER_COMMAND as Ee,SELECT_ALL_COMMAND as Ke,$selectAll as we,$getSlotFrame as ke,COPY_COMMAND as Ie,$isEventFromEmbeddedInput as Oe,CUT_COMMAND as Ae,PASTE_COMMAND as ze,KEY_SPACE_COMMAND as Re,KEY_TAB_COMMAND as Pe,MOVE_TO_END as Me,MOVE_TO_START as $e,nodeSchema as Le,withField as Be,enumValue as qe,$getSiblingCaret as Je,$comparePointCaretNext as We,$setSelectionFromCaretRange as He,$getCaretRangeInDirection as je,$getCaretRange as Ve,$rewindSiblingCaret as Xe,$flushSyncAfterUpdate as Ye,$getCollapsedCaretRange as Ge,$caretFromPoint as Qe,$isRootOrShadowRoot as Ue,$getEditor as Ze,getDOMSelection as et,$hasAncestor as tt,$getRoot as nt,$needsBlockCursorBeside as rt,$isRootNode as ot,INTERNAL_$expandSelectionToWholeDocument as it,CUT_TAG as st,PASTE_TAG as lt,$isShadowRootNode as at,$isSiblingCaret as ct,$extendCaretToRange as ut,$normalizeCaret as ft,$getChildCaret as dt,$createNodeSelection as gt}from\"lexical\";import{AriaLiveRegionExtension as mt}from\"@lexical/a11y\";import{namedSignals as pt}from\"@lexical/extension/namedSignals\";import{DragonExtension as ht}from\"@lexical/dragon\";import{NormalizeInlineElementsExtension as yt}from\"@lexical/extension/NormalizeInlineElementsExtension\";import{NormalizeTripleClickSelectionExtension as xt}from\"@lexical/extension/NormalizeTripleClickSelectionExtension\";import{sel as _t,BlockSchema as Ct,CoreImportExtension as vt,DOMImportExtension as St}from\"@lexical/html\";const Dt=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function Nt(e,t){if(\"number\"==typeof e)return Number.isFinite(e)?e:t;if(\"string\"!=typeof e||!Dt.test(e))return t;const n=Number(e);return Number.isFinite(n)?n:t}function bt(e,t,n,r,o){const i=Nt(e,t);return i>=n&&i<=r&&Number.isInteger(i)?i:t}function Ft(e,t){e.__tag=t.__tag}const Tt=e=>{const t=x(e,\"format\"),n=_(e,\"format\"),r=C(e,\"format\");return{exportJSON:function(e){const n=e.__textFormat,r=e.__textStyle,o=(0!==n||\"\"!==r)&&e.shouldSerializeTextStyles();return{children:[],tag:e.__tag,direction:e.__dir,format:t[e.__format],indent:e.__indent,textFormat:0!==n&&o?n:void 0,textStyle:\"\"!==r&&o?r:void 0,type:e.__type,version:1}},exportCompactJSON:function(e){const n=e.__textFormat,r=e.__textStyle,o=(0!==n||\"\"!==r)&&e.shouldSerializeTextStyles(),i={type:e.__type,children:[]},s=e.__tag;void 0!==s&&\"h1\"!==s&&(i.tag=s);const l=e.__dir;null!=l&&(i.direction=l);const a=t[e.__format];void 0!==a&&\"\"!==a&&(i.format=a);const c=e.__indent;return void 0!==c&&0!==c&&(i.indent=c),void 0!==n&&0!==n&&o&&(i.textFormat=n),void 0!==r&&\"\"!==r&&o&&(i.textStyle=r),i},updateFromJSON:function(e,t){const o=t.direction;e.__dir=null===o||\"ltr\"===o||\"rtl\"===o?o:null;const i=t.format;e.__format=\"string\"==typeof i&&i in n?n[i]:r,e.__indent=bt(t.indent,0,0,Infinity),e.__textFormat=Nt(t.textFormat,0);const s=t.textStyle;e.__textStyle=\"string\"==typeof s?s:\"\";const l=t.tag;return e.__tag=\"h1\"===l||\"h2\"===l||\"h3\"===l||\"h4\"===l||\"h5\"===l||\"h6\"===l?l:\"h1\",e},afterCloneFrom:Ft}},Et=e=>{const t=x(e,\"format\"),n=_(e,\"format\"),r=C(e,\"format\");return{exportJSON:function(e){const n=e.__textFormat,r=e.__textStyle,o=(0!==n||\"\"!==r)&&e.shouldSerializeTextStyles();return{children:[],direction:e.__dir,format:t[e.__format],indent:e.__indent,textFormat:0!==n&&o?n:void 0,textStyle:\"\"!==r&&o?r:void 0,type:e.__type,version:1}},exportCompactJSON:function(e){const n=e.__textFormat,r=e.__textStyle,o=(0!==n||\"\"!==r)&&e.shouldSerializeTextStyles(),i={type:e.__type,children:[]},s=e.__dir;null!=s&&(i.direction=s);const l=t[e.__format];void 0!==l&&\"\"!==l&&(i.format=l);const a=e.__indent;return void 0!==a&&0!==a&&(i.indent=a),void 0!==n&&0!==n&&o&&(i.textFormat=n),void 0!==r&&\"\"!==r&&o&&(i.textStyle=r),i},updateFromJSON:function(e,t){const o=t.direction;e.__dir=null===o||\"ltr\"===o||\"rtl\"===o?o:null;const i=t.format;e.__format=\"string\"==typeof i&&i in n?n[i]:r,e.__indent=bt(t.indent,0,0,Infinity),e.__textFormat=Nt(t.textFormat,0);const s=t.textStyle;return e.__textStyle=\"string\"==typeof s?s:\"\",e}}};function Kt(e){const t=v(e);return Xt(t)?t.getTag():null}const wt={build:(e,t)=>pt(t),config:{created:\"Heading level %s\",destroyed:\"Heading level %s removed\",disabled:!1},dependencies:[mt],name:\"@lexical/rich-text/HeadingAnnounce\",register(e,t,n){const{created:r,destroyed:o,disabled:i}=n.getOutput(),{announce:s}=n.getDependency(mt).output;return l(()=>i.value?void 0:e.registerMutationListener(Jt,(t,{prevEditorState:n})=>{let i=null,l=null;for(const[r,o]of t)\"created\"===o&&null===i?i=e.read(\"latest\",()=>Kt(r)):\"destroyed\"===o&&null===l&&(l=n.read(()=>Kt(r)));null!==i?s(r.peek().replace(\"%s\",i.slice(1))):null!==l&&s(o.peek().replace(\"%s\",l.slice(1)))},{skipInitialization:!0}))}},kt={$import:(e,t)=>{const n=Vt(t.nodeName.toLowerCase());return S(t,n),D(n,t),N(n,t),[n.splice(0,0,e.$importChildren(t))]},match:/* @__PURE__ */_t.tag(\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\"),name:\"@lexical/rich-text/heading\"},It={$import:(e,t)=>{const n=Lt();return D(n,t),S(t,n),N(n,t),[n.splice(0,0,e.$importChildren(t))]},match:/* @__PURE__ */_t.tag(\"blockquote\"),name:\"@lexical/rich-text/blockquote\"},Ot={$import:(e,t)=>{const n=Lt({shadowRoot:!0});return D(n,t),S(t,n),N(n,t),[n.splice(0,0,e.$importChildren(t,{schema:Ct}))]},match:/* @__PURE__ */_t.tag(\"blockquote\"),name:\"@lexical/rich-text/blockquote-shadow-root\"},At=[kt,It,{$import:(e,t,n)=>{const r=t.firstChild;return r&&b(o=r)&&\"SPAN\"===o.nodeName&&\"26pt\"===o.style.fontSize?e.$importChildren(t):n();var o},match:/* @__PURE__ */_t.tag(\"p\"),name:\"@lexical/rich-text/google-docs-title-p\"},{$import:(e,t,n)=>\"26pt\"!==t.style.fontSize?n():[Vt(\"h1\").splice(0,0,e.$importChildren(t))],match:/* @__PURE__ */_t.tag(\"span\"),name:\"@lexical/rich-text/google-docs-title-span\"}];function zt(e,t){return e&&null!==t?F(e,t):t}const Rt={build:(e,t)=>pt(t),config:{escapeFormatTriggers:{capitalize:{enter:!0,space:!0,tab:!0},lowercase:{enter:!0,space:!0,tab:!0},uppercase:{enter:!0,space:!0,tab:!0}},shouldHandlePasteAsFiles:fn},conflictsWith:[\"@lexical/plain-text\"],dependencies:[wt,ht,yt,xt,vt,[St,{rules:At}]],mergeConfig:function(e,t){const n=F(e,t);return t.escapeFormatTriggers&&(n.escapeFormatTriggers=function(e,t){const n=F(e,t);for(const r of Object.keys(t))n[r]=zt(e[r],t[r]);return n}(e.escapeFormatTriggers,t.escapeFormatTriggers)),n},name:\"@lexical/rich-text\",nodes:()=>[Jt,$t],register:(e,t,n)=>l(()=>{const{escapeFormatTriggers:t,shouldHandlePasteAsFiles:r}=n.getOutput();return dn(e,t,r)})},Pt=/* @__PURE__ */E(\"DRAG_DROP_PASTE_FILE\"),Mt=/* @__PURE__ */z(\"shadowRoot\",{parse:/* @__PURE__ */R()});class $t extends K{$config(){return this.config(\"quote\",{children:\"inline\",extends:K,generated:Et,importDOM:{blockquote:()=>({conversion:jt,priority:0})},stateConfigs:[{flat:!0,stateConfig:Mt}]})}isShadowRoot(){return O(this,Mt)}setIsShadowRoot(e){return A(this,Mt,e)}createDOM(e){const t=w().createElement(\"blockquote\");return k(t,e.theme.quote),t}updateDOM(e,t,n){return!1}exportDOM(e){const{element:t}=super.exportDOM(e);if(b(t)){this.isEmpty()&&t.append(w().createElement(\"br\"));const e=this.getFormatType();e&&(t.style.textAlign=e);const n=this.getDirection();n&&(t.dir=n)}return{element:t}}static importJSON(e){return Lt().updateFromJSON(e)}insertNewAfter(e,t){const n=I();n.setTextFormat(e.format),n.setTextStyle(e.style);const r=this.getDirection();return n.setDirection(r),n.setFormat(this.getFormatType()),n.setStyle(this.getStyle()),this.insertAfter(n,t),n}collapseAtStart(){if(this.isShadowRoot()){for(const e of this.getChildren())this.insertBefore(e);return this.remove(),!0}const e=I();return this.getChildren().forEach(t=>e.append(t)),this.replace(e),!0}canMergeWhenEmpty(){return!0}}function Lt(e){const t=T(new $t);return e&&e.shadowRoot?t.setIsShadowRoot(!0):t}function Bt(e){return e instanceof $t}const qt=/* @__PURE__ */Le()({tag:/* @__PURE__ */Be(/* @__PURE__ */qe([\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\"]),{field:\"__tag\"})});class Jt extends K{__tag;$config(){return this.config(\"heading\",{children:\"inline\",extends:K,generated:Tt,importDOM:{h1:()=>({conversion:Ht,priority:0}),h2:()=>({conversion:Ht,priority:0}),h3:()=>({conversion:Ht,priority:0}),h4:()=>({conversion:Ht,priority:0}),h5:()=>({conversion:Ht,priority:0}),h6:()=>({conversion:Ht,priority:0}),p:e=>{const t=e.firstChild;return null!==t&&Wt(t)?{conversion:()=>({node:null}),priority:3}:null},span:e=>Wt(e)?{conversion:()=>({node:Vt(\"h1\")}),priority:3}:null},json:qt})}constructor(e=\"h1\",t){super(t),this.__tag=e}getTag(){return this.getLatest().__tag}setTag(e){const t=this.getWritable();return t.__tag=e,t}createDOM(e){const t=this.__tag,n=w().createElement(t),r=e.theme.heading;if(void 0!==r){const e=r[t];k(n,e)}return n}updateDOM(e,t,n){return e.__tag!==this.__tag}exportDOM(e){const{element:t}=super.exportDOM(e);if(b(t)){this.isEmpty()&&t.append(w().createElement(\"br\"));const e=this.getFormatType();e&&(t.style.textAlign=e);const n=this.getDirection();n&&(t.dir=n)}return{element:t}}insertNewAfter(e,t=!0){const n=!this.getLastDescendant()||e&&d(e.anchor,this),r=e&&g(e.anchor,this),o=n||!e?I():Vt(this.getTag()).setFormat(this.getFormatType()).setStyle(this.getStyle()),i=this.getDirection();if(o.setDirection(i),this.insertAfter(o,t),r&&!this.isEmpty()){const e=I();e.select(),this.replace(e,!0)}return o}collapseAtStart(){if(this.isEmpty()){const e=I();this.getChildren().forEach(t=>e.append(t)),this.replace(e)}return!0}extractWithChild(){return!0}}function Wt(e){return\"span\"===e.nodeName.toLowerCase()&&\"26pt\"===e.style.fontSize}function Ht(e){const t=e.nodeName.toLowerCase();let n=null;return\"h1\"!==t&&\"h2\"!==t&&\"h3\"!==t&&\"h4\"!==t&&\"h5\"!==t&&\"h6\"!==t||(n=Vt(t),S(e,n),D(n,e),N(n,e)),{node:n}}function jt(e){const t=Lt();return D(t,e),S(e,t),N(t,e),{node:t}}function Vt(e=\"h1\"){return T(new Jt(e))}function Xt(e){return e instanceof Jt}function Yt(e){return ye(Se(e))&&!(b(e)&&e.hasAttribute(\"data-lexical-slot\"))}function Gt(e){const t=e.focus;return\"root\"===t.key&&t.offset===nt().getChildrenSize()}function Qt(e){const t=e.focus;return\"root\"===t.key&&0===t.offset}function Ut(e,t){if(!e.isCollapsed())return!1;const n=\"next\"===t;if(!(n?Gt(e):Qt(e)))return!1;const r=e.focus.offset;return rt(nt().getChildAtIndex(n?r-1:r))}function Zt(e,t,n,r){let o=!1,i=null;if(e.isCollapsed()&&\"text\"===e.anchor.type){const t=e.anchor.getNode();if(Ne(t)){i=t;const r=e.anchor.offset,s=r===t.getTextContentSize()&&null===t.getNextSibling(),l=0===r&&null===t.getPreviousSibling();o=\"end\"===n&&s||\"start\"===n&&l||\"both\"===n&&(s||l)}}let s=!1;for(const[n,l]of Object.entries(r)){if(null==l||!l[t])continue;const r=n;if(l.onlyAtBoundary){if(!(o&&i&&Ne(i)&&i.hasFormat(r)))continue;s=!0}e.hasFormat(r)&&e.toggleFormat(r)}s&&e.setStyle(\"\")}const en={capitalize:{enter:!0,space:!0,tab:!0},lowercase:{enter:!0,space:!0,tab:!0},uppercase:{enter:!0,space:!0,tab:!0}};function tn(e,t){return function(e,t){if(!e.isCollapsed())return!1;const n=Qe(e.focus,t),r=Z(n.origin,at);if(!r)return!1;const o=e.focus.getNode();if(!r.is(o)&&!tt(o,r))return!1;const i=Ve(n,Je(r,t));if(i.getTextSlices().some(e=>e&&e.getTextContentSize()>0))return!1;const s=Ve(i.anchor.getSiblingCaret(),i.focus);let l=s.anchor.origin;for(const e of s){if(!ct(e)||!e.origin.is(l.getParent()))return!1;l=e.origin}let a=r;for(const e of ut(Je(r,t))){if(!e.origin.is(a.getParent())){if(rt(e.origin)){const e=Je(a,t);return He(Ve(e,e)),!0}break}if(!at(e.origin))break;a=e.origin}return!1}(e,t)||function(e,t){if(!e.isCollapsed()||\"element\"!==e.anchor.type)return!1;const n=Qe(e.anchor,t).getNodeAtCaret();return!(!at(n)||n.isInline()||(He(Ge(ft(dt(n,t)))),0))}(e,t)}function nn(e){return ye(e)&&!e.isInline()&&!e.isIsolated()&&e.isKeyboardSelectable()}function rn(e){const t=gt();t.add(e),Fe(t)}function on(e,t){if(!e.isCollapsed())return!1;const n=e.focus,r=n.getNode(),o=t?\"previous\":\"next\",i=Qe(n,o);if(\"element\"===n.type&&ee(r)&&Ue(r)){const e=i.getNodeAtCaret();return!(null===e||!nn(e)||(rn(e.__key),0))}const s=Z(ee(r)?r:r.getParentOrThrow(),e=>ee(e)&&!e.isInline()&&Ue(e.getParent()));if(null===s)return!1;const l=Je(s,o).getNodeAtCaret();if(null===l||!nn(l))return!1;if(0===s.getTextContentSize())return rn(l.__key),!0;const a=Ze().getRootElement();if(null===a)return!1;const c=et(a.ownerDocument.defaultView);if(null===c||0===c.rangeCount)return!1;const u=c.anchorNode,f=c.anchorOffset,d=c.focusNode,g=c.focusOffset;c.modify(\"move\",t?\"backward\":\"forward\",\"line\");const m=c.anchorNode,p=c.anchorOffset;if(null===m)return sn(c,u,f,d,g),!1;const h=Se(m);return sn(c,u,f,d,g),null!==h&&((m===u&&p===f||!h.is(s)&&!tt(h,s))&&(rn(l.__key),!0))}function sn(e,t,n,r,o){null!==t&&null!==r&&e.setBaseAndExtent(t,n,r,o)}function ln(e,n){if(!e.isCollapsed())return!1;const r=e.focus.getNode(),o=Z(ee(r)?r:r.getParentOrThrow(),e=>ee(e)&&!e.isInline());if(null===o)return!1;const i=Ze(),s=i.getRootElement();if(null===s)return!1;const l=s.ownerDocument.defaultView;if(null===l)return!1;let a=!1;for(const e of o.getChildren())if(ee(e)&&e.isInline()){const t=i.getElementByKey(e.getKey());if(null!==t){const e=l.getComputedStyle(t).display;if(\"inline-grid\"===e||\"inline-flex\"===e){a=!0;break}}}if(!a)return!1;const c=Je(o,n?\"previous\":\"next\").getNodeAtCaret();if(null===c||!ee(c)){if(n){const e=o.getFirstDescendant();Ne(e)?e.select(0,0):o.select(0,0)}else{const e=o.getLastDescendant();if(Ne(e)){const t=e.getTextContentSize();e.select(t,t)}else{const e=o.getChildrenSize();o.select(e,e)}}return!0}const u=i.getElementByKey(c.getKey());if(null===u)return!1;const f=et(l);if(null===f||0===f.rangeCount)return!1;const d=f.getRangeAt(0).cloneRange();d.collapse(!0);const g=d.getBoundingClientRect(),m=u.getBoundingClientRect(),p=m.top+m.height/2;if(g.height>0){const n=t(g.left,p,s);if(null!==n&&u.contains(n.node)){const t=s.ownerDocument.createRange();return t.setStart(n.node,n.offset),t.collapse(!0),e.applyDOMRange(t),e.dirty=!0,!0}}const h=n?c.getLastDescendant():c.getFirstDescendant();if(Ne(h)){const e=n?h.getTextContentSize():0;h.select(e,e)}else{const e=c.getChildrenSize();c.select(n?e:0,n?e:0)}return!0}function an(e,t){const n=Je(e,t),r=n.getAdjacentCaret();null!==r&&ee(r.origin)&&!r.origin.isInline()&&r.origin.isShadowRoot()?He(Ge(n)):\"next\"===t?e.selectNext(0,0):e.selectPrevious()}function cn(e,t){const n=e.getNodes().map(e=>Je(e,\"next\")).sort(We),r=n[0],o=n[n.length-1];if(!r||!o)return!1;for(let e=0;e<n.length-1;e++)if(!n[e+1].origin.is(n[e].getNodeAtCaret()))return!1;return He(je(Ve(Xe(r),o),t)),Ye(),!0}function un(e,t,n){n.preventDefault(),n.stopPropagation();const r=e.getNodes();if(0===r.length)return!0;const o=r.map(e=>Je(e,\"next\")).sort(We),i=(t?o[0]:o[o.length-1]).origin,s=Z(i,e=>e!==i&&ee(e)&&!e.isInline())??nt(),l=t?0:s.getChildrenSize();return s.select(l,l),!0}function fn(e,t){return e.length>0&&!t}function dn(l,d=a(en),g=a(fn)){return P(l.registerCommand(M,e=>{const t=$();if(L(t)){const n=e.target;if(b(n))for(const e of t.getNodes()){const t=l.getElementByKey(e.getKey());if(null!==t&&t.contains(n))return!1}return t.clear(),!0}return B(t)&&Zt(t,\"click\",\"both\",d.peek()),!1},q),l.registerCommand(J,e=>{const t=$();return B(t)?(t.deleteCharacter(e),!0):!!L(t)&&(t.deleteNodes(),!0)},q),l.registerCommand(W,e=>{const t=$();return!!B(t)&&(t.deleteWord(e),!0)},q),l.registerCommand(H,e=>{const t=$();return!!B(t)&&(t.deleteLine(e),!0)},q),l.registerCommand(j,t=>{const n=$();if(\"string\"==typeof t)null!==n&&n.insertText(t);else{if(null===n)return!1;const r=t.dataTransfer;if(null!=r)e(r,n,l);else if(B(n)){const e=t.data;return e&&n.insertText(e),!0}}return!0},q),l.registerCommand(V,()=>{const e=$();return!!B(e)&&(e.removeText(),!0)},q),l.registerCommand(X,e=>{const t=$();return!(!B(t)&&!L(t)||(Y(t,e),0))},q),l.registerCommand(G,e=>{const t=$();return!(!B(t)&&!L(t)||(Q(t,e),0))},q),l.registerCommand(U,e=>{const t=$();if(!B(t)&&!L(t))return!1;const n=t.getNodes();for(const t of n){const n=Z(t,e=>ee(e)&&!e.isInline());null!==n&&n.setFormat(e)}return!0},q),l.registerCommand(te,e=>{const t=$();return!!B(t)&&(t.insertLineBreak(e),!0)},q),l.registerCommand(ne,()=>{const e=$();return!!B(e)&&(e.insertParagraph(),!0)},q),l.registerCommand(re,()=>{const e=oe(),t=$();return B(t)&&(e.setFormat(t.format),e.setStyle(t.style)),ie([e]),!0},q),l.registerCommand(se,()=>m(e=>{const t=e.getIndent();e.setIndent(t+1)}),q),l.registerCommand(le,()=>m(e=>{const t=e.getIndent();t>0&&e.setIndent(Math.max(0,t-1))}),q),l.registerCommand(ae,e=>{let t=$();if(L(t)){const n=t.getNodes();if(n.length>0){if(!e.shiftKey||!cn(t,\"previous\"))return e.preventDefault(),an(n[0],\"previous\"),!0;t=$()}}if(B(t)){if(Qt(t))return e.preventDefault(),!0;if(!e.shiftKey&&tn(t,\"previous\"))return e.preventDefault(),!0;if(!e.shiftKey&&on(t,!0))return e.preventDefault(),!0;if(!e.shiftKey&&ln(t,!0))return e.preventDefault(),!0}return!1},q),l.registerCommand(ce,e=>{let t=$();if(L(t)){const n=t.getNodes();if(n.length>0){if(!e.shiftKey||!cn(t,\"next\"))return e.preventDefault(),an(n[0],\"next\"),!0;t=$()}}if(B(t)){if(Gt(t))return e.preventDefault(),!0;if(!e.shiftKey&&tn(t,\"next\"))return e.preventDefault(),!0;if(!e.shiftKey&&on(t,!1))return e.preventDefault(),!0;if(!e.shiftKey&&ln(t,!1))return e.preventDefault(),!0}return!1},q),l.registerCommand(ue,e=>{let t=$();if(L(t)){const n=t.getNodes();if(n.length>0){const r=c(n[0])?\"next\":\"previous\";if(!e.shiftKey||!cn(t,r))return e.preventDefault(),an(n[0],r),!0;t=$()}}if(!B(t))return!1;const n=c(t.anchor.getNode())?\"next\":\"previous\";if(Ut(t,n))return e.preventDefault(),!0;if(!e.shiftKey&&tn(t,n))return e.preventDefault(),!0;if(e.shiftKey||Zt(t,\"arrow\",\"start\",d.peek()),u(t,!0)){const n=e.shiftKey;return e.preventDefault(),f(t,n,!0),!0}return!1},q),l.registerCommand(fe,e=>{let t=$();if(L(t)){const n=t.getNodes();if(n.length>0){const r=c(n[0])?\"previous\":\"next\";if(!e.shiftKey||!cn(t,r))return e.preventDefault(),an(n[0],r),!0;t=$()}}if(!B(t))return!1;const n=c(t.anchor.getNode())?\"previous\":\"next\";if(Ut(t,n))return e.preventDefault(),!0;if(!e.shiftKey&&tn(t,n))return e.preventDefault(),!0;if(e.shiftKey||Zt(t,\"arrow\",\"end\",d.peek()),u(t,!1)){const n=e.shiftKey;return e.preventDefault(),f(t,n,!1),!0}return!1},q),l.registerCommand(de,e=>{const t=$();if(!L(t)&&Yt(e.target))return!1;if(B(t)){if(function(e){if(!e.isCollapsed())return!1;const{anchor:t}=e;if(0!==t.offset)return!1;const n=t.getNode();if(ot(n))return!1;const r=y(n);return r.getIndent()>0&&(r.is(n)||n.is(r.getFirstDescendant()))}(t))return e.preventDefault(),l.dispatchCommand(le);if(ge&&me)return!1}else if(!L(t))return!1;return e.preventDefault(),l.dispatchCommand(J,!0)},q),l.registerCommand(pe,e=>{const t=$();return!(!L(t)&&Yt(e.target))&&!(!B(t)&&!L(t))&&(e.preventDefault(),l.dispatchCommand(J,!1))},q),l.registerCommand(he,e=>{let t=$();if(L(t)){const e=t.getNodes();1===e.length&&ye(e[0])&&!e[0].isInline()&&(t=e[0].selectNext())}if(!B(t))return!1;if(Zt(t,\"enter\",\"both\",d.peek()),null!==e){if((ge||xe||_e)&&me)return!1;if(e.preventDefault(),e.shiftKey)return l.dispatchCommand(te,!1)}return l.dispatchCommand(ne)},q),l.registerCommand(Ce,()=>{const e=$();return!!B(e)&&(l.blur(),!0)},q),l.registerCommand(ve,e=>{const[,r]=p(e);if(r.length>0){const n=e.clientX,o=e.clientY,i=t(n,o,l.getRootElement());if(null!==i){const{offset:e,node:t}=i,n=Se(t);if(null!==n){const t=De();if(Ne(n))t.anchor.set(n.getKey(),e,\"text\"),t.focus.set(n.getKey(),e,\"text\");else{const e=n.getParentOrThrow().getKey(),r=n.getIndexWithinParent()+1;t.anchor.set(e,r,\"element\"),t.focus.set(e,r,\"element\")}const r=be(t);Fe(r)}}return!(!l.dispatchCommand(Pt,r)&&ge&&r.every(e=>\"text/plain\"===e.type)||(e.preventDefault(),0))}return n(e,l)},q),l.registerCommand(Te,e=>{const[t]=p(e),n=$();return!(t&&!B(n)||(B(n)&&!n.isCollapsed()&&null!==e.dataTransfer&&(r(e.dataTransfer,o(n)),i(e.dataTransfer,l)),0))},q),l.registerCommand(Ee,e=>{const[n]=p(e),r=$();if(n&&!B(r))return!1;const o=e.clientX,i=e.clientY,s=t(o,i,l.getRootElement());if(null!==s){const t=Se(s.node);ye(t)&&e.preventDefault()}return!0},q),l.registerCommand(Ke,()=>{const e=$();return we(B(e)&&null!==ke(e.anchor.getNode())?e:null),!0},q),l.registerCommand(Ie,e=>!Oe(e)&&(s(l,h(e,ClipboardEvent)?e:null),!0),q),l.registerCommand(Ae,e=>!Oe(e)&&(async function(e,t){t.update(()=>{const e=$();B(e)&&!e.isCollapsed()&&it(e)},{discrete:!0,tag:st}),await s(t,h(e,ClipboardEvent)?e:null),t.update(()=>{const e=$();B(e)?e.removeText():L(e)&&e.getNodes().forEach(e=>e.remove())},{tag:st})}(e,l),!0),q),l.registerCommand(ze,t=>{const[,n,r]=p(t);return!(!g.peek()(n,r)||!l.dispatchCommand(Pt,n))||!Oe(t)&&(null!==$()&&(function(t,n){t.preventDefault(),n.update(()=>{const r=$(),o=h(t,InputEvent)||h(t,KeyboardEvent)?null:t.clipboardData;null!=o&&null!==r&&e(o,r,n)},{tag:lt})}(t,l),!0))},q),l.registerCommand(Re,()=>{const e=$();return B(e)&&Zt(e,\"space\",\"both\",d.peek()),!1},q),l.registerCommand(Pe,()=>{const e=$();return B(e)&&Zt(e,\"tab\",\"both\",d.peek()),!1},q),l.registerCommand(Me,e=>{const t=$();if(L(t))return un(t,!1,e);if(!B(t))return!1;const{anchor:n}=t;if(\"element\"!==n.type||0!==n.offset)return!1;const r=n.getNode();if(!ee(r))return!1;const o=r.getFirstChild();if(!ye(o)||!o.isInline())return!1;const i=r.getKey(),s=r.selectEnd();return e.shiftKey&&s.anchor.set(i,0,\"element\"),e.preventDefault(),e.stopPropagation(),!0},q),l.registerCommand($e,e=>{const t=$();if(L(t))return un(t,!0,e);if(!B(t))return!1;const{anchor:n,focus:r}=t,o=Z(r.getNode(),e=>ee(e)&&!e.isInline());if(null===o)return!1;const i=o.getFirstChild();if(!ye(i)||!i.isInline())return!1;if(Z(n.getNode(),e=>ee(e)&&!e.isInline())!==o)return!1;const s=o.getKey();return(\"element\"!==r.type||r.key!==s||0!==r.offset)&&(t.focus.set(s,0,\"element\"),e.shiftKey||t.anchor.set(s,0,\"element\"),e.preventDefault(),e.stopPropagation(),!0)},q))}export{Vt as $createHeadingNode,Lt as $createQuoteNode,Xt as $isHeadingNode,Bt as $isQuoteNode,Pt as DRAG_DROP_PASTE,wt as HeadingAnnounceExtension,Jt as HeadingNode,$t as QuoteNode,Rt as RichTextExtension,At as RichTextImportRules,Ot as ShadowRootQuoteRule,fn as defaultShouldHandlePasteAsFiles,Mt as quoteShadowRootState,dn as registerRichText};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{$isParagraphNode as t,$isTextNode as e,$setState as n,$createTextNode as o,$getState as r,$findMatchingParent as s,$createLineBreakNode as l,createState as i,$isLineBreakNode as c,$getRoot as f,$isElementNode as u,$isDecoratorNode as a,$isTabNode as d,$createTabNode as g,$createParagraphNode as h,mergeRegister as p,COLLABORATION_TAG as x,HISTORIC_TAG as m,COMPOSITION_END_TAG as C,$getSelection as I,$isRangeSelection as T,$addUpdateTag as v,HISTORY_PUSH_TAG as $,KEY_ENTER_COMMAND as y,COMMAND_PRIORITY_LOW as E,$isRootOrShadowRoot as S,$createRangeSelection as b,$setSelection as w,TEXT_TYPE_TO_FORMAT as N,ArtificialNode__DO_NOT_USE as k}from\"lexical\";import{$sliceSelectedTextNodeContent as F}from\"@lexical/selection\";import{CodeNode as O,$createCodeNode as P,$isCodeNode as M}from\"@lexical/code-core\";import{LinkNode as R,$isLinkNode as _,$createLinkNode as B,$isAutoLinkNode as L}from\"@lexical/link\";import{ListNode as A,ListItemNode as j,$isListNode as z,$createListItemNode as W,$createListNode as U,$isListItemNode as D}from\"@lexical/list\";import{HeadingNode as X,QuoteNode as Z,$isHeadingNode as H,$isQuoteNode as K,$createQuoteNode as q,$createHeadingNode as G}from\"@lexical/rich-text\";function J(t,e){const n={};for(const o of t){const t=e(o);t&&(n[t]?n[t].push(o):n[t]=[o])}return n}function Q(t){const e=J(t,t=>t.type);return{element:e.element||[],multilineElement:e[\"multiline-element\"]||[],textFormat:e[\"text-format\"]||[],textMatch:e[\"text-match\"]||[]}}const V=/[!-/:-@[-`{-~\\s]/,Y=/\\s/,tt=/[!\"#$%&'()*+,\\-./:;<=>?@[\\]^_`{|}~]/,et=/^\\s{0,3}$/;function nt(n){if(!t(n))return!1;const o=n.getFirstChild();return null==o||1===n.getChildrenSize()&&e(o)&&et.test(o.getTextContent())}function ot(t){return t.replace(/\\\\([!-/:-@[-`{-~])|&#(?:(\\d{1,7})|[xX]([\\da-fA-F]{1,6}));/g,(t,e,n,o)=>e??function(t,e){const n=void 0!==t?Number(t):parseInt(e,16);return 0===n||n>=55296&&n<=57343||n>1114111?\"\\ufffd\":String.fromCodePoint(n)}(n,o))}function rt(t,e){let n=0;for(let o=e-1;o>=0&&\"\\\\\"===t[o];o--)n++;return n%2==1}function st(t){const e=e=>{let n=0;for(let o=e-1;o>=0&&\"\\\\\"===t[o];o--)n++;return n%2==1},n=[];let o=0;for(;o<t.length;)if(\"`\"===t[o]){let e=1;for(;o+e<t.length&&\"`\"===t[o+e];)e++;n.push({index:o,length:e}),o+=e}else o++;const r=[];let s=0;for(;s<n.length;){const o=n[s];if(e(o.index)){s++;continue}let l=-1;for(let t=s+1;t<n.length;t++)if(n[t].length===o.length){l=t;break}if(-1===l){s++;continue}const i=n[l];let c=t.slice(o.index+o.length,i.index);c.length>=2&&c.startsWith(\" \")&&c.endsWith(\" \")&&/[^ ]/.test(c)&&(c=c.slice(1,-1)),r.push({content:c,endIndex:i.index+i.length,startIndex:o.index}),s=l+1}return r}function lt(t,e,n,o,r){if(!it(e,n,o,r))return!1;if(\"*\"===t)return!0;if(\"_\"===t){if(!it(e,n,o,!r))return!0;const t=r?e[n-1]:e[n+o];return void 0!==t&&tt.test(t)}return!0}function it(t,e,n,o){const r=t[e-1],s=t[e+n],[l,i]=o?[s,r]:[r,s];return void 0!==l&&!Y.test(l)&&(!tt.test(l)||void 0===i||Y.test(i)||tt.test(i))}const ct=/^(\\s*)(\\d{1,})\\.\\s/,ft=/^(\\s*)[-*+]\\s/,ut=/^(\\s*)(?:[-*+]\\s)?\\s?(\\[(\\s|x)?\\])\\s/i,at=/^(#{1,6})\\s/,dt=/^>\\s/,gt=/^([ \\t]*`{3,})([\\w-]+)?[ \\t]?/,ht=/^[ \\t]*`{3,}$/,pt=/^[ \\t]*```[^`]+(?:(?:`{1,2}|`{4,})[^`]+)*```(?:[^`]|$)/,xt=/^(?:\\|)(.+)(?:\\|)\\s?$/;function mt(t){if(\"|\"!==t[0])return!1;const{length:e}=t;let n=1,o=0;for(;n<e;){let e=n;for(\" \"===t[e]&&e++,\":\"===t[e]&&e++;\"-\"===t[e];)e++;if(\":\"===t[e]&&e++,\" \"===t[e]&&e++,\"|\"!==t[e])break;o++,n=e+1}return o>0&&(n===e||n===e-1&&/\\s/.test(t[n]))}const Ct=/^<[a-z_][\\w-]*(?:\\s[^<>]*)?\\/?>/i,It=/^<\\/[a-z_][\\w-]*\\s*>/i,Tt=t=>new RegExp(`(?:${t.source})$`,t.flags),vt=/* @__PURE__ */i(\"mdListMarker\",{parse:t=>\"string\"==typeof t&&/^[-*+]$/.test(t)?t:\"-\",resetOnCopyNode:!0}),$t=/* @__PURE__ */i(\"mdCodeFence\",{parse:t=>\"string\"==typeof t&&/^`{3,}$/.test(t)?t:\"```\",resetOnCopyNode:!0}),yt=/* @__PURE__ */i(\"mdCodeMeta\",{parse:t=>\"string\"==typeof t?t:\"\",resetOnCopyNode:!0}),Et=/* @__PURE__ */i(\"mdHardLineBreak\",{parse:t=>\"string\"==typeof t&&/^(\\\\| {2,})$/.test(t)?t:\"\",resetOnCopyNode:!0});function St(t){if(t.endsWith(\"\\\\\")){let e=0;for(let n=t.length-1;n>=0&&\"\\\\\"===t[n];n--)e++;return e%2==1?[t.slice(0,-1),\"\\\\\"]:null}const e=t.match(/^(.*?\\S)( {2,})$/);return e?[e[1],e[2]]:null}function bt(t){const o=l(),r=function(t){const n=t.getChildren(),o=n.length-1,r=n[o];if(!e(r))return null;const s=r.getTextContent(),l=St(s);if(null!==l){const[t,e]=l;return r.setTextContent(t),e}return/^ {2,}$/.test(s)&&function(t,e){for(let n=e-1;n>=0;n--){if(c(t[n]))return!1;if(/\\S/.test(t[n].getTextContent()))return!0}return!1}(n,o)?(r.setTextContent(\"\"),s):null}(t);return null!==r&&n(o,Et,r),o}function wt(t){return K(t)}function Nt(t,e){let n=0;for(;n<e&&(\" \"===t[n]||\"\\t\"===t[n]);)n++;return t.slice(n)}function kt(t,e){const o=t.getLastChild();e&&M(o)&&n(o,yt,e)}const Ft=t=>(e,n,o,r)=>{const s=t(o);s.append(...n),e.replace(s),r||s.select(0,0)};function Ot(t){let e=0;for(const n of t)e+=\"\\t\"===n?4-e%4:1;return e}let Pt=null,Mt=!1;const Rt=t=>(e,o,r,s)=>{if(H(e)||!s&&wt(e))return!1;const l=e.getPreviousSibling(),i=e.getNextSibling(),c=W(\"check\"===t?/^x$/i.test(r[3]||\"\"):void 0),f=r[0].trim()[0],u=\"bullet\"!==t&&\"check\"!==t||f!==vt.parse(f)?void 0:f,a=Pt;let d=l;if(null!==a){if(Mt)for(;null!==d&&nt(d);)d=d.getPreviousSibling();z(d)||(a.length=0)}const g=null===a||0===a.length?function(t){const e=t.match(/\\t/g),n=t.match(/ /g);let o=0;return e&&(o+=e.length),n&&(o+=Math.floor(n.length/4)),o}(r[1]):function(t,e){const n=Ot(e);for(let e=t.length-1;e>=0;e--)if(n>=t[e])return e+1;return 0}(a,r[1]);if(z(i)&&i.getListType()===t){const n=i.getFirstChild();null!==n?n.insertBefore(c):i.append(c),\"number\"===t&&0===g&&i.setStart(Number(r[2])),e.remove()}else if(z(d)&&(d.getListType()===t||g>0))d.append(c),e.remove();else{const n=U(t,\"number\"===t?Number(r[2]):void 0);n.append(c),e.replace(n)}c.append(...o),s||c.select(0,0),g&&(c.setIndent(g),function(t,e,n){const o=t.getParent();if(!z(o)||o.getListType()===e)return;const r=o.getParent();if(!D(r))return;const s=U(e,\"number\"===e?Number(n[2]):void 0),l=null===t.getPreviousSibling();s.append(t);const i=W();i.append(s),l?r.insertBefore(i):r.insertAfter(i),0===o.getChildrenSize()&&r.remove()}(c,t,r));const h=c.getParent();u&&z(h)&&n(h,vt,u),null!==a&&function(t,e,n,o){for(let n=t.length;n<e;n++)t[n]=4*(n+1);t.length=e,t[e]=function(t,e){let n=t[0];if(\"check\"===e){const e=n.slice(t[1].length).match(/^[-*+]\\s/);e&&(n=t[1]+e[0])}return Math.min(Ot(n),Ot(t[1])+4)}(n,o)}(a,g,r,t)},_t=(t,e,n,o)=>{const s=[],l=t.getChildren();let i=0;for(const c of l)if(D(c)){if(1===c.getChildrenSize()){const t=c.getFirstChild();if(z(t)){const r=_t(t,e,n+1,o);r&&s.push(r);continue}}if(o&&!c.getChildren().some(t=>t.isSelected(o)))continue;const l=\" \".repeat(4*n),f=t.getListType(),u=r(t,vt),a=\"number\"===f?`${t.getStart()+i}. `:\"check\"===f?`${u} [${c.getChecked()?\"x\":\" \"}] `:u+\" \";let d=e(c);\"number\"!==f&&(d=d.replace(/^(\\s{0,3}\\d+)(\\.\\s)/,\"$1\\\\$2\")),s.push(l+a+d),i++}return s.join(\"\\n\")},Bt=/* @__PURE__ */Ft(t=>{const e=\"h\"+t[1].length;return G(e)}),Lt={dependencies:[X],export:(t,e)=>{if(!H(t))return null;const n=Number(t.getTag().slice(1));return\"#\".repeat(n)+\" \"+e(t)},regExp:at,replace:(t,e,n,o)=>!(!o&&wt(t))&&Bt(t,e,n,o),triggerOnEnter:!0,type:\"element\"},At={dependencies:[Z],export:(t,e)=>{if(!K(t))return null;const n=e(t).split(\"\\n\"),o=[];for(const t of n)o.push(\"> \"+t);return o.join(\"\\n\")},regExp:dt,replace:(t,e,n,o)=>{if(o){const n=t.getPreviousSibling();if(K(n))return n.splice(n.getChildrenSize(),0,[bt(n),...e]),void t.remove()}const r=q();r.append(...e),t.replace(r),o||r.select(0,0)},triggerOnEnter:!0,type:\"element\"},jt={dependencies:[O],export:t=>{if(!M(t))return null;const e=t.getTextContent();let n=r(t,$t);if(e.indexOf(n)>-1){const t=e.match(/`{3,}/g);if(t){const e=Math.max(...t.map(t=>t.length));n=\"`\".repeat(e+1)}}const o=t.getLanguage()||\"\",s=o?r(t,yt):\"\";return n+o+(s?\" \"+s:\"\")+(e?\"\\n\"+e:\"\")+\"\\n\"+n},handleImportAfterStartMatch:({lines:t,rootNode:e,startLineIndex:n,startMatch:o})=>{const r=o[1],s=r.trim().length,l=t[n],i=o.index+r.length,c=l.slice(i),f=new RegExp(`\\`{${s},}$`);if(f.test(c)){const t=c.match(f),r=c.slice(0,c.lastIndexOf(t[0])),s=[...o];return s[2]=\"\",jt.replace(e,null,s,t,[r],!0),[!0,n]}const u=new RegExp(`^[ \\\\t]*\\`{${s},}$`);for(let r=n+1;r<t.length;r++){const s=t[r];if(u.test(s)){const i=s.match(u),c=t.slice(n+1,r),f=o[2]?l.slice(o[0].length).trim():\"\";return c.unshift(f?\"\":l.slice(o[0].length)),jt.replace(e,null,o,i,c,!0),kt(e,f),[!0,r]}}const a=t.slice(n+1);return a.unshift(l.slice(o[0].length)),jt.replace(e,null,o,null,a,!0),[!0,t.length-1]},regExpEnd:{optional:!0,regExp:ht},regExpStart:gt,replace:(t,e,r,s,l,i)=>{let c,f;const u=r[1]?r[1].trim():\"```\",a=r[2]||void 0,d=r[1]?r[1].length-r[1].trimStart().length:0;if(!e&&l){if(1===l.length)s?(c=P(a),f=Nt(l[0],d)):(c=P(a),f=l[0].startsWith(\" \")?l[0].slice(1):l[0]);else{for(c=P(a),l.length>0&&(0===l[0].trim().length?l.shift():l[0].startsWith(\" \")&&(l[0]=l[0].slice(1)));l.length>0&&!l[l.length-1].length;)l.pop();f=l.map(t=>Nt(t,d)).join(\"\\n\")}n(c,$t,u);const e=o(f);c.append(e),t.append(c)}else if(e){if(!i&&wt(t))return!1;Ft(t=>P(t?t[2]:void 0))(t,e,r,i)}},type:\"multiline-element\"},zt={dependencies:[A,j],export:(t,e,n)=>z(t)?_t(t,e,0,n):null,regExp:ft,replace:/* @__PURE__ */Rt(\"bullet\"),triggerOnEnter:!0,type:\"element\"},Wt={dependencies:[A,j],export:(t,e,n)=>z(t)?_t(t,e,0,n):null,regExp:ut,replace:/* @__PURE__ */Rt(\"check\"),triggerOnEnter:!0,type:\"element\"},Ut={dependencies:[A,j],export:(t,e,n)=>z(t)?_t(t,e,0,n):null,regExp:ct,replace:/* @__PURE__ */Rt(\"number\"),triggerOnEnter:!0,type:\"element\"},Dt={format:[\"code\"],tag:\"`\",type:\"text-format\"},Xt={format:[\"highlight\"],tag:\"==\",type:\"text-format\"},Zt={format:[\"bold\",\"italic\"],tag:\"***\",type:\"text-format\"},Ht={format:[\"bold\",\"italic\"],intraword:!1,tag:\"___\",type:\"text-format\"},Kt={format:[\"bold\"],tag:\"**\",type:\"text-format\"},qt={format:[\"bold\"],intraword:!1,tag:\"__\",type:\"text-format\"},Gt={format:[\"strikethrough\"],tag:\"~~\",type:\"text-format\"},Jt={format:[\"italic\"],tag:\"*\",type:\"text-format\"},Qt={format:[\"italic\"],intraword:!1,tag:\"_\",type:\"text-format\"};function Vt(t){return t.replace(/&(?=#\\d+;|#[Xx][\\dA-Fa-f]+;|[A-Za-z][\\dA-Za-z]*;)/g,\"&#38;\")}const Yt={dependencies:[R],export:(t,e,n)=>{if(!_(t)||L(t))return null;const o=e(t);let r=t.getTitle();null!=r&&(r=Vt(r).replace(/([\\\\\"])/g,\"\\\\$1\"));const s=t.getURL(),l=Vt(s),i=\"\"===s||/\\s/.test(s)?`<${l.replace(/([\\\\<>])/g,\"\\\\$1\").replace(/\\r/g,\"&#13;\").replace(/\\n/g,\"&#10;\")}>`:l.replace(/([\\\\()])/g,\"\\\\$1\").replace(/^</,\"\\\\<\");return r?`[${o}](${i} \"${r}\")`:`[${o}](${i})`},importRegExp:/(?:\\[(.+?)\\])(?:\\(\\s*(?:(?:<((?:\\\\.|[^<>\\n\\\\])*)>|((?!<)(?:\\\\[^\\s]|\\\\(?=\\s)|\\((?:\\\\[^\\s]|[^\\s()\\\\]|\\((?:\\\\[^\\s]|[^\\s()\\\\]|\\((?:\\\\[^\\s]|[^\\s()\\\\])*\\))*\\))*\\)|[^\\s()\\\\])+))(?:\\s+(?:\"((?:[^\"]*\\\\\")*[^\"]*)\"|'((?:[^']*\\\\')*[^']*)'|\\(((?:\\\\.|[^()\\\\])*)\\)))?\\s*)?\\))/,regExp:/(?:\\[([^[\\]]*(?:\\[[^[\\]]*\\][^[\\]]*)*)\\])(?:\\(\\s*(?:(?:<((?:\\\\.|[^<>\\n\\\\])*)>|((?!<)(?:\\\\[^\\s]|\\\\(?=\\s)|\\((?:\\\\[^\\s]|[^\\s()\\\\]|\\((?:\\\\[^\\s]|[^\\s()\\\\]|\\((?:\\\\[^\\s]|[^\\s()\\\\])*\\))*\\))*\\)|[^\\s()\\\\])+))(?:\\s+(?:\"((?:[^\"]*\\\\\")*[^\"]*)\"|'((?:[^']*\\\\')*[^']*)'|\\(((?:\\\\.|[^()\\\\])*)\\)))?\\s*)?\\))$/,replace:(t,e)=>{const n=e.input||\"\",r=e.index||0;if(s(t,_)||rt(n,r)||rt(n,r+e[1].length+1))return;const[,l,i,c,f,u,a]=e,d=ot(i??c??\"\"),g=f??u??a,h=null!=g?ot(g):void 0,p=B(d,{title:h}),x=function(t){const e=st(t);let n=0;const o=t.replace(/\\\\.|[[\\]]/g,(t,o)=>{for(;n<e.length&&o>=e[n].endIndex;)n++;return n<e.length&&o>=e[n].startIndex||\"\\\\\"===t[0]?\" \".repeat(t.length):t}),r=[];let s=!1;for(let t=0;t<o.length;t++){const e=o[t];\"[\"===e?r.push(t):\"]\"===e&&void 0===r.pop()&&(s=!0)}return r.pop()??(s?null:-1)}(l);if(null===x)return;let m=l,C=\"\";-1!==x&&(C=\"[\"+function(t){let e=\"\",n=0;for(const{startIndex:o,endIndex:r}of st(t))e+=ot(t.slice(n,o))+t.slice(o,r),n=r;return e+ot(t.slice(n))}(l.slice(0,x)),m=l.slice(x+1));const I=t.getFormat(),T=o(m);return T.setFormat(I),p.append(T),t.replace(p),C&&p.insertBefore(o(C).setFormat(I)),T},trigger:\")\",type:\"text-match\"},te=[Lt,At,zt,Ut],ee=[jt],ne=[Dt,Zt,Ht,Kt,qt,Xt,Jt,Qt,Gt],oe=[Yt];function re(...t){return t.flat()}const se=/* @__PURE__ */re(te,ee,ne,oe);function le(t,e=!1){const n=t.split(\"\\n\");let o=0;const r=[];for(let t=0;t<n.length;t++){const s=n[t],l=s.trimEnd(),i=r[r.length-1],c=t<n.length-1?St(s):null,f=void 0!==i&&null!==St(i);if(pt.test(l))r.push(l);else if(0===o){{const t=l.match(gt);if(t){o=t[1].trim().length,r.push(l);continue}}\"\"===l||\"\"===i||!i||at.test(i)||at.test(l)||dt.test(l)||ct.test(l)||ft.test(l)||ut.test(l)||xt.test(l)||mt(l)||f||!e||Ct.test(l)||It.test(l)||Tt(It).test(i)||Tt(Ct).test(i)||ht.test(i)?r.push(!e&&\"\"!==l||null!==c?s:l):r[r.length-1]=i+\" \"+(null===c?l:s).trimStart()}else{if(ht.test(l)&&l.trim().length>=o){o=0,r.push(l);continue}r.push(s)}}return r.join(\"\\n\")}function ie(t,e,n,o,r,s){let l=t.isSelected(e);for(const i of n){if(!i.export)continue;const n=i.export(t,t=>ce(t,e,o,r,s).markdown,e);if(null!=n)return!l&&u(t)&&ce(t,e,o,r,s).shouldInclude&&(l=!0),{markdown:n,shouldInclude:l}}if(u(t)){const n=ce(t,e,o,r,s);return{markdown:n.markdown,shouldInclude:l||n.shouldInclude}}return a(t)?{markdown:t.getTextContent(),shouldInclude:l}:{markdown:null,shouldInclude:l}}function ce(t,n,o,r,s,l,i){const f=[],d=t.getChildren();let g=!1;l||(l=[]),i||(i=[]);t:for(const t of d){let d=t.isSelected(n);for(const e of r){if(!e.export)continue;const c=e.export(t,t=>ce(t,n,o,r,s,l,[...i,...l]).markdown,(t,e)=>de(t,F(n,t,\"clone\").getTextContent(),o,l,i,s));if(null!=c){!d&&u(t)&&t.getChildren().some(t=>t.isSelected(n))&&t.extractWithChild(t,n,\"html\")&&(d=!0),d&&(f.push(c),g=!0);continue t}}if(c(t))d&&(f.push(ae(t)),g=!0);else if(e(t)){if(d){const e=F(n,t,\"clone\");f.push(de(t,e.getTextContent(),o,l,i,s)),g=!0}}else if(u(t)){const e=ce(t,n,o,r,s,l,i);!d&&e.shouldInclude&&t.extractWithChild(t,n,\"html\")&&(d=!0),(d||e.shouldInclude)&&(f.push(e.markdown),g=!0)}else a(t)&&d&&(f.push(t.getTextContent()),g=!0)}return{markdown:f.join(\"\"),shouldInclude:g}}function fe(t,e,n,o,r){for(const s of e){if(!s.export)continue;const e=s.export(t,t=>ue(t,n,o,void 0,void 0,r));if(null!=e)return e}return u(t)?ue(t,n,o,void 0,void 0,r):a(t)?t.getTextContent():null}function ue(t,n,o,r,s,l=!1){const i=[],f=t.getChildren();r||(r=[]),s||(s=[]);t:for(const t of f){for(const e of o){if(!e.export)continue;const c=e.export(t,t=>ue(t,n,o,r,[...s,...r],l),(t,e)=>de(t,e,n,r,s,l));if(null!=c){i.push(c);continue t}}c(t)?i.push(ae(t)):e(t)?i.push(de(t,t.getTextContent(),n,r,s,l)):u(t)?i.push(ue(t,n,o,r,s,l)):a(t)&&i.push(t.getTextContent())}return i.join(\"\")}function ae(t){return r(t,Et)+\"\\n\"}function de(t,e,n,o,r,s=!1){const l=t.hasFormat(\"code\");let i,c,f,u,a=e;if(l||(a=s?a.replace(/([*_`~])/g,\"\\\\$1\"):a.replace(/([[\\]*_`~\\\\]|<(?=\\S|$)|&(?=#|$))/g,t=>/[*_`~\\\\]/.test(t)?`\\\\${t}`:`&#${t.charCodeAt(0)};`)),l){const{fence:t,padded:n}=function(t){const e=t.match(/`+/g),n=e?Math.max(...e.map(t=>t.length)):0;return{fence:\"`\".repeat(n+1),padded:0===t.length||t.includes(\"`\")||/^\\s/.test(t)&&/\\s$/.test(t)?` ${t} `:t}}(e);i=\"\",f=\"\",c=t+n+t,u=!1}else{const t=a.match(/^(\\s*)(.*?)(\\s*)$/s)||[\"\",\"\",a,\"\"];i=t[1],c=t[2],f=t[3],u=\"\"===c}let d=\"\",g=\"\",h=\"\";const p=ge(t,!0),x=ge(t,!1),m=new Set;for(const e of n){const n=e.format[0],r=e.tag;\"code\"!==n&&(u||!pe(t,n)||m.has(n)||(m.add(n),pe(p,n)&&o.find(t=>t.tag===r)||(o.push({format:n,tag:r}),d+=r)))}for(let e=0;e<o.length;e++){const n=he(t,o[e].format),s=he(x,o[e].format);if(n&&s)continue;const l=[...o];for(;l.length>e;){const t=l.pop();r&&t&&r.find(e=>e.tag===t.tag)||(t&&\"string\"==typeof t.tag&&(n?s||(h+=t.tag):g+=t.tag),o.pop())}break}return u&&!t.hasFormat(\"code\")?g+a:g+i+d+c+h+f}function ge(t,n){const o=n?t.getPreviousSibling():t.getNextSibling();return e(o)?o:null}function he(t,n){return e(t)&&t.hasFormat(n)}function pe(t,e){return!(!he(t,e)||\"code\"!==e&&t&&/^\\s*$/.test(t.getTextContent()))}function xe(t,e){const n=new RegExp(e.source,e.flags.replace(/[gy]/g,\"\")+\"g\");let o;for(;null!==(o=n.exec(t));){if(!rt(t,o.index))return o;n.lastIndex=o.index+1}return null}function me(t){return e(t)&&!t.hasFormat(\"code\")}function Ce(t,e,n){let o=function(t,e){const n=t.getTextContent(),o=e.transformersByTag[\"`\"],r=[];let s=null;if(o){const t=st(n);for(const e of t)s||(s={content:e.content,endIndex:e.endIndex,startIndex:e.startIndex,tag:\"`\"}),r.push({end:e.endIndex,start:e.startIndex})}const l=function(t,e,n=[]){const o=[],r=new Set(Object.keys(e.transformersByTag).filter(t=>\"`\"!==t[0]).map(t=>t[0])),s=e=>{let n=0;for(let o=e-1;o>=0&&\"\\\\\"===t[o];o--)n++;return n%2==1},l=t=>n.some(e=>t>=e.start&&t<e.end);let i=0;for(;i<t.length;){const e=t[i];if(!r.has(e)||s(i)||l(i)){i++;continue}let n=1;for(;i+n<t.length&&t[i+n]===e;)n++;const c=lt(e,t,i,n,!0),f=lt(e,t,i,n,!1);(c||f)&&o.push({active:!0,canClose:f,canOpen:c,char:e,index:i,length:n}),i+=n}return o}(n,e,r),i=l.length>0?function(t,e,n){const o={};let r=0,s=null;for(;r<e.length;){const l=e[r];if(!l.active||!l.canClose||0===l.length){r++;continue}const i=`${l.char}${l.canOpen}${l.length%3}`,c=o[i]??-1;let f=!1;for(let o=r-1;o>c;o--){const i=e[o];if(!i.active||!i.canOpen||0===i.length||i.char!==l.char)continue;if((i.canClose||l.canOpen)&&(i.length+l.length)%3==0&&i.length%3!=0&&l.length%3!=0)continue;const c=Math.min(i.length,l.length),u=Object.keys(n.transformersByTag).filter(t=>t[0]===i.char&&t.length<=c).sort((t,e)=>e.length-t.length)[0];if(!u)continue;f=!0;const a=u.length,d={content:t.slice(i.index+i.length,l.index),endIndex:l.index+a,startIndex:i.index+(i.length-a),tag:u};(!s||d.startIndex<s.startIndex||d.startIndex===s.startIndex&&d.endIndex>s.endIndex)&&(s=d);for(let t=o+1;t<r;t++)e[t].active=!1;i.length-=a,l.length-=a,i.active=i.length>0,l.length>0?l.index+=a:(l.active=!1,r++);break}f||(o[i]=r-1,l.canOpen||(l.active=!1),r++)}return s}(n,l,e):null;let c=null,f=null;if(s&&i?i.startIndex<=s.startIndex&&i.endIndex>=s.endIndex?(c=i,f=e.transformersByTag[i.tag]):(c=s,f=o):s?(c=s,f=o):i&&(c=i,f=e.transformersByTag[i.tag]),!c||!f)return null;const u=[n.slice(c.startIndex,c.endIndex),c.tag,c.content];return u.index=c.startIndex,u.input=n,{endIndex:c.endIndex,isCodeSpan:f===o,match:u,startIndex:c.startIndex,transformer:f}}(t,e),r=function(t,e){const n=t;let o,r,s,l;for(const t of e){if(!t.replace||!t.importRegExp)continue;const e=n.getTextContent(),i=void 0!==Yt.importRegExp&&t.importRegExp.source===Yt.importRegExp.source?xe(e,t.importRegExp):e.match(t.importRegExp);if(!i)continue;const c=i.index||0,f=t.getEndIndex?t.getEndIndex(n,i):c+i[0].length;!1!==f&&(void 0===o||void 0===r||c<o&&(f>r||f<=o))&&(o=c,r=f,s=t,l=i)}return void 0===o||void 0===r||void 0===s||void 0===l?null:{endIndex:r,match:l,startIndex:o,transformer:s}}(t,n);if(o&&r&&(o.isCodeSpan?r.startIndex<=o.startIndex&&r.endIndex>=o.endIndex?o=null:r=null:o.startIndex<=r.startIndex&&o.endIndex>=r.endIndex||r.startIndex>o.endIndex?r=null:o=null),o){const r=function(t,e,n,o,r){const s=t.getTextContent();let l,i,c;if(r[0]===s?l=t:0===e?[l,i]=t.splitText(n):[c,l,i]=t.splitText(e,n),l.setTextContent(r[2]),o)for(const t of o.format)l.hasFormat(t)||l.toggleFormat(t);return{nodeAfter:i,nodeBefore:c,transformedNode:l}}(t,o.startIndex,o.endIndex,o.transformer,o.match);me(r.nodeAfter)&&Ce(r.nodeAfter,e,n),me(r.nodeBefore)&&Ce(r.nodeBefore,e,n),me(r.transformedNode)&&Ce(r.transformedNode,e,n)}else if(r){const o=function(t,e,n,o,r){let s,l,i;return 0===e?[s,l]=t.splitText(n):[i,s,l]=t.splitText(e,n),o.replace?{matchedNode:s,nodeAfter:l,nodeBefore:i,transformedNode:o.replace(s,r)||void 0}:null}(t,r.startIndex,r.endIndex,r.transformer,r.match);if(!o)return;me(o.nodeAfter)&&Ce(o.nodeAfter,e,n),me(o.nodeBefore)&&Ce(o.nodeBefore,e,n),me(o.transformedNode)?Ce(o.transformedNode,e,n):void 0===o.transformedNode&&me(o.matchedNode)&&null!==o.matchedNode.getParent()&&o.matchedNode.setTextContent(ot(o.matchedNode.getTextContent()))}if(!o&&!r){const e=ot(t.getTextContent());t.setTextContent(e)}}function Ie(t,e,n,o=!1){const r=Q(n),s=function(t){const e={},n={},o=[];for(const r of t){const{tag:t}=r;e[t]=r;const s=t.replace(/(\\*|\\^|\\+)/g,\"\\\\$1\");o.push(s),1===t.length?n[t]=\"`\"===t?new RegExp(\"(^|[^\\\\\\\\`])(`)((?:\\\\\\\\`|[^`])+?)(`)(?!`)\"):new RegExp(`(^|[^\\\\\\\\${s}])(${s})((\\\\\\\\${s})?.*?[^${s}\\\\s](\\\\\\\\${s})?)(${s})(?![\\\\\\\\${s}])`):n[t]=new RegExp(`(^|[^\\\\\\\\])(${s})((\\\\\\\\${s})?.*?[^\\\\s](\\\\\\\\${s})?)(${s})(?!\\\\\\\\)`)}return{fullMatchRegExpByTag:n,openTagsRegExp:new RegExp(`(${o.join(\"|\")})`,\"g\"),transformersByTag:e}}(r.textFormat),l=t.split(\"\\n\"),i=l.length;!function(t){const n=Pt,c=Mt;Pt=[],Mt=t;try{return(()=>{for(let t=0;t<i;t++){const n=l[t],[i,c]=Te(l,t,r.multilineElement,e);i?t=c:ve(n,e,r.element,s,r.textMatch,o)}})()}finally{Pt=n,Mt=c}}(!o);const c=e.getChildren();for(const t of c)if(!o&&nt(t)&&e.getChildrenSize()>1)t.remove();else if(u(t))for(const e of t.getAllTextNodes())$e(e)}function Te(t,e,n,o){for(const r of n){const{handleImportAfterStartMatch:n,regExpEnd:s,regExpStart:l,replace:i}=r,c=t[e].match(l);if(!c)continue;if(n){const s=n({lines:t,rootNode:o,startLineIndex:e,startMatch:c,transformer:r});if(null===s)continue;if(s)return s}const f=\"object\"==typeof s&&\"regExp\"in s?s.regExp:s,u=s&&\"object\"==typeof s&&\"optional\"in s?s.optional:!s;let a=e;const d=t.length;for(;a<d;){const n=f?t[a].match(f):null;if(!n&&(!u||u&&a<d-1)){a++;continue}if(n&&e===a&&n.index===c.index){a++;continue}const r=[];if(n&&e===a)r.push(t[e].slice(c[0].length,-n[0].length));else for(let o=e;o<=a;o++)if(o===e){const e=t[o].slice(c[0].length);r.push(e)}else if(o===a&&n){const e=t[o].slice(0,-n[0].length);r.push(e)}else r.push(t[o]);if(!1!==i(o,null,c,n,r,!0))return[!0,a];break}}return[!1,e]}function ve(e,n,r,l,i,c){const f=o(e),u=h();u.append(f),n.append(u);for(const{regExp:t,replace:n}of r){const o=e.match(t);if(o&&(f.setTextContent(e.slice(o[0].length)),!1!==n(u,[f],o,!0)))break}if(Ce(f,l,i),null!==u.getParent()&&e.length>0){const e=u.getPreviousSibling();if(!c&&(t(e)||K(e)||z(e))){let t=e;if(z(e)){const n=e.getLastDescendant();t=null==n?null:s(n,D)}null!=t&&t.getTextContentSize()>0&&(t.splice(t.getChildrenSize(),0,[bt(t),...u.getChildren()]),u.remove())}}}function $e(t){if(d(t))return;const e=t.getTextContent();if(!e.includes(\"\\t\"))return;const n=t.getFormat(),r=t.getStyle(),s=[];let l=0;for(let t=e.indexOf(\"\\t\");-1!==t;t=e.indexOf(\"\\t\",t+1))t>l&&s.push(o(e.slice(l,t)).setFormat(n).setStyle(r)),s.push(g()),l=t+1;l<e.length&&s.push(o(e.slice(l)).setFormat(n).setStyle(r)),t.getParentOrThrow().splice(t.getIndexWithinParent(),1,s)}function ye(t,...e){throw function(t,...e){const n=new URL(\"https://lexical.dev/docs/error\"),o=new URLSearchParams;o.append(\"code\",t);for(const t of e)o.append(\"v\",t);return n.search=o.toString(),new Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(t,...e)}function Ee(t,e,n,o,r){const s=t.getParent();if(!S(s)||t.getFirstChild()!==e)return!1;const l=e.getTextContent();if(!r&&\" \"!==l[n-1])return!1;for(const{regExp:s,replace:i}of o){const o=l.match(s),c=r||o&&o[0].endsWith(\" \")?n:n-1;if(o&&o[0].length===c){const r=e.getNextSiblings(),[s,l]=e.splitText(n);if(!1!==i(t,l?[l,...r]:r,o,!1))return s.remove(),!0}}return!1}function Se(t,e,n,o,r){const s=t.getParent();if(!S(s)||t.getFirstChild()!==e)return!1;const l=e.getTextContent();if(!r&&\" \"!==l[n-1])return!1;for(const{regExpStart:s,replace:i,regExpEnd:c}of o){if(c&&!(\"optional\"in c)||c&&\"optional\"in c&&!c.optional)continue;const o=l.match(s);if(o){const s=r||o[0].endsWith(\" \")?n:n-1;if(o[0].length!==s)continue;const l=e.getNextSiblings(),[c,f]=e.splitText(n);if(!1!==i(t,f?[f,...l]:l,o,null,null,!1))return c.remove(),!0}}return!1}function be(t,e){let n=0;const o=t.getTextContent();for(let t=0;t<e;t++)\"`\"===o[t]&&n++;return n%2!=0}function we(t,e,n){const o=n.length;for(let r=e;r>=o;r--){const e=r-o;if(ke(t,e,n,0,o)&&\" \"!==t[e+o])return e}return-1}function Ne(t){const n=t.getNode();let o=0;if(e(n))o=t.offset;else if(u(n))for(const e of n.getChildren().slice(0,t.offset))o+=e.getTextContentSize();for(let t=n.getPreviousSibling();null!==t;t=t.getPreviousSibling())o+=t.getTextContentSize();return o}function ke(t,e,n,o,r){for(let s=0;s<r;s++)if(t[e+s]!==n[o+s])return!1;return!0}function Fe(t,n=se){const o=Q(n),r=o.element.filter(t=>t.triggerOnEnter),s=J(o.textFormat,({tag:t})=>t[t.length-1]),l=J(o.textMatch,({trigger:t})=>t),i=new Set([\" \"]);for(const t of o.textFormat)i.add(t.tag.slice(-1));for(const t of o.textMatch)void 0!==t.trigger&&i.add(t.trigger);for(const e of n){const n=e.type;if(\"element\"===n||\"text-match\"===n||\"multiline-element\"===n){const n=e.dependencies;for(const e of n)t.hasNode(e)||ye(173,e.getType())}}return p(t.registerUpdateListener(({tags:n,dirtyLeaves:r,editorState:f,prevEditorState:u})=>{if(n.has(x)||n.has(m))return;if(t.isComposing())return;const a=n.has(C),d=f.read(I),g=u.read(I);if(!T(g)||!T(d)||!d.isCollapsed()||d.is(g)&&!a)return;const h=d.anchor.key,p=d.anchor.offset,y=f._nodeMap.get(h);if(e(y)&&r.has(h)&&(a||1===p||!(f.read(()=>Ne(d.anchor))>u.read(()=>Ne(g.anchor))+1))){if(a){const t=f.read(()=>y.getTextContent())[p-1];if(!i.has(t))return}t.update(()=>{if(!me(y))return;const t=y.getParent();null===t||M(t)||((t,n,r)=>!!(Ee(t,n,r,o.element)||Se(t,n,r,o.multilineElement)||function(t,e,n){let o=t.getTextContent();const r=n[o[e-1]];if(null==r)return!1;e<o.length&&(o=o.slice(0,e));for(const e of r){if(!e.replace||!e.regExp)continue;const n=o.match(e.regExp);if(null===n)continue;const r=n.index||0,s=r+n[0].length;let l;return 0===r?[l]=t.splitText(s):[,l]=t.splitText(r,s),l.selectNext(0,0),e.replace(l,n),!0}return!1}(n,r,l)||function(t,n,o){const r=t.getTextContent(),s=n-1,l=r[s],i=o[l];if(!i)return!1;for(const n of i){const{tag:o}=n,i=o.length,f=s-i+1;if(i>1&&!ke(r,f,o,0,i))continue;if(\" \"===r[f-1])continue;const u=r[s+1];if(!1===n.intraword&&u&&!V.test(u))continue;const a=t;let d=a,g=we(r,f,o),h=d;for(;g<0&&(h=h.getPreviousSibling())&&!c(h);)if(e(h)){if(h.hasFormat(\"code\"))continue;const t=h.getTextContent();d=h,g=we(t,t.length,o)}if(g<0)continue;if(d===a&&g+i===f)continue;const p=d.getTextContent();if(g>0&&p[g-1]===l)continue;const x=p[g-1];if(!1===n.intraword&&x&&!V.test(x))continue;if(!n.format.includes(\"code\")&&be(d,g))continue;const m=a.getTextContent(),C=m.slice(0,f)+m.slice(s+1);a.setTextContent(C);const v=d===a?C:p;d.setTextContent(v.slice(0,g)+v.slice(g+i));const $=I(),y=b();w(y);const E=s-i*(d===a?2:1)+1;y.anchor.set(d.__key,g,\"text\"),y.focus.set(a.__key,E,\"text\");for(const t of n.format)y.formatText(t,N[t]);y.anchor.set(y.focus.key,y.focus.offset,y.focus.type);for(const t of n.format)y.hasFormat(t)&&y.toggleFormat(t);return T($)&&(y.format=$.format),!0}return!1}(n,r,s)))(t,y,d.anchor.offset)&&v($)})}}),t.registerCommand(y,t=>{if(null!==t&&t.shiftKey)return!1;const n=I();if(!T(n)||!n.isCollapsed())return!1;const s=n.anchor.offset,l=n.anchor.getNode();if(!e(l)||!me(l))return!1;const i=l.getParent();return null!==i&&!M(i)&&!(s!==l.getTextContent().length||!Se(i,l,s,o.multilineElement,!0)&&!Ee(i,l,s,r,!0)||(null!==t&&t.preventDefault(),0))},E))}function Oe(t,e=se,n,o=!1,r=!1){const s=o?t:le(t,r),l=n||f();l.clear(),Ie(s,l,e,o),null!==I()&&l.selectStart()}function Pe(t,e=se,n=!1,o=!1){const r=n?t:le(t,o),s=new k;return Ie(r,s,e,n),s.getChildren()}function Me(t=se,e,n=!1){const o=function(t,e=!1){const n=Q(t),o=[...n.multilineElement,...n.element],r=!e,s=n.textFormat.filter(t=>1===t.format.length).sort((t,e)=>Number(t.format.includes(\"code\"))-Number(e.format.includes(\"code\")));return t=>{const l=[],i=(t||f()).getChildren();for(let t=0;t<i.length;t++){const c=i[t],f=fe(c,o,s,n.textMatch,e);null!=f&&l.push(r&&t>0&&!nt(c)&&!nt(i[t-1])?\"\\n\".concat(f):f)}return l.join(\"\\n\")}}(t,n);return o(e)}function Re(t=se,e,n=!1){if(!e||T(e)&&e.isCollapsed())return\"\";const o=function(t,e=!1){const n=Q(t),o=[...n.multilineElement,...n.element],r=!e,s=n.textFormat.filter(t=>1===t.format.length).sort((t,e)=>Number(t.format.includes(\"code\"))-Number(e.format.includes(\"code\")));return t=>{const l=[];let i=null;for(const c of f().getChildren()){const{shouldInclude:f,markdown:u}=ie(c,t,o,s,n.textMatch,e);f&&null!=u&&(l.push(!r||null===i||nt(c)||nt(i)?u:\"\\n\".concat(u)),i=c)}return l.join(\"\\n\")}}(t,n);return o(e)}export{Oe as $convertFromMarkdownString,Re as $convertSelectionToMarkdownString,Me as $convertToMarkdownString,Pe as $generateNodesFromMarkdownString,Zt as BOLD_ITALIC_STAR,Ht as BOLD_ITALIC_UNDERSCORE,Kt as BOLD_STAR,qt as BOLD_UNDERSCORE,Wt as CHECK_LIST,jt as CODE,te as ELEMENT_TRANSFORMERS,Lt as HEADING,Xt as HIGHLIGHT,Dt as INLINE_CODE,Jt as ITALIC_STAR,Qt as ITALIC_UNDERSCORE,Yt as LINK,ee as MULTILINE_ELEMENT_TRANSFORMERS,Ut as ORDERED_LIST,At as QUOTE,Gt as STRIKETHROUGH,ne as TEXT_FORMAT_TRANSFORMERS,oe as TEXT_MATCH_TRANSFORMERS,se as TRANSFORMERS,zt as UNORDERED_LIST,mt as isTableRowDivider,Fe as registerMarkdownShortcuts};\n","/**\n * Regular expression sources and helpers to read the Markdown syntax, shared by the Markdown\n * processing and the transformers. They don’t depend on Lexical.\n */\n\nimport { CODE_TAB_PLACEHOLDER } from '../placeholder-chars.js';\n\n/**\n * Regular expression source to match the place after a character that isn’t escaped: one preceded\n * by an even number of backslashes, which escape each other.\n */\nexport const UNESCAPED_LOOKBEHIND = String.raw`(?<!(?:^|[^\\\\])(?:\\\\\\\\)*\\\\)`;\n\n/**\n * Count the backslashes right before the given index, which escape the character there if their\n * number is odd. They’re counted rather than matched with a regular expression, which would take\n * quadratic time on a long run of backslashes.\n * @param {string} text Text.\n * @param {number} index Index.\n * @returns {number} Number of backslashes.\n */\nexport const countBackslashesBefore = (text, index) => {\n  let count = 0;\n\n  while (text[index - count - 1] === '\\\\') {\n    count += 1;\n  }\n\n  return count;\n};\n\n/**\n * Regular expression source to match a whitespace, punctuation or symbol character, which can\n * flank a delimiter run as opposed to a word character. It needs the `u` flag.\n * @see https://spec.commonmark.org/0.31.2/#left-flanking-delimiter-run\n */\nexport const WHITESPACE_OR_PUNCTUATION = String.raw`[\\s\\p{P}\\p{S}]`;\n\n/**\n * Regular expression to match a {@link WHITESPACE_OR_PUNCTUATION whitespace, punctuation or symbol\n * character}.\n */\nexport const WHITESPACE_OR_PUNCTUATION_REGEX = new RegExp(WHITESPACE_OR_PUNCTUATION, 'u');\n\n/**\n * Check if the given character is a word character, which is neither whitespace nor punctuation\n * (or a symbol). An underscore next to one on both sides can’t open or close emphasis.\n * @param {string | undefined} char Character.\n * @returns {boolean} Result.\n * @see https://spec.commonmark.org/0.31.2/#left-flanking-delimiter-run\n */\nexport const isWordChar = (char) => !!char && !WHITESPACE_OR_PUNCTUATION_REGEX.test(char);\n\n/**\n * Regular expression source to match a thematic break after its indentation, like `***` or\n * `- - -`, up to the end of the line. Each character is spelled out rather than matched with a\n * backreference, so the source can be combined with other capturing groups.\n * @see https://spec.commonmark.org/0.31.2/#thematic-breaks\n */\nexport const THEMATIC_BREAK = String.raw`(?:${[\n  String.raw`-(?:[ \\t]*-){2,}`,\n  String.raw`\\*(?:[ \\t]*\\*){2,}`,\n  String.raw`_(?:[ \\t]*_){2,}`,\n].join('|')})[ \\t]*$`;\n/**\n * Regular expression source to match a setext heading underline after its indentation, like `===`\n * or `---`, up to the end of the line. A single `-` is also a bullet list item, so where both are\n * matched as alternatives, the list item comes first.\n * @see https://spec.commonmark.org/0.31.2/#setext-headings\n */\nexport const SETEXT_UNDERLINE = String.raw`(?:=+|-+)[ \\t]*$`;\n/**\n * Regular expression source to match the opening sequence of an ATX heading, like `##`, which has\n * to be followed by {@link MARKER_END}.\n * @see https://spec.commonmark.org/0.31.2/#atx-headings\n */\nexport const ATX_HEADING_MARKER = '#{1,6}';\n/**\n * Regular expression source to match a bullet list marker, which has to be followed by\n * {@link MARKER_END}.\n * @see https://spec.commonmark.org/0.31.2/#list-items\n */\nexport const BULLET_LIST_MARKER = '[-+*]';\n/**\n * Regular expression source to match the number of an ordered list marker.\n * @see https://spec.commonmark.org/0.31.2/#list-items\n */\nexport const ORDERED_LIST_NUMBER = String.raw`\\d{1,9}`;\n/**\n * Regular expression source to match the delimiter after the number of an ordered list marker.\n */\nexport const ORDERED_LIST_DELIMITER = '[.)]';\n\n/**\n * Regular expression source to match an ordered list marker, like `1.` or `1)`.\n */\nconst ORDERED_LIST_MARKER = `${ORDERED_LIST_NUMBER}${ORDERED_LIST_DELIMITER}`;\n\n/**\n * Regular expression source to match a bullet or ordered list marker, which has to be followed by\n * {@link MARKER_END}.\n */\nexport const LIST_MARKER = `(?:${BULLET_LIST_MARKER}|${ORDERED_LIST_MARKER})`;\n/**\n * Regular expression source to match the place after an ATX heading or list marker: whitespace or\n * the end of the line.\n */\nexport const MARKER_END = String.raw`(?=[ \\t]|$)`;\n/**\n * Regular expression source to match a code fence, made of three or more backticks or tildes.\n * @see https://spec.commonmark.org/0.31.2/#fenced-code-blocks\n */\nexport const CODE_FENCE = '(?:`{3,}|~{3,})';\n\n/**\n * Whitespace within an HTML tag, including the placeholder of a tab; see `addImportPlaceholders()`.\n */\nconst TAG_SPACE = `[ \\\\t${CODE_TAB_PLACEHOLDER}]`;\n\n/**\n * Regular expression source to match an HTML open tag or closing tag.\n * @see https://spec.commonmark.org/0.31.2/#raw-html\n */\nexport const HTML_TAG_SOURCE =\n  `<[A-Za-z][A-Za-z0-9-]*(?:${TAG_SPACE}+[A-Za-z_:][\\\\w.:-]*` +\n  `(?:${TAG_SPACE}*=${TAG_SPACE}*` +\n  `(?:[^\\\\s\"'=<>\\`${CODE_TAB_PLACEHOLDER}]+|'[^'\\\\n]*'|\"[^\"\\\\n]*\"))?)*` +\n  `${TAG_SPACE}*/?>|</[A-Za-z][A-Za-z0-9-]*${TAG_SPACE}*>`;\n\n/**\n * Regular expression source to match the place before a `<` that isn’t escaped. The lookahead comes\n * first, so the lookbehind is only tried before a `<`.\n */\nconst UNESCAPED_LT_SOURCE = `(?=<)${UNESCAPED_LOOKBEHIND}`;\n\n/**\n * Regular expression to match inline raw HTML on a line: an open tag, a closing tag, a comment, a\n * processing instruction, a declaration or a CDATA section, which isn’t escaped.\n * @see https://spec.commonmark.org/0.31.2/#raw-html\n */\nexport const INLINE_HTML_REGEX = new RegExp(\n  [\n    UNESCAPED_LT_SOURCE,\n    '(?:',\n    [\n      HTML_TAG_SOURCE,\n      // Comment\n      String.raw`<!-->|<!--->|<!--.*?-->`,\n      // Processing instruction\n      String.raw`<\\?.*?\\?>`,\n      // Declaration\n      String.raw`<![A-Za-z][^>]*>`,\n      // CDATA section\n      String.raw`<!\\[CDATA\\[.*?\\]\\]>`,\n    ].join('|'),\n    ')',\n  ].join(''),\n);\n\n/**\n * Regular expression source to match a URI scheme that runs a script or embeds content, in any\n * case, as a scheme is case-insensitive.\n */\nconst UNSAFE_SCHEME_SOURCE = `(?:${['javascript', 'vbscript', 'data']\n  .map((scheme) => scheme.replace(/[a-z]/g, (char) => `[${char}${char.toUpperCase()}]`))\n  .join('|')})`;\n\n/**\n * Regular expression to match an autolink, like `<https://example.com>` or `<foo@example.com>`,\n * which isn’t escaped.\n * @see https://spec.commonmark.org/0.31.2/#autolinks\n */\nexport const AUTOLINK_REGEX = new RegExp(\n  [\n    UNESCAPED_LT_SOURCE,\n    '(?:',\n    [\n      // URI, other than one with a scheme that runs a script or embeds content, which is left to\n      // be escaped as text\n      String.raw`<(?!${UNSAFE_SCHEME_SOURCE}:)[A-Za-z][A-Za-z0-9+.-]{1,31}:[^\\s<>]*>`,\n      // Email address\n      String.raw`<[\\w.!#$%&'*+/=?^\\x60{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?` +\n        String.raw`(?:\\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*>`,\n    ].join('|'),\n    ')',\n  ].join(''),\n);\n\n/**\n * Regular expression to match a footnote reference, like `[^1]`, which isn’t escaped. Footnotes\n * aren’t supported, but they’re read by GitHub and many other renderers.\n * @see https://github.github.com/gfm/\n */\nexport const FOOTNOTE_REFERENCE_REGEX = new RegExp(\n  String.raw`${UNESCAPED_LOOKBEHIND}\\[\\^[^\\s[\\]]+\\]`,\n);\n/**\n * Regular expression to match a named character reference, like `&copy;`, which isn’t escaped.\n * Lexical imports it as text, the same as the escaped `\\&copy;`, which is exported escaped; see\n * `escapeNamedCharacterReferences()`. The lookahead comes first, so the lookbehind is only tried\n * before a `&`.\n * @see https://spec.commonmark.org/0.31.2/#entity-and-numeric-character-references\n */\nexport const NAMED_CHARACTER_REFERENCE_REGEX = new RegExp(\n  `(?=&)${UNESCAPED_LOOKBEHIND}&[A-Za-z][A-Za-z\\\\d]*;`,\n);\n","/**\n * Helpers to process a Markdown string outside its fenced code blocks, which are left untouched.\n */\n\nimport { LIST_MARKER } from './syntax.js';\n\n/**\n * @typedef {object} CodeBlock\n * @property {number} start Index of the line with the opening fence.\n * @property {number} end Index of the line with the closing fence, or of the last line of the code\n * block if it is not closed, in which case it runs to the end of the document, or to the end of the\n * list item it starts in.\n * @property {string} fence Opening fence, made of three or more backticks or tildes.\n * @property {boolean} closed Whether the code block has a closing fence.\n */\n\n/**\n * Regular expression to match the fence at the start of a line, after the indentation and the\n * markers of list items, if any, which are captured with it. A backtick fence can’t be followed by\n * a backtick on the same line; see `CODE`.\n */\nconst LINE_FENCE_REGEX = new RegExp(\n  `^([ \\\\t]*(?:${LIST_MARKER}[ \\\\t]+)*)(\\`{3,}(?=[^\\`]*$)|~{3,})`,\n);\n\n/**\n * Find the fenced code blocks in the lines of a Markdown string, including those starting right\n * after the marker of a list item, like `- ~~~`, whose closing fence is indented to the content\n * of the item.\n * @param {string[]} lines Lines of a Markdown string.\n * @returns {CodeBlock[]} Code blocks.\n */\nexport const findCodeBlocks = (lines) => {\n  /** @type {CodeBlock[]} */\n  const blocks = [];\n  /** @type {Omit<CodeBlock, 'end' | 'closed'> | undefined} */\n  let openBlock;\n  /**\n   * Indentation of the content of the list item the open code block starts in, if any.\n   * @type {number | undefined}\n   */\n  let contentIndent;\n\n  lines.forEach((line, index) => {\n    // Like Lexical’s `CODE_START_REGEX`, allow an indented fence, and also one after the marker of\n    // a list item\n    const [, prefix = '', fence] = line.match(LINE_FENCE_REGEX) ?? [];\n\n    // A code block in a list item ends with the item, at a line indented less than its content\n    if (\n      openBlock &&\n      contentIndent !== undefined &&\n      line.trim() &&\n      /** @type {RegExpMatchArray} */ (line.match(/^[ \\t]*/))[0].length < contentIndent\n    ) {\n      blocks.push({ ...openBlock, end: index - 1, closed: false });\n      openBlock = undefined;\n    }\n\n    if (!openBlock) {\n      if (fence) {\n        openBlock = { start: index, fence };\n        contentIndent = prefix.trim() ? prefix.length : undefined;\n      }\n\n      return;\n    }\n\n    // Like Lexical’s `CODE_END_REGEX`, a code block is only closed by a bare fence of the same\n    // character that is at least as long as the opening one, so a shorter fence within the block,\n    // like ```` ``` ```` within ```` ```` ````, is part of the code\n    if (\n      fence?.[0] === openBlock.fence[0] &&\n      fence.length >= openBlock.fence.length &&\n      !line.trim().slice(fence.length)\n    ) {\n      blocks.push({ ...openBlock, end: index, closed: true });\n      openBlock = undefined;\n    }\n  });\n\n  if (openBlock) {\n    blocks.push({ ...openBlock, end: lines.length - 1, closed: false });\n  }\n\n  return blocks;\n};\n\n/**\n * Code blocks found in the lines of a Markdown string, keyed by the array of lines.\n * @type {WeakMap<string[], CodeBlock[]>}\n */\nconst codeBlockCache = new WeakMap();\n\n/**\n * Get the fenced code blocks in the lines of a Markdown string, like {@link findCodeBlocks}, but\n * only scan the lines once for the same array, like the one Lexical passes to each transformer of\n * an import, or the one {@link splitLines} returns for the same string. The array must not be\n * changed afterwards.\n * @param {string[]} lines Lines of a Markdown string.\n * @returns {CodeBlock[]} Code blocks.\n */\nexport const getCodeBlocks = (lines) => {\n  let blocks = codeBlockCache.get(lines);\n\n  if (!blocks) {\n    blocks = findCodeBlocks(lines);\n    codeBlockCache.set(lines, blocks);\n  }\n\n  return blocks;\n};\n\n/**\n * Markdown string last split by {@link splitLines}, with its lines, kept only while\n * {@link withLineCache} runs, so the last document isn’t held in memory afterwards.\n * @type {{ value: string, lines: string[] } | undefined}\n */\nlet lastSplit;\n/**\n * Number of {@link withLineCache} calls running, which may be nested.\n */\nlet lineCacheDepth = 0;\n\n/**\n * Run the given steps of an import with the lines of the Markdown cached: {@link splitLines}\n * returns the same array for the same string as the last time, so {@link getCodeBlocks} doesn’t\n * scan it again when a step leaves the string as is. The cache is cleared once the steps are done.\n * @template T\n * @param {() => T} steps Function that runs the steps.\n * @returns {T} Result of the steps.\n */\nexport const withLineCache = (steps) => {\n  lineCacheDepth += 1;\n\n  try {\n    return steps();\n  } finally {\n    lineCacheDepth -= 1;\n\n    if (!lineCacheDepth) {\n      lastSplit = undefined;\n    }\n  }\n};\n\n/**\n * Split a Markdown string into lines. Within {@link withLineCache}, the same array is returned for\n * the same string as the last time. The array must not be changed.\n * @internal\n * @param {string} value Markdown string.\n * @returns {string[]} Lines.\n */\nexport const splitLines = (value) => {\n  if (!lineCacheDepth) {\n    return value.split('\\n');\n  }\n\n  if (lastSplit?.value !== value) {\n    lastSplit = { value, lines: value.split('\\n') };\n  }\n\n  return lastSplit.lines;\n};\n\n/**\n * @typedef {object} OpeningFence\n * @property {string} indent Whitespace before the fence.\n * @property {string} fence Fence, made of three or more backticks or tildes.\n * @property {string} info Rest of the line after the fence, the info string with the whitespace\n * around it.\n * @property {string | undefined} language Leading word of the info string, if any.\n * @property {string} meta Rest of the info string after the language, if any, trimmed. Empty\n * without a language, as the info string is then part of the code.\n * @property {RegExpMatchArray} match Match of the fence, the info string up to the end of the\n * language and the whitespace after it, which Lexical’s `CODE` transformer takes as `startMatch`:\n * the indented fence is the first group, and the language the second.\n */\n\n/**\n * Regular expression to match the opening fence of a code block and the language of its info\n * string, if any; see {@link parseOpeningFence}.\n */\nconst OPENING_FENCE_REGEX = /^([ \\t]*(?:`{3,}|~{3,}))[ \\t]*([\\w-][^\\s`]*)?[ \\t]*/;\n\n/**\n * Parse the opening fence of a code block and its info string. Like Lexical, the language is the\n * leading word of the info string, and the rest is metadata. Unlike Lexical’s, the word runs to the\n * next whitespace or backtick, so a language with symbols, like `c#` or `c++`, isn’t cut off. Like\n * Lexical’s, it must start with a word character; otherwise, like `{.js}`, the text is part of the\n * code.\n * @param {string} line Line.\n * @returns {OpeningFence | undefined} Opening fence, or `undefined` if the line doesn’t start with\n * one, including a backtick fence followed by a backtick, which can’t be in its info string.\n * @see https://spec.commonmark.org/0.31.2/#fenced-code-blocks\n */\nexport const parseOpeningFence = (line) => {\n  const match = line.match(OPENING_FENCE_REGEX);\n\n  if (!match) {\n    return undefined;\n  }\n\n  const [prefix, indentedFence, language] = match;\n  const fence = indentedFence.trimStart();\n  const info = line.slice(indentedFence.length);\n\n  if (fence.startsWith('`') && info.includes('`')) {\n    return undefined;\n  }\n\n  return {\n    indent: indentedFence.slice(0, -fence.length),\n    fence,\n    info,\n    language,\n    meta: language ? line.slice(prefix.length).trim() : '',\n    match,\n  };\n};\n\n/**\n * Apply a function to the parts of a Markdown string outside fenced code blocks, leaving the code\n * blocks, fences included, untouched. Each part is given with the line breaks around it, if any, so\n * a regular expression can tell the start and the end of a line from those of the part.\n * @param {string} value Markdown string to process.\n * @param {(part: string) => string} callback Function that returns a processed part. It must keep\n * the line breaks at the start and the end of the part.\n * @returns {string} Processed Markdown string.\n */\nexport const mapOutsideCodeBlocks = (value, callback) => {\n  const lines = splitLines(value);\n  /** @type {string[]} */\n  const output = [];\n  let index = 0;\n\n  /**\n   * Process the lines from the current index to the given one, exclusive.\n   * @param {number} end Index of the line to stop at.\n   */\n  const flush = (end) => {\n    if (end > index) {\n      const before = index > 0 ? '\\n' : '';\n      const after = end < lines.length ? '\\n' : '';\n      const part = callback(`${before}${lines.slice(index, end).join('\\n')}${after}`);\n\n      output.push(part.slice(before.length, part.length - after.length));\n    }\n  };\n\n  getCodeBlocks(lines).forEach(({ start, end }) => {\n    flush(start);\n    output.push(lines.slice(start, end + 1).join('\\n'));\n    index = end + 1;\n  });\n\n  flush(lines.length);\n\n  return output.join('\\n');\n};\n\n/**\n * Apply a function to each line of a Markdown string, leaving the lines inside fenced code blocks\n * untouched.\n * @param {string} value Markdown string to process.\n * @param {(line: string) => string} callback Function that returns a processed line.\n * @returns {string} Processed Markdown string.\n */\nexport const mapLinesOutsideCodeBlocks = (value, callback) => {\n  const lines = splitLines(value);\n\n  const codeLines = new Set(\n    getCodeBlocks(lines).flatMap(({ start, end }) =>\n      Array.from({ length: end - start + 1 }, (_, offset) => start + offset),\n    ),\n  );\n\n  return lines.map((line, index) => (codeLines.has(index) ? line : callback(line))).join('\\n');\n};\n","import { $isCodeNode as isCodeNode } from '@lexical/code-core';\nimport { CODE as LEXICAL_CODE } from '@lexical/markdown';\nimport { $isTextNode as isTextNode } from 'lexical';\n\nimport { getCodeBlocks, parseOpeningFence } from '../markdown/code-blocks.js';\nimport { INFO_BACKTICK } from '../placeholder-chars.js';\n\n/**\n * @import { MultilineElementTransformer } from '@lexical/markdown';\n * @import { ElementNode, LexicalNode } from 'lexical';\n * @import { OpeningFence } from '../markdown/code-blocks.js';\n */\n\n/**\n * Check if the given line is within a code block starting in a list item, after its opening fence,\n * like `- ~~~`.\n * @param {string[]} lines Lines of the Markdown.\n * @param {number} index Index of the line.\n * @returns {boolean} Result.\n */\nconst isInListItemCodeBlock = (lines, index) =>\n  // Lexical passes the same array of lines for every fence line of an import, so the lines are only\n  // scanned once per import rather than once per fence line\n  getCodeBlocks(lines).some(\n    ({ start, end }) => start < index && index <= end && !/^[ \\t]*[`~]/.test(lines[start]),\n  );\n\n/**\n * For each line of the Markdown being imported, the length of the longest line made only of\n * backticks, which can close a code block, from that line to the end. Lexical passes the same array\n * of lines for every fence line of an import, so it’s only computed once per import. Unlike the\n * closing fence of `getCodeBlocks()`, it’s Lexical’s, which can’t be followed by whitespace.\n * @type {WeakMap<string[], number[]>}\n */\nconst closingFenceLengthCache = new WeakMap();\n\n/**\n * Check if a code block opened with the given fence has a closing fence after the given line.\n * @param {string[]} lines Lines of the Markdown.\n * @param {number} index Index of the line with the opening fence.\n * @param {string} fence Opening fence.\n * @returns {boolean} Result.\n */\nconst hasClosingFence = (lines, index, fence) => {\n  let lengths = closingFenceLengthCache.get(lines);\n\n  if (!lengths) {\n    lengths = Array.from({ length: lines.length + 1 }, () => 0);\n\n    for (let i = lines.length - 1; i >= 0; i -= 1) {\n      const length = lines[i].match(/^[ \\t]*(`{3,})$/)?.[1].length ?? 0;\n\n      lengths[i] = Math.max(length, lengths[i + 1]);\n    }\n\n    closingFenceLengthCache.set(lines, lengths);\n  }\n\n  return lengths[index + 1] >= fence.length;\n};\n\n/**\n * Code block transformer that, unlike Lexical’s, doesn’t take a line with a backtick after the\n * opening backtick fence for a code block. In CommonMark, the info string of a backtick fence\n * can’t contain a backtick, so such a line is a paragraph starting with inline code, like a code\n * span of three backticks, which the editor exports with a fence of four backticks. Lexical would\n * turn it into a code block the next time the Markdown is read. It also reads the info string as\n * CommonMark does when Lexical doesn’t: the language after spaces, like ```` ``` js ````, and the\n * metadata after the language of a code block without a closing fence, like\n * ```` ```js title=x ````, which Lexical would add to the code. It keeps the blank lines at the end\n * of the code as well, which Lexical removes. Last, it exports a code block with a backtick in its\n * info string, imported from a tilde fence, with a tilde fence again. The rest is Lexical’s.\n * @type {MultilineElementTransformer}\n * @see https://spec.commonmark.org/0.31.2/#fenced-code-blocks\n */\nexport const CODE = {\n  ...LEXICAL_CODE,\n  /**\n   * Export a code block.\n   * @param {LexicalNode} node Node.\n   * @param {(node: ElementNode) => string} exportChildren Function to export the children of an\n   * element.\n   * @returns {string | null} Markdown, or `null` if the node isn’t a code block.\n   */\n  export: (node, exportChildren) => {\n    const markdown = LEXICAL_CODE.export?.(node, exportChildren) ?? null;\n    const [openingLine] = markdown?.split('\\n', 1) ?? [];\n\n    if (!markdown || !openingLine.includes(INFO_BACKTICK)) {\n      return markdown;\n    }\n\n    // Lexical makes the fence longer than any backtick run in the code; do the same with tildes\n    const code = markdown.slice(openingLine.length, markdown.lastIndexOf('\\n'));\n\n    const longestRun = Math.max(\n      2,\n      ...(code.match(/^[ \\t]*~+/gm) ?? []).map((run) => run.trim().length),\n    );\n\n    const fence = '~'.repeat(longestRun + 1);\n\n    return `${openingLine.replace(/^`+/, fence).replaceAll(INFO_BACKTICK, '`')}${code}\\n${fence}`;\n  },\n  /**\n   * Import a code block, starting with the given opening fence.\n   * @param {object} args Arguments.\n   * @param {string[]} args.lines Lines of the Markdown.\n   * @param {ElementNode} args.rootNode Node to append the code block to.\n   * @param {number} args.startLineIndex Index of the line with the opening fence.\n   * @param {RegExpMatchArray} args.startMatch Match of the opening fence.\n   * @param {MultilineElementTransformer} args.transformer This transformer.\n   * @returns {[boolean, number] | null | undefined} Whether the code block has been imported, and\n   * the index of its last line.\n   */\n  handleImportAfterStartMatch: ({ lines, startLineIndex, ...args }) => {\n    // The editor doesn’t support a code block in a list item, like `- ~~~`, whose lines are\n    // imported as the text of the item. Its closing fence, indented to the content of the item,\n    // or a fence within it is part of that text, not the opening fence of another code block\n    if (isInListItemCodeBlock(lines, startLineIndex)) {\n      return null;\n    }\n\n    // The language runs to the next whitespace, unlike Lexical’s; see `parseOpeningFence()`\n    const { fence, match: startMatch } = /** @type {OpeningFence} */ (\n      parseOpeningFence(lines[startLineIndex])\n    );\n\n    // Lexical only reads the metadata of a code block with a closing fence, so close it at the end\n    // of the Markdown if it isn’t closed\n    const isClosed = hasClosingFence(lines, startLineIndex, fence);\n\n    const result = LEXICAL_CODE.handleImportAfterStartMatch?.({\n      ...args,\n      lines: isClosed ? lines : [...lines, fence],\n      startLineIndex,\n      startMatch,\n    });\n\n    // Lexical removes the blank lines at the end of the code, which are part of it in CommonMark,\n    // so add them back, unless the code is blank. Those of a code block without a closing fence\n    // are left out, as they’re rather the end of the document\n    if (isClosed && result?.[0] && result[1] > startLineIndex) {\n      const codeLines = lines.slice(startLineIndex + 1, result[1]);\n      const blankLineCount = codeLines.length - codeLines.findLastIndex((line) => !!line) - 1;\n      const codeNode = args.rootNode.getLastChild();\n      const textNode = isCodeNode(codeNode) ? codeNode.getLastChild() : null;\n\n      if (blankLineCount && isTextNode(textNode) && textNode.getTextContent()) {\n        textNode.setTextContent(`${textNode.getTextContent()}${'\\n'.repeat(blankLineCount)}`);\n      }\n    }\n\n    return result && [result[0], Math.min(result[1], lines.length - 1)];\n  },\n  regExpStart: new RegExp(`${LEXICAL_CODE.regExpStart.source}(?=[^\\`]*$)`),\n};\n","import {\n  $createTextNode as createTextNode,\n  $isParagraphNode as isParagraphNode,\n  $isRootNode as isRootNode,\n  $isTextNode as isTextNode,\n} from 'lexical';\n\nimport { WHITESPACE_CODE_PLACEHOLDER } from '../placeholder-chars.js';\n\n/**\n * @import { TextMatchTransformer } from '@lexical/markdown';\n * @import { ElementNode, LexicalNode, TextNode } from 'lexical';\n */\n\n/**\n * Check if the given node is inline code made only of whitespace.\n * @param {LexicalNode | null} node Node.\n * @returns {boolean} Result.\n */\nconst isWhitespaceCode = (node) =>\n  isTextNode(node) && node.hasFormat('code') && /^\\s+$/.test(node.getTextContent());\n\n/**\n * Get a view of the given node that Lexical can export with the formats of inline code made only\n * of whitespace, like the bold in `` **` `** ``. Lexical takes a node with only whitespace as\n * having no format, as it can’t put the syntax of a format around whitespace, but code is exported\n * with its backticks, around which the syntax can go. So the view, and the views of its siblings,\n * give a placeholder as the text of such code. Lexical only reads the text to tell if it has any,\n * and exports the text it’s given. Other methods are those of the node.\n * @param {TextNode} node Text node.\n * @returns {TextNode} View of the node, or the node itself if neither it nor its siblings are such\n * code.\n */\nexport const getFormatExportNode = (node) => {\n  const previous = node.getPreviousSibling();\n  const next = node.getNextSibling();\n\n  if (![node, previous, next].some(isWhitespaceCode)) {\n    return node;\n  }\n\n  /**\n   * Get a view of a node with a placeholder as its text, if it’s inline code made only of\n   * whitespace.\n   * @template {LexicalNode | null} T\n   * @param {T} target Node.\n   * @returns {T} View or the node itself.\n   */\n  const getView = (target) =>\n    isWhitespaceCode(target)\n      ? Object.create(target, {\n          getTextContent: {\n            /**\n             * Get a placeholder instead of the whitespace.\n             * @returns {string} Placeholder.\n             */\n            value: () => WHITESPACE_CODE_PLACEHOLDER,\n          },\n        })\n      : target;\n\n  return Object.create(getView(node), {\n    getPreviousSibling: {\n      /**\n       * Get the view of the previous sibling.\n       * @returns {LexicalNode | null} View or the sibling itself.\n       */\n      value: () => getView(previous),\n    },\n    getNextSibling: {\n      /**\n       * Get the view of the next sibling.\n       * @returns {LexicalNode | null} View or the sibling itself.\n       */\n      value: () => getView(next),\n    },\n  });\n};\n\n/**\n * Check if the given node is a paragraph Lexical takes as empty when it exports the document: one\n * with nothing but a text node of up to 3 whitespace characters, even if the text is code.\n * @param {LexicalNode | null} node Node.\n * @returns {boolean} Result.\n */\nconst isLexicalEmptyParagraph = (node) => {\n  if (!isParagraphNode(node)) {\n    return false;\n  }\n\n  const child = node.getFirstChild();\n\n  return (\n    !child ||\n    (node.getChildrenSize() === 1 && isTextNode(child) && /^\\s{0,3}$/.test(child.getTextContent()))\n  );\n};\n\n/**\n * Get the line breaks to add around a code node made only of whitespace that is the only content\n * of a paragraph in the document root. Lexical takes such a paragraph as empty, so it puts a single\n * line break, not a blank line, between it and the blocks next to it, which would make one\n * paragraph of them. The line break is added on the side of the code, unless the block next to it\n * is a paragraph Lexical takes as empty too: the line break is added by the one before, if it has\n * code, and isn’t needed otherwise, as an empty paragraph adds a line break of its own.\n * @param {TextNode} node Code node.\n * @returns {[string, string]} Line breaks to add before and after the code.\n */\nconst getParagraphLineBreaks = (node) => {\n  const paragraph = node.getParent();\n\n  if (!isLexicalEmptyParagraph(paragraph) || !isRootNode(paragraph?.getParent())) {\n    return ['', ''];\n  }\n\n  const previous = paragraph?.getPreviousSibling() ?? null;\n  const next = paragraph?.getNextSibling() ?? null;\n\n  /**\n   * Check if a paragraph is empty, with no code.\n   * @param {LexicalNode | null} sibling Sibling.\n   * @returns {boolean} Result.\n   */\n  const isEmpty = (sibling) => {\n    const child = /** @type {ElementNode} */ (sibling)?.getFirstChild();\n\n    return isLexicalEmptyParagraph(sibling) && !(isTextNode(child) && child.hasFormat('code'));\n  };\n\n  return [\n    previous && !isLexicalEmptyParagraph(previous) ? '\\n' : '',\n    next && !isEmpty(next) ? '\\n' : '',\n  ];\n};\n\n/**\n * Import-only transformer for a code span at the start of a node, such as a table cell, a\n * paragraph or bold text starting with inline code. Lexical’s `INLINE_CODE` transformer then reuses\n * the node for the code, and removes the backslash escapes from the node once the inline syntax has\n * been imported, so `` `C:\\$MFT` `` would become `C:$MFT`, though backslashes are literal in a code\n * span. Backslashes in a code span split from the text before it are kept. A text match wrapping a\n * code span takes priority over it, and this one replaces the node with a new one, leaving the old\n * node, which is no longer in the document, to be unescaped. It also exports a code span that\n * starts and ends with whitespace, which Lexical pads with a space on both sides, though CommonMark\n * only strips that padding if both ends are spaces and the content isn’t all spaces, so `` ` ` ``\n * would get two spaces longer on every save, and `` `\\t` `` would become `` ` \\t ` ``.\n * It exports code next to inline code made only of whitespace too; see `getFormatExportNode()`.\n * @type {TextMatchTransformer}\n * @see https://github.com/sveltia/sveltia-cms/issues/1100\n * @see https://spec.commonmark.org/0.31.2/#code-spans\n */\nexport const LEADING_INLINE_CODE = {\n  dependencies: [],\n  /**\n   * Export a code span that starts and ends with whitespace without the padding Lexical adds, if\n   * CommonMark wouldn’t strip it, and with the line breaks around it if it’s the only content of a\n   * paragraph; see `getParagraphLineBreaks()`. Lexical exports the other code spans.\n   * @param {LexicalNode} node Node.\n   * @param {(node: ElementNode) => string} _exportChildren Function to export the children of an\n   * element, unused.\n   * @param {(node: TextNode, textContent: string) => string} exportFormat Function to export a text\n   * node with its format.\n   * @returns {string | null} Markdown, or `null` to leave the node to the other transformers.\n   */\n  export: (node, _exportChildren, exportFormat) => {\n    if (!isTextNode(node) || !node.hasFormat('code')) {\n      return null;\n    }\n\n    const content = node.getTextContent();\n    const exportNode = getFormatExportNode(node);\n    const [before, after] = isWhitespaceCode(node) ? getParagraphLineBreaks(node) : ['', ''];\n\n    // Lexical pads code that starts and ends with whitespace, though CommonMark only strips one\n    // space from both ends, if the code isn’t all spaces\n    const hasExtraPadding =\n      !content.includes('`') &&\n      /^\\s/.test(content) &&\n      /\\s$/.test(content) &&\n      !(content.startsWith(' ') && content.endsWith(' ') && /[^ ]/.test(content));\n\n    if (!hasExtraPadding && exportNode === node && !before && !after) {\n      return null;\n    }\n\n    const markdown = exportFormat(exportNode, content);\n\n    // The code is wrapped with the syntax of its other formats, if any, which has no whitespace\n    return `${before}${\n      hasExtraPadding ? markdown.replace(`\\` ${content} \\``, () => `\\`${content}\\``) : markdown\n    }${after}`;\n  },\n  // A code span as Lexical’s `INLINE_CODE` transformer reads it: from a backtick run to the next\n  // run of the same length\n  // @see https://spec.commonmark.org/0.31.2/#code-spans\n  importRegExp: /^(`+)(?!`)([^]*?[^`])\\1(?!`)/,\n  regExp: /(?!)/,\n  /**\n   * Replace the given text node, which has been split at the end of the code span, with a new code\n   * node, keeping its formats and style.\n   * @param {TextNode} node Text node.\n   * @param {RegExpMatchArray} match Match of the code span.\n   * @returns {TextNode} New node.\n   */\n  replace: (node, [, , content]) => {\n    // One space is stripped from both ends of the content if it’s padded on both sides and has a\n    // non-space character\n    const codeNode = createTextNode(/^ .*[^ ].* $/s.test(content) ? content.slice(1, -1) : content)\n      .setFormat(node.getFormat())\n      .setStyle(node.getStyle())\n      // Lexical doesn’t import the inline syntax in a node that is already code\n      .toggleFormat('code');\n\n    node.replace(codeNode);\n\n    return codeNode;\n  },\n  type: 'text-match',\n};\n","import { $isLinkNode as isLinkNode } from '@lexical/link';\nimport { LINK as LEXICAL_LINK } from '@lexical/markdown';\nimport { $isLineBreakNode as isLineBreakNode, $isTextNode as isTextNode } from 'lexical';\n\nimport { WHITESPACE_OR_PUNCTUATION_REGEX } from '../markdown/syntax.js';\n\n/**\n * @import { TextMatchTransformer } from '@lexical/markdown';\n * @import { ElementNode, LexicalNode, TextFormatType, TextNode } from 'lexical';\n */\n\n/**\n * Text formats that can be moved out of a link, with the Markdown delimiters Lexical can export\n * for each. Inline code can’t, as it would make the link text code.\n * @type {Partial<Record<TextFormatType, string[]>>}\n */\nconst FORMAT_DELIMITERS = {\n  bold: ['**', '__'],\n  italic: ['_', '*'],\n  strikethrough: ['~~'],\n};\n\n/**\n * Regular expression to match a format delimiter at the start of a string.\n */\nconst DELIMITER_REGEX = /^(?:\\*\\*|__|~~|\\*|_)/;\n\n/**\n * Get the text of a node as exported: inline code starts and ends with a backtick, even if its text\n * is only whitespace.\n * @param {LexicalNode | null | undefined} node Node.\n * @returns {string} Text.\n */\nconst getExportedText = (node) =>\n  isTextNode(node) && node.hasFormat('code') ? '`' : (node?.getTextContent() ?? '');\n\n/**\n * Get the formats a link can be wrapped with instead of having them in its text, like `**[a](b)**`\n * instead of `[**a**](b)`: the ones every text node in the link has. Lexical puts the delimiters in\n * the link text, so the Markdown would change every time it’s exported. They’re only moved out if\n * the link text is all text with no whitespace at either end, other than in inline code, and the\n * character on either side of the link is whitespace or punctuation, which the delimiters need to\n * open and close emphasis there. If the text next to the link has any of the formats, it must be\n * whitespace, or the delimiters of the link and the text would meet.\n * @param {ElementNode} node Link node.\n * @returns {TextFormatType[]} Formats.\n * @see https://spec.commonmark.org/0.31.2/#left-flanking-delimiter-run\n */\nconst getOuterFormats = (node) => {\n  const children = node.getChildren();\n\n  if (\n    !children.length ||\n    !children.every((child) => isTextNode(child) && /\\S/.test(getExportedText(child))) ||\n    /^\\s/.test(getExportedText(children[0])) ||\n    /\\s$/.test(getExportedText(children.at(-1)))\n  ) {\n    return [];\n  }\n\n  const formats = /** @type {TextFormatType[]} */ (Object.keys(FORMAT_DELIMITERS)).filter(\n    (format) => children.every((child) => /** @type {TextNode} */ (child).hasFormat(format)),\n  );\n\n  /**\n   * Check if the given sibling of the link allows the delimiters next to the link.\n   * @param {LexicalNode | null} sibling Previous or next sibling.\n   * @param {(text: string) => string | undefined} getChar Function to get the character next to\n   * the link from the sibling’s text.\n   * @returns {boolean} Result.\n   */\n  const isSeparated = (sibling, getChar) => {\n    if (!sibling || isLineBreakNode(sibling)) {\n      return true;\n    }\n\n    if (!isTextNode(sibling)) {\n      return false;\n    }\n\n    const char = getChar(getExportedText(sibling)) ?? '';\n\n    // Lexical puts the delimiters of the text inside its whitespace, which keeps them apart\n    return formats.some((format) => sibling.hasFormat(format))\n      ? /\\s/.test(char)\n      : WHITESPACE_OR_PUNCTUATION_REGEX.test(char);\n  };\n\n  return formats.length &&\n    isSeparated(node.getPreviousSibling(), (text) => text.at(-1)) &&\n    isSeparated(node.getNextSibling(), (text) => text[0])\n    ? formats\n    : [];\n};\n\n/**\n * Remove the given formats’ delimiters from either end of the exported link text, where Lexical\n * puts them when every text node in the link has the formats.\n * @param {string} markdown Exported link text.\n * @param {TextFormatType[]} formats Formats.\n * @returns {{ text: string, delimiters: string } | undefined} The text without the delimiters, and\n * the opening delimiters, or `undefined` if the text doesn’t start and end with them.\n */\nconst stripDelimiters = (markdown, formats) => {\n  const remaining = [...formats];\n  let delimiters = '';\n\n  while (remaining.length) {\n    const [delimiter] = markdown.slice(delimiters.length).match(DELIMITER_REGEX) ?? [];\n\n    const index = remaining.findIndex((format) =>\n      FORMAT_DELIMITERS[format]?.includes(delimiter ?? ''),\n    );\n\n    if (!delimiter || index === -1) {\n      return undefined;\n    }\n\n    remaining.splice(index, 1);\n    delimiters += delimiter;\n  }\n\n  const closing = [...delimiters].reverse().join('');\n\n  if (markdown.length < delimiters.length * 2 || !markdown.endsWith(closing)) {\n    return undefined;\n  }\n\n  return { text: markdown.slice(delimiters.length, -closing.length), delimiters };\n};\n\n/**\n * Link transformer that exports the formats of the whole link text outside the link, where they’re\n * imported from; see `getOuterFormats()`. The rest is Lexical’s.\n * @type {TextMatchTransformer}\n */\nexport const LINK = {\n  ...LEXICAL_LINK,\n  /**\n   * Export a link node.\n   * @param {LexicalNode} node Node.\n   * @param {(node: ElementNode) => string} exportChildren Function to export the children of an\n   * element.\n   * @param {(node: TextNode, textContent: string) => string} exportFormat Function to export a text\n   * node with its format.\n   * @returns {string | null} Markdown, or `null` to leave the node to the other transformers.\n   */\n  export: (node, exportChildren, exportFormat) => {\n    const formats = isLinkNode(node) ? getOuterFormats(node) : [];\n    /** @type {string | undefined} */\n    let delimiters;\n\n    const markdown = LEXICAL_LINK.export?.(\n      node,\n      (linkNode) => {\n        const text = exportChildren(linkNode);\n        const stripped = formats.length ? stripDelimiters(text, formats) : undefined;\n\n        delimiters = stripped?.delimiters;\n\n        return stripped?.text ?? text;\n      },\n      exportFormat,\n    );\n\n    return markdown && delimiters\n      ? `${delimiters}${markdown}${[...delimiters].reverse().join('')}`\n      : (markdown ?? null);\n  },\n};\n","import { CHECK_LIST } from '@lexical/markdown';\nimport { $isTextNode as isTextNode } from 'lexical';\n\n/**\n * @import { ElementTransformer } from '@lexical/markdown';\n */\n\n/**\n * Start of a task list item as GitHub Flavored Markdown defines it: a bullet list marker followed\n * by a check box holding a space or `x`, like `- [ ] item`. Like Lexical’s `CHECK_LIST`, it allows\n * one or two spaces between them; with more, the line is a bulleted list item starting with `[ ]`.\n * Like the other block checks in the plain text mode, it doesn’t allow any indentation, which a\n * nested item has.\n * @see https://github.github.com/gfm/#task-list-items-extension-\n */\nexport const TASK_LIST_ITEM_REGEX = /^[-*+][ \\t]{1,2}\\[[ xX]\\][ \\t]/;\n\n/**\n * Transformer for task list items, based on Lexical’s `CHECK_LIST`, which also takes a line without\n * a list marker or with an empty check box, like `[x] Agreed` or `[] Empty`, for a task list item.\n * That suits a Markdown shortcut, like typing `[ ] ` at the start of a paragraph, but would turn\n * such a paragraph into a task list when Markdown is imported, so an import only takes a line that\n * matches {@link TASK_LIST_ITEM_REGEX}, leaving any other line to the other transformers. Lexical\n * has already removed the matched text from the line by then, and doesn’t put it back when a\n * transformer leaves the line, so it’s restored here.\n * @type {ElementTransformer}\n */\nexport const TASK_LIST = {\n  ...CHECK_LIST,\n  /**\n   * Replace the matched line with a task list item, unless it’s imported and isn’t one.\n   * @param {Parameters<ElementTransformer['replace']>} args Arguments.\n   * @returns {boolean | void} `false` if the line isn’t a task list item.\n   */\n  replace: (...args) => {\n    const [, children, match, isImport] = args;\n\n    // The match includes the indentation of a nested item\n    if (isImport && !TASK_LIST_ITEM_REGEX.test(match[0].trimStart())) {\n      const [textNode] = children;\n\n      if (isTextNode(textNode)) {\n        textNode.setTextContent(\n          /** @type {string} */ (/** @type {RegExpMatchArray} */ (match).input),\n        );\n      }\n\n      return false;\n    }\n\n    return CHECK_LIST.replace(...args);\n  },\n};\n","import { CodeHighlightNode, CodeNode } from '@lexical/code-core';\nimport { LinkNode } from '@lexical/link';\nimport {\n  INSERT_CHECK_LIST_COMMAND,\n  INSERT_ORDERED_LIST_COMMAND,\n  INSERT_UNORDERED_LIST_COMMAND,\n  ListItemNode,\n  ListNode,\n} from '@lexical/list';\nimport {\n  BOLD_ITALIC_STAR,\n  BOLD_ITALIC_UNDERSCORE,\n  BOLD_STAR,\n  BOLD_UNDERSCORE,\n  HEADING,\n  INLINE_CODE,\n  ITALIC_STAR,\n  ITALIC_UNDERSCORE,\n  ORDERED_LIST,\n  QUOTE,\n  STRIKETHROUGH,\n  UNORDERED_LIST,\n} from '@lexical/markdown';\nimport { HeadingNode, QuoteNode } from '@lexical/rich-text';\nimport { createCommand } from 'lexical';\n\nimport { CODE } from './conversion/transformers/code.js';\nimport { LEADING_INLINE_CODE } from './conversion/transformers/inline-code.js';\nimport { LINK } from './conversion/transformers/link.js';\nimport { TASK_LIST } from './conversion/transformers/task-list.js';\n\n/**\n * @import { EditorThemeClasses, LexicalCommand } from 'lexical';\n * @import { ListType } from '@lexical/list';\n * @import { Transformer } from '@lexical/markdown';\n * @import {\n * TextEditorBlockType,\n * TextEditorFormatType,\n * TextEditorInlineType,\n * TextEditorNodeType,\n * } from '../../typedefs.js';\n */\n\n/**\n * @type {EditorThemeClasses}\n */\nexport const EDITOR_THEME = {\n  text: {\n    /**\n     * Enable bold+italic, underline and strikethrough styling. Lexical only uses the combined\n     * class for text that is both underlined and struck through.\n     * @see https://github.com/facebook/lexical/discussions/4381\n     */\n    italic: 'italic',\n    underline: 'underline',\n    strikethrough: 'strikethrough',\n    underlineStrikethrough: 'underline strikethrough',\n  },\n  list: {\n    nested: {\n      listitem: 'nested',\n    },\n    // Task list items, drawn with a check box; see `lexical-root.svelte`\n    listitemChecked: 'task-list-item checked',\n    listitemUnchecked: 'task-list-item',\n  },\n  code: 'code-block',\n  // Lexical wraps a table with an element to scroll it horizontally when the table button is\n  // enabled; see `initEditor()`\n  tableScrollableWrapper: 'table-wrapper',\n  tableCellSelected: 'selected',\n  tableSelection: 'table-selection',\n};\n\n/**\n * List of available buttons.\n * @type {{ [key: string]: { labelKey: string, icon: string, inline: boolean } }}\n */\nexport const AVAILABLE_BUTTONS = {\n  bold: {\n    labelKey: 'bold',\n    icon: 'format_bold',\n    inline: true,\n  },\n  italic: {\n    labelKey: 'italic',\n    icon: 'format_italic',\n    inline: true,\n  },\n  underline: {\n    labelKey: 'underline',\n    icon: 'format_underlined',\n    inline: true,\n  },\n  strikethrough: {\n    labelKey: 'strikethrough',\n    icon: 'strikethrough_s',\n    inline: true,\n  },\n  code: {\n    labelKey: 'code',\n    icon: 'code',\n    inline: true,\n  },\n  link: {\n    labelKey: 'link',\n    icon: 'link',\n    inline: true,\n  },\n  paragraph: {\n    labelKey: 'paragraph',\n    icon: 'format_paragraph',\n    inline: false,\n  },\n  'heading-1': {\n    labelKey: 'heading_1',\n    icon: 'format_h1',\n    inline: false,\n  },\n  'heading-2': {\n    labelKey: 'heading_2',\n    icon: 'format_h2',\n    inline: false,\n  },\n  'heading-3': {\n    labelKey: 'heading_3',\n    icon: 'format_h3',\n    inline: false,\n  },\n  'heading-4': {\n    labelKey: 'heading_4',\n    icon: 'format_h4',\n    inline: false,\n  },\n  'heading-5': {\n    labelKey: 'heading_5',\n    icon: 'format_h5',\n    inline: false,\n  },\n  'heading-6': {\n    labelKey: 'heading_6',\n    icon: 'format_h6',\n    inline: false,\n  },\n  'bulleted-list': {\n    labelKey: 'bulleted_list',\n    icon: 'format_list_bulleted',\n    inline: false,\n  },\n  'numbered-list': {\n    labelKey: 'numbered_list',\n    icon: 'format_list_numbered',\n    inline: false,\n  },\n  'task-list': {\n    labelKey: 'task_list',\n    icon: 'checklist',\n    inline: false,\n  },\n  blockquote: {\n    labelKey: 'blockquote',\n    icon: 'format_quote',\n    inline: false,\n  },\n  'code-block': {\n    labelKey: 'code_block',\n    icon: 'code_blocks',\n    inline: false,\n  },\n  table: {\n    labelKey: 'insert_table',\n    icon: 'table',\n    inline: false,\n  },\n  'horizontal-rule': {\n    labelKey: 'insert_horizontal_rule',\n    icon: 'horizontal_rule',\n    inline: false,\n  },\n};\n\n/**\n * @type {TextEditorFormatType[]}\n */\nexport const TEXT_FORMAT_BUTTON_TYPES = ['bold', 'italic', 'underline', 'strikethrough', 'code'];\n\n/**\n * @type {TextEditorInlineType[]}\n */\nexport const INLINE_BUTTON_TYPES = [...TEXT_FORMAT_BUTTON_TYPES, 'link'];\n\n/**\n * @type {TextEditorBlockType[]}\n */\nexport const BLOCK_BUTTON_TYPES = [\n  'paragraph',\n  'heading-1',\n  'heading-2',\n  'heading-3',\n  'heading-4',\n  'heading-5',\n  'heading-6',\n  'bulleted-list',\n  'numbered-list',\n  'task-list',\n  'blockquote',\n  'code-block',\n];\n\n/**\n * Buttons only available for HTML, as Markdown has no syntax for them: the underline format and the\n * alignment menu. They’re hidden for Markdown and in the plain text mode, which shows the HTML\n * source, and they’re not enabled by default.\n * @type {('underline' | 'align')[]}\n */\nexport const HTML_ONLY_BUTTON_TYPES = ['underline', 'align'];\n\n/**\n * Check whether the given button is only available for HTML. See {@link HTML_ONLY_BUTTON_TYPES}.\n * @param {string} type Button type.\n * @returns {type is 'underline' | 'align'} Result.\n */\nexport const isHtmlOnlyButton = (type) =>\n  /** @type {string[]} */ (HTML_ONLY_BUTTON_TYPES).includes(type);\n\n/**\n * Text formats only available for HTML, like underline. See {@link HTML_ONLY_BUTTON_TYPES}.\n */\nexport const HTML_ONLY_FORMAT_TYPES = TEXT_FORMAT_BUTTON_TYPES.filter(isHtmlOnlyButton);\n\n/**\n * Buttons not enabled by default: the HTML-only ones and the task list, a GitHub Flavored Markdown\n * extension that not every Markdown renderer supports.\n * @type {TextEditorNodeType[]}\n */\nexport const OPTIONAL_BUTTON_TYPES = [...HTML_ONLY_BUTTON_TYPES, 'task-list'];\n\n/**\n * Buttons enabled by default: all the inline and block level buttons but the optional ones.\n * @type {TextEditorNodeType[]}\n */\nexport const DEFAULT_BUTTON_TYPES = [...INLINE_BUTTON_TYPES, ...BLOCK_BUTTON_TYPES].filter(\n  (type) => !OPTIONAL_BUTTON_TYPES.includes(type),\n);\n\n/**\n * List block types, with their Lexical list type and the command to insert the list.\n * @type {{ type: TextEditorBlockType, listType: ListType, command: LexicalCommand<void> }[]}\n */\nexport const LIST_TYPES = [\n  { type: 'bulleted-list', listType: 'bullet', command: INSERT_UNORDERED_LIST_COMMAND },\n  { type: 'numbered-list', listType: 'number', command: INSERT_ORDERED_LIST_COMMAND },\n  { type: 'task-list', listType: 'check', command: INSERT_CHECK_LIST_COMMAND },\n];\n\n/**\n * Map of Lexical nodes for each block type. The `paragraph` block type is excluded because it is\n * the default block type.\n * @type {Record<Exclude<TextEditorBlockType | 'link', 'paragraph'>, any[]>}\n */\nexport const NODE_MAP = {\n  'heading-1': [HeadingNode],\n  'heading-2': [HeadingNode],\n  'heading-3': [HeadingNode],\n  'heading-4': [HeadingNode],\n  'heading-5': [HeadingNode],\n  'heading-6': [HeadingNode],\n  'bulleted-list': [ListNode, ListItemNode],\n  'numbered-list': [ListNode, ListItemNode],\n  'task-list': [ListNode, ListItemNode],\n  blockquote: [QuoteNode],\n  'code-block': [CodeNode, CodeHighlightNode],\n  link: [LinkNode],\n};\n\n/**\n * Map of Lexical transformers for each button type. The `paragraph` block type has none because it\n * is the default block type, and neither have the HTML-only buttons. Horizontal rules and tables\n * are always supported in Markdown, so their transformers are added in `core.js`.\n * @type {Partial<Record<TextEditorNodeType, Transformer[]>>}\n */\nexport const TRANSFORMER_MAP = {\n  // ELEMENT_TRANSFORMERS\n  'heading-1': [HEADING],\n  'heading-2': [HEADING],\n  'heading-3': [HEADING],\n  'heading-4': [HEADING],\n  'heading-5': [HEADING],\n  'heading-6': [HEADING],\n  // Before the bulleted list, as `- [ ] item` matches both\n  'task-list': [TASK_LIST],\n  'bulleted-list': [UNORDERED_LIST],\n  'numbered-list': [ORDERED_LIST],\n  blockquote: [QUOTE],\n  // MULTILINE_ELEMENT_TRANSFORMERS\n  'code-block': [CODE],\n  // TEXT_FORMAT_TRANSFORMERS\n  // The second one keeps the backslashes in inline code at the start of a node\n  code: [INLINE_CODE, LEADING_INLINE_CODE],\n  bold: [\n    BOLD_STAR,\n    // Disabled for Markdown output in `DISABLED_MARKDOWN_TAGS` below\n    BOLD_UNDERSCORE,\n    BOLD_ITALIC_STAR,\n    BOLD_ITALIC_UNDERSCORE,\n  ],\n  italic: [\n    ITALIC_UNDERSCORE,\n    // Disabled for Markdown output in `DISABLED_MARKDOWN_TAGS` below\n    ITALIC_STAR,\n    BOLD_ITALIC_STAR,\n    BOLD_ITALIC_UNDERSCORE,\n  ],\n  strikethrough: [STRIKETHROUGH],\n  // TEXT_MATCH_TRANSFORMERS\n  // Unlike Lexical’s, it keeps the formats of the whole link text outside the link\n  link: [LINK],\n};\n\n/**\n * List of Markdown tags that should be disabled in the editor when converting Lexical nodes to\n * Markdown (but not when converting Markdown to Lexical nodes because we don’t want to lose any\n * formatting). Use underscore for italic text in Markdown instead of asterisks, and use double\n * asterisks for bold text in Markdown instead of underscores. Also, disable triple asterisks and\n * triple underscores for bold+italic text in Markdown, which can be confusing and is not commonly\n * used. This is to ensure that the Markdown output is more readable and consistent.\n */\nexport const DISABLED_MARKDOWN_TAGS = ['*', '__', '***', '___'];\n\n/**\n * Tag of the Lexical update that imports a value set from outside, so the editor can tell it from a\n * change made by the user. A custom node can check it with `$hasUpdateTag()` in its `createDOM()`\n * method to tell whether it’s being rendered for an imported value.\n */\nexport const IMPORT_UPDATE_TAG = 'sui-import';\n\n/**\n * Command to show the floating link editor for the link at the selection, or for the selected text\n * to be linked. A listener returns `false` when there is no link or text to edit, in which case the\n * Link button falls back to the dialog.\n * @type {LexicalCommand<void>}\n */\nexport const OPEN_LINK_EDITOR_COMMAND = createCommand('OPEN_LINK_EDITOR_COMMAND');\n\n/**\n * Text alignments offered by the alignment menu, which is only available for HTML, as Markdown\n * has no syntax for alignment. Like most editors, it offers the physical sides rather than the\n * logical `start` and `end`, which are still kept as is when the HTML has them.\n * @type {{ type: 'left' | 'center' | 'right' | 'justify', labelKey: string, icon: string }[]}\n */\nexport const ALIGNMENT_OPTIONS = [\n  { type: 'left', labelKey: 'align_left', icon: 'format_align_left' },\n  { type: 'center', labelKey: 'align_center', icon: 'format_align_center' },\n  { type: 'right', labelKey: 'align_right', icon: 'format_align_right' },\n  { type: 'justify', labelKey: 'align_justify', icon: 'format_align_justify' },\n];\n\n/**\n * Default number of rows, including the header row, and columns of a new table.\n */\nexport const DEFAULT_TABLE_SIZE = 3;\n\n/**\n * Maximum number of rows and columns of a new table.\n */\nexport const MAX_TABLE_SIZE = 50;\n","/**\n * Placing the caret and the focus in the editor.\n */\n\nimport {\n  $createParagraphNode as createParagraphNode,\n  $getNearestNodeFromDOMNode as getNearestNodeFromDOMNode,\n  $getRoot as getRoot,\n  $getSelection as getSelection,\n  $isDecoratorNode as isDecoratorNode,\n  $isElementNode as isElementNode,\n  $isRangeSelection as isRangeSelection,\n} from 'lexical';\n\n/**\n * @import { LexicalEditor } from 'lexical';\n */\n\n/**\n * Selector for the elements in a decorator node, like an editor component, that handle a click on\n * their own.\n */\nconst DECORATOR_INTERACTIVE_SELECTOR = [\n  'input',\n  'textarea',\n  'select',\n  'button',\n  'a[href]',\n  // A label moves the focus to its control on click\n  'label',\n  'summary',\n  'video[controls]',\n  'audio[controls]',\n  '[tabindex]',\n  '[draggable=\"true\"]',\n  '[contenteditable]:not([contenteditable=\"false\"])',\n].join(', ');\n\n/**\n * Whether a click on the given element would put the caret on the static content of a decorator\n * node, like the label or padding of an editor component. The editor cannot map such a position to\n * a node, so the caret appears there but typing does nothing.\n * @param {EventTarget | null} target Event target.\n * @returns {boolean} Result.\n */\nexport const isStaticDecoratorContent = (target) => {\n  if (!(target instanceof Element)) {\n    return false;\n  }\n\n  const decorator = target.closest('[data-lexical-decorator]');\n\n  if (!decorator) {\n    return false;\n  }\n\n  const interactive = target.closest(DECORATOR_INTERACTIVE_SELECTOR);\n\n  // An interactive element outside the decorator is the editor root or one of its ancestors\n  return !interactive || !decorator.contains(interactive);\n};\n\n/**\n * Move a caret placed directly on the root node into a block: the adjacent paragraph or other\n * block, or a new paragraph if the adjacent nodes are decorators, where nothing can be typed.\n * @returns {boolean} Whether the selection has been moved.\n */\nconst $moveCaretIntoBlock = () => {\n  const selection = getSelection();\n\n  if (\n    !isRangeSelection(selection) ||\n    !selection.isCollapsed() ||\n    selection.anchor.type !== 'element'\n  ) {\n    return false;\n  }\n\n  const root = getRoot();\n\n  if (!selection.anchor.getNode().is(root)) {\n    return false;\n  }\n\n  const { offset } = selection.anchor;\n  const before = root.getChildAtIndex(offset - 1);\n  const after = root.getChildAtIndex(offset);\n\n  if (isElementNode(after)) {\n    after.selectStart();\n  } else if (isElementNode(before)) {\n    before.selectEnd();\n  } else {\n    const paragraph = createParagraphNode();\n\n    if (before) {\n      before.insertAfter(paragraph);\n    } else if (after) {\n      after.insertBefore(paragraph);\n    } else {\n      root.append(paragraph);\n    }\n\n    paragraph.select();\n  }\n\n  return true;\n};\n\n/**\n * Move the focus to the editor, and run the given function with the node of the given element\n * within an editor update.\n * @param {LexicalEditor} editor Editor instance.\n * @param {Element} element Element of the node.\n * @param {(node: ReturnType<typeof getNearestNodeFromDOMNode>) => void} callback Function to be\n * called with the node.\n */\nconst updateNodeWithFocus = (editor, element, callback) => {\n  editor.getRootElement()?.focus({ preventScroll: true });\n\n  editor.update(() => {\n    callback(getNearestNodeFromDOMNode(element));\n  });\n};\n\n/**\n * Move the focus to the editor, and the caret to right after the given decorator node, like an\n * editor component: the start of the next block, or a new paragraph if there’s none to type in.\n * @param {LexicalEditor} editor Editor instance.\n * @param {Element} decorator Element of the decorator node.\n */\nconst placeCaretAfterDecorator = (editor, decorator) => {\n  updateNodeWithFocus(editor, decorator, (node) => {\n    // The element has been found by its `data-lexical-decorator` attribute\n    /* v8 ignore next 3 */\n    if (!isDecoratorNode(node)) {\n      return;\n    }\n\n    node.selectNext();\n    $moveCaretIntoBlock();\n  });\n};\n\n/**\n * Move the focus to the editor, and the caret to the end of the given block.\n * @param {LexicalEditor} editor Editor instance.\n * @param {Element} block Element of the block node.\n */\nconst placeCaretAtBlockEnd = (editor, block) => {\n  updateNodeWithFocus(editor, block, (node) => {\n    /* v8 ignore next 3 */\n    if (!isElementNode(node)) {\n      return;\n    }\n\n    node.selectEnd();\n  });\n};\n\n/**\n * Handle a `mousedown` event on the editor, placing the caret where the user expects, rather than\n * leaving it to the browser, when the pointer is not on any editable text. Browsers disagree on\n * where the caret goes in these cases, and some put it within a decorator node, like an editor\n * component, where the editor cannot map it to a node, so typing does nothing:\n *\n * - The static content of a decorator, like its label or padding, places the caret after it.\n * - The empty area of the editor, outside any block, places the caret after the decorator above\n * the pointer, or at the end of the block above the pointer.\n * @param {LexicalEditor} editor Editor instance.\n * @param {MouseEvent} event `mousedown` event.\n * @returns {boolean} Whether the event has been handled.\n */\nexport const handleEditorMouseDown = (editor, event) => {\n  const { target, button, shiftKey, clientY } = event;\n  const root = editor.getRootElement();\n\n  // Leave the primary button with Shift, which extends the selection, and other buttons alone.\n  // Leave a read-only editor alone as well, as a paragraph may be added, and an event already\n  // handled by a nested editor, like one in an editor component\n  if (\n    !root ||\n    !editor.isEditable() ||\n    event.defaultPrevented ||\n    button !== 0 ||\n    shiftKey ||\n    !(target instanceof Element)\n  ) {\n    return false;\n  }\n\n  if (isStaticDecoratorContent(target)) {\n    const decorator = /** @type {Element} */ (target.closest('[data-lexical-decorator]'));\n\n    // A decorator of a nested editor, like one in an editor component, is handled by that editor\n    if (decorator.parentElement?.closest('[data-lexical-editor]') !== root) {\n      return false;\n    }\n\n    event.preventDefault();\n    placeCaretAfterDecorator(editor, decorator);\n\n    return true;\n  }\n\n  if (target !== root) {\n    return false;\n  }\n\n  // Find the last block starting above the pointer. Lexical adds a hidden element to the root\n  // after a decorator, which has no size\n  const block = [...root.children]\n    .filter((element) => !element.hasAttribute('data-lexical-decorator-boundary'))\n    .findLast((element) => element.getBoundingClientRect().top <= clientY);\n\n  if (!block) {\n    return false;\n  }\n\n  if (block.hasAttribute('data-lexical-decorator')) {\n    event.preventDefault();\n    placeCaretAfterDecorator(editor, block);\n\n    return true;\n  }\n\n  // Beside a block, the browser can find the nearest text on its own\n  if (clientY <= block.getBoundingClientRect().bottom) {\n    return false;\n  }\n\n  event.preventDefault();\n  placeCaretAtBlockEnd(editor, block);\n\n  return true;\n};\n\n/**\n * Move focus to the editor so the user can start editing immediately.\n * @param {LexicalEditor} editor Editor instance.\n * @returns {Promise<void>} Nothing.\n */\nexport const focusEditor = async (editor) =>\n  new Promise((resolve) => {\n    editor.focus(() => {\n      resolve(undefined);\n    });\n  });\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{effect as t,signal as e,batch as n}from\"@lexical/extension/signals\";import{getPeerDependencyFromEditor as o}from\"@lexical/extension/getPeerDependencyFromEditor\";import{namedSignals as r}from\"@lexical/extension/namedSignals\";import{mergeRegister as i,UNDO_COMMAND as a,COMMAND_PRIORITY_EDITOR as l,REDO_COMMAND as u,CLEAR_EDITOR_COMMAND as s,CLEAR_HISTORY_COMMAND as d,CAN_REDO_COMMAND as c,CAN_UNDO_COMMAND as f,COMPOSITION_START_TAG as p,HISTORIC_TAG as h,COMPOSITION_END_TAG as m,PASTE_TAG as g,CUT_TAG as y,HISTORY_PUSH_TAG as S,HISTORY_MERGE_TAG as _,$isRangeSelection as x,$isTextNode as k,$isRootNode as v,$isElementNode as C}from\"lexical\";function b(t){return JSON.stringify([t.exportJSON(),C(t)?t.getChildrenKeys():null])}function E(t,e,n){let o=n(),r=0,i=o,a=0,l=null;const u=new Set;return(s,d,c,f,C,E)=>{const w=n();if(E.has(p)&&(i=o,a=r,l=s,u.clear()),null!==l){for(const t of f)u.add(t);for(const t of C.keys())u.add(t)}if(E.has(h))return r=0,o=w,l=null,u.clear(),2;const D=E.has(m);D&&l&&(o=i,r=a,s=l);const M=E.has(g)||E.has(y)?0:function(t,e,n,o,r){if(null===t||0===n.size&&0===o.size&&!r)return 0;const i=e._selection,a=t._selection;if(r)return 1;if(!(x(i)&&x(a)&&a.isCollapsed()&&i.isCollapsed()))return 0;const l=function(t,e,n){const o=t._nodeMap,r=[];for(const t of e){const e=o.get(t);void 0!==e&&r.push(e)}for(const[t,e]of n){if(!e)continue;const n=o.get(t);void 0===n||v(n)||r.push(n)}return r}(e,n,o);if(0===l.length)return 0;if(l.length>1){const n=e._nodeMap,o=n.get(i.anchor.key),r=n.get(a.anchor.key);return o&&r&&!t._nodeMap.has(o.__key)&&k(o)&&1===o.__text.length&&1===i.anchor.offset?2:0}const u=l[0],s=t._nodeMap.get(u.__key);if(!k(s)||!k(u)||s.__mode!==u.__mode)return 0;const d=s.__text,c=u.__text;if(d===c)return 0;const f=i.anchor,p=a.anchor;if(f.key!==p.key||\"text\"!==f.type)return 0;const h=f.offset,m=p.offset,g=c.length-d.length;return 1===g&&m===h-1?2:-1===g&&m===h+1?3:-1===g&&m===h?4:0}(s,d,f,C,t.isComposing());let O=!1;const J=(()=>{const n=null===c||c.editor===t,i=E.has(S),a=!i&&n&&E.has(_);if(D&&null!==l&&n&&!i&&function(t,e,n){for(const o of t){const t=e._nodeMap.get(o),r=n._nodeMap.get(o);if(!(t===r||t&&r&&e.read(()=>b(t))===n.read(()=>b(r))))return!1}return!0}(u,l,d))return O=!0,0;if(a)return 0;if(1===M)return 2;if(null===s)return 1;const p=d._selection;if(!(f.size>0||C.size>0))return null!==p?0:2;const h=\"number\"==typeof e?e:e.peek();return!1===i&&0!==M&&M===r&&w<o+h&&n||!i&&1===f.size&&function(t,e,n){const o=e._nodeMap.get(t),r=n._nodeMap.get(t),i=e._selection,a=n._selection;return!(x(i)&&x(a)&&\"element\"===i.anchor.type&&\"element\"===i.focus.type&&\"text\"===a.anchor.type&&\"text\"===a.focus.type||!k(o)||!k(r)||o.__parent!==r.__parent)&&JSON.stringify(e.read(()=>o.exportJSON()))===JSON.stringify(n.read(()=>r.exportJSON()))}(Array.from(f)[0],s,d)?0:1})();return D&&(l=null,u.clear()),O||(o=w,r=M),J}}function w(t,e){if(null!==e&&e.editor===t.editor)return e;const{editor:n}=t,o=n.getEditorState();return o.isEmpty()?null:{editor:n,editorState:o}}function D(t,e){t.undoStack=[],t.redoStack=[],t.current=null,e&&e(t)}function M(t,e,n,o=Date.now,r,p=null){const m=E(t,n,o),g=()=>{r&&r(e)};return g(),i(t.registerCommand(a,()=>(function(t,e,n){const o=e.redoStack,r=e.undoStack;if(0!==r.length){const i=e.current,a=r.pop();if(a){const e=w(a,i);null!==e&&(o.push(e),t.dispatchCommand(c,!0))}0===r.length&&t.dispatchCommand(f,!1),e.current=a||null,n&&n(e),a&&a.editor.setEditorState(a.editorState,{tag:h})}}(t,e,r),!0),l),t.registerCommand(u,()=>(function(t,e,n){const o=e.redoStack,r=e.undoStack;if(0!==o.length){const i=e.current,a=o.pop();if(a){const e=w(a,i);null!==e&&(r.push(e),t.dispatchCommand(f,!0))}0===o.length&&t.dispatchCommand(c,!1),e.current=a||null,n&&n(e),a&&a.editor.setEditorState(a.editorState,{tag:h})}}(t,e,r),!0),l),t.registerCommand(s,()=>(D(e,r),!1),l),t.registerCommand(d,()=>(D(e,r),t.dispatchCommand(c,!1),t.dispatchCommand(f,!1),!0),l),t.registerUpdateListener(({editorState:n,prevEditorState:o,dirtyLeaves:r,dirtyElements:i,tags:a})=>{const l=e.current,u=e.redoStack,s=e.undoStack,d=null===l?null:l.editorState;if(null!==l&&n===d)return;const h=m(o,n,l,r,i,a);if(1===h){0!==u.length&&(e.redoStack=[],t.dispatchCommand(c,!1));const n=function(t,e,n){return null===n?null:n.editor===t?{...n}:e.isEmpty()?null:{editor:t,editorState:e}}(t,o,l);if(null!==n){s.push(n);const e=\"number\"==typeof p||null===p?p:p.peek();null!==e&&s.length>e&&s.splice(0,s.length-e),t.dispatchCommand(f,!0)}}else if(2===h)return;e.current={editor:t,editorState:n},g()}))}function O(){return{current:null,redoStack:[],undoStack:[]}}const J={build:(t,{delay:e,createInitialHistoryState:n,disabled:o,maxDepth:i,now:a},l)=>({...r({delay:e,disabled:o,historyState:n(t),maxDepth:i,now:a}),...l.getInitResult()}),config:{createInitialHistoryState:O,delay:300,disabled:\"undefined\"==typeof window,maxDepth:null,now:()=>Date.now()},init:()=>({canRedo:e(!1),canUndo:e(!1)}),name:\"@lexical/history/History\",register:(e,o,r)=>{const{canUndo:i,canRedo:a}=r.getInitResult(),l=r.getOutput(),u=t=>n(()=>{i.value=null!=t&&t.undoStack.length>0,a.value=null!=t&&t.redoStack.length>0});return t(()=>{if(!l.disabled.value)return M(e,l.historyState.value,l.delay,()=>l.now.peek()(),u,l.maxDepth);u(null)})}};function N(t){const e=t?o(t,\"@lexical/extension/HMR\"):void 0;return e?e.output.restoreCount.value:0}const z={build:(t,{disabled:e,parentEditor:n})=>r({disabled:e,parentEditor:n||t._parentEditor}),config:{disabled:!1,parentEditor:null},dependencies:[[J,{disabled:!0}]],name:\"@lexical/history/SharedHistory\",register:(e,r,i)=>t(()=>{const{disabled:t,parentEditor:r}=i.getOutput();if(!t.value){const{output:t}=i.getDependency(J);N(e),N(r.value);const a=function(t){return t?o(t,J.name):null}(r.value);if(!a)return;const l=a.output;n(()=>{t.delay.value=l.delay.value,t.historyState.value=l.historyState.value,t.now.value=l.now.value,t.maxDepth.value=l.maxDepth.value,t.disabled.value=l.disabled.value})}})};export{J as HistoryExtension,z as SharedHistoryExtension,O as createEmptyHistoryState,M as registerHistory};\n","/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\nimport{getterTableOf as e,setterTableOf as t,setterDefaultOf as n,ElementNode as o,$getDocument as l,addClassNamesToElement as r,isHTMLElement as i,$setDirectionFromDOM as s,$isInlineElementOrDecoratorNode as c,$isTextNode as a,$isLineBreakNode as u,$createParagraphNode as h,$applyNodeReplacement as d,nodeSchema as f,withField as g,optional as m,numberValue as p,withAccessors as _,enumValue as C,nullable as S,stringValue as y,createCommand as b,$createTextNode as w,$getSelection as x,$isRangeSelection as v,$findMatchingParent as N,$isParagraphNode as T,$copyNode as R,$createPoint as F,$getNodeByKey as A,$isElementNode as O,$normalizeSelection__EXPERIMENTAL as K,isCurrentlyReadOnlyMode as k,TEXT_TYPE_TO_FORMAT as E,$getEditor as z,$setSelection as M,SELECTION_CHANGE_COMMAND as W,removeClassNamesFromElement as $,getDOMSelection as L,$createRangeSelection as H,$isRootNode as D,INSERT_PARAGRAPH_COMMAND as P,registerEventListener as B,KEY_ARROW_DOWN_COMMAND as I,KEY_ARROW_UP_COMMAND as U,KEY_ARROW_LEFT_COMMAND as X,KEY_ARROW_RIGHT_COMMAND as Y,COMMAND_PRIORITY_HIGH as q,KEY_ESCAPE_COMMAND as V,DELETE_WORD_COMMAND as j,DELETE_LINE_COMMAND as J,DELETE_CHARACTER_COMMAND as G,KEY_BACKSPACE_COMMAND as Q,KEY_DELETE_COMMAND as Z,CUT_COMMAND as ee,PASTE_COMMAND as te,getComposedEventTarget as ne,isDOMNode as oe,getActiveElement as le,COPY_COMMAND as re,FORMAT_TEXT_COMMAND as ie,FORMAT_ELEMENT_COMMAND as se,CONTROLLED_TEXT_INSERTION_COMMAND as ce,KEY_TAB_COMMAND as ae,FOCUS_COMMAND as ue,$getNearestNodeFromDOMNode as he,$isRootOrShadowRoot as de,getDOMSelectionRange as fe,getDOMSelectionPoints as ge,mergeRegister as me,registerEventListeners as pe,$getPreviousSelection as _e,$caretFromPoint as Ce,$getChildCaret as Se,$getCommonAncestor as ye,$comparePointCaretNext as be,$isExtendableTextPointCaret as we,$extendCaretToRange as xe,$isSiblingCaret as ve,$getSiblingCaret as Ne,$setPointFromCaret as Te,$normalizeCaret as Re,$createRangeSelectionFromDom as Fe,$isChildCaret as Ae,$getAdjacentChildCaret as Oe,IS_FIREFOX as Ke,$getNodeByKeyOrThrow as ke,isDOMDocumentNode as Ee,isDOMShadowRoot as ze,setDOMStyleFromCSS as Me,setDOMUnmanaged as We,booleanValue as $e,arrayValue as Le,COMMAND_PRIORITY_EDITOR as He,SELECTION_INSERT_CLIPBOARD_NODES_COMMAND as De,SELECT_ALL_COMMAND as Pe,COMMAND_PRIORITY_LOW as Be,CLICK_COMMAND as Ie,$getRoot as Ue,isHTMLTableRowElement as Xe,IS_BOLD as Ye,IS_ITALIC as qe,IS_UNDERLINE as Ve,IS_STRIKETHROUGH as je,$fullReconcile as Je}from\"lexical\";import{signal as Ge,effect as Qe}from\"@lexical/extension/signals\";import{namedSignals as Ze}from\"@lexical/extension/namedSignals\";import{sel as et,ImportTextFormat as tt,ImportTextStyle as nt,contextValue as ot,$propagateTextAlignToBlockChildren as lt,CoreImportExtension as rt,DOMImportExtension as it}from\"@lexical/html\";import{getPeerDependencyFromEditor as st}from\"@lexical/extension/getPeerDependencyFromEditor\";import{$descendantsMatching as ct,objectKlassEquals as at,$insertFirst as ut,$insertNodeToNearestRoot as ht,$dfs as dt,$unwrapAndFilterDescendants as ft}from\"@lexical/utils\";import{copyToClipboard as gt,$getClipboardDataFromSelection as mt}from\"@lexical/clipboard\";const pt=/^(\\d+(?:\\.\\d+)?)px$/,_t=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function Ct(e,t){if(\"number\"==typeof e)return Number.isFinite(e)?e:t;if(\"string\"!=typeof e||!_t.test(e))return t;const n=Number(e);return Number.isFinite(n)?n:t}function St(e,t,n,o,l){const r=Ct(e,t);return r>=n&&r<=o&&Number.isInteger(r)?r:t}function yt(e,t){e.__colWidths=t.__colWidths,e.__frozenColumnCount=t.__frozenColumnCount,e.__frozenRowCount=t.__frozenRowCount,e.__rowStriping=t.__rowStriping}const bt=o=>{const l=e(o,\"format\"),r=t(o,\"format\"),i=n(o,\"format\");return{exportJSON:function(e){const t=e.__textFormat,n=e.__textStyle,o=(0!==t||\"\"!==n)&&e.shouldSerializeTextStyles();return{children:[],colWidths:e.__colWidths,frozenColumnCount:e.getSerializedFrozenColumnCount(),frozenRowCount:e.getSerializedFrozenRowCount(),rowStriping:e.getSerializedRowStriping(),direction:e.__dir,format:l[e.__format],indent:e.__indent,textFormat:0!==t&&o?t:void 0,textStyle:\"\"!==n&&o?n:void 0,type:e.__type,version:1}},exportCompactJSON:function(e){const t=e.__textFormat,n=e.__textStyle,o=(0!==t||\"\"!==n)&&e.shouldSerializeTextStyles(),r={type:e.__type,children:[]},i=e.__colWidths;void 0!==i&&(r.colWidths=i);const s=e.getSerializedFrozenColumnCount();void 0!==s&&0!==s&&(r.frozenColumnCount=s);const c=e.getSerializedFrozenRowCount();void 0!==c&&0!==c&&(r.frozenRowCount=c);const a=e.getSerializedRowStriping();void 0!==a&&!1!==a&&(r.rowStriping=a);const u=e.__dir;null!=u&&(r.direction=u);const h=l[e.__format];void 0!==h&&\"\"!==h&&(r.format=h);const d=e.__indent;return void 0!==d&&0!==d&&(r.indent=d),void 0!==t&&0!==t&&o&&(r.textFormat=t),void 0!==n&&\"\"!==n&&o&&(r.textStyle=n),r},updateFromJSON:function(e,t){const n=t.direction;e.__dir=null===n||\"ltr\"===n||\"rtl\"===n?n:null;const o=t.format;e.__format=\"string\"==typeof o&&o in r?r[o]:i,e.__indent=St(t.indent,0,0,Infinity),e.__textFormat=Ct(t.textFormat,0);const l=t.textStyle;e.__textStyle=\"string\"==typeof l?l:\"\";const s=t.colWidths;e.setColWidths(void 0===s?void 0:Array.isArray(s)?Array.from(s,e=>Ct(e,0)):[]),e.__frozenColumnCount=Ct(t.frozenColumnCount,0),e.__frozenRowCount=Ct(t.frozenRowCount,0);const c=t.rowStriping;return e.__rowStriping=\"boolean\"==typeof c&&c,e},afterCloneFrom:yt}};function wt(e,t){e.__height=t.__height}const xt=o=>{const l=e(o,\"format\"),r=t(o,\"format\"),i=n(o,\"format\");return{exportJSON:function(e){const t=e.__textFormat,n=e.__textStyle,o=(0!==t||\"\"!==n)&&e.shouldSerializeTextStyles();return{children:[],height:e.__height,direction:e.__dir,format:l[e.__format],indent:e.__indent,textFormat:0!==t&&o?t:void 0,textStyle:\"\"!==n&&o?n:void 0,type:e.__type,version:1}},exportCompactJSON:function(e){const t=e.__textFormat,n=e.__textStyle,o=(0!==t||\"\"!==n)&&e.shouldSerializeTextStyles(),r={type:e.__type,children:[]},i=e.__height;void 0!==i&&(r.height=i);const s=e.__dir;null!=s&&(r.direction=s);const c=l[e.__format];void 0!==c&&\"\"!==c&&(r.format=c);const a=e.__indent;return void 0!==a&&0!==a&&(r.indent=a),void 0!==t&&0!==t&&o&&(r.textFormat=t),void 0!==n&&\"\"!==n&&o&&(r.textStyle=n),r},updateFromJSON:function(e,t){const n=t.direction;e.__dir=null===n||\"ltr\"===n||\"rtl\"===n?n:null;const o=t.format;e.__format=\"string\"==typeof o&&o in r?r[o]:i,e.__indent=St(t.indent,0,0,Infinity),e.__textFormat=Ct(t.textFormat,0);const l=t.textStyle;e.__textStyle=\"string\"==typeof l?l:\"\";const s=t.height;return e.__height=void 0===s?void 0:Ct(s,0),e},afterCloneFrom:wt}};function vt(e,t){e.__backgroundColor=t.__backgroundColor,e.__colSpan=t.__colSpan,e.__headerState=t.__headerState,e.__rowSpan=t.__rowSpan,e.__verticalAlign=t.__verticalAlign,e.__width=t.__width}const Nt=o=>{const l=e(o,\"format\"),r=t(o,\"format\"),i=n(o,\"format\");return{exportJSON:function(e){const t=e.__textFormat,n=e.__textStyle,o=(0!==t||\"\"!==n)&&e.shouldSerializeTextStyles();return{children:[],backgroundColor:e.__backgroundColor,colSpan:e.__colSpan,headerState:e.__headerState,rowSpan:e.__rowSpan,verticalAlign:e.getSerializedVerticalAlign(),width:e.__width,direction:e.__dir,format:l[e.__format],indent:e.__indent,textFormat:0!==t&&o?t:void 0,textStyle:\"\"!==n&&o?n:void 0,type:e.__type,version:1}},exportCompactJSON:function(e){const t=e.__textFormat,n=e.__textStyle,o=(0!==t||\"\"!==n)&&e.shouldSerializeTextStyles(),r={type:e.__type,children:[]},i=e.__backgroundColor;null!=i&&(r.backgroundColor=i);const s=e.__colSpan;void 0!==s&&1!==s&&(r.colSpan=s);const c=e.__headerState;void 0!==c&&0!==c&&(r.headerState=c);const a=e.__rowSpan;void 0!==a&&1!==a&&(r.rowSpan=a);const u=e.getSerializedVerticalAlign();void 0!==u&&(r.verticalAlign=u);const h=e.__width;void 0!==h&&(r.width=h);const d=e.__dir;null!=d&&(r.direction=d);const f=l[e.__format];void 0!==f&&\"\"!==f&&(r.format=f);const g=e.__indent;return void 0!==g&&0!==g&&(r.indent=g),void 0!==t&&0!==t&&o&&(r.textFormat=t),void 0!==n&&\"\"!==n&&o&&(r.textStyle=n),r},updateFromJSON:function(e,t){const n=t.direction;e.__dir=null===n||\"ltr\"===n||\"rtl\"===n?n:null;const o=t.format;e.__format=\"string\"==typeof o&&o in r?r[o]:i,e.__indent=St(t.indent,0,0,Infinity),e.__textFormat=Ct(t.textFormat,0);const l=t.textStyle;e.__textStyle=\"string\"==typeof l?l:\"\";const s=t.backgroundColor;e.__backgroundColor=\"string\"==typeof s&&\"\"!==s?s:null,e.__colSpan=St(t.colSpan,1,1,Infinity),e.setHeaderStyles(Ct(t.headerState,0)),e.__rowSpan=St(t.rowSpan,1,1,Infinity);const c=t.verticalAlign;e.__verticalAlign=\"middle\"===c||\"bottom\"===c?c:void 0;const a=t.width;return e.__width=void 0===a||0===Ct(a,0)?void 0:Ct(a,0),e},afterCloneFrom:vt}},Tt={BOTH:3,COLUMN:2,NO_STATUS:0,ROW:1},Rt=/* @__PURE__ */f()({backgroundColor:/* @__PURE__ */g(/* @__PURE__ */S(/* @__PURE__ */y(),{defaultAsNull:!0}),{field:\"__backgroundColor\"}),colSpan:/* @__PURE__ */g(/* @__PURE__ */p(1,{integer:!0,min:1}),{field:\"__colSpan\"}),headerState:/* @__PURE__ */_(/* @__PURE__ */p(0),{getter:{field:\"__headerState\",method:\"getHeaderStyles\"},setter:\"setHeaderStyles\"}),rowSpan:/* @__PURE__ */g(/* @__PURE__ */p(1,{integer:!0,min:1}),{field:\"__rowSpan\"}),verticalAlign:/* @__PURE__ */_(/* @__PURE__ */C([void 0,\"middle\",\"bottom\"]),{getter:\"getSerializedVerticalAlign\",setter:{field:\"__verticalAlign\"}}),width:/* @__PURE__ */g(/* @__PURE__ */m(/* @__PURE__ */p(),{omitDefault:!0}),{field:\"__width\"})});class Ft extends o{__colSpan;__rowSpan;__headerState;__width;__backgroundColor;__verticalAlign;$config(){return this.config(\"tablecell\",{children:\"block\",extends:o,generated:Nt,importDOM:{td:()=>({conversion:Ot,priority:0}),th:()=>({conversion:Ot,priority:0})},json:Rt})}constructor(e=Tt.NO_STATUS,t=1,n,o){super(o),this.__colSpan=t,this.__rowSpan=1,this.__headerState=e,this.__width=n,this.__backgroundColor=null,this.__verticalAlign=void 0}createDOM(e){const t=l().createElement(this.getTag());return this.__width&&(t.style.width=`${this.__width}px`),this.__colSpan>1&&(t.colSpan=this.__colSpan),this.__rowSpan>1&&(t.rowSpan=this.__rowSpan),null!==this.__backgroundColor&&(t.style.backgroundColor=this.__backgroundColor),At(this.__verticalAlign)&&(t.style.verticalAlign=this.__verticalAlign),r(t,e.theme.tableCell,this.hasHeader()&&e.theme.tableCellHeader),t}exportDOM(e){const t=super.exportDOM(e);if(i(t.element)){const e=t.element;e.setAttribute(\"data-temporary-table-cell-lexical-key\",this.getKey()),e.style.border=\"1px solid black\",this.__colSpan>1&&(e.colSpan=this.__colSpan),this.__rowSpan>1&&(e.rowSpan=this.__rowSpan),e.style.width=`${this.getWidth()||75}px`,e.style.verticalAlign=this.getVerticalAlign()||\"top\",e.style.textAlign=\"start\",null===this.__backgroundColor&&this.hasHeader()&&(e.style.backgroundColor=\"#f2f3f5\")}return t}getColSpan(){return this.getLatest().__colSpan}setColSpan(e){const t=this.getWritable();return t.__colSpan=e,t}getRowSpan(){return this.getLatest().__rowSpan}setRowSpan(e){const t=this.getWritable();return t.__rowSpan=e,t}getTag(){return this.hasHeader()?\"th\":\"td\"}setHeaderStyles(e,t=Tt.BOTH){const n=this.getWritable();return n.__headerState=e&t|n.__headerState&~t,n}getHeaderStyles(){return this.getLatest().__headerState}setWidth(e){const t=this.getWritable();return t.__width=e,t}getWidth(){return this.getLatest().__width}getSerializedVerticalAlign(){const e=this.getLatest().__verticalAlign;return At(e)?e:void 0}getBackgroundColor(){return this.getLatest().__backgroundColor}setBackgroundColor(e){const t=this.getWritable();return t.__backgroundColor=e,t}getVerticalAlign(){return this.getLatest().__verticalAlign}setVerticalAlign(e){const t=this.getWritable();return t.__verticalAlign=e||void 0,t}toggleHeaderStyle(e){const t=this.getWritable();return(t.__headerState&e)===e?t.__headerState&=~e:t.__headerState|=e,t}hasHeaderState(e){return(this.getHeaderStyles()&e)===e}hasHeader(){return this.getLatest().__headerState!==Tt.NO_STATUS}updateDOM(e){return e.__headerState!==this.__headerState||e.__width!==this.__width||e.__colSpan!==this.__colSpan||e.__rowSpan!==this.__rowSpan||e.__backgroundColor!==this.__backgroundColor||e.__verticalAlign!==this.__verticalAlign}isShadowRoot(){return!0}collapseAtStart(){return!0}canBeEmpty(){return!1}canIndent(){return!1}}function At(e){return\"middle\"===e||\"bottom\"===e}function Ot(e){const t=e,n=e.nodeName.toLowerCase();let o;pt.test(t.style.width)&&(o=parseFloat(t.style.width));let l=Tt.NO_STATUS;if(\"th\"===n){const e=t.getAttribute(\"scope\");if(\"col\"===e)l=Tt.COLUMN;else if(\"row\"===e)l=Tt.ROW;else{const e=t.parentElement,n=i(e)&&\"tr\"===e.nodeName.toLowerCase()&&i(e.parentElement)&&(\"thead\"===e.parentElement.nodeName.toLowerCase()||0===e.rowIndex),o=0===t.cellIndex;n&&(l|=Tt.ROW),o&&(l|=Tt.COLUMN),l===Tt.NO_STATUS&&(l=Tt.ROW)}}const r=Kt(l,t.colSpan,o);r.__rowSpan=t.rowSpan;const d=t.style.backgroundColor;\"\"!==d&&(r.__backgroundColor=d);const f=t.style.verticalAlign;At(f)&&(r.__verticalAlign=f),s(r,t);const g=t.style,m=(g&&g.textDecoration||\"\").split(\" \"),p=\"700\"===g.fontWeight||\"bold\"===g.fontWeight,_=m.includes(\"line-through\"),C=\"italic\"===g.fontStyle,S=m.includes(\"underline\"),y=g.color;return{after:e=>{const t=[];let n=null;const o=()=>{if(n){const e=n.getFirstChild();u(e)&&1===n.getChildrenSize()&&e.remove()}};for(const l of e)if(c(l)||a(l)||u(l)){if(a(l)&&(p&&l.toggleFormat(\"bold\"),_&&l.toggleFormat(\"strikethrough\"),C&&l.toggleFormat(\"italic\"),S&&l.toggleFormat(\"underline\"),y)){const e=l.getStyle();e.includes(\"color:\")||l.setStyle(e+`color: ${y};`)}n?n.append(l):(n=h().append(l),t.push(n))}else t.push(l),o(),n=null;return o(),0===t.length&&t.push(h()),t},node:r}}function Kt(e=Tt.NO_STATUS,t=1,n){return d(new Ft(e,t,n))}function kt(e){return e instanceof Ft}const Et=/* @__PURE__ */b(\"INSERT_TABLE_COMMAND\");function zt(e,...t){throw function(e,...t){const n=new URL(\"https://lexical.dev/docs/error\"),o=new URLSearchParams;o.append(\"code\",e);for(const e of t)o.append(\"v\",e);return n.search=o.toString(),new Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(e,...t)}const Mt=/* @__PURE__ */f()({height:/* @__PURE__ */g(/* @__PURE__ */m(/* @__PURE__ */p()),{field:\"__height\"})});class Wt extends o{__height;$config(){return this.config(\"tablerow\",{extends:o,generated:xt,importDOM:{tr:()=>({conversion:$t,priority:0})},json:Mt})}constructor(e=void 0,t){super(t),this.__height=e}createDOM(e){const t=l().createElement(\"tr\");return this.__height&&(t.style.height=`${this.__height}px`),r(t,e.theme.tableRow),t}extractWithChild(e,t,n){return\"html\"===n}isShadowRoot(){return!0}setHeight(e){const t=this.getWritable();return t.__height=e,t}getHeight(){return this.getLatest().__height}updateDOM(e){return e.__height!==this.__height}canBeEmpty(){return!1}canIndent(){return!1}}function $t(e){const t=e;let n;return pt.test(t.style.height)&&(n=parseFloat(t.style.height)),{after:e=>ct(e,kt),node:s(Lt(n),t)}}function Lt(e){return d(new Wt(e))}function Ht(e){return e instanceof Wt}function Dt(e,t,n=!0){const o=Mo();for(let l=0;l<e;l++){const e=Lt();for(let o=0;o<t;o++){let t=Tt.NO_STATUS;\"object\"==typeof n?(0===l&&n.rows&&(t|=Tt.ROW),0===o&&n.columns&&(t|=Tt.COLUMN)):n&&(0===l&&(t|=Tt.ROW),0===o&&(t|=Tt.COLUMN));const r=Kt(t),i=h();i.append(w()),r.append(i),e.append(r)}o.append(e)}return o}function Pt(e){const t=N(e,e=>kt(e));return kt(t)?t:null}function Bt(e){const t=N(e,e=>Ht(e));if(Ht(t))return t;throw new Error(\"Expected table cell to be inside of table row.\")}function It(e){const t=N(e,e=>Wo(e));if(Wo(t))return t;throw new Error(\"Expected table cell to be inside of table.\")}function Ut(e){const t=Bt(e);return It(t).getChildren().findIndex(e=>e.is(t))}function Xt(e){return Bt(e).getChildren().findIndex(t=>t.is(e))}function Yt(e,t){const n=It(e),{x:o,y:l}=n.getCordsFromCellNode(e,t);return{above:n.getCellNodeFromCords(o,l-1,t),below:n.getCellNodeFromCords(o,l+1,t),left:n.getCellNodeFromCords(o-1,l,t),right:n.getCellNodeFromCords(o+1,l,t)}}function qt(e,t){const n=e.getChildren();if(t>=n.length||t<0)throw new Error(\"Expected table cell to be inside of table row.\");return n[t].remove(),e}function Vt(e,t,n=!0,o,l){const r=e.getChildren();if(t>=r.length||t<0)throw new Error(\"Table row target index out of range\");const i=r[t];if(!Ht(i))throw new Error(\"Row before insertion index does not exist.\");for(let e=0;e<o;e++){const e=i.getChildren(),t=e.length,o=Lt();for(let n=0;n<t;n++){const t=e[n];kt(t)||zt(12);const{above:r,below:i}=Yt(t,l);let s=Tt.NO_STATUS;const c=r&&r.getWidth()||i&&i.getWidth()||void 0;(r&&r.hasHeaderState(Tt.COLUMN)||i&&i.hasHeaderState(Tt.COLUMN))&&(s|=Tt.COLUMN);const a=Kt(s,1,c);a.append(h()),o.append(a)}n?i.insertAfter(o):i.insertBefore(o)}return e}const jt=(e,t)=>e===Tt.BOTH||e===t?t:Tt.NO_STATUS;function Jt(e=!0){const t=x();v(t)||An(t)||zt(188);const n=t.anchor.getNode(),o=t.focus.getNode(),[l]=Cn(n),[r,,i]=Cn(o),[,s,c]=mn(i,r,l),{startRow:a}=c,{startRow:u}=s;return e?Qt(a+l.__rowSpan>u+r.__rowSpan?l:r,!0):Qt(u<a?r:l,!1)}const Gt=Jt;function Qt(e,t=!0){const[,,n]=Cn(e);_n(n);const[o,l]=mn(n,e,e),r=o[0].length,{startRow:i}=l;let s=null;if(t){const t=i+e.__rowSpan-1,l=o[t],c=Lt();for(let e=0;e<r;e++){const{cell:n,startRow:o}=l[e];if(o+n.__rowSpan-1<=t){const t=l[e].cell.__headerState,n=jt(t,Tt.COLUMN);c.append(Kt(n).append(h()))}else n.setRowSpan(n.__rowSpan+1)}const a=n.getChildAtIndex(t);Ht(a)||zt(256),a.insertAfter(c),s=c}else{const e=i,t=o[e],l=Lt();for(let n=0;n<r;n++){const{cell:o,startRow:r}=t[n];if(r===e){const e=t[n].cell.__headerState,o=jt(e,Tt.COLUMN);l.append(Kt(o).append(h()))}else o.setRowSpan(o.__rowSpan+1)}const c=n.getChildAtIndex(e);Ht(c)||zt(257),c.insertBefore(l),s=l}return s}function Zt(e,t,n=!0,o,l){const r=e.getChildren(),i=[];for(let e=0;e<r.length;e++){const n=r[e];if(Ht(n))for(let e=0;e<o;e++){const e=n.getChildren();if(t>=e.length||t<0)throw new Error(\"Table column target index out of range\");const o=e[t];kt(o)||zt(12);const{left:r,right:s}=Yt(o,l);let c=Tt.NO_STATUS;(r&&r.hasHeaderState(Tt.ROW)||s&&s.hasHeaderState(Tt.ROW))&&(c|=Tt.ROW);const a=Kt(c);a.append(h()),i.push({newTableCell:a,targetCell:o})}}return i.forEach(({newTableCell:e,targetCell:t})=>{n?t.insertAfter(e):t.insertBefore(e)}),e}function en(e=!0){const t=x();v(t)||An(t)||zt(188);const n=t.anchor.getNode(),o=t.focus.getNode(),[l]=Cn(n),[r,,i]=Cn(o),[,s,c]=mn(i,r,l),{startColumn:a}=c,{startColumn:u}=s;return e?nn(a+l.__colSpan>u+r.__colSpan?l:r,!0):nn(u<a?r:l,!1)}const tn=en;function nn(e,t=!0,n=!0){const[,,o]=Cn(e);_n(o);const[l,r]=mn(o,e,e),i=l.length,{startColumn:s}=r,c=t?s+e.__colSpan-1:s-1,a=o.getFirstChild();Ht(a)||zt(120);let u=null;function d(e=Tt.NO_STATUS){const t=Kt(e).append(h());return null===u&&(u=t),t}let f=a;for(let e=0;e<i;e++){if(0!==e){const e=f.getNextSibling();Ht(e)||zt(121),f=e}const t=l[e],n=t[c<0?0:c].cell.__headerState,o=jt(n,Tt.ROW);if(c<0){un(f,d(o));continue}const{cell:r,startColumn:i}=t[c];if(i+r.__colSpan-1<=c){let n=null;for(let o=0;o<=c;o++){const l=t[o];l.startRow===e&&(n=l.cell),l.cell.__colSpan>1&&(o+=l.cell.__colSpan-1)}null===n?un(f,d(o)):n.insertAfter(d(o))}else r.setColSpan(r.__colSpan+1)}null!==u&&n&&an(u);const g=o.getColWidths();if(g){const e=[...g],t=c<0?0:c,n=e[t];e.splice(t,0,n),o.setColWidths(e)}return u}function on(e,t){const n=e.getChildren();for(let e=0;e<n.length;e++){const o=n[e];if(Ht(o)){const e=o.getChildren();if(t>=e.length||t<0)throw new Error(\"Table column target index out of range\");e[t].remove()}}return e}function ln(){const e=x();v(e)||An(e)||zt(188);const[t,n]=e.isBackward()?[e.focus.getNode(),e.anchor.getNode()]:[e.anchor.getNode(),e.focus.getNode()],[o,,l]=Cn(t),[r]=Cn(n);_n(l);const[i,s,c]=mn(l,o,r),{startRow:a}=s,{startRow:u}=c,h=u+r.__rowSpan-1;if(i.length===h-a+1)return l.selectPrevious(),void l.remove();const d=i[0].length,f=i[h+1],g=l.getChildAtIndex(h+1);for(let e=h;e>=a;e--){for(let t=d-1;t>=0;t--){const{cell:n,startRow:o,startColumn:l}=i[e][t];if(l===t){if(o<a||o+n.__rowSpan-1>h){const e=Math.max(o,a),t=Math.min(n.__rowSpan+o-1,h),l=e<=t?t-e+1:0;n.setRowSpan(n.__rowSpan-l)}if(o>=a&&o+n.__rowSpan-1>h&&e===h){Ht(g)||zt(387);let o=null;for(let n=0;n<t;n++){const t=f[n],l=t.cell;t.startRow===e+1&&(o=l),l.__colSpan>1&&(n+=l.__colSpan-1)}null===o?un(g,n):o.insertAfter(n)}}}const t=l.getChildAtIndex(e);Ht(t)||zt(206,String(e)),t.remove()}if(void 0!==f){const{cell:e}=f[0];an(e)}else{const e=i[a-1],{cell:t}=e[0];an(t)}}const rn=ln;function sn(){const e=x();v(e)||An(e)||zt(188);const t=e.anchor.getNode(),n=e.focus.getNode(),[o,,l]=Cn(t),[r]=Cn(n);_n(l);const[i,s,c]=mn(l,o,r),{startColumn:a}=s,{startRow:u,startColumn:h}=c,d=Math.min(a,h),f=Math.max(a+o.__colSpan-1,h+r.__colSpan-1),g=f-d+1;if(i[0].length===f-d+1)return l.selectPrevious(),void l.remove();const m=i.length;for(let e=0;e<m;e++)for(let t=d;t<=f;t++){const{cell:n,startColumn:o}=i[e][t];if(o<d){if(t===d){const e=d-o;n.setColSpan(n.__colSpan-Math.min(g,n.__colSpan-e))}}else if(o+n.__colSpan-1>f){if(t===f){const e=f-o+1;n.setColSpan(n.__colSpan-e)}}else n.remove()}const p=i[u],_=a>h?p[a+o.__colSpan]:p[h+r.__colSpan];if(void 0!==_){const{cell:e}=_;an(e)}else{const e=h<a?p[h-1]:p[a-1],{cell:t}=e;an(t)}const C=l.getColWidths();if(C){const e=[...C];e.splice(d,g),l.setColWidths(e)}}const cn=sn;function an(e){const t=e.getFirstDescendant();null==t?e.selectStart():t.getParentOrThrow().selectStart()}function un(e,t){const n=e.getFirstChild();null!==n?n.insertBefore(t):e.append(t)}function hn(e){if(0===e.length)return null;const t=It(e[0]);_n(t);const[n]=pn(t,null,null);let o=Infinity,l=-Infinity,r=Infinity,i=-Infinity;const s=new Set;for(const t of n)for(const n of t){if(!n||!n.cell)continue;const t=n.cell.getKey();if(!s.has(t)&&e.some(e=>e.is(n.cell))){s.add(t);const e=n.startRow,c=n.startColumn,a=n.cell.__rowSpan||1,u=n.cell.__colSpan||1;o=Math.min(o,e),l=Math.max(l,e+a-1),r=Math.min(r,c),i=Math.max(i,c+u-1)}}if(Infinity===o||Infinity===r)return null;const c=l-o+1,a=i-r+1,u=n[o][r];if(!u.cell)return null;const d=u.cell;d.setColSpan(a),d.setRowSpan(c);const f=new Set([d.getKey()]);for(let e=o;e<=l;e++)for(let t=r;t<=i;t++){const o=n[e][t];if(!o.cell)continue;const l=o.cell,r=l.getKey();f.has(r)||(f.add(r),dn(l)||(dn(d)&&d.clear(),d.append(...l.getChildren())),l.remove())}return 0===d.getChildrenSize()&&d.append(h()),d}function dn(e){if(1!==e.getChildrenSize())return!1;const t=e.getFirstChildOrThrow();return!(!T(t)||!t.isEmpty())}function fn(){const e=x();v(e)||An(e)||zt(188);const t=e.anchor.getNode(),n=N(t,kt);return kt(n)||zt(148),gn(n)}function gn(e){const[t,n,o]=Cn(e),l=t.__colSpan,r=t.__rowSpan;if(1===l&&1===r)return;_n(o);const[i,s]=mn(o,t,t),{startColumn:c,startRow:a}=s,u=t.__headerState&Tt.COLUMN,d=Array.from({length:l},(e,t)=>{let n=u;for(let e=0;0!==n&&e<i.length;e++)n&=i[e][t+c].cell.__headerState;return n}),f=t.__headerState&Tt.ROW,g=Array.from({length:r},(e,t)=>{let n=f;for(let e=0;0!==n&&e<i[0].length;e++)n&=i[t+a][e].cell.__headerState;return n}),m=e=>R(t).setColSpan(1).setRowSpan(1).setHeaderStyles(e).setWidth(void 0).append(h());if(l>1){for(let e=1;e<l;e++)t.insertAfter(m(d[e]|g[0]));t.setColSpan(1)}if(r>1){let e;for(let t=1;t<r;t++){const o=a+t,r=i[o];e=(e||n).getNextSibling(),Ht(e)||zt(125);let s=null;for(let e=0;e<c;e++){const t=r[e],n=t.cell;t.startRow===o&&(s=n),n.__colSpan>1&&(e+=n.__colSpan-1)}if(null===s)for(let n=l-1;n>=0;n--)un(e,m(d[n]|g[t]));else for(let e=l-1;e>=0;e--)s.insertAfter(m(d[e]|g[t]))}t.setRowSpan(1)}}function mn(e,t,n){const[o,l,r]=pn(e,t,n);return null===l&&zt(207),null===r&&zt(208),[o,l,r]}function pn(e,t,n){const o=[];let l=null,r=null;function i(e){let t=o[e];return void 0===t&&(o[e]=t=[]),t}const s=e.getChildren();for(let e=0;e<s.length;e++){const o=s[e];Ht(o)||zt(209);const c=i(e);for(let a=o.getFirstChild(),u=0;null!=a;a=a.getNextSibling()){for(kt(a)||zt(147);void 0!==c[u];)u++;const o={cell:a,startColumn:u,startRow:e},{__rowSpan:h,__colSpan:d}=a;for(let t=0;t<h&&!(e+t>=s.length);t++){const n=i(e+t);for(let e=0;e<d;e++)n[u+e]=o}null!==t&&null===l&&t.is(a)&&(l=o),null!==n&&null===r&&n.is(a)&&(r=o)}}return[o,l,r]}function _n(e){const[t]=pn(e,null,null),n=t.reduce((e,t)=>Math.max(e,t.length),0),o=e.getChildren();let l=!1;for(let e=0;e<t.length;++e){const r=o[e];if(!Ht(r))continue;const i=t[e].reduce((e,t)=>t?1+e:e,0);if(i>=n)continue;const s=r.getLastChild(),c=kt(s)?s.getHeaderStyles()&Tt.ROW:Tt.NO_STATUS;for(let e=i;e<n;++e)r.append(Kt(c).append(h()));l=!0}return l}function Cn(e){let t;if(e instanceof Ft)t=e;else if(\"__type\"in e){const n=N(e,kt);kt(n)||zt(148),t=n}else{const n=N(e.getNode(),kt);kt(n)||zt(148),t=n}const n=t.getParent();Ht(n)||zt(149);const o=n.getParent();return Wo(o)||zt(210),[t,n,o]}function Sn(e,t,n){let o,l=Math.min(t.startColumn,n.startColumn),r=Math.min(t.startRow,n.startRow),i=Math.max(t.startColumn+t.cell.__colSpan-1,n.startColumn+n.cell.__colSpan-1),s=Math.max(t.startRow+t.cell.__rowSpan-1,n.startRow+n.cell.__rowSpan-1);do{o=!1;for(let t=0;t<e.length;t++)for(let n=0;n<e[0].length;n++){const c=e[t][n];if(!c)continue;const a=c.startColumn+c.cell.__colSpan-1,u=c.startRow+c.cell.__rowSpan-1,h=c.startColumn<=i&&a>=l,d=c.startRow<=s&&u>=r;if(h&&d){const e=Math.min(l,c.startColumn),t=Math.max(i,a),n=Math.min(r,c.startRow),h=Math.max(s,u);e===l&&t===i&&n===r&&h===s||(l=e,i=t,r=n,s=h,o=!0)}}}while(o);return{maxColumn:i,maxRow:s,minColumn:l,minRow:r}}function yn(e){const t=e.getChildren();let n=null;for(const e of t){if(!Ht(e))return!1;if(null===n&&(n=e.getChildrenSize()),e.getChildrenSize()!==n)return!1;const t=e.getChildren();for(const e of t)if(!kt(e)||1!==e.getRowSpan()||1!==e.getColSpan())return!1}return(n||0)>0}function bn(e,t,n){if(t===n)return;const o=e.getColumnCount();if(t<0||t>=o||n<0||n>=o)return;if(!yn(e))return;e.getChildren().filter(Ht).forEach(e=>{const o=e.getChildren(),[l]=o.splice(t,1);o.splice(n,0,l),e.splice(0,o.length,o)});const l=e.getColWidths();if(l&&l.length===o){const o=[...l],[r]=o.splice(t,1);o.splice(n,0,r),e.setColWidths(o)}}function wn(e,t,n){if(t===n)return;const o=e.getChildren().filter(Ht),l=o.length;if(t<0||t>=l||n<0||n>=l)return;if(!yn(e))return;const r=o[t],i=o[n];n>t?i.insertAfter(r):i.insertBefore(r)}function xn(e){const[t,,n]=Cn(e),o=n.getChildren().filter(Ht),l=o.length,r=o[0].getChildren().length,i=new Array(l);for(let e=0;e<l;e++)i[e]=new Array(r);for(let e=0;e<l;e++){const n=o[e].getChildren().filter(kt);let l=0;for(let o=0;o<n.length;o++){for(;i[e][l];)l++;const r=n[o],s=r.__rowSpan||1,c=r.__colSpan||1;for(let t=0;t<s;t++)for(let n=0;n<c;n++)i[e+t][l+n]=r;if(t===r)return{colSpan:c,columnIndex:l,rowIndex:e,rowSpan:s};l+=c}}return null}function vn(e,t){const n=t.getStartEndPoints(),o=An(t);if(null===n)return!1;const[l,r]=n,[i,s,c]=Cn(l),u=N(r.getNode(),e=>kt(e));if(!(kt(i)&&kt(u)&&Ht(s)&&Wo(c)))return!1;_n(c);const[d,f,g]=mn(c,i,u),[m]=pn(e,null,null),p=d.length,_=p>0?d[0].length:0;let C=f.startRow,S=f.startColumn,y=m.length,b=y>0?m[0].length:0;if(o){const e=Sn(d,f,g),t=e.maxRow-e.minRow+1,n=e.maxColumn-e.minColumn+1;C=e.minRow,S=e.minColumn,y=Math.min(y,t),b=Math.min(b,n)}let w=!1;const x=Math.min(p,C+y)-1,v=Math.min(_,S+b)-1,T=new Set;for(let e=C;e<=x;e++)for(let t=S;t<=v;t++){const n=d[e][t];T.has(n.cell.getKey())||1===n.cell.__rowSpan&&1===n.cell.__colSpan||(gn(n.cell),T.add(n.cell.getKey()),w=!0)}let[R]=pn(c.getWritable(),null,null);const F=y-p+C;for(let e=0;e<F;e++)Qt(R[p-1][0].cell);const A=b-_+S;for(let e=0;e<A;e++)nn(R[0][_-1].cell,!0,!1);[R]=pn(c.getWritable(),null,null);for(let e=C;e<C+y;e++)for(let t=S;t<S+b;t++){const n=e-C,o=t-S,l=m[n][o];if(l.startRow!==n||l.startColumn!==o)continue;const r=l.cell;if(1!==r.__rowSpan||1!==r.__colSpan){const n=[],o=Math.min(e+r.__rowSpan,C+y)-1,l=Math.min(t+r.__colSpan,S+b)-1;for(let r=e;r<=o;r++)for(let e=t;e<=l;e++){const t=R[r][e];n.push(t.cell)}hn(n),w=!0}const{cell:i}=R[e][t],s=r.getBackgroundColor();null!=s&&i.setBackgroundColor(s);const c=r.getVerticalAlign();void 0!==c&&i.setVerticalAlign(c);const u=i.getChildren();r.getChildren().forEach(e=>{a(e)?(h().append(e),i.append(e)):i.append(e)}),u.forEach(e=>e.remove())}if(o&&w){const[e]=pn(c.getWritable(),null,null);e[f.startRow][f.startColumn].cell.selectEnd()}return!0}function Nn(e,t,n){const[o]=pn(e,null,null);t>=0&&t<o.length||zt(396,String(t));const l=o[t],r=n?Tt.ROW:Tt.NO_STATUS,i=new Set;for(let e=0;e<l.length;e++){const t=l[e];null!=t&&(i.has(t.cell)||(i.add(t.cell),t.cell.setHeaderStyles(r,Tt.ROW)))}}function Tn(e,t,n){const[o]=pn(e,null,null);o.length>0&&t>=0&&t<o[0].length||zt(397,String(t));const l=n?Tt.COLUMN:Tt.NO_STATUS,r=new Set;for(let e=0;e<o.length;e++){const n=o[e][t];null!=n&&(r.has(n.cell)||(r.add(n.cell),n.cell.setHeaderStyles(l,Tt.COLUMN)))}}function Rn(e){const[[t,n,o,l],[r,i,s,c]]=[\"anchor\",\"focus\"].map(t=>{const n=e[t].getNode(),o=N(n,kt);kt(o)||zt(238,t,n.getKey(),n.getType());const l=o.getParent();Ht(l)||zt(239,t);const r=l.getParent();return Wo(r)||zt(240,t),[n,o,l,r]});return l.is(c)||zt(241),{anchorCell:n,anchorNode:t,anchorRow:o,anchorTable:l,focusCell:i,focusNode:r,focusRow:s,focusTable:c}}class Fn{tableKey;anchor;focus;_cachedNodes;dirty;constructor(e,t,n){this.anchor=t,this.focus=n,t._selection=this,n._selection=this,this._cachedNodes=null,this.dirty=!1,this.tableKey=e}getStartEndPoints(){return[this.anchor,this.focus]}isValid(){if(\"root\"===this.tableKey||\"root\"===this.anchor.key||\"element\"!==this.anchor.type||\"root\"===this.focus.key||\"element\"!==this.focus.type)return!1;const e=A(this.tableKey),t=A(this.anchor.key),n=A(this.focus.key);return null!==e&&null!==t&&null!==n}isBackward(){return this.focus.isBefore(this.anchor)}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){return An(e)&&this.tableKey===e.tableKey&&this.anchor.is(e.anchor)&&this.focus.is(e.focus)}set(e,t,n){this.dirty=this.dirty||e!==this.tableKey||t!==this.anchor.key||n!==this.focus.key,this.tableKey=e,this.anchor.key=t,this.focus.key=n,this._cachedNodes=null}clone(){return new Fn(this.tableKey,F(this.anchor.key,this.anchor.offset,this.anchor.type),F(this.focus.key,this.focus.offset,this.focus.type))}isCollapsed(){return!1}extract(){return this.getNodes()}insertRawText(e){if(\"\"===e)return;const t=(e.endsWith(\"\\n\")?e.slice(0,-1):e).split(\"\\n\").map(e=>e.split(\"\\t\")),n=Mo();for(const e of t){const t=Lt();for(const n of e){const e=Kt(Tt.NO_STATUS),o=h();n&&o.append(w(n)),e.append(o),t.append(e)}n.append(t)}const{anchorCell:o}=Rn(this);vn(n,o.select(0,o.getChildrenSize()))}insertText(){}hasFormat(e){let t=0;this.getNodes().filter(kt).forEach(e=>{const n=e.getFirstChild();T(n)&&(t|=n.getTextFormat())});const n=E[e];return 0!==(t&n)}insertNodes(e){const t=this.focus.getNode();O(t)||zt(151),K(t.select(0,t.getChildrenSize())).insertNodes(e)}getShape(){const{anchorCell:e,focusCell:t}=Rn(this),n=xn(e);null===n&&zt(153);const o=xn(t);null===o&&zt(155);const l=Math.min(n.columnIndex,o.columnIndex),r=Math.max(n.columnIndex+n.colSpan-1,o.columnIndex+o.colSpan-1),i=Math.min(n.rowIndex,o.rowIndex),s=Math.max(n.rowIndex+n.rowSpan-1,o.rowIndex+o.rowSpan-1);return{fromX:Math.min(l,r),fromY:Math.min(i,s),toX:Math.max(l,r),toY:Math.max(i,s)}}getNodes(){if(!this.isValid())return[];const e=this._cachedNodes;if(null!==e)return e;const{anchorTable:t,anchorCell:n,focusCell:o}=Rn(this),l=o.getParents()[1];if(l!==t){if(t.isParentOf(o)){const e=l.getParent();null==e&&zt(159),this.set(this.tableKey,o.getKey(),e.getKey())}else{const e=t.getParent();null==e&&zt(158),this.set(this.tableKey,e.getKey(),o.getKey())}return this.getNodes()}const[r,i,s]=mn(t,n,o),{minColumn:c,maxColumn:a,minRow:u,maxRow:h}=Sn(r,i,s),d=new Map([[t.getKey(),t]]);let f=null;for(let e=u;e<=h;e++)for(let t=c;t<=a;t++){const{cell:n}=r[e][t],o=n.getParent();Ht(o)||zt(160),o!==f&&(d.set(o.getKey(),o),f=o),d.has(n.getKey())||kn(n,e=>{d.set(e.getKey(),e)})}const g=Array.from(d.values());return k()||(this._cachedNodes=g),g}getTextContent(){const e=this.getNodes().filter(e=>kt(e));let t=\"\";for(let n=0;n<e.length;n++){const o=e[n],l=o.__parent,r=(e[n+1]||{}).__parent;t+=o.getTextContent()+(r!==l?\"\\n\":\"\\t\")}return t}}function An(e){return e instanceof Fn}function On(){const e=F(\"root\",0,\"element\"),t=F(\"root\",0,\"element\");return new Fn(\"root\",e,t)}function Kn(e,t,n){e.getKey(),t.getKey(),n.getKey();const o=x(),l=An(o)?o.clone():new Fn(\"root\",F(\"root\",0,\"element\"),F(\"root\",0,\"element\"));return l.set(e.getKey(),t.getKey(),n.getKey()),l}function kn(e,t){const n=[[e]];for(let e=n.at(-1);void 0!==e&&n.length>0;e=n.at(-1)){const o=e.pop();void 0===o?n.pop():!1!==t(o)&&O(o)&&n.push(o.getChildren())}}function En(e,t=z()){const n=A(e);Wo(n)||zt(231,e);const o=Pn(n,t.getElementByKey(e));return null===o&&zt(232,e),{tableElement:o,tableNode:n}}class zn{observers;nextFocus;shouldCheckSelectionForTable;touchTapCellKey;constructor(){this.observers=new Map,this.nextFocus=null,this.shouldCheckSelectionForTable=null,this.touchTapCellKey=null}setNextFocus(e){this.nextFocus=e}getAndClearNextFocus(){const{nextFocus:e}=this;return null!==e&&(this.nextFocus=null),e}setShouldCheckSelectionForTable(e){this.shouldCheckSelectionForTable=e}getAndClearShouldCheckSelectionForTable(){const{shouldCheckSelectionForTable:e}=this;return e?(this.shouldCheckSelectionForTable=null,e):null}removeObserver(e){const t=this.observers.get(e);return void 0!==t&&(t[0].removeListeners(),this.observers.delete(e),!0)}removeAllObservers(){for(const e of Array.from(this.observers.keys()))this.removeObserver(e)}$getTableNodesAndObservers(){const e=[];for(const[t,[n]]of Array.from(this.observers.entries())){const o=A(t);Wo(o)?e.push([o,n]):this.removeObserver(t)}return e}}class Mn{focusX;focusY;listenersToRemove;table;isHighlightingCells;anchorX;anchorY;tableNodeKey;anchorCell;focusCell;anchorCellNodeKey;focusCellNodeKey;editor;tableSelection;hasHijackedSelectionStyles;isSelecting;isPointerDrag;pointerStartCell;pointerType;abortController;listenerOptions;constructor(e,t){this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.listenersToRemove=new Set,this.tableNodeKey=t,this.editor=e,this.table={columns:0,domRows:[],rows:0},this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.isSelecting=!1,this.isPointerDrag=!1,this.pointerStartCell=null,this.pointerType=null,this.abortController=new AbortController,this.listenerOptions={signal:this.abortController.signal},this.trackTable()}getTable(){return this.table}removeListeners(){this.abortController.abort(\"removeListeners\"),Array.from(this.listenersToRemove).forEach(e=>e()),this.listenersToRemove.clear()}$lookup(){return En(this.tableNodeKey,this.editor)}trackTable(){const e=new MutationObserver(e=>{this.editor.read(\"latest\",()=>{let t=!1;for(let n=0;n<e.length;n++){const o=e[n].target.nodeName;if(\"TABLE\"===o||\"TBODY\"===o||\"THEAD\"===o||\"TR\"===o){t=!0;break}}if(!t)return;const{tableNode:n,tableElement:o}=this.$lookup();this.table=Zn(n,o)})});this.listenersToRemove.add(()=>e.disconnect()),this.editor.read(\"latest\",()=>{const{tableNode:t,tableElement:n}=this.$lookup();this.table=Zn(t,n),e.observe(n,{attributes:!0,childList:!0,subtree:!0})})}$clearHighlight(e=!0){const t=this.editor;this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.$enableHighlightStyle();const{tableNode:n,tableElement:o}=this.$lookup();eo(t,Zn(n,o),null),e&&null!==x()&&(M(null),t.dispatchCommand(W))}$enableHighlightStyle(){const e=this.editor,{tableElement:t}=this.$lookup();$(t,e._config.theme.tableSelection),t.classList.remove(\"disable-selection\"),this.hasHijackedSelectionStyles=!1}$disableHighlightStyle(){const{tableElement:e}=this.$lookup();r(e,this.editor._config.theme.tableSelection),this.hasHijackedSelectionStyles=!0}$updateTableTableSelection(e){if(null!==e){e.tableKey!==this.tableNodeKey&&zt(233,e.tableKey,this.tableNodeKey);const t=this.editor;this.tableSelection=e,this.isHighlightingCells=!0,this.$disableHighlightStyle(),this.updateDOMSelection(),eo(t,this.table,this.tableSelection)}else this.$clearHighlight()}updateDOMSelection(){if(null!==this.anchorCell&&null!==this.focusCell){const e=L(this.editor._window);e&&e.rangeCount>0&&e.removeAllRanges()}}$setFocusCellForSelection(e,t=!1){const n=this.editor,{tableNode:o}=this.$lookup(),l=e.x,r=e.y;if(this.focusCell=e,this.isHighlightingCells||(t||this.anchorX!==l||this.anchorY!==r||null!=this.tableSelection&&null!=this.anchorCellNodeKey)&&(this.isHighlightingCells=!0,this.$disableHighlightStyle()),-1!==this.focusX&&-1!==this.focusY&&l===this.focusX&&r===this.focusY)return!1;if(this.focusX=l,this.focusY=r,this.isHighlightingCells){const i=So(o,e.elem);if(null!=this.tableSelection&&null!=this.anchorCellNodeKey){let e=i;if(null===e&&t&&(e=o.getCellNodeFromCords(l,r,this.table)),null!==e){const t=this.$getAnchorTableCellOrThrow();return this.focusCellNodeKey=e.getKey(),this.tableSelection=Kn(o,t,e),M(this.tableSelection),n.dispatchCommand(W),eo(n,this.table,this.tableSelection),!0}}}return!1}$getAnchorTableCell(){const e=this.anchorCellNodeKey?A(this.anchorCellNodeKey):null;return kt(e)?e:null}$getAnchorTableCellOrThrow(){const e=this.$getAnchorTableCell();return null===e&&zt(234),e}$getFocusTableCell(){const e=this.focusCellNodeKey?A(this.focusCellNodeKey):null;return kt(e)?e:null}$getFocusTableCellOrThrow(){const e=this.$getFocusTableCell();return null===e&&zt(235),e}$setAnchorCellForSelection(e){this.isHighlightingCells=!1,this.anchorCell=e,this.anchorX=e.x,this.anchorY=e.y,this.focusX=-1,this.focusY=-1,this.focusCell=null,this.focusCellNodeKey=null;const{tableNode:t}=this.$lookup(),n=So(t,e.elem);if(null!==n){const e=n.getKey();null!=this.tableSelection?(this.tableSelection=this.tableSelection.clone(),this.tableSelection.set(t.getKey(),e,e)):this.tableSelection=Kn(t,n,n),this.anchorCellNodeKey=e}}$formatCells(e){const t=x();An(t)||zt(236);const n=H(),o=n.anchor,l=n.focus,r=t.getNodes().filter(kt);r.length>0||zt(237);const i=r[0].getFirstChild(),s=T(i)?i.getFormatFlags(e,null):null;r.forEach(t=>{o.set(t.getKey(),0,\"element\"),l.set(t.getKey(),t.getChildrenSize(),\"element\"),n.formatText(e,s)}),M(t),this.editor.dispatchCommand(W)}$clearText(){const{editor:e}=this,t=A(this.tableNodeKey);if(!Wo(t))throw new Error(\"Expected TableNode.\");const n=x();An(n)||zt(253);const o=n.getNodes().filter(kt),l=t.getFirstChild(),r=t.getLastChild();if(o.length>0&&null!==l&&null!==r&&Ht(l)&&Ht(r)&&o[0]===l.getFirstChild()&&o[o.length-1]===r.getLastChild()){t.selectPrevious();const n=t.getParent();return t.remove(),void(D(n)&&n.isEmpty()&&e.dispatchCommand(P))}o.forEach(e=>{if(O(e)){const t=e.getFirstChild(),n=T(t)?R(t):h(),o=w();n.append(o),e.append(n),e.getChildren().forEach(e=>{e!==n&&e.remove()})}}),eo(e,this.table,null),M(null),e.dispatchCommand(W)}}const Wn=\"__lexicalTableSelection\";function $n(e){const t=ke(e);return Wo(t)||zt(386,e),t}const Ln=40;function Hn(e,t,n,o=1e3/60){const l=e=>Math.max(1,Math.round(Math.max(1,Math.ceil(Math.min(Ln,e)/Ln*18))*o*60/1e3));return e<=t+Ln?-l(t+Ln-e):e>=n-Ln?l(e-(n-Ln)):0}function Dn(e){return i(e)&&\"TABLE\"===e.nodeName}function Pn(e,t){if(!t)return t;const n=Dn(t)?t:t.querySelector(\"table\");return Dn(n)||zt(341,e.constructor.name,e.getType(),e.getKey(),t.nodeName),n}function Bn(e){return e._window}function In(e,t){for(let n=t,o=null;null!==n;n=n.getParent()){if(e.is(n))return o;kt(n)&&(o=n)}return null}const Un=[[I,\"down\"],[U,\"up\"],[X,\"backward\"],[Y,\"forward\"]],Xn=[j,J,G],Yn=[Q,Z];function qn(e,t){return e.registerRootListener(n=>{if(null===n)return;const o=e._window;if(null===o)return;const l=()=>{t.touchTapCellKey=null};return me(B(o,\"pointerdown\",o=>{t.touchTapCellKey=null;const l=ne(o);if(0!==o.button||!oe(l)||!n.contains(l))return;const r=function(e){const t=Gn(e);if(null===t)return null;let n=t.elem;for(;null!=n;){if(\"TABLE\"===n.nodeName&&Wn in n&&n[Wn])return{cellElement:t,tableElement:n,tableObserver:n[Wn]};n=n.parentNode}return null}(l),i=null!==r&&r.tableObserver.editor===e?r:null;e.update(()=>{if(An(x())){for(const[e]of t.observers.values())e.$clearHighlight(!1);M(null),e.dispatchCommand(W)}if(!i)return;const{tableObserver:n,tableElement:l,cellElement:r}=i;!function(e,t,n,o,l,r){const i=e._window;if(!i)return;if(l.pointerType=t.pointerType,\"touch\"===t.pointerType&&!t.shiftKey&&!l.isSelecting){const e=he(n.elem);r.touchTapCellKey=e?e.getKey():null}const s=$n(l.tableNodeKey),c=_e(),a=v(c)||An(c)?ho(c.anchor.getNode()):null,u=null!==a&&a.isParentOf(s);if(Ke&&t.shiftKey&&(v(c)||An(c))&&(so(c,s)||u)){const e=c.anchor.getNode(),o=In(s,c.anchor.getNode());if(o){const e=Co(l,o);e.elem!==n.elem?(l.$setAnchorCellForSelection(e),l.$setFocusCellForSelection(n),mo(t)):\"touch\"!==t.pointerType&&l.$setAnchorCellForSelection(n)}else(s.isBefore(e)?s.selectStart():s.selectEnd()).anchor.set(c.anchor.key,c.anchor.offset,c.anchor.type),mo(t)}else\"touch\"!==t.pointerType&&l.$setAnchorCellForSelection(n);(n=>{if(l.isSelecting)return;l.isSelecting=!0,l.isPointerDrag=!1,l.pointerStartCell=n;const s=\"touch\"===t.pointerType,c=t.pointerId,a=t.clientX,u=t.clientY;let h=!s;s||null!==l.anchorCell||e.update(()=>{l.$setAnchorCellForSelection(n)});let d,f=t.clientX,g=t.clientY,m=null,p=null;const _=e=>e.pointerId===c,C=(e,t)=>!(Math.abs(e-a)<=10&&Math.abs(t-u)<=10),S=()=>{l.isSelecting=!1,l.isPointerDrag=!1,l.pointerStartCell=null,null!==m&&(i.cancelAnimationFrame(m),m=null),null!==p&&(p(),p=null)},y=(e,t)=>{const n=o.getRootNode();if(!Ee(n)&&!ze(n))return null;for(const l of n.elementsFromPoint(e,t)){const e=Qn(o,l);if(e)return e}return null},b=(t,o)=>{if(h||l.isPointerDrag&&t.elem!==n.elem){if(null===l.anchorCell||!h){const o=h?t:n;e.update(()=>{l.$setAnchorCellForSelection(o)})}h=!0,null!==l.focusCell&&t.elem===l.focusCell.elem||(r.setNextFocus({focusCell:t,override:o,tableKey:l.tableNodeKey}),e.dispatchCommand(W))}},w=e=>{for(let t=o.parentElement;t;t=t.parentElement)if(\"x\"===e?t.scrollWidth>t.clientWidth:t.scrollHeight>t.clientHeight){const n=i.getComputedStyle(t),o=\"x\"===e?n.overflowX:n.overflowY;if(\"auto\"===o||\"scroll\"===o)return t}return null},x=(e,t,n,o)=>{let l,r;if(null===e)l=0,r=\"x\"===n?i.innerWidth:i.innerHeight;else{const t=e.getBoundingClientRect();l=\"x\"===n?t.left:t.top,r=\"x\"===n?t.right:t.bottom}const s=Hn(t,l,r,o);if(0===s)return!1;if(null===e){const e=\"x\"===n?i.scrollX:i.scrollY;return i.scrollBy(\"x\"===n?s:0,\"x\"===n?0:s),(\"x\"===n?i.scrollX:i.scrollY)!==e}if(\"x\"===n){const t=e.scrollLeft;return e.scrollLeft+=s,e.scrollLeft!==t}const c=e.scrollTop;return e.scrollTop+=s,e.scrollTop!==c},v=e=>{if(m=null,!l.isSelecting)return;const t=e>d?Math.min(e-d,100):1e3/60;d=e;const n=w(\"x\"),o=w(\"y\"),r=null!==n&&x(n,f,\"x\",t),s=x(o,g,\"y\",t);if(r||s){const[e,t]=((e,t)=>{let n=f,o=g;if(null===e)n=Math.min(Math.max(n,1),i.innerWidth-1);else{const t=e.getBoundingClientRect();n=Math.min(Math.max(n,t.left+1),t.right-1)}if(null===t)o=Math.min(Math.max(o,1),i.innerHeight-1);else{const e=t.getBoundingClientRect();o=Math.min(Math.max(o,e.top+1),e.bottom-1)}return[n,o]})(n,o),l=y(e,t);l&&b(l,!1),m=i.requestAnimationFrame(v)}},N=()=>{null!==m||s&&!l.isPointerDrag||!(()=>{const e=w(\"x\");if(null!==e){const t=e.getBoundingClientRect();if(0!==Hn(f,t.left,t.right))return!0}const t=w(\"y\"),n=null===t?0:t.getBoundingClientRect().top,o=null===t?i.innerHeight:t.getBoundingClientRect().bottom;return 0!==Hn(g,n,o)})()||(d=Infinity,m=i.requestAnimationFrame(v))},T=e=>{_(e)&&(r.touchTapCellKey=null,S())};p=pe(i,{lostpointercapture:T,pointercancel:T,pointermove:e=>{if(!_(e))return;if(!(e=>!(1&~e.buttons))(e)&&l.isSelecting)return r.touchTapCellKey=null,void S();const t=ne(e);if(!oe(t))return;f=e.clientX,g=e.clientY,!l.isPointerDrag&&C(f,g)&&(l.isPointerDrag=!0,r.touchTapCellKey=null);let n=null;const i=!(Ke||o.contains(t));n=i?Qn(o,t):y(e.clientX,e.clientY),n&&b(n,i),N()},pointerup:e=>{_(e)&&(C(e.clientX,e.clientY)&&(r.touchTapCellKey=null),S())}},l.listenerOptions)})(n)}(e,o,r,l,n,t)})}),pe(o,{blur:l,keydown:l},{capture:!0}),l)})}function Vn(e,t,n,o,l){const r=n.getRootElement(),i=Bn(n);null!==r&&null!==i||zt(246);const s=new Mn(n,e.getKey()),c=Pn(e,t);!function(e,t){null!==Jn(e)&&zt(205),e[Wn]=t}(c,s),s.listenersToRemove.add(()=>function(e,t){Jn(e)===t&&delete e[Wn]}(c,s)),s.listenersToRemove.add(B(c,\"mousedown\",e=>{const t=ne(e);e.detail>=3&&oe(t)&&null!==Gn(t)&&e.preventDefault()},s.listenerOptions));for(const[t,o]of Un)s.listenersToRemove.add(n.registerCommand(t,t=>go(n,t,o,e,s,l),q));s.listenersToRemove.add(n.registerCommand(V,t=>{const n=x();if(An(n)){const o=In(e,n.focus.getNode());if(null!==o)return mo(t),o.selectEnd(),!0}return!1},q));const a=()=>{const t=x();return!!so(t,e)&&!!An(t)&&(s.$clearText(),!0)};for(const e of Xn)s.listenersToRemove.add(n.registerCommand(e,a,q));const u=t=>{const n=x();if(!An(n)&&!v(n))return!1;const o=e.isParentOf(n.anchor.getNode());if(o!==e.isParentOf(n.focus.getNode())){const t=o?\"anchor\":\"focus\",l=o?\"focus\":\"anchor\",{key:r,offset:i,type:s}=n[l];return e[n[t].isBefore(n[l])?\"selectPrevious\":\"selectNext\"]()[l].set(r,i,s),!1}return!!so(n,e)&&!!An(n)&&(t&&(t.preventDefault(),t.stopPropagation()),s.$clearText(),!0)};for(const e of Yn)s.listenersToRemove.add(n.registerCommand(e,u,q));s.listenersToRemove.add(n.registerCommand(ee,e=>{const t=x();if(t){if(!An(t)&&!v(t))return!1;gt(n,at(e,ClipboardEvent)?e:null,mt(t));const o=u(e);return v(t)?(t.removeText(),!0):o}return!1},q));const h=r.ownerDocument;return s.listenersToRemove.add(B(h,\"paste\",t=>{t.defaultPrevented||n.read(\"latest\",()=>{const t=x();return r.contains(h.activeElement)&&An(t)&&so(t,e)})&&(t.preventDefault(),n.dispatchCommand(te,t))})),s.listenersToRemove.add(B(h,\"copy\",t=>{if(t.defaultPrevented)return;const o=ne(t);o===r||oe(o)&&r.contains(o)||n.read(\"latest\",()=>{const t=x();return r.contains(le(r))&&An(t)&&so(t,e)})&&(t.preventDefault(),n.dispatchCommand(re,t))})),s.listenersToRemove.add(n.registerCommand(ie,t=>{const n=x();return!!so(n,e)&&!!An(n)&&(s.$formatCells(t),!0)},q)),s.listenersToRemove.add(n.registerCommand(se,t=>{const n=x();if(!An(n)||!so(n,e))return!1;const o=n.anchor.getNode(),l=n.focus.getNode();if(!kt(o)||!kt(l))return!1;const[r,i,s]=mn(e,o,l),{minColumn:c,maxColumn:a,minRow:u,maxRow:h}=Sn(r,i,s);if(0===u&&0===c&&h===r.length-1&&a===r[0].length-1)return e.setFormat(t),!0;const d=new Set;for(let e=u;e<=h;e++)for(let n=c;n<=a;n++){const o=r[e][n].cell;if(d.has(o))continue;d.add(o),o.setFormat(t);const l=o.getChildren();for(let e=0;e<l.length;e++){const n=l[e];O(n)&&!n.isInline()&&n.setFormat(t)}}return!0},q)),s.listenersToRemove.add(n.registerCommand(ce,t=>{const o=x();if(!so(o,e))return!1;if(An(o))return s.$clearHighlight(),!1;if(v(o)){const l=N(o.anchor.getNode(),e=>kt(e));if(!kt(l))return!1;if(\"string\"==typeof t){const l=_o(n,o,e);if(l)return po(l,e,[w(t)]),!0}}return!1},q)),o&&s.listenersToRemove.add(n.registerCommand(ae,t=>{const n=x();if(!v(n)||!n.isCollapsed()||!so(n,e))return!1;const o=ho(n.anchor.getNode());return!(null===o||!e.is(fo(o))||(mo(t),function(e,t){const n=\"next\"===t?\"getNextSibling\":\"getPreviousSibling\",o=\"next\"===t?\"getFirstChild\":\"getLastChild\",l=e[n]();if(O(l))return l.selectEnd();const r=N(e,Ht);null===r&&zt(247);for(let e=r[n]();Ht(e);e=e[n]()){const t=e[o]();if(O(t))return t.selectEnd()}const i=N(r,Wo);null===i&&zt(248),\"next\"===t?i.selectNext():i.selectPrevious()}(o,t.shiftKey?\"previous\":\"next\"),0))},q)),s.listenersToRemove.add(n.registerCommand(ue,t=>e.isSelected(),q)),s.listenersToRemove.add(n.registerCommand(P,()=>{const t=x();if(!v(t)||!t.isCollapsed()||!so(t,e))return!1;const o=_o(n,t,e);return!!o&&(po(o,e),!0)},q)),s}function jn(e,t,n){const o=x(),l=t.isSelected();if(!(An(o)&&o.tableKey===t.getKey()||n.isHighlightingCells||n.hasHijackedSelectionStyles||l))return;const{tableElement:r}=n.$lookup();if(n.table=Zn(t,r),An(o)&&o.tableKey===t.getKey()){const e=A(o.anchor.key),t=A(o.focus.key);if(kt(e)&&kt(t)){const o=Co(n,e),l=Co(n,t);n.anchorCell=o,n.anchorCellNodeKey=e.getKey(),n.anchorX=o.x,n.anchorY=o.y,n.focusCell=l,n.focusCellNodeKey=t.getKey(),n.focusX=l.x,n.focusY=l.y}n.$updateTableTableSelection(o)}else n.isHighlightingCells&&n.$clearHighlight(!1);n.hasHijackedSelectionStyles&&!l?function(e,t){t.$enableHighlightStyle(),to(t.table,t=>{const n=t.elem;t.highlighted=!1,uo(e,t),n.getAttribute(\"style\")||n.removeAttribute(\"style\")})}(e,n):!n.hasHijackedSelectionStyles&&l&&function(e,t){t.$disableHighlightStyle(),to(t.table,t=>{t.highlighted=!0,ao(e,t)})}(e,n)}function Jn(e){return e[Wn]||null}function Gn(e){let t=e;for(;null!=t;){const e=t.nodeName;if(\"TD\"===e||\"TH\"===e){const e=t._cell;return void 0===e?null:e}t=t.parentNode}return null}function Qn(e,t){if(!e.contains(t))return null;let n=null;for(let o=t;null!=o;o=o.parentNode){if(o===e)return n;const t=o.nodeName;\"TD\"!==t&&\"TH\"!==t||(n=o._cell||null)}return null}function Zn(e,t){const n=[],o={columns:0,domRows:n,rows:0};let l=Pn(e,t).querySelector(\"tr\"),r=0,i=0;for(n.length=0;null!=l;){const e=l.nodeName;if(\"TD\"===e||\"TH\"===e){const e={elem:l,hasBackgroundColor:\"\"!==l.style.backgroundColor,highlighted:!1,x:r,y:i};l._cell=e;let t=n[i];void 0===t&&(t=n[i]=[]),t[r]=e}else{const e=l.firstChild;if(null!=e){l=e;continue}}const t=l.nextSibling;if(null!=t){r++,l=t;continue}const o=l.parentNode;if(null!=o){const e=o.nextSibling;if(null==e)break;i++,r=0,l=e}}return o.columns=r+1,o.rows=i+1,o}function eo(e,t,n){const o=new Set(n?n.getNodes():[]);to(t,(t,n)=>{const l=t.elem;o.has(n)?(t.highlighted=!0,ao(e,t)):(t.highlighted=!1,uo(e,t),l.getAttribute(\"style\")||l.removeAttribute(\"style\"))})}function to(e,t){const{domRows:n}=e;for(let e=0;e<n.length;e++){const o=n[e];if(o)for(let n=0;n<o.length;n++){const l=o[n];if(!l)continue;const r=he(l.elem);null!==r&&t(l,r,{x:n,y:e})}}}const no=(e,t,n,o,l)=>{const r=\"forward\"===l;switch(l){case\"backward\":case\"forward\":return n!==(r?e.table.columns-1:0)?co(t.getCellNodeFromCordsOrThrow(n+(r?1:-1),o,e.table),r):o!==(r?e.table.rows-1:0)?co(t.getCellNodeFromCordsOrThrow(r?0:e.table.columns-1,o+(r?1:-1),e.table),r):r?t.selectNext():t.selectPrevious(),!0;case\"up\":return 0!==o?co(t.getCellNodeFromCordsOrThrow(n,o-1,e.table),!1):t.selectPrevious(),!0;case\"down\":return o!==e.table.rows-1?co(t.getCellNodeFromCordsOrThrow(n,o+1,e.table),!0):t.selectNext(),!0;default:return!1}};function oo(e,t){let n,o;if(t.startColumn===e.minColumn)n=\"minColumn\";else{if(t.startColumn+t.cell.__colSpan-1!==e.maxColumn)return null;n=\"maxColumn\"}if(t.startRow===e.minRow)o=\"minRow\";else{if(t.startRow+t.cell.__rowSpan-1!==e.maxRow)return null;o=\"maxRow\"}return[n,o]}function lo(e,t,n){const o=oo(e,t);if(o)return o;const l=oo(e,n);return l?ro(l):[\"minColumn\",\"minRow\"]}function ro([e,t]){return[\"minColumn\"===e?\"maxColumn\":\"minColumn\",\"minRow\"===t?\"maxRow\":\"minRow\"]}function io(e,t,[n,o]){const l=t[o],r=e[l];void 0===r&&zt(250,o,String(l));const i=t[n],s=r[i];return void 0===s&&zt(250,n,String(i)),s}function so(e,t){if(v(e)||An(e)){const n=t.isParentOf(e.anchor.getNode()),o=t.isParentOf(e.focus.getNode());return n&&o}return!1}function co(e,t){t?e.selectStart():e.selectEnd()}function ao(e,t){const n=t.elem,o=e._config.theme;kt(he(n))||zt(131),r(n,o.tableCellSelected)}function uo(e,t){const n=t.elem;kt(he(n))||zt(131);const o=e._config.theme;$(n,o.tableCellSelected)}function ho(e){const t=N(e,kt);return kt(t)?t:null}function fo(e){const t=N(e,Wo);return Wo(t)?t:null}function go(e,t,n,o,l,r){if((\"up\"===n||\"down\"===n)&&function(e){const t=e.getRootElement();return!!t&&(t.hasAttribute(\"aria-controls\")&&\"typeahead-menu\"===t.getAttribute(\"aria-controls\"))}(e))return!1;const i=x();if(!so(i,o)){if(v(i)){if(\"backward\"===n){if(i.focus.offset>0)return!1;const e=function(e){for(let t=e,n=e;null!==n;t=n,n=n.getParent())if(O(n)){if(n!==t&&n.getFirstChild()!==t)return null;if(!n.isInline())return n}return null}(i.focus.getNode());if(!e)return!1;const n=e.getPreviousSibling();return!!Wo(n)&&(mo(t),t.shiftKey?i.focus.set(n.getParentOrThrow().getKey(),n.getIndexWithinParent(),\"element\"):n.selectEnd(),!0)}if(t.shiftKey&&(\"up\"===n||\"down\"===n)){const e=i.focus.getNode();if(!i.isCollapsed()&&(\"up\"===n&&!i.isBackward()||\"down\"===n&&i.isBackward())){let l=N(e,e=>Wo(e));if(kt(l)&&(l=N(l,Wo)),l!==o)return!1;if(!l)return!1;const r=\"down\"===n?l.getNextSibling():l.getPreviousSibling();if(!r)return!1;let s=0;\"up\"===n&&O(r)&&(s=r.getChildrenSize());let c=r;if(\"up\"===n&&O(r)){c=r.getLastChild()||r,s=a(c)?c.getTextContentSize():0}const u=i.clone();return u.focus.set(c.getKey(),s,a(c)?\"text\":\"element\"),M(u),mo(t),!0}if(de(e)){const e=\"up\"===n?i.getNodes()[i.getNodes().length-1]:i.getNodes()[0];if(e&&null!==In(o,e)){const e=o.getFirstDescendant(),t=o.getLastDescendant();if(!e||!t)return!1;const[n]=Cn(e),[r]=Cn(t),i=o.getCordsFromCellNode(n,l.table),s=o.getCordsFromCellNode(r,l.table),c=o.getDOMCellFromCordsOrThrow(i.x,i.y,l.table),a=o.getDOMCellFromCordsOrThrow(s.x,s.y,l.table);return l.$setAnchorCellForSelection(c),l.$setFocusCellForSelection(a,!0),!0}return!1}{let o=N(e,e=>O(e)&&!e.isInline());if(kt(o)&&(o=N(o,Wo)),!o)return!1;const r=\"down\"===n?o.getNextSibling():o.getPreviousSibling();if(Wo(r)&&l.tableNodeKey===r.getKey()){const e=r.getFirstDescendant(),o=r.getLastDescendant();if(!e||!o)return!1;const[l]=Cn(e),[s]=Cn(o),c=i.clone();return c.focus.set((\"up\"===n?l:s).getKey(),\"up\"===n?0:s.getChildrenSize(),\"element\"),mo(t),M(c),!0}}}}return\"down\"===n&&Ao(e)&&function(e,t){if(!v(e))return!1;const n=Ce(e.focus,\"next\"),o=Se(t,\"next\");return null!==ye(n.origin,o.origin)&&be(n,o)<0}(i,o)&&r.setShouldCheckSelectionForTable(o.getKey()),!1}if(v(i)){if(\"backward\"===n||\"forward\"===n)return function(e,t,n,o,l,r,i){const s=Ce(n.focus,l?\"previous\":\"next\");if(we(s))return!1;let c=s;for(const e of xe(s).iterNodeCarets(\"shadowRoot\")){if(!ve(e)||!O(e.origin))return!1;c=e}const a=c.getParentAtCaret();if(!kt(a))return!1;const u=a,h=function(e){for(const t of xe(e).iterNodeCarets(\"root\")){const{origin:n}=t;if(kt(n)){if(Ae(t))return Se(n,e.direction)}else if(!Ht(n))break}return null}(Ne(u,c.direction)),d=N(u,Wo);if(!d||!d.is(r))return!1;const f=e.getElementByKey(u.getKey()),g=Gn(f);if(!f||!g)return!1;const m=Eo(e,d);if(i.table=m,h)if(\"extend\"===o){const t=Gn(e.getElementByKey(h.origin.getKey()));if(!t)return!1;i.$setAnchorCellForSelection(g),i.$setFocusCellForSelection(t,!0)}else{const e=Re(h);Te(n.anchor,e),Te(n.focus,e)}else if(\"extend\"===o)i.$setAnchorCellForSelection(g),i.$setFocusCellForSelection(g,!0);else{const e=function(e){const t=Oe(e);return Ae(t)?Re(t):e}(Ne(d,s.direction));Te(n.anchor,e),Te(n.focus,e)}return mo(t),!0}(e,t,i,t.shiftKey?\"extend\":\"move\",\"backward\"===n,o,l);if(i.isCollapsed()){const{anchor:s,focus:c}=i,a=N(s.getNode(),kt),u=N(c.getNode(),kt);if(!kt(a)||!a.is(u))return!1;const h=fo(a);if(h!==o&&null!=h){const o=Pn(h,e.getElementByKey(h.getKey()));if(null!=o)return l.table=Zn(h,o),go(e,t,n,h,l,r)}const d=e.getElementByKey(a.__key),f=e.getElementByKey(s.key);if(null==f||null==d)return!1;let g;if(\"element\"===s.type)g=f.getBoundingClientRect();else{const t=L(Bn(e));if(null===t||0===t.rangeCount)return!1;const n=fe(t,e.getRootElement());if(null===n)return!1;g=n.getBoundingClientRect()}const m=\"up\"===n?a.getFirstChild():a.getLastChild();if(null==m)return!1;const p=e.getElementByKey(m.__key);if(null==p)return!1;const _=p.getBoundingClientRect();if(\"up\"===n?_.top>g.top-g.height:g.bottom+g.height>_.bottom){mo(t);const e=o.getCordsFromCellNode(a,l.table);if(!t.shiftKey)return no(l,o,e.x,e.y,n);{const t=o.getDOMCellFromCordsOrThrow(e.x,e.y,l.table);l.$setAnchorCellForSelection(t),l.$setFocusCellForSelection(t,!0)}return!0}}}else if(An(i)){const{anchor:r,focus:s,tableKey:c}=i;if(c!==o.getKey())return!1;const a=N(r.getNode(),kt),u=N(s.getNode(),kt),[h]=i.getNodes();Wo(h)||zt(251);const d=Pn(h,e.getElementByKey(h.getKey()));if(!kt(a)||!kt(u)||!Wo(h)||null==d)return!1;l.$updateTableTableSelection(i);const f=Zn(h,d),g=o.getCordsFromCellNode(a,f),m=o.getDOMCellFromCordsOrThrow(g.x,g.y,f);if(l.$setAnchorCellForSelection(m),mo(t),t.shiftKey){const[e,t,r]=mn(o,a,u);return function(e,t,n,o,l){const r=Sn(t,n,o),i=function(e,t){const{minColumn:n,maxColumn:o,minRow:l,maxRow:r}=t;let i=1,s=1,c=1,a=1;const u=e[l],h=e[r];for(let e=n;e<=o;e++)i=Math.max(i,u[e].cell.__rowSpan),a=Math.max(a,h[e].cell.__rowSpan);for(let t=l;t<=r;t++)s=Math.max(s,e[t][n].cell.__colSpan),c=Math.max(c,e[t][o].cell.__colSpan);return{bottomSpan:a,leftSpan:s,rightSpan:c,topSpan:i}}(t,r),{topSpan:s,leftSpan:c,bottomSpan:a,rightSpan:u}=i,h=lo(r,n,o),[d,f]=ro(h);let g=r[d],m=r[f];\"forward\"===l?g+=\"maxColumn\"===d?1:c:\"backward\"===l?g-=\"minColumn\"===d?1:u:\"down\"===l?m+=\"maxRow\"===f?1:s:\"up\"===l&&(m-=\"minRow\"===f?1:a);const p=t[m];if(void 0===p)return!1;const _=p[g];if(void 0===_)return!1;const[C,S]=function(e,t,n){const o=Sn(e,t,n),l=lo(o,t,n);return[io(e,o,l),io(e,o,ro(l))]}(t,n,_),y=Co(e,C.cell),b=Co(e,S.cell);return e.$setAnchorCellForSelection(y),e.$setFocusCellForSelection(b,!0),!0}(l,e,t,r,n)}return u.selectEnd(),!0}return!1}function mo(e){e.preventDefault(),e.stopImmediatePropagation(),e.stopPropagation()}function po(e,t,n){const o=h();\"first\"===e?t.insertBefore(o):t.insertAfter(o),o.append(...n||[]),o.selectEnd()}function _o(e,t,n){const o=n.getParent();if(!o)return;const l=L(Bn(e));if(!l)return;const r=ge(l,e.getRootElement()).anchorNode,i=e.getElementByKey(o.getKey()),s=Pn(n,e.getElementByKey(n.getKey()));if(!r||!i||!s||!i.contains(r)||s.contains(r))return;const c=N(t.anchor.getNode(),e=>kt(e));if(!c)return;const a=N(c,e=>Wo(e));if(!Wo(a)||!a.is(n))return;const[u,h]=mn(n,c,c),d=u[0][0],f=u[u.length-1][u[0].length-1],{startRow:g,startColumn:m}=h,p=g===d.startRow&&m===d.startColumn,_=g===f.startRow&&m===f.startColumn;return p?\"first\":_?\"last\":void 0}function Co(e,t){const{tableNode:n}=e.$lookup(),o=n.getCordsFromCellNode(t,e.table);return n.getDOMCellFromCordsOrThrow(o.x,o.y,e.table)}function So(e,t,n){return In(e,he(t,n))}function yo(e){return i(e)&&\"DIV\"===e.nodeName}const bo=/* @__PURE__ */f()({colWidths:/* @__PURE__ */_(/* @__PURE__ */m(/* @__PURE__ */Le(/* @__PURE__ */p())),{getter:{field:\"__colWidths\"}}),frozenColumnCount:/* @__PURE__ */_(/* @__PURE__ */p(),{getter:\"getSerializedFrozenColumnCount\",setter:{field:\"__frozenColumnCount\",method:\"setFrozenColumns\"}}),frozenRowCount:/* @__PURE__ */_(/* @__PURE__ */p(),{getter:\"getSerializedFrozenRowCount\",setter:{field:\"__frozenRowCount\",method:\"setFrozenRows\"}}),rowStriping:/* @__PURE__ */_(/* @__PURE__ */$e(),{getter:\"getSerializedRowStriping\",setter:{field:\"__rowStriping\"}})});function wo(e,t,n){let o=e.querySelector(\":scope > colgroup\");if(!n)return void(o&&o.remove());o||(o=l().createElement(\"colgroup\"),We(o),e.insertBefore(o,e.firstChild));const r=[];for(let e=0;e<t;e++){const t=l().createElement(\"col\"),o=n[e];o&&(t.style.width=`${o}px`),r.push(t)}o.replaceChildren(...r)}function xo(e,t,n){if(!t.theme.tableAlignment)return;const o=[],l=[];for(const e of[\"center\",\"right\"]){const r=t.theme.tableAlignment[e];r&&(e===n?l:o).push(r)}$(e,...o),r(e,...l)}const vo=new WeakSet;function No(e){const{scrollable:t,scrollbar:n,tableElement:o}=e;if(0===n.classList.length&&0===function(e){const t=e.style.display;e.style.display=\"\";const n=e.offsetHeight-e.clientHeight;return e.style.display=t,n}(n))return vo.add(n),n.style.display=\"none\",t.style.scrollbarWidth=\"auto\",()=>{};let l=t.scrollLeft,r=n.scrollLeft;const i=()=>{t.scrollLeft!==l&&(n.scrollLeft=l=t.scrollLeft,r=n.scrollLeft)},s=()=>{n.scrollLeft!==r&&(t.scrollLeft=r=n.scrollLeft,l=t.scrollLeft)};t.addEventListener(\"scroll\",i,{passive:!0}),n.addEventListener(\"scroll\",s,{passive:!0});let c=null;return\"undefined\"!=typeof ResizeObserver&&(c=new ResizeObserver(()=>{To(t,n)}),c.observe(t),c.observe(o)),To(t,n),()=>{t.removeEventListener(\"scroll\",i),n.removeEventListener(\"scroll\",s),c&&c.disconnect()}}function To(e,t){if(vo.has(t))return;const n=t.firstElementChild;if(!n||!i(n)||!e.isConnected)return;const o=e.ownerDocument.defaultView;if(!o)return void(t.style.display=\"none\");const l=o.getComputedStyle(e).overflowX,r=\"auto\"===l||\"scroll\"===l,s=e.scrollWidth,c=e.clientWidth,a=s+\"px\";n.style.width!==a&&(n.style.width=a);const u=r&&s>c;t.style.display=u?\"\":\"none\"}function Ro(e){if(!e.hasAttribute(\"data-lexical-sticky-scrollbar\"))return null;const t=e.firstElementChild;if(!yo(t))return null;const n=t.querySelector(\":scope > table\");if(!Dn(n))return null;const o=t.nextElementSibling;return yo(o)?{scrollable:t,scrollbar:o,tableElement:n}:null}const Fo=new WeakSet;function Ao(e=z()){return Fo.has(e)}function Oo(e=z()){const t=st(e,\"@lexical/table/Table\");return!!t&&t.output.hasStickyScrollbar.peek()&&t.output.hasHorizontalScroll.peek()}function Ko(e,t){t?Fo.add(e):Fo.delete(e)}class ko extends o{__rowStriping=!1;__frozenColumnCount=0;__frozenRowCount=0;__colWidths=void 0;$config(){return this.config(\"table\",{extends:o,generated:bt,importDOM:{table:()=>({conversion:zo,priority:1})},json:bo})}getSerializedFrozenColumnCount(){return this.getLatest().__frozenColumnCount||void 0}getSerializedFrozenRowCount(){return this.getLatest().__frozenRowCount||void 0}getSerializedRowStriping(){return this.getLatest().__rowStriping||void 0}getColWidths(){return this.getLatest().__colWidths}setColWidths(e){const t=this.getWritable();return t.__colWidths=e,t}extractWithChild(e,t,n){return\"html\"===n}getDOMSlot(e){const t=Dn(e)?e:e.querySelector(\"table\");return Dn(t)||zt(229),super.getDOMSlot(e).withElement(t).withAfter(t.querySelector(\":scope > colgroup\"))}createDOM(e,t){const n=l().createElement(\"table\");if(this.__style&&Me(n.style,this.__style),this.getColWidths()){const e=l().createElement(\"colgroup\");n.appendChild(e),We(e)}if(r(n,e.theme.table),this.updateTableElement(null,n,e),Ao(t)){const o=Oo(t),i=function(e,t,n){const o=l().createElement(\"div\"),i=t.theme.tableScrollableWrapper;return i?r(o,i):o.style.overflowX=\"auto\",n&&(o.style.scrollbarWidth=\"none\"),o.appendChild(e),o}(n,e,o);if(this.updateTableWrapper(null,i,n,e),o){const t=function(e){const t=l(),n=t.createElement(\"div\"),o=e.theme.tableStickyScrollbar;o?r(n,o):(n.style.position=\"sticky\",n.style.bottom=\"0\",n.style.overflowX=\"scroll\",n.style.overflowY=\"hidden\"),n.style.display=\"none\",n.setAttribute(\"aria-hidden\",\"true\"),n.tabIndex=-1;const i=t.createElement(\"div\");return i.style.height=\"1px\",i.style.width=\"0px\",n.appendChild(i),n}(e),n=l().createElement(\"div\");return n.setAttribute(\"data-lexical-sticky-scrollbar\",\"true\"),n.appendChild(i),n.appendChild(t),We(t),n}return i}return n}updateTableWrapper(e,t,n,o){this.__frozenColumnCount!==(e?e.__frozenColumnCount:0)&&function(e,t,n,o){o>0?(r(e,n.theme.tableFrozenColumn),t.setAttribute(\"data-lexical-frozen-column\",\"true\")):($(e,n.theme.tableFrozenColumn),t.removeAttribute(\"data-lexical-frozen-column\"))}(t,n,o,this.__frozenColumnCount),this.__frozenRowCount!==(e?e.__frozenRowCount:0)&&function(e,t,n,o){o>0?(r(e,n.theme.tableFrozenRow),t.setAttribute(\"data-lexical-frozen-row\",\"true\")):($(e,n.theme.tableFrozenRow),t.removeAttribute(\"data-lexical-frozen-row\"))}(t,n,o,this.__frozenRowCount)}updateTableElement(e,t,n){this.__style!==(e?e.__style:\"\")&&Me(t.style,this.__style,e?e.__style:\"\"),this.__rowStriping!==(!!e&&e.__rowStriping)&&function(e,t,n){n?(r(e,t.theme.tableRowStriping),e.setAttribute(\"data-lexical-row-striping\",\"true\")):($(e,t.theme.tableRowStriping),e.removeAttribute(\"data-lexical-row-striping\"))}(t,n,this.__rowStriping);const o=e?e.getColumnCount():0,l=e?e.__colWidths:void 0;this.getColumnCount()===o&&this.getColWidths()===l||wo(t,this.getColumnCount(),this.getColWidths()),xo(t,n,this.getFormatType())}updateDOM(e,t,n){const o=Pn(this,t);if(t===o===Ao())return!0;if(yo(t)){if(t.hasAttribute(\"data-lexical-sticky-scrollbar\")!==Oo())return!0;const l=o.parentElement;yo(l)&&this.updateTableWrapper(e,l,o,n)}return this.updateTableElement(e,o,n),!1}scaleDOMColWidths(e,t){const n=this.getColWidths();n&&wo(Pn(this,e),this.getColumnCount(),n.map(e=>e*t))}exportDOM(e){const t=super.exportDOM(e),{element:n}=t,o=!Dn(n)&&i(n)?n.querySelector(\"table\"):n;if(i(n)&&Dn(o)&&o!==n){n.dir&&(o.dir=n.dir);const{paddingInlineStart:e}=n.style;e&&(o.style.paddingInlineStart=e);const t=n.getAttribute(\"data-lexical-indent\");null!==t&&o.setAttribute(\"data-lexical-indent\",t)}return{after:n=>{if(t.after&&(n=t.after(n)),!Dn(n)&&i(n)&&(n=n.querySelector(\"table\")),!Dn(n))return null;xo(n,e._config,this.getFormatType());const[o]=pn(this,null,null),r=new Map;for(const e of o)for(const t of e){const e=t.cell.getKey();r.has(e)||r.set(e,{colSpan:t.cell.getColSpan(),startColumn:t.startColumn})}const s=new Set;for(const e of n.querySelectorAll(\":scope > tr > [data-temporary-table-cell-lexical-key]\")){const t=e.getAttribute(\"data-temporary-table-cell-lexical-key\");if(t){const n=r.get(t);if(e.removeAttribute(\"data-temporary-table-cell-lexical-key\"),n){r.delete(t);for(let e=0;e<n.colSpan;e++)s.add(e+n.startColumn)}}}const c=n.querySelector(\":scope > colgroup\");if(c){const e=Array.from(n.querySelectorAll(\":scope > colgroup > col\")).filter((e,t)=>s.has(t));c.replaceChildren(...e)}const a=n.querySelectorAll(\":scope > tr\");if(a.length>0){const e=l().createElement(\"tbody\");for(const t of a)e.appendChild(t);n.append(e)}return n},element:o}}canBeEmpty(){return!1}isShadowRoot(){return!0}getCordsFromCellNode(e,t){const{rows:n,domRows:o}=t;for(let t=0;t<n;t++){const n=o[t];if(null!=n)for(let o=0;o<n.length;o++){const l=n[o];if(null==l)continue;const{elem:r}=l,i=So(this,r);if(null!==i&&e.is(i))return{x:o,y:t}}}throw new Error(\"Cell not found in table.\")}getDOMCellFromCords(e,t,n){const{domRows:o}=n,l=o[t];if(null==l)return null;return l[e<l.length?e:l.length-1]??null}getDOMCellFromCordsOrThrow(e,t,n){const o=this.getDOMCellFromCords(e,t,n);if(!o)throw new Error(\"Cell not found at cords.\");return o}getCellNodeFromCords(e,t,n){const o=this.getDOMCellFromCords(e,t,n);if(null==o)return null;const l=he(o.elem);return kt(l)?l:null}getCellNodeFromCordsOrThrow(e,t,n){const o=this.getCellNodeFromCords(e,t,n);if(!o)throw new Error(\"Node at cords not TableCellNode.\");return o}getRowStriping(){return Boolean(this.getLatest().__rowStriping)}setRowStriping(e){const t=this.getWritable();return t.__rowStriping=e,t}setFrozenColumns(e){const t=this.getWritable();return t.__frozenColumnCount=e,t}getFrozenColumns(){return this.getLatest().__frozenColumnCount}setFrozenRows(e){const t=this.getWritable();return t.__frozenRowCount=e,t}getFrozenRows(){return this.getLatest().__frozenRowCount}canSelectBefore(){return!0}canIndent(){return!1}getColumnCount(){const e=this.getFirstChild();if(!Ht(e))return 0;let t=0;return e.getChildren().forEach(e=>{kt(e)&&(t+=e.getColSpan())}),t}}function Eo(e,t){const n=e.getElementByKey(t.getKey());return null===n&&zt(230),Zn(t,n)}function zo(e){const t=Mo();e.hasAttribute(\"data-lexical-row-striping\")&&t.setRowStriping(!0),e.hasAttribute(\"data-lexical-frozen-column\")&&t.setFrozenColumns(1),e.hasAttribute(\"data-lexical-frozen-row\")&&t.setFrozenRows(1);const n=e.querySelector(\":scope > colgroup\");if(n){let e=[];for(const t of n.querySelectorAll(\":scope > col\")){let n=t.style.width||\"\";if(!pt.test(n)&&(n=t.getAttribute(\"width\")||\"\",!/^\\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&t.setColWidths(e)}return s(t,e),{after:e=>ct(e,Ht),node:t}}function Mo(){return d(new ko)}function Wo(e){return e instanceof ko}function $o(e){Ht(e.getParent())?e.isEmpty()&&e.append(h()):e.remove()}function Lo(e){Wo(e.getParent())?ft(e,kt):e.remove()}function Ho(e){ft(e,Ht),_n(e);const t=e.getColWidths(),n=e.getColumnCount();if(t&&t.length!==n){let o;if(n<t.length)o=t.slice(0,n);else if(t.length>0){const e=t[t.length-1];o=[...t,...Array(n-t.length).fill(e)]}e.setColWidths(o)}}function Do(e){if(e.detail<3||!oe(e.target))return!1;const t=he(e.target);if(null===t)return!1;const n=N(t,e=>O(e)&&!e.isInline());return null!==n&&(!!kt(n.getParent())&&(K(n.select(0)),!0))}function Po(){const e=x();if(!v(e))return!1;const t=fo(e.anchor.getNode());if(null===t)return!1;const n=Ue();if(!n.is(t.getParent())||1!==n.getChildrenSize())return!1;const[o]=pn(t,null,null);if(0===o.length||0===o[0].length)return!1;const l=o[0][0];if(!l||!l.cell)return!1;const r=o[o.length-1],i=r[r.length-1];if(!i||!i.cell)return!1;const s=Kn(t,l.cell,i.cell);return M(s),!0}function Bo(e){return e.registerNodeTransform(Ft,e=>{if(e.getColSpan()>1||e.getRowSpan()>1){const[,,t]=Cn(e),[n]=mn(t,e,e),o=n.length,l=n[0].length;let r=t.getFirstChild();Ht(r)||zt(175);const i=[];for(let e=0;e<o;e++){0!==e&&(r=r.getNextSibling(),Ht(r)||zt(175));let t=null;for(let o=0;o<l;o++){const l=n[e][o],s=l.cell;if(l.startRow===e&&l.startColumn===o)t=s,i.push(s);else if(s.getColSpan()>1||s.getRowSpan()>1){kt(s)||zt(176);const e=Kt(s.__headerState);null!==t?t.insertAfter(e):ut(r,e)}}}for(const e of i)e.setColSpan(1),e.setRowSpan(1)}})}function Io(e,t=!0){const n=new zn;let o=!1;const l=(o,l,r)=>{const i=Pn(o,r),s=Vn(o,i,e,t,n);n.observers.set(l,[s,i])};return me(qn(e,n),e.registerCommand(W,()=>null!==e.getRootElement()&&(o=!0,function(e,t){const n=x(),o=_e(),l=e.getAndClearNextFocus();if(null!==l&&Wo(A(l.tableKey))){const{tableKey:t,focusCell:o}=l,r=e.observers.get(t);r||zt(335,t);const[i]=r;if(An(n)&&n.tableKey===i.tableNodeKey)return(o.x!==i.focusX||o.y!==i.focusY)&&(i.$setFocusCellForSelection(o),!0);if(null!==i.anchorCell&&null!==i.anchorCellNodeKey&&o.elem!==i.anchorCell.elem&&null!==i.tableSelection)return i.$setFocusCellForSelection(o,!0),!0}const r=e.getAndClearShouldCheckSelectionForTable();if(r&&v(o)&&v(n)&&n.isCollapsed()){const e=A(r);if(Wo(e)){const t=n.anchor.getNode(),o=e.getFirstChild(),l=ho(t);if(null!==l&&Ht(o)){const t=o.getFirstChild();if(kt(t)&&e.is(N(l,n=>n.is(e)||n.is(t))))return t.selectStart(),!0}}}return An(n)&&function(e,t){const n=Bn(e),o=_e();if(!t.is(o))return;const l=$n(t.tableKey),r=L(n),i=r&&ge(r,e.getRootElement());if(r&&i&&i.anchorNode&&i.focusNode){const n=he(i.focusNode),o=n&&!l.isParentOf(n),s=he(i.anchorNode),c=s&&l.isParentOf(s);if(o&&c&&r.rangeCount>0){const n=Fe(r,e);n&&(n.anchor.set(l.getKey(),t.isBackward()?l.getChildrenSize():0,\"element\"),r.removeAllRanges(),M(n))}}}(t,n),v(n)&&function(e,t){const n=_e(),{anchor:o,focus:l}=e,r=o.getNode(),i=l.getNode(),s=ho(r),c=ho(i),a=s?fo(s):null,u=c?fo(c):null;if(null!==t.touchTapCellKey&&!e.dirty&&!e.isCollapsed()&&v(n)&&n.isCollapsed()&&(!s||!s.is(c))){const e=A(n.anchor.key),r=e&&e.getParent();if(O(e)&&e.isEmpty()&&kt(r)&&r.getKey()===t.touchTapCellKey&&r.getChildren().every(e=>O(e)&&e.isEmpty())&&(o.is(n.anchor)||l.is(n.anchor)))return void M(n.clone())}const h=e.isBackward(),d=s&&c&&a&&u&&a.is(u),f=u&&(!a||a.isParentOf(u)),g=a&&(!u||u.isParentOf(a));if(f){const t=e.clone(),[n]=mn(u,c,c),o=n[0][0].cell,l=n[n.length-1].at(-1).cell;t.focus.set(h?o.getKey():l.getKey(),h?0:l.getChildrenSize(),\"element\"),M(t)}else if(g){const t=e.clone(),[n]=mn(a,s,s),o=n[0][0].cell,l=n[n.length-1].at(-1).cell;t.anchor.set(h?l.getKey():o.getKey(),h?l.getChildrenSize():0,\"element\"),M(t)}else if(d){if(!s.is(c))return void M(Kn(a,s,c));const o=t.observers.get(a.getKey());if(void 0===o)return;const[l]=o;if(\"touch\"===l.pointerType&&l.isSelecting&&l.isPointerDrag&&e.isCollapsed()&&v(n)&&n.isCollapsed()){const e=A(n.anchor.key),t=e&&ho(e),{pointerStartCell:o}=l,r=o&&he(o.elem);null!==r&&!r.is(c)&&t&&a.is(fo(t))&&!t.is(c)&&(M(Kn(a,t,c)),l.pointerType=null)}}}(n,e),!1}(n,e)),q),e.registerUpdateListener(({dirtyElements:t})=>{if(!o)for(const e of t.keys())if(n.observers.has(e)){o=!0;break}o&&(o=!1,null!==e.getRootElement()&&e.read(\"latest\",()=>{!function(e,t){for(const[n,o]of e.$getTableNodesAndObservers())jn(t,n,o)}(n,e)}))}),e.registerMutationListener(ko,t=>{o=!0,e.read(\"latest\",()=>{for(const[e,o]of t){const t=n.observers.get(e);if(\"created\"===o||\"updated\"===o){const{tableNode:o,tableElement:r}=En(e);void 0===t?l(o,e,r):r!==t[1]&&(n.removeObserver(e),l(o,e,r))}else\"destroyed\"===o&&n.removeObserver(e)}})},{skipInitialization:!1}),()=>{n.removeAllObservers()})}function Uo(e,t){e.hasNodes([ko])||zt(255);const{hasNestedTables:n=Ge(!1)}=t??{};return me(e.registerCommand(Et,e=>function({rows:e,columns:t,includeHeaders:n},o){const l=x()||_e();if(!l||!v(l))return!1;if(!o&&fo(l.anchor.getNode()))return!1;const r=Dt(Number(e),Number(t),n);ht(r);const i=r.getFirstDescendant();return a(i)&&i.select(),!0}(e,n.peek()),He),e.registerCommand(De,(t,o)=>e===o&&function(e,t){const{nodes:n,selection:o}=e;if(!n.some(e=>Wo(e)||dt(e).some(e=>Wo(e.node)))){if(An(o)){let e=\"\",t=!1;for(const o of n){const n=O(o)&&!o.isInline();e.length>0&&(n||t)&&(e+=\"\\n\"),e+=o.getTextContent(),t=n}return o.insertRawText(e),!0}return!1}const l=An(o),r=v(o);return!!(r&&null!==N(o.anchor.getNode(),e=>kt(e))&&null!==N(o.focus.getNode(),e=>kt(e))||l)&&(1===n.length&&Wo(n[0])?vn(n[0],o):!(r&&t.peek()&&!function(e){return!(!An(e)||e.focus.getNode().is(e.anchor.getNode()))||!(!v(e)||!kt(e.anchor.getNode())||e.anchor.getNode().is(e.focus.getNode()))}(o)))}(t,n),He),e.registerCommand(Pe,Po,Be),e.registerCommand(Ie,Do,He),e.registerNodeTransform(ko,Ho),e.registerNodeTransform(Wt,Lo),e.registerNodeTransform(Ft,$o))}const Xo={$accepts:Ht,$packageRun:e=>e.every(kt)?[Lt().splice(0,0,e)]:[],name:\"TableSchema\"},Yo={$accepts:kt,name:\"TableRowSchema\"},qo=[{$import:(e,t)=>{const n=Mo();t.hasAttribute(\"data-lexical-row-striping\")&&n.setRowStriping(!0),t.hasAttribute(\"data-lexical-frozen-column\")&&n.setFrozenColumns(1),t.hasAttribute(\"data-lexical-frozen-row\")&&n.setFrozenRows(1);const o=t.querySelector(\":scope > colgroup\");if(o){let e=[];for(const t of o.querySelectorAll(\":scope > col\")){let n=t.style.width||\"\";if(!pt.test(n)&&(n=t.getAttribute(\"width\")||\"\",!/^\\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&n.setColWidths(e)}return[n.splice(0,0,ct(e.$importChildren(t),Ht))]},match:/* @__PURE__ */et.tag(\"table\"),name:\"@lexical/table/table\"},{$import:(e,t)=>[Lt(pt.test(t.style.height)?parseFloat(t.style.height):void 0).splice(0,0,ct(e.$importChildren(t),kt))],match:/* @__PURE__ */et.tag(\"tr\"),name:\"@lexical/table/tr\"},{$import:(e,t)=>{const n=\"TH\"===t.nodeName,o=pt.test(t.style.width)?parseFloat(t.style.width):void 0;let l=Tt.NO_STATUS;if(n){const e=t.getAttribute(\"scope\");if(\"col\"===e)l=Tt.COLUMN;else if(\"row\"===e)l=Tt.ROW;else{const e=t.parentElement,n=Xe(e)&&(e.parentElement&&\"THEAD\"===e.parentElement.nodeName||0===e.rowIndex),o=0===t.cellIndex;n&&(l|=Tt.ROW),o&&(l|=Tt.COLUMN),l===Tt.NO_STATUS&&(l=Tt.ROW)}}const r=Kt(l,t.colSpan,o);r.__rowSpan=t.rowSpan;const i=t.style.backgroundColor;\"\"!==i&&(r.__backgroundColor=i);const s=t.style.verticalAlign;(function(e){return\"middle\"===e||\"bottom\"===e})(s)&&(r.__verticalAlign=s);const d=e.get(tt),f=d|function(e){let t=0;const n=e.fontWeight;\"700\"!==n&&\"bold\"!==n||(t|=Ye),\"italic\"===e.fontStyle&&(t|=qe);const o=(e.textDecoration||\"\").split(\" \");return o.includes(\"underline\")&&(t|=Ve),o.includes(\"line-through\")&&(t|=je),t}(t.style),g=e.get(nt),m=t.style.color,p=m?{...g,color:m}:g,_=[];f!==d&&_.push(ot(tt,f)),p!==g&&_.push(ot(nt,p));const C=function(e){const t=[];let n=null;const o=()=>{if(null!==n){const e=n.getFirstChild();u(e)&&1===n.getChildrenSize()&&e.remove()}};for(const l of e)c(l)||a(l)||u(l)?null!==n?n.append(l):(n=h().append(l),t.push(n)):(o(),n=null,t.push(l));return o(),0===t.length&&t.push(h()),t}(e.$importChildren(t,{context:_})),S=n?C:lt(C,t);return[r.splice(0,0,S)]},match:/* @__PURE__ */et.tag(\"td\",\"th\"),name:\"@lexical/table/cell\"}],Vo={build:(e,t,n)=>Ze(t),config:{hasCellBackgroundColor:!0,hasCellMerge:!0,hasHorizontalScroll:!0,hasNestedTables:!1,hasStickyScrollbar:!1,hasTabHandler:!0},dependencies:[rt,[it,{rules:qo}]],name:\"@lexical/table/Table\",nodes:()=>[ko,Wt,Ft],register(e,t,n){const o=n.getOutput();let l=!1;return me(Qe(()=>{const t=o.hasHorizontalScroll.value,n=o.hasStickyScrollbar.value&&t,r=Ao(e);r!==t&&Ko(e,t),r===t&&l===n||e.update(Je),l=n}),Uo(e,o),Qe(()=>Io(e,o.hasTabHandler.value)),Qe(()=>{if(o.hasStickyScrollbar.value&&o.hasHorizontalScroll.value)return e.registerRootListener(t=>{if(t)return function(e){const t=new Map;return me(()=>{for(const{cleanup:e}of t.values())e();t.clear()},e.registerMutationListener(ko,n=>{for(const[o,l]of n){const n=t.get(o);if(\"destroyed\"===l){n&&(n.cleanup(),t.delete(o));continue}const r=e.getElementByKey(o),s=r&&i(r)?Ro(r):null;n&&s&&n.parts.scrollable===s.scrollable&&n.parts.scrollbar===s.scrollbar&&n.parts.tableElement===s.tableElement?To(s.scrollable,s.scrollbar):(n&&(n.cleanup(),t.delete(o)),s&&t.set(o,{cleanup:No(s),parts:s}))}},{skipInitialization:!1}))}(e)})}),Qe(()=>o.hasCellMerge.value?void 0:Bo(e)),Qe(()=>o.hasCellBackgroundColor.value?void 0:e.registerNodeTransform(Ft,e=>{null!==e.getBackgroundColor()&&e.setBackgroundColor(null)})))}};export{Sn as $computeTableCellRectBoundary,mn as $computeTableMap,pn as $computeTableMapSkipCellCheck,Kt as $createTableCellNode,Mo as $createTableNode,Dt as $createTableNodeWithDimensions,Lt as $createTableRowNode,On as $createTableSelection,Kn as $createTableSelectionFrom,on as $deleteTableColumn,sn as $deleteTableColumnAtSelection,cn as $deleteTableColumn__EXPERIMENTAL,ln as $deleteTableRowAtSelection,rn as $deleteTableRow__EXPERIMENTAL,ho as $findCellNode,fo as $findTableNode,Eo as $getElementForTableNode,Cn as $getNodeTriplet,En as $getTableAndElementByKey,Pt as $getTableCellNodeFromLexicalNode,xn as $getTableCellNodeRect,Xt as $getTableColumnIndexFromTableCellNode,It as $getTableNodeFromLexicalNodeOrThrow,Ut as $getTableRowIndexFromTableCellNode,Bt as $getTableRowNodeFromTableCellNodeOrThrow,Zt as $insertTableColumn,nn as $insertTableColumnAtNode,en as $insertTableColumnAtSelection,tn as $insertTableColumn__EXPERIMENTAL,Vt as $insertTableRow,Qt as $insertTableRowAtNode,Jt as $insertTableRowAtSelection,Gt as $insertTableRow__EXPERIMENTAL,Ao as $isScrollableTablesActive,yn as $isSimpleTable,Oo as $isStickyScrollbarActive,kt as $isTableCellNode,Wo as $isTableNode,Ht as $isTableRowNode,An as $isTableSelection,hn as $mergeCells,bn as $moveTableColumn,wn as $moveTableRow,_n as $padTableRows,qt as $removeTableRowAtIndex,Tn as $setTableColumnIsHeader,Nn as $setTableRowIsHeader,fn as $unmergeCell,gn as $unmergeCellNode,Et as INSERT_TABLE_COMMAND,Tt as TableCellHeaderStates,Ft as TableCellNode,Vo as TableExtension,qo as TableImportRules,ko as TableNode,Mn as TableObserver,Wt as TableRowNode,Yo as TableRowSchema,Xo as TableSchema,Vn as applyTableHandlers,Gn as getDOMCellFromTarget,Pn as getTableElement,Jn as getTableObserverFromTableElement,Bo as registerTableCellUnmergeTransform,Uo as registerTablePlugin,Io as registerTableSelectionObserver,Ko as setScrollableTablesActive};\n","/* eslint-disable jsdoc/require-jsdoc */\n\n/**\n * Implement a wrapper for the IndexedDB API, making it easier to use the client-side database with\n * auto-upgrades and convenient Promise methods.\n */\nexport default class IndexedDB {\n  /**\n   * Database itself.\n   * @type {IDBDatabase | undefined}\n   */\n  #database;\n\n  /**\n   * In-flight promise that resolves to the opened database. Used to prevent concurrent callers from\n   * opening (and potentially version-bumping) the database in parallel.\n   * @type {Promise<IDBDatabase> | undefined}\n   */\n  #databasePromise;\n\n  /**\n   * Database name in use.\n   * @type {string}\n   */\n  #databaseName = '';\n\n  /**\n   * Store name in use.\n   * @type {string}\n   */\n  #storeName = '';\n\n  /**\n   * Store options to be passed to `IDBDatabase.createObjectStore()`. Note that this cannot be\n   * altered after the store is created.\n   * @type {IDBObjectStoreParameters}\n   */\n  #storeOptions = {};\n\n  /**\n   * Index options to be passed to `IDBObjectStore.createIndex()`.\n   * @type {import(\"../typedefs\").DatabaseIndex[]}\n   */\n  #indexes = [];\n\n  /**\n   * Initialize a new `IndexedDB` instance.\n   * @param {string} databaseName Database name.\n   * @param {string} storeName Store name.\n   * @param {object} [options] Options.\n   * @param {string | string[]} [options.keyPath] Option for `createObjectStore()`.\n   * @param {boolean} [options.autoIncrement] Option for `createObjectStore()`.\n   * @param {import(\"../typedefs\").DatabaseIndex[]} [options.indexes] Arguments for `createIndex()`.\n   * @see https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/createObjectStore\n   * @see https://stackoverflow.com/questions/33852508/how-to-create-an-indexeddb-composite-key\n   */\n  constructor(databaseName, storeName, { keyPath, autoIncrement, indexes = [] } = {}) {\n    this.#database = undefined;\n    this.#databaseName = databaseName;\n    this.#storeName = storeName;\n    this.#storeOptions = { keyPath, autoIncrement };\n    this.#indexes = indexes;\n  }\n\n  /**\n   * Open the database and create a store if needed.\n   * @param {number} [version] Database version.\n   * @returns {Promise<IDBDatabase>} Database.\n   */\n  async #openDatabase(version) {\n    return new Promise((resolve, reject) => {\n      const request = globalThis.indexedDB.open(this.#databaseName, version);\n\n      request.onupgradeneeded = () => {\n        const database = request.result;\n        const storeName = this.#storeName;\n\n        const store = database.objectStoreNames.contains(storeName)\n          ? /** @type {IDBTransaction} */ (request.transaction).objectStore(storeName)\n          : database.createObjectStore(storeName, this.#storeOptions);\n\n        this.#indexes.forEach(({ name, keyPath, options }) => {\n          if (!store.indexNames.contains(name)) {\n            store.createIndex(name, keyPath, options);\n          }\n        });\n      };\n\n      request.onsuccess = () => {\n        resolve(request.result);\n      };\n\n      request.onerror = () => {\n        reject(request.error);\n      };\n    });\n  }\n\n  /**\n   * Check whether the database lacks the store or any of the indexes, requiring an upgrade.\n   * @param {IDBDatabase} database Database.\n   * @returns {boolean} Result.\n   */\n  #isUpgradeNeeded(database) {\n    const storeName = this.#storeName;\n\n    if (!database.objectStoreNames.contains(storeName)) {\n      return true;\n    }\n\n    const store = database.transaction(storeName).objectStore(storeName);\n\n    return this.#indexes.some(({ name }) => !store.indexNames.contains(name));\n  }\n\n  /**\n   * Get the database and automatically upgrade it if a new store is not created yet.\n   * @returns {Promise<IDBDatabase>} Database.\n   */\n  async #getDatabase() {\n    let database = await this.#openDatabase();\n\n    // Loop because another connection (e.g. another instance using a different store in the same\n    // database) may upgrade the database concurrently. In that case our `version + 1` open either\n    // succeeds without running `onupgradeneeded`, leaving our store missing, or fails with a\n    // `VersionError` because the database is already at a higher version.\n    while (this.#isUpgradeNeeded(database)) {\n      const { version } = database;\n\n      database.close();\n\n      try {\n        // eslint-disable-next-line no-await-in-loop\n        database = await this.#openDatabase(version + 1);\n      } catch (error) {\n        if (/** @type {DOMException} */ (error)?.name !== 'VersionError') {\n          throw error;\n        }\n\n        // eslint-disable-next-line no-await-in-loop\n        database = await this.#openDatabase();\n      }\n    }\n\n    // Avoid upgrade conflict\n    database.onversionchange = () => {\n      database.close();\n      this.#database = undefined;\n    };\n\n    // The connection can also be closed by the browser, e.g. when site data is cleared. Drop the\n    // cached reference so the next query reopens the database instead of failing forever.\n    database.onclose = () => {\n      this.#database = undefined;\n    };\n\n    return database;\n  }\n\n  /**\n   * Create a database if not yet initialized, then execute the given function over the store.\n   * @param {(store: IDBObjectStore) => IDBRequest | void} getRequest Function to be executed.\n   * @param {object} [options] Options.\n   * @param {IDBTransactionMode} [options.mode] Transaction mode. Default: `readonly`.\n   * @returns {Promise<any | void>} Result.\n   */\n  async #query(getRequest, { mode = 'readonly' } = {}) {\n    if (!this.#database) {\n      // Cache the in-flight promise so concurrent callers share a single DB open.\n      this.#databasePromise ??= this.#getDatabase();\n\n      try {\n        this.#database = await this.#databasePromise;\n      } finally {\n        // Clear in `finally`, not after the `await`: if the open fails, the rejected promise must\n        // not stay cached, or every later query on this instance would replay the same failure with\n        // no way to recover.\n        this.#databasePromise = undefined;\n      }\n    }\n\n    const database = /** @type {IDBDatabase} */ (this.#database);\n    const storeName = this.#storeName;\n    const transaction = database.transaction(storeName, mode);\n    const request = getRequest(transaction.objectStore(storeName));\n\n    return new Promise((resolve, reject) => {\n      transaction.onerror = () => {\n        reject(transaction.error);\n      };\n\n      transaction.onabort = () => {\n        reject(transaction.error);\n      };\n\n      if (mode === 'readwrite') {\n        // For writes, resolve on transaction commit (not on request success) so the caller is only\n        // notified once the data is durably persisted.\n        /** @type {any} */\n        let result;\n\n        if (request) {\n          request.onsuccess = () => {\n            result = request.result;\n          };\n        }\n\n        transaction.oncomplete = () => {\n          resolve(result);\n        };\n      } else if (request) {\n        request.onsuccess = () => {\n          resolve(request.result);\n        };\n      } else {\n        /* v8 ignore next */\n        transaction.oncomplete = () => {\n          resolve(undefined);\n        };\n      }\n    });\n  }\n\n  /**\n   * Save a value with an out-of-line key.\n   * @param {any} key Key.\n   * @param {any} value Value.\n   * @returns {Promise<any>} Key.\n   */\n  async set(key, value) {\n    return this.#query((store) => store.put(value, key), { mode: 'readwrite' });\n  }\n\n  /**\n   * Save a value with an inline key.\n   * @param {any} value Value.\n   * @returns {Promise<any>} Key.\n   */\n  async put(value) {\n    return this.#query((store) => store.put(value), { mode: 'readwrite' });\n  }\n\n  /**\n   * Save multiple records.\n   * @param {[any, any][]} records Key/value pairs.\n   * @returns {Promise<any>} Key.\n   */\n  async saveEntries(records) {\n    return this.#query(\n      (store) => {\n        records.forEach(([key, value]) => {\n          store.put(value, key);\n        });\n      },\n      { mode: 'readwrite' },\n    );\n  }\n\n  /**\n   * Retrieve a value by key.\n   * @param {any} key Key.\n   * @returns {Promise<any>} Value.\n   */\n  async get(key) {\n    return this.#query((store) => store.get(key));\n  }\n\n  /**\n   * Retrieve all the keys.\n   * @returns {Promise<any[]>} Keys.\n   */\n  async keys() {\n    return this.#query((store) => store.getAllKeys());\n  }\n\n  /**\n   * Retrieve all the values.\n   * @returns {Promise<any[]>} Values.\n   */\n  async values() {\n    return this.#query((store) => store.getAll());\n  }\n\n  /**\n   * Retrieve all the records.\n   * @returns {Promise<[any, any][]>} Key/value pairs.\n   */\n  async entries() {\n    // Bulk-read keys and values rather than walking a cursor, which costs one event-loop round trip\n    // per record. Both requests run in the same transaction and return records in key order, so\n    // the two arrays line up.\n    /** @type {any[]} */\n    let keys = [];\n\n    const values = await this.#query((store) => {\n      const keysRequest = store.getAllKeys();\n\n      keysRequest.onsuccess = () => {\n        keys = keysRequest.result;\n      };\n\n      return store.getAll();\n    });\n\n    return keys.map((key, index) => [key, values[index]]);\n  }\n\n  /**\n   * Get the given index of the store, or the store itself if no index is given.\n   * @param {IDBObjectStore} store Store.\n   * @param {string} [index] Index name.\n   * @returns {IDBObjectStore | IDBIndex} Store or index.\n   */\n  static #getSource(store, index) {\n    return index ? store.index(index) : store;\n  }\n\n  /**\n   * Find a record using a cursor, stopping at the first match.\n   * @param {object} args Arguments.\n   * @param {(record: any) => boolean} [args.callback] A function to execute for each record.\n   * @param {string} [args.index] Index name.\n   * @param {IDBValidKey | IDBKeyRange} [args.query] Query option for `openCursor()`.\n   * @param {IDBCursorDirection} [args.direction] The direction option for `openCursor()`.\n   * @returns {Promise<any>} Found record.\n   */\n  async #search({\n    callback = undefined,\n    index = undefined,\n    query = undefined,\n    direction = 'next',\n  }) {\n    return new Promise((resolve, reject) => {\n      this.#query((store) => {\n        const request = IndexedDB.#getSource(store, index).openCursor(query, direction);\n\n        request.onsuccess = () => {\n          const cursor = request.result;\n\n          if (cursor) {\n            const { value } = cursor;\n\n            if (typeof callback === 'function' ? callback(value) : true) {\n              resolve(value);\n            } else {\n              cursor.continue();\n            }\n          } else {\n            resolve(undefined);\n          }\n        };\n      }).catch(reject);\n    });\n  }\n\n  /**\n   * Find the first record that matches the condition.\n   * @param {(record: any) => boolean} [callback] A function to execute for each record.\n   * @param {object} [options] Options.\n   * @param {string} [options.index] Index.\n   * @param {IDBValidKey | IDBKeyRange} [options.query] Query option for `openCursor()`.\n   * @returns {Promise<any>} Found record.\n   */\n  async find(callback, { index, query } = {}) {\n    return this.#search({ callback, index, query });\n  }\n\n  /**\n   * Find the last record that matches the condition.\n   * @param {(record: any) => boolean} [callback] A function to execute for each record.\n   * @param {object} [options] Options.\n   * @param {string} [options.index] Index.\n   * @param {IDBValidKey | IDBKeyRange} [options.query] Query option for `openCursor()`.\n   * @returns {Promise<any>} Found record.\n   */\n  async findLast(callback, { index, query } = {}) {\n    return this.#search({ callback, index, query, direction: 'prev' });\n  }\n\n  /**\n   * Find all the records that match the condition.\n   * @param {(record: any) => boolean} [callback] A function to execute for each record.\n   * @param {object} [options] Options.\n   * @param {string} [options.index] Index.\n   * @param {IDBValidKey | IDBKeyRange} [options.query] Query option for `openCursor()`.\n   * @returns {Promise<any[]>} Found records.\n   */\n  async filter(callback, { index, query } = {}) {\n    // Every record has to be visited anyway, so a single bulk read beats a cursor that costs one\n    // event-loop round trip per record. The callback also runs after the transaction is released.\n    /** @type {any[]} */\n    const values = await this.#query((store) => IndexedDB.#getSource(store, index).getAll(query));\n\n    // Wrap the callback so it only receives the record, not `Array#filter`’s index/array arguments\n    return typeof callback === 'function' ? values.filter((value) => callback(value)) : values;\n  }\n\n  /**\n   * Delete an record by key.\n   * @param {any} key Key.\n   * @returns {Promise<void>} Result.\n   */\n  async delete(key) {\n    await this.#query((store) => store.delete(key), { mode: 'readwrite' });\n  }\n\n  /**\n   * Delete multiple records by keys.\n   * @param {any[]} keys Property keys.\n   * @returns {Promise<void>} Result.\n   */\n  async deleteEntries(keys) {\n    await this.#query(\n      (store) => {\n        keys.forEach((key) => {\n          store.delete(key);\n        });\n      },\n      { mode: 'readwrite' },\n    );\n  }\n\n  /**\n   * Delete all the records.\n   * @returns {Promise<void>} Result.\n   */\n  async clear() {\n    await this.#query((store) => store.clear(), { mode: 'readwrite' });\n  }\n}\n","/**\n * Safely parse a JSON string returning `null` on failure, so a single corrupt or foreign-written\n * entry doesn’t break iteration over the whole storage.\n * @param {string} raw Raw stored value.\n * @returns {any} Parsed value, or `null` on failure.\n */\nconst safeParse = (raw) => {\n  try {\n    return JSON.parse(raw);\n  } catch {\n    return null;\n  }\n};\n\n/**\n * Implement a wrapper for the Web Storage API. These methods are async just like the experimental\n * KV Storage and automatically parse/stringify JSON data.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Storage\n * @see https://developer.chrome.com/blog/kv-storage/\n */\nexport default class LocalStorage {\n  /**\n   * Save data.\n   * @param {string} key Storage key.\n   * @param {any} value Serializable value.\n   * @throws {DOMException} When storage access is denied.\n   */\n  static async set(key, value) {\n    // `JSON.stringify(undefined)` returns `undefined`, which would be coerced to the literal string\n    // \"undefined\" and later throw on parse. Treat `undefined` as a delete.\n    if (value === undefined) {\n      globalThis.localStorage.removeItem(key);\n\n      return;\n    }\n\n    globalThis.localStorage.setItem(key, JSON.stringify(value));\n  }\n\n  /**\n   * Retrieve data by key.\n   * @param {string} key Storage key.\n   * @returns {Promise<*>} Data.\n   * @throws {DOMException} When storage access is denied.\n   */\n  static async get(key) {\n    const cache = globalThis.localStorage.getItem(key);\n\n    return cache ? safeParse(cache) : null;\n  }\n\n  /**\n   * Delete data by key.\n   * @param {string} key Storage key.\n   * @throws {DOMException} When storage access is denied.\n   */\n  static async delete(key) {\n    globalThis.localStorage.removeItem(key);\n  }\n\n  /**\n   * Clear the storage.\n   * @throws {DOMException} When storage access is denied.\n   */\n  static async clear() {\n    globalThis.localStorage.clear();\n  }\n\n  /**\n   * Get a list of storage keys.\n   * @returns {Promise<string[]>} Keys.\n   * @throws {DOMException} When storage access is denied.\n   */\n  static async keys() {\n    return Object.keys(globalThis.localStorage);\n  }\n\n  /**\n   * Get a list of storage values. Entries with invalid JSON are returned as `null` instead of\n   * throwing, so third-party/foreign entries on the same origin don’t break iteration.\n   * @returns {Promise<*[]>} Values.\n   * @throws {DOMException} When storage access is denied.\n   */\n  static async values() {\n    return Object.values(globalThis.localStorage).map(safeParse);\n  }\n\n  /**\n   * Get a list of storage entries. Entries with invalid JSON are returned with a `null` value\n   * instead of throwing.\n   * @returns {Promise<[string, any][]>} Entries.\n   * @throws {DOMException} When storage access is denied.\n   */\n  static async entries() {\n    return Object.entries(globalThis.localStorage).map(([key, value]) => [key, safeParse(value)]);\n  }\n}\n","// Generated by `scripts/generate-shiki-metadata.js`. DO NOT EDIT.\n\n/**\n * Version of Shiki whose grammars and themes are fetched at runtime. Must stay in sync with the\n * version bundled into `dist/shiki-engine.js`, because grammar and theme payloads are only\n * guaranteed to be compatible with the matching engine.\n */\nexport const SHIKI_VERSION = \"4.6.0\";\n\n/**\n * Available syntax highlighting languages, sorted by display name.\n * @type {{ id: string, name: string, aliases?: string[] }[]}\n */\nexport const LANGUAGES = [{\"id\":\"bsl\",\"name\":\"1C (Enterprise)\",\"aliases\":[\"1c\"]},{\"id\":\"sdbl\",\"name\":\"1C (Query)\",\"aliases\":[\"1c-query\"]},{\"id\":\"abap\",\"name\":\"ABAP\"},{\"id\":\"actionscript-3\",\"name\":\"ActionScript\",\"aliases\":[\"actionscript\",\"as3\"]},{\"id\":\"ada\",\"name\":\"Ada\"},{\"id\":\"angular-html\",\"name\":\"Angular HTML\"},{\"id\":\"angular-ts\",\"name\":\"Angular TypeScript\"},{\"id\":\"apache\",\"name\":\"Apache Conf\"},{\"id\":\"apex\",\"name\":\"Apex\"},{\"id\":\"apl\",\"name\":\"APL\"},{\"id\":\"applescript\",\"name\":\"AppleScript\"},{\"id\":\"ara\",\"name\":\"Ara\"},{\"id\":\"asciidoc\",\"name\":\"AsciiDoc\",\"aliases\":[\"adoc\"]},{\"id\":\"razor\",\"name\":\"ASP.NET Razor\"},{\"id\":\"asm\",\"name\":\"Assembly\"},{\"id\":\"astro\",\"name\":\"Astro\"},{\"id\":\"ahk\",\"name\":\"AutoHotkey\",\"aliases\":[\"ahk1\"]},{\"id\":\"ahk2\",\"name\":\"AutoHotkey2\"},{\"id\":\"awk\",\"name\":\"AWK\"},{\"id\":\"ballerina\",\"name\":\"Ballerina\"},{\"id\":\"bat\",\"name\":\"Batch File\",\"aliases\":[\"batch\",\"cmd\"]},{\"id\":\"beancount\",\"name\":\"Beancount\"},{\"id\":\"berry\",\"name\":\"Berry\",\"aliases\":[\"be\"]},{\"id\":\"bibtex\",\"name\":\"BibTeX\"},{\"id\":\"bicep\",\"name\":\"Bicep\"},{\"id\":\"bird2\",\"name\":\"BIRD2 Configuration\",\"aliases\":[\"bird\"]},{\"id\":\"blade\",\"name\":\"Blade\"},{\"id\":\"c\",\"name\":\"C\"},{\"id\":\"csharp\",\"name\":\"C#\",\"aliases\":[\"c#\",\"cs\"]},{\"id\":\"cpp\",\"name\":\"C++\",\"aliases\":[\"c++\"]},{\"id\":\"c3\",\"name\":\"C3\"},{\"id\":\"cadence\",\"name\":\"Cadence\",\"aliases\":[\"cdc\"]},{\"id\":\"cairo\",\"name\":\"Cairo\"},{\"id\":\"chapel\",\"name\":\"Chapel\",\"aliases\":[\"chpl\"]},{\"id\":\"clarity\",\"name\":\"Clarity\"},{\"id\":\"clojure\",\"name\":\"Clojure\",\"aliases\":[\"clj\"]},{\"id\":\"soy\",\"name\":\"Closure Templates\",\"aliases\":[\"closure-templates\"]},{\"id\":\"cmake\",\"name\":\"CMake\"},{\"id\":\"cobol\",\"name\":\"COBOL\"},{\"id\":\"codeowners\",\"name\":\"CODEOWNERS\"},{\"id\":\"codeql\",\"name\":\"CodeQL\",\"aliases\":[\"ql\"]},{\"id\":\"coffee\",\"name\":\"CoffeeScript\",\"aliases\":[\"coffeescript\"]},{\"id\":\"common-lisp\",\"name\":\"Common Lisp\",\"aliases\":[\"lisp\"]},{\"id\":\"crystal\",\"name\":\"Crystal\"},{\"id\":\"css\",\"name\":\"CSS\"},{\"id\":\"csv\",\"name\":\"CSV\"},{\"id\":\"cue\",\"name\":\"CUE\"},{\"id\":\"cypher\",\"name\":\"Cypher\",\"aliases\":[\"cql\"]},{\"id\":\"d\",\"name\":\"D\"},{\"id\":\"dart\",\"name\":\"Dart\"},{\"id\":\"dax\",\"name\":\"DAX\"},{\"id\":\"desktop\",\"name\":\"Desktop\"},{\"id\":\"diff\",\"name\":\"Diff\"},{\"id\":\"docker\",\"name\":\"Dockerfile\",\"aliases\":[\"dockerfile\"]},{\"id\":\"dotenv\",\"name\":\"dotEnv\"},{\"id\":\"dream-maker\",\"name\":\"Dream Maker\"},{\"id\":\"edge\",\"name\":\"Edge\"},{\"id\":\"elixir\",\"name\":\"Elixir\"},{\"id\":\"elm\",\"name\":\"Elm\"},{\"id\":\"emacs-lisp\",\"name\":\"Emacs Lisp\",\"aliases\":[\"elisp\"]},{\"id\":\"erb\",\"name\":\"ERB\"},{\"id\":\"erlang\",\"name\":\"Erlang\",\"aliases\":[\"erl\"]},{\"id\":\"fsharp\",\"name\":\"F#\",\"aliases\":[\"f#\",\"fs\"]},{\"id\":\"fennel\",\"name\":\"Fennel\"},{\"id\":\"fish\",\"name\":\"Fish\"},{\"id\":\"fluent\",\"name\":\"Fluent\",\"aliases\":[\"ftl\"]},{\"id\":\"fortran-fixed-form\",\"name\":\"Fortran (Fixed Form)\",\"aliases\":[\"f\",\"for\",\"f77\"]},{\"id\":\"fortran-free-form\",\"name\":\"Fortran (Free Form)\",\"aliases\":[\"f90\",\"f95\",\"f03\",\"f08\",\"f18\"]},{\"id\":\"gdresource\",\"name\":\"GDResource\",\"aliases\":[\"tscn\",\"tres\"]},{\"id\":\"gdscript\",\"name\":\"GDScript\",\"aliases\":[\"gd\"]},{\"id\":\"gdshader\",\"name\":\"GDShader\"},{\"id\":\"genie\",\"name\":\"Genie\"},{\"id\":\"po\",\"name\":\"Gettext PO\",\"aliases\":[\"pot\",\"potx\"]},{\"id\":\"gherkin\",\"name\":\"Gherkin\"},{\"id\":\"git-commit\",\"name\":\"Git Commit Message\"},{\"id\":\"git-rebase\",\"name\":\"Git Rebase Message\"},{\"id\":\"gleam\",\"name\":\"Gleam\"},{\"id\":\"glimmer-js\",\"name\":\"Glimmer JS\",\"aliases\":[\"gjs\"]},{\"id\":\"glimmer-ts\",\"name\":\"Glimmer TS\",\"aliases\":[\"gts\"]},{\"id\":\"glsl\",\"name\":\"GLSL\"},{\"id\":\"gn\",\"name\":\"GN\"},{\"id\":\"smalltalk\",\"name\":\"GNU Smalltalk\"},{\"id\":\"gnuplot\",\"name\":\"Gnuplot\"},{\"id\":\"go\",\"name\":\"Go\"},{\"id\":\"graphql\",\"name\":\"GraphQL\",\"aliases\":[\"gql\"]},{\"id\":\"groovy\",\"name\":\"Groovy\"},{\"id\":\"hack\",\"name\":\"Hack\"},{\"id\":\"handlebars\",\"name\":\"Handlebars\",\"aliases\":[\"hbs\"]},{\"id\":\"hcl\",\"name\":\"HashiCorp HCL\"},{\"id\":\"haskell\",\"name\":\"Haskell\",\"aliases\":[\"hs\"]},{\"id\":\"haxe\",\"name\":\"Haxe\"},{\"id\":\"hjson\",\"name\":\"Hjson\"},{\"id\":\"hlsl\",\"name\":\"HLSL\"},{\"id\":\"html\",\"name\":\"HTML\"},{\"id\":\"html-derivative\",\"name\":\"HTML (Derivative)\"},{\"id\":\"http\",\"name\":\"HTTP\"},{\"id\":\"hurl\",\"name\":\"Hurl\"},{\"id\":\"hxml\",\"name\":\"HXML\"},{\"id\":\"hy\",\"name\":\"Hy\"},{\"id\":\"imba\",\"name\":\"Imba\"},{\"id\":\"ini\",\"name\":\"INI\",\"aliases\":[\"properties\"]},{\"id\":\"java\",\"name\":\"Java\"},{\"id\":\"javascript\",\"name\":\"JavaScript\",\"aliases\":[\"js\",\"cjs\",\"mjs\"]},{\"id\":\"jinja\",\"name\":\"Jinja\"},{\"id\":\"jison\",\"name\":\"Jison\"},{\"id\":\"json\",\"name\":\"JSON\"},{\"id\":\"jsonl\",\"name\":\"JSON Lines\"},{\"id\":\"jsonc\",\"name\":\"JSON with Comments\"},{\"id\":\"json5\",\"name\":\"JSON5\"},{\"id\":\"jsonnet\",\"name\":\"Jsonnet\"},{\"id\":\"jssm\",\"name\":\"JSSM\",\"aliases\":[\"fsl\"]},{\"id\":\"jsx\",\"name\":\"JSX\"},{\"id\":\"julia\",\"name\":\"Julia\",\"aliases\":[\"jl\"]},{\"id\":\"just\",\"name\":\"Just\",\"aliases\":[\"justfile\"]},{\"id\":\"kdl\",\"name\":\"KDL\"},{\"id\":\"kotlin\",\"name\":\"Kotlin\",\"aliases\":[\"kt\",\"kts\"]},{\"id\":\"kusto\",\"name\":\"Kusto\",\"aliases\":[\"kql\"]},{\"id\":\"latex\",\"name\":\"LaTeX\"},{\"id\":\"lean\",\"name\":\"Lean 4\",\"aliases\":[\"lean4\"]},{\"id\":\"less\",\"name\":\"Less\"},{\"id\":\"liquid\",\"name\":\"Liquid\"},{\"id\":\"llvm\",\"name\":\"LLVM IR\"},{\"id\":\"log\",\"name\":\"Log file\"},{\"id\":\"logo\",\"name\":\"Logo\"},{\"id\":\"lua\",\"name\":\"Lua\"},{\"id\":\"luau\",\"name\":\"Luau\"},{\"id\":\"make\",\"name\":\"Makefile\",\"aliases\":[\"makefile\"]},{\"id\":\"markdown\",\"name\":\"Markdown\",\"aliases\":[\"md\"]},{\"id\":\"marko\",\"name\":\"Marko\"},{\"id\":\"matlab\",\"name\":\"MATLAB\"},{\"id\":\"mdc\",\"name\":\"MDC\"},{\"id\":\"mdx\",\"name\":\"MDX\"},{\"id\":\"mermaid\",\"name\":\"Mermaid\",\"aliases\":[\"mmd\"]},{\"id\":\"mipsasm\",\"name\":\"MIPS Assembly\",\"aliases\":[\"mips\"]},{\"id\":\"mojo\",\"name\":\"Mojo\"},{\"id\":\"moonbit\",\"name\":\"MoonBit\",\"aliases\":[\"mbt\",\"mbti\"]},{\"id\":\"move\",\"name\":\"Move\"},{\"id\":\"narrat\",\"name\":\"Narrat Language\",\"aliases\":[\"nar\"]},{\"id\":\"nextflow\",\"name\":\"Nextflow\",\"aliases\":[\"nf\"]},{\"id\":\"nextflow-groovy\",\"name\":\"Nextflow Groovy\"},{\"id\":\"nginx\",\"name\":\"Nginx\"},{\"id\":\"nim\",\"name\":\"Nim\"},{\"id\":\"nix\",\"name\":\"Nix\"},{\"id\":\"nsis\",\"name\":\"NSIS\"},{\"id\":\"nushell\",\"name\":\"nushell\",\"aliases\":[\"nu\"]},{\"id\":\"objective-c\",\"name\":\"Objective-C\",\"aliases\":[\"objc\"]},{\"id\":\"objective-cpp\",\"name\":\"Objective-C++\"},{\"id\":\"ocaml\",\"name\":\"OCaml\"},{\"id\":\"odin\",\"name\":\"Odin\"},{\"id\":\"openscad\",\"name\":\"OpenSCAD\",\"aliases\":[\"scad\"]},{\"id\":\"org\",\"name\":\"Org Markup\"},{\"id\":\"pascal\",\"name\":\"Pascal\"},{\"id\":\"perl\",\"name\":\"Perl\"},{\"id\":\"php\",\"name\":\"PHP\"},{\"id\":\"pkl\",\"name\":\"Pkl\"},{\"id\":\"plsql\",\"name\":\"PL/SQL\"},{\"id\":\"polar\",\"name\":\"Polar\"},{\"id\":\"postcss\",\"name\":\"PostCSS\"},{\"id\":\"powerquery\",\"name\":\"PowerQuery\"},{\"id\":\"powershell\",\"name\":\"PowerShell\",\"aliases\":[\"ps\",\"ps1\",\"pwsh\"]},{\"id\":\"prisma\",\"name\":\"Prisma\"},{\"id\":\"prolog\",\"name\":\"Prolog\"},{\"id\":\"proto\",\"name\":\"Protocol Buffer 3\",\"aliases\":[\"protobuf\"]},{\"id\":\"pug\",\"name\":\"Pug\",\"aliases\":[\"jade\"]},{\"id\":\"puppet\",\"name\":\"Puppet\"},{\"id\":\"purescript\",\"name\":\"PureScript\"},{\"id\":\"python\",\"name\":\"Python\",\"aliases\":[\"py\"]},{\"id\":\"qml\",\"name\":\"QML\"},{\"id\":\"qmldir\",\"name\":\"QML Directory\"},{\"id\":\"qss\",\"name\":\"Qt Style Sheets\"},{\"id\":\"r\",\"name\":\"R\"},{\"id\":\"racket\",\"name\":\"Racket\"},{\"id\":\"raku\",\"name\":\"Raku\",\"aliases\":[\"perl6\"]},{\"id\":\"rbs\",\"name\":\"RBS\",\"aliases\":[\"ruby-signature\"]},{\"id\":\"regexp\",\"name\":\"RegExp\",\"aliases\":[\"regex\"]},{\"id\":\"rel\",\"name\":\"Rel\"},{\"id\":\"rst\",\"name\":\"reStructuredText\"},{\"id\":\"riscv\",\"name\":\"RISC-V\"},{\"id\":\"coq\",\"name\":\"Rocq\"},{\"id\":\"ron\",\"name\":\"RON\"},{\"id\":\"rosmsg\",\"name\":\"ROS Interface\"},{\"id\":\"ruby\",\"name\":\"Ruby\",\"aliases\":[\"rb\"]},{\"id\":\"haml\",\"name\":\"Ruby Haml\"},{\"id\":\"rust\",\"name\":\"Rust\",\"aliases\":[\"rs\"]},{\"id\":\"sas\",\"name\":\"SAS\"},{\"id\":\"sass\",\"name\":\"Sass\"},{\"id\":\"scala\",\"name\":\"Scala\"},{\"id\":\"scheme\",\"name\":\"Scheme\"},{\"id\":\"scss\",\"name\":\"SCSS\"},{\"id\":\"shaderlab\",\"name\":\"ShaderLab\",\"aliases\":[\"shader\"]},{\"id\":\"shellscript\",\"name\":\"Shell\",\"aliases\":[\"bash\",\"sh\",\"shell\",\"zsh\"]},{\"id\":\"shellsession\",\"name\":\"Shell Session\",\"aliases\":[\"console\"]},{\"id\":\"smithy\",\"name\":\"Smithy\"},{\"id\":\"solidity\",\"name\":\"Solidity\"},{\"id\":\"sparql\",\"name\":\"SPARQL\"},{\"id\":\"splunk\",\"name\":\"Splunk Query Language\",\"aliases\":[\"spl\"]},{\"id\":\"sql\",\"name\":\"SQL\"},{\"id\":\"ssh-config\",\"name\":\"SSH Config\"},{\"id\":\"stata\",\"name\":\"Stata\"},{\"id\":\"stylus\",\"name\":\"Stylus\",\"aliases\":[\"styl\"]},{\"id\":\"surrealql\",\"name\":\"SurrealQL\",\"aliases\":[\"surql\"]},{\"id\":\"svelte\",\"name\":\"Svelte\"},{\"id\":\"swift\",\"name\":\"Swift\"},{\"id\":\"systemd\",\"name\":\"Systemd Units\"},{\"id\":\"system-verilog\",\"name\":\"SystemVerilog\"},{\"id\":\"talonscript\",\"name\":\"TalonScript\",\"aliases\":[\"talon\"]},{\"id\":\"tasl\",\"name\":\"Tasl\"},{\"id\":\"tcl\",\"name\":\"Tcl\"},{\"id\":\"templ\",\"name\":\"Templ\"},{\"id\":\"terraform\",\"name\":\"Terraform\",\"aliases\":[\"tf\",\"tfvars\"]},{\"id\":\"tex\",\"name\":\"TeX\"},{\"id\":\"toml\",\"name\":\"TOML\"},{\"id\":\"tsv\",\"name\":\"TSV\"},{\"id\":\"tsx\",\"name\":\"TSX\"},{\"id\":\"turtle\",\"name\":\"Turtle\"},{\"id\":\"twig\",\"name\":\"Twig\"},{\"id\":\"typescript\",\"name\":\"TypeScript\",\"aliases\":[\"ts\",\"cts\",\"mts\"]},{\"id\":\"ts-tags\",\"name\":\"TypeScript with Tags\",\"aliases\":[\"lit\"]},{\"id\":\"typespec\",\"name\":\"TypeSpec\",\"aliases\":[\"tsp\"]},{\"id\":\"typst\",\"name\":\"Typst\",\"aliases\":[\"typ\"]},{\"id\":\"v\",\"name\":\"V\"},{\"id\":\"vala\",\"name\":\"Vala\"},{\"id\":\"verilog\",\"name\":\"Verilog\"},{\"id\":\"vhdl\",\"name\":\"VHDL\"},{\"id\":\"viml\",\"name\":\"Vim Script\",\"aliases\":[\"vim\",\"vimscript\"]},{\"id\":\"vb\",\"name\":\"Visual Basic\"},{\"id\":\"vue\",\"name\":\"Vue\"},{\"id\":\"vue-html\",\"name\":\"Vue HTML\"},{\"id\":\"vue-vine\",\"name\":\"Vue Vine\"},{\"id\":\"vyper\",\"name\":\"Vyper\",\"aliases\":[\"vy\"]},{\"id\":\"wasm\",\"name\":\"WebAssembly\"},{\"id\":\"wit\",\"name\":\"WebAssembly Interface Types\"},{\"id\":\"wenyan\",\"name\":\"Wenyan\",\"aliases\":[\"文言\"]},{\"id\":\"wgsl\",\"name\":\"WGSL\"},{\"id\":\"wikitext\",\"name\":\"Wikitext\",\"aliases\":[\"mediawiki\",\"wiki\"]},{\"id\":\"reg\",\"name\":\"Windows Registry Script\"},{\"id\":\"wolfram\",\"name\":\"Wolfram\",\"aliases\":[\"wl\"]},{\"id\":\"xml\",\"name\":\"XML\"},{\"id\":\"xsl\",\"name\":\"XSL\"},{\"id\":\"yaml\",\"name\":\"YAML\",\"aliases\":[\"yml\"]},{\"id\":\"zenscript\",\"name\":\"ZenScript\"},{\"id\":\"zig\",\"name\":\"Zig\"}];\n\n/**\n * Available syntax highlighting themes.\n * @type {{ id: string, displayName: string, type: string }[]}\n */\nexport const THEMES = [{\"id\":\"andromeeda\",\"displayName\":\"Andromeeda\",\"type\":\"dark\"},{\"id\":\"aurora-x\",\"displayName\":\"Aurora X\",\"type\":\"dark\"},{\"id\":\"ayu-dark\",\"displayName\":\"Ayu Dark\",\"type\":\"dark\"},{\"id\":\"ayu-light\",\"displayName\":\"Ayu Light\",\"type\":\"light\"},{\"id\":\"ayu-mirage\",\"displayName\":\"Ayu Mirage\",\"type\":\"dark\"},{\"id\":\"catppuccin-frappe\",\"displayName\":\"Catppuccin Frappé\",\"type\":\"dark\"},{\"id\":\"catppuccin-latte\",\"displayName\":\"Catppuccin Latte\",\"type\":\"light\"},{\"id\":\"catppuccin-macchiato\",\"displayName\":\"Catppuccin Macchiato\",\"type\":\"dark\"},{\"id\":\"catppuccin-mocha\",\"displayName\":\"Catppuccin Mocha\",\"type\":\"dark\"},{\"id\":\"dark-plus\",\"displayName\":\"Dark Plus\",\"type\":\"dark\"},{\"id\":\"dracula\",\"displayName\":\"Dracula Theme\",\"type\":\"dark\"},{\"id\":\"dracula-soft\",\"displayName\":\"Dracula Theme Soft\",\"type\":\"dark\"},{\"id\":\"everforest-dark\",\"displayName\":\"Everforest Dark\",\"type\":\"dark\"},{\"id\":\"everforest-light\",\"displayName\":\"Everforest Light\",\"type\":\"light\"},{\"id\":\"github-dark\",\"displayName\":\"GitHub Dark\",\"type\":\"dark\"},{\"id\":\"github-dark-default\",\"displayName\":\"GitHub Dark Default\",\"type\":\"dark\"},{\"id\":\"github-dark-dimmed\",\"displayName\":\"GitHub Dark Dimmed\",\"type\":\"dark\"},{\"id\":\"github-dark-high-contrast\",\"displayName\":\"GitHub Dark High Contrast\",\"type\":\"dark\"},{\"id\":\"github-light\",\"displayName\":\"GitHub Light\",\"type\":\"light\"},{\"id\":\"github-light-default\",\"displayName\":\"GitHub Light Default\",\"type\":\"light\"},{\"id\":\"github-light-high-contrast\",\"displayName\":\"GitHub Light High Contrast\",\"type\":\"light\"},{\"id\":\"gruvbox-dark-hard\",\"displayName\":\"Gruvbox Dark Hard\",\"type\":\"dark\"},{\"id\":\"gruvbox-dark-medium\",\"displayName\":\"Gruvbox Dark Medium\",\"type\":\"dark\"},{\"id\":\"gruvbox-dark-soft\",\"displayName\":\"Gruvbox Dark Soft\",\"type\":\"dark\"},{\"id\":\"gruvbox-light-hard\",\"displayName\":\"Gruvbox Light Hard\",\"type\":\"light\"},{\"id\":\"gruvbox-light-medium\",\"displayName\":\"Gruvbox Light Medium\",\"type\":\"light\"},{\"id\":\"gruvbox-light-soft\",\"displayName\":\"Gruvbox Light Soft\",\"type\":\"light\"},{\"id\":\"horizon\",\"displayName\":\"Horizon\",\"type\":\"dark\"},{\"id\":\"horizon-bright\",\"displayName\":\"Horizon Bright\",\"type\":\"light\"},{\"id\":\"houston\",\"displayName\":\"Houston\",\"type\":\"dark\"},{\"id\":\"kanagawa-dragon\",\"displayName\":\"Kanagawa Dragon\",\"type\":\"dark\"},{\"id\":\"kanagawa-lotus\",\"displayName\":\"Kanagawa Lotus\",\"type\":\"light\"},{\"id\":\"kanagawa-wave\",\"displayName\":\"Kanagawa Wave\",\"type\":\"dark\"},{\"id\":\"laserwave\",\"displayName\":\"LaserWave\",\"type\":\"dark\"},{\"id\":\"light-plus\",\"displayName\":\"Light Plus\",\"type\":\"light\"},{\"id\":\"material-theme\",\"displayName\":\"Material Theme\",\"type\":\"dark\"},{\"id\":\"material-theme-darker\",\"displayName\":\"Material Theme Darker\",\"type\":\"dark\"},{\"id\":\"material-theme-lighter\",\"displayName\":\"Material Theme Lighter\",\"type\":\"light\"},{\"id\":\"material-theme-ocean\",\"displayName\":\"Material Theme Ocean\",\"type\":\"dark\"},{\"id\":\"material-theme-palenight\",\"displayName\":\"Material Theme Palenight\",\"type\":\"dark\"},{\"id\":\"min-dark\",\"displayName\":\"Min Dark\",\"type\":\"dark\"},{\"id\":\"min-light\",\"displayName\":\"Min Light\",\"type\":\"light\"},{\"id\":\"monokai\",\"displayName\":\"Monokai\",\"type\":\"dark\"},{\"id\":\"night-owl\",\"displayName\":\"Night Owl\",\"type\":\"dark\"},{\"id\":\"night-owl-light\",\"displayName\":\"Night Owl Light\",\"type\":\"light\"},{\"id\":\"nord\",\"displayName\":\"Nord\",\"type\":\"dark\"},{\"id\":\"one-dark-pro\",\"displayName\":\"One Dark Pro\",\"type\":\"dark\"},{\"id\":\"one-light\",\"displayName\":\"One Light\",\"type\":\"light\"},{\"id\":\"plastic\",\"displayName\":\"Plastic\",\"type\":\"dark\"},{\"id\":\"poimandres\",\"displayName\":\"Poimandres\",\"type\":\"dark\"},{\"id\":\"red\",\"displayName\":\"Red\",\"type\":\"dark\"},{\"id\":\"rose-pine\",\"displayName\":\"Rosé Pine\",\"type\":\"dark\"},{\"id\":\"rose-pine-dawn\",\"displayName\":\"Rosé Pine Dawn\",\"type\":\"light\"},{\"id\":\"rose-pine-moon\",\"displayName\":\"Rosé Pine Moon\",\"type\":\"dark\"},{\"id\":\"slack-dark\",\"displayName\":\"Slack Dark\",\"type\":\"dark\"},{\"id\":\"slack-ochin\",\"displayName\":\"Slack Ochin\",\"type\":\"light\"},{\"id\":\"snazzy-light\",\"displayName\":\"Snazzy Light\",\"type\":\"light\"},{\"id\":\"solarized-dark\",\"displayName\":\"Solarized Dark\",\"type\":\"dark\"},{\"id\":\"solarized-light\",\"displayName\":\"Solarized Light\",\"type\":\"light\"},{\"id\":\"synthwave-84\",\"displayName\":\"Synthwave '84\",\"type\":\"dark\"},{\"id\":\"tokyo-night\",\"displayName\":\"Tokyo Night\",\"type\":\"dark\"},{\"id\":\"vesper\",\"displayName\":\"Vesper\",\"type\":\"dark\"},{\"id\":\"vitesse-black\",\"displayName\":\"Vitesse Black\",\"type\":\"dark\"},{\"id\":\"vitesse-dark\",\"displayName\":\"Vitesse Dark\",\"type\":\"dark\"},{\"id\":\"vitesse-light\",\"displayName\":\"Vitesse Light\",\"type\":\"light\"}];\n","import { IndexedDB } from '@sveltia/utils/storage';\nimport { SHIKI_VERSION } from './generated.js';\n\n/**\n * Client-side cache for Shiki grammars and themes.\n *\n * Grammars and themes resolve to plain data, so they can be stored and replayed without going back\n * to the network. That saves more than bytes: a grammar references its embedded languages by\n * relative path, so loading Vue or Svelte fans out to several requests, and a cache hit collapses\n * all of them into one read.\n *\n * The engine is deliberately not cached here. It is executable code, so replaying it from storage\n * would mean importing a `blob:` URL, which needs `script-src blob:` in the page’s CSP. It also\n * gains nothing, because it is fetched from a version-immutable URL that the browser’s HTTP cache\n * already keeps.\n */\n\nconst DATABASE_NAME = 'sveltia-ui';\nconst STORE_NAME = 'shiki';\n/** @type {IndexedDB | undefined | null} `null` once the store is known to be unusable. */\nlet database;\n/** @type {Promise<void> | undefined} */\nlet purgePromise;\nlet enabled = true;\n\n/**\n * Enable or disable the cache.\n *\n * Worth turning off when the grammars are bundled with the app rather than fetched, since reading\n * them back from storage is then slower than the bundled import it replaces.\n * @param {boolean} value Whether to use the cache.\n */\nexport const setCodeHighlighterCacheEnabled = (value) => {\n  enabled = value;\n};\n\n/**\n * Build the cache key for a payload.\n * @param {string} kind Payload kind, either `lang` or `theme`.\n * @param {string} id Language or theme ID.\n * @returns {string} Key, scoped to the Shiki version the payload came from.\n */\nconst getKey = (kind, id) => `${SHIKI_VERSION}/${kind}/${id}`;\n\n/**\n * Get the store, or `null` when IndexedDB is unavailable, as in a server-side render or with\n * storage blocked.\n * @returns {IndexedDB | null} Store.\n */\nconst getDatabase = () => {\n  if (database === undefined) {\n    database = typeof indexedDB === 'undefined' ? null : new IndexedDB(DATABASE_NAME, STORE_NAME);\n  }\n\n  return database;\n};\n\n/**\n * Drop anything cached for a different Shiki version, once per session. A version bump changes\n * every key, so the old payloads would otherwise linger forever.\n * @param {IndexedDB} db Store.\n * @returns {Promise<void>} Nothing.\n */\nconst purgeStaleVersions = async (db) => {\n  purgePromise ??= (async () => {\n    const stale = (await db.keys()).filter(\n      (key) => typeof key === 'string' && !key.startsWith(`${SHIKI_VERSION}/`),\n    );\n\n    if (stale.length) {\n      await db.deleteEntries(stale);\n    }\n  })();\n\n  return purgePromise;\n};\n\n/**\n * Read a cached grammar or theme.\n * @param {string} kind Payload kind, either `lang` or `theme`.\n * @param {string} id Language or theme ID.\n * @returns {Promise<any>} Cached payload, or `undefined` when not cached or unreadable.\n */\nexport const getCachedPayload = async (kind, id) => {\n  const db = enabled ? getDatabase() : null;\n\n  if (!db) {\n    return undefined;\n  }\n\n  try {\n    await purgeStaleVersions(db);\n\n    return await db.get(getKey(kind, id));\n  } catch {\n    // A failed cache read must never stop a code block from highlighting\n    return undefined;\n  }\n};\n\n/**\n * Store a grammar or theme.\n * @param {string} kind Payload kind, either `lang` or `theme`.\n * @param {string} id Language or theme ID.\n * @param {any} payload Payload to store. Must be structured-cloneable, which grammars and themes\n * are, being plain data.\n * @returns {Promise<void>} Nothing.\n */\nexport const cachePayload = async (kind, id, payload) => {\n  const db = enabled ? getDatabase() : null;\n\n  if (!db) {\n    return;\n  }\n\n  try {\n    await db.set(getKey(kind, id), payload);\n  } catch {\n    // Out of quota, storage blocked, or a payload that won’t clone: not worth failing over\n  }\n};\n","import { SHIKI_VERSION } from './generated.js';\nimport { UI_VERSION } from './version.js';\n\n/**\n * @import { CodeHighlighterLoaders } from '../../../typedefs.js';\n */\n\nconst SHIKI_CDN_BASE_URL = 'https://unpkg.com/@shikijs';\nconst UI_CDN_BASE_URL = 'https://unpkg.com/@sveltia/ui';\n\n/**\n * Get the URL of the prebuilt syntax highlighting engine.\n *\n * The engine is a single self-contained chunk published with this package, so its version is this\n * package’s. Loading `@shikijs/core` from a CDN directly would instead fan out to some 50 requests,\n * because its dependency graph is preserved module by module.\n * @returns {string} URL.\n */\nexport const getEngineURL = () => `${UI_CDN_BASE_URL}@${UI_VERSION}/dist/shiki-engine.js`;\n\n/**\n * Get the URL of a syntax highlighting grammar.\n *\n * Grammars reference their embedded languages by relative path, so importing one grammar URL pulls\n * in whatever else it needs without any manifest of ours. The version must match the engine’s,\n * which `generated.js` guarantees by recording the Shiki version the engine was built from.\n * @param {string} id Canonical language ID.\n * @returns {string} URL.\n */\nexport const getLanguageURL = (id) => `${SHIKI_CDN_BASE_URL}/langs@${SHIKI_VERSION}/dist/${id}.mjs`;\n\n/**\n * Get the URL of a syntax highlighting theme.\n * @param {string} id Theme ID.\n * @returns {string} URL.\n */\nexport const getThemeURL = (id) => `${SHIKI_CDN_BASE_URL}/themes@${SHIKI_VERSION}/dist/${id}.mjs`;\n\n/**\n * Load the prebuilt syntax highlighting engine.\n * @returns {Promise<any>} Loaded module.\n */\nconst loadEngine = async () =>\n  // eslint-disable-next-line jsdoc/no-bad-blocks\n  import(/* @vite-ignore */ getEngineURL());\n\n/**\n * Load a syntax highlighting grammar.\n * @param {string} id Canonical language ID.\n * @returns {Promise<any>} Loaded module.\n */\nconst loadLanguage = async (id) =>\n  // eslint-disable-next-line jsdoc/no-bad-blocks\n  import(/* @vite-ignore */ getLanguageURL(id));\n\n/**\n * Load a syntax highlighting theme.\n * @param {string} id Theme ID.\n * @returns {Promise<any>} Loaded module.\n */\nconst loadTheme = async (id) =>\n  // eslint-disable-next-line jsdoc/no-bad-blocks\n  import(/* @vite-ignore */ getThemeURL(id));\n\n/**\n * Loaders in effect. Everything is fetched from a CDN on demand by default, so that nothing\n * Shiki-related ends up in the consumer’s bundle.\n * @type {CodeHighlighterLoaders}\n */\nlet loaders = { loadEngine, loadLanguage, loadTheme };\n\n/**\n * Override how the code editor obtains the Shiki engine, grammars and themes.\n *\n * By default these are fetched from a CDN on demand, which keeps them out of the bundle entirely.\n * Consumers who would rather bundle them, self-host them, or ship only a handful of languages can\n * replace any of the loaders. Note that a bundler cannot resolve a dynamic import with a variable\n * bare specifier, so bundling grammars needs a map of static imports.\n *\n * ```js\n * setCodeHighlighterLoaders({\n *   loadLanguage: (id) =>\n *     ({\n *       astro: () => import('@shikijs/langs/astro'),\n *       typescript: () => import('@shikijs/langs/typescript'),\n *     })[id]?.(),\n * });\n * ```\n *\n * A loader may return a falsy value for an unsupported language or theme, in which case the code\n * block is rendered as plain text.\n * @param {Partial<CodeHighlighterLoaders>} overrides Loaders to replace. Any omitted loader keeps\n * its current implementation.\n */\nexport const setCodeHighlighterLoaders = (overrides) => {\n  loaders = { ...loaders, ...overrides };\n};\n\n/**\n * Get the loaders currently in effect.\n * @returns {CodeHighlighterLoaders} Active loaders.\n */\nexport const getCodeHighlighterLoaders = () => loaders;\n","import { SKIP_DOM_SELECTION_TAG } from 'lexical';\n\n/**\n * @import { LexicalEditor, UpdateTag } from 'lexical';\n */\n\n/**\n * Get the tags of an editor update the user didn’t make, such as one that highlights the code once\n * a grammar has loaded. While the focus is elsewhere, the update leaves the DOM selection alone,\n * which would otherwise move the focus back to the editor, taking over what the user types next.\n * @param {LexicalEditor} editor Editor instance.\n * @param {UpdateTag[]} [tags] Other tags of the update.\n * @returns {UpdateTag[]} Tags.\n */\nexport const getBackgroundUpdateTags = (editor, tags = []) =>\n  editor.getRootElement()?.contains(document.activeElement)\n    ? tags\n    : [...tags, SKIP_DOM_SELECTION_TAG];\n","import { $isCodeNode as isCodeNode } from '@lexical/code-core';\nimport { $getRoot as getRoot, HISTORY_MERGE_TAG } from 'lexical';\nimport { getBackgroundUpdateTags } from '../background-update.js';\n\n/**\n * @import { LexicalEditor } from 'lexical';\n */\n\n/**\n * Shiki themes matching the app’s light and dark appearance. Only the per-token colours are used;\n * the code block’s own background comes from `--sui-code-background-color`.\n */\nexport const CODE_THEME_LIGHT = 'github-light';\nexport const CODE_THEME_DARK = 'github-dark';\n\n/**\n * Get the syntax highlighting theme matching the current appearance.\n * @returns {string} Shiki theme ID.\n */\nexport const getCodeTheme = () => {\n  /* v8 ignore next 3 */\n  if (typeof document === 'undefined') {\n    return CODE_THEME_LIGHT;\n  }\n\n  const { theme } = document.documentElement.dataset;\n\n  if (theme) {\n    return theme === 'dark' ? CODE_THEME_DARK : CODE_THEME_LIGHT;\n  }\n\n  return window.matchMedia('(prefers-color-scheme: dark)').matches\n    ? CODE_THEME_DARK\n    : CODE_THEME_LIGHT;\n};\n\n/**\n * Call the given function whenever the app’s appearance, and therefore the matching syntax\n * highlighting theme, may have changed.\n * @param {() => void} callback Function to call.\n * @returns {() => void} Cleanup function.\n */\nexport const onCodeThemeChange = (callback) => {\n  /* v8 ignore next 3 */\n  if (typeof document === 'undefined') {\n    return () => undefined;\n  }\n\n  const observer = new MutationObserver(callback);\n\n  observer.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: ['data-theme'],\n  });\n\n  const media = window.matchMedia('(prefers-color-scheme: dark)');\n\n  media.addEventListener('change', callback);\n\n  return () => {\n    observer.disconnect();\n    media.removeEventListener('change', callback);\n  };\n};\n\n/**\n * Keep code blocks in sync with the app’s appearance.\n *\n * Unlike Prism, Shiki bakes token colours into inline styles, so a theme change cannot be handled\n * in CSS alone: every code node has to be re-tokenized.\n * @param {LexicalEditor} editor Editor instance.\n * @returns {() => void} Cleanup function.\n */\nexport const observeCodeTheme = (editor) =>\n  onCodeThemeChange(() => {\n    const theme = getCodeTheme();\n\n    editor.update(\n      () => {\n        getRoot()\n          .getChildren()\n          .forEach((node) => {\n            if (isCodeNode(node) && node.getTheme() !== theme) {\n              node.setTheme(theme);\n              node.markDirty();\n            }\n          });\n      },\n      { tag: getBackgroundUpdateTags(editor, [HISTORY_MERGE_TAG]) },\n    );\n  });\n","/**\n * Thin wrapper around a Shiki highlighter instance, independent of any editor. The Lexical glue\n * that turns tokens into nodes and refreshes code blocks lives in `lexical.js`.\n *\n * Adapted from Lexical’s `FacadeShiki.ts` (MIT licensed). Two things differ from upstream, both to\n * keep Shiki out of the consumer’s bundle. First, the engine is loaded on demand rather than\n * imported at module scope, so a page that never shows a code block never pays for it. Second,\n * grammar and theme metadata comes from `generated.js` rather than `shiki/langs` and\n * `shiki/themes`, whose lazy `import()` thunks would drag the whole grammar set into a bundle.\n * @see https://github.com/facebook/lexical/tree/v0.50.0/packages/lexical-code-shiki\n * @see https://github.com/sveltia/sveltia-cms/issues/587\n */\n\nimport { cachePayload, getCachedPayload } from './cache.js';\nimport { LANGUAGES, THEMES } from './generated.js';\nimport { getCodeHighlighterLoaders } from './loader.js';\nimport { getCodeTheme } from './theme.js';\n\n/**\n * @import { HighlightedToken } from '../../../typedefs.js';\n */\n\n/**\n * Languages that need no grammar and no engine: the content is shown verbatim. Shiki treats these\n * as special languages internally; we short-circuit them so that a plain code block — the default\n * for a new block — costs no network request at all.\n *\n * `ansi` is deliberately excluded: Shiki does render it, so it still needs the engine.\n */\nconst PLAIN_LANGUAGES = ['', 'plain', 'plaintext', 'text', 'txt'];\nconst DIFF_LANGUAGE_REGEX = /^diff-([\\w-]+)/i;\n/**\n * Loaded engine module, once `loadEngine()` has resolved.\n * @type {any}\n */\nlet engine = null;\n/**\n * Highlighter instance built from the loaded engine.\n * @type {any}\n */\nlet highlighter = null;\n/** Set when the engine could not be fetched, so we stop retrying on every keystroke. */\nlet engineUnavailable = false;\n/**\n * Get the language a `diff-*` language wraps, if any.\n * @param {string} language Language identifier.\n * @returns {string | null} Wrapped language, or `null` when this is not a diff language.\n */\nconst getDiffedLanguage = (language) => DIFF_LANGUAGE_REGEX.exec(language)?.[1] ?? null;\n\n/**\n * Whether the given language is rendered as plain text without any highlighting.\n * @param {string | null | undefined} language Language identifier.\n * @returns {boolean} Result.\n */\nexport const isPlainLanguage = (language) => PLAIN_LANGUAGES.includes(language ?? '');\n\n/**\n * Whether the syntax highlighting engine is loaded and ready to tokenize.\n * @returns {boolean} Result.\n */\nexport const isEngineLoaded = () => !!highlighter;\n\n/**\n * Whether the engine failed to load. Code blocks fall back to plain text in that case instead of\n * waiting forever.\n * @returns {boolean} Result.\n */\nexport const isEngineUnavailable = () => engineUnavailable;\n\n/**\n * Whether the grammar for the given language is loaded.\n * @param {string} language Language identifier, like `scss` or `diff-js`.\n * @returns {boolean} Result.\n */\nexport const isCodeLanguageLoaded = (language) => {\n  if (!highlighter) {\n    return false;\n  }\n\n  const id = getDiffedLanguage(language) ?? language;\n\n  // Shiki handles a handful of languages without a grammar\n  if (engine.isSpecialLang(id)) {\n    return true;\n  }\n\n  // `getLoadedLanguages()` also returns aliases\n  return highlighter.getLoadedLanguages().includes(id);\n};\n\n/**\n * In-flight loads, keyed by what is being loaded.\n * @type {Map<string, { promise: Promise<void>, callbacks: Set<() => void> }>}\n */\nconst pendingLoads = new Map();\n\n/**\n * Run an asynchronous load once, however many callers ask for it while it is in flight, and call\n * each distinct callback exactly once when it completes.\n *\n * The editor transform fires on every keystroke, so without this a burst of typing during a load\n * would start a download per keystroke and then flood the editor with one update each. That storm\n * is enough to starve the final re-highlight, leaving a block tokenized as of an earlier keystroke.\n * Callers that want a single notification for repeated requests should therefore pass the same\n * callback each time.\n * @param {string} key Cache key identifying the load.\n * @param {() => Promise<void>} run Work to perform on the first call.\n * @param {() => void} [onLoaded] Function to call once the load completes.\n * @returns {Promise<void>} Promise resolving when the load has completed.\n */\nconst loadOnce = (key, run, onLoaded) => {\n  let entry = pendingLoads.get(key);\n\n  if (!entry) {\n    /** @type {Set<() => void>} */\n    const callbacks = new Set();\n\n    const promise = (async () => {\n      try {\n        await run();\n      } catch {\n        // Leave the block unhighlighted; the transform falls back to plain text\n      }\n\n      pendingLoads.delete(key);\n      callbacks.forEach((callback) => callback());\n    })();\n\n    entry = { promise, callbacks };\n    pendingLoads.set(key, entry);\n  }\n\n  if (onLoaded) {\n    entry.callbacks.add(onLoaded);\n  }\n\n  return entry.promise;\n};\n\n/**\n * Load the syntax highlighting engine, then call the given function.\n *\n * Tokenizing is synchronous because it runs inside a Lexical node transform, so the engine has to\n * be resident before any highlighting can happen. The transform bails out while this is in flight\n * and is re-run by the callback, the same mechanism upstream already uses for grammars.\n * @param {() => void} [onLoaded] Function to call once the load has completed, whether or not it\n * succeeded.\n * @returns {Promise<void> | undefined} Promise resolving when the engine is ready, or `undefined`\n * when it is already loaded or known to be unavailable.\n */\nexport const loadEngine = (onLoaded) => {\n  if (highlighter || engineUnavailable) {\n    return undefined;\n  }\n\n  return loadOnce(\n    'engine',\n    async () => {\n      try {\n        engine = await getCodeHighlighterLoaders().loadEngine();\n\n        highlighter = engine.createHighlighterCoreSync({\n          engine: engine.createJavaScriptRegexEngine(),\n          langs: [],\n          themes: [],\n        });\n      } catch {\n        engineUnavailable = true;\n      }\n    },\n    onLoaded,\n  );\n};\n\n/**\n * Get a grammar or theme, from the cache when possible, otherwise through the configured loader.\n *\n * Shiki normalizes a registration in place while loading it, so the payload is cached before it is\n * handed over. Caching is best-effort and never blocks: a write that fails just means the next\n * session fetches again.\n * @param {string} kind Payload kind, either `lang` or `theme`.\n * @param {string} id Language or theme ID.\n * @param {() => Promise<any>} load Loader to call on a cache miss.\n * @returns {Promise<any>} Payload, or a falsy value when unavailable.\n */\nconst resolvePayload = async (kind, id, load) => {\n  const cached = await getCachedPayload(kind, id);\n\n  if (cached) {\n    return cached;\n  }\n\n  const module = await load();\n\n  if (!module) {\n    return undefined;\n  }\n\n  const payload = module.default ?? module;\n\n  await cachePayload(kind, id, payload);\n\n  return payload;\n};\n\n/**\n * Load a grammar or theme into the highlighter once, then call the given function. The configured\n * loader and the highlighter share the method name for each kind.\n * @param {'lang' | 'theme'} kind Payload kind.\n * @param {string} id Language or theme ID.\n * @param {() => void} [onLoaded] Function to call once the load has completed.\n * @returns {Promise<void>} Promise resolving when the payload is loaded.\n */\nconst loadAsset = (kind, id, onLoaded) => {\n  const method = kind === 'lang' ? 'loadLanguage' : 'loadTheme';\n\n  return loadOnce(\n    `${kind}/${id}`,\n    async () => {\n      const payload = await resolvePayload(kind, id, () => getCodeHighlighterLoaders()[method](id));\n\n      if (payload) {\n        await highlighter[method](payload);\n      }\n    },\n    onLoaded,\n  );\n};\n\n/**\n * Find the metadata of the given language.\n * @param {string} language Language identifier or alias, like `ts`.\n * @returns {(typeof LANGUAGES)[number] | undefined} Language metadata, or `undefined` when the\n * language is unknown.\n */\nconst findLanguage = (language) =>\n  LANGUAGES.find(({ id, aliases }) => id === language || aliases?.includes(language));\n\n/**\n * Resolve a language alias to its canonical identifier.\n * @param {string} language Language identifier or alias, like `ts`.\n * @returns {string} Canonical identifier, like `typescript`. Returns the input unchanged when the\n * language is unknown.\n */\nexport const normalizeCodeLanguage = (language) => findLanguage(language)?.id ?? language;\n\n/**\n * Load the grammar for the given language, then call the given function.\n * @param {string} language Language identifier, like `scss` or `diff-js`.\n * @param {() => void} [onLoaded] Function to call once the load has completed.\n * @returns {Promise<void> | undefined} Promise resolving when the grammar is ready, or `undefined`\n * when it is already loaded or the language is not supported.\n */\nexport const loadCodeLanguage = (language, onLoaded) => {\n  const id = getDiffedLanguage(language) ?? language;\n\n  if (!highlighter || isCodeLanguageLoaded(id)) {\n    return undefined;\n  }\n\n  const info = findLanguage(id);\n\n  if (!info) {\n    return undefined;\n  }\n\n  return loadAsset('lang', info.id, onLoaded);\n};\n\n/**\n * Whether the given theme is loaded.\n * @param {string} theme Theme identifier, like `github-light`.\n * @returns {boolean} Result.\n */\nexport const isCodeThemeLoaded = (theme) => {\n  if (!highlighter) {\n    return false;\n  }\n\n  return engine.isSpecialTheme(theme) || highlighter.getLoadedThemes().includes(theme);\n};\n\n/**\n * Load the given theme, then call the given function.\n * @param {string} theme Theme identifier, like `github-light`.\n * @param {() => void} [onLoaded] Function to call once the load has completed.\n * @returns {Promise<void> | undefined} Promise resolving when the theme is ready, or `undefined`\n * when it is already loaded or unknown.\n */\nexport const loadCodeTheme = (theme, onLoaded) => {\n  if (!highlighter || isCodeThemeLoaded(theme)) {\n    return undefined;\n  }\n\n  if (!THEMES.some(({ id }) => id === theme)) {\n    return undefined;\n  }\n\n  return loadAsset('theme', theme, onLoaded);\n};\n\n/**\n * Tokenize a snippet of code with the raw Shiki tokens, for building editor nodes. The engine, the\n * grammar and the theme must all be loaded.\n * @param {string} code Code to tokenize.\n * @param {string} language Language identifier, like `scss` or `diff-js`.\n * @param {string} [theme] Shiki theme ID.\n * @returns {{ tokens: any[][], diff: boolean }} Tokens, one array per line, and whether the\n * language is a `diff-*` language, in which case the code is tokenized with the language it wraps.\n */\nexport const tokenizeCode = (code, language, theme) => {\n  const diffedLanguage = getDiffedLanguage(language);\n  const { tokens } = highlighter.codeToTokens(code, { lang: diffedLanguage ?? language, theme });\n\n  return { tokens, diff: !!diffedLanguage };\n};\n\n/**\n * Get the inline style of a Shiki token, preferring its own inline style over the derived one.\n * @param {any} token Token returned by {@link tokenizeCode}.\n * @returns {string} CSS declarations.\n */\nexport const getTokenStyle = (token) =>\n  engine.stringifyTokenStyle(token.htmlStyle || engine.getTokenStyleObject(token));\n\n/**\n * Get the theme to highlight a snippet of code with, if it can be highlighted synchronously: the\n * engine, the grammar of the given language and the theme are all loaded.\n * @param {string} id Canonical language identifier.\n * @param {string} [theme] Shiki theme ID. Defaults to the one matching the app’s appearance.\n * @returns {string | undefined} Theme ID, or `undefined` when the code cannot be highlighted yet.\n */\nconst getHighlightTheme = (id, theme) => {\n  if (!highlighter || isPlainLanguage(id) || !isCodeLanguageLoaded(id)) {\n    return undefined;\n  }\n\n  // Resolved only once the cheap checks pass, so bailing out early costs nothing\n  const resolvedTheme = theme ?? getCodeTheme();\n\n  return isCodeThemeLoaded(resolvedTheme) ? resolvedTheme : undefined;\n};\n\n/**\n * Highlight a snippet of code as an HTML string.\n *\n * Unlike the editor, which builds Lexical nodes, this returns markup for rendering elsewhere, such\n * as a Markdown preview. It is synchronous, so it can be called from a renderer that cannot await:\n * when the engine, grammar or theme is not loaded yet, it returns `undefined` rather than blocking,\n * and the caller can render the code unhighlighted. Call {@link loadCodeHighlighter} first and\n * render again once it resolves to get the highlighted result.\n * @param {string} code Code to highlight.\n * @param {string} language Language identifier or alias, like `ts` or `diff-js`.\n * @param {object} [options] Options.\n * @param {string} [options.theme] Shiki theme ID. Defaults to the one matching the app’s\n * appearance.\n * @returns {string | undefined} HTML string, or `undefined` when the code cannot be highlighted\n * yet.\n */\nexport const highlightCodeToHTML = (code, language, { theme } = {}) => {\n  // Unlike tokens, the HTML is highlighted with the language a `diff-*` language wraps\n  const id = normalizeCodeLanguage(getDiffedLanguage(language) ?? language);\n  const resolvedTheme = getHighlightTheme(id, theme);\n\n  if (resolvedTheme === undefined) {\n    return undefined;\n  }\n\n  return highlighter.codeToHtml(code, { lang: id, theme: resolvedTheme });\n};\n\n/**\n * Highlight a snippet of code as plain tokens.\n *\n * Meant for painting the highlighting behind a `<textarea>`, where the highlighted text has to line\n * up with the editable text glyph by glyph. Only the styles that don’t change the text width are\n * kept: colours, bold, which is rendered as a stroke rather than with a bolder font, underline and\n * strikethrough. Italic is dropped. Tokens in the theme’s default foreground colour have no colour,\n * so they can follow the app’s theme instead. Like {@link highlightCodeToHTML}, this is synchronous\n * and returns `undefined` when the engine, grammar or theme is not loaded yet.\n * @param {string} code Code to highlight.\n * @param {string} language Language identifier or alias, like `md`.\n * @param {object} [options] Options.\n * @param {string} [options.theme] Shiki theme ID. Defaults to the one matching the app’s\n * appearance.\n * @returns {HighlightedToken[][] | undefined} Tokens, one array per line, or `undefined` when the\n * code cannot be highlighted yet.\n */\nexport const highlightCodeToTokens = (code, language, { theme } = {}) => {\n  const id = normalizeCodeLanguage(language);\n  const resolvedTheme = getHighlightTheme(id, theme);\n\n  if (resolvedTheme === undefined) {\n    return undefined;\n  }\n\n  const { tokens, fg = '' } = highlighter.codeToTokens(code, { lang: id, theme: resolvedTheme });\n\n  return tokens.map((/** @type {any[]} */ line) =>\n    line.map(({ content, color, fontStyle = 0 }) => {\n      /** @type {HighlightedToken} */\n      const token = { content };\n\n      if (color && color.toLowerCase() !== fg.toLowerCase()) {\n        token.color = color;\n      }\n\n      /* eslint-disable no-bitwise */\n      // Shiki’s `FontStyle` flags\n      if (fontStyle & 2) {\n        token.bold = true;\n      }\n\n      if (fontStyle & 4) {\n        token.underline = true;\n      }\n\n      if (fontStyle & 8) {\n        token.strikethrough = true;\n      }\n      /* eslint-enable no-bitwise */\n\n      return token;\n    }),\n  );\n};\n","/**\n * HTML of GitHub Flavored Markdown task lists, which Lexical calls check lists. They’re exported\n * the way GitHub and markdown-it render them, a `<ul class=\"contains-task-list\">` holding\n * `<li class=\"task-list-item\">` items that start with a disabled `<input type=\"checkbox\">`, which\n * Lexical imports back as a check list. The Markdown transformer is in\n * `../transformers/task-list.js`.\n */\n\nimport { $isListNode as isListNode } from '@lexical/list';\n\n/**\n * @import { ListItemNode, ListNode } from '@lexical/list';\n * @import { DOMConversion, DOMConversionMap, DOMConversionOutput } from 'lexical';\n */\n\n/**\n * Add the class of a task list to the exported element of a check list.\n * @param {ListNode} node List node.\n * @param {HTMLElement} element Exported element.\n */\nexport const decorateTaskList = (node, element) => {\n  if (node.getListType() === 'check') {\n    element.classList.add('contains-task-list');\n  }\n};\n\n/**\n * Add the class and a disabled check box to the exported element of a check list item. An item\n * that only holds a nested list has neither, as it’s merged into the previous item.\n * @param {ListItemNode} node List item node.\n * @param {HTMLElement} element Exported element.\n */\nexport const decorateTaskListItem = (node, element) => {\n  const parent = node.getParent();\n\n  if (!isListNode(parent) || parent.getListType() !== 'check' || isListNode(node.getFirstChild())) {\n    return;\n  }\n\n  const checkbox = element.ownerDocument.createElement('input');\n\n  checkbox.type = 'checkbox';\n  checkbox.disabled = true;\n  checkbox.toggleAttribute('checked', !!node.getChecked());\n  element.classList.add('task-list-item');\n  element.prepend(checkbox, ' ');\n};\n\n/**\n * Check whether the given element is the check box of a task list item, like the `<input>` in\n * `<li class=\"task-list-item\"><input type=\"checkbox\" disabled> Item</li>`. Lexical imports the\n * item as a check list item, taking its state from the first `<input>` in it.\n * @param {Element} element Element.\n * @returns {boolean} Result.\n */\nexport const isTaskListCheckbox = (element) =>\n  element.localName === 'input' &&\n  element.getAttribute('type')?.toLowerCase() === 'checkbox' &&\n  !!element.parentElement?.matches('li.task-list-item') &&\n  element.parentElement.querySelector(':scope > input') === element;\n\n/**\n * Drop an element without importing it.\n * @returns {DOMConversionOutput} Conversion output.\n */\nconst dropElement = () => ({ node: null });\n\n/**\n * Additional DOM conversions to import HTML with task lists. The check box of a task list item is\n * dropped, as Lexical has already taken its state for the item. Any other `<input>` is still\n * reported by `findUnsupportedNode()` in `unsupported.js`.\n * @type {DOMConversionMap}\n */\nexport const HTML_TASK_LIST_IMPORT_MAP = {\n  /**\n   * Get the conversion for an `<input>` element.\n   * @param {HTMLElement} element Element.\n   * @returns {DOMConversion | null} Conversion.\n   */\n  input: (element) =>\n    isTaskListCheckbox(element) ? { conversion: dropElement, priority: 1 } : null,\n};\n","/**\n * Helpers and constants shared by the HTML import and export.\n */\n\n/**\n * Check if the given node is within a `<pre>` element or an element with preformatted whitespace,\n * whose text is imported by Lexical’s own conversion as is.\n * @param {Node} node Node.\n * @returns {boolean} Result.\n */\nexport const isPreformatted = (node) => {\n  for (let element = node.parentElement; element; element = element.parentElement) {\n    if (element.localName === 'pre' || element.style.whiteSpace.startsWith('pre')) {\n      return true;\n    }\n  }\n\n  return false;\n};\n\n/**\n * Text formats and their HTML tags, from the innermost to the outermost.\n * @type {[import('lexical').TextFormatType, string][]}\n */\nexport const TEXT_FORMAT_TAGS = [\n  ['code', 'code'],\n  ['subscript', 'sub'],\n  ['superscript', 'sup'],\n  ['highlight', 'mark'],\n  ['underline', 'u'],\n  ['strikethrough', 's'],\n  ['italic', 'em'],\n  ['bold', 'strong'],\n];\n","/**\n * Splitting of an exported paragraph around the elements a paragraph can’t hold, like a figure,\n * which the HTML parser would otherwise move out of it.\n */\n\nimport { isDOMTextNode, isHTMLElement } from 'lexical';\nimport { isPreformatted, TEXT_FORMAT_TAGS } from './utils.js';\n\n/**\n * Elements a paragraph can’t hold: the HTML parser ends an open `<p>` before any of them.\n * @see https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inbody\n */\n// prettier-ignore\nconst PARAGRAPH_ENDING_TAGS = [\n  'address', 'article', 'aside', 'blockquote', 'center', 'dd', 'details', 'dialog', 'dir', 'div',\n  'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5',\n  'h6', 'header', 'hgroup', 'hr', 'li', 'listing', 'main', 'menu', 'nav', 'ol', 'p', 'plaintext',\n  'pre', 'search', 'section', 'summary', 'table', 'ul', 'xmp',\n];\n\n/**\n * Check whether the given node is an element a paragraph can’t hold, like a `<figure>`.\n * @param {Node} node Node.\n * @returns {boolean} Result.\n */\nconst isParagraphEndingElement = (node) =>\n  isHTMLElement(node) && PARAGRAPH_ENDING_TAGS.includes(node.localName);\n\n/**\n * Find the first or last text node within the given node, or the node itself if it’s a text node.\n * @param {Node | undefined} node Node.\n * @param {boolean} forward Whether to look for the first text node rather than the last.\n * @returns {Text | undefined} Text node, if any.\n */\nconst findEdgeTextNode = (node, forward) => {\n  let current = node ?? null;\n\n  while (current && !isDOMTextNode(current)) {\n    current = forward ? current.firstChild : current.lastChild;\n  }\n\n  return current ?? undefined;\n};\n\n/**\n * Names of the elements of the text formats, which hold nothing but text. See\n * {@link TEXT_FORMAT_TAGS}.\n */\nconst TEXT_FORMAT_TAG_NAMES = TEXT_FORMAT_TAGS.map(([, tagName]) => tagName);\n\n/**\n * Check whether the given node is blank: text with nothing but whitespace, or the element of a text\n * format, like `<strong>`, holding only such text. Any other element, like an image, a line break\n * or a link, is content, even without any text.\n * @param {Node} node Node.\n * @returns {boolean} Result.\n */\nconst isBlank = (node) =>\n  isDOMTextNode(node)\n    ? !node.data.trim()\n    : isHTMLElement(node) &&\n      TEXT_FORMAT_TAG_NAMES.includes(node.localName) &&\n      [...node.childNodes].every(isBlank);\n\n/**\n * Split the given exported paragraph around the elements it can’t hold, like the `<figure>` an\n * inline editor component exports for an image with a caption: the HTML parser would end the `<p>`\n * before the first one, leaving the content after it in an empty paragraph. The rest of the content\n * stays in copies of the paragraph, which keep its alignment, while the whitespace next to such an\n * element is dropped, as the parser collapses it at the start and end of a paragraph.\n * @param {HTMLElement} paragraph Exported paragraph element.\n * @returns {DocumentFragment | undefined} Paragraphs and elements to replace the paragraph with,\n * or `undefined` if it holds no such element.\n */\nexport const splitParagraphAroundBlocks = (paragraph) => {\n  const children = [...paragraph.childNodes];\n\n  if (!children.some(isParagraphEndingElement)) {\n    return undefined;\n  }\n\n  const fragment = document.createDocumentFragment();\n  /** @type {ChildNode[]} */\n  let run = [];\n\n  /**\n   * Add the content collected since the last block, if any, to the fragment in a new paragraph.\n   */\n  const flush = () => {\n    const first = findEdgeTextNode(run[0], true);\n    const last = findEdgeTextNode(run.at(-1), false);\n\n    // Preformatted whitespace is imported as is, so it’s kept as well\n    if (first && !isPreformatted(first)) {\n      first.data = first.data.trimStart();\n    }\n\n    if (last && !isPreformatted(last)) {\n      last.data = last.data.trimEnd();\n    }\n\n    if (!run.every(isBlank)) {\n      const newParagraph = /** @type {HTMLElement} */ (paragraph.cloneNode(false));\n\n      newParagraph.append(...run);\n      fragment.append(newParagraph);\n    }\n\n    run = [];\n  };\n\n  children.forEach((child) => {\n    if (isParagraphEndingElement(child)) {\n      flush();\n      fragment.append(child);\n    } else {\n      run.push(child);\n    }\n  });\n\n  flush();\n\n  return fragment;\n};\n","/**\n * Export of the editor content to clean HTML, without the attributes and elements only meant for\n * the editor.\n */\n\nimport { CodeHighlightNode, CodeNode } from '@lexical/code-core';\nimport { HorizontalRuleNode } from '@lexical/extension';\nimport { $generateHtmlFromNodes as generateHtmlFromNodes } from '@lexical/html';\nimport { LinkNode } from '@lexical/link';\nimport { ListItemNode, ListNode } from '@lexical/list';\nimport { HeadingNode, QuoteNode } from '@lexical/rich-text';\nimport { TableCellNode, TableNode } from '@lexical/table';\nimport {\n  $isParagraphNode as isParagraphNode,\n  isHTMLElement,\n  ParagraphNode,\n  TabNode,\n  TextNode,\n} from 'lexical';\nimport { isPlainLanguage } from '../../shiki/engine.js';\nimport { decorateTaskList, decorateTaskListItem } from './task-list.js';\nimport { splitParagraphAroundBlocks } from './paragraph.js';\nimport { TEXT_FORMAT_TAGS } from './utils.js';\n\n/**\n * @import {\n * DOMExportOutput,\n * DOMExportOutputMap,\n * ElementNode,\n * LexicalEditor,\n * } from 'lexical';\n */\n\n/**\n * Attributes to be kept on the exported elements, by tag name. Anything else Lexical adds, like\n * `class`, `dir`, `style`, `value` or `spellcheck`, is only meant for the editor itself, except for\n * the text alignment of a block; see {@link ALIGNABLE_TAGS}.\n * @type {Record<string, string[]>}\n */\nconst ALLOWED_ATTRIBUTES = {\n  a: ['href', 'rel', 'target', 'title'],\n  ol: ['start'],\n  td: ['colspan', 'rowspan'],\n  th: ['colspan', 'rowspan'],\n};\n\n/**\n * Elements that keep their text alignment, which is the only style kept in the exported HTML.\n * Lexical writes it as `style=\"text-align: …\"` for the blocks it can be set on.\n */\nconst ALIGNABLE_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'li'];\n\n/**\n * Remove the attributes not listed in {@link ALLOWED_ATTRIBUTES} from the given element, as well as\n * any style but the text alignment of a block listed in {@link ALIGNABLE_TAGS}.\n * @param {Element} element Element.\n */\nconst removeExtraAttributes = (element) => {\n  const allowedAttributes = ALLOWED_ATTRIBUTES[element.localName] ?? [];\n\n  const textAlign = ALIGNABLE_TAGS.includes(element.localName)\n    ? /** @type {HTMLElement} */ (element).style.textAlign\n    : '';\n\n  [...element.attributes].forEach(({ name }) => {\n    if (!allowedAttributes.includes(name)) {\n      element.removeAttribute(name);\n    }\n  });\n\n  if (textAlign) {\n    /** @type {HTMLElement} */ (element).style.textAlign = textAlign;\n  }\n};\n\n/**\n * Export an element node with Lexical’s own implementation, then remove the extra attributes from\n * the element, as well as the attribute Lexical adds to the `<br>` terminating a trailing line\n * break. The element’s own `after` function, if any, still runs first, so the structure is kept,\n * like a nested list moved into the previous list item.\n * @param {LexicalEditor} editor Editor instance.\n * @param {ElementNode} node Element node.\n * @returns {DOMExportOutput} Export output.\n */\nconst exportElementNode = (editor, node) => {\n  const { after, ...output } = node.exportDOM(editor);\n\n  if (isHTMLElement(output.element)) {\n    removeExtraAttributes(output.element);\n  }\n\n  return {\n    ...output,\n    /**\n     * Clean up the element once its children are in place.\n     * @param {HTMLElement | DocumentFragment | Text | null | undefined} element Exported element.\n     * @returns {HTMLElement | DocumentFragment | Text | null | undefined} New element to replace\n     * the exported one, if any.\n     */\n    after: (element) => {\n      const newElement = after ? after.call(node, element) : undefined;\n      const target = newElement ?? element;\n\n      if (isHTMLElement(target)) {\n        removeExtraAttributes(target);\n        target.querySelectorAll(':scope > br').forEach(removeExtraAttributes);\n      }\n\n      // Returning the same element would make Lexical replace it with itself\n      return newElement === element ? undefined : newElement;\n    },\n  };\n};\n\n/**\n * Export a paragraph node. Empty paragraphs at the end are left out, as they have no content; one\n * may be added just by clicking below a block decorator. A paragraph that is the only child of a\n * table cell is exported without the `<p>` element, unless it’s aligned. A paragraph holding\n * elements it can’t hold, like a `<figure>`, is split around them.\n * @param {LexicalEditor} editor Editor instance.\n * @param {ParagraphNode} node Paragraph node.\n * @returns {DOMExportOutput} Export output.\n */\nconst exportParagraphNode = (editor, node) => {\n  const parent = node.getParent();\n\n  // Keep the `<p>` of an aligned paragraph, which holds the alignment\n  if (parent instanceof TableCellNode && parent.getChildrenSize() === 1 && !node.getFormatType()) {\n    return { element: document.createDocumentFragment() };\n  }\n\n  if (\n    node.isEmpty() &&\n    node.getNextSiblings().every((sibling) => isParagraphNode(sibling) && sibling.isEmpty())\n  ) {\n    return { element: null };\n  }\n\n  const { after, ...output } = exportElementNode(editor, node);\n\n  return {\n    ...output,\n    /**\n     * Clean up the paragraph once its children are in place, and split it around the elements it\n     * can’t hold, if any.\n     * @param {HTMLElement | DocumentFragment | Text | null | undefined} element Exported element.\n     * @returns {HTMLElement | DocumentFragment | Text | null | undefined} New element to replace\n     * the exported one, if any.\n     */\n    after: (element) => {\n      const newElement = /** @type {NonNullable<DOMExportOutput['after']>} */ (after).call(\n        node,\n        element,\n      );\n\n      const target = newElement ?? element;\n\n      return (isHTMLElement(target) && splitParagraphAroundBlocks(target)) || newElement;\n    },\n  };\n};\n\n/**\n * Export a text node as plain text wrapped with the elements for its formats, instead of the\n * `<span>`, `<b>` and `<i>` elements with styles and classes Lexical uses.\n * @param {LexicalEditor} _editor Editor instance.\n * @param {TextNode} node Text node.\n * @returns {DOMExportOutput} Export output.\n */\nconst exportTextNode = (_editor, node) => {\n  /** @type {HTMLElement | Text} */\n  let element = document.createTextNode(node.getTextContent());\n\n  TEXT_FORMAT_TAGS.forEach(([format, tagName]) => {\n    if (node.hasFormat(format)) {\n      const wrapper = document.createElement(tagName);\n\n      wrapper.append(element);\n      element = wrapper;\n    }\n  });\n\n  return { element };\n};\n\n/**\n * Export a code block node as `<pre><code>` with the common `language-*` class, instead of the\n * highlighted tokens Lexical renders in the editor. The children are still exported as usual, so\n * copying part of a code block only exports the selected text, then their text is moved into the\n * `<code>` element.\n * @param {LexicalEditor} _editor Editor instance.\n * @param {CodeNode} node Code node.\n * @returns {DOMExportOutput} Export output.\n */\nconst exportCodeNode = (_editor, node) => ({\n  element: document.createElement('pre'),\n  /**\n   * Replace the exported children with a `<code>` element holding their text.\n   * @param {HTMLElement | DocumentFragment | Text | null | undefined} pre Exported element.\n   * @returns {undefined} Nothing, as the element is updated in place.\n   */\n  after: (pre) => {\n    /* v8 ignore next 3 */\n    if (!isHTMLElement(pre)) {\n      return undefined;\n    }\n\n    const code = document.createElement('code');\n    const language = node.getLanguage();\n\n    if (language && !isPlainLanguage(language)) {\n      code.className = `language-${language}`;\n    }\n\n    code.textContent = [...pre.childNodes]\n      .map((child) => {\n        if (child.nodeName !== 'BR') {\n          return child.textContent;\n        }\n\n        // Skip the `<br>` Lexical adds to terminate a trailing line break\n        return isHTMLElement(child) && child.hasAttribute('data-lexical-managed-linebreak')\n          ? ''\n          : '\\n';\n      })\n      .join('');\n\n    pre.replaceChildren(code);\n\n    return undefined;\n  },\n});\n\n/**\n * Selector for the structural elements of a table, excluding the cell content.\n */\nconst TABLE_STRUCTURE_SELECTOR = [\n  ':scope > :is(thead, tbody, tfoot)',\n  ':scope > :is(thead, tbody, tfoot) > tr',\n  ':scope > :is(thead, tbody, tfoot) > tr > :is(th, td)',\n  ':scope > tr',\n  ':scope > tr > :is(th, td)',\n].join(', ');\n\n/**\n * Export a table node, then remove the column definitions and extra attributes Lexical adds to the\n * table and its descendants. The cleanup has to wait until the table is complete, as Lexical uses\n * temporary attributes on the cells to compute the columns.\n * @param {LexicalEditor} editor Editor instance.\n * @param {TableNode} node Table node.\n * @returns {DOMExportOutput} Export output.\n */\nconst exportTableNode = (editor, node) => {\n  const { after, ...output } = node.exportDOM(editor);\n\n  return {\n    ...output,\n    /**\n     * Clean up the table once Lexical has completed it.\n     * @param {HTMLElement | DocumentFragment | Text | null | undefined} element Exported element.\n     * @returns {HTMLElement | DocumentFragment | Text | null | undefined} New element to replace\n     * the exported one, if any.\n     */\n    after: (element) => {\n      const newElement = after ? after.call(node, element) : undefined;\n      const target = newElement ?? element;\n\n      if (isHTMLElement(target)) {\n        target.querySelectorAll(':scope > colgroup').forEach((colgroup) => colgroup.remove());\n        // Leave the cell content alone, which has been cleaned up by its own nodes, while the\n        // content of an editor component may need its attributes\n        [target, ...target.querySelectorAll(TABLE_STRUCTURE_SELECTOR)].forEach(\n          removeExtraAttributes,\n        );\n      }\n\n      // Returning the same element would make Lexical replace it with itself\n      return newElement === element ? undefined : newElement;\n    },\n  };\n};\n\n/**\n * Export an element node with {@link exportElementNode}, then update the cleaned-up element with\n * the given function, like adding the classes and check boxes of a task list.\n * @param {LexicalEditor} editor Editor instance.\n * @param {ElementNode} node Element node.\n * @param {(element: HTMLElement) => void} decorate Function to update the exported element.\n * @returns {DOMExportOutput} Export output.\n */\nconst exportDecoratedElementNode = (editor, node, decorate) => {\n  const output = exportElementNode(editor, node);\n\n  return {\n    ...output,\n    /**\n     * Update the element once it’s been cleaned up.\n     * @param {HTMLElement | DocumentFragment | Text | null | undefined} element Exported element.\n     * @returns {HTMLElement | DocumentFragment | Text | null | undefined} New element, if any.\n     */\n    after: (element) => {\n      const newElement = output.after?.(element);\n      const target = newElement ?? element;\n\n      if (isHTMLElement(target)) {\n        decorate(target);\n      }\n\n      return newElement;\n    },\n  };\n};\n\n/**\n * Export a list node, adding the class of a task list to a check list.\n * @param {LexicalEditor} editor Editor instance.\n * @param {ListNode} node List node.\n * @returns {DOMExportOutput} Export output.\n */\nconst exportListNode = (editor, node) =>\n  exportDecoratedElementNode(editor, node, (element) => decorateTaskList(node, element));\n\n/**\n * Export a list item node, adding the class and a disabled check box to an item of a check list.\n * @param {LexicalEditor} editor Editor instance.\n * @param {ListItemNode} node List item node.\n * @returns {DOMExportOutput} Export output.\n */\nconst exportListItemNode = (editor, node) =>\n  exportDecoratedElementNode(editor, node, (element) => decorateTaskListItem(node, element));\n\n/**\n * Map of Lexical node classes and functions to export them to clean HTML. A class only takes effect\n * if the node is registered with the editor. Other nodes, including the ones of editor components,\n * are exported with their own `exportDOM` method.\n * @type {DOMExportOutputMap}\n */\nexport const HTML_EXPORT_MAP = new Map(\n  /** @type {[any, (editor: LexicalEditor, node: any) => DOMExportOutput][]} */ ([\n    [TextNode, exportTextNode],\n    [TabNode, exportTextNode],\n    [CodeHighlightNode, exportTextNode],\n    [ParagraphNode, exportParagraphNode],\n    [HeadingNode, exportElementNode],\n    [QuoteNode, exportElementNode],\n    [ListNode, exportListNode],\n    [ListItemNode, exportListItemNode],\n    [LinkNode, exportElementNode],\n    [HorizontalRuleNode, exportElementNode],\n    [CodeNode, exportCodeNode],\n    [TableNode, exportTableNode],\n  ]),\n);\n\n/**\n * Convert the editor content to HTML. Call this within an editor update or read.\n * @param {LexicalEditor} editor Editor instance.\n * @returns {string} HTML value.\n */\nexport const exportHtml = (editor) => generateHtmlFromNodes(editor);\n","/**\n * Editor components in HTML: the elements they import, which come with their content.\n */\n\nimport { $getEditor as getEditor } from 'lexical';\n\n/**\n * @import { DOMConversionMap, LexicalEditor } from 'lexical';\n * @import { TextEditorComponent } from '../../../../typedefs.js';\n */\n\n/**\n * Editor components of each editor, used to tell the elements they import, which come with their\n * content, when HTML is imported.\n * @type {WeakMap<LexicalEditor, TextEditorComponent[]>}\n */\nexport const editorComponents = new WeakMap();\n\n/**\n * Conversion maps of the editor component nodes, cached as each `importDOM()` call can create a new\n * map.\n * @type {WeakMap<any, DOMConversionMap>}\n */\nconst componentConversionMaps = new WeakMap();\n\n/**\n * Get the conversion map of the given editor component node.\n * @param {any} node Lexical node class.\n * @returns {DOMConversionMap} Conversion map.\n */\nexport const getComponentConversionMap = (node) => {\n  let map = componentConversionMaps.get(node);\n\n  if (!map) {\n    map = node.importDOM?.() ?? {};\n    componentConversionMaps.set(node, /** @type {DOMConversionMap} */ (map));\n  }\n\n  return /** @type {DOMConversionMap} */ (map);\n};\n\n/**\n * Editor component that imports each element, or `null` if none does, cached as the same element is\n * checked many times during an import, and a conversion can run developer code. An element is only\n * imported to one editor, as each import parses the HTML anew.\n * @type {WeakMap<Element, TextEditorComponent | null>}\n */\nconst elementComponents = new WeakMap();\n\n/**\n * Get the editor component that imports the given element, if any. The element’s content is then\n * part of the component.\n * @param {LexicalEditor} editor Editor instance.\n * @param {Element} element Element.\n * @returns {TextEditorComponent | undefined} Component.\n */\nexport const getElementComponent = (editor, element) => {\n  let component = elementComponents.get(element);\n\n  if (component === undefined) {\n    component =\n      editorComponents\n        .get(editor)\n        ?.find(\n          ({ node }) =>\n            !!getComponentConversionMap(node)[element.localName]?.(\n              /** @type {HTMLElement} */ (element),\n            ),\n        ) ?? null;\n    elementComponents.set(element, component);\n  }\n\n  return component ?? undefined;\n};\n\n/**\n * Check if the given element is imported by an inline editor component, like an image, which is\n * content in the line just like text.\n * @param {Element} element Element.\n * @returns {boolean} Result.\n */\nexport const isInlineComponentElement = (element) => {\n  const component = getElementComponent(getEditor(), element);\n\n  // The `node` is actually a node class\n  return !!component && !!(/** @type {any} */ (component.node).prototype.isInline?.());\n};\n","/**\n * Rules to import HTML: DOM conversions that take priority over Lexical’s own.\n */\n\nimport { $createCodeNode as createCodeNode } from '@lexical/code-core';\nimport {\n  $createTextNode as createTextNode,\n  isDOMTextNode,\n  isHTMLElement,\n  isInlineDomNode,\n} from 'lexical';\nimport { isInlineComponentElement } from './components.js';\nimport { isPreformatted } from './utils.js';\n\n/**\n * @import {\n * DOMConversion,\n * DOMConversionMap,\n * DOMConversionOutput,\n * LexicalNode,\n * } from 'lexical';\n */\n\n/**\n * Get the programming language from the `language-*` or `lang-*` class of the given `<code>`\n * element, which is common in HTML generated from Markdown.\n * @param {Element} code `<code>` element.\n * @returns {string | undefined} Language.\n */\nexport const getCodeLanguage = (code) =>\n  code.className.match(/(?:^|\\s)(?:lang|language)-(\\S+)/)?.[1];\n\n/**\n * Get the text content of the given element, with `<br>` elements as line breaks.\n * @param {Element} element Element.\n * @returns {string} Text.\n */\nconst getTextWithLineBreaks = (element) => {\n  const walker = document.createTreeWalker(element, NodeFilter.SHOW_ALL);\n  let text = '';\n\n  for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n    if (node.nodeType === Node.TEXT_NODE) {\n      text += /** @type {Text} */ (node).data;\n    } else if (node.nodeName === 'BR') {\n      text += '\\n';\n    }\n  }\n\n  return text;\n};\n\n/**\n * Convert a `<pre>` element to a code block node, taking the language from the `language-*` or\n * `lang-*` class of the `<code>` element within it, which is common in HTML generated from\n * Markdown, as well as the `data-language` attribute Lexical uses. The content is imported as plain\n * text, so any markup within it, like highlighted tokens, is dropped, while a `<br>` element\n * becomes a line break.\n * @param {HTMLElement} pre `<pre>` element.\n * @returns {DOMConversionOutput} Conversion output.\n */\nconst convertPreElement = (pre) => {\n  const code = pre.querySelector(':scope > code');\n  const language = (code ? getCodeLanguage(code) : undefined) ?? pre.getAttribute('data-language');\n  const node = createCodeNode(language);\n  // A code block generated from Markdown ends with a line break\n  const text = getTextWithLineBreaks(pre).replace(/\\n$/, '');\n\n  if (text) {\n    node.append(createTextNode(text));\n  }\n\n  return {\n    node,\n    /**\n     * Drop the child nodes, which are already imported as the text content.\n     * @returns {LexicalNode[]} Nodes.\n     */\n    after: () => [],\n  };\n};\n\n/**\n * Find the text or the inline editor component element next to the given text in the same line,\n * like Lexical’s own `findTextInLine()` does for text only. Without the component, Lexical takes an\n * element like an image for the end of the line, or skips it, and drops the space between it and\n * the text, e.g. `a <img> b` becomes `a<img>b`.\n * @param {Node} text Text node.\n * @param {boolean} forward Whether to search forward.\n * @returns {Text | Element | null} Text or element, or `null` if the line ends.\n */\nconst findContentInLine = (text, forward) => {\n  let node = text;\n\n  for (;;) {\n    let sibling = forward ? node.nextSibling : node.previousSibling;\n\n    while (!sibling) {\n      const { parentElement } = node;\n\n      if (!parentElement) {\n        return null;\n      }\n\n      node = parentElement;\n      sibling = forward ? node.nextSibling : node.previousSibling;\n    }\n\n    node = sibling;\n\n    if (isHTMLElement(node)) {\n      if (isInlineComponentElement(node)) {\n        return node;\n      }\n\n      const { display } = node.style;\n\n      if (display ? !display.startsWith('inline') : !isInlineDomNode(node)) {\n        return null;\n      }\n    }\n\n    let descendant = forward ? node.firstChild : node.lastChild;\n\n    while (descendant) {\n      node = descendant;\n\n      if (isHTMLElement(node) && isInlineComponentElement(node)) {\n        return node;\n      }\n\n      descendant = forward ? node.firstChild : node.lastChild;\n    }\n\n    if (isDOMTextNode(node)) {\n      return node;\n    }\n\n    if (node.nodeName === 'BR') {\n      return null;\n    }\n  }\n};\n\n/**\n * Convert a text node, collapsing whitespace like Lexical’s own conversion does, except that an\n * inline editor component element counts as content. See {@link findContentInLine}.\n * @param {Text} domNode Text node.\n * @returns {DOMConversionOutput} Conversion output.\n */\nconst convertTextNode = (domNode) => {\n  let textContent = domNode.data.replace(/\\r/g, '').replace(/[ \\t\\n]+/g, ' ');\n\n  if (textContent.startsWith(' ')) {\n    let previous = findContentInLine(domNode, false);\n    // Drop the space at the start of a line, or after another space\n    let drop = true;\n\n    for (; previous; previous = findContentInLine(previous, false)) {\n      if (!isDOMTextNode(previous)) {\n        drop = false;\n        break;\n      }\n\n      const previousText = previous.data;\n\n      // Skip empty text\n      if (previousText) {\n        drop = /[ \\t\\n]$/.test(previousText);\n        break;\n      }\n    }\n\n    if (drop) {\n      textContent = textContent.slice(1);\n    }\n  }\n\n  if (textContent.endsWith(' ')) {\n    let next = findContentInLine(domNode, true);\n    let isEndOfLine = true;\n\n    // Skip any text that only has whitespace, which is dropped as well\n    for (; next; next = findContentInLine(next, true)) {\n      if (!isDOMTextNode(next) || next.data.replace(/^[ \\t\\n]+/, '')) {\n        isEndOfLine = false;\n        break;\n      }\n    }\n\n    if (isEndOfLine) {\n      textContent = textContent.slice(0, -1);\n    }\n  }\n\n  return { node: textContent ? createTextNode(textContent) : null };\n};\n\n/**\n * Additional DOM conversions to import HTML. They take priority over Lexical’s own conversions.\n * @type {DOMConversionMap}\n */\nexport const HTML_IMPORT_MAP = {\n  /**\n   * Get the conversion for a text node, unless it’s preformatted, which Lexical’s own conversion\n   * handles.\n   * @param {Node} node Text node.\n   * @returns {DOMConversion | null} Conversion.\n   */\n  '#text': (node) =>\n    isPreformatted(node)\n      ? null\n      : {\n          /**\n           * Convert the text node.\n           * @param {Node} domNode Text node.\n           * @returns {DOMConversionOutput} Conversion output.\n           */\n          conversion: (domNode) => convertTextNode(/** @type {Text} */ (domNode)),\n          priority: 1,\n        },\n};\n\n/**\n * Additional DOM conversions to import HTML with code blocks.\n * @type {DOMConversionMap}\n */\nexport const HTML_CODE_IMPORT_MAP = {\n  /**\n   * Get the conversion for a `<pre>` element.\n   * @returns {DOMConversion} Conversion.\n   */\n  pre: () => ({ conversion: convertPreElement, priority: 2 }),\n};\n","/**\n * Detection of HTML the rich text editor can’t import, which can then only be edited as source.\n */\n\nimport { isTaskListCheckbox } from './task-list.js';\nimport { editorComponents, getComponentConversionMap, getElementComponent } from './components.js';\n\n/**\n * @import { LexicalEditor } from 'lexical';\n */\n\n/**\n * Table elements that have no Lexical node of their own. The rows are imported as is, while the\n * column definitions are only used for the column widths.\n */\nconst PASSTHROUGH_TAGS = ['tbody', 'thead', 'tfoot', 'colgroup', 'col'];\n/**\n * Elements the HTML parser always creates, which hold the content rather than being part of it.\n */\nconst DOCUMENT_TAGS = ['html', 'head', 'body'];\n\n/**\n * Get the names of the elements only editor components import, which no other node handles.\n * @param {LexicalEditor} editor Editor instance.\n * @returns {Set<string>} Tag names.\n */\nconst getComponentOnlyTagNames = (editor) => {\n  const components = editorComponents.get(editor) ?? [];\n  // The `node` is actually a node class\n  const componentNodes = new Set(components.map(({ node }) => /** @type {any} */ (node)));\n\n  const otherTagNames = new Set(\n    [...editor._nodes.values()]\n      .filter(({ klass }) => !componentNodes.has(klass))\n      .flatMap(({ klass }) => Object.keys(klass.importDOM?.() ?? {})),\n  );\n\n  return new Set(\n    components\n      .flatMap(({ node }) => Object.keys(getComponentConversionMap(node)))\n      .filter((tagName) => !otherTagNames.has(tagName)),\n  );\n};\n\n/**\n * Get the first node in the given document that the editor cannot import, which would be silently\n * dropped, possibly along with its content:\n *\n * - An element none of the registered nodes, including the ones of editor components, handle. This\n * includes an element the parser moves to `<head>`, like a `<script>` at the beginning, and an\n * element only editor components handle, but none of them imports, like a `<figure>` that isn’t an\n * instance of a component for `<figure class=\"photo\">`, which would be unwrapped.\n * - A comment, like `<!-- more -->`.\n *\n * The content of an element an editor component imports is part of the component, which is\n * expected to drop the children, and the elements within a `<pre>` element are imported as plain\n * text, so they’re ignored.\n * @param {LexicalEditor} editor Editor instance.\n * @param {Document} dom Parsed document.\n * @returns {Element | Comment | undefined} Unsupported node.\n */\nexport const findUnsupportedNode = (editor, dom) => {\n  const componentOnlyTagNames = getComponentOnlyTagNames(editor);\n\n  /**\n   * Find an unsupported node among the descendants of the given node.\n   * @param {Node} parent Parent node.\n   * @returns {Element | Comment | undefined} Unsupported node.\n   */\n  const findWithin = (parent) => {\n    /** @type {Element | Comment | undefined} */\n    let found;\n\n    [...parent.childNodes].some((node) => {\n      if (node.nodeType === Node.COMMENT_NODE) {\n        found = /** @type {Comment} */ (node);\n\n        return true;\n      }\n\n      if (node.nodeType !== Node.ELEMENT_NODE) {\n        return false;\n      }\n\n      const element = /** @type {Element} */ (node);\n      const tagName = element.localName;\n\n      if (getElementComponent(editor, element)) {\n        return false;\n      }\n\n      // `_htmlConversions` holds the conversions of all the registered nodes, along with the ones\n      // in the `html.import` editor config. A conversion may still skip an element on purpose,\n      // like a `<br>` at the end of a paragraph, which browsers don’t render\n      if (\n        !DOCUMENT_TAGS.includes(tagName) &&\n        !PASSTHROUGH_TAGS.includes(tagName) &&\n        (!editor._htmlConversions.has(tagName) ||\n          componentOnlyTagNames.has(tagName) ||\n          // Only the check box of a task list item can be imported\n          (tagName === 'input' && !isTaskListCheckbox(element)))\n      ) {\n        found = element;\n\n        return true;\n      }\n\n      found =\n        tagName === 'pre'\n          ? /** @type {Comment | undefined} */ (\n              dom.createTreeWalker(element, NodeFilter.SHOW_COMMENT).nextNode() ?? undefined\n            )\n          : findWithin(element);\n\n      return !!found;\n    });\n\n    return found;\n  };\n\n  return findWithin(dom);\n};\n","/**\n * HTML import and export of the rich text editor.\n */\n\nimport { exportHtml, HTML_EXPORT_MAP } from './export.js';\nimport { getCodeLanguage, HTML_CODE_IMPORT_MAP, HTML_IMPORT_MAP } from './import-rules.js';\nimport { HTML_TASK_LIST_IMPORT_MAP } from './task-list.js';\n\n/**\n * @import { HTMLConfig } from 'lexical';\n */\n\nexport { editorComponents } from './components.js';\nexport { findUnsupportedNode } from './unsupported.js';\nexport { exportHtml, getCodeLanguage };\n\n/**\n * Get the HTML configuration of an editor for the HTML format: the export map, which also applies\n * to copying, to export clean HTML without the attributes and elements only meant for the editor,\n * and the import rules for the enabled features, like code blocks with their language.\n * @param {object} features Enabled features.\n * @param {boolean} features.hasCodeBlock Whether code blocks are supported.\n * @param {boolean} features.hasTaskList Whether task lists are supported.\n * @returns {HTMLConfig} Configuration.\n */\nexport const getHtmlConfig = ({ hasCodeBlock, hasTaskList }) => ({\n  export: HTML_EXPORT_MAP,\n  import: {\n    ...HTML_IMPORT_MAP,\n    ...(hasCodeBlock ? HTML_CODE_IMPORT_MAP : {}),\n    ...(hasTaskList ? HTML_TASK_LIST_IMPORT_MAP : {}),\n  },\n});\n","/**\n * Lexical glue for the Shiki engine: turning tokens into code highlight nodes, and refreshing code\n * nodes once an async load has completed.\n *\n * Adapted from Lexical’s `FacadeShiki.ts` (MIT licensed).\n * @see https://github.com/facebook/lexical/tree/v0.50.0/packages/lexical-code-shiki\n */\n\nimport {\n  $isCodeNode as isCodeNode,\n  $createCodeHighlightNode as createCodeHighlightNode,\n} from '@lexical/code-core';\nimport {\n  $createLineBreakNode as createLineBreakNode,\n  $createTabNode as createTabNode,\n  $getNodeByKey as getNodeByKey,\n  HISTORY_MERGE_TAG,\n  tokenizeRawText,\n} from 'lexical';\nimport { getBackgroundUpdateTags } from '../background-update.js';\nimport { getTokenStyle, isCodeLanguageLoaded, tokenizeCode } from './engine.js';\n\n/**\n * @import { CodeNode } from '@lexical/code-core';\n * @import { LexicalEditor, LexicalNode, NodeKey } from 'lexical';\n */\n\n/**\n * Mark a code node dirty so the highlighting transform runs again once an async load has completed.\n * @param {LexicalEditor} editor Editor instance.\n * @param {NodeKey} codeNodeKey Key of the code node to refresh.\n */\nconst refreshCodeNode = (editor, codeNodeKey) => {\n  editor.update(\n    () => {\n      const codeNode = getNodeByKey(codeNodeKey);\n\n      if (!isCodeNode(codeNode)) {\n        return;\n      }\n\n      const language = codeNode.getLanguage();\n\n      if (language && isCodeLanguageLoaded(language) && !codeNode.getIsSyntaxHighlightSupported()) {\n        codeNode.setIsSyntaxHighlightSupported(true);\n      }\n\n      codeNode.markDirty();\n    },\n    { tag: getBackgroundUpdateTags(editor, [HISTORY_MERGE_TAG]) },\n  );\n};\n\n/**\n * Refresh callbacks created so far, per editor and code node.\n * @type {WeakMap<LexicalEditor, Map<NodeKey, () => void>>}\n */\nconst refreshers = new WeakMap();\n\n/**\n * Get a function that refreshes the given code node, to pass to the engine’s loaders as the\n * `onLoaded` callback. The same function is returned for the same node, so the engine calls it once\n * per load, however many keystrokes have asked for that load while it was in flight.\n * @param {LexicalEditor} editor Editor instance.\n * @param {NodeKey} codeNodeKey Key of the code node to refresh.\n * @returns {() => void} Refresh function.\n */\nexport const getCodeNodeRefresher = (editor, codeNodeKey) => {\n  let map = refreshers.get(editor);\n\n  if (!map) {\n    map = new Map();\n    refreshers.set(editor, map);\n  }\n\n  let refresher = map.get(codeNodeKey);\n\n  if (!refresher) {\n    /** Refresh the code node. */\n    refresher = () => {\n      refreshCodeNode(editor, codeNodeKey);\n    };\n\n    map.set(codeNodeKey, refresher);\n  }\n\n  return refresher;\n};\n\n/**\n * Convert Shiki tokens to Lexical nodes.\n * @param {any[][]} tokens Tokens, one array per line.\n * @param {boolean} diff Whether the language is a `diff-*` language.\n * @returns {LexicalNode[]} Lexical nodes.\n */\nconst mapTokensToLexicalStructure = (tokens, diff) => {\n  /** @type {LexicalNode[]} */\n  const nodes = [];\n\n  tokens.forEach((line, lineIndex) => {\n    if (lineIndex) {\n      nodes.push(createLineBreakNode());\n    }\n\n    line.forEach((token, tokenIndex) => {\n      let { content: text } = token;\n\n      // Implement `diff-*` languages\n      if (diff && tokenIndex === 0 && text.length > 0) {\n        const prefixes = ['+', '-', '>', '<', ' '];\n        const prefixTypes = ['inserted', 'deleted', 'inserted', 'deleted', 'unchanged'];\n        const prefixIndex = prefixes.indexOf(text[0]);\n\n        if (prefixIndex !== -1) {\n          nodes.push(createCodeHighlightNode(prefixes[prefixIndex], prefixTypes[prefixIndex]));\n          text = text.slice(1);\n        }\n      }\n\n      const style = getTokenStyle(token);\n\n      tokenizeRawText(text, {\n        /**\n         * Append a line break node.\n         * @returns {number} New node count.\n         */\n        linebreak: () => nodes.push(createLineBreakNode()),\n        /**\n         * Append a tab node.\n         * @returns {number} New node count.\n         */\n        tab: () => nodes.push(createTabNode()),\n        /**\n         * Create a highlight node carrying the token’s colour.\n         * @param {string} part Text fragment.\n         */\n        text: (part) => {\n          const node = createCodeHighlightNode(part);\n\n          node.setStyle(style);\n          nodes.push(node);\n        },\n      });\n    });\n  });\n\n  return nodes;\n};\n\n/**\n * Tokenize a code node’s content into Lexical nodes.\n *\n * Unlike upstream, the theme’s background and foreground colours are not copied onto the code node.\n * The block’s own colours come from `--sui-code-background-color` so that plain and highlighted\n * blocks look alike and follow the app’s theme rather than Shiki’s; only the per-token colours are\n * taken from the theme.\n * @param {CodeNode} codeNode Code node to tokenize.\n * @param {string} language Language identifier.\n * @returns {LexicalNode[]} Lexical nodes.\n */\nexport const getHighlightNodes = (codeNode, language) => {\n  const { tokens, diff } = tokenizeCode(codeNode.getTextContent(), language, codeNode.getTheme());\n\n  return mapTokensToLexicalStructure(tokens, diff);\n};\n","/**\n * Lexical node transforms that keep code blocks syntax highlighted.\n *\n * Adapted from Lexical’s `CodeHighlighterShiki.ts` (MIT licensed). The transform logic is copied\n * as-is; only the highlighting back end differs, because upstream imports its Shiki facade directly\n * and offers no way to substitute one that loads grammars on demand.\n * @see https://github.com/facebook/lexical/blob/v0.50.0/packages/lexical-code-shiki/src/CodeHighlighterShiki.ts\n * @see https://github.com/sveltia/sveltia-cms/issues/587\n *\n * The extension APIs (`CodeShikiExtension`, `CodeHighlighterShikiExtension`) are intentionally left\n * out, since this library registers the transforms directly.\n */\n\nimport {\n  CodeHighlightNode,\n  CodeNode,\n  DEFAULT_CODE_LANGUAGE,\n  $isCodeHighlightNode as isCodeHighlightNode,\n  $isCodeNode as isCodeNode,\n  $plainifyCodeContent as plainifyCodeContent,\n  registerCodeIndentation,\n} from '@lexical/code-core';\nimport { mergeRegister } from '@lexical/utils';\nimport {\n  $createTextNode as createTextNode,\n  $getNodeByKey as getNodeByKey,\n  $getSelection as getSelection,\n  $isLineBreakNode as isLineBreakNode,\n  $isRangeSelection as isRangeSelection,\n  $isTabNode as isTabNode,\n  $isTextNode as isTextNode,\n  $onUpdate as onUpdate,\n  HISTORY_MERGE_TAG,\n  TextNode,\n} from 'lexical';\nimport { getBackgroundUpdateTags } from '../background-update.js';\nimport {\n  isCodeLanguageLoaded,\n  isCodeThemeLoaded,\n  isEngineLoaded,\n  isEngineUnavailable,\n  isPlainLanguage,\n  loadCodeLanguage,\n  loadCodeTheme,\n  loadEngine,\n} from './engine.js';\nimport { getCodeNodeRefresher, getHighlightNodes } from './lexical.js';\nimport { CODE_THEME_LIGHT } from './theme.js';\n\n/**\n * @import { CodeNode as CodeNodeType } from '@lexical/code-core';\n * @import { LexicalEditor, LexicalNode, NodeKey } from 'lexical';\n * @import { CodeTokenizer, CodeTransformState } from '../../../typedefs.js';\n */\n\n/**\n * Default tokenizer backed by Shiki.\n *\n * Falls back to unhighlighted text whenever highlighting is impossible — a plain language, or an\n * engine that has not loaded yet or could not be fetched — so a code block always renders.\n * @type {CodeTokenizer}\n */\nexport const shikiTokenizer = {\n  defaultLanguage: DEFAULT_CODE_LANGUAGE,\n  defaultTheme: CODE_THEME_LIGHT,\n  /**\n   * Convert a code node’s content into Lexical nodes.\n   * @param {CodeNodeType} codeNode Code node to tokenize.\n   * @param {string} [language] Language identifier.\n   * @returns {LexicalNode[]} Lexical nodes.\n   */\n  tokenize(codeNode, language) {\n    const lang = language || this.defaultLanguage;\n\n    if (lang === null || isPlainLanguage(lang) || !isEngineLoaded()) {\n      return plainifyCodeContent(codeNode.getTextContent());\n    }\n\n    return getHighlightNodes(codeNode, lang);\n  },\n};\n\n/**\n * Update the line number gutter of a code block.\n * @param {CodeNodeType} node Code node.\n * @param {LexicalEditor} editor Editor instance.\n */\nconst updateCodeGutter = (node, editor) => {\n  const codeElement = editor.getElementByKey(node.getKey());\n\n  if (codeElement === null) {\n    return;\n  }\n\n  const children = node.getChildren();\n  const childrenLength = children.length;\n\n  // @ts-ignore Internal field\n  if (childrenLength === codeElement.__cachedChildrenLength) {\n    // Avoid updating the attribute if the children length hasn’t changed\n    return;\n  }\n\n  // @ts-ignore Internal field\n  codeElement.__cachedChildrenLength = childrenLength;\n\n  let gutter = '1';\n  let count = 1;\n\n  for (let i = 0; i < childrenLength; i += 1) {\n    if (isLineBreakNode(children[i])) {\n      count += 1;\n      gutter += `\\n${count}`;\n    }\n  }\n\n  codeElement.setAttribute('data-gutter', gutter);\n};\n\n/**\n * Compare two nodes for the purpose of diffing highlight output. Only code highlight nodes, tabs\n * and line breaks are considered equal; a regular text node always compares unequal so that it gets\n * transformed into a code highlight node.\n * @param {LexicalNode} nodeA First node.\n * @param {LexicalNode} nodeB Second node.\n * @returns {boolean} Result.\n */\nconst isEqual = (nodeA, nodeB) =>\n  (isCodeHighlightNode(nodeA) &&\n    isCodeHighlightNode(nodeB) &&\n    // @ts-ignore Internal fields\n    nodeA.__text === nodeB.__text &&\n    // @ts-ignore Internal fields\n    nodeA.__highlightType === nodeB.__highlightType &&\n    // @ts-ignore Internal fields\n    nodeA.__style === nodeB.__style) ||\n  (isTabNode(nodeA) && isTabNode(nodeB)) ||\n  (isLineBreakNode(nodeA) && isLineBreakNode(nodeB));\n\n/**\n * Find the minimal diff range between two node lists.\n * @param {LexicalNode[]} prevNodes Current nodes.\n * @param {LexicalNode[]} nextNodes Desired nodes.\n * @returns {{ from: number, to: number, nodesForReplacement: LexicalNode[] }} Boundaries of\n * `prevNodes` to replace, and the replacement nodes.\n */\nconst getDiffRange = (prevNodes, nextNodes) => {\n  let leadingMatch = 0;\n\n  while (leadingMatch < prevNodes.length) {\n    if (!isEqual(prevNodes[leadingMatch], nextNodes[leadingMatch])) {\n      break;\n    }\n\n    leadingMatch += 1;\n  }\n\n  const prevNodesLength = prevNodes.length;\n  const nextNodesLength = nextNodes.length;\n  const maxTrailingMatch = Math.min(prevNodesLength, nextNodesLength) - leadingMatch;\n  let trailingMatch = 0;\n\n  while (trailingMatch < maxTrailingMatch) {\n    trailingMatch += 1;\n\n    if (\n      !isEqual(\n        prevNodes[prevNodesLength - trailingMatch],\n        nextNodes[nextNodesLength - trailingMatch],\n      )\n    ) {\n      trailingMatch -= 1;\n      break;\n    }\n  }\n\n  return {\n    from: leadingMatch,\n    to: prevNodesLength - trailingMatch,\n    nodesForReplacement: nextNodes.slice(leadingMatch, nextNodesLength - trailingMatch),\n  };\n};\n\n/**\n * Run an update while trying to keep the cursor where it was.\n * @param {NodeKey} nodeKey Key of the code node being updated.\n * @param {() => boolean} updateFn Update to run. Should return whether anything changed.\n */\nconst updateAndRetainSelection = (nodeKey, updateFn) => {\n  const node = getNodeByKey(nodeKey);\n\n  // Unreachable in practice, since Lexical only runs transforms on attached nodes\n  /* v8 ignore next */\n  if (!isCodeNode(node) || !node.isAttached()) {\n    return;\n  }\n\n  const selection = getSelection();\n\n  // If it’s not a range selection there’s no need to change it, but we can still run the\n  // highlighting logic\n  if (!isRangeSelection(selection)) {\n    updateFn();\n\n    return;\n  }\n\n  const { anchor } = selection;\n  // The selection is restored by walking this code node’s children, so it can only be retained when\n  // it actually points inside this code node. When the selection lives elsewhere there is nothing\n  // to retain, and restoring would drag the caret into the code block instead of leaving it where\n  // the user put it.\n  const anchorNode = anchor.getNode();\n\n  if (anchorNode !== node && !node.isParentOf(anchorNode)) {\n    updateFn();\n\n    return;\n  }\n\n  const anchorOffset = anchor.offset;\n\n  const isNewLineAnchor =\n    anchor.type === 'element' && isLineBreakNode(node.getChildAtIndex(anchor.offset - 1));\n\n  let textOffset = 0;\n\n  // Calculate the previous text offset: all text nodes prior to the anchor, plus the anchor’s own\n  // text offset\n  if (!isNewLineAnchor) {\n    textOffset =\n      anchorOffset +\n      anchorNode\n        .getPreviousSiblings()\n        .reduce((offset, node_) => offset + node_.getTextContentSize(), 0);\n  }\n\n  if (!updateFn()) {\n    return;\n  }\n\n  // Non-text anchors only happen for line breaks, otherwise the selection will be within a text\n  // node\n  if (isNewLineAnchor) {\n    anchor.getNode().select(anchorOffset, anchorOffset);\n\n    return;\n  }\n\n  // If it was a non-element anchor, walk through the child nodes looking for the position of the\n  // original text offset. A line break node consumes one unit of the offset but cannot host a text\n  // point, so when the offset lands on one, use an element point on the code node instead of\n  // letting the offset go negative and selecting the next text node at an out-of-range position.\n  // A code node holds nothing but text, tab and line break nodes, so there is no third case.\n  const children = node.getChildren();\n\n  for (let index = 0; index < children.length; index += 1) {\n    const child = children[index];\n\n    if (isTextNode(child)) {\n      const textContentSize = child.getTextContentSize();\n\n      if (textContentSize >= textOffset) {\n        child.select(textOffset, textOffset);\n\n        return;\n      }\n\n      textOffset -= textContentSize;\n    } else /* v8 ignore else */ if (isLineBreakNode(child)) {\n      if (textOffset === 0) {\n        node.select(index, index);\n\n        return;\n      }\n\n      textOffset -= 1;\n    }\n  }\n\n  node.select(children.length, children.length);\n};\n\n/**\n * Re-highlight a code node.\n * @param {LexicalEditor} editor Editor instance.\n * @param {CodeTokenizer} tokenizer Tokenizer.\n * @param {CodeTransformState} transformState Shared transform state.\n * @param {CodeNodeType} node Code node to transform.\n */\nconst codeNodeTransform = (editor, tokenizer, transformState, node) => {\n  const nodeKey = node.getKey();\n  const { nodesCurrentlyHighlighting } = transformState;\n  // A newly inserted code block might not have a language yet. A tokenizer configured with\n  // `defaultLanguage: null` opts out of the implicit fallback, so that Markdown round-trips ```\n  // with no info string.\n  let language = node.getLanguage();\n\n  if (!language && tokenizer.defaultLanguage !== null) {\n    language = tokenizer.defaultLanguage;\n    node.setLanguage(language);\n  }\n\n  let theme = node.getTheme();\n\n  if (!theme) {\n    theme = tokenizer.defaultTheme;\n    node.setTheme(theme);\n  }\n\n  // Plain text needs no engine, grammar or theme, so it is highlighted — that is, rendered verbatim\n  // — without a single network request. This is the common case: it is the default for a new block.\n  const isPlain = !language || isPlainLanguage(language);\n  let inFlight = false;\n\n  // `!language` is redundant with `isPlain`, but it lets the type checker narrow `language` to a\n  // string in the branches below\n  if (isPlain || !language || isEngineUnavailable()) {\n    if (node.getIsSyntaxHighlightSupported()) {\n      node.setIsSyntaxHighlightSupported(false);\n    }\n  } else if (!isEngineLoaded()) {\n    // Dynamic load of the engine itself\n    loadEngine(getCodeNodeRefresher(editor, nodeKey));\n    inFlight = true;\n  } else {\n    // Dynamic load of themes\n    if (!isCodeThemeLoaded(theme)) {\n      loadCodeTheme(theme, getCodeNodeRefresher(editor, nodeKey));\n      inFlight = true;\n    }\n\n    // Dynamic load of languages\n    if (isCodeLanguageLoaded(language)) {\n      if (!node.getIsSyntaxHighlightSupported()) {\n        node.setIsSyntaxHighlightSupported(true);\n      }\n    } else {\n      const loadingTask = loadCodeLanguage(language, getCodeNodeRefresher(editor, nodeKey));\n\n      // If the language is not supported, no download will occur\n      if (!loadingTask && node.getIsSyntaxHighlightSupported()) {\n        node.setIsSyntaxHighlightSupported(false);\n      }\n\n      inFlight = true;\n    }\n  }\n\n  if (inFlight) {\n    return;\n  }\n\n  if (nodesCurrentlyHighlighting.has(nodeKey)) {\n    // Upstream drops this edit, which loses the last keystroke of a fast burst. Schedule one\n    // re-highlight for after the in-progress pass settles instead, deduplicated per node so a\n    // burst does not queue an update each.\n    if (!transformState.pendingRefresh.has(nodeKey)) {\n      transformState.pendingRefresh.add(nodeKey);\n\n      onUpdate(() => {\n        transformState.pendingRefresh.delete(nodeKey);\n\n        editor.update(\n          () => {\n            const staleNode = getNodeByKey(nodeKey);\n\n            if (isCodeNode(staleNode)) {\n              staleNode.markDirty();\n            }\n          },\n          { tag: getBackgroundUpdateTags(editor, [HISTORY_MERGE_TAG]) },\n        );\n      });\n    }\n\n    return;\n  }\n\n  nodesCurrentlyHighlighting.add(nodeKey);\n\n  if (!transformState.didTransform) {\n    transformState.didTransform = true;\n\n    onUpdate(() => {\n      transformState.didTransform = false;\n      nodesCurrentlyHighlighting.clear();\n    });\n  }\n\n  updateAndRetainSelection(nodeKey, () => {\n    const currentNode = getNodeByKey(nodeKey);\n\n    // Unreachable in practice, since the update runs synchronously on a node just checked above\n    /* v8 ignore next */\n    if (!isCodeNode(currentNode) || !currentNode.isAttached()) {\n      return false;\n    }\n\n    const lang = currentNode.getLanguage() || tokenizer.defaultLanguage;\n    const highlightNodes = tokenizer.tokenize(currentNode, lang ?? undefined);\n\n    const { from, to, nodesForReplacement } = getDiffRange(\n      currentNode.getChildren(),\n      highlightNodes,\n    );\n\n    if (from !== to || nodesForReplacement.length) {\n      node.splice(from, to - from, nodesForReplacement);\n\n      return true;\n    }\n\n    return false;\n  });\n};\n\n/**\n * Re-highlight the code block a text node belongs to.\n * @param {LexicalEditor} editor Editor instance.\n * @param {CodeTokenizer} tokenizer Tokenizer.\n * @param {CodeTransformState} transformState Shared transform state.\n * @param {TextNode} node Text node that changed.\n */\nconst textNodeTransform = (editor, tokenizer, transformState, node) => {\n  // `CodeNode` has a flat children structure, so we only need to check whether the node’s parent is\n  // a code node and run highlighting if so\n  const parentNode = node.getParent();\n\n  if (isCodeNode(parentNode)) {\n    codeNodeTransform(editor, tokenizer, transformState, parentNode);\n  } else if (isCodeHighlightNode(node)) {\n    // When a code block is converted into a paragraph or other element, code highlight nodes are\n    // converted back to normal text\n    // @ts-ignore Internal field\n    node.replace(createTextNode(node.__text));\n  }\n};\n\n/**\n * Register syntax highlighting, along with the indentation and arrow key handlers.\n * @param {LexicalEditor} editor Editor instance.\n * @param {CodeTokenizer} [tokenizer] Tokenizer to use.\n * @returns {() => void} Cleanup function.\n * @throws {Error} When the required nodes are not registered on the editor.\n */\nexport const registerCodeHighlighting = (editor, tokenizer = shikiTokenizer) => {\n  if (!editor.hasNodes([CodeNode, CodeHighlightNode])) {\n    throw new Error('CodeNode or CodeHighlightNode not registered on editor');\n  }\n\n  /** @type {Array<() => void>} */\n  const registrations = [];\n\n  // Only register the mutation listener if not in headless mode\n  if (editor._headless !== true) {\n    registrations.push(\n      editor.registerMutationListener(\n        CodeNode,\n        (mutations) => {\n          editor.read('latest', () => {\n            mutations.forEach((type, key) => {\n              if (type !== 'destroyed') {\n                const node = getNodeByKey(key);\n\n                if (node !== null) {\n                  updateCodeGutter(/** @type {CodeNodeType} */ (node), editor);\n                }\n              }\n            });\n          });\n        },\n        { skipInitialization: false },\n      ),\n    );\n  }\n\n  /** @type {CodeTransformState} */\n  const transformState = {\n    didTransform: false,\n    nodesCurrentlyHighlighting: new Set(),\n    pendingRefresh: new Set(),\n  };\n\n  registrations.push(\n    editor.registerNodeTransform(\n      CodeNode,\n      codeNodeTransform.bind(null, editor, tokenizer, transformState),\n    ),\n    editor.registerNodeTransform(\n      TextNode,\n      textNodeTransform.bind(null, editor, tokenizer, transformState),\n    ),\n    editor.registerNodeTransform(\n      CodeHighlightNode,\n      textNodeTransform.bind(null, editor, tokenizer, transformState),\n    ),\n    registerCodeIndentation(editor),\n  );\n\n  return mergeRegister(...registrations);\n};\n","// Adopted from https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/plugins/MarkdownTransformers/index.ts\n\n/* eslint-disable jsdoc/require-jsdoc */\n\nimport {\n  $createHorizontalRuleNode as createHorizontalRuleNode,\n  HorizontalRuleNode,\n  $isHorizontalRuleNode as isHorizontalRuleNode,\n} from '@lexical/extension';\n\n/**\n * @import { ElementTransformer } from '@lexical/markdown';\n */\n\n/**\n * Markdown of a horizontal rule. Unlike `---`, it can’t be taken for the underline of a setext\n * heading or the delimiter of front matter.\n */\nexport const HORIZONTAL_RULE_MARKDOWN = '***';\n\n/**\n * @type {ElementTransformer}\n */\nexport const HR = {\n  dependencies: [HorizontalRuleNode],\n  export: (node) => (isHorizontalRuleNode(node) ? HORIZONTAL_RULE_MARKDOWN : null),\n  regExp: /^(---|\\*\\*\\*|___)\\s?$/,\n  replace: (parentNode, _1, _2, isImport) => {\n    const line = createHorizontalRuleNode();\n\n    if (isImport || parentNode.getNextSibling() !== null) {\n      parentNode.replace(line);\n    } else {\n      parentNode.insertBefore(line);\n    }\n\n    // A pasted rule is created in a detached container, where there’s nothing to select\n    if (line.isAttached()) {\n      line.selectNext();\n    }\n  },\n  type: 'element',\n};\n","import { $getState as getState, $setState as setState, createState } from 'lexical';\n\nimport {\n  ATX_HEADING_MARKER,\n  AUTOLINK_REGEX,\n  CODE_FENCE,\n  FOOTNOTE_REFERENCE_REGEX,\n  INLINE_HTML_REGEX,\n  LIST_MARKER,\n  MARKER_END,\n  NAMED_CHARACTER_REFERENCE_REGEX,\n  SETEXT_UNDERLINE,\n  THEMATIC_BREAK,\n} from '../markdown/syntax.js';\nimport { HTML_BLOCK_PLACEHOLDER } from '../placeholder-chars.js';\n\n/**\n * @import { TextMatchTransformer } from '@lexical/markdown';\n * @import { TextNode } from 'lexical';\n */\n\n/**\n * Block syntax at the start of a line, after up to 3 spaces.\n */\nconst BLOCK_SYNTAX = [\n  // Thematic break, which comes first as it can start like a bullet list item\n  THEMATIC_BREAK,\n  // ATX heading, bullet list item or ordered list item, which comes before a setext heading\n  // underline, as a single `-` is a list item\n  `(?:${ATX_HEADING_MARKER}|${LIST_MARKER})${MARKER_END}`,\n  // Setext heading underline\n  SETEXT_UNDERLINE,\n  // Blockquote or code fence\n  `>|${CODE_FENCE}`,\n].join('|');\n\n/**\n * Label of a link reference definition or a footnote definition, like `[foo]:` in\n * `[foo]: https://example.com` or `[^1]:` in `[^1]: Note`, which isn’t supported. The rest of the\n * line is left to the other transformers, so a paragraph that only starts like one keeps its\n * formatting.\n * @see https://spec.commonmark.org/0.31.2/#link-reference-definitions\n */\nconst DEFINITION_SYNTAX = String.raw`\\[(?:[^\\\\[\\]]|\\\\.)+\\]:`;\n/**\n * Regular expression to match the Markdown syntax that the editor imports as text, but that has to\n * be exported as is: the block syntax at the start of a line, which can’t be nested in a blockquote\n * or a list item, or isn’t supported, like the `)` ordered list delimiter or a definition.\n */\nconst RAW_SYNTAX_REGEX = new RegExp(`^ {0,3}(?:${BLOCK_SYNTAX}|${DEFINITION_SYNTAX})`);\n\n/**\n * State of a text node imported from the {@link RAW_SYNTAX_REGEX raw syntax}, holding the Markdown\n * it was imported from.\n */\nconst rawSyntaxState = createState('suiRawSyntax', {\n  /**\n   * Parse the state value.\n   * @param {unknown} value Value.\n   * @returns {string} Markdown, or an empty string if the node is not raw syntax.\n   */\n  parse: (value) => (typeof value === 'string' ? value : ''),\n});\n\n/**\n * Get the Markdown a text node was imported from, if it’s raw syntax.\n * @param {TextNode} node Text node.\n * @returns {string | undefined} Markdown, or `undefined` if the node is not raw syntax.\n */\nexport const getImportedRawSyntax = (node) => getState(node, rawSyntaxState) || undefined;\n\n/**\n * Get the Markdown of a text node imported from raw syntax.\n * @param {TextNode} node Text node.\n * @returns {string | undefined} The Markdown the node was imported from, or its current text if it\n * has been edited since. `undefined` if the node is not raw syntax.\n */\nexport const getRawSyntax = (node) => {\n  const markdown = getState(node, rawSyntaxState);\n\n  if (!markdown) {\n    return undefined;\n  }\n\n  // Raw syntax has no escapes, so the text is the Markdown, even if it has been edited since\n  return node.getTextContent();\n};\n\n/**\n * Import-only transformer that marks the text imported from the Markdown syntax the editor doesn’t\n * support, like a list in a blockquote, so it’s exported as is, while the same text typed by the\n * user, pasted as text, or imported from escaped Markdown, like `\\- a`, is escaped; see\n * `BLOCK_SYNTAX_ESCAPE`. Without it, the syntax from the Markdown would be escaped, changing the\n * meaning of the Markdown.\n * @type {TextMatchTransformer}\n */\nexport const RAW_SYNTAX = {\n  dependencies: [],\n  /**\n   * Leave the export to `BLOCK_SYNTAX_ESCAPE`.\n   * @returns {null} Nothing.\n   */\n  export: () => null,\n  importRegExp: RAW_SYNTAX_REGEX,\n  // Never used as a shortcut\n  regExp: /(?!)/,\n  /**\n   * Mark the text node as raw syntax. The node is left out of the other transformers, as nothing\n   * in the syntax is converted.\n   * @param {TextNode} node Text node with the matched text.\n   */\n  replace: (node) => {\n    setState(node, rawSyntaxState, node.getTextContent());\n  },\n  type: 'text-match',\n};\n\n/**\n * Regular expression to match raw HTML: a line of an HTML block after the placeholder that marks\n * it, inline HTML, like a tag, an autolink or a footnote reference, which would otherwise be\n * escaped on export as text that only looks like one. The placeholder is left out of the match, so\n * an editor component that matches the line after it, which comes first, still takes precedence;\n * see `removePlaceholdersFromMatch()` in `editor-components.js`. It’s included if the line starts\n * with a formatting marker, though: Lexical prefers formatting to a text match that covers the\n * same text, so a line like `*foo*` would otherwise be imported as italic. A component pattern\n * doesn’t start with one.\n */\nconst RAW_HTML_REGEX = new RegExp(\n  [\n    `^${HTML_BLOCK_PLACEHOLDER}(?=[*_~=]).+`,\n    `(?<=^${HTML_BLOCK_PLACEHOLDER}).+`,\n    INLINE_HTML_REGEX.source,\n    AUTOLINK_REGEX.source,\n    FOOTNOTE_REFERENCE_REGEX.source,\n    NAMED_CHARACTER_REFERENCE_REGEX.source,\n  ].join('|'),\n);\n\n/**\n * Import-only transformer that marks raw HTML, so it’s exported as is. Neither the Markdown syntax\n * nor the escapes are read in raw HTML, so an escape added to it on export, like `\\_` in an\n * attribute value or `\\*` in the text of an HTML block, would show up as a backslash. Lexical\n * removes the escapes from the text it has imported, so the text is restored with\n * `getImportedRawSyntax()` once the import is done.\n * @type {TextMatchTransformer}\n * @see https://spec.commonmark.org/0.31.2/#raw-html\n * @see https://spec.commonmark.org/0.31.2/#html-blocks\n * @see https://github.com/sveltia/sveltia-cms/issues/1105\n * @see https://github.com/sveltia/sveltia-cms/issues/1106\n */\nexport const RAW_HTML = {\n  dependencies: [],\n  /**\n   * Leave the export to `BLOCK_SYNTAX_ESCAPE`.\n   * @returns {null} Nothing.\n   */\n  export: () => null,\n  importRegExp: RAW_HTML_REGEX,\n  // Never used as a shortcut\n  regExp: /(?!)/,\n  replace: RAW_SYNTAX.replace,\n  type: 'text-match',\n};\n","/**\n * Helpers for inserting block nodes, like a table or a horizontal rule, into the rich text editor.\n * Functions starting with `$` must be called within an editor update.\n */\n\nimport { $createHorizontalRuleNode as createHorizontalRuleNode } from '@lexical/extension';\nimport { $insertNodeToNearestRoot as insertNodeToNearestRoot } from '@lexical/utils';\nimport {\n  $createParagraphNode as createParagraphNode,\n  $getPreviousSelection as getPreviousSelection,\n  $getSelection as getSelection,\n  $isElementNode as isElementNode,\n  $isParagraphNode as isParagraphNode,\n  $isRangeSelection as isRangeSelection,\n  $isRootNode as isRootNode,\n  $setSelection as setSelection,\n} from 'lexical';\n\n/**\n * @import { LexicalNode } from 'lexical';\n * @import { HorizontalRuleNode } from '@lexical/extension';\n */\n\n/**\n * Insert the given block node at the selection, which is restored if the focus has moved to the\n * toolbar or a dialog in the meantime. The node takes the place of the empty paragraph the caret is\n * in, rather than leaving the paragraph above it. Otherwise, the block the caret is in is split at\n * the caret, and the node is inserted in between.\n * @template {LexicalNode} T\n * @param {T} node Node.\n * @returns {T} The node, once inserted.\n */\nexport const $insertBlockNode = (node) => {\n  const selection = getSelection() ?? getPreviousSelection();\n\n  if (selection && !getSelection()) {\n    setSelection(selection.clone());\n  }\n\n  const anchor = isRangeSelection(selection) ? selection.anchor.getNode() : null;\n\n  if (isParagraphNode(anchor) && anchor.isEmpty() && isRootNode(anchor.getParent())) {\n    return anchor.replace(node);\n  }\n\n  return insertNodeToNearestRoot(node);\n};\n\n/**\n * Insert a horizontal rule at the selection, and move the caret to the start of the block after it,\n * or a new paragraph if there’s none to type in.\n * @returns {HorizontalRuleNode} The rule.\n */\nexport const $insertHorizontalRule = () => {\n  const rule = $insertBlockNode(createHorizontalRuleNode());\n  const next = rule.getNextSibling();\n\n  if (isElementNode(next)) {\n    next.selectStart();\n  } else {\n    rule.insertAfter(createParagraphNode()).selectStart();\n  }\n\n  return rule;\n};\n","/**\n * Table editing helpers for the rich text editor: inserting a table, and the row and column\n * operations offered by the table menu. Functions starting with `$` must be called within an editor\n * update.\n */\n\nimport {\n  $createTableNodeWithDimensions as createTableNodeWithDimensions,\n  $deleteTableColumnAtSelection as deleteTableColumnAtSelection,\n  $deleteTableRowAtSelection as deleteTableRowAtSelection,\n  $findTableNode as findTableNode,\n  $insertTableColumnAtSelection as insertTableColumnAtSelection,\n  $insertTableRowAtSelection as insertTableRowAtSelection,\n  $isTableCellNode as isTableCellNode,\n  $isTableRowNode as isTableRowNode,\n  $isTableSelection as isTableSelection,\n  TableCellHeaderStates,\n} from '@lexical/table';\nimport { $findMatchingParent as findMatchingParent } from '@lexical/utils';\nimport {\n  $createParagraphNode as createParagraphNode,\n  $getNodeByKey as getNodeByKey,\n  $getPreviousSelection as getPreviousSelection,\n  $getSelection as getSelection,\n  $isElementNode as isElementNode,\n  $isRangeSelection as isRangeSelection,\n  $isRootNode as isRootNode,\n  $setSelection as setSelection,\n} from 'lexical';\nimport { $insertBlockNode } from './block.js';\nimport { MAX_TABLE_SIZE } from '../constants.js';\n\n/**\n * @import { LexicalNode, RangeSelection } from 'lexical';\n * @import { TableCellNode, TableNode, TableRowNode, TableSelection } from '@lexical/table';\n */\n\n/**\n * Operation offered by the table menu.\n * @typedef {'insert-row-above' | 'insert-row-below' | 'insert-column-left' |\n * 'insert-column-right' | 'delete-row' | 'delete-column' | 'delete-table'} TableAction\n */\n\n/**\n * Get the number of rows or columns for a new table from the given input, which can be anything\n * the user has entered: a whole number from 1 to {@link MAX_TABLE_SIZE}.\n * @param {unknown} value Input value.\n * @returns {number | undefined} Number, or `undefined` if the value is not a valid size.\n */\nexport const parseTableSize = (value) => {\n  const number = Number(value);\n\n  return Number.isInteger(number) && number >= 1 && number <= MAX_TABLE_SIZE ? number : undefined;\n};\n\n/**\n * Create the Markdown of a new empty table with a header row, to insert it in the plain text mode.\n * The cells are written the same way the rich text editor exports them, so switching the mode\n * doesn’t change the value.\n * @param {number} rows Number of rows, including the header row.\n * @param {number} columns Number of columns.\n * @returns {string} Markdown.\n */\nexport const createTableMarkdown = (rows, columns) => {\n  const row = `| ${Array(columns).fill('').join(' | ')} |`;\n  const divider = `| ${Array(columns).fill('---').join(' | ')} |`;\n\n  return [row, divider, ...Array(rows - 1).fill(row)].join('\\n');\n};\n\n/**\n * Check if the table the given cell element is in is laid out from right to left. The columns\n * follow the direction of the table, while each cell can have a direction of its own.\n * @param {HTMLElement} cell Cell element.\n * @returns {boolean} Result.\n */\nexport const isRightToLeftTable = (cell) => {\n  const table = cell.closest('table');\n\n  return !!table && getComputedStyle(table).direction === 'rtl';\n};\n\n/**\n * Get the table cell that contains the given node.\n * @param {LexicalNode | null | undefined} node Node.\n * @returns {TableCellNode | null} Cell, if any.\n */\nexport const $getTableCell = (node) =>\n  node ? /** @type {TableCellNode | null} */ (findMatchingParent(node, isTableCellNode)) : null;\n\n/**\n * Get the key of the table cell the selection’s focus is in. The focus is where the user has moved\n * the caret last, including when they have selected several cells.\n * @returns {string | null} Key, or `null` if the selection is not in a table.\n */\nexport const $getSelectedTableCellKey = () => {\n  const selection = getSelection();\n\n  if (!isRangeSelection(selection) && !isTableSelection(selection)) {\n    return null;\n  }\n\n  return $getTableCell(selection.focus.getNode())?.getKey() ?? null;\n};\n\n/**\n * Insert a new empty table with a header row at the selection, and move the caret to its first\n * cell. A table can’t be inserted into another table, as neither Markdown nor the editor supports\n * nested tables.\n * @param {number} rows Number of rows, including the header row.\n * @param {number} columns Number of columns.\n * @returns {boolean} Whether the table has been inserted.\n */\nexport const $insertTable = (rows, columns) => {\n  const selection = getSelection() ?? getPreviousSelection();\n\n  if (\n    (isRangeSelection(selection) || isTableSelection(selection)) &&\n    findTableNode(selection.anchor.getNode())\n  ) {\n    return false;\n  }\n\n  const table = $insertBlockNode(\n    createTableNodeWithDimensions(rows, columns, { rows: true, columns: false }),\n  );\n\n  // The table has at least one row and one column\n  /** @type {TableRowNode} */ (table.getFirstChildOrThrow()).getFirstChildOrThrow().selectStart();\n\n  return true;\n};\n\n/**\n * Add an empty paragraph after the given table if it’s the last block of the document. The caret\n * can’t otherwise be moved below the table, so nothing could be added after it. An empty paragraph\n * at the end is left out of the Markdown and HTML values, so this doesn’t change them.\n * @param {TableNode} table Table.\n */\nexport const $ensureParagraphAfterTable = (table) => {\n  if (!table.getNextSibling() && isRootNode(table.getParent())) {\n    table.insertAfter(createParagraphNode());\n  }\n};\n\n/**\n * Make the first row of the given table the header row, and the other rows plain rows. A Markdown\n * table always has exactly one header row on top, so this keeps the table in the editor in line\n * with its Markdown, even after a row has been inserted above the header or the header removed.\n * @param {TableNode} table Table.\n */\nexport const $normalizeTableHeaders = (table) => {\n  table.getChildren().forEach((row, rowIndex) => {\n    // The table transform of Lexical removes anything but rows and cells\n    /* v8 ignore next 3 */\n    if (!isTableRowNode(row)) {\n      return;\n    }\n\n    const headerState =\n      rowIndex === 0 ? TableCellHeaderStates.ROW : TableCellHeaderStates.NO_STATUS;\n\n    row.getChildren().forEach((cell) => {\n      if (isTableCellNode(cell) && cell.getHeaderStyles() !== headerState) {\n        cell.setHeaderStyles(headerState);\n      }\n    });\n  });\n};\n\n/**\n * Move the caret out of the given table, which is about to be removed: to the end of the block\n * before it, the start of the block after it, or a new paragraph if there’s neither to type in.\n * @param {TableNode} table Table.\n */\nconst $moveCaretOutOfTable = (table) => {\n  const previous = table.getPreviousSibling();\n  const next = table.getNextSibling();\n\n  if (isElementNode(previous)) {\n    previous.selectEnd();\n  } else if (isElementNode(next)) {\n    next.selectStart();\n  } else {\n    table.insertAfter(createParagraphNode()).selectStart();\n  }\n};\n\n/**\n * Check if the given operation deletes rows or columns.\n * @param {TableAction} action Operation.\n * @returns {action is 'delete-row' | 'delete-column'} Result.\n */\nconst isDeleteAction = (action) => action === 'delete-row' || action === 'delete-column';\n\n/**\n * Check if the selection spans all the rows or all the columns of the given table, depending on the\n * action, in which case deleting them deletes the whole table. Merged cells are disabled, so the\n * table is a plain grid, where the index of a row or cell tells its position.\n * @param {TableNode} table Table the selection is in.\n * @param {'delete-row' | 'delete-column'} action Operation.\n * @returns {boolean} Result.\n */\nconst $selectionSpansTable = (table, action) => {\n  const selection = /** @type {RangeSelection | TableSelection} */ (getSelection());\n\n  const cells = /** @type {TableCellNode[]} */ (\n    [selection.anchor, selection.focus].map((point) => $getTableCell(point.getNode()))\n  );\n\n  const [start, end] = cells\n    .map((cell) =>\n      action === 'delete-row'\n        ? cell.getParentOrThrow().getIndexWithinParent()\n        : cell.getIndexWithinParent(),\n    )\n    .sort((a, b) => a - b);\n\n  return (\n    end - start + 1 === (action === 'delete-row' ? table.getChildrenSize() : table.getColumnCount())\n  );\n};\n\n/**\n * Run the given table menu operation on the cell with the given key. If the selection is already\n * in the same table, it’s kept, so an operation applies to all the selected rows or columns.\n * Otherwise, the caret is moved to the cell first.\n * @param {TableAction} action Operation.\n * @param {string} cellKey Key of the cell the menu has been opened for.\n * @param {object} [options] Options.\n * @param {boolean} [options.rtl] Whether the table is laid out from right to left, in which case\n * the left column comes after the cell rather than before it.\n * @returns {boolean} Whether the operation has been run. It’s not if the cell is gone.\n */\nexport const $runTableAction = (action, cellKey, { rtl = false } = {}) => {\n  const cell = getNodeByKey(cellKey);\n\n  if (!isTableCellNode(cell)) {\n    return false;\n  }\n\n  const table = /** @type {TableNode} */ (findTableNode(cell));\n  const selection = getSelection() ?? getPreviousSelection();\n\n  if (\n    (isRangeSelection(selection) || isTableSelection(selection)) &&\n    findTableNode(selection.anchor.getNode())?.is(table) &&\n    findTableNode(selection.focus.getNode())?.is(table)\n  ) {\n    if (!getSelection()) {\n      setSelection(selection.clone());\n    }\n  } else {\n    cell.selectStart();\n  }\n\n  if (\n    action === 'delete-table' ||\n    (isDeleteAction(action) && $selectionSpansTable(table, action))\n  ) {\n    // Deleting every row or column deletes the table, which Lexical does by moving the caret to\n    // the previous node, even if that’s a decorator or there’s none, where the user can’t type\n    $moveCaretOutOfTable(table);\n    table.remove();\n  } else if (action === 'delete-row') {\n    deleteTableRowAtSelection();\n  } else if (action === 'delete-column') {\n    deleteTableColumnAtSelection();\n  } else if (action === 'insert-row-above' || action === 'insert-row-below') {\n    insertTableRowAtSelection(action === 'insert-row-below');\n  } else {\n    // In a right-to-left table, the left column comes after the cell\n    insertTableColumnAtSelection((action === 'insert-column-right') !== rtl);\n  }\n\n  return true;\n};\n","/**\n * Find the code spans in Markdown, as Lexical reads them.\n */\n\nimport { countBackslashesBefore } from './syntax.js';\n\n/**\n * @typedef {object} CodeSpan\n * @property {number} start Index of the opening backticks.\n * @property {number} end Index after the closing backticks.\n * @property {number} fenceLength Number of backticks on either side.\n */\n\n/**\n * Find the code spans in a line like Lexical does: a run of backticks that isn’t escaped opens a\n * code span, which is closed by the next run of as many backticks.\n * @param {string} line Line.\n * @returns {CodeSpan[]} Code spans.\n * @see https://spec.commonmark.org/0.31.2/#code-spans\n */\nexport const findCodeSpans = (line) => {\n  const runs = [...line.matchAll(/`+/g)].map(({ 0: { length }, index }) => ({\n    index,\n    length,\n    escaped: countBackslashesBefore(line, index) % 2 === 1,\n  }));\n\n  /** @type {CodeSpan[]} */\n  const spans = [];\n\n  for (let open = 0; open < runs.length; open += 1) {\n    let close = open + 1;\n\n    while (close < runs.length && runs[close].length !== runs[open].length) {\n      close += 1;\n    }\n\n    if (!runs[open].escaped && close < runs.length) {\n      const { index, length } = runs[close];\n\n      spans.push({ start: runs[open].index, end: index + length, fenceLength: length });\n      open = close;\n    }\n  }\n\n  return spans;\n};\n\n/**\n * Apply functions to the code spans of a text and to the text outside them, like {@link\n * findCodeSpans} finds them.\n * @param {string} text Text.\n * @param {object} callbacks Functions to apply.\n * @param {(text: string) => string} [callbacks.outside] Function that returns a processed piece of\n * text between code spans. The text is kept as is by default.\n * @param {(codeSpan: string, span: CodeSpan) => string} [callbacks.inside] Function that returns a\n * processed code span, given with its backticks. The code span is kept as is by default.\n * @returns {string} Processed text.\n */\nexport const mapCodeSpans = (text, { outside = (piece) => piece, inside = (span) => span }) => {\n  let result = '';\n  let index = 0;\n\n  findCodeSpans(text).forEach((span) => {\n    result +=\n      outside(text.slice(index, span.start)) + inside(text.slice(span.start, span.end), span);\n    index = span.end;\n  });\n\n  return result + outside(text.slice(index));\n};\n","import { $isLineBreakNode as isLineBreakNode, $isTextNode as isTextNode } from 'lexical';\n\nimport {\n  ATX_HEADING_MARKER,\n  isWordChar,\n  MARKER_END,\n  ORDERED_LIST_DELIMITER,\n  ORDERED_LIST_NUMBER,\n  SETEXT_UNDERLINE,\n} from '../markdown/syntax.js';\nimport { RAW_TEXT_PLACEHOLDER } from '../placeholder-chars.js';\nimport { getFormatExportNode } from './inline-code.js';\nimport { getRawSyntax } from './raw-syntax.js';\n\n/**\n * @import { TextMatchTransformer } from '@lexical/markdown';\n * @import { ElementNode, LexicalNode, TextNode } from 'lexical';\n */\n\n/**\n * Regular expression to match the block syntax at the start of a line that is escaped with a\n * backslash before its first character: an ATX heading, a bullet list item, a blockquote, a setext\n * heading underline or a thematic break. A `*` bullet is left out, as Lexical already escapes it. A\n * single `-` is a list item rather than a setext heading underline, which comes after it.\n */\nconst BLOCK_SYNTAX_REGEX = new RegExp(\n  `^( {0,3})(${ATX_HEADING_MARKER}${MARKER_END}|[-+]${MARKER_END}|>|${SETEXT_UNDERLINE})`,\n);\n\n/**\n * Regular expression to match an ordered list item at the start of a line, whose number can’t be\n * escaped, unlike the delimiter after it.\n */\nconst ORDERED_LIST_ITEM_REGEX = new RegExp(\n  `^( {0,3}${ORDERED_LIST_NUMBER})(${ORDERED_LIST_DELIMITER})${MARKER_END}`,\n);\n\n/**\n * Escape the Markdown block syntax at the start of a line, so text that only looks like a heading,\n * a list item, a blockquote, a setext heading underline or a thematic break stays text when the\n * Markdown is read again. Lexical already escapes the inline syntax characters, including `*`, `_`,\n * `` ` `` and `~`.\n * @param {string} text Exported Markdown of a line start.\n * @returns {string} Escaped Markdown.\n */\nexport const escapeBlockSyntax = (text) =>\n  text.replace(BLOCK_SYNTAX_REGEX, '$1\\\\$2').replace(ORDERED_LIST_ITEM_REGEX, '$1\\\\$2');\n\n/**\n * Remove the backslashes Lexical adds before underscores and backslashes in text, where they’re not\n * needed, so `snake_case` and `C:\\Users` aren’t exported as `snake\\_case` and `C:\\\\Users`. Unlike\n * a global replacement, the escapes that are needed are kept: an underscore that could open or\n * close emphasis, like that in `\\_not italic\\_`, and a backslash that would otherwise escape the\n * next character or make a hard line break.\n * @param {string} markdown Markdown exported from a text node with its format, in which every\n * backslash starts an escape.\n * @returns {string} Tidied Markdown.\n * @see https://github.com/sveltia/sveltia-cms/issues/430\n * @see https://github.com/sveltia/sveltia-cms/issues/512\n */\nexport const unescapeText = (markdown) =>\n  markdown.replace(/((?:\\\\_)+)|\\\\(.)/gs, (match, underscores, char, offset, string) => {\n    if (underscores) {\n      return isWordChar(string[offset - 1]) && isWordChar(string[offset + match.length])\n        ? underscores.replaceAll('\\\\', '')\n        : match;\n    }\n\n    if (char === '\\\\') {\n      const next = string[offset + 2];\n\n      // The backslash is literal unless it’s followed by ASCII punctuation, which it would\n      // escape, or a line break, which it would turn into a hard line break. The end of the node\n      // is kept escaped, as the next node may start with either\n      return next && !/[\\n\\r!-/:-@[-`{-~]/.test(next) ? char : match;\n    }\n\n    return match;\n  });\n\n/**\n * Characters for the numeric character references Lexical exports in place of literal text.\n * @type {Record<string, string>}\n */\nconst REFERENCED_CHARS = { 38: '&', 60: '<', 91: '[', 93: ']' };\n/**\n * Regular expression to match the start of an email autolink after its `<`, which can start with a\n * digit or a symbol, like `<1@example.com>`.\n * @see https://spec.commonmark.org/0.31.2/#email-autolink\n */\nconst EMAIL_AUTOLINK_START_REGEX = /^[\\w.!#$%&'*+/=?^`{|}~-]{1,64}@[A-Za-z\\d]/;\n\n/**\n * Replace the numeric character references Lexical exports for `<`, `&`, `[` and `]` in text, so\n * HTML, a character reference or a link isn’t read from it, with the characters themselves where\n * they can’t start one, so `a <= b`, `see [1]` and the `[ ]` of a task list item stay readable.\n * The others are escaped with a backslash instead, as the Markdown would be written by hand: a `<`\n * that could start a tag, a comment or an autolink, a `&` that could start a numeric reference, a\n * `[` that could start a footnote and a `]` that could end a link text or a link label. One at the\n * end of the node stays escaped, as the next node may complete the syntax, unless nothing but a\n * line break follows, which none of them can be followed by. A bracket in a link text stays escaped\n * too, as unbalanced brackets would end the link text early. Every replacement is punctuation,\n * like the reference, so the escapes left by `unescapeText()` stay valid.\n * @param {string} markdown Markdown exported from a text node with its format.\n * @param {object} context Where the text node is.\n * @param {boolean} context.isInLink Whether the text node is in a link.\n * @param {boolean} context.isAtLineEnd Whether the text node is at the end of a line.\n * @returns {string} Tidied Markdown.\n * @see https://github.com/facebook/lexical/pull/9481\n */\nexport const unescapeCharacterReferences = (markdown, { isInLink, isAtLineEnd }) =>\n  markdown.replace(/&#(38|60|91|93);/g, (match, code, offset, string) => {\n    const char = REFERENCED_CHARS[code];\n    // Enough for the local part of an email address, the longest the checks below need, without\n    // copying the rest of a long text each time\n    const next = string.slice(offset + match.length, offset + match.length + 70);\n\n    const isNeeded =\n      (!next && !isAtLineEnd) ||\n      (char === '<' && (/^[A-Za-z/!?]/.test(next) || EMAIL_AUTOLINK_START_REGEX.test(next))) ||\n      (char === '&' && /^#(?:\\d{1,7}|[xX][\\dA-Fa-f]{1,6});/.test(next)) ||\n      (char === '[' && (isInLink || next.startsWith('^'))) ||\n      (char === ']' && (isInLink || /^[(:[]/.test(next)));\n\n    return isNeeded ? `\\\\${char}` : char;\n  });\n\n/**\n * Escape the `&` that would start a named character reference in text, like that in `&copy;`.\n * Lexical imports a named reference as text and exports the text as is, so the text, typed by the\n * user or imported from the escaped `\\&copy;`, would become `©` the next time the Markdown is read\n * by another renderer. A named reference in the Markdown is imported as raw syntax instead, so it’s\n * exported as is; see `RAW_HTML`.\n * @param {string} markdown Markdown exported from a text node with its format, in which every\n * backslash starts an escape.\n * @returns {string} Escaped Markdown.\n * @see https://spec.commonmark.org/0.31.2/#entity-and-numeric-character-references\n */\nexport const escapeNamedCharacterReferences = (markdown) =>\n  markdown.replace(/&(?=[A-Za-z][A-Za-z\\d]*;)/g, '\\\\&');\n\n/**\n * Check if the given text node is italic and the italic text it’s part of is next to a word\n * character, like `b` in `a*b*c`. The italic text then needs the `*` delimiter instead of `_`,\n * which can’t be used within a word.\n * @param {TextNode} node Text node.\n * @returns {boolean} Result.\n */\nconst isItalicWithinWord = (node) => {\n  if (!node.hasFormat('italic')) {\n    return false;\n  }\n\n  /**\n   * Check if the given node is italic text.\n   * @param {LexicalNode | null} sibling Node.\n   * @returns {sibling is TextNode} Result.\n   */\n  const isItalicText = (sibling) => isTextNode(sibling) && sibling.hasFormat('italic');\n  let first = node;\n  let last = node;\n\n  while (isItalicText(first.getPreviousSibling())) {\n    first = /** @type {TextNode} */ (first.getPreviousSibling());\n  }\n\n  while (isItalicText(last.getNextSibling())) {\n    last = /** @type {TextNode} */ (last.getNextSibling());\n  }\n\n  // Lexical puts the delimiters inside the leading and trailing whitespace, if any\n  const firstText = first.getTextContent();\n  const lastText = last.getTextContent();\n  const before = /^\\s/.test(firstText) ? ' ' : first.getPreviousSibling()?.getTextContent().at(-1);\n  const after = /\\s$/.test(lastText) ? ' ' : last.getNextSibling()?.getTextContent()[0];\n\n  return isWordChar(before) || isWordChar(after);\n};\n\n/**\n * Export-only transformer that tidies up the Markdown of a text node that isn’t inline code, which\n * Lexical exports verbatim. It removes the unnecessary escapes Lexical adds; see `unescapeText()`.\n * It uses `*` instead of `_` for italic text within a word, like `a*b*c`, which would otherwise be\n * exported as `a_b_c`, plain text. Last, it escapes the Markdown block syntax at the start of a\n * block or of a line after a line break. Without it, a paragraph typed as `## Hours` with the\n * Markdown shortcuts turned off, pasted as text, or imported from the escaped `\\## Hours` would be\n * exported as is and become a heading the next time the Markdown is read. The text imported from\n * the syntax the editor doesn’t support, like a list in a blockquote, is exported as is instead;\n * see `RAW_SYNTAX`.\n * @type {TextMatchTransformer}\n */\nexport const BLOCK_SYNTAX_ESCAPE = {\n  dependencies: [],\n  /**\n   * Export a text node.\n   * @param {LexicalNode} node Node.\n   * @param {(node: ElementNode) => string} _exportChildren Function to export the children of an\n   * element, unused.\n   * @param {(node: TextNode, textContent: string) => string} exportFormat Function to export a text\n   * node with its format.\n   * @returns {string | null} Markdown, or `null` to leave the node to the other transformers.\n   */\n  export: (node, _exportChildren, exportFormat) => {\n    if (!isTextNode(node) || node.hasFormat('code')) {\n      return null;\n    }\n\n    const text = node.getTextContent();\n\n    // Lexical exports formatted whitespace, like the bold space in `**_a_ [b](u)**`, as is, but it\n    // drops the closing syntax due after it, before a link for example, leaving `**_a_ **[b](u)**`.\n    // Export a placeholder instead to get the closing syntax, which goes before the whitespace\n    if (node.getFormat() && /^\\s+$/.test(text)) {\n      const syntax = exportFormat(getFormatExportNode(node), RAW_TEXT_PLACEHOLDER);\n\n      return `${syntax.replace(RAW_TEXT_PLACEHOLDER, '')}${text}`;\n    }\n\n    const rawSyntax = getRawSyntax(node);\n\n    // Raw syntax is exported as is, but with the syntax of its format, if any\n    let markdown = exportFormat(\n      getFormatExportNode(node),\n      rawSyntax === undefined ? text : RAW_TEXT_PLACEHOLDER,\n    );\n\n    if (isItalicWithinWord(node)) {\n      // Every underscore in the text is escaped, so an unescaped one is an italic delimiter\n      markdown = markdown.replace(/\\\\.|_/gs, (match) => (match === '_' ? '*' : match));\n    }\n\n    if (rawSyntax !== undefined) {\n      return markdown.replace(RAW_TEXT_PLACEHOLDER, () => rawSyntax);\n    }\n\n    const parent = node.getParent();\n    const previous = node.getPreviousSibling();\n    const next = node.getNextSibling();\n\n    markdown = escapeNamedCharacterReferences(\n      unescapeCharacterReferences(unescapeText(markdown), {\n        isInLink: !!parent?.isInline(),\n        isAtLineEnd: !next || isLineBreakNode(next),\n      }),\n    );\n\n    // Text in a link or other inline element, in a code block, which is exported verbatim, or in a\n    // heading, whose content is only parsed for inline syntax, or text after the start of a line\n    if (\n      !parent ||\n      parent.isInline() ||\n      ['code', 'heading'].includes(parent.getType()) ||\n      (previous && !isLineBreakNode(previous))\n    ) {\n      return markdown;\n    }\n\n    // A formatted node starts with its own syntax, such as `**`, which is left as is\n    return escapeBlockSyntax(markdown);\n  },\n  // Never used to import Markdown or as a shortcut\n  regExp: /(?!)/,\n  type: 'text-match',\n};\n","// Adopted from https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/plugins/MarkdownTransformers/index.ts\n\n/* eslint-disable jsdoc/require-jsdoc */\n/* eslint-disable jsdoc/require-returns-description */\n/* eslint-disable jsdoc/require-param-description */\n\nimport {\n  $convertFromMarkdownString as convertFromMarkdownString,\n  $convertToMarkdownString as convertToMarkdownString,\n  LINK as LEXICAL_LINK,\n  TRANSFORMERS,\n} from '@lexical/markdown';\nimport {\n  $createTableCellNode as createTableCellNode,\n  $createTableNode as createTableNode,\n  $createTableRowNode as createTableRowNode,\n  $isTableCellNode as isTableCellNode,\n  $isTableNode as isTableNode,\n  $isTableRowNode as isTableRowNode,\n  TableCellHeaderStates,\n  TableCellNode,\n  TableNode,\n  TableRowNode,\n} from '@lexical/table';\nimport { $isParagraphNode as isParagraphNode, $isTextNode as isTextNode } from 'lexical';\n\nimport { mapCodeSpans } from '../markdown/code-spans.js';\nimport { UNESCAPED_LOOKBEHIND } from '../markdown/syntax.js';\nimport { BLOCK_SYNTAX_ESCAPE } from './block-escape.js';\nimport { LEADING_INLINE_CODE } from './inline-code.js';\nimport { LINK } from './link.js';\nimport { RAW_HTML, RAW_SYNTAX } from './raw-syntax.js';\n\n/**\n * @import { ElementTransformer, TextMatchTransformer, Transformer } from '@lexical/markdown';\n * @import { ElementFormatType, ElementNode } from 'lexical';\n */\n\nconst TABLE_ROW_REG_EXP = /^(?:\\|)(.+)(?:\\|)\\s?$/;\n/**\n * Regular expression to match a delimiter row, like `| --- | :-: |`. Each cell needs a hyphen, so a\n * row of empty cells, like `|  |  |`, is an empty header row, not a delimiter row.\n * @see https://github.github.com/gfm/#delimiter-row\n */\nconst TABLE_ROW_DIVIDER_REG_EXP = /^(?:\\|[ \\t]*:?-+:?[ \\t]*)+\\|\\s?$/;\n/**\n * Delimiter row cell for each column alignment, which is kept as the format of the column’s cells.\n * @type {Record<string, string>}\n */\nconst ALIGNMENT_DELIMITERS = { left: ':---', center: ':---:', right: '---:' };\n\n/**\n * Get the alignment of a column from its delimiter row cell, like `:-:`.\n * @param {string} delimiter Delimiter row cell.\n * @returns {ElementFormatType} Alignment, or an empty string for the default.\n */\nconst getColumnAlignment = (delimiter) => {\n  const text = delimiter.trim();\n  const left = text.startsWith(':');\n  const right = text.endsWith(':');\n\n  return left && right ? 'center' : left ? 'left' : right ? 'right' : '';\n};\n\n/**\n * Regular expression to match `\\n` in a cell, which stands for a line break unless its backslash is\n * escaped, like `\\\\n`. The lookahead comes first, so the lookbehind is only tried before a `\\n`.\n */\nconst CELL_LINE_BREAK_REG_EXP = new RegExp(String.raw`(?=\\\\n)${UNESCAPED_LOOKBEHIND}\\\\n`, 'g');\n/**\n * Regular expression to match a pipe that isn’t escaped, which separates the cells of a row. The\n * lookahead comes first, so the lookbehind is only tried before a pipe.\n */\nconst UNESCAPED_PIPE_REG_EXP = new RegExp(String.raw`(?=\\|)${UNESCAPED_LOOKBEHIND}\\|`);\n\n/**\n * Returns the number of columns in the table.\n * @internal\n * @param {TableNode} table\n * @returns {number}\n */\nexport const getTableColumnsSize = (table) => {\n  const row = table.getFirstChild();\n\n  return isTableRowNode(row) ? row.getChildrenSize() : 0;\n};\n\n/**\n * Creates a table cell with the given text content.\n * @param {string} textContent\n * @param {Transformer[]} transformers Transformers to import the cell content with.\n * @returns {TableCellNode}\n */\nconst createTableCell = (textContent, transformers) => {\n  // `\\n` is a line break in the cell, except within inline code, where it’s literal, or after an\n  // escaped backslash. An escaped pipe is part of the cell, even within inline code, like GitHub\n  // Flavored Markdown. The spaces around the content only separate it from the pipes\n  textContent = mapCodeSpans(textContent.trim(), {\n    outside: (text) => text.replace(CELL_LINE_BREAK_REG_EXP, '\\n'),\n  }).replace(/\\\\\\|/g, '|');\n\n  const cell = createTableCellNode(TableCellHeaderStates.NO_STATUS);\n\n  convertFromMarkdownString(textContent, transformers, cell);\n\n  return cell;\n};\n\n/**\n * Maps the given text content to an array of table cells.\n * @internal\n * @param {string} textContent\n * @param {Transformer[]} transformers Transformers to import the cell content with.\n * @returns {TableCellNode[] | null}\n */\nexport const mapToTableCells = (textContent, transformers) => {\n  const [, match] = textContent.match(TABLE_ROW_REG_EXP) ?? [];\n\n  if (!match) {\n    return null;\n  }\n\n  // Split the row at the pipes that are not escaped, which are preceded by an even number of\n  // backslashes, if any\n  return match.split(UNESCAPED_PIPE_REG_EXP).map((text) => createTableCell(text, transformers));\n};\n\n/**\n * Export a table row to Markdown, followed by a delimiter row if it’s a header row.\n * @param {TableRowNode} row Table row.\n * @param {Transformer[]} transformers Transformers to export the cell content with.\n * @returns {string[]} Lines.\n */\nconst exportTableRow = (row, transformers) => {\n  /** @type {string[]} */\n  const rowOutput = [];\n  /** @type {TableCellNode[]} */\n  const cells = [];\n  let isHeaderRow = false;\n\n  row.getChildren().forEach((cell) => {\n    // It’s TableCellNode so it’s just to make flow happy\n    if (isTableCellNode(cell)) {\n      rowOutput.push(\n        // A backslash followed by `n` in text, like that in `C:\\new`, is escaped, so it’s not read\n        // as a line break; it means the same in Markdown. Inline code is left as is, as `\\n` is\n        // literal there\n        mapCodeSpans(convertToMarkdownString(transformers, cell), {\n          outside: (text) => text.replace(CELL_LINE_BREAK_REG_EXP, '\\\\\\\\n'),\n        })\n          // Escape a pipe, which would otherwise end the cell, even within inline code\n          .replace(/\\|/g, '\\\\|')\n          .replace(/\\n/g, '\\\\n')\n          .trim(),\n      );\n      cells.push(cell);\n\n      if (cell.__headerState === TableCellHeaderStates.ROW) {\n        isHeaderRow = true;\n      }\n    }\n  });\n\n  const lines = [`| ${rowOutput.join(' | ')} |`];\n\n  if (isHeaderRow) {\n    lines.push(\n      `| ${cells.map((cell) => ALIGNMENT_DELIMITERS[cell.getFormatType()] ?? '---').join(' | ')} |`,\n    );\n  }\n\n  return lines;\n};\n\n/**\n * Turn the last row of the table before a delimiter row into the header row, and remove the\n * delimiter row. Nothing happens if there is no such table.\n * @param {ElementNode} parentNode Paragraph holding the delimiter row.\n * @param {string} textContent Delimiter row, like `| --- | :-: |`.\n */\nconst $applyHeaderRow = (parentNode, textContent) => {\n  const table = parentNode.getPreviousSibling();\n\n  if (!table || !isTableNode(table)) {\n    return;\n  }\n\n  const rows = table.getChildren();\n  const lastRow = rows[rows.length - 1];\n\n  if (!lastRow || !isTableRowNode(lastRow)) {\n    return;\n  }\n\n  const alignments = textContent.trim().slice(1, -1).split('|').map(getColumnAlignment);\n\n  // Add header state to row cells, and the column alignment, which the rows that follow take from\n  // the header row\n  lastRow.getChildren().forEach((cell, index) => {\n    if (!isTableCellNode(cell)) {\n      return;\n    }\n\n    cell.setHeaderStyles(TableCellHeaderStates.ROW, TableCellHeaderStates.ROW);\n    cell.setFormat(alignments[index] ?? '');\n  });\n\n  // Remove line\n  parentNode.remove();\n};\n\n/**\n * Take the table rows from the paragraphs right before the given one, removing those paragraphs.\n * @param {ElementNode} parentNode Paragraph holding the current table row.\n * @param {Transformer[]} transformers Transformers to import the cell content with.\n * @returns {TableCellNode[][]} Cells of each row, in the document order.\n */\nconst $takePrecedingRows = (parentNode, transformers) => {\n  /** @type {TableCellNode[][]} */\n  const rows = [];\n  let sibling = parentNode.getPreviousSibling();\n\n  while (sibling) {\n    if (!isParagraphNode(sibling)) {\n      break;\n    }\n\n    if (sibling.getChildrenSize() !== 1) {\n      break;\n    }\n\n    const firstChild = sibling.getFirstChild();\n\n    if (!isTextNode(firstChild)) {\n      break;\n    }\n\n    const cells = mapToTableCells(firstChild.getTextContent(), transformers);\n\n    if (!cells) {\n      break;\n    }\n\n    rows.unshift(cells);\n\n    const previousSibling = sibling.getPreviousSibling();\n\n    sibling.remove();\n    sibling = previousSibling;\n  }\n\n  return rows;\n};\n\n/**\n * Create a table from the given rows, padding the shorter ones with empty cells.\n * @param {TableCellNode[][]} rows Cells of each row.\n * @param {Transformer[]} transformers Transformers to import the empty cell content with.\n * @param {number} [columnsSize] Number of columns. The cells beyond it are dropped. The default is\n * the number of cells in the longest row.\n * @returns {TableNode} Table.\n */\nconst $createTable = (\n  rows,\n  transformers,\n  columnsSize = Math.max(...rows.map((cells) => cells.length)),\n) => {\n  const table = createTableNode();\n\n  rows.forEach((cells) => {\n    const tableRow = createTableRowNode();\n\n    table.append(tableRow);\n\n    for (let i = 0; i < columnsSize; i += 1) {\n      tableRow.append(i < cells.length ? cells[i] : createTableCell('', transformers));\n    }\n  });\n\n  return table;\n};\n\n/**\n * Put a new table with the given rows in place of the given paragraph, or add the rows to the table\n * right before it if that has a header row or the same number of columns. Like GitHub Flavored\n * Markdown, a row with fewer cells than the header row is padded with empty cells, and the cells\n * beyond it are dropped. The rows then take the column alignment from the header.\n * @param {ElementNode} parentNode Paragraph to replace.\n * @param {TableCellNode[][]} rows Cells of each row.\n * @param {Transformer[]} transformers Transformers to import the empty cell content with.\n * @see https://github.github.com/gfm/#tables-extension-\n */\nconst $insertImportedTable = (parentNode, rows, transformers) => {\n  const previousSibling = parentNode.getPreviousSibling();\n  const headerRow = isTableNode(previousSibling) ? previousSibling.getFirstChild() : null;\n  const headerCells = isTableRowNode(headerRow) ? headerRow.getChildren() : [];\n\n  const hasHeaderRow = headerCells.some(\n    (cell) => isTableCellNode(cell) && cell.hasHeaderState(TableCellHeaderStates.ROW),\n  );\n\n  /** @type {TableNode} */\n  let table;\n\n  if (\n    isTableNode(previousSibling) &&\n    (hasHeaderRow ||\n      getTableColumnsSize(previousSibling) === Math.max(...rows.map((cells) => cells.length)))\n  ) {\n    table = $createTable(rows, transformers, headerCells.length);\n\n    table.getChildren().forEach((row) => {\n      /** @type {TableRowNode} */ (row).getChildren().forEach((cell, index) => {\n        /** @type {TableCellNode} */ (cell).setFormat(\n          /** @type {TableCellNode} */ (headerCells[index]).getFormatType(),\n        );\n      });\n    });\n\n    previousSibling.append(...table.getChildren());\n    parentNode.remove();\n  } else {\n    table = $createTable(rows, transformers);\n    parentNode.replace(table);\n  }\n\n  table.selectEnd();\n};\n\n/**\n * Create a table transformer. A cell can only have inline content, so it’s converted with the\n * standard Markdown transformers and the given text match transformers, like those of the inline\n * editor components, which come first to take priority, as they do for the rest of the document.\n * @param {TextMatchTransformer[]} [cellTransformers] Additional transformers for the cell content.\n * @returns {ElementTransformer}\n */\nexport const createTableTransformer = (cellTransformers = []) => {\n  /** @type {Transformer[]} */\n  const transformers = [\n    ...cellTransformers,\n    ...TRANSFORMERS.map((transformer) => (transformer === LEXICAL_LINK ? LINK : transformer)),\n    LEADING_INLINE_CODE,\n    RAW_HTML,\n    RAW_SYNTAX,\n  ];\n\n  /** @type {Transformer[]} */\n  const exportTransformers = [...transformers, BLOCK_SYNTAX_ESCAPE];\n\n  return {\n    dependencies: [TableNode, TableRowNode, TableCellNode],\n    export: (node) => {\n      if (!isTableNode(node)) {\n        return null;\n      }\n\n      return node\n        .getChildren()\n        .flatMap((row) => (isTableRowNode(row) ? exportTableRow(row, exportTransformers) : []))\n        .join('\\n');\n    },\n    regExp: TABLE_ROW_REG_EXP,\n    replace: (parentNode, _children, [textContent]) => {\n      // Header row\n      if (TABLE_ROW_DIVIDER_REG_EXP.test(textContent)) {\n        $applyHeaderRow(parentNode, textContent);\n\n        return;\n      }\n\n      const matchCells = mapToTableCells(textContent, transformers);\n\n      if (!matchCells) {\n        return;\n      }\n\n      const rows = [...$takePrecedingRows(parentNode, transformers), matchCells];\n\n      $insertImportedTable(parentNode, rows, transformers);\n    },\n    type: 'element',\n  };\n};\n","/**\n * Regular expressions and helpers to read the block structure of a Markdown string, like the\n * headings, the HTML blocks and the lines that end a paragraph.\n */\n\nimport {\n  ATX_HEADING_MARKER,\n  CODE_FENCE,\n  HTML_TAG_SOURCE,\n  LIST_MARKER,\n  MARKER_END,\n  SETEXT_UNDERLINE,\n  THEMATIC_BREAK,\n} from './syntax.js';\n\n/**\n * Regular expression to match a setext heading underline, like `===` or `---`.\n */\nexport const SETEXT_UNDERLINE_REGEX = new RegExp(`^ {0,3}${SETEXT_UNDERLINE}`);\n/**\n * Regular expression to match an ATX heading, like `## Heading`.\n */\nexport const ATX_HEADING_REGEX = new RegExp(`^ {0,3}${ATX_HEADING_MARKER}${MARKER_END}`);\n\n/**\n * Regular expression to match a thematic break, like `***` or `- - -`.\n */\nconst THEMATIC_BREAK_REGEX = new RegExp(`^ {0,3}${THEMATIC_BREAK}`);\n\n/**\n * Names of the HTML elements that start an HTML block that can interrupt a paragraph, as opposed to\n * inline HTML, like `<span>`, which a paragraph can start with.\n * @see https://spec.commonmark.org/0.31.2/#html-blocks\n */\nconst HTML_BLOCK_TAG_NAMES = [\n  'address',\n  'article',\n  'aside',\n  'base',\n  'basefont',\n  'blockquote',\n  'body',\n  'caption',\n  'center',\n  'col',\n  'colgroup',\n  'dd',\n  'details',\n  'dialog',\n  'dir',\n  'div',\n  'dl',\n  'dt',\n  'fieldset',\n  'figcaption',\n  'figure',\n  'footer',\n  'form',\n  'frame',\n  'frameset',\n  'h[1-6]',\n  'head',\n  'header',\n  'hr',\n  'html',\n  'iframe',\n  'legend',\n  'li',\n  'link',\n  'main',\n  'menu',\n  'menuitem',\n  'nav',\n  'noframes',\n  'ol',\n  'optgroup',\n  'option',\n  'p',\n  'param',\n  'search',\n  'section',\n  'summary',\n  'table',\n  'tbody',\n  'td',\n  'tfoot',\n  'th',\n  'thead',\n  'title',\n  'tr',\n  'track',\n  'ul',\n];\n\n/**\n * Start and end conditions of the HTML blocks that can interrupt a paragraph: a raw text element, a\n * comment, a processing instruction, a declaration, a CDATA section or a block element. The start\n * is what follows the `<` at the start of the line. The end of the block is the line that matches\n * the end condition, or the line before a blank line if there’s none.\n * @type {[string, RegExp | null][]}\n * @see https://spec.commonmark.org/0.31.2/#html-blocks\n */\nconst HTML_BLOCK_CONDITION_SOURCES = [\n  ['(?:script|pre|style|textarea)(?:[ \\\\t>]|$)', /<\\/(?:pre|script|style|textarea)>/i],\n  ['!--', /-->/],\n  ['\\\\?', /\\?>/],\n  ['![A-Za-z]', />/],\n  ['!\\\\[CDATA\\\\[', /\\]\\]>/],\n  [`/?(?:${HTML_BLOCK_TAG_NAMES.join('|')})(?:[ \\\\t>]|/>|$)`, null],\n];\n\n/**\n * Regular expression to match the start of an HTML block that can interrupt a paragraph; see\n * {@link HTML_BLOCK_CONDITION_SOURCES}.\n */\nconst HTML_BLOCK_START_REGEX = new RegExp(\n  `<(?:${HTML_BLOCK_CONDITION_SOURCES.map(([start]) => start).join('|')})`,\n  'i',\n);\n\n/**\n * Start and end conditions of the HTML blocks that can interrupt a paragraph, with the start as a\n * regular expression to match a line; see {@link HTML_BLOCK_CONDITION_SOURCES}.\n * @type {[RegExp, RegExp | null][]}\n */\nconst HTML_BLOCK_CONDITIONS = HTML_BLOCK_CONDITION_SOURCES.map(([start, end]) => [\n  new RegExp(`^ {0,3}<(?:${start})`, 'i'),\n  end,\n]);\n\n/**\n * Regular expression to match a line that starts an HTML block that can’t interrupt a paragraph.\n * @see https://spec.commonmark.org/0.31.2/#html-blocks\n */\nconst STANDALONE_HTML_TAG_REGEX = new RegExp(\n  `^ {0,3}(?!</?(?:pre|script|style|textarea)\\\\b)(?:${HTML_TAG_SOURCE})[ \\\\t]*$`,\n  'i',\n);\n\n/**\n * Regular expression to match a line that doesn’t continue a paragraph: an ATX heading, a\n * blockquote, a list item, a code fence, a table row, an HTML block, an indented code block, a\n * thematic break or a setext heading underline.\n */\nconst NON_PARAGRAPH_LINE_REGEX = new RegExp(\n  [\n    ATX_HEADING_REGEX.source,\n    `^ {0,3}(?:>|${LIST_MARKER}${MARKER_END}|${CODE_FENCE}|\\\\|)`,\n    `^ {0,3}${HTML_BLOCK_START_REGEX.source}`,\n    /^(?: {4}|\\t)/.source,\n    THEMATIC_BREAK_REGEX.source,\n    SETEXT_UNDERLINE_REGEX.source,\n  ].join('|'),\n  'i',\n);\n\n/**\n * Regular expression to match a table row, which starts with a pipe.\n */\nexport const TABLE_ROW_LINE_REGEX = /^ {0,3}\\|/;\n\n/**\n * Regular expression to match a line that is a block on its own, so the line after it isn’t in a\n * paragraph: an ATX heading or a thematic break. A setext heading underline is one as well, but\n * only after a paragraph line.\n */\nconst SINGLE_LINE_BLOCK_REGEX = new RegExp(\n  [ATX_HEADING_REGEX.source, THEMATIC_BREAK_REGEX.source].join('|'),\n);\n\n/**\n * Regular expression to match a line that ends the paragraph before it: a line that doesn’t\n * continue a paragraph, other than an indented line, which does.\n */\nconst PARAGRAPH_INTERRUPTION_REGEX = new RegExp(\n  NON_PARAGRAPH_LINE_REGEX.source.replace(`|${/^(?: {4}|\\t)/.source}`, ''),\n  'i',\n);\n\n/**\n * Check if the given line is paragraph text: a line that isn’t blank and doesn’t start another\n * block, or continue one like an indented code block.\n * @param {string} line Line.\n * @returns {boolean} Result.\n */\nexport const isParagraphLine = (line) => !!line.trim() && !NON_PARAGRAPH_LINE_REGEX.test(line);\n\n/**\n * Check if a paragraph can’t continue after the given line: a blank line, or a block on its own,\n * like a heading or a thematic break.\n * @param {string} line Line.\n * @returns {boolean} Result.\n */\nexport const endsParagraph = (line) => !line.trim() || SINGLE_LINE_BLOCK_REGEX.test(line);\n\n/**\n * Check if the given line can’t continue the paragraph before it: a blank line, or a line that\n * starts another block, like a list item, a heading or a table row. An indented line continues it.\n * @param {string} line Line.\n * @returns {boolean} Result.\n */\nexport const interruptsParagraph = (line) =>\n  !line.trim() || PARAGRAPH_INTERRUPTION_REGEX.test(line);\n\n/**\n * Find the lines of a part of a Markdown string that are in an HTML block, which is raw HTML,\n * without any Markdown syntax.\n * @param {string[]} lines Lines of a part of a Markdown string outside fenced code blocks.\n * @returns {boolean[]} Whether each line is in an HTML block.\n * @see https://spec.commonmark.org/0.31.2/#html-blocks\n */\nexport const findHtmlBlockLines = (lines) => {\n  /**\n   * End condition of the current HTML block: a regular expression, `null` for a blank line, or\n   * `undefined` if the line is not in an HTML block.\n   * @type {RegExp | null | undefined}\n   */\n  let end;\n  let isInParagraph = false;\n\n  return lines.map((line) => {\n    const isBlankLine = !line.trim();\n\n    if (end === null && isBlankLine) {\n      end = undefined;\n    }\n\n    if (end === undefined) {\n      const condition = HTML_BLOCK_CONDITIONS.find(([start]) => start.test(line));\n\n      if (condition) {\n        [, end] = condition;\n      } else if (!isInParagraph && STANDALONE_HTML_TAG_REGEX.test(line)) {\n        end = null;\n      } else {\n        // A heading or a thematic break doesn’t leave a paragraph open, so a standalone tag after\n        // it starts an HTML block. A line like `===` is a heading underline only after a\n        // paragraph line, and paragraph text otherwise\n        isInParagraph =\n          !endsParagraph(line) && !(isInParagraph && SETEXT_UNDERLINE_REGEX.test(line));\n\n        return false;\n      }\n    }\n\n    if (end?.test(line)) {\n      end = undefined;\n    }\n\n    isInParagraph = false;\n\n    return true;\n  });\n};\n","/**\n * Convert the block syntax Lexical doesn’t support, like tilde fences and setext headings, to the\n * one it does, and keep blank blockquote lines.\n */\n\nimport { INFO_BACKTICK } from '../placeholder-chars.js';\nimport { ATX_HEADING_REGEX, isParagraphLine, SETEXT_UNDERLINE_REGEX } from './block-structure.js';\nimport {\n  findCodeBlocks,\n  mapLinesOutsideCodeBlocks,\n  mapOutsideCodeBlocks,\n  parseOpeningFence,\n} from './code-blocks.js';\n\n/**\n * @import { OpeningFence } from './code-blocks.js';\n */\n\n/**\n * Convert the fenced code blocks using tildes, like `~~~`, to ones using backticks, because Lexical\n * only supports the latter. The new fence is made longer than any backtick fence in the code, so\n * the code block isn’t closed early. Backticks can’t be used in the info string of a backtick\n * fence, so those after the language are replaced with a placeholder, which the code block\n * transformer turns back into backticks, exporting a tilde fence again; see `CODE`. Other backticks\n * are removed.\n * @param {string} value Markdown string to process.\n * @returns {string} Processed Markdown string.\n */\nexport const convertTildeFences = (value) => {\n  if (!/^[ \\t]*~{3,}/m.test(value)) {\n    return value;\n  }\n\n  const lines = value.split('\\n');\n\n  findCodeBlocks(lines)\n    // A code block in a list item, like `- ~~~`, is left as is, as it’s imported as the text of\n    // the item; see `CODE`\n    .filter(({ start, fence }) => fence.startsWith('~') && /^[ \\t]*~/.test(lines[start]))\n    .forEach(({ start, end, closed }) => {\n      const codeLines = lines.slice(start + 1, closed ? end : end + 1);\n\n      const longestFence = Math.max(\n        2,\n        ...codeLines.map(\n          (line) => /** @type {RegExpMatchArray} */ (line.match(/^[ \\t]*(`*)/))[1].length,\n        ),\n      );\n\n      const backticks = '`'.repeat(longestFence + 1);\n\n      const { indent, info, language } = /** @type {OpeningFence} */ (\n        parseOpeningFence(lines[start])\n      );\n\n      // Unlike that of a tilde fence, the info string of a backtick fence can’t contain a backtick.\n      // The language can’t contain one either, so only the metadata after it is replaced\n      lines[start] = `${indent}${backticks}${info.replaceAll('`', language ? INFO_BACKTICK : '')}`;\n\n      if (closed) {\n        lines[end] = lines[end].replace(/^([ \\t]*)~+[ \\t]*$/, `$1${backticks}`);\n      }\n    });\n\n  return lines.join('\\n');\n};\n\n/**\n * Multiline version of `SETEXT_UNDERLINE_REGEX`, which matches at the start of any line.\n */\nconst SETEXT_UNDERLINE_MULTILINE_REGEX = new RegExp(SETEXT_UNDERLINE_REGEX.source, 'm');\n\n/**\n * Convert setext headings, underlined with `===` or `---`, to ATX headings, like `# Heading`,\n * because Lexical only supports the latter. Without it, the underline is imported as text or a\n * horizontal rule. Fenced code blocks are left untouched. To avoid misreading a horizontal rule,\n * only a paragraph that follows a blank line, an ATX heading or the start of the document is\n * converted; for example, the second `---` of a block like front matter, which starts with a\n * horizontal rule, is left as is.\n * @param {string} value Markdown string to process.\n * @returns {string} Processed Markdown string.\n */\nexport const convertSetextHeadings = (value) => {\n  if (!SETEXT_UNDERLINE_MULTILINE_REGEX.test(value)) {\n    return value;\n  }\n\n  return mapOutsideCodeBlocks(value, (part) => {\n    /** @type {string[]} */\n    const lines = [];\n    // Index of the first of the paragraph lines at the end of `lines`, tracked as the lines are\n    // added rather than found by walking back, which would take quadratic time on a long paragraph\n    let start = 0;\n\n    part.split('\\n').forEach((line) => {\n      const previous = lines[start - 1];\n\n      if (\n        !SETEXT_UNDERLINE_REGEX.test(line) ||\n        start === lines.length ||\n        (previous !== undefined && previous.trim() && !ATX_HEADING_REGEX.test(previous))\n      ) {\n        lines.push(line);\n\n        if (!isParagraphLine(line)) {\n          start = lines.length;\n        }\n\n        return;\n      }\n\n      const text = lines\n        .splice(start)\n        .map((paragraphLine) => paragraphLine.trim())\n        .join(' ');\n\n      lines.push(`${line.trimStart().startsWith('=') ? '#' : '##'} ${text}`);\n      start = lines.length;\n    });\n\n    return lines.join('\\n');\n  });\n};\n\n/**\n * Add a trailing space to a blank blockquote line (`>`) so Lexical treats it as a blank line within\n * the blockquote. Without the space, the line does not match Lexical's `/^>\\s/` quote pattern and\n * is imported as literal `>` text, which is then exported as `> >`, an empty nested blockquote.\n * @param {string} value Markdown string to process.\n * @returns {string} Processed Markdown string.\n * @see https://github.com/sveltia/sveltia-cms/issues/995\n */\nexport const padBlankBlockquoteLines = (value) => {\n  if (!/^>$/m.test(value)) {\n    return value;\n  }\n\n  return mapLinesOutsideCodeBlocks(value, (line) => (line === '>' ? '> ' : line));\n};\n\n/**\n * Remove the trailing space Lexical outputs for a blank blockquote line (`> `) so the line\n * round-trips as `>`, the canonical form.\n * @param {string} value Markdown string to process.\n * @returns {string} Processed Markdown string.\n * @see https://github.com/sveltia/sveltia-cms/issues/995\n */\nexport const trimBlankBlockquoteLines = (value) => {\n  if (!/^> $/m.test(value)) {\n    return value;\n  }\n\n  return mapLinesOutsideCodeBlocks(value, (line) => (line === '> ' ? '>' : line));\n};\n","/**\n * Split the formatting, code spans and links that span line breaks into separate lines, as\n * Lexical reads Markdown line by line.\n */\n\nimport {\n  findHtmlBlockLines,\n  endsParagraph,\n  interruptsParagraph,\n  TABLE_ROW_LINE_REGEX,\n} from './block-structure.js';\nimport { mapOutsideCodeBlocks } from './code-blocks.js';\nimport { findCodeSpans, mapCodeSpans } from './code-spans.js';\nimport {\n  countBackslashesBefore,\n  UNESCAPED_LOOKBEHIND,\n  WHITESPACE_OR_PUNCTUATION,\n} from './syntax.js';\n\n/**\n * @import { CodeSpan } from './code-spans.js';\n */\n\n/**\n * Get the blockquote markers at the start of a line, like `> >` in `> > foo`, without the\n * whitespace after the last one.\n * @param {string} line Line.\n * @returns {string} Markers, like `> >`, or an empty string if the line isn’t in a blockquote.\n */\nconst getBlockquotePrefix = (line) => /^(?: {0,3}>)*/.exec(line)?.[0] ?? '';\n\n/**\n * Create a regular expression to match formatting that spans one or more line breaks, like\n * `**foo\\nbar**`. It captures the text between the markers, line breaks included. The text of each\n * line is read as CommonMark does: a backslash escapes the next character, so an escaped marker is\n * part of the text, and the text can end with an escaped backslash, like `_foo\\\\`, which is\n * followed by a soft line break, not a hard one. A line can end with whitespace or the backslash of\n * a hard line break, and start with whitespace and blockquote markers, like `> ` in\n * `> **foo\\n> bar**`, outside its text. The blockquote markers are matched as many as there are, so\n * the text of a line can’t start with one, and the line can only be matched one way. The markers\n * can’t be escaped, or next to whitespace within the formatting. The formatting must be at the\n * start or the end of the value, or next to whitespace or punctuation other than its own marker, so\n * a marker within a word, like `_` in `snake_case`, is left alone. As per the CommonMark flanking\n * rules, `*` can open and close formatting within a word as well, like `**foo\\nbar**baz`, unless\n * the text starts or ends with punctuation there. The surrounding characters are checked with\n * lookarounds rather than matched with `\\s+`, which would take quadratic time on a long run of\n * whitespace not followed by a marker. The text of a line can’t contain the marker, and it can’t\n * start or end with whitespace, so the text and the line breaks can only be matched one way, which\n * keeps the time linear.\n * @param {string} char Marker character.\n * @param {number} length Number of marker characters.\n * @returns {RegExp} Regular expression.\n * @see https://spec.commonmark.org/0.31.2/#left-flanking-delimiter-run\n */\nconst createMultilineFormattingRegex = (char, length) => {\n  const marker = `[${char}]`.repeat(length);\n  // A character other than the marker and a line break, or an escape. The first and the last of the\n  // text can’t be whitespace\n  const unit = String.raw`(?:\\\\[^\\s]|[^${char}\\\\\\n])`;\n  const edgeUnit = String.raw`(?:\\\\[^\\s]|[^${char}\\s\\\\])`;\n  const text = `${edgeUnit}(?:${unit}*?${edgeUnit})?`;\n  const boundary = WHITESPACE_OR_PUNCTUATION;\n  const isWithinWordAllowed = char === '*';\n\n  const opening = isWithinWordAllowed\n    ? `(?:(?<=^|${boundary})${marker}|${marker}(?!${boundary}))`\n    : `(?<=^|${boundary})${marker}`;\n\n  const closing = isWithinWordAllowed\n    ? `(?:(?<!${boundary})${marker}|${marker}(?=${boundary}|$))`\n    : `${marker}(?=${boundary}|$)`;\n\n  const lineBreak = String.raw`(?:\\\\|[ \\t]*)\\n(?: {0,3}>)*(?! {0,3}>)[ \\t]*`;\n\n  return new RegExp(\n    String.raw`(?<![${char}\\\\])${opening}(${text}(?:${lineBreak}${text})+)${closing}(?![${char}])`,\n    'gu',\n  );\n};\n\n/**\n * Regular expressions to match formatting that spans line breaks, with the marker of each.\n * @type {[string, RegExp][]}\n */\nconst MULTILINE_FORMATTING_REGEXES = [\n  ['***', createMultilineFormattingRegex('*', 3)],\n  ['___', createMultilineFormattingRegex('_', 3)],\n  ['**', createMultilineFormattingRegex('*', 2)],\n  ['__', createMultilineFormattingRegex('_', 2)],\n  ['~~', createMultilineFormattingRegex('~', 2)],\n  ['*', createMultilineFormattingRegex('*', 1)],\n  ['_', createMultilineFormattingRegex('_', 1)],\n];\n\n/**\n * Get the number of blockquote markers in a prefix, which is the nesting level of the blockquote.\n * @param {string} prefix Prefix returned by {@link getBlockquotePrefix}.\n * @returns {number} Level, or `0` if the line isn’t in a blockquote.\n */\nconst getBlockquoteLevel = (prefix) => prefix.split('>').length - 1;\n\n/**\n * @typedef {object} FormattedLine\n * @property {string} quote Blockquote markers at the start of the line, outside the formatting.\n * Always empty for the first line.\n * @property {string} indent Blockquote markers and whitespace at the start of the line, outside the\n * formatting.\n * @property {string} text Text of the line within the formatting.\n * @property {string} lineEnd Whitespace or the backslash of a hard line break at the end of the\n * line, outside the formatting.\n */\n\n/**\n * Split the text of formatting that spans line breaks into lines. The text of a line doesn’t start\n * or end with whitespace, a line after the first can start with blockquote markers, and the\n * backslash of a hard line break is the last of an odd number of backslashes at the end of a line,\n * as the others escape each other.\n * @param {string} text Text matched by one of {@link MULTILINE_FORMATTING_REGEXES}.\n * @returns {FormattedLine[]} Lines.\n */\nconst splitFormattedLines = (text) =>\n  text.split('\\n').map((line, index) => {\n    const quote = index ? getBlockquotePrefix(line) : '';\n    const start = line.length - line.slice(quote.length).trimStart().length;\n    // Not a regular expression like `[ \\t]*$`, which would take quadratic time on a long run of\n    // whitespace within the line\n    let end = line.length;\n\n    while (end > start && /[ \\t]/.test(line[end - 1])) {\n      end -= 1;\n    }\n\n    if (countBackslashesBefore(line, end) % 2) {\n      end -= 1;\n    }\n\n    return {\n      quote,\n      indent: line.slice(0, start),\n      text: line.slice(start, end),\n      lineEnd: line.slice(end),\n    };\n  });\n\n/**\n * Check if a line after the first one of a paragraph is in the same blockquote: it has the same\n * blockquote markers, or none, as a lazy continuation line. Lines in a nested or another blockquote\n * aren’t in the same paragraph.\n * @param {number} level Blockquote level of the first line of the paragraph.\n * @param {string} prefix Blockquote prefix of the line.\n * @returns {boolean} Result.\n * @see https://spec.commonmark.org/0.31.2/#lazy-continuation-line\n */\nconst isInSameBlockquote = (level, prefix) => !prefix || getBlockquoteLevel(prefix) === level;\n\n/**\n * Check if the text of formatting that spans line breaks has other formatting that spans line\n * breaks, like `_foo\\nbar_` in `**_foo\\nbar_**` or `**_foo\\nbar_\\nbaz**`, which has to be split\n * first.\n * @param {string} text Text matched by one of {@link MULTILINE_FORMATTING_REGEXES}.\n * @returns {boolean} Result.\n */\nconst hasMultilineFormatting = (text) =>\n  MULTILINE_FORMATTING_REGEXES.some(([, regex]) => text.search(regex) !== -1);\n\n/**\n * Regular expression to match a link whose text spans one or more line breaks, like\n * `[foo\\nbar](url)`, but not an image. The text can’t have brackets, so a `[` followed by many\n * lines isn’t matched in quadratic time.\n */\nconst MULTILINE_LINK_REGEX = new RegExp(\n  String.raw`(?<!(?:^|[^\\\\])(?:\\\\\\\\)*[\\\\!])\\[([^[\\]\\n]*\\n[^[\\]]*)\\]` +\n    String.raw`\\(([^()\\s]*(?:[ \\t]+\"[^\"\\n]*\")?)\\)`,\n  'g',\n);\n\n/**\n * Split a link whose text spans one or more line breaks into one per line, like\n * `[foo\\nbar](url)` into `[foo](url)\\n[bar](url)`, as Lexical can’t read a link across a line\n * break, and so the formatting around it can be split into separate lines as well. The whitespace\n * at the start and the end of a line goes outside the link text. A link is left as is if a line\n * has no text, or ends with the backslash of a hard line break. An image is left as is, as it\n * would be duplicated, and so is anything in a code span, or a link with a code span that spans a\n * line break, which can’t be split.\n * @param {string} text Paragraph, or text matched by one of {@link MULTILINE_FORMATTING_REGEXES}.\n * @returns {string} Processed text.\n */\nconst splitMultilineLinks = (text) => {\n  if (!text.includes('[')) {\n    return text;\n  }\n\n  const codeSpans = findCodeSpans(text);\n\n  return text.replace(MULTILINE_LINK_REGEX, (match, linkText, target, offset) => {\n    const matchEnd = offset + match.length;\n\n    if (\n      codeSpans.some(\n        ({ start, end }) =>\n          start < matchEnd &&\n          end > offset &&\n          (start < offset || end > matchEnd || text.slice(start, end).includes('\\n')),\n      )\n    ) {\n      return match;\n    }\n\n    const lines = splitFormattedLines(linkText);\n    const lastLine = lines[lines.length - 1];\n\n    // The whitespace at the start and the end of the link text is part of it\n    lines[0] = { ...lines[0], indent: '', text: `${lines[0].indent}${lines[0].text}` };\n    lines[lines.length - 1] = {\n      ...lastLine,\n      text: `${lastLine.text}${lastLine.lineEnd}`,\n      lineEnd: '',\n    };\n\n    if (\n      lines.some(({ text: lineText }) => !/\\S/.test(lineText)) ||\n      lines.some(({ lineEnd }) => lineEnd.includes('\\\\'))\n    ) {\n      return match;\n    }\n\n    return lines\n      .map(({ indent, text: lineText, lineEnd }) => `${indent}[${lineText}](${target})${lineEnd}`)\n      .join('\\n');\n  });\n};\n\n/**\n * Regular expression to match the character before or after a code span that can be split into\n * lines, which isn’t a word character, or the start or the end of the paragraph.\n */\nconst SPAN_BOUNDARY_REGEX = new RegExp(`^$|${WHITESPACE_OR_PUNCTUATION}`, 'u');\n\n/**\n * Split a code span whose code spans one or more line breaks into one per line; see\n * {@link splitMultilineSpans}.\n * @param {string} paragraph Paragraph.\n * @param {CodeSpan} span Code span in the paragraph.\n * @returns {string} Code spans, one per line, or the code span as is if it can’t be split.\n */\nconst splitCodeSpan = (paragraph, { start, end, fenceLength }) => {\n  const codeSpan = paragraph.slice(start, end);\n  let code = codeSpan.slice(fenceLength, -fenceLength);\n\n  if (\n    !code.includes('\\n') ||\n    !SPAN_BOUNDARY_REGEX.test(paragraph.slice(start - 1, start)) ||\n    !SPAN_BOUNDARY_REGEX.test(paragraph.slice(end, end + 1))\n  ) {\n    return codeSpan;\n  }\n\n  // Like CommonMark, strip a space from both ends of the code if it starts and ends with one, like\n  // in `` ` foo\\nbar ` ``, as it would otherwise be kept at the end of a single line\n  if (code.startsWith(' ') && code.endsWith(' ')) {\n    code = code.slice(1, -1);\n  }\n\n  // The blockquote markers and the indentation of a line after the first aren’t part of the code,\n  // so they go before the opening backticks\n  const codeLines = code.split('\\n').map((line, index) => {\n    const indent = index ? (/^(?: {0,3}>)*[ \\t]*/.exec(line)?.[0] ?? '') : '';\n\n    return { indent, text: line.slice(indent.length) };\n  });\n\n  // A line without code, like the first one of `` `\\nfoo` ``, can’t be a code span\n  if (codeLines.some(({ text }) => !/\\S/.test(text))) {\n    return codeSpan;\n  }\n\n  const fence = '`'.repeat(fenceLength);\n\n  return codeLines\n    .map(({ indent, text }) => {\n      // A backtick next to the fence would become part of it, and a space at both ends would be\n      // stripped, so the code is padded with a space on both sides, which is stripped from it\n      // instead, like in ``` `` `foo` `` ```\n      const padding = /^`|`$|^ [^]* $/.test(text) ? ' ' : '';\n\n      return `${indent}${fence}${padding}${text}${padding}${fence}`;\n    })\n    .join('\\n');\n};\n\n/**\n * Split a code span whose code spans one or more line breaks into one per line, like\n * `` `foo\\nbar` `` into `` `foo`\\n`bar` ``, or ``` ``foo\\nbar`` ``` into ``` ``foo``\\n``bar`` ```,\n * so the formatting around it can be split into separate lines as well, then do the same with a\n * link with {@link splitMultilineLinks}. Backslashes and spaces are literal in a code span. The\n * backticks are paired as Lexical pairs them, within a paragraph, so the closing backtick of a code\n * span isn’t taken as the opening one of another, like in table rows such as\n * `` | `**a**` | b |\\n| `*c*` | d | ``, which would get stray backticks otherwise. A code span or a\n * link can’t span a blank line or the start of another block, like a list item, a heading or a\n * table row.\n * @param {string} part Part of a Markdown string outside fenced code blocks.\n * @returns {string} Processed part.\n * @see https://github.com/sveltia/sveltia-cms/issues/1168\n */\nconst splitMultilineSpans = (part) => {\n  if (!/[`[]/.test(part)) {\n    return part;\n  }\n\n  const lines = part.split('\\n');\n  // An HTML block is raw HTML, which is kept as is, so each of its lines is left on its own\n  const htmlBlockLines = part.includes('<') ? findHtmlBlockLines(lines) : [];\n  // The lines of a paragraph in a blockquote are read without the blockquote markers\n  const quotes = lines.map(getBlockquotePrefix);\n  const contents = lines.map((line, index) => line.slice(quotes[index].length));\n  /** @type {string[][]} */\n  const paragraphs = [];\n  let level = 0;\n\n  lines.forEach((line, index) => {\n    const previous = contents[index - 1];\n\n    if (\n      index === 0 ||\n      htmlBlockLines[index] ||\n      htmlBlockLines[index - 1] ||\n      endsParagraph(previous) ||\n      interruptsParagraph(contents[index]) ||\n      !isInSameBlockquote(level, quotes[index]) ||\n      // Lexical reads a table row as a line of its own, so a code span can’t continue after it\n      TABLE_ROW_LINE_REGEX.test(previous)\n    ) {\n      paragraphs.push([line]);\n      level = getBlockquoteLevel(quotes[index]);\n    } else {\n      paragraphs[paragraphs.length - 1].push(line);\n    }\n  });\n\n  return paragraphs\n    .map((paragraphLines) => {\n      if (paragraphLines.length === 1) {\n        return paragraphLines[0];\n      }\n\n      const paragraph = paragraphLines.join('\\n');\n\n      return splitMultilineLinks(\n        mapCodeSpans(paragraph, {\n          /**\n           * Split a code span of the paragraph.\n           * @param {string} _codeSpan Code span, with its backticks.\n           * @param {CodeSpan} span Position of the code span.\n           * @returns {string} Processed code span.\n           */\n          inside: (_codeSpan, span) => splitCodeSpan(paragraph, span),\n        }),\n      );\n    })\n    .join('\\n');\n};\n\n/**\n * Regular expression to match an inline link or a full reference link whose text spans one or more\n * line breaks. The first run can’t have a line break, so a `[` followed by many lines isn’t matched\n * in quadratic time. A bracket after an escaped backslash, like `\\\\[`, isn’t escaped.\n */\nconst HAS_MULTILINE_LINK_TEXT_REGEX = new RegExp(\n  String.raw`${UNESCAPED_LOOKBEHIND}\\[[^[\\]\\n]*\\n[^[\\]]*\\](?=[([])`,\n);\n\n/**\n * Check if the text of formatting that spans line breaks has a line break within a code span or a\n * link text, which {@link splitMultilineSpans} and {@link splitMultilineLinks} couldn’t split.\n * @param {string} text Text matched by one of {@link MULTILINE_FORMATTING_REGEXES}.\n * @returns {boolean} Result.\n */\nconst hasLineBreakInSpan = (text) =>\n  findCodeSpans(text).some(({ start, end }) => text.slice(start, end).includes('\\n')) ||\n  HAS_MULTILINE_LINK_TEXT_REGEX.test(text);\n\n/**\n * Split multiline formatting into separate lines to prevent Markdown parsing issues. Fenced code\n * blocks are left untouched, as the formatting syntax is not parsed there. Formatting is left as is\n * if a line after the first starts a block, like a heading or a list item, which ends the paragraph\n * and therefore the formatting.\n * @param {string} value Markdown string to process.\n * @returns {string} Processed Markdown string.\n * @see https://github.com/sveltia/sveltia-cms/issues/548\n */\nexport const splitMultilineFormatting = (value) =>\n  mapOutsideCodeBlocks(value, (part) => {\n    let result = splitMultilineSpans(part);\n    let previous;\n\n    // Split the inner formatting first, so `**_foo\\nbar_**` becomes `**_foo_**\\n**_bar_**`, not\n    // `**_foo**_\\n_**bar_**`. The outer one is split on the next pass. A text can’t have its own\n    // marker, so formatting is nested a few levels deep at most\n    while (result !== previous) {\n      previous = result;\n      result = MULTILINE_FORMATTING_REGEXES.reduce(\n        (current, [marker, regex]) =>\n          current.replace(regex, (match, formattedText, offset) => {\n            if (hasMultilineFormatting(formattedText)) {\n              return match;\n            }\n\n            const text = splitMultilineLinks(formattedText);\n\n            // A line break left within a code span or a link text can’t be split there, as the\n            // markers would become part of the code or the link\n            if (hasLineBreakInSpan(text)) {\n              return match;\n            }\n\n            const lines = splitFormattedLines(text);\n\n            // The formatting can only continue on a line in the same blockquote as the first one\n            const level = getBlockquoteLevel(\n              getBlockquotePrefix(current.slice(current.lastIndexOf('\\n', offset - 1) + 1, offset)),\n            );\n\n            // A line with only markers, like `**` in `_**\\n**_` of `**_(a)_**\\n**_(b)_**`, means\n            // the match runs from the closing marker of one line to the opening marker of the next,\n            // which isn’t formatting. Splitting it would add markers that match again, without end\n            if (\n              lines.some(({ text: lineText }) => /^[*_~]+$/.test(lineText)) ||\n              lines\n                .slice(1)\n                .some(\n                  ({ quote, indent, text: lineText }) =>\n                    !isInSameBlockquote(level, quote) ||\n                    interruptsParagraph(`${indent.slice(quote.length)}${lineText}`),\n                )\n            ) {\n              return match;\n            }\n\n            return lines\n              .map(\n                ({ indent, text: lineText, lineEnd }) =>\n                  `${indent}${marker}${lineText}${marker}${lineEnd}`,\n              )\n              .join('\\n');\n          }),\n        result,\n      );\n    }\n\n    return result;\n  });\n","/**\n * Placeholders added to Markdown before it’s imported, so Lexical reads it as CommonMark does,\n * and removed from the imported text.\n */\n\nimport {\n  CODE_SPACE_PLACEHOLDER,\n  CODE_TAB_PLACEHOLDER,\n  ESCAPED_BACKSLASH_PLACEHOLDER,\n  HTML_BLOCK_PLACEHOLDER,\n  PUNCTUATION_PLACEHOLDER,\n} from '../placeholder-chars.js';\nimport { findHtmlBlockLines } from './block-structure.js';\nimport { mapLinesOutsideCodeBlocks, mapOutsideCodeBlocks } from './code-blocks.js';\nimport { findCodeSpans, mapCodeSpans } from './code-spans.js';\nimport { countBackslashesBefore, INLINE_HTML_REGEX } from './syntax.js';\n\n/**\n * @import { CodeSpan } from './code-spans.js';\n */\n\n/**\n * Global version of `INLINE_HTML_REGEX`.\n */\nconst GLOBAL_INLINE_HTML_REGEX = new RegExp(INLINE_HTML_REGEX, 'g');\n\n/**\n * Add placeholders around the backslashes at the end of a line, so Lexical reads them as CommonMark\n * does. Lexical looks for a hard line break, a backslash at the end of a line, after it has removed\n * the escapes from the text, so an escaped backslash, like `foo\\\\`, `` `foo\\` `` in a code span or\n * `_foo\\\\_`, becomes a hard line break, losing the backslash, and `foo\\\\\\` loses its hard line\n * break. A placeholder after the escaped backslashes, or before the closing backticks of a code\n * span, keeps the backslash from ending the text.\n * @param {string} line Line.\n * @returns {string} Processed line.\n * @see https://spec.commonmark.org/0.31.2/#hard-line-breaks\n */\nconst markLineEndBackslashes = (line) => {\n  if (!/[\\\\`][*_~]*$/.test(line)) {\n    return line;\n  }\n\n  const codeSpan = findCodeSpans(line).findLast(({ end }) => /^[*_~]*$/.test(line.slice(end)));\n\n  // Backslashes are literal in a code span\n  if (codeSpan) {\n    const index = codeSpan.end - codeSpan.fenceLength;\n\n    return line[index - 1] === '\\\\'\n      ? `${line.slice(0, index)}${ESCAPED_BACKSLASH_PLACEHOLDER}${line.slice(index)}`\n      : line;\n  }\n\n  // The escaped backslashes are followed by formatting markers, if any, and the backslash of a hard\n  // line break, if any. They’re counted from the end rather than matched with a regular expression,\n  // which would take quadratic time on a long run of backslashes or markers\n  const index = [true, false]\n    .map((hasHardLineBreak) => {\n      let end = line.length - (hasHardLineBreak && line.endsWith('\\\\') ? 1 : 0);\n\n      while (end > 0 && '*_~'.includes(line[end - 1])) {\n        end -= 1;\n      }\n\n      const backslashes = countBackslashesBefore(line, end);\n\n      return backslashes && backslashes % 2 === 0 ? end : -1;\n    })\n    .find((end) => end !== -1);\n\n  return index === undefined\n    ? line\n    : `${line.slice(0, index)}${ESCAPED_BACKSLASH_PLACEHOLDER}${line.slice(index)}`;\n};\n\n/**\n * Regular expression to match the place between a formatting marker run that isn’t escaped and a\n * backslash: after the run, like in `_foo_\\`, or before it, after an escaped backslash, like in\n * `\\\\_foo_`.\n */\nconst MARKER_BACKSLASH_REGEX =\n  // Each lookahead comes first, so its lookbehind is only tried next to a marker or a backslash\n  /(?=\\\\)(?<=(?:^|[^\\\\])(?:\\\\\\\\)*[*_~])|(?=[*_~])(?<=(?:^|[^\\\\])(?:\\\\\\\\)+)/g;\n\n/**\n * Put a period, which Lexical takes as punctuation, between a backslash and a formatting marker.\n * Unlike CommonMark, Lexical doesn’t take a backslash as punctuation, so it reads the marker as\n * being within a word: it doesn’t read `_foo_\\` or `**foo.**\\` as formatted, as the marker can’t\n * close the formatting there, nor `\\\\_foo_`, as it can’t open it. The period gives the marker the\n * same neighbor as in CommonMark. A placeholder on the backslash side lets it be removed, and keeps\n * it from being escaped by the backslash.\n * @param {string} line Line.\n * @returns {string} Processed line.\n * @see https://spec.commonmark.org/0.31.2/#left-flanking-delimiter-run\n */\nconst markMarkersNextToBackslashes = (line) =>\n  /[*_~]\\\\|\\\\[*_~]/.test(line)\n    ? line.replace(MARKER_BACKSLASH_REGEX, (_match, index) =>\n        // The period goes next to the marker\n        '*_~'.includes(line[index]) ? `${PUNCTUATION_PLACEHOLDER}.` : `.${PUNCTUATION_PLACEHOLDER}`,\n      )\n    : line;\n\n/**\n * Regular expression to match the place between a formatting marker and a punctuation character or\n * a symbol other than ASCII, like an en dash or a curly quote.\n */\nconst MARKER_UNICODE_PUNCTUATION_REGEX =\n  /(?<=[*_~])(?=(?![\\0-\\x7F])[\\p{P}\\p{S}])|(?<=(?![\\0-\\x7F])[\\p{P}\\p{S}])(?=[*_~])/gu;\n\n/**\n * Put a period, which Lexical takes as punctuation, between a formatting marker and a punctuation\n * character or a symbol other than ASCII. Unlike CommonMark, Lexical only takes ASCII characters as\n * punctuation, so it reads the marker as being next to a letter: it doesn’t read `**[a](u)**` in\n * `–**[a](u)**` or `“**[a](u)**”` as bold, as the marker can’t open or close the formatting there.\n * The period gives the marker the same neighbor as in CommonMark. A placeholder on the other side\n * lets it be removed.\n * @param {string} line Line.\n * @returns {string} Processed line.\n * @see https://spec.commonmark.org/0.31.2/#unicode-punctuation-character\n * @see https://github.com/sveltia/sveltia-cms/issues/1107\n */\nconst markMarkersNextToUnicodePunctuation = (line) =>\n  /[^\\0-\\x7F]/.test(line)\n    ? line.replace(MARKER_UNICODE_PUNCTUATION_REGEX, (_match, index) =>\n        // The period goes next to the marker\n        '*_~'.includes(line[index - 1])\n          ? `.${PUNCTUATION_PLACEHOLDER}`\n          : `${PUNCTUATION_PLACEHOLDER}.`,\n      )\n    : line;\n\n/**\n * Replace the tabs in the code spans of a line, and the spaces in a code span made only of spaces,\n * with placeholders. Lexical turns a tab into a tab node, which has no format, so a tab in a code\n * span would leave the code span, and a code span with only tabs would be exported as text. Also,\n * Lexical takes a paragraph with up to 3 whitespace characters as empty, and removes it, even if\n * they’re code, like `` ` ` ``. The spaces of other code spans are left alone, as one of them is\n * stripped from both ends of the code span if the code isn’t all spaces.\n * @param {string} line Line.\n * @returns {string} Processed line.\n * @see https://spec.commonmark.org/0.31.2/#code-spans\n */\nconst markCodeSpanWhitespace = (line) => {\n  if (!/`[ \\t]|\\t/.test(line)) {\n    return line;\n  }\n\n  return mapCodeSpans(line, {\n    /**\n     * Replace the whitespace in the code of a code span.\n     * @param {string} codeSpan Code span, with its backticks.\n     * @param {CodeSpan} span Position of the code span.\n     * @returns {string} Processed code span.\n     */\n    inside: (codeSpan, { fenceLength }) => {\n      const fence = codeSpan.slice(0, fenceLength);\n      const content = codeSpan.slice(fenceLength, -fenceLength);\n\n      return `${fence}${\n        /^ +$/.test(content)\n          ? CODE_SPACE_PLACEHOLDER.repeat(content.length)\n          : content.replaceAll('\\t', CODE_TAB_PLACEHOLDER)\n      }${fence}`;\n    },\n  });\n};\n\n/**\n * Mark the lines of the HTML blocks in a part of a Markdown string with a placeholder at the start,\n * so they’re imported as raw HTML, without the Markdown syntax being read; see `RAW_HTML`. Their\n * tabs, and those in the inline HTML of the other lines, are replaced with a placeholder, as\n * Lexical would otherwise split the raw HTML into separate nodes around a tab node.\n * @param {string} part Part of a Markdown string outside fenced code blocks.\n * @returns {string} Processed part.\n * @see https://spec.commonmark.org/0.31.2/#html-blocks\n * @see https://github.com/sveltia/sveltia-cms/issues/1106\n */\nconst markHtml = (part) => {\n  const lines = part.split('\\n');\n  const htmlBlockLines = findHtmlBlockLines(lines);\n\n  return lines\n    .map((line, index) => {\n      if (htmlBlockLines[index]) {\n        return `${HTML_BLOCK_PLACEHOLDER}${line.replaceAll('\\t', CODE_TAB_PLACEHOLDER)}`;\n      }\n\n      return line.includes('\\t')\n        ? line.replace(GLOBAL_INLINE_HTML_REGEX, (tag) =>\n            tag.replaceAll('\\t', CODE_TAB_PLACEHOLDER),\n          )\n        : line;\n    })\n    .join('\\n');\n};\n\n/**\n * Add placeholders to a Markdown string, so Lexical reads it as CommonMark does; see\n * `markLineEndBackslashes()`, `markMarkersNextToBackslashes()`,\n * `markMarkersNextToUnicodePunctuation()` and `markCodeSpanWhitespace()`.\n * Lines in fenced code blocks are left untouched. The placeholders are removed from the imported\n * text with `removeImportPlaceholders()`.\n * @param {string} value Markdown string to process.\n * @returns {string} Processed Markdown string.\n */\nexport const addImportPlaceholders = (value) =>\n  mapLinesOutsideCodeBlocks(\n    value.includes('<') ? mapOutsideCodeBlocks(value, markHtml) : value,\n    (line) =>\n      markCodeSpanWhitespace(\n        markMarkersNextToUnicodePunctuation(\n          markMarkersNextToBackslashes(markLineEndBackslashes(line)),\n        ),\n      ),\n  );\n\n/**\n * Remove the placeholders added by `addImportPlaceholders()` from imported text.\n * @param {string} text Text.\n * @returns {string} Text without the placeholders.\n */\nexport const removeImportPlaceholders = (text) =>\n  text\n    .replace(new RegExp(`\\\\.${PUNCTUATION_PLACEHOLDER}|${PUNCTUATION_PLACEHOLDER}\\\\.`, 'g'), '')\n    .replaceAll(ESCAPED_BACKSLASH_PLACEHOLDER, '')\n    .replaceAll(HTML_BLOCK_PLACEHOLDER, '')\n    .replaceAll(CODE_TAB_PLACEHOLDER, '\\t')\n    .replaceAll(CODE_SPACE_PLACEHOLDER, ' ');\n","/**\n * Markdown processing of the rich text editor: the Markdown is prepared before it’s imported, so\n * Lexical reads it as CommonMark does, and the placeholders added for that are removed afterwards.\n */\n\nimport {\n  convertSetextHeadings,\n  convertTildeFences,\n  padBlankBlockquoteLines,\n} from './block-conversion.js';\nimport { withLineCache } from './code-blocks.js';\nimport { splitMultilineFormatting } from './formatting.js';\nimport { addImportPlaceholders } from './placeholders.js';\n\nexport { trimBlankBlockquoteLines } from './block-conversion.js';\nexport { removeImportPlaceholders } from './placeholders.js';\n\n/**\n * Convert the block syntax Lexical doesn’t support to the one it does, if the element is enabled:\n * tilde code fences to backtick ones, and setext headings to ATX ones. Otherwise the syntax is kept\n * as text, as written.\n * @param {string} value Markdown.\n * @param {object} features Enabled features.\n * @param {boolean} features.hasCodeBlocks Whether code blocks are supported.\n * @param {boolean} features.hasHeadings Whether headings are supported.\n * @returns {string} Converted Markdown.\n */\nexport const convertBlockSyntax = (value, { hasCodeBlocks, hasHeadings }) =>\n  withLineCache(() => {\n    const fencedValue = hasCodeBlocks ? convertTildeFences(value) : value;\n\n    return hasHeadings ? convertSetextHeadings(fencedValue) : fencedValue;\n  });\n\n/**\n * Get the Markdown Lexical reads as CommonMark does, from Markdown converted with\n * {@link convertBlockSyntax}. Formatting that spans line breaks is split into one per line first,\n * as Lexical reads Markdown line by line, so the placeholders that follow are added to the final\n * lines: they mark the backslashes, the tabs in code spans and raw HTML. Blank blockquote lines\n * are then padded, so they are not imported as literal `>` text. The placeholders are removed from\n * the imported text with `removeImportPlaceholders()`.\n * @param {string} value Markdown.\n * @returns {{ markdown: string, hasPlaceholders: boolean }} Markdown to import, and whether any\n * placeholder has been added.\n */\nexport const toLexicalMarkdown = (value) =>\n  withLineCache(() => {\n    const splitValue = splitMultilineFormatting(value);\n    const markedValue = addImportPlaceholders(splitValue);\n\n    return {\n      markdown: padBlankBlockquoteLines(markedValue),\n      hasPlaceholders: markedValue !== splitValue,\n    };\n  });\n","/**\n * Text alignment helpers for the rich text editor. Alignment is only available for HTML, as\n * Markdown has no syntax for it. Functions starting with `$` must be called within an editor update\n * or read.\n */\n\nimport { $findMatchingParent as findMatchingParent } from '@lexical/utils';\nimport {\n  $getSelection as getSelection,\n  $isElementNode as isElementNode,\n  $isRangeSelection as isRangeSelection,\n} from 'lexical';\n\n/**\n * @import { ElementFormatType, ElementNode } from 'lexical';\n */\n\n/**\n * Get the text alignment of the block the selection’s anchor is in, like a paragraph, a heading or\n * a list item.\n * @returns {ElementFormatType} Alignment. An empty string means the default alignment, as well as\n * no selection.\n */\nexport const $getSelectedAlignment = () => {\n  const selection = getSelection();\n\n  if (!isRangeSelection(selection)) {\n    return '';\n  }\n\n  const block = /** @type {ElementNode | null} */ (\n    findMatchingParent(\n      selection.anchor.getNode(),\n      (node) => isElementNode(node) && !node.isInline(),\n    )\n  );\n\n  // The caret can be on the root itself, between blocks, like next to a horizontal rule\n  return block?.getFormatType() ?? '';\n};\n","/**\n * The state of the editor selection, for the toolbar.\n */\n\nimport {\n  $isCodeHighlightNode as isCodeHighlightNode,\n  $isCodeNode as isCodeNode,\n} from '@lexical/code-core';\nimport { $isLinkNode as isLinkNode } from '@lexical/link';\nimport {\n  $isListItemNode as isListItemNode,\n  $isListNode as isListNode,\n  ListNode,\n} from '@lexical/list';\nimport { $isHeadingNode as isHeadingNode, $isQuoteNode as isQuoteNode } from '@lexical/rich-text';\nimport { $getNearestNodeOfType as getNearestNodeOfType } from '@lexical/utils';\nimport {\n  ElementNode,\n  $getSelection as getSelection,\n  $isRangeSelection as isRangeSelection,\n} from 'lexical';\nimport { BLOCK_BUTTON_TYPES, LIST_TYPES, TEXT_FORMAT_BUTTON_TYPES } from '../constants.js';\nimport { $getSelectedAlignment } from './alignment.js';\nimport { $getSelectedTableCellKey } from './table.js';\n\n/**\n * @import { LexicalNode } from 'lexical';\n * @import {\n * TextEditorBlockType,\n * TextEditorInlineType,\n * TextEditorSelectionState,\n * } from '../../../typedefs.js';\n */\n\n/**\n * Get the given node itself if it’s an element node, or its nearest element node ancestor.\n * @param {LexicalNode} node Node.\n * @returns {ElementNode | null} Element node.\n */\nexport const getNearestElementNode = (node) =>\n  node instanceof ElementNode ? node : getNearestNodeOfType(node, ElementNode);\n\n/**\n * Get the current selection’s block node key as well as block and inline level types.\n * @internal\n * @returns {TextEditorSelectionState} Current selection state.\n */\nexport const getSelectionTypes = () => {\n  const selection = getSelection();\n\n  if (!isRangeSelection(selection)) {\n    return {\n      blockNodeKey: null,\n      blockType: 'paragraph',\n      inlineTypes: [],\n      // Several cells can be selected at once\n      tableCellKey: $getSelectedTableCellKey(),\n      alignment: '',\n    };\n  }\n\n  const anchor = selection.anchor.getNode();\n  /** @type {ElementNode | null} */\n  let parent = null;\n  /** @type {TextEditorInlineType[]} */\n  const inlineTypes = TEXT_FORMAT_BUTTON_TYPES.filter((type) => selection.hasFormat(type));\n\n  if (anchor.getType() !== 'root') {\n    parent = getNearestElementNode(anchor);\n\n    if (isLinkNode(parent)) {\n      inlineTypes.push('link');\n      // `getNearestNodeOfType()` would return the link itself, so start from its parent to find the\n      // block the link is in\n      parent = parent.getParent();\n    }\n\n    if (isListItemNode(parent)) {\n      parent = getNearestNodeOfType(parent, ListNode);\n    }\n  }\n\n  const blockType = /** @type {TextEditorBlockType} */ (\n    (() => {\n      if (!parent) {\n        return 'paragraph';\n      }\n\n      if (isHeadingNode(parent)) {\n        return `heading-${parent.getTag().match(/\\d/)?.[0]}`;\n      }\n\n      if (isListNode(parent)) {\n        const listType = parent.getListType();\n\n        return /** @type {TextEditorBlockType} */ (\n          LIST_TYPES.find((list) => list.listType === listType)?.type\n        );\n      }\n\n      if (isQuoteNode(parent)) {\n        return 'blockquote';\n      }\n\n      if (isCodeNode(parent) || isCodeHighlightNode(parent)) {\n        return 'code-block';\n      }\n\n      const type = parent.getType();\n\n      if (BLOCK_BUTTON_TYPES.includes(/** @type {any} */ (type))) {\n        return type;\n      }\n\n      return 'paragraph';\n    })()\n  );\n\n  return {\n    blockNodeKey: parent?.getKey() ?? null,\n    blockType,\n    inlineTypes,\n    tableCellKey: $getSelectedTableCellKey(),\n    alignment: $getSelectedAlignment(),\n  };\n};\n","/**\n * Helpers shared by the editor modules.\n */\n\n/**\n * Combine the given cleanup handlers into one, which calls them in the given order. Missing\n * handlers, like those of the features that are not enabled, are skipped.\n * @param {...((() => void) | undefined | null)} unregisters Cleanup handlers.\n * @returns {() => void} Combined cleanup handler.\n */\nexport const mergeUnregisters = (...unregisters) => {\n  const handlers = unregisters.filter((unregister) => typeof unregister === 'function');\n\n  return () => {\n    handlers.forEach((unregister) => unregister());\n  };\n};\n","/**\n * Exporting the editor content, and passing it on as it changes.\n */\n\nimport { $convertToMarkdownString as convertToMarkdownString } from '@lexical/markdown';\nimport { sleep } from '@sveltia/utils/misc';\nimport { DISABLED_MARKDOWN_TAGS } from '../constants.js';\nimport { exportHtml } from './html/index.js';\nimport { trimBlankBlockquoteLines } from './markdown/index.js';\nimport { BLOCK_SYNTAX_ESCAPE } from './transformers/block-escape.js';\nimport { getSelectionTypes } from '../editing/selection.js';\nimport { mergeUnregisters } from '../utils.js';\n\n/**\n * @import { LexicalEditor } from 'lexical';\n * @import { Transformer } from '@lexical/markdown';\n * @import { TextEditorSelectionState, TextEditorValueFormat } from '../../../typedefs.js';\n */\n\n/**\n * Value exported from the editor, and the selection state at the time.\n * @typedef {object} ExportDetail\n * @property {string} value Markdown or HTML value.\n * @property {TextEditorSelectionState} selection Selection state.\n */\n\n/**\n * Convert the editor content to Markdown. Call this within an editor update or read.\n * @internal\n * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.\n * @returns {string} Markdown value.\n */\nexport const exportMarkdown = (enabledTransformers) => {\n  const transformers = [\n    ...enabledTransformers.filter(\n      (/** @type {any} */ { tag }) => !DISABLED_MARKDOWN_TAGS.includes(tag),\n    ),\n    // Tidy up the escapes in text and escape the block syntax at the start of a line. Last, so a\n    // transformer of the editor’s own, such as a link, comes first\n    BLOCK_SYNTAX_ESCAPE,\n  ];\n\n  return trimBlankBlockquoteLines(\n    convertToMarkdownString(transformers)\n      // Remove the line breaks left by empty paragraphs at the end, which have no content. One\n      // may be added just by clicking below a block decorator; see `$moveCaretIntoBlock()`\n      .replace(/\\n+$/, ''),\n  );\n};\n\n/**\n * Export the editor content as Markdown or HTML. Call this within an editor update or read.\n * @internal\n * @param {LexicalEditor} editor Editor instance.\n * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.\n * @param {TextEditorValueFormat} [format] Value format.\n * @returns {string} Markdown or HTML value.\n */\nexport const exportValue = (editor, enabledTransformers, format = 'markdown') =>\n  format === 'html' ? exportHtml(editor) : exportMarkdown(enabledTransformers);\n\n/**\n * Register an update listener that exports the editor content as Markdown or HTML, and passes it\n * on along with the selection state, debounced so only the latest update in a burst is exported.\n * @param {LexicalEditor} editor Editor instance.\n * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.\n * @param {TextEditorValueFormat} format Value format.\n * @param {(detail: ExportDetail) => void} onExport Function to call with the exported value. It’s\n * called within an editor update.\n * @returns {{ flush: () => void, unregister: () => void }} `flush` exports the content scheduled\n * to be exported right away, instead of after the delay, so the value reflects what was just\n * typed. Call it before acting on the value, like when the focus leaves the editor or before\n * switching to the Markdown or HTML source. It does nothing if nothing is scheduled. `unregister`\n * removes the listener.\n */\nexport const registerValueExport = (editor, enabledTransformers, format, onExport) => {\n  /** Incremented on every update, so only the latest one in a burst is exported. */\n  let updateCount = 0;\n  /** Whether the content has changed since it was last exported. */\n  let contentChanged = true;\n  /** @type {string | undefined} */\n  let lastValue = undefined;\n  let disposed = false;\n  /** Whether an export is scheduled, and hasn’t been made yet. */\n  let scheduled = false;\n\n  /**\n   * Export the current value, and pass it on.\n   */\n  const triggerExport = () => {\n    scheduled = false;\n\n    editor.update(() => {\n      // Reuse the value when only the selection has changed, instead of converting the whole\n      // document again\n      const value =\n        (contentChanged ? undefined : lastValue) ??\n        exportValue(editor, enabledTransformers, format);\n\n      onExport({ value, selection: getSelectionTypes() });\n      lastValue = value;\n      contentChanged = false;\n    });\n  };\n\n  /**\n   * Export the scheduled value right away.\n   */\n  const flush = () => {\n    if (scheduled && !disposed && !editor.isComposing()) {\n      triggerExport();\n    }\n  };\n\n  const unregister = mergeUnregisters(\n    () => {\n      disposed = true;\n    },\n    editor.registerUpdateListener(({ dirtyElements, dirtyLeaves } = /** @type {any} */ ({})) => {\n      // An update that only moves the selection leaves no dirty nodes. Remember whether any update\n      // in the burst changed the content, so the document is only converted again when needed.\n      // This includes the updates made while composing, which are otherwise skipped.\n      contentChanged ||= !dirtyElements || dirtyElements.size > 0 || dirtyLeaves.size > 0;\n\n      if (editor?.isComposing()) {\n        return;\n      }\n\n      updateCount += 1;\n      scheduled = true;\n\n      const currentCount = updateCount;\n\n      (async () => {\n        await sleep(100);\n\n        // Skip if a newer update has been made in the meantime, the value has been exported\n        // already with `flush()`, or the editor has been disposed\n        if (currentCount !== updateCount || !scheduled || disposed) {\n          return;\n        }\n\n        triggerExport();\n      })();\n    }),\n  );\n\n  return { flush, unregister };\n};\n","/**\n * Editor components: custom nodes with their own Markdown transformers.\n */\n\nimport {\n  createEditor,\n  $createParagraphNode as createParagraphNode,\n  $getRoot as getRoot,\n} from 'lexical';\nimport { removeImportPlaceholders } from './markdown/index.js';\nimport { HTML_BLOCK_PLACEHOLDER } from './placeholder-chars.js';\nimport { exportValue } from './update.js';\n\n/**\n * @import { Transformer } from '@lexical/markdown';\n * @import { TextEditorComponent } from '../../../typedefs.js';\n */\n\n/**\n * Get the Markdown of a new instance of the given editor component, to insert it in the plain text\n * mode. The component’s own `createMarkdown` function is used if any. Otherwise, a new node is\n * created in a temporary editor and exported with the component’s transformer, just like the rich\n * text editor does.\n * @param {TextEditorComponent} component Editor component.\n * @returns {string} Markdown. It can be empty, for example if the component’s output depends on a\n * field value that is not set yet.\n */\nexport const getComponentMarkdown = ({ node, createNode, transformer, createMarkdown }) => {\n  if (createMarkdown) {\n    return createMarkdown().trim();\n  }\n\n  const editor = createEditor({\n    namespace: 'component',\n    nodes: node ? [/** @type {any} */ (node)] : [],\n    /**\n     * Throw an error, so the export below fails as a whole.\n     * @param {Error} error Error.\n     * @throws {Error} Always.\n     */\n    onError: (error) => {\n      throw error;\n    },\n  });\n\n  let markdown = '';\n\n  try {\n    editor.update(\n      () => {\n        const newNode = createNode();\n\n        // An inline node needs a paragraph to live in\n        getRoot().append(newNode.isInline() ? createParagraphNode().append(newNode) : newNode);\n\n        markdown = exportValue(editor, [transformer]);\n      },\n      { discrete: true },\n    );\n  } catch {\n    // The component cannot be created or exported outside the rich text editor\n  }\n\n  return markdown.trim();\n};\n\n/**\n * Check if the given editor component is inline, which means its Markdown is matched within a line\n * of text by a text match transformer. Only an inline component can be inserted into a Markdown\n * table cell or a single-line editor.\n * @param {TextEditorComponent} component Editor component.\n * @returns {boolean} Result.\n */\nexport const isInlineComponent = ({ transformer }) => transformer.type === 'text-match';\n\n/**\n * Remove the placeholders added by `addImportPlaceholders()` from a regular expression match.\n * @param {RegExpMatchArray} match Match.\n * @returns {RegExpMatchArray} Match without the placeholders, with the same index and input.\n */\nconst cleanMatch = (match) => {\n  /**\n   * Remove the placeholders from a captured string, if any.\n   * @param {string | undefined} value Captured string.\n   * @returns {string | undefined} Cleaned string.\n   */\n  const clean = (value) => (value === undefined ? value : removeImportPlaceholders(value));\n\n  return /** @type {RegExpMatchArray} */ (\n    Object.assign(match.map(clean), {\n      index: match.index,\n      input: match.input,\n      groups: match.groups\n        ? Object.fromEntries(\n            Object.entries(match.groups).map(([key, value]) => [key, clean(value)]),\n          )\n        : undefined,\n    })\n  );\n};\n\n/**\n * Make a regular expression match the text after the placeholder at the start of a line of an HTML\n * block, if any, so the pattern of an editor component, like `^<aside>`, still matches the line.\n * @param {RegExp} regExp Regular expression without the `g` flag.\n * @param {boolean} isLineStart Whether Lexical takes the match as the start of the line and removes\n * it by its length, like that of an element transformer, in which case the match includes the\n * placeholder. Otherwise its index is moved past the placeholder.\n * @returns {RegExp} Regular expression.\n */\nconst skipHtmlBlockPlaceholder = (regExp, isLineStart) =>\n  // Lexical matches the text with `String.prototype.match()`, which calls this method\n  Object.assign(new RegExp(regExp), {\n    /**\n     * Match the text after the placeholder at its start, if any.\n     * @param {string} text Text.\n     * @returns {RegExpMatchArray | null} Match.\n     */\n    [Symbol.match]: (text) => {\n      const offset = text.startsWith(HTML_BLOCK_PLACEHOLDER) ? 1 : 0;\n      const match = text.slice(offset).match(regExp);\n\n      if (!match || !offset) {\n        return match;\n      }\n\n      match.input = text;\n\n      if (isLineStart && match.index === 0) {\n        match[0] = `${HTML_BLOCK_PLACEHOLDER}${match[0]}`;\n      } else {\n        // The pattern has no `g` flag, so the match has an index\n        /** @type {number} */ (match.index) += offset;\n      }\n\n      return match;\n    },\n  });\n\n/**\n * Remove the placeholders added by `addImportPlaceholders()` from an argument of a transformer’s\n * `replace()`: a regular expression match, or the lines of a multiline element.\n * @param {any} arg Argument.\n * @returns {any} Argument without the placeholders.\n */\nconst cleanReplaceArg = (arg) => {\n  if (!Array.isArray(arg)) {\n    return arg;\n  }\n\n  if ('index' in arg) {\n    return cleanMatch(/** @type {RegExpMatchArray} */ (arg));\n  }\n\n  return arg.every((item) => typeof item === 'string')\n    ? arg.map((line) => removeImportPlaceholders(line))\n    : arg;\n};\n\n/**\n * Make an editor component’s transformer import the Markdown without the placeholders added by\n * `addImportPlaceholders()`, which `removePlaceholders()` can’t remove from the properties of the\n * component node it creates, like the alt text of an image. The line of an HTML block starts with\n * a placeholder, so the patterns of a component, like `^<aside>`, are matched after it.\n * @param {Transformer} transformer Transformer.\n * @returns {Transformer} Transformer.\n */\nexport const removePlaceholdersFromMatch = (transformer) => {\n  /** @type {any} */\n  const {\n    type,\n    handleImportAfterStartMatch,\n    importRegExp,\n    regExp,\n    regExpStart,\n    regExpEnd,\n    replace,\n  } = transformer;\n\n  /** @type {Record<string, any>} */\n  const overrides = {};\n\n  if (handleImportAfterStartMatch) {\n    /**\n     * Import the lines without the placeholders.\n     * @param {{ lines: string[] }} args Arguments.\n     * @returns {any} Result.\n     */\n    overrides.handleImportAfterStartMatch = (args) =>\n      handleImportAfterStartMatch({\n        ...args,\n        lines: args.lines.map((line) => removeImportPlaceholders(line)),\n      });\n  }\n\n  if (importRegExp) {\n    overrides.importRegExp = skipHtmlBlockPlaceholder(importRegExp, false);\n  }\n\n  // The regular expression of an element is matched against the start of a line on import\n  if (type === 'element' && regExp) {\n    overrides.regExp = skipHtmlBlockPlaceholder(regExp, true);\n  }\n\n  if (regExpStart) {\n    overrides.regExpStart = skipHtmlBlockPlaceholder(regExpStart, true);\n  }\n\n  if (regExpEnd instanceof RegExp) {\n    overrides.regExpEnd = skipHtmlBlockPlaceholder(regExpEnd, true);\n  } else if (regExpEnd?.regExp) {\n    overrides.regExpEnd = {\n      ...regExpEnd,\n      regExp: skipHtmlBlockPlaceholder(regExpEnd.regExp, true),\n    };\n  }\n\n  if (replace) {\n    /**\n     * Import the match and the lines without the placeholders.\n     * @param {...any} args Arguments.\n     * @returns {any} Result.\n     */\n    overrides.replace = (...args) => replace(...args.map(cleanReplaceArg));\n  }\n\n  return /** @type {Transformer} */ ({ ...transformer, ...overrides });\n};\n","/**\n * Keeping a single-line editor on one line.\n */\n\nimport { $isLinkNode as isLinkNode } from '@lexical/link';\nimport {\n  COMMAND_PRIORITY_HIGH,\n  $createParagraphNode as createParagraphNode,\n  $createTextNode as createTextNode,\n  INSERT_LINE_BREAK_COMMAND,\n  INSERT_PARAGRAPH_COMMAND,\n  KEY_ENTER_COMMAND,\n  LineBreakNode,\n  $isElementNode as isElementNode,\n  $isParagraphNode as isParagraphNode,\n  $isTextNode as isTextNode,\n  RootNode,\n} from 'lexical';\nimport { INLINE_BUTTON_TYPES, TEXT_FORMAT_BUTTON_TYPES } from '../constants.js';\nimport { isInlineComponent } from '../conversion/editor-components.js';\nimport { mergeUnregisters } from '../utils.js';\n\n/**\n * @import { LexicalEditor, LexicalNode } from 'lexical';\n * @import { TextEditorConfig, TextEditorNodeType } from '../../../typedefs.js';\n */\n\n/**\n * Limit the given editor configuration to what a single-line editor can hold, if it’s one: only\n * the inline buttons and components, and no plain text mode for HTML, whose source can’t be kept to\n * a single paragraph by keeping it on a single line. Any other configuration is returned as is.\n * @param {TextEditorConfig} config Editor configuration.\n * @returns {TextEditorConfig} Limited configuration.\n */\nexport const limitToSingleLine = (config) => {\n  if (config.multiline !== false || config.isCodeEditor) {\n    return config;\n  }\n\n  return {\n    ...config,\n    modes: config.format === 'html' ? ['rich-text'] : config.modes,\n    enabledButtons: (config.enabledButtons ?? []).filter((button) =>\n      /** @type {TextEditorNodeType[]} */ (INLINE_BUTTON_TYPES).includes(button),\n    ),\n    components: (config.components ?? []).filter(isInlineComponent),\n  };\n};\n\n/**\n * Get the inline content of the given top-level node, looking into any block within it.\n * @param {LexicalNode} node Node.\n * @returns {LexicalNode[]} Inline nodes, or an empty array for a block that has no inline content,\n * like a horizontal rule.\n */\nconst getInlineContent = (node) => {\n  if (isElementNode(node) && !node.isInline()) {\n    return node.getChildren().flatMap(getInlineContent);\n  }\n\n  return node.isInline() ? [node] : [];\n};\n\n/**\n * Join the top-level nodes of the given root into a single paragraph, with a space between the\n * content of each, for a single-line editor.\n * @param {RootNode} root Root node.\n */\nexport const $joinIntoSingleParagraph = (root) => {\n  const children = root.getChildren();\n  const [firstChild] = children;\n\n  if (!firstChild || (children.length === 1 && isParagraphNode(firstChild))) {\n    return;\n  }\n\n  const paragraph = isParagraphNode(firstChild) ? firstChild : createParagraphNode();\n\n  if (paragraph !== firstChild) {\n    firstChild.insertBefore(paragraph);\n  }\n\n  // Keep track of the last character rather than reading the growing text of the paragraph again\n  // for each block, which would take quadratic time on a long pasted document\n  let lastChar = paragraph.getTextContent().at(-1) ?? '';\n\n  children\n    .filter((child) => child !== paragraph)\n    .forEach((child) => {\n      const content = getInlineContent(child);\n      const text = content.map((node) => node.getTextContent()).join('');\n\n      // Add a space between the content of each block, unless there’s one already\n      if (content.length && paragraph.getChildrenSize() && !/\\s/.test(lastChar + text.charAt(0))) {\n        paragraph.append(createTextNode(' '));\n      }\n\n      paragraph.append(...content);\n      lastChar = text.at(-1) ?? lastChar;\n      // Lexical moves the selection out of a removed node on its own\n      child.remove();\n    });\n};\n\n/**\n * Replace the given line break with a space for a single-line editor, with the formats the text on\n * both sides shares, so a line break within bold text doesn’t split it. With a space on either side\n * already, or nothing at all, the line break is just removed.\n * @param {LineBreakNode} node Line break.\n */\nexport const $replaceLineBreak = (node) => {\n  const previous = node.getPreviousSibling();\n  const next = node.getNextSibling();\n\n  // A line break at either end of the paragraph separates nothing, so it leaves no space\n  if (\n    !previous ||\n    !next ||\n    /\\s$/.test(previous.getTextContent()) ||\n    /^\\s/.test(next.getTextContent())\n  ) {\n    node.remove();\n\n    return;\n  }\n\n  const space = createTextNode(' ');\n\n  // A link split over lines, like the ones `splitMultilineFormatting()` makes from a link within\n  // formatting, is joined back into one link\n  const isSameLink =\n    isLinkNode(previous) &&\n    isLinkNode(next) &&\n    previous.getURL() === next.getURL() &&\n    previous.getTitle() === next.getTitle() &&\n    previous.getTarget() === next.getTarget() &&\n    previous.getRel() === next.getRel();\n\n  // The text next to the line break, also within an inline element like a link\n  const before = isElementNode(previous) ? previous.getLastDescendant() : previous;\n  const after = isElementNode(next) ? next.getFirstDescendant() : next;\n\n  if (isTextNode(before) && isTextNode(after)) {\n    // Keep the formats both sides share, e.g. italic between italic and bold italic text\n    TEXT_FORMAT_BUTTON_TYPES.forEach((format) => {\n      if (before.hasFormat(format) && after.hasFormat(format)) {\n        space.toggleFormat(format);\n      }\n    });\n\n    if (before.getStyle() === after.getStyle()) {\n      space.setStyle(before.getStyle());\n    }\n  }\n\n  if (isSameLink) {\n    previous.append(space, ...next.getChildren());\n    next.remove();\n    node.remove();\n\n    return;\n  }\n\n  node.replace(space);\n};\n\n/**\n * Register the commands and transforms that keep a single-line editor on one line. Neither a new\n * paragraph nor a line break can be inserted, and any content that brings them in anyway, like\n * pasted text or an imported value, is joined into a single paragraph with spaces.\n * @param {LexicalEditor} editor Editor instance.\n * @returns {() => void} Cleanup handler.\n */\nexport const registerSingleLine = (editor) =>\n  mergeUnregisters(\n    // The emoji autocomplete, which selects an emoji with the Enter key, takes priority\n    editor.registerCommand(\n      KEY_ENTER_COMMAND,\n      (event) => {\n        event?.preventDefault();\n\n        return true;\n      },\n      COMMAND_PRIORITY_HIGH,\n    ),\n    editor.registerCommand(INSERT_PARAGRAPH_COMMAND, () => true, COMMAND_PRIORITY_HIGH),\n    editor.registerCommand(INSERT_LINE_BREAK_COMMAND, () => true, COMMAND_PRIORITY_HIGH),\n    editor.registerNodeTransform(LineBreakNode, $replaceLineBreak),\n    editor.registerNodeTransform(RootNode, $joinIntoSingleParagraph),\n  );\n","/**\n * The editor configuration: its defaults, and the features derived from it.\n */\n\nimport { limitToSingleLine } from './editing/single-line.js';\n\n/**\n * @import {\n * TextEditorComponent,\n * TextEditorConfig,\n * TextEditorNodeType,\n * TextEditorValueFormat,\n * } from '../../typedefs.js';\n */\n\n/**\n * Editor configuration with the defaults applied.\n * @typedef {TextEditorConfig & {\n * useEmojiAutocomplete: boolean,\n * defaultLanguage: string,\n * format: TextEditorValueFormat,\n * multiline: boolean,\n * }} NormalizedEditorConfig\n */\n\n/**\n * Editor configuration with the defaults applied, and the features derived from it.\n * @typedef {object} EditorSetup\n * @property {TextEditorNodeType[]} enabledButtons Enabled buttons.\n * @property {TextEditorComponent[]} components Editor components.\n * @property {boolean | undefined} useMarkdownShortcuts Whether to enable Markdown shortcuts.\n * @property {boolean} isCodeEditor Whether the editor is a code editor.\n * @property {string} defaultLanguage Default code block language.\n * @property {TextEditorValueFormat} format Value format.\n * @property {boolean} multiline Whether the editor accepts multiple lines.\n * @property {boolean} hasCodeBlock Whether to support code blocks.\n * @property {boolean} hasTable Whether to support table editing.\n * @property {boolean} hasHorizontalRule Whether to support selecting a horizontal rule.\n * @property {boolean} hasLink Whether to support links.\n * @property {boolean} hasTaskList Whether to support task lists.\n * @property {boolean} hasBlockSyntax Whether to support horizontal rules and tables in Markdown,\n * even without their buttons.\n */\n\n/**\n * Apply the defaults to the editor configuration, and limit it to the inline features if the editor\n * is limited to a single line. Normalizing a configuration again gives an equal one.\n * @param {Partial<TextEditorConfig>} config Editor configuration.\n * @returns {NormalizedEditorConfig} Normalized configuration.\n */\nexport const normalizeConfig = ({\n  modes = [],\n  enabledButtons = [],\n  components = [],\n  isCodeEditor = false,\n  useEmojiAutocomplete = false,\n  defaultLanguage = 'plain',\n  format = 'markdown',\n  multiline = true,\n  ...rest\n}) =>\n  /** @type {NormalizedEditorConfig} */ (\n    limitToSingleLine({\n      ...rest,\n      // The store always gives one; a configuration without one has no Markdown shortcuts\n      useMarkdownShortcuts: /** @type {boolean} */ (rest.useMarkdownShortcuts),\n      modes,\n      enabledButtons,\n      components,\n      isCodeEditor,\n      useEmojiAutocomplete,\n      defaultLanguage,\n      format,\n      multiline,\n    })\n  );\n\n/**\n * Derive the features from the editor configuration.\n * @param {NormalizedEditorConfig} config Editor configuration normalized with\n * {@link normalizeConfig}, like the one the editor store holds.\n * @returns {EditorSetup} Editor setup.\n */\nexport const getEditorSetup = (config) => {\n  const {\n    enabledButtons,\n    components,\n    useMarkdownShortcuts,\n    isCodeEditor,\n    defaultLanguage,\n    format,\n    multiline,\n  } = config;\n\n  return {\n    enabledButtons,\n    components,\n    useMarkdownShortcuts,\n    isCodeEditor,\n    defaultLanguage,\n    format,\n    multiline,\n    hasCodeBlock: enabledButtons.includes('code-block') || isCodeEditor,\n    hasTable: enabledButtons.includes('table') && !isCodeEditor,\n    hasHorizontalRule: enabledButtons.includes('horizontal-rule') && !isCodeEditor,\n    hasLink: enabledButtons.includes('link'),\n    hasTaskList: enabledButtons.includes('task-list'),\n    hasBlockSyntax: !isCodeEditor && multiline,\n  };\n};\n","/**\n * Commands of the code editor, lists and indentation.\n */\n\nimport {\n  CodeNode,\n  $createCodeNode as createCodeNode,\n  $isCodeNode as isCodeNode,\n} from '@lexical/code-core';\nimport {\n  $handleListInsertParagraph as handleListInsertParagraph,\n  $insertList as insertList,\n  $isListItemNode as isListItemNode,\n  registerCheckList,\n} from '@lexical/list';\nimport { $getNearestNodeOfType as getNearestNodeOfType } from '@lexical/utils';\nimport {\n  COMMAND_PRIORITY_LOW,\n  COMMAND_PRIORITY_NORMAL,\n  DELETE_CHARACTER_COMMAND,\n  $getSelection as getSelection,\n  INDENT_CONTENT_COMMAND,\n  INSERT_PARAGRAPH_COMMAND,\n  KEY_ENTER_COMMAND,\n  $isElementNode as isElementNode,\n  $isRangeSelection as isRangeSelection,\n  OUTDENT_CONTENT_COMMAND,\n  RootNode,\n} from 'lexical';\nimport { getNearestElementNode } from './selection.js';\nimport { LIST_TYPES } from '../constants.js';\nimport { mergeUnregisters } from '../utils.js';\n\n/**\n * @import { LexicalEditor } from 'lexical';\n * @import { TextEditorConfig } from '../../../typedefs.js';\n */\n\n/**\n * Register the commands and transform specific to the code editor, which only holds a single code\n * block.\n * @param {LexicalEditor} editor Editor instance.\n * @param {string} defaultLanguage Default language of the code block.\n * @returns {() => void} Cleanup handler.\n */\nexport const registerCodeEditorCommands = (editor, defaultLanguage) =>\n  mergeUnregisters(\n    // Pressing Backspace at the very beginning of a code block converts it to a paragraph by\n    // default (`CodeNode.collapseAtStart()`), which makes no sense when the editor only holds a\n    // single code block, so ignore it\n    editor.registerCommand(\n      DELETE_CHARACTER_COMMAND,\n      (isBackward) => {\n        const selection = getSelection();\n\n        if (!isBackward || !isRangeSelection(selection) || !selection.isCollapsed()) {\n          return false;\n        }\n\n        const { offset } = selection.anchor;\n        const node = selection.anchor.getNode();\n        const codeNode = isCodeNode(node) ? node : getNearestNodeOfType(node, CodeNode);\n\n        return (\n          !!codeNode &&\n          offset === 0 &&\n          (node.is(codeNode) || !!codeNode.getFirstDescendant()?.is(node))\n        );\n      },\n      COMMAND_PRIORITY_LOW,\n    ),\n    // Pressing Enter after two blank lines at the end of a code block exits it by default\n    // (`CodeExtension`), adding a paragraph after it, which would be left out of the code. Insert a\n    // new line instead, which `CodeNode.insertNewAfter()` does without exiting when the extension\n    // is in place. This has to take priority over the extension’s own handler\n    editor.registerCommand(\n      KEY_ENTER_COMMAND,\n      (event) => {\n        const selection = getSelection();\n\n        if (!isRangeSelection(selection)) {\n          return false;\n        }\n\n        event?.preventDefault();\n\n        return editor.dispatchCommand(INSERT_PARAGRAPH_COMMAND, undefined);\n      },\n      COMMAND_PRIORITY_NORMAL,\n    ),\n    // Make sure the editor always has a single code block. This runs within the same update that\n    // made the change, so the user never gets a chance to type in anything else\n    editor.registerNodeTransform(RootNode, (root) => {\n      const children = root.getChildren();\n\n      if (children.length === 1 && isCodeNode(children[0])) {\n        return;\n      }\n\n      const [firstChild] = children;\n\n      if (children.length === 1 && isElementNode(firstChild)) {\n        const node = createCodeNode(defaultLanguage);\n\n        // Keep the content and the selection\n        firstChild.replace(node, true);\n      } else if (children.length === 0) {\n        const node = createCodeNode(defaultLanguage);\n\n        root.append(node);\n        node.selectStart();\n      }\n    }),\n  );\n\n/**\n * Register the commands for the enabled list buttons. With the task list button, a check box can be\n * toggled with a click or the Space key.\n * @param {LexicalEditor} editor Editor instance.\n * @param {TextEditorConfig['enabledButtons']} enabledButtons Enabled buttons.\n * @returns {() => void} Cleanup handler.\n */\nexport const registerListCommands = (editor, enabledButtons = []) => {\n  const enabledLists = LIST_TYPES.filter(({ type }) => enabledButtons.includes(type));\n\n  return mergeUnregisters(\n    ...enabledLists.map(({ command, listType }) =>\n      editor.registerCommand(\n        command,\n        () => {\n          insertList(listType);\n\n          return true;\n        },\n        COMMAND_PRIORITY_NORMAL,\n      ),\n    ),\n    // https://github.com/facebook/lexical/blob/main/packages/lexical-react/src/shared/useList.ts\n    enabledLists.length\n      ? editor.registerCommand(\n          INSERT_PARAGRAPH_COMMAND,\n          () => handleListInsertParagraph(),\n          COMMAND_PRIORITY_NORMAL,\n        )\n      : undefined,\n    enabledButtons.includes('task-list') ? registerCheckList(editor) : undefined,\n  );\n};\n\n/**\n * Register a handler for the Tab key that indents a list item, or unindents it with Shift.\n * `editor.registerCommand(KEY_TAB_COMMAND, listener, priority)` doesn’t work for some reason, so\n * listen to the `keydown` event on the root element instead.\n * @param {LexicalEditor} editor Editor instance.\n * @returns {() => void} Cleanup handler.\n */\nexport const registerTabIndentation = (editor) =>\n  editor.registerRootListener((root) => {\n    if (!root) {\n      return undefined;\n    }\n\n    /**\n     * Handle Tab indentation shortcuts.\n     * @param {KeyboardEvent} event Keydown event.\n     */\n    const onKeydown = (event) => {\n      editor.update(() => {\n        if (event.key === 'Tab') {\n          const selection = getSelection();\n\n          if (!isRangeSelection(selection)) {\n            return;\n          }\n\n          const parent = getNearestElementNode(selection.anchor.getNode());\n\n          if (isListItemNode(parent) && parent.canIndent()) {\n            if (!event.shiftKey) {\n              event.preventDefault();\n              editor.dispatchCommand(INDENT_CONTENT_COMMAND, undefined);\n            } else if (parent.getIndent() > 0) {\n              event.preventDefault();\n              editor.dispatchCommand(OUTDENT_CONTENT_COMMAND, undefined);\n            }\n          }\n        }\n      });\n    };\n\n    root.addEventListener('keydown', onKeydown);\n\n    return () => {\n      root.removeEventListener('keydown', onKeydown);\n    };\n  });\n","/**\n * Guards that keep the formats and blocks a field can’t hold out of the editor, as they could come\n * in anyway with a keyboard shortcut Lexical handles on its own, pasted HTML or a stored value.\n */\n\nimport { ListNode } from '@lexical/list';\nimport {\n  COMMAND_PRIORITY_CRITICAL,\n  FORMAT_TEXT_COMMAND,\n  $getSelection as getSelection,\n  $isRangeSelection as isRangeSelection,\n  $isTextNode as isTextNode,\n  TextNode,\n} from 'lexical';\nimport { HTML_ONLY_FORMAT_TYPES, isHtmlOnlyButton, LIST_TYPES } from '../constants.js';\nimport { mergeUnregisters } from '../utils.js';\n\n/**\n * @import { LexicalEditor, TextFormatType } from 'lexical';\n * @import { TextEditorConfig, TextEditorValueFormat } from '../../../typedefs.js';\n */\n\n/**\n * Remove the given format from all the text in the selection, including the text partly selected,\n * or from the text to be typed at the caret. Unlike Lexical’s own toggle, which follows the text at\n * the start of the selection, it never applies the format.\n * @param {TextFormatType} type Format type.\n */\nconst $removeFormat = (type) => {\n  const selection = getSelection();\n\n  if (\n    !isRangeSelection(selection) ||\n    !(\n      selection.hasFormat(type) ||\n      selection.getNodes().some((node) => isTextNode(node) && node.hasFormat(type))\n    )\n  ) {\n    return;\n  }\n\n  // Align every node with a format that doesn’t have it\n  selection.formatText(type, 0);\n};\n\n/**\n * Keep the HTML-only text formats, like underline, out of the editor unless their buttons are\n * enabled for HTML. Lexical applies underline with the Ctrl/Cmd+U shortcut on its own, and pasted\n * HTML can bring it in as well. For Markdown, which has no syntax for them and would drop them when\n * saved, the formats are removed from any text that gets them, and the shortcut does nothing. For\n * HTML without the button, the shortcut can only remove an existing format, like one in the stored\n * value or in pasted text, which would otherwise have no button to undo it.\n * @param {LexicalEditor} editor Editor instance.\n * @param {object} args Arguments.\n * @param {TextEditorValueFormat} args.format Value format.\n * @param {TextEditorConfig['enabledButtons']} args.enabledButtons Enabled buttons.\n * @returns {() => void} Cleanup handler.\n */\nconst registerFormatGuard = (editor, { format, enabledButtons = [] }) => {\n  if (format !== 'html') {\n    return mergeUnregisters(\n      editor.registerNodeTransform(TextNode, (node) => {\n        HTML_ONLY_FORMAT_TYPES.forEach((type) => {\n          if (node.hasFormat(type)) {\n            node.toggleFormat(type);\n          }\n        });\n      }),\n      editor.registerCommand(FORMAT_TEXT_COMMAND, isHtmlOnlyButton, COMMAND_PRIORITY_CRITICAL),\n    );\n  }\n\n  return editor.registerCommand(\n    FORMAT_TEXT_COMMAND,\n    (type) => {\n      if (!isHtmlOnlyButton(type) || enabledButtons.includes(type)) {\n        return false;\n      }\n\n      $removeFormat(type);\n\n      return true;\n    },\n    COMMAND_PRIORITY_CRITICAL,\n  );\n};\n\n/**\n * Turn a task list into a bulleted list without the task list button, as its items couldn’t be\n * toggled. One can come in with pasted HTML, for example. `ListNode` is only registered with a list\n * button, so nothing is registered without any.\n * @param {LexicalEditor} editor Editor instance.\n * @param {TextEditorConfig['enabledButtons']} enabledButtons Enabled buttons.\n * @returns {(() => void) | undefined} Cleanup handler, if anything is registered.\n */\nconst registerTaskListGuard = (editor, enabledButtons = []) => {\n  if (\n    enabledButtons.includes('task-list') ||\n    !LIST_TYPES.some(({ type }) => enabledButtons.includes(type))\n  ) {\n    return undefined;\n  }\n\n  return editor.registerNodeTransform(ListNode, (list) => {\n    if (list.getListType() === 'check') {\n      list.setListType('bullet');\n    }\n  });\n};\n\n/**\n * Register all the guards.\n * @param {LexicalEditor} editor Editor instance.\n * @param {object} args Arguments.\n * @param {TextEditorValueFormat} args.format Value format.\n * @param {TextEditorConfig['enabledButtons']} args.enabledButtons Enabled buttons.\n * @returns {() => void} Cleanup handler.\n */\nexport const registerGuards = (editor, { format, enabledButtons = [] }) =>\n  mergeUnregisters(\n    registerFormatGuard(editor, { format, enabledButtons }),\n    registerTaskListGuard(editor, enabledButtons),\n  );\n","/**\n * Escape the given string so it can be used safely for `new RegExp()`.\n * @param {string} string Original string.\n * @returns {string} Escaped string.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping\n */\nconst escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/**\n * Truncate the given string.\n * @param {string} input Original string.\n * @param {number} max Maximum number of characters.\n * @param {object} [options] Options.\n * @param {string} [options.ellipsis] Character(s) to be appended if the the truncated string is\n * longer than `max`.\n * @returns {string} Truncated string.\n */\nconst truncate = (input, max, { ellipsis = '…' } = {}) => {\n  // Trim up front so that surrounding whitespace neither counts toward `max` nor triggers the\n  // ellipsis when nothing but whitespace would be cut off.\n  const string = input.trim();\n\n  // A string’s UTF-16 `length` is always >= its code point count, so this is a safe fast path that\n  // avoids walking the string at all when it cannot possibly need truncating.\n  if (string.length <= max) {\n    return string;\n  }\n\n  // Don’t use `split()` because it breaks Unicode characters like emoji. Every code point occupies\n  // at most two UTF-16 units, so the first `max * 2` units are guaranteed to contain at least `max`\n  // code points — spreading that bounded prefix costs O(max) instead of walking the whole string.\n  // A surrogate pair split by the slice can only land at index >= max, so it is always discarded.\n  const chars = [...string.slice(0, max * 2)];\n  const truncated = chars.slice(0, max).join('').trim();\n  // More code points remain either within the prefix, or beyond the point where it was cut.\n  const overflow = chars.length > max || string.length > max * 2;\n\n  return `${truncated}${overflow ? ellipsis : ''}`;\n};\n\n/**\n * Strip the leading and trailing slashes from the given string.\n * @param {string} string Original string, e.g. `/foo/bar/`.\n * @returns {string} Trimmed string, e.g. `foo/bar`.\n */\nconst stripSlashes = (string) => string.replace(/^\\/+|\\/+$/g, '');\n/**\n * Lazily-created shared parser. `DOMParser` is stateless across `parseFromString()` calls, so one\n * instance can be reused instead of constructing a new one on every call.\n * @type {DOMParser | undefined}\n */\nlet sharedDOMParser;\n\n/**\n * Remove all HTML tags from the given string, returning only the text content.\n * Security note: the returned value is plain text, not HTML. It is safe to insert via\n * `textContent`, but if you re-inject it via `innerHTML` you must re-escape it first to avoid XSS.\n * @param {string} string Original string that may include tags, e.g. `<div>Hello</div>`.\n * @returns {string} Text content, e.g. `Hello`.\n */\nconst stripTags = (string) => {\n  sharedDOMParser ??= new DOMParser();\n\n  return /** @type {string} */ (\n    sharedDOMParser.parseFromString(string, 'text/html').body.textContent\n  );\n};\n\n/**\n * Check if the given string is a URL.\n * @param {string} string String that might be a URL.\n * @returns {boolean} Result.\n */\nconst isURL = (string) => {\n  // Check for newlines and spaces, which are not allowed in URLs\n  if (/\\s/.test(string)) {\n    return false;\n  }\n\n  return URL.canParse(string);\n};\n\n/**\n * Compare strings for natural sorting.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare\n */\n// eslint-disable-next-line prefer-destructuring\nconst compare = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare;\n\nexport { compare, escapeRegExp, isURL, stripSlashes, stripTags, truncate };\n","/**\n * Links: the URL check, the link commands, and the helpers of the floating link editor.\n */\n\nimport {\n  $isLinkNode as isLinkNode,\n  LinkNode,\n  TOGGLE_LINK_COMMAND,\n  $toggleLink as toggleLink,\n} from '@lexical/link';\nimport { createDOMRange } from '@lexical/selection';\nimport {\n  $findMatchingParent as findMatchingParent,\n  objectKlassEquals,\n  $unwrapNode as unwrapNode,\n} from '@lexical/utils';\nimport { isURL } from '@sveltia/utils/string';\nimport {\n  COMMAND_PRIORITY_LOW,\n  COMMAND_PRIORITY_NORMAL,\n  $createTextNode as createTextNode,\n  $getSelection as getSelection,\n  $insertNodes as insertNodes,\n  $isElementNode as isElementNode,\n  $isRangeSelection as isRangeSelection,\n  $isTextNode as isTextNode,\n  PASTE_COMMAND,\n} from 'lexical';\nimport { mergeUnregisters } from '../utils.js';\n\n/**\n * @import { LexicalEditor, RangeSelection } from 'lexical';\n * @import { LinkAttributes } from '@lexical/link';\n * @import { EmojiAnchorRect } from '../../../typedefs.js';\n */\n\n/**\n * Payload of `TOGGLE_LINK_COMMAND` with the URL and the link attributes, like `target`.\n * @typedef {LinkAttributes & { url: string }} LinkAttributesWithURL\n */\n\n/**\n * URL schemes allowed in a link, the same as the ones Lexical renders as is.\n */\nconst SAFE_LINK_URL_SCHEMES = ['http', 'https', 'mailto', 'sms', 'tel'];\n\n/**\n * Whether the given URL is safe to be used as a link, meaning it’s either relative or uses one of\n * the {@link SAFE_LINK_URL_SCHEMES}. This keeps a URL like `javascript:alert(1)` out of the\n * Markdown, where the site that renders it may not sanitize it.\n * @param {string} url URL.\n * @returns {boolean} Result.\n */\nexport const isSafeLinkURL = (url) => {\n  // Browsers ignore control characters and spaces around a URL as well as tabs and newlines within\n  // it, e.g. `java\\tscript:`, so strip them all before looking for the scheme\n  // eslint-disable-next-line no-control-regex\n  const normalizedURL = url.replace(/[\\u0000-\\u0020]/g, '');\n\n  // Markdown decodes character references and backslash escapes in a link destination, so a scheme\n  // can be hidden with them, e.g. `&#106;avascript:`, `javascript&colon;` or `javascript\\:`. Reject\n  // any of them before the path, query or fragment.\n  if (/^[^/?#]*[&\\\\]/.test(normalizedURL)) {\n    return false;\n  }\n\n  const scheme = /^([a-z][a-z\\d+.-]*):/i.exec(normalizedURL)?.[1];\n\n  return !scheme || SAFE_LINK_URL_SCHEMES.includes(scheme.toLowerCase());\n};\n\n/**\n * Register the link command, the paste handler that turns a pasted URL into a link, and the\n * transform that removes a link with an unsafe URL.\n * @param {LexicalEditor} editor Editor instance.\n * @returns {() => void} Cleanup handler.\n * @see https://github.com/facebook/lexical/blob/main/packages/lexical-link/src/LexicalLinkExtension.ts\n */\nexport const registerLinkCommands = (editor) =>\n  mergeUnregisters(\n    // A link can also be created by importing the value or pasting rich text, which bypass the\n    // command below. Unwrap a link with an unsafe URL, keeping its text, so the URL never reaches\n    // the Markdown or HTML value\n    editor.registerNodeTransform(LinkNode, (node) => {\n      if (!isSafeLinkURL(node.getURL())) {\n        unwrapNode(node);\n      }\n    }),\n    editor.registerCommand(\n      TOGGLE_LINK_COMMAND,\n      (payload) => {\n        // The payload is the URL, or an object with the URL and attributes like `target`\n        const url = typeof payload === 'string' ? payload : (payload?.url ?? null);\n\n        // Ignore an unsafe URL rather than linking to it\n        if (url !== null && !isSafeLinkURL(url)) {\n          return true;\n        }\n\n        toggleLink(url === null ? null : /** @type {string | LinkAttributesWithURL} */ (payload));\n\n        return true;\n      },\n      COMMAND_PRIORITY_NORMAL,\n    ),\n    editor.registerCommand(\n      PASTE_COMMAND,\n      (event) => {\n        const selection = getSelection();\n\n        if (\n          !isRangeSelection(selection) ||\n          !objectKlassEquals(event, ClipboardEvent) ||\n          !event.clipboardData ||\n          /** @type {HTMLElement} */ (event.target).matches('input, textarea')\n        ) {\n          return false;\n        }\n\n        const clipboardText = event.clipboardData.getData('text').trim();\n\n        // Paste an unsafe URL as plain text rather than as a link\n        if (!isURL(clipboardText) || !isSafeLinkURL(clipboardText)) {\n          return false;\n        }\n\n        if (selection.isCollapsed()) {\n          insertNodes([createTextNode(clipboardText)]);\n        }\n\n        if (\n          !selection\n            .getNodes()\n            .some((node) => isElementNode(node) || (isTextNode(node) && !node.isSimpleText()))\n        ) {\n          editor.dispatchCommand(TOGGLE_LINK_COMMAND, clipboardText);\n          event.preventDefault();\n          return true;\n        }\n\n        return false;\n      },\n      COMMAND_PRIORITY_LOW,\n    ),\n  );\n\n/**\n * Find the link that contains the whole selection. This must be called within an editor state\n * read.\n * @returns {LinkNode | null} Link, if any.\n */\nexport const $findSelectedLink = () => {\n  const selection = getSelection();\n\n  if (!isRangeSelection(selection)) {\n    return null;\n  }\n\n  const link = findMatchingParent(selection.anchor.getNode(), isLinkNode);\n\n  return link && findMatchingParent(selection.focus.getNode(), isLinkNode) === link\n    ? /** @type {LinkNode} */ (link)\n    : null;\n};\n\n/**\n * Get the viewport-relative bounds of the given selection.\n * @param {LexicalEditor} editor Editor instance.\n * @param {RangeSelection} selection Selection, which may come from an earlier editor state.\n * @returns {DOMRect | undefined} Bounds, or `undefined` if the selected nodes are gone.\n */\nconst getSelectionRect = (editor, selection) => {\n  /** @type {DOMRect | undefined} */\n  let rect;\n\n  editor.getEditorState().read(() => {\n    const [start, end] = selection.isBackward()\n      ? [selection.focus, selection.anchor]\n      : [selection.anchor, selection.focus];\n\n    // The selected nodes may be gone, e.g. after an undo\n    /* v8 ignore else */\n    if (start.getNode().isAttached() && end.getNode().isAttached()) {\n      rect = createDOMRange(\n        editor,\n        start.getNode(),\n        start.offset,\n        end.getNode(),\n        end.offset,\n      )?.getBoundingClientRect();\n    }\n  });\n\n  return rect;\n};\n\n/**\n * Get the viewport-relative bounds of what the link editor is anchored to: the selected text to be\n * linked, or a link.\n * @param {LexicalEditor} editor Editor instance.\n * @param {{ selection: RangeSelection } | { linkKey: string | undefined }} target Selected text,\n * or the key of the link.\n * @returns {EmojiAnchorRect | undefined} Bounds, or `undefined` if they can’t be determined.\n */\nexport const getLinkAnchorRect = (editor, target) => {\n  const rect =\n    'selection' in target\n      ? getSelectionRect(editor, target.selection)\n      : target.linkKey\n        ? editor.getElementByKey(target.linkKey)?.getBoundingClientRect()\n        : undefined;\n\n  // The link or text may not be laid out, e.g. while the editor is hidden\n  /* v8 ignore next */\n  if (!rect || !(rect.top || rect.bottom || rect.left || rect.width || rect.height)) {\n    return undefined;\n  }\n\n  const { top, bottom, left, right } = rect;\n\n  return { top, bottom, left, right };\n};\n","/**\n * Preloading the syntax highlighter.\n */\n\nimport {\n  isPlainLanguage,\n  loadCodeLanguage,\n  loadCodeTheme,\n  loadEngine,\n  normalizeCodeLanguage,\n} from './engine.js';\nimport { getCodeTheme } from './theme.js';\n\n/**\n * Preload the syntax highlighter for the given programming language.\n *\n * Highlighting also works without this — the transform loads whatever it needs and re-highlights\n * once it arrives — but preloading avoids a visible flash of unhighlighted code.\n * @param {string} lang Language name, like scss.\n */\nexport const loadCodeHighlighter = async (lang) => {\n  if (isPlainLanguage(lang)) {\n    return;\n  }\n\n  // The grammar and theme loaders are no-ops until the engine is in place\n  await loadEngine();\n\n  await Promise.all([loadCodeLanguage(normalizeCodeLanguage(lang)), loadCodeTheme(getCodeTheme())]);\n};\n","import { findCodeSpans } from '../markdown/code-spans.js';\nimport { countBackslashesBefore } from '../markdown/syntax.js';\n\n/**\n * @import { TextFormatTransformer, TextMatchTransformer, Transformer } from '@lexical/markdown';\n * @import { TextNode } from 'lexical';\n */\n\n/**\n * @typedef {object} Range\n * @property {number} start Start index.\n * @property {number} end End index, exclusive.\n */\n\n/**\n * @typedef {object} Delimiter\n * @property {string} char Delimiter character.\n * @property {number} index Index of the remaining delimiter characters.\n * @property {number} length Number of the remaining delimiter characters.\n * @property {boolean} canOpen Whether the run can open emphasis.\n * @property {boolean} canClose Whether the run can close emphasis.\n * @property {boolean} active Whether the run can still be paired.\n */\n\n/**\n * Whitespace, as Lexical reads it.\n */\nconst WHITESPACE = /\\s/;\n/**\n * ASCII punctuation, as Lexical reads it. Unlike CommonMark, Lexical leaves out the backslash.\n */\nconst PUNCTUATION = /[!\"#$%&'()*+,\\-./:;<=>?@[\\]^_`{|}~]/;\n\n/**\n * Check if a delimiter run is left-flanking or right-flanking, like Lexical does.\n * @param {string} text Text.\n * @param {number} index Index of the run.\n * @param {number} length Length of the run.\n * @param {boolean} isLeft Whether to check if it’s left-flanking.\n * @returns {boolean} Result.\n * @see https://spec.commonmark.org/0.31.2/#left-flanking-delimiter-run\n */\nconst isFlanking = (text, index, length, isLeft) => {\n  const before = text[index - 1];\n  const after = text[index + length];\n  const [primary, secondary] = isLeft ? [after, before] : [before, after];\n\n  if (primary === undefined || WHITESPACE.test(primary)) {\n    return false;\n  }\n\n  return (\n    !PUNCTUATION.test(primary) ||\n    secondary === undefined ||\n    WHITESPACE.test(secondary) ||\n    PUNCTUATION.test(secondary)\n  );\n};\n\n/**\n * Check if a delimiter run can open or close emphasis, like Lexical does.\n * @param {string} text Text.\n * @param {number} index Index of the run.\n * @param {number} length Length of the run.\n * @param {boolean} isOpen Whether to check if it can open emphasis.\n * @returns {boolean} Result.\n */\nconst canEmphasis = (text, index, length, isOpen) => {\n  if (!isFlanking(text, index, length, isOpen)) {\n    return false;\n  }\n\n  if (text[index] !== '_' || !isFlanking(text, index, length, !isOpen)) {\n    return true;\n  }\n\n  const adjacent = isOpen ? text[index - 1] : text[index + length];\n\n  return adjacent !== undefined && PUNCTUATION.test(adjacent);\n};\n\n/**\n * Find the delimiter runs outside code spans that can open or close emphasis, like Lexical does.\n * @param {string} text Text.\n * @param {Set<string>} chars Delimiter characters.\n * @param {Range[]} codeSpans Code spans.\n * @returns {Delimiter[]} Delimiter runs.\n */\nconst findDelimiters = (text, chars, codeSpans) => {\n  /** @type {Delimiter[]} */\n  const delimiters = [];\n  let spanIndex = 0;\n  let index = 0;\n\n  while (index < text.length) {\n    while (spanIndex < codeSpans.length && codeSpans[spanIndex].end <= index) {\n      spanIndex += 1;\n    }\n\n    const char = text[index];\n    const span = codeSpans[spanIndex];\n\n    if (span && span.start <= index) {\n      index = span.end;\n    } else if (!chars.has(char) || countBackslashesBefore(text, index) % 2 === 1) {\n      index += 1;\n    } else {\n      let length = 1;\n\n      while (text[index + length] === char) {\n        length += 1;\n      }\n\n      const canOpen = canEmphasis(text, index, length, true);\n      const canClose = canEmphasis(text, index, length, false);\n\n      if (canOpen || canClose) {\n        delimiters.push({ char, index, length, canOpen, canClose, active: true });\n      }\n\n      index += length;\n    }\n  }\n\n  return delimiters;\n};\n\n/**\n * Pair the delimiter runs like Lexical does, following the CommonMark algorithm.\n * @param {Delimiter[]} delimiters Delimiter runs, which are updated as they’re paired.\n * @param {string[]} tags Delimiters of the text formats, like `**`.\n * @returns {Range[]} Emphasis, from the opening delimiters to the closing ones.\n * @see https://spec.commonmark.org/0.31.2/#process-emphasis\n */\nconst pairDelimiters = (delimiters, tags) => {\n  /** @type {Record<string, number>} */\n  const openersBottom = {};\n  /** @type {Range[]} */\n  const pairs = [];\n  let position = 0;\n\n  while (position < delimiters.length) {\n    const closer = delimiters[position];\n\n    if (!closer.active || !closer.canClose || !closer.length) {\n      position += 1;\n    } else {\n      const bottomKey = `${closer.char}${closer.canOpen}${closer.length % 3}`;\n      const bottom = openersBottom[bottomKey] ?? -1;\n      let found = false;\n\n      for (let openIndex = position - 1; openIndex > bottom && !found; openIndex -= 1) {\n        const opener = delimiters[openIndex];\n\n        const canPair =\n          opener.active &&\n          opener.canOpen &&\n          opener.length > 0 &&\n          opener.char === closer.char &&\n          // The rule of 3\n          !(\n            (opener.canClose || closer.canOpen) &&\n            (opener.length + closer.length) % 3 === 0 &&\n            opener.length % 3 !== 0 &&\n            closer.length % 3 !== 0\n          );\n\n        const maxLength = Math.min(opener.length, closer.length);\n\n        const tag = canPair\n          ? tags\n              .filter((t) => t[0] === opener.char && t.length <= maxLength)\n              .sort((a, b) => b.length - a.length)[0]\n          : undefined;\n\n        if (tag) {\n          found = true;\n          pairs.push({\n            start: opener.index + opener.length - tag.length,\n            end: closer.index + tag.length,\n          });\n\n          for (let index = openIndex + 1; index < position; index += 1) {\n            delimiters[index].active = false;\n          }\n\n          opener.length -= tag.length;\n          closer.length -= tag.length;\n          opener.active = opener.length > 0;\n\n          if (closer.length > 0) {\n            closer.index += tag.length;\n          } else {\n            closer.active = false;\n            position += 1;\n          }\n        }\n      }\n\n      if (!found) {\n        openersBottom[bottomKey] = position - 1;\n        closer.active = closer.canOpen;\n        position += 1;\n      }\n    }\n  }\n\n  return pairs;\n};\n\n/**\n * Create a function that finds where a text node has to be split before Lexical imports it, so the\n * formatting around a code span isn’t lost; see `addCodeSpanSplit()`.\n * @param {string[]} tags Delimiters of the text formats other than code, like `**`.\n * @param {TextMatchTransformer[]} textMatchTransformers Text match transformers.\n * @returns {(text: string) => number | undefined} Function that returns the index to split the\n * text at, or `undefined` if it doesn’t have to be split.\n */\nconst createSplitIndexFinder = (tags, textMatchTransformers) => {\n  const chars = new Set(tags.map((tag) => tag[0]));\n\n  const regexes = textMatchTransformers.flatMap(({ importRegExp }) =>\n    importRegExp\n      ? [new RegExp(importRegExp.source, `${importRegExp.flags.replace('g', '')}g`)]\n      : [],\n  );\n\n  /** @type {{ text: string, index: number | undefined } | undefined} */\n  let cache;\n\n  /**\n   * Find the index to split the text at.\n   * @param {string} text Text.\n   * @returns {number | undefined} Index.\n   */\n  const findSplitIndex = (text) => {\n    const codeSpans = findCodeSpans(text);\n    const [code] = codeSpans;\n\n    if (!code) {\n      return undefined;\n    }\n\n    const pairs = pairDelimiters(findDelimiters(text, chars, codeSpans), tags);\n    /**\n     * Check if the given emphasis wraps the first code span.\n     * @param {Range} pair Emphasis.\n     * @returns {boolean} Result.\n     */\n    const wrapsCode = ({ start, end }) => start <= code.start && end >= code.end;\n    // The emphasis Lexical imports first: the one that starts first, or the longest of those\n    const [first] = [...pairs].sort((a, b) => a.start - b.start || b.end - a.end);\n\n    if (!first || wrapsCode(first)) {\n      return undefined;\n    }\n\n    // The outermost emphasis around the code span\n    const [outer] = pairs.filter(wrapsCode).sort((a, b) => a.start - b.start);\n\n    if (\n      !outer ||\n      // A text match, like a link, that the split would cut in two\n      regexes.some((regex) =>\n        [...text.matchAll(regex)].some(\n          ({ 0: { length }, index }) => index < outer.start && index + length > outer.start,\n        ),\n      )\n    ) {\n      return undefined;\n    }\n\n    return outer.start;\n  };\n\n  return (text) => {\n    if (cache?.text !== text) {\n      cache = { text, index: findSplitIndex(text) };\n    }\n\n    return cache.index;\n  };\n};\n\n/**\n * Add a transformer to the given ones that keeps the formatting around a code span when Lexical\n * imports it after other formatting or a link, like `` **`a`** `` in `` **b** **`a`** `` or\n * `` [**b**](u)**`a`** ``. Lexical takes a code span before the formatting, unless the formatting\n * it would take first wraps the code span, and that formatting is the one that starts first, like\n * `**b**`. So Lexical takes the code span, splitting the text around it, and the formatting around\n * the code span is lost, along with its delimiters, which are then escaped on export. The added\n * transformer splits the text where the formatting around the code span starts, so each part is\n * imported on its own. To find it, the delimiters are paired like Lexical does. Lexical only lets a\n * text match take precedence over the code span if it wraps the code span, so the text is matched\n * from there to its end. The other text match transformers are wrapped so they don’t match before\n * that point, as Lexical takes the text match that starts first; they match in the part before it\n * instead. The text isn’t split if it would cut a text match in two. It’s only for the import.\n * @param {Transformer[]} transformers Transformers.\n * @returns {Transformer[]} Transformers for the import.\n * @see https://spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis\n */\nexport const addCodeSpanSplit = (transformers) => {\n  const tags = transformers\n    .filter((transformer) => transformer.type === 'text-format')\n    .map((transformer) => /** @type {TextFormatTransformer} */ (transformer).tag);\n\n  if (!tags.includes('`')) {\n    return transformers;\n  }\n\n  const findSplitIndex = createSplitIndexFinder(\n    tags.filter((tag) => tag !== '`'),\n    /** @type {TextMatchTransformer[]} */ (\n      transformers.filter((transformer) => transformer.type === 'text-match')\n    ),\n  );\n\n  /** @type {TextMatchTransformer} */\n  const splitter = {\n    dependencies: [],\n    /**\n     * Leave the export to the other transformers.\n     * @returns {null} Nothing.\n     */\n    export: () => null,\n    // Lexical matches the text with `String.prototype.match()`, which calls this method\n    importRegExp: Object.assign(/(?!)/, {\n      /**\n       * Match the text from the index to split it at to its end.\n       * @param {string} text Text.\n       * @returns {RegExpMatchArray | null} Match.\n       */\n      [Symbol.match]: (text) => {\n        const index = findSplitIndex(text);\n\n        return index === undefined\n          ? null\n          : /** @type {RegExpMatchArray} */ (\n              Object.assign([text.slice(index)], { index, input: text })\n            );\n      },\n    }),\n    regExp: /(?!)/,\n    /**\n     * Leave the part of the text from the split to Lexical, which imports it on its own.\n     * @param {TextNode} node Text node with the matched text.\n     * @returns {TextNode} Same node.\n     */\n    replace: (node) => node,\n    type: 'text-match',\n  };\n\n  return [\n    splitter,\n    ...transformers.map((transformer) => {\n      if (transformer.type !== 'text-match') {\n        return transformer;\n      }\n\n      const { getEndIndex } = /** @type {TextMatchTransformer} */ (transformer);\n\n      return {\n        ...transformer,\n        /**\n         * Get the end index of a match, or `false` to skip it if it ends before the split.\n         * @param {TextNode} node Text node.\n         * @param {RegExpMatchArray} match Match.\n         * @returns {number | false} End index or `false`.\n         */\n        getEndIndex: (node, match) => {\n          const end = getEndIndex ? getEndIndex(node, match) : (match.index ?? 0) + match[0].length;\n          const splitIndex = findSplitIndex(node.getTextContent());\n\n          return end !== false && splitIndex !== undefined && end <= splitIndex ? false : end;\n        },\n      };\n    }),\n  ];\n};\n","/**\n * Importing a Markdown or HTML value to the editor.\n */\n\nimport { $generateNodesFromDOM as generateNodesFromDOM } from '@lexical/html';\nimport { $isLinkNode as isLinkNode } from '@lexical/link';\nimport {\n  HEADING,\n  $convertFromMarkdownString as convertFromMarkdownString,\n  $generateNodesFromMarkdownString as generateNodesFromMarkdownString,\n} from '@lexical/markdown';\nimport {\n  $createParagraphNode as createParagraphNode,\n  $getRoot as getRoot,\n  $getSelection as getSelection,\n  HISTORY_MERGE_TAG,\n  $isDecoratorNode as isDecoratorNode,\n  $isElementNode as isElementNode,\n  $isTextNode as isTextNode,\n} from 'lexical';\nimport { IMPORT_UPDATE_TAG } from '../constants.js';\nimport { exportHtml, findUnsupportedNode, getCodeLanguage } from './html/index.js';\nimport {\n  convertBlockSyntax,\n  toLexicalMarkdown,\n  removeImportPlaceholders,\n} from './markdown/index.js';\nimport { findCodeBlocks, parseOpeningFence } from './markdown/code-blocks.js';\nimport { loadCodeHighlighter } from '../shiki/preload.js';\nimport { CODE } from './transformers/code.js';\nimport { addCodeSpanSplit } from './transformers/formatted-code.js';\nimport { getImportedRawSyntax } from './transformers/raw-syntax.js';\nimport { exportMarkdown } from './update.js';\n\n/**\n * @import { ElementNode, LexicalEditor, LexicalNode } from 'lexical';\n * @import { Transformer } from '@lexical/markdown';\n */\n\n/**\n * Remove the placeholders added by `addImportPlaceholders()` from the imported nodes: the text, the\n * Markdown of raw syntax, and the URL and title of a link. The text of raw syntax is restored from\n * the Markdown it was imported from, as Lexical has removed its escapes, which are not escapes in\n * raw HTML; see `RAW_HTML`.\n * @param {LexicalNode[]} nodes Imported nodes.\n */\nconst removePlaceholders = (nodes) => {\n  nodes\n    .flatMap((node) => (isElementNode(node) ? node.getAllTextNodes() : node))\n    .filter((node) => isTextNode(node))\n    .forEach((node) => {\n      const text = node.getTextContent();\n      const newText = removeImportPlaceholders(getImportedRawSyntax(node) ?? text);\n      const link = node.getParent();\n\n      if (newText !== text) {\n        node.setTextContent(newText);\n      }\n\n      if (isLinkNode(link)) {\n        const url = link.getURL();\n        const title = link.getTitle();\n\n        if (removeImportPlaceholders(url) !== url) {\n          link.setURL(removeImportPlaceholders(url));\n        }\n\n        if (title && removeImportPlaceholders(title) !== title) {\n          link.setTitle(removeImportPlaceholders(title));\n        }\n      }\n    });\n};\n\n/**\n * Get the programming languages used in the code blocks of Markdown: the leading word of the info\n * string of each opening backtick fence, like `js` in the info string ` js title=x`, as `CODE`\n * reads it. A code block in a list item, like `- ~~~`, is left out, as it’s imported as the text\n * of the item, and so is one with a tilde fence, which is only imported as a code block once\n * converted.\n * @param {string} markdown Markdown.\n * @returns {string[]} Languages.\n */\nconst getCodeBlockLanguages = (markdown) => {\n  const lines = markdown.split('\\n');\n\n  return findCodeBlocks(lines).flatMap(({ start }) => {\n    const { fence = '', language } = parseOpeningFence(lines[start]) ?? {};\n\n    return fence.startsWith('`') && language ? [language] : [];\n  });\n};\n\n/**\n * Prepare Markdown for the import: convert the syntax Lexical doesn’t support to the one it does,\n * if the element is enabled, and list the programming languages used in the code blocks.\n * @param {string} value Markdown.\n * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.\n * @returns {{ markdown: string, languages: string[] }} Normalized Markdown and the languages.\n */\nexport const prepareMarkdown = (value, enabledTransformers) => {\n  // A transformer is found by its regular expression, because the transformers can come wrapped\n  // in a `$state` proxy, which leaves a regular expression as is but not the transformer object\n  // itself\n  const hasCodeBlocks = enabledTransformers.some(\n    (transformer) => 'regExpStart' in transformer && transformer.regExpStart === CODE.regExpStart,\n  );\n\n  const hasHeadings = enabledTransformers.some(\n    (transformer) => 'regExp' in transformer && transformer.regExp === HEADING.regExp,\n  );\n\n  const markdown = convertBlockSyntax(value, { hasCodeBlocks, hasHeadings });\n\n  return {\n    markdown,\n    languages: getCodeBlockLanguages(markdown),\n  };\n};\n\n/**\n * Convert Markdown prepared with {@link prepareMarkdown} to Lexical nodes, either replacing the\n * content of the root or returning the nodes to be inserted somewhere. Called within an editor\n * update.\n * @param {string} markdown Markdown.\n * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.\n * @param {object} [options] Options.\n * @param {boolean} [options.toRoot] Whether to replace the content of the root.\n * @returns {LexicalNode[]} Imported nodes.\n */\nexport const $importMarkdown = (markdown, enabledTransformers, { toRoot = false } = {}) => {\n  const { markdown: preparedValue, hasPlaceholders } = toLexicalMarkdown(markdown);\n  // Keep the formatting around a code span after other formatting\n  const transformers = addCodeSpanSplit(enabledTransformers);\n  /** @type {LexicalNode[]} */\n  let nodes;\n\n  if (toRoot) {\n    convertFromMarkdownString(preparedValue, transformers);\n    nodes = getRoot().getChildren();\n  } else {\n    nodes = generateNodesFromMarkdownString(preparedValue, transformers);\n  }\n\n  // The text of raw HTML and raw syntax is restored as well. The lines of an HTML block have a\n  // placeholder. Other raw syntax, like an autolink or a definition label, only differs from its\n  // text if Lexical has decoded an escape or a character reference in it\n  if (hasPlaceholders || /[\\\\&]/.test(preparedValue)) {\n    removePlaceholders(nodes);\n  }\n\n  return nodes;\n};\n\n/**\n * Number of the latest import started for each editor.\n * @type {WeakMap<LexicalEditor, number>}\n */\nconst latestImports = new WeakMap();\n\n/**\n * Import a value to the editor, replacing the current content.\n * @param {LexicalEditor} editor Editor instance.\n * @param {object} args Arguments.\n * @param {string[]} args.languages Programming languages used in the code blocks.\n * @param {() => void} args.$import Function to convert the value to Lexical nodes, called within an\n * editor update.\n * @param {() => string} args.$export Function to convert the editor content back to the value.\n * @param {string} args.formatName Name of the value format, used in the error message.\n * @returns {Promise<string | undefined>} The value as the editor exports it once imported, which\n * can differ in style from the given value. `undefined` if another import has been started for the\n * same editor in the meantime, in which case this value is skipped.\n * @throws {Error} Failed to convert the value to Lexical nodes.\n */\nconst importValue = async (editor, { languages, $import, $export, formatName }) => {\n  const importId = (latestImports.get(editor) ?? 0) + 1;\n\n  latestImports.set(editor, importId);\n\n  /**\n   * Check if a newer import has been started while waiting for the highlighter. Imports can finish\n   * out of order, as only those with code blocks have to wait, and an older value must not\n   * overwrite a newer one.\n   * @returns {boolean} Result.\n   */\n  const isSuperseded = () => latestImports.get(editor) !== importId;\n\n  try {\n    // Preload the highlighter for every language used in the document, so code blocks are\n    // highlighted as soon as they appear rather than a moment later\n    await Promise.all(languages.map(async (lang) => loadCodeHighlighter(lang)));\n  } catch (ex) {\n    if (isSuperseded()) {\n      return undefined;\n    }\n\n    throw ex;\n  }\n\n  if (isSuperseded()) {\n    return undefined;\n  }\n\n  // Lexical commits an empty state when the root element is attached, and the history keeps it as\n  // the current entry. An empty state can’t be restored, so undoing to it throws an error. Merge\n  // the first import into that entry instead of pushing it onto the undo stack\n  const isEmpty = editor.getEditorState().isEmpty();\n  /** @type {unknown} */\n  let error;\n\n  editor.update(\n    () => {\n      try {\n        $import();\n      } catch (ex) {\n        error = ex;\n      }\n    },\n    // Tell the import from a change made by the user, and commit it right away, so the node\n    // transforms, e.g. the one giving a code block its default language, have run by the time the\n    // content is exported below\n    { tag: isEmpty ? [IMPORT_UPDATE_TAG, HISTORY_MERGE_TAG] : IMPORT_UPDATE_TAG, discrete: true },\n  );\n\n  if (error) {\n    throw new Error(`Failed to convert ${formatName}`, { cause: error });\n  }\n\n  return editor.read($export);\n};\n\n/**\n * Convert Markdown to Lexical nodes.\n * @param {LexicalEditor} editor Editor instance.\n * @param {string} value Current Markdown value.\n * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.\n * @returns {Promise<string | undefined>} The value as the editor exports it once imported, which\n * can differ in style from the given value, e.g. `_text_` for `*text*`. `undefined` if another\n * import has been started for the same editor in the meantime, in which case this value is skipped.\n * @throws {Error} Failed to convert the value to Lexical nodes.\n */\nexport const convertMarkdownToLexical = async (editor, value, enabledTransformers) => {\n  const { markdown, languages } = prepareMarkdown(value, enabledTransformers);\n\n  return importValue(editor, {\n    languages,\n    /**\n     * Import the Markdown.\n     */\n    $import: () => {\n      $importMarkdown(markdown, enabledTransformers, { toRoot: true });\n    },\n    /**\n     * Export the content as Markdown.\n     * @returns {string} Markdown.\n     */\n    $export: () => exportMarkdown(enabledTransformers),\n    formatName: 'Markdown',\n  });\n};\n\n/**\n * Convert HTML to Lexical nodes. Inline content outside any block, like bare text, is wrapped with\n * a paragraph. An element that none of the registered nodes can import, like `<img>` or a heading\n * with the heading buttons disabled, as well as a comment, causes an error instead of being\n * silently dropped.\n * @param {LexicalEditor} editor Editor instance.\n * @param {string} value Current HTML value.\n * @returns {Promise<string | undefined>} The value as the editor exports it once imported, which\n * can differ in style from the given value, e.g. `<strong>` for `<b>`. `undefined` if another\n * import has been started for the same editor in the meantime, in which case this value is skipped.\n * @throws {Error} Failed to convert the value to Lexical nodes.\n */\nexport const convertHtmlToLexical = async (editor, value) => {\n  const dom = new DOMParser().parseFromString(value, 'text/html');\n\n  return importValue(editor, {\n    languages: [...dom.querySelectorAll('pre > code')]\n      .map(getCodeLanguage)\n      .filter((lang) => lang !== undefined),\n    /**\n     * Import the HTML.\n     * @throws {Error} The HTML has an element the editor cannot handle.\n     */\n    $import: () => {\n      const unsupportedNode = findUnsupportedNode(editor, dom);\n\n      if (unsupportedNode) {\n        throw new Error(\n          unsupportedNode.nodeType === Node.COMMENT_NODE\n            ? 'Unsupported comment'\n            : `Unsupported element: <${/** @type {Element} */ (unsupportedNode).localName}>`,\n        );\n      }\n\n      const root = getRoot();\n      /** @type {ElementNode | null} */\n      let paragraph = null;\n\n      root.clear();\n\n      generateNodesFromDOM(editor, dom).forEach((node) => {\n        if (isElementNode(node) ? !node.isInline() : isDecoratorNode(node) && !node.isInline()) {\n          paragraph = null;\n          root.append(node);\n        } else {\n          if (!paragraph) {\n            paragraph = createParagraphNode();\n            root.append(paragraph);\n          }\n\n          paragraph.append(node);\n        }\n      });\n\n      // Like the Markdown import, there should be at least one paragraph\n      // @see https://github.com/facebook/lexical/issues/2308\n      if (root.isEmpty()) {\n        root.append(createParagraphNode());\n      }\n\n      if (getSelection() !== null) {\n        root.selectStart();\n      }\n    },\n    /**\n     * Export the content as HTML.\n     * @returns {string} HTML.\n     */\n    $export: () => exportHtml(editor),\n    formatName: 'HTML',\n  });\n};\n","/**\n * Pasting Markdown, either as is or with the Paste as Markdown shortcut.\n */\n\nimport { objectKlassEquals } from '@lexical/utils';\nimport { isURL } from '@sveltia/utils/string';\nimport { isMac, matchesShortcuts } from '@sveltia/utils/events';\nimport {\n  COMMAND_PRIORITY_NORMAL,\n  $getSelection as getSelection,\n  $setSelection as setSelection,\n  KEY_DOWN_COMMAND,\n  PASTE_COMMAND,\n  PASTE_TAG,\n} from 'lexical';\nimport { loadCodeHighlighter } from '../shiki/preload.js';\nimport { $importMarkdown, prepareMarkdown } from './import.js';\nimport { mergeUnregisters } from '../utils.js';\n\n/**\n * @import { LexicalEditor, LexicalNode } from 'lexical';\n * @import { Transformer } from '@lexical/markdown';\n */\n\n/**\n * Insert the given Markdown at the selection, converted to Lexical nodes, as if it were pasted. The\n * content stays as it is if the editor is read-only or has no selection.\n * @param {LexicalEditor} editor Editor instance.\n * @param {string} value Markdown.\n * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.\n * @returns {Promise<void>} Nothing.\n */\nexport const pasteMarkdown = async (editor, value, enabledTransformers) => {\n  const { markdown, languages } = prepareMarkdown(value, enabledTransformers);\n\n  // Preload the highlighter like the import does, but carry on without it if it fails to load: the\n  // code is highlighted once it’s available, if ever\n  await Promise.allSettled(languages.map((lang) => loadCodeHighlighter(lang)));\n\n  if (!editor.isEditable()) {\n    return;\n  }\n\n  editor.update(\n    () => {\n      // The Markdown import moves the selection to the nodes it creates, so keep a copy to insert\n      // the nodes where the caret was\n      const selection = getSelection()?.clone();\n\n      if (!selection) {\n        return;\n      }\n\n      /** @type {LexicalNode[] | undefined} */\n      let nodes;\n\n      try {\n        nodes = $importMarkdown(markdown, enabledTransformers);\n      } catch (ex) {\n        // The browser paste has been canceled, so paste the text as is rather than nothing\n        // eslint-disable-next-line no-console\n        console.error(ex);\n      }\n\n      setSelection(selection);\n\n      if (nodes) {\n        selection.insertNodes(nodes);\n      } else {\n        selection.insertRawText(value);\n      }\n    },\n    { tag: PASTE_TAG },\n  );\n};\n\n/**\n * How long to wait for the `paste` event after a Paste as Markdown shortcut, in milliseconds.\n */\nconst PASTE_AS_MARKDOWN_TIMEOUT = 1000;\n\n/**\n * Keyboard shortcuts to paste the text on the clipboard as Markdown: the browser’s own shortcuts to\n * paste plain text, Accel+Shift+V, plus Command+Option+Shift+V, the macOS Paste and Match Style.\n * @returns {string} Shortcuts.\n */\nconst getPasteAsMarkdownShortcuts = () =>\n  isMac() ? 'Meta+Shift+V Meta+Alt+Shift+V' : 'Ctrl+Shift+V';\n\n/**\n * Register the keyboard shortcuts to paste the text on the clipboard as Markdown. A regular paste\n * prefers the HTML on the clipboard, so text copied from a code editor or a terminal ends up in a\n * code block, while Markdown pasted as plain text is kept as literal text. The shortcuts make the\n * browser paste plain text, which is then converted from Markdown. The browser does the paste,\n * because a script can’t read the clipboard after a key combination in every browser: Firefox\n * doesn’t allow it after a key pressed with Ctrl, Alt or Command.\n * @param {LexicalEditor} editor Editor instance.\n * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.\n * @returns {() => void} Cleanup handler.\n */\nexport const registerPasteAsMarkdown = (editor, enabledTransformers) => {\n  const shortcuts = getPasteAsMarkdownShortcuts();\n  /** Whether the paste that follows was started with one of the shortcuts. */\n  let pasteAsMarkdown = false;\n  let timer = 0;\n\n  return mergeUnregisters(\n    () => {\n      clearTimeout(timer);\n    },\n    editor.registerCommand(\n      KEY_DOWN_COMMAND,\n      (event) => {\n        // Any other key cancels the shortcut. Chrome on macOS fires the `paste` event in a later\n        // task, so wait a moment for it, but not too long, in case the browser doesn’t paste with\n        // the shortcut, like Safari with Command+Shift+V\n        pasteAsMarkdown = matchesShortcuts(event, shortcuts);\n        clearTimeout(timer);\n\n        if (pasteAsMarkdown) {\n          timer = window.setTimeout(() => {\n            pasteAsMarkdown = false;\n          }, PASTE_AS_MARKDOWN_TIMEOUT);\n        }\n\n        // Let the browser paste\n        return false;\n      },\n      COMMAND_PRIORITY_NORMAL,\n    ),\n    editor.registerCommand(\n      PASTE_COMMAND,\n      (event) => {\n        if (!pasteAsMarkdown) {\n          return false;\n        }\n\n        pasteAsMarkdown = false;\n\n        const isClipboardEvent = objectKlassEquals(event, ClipboardEvent);\n\n        // Safari pastes with an `insertFromPaste` input event instead of a `paste` event\n        const dataTransfer = isClipboardEvent\n          ? /** @type {ClipboardEvent} */ (event).clipboardData\n          : objectKlassEquals(event, InputEvent)\n            ? /** @type {InputEvent} */ (event).dataTransfer\n            : null;\n\n        const text = dataTransfer?.getData('text/plain');\n\n        // Leave a URL to the link paste handler, which links the selected text. It only handles a\n        // `paste` event, so Safari still pastes a URL as Markdown\n        if (!text || (isClipboardEvent && isURL(text.trim()))) {\n          return false;\n        }\n\n        event.preventDefault();\n        pasteMarkdown(editor, text, enabledTransformers);\n\n        return true;\n      },\n      // Before the link paste handler and Lexical’s own one\n      COMMAND_PRIORITY_NORMAL,\n    ),\n  );\n};\n","import { CodeExtension, CodeHighlightNode, CodeNode } from '@lexical/code-core';\nimport { registerDragonSupport } from '@lexical/dragon';\nimport {\n  buildEditorFromExtensions,\n  HorizontalRuleExtension,\n  HorizontalRuleNode,\n} from '@lexical/extension';\nimport { createEmptyHistoryState, registerHistory } from '@lexical/history';\nimport { registerMarkdownShortcuts } from '@lexical/markdown';\nimport { registerRichText } from '@lexical/rich-text';\nimport { TableCellNode, TableExtension, TableNode, TableRowNode } from '@lexical/table';\nimport { configExtension, defineExtension } from 'lexical';\nimport { EDITOR_THEME, NODE_MAP, TRANSFORMER_MAP } from './constants.js';\nimport { editorComponents, getHtmlConfig } from './conversion/html/index.js';\nimport { registerCodeHighlighting, shikiTokenizer } from './shiki/highlighter.js';\nimport { getCodeTheme, observeCodeTheme } from './shiki/theme.js';\nimport { CODE } from './conversion/transformers/code.js';\nimport { HR } from './conversion/transformers/hr.js';\nimport { RAW_HTML, RAW_SYNTAX } from './conversion/transformers/raw-syntax.js';\nimport { $ensureParagraphAfterTable, $normalizeTableHeaders } from './editing/table.js';\nimport { createTableTransformer } from './conversion/transformers/table.js';\nimport { registerSingleLine } from './editing/single-line.js';\nimport { getEditorSetup, normalizeConfig } from './config.js';\nimport { removePlaceholdersFromMatch } from './conversion/editor-components.js';\nimport {\n  registerCodeEditorCommands,\n  registerListCommands,\n  registerTabIndentation,\n} from './editing/commands.js';\nimport { registerGuards } from './editing/guards.js';\nimport { mergeUnregisters } from './utils.js';\nimport { registerLinkCommands } from './editing/link.js';\nimport { registerValueExport } from './conversion/update.js';\nimport { registerPasteAsMarkdown } from './conversion/paste.js';\n\n/**\n * @import { LexicalEditor } from 'lexical';\n * @import { TextMatchTransformer, Transformer } from '@lexical/markdown';\n * @import { TextEditorConfig, TextEditorNodeType } from '../../typedefs.js';\n * @import { EditorSetup } from './config.js';\n * @import { ExportDetail } from './conversion/update.js';\n */\n\n/**\n * @typedef {object} InitEditorResult\n * @property {LexicalEditor} editor Editor instance.\n * @property {Transformer[]} enabledTransformers List of enabled Markdown transformers.\n * @property {() => void} flush Export the content scheduled to be exported right away, instead\n * of after the delay, so the value reflects what was just typed. Does nothing if nothing is\n * scheduled.\n * @property {() => void} dispose Remove all registered Lexical listeners.\n */\n\n/**\n * @typedef {object} InitEditorOptions\n * @property {(detail: ExportDetail) => void} [onExport] Function to call with the Markdown or HTML\n * value and the selection state, a moment after the editor content or selection has changed.\n */\n\n/**\n * Maximum number of entries in the undo stack.\n */\nconst HISTORY_MAX_DEPTH = 200;\n\n/**\n * Get the unique items of a map keyed by button type, for the enabled buttons.\n * @template T\n * @param {Partial<Record<TextEditorNodeType, T[]>>} map Items by button type.\n * @param {TextEditorNodeType[]} enabledButtons Enabled buttons.\n * @returns {T[]} Items.\n */\nconst pickForButtons = (map, enabledButtons) => [\n  ...new Set(\n    Object.entries(map)\n      .filter(([button]) => enabledButtons.includes(/** @type {TextEditorNodeType} */ (button)))\n      .flatMap(([, items]) => /** @type {T[]} */ (items)),\n  ),\n];\n\n/**\n * Define the Lexical extension the editor is built from, with the nodes and the dependencies the\n * enabled features need.\n * @param {EditorSetup} setup Editor setup.\n * @returns {ReturnType<typeof defineExtension>} Extension.\n */\nconst createEditorExtension = ({\n  enabledButtons,\n  components,\n  isCodeEditor,\n  format,\n  hasCodeBlock,\n  hasTable,\n  hasHorizontalRule,\n  hasTaskList,\n  hasBlockSyntax,\n}) =>\n  defineExtension({\n    name: '@sveltia/ui/editor',\n    namespace: 'editor',\n    dependencies: [\n      // `CodeNode` expects the editor to be built with `CodeExtension`, which also registers the\n      // `CodeNode` and `CodeHighlightNode` nodes\n      ...(hasCodeBlock ? [CodeExtension] : []),\n      // Table editing: selecting cells, moving between them with the Tab key, and scrolling a wide\n      // table. Markdown and the HTML export support neither merged cells nor cell colors\n      ...(hasTable\n        ? [\n            configExtension(TableExtension, {\n              hasCellMerge: false,\n              hasCellBackgroundColor: false,\n              hasHorizontalScroll: true,\n              hasTabHandler: true,\n            }),\n          ]\n        : []),\n      // Selecting a horizontal rule with a click, so it can be deleted\n      ...(hasHorizontalRule ? [HorizontalRuleExtension] : []),\n    ],\n    // Start with an empty editor state like `createEditor` does, instead of a blank paragraph. The\n    // Markdown import then becomes the first state in the history, so undoing right after the\n    // editor loads doesn’t revert it to the blank paragraph and clear the value\n    $initialEditorState: null,\n    nodes: [\n      ...components.map(({ node }) => node),\n      ...pickForButtons(NODE_MAP, enabledButtons),\n      ...(isCodeEditor ? [CodeNode, CodeHighlightNode] : []),\n      // We haven’t implemented buttons for horizontal rules and tables yet, but we still want to\n      // support them in Markdown, so always include them in the node list, unless the editor is\n      // limited to a single line\n      ...(hasBlockSyntax ? [HorizontalRuleNode, TableNode, TableCellNode, TableRowNode] : []),\n    ],\n    theme: EDITOR_THEME,\n    html: format === 'html' ? getHtmlConfig({ hasCodeBlock, hasTaskList }) : undefined,\n    /**\n     * Log an error like `createEditor` does by default, instead of throwing it.\n     * @param {Error} error Error.\n     */\n    onError: (error) => {\n      // eslint-disable-next-line no-console\n      console.error(error);\n    },\n  });\n\n/**\n * Get the Markdown transformers for the enabled features, in the order they have to be applied.\n * @param {EditorSetup} setup Editor setup.\n * @returns {Transformer[]} Transformers.\n */\nconst getEnabledTransformers = ({ enabledButtons, components, isCodeEditor, hasBlockSyntax }) => {\n  const componentTransformers = components.map(({ transformer }) =>\n    removePlaceholdersFromMatch(transformer),\n  );\n\n  return [\n    ...componentTransformers,\n    // Raw HTML comes before the editor’s own syntax, so a line of an HTML block that starts like a\n    // link, for example, is still raw HTML. Only an editor component takes precedence\n    ...(isCodeEditor ? [] : [RAW_HTML]),\n    ...pickForButtons(TRANSFORMER_MAP, enabledButtons),\n    ...(isCodeEditor ? [CODE] : []),\n    // Horizontal rules and tables are always supported in Markdown; see `createEditorExtension()`\n    ...(hasBlockSyntax\n      ? [\n          HR,\n          // A table cell can only have inline content, so only the components with a text match\n          // transformer can be used there\n          createTableTransformer(\n            /** @type {TextMatchTransformer[]} */ (\n              componentTransformers.filter(({ type }) => type === 'text-match')\n            ),\n          ),\n        ]\n      : []),\n    // Last, so the syntax of the editor’s own comes first\n    ...(isCodeEditor ? [] : [RAW_SYNTAX]),\n  ];\n};\n\n/**\n * Register the Lexical listeners for the enabled features.\n * @param {LexicalEditor} editor Editor instance.\n * @param {EditorSetup} setup Editor setup.\n * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.\n * @param {(detail: ExportDetail) => void} onExport Function to call with the exported value.\n * @returns {{ flush: () => void, unregister: () => void }} Function to export the value right\n * away, and function to unregister them all.\n */\nconst registerEditorListeners = (\n  editor,\n  {\n    enabledButtons,\n    useMarkdownShortcuts,\n    isCodeEditor,\n    defaultLanguage,\n    format,\n    multiline,\n    hasCodeBlock,\n    hasTable,\n    hasLink,\n  },\n  enabledTransformers,\n  onExport,\n) => {\n  // The order matters, as listeners with the same priority are called in the registration order\n  const unregisterFeatures = mergeUnregisters(\n    registerRichText(editor),\n    registerDragonSupport(editor),\n    // Cap the undo stack, as each entry holds a snapshot of the whole document\n    registerHistory(\n      editor,\n      createEmptyHistoryState(),\n      1000,\n      undefined,\n      undefined,\n      HISTORY_MAX_DEPTH,\n    ),\n    isCodeEditor ? registerCodeEditorCommands(editor, defaultLanguage) : undefined,\n    multiline || isCodeEditor ? undefined : registerSingleLine(editor),\n    useMarkdownShortcuts ? registerMarkdownShortcuts(editor, enabledTransformers) : undefined,\n    hasCodeBlock\n      ? registerCodeHighlighting(editor, {\n          ...shikiTokenizer,\n          defaultLanguage,\n          defaultTheme: getCodeTheme(),\n        })\n      : undefined,\n    hasCodeBlock ? observeCodeTheme(editor) : undefined,\n    hasLink ? registerLinkCommands(editor) : undefined,\n    hasTable\n      ? editor.registerNodeTransform(TableNode, (table) => {\n          $ensureParagraphAfterTable(table);\n\n          // A Markdown table always has a single header row on top, while an HTML table can have\n          // any number of them, as well as a header column\n          if (format === 'markdown') {\n            $normalizeTableHeaders(table);\n          }\n        })\n      : undefined,\n    registerListCommands(editor, enabledButtons),\n    isCodeEditor ? undefined : registerGuards(editor, { format, enabledButtons }),\n  );\n\n  const valueExport = registerValueExport(editor, enabledTransformers, format, onExport);\n\n  const unregisterInput = mergeUnregisters(\n    registerTabIndentation(editor),\n    isCodeEditor ? undefined : registerPasteAsMarkdown(editor, enabledTransformers),\n  );\n\n  return {\n    flush: valueExport.flush,\n    unregister: mergeUnregisters(unregisterFeatures, valueExport.unregister, unregisterInput),\n  };\n};\n\n/**\n * Initialize the Lexical editor.\n * @param {Partial<TextEditorConfig>} config Editor configuration.\n * @param {InitEditorOptions} [options] Options.\n * @returns {InitEditorResult} Editor instance and cleanup.\n */\nexport const initEditor = (config, { onExport = () => {} } = {}) => {\n  const setup = getEditorSetup(normalizeConfig(config));\n  const enabledTransformers = getEnabledTransformers(setup);\n  const editor = buildEditorFromExtensions(createEditorExtension(setup));\n\n  // Let the HTML import tell the elements the components import\n  editorComponents.set(editor, setup.components);\n\n  const { flush, unregister } = registerEditorListeners(\n    editor,\n    setup,\n    enabledTransformers,\n    onExport,\n  );\n\n  return {\n    editor,\n    enabledTransformers,\n    flush,\n    /**\n     * Remove all registered Lexical listeners.\n     */\n    dispose: () => {\n      unregister();\n      editor.dispose();\n    },\n  };\n};\n","<script>\n  import { $getRoot as getRoot, HISTORY_MERGE_TAG } from 'lexical';\n  import { getContext, onMount, untrack } from 'svelte';\n  import { on } from 'svelte/events';\n  import { IMPORT_UPDATE_TAG } from './constants.js';\n  import { handleEditorMouseDown, isStaticDecoratorContent } from './editing/caret.js';\n  import { initEditor } from './core.js';\n  import { mergeUnregisters } from './utils.js';\n\n  /**\n   * @import { ExportDetail } from './conversion/update.js';\n   * @import { FormFieldStateProps, TextEditorStore, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'ltr' | 'rtl' | 'auto'} [dir] Direction of the text. With `auto` or no value, each\n   * paragraph takes the direction of its own text.\n   */\n\n  /**\n   * @type {WidgetStateProps & FormFieldStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    dir = undefined,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  /**\n   * Reference to the Lexical editor root element.\n   * @type {HTMLElement | undefined}\n   */\n  let lexicalRoot = $state();\n\n  const editable = $derived(!(disabled || readonly));\n\n  $effect(() => {\n    editorStore.editor?.setEditable(editable);\n  });\n\n  $effect(() => {\n    // Lexical owns the root element’s `dir` attribute, so set the direction on the root node, which\n    // the paragraphs then follow. Without one, each paragraph gets `dir=\"auto\"`\n    const { editor } = editorStore;\n    const direction = dir === 'ltr' || dir === 'rtl' ? dir : null;\n\n    // Check first, as even an update that changes nothing makes the editor convert its content\n    if (!editor || editor.getEditorState().read(() => getRoot().getDirection()) === direction) {\n      return;\n    }\n\n    editor.update(\n      () => {\n        getRoot().setDirection(direction);\n      },\n      // Keep the change out of the undo history\n      { tag: 'history-merge' },\n    );\n  });\n\n  /**\n   * Update the input value and the selection state whenever the editor exports its content.\n   * @param {ExportDetail} detail Exported value and selection state.\n   */\n  const onExport = ({ value: exportedValue, selection }) => {\n    const { hasConverterError, useRichText, inputValue } = editorStore;\n\n    // The content has been converted, if it has changed at all\n    editorStore.pending = false;\n\n    // Ignore the content while a value is being imported, like the empty code block the editor\n    // starts with: it would overwrite the value, which then replaces the content once imported\n    if (hasConverterError || !useRichText || editorStore.importing) {\n      return;\n    }\n\n    // Keep the value as given when the content is the one last imported, which the editor only\n    // writes in its own Markdown style, e.g. `_text_` for `*text*`: that’s not a change, whether\n    // the content is untouched or the user has undone their changes to it\n    const newValue = editorStore.getImportedValue(exportedValue) ?? exportedValue;\n\n    if (inputValue !== newValue) {\n      editorStore.setExportedValue(newValue);\n    }\n\n    editorStore.selection = selection;\n  };\n\n  /**\n   * Listen to `click` events on the editor. Ignore a click on a link, including one on the text\n   * within it, which Lexical renders as a child element of the `<a>`.\n   * @param {MouseEvent} event `click` event.\n   */\n  const onClick = (event) => {\n    if (/** @type {HTMLElement} */ (event.target)?.closest('a')) {\n      event.preventDefault();\n    }\n  };\n\n  /**\n   * Listen to `mousedown` events on the editor to place the caret where the user expects when the\n   * pointer is not on any editable text, like on an editor component.\n   * @param {MouseEvent} event `mousedown` event.\n   */\n  const onMouseDown = (event) => {\n    if (editorStore.editor) {\n      handleEditorMouseDown(editorStore.editor, event);\n    }\n  };\n\n  // The state is updated within `untrack()` or a microtask below, because the browser fires these\n  // events synchronously while it removes a focused element from the DOM, e.g. a nested editor in a\n  // component being removed, in the middle of Svelte rendering, where a plain assignment would be\n  // reported as an unsafe mutation. See also `<FloatingLinkEditor>`.\n\n  /**\n   * Check if the given element is a dialog other than the one the editor is in, if any, like a menu\n   * opened from the toolbar of a nested editor, which is rendered outside the editor.\n   * @param {Element | null} dialog Dialog element.\n   * @returns {boolean} Result.\n   */\n  const isOtherDialog = (dialog) => !!dialog && !dialog.contains(lexicalRoot ?? null);\n\n  /**\n   * Interactive element in an editor component the pointer has just been pressed on, if any.\n   * @type {Element | undefined}\n   */\n  let pressedComponentElement;\n\n  /**\n   * Track the pointer being pressed on an interactive element within an editor component. Safari\n   * doesn’t focus a button on click, like one on the toolbar of a nested editor, and moves the\n   * focus to the closest focusable ancestor, which is the root, or `<body>` instead. Neither is the\n   * focus leaving the component. A press on its static content, like its label, does move the\n   * focus to the root; see `handleEditorMouseDown()`.\n   * @param {MouseEvent} event `mousedown` event.\n   */\n  const onComponentMouseDown = ({ target }) => {\n    if (\n      target instanceof Element &&\n      target.closest('[data-lexical-decorator]') &&\n      !isStaticDecoratorContent(target)\n    ) {\n      pressedComponentElement = target;\n      window.setTimeout(() => {\n        pressedComponentElement = undefined;\n      });\n    }\n  };\n\n  /**\n   * Track the focus, to tell whether it’s in an editor component, like a nested editor or a field\n   * of the component, rather than on the editor itself. The focus moving to another dialog doesn’t\n   * change anything.\n   * @param {FocusEvent} event `focusin` event.\n   */\n  const onFocusIn = ({ target }) => {\n    const node = /** @type {Node} */ (target);\n\n    if (lexicalRoot?.contains(node)) {\n      // Safari moves the focus to the root when a button in a component is pressed; see above\n      if (node === lexicalRoot && pressedComponentElement?.isConnected) {\n        return;\n      }\n\n      untrack(() => {\n        editorStore.componentHasFocus = node !== lexicalRoot;\n      });\n    } else if (!(node instanceof Element && isOtherDialog(node.closest('dialog')))) {\n      untrack(() => {\n        editorStore.componentHasFocus = false;\n      });\n    }\n  };\n\n  /**\n   * Clear the state if the focus has left the editor component, landing on `<body>`, unless the\n   * pointer has just been pressed within the component, or another modal dialog is open.\n   */\n  const checkComponentFocus = () => {\n    // The update listener below may run within an effect, which mustn’t depend on the state\n    untrack(() => {\n      if (\n        editorStore.componentHasFocus &&\n        document.activeElement === document.body &&\n        !pressedComponentElement?.isConnected &&\n        ![...document.querySelectorAll(':modal')].some(isOtherDialog)\n      ) {\n        editorStore.componentHasFocus = false;\n      }\n    });\n  };\n\n  /**\n   * Track the focus leaving a removed element, which doesn’t fire `focusin`. The event also comes\n   * without a related target when a dialog opens, which only moves the focus into itself a moment\n   * later, so the state is kept while another modal dialog is open. Firefox and Safari don’t fire\n   * the event for a removed element at all; see the update listener below.\n   * @param {FocusEvent} event `focusout` event.\n   */\n  const onFocusOut = ({ relatedTarget }) => {\n    if (!relatedTarget) {\n      queueMicrotask(checkComponentFocus);\n    }\n  };\n\n  /**\n   * Pass what was just typed on as soon as the focus leaves the editor, rather than after the\n   * delay, so the value is up to date by the time the user acts on it, like with a button. That\n   * includes a nested editor in a component, which passes the change on to this editor through the\n   * component.\n   * @param {FocusEvent} event `focusout` event.\n   */\n  const onRootFocusOut = ({ relatedTarget }) => {\n    if (!lexicalRoot?.contains(/** @type {Node | null} */ (relatedTarget))) {\n      // The root may be being removed; see above\n      untrack(() => {\n        editorStore.flushExport();\n      });\n    }\n  };\n\n  onMount(() => {\n    const { editor, enabledTransformers, flush, dispose } = initEditor(editorStore.config, {\n      onExport,\n    });\n\n    editorStore.editor = editor;\n    editorStore.enabledTransformers = enabledTransformers;\n    editorStore.flushExport = flush;\n\n    // The root is bound before this runs\n    const root = /** @type {HTMLElement} */ (lexicalRoot);\n\n    const unregister = mergeUnregisters(\n      on(root, 'focusout', onRootFocusOut),\n      on(root, 'click', onClick),\n      on(root, 'mousedown', onMouseDown),\n      on(root, 'mousedown', onComponentMouseDown),\n      on(document, 'focusin', onFocusIn),\n      on(document, 'focusout', onFocusOut),\n      // A change made by the user is converted to Markdown a moment later, so report it as pending\n      // until then. An import, or an update that only changes how the content looks, e.g. the code\n      // highlighting, isn’t a change\n      editor.registerUpdateListener(({ dirtyElements, dirtyLeaves, tags }) => {\n        if (\n          (dirtyElements.size || dirtyLeaves.size) &&\n          !tags.has(IMPORT_UPDATE_TAG) &&\n          !tags.has(HISTORY_MERGE_TAG)\n        ) {\n          editorStore.pending = true;\n        }\n\n        // An editor component with the focus may have been removed, which doesn’t fire `focusout`\n        // in Firefox and Safari\n        checkComponentFocus();\n      }),\n    );\n\n    return () => {\n      // Pass on what was just typed, as Firefox and Safari don’t fire `focusout` when the focused\n      // root is removed. This does nothing if the change has been passed on already\n      flush();\n      unregister();\n      dispose();\n      editor.setRootElement(null);\n      editorStore.initialized = false;\n      editorStore.editor = undefined;\n    };\n  });\n\n  $effect(() => {\n    // Both are in place by the time the effect first runs; see `onMount()` above\n    /* v8 ignore else */\n    if (editorStore.editor && lexicalRoot) {\n      editorStore.editor.setRootElement(lexicalRoot);\n      editorStore.initialized = true;\n    }\n  });\n</script>\n\n<div\n  bind:this={lexicalRoot}\n  {...restProps}\n  role=\"textbox\"\n  aria-multiline={editorStore.config.multiline !== false}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-readonly={readonly}\n  aria-required={required}\n  aria-invalid={invalid}\n  class=\"lexical-root\"\n  class:code={editorStore.config.isCodeEditor}\n  id={`${editorStore.editorId}-lexical-root`}\n  contenteditable={editable}\n  {hidden}\n></div>\n\n<style>.lexical-root {\n  overflow: clip;\n  border: 1px solid var(--sui-textbox-border-color);\n  border-radius: var(--sui-textbox-border-radius) !important;\n  padding: var(--sui-textbox-multiline-padding);\n  min-height: 120px;\n  color: var(--sui-textbox-foreground-color);\n  background-color: var(--sui-textbox-background-color);\n  font-family: var(--sui-textbox-font-family);\n  font-size: var(--sui-textbox-font-size);\n  line-height: var(--sui-textbox-multiline-line-height);\n  transition-duration: 200ms;\n  transition-property: outline-color, border-color, color, background-color;\n  outline-offset: calc(var(--sui-focus-ring-width) * -1);\n}\n.lexical-root:not(:first-child) {\n  border-start-start-radius: 0 !important;\n  border-start-end-radius: 0 !important;\n}\n.lexical-root.code {\n  padding: 0;\n}\n.lexical-root.code :global(.code-block) {\n  border-radius: 0 !important;\n  min-height: 120px;\n}\n.lexical-root:focus {\n  color: var(--sui-textbox-foreground-color-focus, var(--sui-textbox-foreground-color));\n  background-color: var(--sui-textbox-background-color-focus, var(--sui-textbox-background-color));\n}\n.lexical-root[aria-invalid=true] {\n  border-color: var(--sui-error-border-color);\n}\n.lexical-root[aria-readonly=true] {\n  color: var(--sui-secondary-foreground-color);\n  background-color: var(--sui-disabled-background-color);\n}\n.lexical-root :global(:not(.sui):first-child) {\n  margin-top: 0;\n}\n.lexical-root :global(:not(.sui):last-child) {\n  margin-bottom: 0;\n}\n.lexical-root :global(strong.italic) {\n  font-style: italic;\n}\n.lexical-root :global(.underline) {\n  text-decoration: underline;\n}\n.lexical-root :global(.strikethrough) {\n  text-decoration: line-through;\n}\n.lexical-root :global(.underline.strikethrough) {\n  text-decoration: underline line-through;\n}\n.lexical-root :global(li.nested) {\n  list-style-type: none;\n}\n.lexical-root :global(li.task-list-item:not(.nested)) {\n  position: relative;\n  padding-inline-start: 1.5em;\n  list-style-type: none;\n}\n.lexical-root :global(li.task-list-item:not(.nested)::before) {\n  position: absolute;\n  inset-block-start: calc((1lh - 1em) / 2);\n  inset-inline-start: 0;\n  border: var(--sui-checkbox-border-width, 1.5px) solid var(--sui-checkbox-border-color);\n  border-radius: var(--sui-checkbox-border-radius);\n  width: 1em;\n  height: 1em;\n  background-color: var(--sui-checkbox-background-color);\n  content: \"\";\n  cursor: pointer;\n}\n.lexical-root :global(li.task-list-item:not(.nested).checked::before) {\n  border-color: var(--sui-checkbox-border-color-checked, var(--sui-primary-accent-color));\n  background-color: var(--sui-checkbox-background-color-checked, var(--sui-primary-accent-color));\n}\n.lexical-root :global(li.task-list-item:not(.nested).checked::after) {\n  position: absolute;\n  inset-block-start: calc((1lh - 1em) / 2 + 0.15em);\n  inset-inline-start: 0.35em;\n  border-width: 0 2px 2px 0;\n  border-style: solid;\n  border-color: var(--sui-checkbox-foreground-color-checked, var(--sui-primary-accent-color-inverted));\n  width: 0.3em;\n  height: 0.55em;\n  content: \"\";\n  transform: rotate(45deg);\n  pointer-events: none;\n}\n.lexical-root :global(.code-block) {\n  position: relative;\n  display: block;\n  padding-block: 8px;\n  padding-inline-start: 56px;\n  padding-inline-end: 8px;\n  background-color: var(--sui-code-background-color);\n  overflow-x: auto;\n  white-space: pre;\n}\n.lexical-root :global(.code-block:not(:first-child)) {\n  margin-top: 1em;\n}\n.lexical-root :global(.code-block:not(:last-child)) {\n  margin-bottom: 1em;\n}\n.lexical-root :global(.code-block::before) {\n  position: absolute;\n  inset-block: 0;\n  inset-inline-start: 0;\n  inset-inline-end: auto;\n  content: attr(data-gutter);\n  padding: 8px;\n  min-width: 40px;\n  color: var(--sui-tertiary-foreground-color);\n  background-color: var(--sui-tertiary-background-color);\n  text-align: end;\n}\n.lexical-root :global([data-lexical-text=true]) {\n  cursor: text;\n}\n.lexical-root :global(:is(th, td)) > :global(p) {\n  margin: 0;\n  white-space: normal;\n  word-break: normal;\n}\n.lexical-root :global(.table-wrapper) {\n  overflow-x: auto;\n}\n.lexical-root :global(.table-wrapper:not(:first-child)) {\n  margin-top: 1em;\n}\n.lexical-root :global(.table-wrapper:not(:last-child)) {\n  margin-bottom: 1em;\n}\n.lexical-root :global(:is(th, td)) {\n  min-width: 80px;\n  vertical-align: top;\n  text-align: start;\n}\n.lexical-root :global(th) {\n  background-color: var(--sui-secondary-background-color);\n}\n.lexical-root :global(:is(th, td).selected) {\n  background-color: var(--sui-selected-background-color);\n}\n.lexical-root :global(.table-selection) :global(::selection) {\n  background-color: transparent;\n}\n.lexical-root :global(hr) {\n  margin: var(--sui-paragraph-margin) 0;\n  border: none;\n  padding: 0;\n}\n.lexical-root :global(hr.selected) {\n  outline: 2px solid var(--sui-primary-accent-color);\n  outline-offset: 4px;\n}\n.lexical-root :global(hr::after) {\n  display: block;\n  height: 2px;\n  background-color: var(--sui-control-border-color);\n  line-height: 2px;\n  content: \"\";\n}</style>\n","import { generateElementId } from '@sveltia/utils/element';\nimport { untrack } from 'svelte';\nimport { convertHtmlToLexical, convertMarkdownToLexical } from './conversion/import.js';\nimport { normalizeConfig } from './config.js';\n\n/**\n * @import { LexicalEditor } from 'lexical';\n * @import { Transformer } from '@lexical/markdown';\n * @import { TextEditorConfig, TextEditorSelectionState, TextEditorStore } from '../../typedefs.js';\n */\n\n/**\n * Function to call with the new input value whenever it changes, for each editor store; see\n * {@link syncEditorProps}.\n * @type {WeakMap<TextEditorStore, (inputValue: string) => void>}\n */\nconst inputValueListeners = new WeakMap();\n\n/**\n * Create an editor editor store that contains all the states and configuration.\n * @returns {TextEditorStore} Store.\n */\nexport const createEditorStore = () => {\n  /** @type {string} */\n  const editorId = generateElementId('editor');\n  /** @type {boolean} */\n  let initialized = $state(false);\n  /** @type {LexicalEditor | undefined} */\n  let editor = $state();\n  /** @type {Transformer[]} */\n  let enabledTransformers = $state([]);\n  /** @type {TextEditorConfig} */\n  let config = $state(normalizeConfig({ useMarkdownShortcuts: true }));\n  /** @type {string} */\n  let inputValue = $state('');\n  /** @type {TextEditorSelectionState} */\n  let selection = $state({ blockNodeKey: null, blockType: 'paragraph', inlineTypes: [] });\n  /** @type {boolean} */\n  let useRichText = $state(true);\n  /** @type {HTMLTextAreaElement | undefined} */\n  let textArea = $state();\n  /** @type {number} */\n  let toolbarHeight = $state(0);\n  /** @type {boolean} */\n  let componentHasFocus = $state(false);\n  /** @type {boolean} */\n  let hasConverterError = $state(false);\n  /** @type {boolean} */\n  let showConverterError = $state(false);\n  /** @type {boolean} */\n  let pending = $state(false);\n  /**\n   * Number of editor operations started by the user that have yet to update the editor.\n   * @type {number}\n   */\n  let runningOperations = $state(0);\n  /**\n   * Value last imported to the Lexical editor, and the Markdown or HTML the editor exports for it.\n   * @type {{ source: string, exported: string } | undefined}\n   */\n  let lastImport = undefined;\n  /**\n   * Number of imports started, to tell the latest one.\n   * @type {number}\n   */\n  let importCount = 0;\n  /**\n   * Whether the latest import is still in progress.\n   * @type {boolean}\n   */\n  let importing = false;\n\n  /**\n   * Flag a conversion error, which takes the editor out of the rich text mode, and shows the error\n   * to the user.\n   * @param {boolean} newValue Whether there is an error.\n   */\n  const setConverterError = (newValue) => {\n    hasConverterError = newValue;\n\n    if (newValue) {\n      useRichText = false;\n      showConverterError = true;\n    }\n  };\n\n  /**\n   * Convert the Markdown or HTML {@link inputValue} to Lexical nodes. Disable the rich text mode\n   * and restore the original value when there is an error while conversion.\n   */\n  const convertToLexical = async () => {\n    if (!editor || !initialized) {\n      return;\n    }\n\n    const originalValue = inputValue;\n\n    importCount += 1;\n\n    const importId = importCount;\n\n    importing = true;\n\n    try {\n      // We should avoid an empty editor; there should be at least one `<p>`, so give it an empty\n      // string if the `value` is `undefined`\n      // @see https://github.com/facebook/lexical/issues/2308\n      const exported =\n        config.format === 'html'\n          ? await convertHtmlToLexical(editor, inputValue || '')\n          : await convertMarkdownToLexical(editor, inputValue || '', enabledTransformers);\n\n      // Skip an import superseded by a newer one, which sets its own value\n      if (exported !== undefined) {\n        lastImport = { source: originalValue, exported };\n      }\n    } catch (ex) {\n      // Go through the setter, so the editor actually falls back to the plain text mode\n      setConverterError(true);\n      inputValue = originalValue;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      // An earlier import finishing last doesn’t end the latest one\n      if (importId === importCount) {\n        importing = false;\n      }\n    }\n  };\n\n  /** @type {TextEditorStore} */\n  const store = {\n    /* eslint-disable jsdoc/require-jsdoc */\n    get editor() {\n      return editor;\n    },\n    set editor(newValue) {\n      editor = newValue;\n    },\n    set enabledTransformers(newValue) {\n      enabledTransformers = newValue;\n    },\n    get enabledTransformers() {\n      return enabledTransformers;\n    },\n    get initialized() {\n      return initialized;\n    },\n    set initialized(newValue) {\n      initialized = newValue;\n    },\n    get config() {\n      return config;\n    },\n    set config(newValue) {\n      config = normalizeConfig(newValue);\n      useRichText = config.modes[0] === 'rich-text' || config.isCodeEditor;\n    },\n    get inputValue() {\n      return inputValue;\n    },\n    set inputValue(newValue) {\n      const hasChange = inputValue !== newValue;\n\n      store.setExportedValue(newValue);\n\n      if (useRichText && (hasChange || editor?.getEditorState().isEmpty())) {\n        convertToLexical();\n      }\n    },\n    get selection() {\n      return selection;\n    },\n    set selection(newValue) {\n      selection = newValue;\n    },\n    get controlId() {\n      return useRichText ? `${editorId}-lexical-root` : `${editorId}-plain-text`;\n    },\n    get textArea() {\n      return textArea;\n    },\n    set textArea(newValue) {\n      textArea = newValue;\n    },\n    get toolbarHeight() {\n      return toolbarHeight;\n    },\n    set toolbarHeight(newValue) {\n      toolbarHeight = newValue;\n    },\n    get componentHasFocus() {\n      return componentHasFocus;\n    },\n    set componentHasFocus(newValue) {\n      componentHasFocus = newValue;\n    },\n    get useRichText() {\n      return useRichText;\n    },\n    set useRichText(newValue) {\n      useRichText = newValue;\n    },\n    get hasConverterError() {\n      return hasConverterError;\n    },\n    set hasConverterError(newValue) {\n      setConverterError(newValue);\n    },\n    get showConverterError() {\n      return showConverterError;\n    },\n    set showConverterError(newValue) {\n      showConverterError = newValue;\n    },\n    get pending() {\n      return pending || runningOperations > 0;\n    },\n    set pending(newValue) {\n      pending = newValue;\n    },\n    get importing() {\n      return importing;\n    },\n    editorId,\n    convertToLexical,\n    /**\n     * Mark an operation the user started as running, which makes the content count as\n     * {@link TextEditorStore.pending} until it’s done. Use it for an operation that only reaches\n     * the editor after an `await`, such as a language change waiting for the highlighter to load:\n     * the flag the editor sets for itself is cleared by every update it makes in the meantime,\n     * including the one the focus move fires, so it can’t cover the wait.\n     * @returns {() => void} Function to call once the operation has updated the editor. Calling it\n     * more than once has no further effect.\n     */\n    startOperation: () => {\n      runningOperations += 1;\n\n      let done = false;\n\n      return () => {\n        if (!done) {\n          done = true;\n          runningOperations -= 1;\n        }\n      };\n    },\n    /**\n     * Get the value last imported if the given value, exported by the editor, is only that value\n     * written in the editor’s own Markdown or HTML style.\n     * @param {string} value Exported value.\n     * @returns {string | undefined} Imported value, or `undefined` if the content has changed.\n     */\n    getImportedValue: (value) => (lastImport?.exported === value ? lastImport.source : undefined),\n    /**\n     * Set the input value to the one exported from the Lexical editor, without importing it back\n     * into the editor, which would reset its nodes and selection.\n     * @param {string} value Exported value.\n     */\n    setExportedValue: (value) => {\n      if (inputValue !== value) {\n        inputValue = value;\n        inputValueListeners.get(store)?.(value);\n      }\n    },\n    /**\n     * Export the content of the Lexical editor right away, if it’s scheduled to be exported. The\n     * editor root sets this while the editor is there.\n     */\n    flushExport: () => {},\n    /* eslint-enable jsdoc/require-jsdoc */\n  };\n\n  return store;\n};\n\n/**\n * Keep the bindable props of a `<TextEditor>` or `<CodeEditor>` in sync with its editor store: the\n * `pending` flag, and the value going into and coming out of the editor. This must be called\n * during the component initialization, after the store is created.\n * @param {TextEditorStore} editorStore Editor store.\n * @param {object} args Arguments.\n * @param {() => string} args.getInputValue Read the props and return them as the editor input\n * value. The props read here are tracked, so the editor is updated whenever they change.\n * @param {(inputValue: string) => void} args.setValue Update the props with the editor input value\n * when it changes.\n * @param {(pending: boolean) => void} args.setPending Update the `pending` prop.\n */\nexport const syncEditorProps = (editorStore, { getInputValue, setValue, setPending }) => {\n  /**\n   * Input value last passed on to the props.\n   * @type {string | undefined}\n   */\n  let appliedValue = undefined;\n  /**\n   * Latest input value, which may not have been passed on to the props yet.\n   * @type {string | undefined}\n   */\n  let latestValue = undefined;\n\n  $effect(() => {\n    setPending(editorStore.pending);\n  });\n\n  // An editor removed right after a change never converts it, so don’t leave a bound `pending` set\n  // for good, which would hold up anything waiting for the change\n  $effect(() => () => {\n    setPending(false);\n  });\n\n  $effect(() => {\n    // The root initializes the editor before these effects first run, and stays initialized\n    /* v8 ignore next */\n    if (!editorStore.initialized) {\n      return;\n    }\n\n    const newValue = getInputValue();\n\n    untrack(() => {\n      editorStore.inputValue = newValue;\n    });\n  });\n\n  $effect(() => {\n    // The root initializes the editor before these effects first run, and stays initialized\n    /* v8 ignore next */\n    if (!editorStore.initialized) {\n      return;\n    }\n\n    const newValue = editorStore.inputValue;\n\n    appliedValue = newValue;\n\n    untrack(() => {\n      setValue(newValue);\n    });\n  });\n\n  // An editor being removed passes on what was just typed as it goes, either as the focus leaves it\n  // or as `<LexicalRoot>` is destroyed, but the effect above is gone by then. Remember the change,\n  // and pass it on once the removal is done: a teardown function only sees the state as it was\n  // before, so it can’t tell whether the props have been changed from outside in the meantime,\n  // e.g. in the same tick as the removal, in which case they win\n  inputValueListeners.set(editorStore, (newValue) => {\n    latestValue = newValue;\n  });\n\n  $effect(() => () => {\n    queueMicrotask(() => {\n      if (\n        latestValue !== undefined &&\n        latestValue !== appliedValue &&\n        untrack(getInputValue) === appliedValue\n      ) {\n        setValue(latestValue);\n      }\n    });\n  });\n};\n","<script>\n  import { $isCodeNode as isCodeNode } from '@lexical/code-core';\n  import { _ } from '@sveltia/i18n';\n  import { $getNodeByKey as getNodeByKey, $getRoot as getRoot } from 'lexical';\n  import { getContext } from 'svelte';\n  import Option from '../../listbox/option.svelte';\n  import Select from '../../select/select.svelte';\n  import { getBackgroundUpdateTags } from '../background-update.js';\n  import { focusEditor } from '../editing/caret.js';\n  import { loadCodeHighlighter } from '../shiki/preload.js';\n  import { LANGUAGES } from '../shiki/generated.js';\n\n  /**\n   * @import { CodeNode } from '@lexical/code-core';\n   * @import { TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [disabled] Whether to disable the switcher.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    disabled = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {{ key: string, label: string, aliases: string[] }[]} */\n  const codeLanguages = LANGUAGES.map(({ id, name, aliases = [] }) => ({\n    key: id,\n    label: name,\n    aliases,\n  }));\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  let selectedLanguage = $state('plain');\n\n  // A code block can carry an alias, e.g. `js`, while the options are keyed by the canonical ID,\n  // e.g. `javascript`, so resolve the alias for the selector to find its option. A language that\n  // isn’t listed, e.g. `txt`, is shown as plain text; otherwise the selector would keep the label\n  // of the previous block, as it only updates the label when an option matches\n  const selectedKey = $derived(\n    codeLanguages.find(\n      ({ key, aliases }) => key === selectedLanguage || aliases.includes(selectedLanguage),\n    )?.key ?? 'plain',\n  );\n\n  /**\n   * Get the code block the switcher targets. A code editor has exactly one code block, and its\n   * `blockNodeKey` is still unset the first time the switcher is used, before the editor has ever\n   * been focused. Call this within `editor.read()` or `editor.update()`.\n   * @returns {CodeNode | null} Code node, or `null` if the selection is not in a code block.\n   */\n  const getCodeNode = () => {\n    const { blockNodeKey } = editorStore.selection;\n\n    const node = editorStore.config.isCodeEditor\n      ? getRoot().getChildren()[0]\n      : blockNodeKey\n        ? getNodeByKey(blockNodeKey)\n        : null;\n\n    return isCodeNode(node) ? node : null;\n  };\n\n  /**\n   * Give the code block the given language, once the highlighter for it has loaded.\n   * @param {string} lang Language ID.\n   */\n  const changeLanguage = async (lang) => {\n    const { editor } = editorStore;\n\n    if (!editor || selectedKey === lang) {\n      return;\n    }\n\n    // The change only reaches the editor, and anything bound to it, once the highlighter has\n    // loaded, so report the content as pending until then: the flag the editor sets for itself is\n    // cleared by the update the focus move below fires\n    const endOperation = editorStore.startOperation();\n\n    try {\n      await focusEditor(editor);\n      await loadCodeHighlighter(lang);\n\n      // The user may have moved on to another field while the highlighter was loading\n      editor.update(\n        () => {\n          // https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/plugins/ToolbarPlugin/index.tsx#L713\n          const node = getCodeNode();\n\n          if (node) {\n            node.setLanguage(lang);\n            selectedLanguage = lang;\n          }\n        },\n        { tag: getBackgroundUpdateTags(editor) },\n      );\n    } finally {\n      // The editor has flagged the export that follows as pending by now, so the hand-off leaves\n      // no gap\n      endOperation();\n    }\n  };\n\n  $effect(() => {\n    void editorStore.selection.blockNodeKey;\n\n    editorStore.editor?.read(() => {\n      const node = getCodeNode();\n\n      if (node) {\n        // The highlighter gives a block without a language the default one as it’s transformed,\n        // so the fallbacks here are only for the unexpected\n        /* v8 ignore next */\n        selectedLanguage = node.getLanguage() ?? editorStore.config.defaultLanguage ?? 'plain';\n      }\n    });\n  });\n</script>\n\n<Select\n  {disabled}\n  ariaLabel={_('_sui.text_editor.language')}\n  value={selectedKey}\n  onChange={({ detail: { value: lang } }) => {\n    changeLanguage(lang);\n  }}\n>\n  <Option label={_('_sui.text_editor.plain_text')} value=\"plain\" dir=\"ltr\" />\n  {#each codeLanguages as { key, label } (key)}\n    <Option {label} value={key} selected={key === selectedKey} dir=\"ltr\" />\n  {/each}\n</Select>\n","<!--\n  @component\n  A toolbar layout that can contain `<Button>`, `<Select>` and other widgets.\n  @see https://w3c.github.io/aria/#toolbar\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/\n-->\n<script>\n  /**\n   * @import { ContainerProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'horizontal' | 'vertical'} [orientation] Orientation of the widget. An alias of the\n   * `aria-orientation` attribute.\n   * @property {'primary' | 'secondary'} [variant] The style variant of the toolbar.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    orientation = 'horizontal',\n    variant = undefined,\n    ariaLabel = undefined,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div\n  {...restProps}\n  role=\"toolbar\"\n  class={['sui', 'toolbar', orientation, variant, className]}\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-orientation={orientation}\n  aria-label={ariaLabel}\n>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    {@render children?.()}\n  </div>\n</div>\n\n<style>[role=toolbar] {\n  --toolbar-size: var(--sui-secondary-toolbar-size);\n  flex: none !important;\n  display: flex;\n  align-items: center;\n  padding-inline: 8px;\n  background-color: var(--toolbar-background-color, transparent);\n}\n[role=toolbar].primary {\n  --toolbar-size: var(--sui-primary-toolbar-size);\n}\n@media (width < 768px) {\n  [role=toolbar].secondary {\n    padding-inline: 0;\n  }\n}\n[role=toolbar][aria-orientation=horizontal] {\n  height: var(--toolbar-size);\n}\n[role=toolbar][aria-orientation=vertical] {\n  flex-direction: column;\n  width: var(--toolbar-size);\n}\n[role=toolbar] :global(button[role=button]:is([aria-pressed=true], [aria-checked=true])) {\n  background-color: var(--sui-selected-background-color);\n}\n[role=toolbar] :global(h2) {\n  flex: auto;\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin: 0;\n  padding-inline-end: 12px;\n  min-width: 0;\n  font-size: var(--sui-font-size-x-large);\n}\n[role=toolbar] :global(h2:first-child) {\n  padding-inline-start: 12px;\n}\n[role=toolbar] :global(h2) :global(span:not(.sui.truncated-text)) {\n  font-size: var(--sui-font-size-small);\n  font-weight: var(--sui-font-weight-normal, normal);\n  opacity: 0.8;\n}\n[role=toolbar] :global(.divider[aria-orientation=horizontal]) {\n  margin: 0 4px;\n  width: calc(100% - 8px);\n}\n[role=toolbar] :global(.divider[aria-orientation=vertical]) {\n  margin: 4px 0;\n  height: calc(100% - 8px);\n}\n\n.inner {\n  display: contents;\n}</style>\n","<script>\n  import { getContext } from 'svelte';\n  import Toolbar from '../../toolbar/toolbar.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\n   * @property {Snippet} [children] Primary slot content.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    disabled = false,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  /**\n   * Keep the toolbar height in the store, so the sticky toolbars of nested editors can be placed\n   * below this one.\n   * @param {HTMLElement} toolbar Toolbar element.\n   * @returns {() => void} Cleanup function.\n   */\n  const observeHeight = (toolbar) => {\n    const observer = new ResizeObserver(([entry]) => {\n      editorStore.toolbarHeight = entry.borderBoxSize[0].blockSize;\n    });\n\n    observer.observe(toolbar);\n\n    return () => {\n      observer.disconnect();\n      editorStore.toolbarHeight = 0;\n    };\n  };\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <Toolbar {...restProps} {disabled} {@attach observeHeight}>\n    {@render children?.()}\n  </Toolbar>\n</div>\n\n<style>.wrapper {\n  display: contents;\n}\n.wrapper :global([role=toolbar]) {\n  position: sticky;\n  top: var(--sui-text-editor-toolbar-top, 0px);\n  z-index: var(--sui-text-editor-toolbar-z-index, 100);\n  display: flex;\n  flex-wrap: wrap;\n  gap: 4px;\n  border-width: 1px 1px 0;\n  border-style: solid;\n  border-color: var(--sui-textbox-border-color);\n  border-start-start-radius: var(--sui-textbox-border-radius);\n  border-start-end-radius: var(--sui-textbox-border-radius);\n  border-end-start-radius: 0;\n  border-end-end-radius: 0;\n  padding: 0 4px;\n  height: auto;\n  min-height: 40px;\n  background-color: var(--sui-tertiary-background-color);\n}\n.wrapper :global([role=toolbar][aria-disabled=true]) {\n  filter: none;\n}\n.wrapper :global([role=toolbar][aria-disabled=true]) > :global([inert]) {\n  filter: grayscale(1) opacity(var(--sui-disabled-opacity, 0.35));\n}\n.wrapper :global(.sui.menu-button) {\n  padding: 0 4px;\n}\n.wrapper :global(.sui.button) {\n  flex: none;\n  margin: 0 !important;\n}\n.wrapper :global(.sui.button-group) {\n  gap: 4px;\n}</style>\n","<!--\n  @component\n  A code editor based on Lexical.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { setContext } from 'svelte';\n  import Alert from '../alert/alert.svelte';\n  import Toast from '../toast/toast.svelte';\n  import { parseCodeBlock, toCodeBlock } from './code-editor.js';\n  import LexicalRoot from './lexical-root.svelte';\n  import { createEditorStore, syncEditorProps } from './store.svelte.js';\n  import CodeLanguageSwitcher from './toolbar/code-language-switcher.svelte';\n  import ToolbarWrapper from './toolbar/toolbar-wrapper.svelte';\n\n  /**\n   * @import {\n   * EditorCommonProps,\n   * FormFieldStateProps,\n   * WidgetStateProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [code] Input value.\n   * @property {string} [lang] Selected language.\n   * @property {boolean} [pending] Whether the user has changed the code, and the editor has yet to\n   * update {@link code}, which it does a moment later. Bind it to wait for the change before\n   * reading the code, for example to save it. Read-only.\n   * @property {boolean} [showLanguageSwitcher] Whether to show the language selector.\n   */\n\n  /**\n   * @type {EditorCommonProps & WidgetStateProps & FormFieldStateProps & Props &\n   * Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    code = $bindable(''),\n    lang = $bindable('plain'),\n    pending = $bindable(false),\n    showLanguageSwitcher = false,\n    flex = false,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    ariaLabel = undefined,\n    ariaLabelledby = undefined,\n    ariaDescribedby = undefined,\n    'aria-label': ariaLabelAttr = undefined,\n    'aria-labelledby': ariaLabelledbyAttr = undefined,\n    'aria-describedby': ariaDescribedbyAttr = undefined,\n    // Not rendered, but kept out of `restProps`, which go on the wrapper element\n    children: _children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Labelling attributes for the editable text box. They’re pulled out of `restProps` because the\n   * rest goes on the presentational wrapper, where ARIA would ignore them.\n   */\n  const labelAttrs = $derived({\n    'aria-label': ariaLabel ?? ariaLabelAttr,\n    'aria-labelledby': ariaLabelledby ?? ariaLabelledbyAttr,\n    'aria-describedby': ariaDescribedby ?? ariaDescribedbyAttr,\n  });\n\n  const editorStore = createEditorStore();\n\n  editorStore.config = {\n    ...editorStore.config,\n    useMarkdownShortcuts: false,\n    isCodeEditor: true,\n    defaultLanguage: lang,\n  };\n\n  setContext('editorStore', editorStore);\n\n  syncEditorProps(editorStore, {\n    /**\n     * Wrap the code in a fenced code block for the editor.\n     * @returns {string} Code block.\n     */\n    getInputValue: () => toCodeBlock(lang, code),\n    /**\n     * Take the editor’s code block apart into the language and the code.\n     * @param {string} inputValue Code block.\n     */\n    setValue: (inputValue) => {\n      const { lang: _lang, code: _code } = parseCodeBlock(inputValue);\n\n      if (lang !== _lang) {\n        lang = _lang;\n      }\n\n      if (code !== _code) {\n        code = _code;\n      }\n    },\n    /**\n     * Update the `pending` prop.\n     * @param {boolean} newValue New value.\n     */\n    setPending: (newValue) => {\n      pending = newValue;\n    },\n  });\n</script>\n\n<div\n  {...restProps}\n  role=\"none\"\n  class=\"sui code-editor\"\n  class:flex\n  {hidden}\n  style:--sui-text-editor-toolbar-height=\"{editorStore.toolbarHeight}px\"\n>\n  {#if showLanguageSwitcher}\n    <ToolbarWrapper disabled={disabled || readonly} ariaLabel={_('_sui.text_editor.code_editor')}>\n      <CodeLanguageSwitcher disabled={disabled || readonly} />\n    </ToolbarWrapper>\n  {/if}\n  <LexicalRoot {...labelAttrs} {hidden} {disabled} {readonly} {required} {invalid} />\n</div>\n\n{#if editorStore.showConverterError}\n  <Toast bind:show={editorStore.showConverterError}>\n    <Alert status=\"error\">{_('_sui.text_editor.converter_error')}</Alert>\n  </Toast>\n{/if}\n\n<style>.code-editor {\n  margin: var(--sui-focus-ring-width);\n  width: calc(100% - var(--sui-focus-ring-width) * 2);\n}\n.code-editor.flex:not([hidden]) {\n  display: block;\n}\n.code-editor {\n  --sui-text-editor-toolbar-top: var(--sui-text-editor-inner-toolbar-top, 0px);\n  --sui-text-editor-toolbar-z-index: var(--sui-text-editor-inner-toolbar-z-index, 100);\n}\n.code-editor > :global(*) {\n  --sui-text-editor-inner-toolbar-top: calc(\n    var(--sui-text-editor-toolbar-top) + var(--sui-text-editor-toolbar-height)\n  );\n  --sui-text-editor-inner-toolbar-z-index: calc(var(--sui-text-editor-toolbar-z-index) - 1);\n}</style>\n","/**\n * Logic behind `<TextArea>`, kept apart from the component so the syntax highlighting can be tested\n * without rendering anything.\n */\n\n/**\n * @import { HighlightedToken } from '../../typedefs.js';\n */\n\n/**\n * Get the syntax-highlighted tokens of the value, flattened with line breaks in between, plus a\n * trailing one, like the content of the clone element that measures the auto-resized height.\n * They’re only used when they add up to the value exactly, since stale tokens would show text\n * different from what’s being edited.\n * @param {string | undefined} value Value of the `<textarea>`.\n * @param {((value: string) => HighlightedToken[][] | undefined) | undefined} highlight Function to\n * tokenize the value, returning one array of tokens per line.\n * @returns {HighlightedToken[] | undefined} Tokens, or `undefined` if there’s no `highlight`\n * function, it returns no tokens, or the tokens don’t add up to the value.\n */\nexport const getHighlightedTokens = (value, highlight) => {\n  const lines = highlight?.(value ?? '');\n\n  if (!lines) {\n    return undefined;\n  }\n\n  const tokens = lines.flatMap((line) => [...line, { content: '\\n' }]);\n\n  return tokens.map(({ content }) => content).join('') === `${value}\\n` ? tokens : undefined;\n};\n","<!--\n  @component\n  A multi-line text field based on the HTML `<textarea>` element, providing the auto-resize support.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea\n  @see https://w3c.github.io/aria/#textbox\n  @see https://css-tricks.com/the-cleanest-trick-for-autogrowing-textareas/\n-->\n<script>\n  import { getLabelAboveText } from '../../services/label.js';\n  import LabelAbove from '../util/label-above.svelte';\n  import EmojiAutocomplete from './emoji-autocomplete.svelte';\n  import { getHighlightedTokens } from './text-area.js';\n\n  /**\n   * @import {\n   * CommonEventHandlers,\n   * ContainerProps,\n   * FormFieldStateProps,\n   * HighlightedToken,\n   * InputEventHandlers,\n   * LabelAboveProps,\n   * WidgetStateProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [value] Input value.\n   * @property {HTMLTextAreaElement} [element] A reference to the `<textarea>` element.\n   * @property {boolean} [flex] Make the text input container flexible.\n   * @property {'ltr' | 'rtl' | 'auto'} [dir] The `dir` attribute on the `<textarea>` element.\n   * @property {string} [name] The `name` attribute on the `<textarea>` element.\n   * @property {boolean} [autoResize] Whether to automatically resize the `<textarea>` based on the\n   * content.\n   * @property {boolean} [useEmojiAutocomplete] Whether to autocomplete emojis when the user\n   * types a shortcode, like `:smi`.\n   * @property {(value: string) => HighlightedToken[][] | undefined} [highlight] Function to\n   * tokenize the value for syntax highlighting, returning one array of tokens per line, or\n   * `undefined` to show the text as is, for example while a grammar is still loading. The tokens\n   * are painted behind the text, which is made transparent, so the `<textarea>` keeps working as\n   * usual. Only styles that keep the text width can be applied, so the glyphs stay aligned.\n   */\n\n  /**\n   * @type {LabelAboveProps & CommonEventHandlers & InputEventHandlers & ContainerProps &\n   * WidgetStateProps & FormFieldStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(''),\n    element: boundElement = $bindable(),\n    flex = false,\n    dir = undefined,\n    name = undefined,\n    autoResize = false,\n    useEmojiAutocomplete = false,\n    highlight = undefined,\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    showLabelAbove = false,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * A reference to the `<textarea>` element. It’s kept apart from the bindable `element` prop,\n   * which Svelte resets whenever the props spread onto this component change, unless the consumer\n   * binds it.\n   * @type {HTMLTextAreaElement | undefined}\n   */\n  let element = $state.raw();\n\n  const uid = $props.id();\n  /** ID of the `<textarea>` element, which the label above it points to. */\n  const textareaId = $derived(restProps.id ?? `${uid}-textarea`);\n  /** Label shown above the field with `showLabelAbove`. */\n  const labelAbove = $derived(getLabelAboveText({ showLabelAbove, props: restProps }));\n\n  /**\n   * Content for the clone element used to measure the auto-resized height. A trailing line break is\n   * added because browsers don’t render the last empty line, which would otherwise make the clone\n   * one line shorter than the `<textarea>`.\n   * @type {string}\n   */\n  const cloneValue = $derived(`${value}\\n`);\n  /**\n   * Syntax-highlighted tokens of the value, flattened with line breaks in between, plus a trailing\n   * one like {@link cloneValue}. They’re only used when they add up to the value exactly, since\n   * stale tokens would show text different from what’s being edited.\n   * @type {HighlightedToken[] | undefined}\n   */\n  const highlightedTokens = $derived(getHighlightedTokens(value, highlight));\n  /** A reference to the clone element. */\n  let cloneElement = $state();\n\n  $effect(() => {\n    // Keep the highlighted text scrolled along with the `<textarea>`, which can also scroll when\n    // it’s auto-resized, if its height is capped with `max-height`\n    if (!element || !cloneElement) {\n      return undefined;\n    }\n\n    const textarea = element;\n    const clone = cloneElement;\n\n    /**\n     * Sync the scroll position.\n     */\n    const onScroll = () => {\n      clone.scrollTop = textarea.scrollTop;\n      clone.scrollLeft = textarea.scrollLeft;\n    };\n\n    onScroll();\n    textarea.addEventListener('scroll', onScroll);\n\n    return () => {\n      textarea.removeEventListener('scroll', onScroll);\n    };\n  });\n</script>\n\n<div\n  role=\"none\"\n  class=\"sui text-area {className}\"\n  class:flex\n  class:disabled\n  class:readonly\n  class:highlighted={!!highlightedTokens}\n  class:has-label-above={!!labelAbove}\n  {hidden}\n>\n  {#if labelAbove}\n    <LabelAbove label={labelAbove} for={textareaId} />\n  {/if}\n  <textarea\n    bind:this={\n      () => element,\n      (el) => {\n        element = el;\n        boundElement = el;\n      }\n    }\n    {...restProps}\n    id={textareaId}\n    {dir}\n    {name}\n    bind:value\n    disabled={disabled || undefined}\n    readonly={readonly || undefined}\n    aria-hidden={hidden}\n    aria-disabled={disabled}\n    aria-readonly={readonly}\n    aria-required={required}\n    aria-invalid={invalid}\n    class:auto-resize={autoResize}></textarea>\n  {#if highlightedTokens}\n    <!-- Line breaks are only allowed within tags, as any whitespace would end up in the text -->\n    <!-- prettier-ignore -->\n    <div\n      bind:this={cloneElement}\n      class=\"clone\"\n      class:auto-resize={autoResize}\n      aria-hidden=\"true\"\n      {dir}\n    >{#each highlightedTokens as token, index (index)}<span\n          style:color={token.color}\n          class:bold={token.bold}\n          class:underline={token.underline}\n          class:strikethrough={token.strikethrough}\n        >{token.content}</span\n      >{/each}</div>\n  {:else if autoResize}\n    <div class=\"clone auto-resize\" aria-hidden=\"true\" {dir}>{cloneValue}</div>\n  {/if}\n  {#if useEmojiAutocomplete && !disabled && !readonly}\n    <EmojiAutocomplete {element} />\n  {/if}\n</div>\n\n<style>.text-area {\n  position: relative;\n  display: inline-grid;\n  margin: var(--sui-focus-ring-width);\n  min-width: var(--sui-textbox-multiline-min-width);\n}\n.text-area[hidden] {\n  display: none;\n}\n.text-area.flex:not([hidden]) {\n  display: inline-grid;\n  width: -moz-available;\n  width: -webkit-fill-available;\n  width: stretch;\n  min-width: 0;\n}\n.text-area.has-label-above :is(textarea, .clone) {\n  grid-row: 2;\n}\n\n:is(textarea, .clone) {\n  grid-area: 1/1/2/2;\n  display: block;\n  margin: 0;\n  width: 100%;\n  min-height: 8em;\n  border-width: var(--sui-textbox-border-width, 1px);\n  border-color: var(--sui-textbox-border-color);\n  border-radius: var(--sui-textbox-border-radius);\n  padding: var(--sui-textbox-multiline-padding);\n  color: var(--sui-textbox-foreground-color);\n  background-color: var(--sui-textbox-background-color);\n  font-family: var(--sui-textbox-font-family);\n  font-size: var(--sui-textbox-font-size);\n  line-height: var(--sui-textbox-multiline-line-height);\n  font-weight: var(--sui-textbox-font-weight, var(--sui-font-weight-normal, normal));\n  letter-spacing: var(--sui-textbox-letter-spacing, normal);\n  transition: all 200ms;\n  text-align: var(--sui-textbox-text-align, start);\n  text-indent: var(--sui-textbox-text-indent, 0);\n  text-transform: var(--sui-textbox-text-transform, none);\n  word-spacing: var(--sui-word-spacing-normal, normal);\n}\n:is(textarea, .clone):focus {\n  color: var(--sui-textbox-foreground-color-focus, var(--sui-textbox-foreground-color));\n  background-color: var(--sui-textbox-background-color-focus, var(--sui-textbox-background-color));\n}\n:is(textarea, .clone)[aria-invalid=true] {\n  border-color: var(--sui-error-border-color);\n}\n:is(textarea, .clone).resizing {\n  transition-duration: 0ms;\n}\n:is(textarea, .clone):is(:disabled, :read-only):not(.clone) {\n  background-color: var(--sui-disabled-background-color);\n}\n\ntextarea {\n  resize: vertical;\n}\ntextarea.auto-resize {\n  overflow: hidden;\n  resize: none;\n}\n\n.clone {\n  overflow: hidden;\n  visibility: hidden;\n  scroll-behavior: auto;\n}\n.clone:not(.auto-resize) {\n  position: absolute;\n  inset: 0;\n  min-height: 0;\n}\n\n.highlighted textarea {\n  z-index: 1;\n  caret-color: var(--sui-textbox-foreground-color);\n  color: transparent !important;\n  background-color: transparent !important;\n}\n.highlighted textarea:not(.auto-resize) {\n  scrollbar-gutter: stable;\n}\n.highlighted textarea::placeholder {\n  color: var(--sui-textbox-placeholder-foreground-color, var(--sui-textbox-foreground-color));\n  opacity: var(--sui-textbox-placeholder-opacity, 1);\n}\n.highlighted .clone {\n  visibility: visible;\n  pointer-events: none;\n}\n.highlighted .clone .bold {\n  -webkit-text-stroke: 0.03em currentColor;\n}\n.highlighted .clone .underline {\n  text-decoration-line: underline;\n}\n.highlighted .clone .strikethrough {\n  text-decoration-line: line-through;\n}\n.highlighted .clone .underline.strikethrough {\n  text-decoration-line: underline line-through;\n}\n.highlighted .clone:not(.auto-resize) {\n  scrollbar-gutter: stable;\n}\n.highlighted:focus-within .clone {\n  color: var(--sui-textbox-foreground-color-focus, var(--sui-textbox-foreground-color));\n  background-color: var(--sui-textbox-background-color-focus, var(--sui-textbox-background-color));\n}\n.highlighted:is(.disabled, .readonly) .clone {\n  background-color: var(--sui-disabled-background-color);\n}\n\ntextarea,\n.clone {\n  white-space: pre-wrap;\n  word-break: normal;\n  overflow-wrap: anywhere;\n}</style>\n","<!--\n  @component\n  Emoji autocomplete for the rich text editor. Typing a colon followed by one or more characters,\n  like `:smi`, brings up a list of matching emojis that can be inserted with a click or the Enter\n  key, the same way it works on GitHub, Slack and other apps. This wires the Lexical editor up to\n  `<EmojiSuggestions>`, which owns the dropdown itself.\n-->\n<script>\n  import { $isCodeNode as isCodeNode } from '@lexical/code-core';\n  import {\n    COMMAND_PRIORITY_CRITICAL,\n    $getNodeByKey as getNodeByKey,\n    $getSelection as getSelection,\n    $isRangeSelection as isRangeSelection,\n    $isTextNode as isTextNode,\n    KEY_ARROW_DOWN_COMMAND,\n    KEY_ARROW_UP_COMMAND,\n    KEY_ENTER_COMMAND,\n    KEY_ESCAPE_COMMAND,\n    KEY_TAB_COMMAND,\n  } from 'lexical';\n  import { getContext } from 'svelte';\n  import { detectEmojiTrigger, getEmojiInsertText } from '../../emoji/emoji.js';\n  import EmojiSuggestions from '../../emoji/emoji-suggestions.svelte';\n  import { mergeUnregisters } from '../utils.js';\n\n  /**\n   * @import { EmojiAnchorRect, EmojiEntry, EmojiTrigger, TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * A shortcode within the Lexical editor, identified by the text node it sits in and where its\n   * colon is, which doesn’t change as the query grows.\n   * @typedef {EmojiTrigger & { nodeKey: string, offset: number }} LexicalEmojiTrigger\n   */\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  /**\n   * A reference to the dropdown.\n   * @type {ReturnType<typeof EmojiSuggestions> | undefined}\n   */\n  let list = $state();\n\n  /**\n   * Look for a shortcode being typed right before the caret. This must be called within an editor\n   * state read.\n   * @returns {LexicalEmojiTrigger | undefined} Shortcode state, if any.\n   */\n  const findTrigger = () => {\n    const selection = getSelection();\n\n    // Never suggest emojis within code, where a colon is much more likely to be code than a\n    // shortcode\n    if (!isRangeSelection(selection) || !selection.isCollapsed() || selection.hasFormat('code')) {\n      return undefined;\n    }\n\n    const node = selection.anchor.getNode();\n\n    if (!isTextNode(node) || !node.isSimpleText() || isCodeNode(node.getParent())) {\n      return undefined;\n    }\n\n    const { offset } = selection.anchor;\n    const query = detectEmojiTrigger(node.getTextContent().slice(0, offset));\n\n    if (query === undefined) {\n      return undefined;\n    }\n\n    const nodeKey = node.getKey();\n\n    return { id: `${nodeKey}:${offset - query.length - 1}`, query, nodeKey, offset };\n  };\n\n  /**\n   * Get the viewport-relative bounds of the shortcode being typed. The DOM selection is used rather\n   * than the Lexical node, because the caret is exactly where the shortcode ends, and the browser\n   * has already laid it out by the time an update listener runs.\n   * @param {EmojiTrigger} trigger Shortcode state.\n   * @returns {EmojiAnchorRect | undefined} Bounds, or `undefined` if they can’t be determined.\n   */\n  const getAnchorRect = ({ query }) => {\n    const domSelection = window.getSelection();\n\n    // A shortcode has just been detected at the caret, so there is a selection\n    /* v8 ignore next */\n    if (!domSelection?.rangeCount) {\n      return undefined;\n    }\n\n    const range = domSelection.getRangeAt(0).cloneRange();\n\n    try {\n      range.setStart(range.startContainer, Math.max(0, range.startOffset - query.length - 1));\n    } catch {\n      // The container turned out to be shorter than expected; fall back to the collapsed caret\n    }\n\n    const { top, bottom, left, right, width, height } = range.getBoundingClientRect();\n\n    // A range with no client rects yields an all-zero rectangle\n    return top || bottom || left || width || height ? { top, bottom, left, right } : undefined;\n  };\n\n  /**\n   * Replace the shortcode being typed with the given emoji.\n   * @param {EmojiEntry} entry Emoji to insert.\n   * @param {EmojiTrigger} trigger Shortcode to replace.\n   */\n  const insertEmoji = (entry, trigger) => {\n    const { editor } = editorStore;\n    const { query, nodeKey, offset } = /** @type {LexicalEmojiTrigger} */ (trigger);\n    const start = offset - query.length - 1;\n\n    editor?.update(() => {\n      const node = getNodeByKey(nodeKey);\n\n      // Make sure the shortcode is still where it was when the suggestions appeared. The list is\n      // closed as soon as the shortcode changes, so this only guards against a race.\n      /* v8 ignore next */\n      if (!isTextNode(node) || node.getTextContent().slice(start, offset) !== `:${query}`) {\n        return;\n      }\n\n      const text = getEmojiInsertText(entry.emoji, node.getTextContent().slice(offset));\n\n      node.spliceText(start, query.length + 1, text, true);\n    });\n  };\n\n  /**\n   * Register the keyboard shortcuts that drive the list, as well as the listener that watches for\n   * shortcodes. The shortcuts are registered with the highest priority, so they take precedence\n   * over the editor’s own handling while the list is open, and return `false` otherwise to leave\n   * the editor alone.\n   * @returns {() => void} Cleanup handler.\n   */\n  const registerCommands = () => {\n    const { editor } = editorStore;\n\n    // Only called from the effect below, once the editor is there\n    /* v8 ignore next */\n    if (!editor) {\n      return mergeUnregisters();\n    }\n\n    /**\n     * Create a command listener that only acts while the list is open.\n     * @param {() => void} handler Handler to be called.\n     * @returns {(event: KeyboardEvent | null) => boolean} Command listener.\n     */\n    const whileOpen = (handler) => (event) => {\n      if (!list?.isOpen()) {\n        return false;\n      }\n\n      event?.preventDefault();\n      handler();\n\n      return true;\n    };\n\n    return mergeUnregisters(\n      editor.registerCommand(\n        KEY_ARROW_DOWN_COMMAND,\n        whileOpen(() => list?.moveSelection(1)),\n        COMMAND_PRIORITY_CRITICAL,\n      ),\n      editor.registerCommand(\n        KEY_ARROW_UP_COMMAND,\n        whileOpen(() => list?.moveSelection(-1)),\n        COMMAND_PRIORITY_CRITICAL,\n      ),\n      editor.registerCommand(\n        KEY_ENTER_COMMAND,\n        whileOpen(() => list?.selectHighlighted()),\n        COMMAND_PRIORITY_CRITICAL,\n      ),\n      editor.registerCommand(\n        KEY_TAB_COMMAND,\n        whileOpen(() => list?.selectHighlighted()),\n        COMMAND_PRIORITY_CRITICAL,\n      ),\n      editor.registerCommand(\n        KEY_ESCAPE_COMMAND,\n        whileOpen(() => list?.close(true)),\n        COMMAND_PRIORITY_CRITICAL,\n      ),\n      editor.registerUpdateListener(({ editorState }) => {\n        /** @type {LexicalEmojiTrigger | undefined} */\n        let trigger;\n\n        editorState.read(() => {\n          trigger = findTrigger();\n        });\n\n        list?.update(trigger);\n      }),\n    );\n  };\n\n  $effect(() => {\n    // The root initializes the editor, and the list is bound, before this first runs\n    /* v8 ignore next */\n    if (!editorStore.editor || !list) {\n      return undefined;\n    }\n\n    const unregister = registerCommands();\n\n    return () => {\n      unregister();\n      list?.close();\n    };\n  });\n\n  // The rich text editor can be swapped for the plain text one at any time, in which case there is\n  // no caret to anchor the dropdown to anymore\n  $effect(() => {\n    if (!editorStore.useRichText) {\n      list?.close();\n    }\n  });\n</script>\n\n<EmojiSuggestions\n  bind:this={list}\n  {getAnchorRect}\n  onSelect={insertEmoji}\n  ariaOwner={editorStore.editor?.getRootElement() ?? undefined}\n/>\n","/**\n * Markdown editing helpers for the plain text mode of the text editor, where the toolbar buttons\n * edit the Markdown source in the `<textarea>` instead of Lexical nodes. Apart from\n * {@link getRawTextState}, {@link applyRawTextEdit}, {@link editRawText},\n * {@link registerRawTextShortcut}, {@link insertComponent} and the other functions that register\n * listeners, everything here is pure: a function takes the current value and selection, and returns\n * the edit to apply.\n */\n\nimport { isMac, matchesShortcuts } from '@sveltia/utils/events';\nimport { getComponentMarkdown } from '../conversion/editor-components.js';\nimport { TASK_LIST_ITEM_REGEX } from '../conversion/transformers/task-list.js';\n\n/**\n * @import {\n * TextEditorBlockType,\n * TextEditorComponent,\n * TextEditorFormatType,\n * } from '../../../typedefs.js';\n */\n\n/**\n * Current value and selection of the `<textarea>`.\n * @typedef {object} RawTextState\n * @property {string} value Value.\n * @property {number} start Selection start.\n * @property {number} end Selection end.\n */\n\n/**\n * Edit to apply to the `<textarea>`: replace the text between `start` and `end` with `text`, then\n * select the text between `selectionStart` and `selectionEnd`, which are offsets in the new value.\n * @typedef {object} RawTextEdit\n * @property {number} start Start of the range to replace.\n * @property {number} end End of the range to replace.\n * @property {string} text Replacement text.\n * @property {number} selectionStart New selection start.\n * @property {number} selectionEnd New selection end.\n */\n\n/**\n * Markdown markers for the inline formats. Markdown has no syntax for underline.\n * @type {Record<Exclude<TextEditorFormatType, 'underline'>, string>}\n */\nconst INLINE_MARKERS = {\n  bold: '**',\n  italic: '_',\n  strikethrough: '~~',\n  code: '`',\n};\n\n/**\n * Prefix of a heading, list item or blockquote line, including the check box of a task list item,\n * which can only be one or two spaces after the marker; see `TASK_LIST_ITEM_REGEX`.\n */\nconst BLOCK_PREFIX_REGEX =\n  /^(?:#{1,6}[ \\t]+|>[ \\t]?|[-*+](?:[ \\t]{1,2}\\[[ xX]\\][ \\t]+|[ \\t]+)|\\d+[.)][ \\t]+)/;\n\nconst CODE_FENCE_REGEX = /^[ \\t]*(?:```|~~~)/;\n\n/**\n * Get the range of the full lines covered by the selection.\n * @param {RawTextState} state Current state.\n * @returns {{ lineStart: number, lineEnd: number }} Start of the first line and end of the last\n * line, excluding the line break.\n */\nconst getLineRange = ({ value, start, end }) => {\n  const lineStart = value.lastIndexOf('\\n', start - 1) + 1;\n  // Ignore a selection that ends at the very start of a line, like a triple-clicked line\n  const lastIndex = end > start && value[end - 1] === '\\n' ? end - 1 : end;\n  const lineEndIndex = value.indexOf('\\n', lastIndex);\n\n  return { lineStart, lineEnd: lineEndIndex === -1 ? value.length : lineEndIndex };\n};\n\n/**\n * Get the index of the line where the selection starts.\n * @param {RawTextState} state Current state.\n * @returns {number} Line index.\n */\nconst getStartLineIndex = ({ value, start }) => value.slice(0, start).split('\\n').length - 1;\n\n/**\n * Find the fenced code block the given line is in.\n * @param {string[]} lines All the lines.\n * @param {number} lineIndex Index of the line.\n * @returns {{ open: number, close: number } | undefined} Indexes of the opening and closing fence\n * lines, or `undefined` if the line is not in a code block. An unclosed block ends at the last\n * line.\n */\nconst findCodeBlock = (lines, lineIndex) => {\n  /** @type {number | undefined} */\n  let open;\n\n  for (let index = 0; index < lines.length; index += 1) {\n    if (CODE_FENCE_REGEX.test(lines[index])) {\n      if (open === undefined) {\n        open = index;\n      } else {\n        if (lineIndex >= open && lineIndex <= index) {\n          return { open, close: index };\n        }\n\n        open = undefined;\n      }\n    }\n\n    if (open === undefined && index >= lineIndex) {\n      return undefined;\n    }\n  }\n\n  return open !== undefined && lineIndex >= open ? { open, close: lines.length } : undefined;\n};\n\n/**\n * Get the type of the block where the selection starts.\n * @param {RawTextState} state Current state.\n * @param {object} [options] Options.\n * @param {boolean} [options.hasTaskList] Whether the task list button is enabled, which it isn’t\n * by default. Without it, a task list item is a bulleted list item, as the rich text editor imports\n * it.\n * @returns {TextEditorBlockType} Block type.\n */\nexport const getBlockType = (state, { hasTaskList = false } = {}) => {\n  const lines = state.value.split('\\n');\n  const lineIndex = getStartLineIndex(state);\n  const line = lines[lineIndex];\n\n  if (findCodeBlock(lines, lineIndex)) {\n    return 'code-block';\n  }\n\n  const [, hashes] = line.match(/^(#{1,6})[ \\t]/) ?? [];\n\n  if (hashes) {\n    return /** @type {TextEditorBlockType} */ (`heading-${hashes.length}`);\n  }\n\n  if (hasTaskList && TASK_LIST_ITEM_REGEX.test(line)) {\n    return 'task-list';\n  }\n\n  if (/^[-*+][ \\t]/.test(line)) {\n    return 'bulleted-list';\n  }\n\n  if (/^\\d+[.)][ \\t]/.test(line)) {\n    return 'numbered-list';\n  }\n\n  if (line.startsWith('>')) {\n    return 'blockquote';\n  }\n\n  return 'paragraph';\n};\n\n/**\n * Wrap the selection with the Markdown markers of the given inline format, or unwrap it if it’s\n * already formatted. Without a selection, the markers are inserted with the caret in between.\n * @param {RawTextState} state Current state.\n * @param {Exclude<TextEditorFormatType, 'underline'>} type Format type.\n * @returns {RawTextEdit} Edit.\n */\nexport const toggleInlineFormat = ({ value, start, end }, type) => {\n  const marker = INLINE_MARKERS[type];\n  const { length } = marker;\n  const selected = value.slice(start, end);\n\n  // The markers are selected along with the text\n  if (selected.length >= length * 2 && selected.startsWith(marker) && selected.endsWith(marker)) {\n    const text = selected.slice(length, -length);\n\n    return { start, end, text, selectionStart: start, selectionEnd: start + text.length };\n  }\n\n  // The markers surround the selection\n  if (value.slice(start - length, start) === marker && value.slice(end, end + length) === marker) {\n    return {\n      start: start - length,\n      end: end + length,\n      text: selected,\n      selectionStart: start - length,\n      selectionEnd: end - length,\n    };\n  }\n\n  // Keep the surrounding whitespace out of the markers, because `** bold **` is not bold\n  const [, leading, content, trailing] = /** @type {RegExpMatchArray} */ (\n    selected.match(/^(\\s*)([\\s\\S]*?)(\\s*)$/)\n  );\n\n  // Inline formatting cannot span multiple paragraphs, so format each line separately\n  const text = `${leading}${content\n    .split('\\n')\n    .map((line) => (line.trim() ? `${marker}${line}${marker}` : line))\n    .join('\\n')}${trailing}`;\n\n  if (!content) {\n    const caret = start + leading.length + length;\n\n    return {\n      start,\n      end,\n      text: `${leading}${marker}${marker}${trailing}`,\n      selectionStart: caret,\n      selectionEnd: caret,\n    };\n  }\n\n  return {\n    start,\n    end,\n    text,\n    selectionStart: start + leading.length + length,\n    selectionEnd: start + text.length - trailing.length - length,\n  };\n};\n\n/**\n * Change the type of the blocks covered by the selection.\n * @param {RawTextState} state Current state.\n * @param {TextEditorBlockType} type New block type.\n * @returns {RawTextEdit} Edit.\n */\nexport const setBlockType = (state, type) => {\n  const { value, start, end } = state;\n  const lines = value.split('\\n');\n  const firstIndex = getStartLineIndex(state);\n  const codeBlock = findCodeBlock(lines, firstIndex);\n\n  // Leave a code block by removing its fences, then change the type of the selected lines\n  if (codeBlock) {\n    const { open, close } = codeBlock;\n    const blockStart = lines.slice(0, open).join('\\n').length + (open ? 1 : 0);\n    const blockEnd = blockStart + lines.slice(open, close + 1).join('\\n').length;\n    const content = lines.slice(open + 1, close).join('\\n');\n    const contentStart = blockStart + lines[open].length + 1;\n    /**\n     * Map a position in the whole value to one in the content.\n     * @param {number} position Position.\n     * @returns {number} Position in the content.\n     */\n    const map = (position) => Math.min(Math.max(position - contentStart, 0), content.length);\n    const edit = setBlockType({ value: content, start: map(start), end: map(end) }, type);\n\n    return {\n      start: blockStart,\n      end: blockEnd,\n      text: `${content.slice(0, edit.start)}${edit.text}${content.slice(edit.end)}`,\n      selectionStart: blockStart + edit.selectionStart,\n      selectionEnd: blockStart + edit.selectionEnd,\n    };\n  }\n\n  const { lineStart, lineEnd } = getLineRange(state);\n  const oldLines = value.slice(lineStart, lineEnd).split('\\n');\n\n  if (type === 'code-block') {\n    const text = `\\`\\`\\`\\n${oldLines.join('\\n')}\\n\\`\\`\\``;\n\n    return {\n      start: lineStart,\n      end: lineEnd,\n      text,\n      selectionStart: start + 4,\n      selectionEnd: end + 4,\n    };\n  }\n\n  const [, level] = type.match(/^heading-(\\d)$/) ?? [];\n  let number = 0;\n\n  /**\n   * Get the prefix for the given line.\n   * @param {string} line Line content without the prefix.\n   * @returns {string} Prefix.\n   */\n  const getPrefix = (line) => {\n    if (level) {\n      return line.trim() ? `${'#'.repeat(Number(level))} ` : '';\n    }\n\n    if (type === 'bulleted-list') {\n      return line.trim() ? '- ' : '';\n    }\n\n    if (type === 'task-list') {\n      return line.trim() ? '- [ ] ' : '';\n    }\n\n    if (type === 'numbered-list') {\n      if (!line.trim()) {\n        return '';\n      }\n\n      number += 1;\n\n      return `${number}. `;\n    }\n\n    if (type === 'blockquote') {\n      return line.trim() ? '> ' : '>';\n    }\n\n    return '';\n  };\n\n  let offset = 0;\n  let selectionStart = start;\n  let selectionEnd = end;\n\n  const newLines = oldLines.map((line, index) => {\n    const [oldPrefix = ''] = line.match(BLOCK_PREFIX_REGEX) ?? [];\n    const content = line.slice(oldPrefix.length);\n    const newPrefix = getPrefix(content);\n    const oldLineStart = lineStart + oldLines.slice(0, index).join('\\n').length + (index ? 1 : 0);\n    const oldContentStart = oldLineStart + oldPrefix.length;\n    const oldLineEnd = oldLineStart + line.length;\n    const newContentStart = oldContentStart + offset + newPrefix.length - oldPrefix.length;\n    /**\n     * Map a position on the old line to the new line, keeping it after the prefix.\n     * @param {number} position Position.\n     * @returns {number} New position.\n     */\n    const map = (position) => newContentStart + Math.max(position - oldContentStart, 0);\n\n    if (start >= oldLineStart && start <= oldLineEnd) {\n      selectionStart = map(start);\n    }\n\n    if (end >= oldLineStart && end <= oldLineEnd) {\n      selectionEnd = map(end);\n    }\n\n    offset += newPrefix.length - oldPrefix.length;\n\n    return `${newPrefix}${content}`;\n  });\n\n  // The selection may end on the next line, which is left as is, but still shifted\n  if (end > lineEnd) {\n    selectionEnd = end + offset;\n  }\n\n  return {\n    start: lineStart,\n    end: lineEnd,\n    text: newLines.join('\\n'),\n    selectionStart,\n    selectionEnd: Math.max(selectionStart, selectionEnd),\n  };\n};\n\n/**\n * Replace the selection with a Markdown link.\n * @param {RawTextState} state Current state.\n * @param {object} link Link.\n * @param {string} link.url URL.\n * @param {string} [link.text] Link text. Defaults to the selected text, then the URL.\n * @returns {RawTextEdit} Edit.\n */\nexport const insertLink = ({ value, start, end }, { url, text }) => {\n  // Keep the whitespace around the selected text out of the link, as a double-clicked word may come\n  // with a trailing space\n  const [, leading, selected, trailing] = /** @type {RegExpMatchArray} */ (\n    value.slice(start, end).match(/^(\\s*)([\\s\\S]*?)(\\s*)$/)\n  );\n\n  const label = (text ?? selected).trim() || url;\n  const escapedLabel = label.replace(/([[\\]\\\\])/g, '\\\\$1');\n  // A URL with whitespace or parentheses has to be enclosed in angle brackets\n  const destination = /[\\s()<>]/.test(url) ? `<${url.replace(/[<>]/g, encodeURIComponent)}>` : url;\n  const markdown = `[${escapedLabel}](${destination})`;\n  const caret = start + leading.length + markdown.length;\n\n  return {\n    start,\n    end,\n    text: `${leading}${markdown}${trailing}`,\n    selectionStart: caret,\n    selectionEnd: caret,\n  };\n};\n\n/**\n * Insert the given Markdown at the selection. A block is separated from the surrounding text with\n * blank lines, while inline content is inserted as is.\n * @param {RawTextState} state Current state.\n * @param {string} markdown Markdown to insert.\n * @param {object} [options] Options.\n * @param {boolean} [options.block] Whether the Markdown is a block.\n * @returns {RawTextEdit} Edit.\n */\nexport const insertMarkdown = ({ value, start, end }, markdown, { block = false } = {}) => {\n  if (!block) {\n    const caret = start + markdown.length;\n\n    return { start, end, text: markdown, selectionStart: caret, selectionEnd: caret };\n  }\n\n  const before = value.slice(0, start).replace(/[ \\t]*$/, '');\n  const after = value.slice(end).replace(/^[ \\t]*/, '');\n  const trimmedStart = before.length;\n  const trimmedEnd = value.length - after.length;\n\n  const leading = !before\n    ? ''\n    : before.endsWith('\\n\\n')\n      ? ''\n      : before.endsWith('\\n')\n        ? '\\n'\n        : '\\n\\n';\n\n  const trailing = after.startsWith('\\n\\n') ? '' : after.startsWith('\\n') ? '\\n' : '\\n\\n';\n  const text = `${leading}${markdown}${trailing}`;\n  // Place the caret after the block\n  const caret = trimmedStart + text.length;\n\n  return { start: trimmedStart, end: trimmedEnd, text, selectionStart: caret, selectionEnd: caret };\n};\n\n/**\n * Get the current value and selection of the given `<textarea>`.\n * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n * @returns {RawTextState} State.\n */\nexport const getRawTextState = ({ value, selectionStart, selectionEnd }) => ({\n  value,\n  start: selectionStart,\n  end: selectionEnd,\n});\n\n/**\n * Move the focus to the given `<textarea>`. A toolbar menu is a modal, which leaves the rest of the\n * page inert until it’s closed, so the focus may not move right away when an item is selected;\n * retry until it does, or give up after a second.\n * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n * @returns {Promise<boolean>} Whether the `<textarea>` has the focus.\n */\nexport const focusTextArea = async (textArea) => {\n  const deadline = Date.now() + 1000;\n\n  for (;;) {\n    textArea.focus();\n\n    if (document.activeElement === textArea || Date.now() > deadline) {\n      return document.activeElement === textArea;\n    }\n\n    // eslint-disable-next-line no-await-in-loop\n    await new Promise((resolve) => {\n      window.setTimeout(resolve, 20);\n    });\n  }\n};\n\n/**\n * Whether the given `<textarea>` can be edited by the user, and therefore by the toolbar.\n * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n * @returns {boolean} Result.\n */\nexport const isRawTextEditable = ({ readOnly, disabled }) => !readOnly && !disabled;\n\n/**\n * Apply the given edit to the `<textarea>`, and focus it. Nothing happens if it’s read-only or\n * disabled, because the fallback below would edit it anyway.\n * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n * @param {RawTextEdit} edit Edit.\n * @returns {Promise<void>} Nothing.\n */\nexport const applyRawTextEdit = async (\n  textArea,\n  { start, end, text, selectionStart, selectionEnd },\n) => {\n  if (!isRawTextEditable(textArea)) {\n    return;\n  }\n\n  // The edit only goes into the undo history while the `<textarea>` has the focus\n  const focused = await focusTextArea(textArea);\n\n  if (textArea.value.slice(start, end) !== text) {\n    textArea.setSelectionRange(start, end);\n\n    // `execCommand()` is deprecated, but it’s still the only way to keep the edit in the native\n    // undo history. It fires an `input` event, so a bound value is updated as well\n    const done =\n      focused &&\n      typeof document.execCommand === 'function' &&\n      (text\n        ? document.execCommand('insertText', false, text)\n        : document.execCommand('delete', false));\n\n    if (!done || textArea.value.slice(start, start + text.length) !== text) {\n      textArea.setRangeText(text, start, end);\n      textArea.dispatchEvent(new Event('input', { bubbles: true }));\n    }\n  }\n\n  textArea.setSelectionRange(selectionStart, selectionEnd);\n};\n\n/**\n * Apply the edit made by the given function from the current state of the `<textarea>`, and focus\n * it. Nothing happens if there’s no `<textarea>`.\n * @param {HTMLTextAreaElement | undefined} textArea `<textarea>` element.\n * @param {(state: RawTextState) => RawTextEdit} getEdit Function to make the edit from the current\n * state.\n * @returns {Promise<void>} Nothing.\n */\nexport const editRawText = async (textArea, getEdit) => {\n  if (!textArea) {\n    return;\n  }\n\n  await applyRawTextEdit(textArea, getEdit(getRawTextState(textArea)));\n};\n\n/**\n * Handle the given keyboard shortcut, Accel+{key}, on the `<textarea>` while it’s editable. The\n * rich text editor handles its shortcuts on its own.\n * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n * @param {string} key Key to combine with the Accel key, like `B`.\n * @param {() => void} handler Function to call when the shortcut is pressed.\n * @returns {() => void} Function to stop handling the shortcut.\n */\nexport const registerRawTextShortcut = (textArea, key, handler) => {\n  /**\n   * Handle the `keydown` event.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  const onKeyDown = (event) => {\n    if (\n      isRawTextEditable(textArea) &&\n      matchesShortcuts(event, isMac() ? `Meta+${key}` : `Ctrl+${key}`)\n    ) {\n      event.preventDefault();\n      handler();\n    }\n  };\n\n  textArea.addEventListener('keydown', onKeyDown);\n\n  return () => {\n    textArea.removeEventListener('keydown', onKeyDown);\n  };\n};\n\n/**\n * Insert the Markdown of a new instance of the given editor component into the `<textarea>`. A\n * component matched by a single-line pattern is inserted inline at the caret; anything else is\n * inserted as a separate block. If the component has no Markdown to insert, the focus just moves\n * back to the `<textarea>`.\n * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n * @param {TextEditorComponent} component Editor component.\n * @returns {Promise<void>} Nothing.\n */\nexport const insertComponent = async (textArea, component) => {\n  const markdown = getComponentMarkdown(component);\n\n  if (!markdown) {\n    textArea.focus();\n\n    return;\n  }\n\n  const block = component.transformer?.type !== 'text-match';\n\n  await applyRawTextEdit(textArea, insertMarkdown(getRawTextState(textArea), markdown, { block }));\n};\n\n/**\n * Line breaks, along with the spaces and tabs around them, to replace with a single space.\n */\nconst LINE_BREAK_REGEX = /[ \\t]*(?:\\r?\\n[ \\t]*)+/g;\n\n/**\n * Join the lines of the given value with spaces, for a single-line editor, keeping the caret where\n * it was in the text.\n * @param {object} state Value and caret position.\n * @param {string} state.value Value.\n * @param {number} state.caret Caret position.\n * @returns {{ value: string, caret: number }} Joined value and the new caret position.\n */\nexport const joinLines = ({ value, caret }) => {\n  const before = value.slice(0, caret).replace(LINE_BREAK_REGEX, ' ');\n\n  return {\n    value: before + value.slice(caret).replace(LINE_BREAK_REGEX, ' '),\n    caret: before.length,\n  };\n};\n\n/**\n * Keep the `<textarea>` on a single line: the Enter key doesn’t insert a line break, and the lines\n * of pasted or dropped text are joined with spaces before the value is read.\n * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n * @returns {() => void} Function to stop handling the events.\n */\nexport const registerRawTextSingleLine = (textArea) => {\n  /**\n   * Handle the `beforeinput` event. The emoji autocomplete, which selects an emoji with the Enter\n   * key, cancels the `keydown` event first, so there’s no `beforeinput` event then. Pasted text is\n   * inserted with its lines joined instead, which keeps the edit in the native undo history.\n   * @param {InputEvent} event `beforeinput` event.\n   */\n  const onBeforeInput = (event) => {\n    const { inputType } = event;\n\n    if (inputType === 'insertLineBreak' || inputType === 'insertParagraph') {\n      event.preventDefault();\n\n      return;\n    }\n\n    const text = event.data || event.dataTransfer?.getData('text/plain') || '';\n\n    if (\n      (inputType === 'insertFromPaste' || inputType === 'insertReplacementText') &&\n      text.includes('\\n') &&\n      // `execCommand()` is deprecated, but it’s still the only way to keep the edit in the native\n      // undo history. If it’s unavailable, the `input` listener below joins the lines instead\n      typeof document.execCommand === 'function'\n    ) {\n      event.preventDefault();\n      document.execCommand('insertText', false, text.replace(LINE_BREAK_REGEX, ' '));\n    }\n  };\n\n  /**\n   * Handle the `input` event, in the capture phase, so the value is joined before the bound value\n   * is updated. It catches the line breaks the `beforeinput` listener can’t, like those of dropped\n   * text, but the edit then leaves the native undo history.\n   */\n  const onInput = () => {\n    const { value, selectionStart } = textArea;\n\n    if (!value.includes('\\n')) {\n      return;\n    }\n\n    const joined = joinLines({ value, caret: selectionStart });\n\n    textArea.value = joined.value;\n    textArea.setSelectionRange(joined.caret, joined.caret);\n  };\n\n  textArea.addEventListener('beforeinput', onBeforeInput);\n  textArea.addEventListener('input', onInput, { capture: true });\n\n  return () => {\n    textArea.removeEventListener('beforeinput', onBeforeInput);\n    textArea.removeEventListener('input', onInput, { capture: true });\n  };\n};\n\n/**\n * Events after which the selection of the `<textarea>` may have changed.\n */\nconst SELECTION_EVENT_TYPES = ['selectionchange', 'select', 'input', 'keyup', 'mouseup', 'focus'];\n\n/**\n * Keep track of the type of the block where the selection of the `<textarea>` starts, so the\n * toolbar can reflect it like in the rich text mode. Until the `<textarea>` gets the focus, its\n * caret is at the end of the value rather than where the user would expect, so the block type is\n * not detected yet, and is reported as a paragraph.\n * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n * @param {(blockType: TextEditorBlockType) => void} onChange Function to call with the block type,\n * right away and whenever the selection may have changed.\n * @param {object} [options] Options.\n * @param {() => boolean} [options.hasTaskList] Function that tells whether the task list button is\n * enabled; see {@link getBlockType}. It’s called on every change, so it can follow the editor\n * configuration.\n * @returns {() => void} Function to stop tracking the selection.\n */\nexport const registerRawTextSelection = (\n  textArea,\n  onChange,\n  { hasTaskList = () => false } = {},\n) => {\n  /**\n   * Report the block type.\n   */\n  const update = () => {\n    onChange(\n      document.activeElement === textArea\n        ? getBlockType(getRawTextState(textArea), { hasTaskList: hasTaskList() })\n        : 'paragraph',\n    );\n  };\n\n  update();\n  SELECTION_EVENT_TYPES.forEach((type) => textArea.addEventListener(type, update));\n\n  return () => {\n    SELECTION_EVENT_TYPES.forEach((type) => textArea.removeEventListener(type, update));\n  };\n};\n","/**\n * Toolbar actions that work in both the rich text and plain text modes.\n */\n\nimport { $createParagraphNode as createParagraphNode, $insertNodes as insertNodes } from 'lexical';\nimport { focusEditor } from '../editing/caret.js';\nimport { insertComponent } from '../editing/raw-markdown.js';\n\n/**\n * @import { LexicalEditor } from 'lexical';\n * @import { TextEditorComponent, TextEditorStore } from '../../../typedefs.js';\n */\n\n/**\n * @typedef {object} EditorAction\n * @property {(textArea: HTMLTextAreaElement) => void | Promise<void>} [raw] Edit the `<textarea>`\n * in the plain text mode, which also moves the focus there. Without it, nothing happens in the\n * plain text mode.\n * @property {(editor: LexicalEditor) => void | Promise<void>} rich Edit the Lexical editor in the\n * rich text mode.\n * @property {'after' | 'before' | false} [focus] When to move the focus back to the Lexical\n * editor: `after` the edit (default), `before` it, for an edit that applies to the selection the\n * focus restores, or not at all, for an edit that moves the focus on its own.\n */\n\n/**\n * Run a toolbar action in the mode the editor is in.\n * @param {TextEditorStore} editorStore Editor store.\n * @param {EditorAction} action Action.\n * @returns {Promise<void>} Nothing.\n */\nexport const runEditorAction = async (editorStore, { raw, rich, focus = 'after' }) => {\n  const { editor, textArea, useRichText } = editorStore;\n\n  if (!useRichText) {\n    // The toolbar is only enabled while the `<textarea>` is there\n    /* v8 ignore else */\n    if (raw && textArea) {\n      await raw(textArea);\n    }\n\n    return;\n  }\n\n  // The toolbar is only enabled while the editor is there\n  /* v8 ignore next 3 */\n  if (!editor) {\n    return;\n  }\n\n  if (focus === 'before') {\n    await focusEditor(editor);\n  }\n\n  await rich(editor);\n\n  if (focus === 'after') {\n    await focusEditor(editor);\n  }\n};\n\n/**\n * Move the focus back to the editor shown, the Lexical editor or the `<textarea>`, like after a\n * dialog that leaves the focus alone has been closed without changing anything.\n * @param {TextEditorStore} editorStore Editor store.\n * @returns {Promise<void>} Nothing.\n */\nexport const refocusEditor = async (editorStore) => {\n  const { editor, textArea, useRichText } = editorStore;\n\n  if (!useRichText) {\n    textArea?.focus();\n  } else if (editor) {\n    await focusEditor(editor);\n  }\n};\n\n/**\n * Insert a new instance of the given editor component into the editor: its Markdown in the plain\n * text mode, or its node in the rich text mode. The focus is left to the component.\n * @param {TextEditorStore} editorStore Editor store.\n * @param {TextEditorComponent} component Editor component.\n * @returns {Promise<void>} Nothing.\n */\nexport const insertEditorComponent = (editorStore, component) =>\n  runEditorAction(editorStore, {\n    /**\n     * Insert the component’s Markdown.\n     * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n     * @returns {void | Promise<void>} Nothing.\n     */\n    raw: (textArea) => insertComponent(textArea, component),\n    /**\n     * Insert the component’s node.\n     * @param {LexicalEditor} editor Editor instance.\n     */\n    rich: (editor) => {\n      editor.update(() => {\n        const node = component.createNode();\n\n        // Add an additional paragraph after a block for easier editing. An inline node stays\n        // within the text, which may be in a table cell where a paragraph can’t be added\n        insertNodes(node.isInline() ? [node] : [node, createParagraphNode()]);\n      });\n    },\n    focus: false,\n  });\n","<!--\n  @component\n  Floating link editor for the rich text editor. While the caret is on a link, a small popup below\n  it shows the URL along with buttons to edit and remove the link, and the URL can be edited right\n  there, the same way it works in the Lexical Playground and Google Docs. The Link button and the\n  Accel+K shortcut open the popup in the edit mode, also to link the selected text.\n\n  The popup is rendered in the top layer with the Popover API, so it’s never clipped by whatever\n  contains the editor.\n  @see https://github.com/sveltia/sveltia-cms/issues/164\n  @see https://developer.mozilla.org/en-US/docs/Web/API/Popover_API\n-->\n<script>\n  import { $isLinkNode as isLinkNode, TOGGLE_LINK_COMMAND } from '@lexical/link';\n  import { _, isRTL } from '@sveltia/i18n';\n  import { matchesShortcuts } from '@sveltia/utils/events';\n  import { isURL } from '@sveltia/utils/string';\n  import {\n    COMMAND_PRIORITY_HIGH,\n    COMMAND_PRIORITY_NORMAL,\n    KEY_ESCAPE_COMMAND,\n    $getNodeByKey as getNodeByKey,\n    $getPreviousSelection as getPreviousSelection,\n    $getSelection as getSelection,\n    $isRangeSelection as isRangeSelection,\n    $setSelection as setSelection,\n  } from 'lexical';\n  import { getContext, onMount, tick, untrack } from 'svelte';\n  import { on } from 'svelte/events';\n  import Button from '../../button/button.svelte';\n  import { getSuggestionListPosition } from '../../emoji/position.js';\n  import Icon from '../../icon/icon.svelte';\n  import TextInput from '../../text-field/text-input.svelte';\n  import { OPEN_LINK_EDITOR_COMMAND } from '../constants.js';\n  import {\n    $findSelectedLink as findSelectedLink,\n    getLinkAnchorRect,\n    isSafeLinkURL,\n  } from '../editing/link.js';\n  import { refocusEditor } from '../toolbar/actions.js';\n  import { mergeUnregisters } from '../utils.js';\n\n  /**\n   * @import { LexicalEditor, RangeSelection } from 'lexical';\n   * @import { EmojiAnchorRect, TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * What the edit mode is editing: an existing link, or the selected text to be linked.\n   * @typedef {{ linkKey: string } | { selection: RangeSelection }} LinkEditTarget\n   */\n\n  /**\n   * Maximum width of the popup, also enforced in the stylesheet.\n   */\n  const MAX_WIDTH = 400;\n  /**\n   * Height to assume until the popup has been measured, so the first open is positioned sensibly.\n   */\n  const FALLBACK_HEIGHT = 48;\n  /**\n   * Margin to the viewport edges, matching the emoji suggestions.\n   */\n  const VIEWPORT_MARGIN = 8;\n\n  const id = $props.id();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  /**\n   * The link at the selection, if any.\n   * @type {{ key: string, url: string, target: string | null } | undefined}\n   */\n  let currentLink = $state();\n  /**\n   * Whether the focus is within the editor or the popup. The popup is hidden otherwise, so it\n   * doesn’t linger once the user has moved on.\n   */\n  let hasFocus = $state(false);\n  /**\n   * Key of the link the user has dismissed the popup for with the Escape key, so it doesn’t come\n   * back while the caret stays on the link.\n   * @type {string | undefined}\n   */\n  let dismissedLinkKey = $state();\n  /**\n   * What is being edited, while the popup is in the edit mode.\n   * @type {LinkEditTarget | undefined}\n   */\n  let editTarget = $state.raw();\n  /** URL entered in the edit mode. */\n  let url = $state('');\n  /** Whether the link opens in a new tab, chosen in the edit mode. */\n  let openInNewTab = $state(false);\n  /** Whether the link opened in a new tab when the edit mode started. */\n  let initialOpenInNewTab = false;\n  /**\n   * Whether the link can be set to open in a new tab. Markdown has no syntax for the link target,\n   * so it’s only available for HTML.\n   */\n  const canSetTarget = $derived(editorStore.config.format === 'html');\n  /**\n   * Viewport-relative bounds of the link, or the selected text, the popup is anchored to.\n   * @type {EmojiAnchorRect | undefined}\n   */\n  let anchorRect = $state.raw();\n  /**\n   * Measured height of the popup.\n   * @type {number}\n   */\n  let popupHeight = $state(0);\n  /**\n   * A reference to the popup element, which is only mounted while it’s shown.\n   * @type {HTMLElement | undefined}\n   */\n  let popupElement = $state();\n  /**\n   * A reference to the URL field, which is only mounted in the edit mode.\n   * @type {HTMLInputElement | undefined}\n   */\n  let inputElement = $state();\n\n  const editing = $derived(!!editTarget);\n  const isValidURL = $derived(!!url.trim() && isSafeLinkURL(url));\n  const open = $derived(\n    editing || (!!currentLink && hasFocus && dismissedLinkKey !== currentLink.key),\n  );\n\n  /**\n   * Position of the popup, flipped above the link and clamped to the viewport as needed.\n   */\n  const position = $derived(\n    anchorRect\n      ? getSuggestionListPosition({\n          anchorRect,\n          listMaxHeight: popupHeight || FALLBACK_HEIGHT,\n          viewport: { width: window.innerWidth, height: window.innerHeight },\n          rtl: isRTL(),\n          listWidth: Math.min(MAX_WIDTH, window.innerWidth - VIEWPORT_MARGIN * 2),\n        })\n      : undefined,\n  );\n\n  /**\n   * Get the viewport-relative bounds of what the popup is anchored to: the text being linked in the\n   * edit mode for a new link, or the link otherwise.\n   * @param {LexicalEditor} editor Editor instance.\n   * @returns {EmojiAnchorRect | undefined} Bounds, or `undefined` if they can’t be determined.\n   */\n  const getAnchorRect = (editor) =>\n    getLinkAnchorRect(\n      editor,\n      editTarget && 'selection' in editTarget\n        ? editTarget\n        : {\n            linkKey: editTarget && 'linkKey' in editTarget ? editTarget.linkKey : currentLink?.key,\n          },\n    );\n\n  /**\n   * Follow the link when the page or an ancestor is scrolled, the window is resized, or the\n   * content has changed.\n   */\n  const reposition = () => {\n    const { editor } = editorStore;\n\n    anchorRect = editor && open ? getAnchorRect(editor) : undefined;\n  };\n\n  /**\n   * Switch the popup to the edit mode, and move the focus to the URL field.\n   * @param {LinkEditTarget} target What to edit.\n   * @param {string} initialURL URL to fill the field with.\n   * @param {boolean} [newTab] Whether the link opens in a new tab.\n   */\n  const startEditing = async (target, initialURL, newTab = false) => {\n    editTarget = target;\n    url = initialURL;\n    openInNewTab = newTab;\n    initialOpenInNewTab = newTab;\n    dismissedLinkKey = undefined;\n    await tick();\n    reposition();\n    await tick();\n    inputElement?.focus();\n    inputElement?.select();\n  };\n\n  /**\n   * Leave the edit mode without applying anything.\n   */\n  const stopEditing = () => {\n    editTarget = undefined;\n    url = '';\n    openInNewTab = false;\n  };\n\n  /**\n   * Start editing the link at the selection, or start linking the selected text. This is the\n   * handler for {@link OPEN_LINK_EDITOR_COMMAND}.\n   * @returns {boolean} Whether there is anything to edit. If not, the Link button opens the dialog\n   * to insert a link along with its text.\n   */\n  const onOpenCommand = () => {\n    /** @type {LinkEditTarget | undefined} */\n    let target;\n    let initialURL = '';\n    let newTab = false;\n\n    editorStore.editor?.getEditorState().read(() => {\n      const link = findSelectedLink();\n\n      if (link) {\n        target = { linkKey: link.getKey() };\n        initialURL = link.getURL();\n        newTab = link.getTarget() === '_blank';\n\n        return;\n      }\n\n      // The selection is kept while the focus is on the toolbar\n      const selection = getSelection() ?? getPreviousSelection();\n\n      if (isRangeSelection(selection) && !selection.isCollapsed()) {\n        const text = selection.getTextContent().trim();\n\n        if (text) {\n          target = { selection: selection.clone() };\n          // Prefill the URL field with the selected text only if it’s a URL that can be linked to.\n          // Otherwise, it’s just the link text, like a word or phrase.\n          initialURL = isURL(text) && isSafeLinkURL(text) ? text : '';\n        }\n      }\n    });\n\n    if (!target) {\n      return false;\n    }\n\n    startEditing(target, initialURL, newTab);\n\n    return true;\n  };\n\n  /**\n   * Apply the URL entered in the edit mode: update the link being edited, or link the selected\n   * text.\n   */\n  const applyURL = async () => {\n    const { editor } = editorStore;\n    const target = editTarget;\n    const newURL = url.trim();\n\n    // Only set the target when the toggle has been changed, so another target, like `_top`, is\n    // kept. The toggle isn’t available for Markdown, which can’t hold the target\n    const newTarget =\n      canSetTarget && openInNewTab !== initialOpenInNewTab\n        ? openInNewTab\n          ? '_blank'\n          : null\n        : undefined;\n\n    // The Apply button is disabled and the Enter key is ignored otherwise\n    /* v8 ignore next */\n    if (!editor || !target || !isValidURL) {\n      return;\n    }\n\n    stopEditing();\n\n    if ('linkKey' in target) {\n      editor.update(() => {\n        const node = getNodeByKey(target.linkKey);\n\n        // The edit mode ends once the link is gone; see the update listener below\n        /* v8 ignore else */\n        if (isLinkNode(node)) {\n          node.setURL(newURL);\n\n          if (newTarget !== undefined) {\n            node.setTarget(newTarget);\n          }\n        }\n      });\n    } else {\n      editor.update(() => {\n        setSelection(target.selection.clone());\n      });\n      editor.dispatchCommand(\n        TOGGLE_LINK_COMMAND,\n        newTarget ? { url: newURL, target: newTarget } : newURL,\n      );\n    }\n\n    // Move the focus back to the editor, where the selection is restored\n    await refocusEditor(editorStore);\n  };\n\n  /**\n   * Cancel the edit mode, and bring the focus back to the editor.\n   */\n  const cancelEditing = async () => {\n    stopEditing();\n    await refocusEditor(editorStore);\n  };\n\n  /**\n   * Remove the link at the selection, keeping its text.\n   */\n  const removeLink = async () => {\n    const key = currentLink?.key;\n\n    // The Remove button is only shown for a link\n    /* v8 ignore next */\n    if (!key) {\n      return;\n    }\n\n    editorStore.editor?.update(() => {\n      const node = getNodeByKey(key);\n\n      // The popup only shows a link that is there\n      /* v8 ignore else */\n      if (isLinkNode(node)) {\n        node.getChildren().forEach((child) => {\n          node.insertBefore(child);\n        });\n        node.remove();\n      }\n    });\n\n    await refocusEditor(editorStore);\n  };\n\n  /**\n   * Handle `keydown` event fired on the URL field.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  const onInputKeyDown = (event) => {\n    // Leave the keys to an input method editor while it’s composing text, where Enter commits the\n    // text and Escape cancels the composition\n    if (event.isComposing) {\n      return;\n    }\n\n    if (matchesShortcuts(event, 'Enter')) {\n      event.preventDefault();\n\n      if (isValidURL) {\n        applyURL();\n      }\n    } else if (matchesShortcuts(event, 'Escape')) {\n      // Don’t let the Escape key also close a dialog the editor is in\n      event.preventDefault();\n      event.stopPropagation();\n      cancelEditing();\n    }\n  };\n\n  $effect(() => {\n    const { editor } = editorStore;\n\n    // The root initializes the editor before this first runs\n    /* v8 ignore next */\n    if (!editor) {\n      return undefined;\n    }\n\n    const unregisterCommand = editor.registerCommand(\n      OPEN_LINK_EDITOR_COMMAND,\n      onOpenCommand,\n      COMMAND_PRIORITY_NORMAL,\n    );\n\n    // Dismiss the popup with the Escape key while the caret is on a link\n    const unregisterEscape = editor.registerCommand(\n      KEY_ESCAPE_COMMAND,\n      (event) => {\n        if (!open || editing || !currentLink) {\n          return false;\n        }\n\n        event?.preventDefault();\n        dismissedLinkKey = currentLink.key;\n\n        return true;\n      },\n      COMMAND_PRIORITY_HIGH,\n    );\n\n    const unregisterUpdateListener = editor.registerUpdateListener(({ editorState }) => {\n      editorState.read(() => {\n        const link = findSelectedLink();\n\n        currentLink = link\n          ? { key: link.getKey(), url: link.getURL(), target: link.getTarget() }\n          : undefined;\n\n        // What is being edited may be gone, e.g. when the value is replaced from outside, in which\n        // case there is nothing to apply the URL to anymore\n        if (\n          editTarget &&\n          ('linkKey' in editTarget\n            ? !isLinkNode(getNodeByKey(editTarget.linkKey))\n            : [editTarget.selection.anchor, editTarget.selection.focus].some(\n                ({ key }) => !getNodeByKey(key)?.isAttached(),\n              ))\n        ) {\n          stopEditing();\n        }\n      });\n\n      if (dismissedLinkKey && currentLink?.key !== dismissedLinkKey) {\n        dismissedLinkKey = undefined;\n      }\n\n      reposition();\n    });\n\n    const unregisterEditableListener = editor.registerEditableListener((editable) => {\n      if (!editable) {\n        stopEditing();\n      }\n    });\n\n    return mergeUnregisters(\n      unregisterCommand,\n      unregisterEscape,\n      unregisterUpdateListener,\n      unregisterEditableListener,\n    );\n  });\n\n  // The rich text editor can be swapped for the plain text one at any time, in which case there is\n  // no link to anchor the popup to anymore\n  $effect(() => {\n    if (!editorStore.useRichText) {\n      stopEditing();\n      currentLink = undefined;\n    }\n  });\n\n  $effect(() => {\n    void open;\n    reposition();\n  });\n\n  // Move the popup to the top layer, so it’s not clipped by anything around the editor, then\n  // measure it. The measurement has to happen after the popover is shown, because until then the\n  // element isn’t rendered at all and everything measures zero.\n  $effect(() => {\n    void editing;\n\n    if (!popupElement) {\n      return;\n    }\n\n    if (!popupElement.matches(':popover-open')) {\n      popupElement.showPopover?.();\n    }\n\n    popupHeight = popupElement.getBoundingClientRect().height;\n  });\n\n  onMount(() => {\n    /**\n     * Check if the given node is within the editor or the popup.\n     * @param {EventTarget | null} target Node.\n     * @returns {boolean} Result.\n     */\n    const isWithin = (target) => {\n      const node = /** @type {Node | null} */ (target);\n      const root = editorStore.editor?.getRootElement();\n\n      return !!node && (!!root?.contains(node) || !!popupElement?.contains(node));\n    };\n\n    // The state is updated within `untrack()` below, because the browser fires these events\n    // synchronously while it removes a focused element from the DOM, e.g. the URL field when the\n    // edit mode ends — which is to say, in the middle of Svelte rendering, where a plain assignment\n    // would be reported as an unsafe mutation. See also `close()` in `<EmojiSuggestions>`.\n\n    /**\n     * Track the focus. Moving it anywhere but the popup, including back to the text, leaves the\n     * edit mode without applying anything, like clicking away from a menu.\n     * @param {FocusEvent} event `focusin` event.\n     */\n    const onFocusIn = ({ target }) => {\n      untrack(() => {\n        hasFocus = isWithin(target);\n\n        if (editing && !popupElement?.contains(/** @type {Node} */ (target))) {\n          stopEditing();\n        }\n      });\n    };\n\n    /**\n     * Track the focus leaving the page or a removed element, which doesn’t fire `focusin`.\n     * @param {FocusEvent} event `focusout` event.\n     */\n    const onFocusOut = ({ relatedTarget }) => {\n      if (!relatedTarget) {\n        untrack(() => {\n          hasFocus = false;\n        });\n      }\n    };\n\n    return mergeUnregisters(\n      on(window, 'scroll', reposition, { capture: true, passive: true }),\n      on(window, 'resize', reposition, { passive: true }),\n      on(document, 'focusin', onFocusIn),\n      on(document, 'focusout', onFocusOut),\n    );\n  });\n</script>\n\n{#if open && position}\n  <!--\n    The `mousedown` listener isn’t an interaction with the group: it only keeps the focus where it\n    is when the popup is pressed, as the controls in it take the interactions.\n  -->\n  <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->\n  <div\n    bind:this={popupElement}\n    role=\"group\"\n    class=\"sui floating-link-editor\"\n    aria-label={_('_sui.text_editor.link')}\n    popover=\"manual\"\n    style:top={position.top}\n    style:bottom={position.bottom}\n    style:left={position.left}\n    onmousedown={(event) => {\n      // Keep the focus where it is when the popup’s background or a button is pressed, except for\n      // the URL field, which takes it. Otherwise, the focus would move to the page, hiding the\n      // popup or blurring the URL field. Safari doesn’t focus a button on click, and moves the\n      // focus to the closest focusable ancestor instead, which ends the edit mode before the click\n      // can apply the URL\n      // @see https://github.com/sveltia/sveltia-cms/issues/1148\n      if (!(/** @type {Element} */ (event.target).closest('input'))) {\n        event.preventDefault();\n      }\n    }}\n  >\n    {#if editing}\n      <TextInput\n        bind:element={inputElement}\n        dir=\"ltr\"\n        id=\"{id}-url\"\n        bind:value={url}\n        flex\n        invalid={!!url.trim() && !isSafeLinkURL(url)}\n        aria-label={_('_sui.text_editor.url')}\n        onkeydown={(event) => {\n          onInputKeyDown(event);\n        }}\n      />\n      {#if canSetTarget}\n        <Button\n          iconic\n          variant=\"ghost\"\n          pressed={openInNewTab}\n          aria-label={_('_sui.text_editor.open_in_new_tab')}\n          onclick={() => {\n            openInNewTab = !openInNewTab;\n          }}\n        >\n          {#snippet startIcon()}\n            <Icon name=\"open_in_new\" />\n          {/snippet}\n        </Button>\n      {/if}\n      <Button\n        iconic\n        variant=\"ghost\"\n        disabled={!isValidURL}\n        aria-label={editTarget && 'linkKey' in editTarget ? _('_sui.update') : _('_sui.insert')}\n        onclick={() => {\n          applyURL();\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"check\" />\n        {/snippet}\n      </Button>\n      <Button\n        iconic\n        variant=\"ghost\"\n        aria-label={_('_sui.cancel')}\n        onclick={() => {\n          cancelEditing();\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"close\" />\n        {/snippet}\n      </Button>\n    {:else if currentLink}\n      <a\n        class=\"url\"\n        href={isSafeLinkURL(currentLink.url) ? currentLink.url : undefined}\n        target=\"_blank\"\n        rel=\"external noopener noreferrer\"\n        dir=\"ltr\"\n      >\n        {currentLink.url}\n      </a>\n      <Button\n        iconic\n        variant=\"ghost\"\n        aria-label={_('_sui.text_editor.edit_link')}\n        onclick={() => {\n          // The link is still at the selection, since the focus is within the popup\n          /* v8 ignore else */\n          if (currentLink) {\n            startEditing(\n              { linkKey: currentLink.key },\n              currentLink.url,\n              currentLink.target === '_blank',\n            );\n          }\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"edit\" />\n        {/snippet}\n      </Button>\n      <Button\n        iconic\n        variant=\"ghost\"\n        aria-label={_('_sui.text_editor.remove_link')}\n        onclick={() => {\n          removeLink();\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"link_off\" />\n        {/snippet}\n      </Button>\n    {/if}\n  </div>\n{/if}\n\n<style>.floating-link-editor {\n  position: fixed;\n  inset: auto;\n  z-index: 1000;\n  display: flex;\n  align-items: center;\n  gap: 4px;\n  margin: 0;\n  padding: 4px;\n  width: min(400px, 100vw - 16px);\n  font-family: var(--sui-control-font-family);\n  font-size: var(--sui-control-font-size);\n  line-height: var(--sui-control-line-height);\n  border-width: var(--sui-listbox-border-width, 1px);\n  border-style: var(--sui-listbox-border-style, solid);\n  border-color: var(--sui-listbox-border-color, var(--sui-secondary-border-color));\n  border-radius: var(--sui-listbox-border-radius, 4px);\n  color: var(--sui-primary-foreground-color);\n  background-color: var(--sui-secondary-background-color-translucent);\n  box-shadow: 0 8px 16px var(--sui-popup-shadow-color);\n  -webkit-backdrop-filter: blur(16px);\n  backdrop-filter: blur(16px);\n}\n.floating-link-editor :global(.sui.text-input) {\n  flex: auto;\n  margin: 0 !important;\n  min-width: 0;\n}\n.floating-link-editor :global(.sui.button) {\n  flex: none;\n  margin: 0 !important;\n}\n\n.url {\n  flex: auto;\n  overflow: hidden;\n  padding: 0 8px;\n  min-width: 0;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n}</style>\n","/**\n * Helpers for the menus on the text editor toolbar.\n */\n\n/**\n * Maximum number of frames to wait for a menu to close.\n */\nconst MAX_CLOSE_FRAMES = 60;\n\n/**\n * Wait for the menu the given item is in to close. A menu is a modal dialog, which makes the rest\n * of the page inert while it’s open, so the editor can’t take the focus yet. Once closed, the\n * dialog moves the focus back to the button that opened it on the next task, so wait for that as\n * well.\n * Call this before moving the focus back to the editor after an item is chosen.\n * @param {HTMLElement} item Menu item chosen.\n * @param {number} [frames] Number of frames waited so far.\n * @returns {Promise<void>} Nothing.\n */\nexport const waitForMenuToClose = async (item, frames = 0) => {\n  if (item.closest('dialog')?.open && frames < MAX_CLOSE_FRAMES) {\n    await new Promise((resolve) => {\n      window.requestAnimationFrame(resolve);\n    });\n\n    return waitForMenuToClose(item, frames + 1);\n  }\n\n  return new Promise((resolve) => {\n    window.setTimeout(resolve);\n  });\n};\n","<!--\n  @component\n  Menu of the operations on a table: inserting and deleting rows and columns, and deleting the whole\n  table. It’s opened from the toolbar or the button on the selected table cell.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { getContext } from 'svelte';\n  import Divider from '../../divider/divider.svelte';\n  import MenuItem from '../../menu/menu-item.svelte';\n  import Menu from '../../menu/menu.svelte';\n  import { isRightToLeftTable, $runTableAction as runTableAction } from '../editing/table.js';\n  import { runEditorAction } from './actions.js';\n  import { waitForMenuToClose } from './menu.js';\n\n  /**\n   * @import { LexicalEditor } from 'lexical';\n   * @import { TextEditorStore } from '../../../typedefs.js';\n   * @import { TableAction } from '../editing/table.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} cellKey Key of the table cell to run the operations on.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    cellKey,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  /**\n   * Menu items, grouped by what they do. Each item has the operation and the key of its label.\n   * @type {[TableAction, string][][]}\n   */\n  const ITEM_GROUPS = [\n    [\n      ['insert-row-above', 'insert_row_above'],\n      ['insert-row-below', 'insert_row_below'],\n    ],\n    [\n      ['insert-column-left', 'insert_column_left'],\n      ['insert-column-right', 'insert_column_right'],\n    ],\n    [\n      ['delete-row', 'delete_row'],\n      ['delete-column', 'delete_column'],\n      ['delete-table', 'delete_table'],\n    ],\n  ];\n\n  /**\n   * Run the given operation on the cell, then move the focus back to the editor.\n   * @param {TableAction} action Operation.\n   * @param {HTMLElement} item Menu item chosen.\n   * @returns {Promise<void>} Nothing.\n   */\n  const runAction = (action, item) =>\n    // The menu is only shown for a cell in the rich text editor\n    runEditorAction(editorStore, {\n      /**\n       * Run the operation, and wait for the menu to close.\n       * @param {LexicalEditor} editor Editor instance.\n       * @returns {Promise<void>} Nothing.\n       */\n      rich: async (editor) => {\n        const cell = editor.getElementByKey(cellKey);\n        const rtl = !!cell && isRightToLeftTable(cell);\n\n        editor.update(() => {\n          runTableAction(action, cellKey, { rtl });\n        });\n\n        await waitForMenuToClose(item);\n      },\n    });\n</script>\n\n<Menu ariaLabel={_('_sui.text_editor.table_options')}>\n  {#each ITEM_GROUPS as items, index (index)}\n    {#if index > 0}\n      <Divider />\n    {/if}\n    {#each items as [action, labelKey] (action)}\n      <MenuItem\n        label={_(`_sui.text_editor.${labelKey}`)}\n        onclick={(/** @type {MouseEvent} */ event) => {\n          runAction(action, /** @type {HTMLElement} */ (event.currentTarget));\n        }}\n      />\n    {/each}\n  {/each}\n</Menu>\n","<!--\n  @component\n  Button on the table cell where the caret is, at its top end corner, that opens the table menu to\n  insert and delete rows and columns, the same way it works in the Lexical Playground. The same menu\n  is also available on the toolbar, which is easier to reach with the keyboard.\n  @see https://playground.lexical.dev/\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { getContext, onMount } from 'svelte';\n  import { on } from 'svelte/events';\n  import Icon from '../../icon/icon.svelte';\n  import MenuButton from '../../menu/menu-button.svelte';\n  import {\n    $getSelectedTableCellKey as getSelectedTableCellKey,\n    isRightToLeftTable,\n  } from '../editing/table.js';\n  import TableActionMenu from '../toolbar/table-action-menu.svelte';\n  import { mergeUnregisters } from '../utils.js';\n\n  /**\n   * @import { PopupPosition, TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * Space between the button and the cell border.\n   */\n  const OFFSET = 4;\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  /**\n   * Key of the table cell the selection is in, if any.\n   * @type {string | null}\n   */\n  let cellKey = $state(null);\n  /**\n   * Whether the focus is within the editor, or on the menu opened from the button. The button is\n   * hidden otherwise, so it doesn’t linger once the user has moved on.\n   */\n  let hasFocus = $state(false);\n  /**\n   * Position of the button relative to the editor wrapper: the top end corner of the cell.\n   * @type {{ top: number, left: number, rtl: boolean, popupPosition: PopupPosition } |\n   * undefined}\n   */\n  let position = $state.raw();\n  /**\n   * A reference to the element positioning the button.\n   * @type {HTMLElement | undefined}\n   */\n  let container = $state();\n\n  const show = $derived(!!cellKey && hasFocus && !!position && editorStore.useRichText);\n  const style = $derived(position ? `top: ${position.top}px; left: ${position.left}px` : undefined);\n\n  /**\n   * Get the editor wrapper, which the button is positioned against.\n   * @returns {HTMLElement | null | undefined} Wrapper.\n   */\n  const getWrapper = () => container?.parentElement;\n\n  /**\n   * Move the button to the top end corner of the cell, as much of it as is visible: a wide table\n   * can be scrolled horizontally within its wrapper, and the editor can be scrolled itself when its\n   * height is limited. Nothing is measured while the button is hidden for the lack of focus.\n   */\n  const reposition = () => {\n    const wrapper = getWrapper();\n    const cell = cellKey ? editorStore.editor?.getElementByKey(cellKey) : undefined;\n\n    if (!hasFocus || !wrapper || !cell) {\n      position = undefined;\n\n      return;\n    }\n\n    const cellRect = cell.getBoundingClientRect();\n\n    // The table is wrapped with an element scrolling it horizontally; see `initEditor()`\n    const tableRect = /** @type {HTMLElement} */ (\n      cell.closest('.table-wrapper')\n    ).getBoundingClientRect();\n\n    // The cell is in the editor root\n    const rootRect = /** @type {HTMLElement} */ (\n      cell.closest('.lexical-root')\n    ).getBoundingClientRect();\n\n    const wrapperRect = wrapper.getBoundingClientRect();\n    const rtl = isRightToLeftTable(cell);\n    const left = Math.max(cellRect.left, tableRect.left);\n    const right = Math.min(cellRect.right, tableRect.right);\n    const top = Math.max(cellRect.top, rootRect.top);\n    const bottom = Math.min(cellRect.bottom, rootRect.bottom);\n\n    // The cell is not laid out, e.g. while the editor is hidden, or scrolled out of view\n    if (right <= left || bottom <= top) {\n      position = undefined;\n\n      return;\n    }\n\n    position = {\n      top: top - wrapperRect.top + OFFSET,\n      left: (rtl ? left + OFFSET : right - OFFSET) - wrapperRect.left,\n      rtl,\n      // Open the menu toward the inline end, so it doesn’t cover the cell\n      popupPosition: rtl ? 'bottom-right' : 'bottom-left',\n    };\n  };\n\n  /**\n   * Timer to check the focus once it has settled.\n   * @type {number | undefined}\n   */\n  let focusTimer;\n\n  /**\n   * Check whether the focus is within the editor, or on the menu, once it has settled. While it\n   * moves, it’s on `<body>` for a moment.\n   */\n  const updateFocus = () => {\n    window.clearTimeout(focusTimer);\n    focusTimer = window.setTimeout(() => {\n      const wrapper = getWrapper();\n\n      hasFocus =\n        !!wrapper?.contains(document.activeElement) ||\n        !!container?.querySelector('[aria-expanded=\"true\"]');\n      reposition();\n    });\n  };\n\n  $effect(() => {\n    const { editor } = editorStore;\n\n    // The root initializes the editor before this first runs\n    /* v8 ignore next 3 */\n    if (!editor) {\n      return undefined;\n    }\n\n    return mergeUnregisters(\n      editor.registerUpdateListener(({ editorState }) => {\n        cellKey = editorState.read(getSelectedTableCellKey);\n        reposition();\n      }),\n      // Follow the cell when a wide table is scrolled, or the editor is resized\n      editor.registerRootListener((root) => {\n        if (!root) {\n          return undefined;\n        }\n\n        const resizeObserver = new ResizeObserver(reposition);\n\n        resizeObserver.observe(root);\n\n        return mergeUnregisters(on(root, 'scroll', reposition, { capture: true }), () => {\n          resizeObserver.disconnect();\n        });\n      }),\n    );\n  });\n\n  onMount(() => {\n    const unregister = mergeUnregisters(\n      on(window, 'resize', reposition),\n      on(document, 'focusin', updateFocus),\n      on(document, 'focusout', updateFocus),\n    );\n\n    return () => {\n      window.clearTimeout(focusTimer);\n      unregister();\n    };\n  });\n</script>\n\n<!--\n  The `mousedown` listener isn’t an interaction with the element: it only keeps the focus in the\n  editor when the button is pressed. Safari doesn’t focus a button on click, and moves the focus to\n  `<body>` instead, which would hide the button before the click could open the menu.\n  @see https://github.com/sveltia/sveltia-cms/issues/1148\n-->\n<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->\n<div\n  role=\"none\"\n  class=\"table-cell-menu-button\"\n  class:rtl={position?.rtl}\n  hidden={!show}\n  {style}\n  bind:this={container}\n  onmousedown={(event) => {\n    event.preventDefault();\n  }}\n>\n  {#if show && cellKey}\n    {@const key = cellKey}\n    <MenuButton\n      iconic\n      size=\"small\"\n      variant=\"tertiary\"\n      popupPosition={position?.popupPosition}\n      aria-label={_('_sui.text_editor.show_table_options')}\n      aria-controls={editorStore.controlId}\n    >\n      {#snippet endIcon()}\n        <Icon name=\"expand_more\" />\n      {/snippet}\n      {#snippet popup()}\n        <TableActionMenu cellKey={key} />\n      {/snippet}\n    </MenuButton>\n  {/if}\n</div>\n\n<style>.table-cell-menu-button {\n  position: absolute;\n  z-index: 1;\n  translate: -100% 0;\n}\n.table-cell-menu-button.rtl {\n  translate: 0 0;\n}\n.table-cell-menu-button[hidden] {\n  display: none;\n}\n.table-cell-menu-button :global(.sui.button) {\n  margin: 0;\n  border-radius: 50%;\n  background-color: var(--sui-secondary-background-color);\n}</style>\n","/**\n * Check if the given input is a simple object.\n * @param {any} input Input, probably an object.\n * @returns {input is Record<string, any>} Result.\n */\nconst isObject = (input) => input !== null && typeof input === 'object' && !Array.isArray(input);\n/**\n * Convert a Proxy to the original object. The built-in `structuredClone()` method throws with a\n * Proxy in some environments, so this can be used instead. The name of `toRaw` is derived from the\n * equivalent in Vue.\n * Note: this is JSON-based, so the following values are lost or transformed:\n * - `Date` → ISO string\n * - `Map`/`Set` → `{}`\n * - `undefined`, functions, symbols → dropped\n * - `BigInt` → throws\n * - circular references → throws\n * For richer cloning of plain objects, prefer `structuredClone()` directly.\n * @param {object} obj Proxified object.\n * @returns {object} Deproxified object.\n */\nconst toRaw = (obj) => JSON.parse(JSON.stringify(obj));\n\nexport { isObject, toRaw };\n","import { isObject } from './object.js';\n\n/**\n * Check if the given input is an array of objects.\n * @param {any} input Input, probably an array.\n * @returns {input is Record<string, any>[]} Result.\n */\nconst isObjectArray = (input) =>\n  Array.isArray(input) && /** @type {any[]} */ (input).every(isObject);\n\n/**\n * Remove duplicate values from the given array.\n * @param {any[]} array Original array with primitive values.\n * @returns {any[]} - Array without duplicates.\n */\nconst unique = (array) => [...new Set(array)];\n\nexport { isObjectArray, unique };\n","/**\n * Syntax highlighting of the Markdown or HTML source shown in the plain text mode of the text\n * editor.\n */\n\nimport { unique } from '@sveltia/utils/array';\nimport { untrack } from 'svelte';\nimport { parseOpeningFence } from '../conversion/markdown/code-blocks.js';\nimport { highlightCodeToTokens } from './engine.js';\nimport { loadCodeHighlighter } from './preload.js';\nimport { getCodeTheme, onCodeThemeChange } from './theme.js';\n\n/**\n * @import { HighlightedToken } from '../../../typedefs.js';\n */\n\n/**\n * Maximum length of the Markdown or HTML source to highlight in the plain text mode. The whole\n * source is tokenized on every keystroke, so highlighting a longer one would make typing sluggish.\n */\nexport const MAX_HIGHLIGHT_LENGTH = 20_000;\n\n/**\n * Get the languages used in the fenced code blocks of the given Markdown source, read from the\n * opening fences the same way the rich text mode reads them; see `parseOpeningFence()`. Fences\n * within a code block are taken in as well, which only means loading a grammar that isn’t needed.\n * @param {string} source Markdown source.\n * @returns {string[]} Unique languages, in the order they first appear.\n */\nexport const getCodeFenceLanguages = (source) =>\n  unique(\n    source\n      .split('\\n')\n      .map((line) => parseOpeningFence(line)?.language)\n      .filter((language) => language !== undefined),\n  );\n\n/**\n * Create a function that highlights the Markdown or HTML source in the plain text mode, loading the\n * highlighter, as well as the languages of the fenced code blocks in Markdown, while the mode is\n * shown, and following the app’s appearance. This must be called during the component\n * initialization, as it sets up effects.\n * @param {object} args Arguments.\n * @param {'markdown' | 'html'} args.language Language of the source.\n * @param {() => boolean} args.isActive Whether the plain text mode is shown. Nothing is loaded or\n * highlighted otherwise.\n * @param {() => string} args.getSource Get the current source, to find the languages of its fenced\n * code blocks.\n * @returns {(source: string) => HighlightedToken[][] | undefined} Function to highlight the given\n * source, which returns `undefined` while the highlighter is still loading, the plain text mode\n * isn’t shown, or the source is too long. It’s reactive: it gives new tokens once something has\n * been loaded, or the theme has changed.\n */\nexport const createSourceHighlighter = ({ language, isActive, getSource }) => {\n  /** Syntax highlighting theme matching the app’s appearance. */\n  let codeTheme = $state(getCodeTheme());\n  /** Incremented whenever the highlighter has loaded something, to highlight the text again. */\n  let loadCount = $state(0);\n\n  /**\n   * Comma-separated languages used in the fenced code blocks of the Markdown source, which are\n   * highlighted as well. It’s a string rather than an array, so the highlighter isn’t reloaded on\n   * every keystroke.\n   */\n  const codeLanguages = $derived.by(() => {\n    if (!isActive() || language !== 'markdown' || getSource().length > MAX_HIGHLIGHT_LENGTH) {\n      return '';\n    }\n\n    return getCodeFenceLanguages(getSource()).join(',');\n  });\n\n  $effect(() =>\n    onCodeThemeChange(async () => {\n      const theme = getCodeTheme();\n\n      // Keep the current highlighting until the new theme is ready, so the text doesn’t flash\n      if (isActive()) {\n        await loadCodeHighlighter(language);\n      }\n\n      // Ignore an outdated change, in case the appearance has changed again while loading\n      if (theme === getCodeTheme()) {\n        codeTheme = theme;\n      }\n    }),\n  );\n\n  $effect(() => {\n    // Load the highlighter only when the plain text mode is actually shown\n    if (!isActive()) {\n      return;\n    }\n\n    const languages = codeLanguages ? codeLanguages.split(',') : [];\n\n    void codeTheme;\n\n    untrack(() => {\n      // The Markdown or HTML grammar is loaded first, because the engine has to be in place before\n      // anything else can be loaded\n      loadCodeHighlighter(language).then(async () => {\n        loadCount += 1;\n        await Promise.all(languages.map((lang) => loadCodeHighlighter(lang)));\n        loadCount += 1;\n      });\n    });\n  });\n\n  return (source) => {\n    void loadCount;\n\n    // Don’t waste time on tokenizing the source while the rich text mode is shown\n    if (!isActive() || source.length > MAX_HIGHLIGHT_LENGTH) {\n      return undefined;\n    }\n\n    return highlightCodeToTokens(source, language, { theme: codeTheme });\n  };\n};\n","<script>\n  /**\n   * @import { ContainerProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   */\n\n  /**\n   * @type {ContainerProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    ariaLabel = undefined,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div {...restProps} role=\"group\" class=\"sui button-group {className}\" aria-label={ariaLabel}>\n  {@render children?.()}\n</div>\n\n<style>.button-group {\n  flex: none;\n  display: inline-flex;\n  align-items: center;\n}</style>\n","<!--\n  @component\n  Toolbar menu button to change the text alignment of the selected blocks, showing the current\n  alignment. It’s only available for HTML, as Markdown has no syntax for alignment.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { FORMAT_ELEMENT_COMMAND } from 'lexical';\n  import { getContext } from 'svelte';\n  import Icon from '../../icon/icon.svelte';\n  import MenuButton from '../../menu/menu-button.svelte';\n  import MenuItemRadio from '../../menu/menu-item-radio.svelte';\n  import Menu from '../../menu/menu.svelte';\n  import { ALIGNMENT_OPTIONS } from '../constants.js';\n  import { runEditorAction } from './actions.js';\n  import { waitForMenuToClose } from './menu.js';\n\n  /**\n   * @import { LexicalEditor } from 'lexical';\n   * @import { TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  const alignment = $derived(editorStore.selection.alignment ?? '');\n  /**\n   * Icon of the current alignment. The default alignment, as well as one the menu doesn’t offer,\n   * like `start`, is shown as left aligned.\n   */\n  const icon = $derived(\n    ALIGNMENT_OPTIONS.find(({ type }) => type === alignment)?.icon ?? 'format_align_left',\n  );\n\n  /**\n   * Align the selected blocks, then move the focus back to the editor.\n   * @param {(typeof ALIGNMENT_OPTIONS)[number]['type']} type Alignment.\n   * @param {HTMLElement} item Menu item chosen.\n   * @returns {Promise<void>} Nothing.\n   */\n  const align = (type, item) =>\n    // The menu is only shown in the rich text mode\n    runEditorAction(editorStore, {\n      /**\n       * Align the selected blocks, and wait for the menu to close.\n       * @param {LexicalEditor} editor Editor instance.\n       * @returns {Promise<void>} Nothing.\n       */\n      rich: async (editor) => {\n        editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, type);\n        await waitForMenuToClose(item);\n      },\n    });\n</script>\n\n<MenuButton\n  aria-label={_('_sui.text_editor.show_alignment_options')}\n  aria-controls={editorStore.controlId}\n>\n  {#snippet startIcon()}\n    <Icon name={icon} />\n  {/snippet}\n  {#snippet popup()}\n    <Menu ariaLabel={_('_sui.text_editor.alignment_options')}>\n      <!--\n        The menu checks the item chosen on its own, which is wrong if nothing could be aligned, like\n        when a horizontal rule is selected, so start over whenever the editor reports the selection\n      -->\n      {#key editorStore.selection}\n        {#each ALIGNMENT_OPTIONS as option (option.type)}\n          <MenuItemRadio\n            label={_(`_sui.text_editor.${option.labelKey}`)}\n            checked={alignment === option.type}\n            onclick={(/** @type {MouseEvent} */ event) => {\n              align(option.type, /** @type {HTMLElement} */ (event.currentTarget));\n            }}\n          >\n            {#snippet startIcon()}\n              <Icon name={option.icon} />\n            {/snippet}\n          </MenuItemRadio>\n        {/each}\n      {/key}\n    </Menu>\n  {/snippet}\n</MenuButton>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { FORMAT_TEXT_COMMAND } from 'lexical';\n  import { getContext } from 'svelte';\n  import Button from '../../button/button.svelte';\n  import Icon from '../../icon/icon.svelte';\n  import { AVAILABLE_BUTTONS, isHtmlOnlyButton } from '../constants.js';\n  import {\n    editRawText,\n    registerRawTextShortcut,\n    toggleInlineFormat,\n  } from '../editing/raw-markdown.js';\n  import { runEditorAction } from './actions.js';\n\n  /**\n   * @import { LexicalEditor } from 'lexical';\n   * @import { TextEditorFormatType, TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {TextEditorFormatType} type Button type.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    type,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n  const selectionTypeMatches = $derived(editorStore.selection.inlineTypes.includes(type));\n\n  /**\n   * Keyboard shortcut keys for the plain text mode. The rich text editor handles them on its own.\n   * @type {Record<string, string>}\n   */\n  const SHORTCUT_KEYS = { bold: 'B', italic: 'I' };\n\n  /**\n   * Format the selection.\n   * @returns {Promise<void>} Nothing.\n   */\n  const format = () =>\n    runEditorAction(editorStore, {\n      /**\n       * Format the selected Markdown.\n       * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n       */\n      raw: (textArea) => {\n        // The `<textarea>` is only there for Markdown, which hides the HTML-only formats\n        /* v8 ignore else */\n        if (!isHtmlOnlyButton(type)) {\n          editRawText(textArea, (state) => toggleInlineFormat(state, type));\n        }\n      },\n      /**\n       * Format the selection.\n       * @param {LexicalEditor} editor Editor instance.\n       */\n      rich: (editor) => {\n        editor.dispatchCommand(FORMAT_TEXT_COMMAND, type);\n      },\n      // The format applies to the selection, which the focus restores\n      focus: 'before',\n    });\n\n  $effect(() => {\n    const { textArea } = editorStore;\n    const key = SHORTCUT_KEYS[type];\n\n    if (!textArea || !key) {\n      return undefined;\n    }\n\n    // Handle the keyboard shortcut in the plain text mode\n    return registerRawTextShortcut(textArea, key, () => {\n      format();\n    });\n  });\n</script>\n\n<Button\n  iconic\n  aria-label={_(`_sui.text_editor.${AVAILABLE_BUTTONS[type].labelKey}`)}\n  aria-controls={editorStore.controlId}\n  pressed={selectionTypeMatches}\n  onclick={() => {\n    format();\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name={AVAILABLE_BUTTONS[type].icon} />\n  {/snippet}\n</Button>\n","<!--\n  @component\n  Toolbar button to insert a horizontal rule: a node in the rich text mode, with the caret moved\n  below it, or its Markdown in the plain text mode.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { getContext } from 'svelte';\n  import Button from '../../button/button.svelte';\n  import Icon from '../../icon/icon.svelte';\n  import { $insertHorizontalRule as insertHorizontalRule } from '../editing/block.js';\n  import { AVAILABLE_BUTTONS } from '../constants.js';\n  import { editRawText, insertMarkdown } from '../editing/raw-markdown.js';\n  import { HORIZONTAL_RULE_MARKDOWN } from '../conversion/transformers/hr.js';\n  import { runEditorAction } from './actions.js';\n\n  /**\n   * @import { LexicalEditor } from 'lexical';\n   * @import { TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  const { labelKey, icon } = AVAILABLE_BUTTONS['horizontal-rule'];\n\n  /**\n   * Insert a horizontal rule, then move the focus back to the editor.\n   * @returns {Promise<void>} Nothing.\n   */\n  const insert = () =>\n    runEditorAction(editorStore, {\n      /**\n       * Insert the Markdown.\n       * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n       * @returns {void | Promise<void>} Nothing.\n       */\n      raw: (textArea) =>\n        editRawText(textArea, (state) =>\n          insertMarkdown(state, HORIZONTAL_RULE_MARKDOWN, { block: true }),\n        ),\n      /**\n       * Insert a horizontal rule node.\n       * @param {LexicalEditor} editor Editor instance.\n       */\n      rich: (editor) => {\n        editor.update(() => {\n          insertHorizontalRule();\n        });\n      },\n    });\n</script>\n\n<Button\n  iconic\n  aria-label={_(`_sui.text_editor.${labelKey}`)}\n  aria-controls={editorStore.controlId}\n  onclick={() => {\n    insert();\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name={icon} />\n  {/snippet}\n</Button>\n","<script>\n  import { getContext } from 'svelte';\n  import Button from '../../button/button.svelte';\n  import Icon from '../../icon/icon.svelte';\n  import { insertEditorComponent } from './actions.js';\n\n  /**\n   * @import { TextEditorComponent, TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {TextEditorComponent} component Editor component.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    component,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  const { label, icon } = $derived(component);\n</script>\n\n<Button\n  iconic={!!icon}\n  label={icon ? undefined : label}\n  title={label}\n  aria-label={label}\n  aria-controls={editorStore.controlId}\n  onclick={() => {\n    insertEditorComponent(editorStore, component);\n  }}\n>\n  {#snippet startIcon()}\n    {#if icon}\n      <Icon name={icon} />\n    {/if}\n  {/snippet}\n</Button>\n","<script>\n  import { TOGGLE_LINK_COMMAND } from '@lexical/link';\n  import { _ } from '@sveltia/i18n';\n  import { isMac, matchesShortcuts } from '@sveltia/utils/events';\n  import { isURL } from '@sveltia/utils/string';\n  import {\n    COMMAND_PRIORITY_NORMAL,\n    KEY_DOWN_COMMAND,\n    $createRangeSelection as createRangeSelection,\n    $createTextNode as createTextNode,\n    $getPreviousSelection as getPreviousSelection,\n    $getSelection as getSelection,\n    $getTextContent as getTextContent,\n    $insertNodes as insertNodes,\n    $isRangeSelection as isRangeSelection,\n    $setSelection as setSelection,\n  } from 'lexical';\n  import { getContext } from 'svelte';\n  import Button from '../../button/button.svelte';\n  import Checkbox from '../../checkbox/checkbox.svelte';\n  import Dialog from '../../dialog/dialog.svelte';\n  import Icon from '../../icon/icon.svelte';\n  import TextInput from '../../text-field/text-input.svelte';\n  import { AVAILABLE_BUTTONS, OPEN_LINK_EDITOR_COMMAND } from '../constants.js';\n  import { focusEditor } from '../editing/caret.js';\n  import { isSafeLinkURL } from '../editing/link.js';\n  import {\n    editRawText,\n    getRawTextState,\n    insertLink,\n    registerRawTextShortcut,\n  } from '../editing/raw-markdown.js';\n  import { refocusEditor, runEditorAction } from './actions.js';\n\n  /**\n   * @import { LexicalEditor } from 'lexical';\n   * @import { TextEditorStore } from '../../../typedefs.js';\n   */\n\n  const id = $props.id();\n\n  /**\n   * Button type.\n   */\n  const type = 'link';\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n  const selectionTypeMatches = $derived(editorStore.selection.inlineTypes.includes(type));\n\n  let openDialog = $state(false);\n  let hasAnchor = $state(false);\n  let anchorURL = $state('');\n  let anchorText = $state('');\n  let openInNewTab = $state(false);\n  /**\n   * Whether the link can be set to open in a new tab. Markdown has no syntax for the link target,\n   * so it’s only available for HTML, whose source isn’t edited with the toolbar.\n   */\n  const canSetTarget = $derived(editorStore.config.format === 'html' && editorStore.useRichText);\n  /**\n   * Whether the URL can be inserted: not empty, and safe to link to.\n   */\n  const isValidURL = $derived(!!anchorURL.trim() && isSafeLinkURL(anchorURL));\n\n  /**\n   * Open the dialog to create a new link from the given selected text.\n   * @param {string} textContent Selected text.\n   */\n  const openCreateDialog = (textContent) => {\n    // Prefill the URL field with the selected text only if it’s a URL that can be linked to.\n    // Otherwise, it’s just the link text, like a word or phrase.\n    anchorURL = isURL(textContent) && isSafeLinkURL(textContent) ? textContent : '';\n    hasAnchor = !!textContent;\n    openDialog = true;\n  };\n\n  /**\n   * Create a new link by showing a dialog to accept a URL and optionally text.\n   */\n  const createLink = () => {\n    const { textArea, useRichText } = editorStore;\n\n    if (!useRichText) {\n      // The button is only enabled while the `<textarea>` is there\n      /* v8 ignore else */\n      if (textArea) {\n        const { value, start, end } = getRawTextState(textArea);\n\n        openCreateDialog(value.slice(start, end).trim());\n      }\n\n      return;\n    }\n\n    editorStore.editor?.getEditorState().read(() => {\n      openCreateDialog(getTextContent().trim());\n    });\n  };\n\n  /**\n   * Handle `click` event fired on the Link button. In the rich text mode, the floating link editor\n   * takes care of a selected link or text. Otherwise, create a new link with the dialog.\n   */\n  const onButtonClick = () => {\n    // Links are not detected in the plain text mode, so a new one is always created there\n    if (\n      editorStore.useRichText &&\n      editorStore.editor?.dispatchCommand(OPEN_LINK_EDITOR_COMMAND, undefined)\n    ) {\n      return;\n    }\n\n    createLink();\n  };\n\n  /**\n   * Handle `keydown` event fired on the input fields on the dialog.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  const onInputKeyDown = (event) => {\n    if (matchesShortcuts(event, 'Enter') && isValidURL) {\n      openDialog = false;\n    }\n  };\n\n  /**\n   * Handle `close` event fired on the dialog. Insert a link with the given URL and optionally text.\n   * @param {CustomEvent} event `close` event.\n   * @see https://github.com/facebook/lexical/discussions/3013\n   */\n  const onDialogClose = async (event) => {\n    if (event.detail.returnValue === 'cancel') {\n      // The dialog leaves the focus alone (see `restoreFocus` below), so bring it back here\n      await refocusEditor(editorStore);\n    } else {\n      await runEditorAction(editorStore, {\n        /**\n         * Insert the link’s Markdown.\n         * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n         * @returns {void | Promise<void>} Nothing.\n         */\n        raw: (textArea) =>\n          editRawText(textArea, (state) =>\n            insertLink(state, { url: anchorURL.trim(), text: hasAnchor ? undefined : anchorText }),\n          ),\n        /**\n         * Insert the link text if needed, and link the selection.\n         * @param {LexicalEditor} editor Editor instance.\n         * @returns {Promise<void>} Nothing.\n         */\n        rich: async (editor) => {\n          await new Promise((resolve) => {\n            editor.update(async () => {\n              let _selection = getSelection() ?? getPreviousSelection()?.clone();\n\n              if (!isRangeSelection(_selection)) {\n                _selection = createRangeSelection();\n              }\n\n              if (!hasAnchor) {\n                anchorText = anchorText.trim();\n                anchorText ||= anchorURL;\n                insertNodes([createTextNode(anchorText)]);\n              }\n\n              setSelection(_selection);\n              resolve(undefined);\n            });\n          });\n\n          // The link applies to the selection, which the focus restores\n          await focusEditor(editor);\n          editor.dispatchCommand(\n            TOGGLE_LINK_COMMAND,\n            canSetTarget && openInNewTab ? { url: anchorURL, target: '_blank' } : anchorURL,\n          );\n        },\n        // Moved within the edit above, between inserting the text and linking it\n        focus: false,\n      });\n    }\n\n    anchorURL = '';\n    anchorText = '';\n    openInNewTab = false;\n  };\n\n  /**\n   * Open the dialog with a keyboard shortcut: Accel+K.\n   * @returns {(() => void) | undefined} Function to unregister the command.\n   */\n  const _registerCommand = () =>\n    editorStore.editor?.registerCommand(\n      KEY_DOWN_COMMAND,\n      (event) => {\n        if (matchesShortcuts(event, isMac() ? 'Meta+K' : 'Ctrl+K')) {\n          event.preventDefault();\n          onButtonClick();\n        }\n\n        return false;\n      },\n      COMMAND_PRIORITY_NORMAL,\n    );\n\n  $effect(() => {\n    const { textArea } = editorStore;\n\n    if (!textArea) {\n      return undefined;\n    }\n\n    // Handle the keyboard shortcut in the plain text mode\n    return registerRawTextShortcut(textArea, 'K', () => {\n      onButtonClick();\n    });\n  });\n\n  $effect(() => {\n    if (editorStore.editor) {\n      // Unregister on unmount, e.g. when the toolbar swaps the button out while the caret is in a\n      // code block, so the shortcut isn’t handled by a stale instance\n      return _registerCommand();\n    }\n\n    return undefined;\n  });\n</script>\n\n<Button\n  iconic\n  aria-label={_(`_sui.text_editor.${AVAILABLE_BUTTONS[type].labelKey}`)}\n  aria-controls={editorStore.controlId}\n  pressed={selectionTypeMatches && editorStore.useRichText}\n  onclick={() => {\n    onButtonClick();\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name={AVAILABLE_BUTTONS[type].icon} />\n  {/snippet}\n</Button>\n\n<Dialog\n  title={_('_sui.text_editor.insert_link')}\n  bind:open={openDialog}\n  okDisabled={!isValidURL}\n  okLabel={_('_sui.insert')}\n  restoreFocus={false}\n  onClose={(event) => {\n    onDialogClose(event);\n  }}\n>\n  <div role=\"none\">\n    <label for=\"{id}-url\">{_('_sui.text_editor.url')}</label>\n    <TextInput\n      dir=\"ltr\"\n      id=\"{id}-url\"\n      bind:value={anchorURL}\n      flex\n      invalid={!!anchorURL.trim() && !isSafeLinkURL(anchorURL)}\n      aria-label={_('_sui.text_editor.url')}\n      onkeydown={(event) => {\n        onInputKeyDown(event);\n      }}\n    />\n  </div>\n  {#if !hasAnchor}\n    <div role=\"none\">\n      <label for=\"{id}-text\">{_('_sui.text_editor.text')}</label>\n      <TextInput\n        dir=\"auto\"\n        id=\"{id}-text\"\n        bind:value={anchorText}\n        flex\n        aria-label={_('_sui.text_editor.text')}\n        onkeydown={(event) => {\n          onInputKeyDown(event);\n        }}\n      />\n    </div>\n  {/if}\n  {#if canSetTarget}\n    <div role=\"none\">\n      <Checkbox bind:checked={openInNewTab} label={_('_sui.text_editor.open_in_new_tab')} />\n    </div>\n  {/if}\n</Dialog>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { getContext } from 'svelte';\n  import Icon from '../../icon/icon.svelte';\n  import MenuButton from '../../menu/menu-button.svelte';\n  import MenuItem from '../../menu/menu-item.svelte';\n  import Menu from '../../menu/menu.svelte';\n  import { insertEditorComponent } from './actions.js';\n\n  /**\n   * @import { TextEditorComponent, TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {TextEditorComponent[]} components Editor components.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    components,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n</script>\n\n<MenuButton label={_('_sui.insert')}>\n  {#snippet endIcon()}\n    <Icon name=\"arrow_drop_down\" class=\"small-arrow\" />\n  {/snippet}\n  {#snippet popup()}\n    <Menu>\n      {#each components as component (component.id)}\n        {@const { label, icon } = component}\n        <MenuItem\n          {label}\n          onclick={() => {\n            insertEditorComponent(editorStore, component);\n          }}\n        >\n          {#snippet startIcon()}\n            {#if icon}\n              <Icon name={icon} />\n            {/if}\n          {/snippet}\n        </MenuItem>\n      {/each}\n    </Menu>\n  {/snippet}\n</MenuButton>\n","import { getMaximumFractionDigits } from '../../services/number.js';\n\n/**\n * Logic behind `<NumberInput>`, kept apart from the component so the number handling can be tested\n * without rendering anything.\n */\n\n/**\n * Step value that turns stepping off: the spin buttons are hidden and the arrow keys are ignored.\n */\nexport const STEP_DISABLED = -1;\n\n/**\n * Get the `inputmode` attribute for the field. The numeric and decimal keypads on iOS have no minus\n * key, so a field that accepts a negative number gets the full keyboard instead.\n * @param {object} options Options.\n * @param {boolean} options.fractional Whether the number can have a fraction.\n * @param {number} [options.min] Minimum allowed value.\n * @returns {'text' | 'decimal' | 'numeric'} Input mode.\n */\nexport const getInputMode = ({ fractional, min }) => {\n  if (!(typeof min === 'number' && min >= 0)) {\n    return 'text';\n  }\n\n  return fractional ? 'decimal' : 'numeric';\n};\n\n/**\n * Decimal separators of the locales looked up, keyed by locale. The separator is read on every\n * keystroke, while creating an `Intl.NumberFormat` is comparatively expensive.\n * @type {Map<string, string>}\n */\nconst decimalSeparatorCache = new Map();\n\n/**\n * Get the decimal separator of the given locale, like `,` in German.\n * @param {string | undefined} locale Locale, like `de`. If omitted, the browser’s default locale is\n * used.\n * @returns {string} Decimal separator. `.` if the locale is invalid.\n */\nexport const getDecimalSeparator = (locale) => {\n  const key = locale || '';\n  let separator = decimalSeparatorCache.get(key);\n\n  if (separator === undefined) {\n    try {\n      separator = /** @type {Intl.NumberFormatPart} */ (\n        new Intl.NumberFormat(locale || undefined)\n          .formatToParts(1.5)\n          .find(({ type }) => type === 'decimal')\n      ).value;\n    } catch {\n      separator = '.';\n    }\n\n    decimalSeparatorCache.set(key, separator);\n  }\n\n  return separator;\n};\n\n/**\n * Normalize the text entered in the field, so a number typed with the locale’s decimal separator,\n * like `1,5` in German, can be parsed as `1.5`. A period is always accepted as the decimal\n * separator, as a value set from outside is shown with one, so the text is left as is if it has\n * one, or more than one decimal separator of the locale. Thousands separators are not supported:\n * `1,500` in English, whose decimal separator is a period, remains no number.\n * @param {string} inputValue Text in the field.\n * @param {string | undefined} locale Locale of the field.\n * @returns {string} Normalized text.\n */\nexport const normalizeNumber = (inputValue, locale) => {\n  const separator = getDecimalSeparator(locale);\n\n  if (!inputValue || separator === '.' || inputValue.includes('.')) {\n    return inputValue;\n  }\n\n  const parts = inputValue.split(separator);\n\n  return parts.length === 2 ? parts.join('.') : inputValue;\n};\n\n/**\n * Parse the text entered in the field.\n * @param {string} inputValue Text in the field.\n * @returns {number | undefined} Number, or `undefined` if the field is empty or holds no number.\n */\nexport const parseNumber = (inputValue) => {\n  const value = inputValue.trim() ? Number(inputValue) : NaN;\n\n  return Number.isNaN(value) ? undefined : value;\n};\n\n/**\n * Get the number the field currently represents for range checks: an empty field counts as zero,\n * so the spin buttons and the arrow keys have something to step from.\n * @param {string} inputValue Text in the field.\n * @returns {number} Number, possibly `NaN`.\n */\nconst toNumber = (inputValue) => Number(inputValue || 0);\n\n/**\n * Whether the field is at or below the minimum, if any.\n * @param {string} inputValue Text in the field.\n * @param {number | undefined} min Minimum allowed value.\n * @returns {boolean} Result.\n */\nexport const isAtMin = (inputValue, min) => typeof min === 'number' && toNumber(inputValue) <= min;\n\n/**\n * Whether the field is at or above the maximum, if any.\n * @param {string} inputValue Text in the field.\n * @param {number | undefined} max Maximum allowed value.\n * @returns {boolean} Result.\n */\nexport const isAtMax = (inputValue, max) => typeof max === 'number' && toNumber(inputValue) >= max;\n\n/**\n * Step the number in the field up or down.\n * @param {string} inputValue Text in the field.\n * @param {object} options Options.\n * @param {number} options.step Amount to add or subtract.\n * @param {1 | -1} options.direction `1` to increase, `-1` to decrease.\n * @param {number} [options.min] Minimum allowed value.\n * @param {number} [options.max] Maximum allowed value.\n * @returns {string | undefined} New text for the field, clamped to the range, or `undefined` if\n * the field holds no number or is already at the limit in that direction, in which case it’s left\n * as is.\n */\nexport const stepNumber = (inputValue, { step, direction, min, max }) => {\n  if (Number.isNaN(Number(inputValue))) {\n    return undefined;\n  }\n\n  if (direction > 0 ? isAtMax(inputValue, max) : isAtMin(inputValue, min)) {\n    return undefined;\n  }\n\n  // Snap to the step grid, which starts at the minimum if any, otherwise at zero, as the native\n  // `<input type=\"number\">` does: with a step of `1`, `2.5` goes up to `3` and down to `2` rather\n  // than moving by the full step and then being rounded\n  const base = typeof min === 'number' ? min : 0;\n\n  const maximumFractionDigits = Math.max(\n    getMaximumFractionDigits(step),\n    getMaximumFractionDigits(base),\n  );\n\n  const position = (toNumber(inputValue) - base) / step;\n  const nearestPosition = Math.round(position);\n  // Allow for floating-point errors, like `(0.3 - 0) / 0.1` being `2.9999999999999996`\n  const isOnGrid = Math.abs(position - nearestPosition) < 1e-9;\n  let newPosition;\n\n  if (isOnGrid) {\n    newPosition = nearestPosition + direction;\n  } else {\n    newPosition = direction > 0 ? Math.ceil(position) : Math.floor(position);\n  }\n\n  const newValue = Number((base + newPosition * step).toFixed(maximumFractionDigits));\n\n  // Stop at the limit rather than stepping past it, as the native `<input type=\"number\">` does\n  if (typeof max === 'number' && newValue > max) {\n    return String(max);\n  }\n\n  if (typeof min === 'number' && newValue < min) {\n    return String(min);\n  }\n\n  return newValue.toFixed(maximumFractionDigits);\n};\n\n/**\n * Check whether the field content is invalid.\n * @param {string} inputValue Text in the field.\n * @param {object} options Options.\n * @param {boolean} [options.required] Whether a value is required.\n * @param {number} [options.min] Minimum allowed value.\n * @param {number} [options.max] Maximum allowed value.\n * @returns {boolean} `true` if the field is empty while required, holds something other than a\n * number, or holds a number outside the allowed range.\n */\nexport const isInvalidNumber = (inputValue, { required = false, min, max } = {}) => {\n  if (required && (parseNumber(inputValue) === undefined || inputValue === '')) {\n    return true;\n  }\n\n  if (inputValue === undefined || inputValue === '') {\n    return false;\n  }\n\n  const value = Number(inputValue);\n\n  return (\n    Number.isNaN(value) ||\n    (typeof min === 'number' && toNumber(inputValue) < min) ||\n    (typeof max === 'number' && toNumber(inputValue) > max)\n  );\n};\n","<!--\n  @component\n  The equivalent of the HTML `<input type=\"number\">` element.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number\n  @see https://w3c.github.io/aria/#textbox\n-->\n<script>\n  import { _, locale } from '@sveltia/i18n';\n  import { untrack } from 'svelte';\n  import { getLabelAboveText } from '../../services/label.js';\n  import { hasModifier } from '../../services/navigation.js';\n  import { getMaximumFractionDigits, normalizeStep } from '../../services/number.js';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import LabelAbove from '../util/label-above.svelte';\n  import {\n    STEP_DISABLED,\n    getInputMode,\n    isAtMax,\n    isAtMin,\n    isInvalidNumber,\n    normalizeNumber,\n    parseNumber,\n    stepNumber,\n  } from './number-input.js';\n  import TextInput from './text-input.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import {\n   * CommonEventHandlers,\n   * InputEventHandlers,\n   * LabelAboveProps,\n   * TextInputProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {number} [value] Input value.\n   * @property {number} [min] Minimum allowed value.\n   * @property {number} [max] Maximum allowed value.\n   * @property {number} [step] Value to be added or removed when using the up/down arrow key or\n   * button. Set to `-1` to hide the buttons and disable stepping with the arrow keys, for a number\n   * that isn’t meant to be stepped, like an ID. Any other value that isn’t a positive number falls\n   * back to `1`.\n   * @property {boolean} [fractional] Whether the number can have a fraction, which brings up the\n   * decimal keypad rather than the numeric one on mobile. If omitted, it’s inferred from `step`:\n   * `true` for a fractional step or with stepping turned off, `false` for an integer step.\n   * @property {'text' | 'decimal' | 'numeric'} [inputmode] The `inputmode` attribute on the\n   * `<input>`. If omitted, it’s `text` if a negative number is allowed, as the numeric and decimal\n   * keypads on iOS have no minus key, otherwise `decimal` or `numeric` depending on `fractional`.\n   * @property {Snippet} [increaseIcon] Increase icon slot content.\n   * @property {Snippet} [decreaseIcon] Decrease icon slot content.\n   */\n\n  /**\n   * @type {LabelAboveProps & TextInputProps & CommonEventHandlers & InputEventHandlers & Props &\n   * Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    invalid = $bindable(false),\n    element = $bindable(),\n    flex = false,\n    min = undefined,\n    max = undefined,\n    step = 1,\n    fractional = undefined,\n    inputmode = undefined,\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    showLabelAbove = false,\n    children,\n    increaseIcon,\n    decreaseIcon,\n    onkeydown,\n    oninput,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n  /**\n   * Label shown above the field with `showLabelAbove`. It’s rendered here rather than by the\n   * `<TextInput>`, so the spin buttons stay on the field rather than spanning the label too.\n   */\n  const labelAbove = $derived(getLabelAboveText({ showLabelAbove, props: restProps }));\n\n  let edited = $state(false);\n  let inputValue = $state('');\n\n  // `-1` turns stepping off altogether, leaving a plain text box: a spin button promises the arrow\n  // keys step the value\n  const stepEnabled = $derived(step !== STEP_DISABLED);\n  const stepSize = $derived(normalizeStep(step));\n  const isFractional = $derived(\n    fractional ?? (!stepEnabled || getMaximumFractionDigits(stepSize) > 0),\n  );\n  // A plain text box can’t expose the range with `aria-valuemin` and `aria-valuemax`, so it’s\n  // described instead, by a hidden element: `aria-description` isn’t supported everywhere\n  const rangeDescription = $derived.by(() => {\n    const hasMin = typeof min === 'number';\n    const hasMax = typeof max === 'number';\n\n    if (stepEnabled || (!hasMin && !hasMax)) {\n      return undefined;\n    }\n\n    if (hasMin && hasMax) {\n      return _('_sui.number_input.range', { values: { min, max } });\n    }\n\n    return hasMin\n      ? _('_sui.number_input.min', { values: { min } })\n      : _('_sui.number_input.max', { values: { max } });\n  });\n  const describedBy = $derived(\n    [restProps['aria-describedby'], rangeDescription ? `${id}-range` : undefined]\n      .filter(Boolean)\n      .join(' ') || undefined,\n  );\n  // Accept the decimal separator of the field’s language, or that of the UI, like `,` in German\n  const numberValue = $derived(normalizeNumber(inputValue, restProps.lang ?? locale.current));\n  const isMin = $derived(isAtMin(numberValue, min));\n  const isMax = $derived(isAtMax(numberValue, max));\n\n  $effect(() => {\n    const newValue = value;\n\n    // Only overwrite the field when it doesn’t already hold the value, so text that is still being\n    // typed, like `1.` or `-`, isn’t wiped out when it parses to the same number or no number\n    untrack(() => {\n      if (parseNumber(numberValue) !== newValue) {\n        inputValue = String(newValue ?? '');\n      }\n    });\n  });\n\n  $effect(() => {\n    value = parseNumber(numberValue);\n  });\n\n  $effect(() => {\n    if (edited) {\n      invalid = isInvalidNumber(numberValue, { required, min, max });\n    }\n  });\n\n  /**\n   * Step the number up or down, unless the field holds no number or is already at the limit.\n   * @param {1 | -1} direction `1` to increase, `-1` to decrease.\n   */\n  const stepValue = (direction) => {\n    const newInputValue = stepNumber(numberValue, { step: stepSize, direction, min, max });\n\n    if (newInputValue === undefined) {\n      return;\n    }\n\n    inputValue = newInputValue;\n\n    if (element) {\n      // Fire the `input` and `change` events, as the native `<input type=\"number\">` does when\n      // stepped, so a consumer listening for them rather than binding the value sees the change\n      element.value = newInputValue;\n      element.dispatchEvent(new Event('input', { bubbles: true }));\n      element.dispatchEvent(new Event('change', { bubbles: true }));\n    }\n  };\n\n  /**\n   * Decrease the number.\n   */\n  const decrease = () => {\n    stepValue(-1);\n  };\n\n  /**\n   * Increase the number.\n   */\n  const increase = () => {\n    stepValue(1);\n  };\n</script>\n\n<div\n  role=\"none\"\n  class=\"sui number-input {className}\"\n  class:flex\n  class:disabled\n  class:readonly\n  class:stepper={stepEnabled}\n  class:has-label-above={!!labelAbove}\n  {hidden}\n>\n  {#if labelAbove}\n    <LabelAbove label={labelAbove} for={id} />\n  {/if}\n  {#if stepEnabled}\n    <div role=\"none\" class=\"buttons\">\n      <Button\n        iconic\n        disabled={disabled || readonly || Number.isNaN(Number(numberValue)) || isMax}\n        aria-label={_('_sui.number_input.increase')}\n        aria-controls={id}\n        onclick={() => {\n          increase();\n        }}\n      >\n        {#snippet startIcon()}\n          {#if increaseIcon}\n            {@render increaseIcon()}\n          {:else}\n            <Icon name=\"expand_less\" />\n          {/if}\n        {/snippet}\n      </Button>\n      <Button\n        iconic\n        disabled={disabled || readonly || Number.isNaN(Number(numberValue)) || isMin}\n        aria-label={_('_sui.number_input.decrease')}\n        aria-controls={id}\n        onclick={() => {\n          decrease();\n        }}\n      >\n        {#snippet startIcon()}\n          {#if decreaseIcon}\n            {@render decreaseIcon()}\n          {:else}\n            <Icon name=\"expand_more\" />\n          {/if}\n        {/snippet}\n      </Button>\n    </div>\n  {:else if rangeDescription}\n    <span id=\"{id}-range\" hidden>{rangeDescription}</span>\n  {/if}\n  <TextInput\n    dir=\"ltr\"\n    {...restProps}\n    role={stepEnabled ? 'spinbutton' : 'textbox'}\n    {id}\n    bind:element\n    bind:value={inputValue}\n    spellcheck=\"false\"\n    {flex}\n    {hidden}\n    {disabled}\n    {readonly}\n    {required}\n    {invalid}\n    aria-valuenow={stepEnabled && Number.isFinite(value) ? value : undefined}\n    aria-valuemin={stepEnabled ? min : undefined}\n    aria-valuemax={stepEnabled ? max : undefined}\n    inputmode={inputmode ?? getInputMode({ fractional: isFractional, min })}\n    aria-describedby={describedBy}\n    onkeydown={(event) => {\n      const { key } = event;\n      // A read-only field can’t be stepped, just like the spin buttons\n      const canStep = stepEnabled && !disabled && !readonly && !hasModifier(event);\n\n      if (key === 'ArrowDown' && canStep) {\n        event.preventDefault();\n        decrease();\n      }\n\n      if (key === 'ArrowUp' && canStep) {\n        event.preventDefault();\n        increase();\n      }\n\n      if (!edited) {\n        edited = true;\n      }\n\n      onkeydown?.(event);\n    }}\n    oninput={(event) => {\n      if (!edited) {\n        edited = true;\n      }\n\n      oninput?.(event);\n    }}\n  />\n</div>\n\n<style>.number-input {\n  display: inline-flex;\n  align-items: center;\n  position: relative;\n  margin: var(--sui-focus-ring-width);\n  min-width: var(--sui-textbox-singleline-min-width);\n}\n.number-input.stepper {\n  --sui-number-input-end-padding: 24px;\n}\n.number-input.flex:not([hidden]) {\n  display: inline-flex;\n  width: -moz-available;\n  width: -webkit-fill-available;\n  width: stretch;\n  min-width: 0;\n}\n.number-input.has-label-above:not([hidden]) {\n  display: inline-grid;\n  grid-template-columns: 1fr;\n}\n.number-input.has-label-above:not([hidden]) :global(.text-input) {\n  width: auto;\n}\n.number-input.has-label-above .buttons {\n  inset-block-start: auto;\n  height: calc(var(--sui-textbox-height) - 4px);\n}\n.number-input:not(.disabled) :global(button[aria-disabled='true']) {\n  filter: grayscale(0) opacity(1);\n}\n.number-input:not(.disabled) :global(button[aria-disabled='true']) :global(*) {\n  filter: grayscale(1) opacity(var(--sui-disabled-opacity, 0.35));\n}\n.number-input :global(input) {\n  padding-right: var(--sui-number-input-end-padding, 8px);\n}\n.number-input :global(.text-input) {\n  flex: auto;\n  margin: 0 !important;\n  width: 0;\n  min-width: 0 !important;\n}\n\n.buttons {\n  display: flex;\n  flex-direction: column;\n  position: absolute;\n  inset-block: 2px;\n  right: 2px;\n  z-index: 3;\n  width: 18px;\n}\n.buttons :global(button) {\n  flex: none;\n  margin: 0 !important;\n  border-width: 0;\n  border-radius: 3px;\n  padding: 0;\n  width: 100%;\n  height: 50%;\n  min-height: 0;\n}\n.buttons :global(button) :global(.icon) {\n  font-size: 16px;\n}\n\n.number-input:dir(rtl) {\n  --sui-textbox-text-align: right;\n}\n.number-input:dir(rtl) .buttons {\n  right: auto;\n  left: 2px;\n}\n.number-input:dir(rtl) :global(input) {\n  padding-right: 8px;\n  padding-left: var(--sui-number-input-end-padding, 8px);\n}</style>\n","<!--\n  @component\n  Toolbar button to insert a table. It opens a dialog to choose the number of rows and columns, then\n  inserts an empty table with a header row: a table node in the rich text mode, or its Markdown in\n  the plain text mode.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { matchesShortcuts } from '@sveltia/utils/events';\n  import { getContext } from 'svelte';\n  import Button from '../../button/button.svelte';\n  import Dialog from '../../dialog/dialog.svelte';\n  import Icon from '../../icon/icon.svelte';\n  import NumberInput from '../../text-field/number-input.svelte';\n  import { AVAILABLE_BUTTONS, DEFAULT_TABLE_SIZE, MAX_TABLE_SIZE } from '../constants.js';\n  import { editRawText, insertMarkdown } from '../editing/raw-markdown.js';\n  import {\n    $insertTable as insertTable,\n    createTableMarkdown,\n    parseTableSize,\n  } from '../editing/table.js';\n  import { refocusEditor, runEditorAction } from './actions.js';\n\n  /**\n   * @import { LexicalEditor } from 'lexical';\n   * @import { TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * Number of rows, including the header row, and columns of a new table.\n   * @typedef {{ rows: number, columns: number }} TableSize\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [disabled] Whether to disable the button, like when the caret is already in\n   * a table, as tables can’t be nested.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    disabled = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  let openDialog = $state(false);\n  /** @type {number | undefined} */\n  let rows = $state(DEFAULT_TABLE_SIZE);\n  /** @type {number | undefined} */\n  let columns = $state(DEFAULT_TABLE_SIZE);\n\n  const rowCount = $derived(parseTableSize(rows));\n  const columnCount = $derived(parseTableSize(columns));\n  const isValid = $derived(!!rowCount && !!columnCount);\n\n  /**\n   * Open the dialog. The size last chosen is kept, unless it was left invalid when the dialog was\n   * canceled.\n   */\n  const onButtonClick = () => {\n    if (!rowCount) {\n      rows = DEFAULT_TABLE_SIZE;\n    }\n\n    if (!columnCount) {\n      columns = DEFAULT_TABLE_SIZE;\n    }\n\n    openDialog = true;\n  };\n\n  /**\n   * Handle `keydown` event fired on the input fields on the dialog: insert the table with Enter.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  const onInputKeyDown = (event) => {\n    if (matchesShortcuts(event, 'Enter') && isValid) {\n      openDialog = false;\n    }\n  };\n\n  /**\n   * Insert the table: a table node into the rich text editor, then move the focus back to it, or\n   * the table’s Markdown into the `<textarea>`. Either way, the caret ends up in the first cell.\n   * @param {TableSize} size Table size.\n   * @returns {Promise<void>} Nothing.\n   */\n  const insert = ({ rows: rowSize, columns: columnSize }) =>\n    runEditorAction(editorStore, {\n      /**\n       * Insert the table’s Markdown, with the caret in the first cell.\n       * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n       * @returns {void | Promise<void>} Nothing.\n       */\n      raw: (textArea) => {\n        const markdown = createTableMarkdown(rowSize, columnSize);\n\n        return editRawText(textArea, (state) => {\n          const edit = insertMarkdown(state, markdown, { block: true });\n          // Right after the leading pipe and space of the first cell\n          const caret = edit.start + edit.text.indexOf(markdown) + 2;\n\n          return { ...edit, selectionStart: caret, selectionEnd: caret };\n        });\n      },\n      /**\n       * Insert a table node.\n       * @param {LexicalEditor} editor Editor instance.\n       */\n      rich: (editor) => {\n        editor.update(() => {\n          insertTable(rowSize, columnSize);\n        });\n      },\n    });\n\n  /**\n   * Handle `close` event fired on the dialog. Insert the table unless the dialog has been canceled.\n   * @param {CustomEvent} event `close` event.\n   */\n  const onDialogClose = async (event) => {\n    const canceled = event.detail.returnValue === 'cancel';\n\n    if (!canceled && rowCount && columnCount) {\n      await insert({ rows: rowCount, columns: columnCount });\n    } else {\n      // The dialog leaves the focus alone (see `restoreFocus` below), so bring it back here\n      await refocusEditor(editorStore);\n    }\n  };\n</script>\n\n<Button\n  iconic\n  {disabled}\n  aria-label={_(`_sui.text_editor.${AVAILABLE_BUTTONS.table.labelKey}`)}\n  aria-controls={editorStore.controlId}\n  onclick={() => {\n    onButtonClick();\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name={AVAILABLE_BUTTONS.table.icon} />\n  {/snippet}\n</Button>\n\n<Dialog\n  size=\"x-small\"\n  title={_('_sui.text_editor.insert_table')}\n  bind:open={openDialog}\n  okDisabled={!isValid}\n  okLabel={_('_sui.insert')}\n  restoreFocus={false}\n  onClose={(event) => {\n    onDialogClose(event);\n  }}\n>\n  <div role=\"none\" class=\"table-size\">\n    <label for=\"{id}-rows\">{_('_sui.text_editor.rows')}</label>\n    <NumberInput\n      id=\"{id}-rows\"\n      bind:value={rows}\n      min={1}\n      max={MAX_TABLE_SIZE}\n      invalid={!rowCount}\n      aria-label={_('_sui.text_editor.rows')}\n      onkeydown={(event) => {\n        onInputKeyDown(event);\n      }}\n    />\n    <label for=\"{id}-columns\">{_('_sui.text_editor.columns')}</label>\n    <NumberInput\n      id=\"{id}-columns\"\n      bind:value={columns}\n      min={1}\n      max={MAX_TABLE_SIZE}\n      invalid={!columnCount}\n      aria-label={_('_sui.text_editor.columns')}\n      onkeydown={(event) => {\n        onInputKeyDown(event);\n      }}\n    />\n  </div>\n</Dialog>\n\n<style>.table-size {\n  display: grid;\n  grid-template-columns: auto 1fr;\n  align-items: center;\n  gap: 8px 16px;\n}</style>\n","<script>\n  import { $createCodeNode as createCodeNode } from '@lexical/code-core';\n  import {\n    $createHeadingNode as createHeadingNode,\n    $createQuoteNode as createQuoteNode,\n  } from '@lexical/rich-text';\n  import { $setBlocksType as setBlocksType } from '@lexical/selection';\n  import { _ } from '@sveltia/i18n';\n  import {\n    $createParagraphNode as createParagraphNode,\n    $getSelection as getSelection,\n  } from 'lexical';\n  import { getContext } from 'svelte';\n  import Icon from '../../icon/icon.svelte';\n  import MenuItemCheckbox from '../../menu/menu-item-checkbox.svelte';\n  import { AVAILABLE_BUTTONS, LIST_TYPES } from '../constants.js';\n  import { editRawText, setBlockType } from '../editing/raw-markdown.js';\n  import { runEditorAction } from './actions.js';\n\n  /**\n   * @import { TextEditorBlockType, TextEditorStore } from '../../../typedefs.js';\n   * @import { HeadingTagType } from '@lexical/rich-text';\n   * @import { ElementNode, LexicalEditor } from 'lexical';\n   */\n\n  /**\n   * Node factories for the block types applied with `$setBlocksType()`, except headings, whose\n   * level is parsed from the type.\n   * @type {Record<string, () => ElementNode>}\n   */\n  const NODE_FACTORIES = {\n    paragraph: createParagraphNode,\n    blockquote: createQuoteNode,\n    'code-block': createCodeNode,\n  };\n\n  /**\n   * @typedef {object} Props\n   * @property {TextEditorBlockType} type Button type.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    type,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n  const selectionTypeMatches = $derived(editorStore.selection.blockType === type);\n\n  /**\n   * Change the current selection’s type to {@link type}.\n   * @returns {Promise<void>} Nothing.\n   */\n  const changeBlockType = () =>\n    runEditorAction(editorStore, {\n      /**\n       * Change the block type in the Markdown.\n       * @param {HTMLTextAreaElement} textArea `<textarea>` element.\n       * @returns {void | Promise<void>} Nothing.\n       */\n      raw: (textArea) => editRawText(textArea, (state) => setBlockType(state, type)),\n      /**\n       * Change the block type of the selection.\n       * @param {LexicalEditor} editor Editor instance.\n       */\n      rich: (editor) => {\n        const [, headingLevel] = type.match(/^heading-(\\d)$/) ?? [];\n\n        const createNode = headingLevel\n          ? () => createHeadingNode(/** @type {HeadingTagType} */ (`h${headingLevel}`))\n          : NODE_FACTORIES[type];\n\n        if (createNode) {\n          editor.update(() => {\n            setBlocksType(getSelection(), createNode);\n          });\n        }\n\n        // A list is toggled by its command instead\n        const list = LIST_TYPES.find((item) => item.type === type);\n\n        if (list) {\n          editor.dispatchCommand(list.command, undefined);\n        }\n      },\n      // The block type applies to the selection, which the focus restores\n      focus: 'before',\n    });\n</script>\n\n{#key selectionTypeMatches}\n  <MenuItemCheckbox\n    label={_(`_sui.text_editor.${AVAILABLE_BUTTONS[type].labelKey}`)}\n    checked={selectionTypeMatches}\n    onclick={() => {\n      if (!selectionTypeMatches) {\n        changeBlockType();\n      }\n    }}\n  >\n    {#snippet startIcon()}\n      <Icon name={AVAILABLE_BUTTONS[type].icon} />\n    {/snippet}\n  </MenuItemCheckbox>\n{/key}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { unique } from '@sveltia/utils/array';\n  import { getContext } from 'svelte';\n  import ButtonGroup from '../../button/button-group.svelte';\n  import Button from '../../button/button.svelte';\n  import Divider from '../../divider/divider.svelte';\n  import Spacer from '../../divider/spacer.svelte';\n  import Icon from '../../icon/icon.svelte';\n  import MenuButton from '../../menu/menu-button.svelte';\n  import Menu from '../../menu/menu.svelte';\n  import {\n    AVAILABLE_BUTTONS,\n    BLOCK_BUTTON_TYPES,\n    INLINE_BUTTON_TYPES,\n    isHtmlOnlyButton,\n  } from '../constants.js';\n  import { getEditorSetup } from '../config.js';\n  import { isInlineComponent } from '../conversion/editor-components.js';\n  import CodeLanguageSwitcher from './code-language-switcher.svelte';\n  import AlignMenuButton from './align-menu-button.svelte';\n  import FormatTextButton from './format-text-button.svelte';\n  import InsertHorizontalRuleButton from './insert-horizontal-rule-button.svelte';\n  import InsertItemButton from './insert-item-button.svelte';\n  import InsertLinkButton from './insert-link-button.svelte';\n  import InsertMenuButton from './insert-menu-button.svelte';\n  import InsertTableButton from './insert-table-button.svelte';\n  import TableActionMenu from './table-action-menu.svelte';\n  import ToggleBlockMenuItem from './toggle-block-menu-item.svelte';\n  import ToolbarWrapper from './toolbar-wrapper.svelte';\n\n  /**\n   * @import {\n   * TextEditorBlockType,\n   * TextEditorInlineType,\n   * TextEditorStore,\n   * } from '../../../typedefs.js';\n   * @import { NormalizedEditorConfig } from '../config.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\n   * @property {boolean} [readonly] Whether to make the widget read-only. An alias of the\n   * `aria-readonly` attribute.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    disabled = false,\n    readonly = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {TextEditorStore} */\n  const editorStore = getContext('editorStore');\n\n  /**\n   * Enabled block level buttons.\n   * @type {TextEditorBlockType[]}\n   */\n  const blockLevelButtons = $derived(\n    unique([\n      'paragraph', // Always needed\n      ...editorStore.config.enabledButtons.filter((type) =>\n        BLOCK_BUTTON_TYPES.includes(/** @type {any} */ (type)),\n      ),\n    ]),\n  );\n\n  const isHtml = $derived(editorStore.config.format === 'html');\n  /**\n   * Whether the formatting buttons are available. They insert Markdown syntax in the plain text\n   * mode, so they’re hidden while the HTML source is edited.\n   */\n  const canFormat = $derived(editorStore.useRichText || !isHtml);\n\n  /**\n   * Whether the HTML-only buttons, like underline and the alignment menu, are available. Markdown\n   * has no syntax for them, so they’re only available for HTML, and only in the rich text mode, as\n   * the plain text mode shows the source.\n   */\n  const canUseHtmlOnlyButtons = $derived(isHtml && editorStore.useRichText);\n\n  // The store holds the configuration normalized\n  const { hasTable, hasHorizontalRule } = $derived(\n    getEditorSetup(/** @type {NormalizedEditorConfig} */ (editorStore.config)),\n  );\n  const canAlign = $derived(\n    canUseHtmlOnlyButtons && editorStore.config.enabledButtons.includes('align'),\n  );\n  /**\n   * Key of the table cell the caret is in, if any. The table menu only works with the rich text\n   * editor.\n   */\n  const tableCellKey = $derived(\n    editorStore.useRichText ? (editorStore.selection.tableCellKey ?? null) : null,\n  );\n  /**\n   * Whether the caret is in a Markdown table cell, which can only have inline content, so neither\n   * a horizontal rule nor a block editor component can be inserted.\n   */\n  const inMarkdownTable = $derived(!!tableCellKey && !isHtml);\n  /**\n   * Editor components that can be inserted at the caret: only the inline ones in a Markdown table\n   * cell.\n   */\n  const components = $derived(\n    inMarkdownTable\n      ? editorStore.config.components.filter(isInlineComponent)\n      : editorStore.config.components,\n  );\n  const buttons = $derived(components.filter(({ trigger = 'menuitem' }) => trigger === 'button'));\n  const menuitems = $derived(\n    components.filter(({ trigger = 'menuitem' }) => trigger === 'menuitem'),\n  );\n  /**\n   * Whether any of the buttons to insert a table, a horizontal rule or an editor component is\n   * shown.\n   */\n  const hasInsertButtons = $derived(\n    hasTable || (!inMarkdownTable && hasHorizontalRule) || components.length > 0,\n  );\n  /**\n   * Whether the block level styles are available.\n   */\n  const canChangeBlock = $derived(canFormat && !inMarkdownTable);\n\n  /**\n   * Enabled inline level buttons, leaving out the HTML-only ones, like underline, when they’re not\n   * available.\n   * @type {TextEditorInlineType[]}\n   */\n  const inlineLevelButtons = $derived(\n    unique(\n      editorStore.config.enabledButtons.filter(\n        (type) =>\n          INLINE_BUTTON_TYPES.includes(/** @type {any} */ (type)) &&\n          (canUseHtmlOnlyButtons || !isHtmlOnlyButton(type)),\n      ),\n    ),\n  );\n</script>\n\n<!-- Disabled while an editor component has focus, as the buttons only apply to this editor -->\n<ToolbarWrapper\n  disabled={disabled || readonly || editorStore.componentHasFocus}\n  ariaLabel={_('_sui.text_editor.text_editor')}\n>\n  {#if canChangeBlock && blockLevelButtons.length > 1}\n    <MenuButton\n      aria-label={_('_sui.text_editor.show_text_style_options')}\n      aria-controls={editorStore.controlId}\n    >\n      {#snippet startIcon()}\n        <Icon\n          name={AVAILABLE_BUTTONS[editorStore.selection.blockType]?.icon ?? 'format_paragraph'}\n        />\n      {/snippet}\n      {#snippet popup()}\n        <Menu ariaLabel={_('_sui.text_editor.text_style_options')}>\n          {#each blockLevelButtons as type (type)}\n            <ToggleBlockMenuItem {type} />\n          {/each}\n        </Menu>\n      {/snippet}\n    </MenuButton>\n  {/if}\n  <!-- The language switcher only works with the rich text editor -->\n  {#if editorStore.useRichText && editorStore.selection.blockType === 'code-block'}\n    <Divider orientation=\"vertical\" />\n    <CodeLanguageSwitcher />\n  {:else if canFormat}\n    {#if hasTable && tableCellKey}\n      {#if canChangeBlock && blockLevelButtons.length > 1}\n        <Divider orientation=\"vertical\" />\n      {/if}\n      <MenuButton\n        aria-label={_('_sui.text_editor.show_table_options')}\n        aria-controls={editorStore.controlId}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"table_edit\" />\n        {/snippet}\n        {#snippet popup()}\n          <TableActionMenu cellKey={tableCellKey} />\n        {/snippet}\n      </MenuButton>\n    {/if}\n    {#if inlineLevelButtons.length}\n      <Divider orientation=\"vertical\" />\n      <ButtonGroup>\n        {#each inlineLevelButtons as type (type)}\n          {#if type === 'link'}\n            <InsertLinkButton />\n          {:else}\n            <FormatTextButton {type} />\n          {/if}\n        {/each}\n      </ButtonGroup>\n    {/if}\n    {#if canAlign}\n      <Divider orientation=\"vertical\" />\n      <AlignMenuButton />\n    {/if}\n    {#if hasInsertButtons}\n      <Divider orientation=\"vertical\" />\n      {#if hasTable}\n        <!-- Tables can’t be nested -->\n        <InsertTableButton disabled={!!tableCellKey} />\n      {/if}\n      {#if hasHorizontalRule && !inMarkdownTable}\n        <InsertHorizontalRuleButton />\n      {/if}\n      {#each buttons as button (button.id)}\n        <InsertItemButton component={button} />\n      {/each}\n      {#if menuitems.length}\n        <InsertMenuButton components={menuitems} />\n      {/if}\n    {/if}\n  {/if}\n  <Spacer flex />\n  {#if editorStore.config.modes.length > 1}\n    <Button\n      iconic\n      disabled={editorStore.hasConverterError}\n      pressed={!editorStore.useRichText}\n      aria-label={_(`_sui.text_editor.${isHtml ? 'edit_in_html' : 'edit_in_markdown'}`)}\n      onclick={() => {\n        // The source shows the value, which has to include what was just typed\n        if (editorStore.useRichText) {\n          editorStore.flushExport();\n        }\n\n        editorStore.useRichText = !editorStore.useRichText;\n\n        if (editorStore.useRichText) {\n          editorStore.convertToLexical();\n        }\n      }}\n    >\n      {#snippet startIcon()}\n        <Icon name={isHtml ? 'html' : 'markdown'} />\n      {/snippet}\n    </Button>\n  {/if}\n</ToolbarWrapper>\n","<!--\n  @component\n  A rich text editor based on Lexical.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { setContext, untrack } from 'svelte';\n  import Alert from '../alert/alert.svelte';\n  import TextArea from '../text-field/text-area.svelte';\n  import Toast from '../toast/toast.svelte';\n  import { getEditorSetup } from './config.js';\n  import { DEFAULT_BUTTON_TYPES } from './constants.js';\n  import EmojiAutocomplete from './widgets/emoji-autocomplete.svelte';\n  import FloatingLinkEditor from './widgets/floating-link-editor.svelte';\n  import LexicalRoot from './lexical-root.svelte';\n  import TableCellMenuButton from './widgets/table-cell-menu-button.svelte';\n  import { registerRawTextSelection, registerRawTextSingleLine } from './editing/raw-markdown.js';\n  import { createSourceHighlighter } from './shiki/source-highlight.svelte.js';\n  import { createEditorStore, syncEditorProps } from './store.svelte.js';\n  import TextEditorToolbar from './toolbar/text-editor-toolbar.svelte';\n\n  /**\n   * @import {\n   * EditorCommonProps,\n   * FormFieldStateProps,\n   * TextEditorComponent,\n   * TextEditorMode,\n   * TextEditorNodeType,\n   * TextEditorValueFormat,\n   * WidgetStateProps,\n   * } from '../../typedefs.js';\n   * @import { NormalizedEditorConfig } from './config.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [value] Input value in the {@link format}. A value set from outside\n   * is kept as is until the user changes the content, although the rich text editor writes Markdown\n   * or HTML in its own style, such as `_text_` for `*text*` or `<strong>` for `<b>`.\n   * @property {TextEditorValueFormat} [format] Format of the {@link value}: `markdown` or `html`.\n   * With `html`, the plain text mode shows the HTML source, and editor components have to\n   * implement `importDOM` and `exportDOM` for their nodes. HTML with an element the editor cannot\n   * handle, like `<img>`, can only be edited in the plain text mode. Attributes not used by the\n   * editor, like `class`, are dropped once the content is changed in the rich text mode.\n   * @property {boolean} [pending] Whether the user has changed the rich text content, and the\n   * editor has yet to update {@link value}, which it does a moment later. Bind it to wait for the\n   * change before reading the value, for example to save it. Read-only.\n   * @property {'ltr' | 'rtl' | 'auto'} [dir] The `dir` attribute on the editable text box, both\n   * the rich text editor and the `<textarea>` element of the plain text mode.\n   * @property {TextEditorMode[]} [modes] Enabled modes.\n   * @property {TextEditorNodeType[]} [buttons] Enabled buttons. All the inline and block level\n   * buttons by default, except the HTML-only `underline`.\n   * @property {TextEditorComponent[]} [components] Editor components.\n   * @property {boolean} [multiline] Whether the content can span multiple paragraphs and lines.\n   * With `false`, the content is kept in a single paragraph: the Enter key does nothing, and the\n   * paragraphs and lines of pasted or imported content are joined with spaces. Only the inline\n   * buttons and the editor components with a text match transformer are enabled then, horizontal\n   * rules and tables in Markdown are kept as text, and the HTML format has no plain text mode.\n   * @property {boolean} [minimal] Whether to make the editor compact: it starts with the height of\n   * a single line, like a single-line editor, and stops growing at 240 pixels, scrolling the\n   * content beyond that.\n   * @property {boolean} [useMarkdownShortcuts] Whether to enable Markdown keyboard shortcuts in the\n   * rich text editor.\n   * @property {boolean} [useEmojiAutocomplete] Whether to autocomplete emojis when the user\n   * types a shortcode, like `:smi`.\n   */\n\n  /**\n   * @type {EditorCommonProps & WidgetStateProps & FormFieldStateProps & Props &\n   * Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(''),\n    pending = $bindable(false),\n    format = 'markdown',\n    flex = false,\n    dir = undefined,\n    modes = ['rich-text', 'plain-text'],\n    buttons = [...DEFAULT_BUTTON_TYPES],\n    components = [],\n    multiline = true,\n    minimal = false,\n    useMarkdownShortcuts = true,\n    useEmojiAutocomplete = true,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    ariaLabel = undefined,\n    ariaLabelledby = undefined,\n    ariaDescribedby = undefined,\n    'aria-label': ariaLabelAttr = undefined,\n    'aria-labelledby': ariaLabelledbyAttr = undefined,\n    'aria-describedby': ariaDescribedbyAttr = undefined,\n    // Not rendered, but kept out of `restProps`, which go on the wrapper element\n    children: _children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Labelling attributes for the editable text box. They’re pulled out of `restProps` because the\n   * rest goes on the presentational wrapper, where ARIA would ignore them.\n   */\n  const labelAttrs = $derived({\n    'aria-label': ariaLabel ?? ariaLabelAttr,\n    'aria-labelledby': ariaLabelledby ?? ariaLabelledbyAttr,\n    'aria-describedby': ariaDescribedby ?? ariaDescribedbyAttr,\n  });\n\n  /** Whether the user can change the content, which the widgets below are only shown for. */\n  const editable = $derived(!disabled && !readonly);\n\n  const editorStore = createEditorStore();\n\n  // svelte-ignore state_referenced_locally\n  editorStore.config = {\n    ...editorStore.config,\n    modes,\n    enabledButtons: buttons,\n    components,\n    multiline,\n    useMarkdownShortcuts,\n    useEmojiAutocomplete,\n    format,\n  };\n\n  setContext('editorStore', editorStore);\n\n  /** Features derived from the editor configuration, which the store holds normalized. */\n  const setup = $derived(\n    getEditorSetup(/** @type {NormalizedEditorConfig} */ (editorStore.config)),\n  );\n\n  const usePlainText = $derived(!editorStore.useRichText && !hidden);\n  /**\n   * The `dir` attribute on the `<textarea>` of the plain text mode. The rich text mode keeps the\n   * hidden `<textarea>` in sync with the editor, setting its value on every change, and the browser\n   * resolves `dir=\"auto\"` over the whole value each time it’s set, which makes typing in a long\n   * document slow. As nobody sees the `<textarea>` meanwhile, it only gets `auto` once it’s shown.\n   */\n  const textAreaDir = $derived(dir === 'auto' && editorStore.useRichText ? undefined : dir);\n\n  /** Language of the source shown in the plain text mode. */\n  // svelte-ignore state_referenced_locally\n  const sourceLanguage = format === 'html' ? 'html' : 'markdown';\n\n  /** Highlighter of the Markdown or HTML source shown in the plain text mode. */\n  const highlightSource = createSourceHighlighter({\n    language: sourceLanguage,\n    /**\n     * Check if the plain text mode is shown.\n     * @returns {boolean} Result.\n     */\n    isActive: () => usePlainText,\n    /**\n     * Get the Markdown or HTML source.\n     * @returns {string} Source.\n     */\n    getSource: () => editorStore.inputValue,\n  });\n\n  $effect(() => {\n    // Keep the block type of the selection up to date in the plain text mode, so the toolbar can\n    // reflect it like in the rich text mode\n    const { textArea, useRichText } = editorStore;\n\n    if (!textArea || useRichText) {\n      return undefined;\n    }\n\n    return untrack(() =>\n      registerRawTextSelection(\n        textArea,\n        (blockType) => {\n          editorStore.selection = { blockNodeKey: null, blockType, inlineTypes: [] };\n        },\n        {\n          /**\n           * Tell whether the task list button is enabled. It’s read on every change rather than\n           * once, so a change to the buttons is followed.\n           * @returns {boolean} Result.\n           */\n          hasTaskList: () => setup.hasTaskList,\n        },\n      ),\n    );\n  });\n\n  $effect(() => {\n    const { textArea } = editorStore;\n\n    if (!textArea || multiline) {\n      return undefined;\n    }\n\n    return registerRawTextSingleLine(textArea);\n  });\n\n  syncEditorProps(editorStore, {\n    /**\n     * Pass the value to the editor.\n     * @returns {string} Value.\n     */\n    getInputValue: () => value,\n    /**\n     * Update the value with the editor’s.\n     * @param {string} newValue New value.\n     */\n    setValue: (newValue) => {\n      if (value !== newValue) {\n        value = newValue;\n      }\n    },\n    /**\n     * Update the `pending` prop.\n     * @param {boolean} newValue New value.\n     */\n    setPending: (newValue) => {\n      pending = newValue;\n    },\n  });\n</script>\n\n<div\n  {...restProps}\n  role=\"none\"\n  class=\"sui text-editor\"\n  class:flex\n  class:single-line={!multiline}\n  class:minimal\n  {hidden}\n  style:--sui-text-editor-toolbar-height=\"{editorStore.toolbarHeight}px\"\n>\n  <TextEditorToolbar {disabled} {readonly} />\n  <LexicalRoot\n    {...labelAttrs}\n    {dir}\n    hidden={!editorStore.useRichText || hidden}\n    {disabled}\n    {readonly}\n    {required}\n    {invalid}\n  />\n  <TextArea\n    {...labelAttrs}\n    bind:element={editorStore.textArea}\n    id=\"{editorStore.editorId}-plain-text\"\n    autoResize={true}\n    rows={multiline ? undefined : 1}\n    aria-multiline={multiline ? undefined : false}\n    bind:value={editorStore.inputValue}\n    {useEmojiAutocomplete}\n    highlight={highlightSource}\n    {flex}\n    dir={textAreaDir}\n    hidden={editorStore.useRichText || hidden}\n    {disabled}\n    {readonly}\n    {required}\n    {invalid}\n  />\n  {#if editorStore.config.useEmojiAutocomplete && editable}\n    <EmojiAutocomplete />\n  {/if}\n  {#if setup.hasLink && editable}\n    <FloatingLinkEditor />\n  {/if}\n  {#if setup.hasTable && editable}\n    <TableCellMenuButton />\n  {/if}\n</div>\n\n{#if editorStore.showConverterError}\n  <Toast bind:show={editorStore.showConverterError}>\n    <Alert status=\"error\">{_('_sui.text_editor.converter_error')}</Alert>\n  </Toast>\n{/if}\n\n<style>.text-editor {\n  position: relative;\n  margin: var(--sui-focus-ring-width);\n  width: calc(100% - var(--sui-focus-ring-width) * 2);\n}\n.text-editor.flex:not([hidden]) {\n  display: block;\n}\n.text-editor:is(.single-line, .minimal) > :global(.lexical-root), .text-editor:is(.single-line, .minimal) > :global(.text-area) > :global(:is(textarea, .clone)) {\n  min-height: 0;\n}\n.text-editor.minimal > :global(.lexical-root),\n.text-editor.minimal > :global(.text-area) > :global(:is(textarea, .clone)) {\n  max-height: 240px;\n}\n.text-editor.minimal > :global(.lexical-root),\n.text-editor.minimal > :global(.text-area) > :global(textarea) {\n  overflow: auto;\n}\n.text-editor.minimal > :global(.lexical-root) {\n  --sui-text-editor-inner-toolbar-top: 0px;\n}\n.text-editor.minimal > :global(.text-area) > :global(:is(textarea, .clone)) {\n  scrollbar-gutter: stable;\n}\n.text-editor :global(.sui.text-area) {\n  margin: 0 !important;\n  width: 100% !important;\n  min-width: auto;\n}\n.text-editor :global(.sui.text-area) :global(textarea) {\n  border-start-start-radius: 0 !important;\n  border-start-end-radius: 0 !important;\n  border-end-start-radius: var(--sui-textbox-border-radius) !important;\n  border-end-end-radius: var(--sui-textbox-border-radius) !important;\n  outline-offset: calc(var(--sui-focus-ring-width) * -1);\n}\n.text-editor {\n  --sui-text-editor-toolbar-top: var(--sui-text-editor-inner-toolbar-top, 0px);\n  --sui-text-editor-toolbar-z-index: var(--sui-text-editor-inner-toolbar-z-index, 100);\n}\n.text-editor > :global(*) {\n  --sui-text-editor-inner-toolbar-top: calc(\n    var(--sui-text-editor-toolbar-top) + var(--sui-text-editor-toolbar-height)\n  );\n  --sui-text-editor-inner-toolbar-z-index: calc(var(--sui-text-editor-toolbar-z-index) - 1);\n}</style>\n","<!--\n  @component\n  A color swatch button that opens the browser’s color picker. The equivalent of the HTML\n  `<input type=\"color\">` element, styled like the other controls.\n  @todo Replace the native `<input>` with a custom component.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/color\n-->\n<script>\n  import { getAccessibleName } from '../../services/label.js';\n\n  /**\n   * @import { CommonEventHandlers, InputEventHandlers } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [value] Input value, a lowercase hex color in the `#rrggbb` format. The\n   * swatch shows black if no value is given.\n   * @property {HTMLInputElement} [element] Reference to the `<input>` element.\n   * @property {string} [class] The `class` attribute on the `<input>` element.\n   * @property {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\n   * @property {boolean} [readonly] Whether to make the widget read-only. An alias of the\n   * `aria-readonly` attribute. A native color input doesn’t support the `readonly` attribute, so\n   * the picker is kept from opening instead, while the input stays focusable, so the current color\n   * can still be reached and read by keyboard and assistive technology users, unlike with\n   * `disabled`.\n   * @property {boolean} [required] Whether to mark the widget required. An alias of the\n   * `aria-required` attribute.\n   * @property {boolean} [invalid] Whether to mark the widget invalid. An alias of the\n   * `aria-invalid` attribute.\n   * @property {string} [ariaLabel] `aria-label` attribute.\n   */\n\n  /**\n   * @type {CommonEventHandlers & InputEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    element = $bindable(),\n    class: className,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    ariaLabel = undefined,\n    onclick,\n    oninput,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Handle the `click` event. Prevent the picker from opening while read-only; the keyboard\n   * activation with the Enter or Space key also fires a `click` event.\n   * @param {MouseEvent} event The `click` event object.\n   */\n  const handleClick = (event) => {\n    if (readonly) {\n      event.preventDefault();\n    }\n\n    onclick?.(event);\n  };\n\n  /**\n   * Update the `value` and call the `oninput` callback.\n   * @param {Event} event The `input` event object.\n   */\n  const handleInput = (event) => {\n    value = /** @type {HTMLInputElement} */ (event.currentTarget).value;\n    oninput?.(event);\n  };\n</script>\n\n<input\n  bind:this={element}\n  {...restProps}\n  value={value ?? ''}\n  type=\"color\"\n  class=\"sui color-input {className}\"\n  disabled={disabled || undefined}\n  aria-label={getAccessibleName({ ariaLabel, props: restProps })}\n  aria-disabled={disabled}\n  aria-readonly={readonly}\n  aria-required={required}\n  aria-invalid={invalid}\n  onclick={handleClick}\n  oninput={handleInput}\n/>\n\n<style>.color-input {\n  display: inline-block;\n  margin: var(--sui-focus-ring-width);\n  border-width: var(--sui-color-input-border-width, 1px);\n  border-color: var(--sui-color-input-border-color, var(--sui-control-border-color));\n  border-radius: var(--sui-color-input-border-radius, var(--sui-button-medium-border-radius));\n  padding: var(--sui-color-input-padding, 3px);\n  width: var(--sui-color-input-width, calc(var(--sui-button-medium-height) * 1.5));\n  height: var(--sui-color-input-height, var(--sui-button-medium-height));\n  color: inherit;\n  background-color: var(--sui-color-input-background-color, var(--sui-textbox-background-color));\n  font-family: var(--sui-textbox-font-family);\n  cursor: pointer;\n  transition: all 200ms;\n}\n.color-input:is(:hover, :focus-visible) {\n  background-color: var(--sui-color-input-background-color-focus, var(--sui-hover-background-color));\n}\n.color-input:active {\n  background-color: var(--sui-color-input-background-color-active, var(--sui-active-background-color));\n}\n.color-input[aria-readonly=true] {\n  cursor: default;\n  background-color: var(--sui-disabled-background-color);\n}\n.color-input[aria-invalid=true] {\n  border-color: var(--sui-error-border-color);\n}\n.color-input::-webkit-color-swatch-wrapper {\n  padding: 0;\n}\n.color-input::-webkit-color-swatch {\n  border: 1px solid var(--sui-secondary-border-color);\n  border-radius: calc(var(--sui-button-medium-border-radius) / 2);\n}\n.color-input::-moz-color-swatch {\n  border: 1px solid var(--sui-secondary-border-color);\n  border-radius: calc(var(--sui-button-medium-border-radius) / 2);\n}</style>\n","<!--\n  @component\n  A date and/or time field. The equivalent of the HTML `<input type=\"date\">`,\n  `<input type=\"datetime-local\">` and `<input type=\"time\">` elements, styled like the other text\n  fields. The browser’s native picker is kept, and follows the light or dark theme through the\n  inherited `color-scheme`.\n  @todo Replace the native `<input>` with a custom component.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time\n-->\n<script>\n  import { getAccessibleName } from '../../services/label.js';\n  import LabelAbove from '../util/label-above.svelte';\n\n  /**\n   * @import {\n   * CommonEventHandlers,\n   * FormFieldStateProps,\n   * InputEventHandlers,\n   * LabelAboveProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [value] Input value, in the native input’s format: `YYYY-MM-DD` for `date`,\n   * `YYYY-MM-DDTHH:mm` (with optional seconds) for `datetime-local`, and `HH:mm` (with optional\n   * seconds) for `time`. An empty string if no value is entered.\n   * @property {HTMLInputElement} [element] Reference to the `<input>` element.\n   * @property {'date' | 'datetime-local' | 'time'} [type] The `type` attribute on the `<input>`.\n   * @property {string} [min] Minimum allowed value, in the same format as `value`.\n   * @property {string} [max] Maximum allowed value, in the same format as `value`.\n   * @property {number | 'any'} [step] Stepping interval: in days for `date`, in seconds for\n   * `datetime-local` and `time`. A step under 60 for the latter two shows the seconds.\n   * @property {string} [class] The `class` attribute on the `<input>` element, or on its wrapper\n   * when there’s a label above it, so the class still sizes the whole field.\n   * @property {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\n   * @property {string} [ariaLabel] `aria-label` attribute.\n   */\n\n  /**\n   * @type {LabelAboveProps & CommonEventHandlers & InputEventHandlers & FormFieldStateProps &\n   * Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    element = $bindable(),\n    type = 'date',\n    min = undefined,\n    max = undefined,\n    step = undefined,\n    class: className,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    ariaLabel = undefined,\n    showLabelAbove = false,\n    oninput,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const uid = $props.id();\n  /** ID of the `<input>` element, which the label above it points to. */\n  const inputId = $derived(restProps.id ?? `${uid}-input`);\n  const label = $derived(getAccessibleName({ ariaLabel, props: restProps }));\n  /** Label shown above the field with `showLabelAbove`, which wraps the input. */\n  const labelAbove = $derived(showLabelAbove ? label : undefined);\n\n  /**\n   * Update the `value` and call the `oninput` callback.\n   * @param {Event} event The `input` event object.\n   */\n  const handleInput = (event) => {\n    value = /** @type {HTMLInputElement} */ (event.currentTarget).value;\n    oninput?.(event);\n  };\n</script>\n\n{#snippet field()}\n  <input\n    bind:this={element}\n    {...restProps}\n    id={inputId}\n    value={value ?? ''}\n    {type}\n    {min}\n    {max}\n    {step}\n    class=\"sui date-time-input {labelAbove ? '' : className}\"\n    disabled={disabled || undefined}\n    readonly={readonly || undefined}\n    aria-label={label}\n    aria-disabled={disabled}\n    aria-readonly={readonly}\n    aria-required={required}\n    aria-invalid={invalid}\n    oninput={handleInput}\n  />\n{/snippet}\n\n<!-- The input is the root element, so it’s only wrapped when there’s a label to show above it -->\n{#if labelAbove}\n  <div role=\"none\" class=\"sui date-time-input-wrapper {className}\">\n    <LabelAbove label={labelAbove} for={inputId} />\n    {@render field()}\n  </div>\n{:else}\n  {@render field()}\n{/if}\n\n<style>.date-time-input-wrapper {\n  display: inline-grid;\n}\n\n.date-time-input {\n  display: inline-block;\n  margin: var(--sui-focus-ring-width);\n  width: auto;\n  min-width: 0;\n  height: var(--sui-textbox-height);\n  text-transform: var(--sui-date-time-input-text-transform, uppercase);\n  font-variant-numeric: tabular-nums;\n  border-width: var(--sui-textbox-border-width, 1px);\n  border-color: var(--sui-textbox-border-color);\n  border-radius: var(--sui-textbox-border-radius);\n  padding: var(--sui-textbox-singleline-padding);\n  color: var(--sui-textbox-foreground-color);\n  background-color: var(--sui-textbox-background-color);\n  font-family: var(--sui-textbox-font-family);\n  font-size: var(--sui-textbox-font-size);\n  line-height: var(--sui-textbox-singleline-line-height);\n  font-weight: var(--sui-textbox-font-weight, var(--sui-font-weight-normal, normal));\n  letter-spacing: var(--sui-textbox-letter-spacing, normal);\n  transition: all 200ms;\n}\n.date-time-input:focus {\n  color: var(--sui-textbox-foreground-color-focus, var(--sui-textbox-foreground-color));\n  background-color: var(--sui-textbox-background-color-focus, var(--sui-textbox-background-color));\n}\n.date-time-input[aria-invalid=true] {\n  border-color: var(--sui-error-border-color);\n}\n.date-time-input:read-only {\n  color: var(--sui-secondary-foreground-color);\n  border-color: var(--sui-textbox-border-color) !important;\n}\n.date-time-input:is(:disabled, :read-only) {\n  background-color: var(--sui-disabled-background-color);\n}\n.date-time-input::-webkit-calendar-picker-indicator {\n  cursor: pointer;\n}\n.date-time-input:is(:disabled, :read-only)::-webkit-calendar-picker-indicator {\n  cursor: default;\n}</style>\n","<!--\n  @component\n  Internal base of `<PasswordInput>` and `<SecretInput>`: a text field whose value is masked, with a\n  Show/Hide button.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { getLabelAboveText } from '../../services/label.js';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import LabelAbove from '../util/label-above.svelte';\n  import TextInput from './text-input.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import {\n   * CommonEventHandlers,\n   * InputEventHandlers,\n   * LabelAboveProps,\n   * TextInputProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'type' | 'css'} mask How to mask the value: `type` uses `type=\"password\"`, while\n   * `css` uses `-webkit-text-security` so password managers don’t prompt to save the value.\n   * @property {string} [value] Input value.\n   * @property {Snippet} [visibilityIcon] Visibility icon slot content.\n   */\n\n  /**\n   * @type {LabelAboveProps & TextInputProps & CommonEventHandlers & InputEventHandlers & Props &\n   * Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    mask,\n    value = $bindable(),\n    flex = false,\n    monospace = true,\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    showLabelAbove = false,\n    // Not rendered, but kept out of `restProps` so it isn’t spread onto the `<input>`\n    children,\n    visibilityIcon,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n  /**\n   * Label shown above the field with `showLabelAbove`. It’s rendered here rather than by the\n   * `<TextInput>`, so it sits above the Show/Hide button as well.\n   */\n  const labelAbove = $derived(getLabelAboveText({ showLabelAbove, props: restProps }));\n\n  let show = $state(false);\n\n  const labels = $derived(\n    mask === 'type'\n      ? {\n          show: '_sui.password_input.show_password',\n          hide: '_sui.password_input.hide_password',\n        }\n      : {\n          show: '_sui.secret_input.show_secret',\n          hide: '_sui.secret_input.hide_secret',\n        },\n  );\n</script>\n\n<div\n  role=\"none\"\n  class=\"sui {mask === 'type' ? 'password-input' : 'secret-input'} {className}\"\n  class:flex\n  class:disabled\n  class:readonly\n  class:show={mask === 'css' && show}\n  class:has-label-above={!!labelAbove}\n  {hidden}\n>\n  {#if labelAbove}\n    <LabelAbove label={labelAbove} for={id} />\n  {/if}\n  <!-- With the `css` mask, the field is masked with CSS rather than `type=\"password\"`, so opt out\n  of the features that would remember the secret, like autofill history and the keyboard’s learned\n  words -->\n  <TextInput\n    dir=\"ltr\"\n    {...mask === 'css' ? { autocomplete: 'off', autocapitalize: 'off', autocorrect: 'off' } : {}}\n    {...restProps}\n    {id}\n    bind:value\n    {...mask === 'type' ? { type: show ? 'text' : 'password' } : {}}\n    spellcheck=\"false\"\n    {flex}\n    {monospace}\n    {hidden}\n    {disabled}\n    {readonly}\n    {required}\n    {invalid}\n  />\n  <Button\n    iconic\n    disabled={disabled || readonly}\n    pressed={show}\n    aria-label={_(show ? labels.hide : labels.show)}\n    aria-controls={id}\n    onclick={() => {\n      show = !show;\n    }}\n  >\n    {#snippet startIcon()}\n      {#if visibilityIcon}\n        {@render visibilityIcon()}\n      {:else}\n        <Icon name={show ? 'visibility_off' : 'visibility'} />\n      {/if}\n    {/snippet}\n  </Button>\n</div>\n\n<style>.password-input,\n.secret-input {\n  display: inline-flex;\n  align-items: center;\n  margin: var(--sui-focus-ring-width);\n  min-width: var(--sui-textbox-singleline-min-width);\n}\n.password-input.flex:not([hidden]),\n.secret-input.flex:not([hidden]) {\n  display: inline-flex;\n  width: -moz-available;\n  width: -webkit-fill-available;\n  width: stretch;\n  min-width: 0;\n}\n.password-input.has-label-above:not([hidden]),\n.secret-input.has-label-above:not([hidden]) {\n  display: inline-grid;\n  grid-template-columns: 1fr auto;\n}\n.password-input.has-label-above:not([hidden]) :global(.text-input),\n.secret-input.has-label-above:not([hidden]) :global(.text-input) {\n  width: auto;\n}\n.password-input :global(.text-input),\n.secret-input :global(.text-input) {\n  flex: auto;\n  margin: 0 !important;\n  width: 0;\n  min-width: 0 !important;\n}\n.password-input :global(input),\n.secret-input :global(input) {\n  border-start-end-radius: 0;\n  border-end-end-radius: 0;\n}\n.password-input :global(button),\n.secret-input :global(button) {\n  margin-block: 0;\n  margin-inline-end: 0;\n  flex: none;\n  margin-inline-start: -1px;\n  border-width: 1px;\n  border-color: var(--sui-textbox-border-color);\n  width: var(--sui-textbox-height);\n  aspect-ratio: 1/1;\n}\n.password-input :global(button:last-child),\n.secret-input :global(button:last-child) {\n  border-start-start-radius: 0;\n  border-start-end-radius: 4px;\n  border-end-end-radius: 4px;\n  border-end-start-radius: 0;\n}\n.password-input :global(button) :global(.icon),\n.secret-input :global(button) :global(.icon) {\n  font-size: var(--sui-font-size-xx-large);\n}\n\n.secret-input.show :global(input) {\n  -webkit-text-security: none;\n}\n.secret-input :global(input) {\n  -webkit-text-security: disc;\n}\n\n.password-input:dir(rtl),\n.secret-input:dir(rtl) {\n  --sui-textbox-text-align: right;\n}</style>\n","<!--\n  @component\n  The equivalent of the HTML `<input type=\"password\">` element, but it comes with the Show/Hide\n  button.\n  @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/password\n  @see https://w3c.github.io/aria/#textbox\n-->\n<script>\n  import MaskedInput from './masked-input.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import {\n   * CommonEventHandlers,\n   * InputEventHandlers,\n   * LabelAboveProps,\n   * TextInputProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [value] Input value.\n   * @property {Snippet} [visibilityIcon] Visibility icon slot content.\n   */\n\n  /**\n   * @type {LabelAboveProps & TextInputProps & CommonEventHandlers & InputEventHandlers & Props &\n   * Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<MaskedInput bind:value {...restProps} mask=\"type\" />\n","<!--\n  @component\n  Similar to `PasswordInput`, but it doesn’t use `type=\"password\"` to hide the input value. Instead,\n  it relies on CSS to visually conceal the input to prevent password managers from prompting to save\n  the password.\n  @see https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/-webkit-text-security\n-->\n<script>\n  import MaskedInput from './masked-input.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import {\n   * CommonEventHandlers,\n   * InputEventHandlers,\n   * LabelAboveProps,\n   * TextInputProps,\n   * } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [value] Input value.\n   * @property {Snippet} [visibilityIcon] Visibility icon slot content.\n   */\n\n  /**\n   * @type {LabelAboveProps & TextInputProps & CommonEventHandlers & InputEventHandlers & Props &\n   * Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<MaskedInput bind:value {...restProps} mask=\"css\" />\n","<!--\n  @component\n  An item (node) within the `<Tree>` widget. An item that has the `items` slot content becomes a\n  parent node that can be expanded and collapsed.\n  @see https://w3c.github.io/aria/#treeitem\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/treeview/\n-->\n<script>\n  import { isRTL } from '@sveltia/i18n';\n  import { getContext, setContext } from 'svelte';\n  import { getValueType } from '../../services/value.js';\n  import Icon from '../icon/icon.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { Attachment } from 'svelte/attachments';\n   * @import { CommonEventHandlers, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [selected] Whether to select the item. An alias of the `aria-selected`\n   * attribute.\n   * @property {boolean} [expanded] Whether to expand the item. An alias of the `aria-expanded`\n   * attribute. Ignored if the item has no `items` slot content.\n   * @property {string} [label] Text label displayed on the item.\n   * @property {any} [value] The `data-value` attribute on the item. Default: the `label`.\n   * @property {string} [valueType] Data type of the `value`. Typically `string`, `number`,\n   * `boolean` or `null`. Default: auto detect.\n   * @property {Snippet} [children] Primary slot content, used instead of the `label`.\n   * @property {Snippet} [items] Child items slot content, which makes the item a parent node.\n   * @property {Snippet} [startIcon] Start icon slot content.\n   * @property {Snippet} [endIcon] End icon slot content, which is part of the accessible name\n   * unless it’s hidden with `aria-hidden`.\n   * @property {Snippet} [chevronIcon] Chevron icon slot content.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler, called when\n   * the selection state is changed.\n   * @property {(event: CustomEvent) => void} [onSelect] Custom `Select` event handler.\n   * @property {(event: CustomEvent) => void} [onExpand] Custom `Expand` event handler, called when\n   * the item is expanded or collapsed.\n   */\n\n  /**\n   * @type {CommonEventHandlers & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    selected = $bindable(false),\n    expanded = $bindable(false),\n    class: className,\n    hidden = false,\n    disabled = false,\n    label = '',\n    value: _value = undefined,\n    valueType: _valueType = undefined,\n    children,\n    items,\n    startIcon,\n    endIcon,\n    chevronIcon,\n    onChange,\n    onSelect,\n    onExpand,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n\n  // The label is the default, followed when it changes, like on a locale switch. A prop fallback\n  // would only take its first value\n  const value = $derived(_value === undefined ? label : _value);\n  const valueType = $derived(_valueType === undefined ? getValueType(value) : _valueType);\n  /** Nesting level of the item, starting with 1 for the root level items. */\n  const level = /** @type {number} */ (getContext('sui:tree-item-level') ?? 0) + 1;\n\n  setContext('sui:tree-item-level', level);\n\n  /**\n   * Handle the `Change` event dispatched by the parent widget when the selection state is changed.\n   * @param {any} event `Change` event.\n   */\n  const handleChange = (event) => {\n    selected = event.detail.selected;\n    onChange?.(event);\n  };\n\n  /**\n   * Handle the `Expand` event dispatched by the parent widget when the item is expanded or\n   * collapsed.\n   * @param {any} event `Expand` event.\n   */\n  const handleExpand = (event) => {\n    expanded = event.detail.expanded;\n    onExpand?.(event);\n  };\n\n  /**\n   * Handle the `Select` event dispatched by the parent widget when the item is selected.\n   * @param {any} event `Select` event.\n   */\n  const handleSelect = (event) => {\n    onSelect?.(event);\n  };\n\n  /**\n   * Listen to the custom events dispatched on the item element by the parent `<Tree>` widget, so\n   * the component state can be kept in sync with the DOM state.\n   * @type {Attachment}\n   */\n  const handleEvents = (element) => {\n    /** @type {[string, (event: any) => void][]} */\n    const listeners = [\n      ['Change', handleChange],\n      ['Expand', handleExpand],\n      ['Select', handleSelect],\n    ];\n\n    listeners.forEach(([type, handler]) => {\n      element.addEventListener(type, handler);\n    });\n\n    return () => {\n      listeners.forEach(([type, handler]) => {\n        element.removeEventListener(type, handler);\n      });\n    };\n  };\n</script>\n\n<div\n  {...restProps}\n  {id}\n  role=\"treeitem\"\n  class=\"sui treeitem {className}\"\n  tabindex=\"-1\"\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-selected={selected}\n  aria-expanded={items ? expanded : undefined}\n  aria-level={level}\n  aria-labelledby={endIcon ? `${id}-label ${id}-end` : `${id}-label`}\n  data-label={label}\n  data-value={value}\n  data-type={valueType}\n  {@attach handleEvents}\n>\n  <div role=\"none\" class=\"row\" style:--sui-tree-item-level={level}>\n    {#if items}\n      <span role=\"none\" class=\"chevron\" data-action=\"toggle\">\n        {#if chevronIcon}\n          {@render chevronIcon()}\n        {:else}\n          <Icon name={isRTL() ? 'chevron_left' : 'chevron_right'} />\n        {/if}\n      </span>\n    {:else}\n      <span role=\"none\" class=\"chevron placeholder\"></span>\n    {/if}\n    {@render startIcon?.()}\n    <span role=\"none\" class=\"label\" id=\"{id}-label\">\n      {#if label}\n        {label}\n      {:else}\n        {@render children?.()}\n      {/if}\n    </span>\n    {#if endIcon}\n      <!-- Part of the name, like a count next to the label -->\n      <span role=\"none\" class=\"end-icon\" id=\"{id}-end\">\n        {@render endIcon()}\n      </span>\n    {/if}\n  </div>\n  {#if items}\n    <div role=\"group\" class=\"group\" hidden={!expanded}>\n      {@render items()}\n    </div>\n  {/if}\n</div>\n\n<style>.end-icon {\n  display: contents;\n}\n\n[role=treeitem] {\n  display: block;\n}\n[role=treeitem][hidden] {\n  display: none;\n}\n[role=treeitem]:focus-visible {\n  outline-color: transparent;\n}\n[role=treeitem]:focus-visible > .row {\n  outline-color: var(--sui-focus-ring-color);\n  outline-offset: calc(var(--sui-focus-ring-width) * -1);\n}\n[role=treeitem][aria-selected=true] > .row {\n  color: var(--sui-highlight-foreground-color);\n  background-color: var(--sui-selected-background-color);\n}\n[role=treeitem] > .row:hover {\n  color: var(--sui-highlight-foreground-color);\n  background-color: var(--sui-hover-background-color);\n}\n[role=treeitem] > .row:active {\n  background-color: var(--sui-active-background-color);\n}\n:global([role='tree'][aria-readonly='true']) [role=treeitem] > .row {\n  cursor: default;\n}\n:global([role='tree'][aria-readonly='true']) [role=treeitem] > .row:is(:hover, :active) {\n  color: var(--sui-tree-foreground-color);\n  background-color: transparent;\n}\n:global([role='tree'][aria-readonly='true']) [role=treeitem] > .row > .chevron:not(.placeholder) {\n  cursor: pointer;\n}\n:global([role='tree'][aria-readonly='true']) [role=treeitem][aria-selected=true] > .row:is(:hover, :active) {\n  color: var(--sui-highlight-foreground-color);\n  background-color: var(--sui-selected-background-color);\n}\n[role=treeitem][aria-expanded=true] > .row > .chevron:dir(ltr) {\n  transform: rotate(90deg);\n}\n[role=treeitem][aria-expanded=true] > .row > .chevron:dir(rtl) {\n  transform: rotate(-90deg);\n}\n\n.row {\n  display: flex;\n  align-items: center;\n  gap: 4px;\n  border-radius: var(--sui-tree-item-border-radius, var(--sui-option-border-radius, 4px));\n  padding: var(--sui-tree-item-padding, var(--sui-option-padding, 0 8px));\n  min-height: var(--sui-tree-item-height, var(--sui-option-height));\n  cursor: pointer;\n  transition: background-color 200ms;\n}\n\n.chevron {\n  flex: none;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  margin-inline-start: calc((var(--sui-tree-item-level, 1) - 1) * var(--sui-tree-item-indent, 16px));\n  width: var(--sui-tree-item-chevron-size, 24px);\n  height: var(--sui-tree-item-chevron-size, 24px);\n  transition: transform 200ms;\n}\n\n.label {\n  flex: auto;\n  overflow: hidden;\n  padding: 0 4px;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n}\n\n.group {\n  display: block;\n}\n.group[hidden] {\n  display: none;\n}</style>\n","import { isRTL } from '@sveltia/i18n';\nimport { generateElementId } from '@sveltia/utils/element';\nimport { CompositeWidget, createWidgetAttachment } from './composite-widget.svelte.js';\nimport { getArrowKeys } from './navigation.js';\nimport { scrollIntoViewIfNeeded } from './scroll.js';\nimport { getItemLabel } from './text.js';\nimport { isPrintableKey } from './type-ahead.js';\n\n/**\n * CSS selector to retrieve the tree items.\n */\nconst ITEM_SELECTOR = '[role=\"treeitem\"]';\n\n/**\n * Implement keyboard and mouse interactions for the `tree` composite widget, following the ARIA\n * Tree View pattern. Unlike the other composite widgets handled by the `Group` class, a tree\n * manages the focus (roving `tabindex`) and the selection separately, and it also supports\n * expanding and collapsing parent nodes.\n * @see https://www.w3.org/WAI/ARIA/apg/patterns/treeview/\n */\nexport class Tree extends CompositeWidget {\n  /**\n   * Initialize a new `Tree` instance.\n   * @param {HTMLElement} parent Parent element.\n   * @param {object} [options] Options.\n   * @param {boolean} [options.clickToSelect] Whether to select an item by clicking on it.\n   * @param {boolean} [options.selectionFollowsFocus] Whether to select an item as soon as it\n   * receives focus. Default: `true` on a single-select tree, `false` on a multi-select tree.\n   * @param {boolean} [options.expandOnSelect] Whether to expand or collapse a parent item when the\n   * item itself, rather than its chevron, is clicked or activated.\n   */\n  constructor(parent, options = {}) {\n    super(parent);\n\n    this.id = generateElementId('tree');\n\n    /**\n     * Whether to select an item by clicking on it.\n     * @type {boolean}\n     */\n    this.clickToSelect = true;\n\n    /**\n     * Whether to expand or collapse a parent item when the item itself is clicked or activated.\n     * @type {boolean}\n     */\n    this.expandOnSelect = true;\n\n    /**\n     * Whether the selection follows the focus. `undefined` means auto detect.\n     * @type {boolean | undefined}\n     */\n    this.selectionFollowsFocusOption = undefined;\n\n    this.onUpdate(options);\n\n    /**\n     * Item used as the starting point of a range selection.\n     * @type {HTMLElement | undefined}\n     */\n    this.anchor = undefined;\n\n    // The items can be added or removed at any time, e.g. when a subtree is lazily rendered, and\n    // collapsed, hidden or disabled from outside, e.g. with a “collapse all” button, which can take\n    // the tab stop out of reach\n    this.observer = new globalThis.MutationObserver(() => {\n      this.update();\n    });\n\n    // The widget root itself is never part of the tab order; one of the items always is\n    this.parent.tabIndex = -1;\n\n    // Listen right away: a click, a key press or a focus that comes before the activation below\n    // activates the items first, rather than being lost\n    this.listen('click', (event) => this.onClick(event));\n    this.listen('keydown', (event) => this.onKeyDown(event));\n    this.listen('focusin', (event) => this.onFocusIn(event));\n  }\n\n  /**\n   * Set up the items on activation. The observer is only connected here, rather than in the\n   * constructor, so a widget unmounted before its activation leaves nothing to disconnect.\n   * @override\n   */\n  setUp() {\n    this.update();\n    this.observer.observe(this.parent, {\n      childList: true,\n      subtree: true,\n      attributes: true,\n      attributeFilter: ['hidden', 'aria-hidden', 'aria-disabled', 'aria-expanded'],\n    });\n  }\n\n  /**\n   * Called whenever the params are updated, as well as on creation. Apply the options.\n   * @override\n   * @param {object} params Updated params.\n   * @param {boolean} [params.clickToSelect] Whether to select an item by clicking on it.\n   * @param {boolean} [params.selectionFollowsFocus] Whether to select an item as soon as it\n   * receives focus. Default: `true` on a single-select tree, `false` on a multi-select tree.\n   * @param {boolean} [params.expandOnSelect] Whether to expand or collapse a parent item when the\n   * item itself, rather than its chevron, is clicked or activated.\n   */\n  onUpdate({ clickToSelect = true, selectionFollowsFocus, expandOnSelect = true }) {\n    this.clickToSelect = clickToSelect;\n    this.selectionFollowsFocusOption = selectionFollowsFocus;\n    this.expandOnSelect = expandOnSelect;\n  }\n\n  /**\n   * Whether more than one item can be selected.\n   * @type {boolean}\n   */\n  get multi() {\n    return this.parent.getAttribute('aria-multiselectable') === 'true';\n  }\n\n  /**\n   * Whether an item is selected as soon as it receives focus.\n   * @type {boolean}\n   */\n  get selectionFollowsFocus() {\n    return this.selectionFollowsFocusOption ?? !this.multi;\n  }\n\n  /**\n   * List of all the items, including the ones within a collapsed parent, in document order.\n   * @type {HTMLElement[]}\n   */\n  get allItems() {\n    return /** @type {HTMLElement[]} */ ([...this.parent.querySelectorAll(ITEM_SELECTOR)]);\n  }\n\n  /**\n   * List of the items that are not hidden, either explicitly or by a collapsed ancestor.\n   * @type {HTMLElement[]}\n   */\n  get visibleItems() {\n    /** @type {HTMLElement[]} */\n    const items = [];\n\n    /**\n     * Collect the items below the given node in document order, descending only into the parents\n     * that are actually expanded. Pruning the collapsed subtrees outright is what keeps this\n     * proportional to the number of displayed items; testing each item in the tree for a collapsed\n     * ancestor instead costs a walk back up per item.\n     * @param {Element} node Node whose children to scan.\n     */\n    const collect = (node) => {\n      [...node.children].forEach((child) => {\n        if (child.getAttribute('role') !== 'treeitem') {\n          // Anything else is a wrapper to see through — including a group that no item owns, whose\n          // items sit at the level of the group itself\n          collect(child);\n\n          return;\n        }\n\n        const item = /** @type {HTMLElement} */ (child);\n\n        // A hidden item hides everything below it, and so does a collapsed parent, so there is\n        // nothing to descend into\n        if (item.matches('[hidden], [aria-hidden=\"true\"]')) {\n          return;\n        }\n\n        items.push(item);\n\n        if (this.isParent(item) && !this.isExpanded(item)) {\n          return;\n        }\n\n        const group = this.getGroup(item);\n\n        if (group) {\n          collect(group);\n        }\n      });\n    };\n\n    collect(this.parent);\n\n    return items;\n  }\n\n  /**\n   * List of the items that can receive focus.\n   * @type {HTMLElement[]}\n   */\n  get activeItems() {\n    return this.visibleItems.filter((item) => !item.matches('[aria-disabled=\"true\"]'));\n  }\n\n  /**\n   * List of the selected items.\n   * @type {HTMLElement[]}\n   */\n  get selectedItems() {\n    return /** @type {HTMLElement[]} */ ([\n      ...this.parent.querySelectorAll(`${ITEM_SELECTOR}[aria-selected=\"true\"]`),\n    ]);\n  }\n\n  /**\n   * Item that is currently in the tab order, which is the item that has or last had focus.\n   * @type {HTMLElement | undefined}\n   */\n  get currentItem() {\n    return this.allItems.find((item) => item.tabIndex === 0);\n  }\n\n  /**\n   * Get the group element that contains the child items of the given item.\n   * @param {HTMLElement} item Parent item.\n   * @returns {HTMLElement | undefined} Group element, if the item has one.\n   */\n  getGroup(item) {\n    return /** @type {HTMLElement | undefined} */ (\n      [...item.children].find((child) => child.getAttribute('role') === 'group')\n    );\n  }\n\n  /**\n   * Get the child items of the given item.\n   * @param {HTMLElement} item Parent item.\n   * @returns {HTMLElement[]} Child items. Empty if the item is a leaf node.\n   */\n  getChildItems(item) {\n    const group = this.getGroup(item);\n\n    return group ? this.getItemsInGroup(group) : [];\n  }\n\n  /**\n   * Get the items directly owned by the given group, ignoring any deeper descendants.\n   * @param {HTMLElement} group Group element or the widget root.\n   * @returns {HTMLElement[]} Child items.\n   */\n  getItemsInGroup(group) {\n    /** @type {HTMLElement[]} */\n    const items = [];\n\n    /**\n     * Scan the children of the given node, descending through plain wrapper elements but never into\n     * an item or a nested group — whatever lies below those belongs to the item that owns them.\n     * Querying the whole subtree and then discarding the deeper items with a `closest()` call each\n     * costs `update()`, which runs this once per group, quadratic time overall.\n     * @param {Element} node Node whose children to scan.\n     */\n    const walk = (node) => {\n      [...node.children].forEach((child) => {\n        const role = child.getAttribute('role');\n\n        if (role === 'treeitem') {\n          items.push(/** @type {HTMLElement} */ (child));\n        } else if (role !== 'group' && role !== 'tree') {\n          walk(child);\n        }\n      });\n    };\n\n    walk(group);\n\n    return items;\n  }\n\n  /**\n   * Get the parent item of the given item.\n   * @param {HTMLElement} item Item.\n   * @returns {HTMLElement | undefined} Parent item, if the item is not at the root level.\n   */\n  getParentItem(item) {\n    return /** @type {HTMLElement | undefined} */ (\n      item.parentElement?.closest(ITEM_SELECTOR) ?? undefined\n    );\n  }\n\n  /**\n   * Whether the given item is a parent node that can be expanded and collapsed.\n   * @param {HTMLElement} item Item.\n   * @returns {boolean} Result.\n   */\n  isParent(item) {\n    return item.hasAttribute('aria-expanded');\n  }\n\n  /**\n   * Whether the given parent item is expanded.\n   * @param {HTMLElement} item Item.\n   * @returns {boolean} Result.\n   */\n  isExpanded(item) {\n    return item.getAttribute('aria-expanded') === 'true';\n  }\n\n  /**\n   * Get the text label of the given item, which is used for the type-ahead search.\n   * @param {HTMLElement} item Item.\n   * @returns {string} Label.\n   */\n  getLabel(item) {\n    return getItemLabel(item, { textFallback: false });\n  }\n\n  /**\n   * Assign the element IDs, positional attributes and roving `tabindex` to the items. Called\n   * whenever the items are added or removed.\n   */\n  update() {\n    const { allItems, activeItems } = this;\n\n    allItems.forEach((item, index) => {\n      item.id ||= `${this.id}-item-${index + 1}`;\n\n      if (!item.hasAttribute('aria-selected')) {\n        item.setAttribute('aria-selected', 'false');\n      }\n    });\n\n    const groups = /** @type {HTMLElement[]} */ ([\n      this.parent,\n      ...this.parent.querySelectorAll('[role=\"group\"]'),\n    ]);\n\n    groups.forEach((group) => {\n      const items = this.getItemsInGroup(group);\n\n      items.forEach((item, index) => {\n        item.setAttribute('aria-posinset', String(index + 1));\n        item.setAttribute('aria-setsize', String(items.length));\n      });\n    });\n\n    // Keep exactly one item in the tab order, preferring the focused, current or selected one\n    const current =\n      activeItems.find((item) => item === document.activeElement) ??\n      activeItems.find((item) => item.tabIndex === 0) ??\n      activeItems.find((item) => item.getAttribute('aria-selected') === 'true') ??\n      activeItems[0];\n\n    this.setTabStop(current);\n  }\n\n  /**\n   * Put exactly one item in the tab order. Only the items actually in it are touched: writing a\n   * `tabindex` to every item costs a pass over the whole widget on each arrow key, and all but one\n   * of those writes set the value the item already had.\n   * @param {HTMLElement} [item] Item to become the tab stop. When omitted, no item is left in the\n   * tab order, which is the case for a tree with nothing to focus.\n   */\n  setTabStop(item) {\n    this.parent\n      .querySelectorAll(`${ITEM_SELECTOR}[tabindex]:not([tabindex=\"-1\"])`)\n      .forEach((element) => {\n        if (element !== item) {\n          /** @type {HTMLElement} */ (element).tabIndex = -1;\n        }\n      });\n\n    if (item) {\n      item.tabIndex = 0;\n    }\n  }\n\n  /**\n   * Move focus to the given item.\n   * @param {HTMLElement} item Item to be focused.\n   * @param {object} [options] Options.\n   * @param {boolean} [options.select] Whether to also select the item. Default: depends on the\n   * `selectionFollowsFocus` option.\n   */\n  focusItem(item, { select = this.selectionFollowsFocus } = {}) {\n    this.setTabStop(item);\n    item.focus();\n    item.dispatchEvent(new CustomEvent('Focus'));\n    scrollIntoViewIfNeeded(item);\n\n    if (select) {\n      this.selectItem(item);\n    }\n  }\n\n  /**\n   * Update the selection state of the given item, and notify the change if needed.\n   * @param {HTMLElement} item Item.\n   * @param {boolean} selected Whether to select the item.\n   */\n  setSelected(item, selected) {\n    if ((item.getAttribute('aria-selected') === 'true') === selected) {\n      return;\n    }\n\n    item.setAttribute('aria-selected', String(selected));\n    item.dispatchEvent(new CustomEvent('Change', { detail: { selected } }));\n\n    if (selected) {\n      item.dispatchEvent(new CustomEvent('Select'));\n    }\n  }\n\n  /**\n   * Select the given item.\n   * @param {HTMLElement} item Item to be selected.\n   * @param {object} [options] Options.\n   * @param {boolean} [options.additive] Whether to toggle the item without deselecting the other\n   * items. Multi-select only.\n   * @param {boolean} [options.range] Whether to select all the items between the anchor and the\n   * given item. Multi-select only.\n   */\n  selectItem(item, { additive = false, range = false } = {}) {\n    if (this.isDisabled || this.isReadOnly) {\n      return;\n    }\n\n    const { multi, anchor } = this;\n    const items = multi && range && anchor && anchor !== item ? this.visibleItems : [];\n    const anchorIndex = items.indexOf(/** @type {HTMLElement} */ (anchor));\n\n    // An anchor that has been hidden in a collapsed parent, or removed, can’t start a range, so\n    // the item is selected on its own instead, becoming the new anchor\n    if (anchorIndex !== -1) {\n      const indexes = [anchorIndex, items.indexOf(item)].sort((a, b) => a - b);\n\n      items.forEach((element, index) => {\n        this.setSelected(\n          element,\n          index >= indexes[0] && index <= indexes[1] && !element.matches('[aria-disabled=\"true\"]'),\n        );\n      });\n    } else if (multi && additive) {\n      this.setSelected(item, item.getAttribute('aria-selected') !== 'true');\n      this.anchor = item;\n    } else {\n      // Only the items that are actually selected need clearing; running every item in the tree\n      // through `setSelected()` would leave all but one of them untouched anyway\n      this.selectedItems.forEach((element) => {\n        if (element !== item) {\n          this.setSelected(element, false);\n        }\n      });\n\n      this.setSelected(item, true);\n      this.anchor = item;\n    }\n\n    this.dispatchChange(item);\n  }\n\n  /**\n   * Select all the items that are currently displayed. Multi-select only.\n   * @param {HTMLElement} item Item that triggered the action.\n   */\n  selectAll(item) {\n    if (this.isDisabled || this.isReadOnly || !this.multi) {\n      return;\n    }\n\n    this.activeItems.forEach((element) => {\n      this.setSelected(element, true);\n    });\n\n    this.dispatchChange(item);\n  }\n\n  /**\n   * Expand or collapse the given parent item.\n   * @param {HTMLElement} item Item to be expanded or collapsed.\n   * @param {boolean} expanded Whether to expand the item.\n   */\n  expandItem(item, expanded) {\n    if (this.isDisabled || !this.isParent(item) || this.isExpanded(item) === expanded) {\n      return;\n    }\n\n    const group = this.getGroup(item);\n\n    // Update the DOM right away; the component will render the same state shortly\n    item.setAttribute('aria-expanded', String(expanded));\n\n    if (group) {\n      group.hidden = !expanded;\n    }\n\n    item.dispatchEvent(new CustomEvent('Expand', { detail: { expanded } }));\n    this.update();\n  }\n\n  /**\n   * Expand all the sibling parent items at the same level as the given item.\n   * @param {HTMLElement} item Item.\n   */\n  expandSiblings(item) {\n    const parentItem = this.getParentItem(item);\n    const group = parentItem ? this.getGroup(parentItem) : this.parent;\n\n    if (!group) {\n      return;\n    }\n\n    this.getItemsInGroup(group).forEach((sibling) => {\n      this.expandItem(sibling, true);\n    });\n  }\n\n  /**\n   * Move focus to the next item that matches the accumulated type-ahead search terms. Typing the\n   * same character repeatedly cycles through the items starting with it.\n   * @param {string} char Typed character.\n   * @param {HTMLElement} currentItem Currently focused item.\n   */\n  typeAhead(char, currentItem) {\n    const items = this.activeItems;\n\n    const index = this.typeAheadBuffer.match(\n      items.map((item) => this.getLabel(item)),\n      char,\n      items.indexOf(currentItem),\n    );\n\n    if (index !== -1 && items[index] !== currentItem) {\n      this.focusItem(items[index]);\n    }\n  }\n\n  /**\n   * Handle the `focusin` event on the widget. Make the newly focused item the only one in the tab\n   * order, so that Shift+Tab and Tab move focus out of the widget.\n   * @param {FocusEvent} event `focusin` event.\n   */\n  onFocusIn(event) {\n    const item = /** @type {HTMLElement | null} */ (\n      /** @type {HTMLElement} */ (event.target).closest(ITEM_SELECTOR)\n    );\n\n    // A disabled item can still take focus from a click, but it’s never the tab stop\n    if (!item || item.matches('[aria-disabled=\"true\"]')) {\n      return;\n    }\n\n    this.setTabStop(item);\n  }\n\n  /**\n   * Handle the `click` event on the widget.\n   * @param {MouseEvent} event `click` event.\n   */\n  onClick(event) {\n    // eslint-disable-next-line prefer-destructuring\n    const target = /** @type {HTMLElement} */ (event.target);\n    const item = /** @type {HTMLElement | null} */ (target.closest(ITEM_SELECTOR));\n\n    if (!item || event.button !== 0 || this.isDisabled) {\n      return;\n    }\n\n    if (item.matches('[aria-disabled=\"true\"]')) {\n      event.preventDefault();\n\n      return;\n    }\n\n    const { ctrlKey, metaKey, shiftKey } = event;\n\n    // The chevron only expands or collapses the item\n    if (target.closest('[data-action=\"toggle\"]')) {\n      event.preventDefault();\n      this.focusItem(item, { select: false });\n      this.expandItem(item, !this.isExpanded(item));\n\n      return;\n    }\n\n    this.focusItem(item, { select: false });\n\n    if (this.clickToSelect) {\n      this.selectItem(item, { additive: ctrlKey || metaKey, range: shiftKey });\n    }\n\n    if (this.expandOnSelect && !ctrlKey && !metaKey && !shiftKey) {\n      this.expandItem(item, !this.isExpanded(item));\n    }\n  }\n\n  /**\n   * Handle the `keydown` event on the widget.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  onKeyDown(event) {\n    const { key, ctrlKey, metaKey, shiftKey, altKey } = event;\n    const { activeItems, multi } = this;\n\n    if (this.isDisabled || altKey || !activeItems.length) {\n      return;\n    }\n\n    const target = /** @type {HTMLElement | null} */ (\n      /** @type {HTMLElement} */ (event.target).closest(ITEM_SELECTOR)\n    );\n\n    // Keys pressed on a disabled item, which a click can focus, act on the tab stop instead\n    const currentItem =\n      (target && activeItems.includes(target) ? target : undefined) ??\n      this.currentItem ??\n      activeItems[0];\n\n    const index = activeItems.indexOf(currentItem);\n    // In RTL, the Left and Right arrow keys are swapped\n    const { prevKey: backwardKey, nextKey: forwardKey } = getArrowKeys('horizontal', isRTL());\n\n    if (key === 'a' && (ctrlKey || metaKey)) {\n      if (multi) {\n        event.preventDefault();\n        this.selectAll(currentItem);\n      }\n\n      return;\n    }\n\n    if (ctrlKey || metaKey) {\n      return;\n    }\n\n    if (key === 'Enter') {\n      event.preventDefault();\n      // Also trigger any custom `onclick` handler on the item\n      currentItem.click();\n\n      return;\n    }\n\n    if (key === ' ') {\n      event.preventDefault();\n\n      if (multi) {\n        this.selectItem(currentItem, { additive: !shiftKey, range: shiftKey });\n      } else {\n        this.selectItem(currentItem);\n      }\n\n      return;\n    }\n\n    if (key === 'ArrowDown' || key === 'ArrowUp') {\n      event.preventDefault();\n\n      const newItem = activeItems[key === 'ArrowDown' ? index + 1 : index - 1];\n\n      if (!newItem) {\n        return;\n      }\n\n      if (multi && shiftKey) {\n        this.focusItem(newItem, { select: false });\n        this.selectItem(newItem, { additive: true });\n      } else {\n        this.focusItem(newItem);\n      }\n\n      return;\n    }\n\n    if (key === forwardKey) {\n      event.preventDefault();\n\n      if (!this.isParent(currentItem)) {\n        return;\n      }\n\n      if (!this.isExpanded(currentItem)) {\n        this.expandItem(currentItem, true);\n\n        return;\n      }\n\n      const childItem = this.getChildItems(currentItem).find((item) => activeItems.includes(item));\n\n      if (childItem) {\n        this.focusItem(childItem);\n      }\n\n      return;\n    }\n\n    if (key === backwardKey) {\n      event.preventDefault();\n\n      if (this.isParent(currentItem) && this.isExpanded(currentItem)) {\n        this.expandItem(currentItem, false);\n\n        return;\n      }\n\n      const parentItem = this.getParentItem(currentItem);\n\n      if (parentItem && activeItems.includes(parentItem)) {\n        this.focusItem(parentItem);\n      }\n\n      return;\n    }\n\n    if (key === 'Home' || key === 'End') {\n      event.preventDefault();\n      this.focusItem(key === 'Home' ? activeItems[0] : activeItems[activeItems.length - 1]);\n\n      return;\n    }\n\n    if (key === '*') {\n      event.preventDefault();\n      this.expandSiblings(currentItem);\n\n      return;\n    }\n\n    if (isPrintableKey(event)) {\n      this.typeAhead(key, currentItem);\n    }\n  }\n\n  /**\n   * Clean up event listeners and the observer.\n   * @override\n   */\n  destroy() {\n    super.destroy();\n    this.observer.disconnect();\n  }\n}\n\n/**\n * Activate a new tree. Takes the params to be passed to the `Tree` constructor, or a getter\n * function for reactive params, and returns an attachment.\n */\nexport const activateTree = createWidgetAttachment(Tree);\n","<!--\n  @component\n  A tree view widget that displays a hierarchical list of items, which can be expanded, collapsed\n  and selected.\n  @see https://w3c.github.io/aria/#tree\n  @see https://www.w3.org/WAI/ARIA/apg/patterns/treeview/\n-->\n<script>\n  import { activateTree } from '../../services/tree.svelte.js';\n\n  /**\n   * @import { CommonEventHandlers, ContainerProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {HTMLElement} [element] A reference to the wrapper element.\n   * @property {boolean} [readonly] Whether to make the widget read-only. An alias of the\n   * `aria-readonly` attribute.\n   * @property {boolean} [multiple] Whether to allow selecting more than one `<TreeItem>`. An alias\n   * of the `aria-multiselectable` attribute.\n   * @property {boolean} [clickToSelect] Whether to select an item by clicking on it.\n   * @property {boolean} [selectionFollowsFocus] Whether to select an item as soon as it receives\n   * focus. Default: `true` on a single-select tree, `false` on a multi-select tree.\n   * @property {boolean} [expandOnSelect] Whether to expand or collapse a parent item when the item\n   * itself, rather than its chevron, is clicked or activated with the Enter key.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element. Required\n   * unless the `aria-labelledby` attribute is provided.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {CommonEventHandlers & ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    element = $bindable(),\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    multiple = false,\n    clickToSelect = true,\n    selectionFollowsFocus = undefined,\n    expandOnSelect = true,\n    ariaLabel = undefined,\n    children,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<!--\n  The `aria-readonly` attribute is not part of the `tree` role in ARIA, but we still use it to keep\n  the API consistent with the other selection widgets, including `<Listbox>`. It’s only rendered\n  when the widget is actually read-only, so assistive technologies can safely ignore it.\n-->\n<!-- svelte-ignore a11y_role_supports_aria_props -->\n<div\n  bind:this={element}\n  {...restProps}\n  role=\"tree\"\n  class=\"sui tree {className}\"\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-readonly={readonly || undefined}\n  aria-multiselectable={multiple}\n  aria-label={ariaLabel}\n  onChange={(/** @type {CustomEvent} */ event) => {\n    onChange?.(event);\n  }}\n  {@attach activateTree(() => ({ clickToSelect, selectionFollowsFocus, expandOnSelect }))}\n>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    {@render children?.()}\n  </div>\n</div>\n\n<style>[role=tree] {\n  display: flex;\n  flex-direction: column;\n  margin: var(--sui-focus-ring-width);\n  border-width: var(--sui-tree-border-width, 1px);\n  border-style: var(--sui-tree-border-style, solid);\n  border-color: var(--sui-tree-border-color, var(--sui-secondary-border-color));\n  border-radius: var(--sui-tree-border-radius, 4px);\n  padding: var(--sui-tree-padding, 4px);\n  min-width: var(--sui-tree-min-width, calc(var(--sui-option-height) * 5));\n  overflow: auto;\n  color: var(--sui-tree-foreground-color, var(--sui-control-foreground-color));\n  background-color: var(--sui-tree-background-color);\n  font-family: var(--sui-control-font-family);\n  font-size: var(--sui-control-font-size);\n  line-height: var(--sui-control-line-height);\n}\n\n.inner {\n  display: contents;\n}</style>\n","/**\n * Helpers behind `<AppShell>`, kept apart from the component so they can be tested on their own.\n */\n\n/**\n * `<input>` types that hold editable text.\n */\nconst TEXT_INPUT_TYPES = ['text', 'search', 'url', 'tel', 'email', 'password', 'number'];\n\n/**\n * Whether the browser’s context menu should be allowed on the given element. The shell suppresses\n * it to feel more like a native app, except where it’s actually useful: on text fields and rich\n * text editors, where the menu carries the cut/copy/paste and spell-checking commands.\n * @param {EventTarget | null} target The element that was right-clicked.\n * @returns {boolean} `true` to leave the browser’s context menu alone.\n */\nexport const shouldAllowContextMenu = (target) => {\n  // Allow context menu in developer mode\n  if (document.documentElement.matches('[data-env=\"dev\"]')) {\n    return true;\n  }\n\n  if (!(target instanceof Element)) {\n    return false;\n  }\n\n  // Allow context menu on text inputs and contentEditable elements. Only the input types that hold\n  // editable text qualify, not a checkbox or a button. (Every `<input>` has a `maxLength` property\n  // whatever its type, so that can’t tell them apart.)\n  return (\n    target instanceof HTMLTextAreaElement ||\n    // The `type` property is normalized: lowercased, and `text` for a missing or unknown type\n    (target instanceof HTMLInputElement && TEXT_INPUT_TYPES.includes(target.type)) ||\n    /** @type {HTMLElement | null} */ (target.closest('[role=\"textbox\"]'))?.contentEditable ===\n      'true'\n  );\n};\n","<!--\n  @component\n  Provide an application’s shell that makes the web app more like a native app. It also handles the\n  dark/light mode switching. This component has to be placed directly under `<body>` (or\n  `<div style=\"display:contents\">` in a SvelteKit app).\n-->\n<script>\n  import { onMount } from 'svelte';\n  import { shouldAllowContextMenu } from './app-shell.js';\n  import FontLinks from './font-links.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'horizontal' | 'vertical'} [orientation] Orientation of the app shell’s children.\n   * @property {Snippet} [children] Primary slot content.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    orientation = 'horizontal',\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  let fontLoaded = $state(false);\n\n  onMount(() => {\n    const mediaQuery = globalThis.matchMedia('(prefers-color-scheme: dark)');\n    const { dataset } = document.documentElement;\n\n    /**\n     * Apply the Dark or Light theme.\n     */\n    const applyTheme = () => {\n      if (dataset.autoTheming !== 'false') {\n        dataset.theme = mediaQuery.matches ? 'dark' : 'light';\n      }\n    };\n\n    applyTheme();\n    mediaQuery.addEventListener('change', applyTheme);\n\n    const fontTimer = globalThis.setTimeout(() => {\n      fontLoaded = true;\n    }, 1000);\n\n    return () => {\n      mediaQuery.removeEventListener('change', applyTheme);\n      globalThis.clearTimeout(fontTimer);\n    };\n  });\n</script>\n\n<!--\n  In the viewport meta tag, we set the maximum scale to 1 to prevent zooming in on mobile devices.\n  @see https://stackoverflow.com/q/2989263\n-->\n<svelte:head>\n  <meta\n    name=\"viewport\"\n    content={[\n      'width=device-width',\n      'initial-scale=1',\n      'maximum-scale=1',\n      'interactive-widget=resizes-content',\n    ].join(', ')}\n  />\n  <meta name=\"google\" content=\"notranslate\" />\n  <FontLinks />\n</svelte:head>\n\n{#if !fontLoaded}\n  <!-- Preload fonts, including the icons -->\n  <div class=\"font-loader\" aria-hidden=\"true\" style:opacity=\"0\">\n    Loading <strong>Sveltia</strong> <em>UI</em>\n    <span role=\"none\" class=\"material-symbols-outlined\">favorite</span>\n  </div>\n{/if}\n\n<div\n  {...restProps}\n  role=\"none\"\n  class={['sui', 'app-shell', orientation]}\n  ondragover={(event) => event.preventDefault()}\n  ondrop={(event) => event.preventDefault()}\n  oncontextmenu={(event) => {\n    if (!shouldAllowContextMenu(event.target)) {\n      event.preventDefault();\n    }\n  }}\n>\n  {@render children?.()}\n</div>\n\n<style>:global(:root),\n:global(:host) {\n  --sui-base-hue: 210;\n  --sui-highlight-foreground-color: hsl(var(--sui-foreground-color-1-hsl));\n  --sui-primary-foreground-color: hsl(var(--sui-foreground-color-2-hsl));\n  --sui-secondary-foreground-color: hsl(var(--sui-foreground-color-3-hsl));\n  --sui-tertiary-foreground-color: hsl(var(--sui-foreground-color-4-hsl));\n  --sui-disabled-foreground-color: hsl(var(--sui-foreground-color-5-hsl));\n  --sui-error-foreground-color: hsl(\n    var(--sui-error-color-hue) var(--sui-alert-foreground-color-saturation)\n      var(--sui-alert-foreground-color-lightness)\n  );\n  --sui-warning-foreground-color: hsl(\n    var(--sui-warning-color-hue) var(--sui-alert-foreground-color-saturation)\n      var(--sui-alert-foreground-color-lightness)\n  );\n  --sui-info-foreground-color: hsl(\n    var(--sui-info-color-hue) var(--sui-alert-foreground-color-saturation)\n      var(--sui-alert-foreground-color-lightness)\n  );\n  --sui-success-foreground-color: hsl(\n    var(--sui-success-color-hue) var(--sui-alert-foreground-color-saturation)\n      var(--sui-alert-foreground-color-lightness)\n  );\n  --sui-hover-background-color: hsl(var(--sui-background-color-5-hsl) / 35%);\n  --sui-selected-background-color: hsl(var(--sui-background-color-5-hsl) / 75%);\n  --sui-active-background-color: hsl(var(--sui-background-color-5-hsl) / 100%);\n  --sui-content-background-color: hsl(var(--sui-background-color-1-hsl));\n  --sui-code-background-color: hsl(var(--sui-background-color-3-hsl));\n  --sui-primary-background-color: hsl(var(--sui-background-color-2-hsl));\n  --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl) / 80%);\n  --sui-secondary-background-color: hsl(var(--sui-background-color-3-hsl));\n  --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl) / 80%);\n  --sui-tertiary-background-color: hsl(var(--sui-background-color-4-hsl));\n  --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl) / 80%);\n  --sui-disabled-background-color: hsl(var(--sui-background-color-4-hsl));\n  --sui-error-background-color: hsl(\n    var(--sui-error-color-hue) var(--sui-alert-background-color-saturation)\n      var(--sui-alert-background-color-lightness)\n  );\n  --sui-warning-background-color: hsl(\n    var(--sui-warning-color-hue) var(--sui-alert-background-color-saturation)\n      var(--sui-alert-background-color-lightness)\n  );\n  --sui-info-background-color: hsl(\n    var(--sui-info-color-hue) var(--sui-alert-background-color-saturation)\n      var(--sui-alert-background-color-lightness)\n  );\n  --sui-success-background-color: hsl(\n    var(--sui-success-color-hue) var(--sui-alert-background-color-saturation)\n      var(--sui-alert-background-color-lightness)\n  );\n  --sui-disabled-opacity: 0.35;\n  --sui-modal-border-width: 0;\n  --sui-focus-ring-width: 2px;\n  --sui-focus-ring-color: var(--sui-primary-accent-color);\n  --sui-focus-ring-offset: 1px;\n  --sui-primary-border-color: hsl(var(--sui-border-color-2-hsl));\n  --sui-secondary-border-color: hsl(var(--sui-border-color-3-hsl));\n  --sui-error-border-color: hsl(\n    var(--sui-error-color-hue) var(--sui-alert-border-color-saturation)\n      var(--sui-error-border-color-lightness, var(--sui-alert-border-color-lightness))\n  );\n  --sui-warning-border-color: hsl(\n    var(--sui-warning-color-hue) var(--sui-alert-border-color-saturation)\n      var(--sui-alert-border-color-lightness)\n  );\n  --sui-info-border-color: hsl(\n    var(--sui-info-color-hue) var(--sui-alert-border-color-saturation)\n      var(--sui-alert-border-color-lightness)\n  );\n  --sui-success-border-color: hsl(\n    var(--sui-success-color-hue) var(--sui-alert-border-color-saturation)\n      var(--sui-alert-border-color-lightness)\n  );\n  --sui-popup-shadow-color: hsl(var(--sui-shadow-color) / 40%);\n  --sui-popup-backdrop-color: hsl(var(--sui-shadow-color) / 40%);\n  --sui-font-family-default: \"Source Sans 3\", system-ui, sans-serif;\n  --sui-font-size-xxx-large: 25px;\n  --sui-font-size-xx-large: 21px;\n  --sui-font-size-x-large: 19px;\n  --sui-font-size-large: 17px;\n  --sui-font-size-default: 15px;\n  --sui-font-size-small: 13px;\n  --sui-font-size-x-small: 11px;\n  --sui-font-weight-normal: 400;\n  --sui-font-weight-bold: 700;\n  --sui-font-family-monospace: \"Noto Sans Mono\", ui-monospace, monospace;\n  --sui-font-size-monospace: 0.9em;\n  --sui-line-height-default: 1.2;\n  --sui-line-height-compact: 1.4;\n  --sui-line-height-comfortable: 1.6;\n  --sui-word-spacing-normal: 1px;\n  --sui-heading-margin: 0;\n  --sui-heading-font-family: var(--sui-font-family-default);\n  --sui-heading-font-weight: var(--sui-font-weight-bold);\n  --sui-heading-line-height: var(--sui-line-height-default);\n  --sui-paragraph-margin: 1.75em;\n  --sui-menuitem-font-size: 14px;\n  --sui-control-small-border-width: 1px;\n  --sui-control-small-border-radius: calc(var(--sui-control-small-height) / 8);\n  --sui-control-small-padding: 0 calc((var(--sui-control-small-height) / 5));\n  --sui-control-small-height: 24px;\n  --sui-control-medium-border-width: 1px;\n  --sui-control-medium-border-radius: calc(var(--sui-control-medium-height) / 8);\n  --sui-control-medium-padding: 0 calc((var(--sui-control-medium-height) / 4));\n  --sui-control-medium-height: 32px;\n  --sui-control-large-border-width: 1px;\n  --sui-control-large-border-radius: calc(var(--sui-control-large-height) / 8);\n  --sui-control-large-padding: 0 calc((var(--sui-control-large-height) / 3));\n  --sui-control-large-height: 40px;\n  --sui-control-border-color: hsl(var(--sui-border-color-2-hsl));\n  --sui-control-foreground-color: var(--sui-primary-foreground-color);\n  --sui-control-background-color: hsl(var(--sui-background-color-4-hsl));\n  --sui-control-font-family: var(--sui-font-family-default);\n  --sui-control-font-size: var(--sui-font-size-default);\n  --sui-control-line-height: var(--sui-line-height-compact);\n  --sui-button-small-border-radius: var(--sui-control-small-border-radius);\n  --sui-button-small-padding: var(--sui-control-small-padding);\n  --sui-button-small-height: var(--sui-control-small-height);\n  --sui-button-medium-border-radius: var(--sui-control-medium-border-radius);\n  --sui-button-medium-padding: var(--sui-control-medium-padding);\n  --sui-button-medium-height: var(--sui-control-medium-height);\n  --sui-button-large-border-radius: var(--sui-control-large-border-radius);\n  --sui-button-large-padding: var(--sui-control-large-padding);\n  --sui-button-large-height: var(--sui-control-large-height);\n  --sui-button-border-color: var(--sui-control-border-color);\n  --sui-button-background-color: var(--sui-control-background-color);\n  --sui-checkbox-border-radius: var(--sui-control-medium-border-radius);\n  --sui-checkbox-height: 20px;\n  --sui-checkbox-border-color: hsl(var(--sui-border-color-1-hsl));\n  --sui-checkbox-background-color: var(--sui-control-background-color);\n  --sui-readonly-accent-color: var(--sui-tertiary-foreground-color);\n  --sui-readonly-accent-color-inverted: var(--sui-primary-background-color);\n  --sui-option-border-radius: var(--sui-control-medium-border-radius);\n  --sui-option-padding: calc((var(--sui-control-medium-height) / 6))\n    calc((var(--sui-control-medium-height) / 5));\n  --sui-option-height: var(--sui-control-medium-height);\n  --sui-listbox-border-radius: var(--sui-control-medium-border-radius);\n  --sui-listbox-border-color: var(--sui-control-border-color);\n  --sui-listbox-foreground-color: var(--sui-control-foreground-color);\n  --sui-listbox-background-color: hsl(var(--sui-background-color-1-hsl));\n  --sui-tree-border-radius: var(--sui-control-medium-border-radius);\n  --sui-tree-border-color: var(--sui-control-border-color);\n  --sui-tree-foreground-color: var(--sui-control-foreground-color);\n  --sui-tree-background-color: hsl(var(--sui-background-color-1-hsl));\n  --sui-tree-item-border-radius: var(--sui-control-medium-border-radius);\n  --sui-tree-item-padding: var(--sui-option-padding);\n  --sui-tree-item-height: var(--sui-control-medium-height);\n  --sui-tree-item-indent: 16px;\n  --sui-textbox-border-radius: var(--sui-control-medium-border-radius);\n  --sui-textbox-height: var(--sui-control-medium-height);\n  --sui-textbox-border-color: var(--sui-control-border-color);\n  --sui-textbox-foreground-color: var(--sui-control-foreground-color);\n  --sui-textbox-background-color: hsl(var(--sui-background-color-1-hsl));\n  --sui-textbox-font-family: var(--sui-font-family-default);\n  --sui-textbox-font-size: var(--sui-font-size-default);\n  --sui-textbox-singleline-padding: 0 8px;\n  --sui-textbox-singleline-min-width: 240px;\n  --sui-textbox-singleline-line-height: var(--sui-line-height-compact);\n  --sui-textbox-multiline-padding: 16px;\n  --sui-textbox-multiline-min-width: 480px;\n  --sui-textbox-multiline-line-height: var(--sui-line-height-comfortable);\n  --sui-tab-height: var(--sui-control-medium-height);\n  --sui-tab-small-height: var(--sui-control-small-height);\n  --sui-tab-medium-height: var(--sui-control-medium-height);\n  --sui-tab-large-height: var(--sui-control-large-height);\n  --sui-primary-toolbar-size: 56px;\n  --sui-secondary-toolbar-size: 48px;\n  --sui-bottom-navigation-height: var(--sui-primary-toolbar-size);\n  --sui-primary-row-height: 56px;\n  --sui-secondary-row-height: 40px;\n}\n@media (pointer: coarse) {\n  :global(:root),\n  :global(:host) {\n    --sui-menuitem-height: 40px;\n    --sui-control-small-height: 32px;\n    --sui-control-medium-height: 40px;\n    --sui-control-large-height: 48px;\n    --sui-checkbox-height: 24px;\n    --sui-secondary-row-height: 48px;\n  }\n}\n@media (prefers-reduced-transparency) {\n  :global(:root),\n  :global(:host) {\n    --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl));\n    --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl));\n    --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl));\n  }\n}\n:global(:root[data-theme=light]),\n:global(:host[data-theme=light]) {\n  color-scheme: light;\n  --sui-foreground-color-1-hsl: var(--sui-base-hue) 5% 5%;\n  --sui-foreground-color-2-hsl: var(--sui-base-hue) 5% 25%;\n  --sui-foreground-color-3-hsl: var(--sui-base-hue) 5% 35%;\n  --sui-foreground-color-4-hsl: var(--sui-base-hue) 5% 45%;\n  --sui-foreground-color-5-hsl: var(--sui-base-hue) 5% 65%;\n  --sui-background-color-1-hsl: var(--sui-base-hue) 5% 100%;\n  --sui-background-color-2-hsl: var(--sui-base-hue) 5% 98%;\n  --sui-background-color-3-hsl: var(--sui-base-hue) 5% 95%;\n  --sui-background-color-4-hsl: var(--sui-base-hue) 5% 92%;\n  --sui-background-color-5-hsl: var(--sui-base-hue) 5% 84%;\n  --sui-border-color-1-hsl: var(--sui-base-hue) 5% 60%;\n  --sui-border-color-2-hsl: var(--sui-base-hue) 5% 72%;\n  --sui-border-color-3-hsl: var(--sui-base-hue) 5% 80%;\n  --sui-shadow-color: var(--sui-base-hue) 10% 0%;\n  --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 80% 40%);\n  --sui-primary-accent-color-light: hsl(var(--sui-base-hue) 80% 45%);\n  --sui-primary-accent-color: hsl(var(--sui-base-hue) 80% 40%);\n  --sui-primary-accent-color-dark: hsl(var(--sui-base-hue) 80% 35%);\n  --sui-primary-accent-color-inverted: hsl(var(--sui-base-hue) 10% 100%);\n  --sui-primary-accent-color-translucent: hsl(var(--sui-base-hue) 80% 50% / 60%);\n  --sui-primary-accent-color-translucent-light: hsl(var(--sui-base-hue) 80% 50% / 40%);\n  --sui-error-color-hue: 0;\n  --sui-warning-color-hue: 40;\n  --sui-info-color-hue: 210;\n  --sui-success-color-hue: 100;\n  --sui-alert-foreground-color-saturation: 85%;\n  --sui-alert-foreground-color-lightness: 25%;\n  --sui-alert-background-color-saturation: 65%;\n  --sui-alert-background-color-lightness: 90%;\n  --sui-alert-border-color-saturation: 48%;\n  --sui-alert-border-color-lightness: 68%;\n  --sui-error-border-color-lightness: 60%;\n}\n:global(:root[data-theme=dark]),\n:global(:host[data-theme=dark]) {\n  color-scheme: dark;\n  --sui-foreground-color-1-hsl: var(--sui-base-hue) 10% 95%;\n  --sui-foreground-color-2-hsl: var(--sui-base-hue) 10% 75%;\n  --sui-foreground-color-3-hsl: var(--sui-base-hue) 10% 65%;\n  --sui-foreground-color-4-hsl: var(--sui-base-hue) 10% 55%;\n  --sui-foreground-color-5-hsl: var(--sui-base-hue) 10% 35%;\n  --sui-background-color-1-hsl: var(--sui-base-hue) 10% 8%;\n  --sui-background-color-2-hsl: var(--sui-base-hue) 10% 10%;\n  --sui-background-color-3-hsl: var(--sui-base-hue) 10% 13%;\n  --sui-background-color-4-hsl: var(--sui-base-hue) 10% 16%;\n  --sui-background-color-5-hsl: var(--sui-base-hue) 10% 26%;\n  --sui-border-color-1-hsl: var(--sui-base-hue) 10% 40%;\n  --sui-border-color-2-hsl: var(--sui-base-hue) 10% 24%;\n  --sui-border-color-3-hsl: var(--sui-base-hue) 10% 20%;\n  --sui-shadow-color: var(--sui-base-hue) 10% 0%;\n  --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 100% 60%);\n  --sui-primary-accent-color-light: hsl(var(--sui-base-hue) 100% 45%);\n  --sui-primary-accent-color: hsl(var(--sui-base-hue) 100% 40%);\n  --sui-primary-accent-color-dark: hsl(var(--sui-base-hue) 100% 35%);\n  --sui-primary-accent-color-inverted: hsl(var(--sui-base-hue) 10% 100%);\n  --sui-primary-accent-color-translucent: hsl(var(--sui-base-hue) 80% 50% / 60%);\n  --sui-primary-accent-color-translucent-light: hsl(var(--sui-base-hue) 80% 50% / 40%);\n  --sui-error-color-hue: 0;\n  --sui-warning-color-hue: 40;\n  --sui-info-color-hue: 210;\n  --sui-success-color-hue: 100;\n  --sui-alert-foreground-color-saturation: 85%;\n  --sui-alert-foreground-color-lightness: 75%;\n  --sui-alert-background-color-saturation: 40%;\n  --sui-alert-background-color-lightness: 10%;\n  --sui-alert-border-color-saturation: 48%;\n  --sui-alert-border-color-lightness: 38%;\n}\n@media (prefers-color-scheme: light) {\n  :global(:root:not([data-theme])),\n  :global(:host:not([data-theme])) {\n    color-scheme: light;\n    --sui-foreground-color-1-hsl: var(--sui-base-hue) 5% 5%;\n    --sui-foreground-color-2-hsl: var(--sui-base-hue) 5% 25%;\n    --sui-foreground-color-3-hsl: var(--sui-base-hue) 5% 35%;\n    --sui-foreground-color-4-hsl: var(--sui-base-hue) 5% 45%;\n    --sui-foreground-color-5-hsl: var(--sui-base-hue) 5% 65%;\n    --sui-background-color-1-hsl: var(--sui-base-hue) 5% 100%;\n    --sui-background-color-2-hsl: var(--sui-base-hue) 5% 98%;\n    --sui-background-color-3-hsl: var(--sui-base-hue) 5% 95%;\n    --sui-background-color-4-hsl: var(--sui-base-hue) 5% 92%;\n    --sui-background-color-5-hsl: var(--sui-base-hue) 5% 84%;\n    --sui-border-color-1-hsl: var(--sui-base-hue) 5% 60%;\n    --sui-border-color-2-hsl: var(--sui-base-hue) 5% 72%;\n    --sui-border-color-3-hsl: var(--sui-base-hue) 5% 80%;\n    --sui-shadow-color: var(--sui-base-hue) 10% 0%;\n    --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 80% 40%);\n    --sui-primary-accent-color-light: hsl(var(--sui-base-hue) 80% 45%);\n    --sui-primary-accent-color: hsl(var(--sui-base-hue) 80% 40%);\n    --sui-primary-accent-color-dark: hsl(var(--sui-base-hue) 80% 35%);\n    --sui-primary-accent-color-inverted: hsl(var(--sui-base-hue) 10% 100%);\n    --sui-primary-accent-color-translucent: hsl(var(--sui-base-hue) 80% 50% / 60%);\n    --sui-primary-accent-color-translucent-light: hsl(var(--sui-base-hue) 80% 50% / 40%);\n    --sui-error-color-hue: 0;\n    --sui-warning-color-hue: 40;\n    --sui-info-color-hue: 210;\n    --sui-success-color-hue: 100;\n    --sui-alert-foreground-color-saturation: 85%;\n    --sui-alert-foreground-color-lightness: 25%;\n    --sui-alert-background-color-saturation: 65%;\n    --sui-alert-background-color-lightness: 90%;\n    --sui-alert-border-color-saturation: 48%;\n    --sui-alert-border-color-lightness: 68%;\n    --sui-error-border-color-lightness: 60%;\n  }\n}\n@media (prefers-color-scheme: dark) {\n  :global(:root:not([data-theme])),\n  :global(:host:not([data-theme])) {\n    color-scheme: dark;\n    --sui-foreground-color-1-hsl: var(--sui-base-hue) 10% 95%;\n    --sui-foreground-color-2-hsl: var(--sui-base-hue) 10% 75%;\n    --sui-foreground-color-3-hsl: var(--sui-base-hue) 10% 65%;\n    --sui-foreground-color-4-hsl: var(--sui-base-hue) 10% 55%;\n    --sui-foreground-color-5-hsl: var(--sui-base-hue) 10% 35%;\n    --sui-background-color-1-hsl: var(--sui-base-hue) 10% 8%;\n    --sui-background-color-2-hsl: var(--sui-base-hue) 10% 10%;\n    --sui-background-color-3-hsl: var(--sui-base-hue) 10% 13%;\n    --sui-background-color-4-hsl: var(--sui-base-hue) 10% 16%;\n    --sui-background-color-5-hsl: var(--sui-base-hue) 10% 26%;\n    --sui-border-color-1-hsl: var(--sui-base-hue) 10% 40%;\n    --sui-border-color-2-hsl: var(--sui-base-hue) 10% 24%;\n    --sui-border-color-3-hsl: var(--sui-base-hue) 10% 20%;\n    --sui-shadow-color: var(--sui-base-hue) 10% 0%;\n    --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 100% 60%);\n    --sui-primary-accent-color-light: hsl(var(--sui-base-hue) 100% 45%);\n    --sui-primary-accent-color: hsl(var(--sui-base-hue) 100% 40%);\n    --sui-primary-accent-color-dark: hsl(var(--sui-base-hue) 100% 35%);\n    --sui-primary-accent-color-inverted: hsl(var(--sui-base-hue) 10% 100%);\n    --sui-primary-accent-color-translucent: hsl(var(--sui-base-hue) 80% 50% / 60%);\n    --sui-primary-accent-color-translucent-light: hsl(var(--sui-base-hue) 80% 50% / 40%);\n    --sui-error-color-hue: 0;\n    --sui-warning-color-hue: 40;\n    --sui-info-color-hue: 210;\n    --sui-success-color-hue: 100;\n    --sui-alert-foreground-color-saturation: 85%;\n    --sui-alert-foreground-color-lightness: 75%;\n    --sui-alert-background-color-saturation: 40%;\n    --sui-alert-background-color-lightness: 10%;\n    --sui-alert-border-color-saturation: 48%;\n    --sui-alert-border-color-lightness: 38%;\n  }\n}\n:global(:root[data-contrast=more][data-theme=light]),\n:global(:host[data-contrast=more][data-theme=light]) {\n  --sui-foreground-color-2-hsl: var(--sui-base-hue) 5% 10%;\n  --sui-foreground-color-3-hsl: var(--sui-base-hue) 5% 18%;\n  --sui-foreground-color-4-hsl: var(--sui-base-hue) 5% 28%;\n  --sui-foreground-color-5-hsl: var(--sui-base-hue) 5% 45%;\n  --sui-background-color-3-hsl: var(--sui-base-hue) 5% 93%;\n  --sui-background-color-4-hsl: var(--sui-base-hue) 5% 88%;\n  --sui-background-color-5-hsl: var(--sui-base-hue) 5% 70%;\n  --sui-border-color-1-hsl: var(--sui-base-hue) 5% 40%;\n  --sui-border-color-2-hsl: var(--sui-base-hue) 5% 55%;\n  --sui-border-color-3-hsl: var(--sui-base-hue) 5% 65%;\n  --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 80% 32%);\n  --sui-primary-accent-color-light: hsl(var(--sui-base-hue) 80% 37%);\n  --sui-primary-accent-color: hsl(var(--sui-base-hue) 80% 32%);\n  --sui-primary-accent-color-dark: hsl(var(--sui-base-hue) 80% 26%);\n  --sui-alert-foreground-color-lightness: 18%;\n  --sui-alert-border-color-saturation: 55%;\n  --sui-alert-border-color-lightness: 40%;\n  --sui-error-border-color-lightness: 40%;\n  --sui-hover-background-color: hsl(var(--sui-background-color-5-hsl) / 60%);\n  --sui-selected-background-color: hsl(var(--sui-background-color-5-hsl));\n  --sui-active-background-color: hsl(var(--sui-background-color-5-hsl));\n  --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl));\n  --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl));\n  --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl));\n  --sui-popup-shadow-color: hsl(var(--sui-shadow-color) / 70%);\n  --sui-popup-backdrop-color: hsl(var(--sui-shadow-color) / 60%);\n  --sui-textbox-border-color: hsl(var(--sui-border-color-1-hsl));\n  --sui-textbox-placeholder-foreground-color: var(--sui-tertiary-foreground-color);\n  --sui-textbox-placeholder-opacity: 1;\n  --sui-disabled-opacity: 0.6;\n  --sui-modal-border-width: 1px;\n}\n:global(:root[data-contrast=more][data-theme=dark]),\n:global(:host[data-contrast=more][data-theme=dark]) {\n  --sui-foreground-color-2-hsl: var(--sui-base-hue) 10% 92%;\n  --sui-foreground-color-3-hsl: var(--sui-base-hue) 10% 85%;\n  --sui-foreground-color-4-hsl: var(--sui-base-hue) 10% 75%;\n  --sui-foreground-color-5-hsl: var(--sui-base-hue) 10% 55%;\n  --sui-background-color-1-hsl: var(--sui-base-hue) 10% 4%;\n  --sui-background-color-2-hsl: var(--sui-base-hue) 10% 7%;\n  --sui-background-color-3-hsl: var(--sui-base-hue) 10% 12%;\n  --sui-background-color-4-hsl: var(--sui-base-hue) 10% 18%;\n  --sui-background-color-5-hsl: var(--sui-base-hue) 10% 40%;\n  --sui-border-color-1-hsl: var(--sui-base-hue) 10% 60%;\n  --sui-border-color-2-hsl: var(--sui-base-hue) 10% 50%;\n  --sui-border-color-3-hsl: var(--sui-base-hue) 10% 40%;\n  --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 100% 70%);\n  --sui-focus-ring-color: var(--sui-primary-accent-color-text);\n  --sui-alert-foreground-color-lightness: 85%;\n  --sui-alert-border-color-saturation: 55%;\n  --sui-alert-border-color-lightness: 55%;\n  --sui-hover-background-color: hsl(var(--sui-background-color-5-hsl) / 60%);\n  --sui-selected-background-color: hsl(var(--sui-background-color-5-hsl));\n  --sui-active-background-color: hsl(var(--sui-background-color-5-hsl));\n  --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl));\n  --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl));\n  --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl));\n  --sui-popup-shadow-color: hsl(var(--sui-shadow-color) / 70%);\n  --sui-popup-backdrop-color: hsl(var(--sui-shadow-color) / 60%);\n  --sui-textbox-border-color: hsl(var(--sui-border-color-1-hsl));\n  --sui-textbox-placeholder-foreground-color: var(--sui-tertiary-foreground-color);\n  --sui-textbox-placeholder-opacity: 1;\n  --sui-disabled-opacity: 0.6;\n  --sui-modal-border-width: 1px;\n}\n@media (prefers-color-scheme: light) {\n  :global(:root[data-contrast=more]:not([data-theme])),\n  :global(:host[data-contrast=more]:not([data-theme])) {\n    --sui-foreground-color-2-hsl: var(--sui-base-hue) 5% 10%;\n    --sui-foreground-color-3-hsl: var(--sui-base-hue) 5% 18%;\n    --sui-foreground-color-4-hsl: var(--sui-base-hue) 5% 28%;\n    --sui-foreground-color-5-hsl: var(--sui-base-hue) 5% 45%;\n    --sui-background-color-3-hsl: var(--sui-base-hue) 5% 93%;\n    --sui-background-color-4-hsl: var(--sui-base-hue) 5% 88%;\n    --sui-background-color-5-hsl: var(--sui-base-hue) 5% 70%;\n    --sui-border-color-1-hsl: var(--sui-base-hue) 5% 40%;\n    --sui-border-color-2-hsl: var(--sui-base-hue) 5% 55%;\n    --sui-border-color-3-hsl: var(--sui-base-hue) 5% 65%;\n    --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 80% 32%);\n    --sui-primary-accent-color-light: hsl(var(--sui-base-hue) 80% 37%);\n    --sui-primary-accent-color: hsl(var(--sui-base-hue) 80% 32%);\n    --sui-primary-accent-color-dark: hsl(var(--sui-base-hue) 80% 26%);\n    --sui-alert-foreground-color-lightness: 18%;\n    --sui-alert-border-color-saturation: 55%;\n    --sui-alert-border-color-lightness: 40%;\n    --sui-error-border-color-lightness: 40%;\n    --sui-hover-background-color: hsl(var(--sui-background-color-5-hsl) / 60%);\n    --sui-selected-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-active-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl));\n    --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl));\n    --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl));\n    --sui-popup-shadow-color: hsl(var(--sui-shadow-color) / 70%);\n    --sui-popup-backdrop-color: hsl(var(--sui-shadow-color) / 60%);\n    --sui-textbox-border-color: hsl(var(--sui-border-color-1-hsl));\n    --sui-textbox-placeholder-foreground-color: var(--sui-tertiary-foreground-color);\n    --sui-textbox-placeholder-opacity: 1;\n    --sui-disabled-opacity: 0.6;\n    --sui-modal-border-width: 1px;\n  }\n}\n@media (prefers-color-scheme: dark) {\n  :global(:root[data-contrast=more]:not([data-theme])),\n  :global(:host[data-contrast=more]:not([data-theme])) {\n    --sui-foreground-color-2-hsl: var(--sui-base-hue) 10% 92%;\n    --sui-foreground-color-3-hsl: var(--sui-base-hue) 10% 85%;\n    --sui-foreground-color-4-hsl: var(--sui-base-hue) 10% 75%;\n    --sui-foreground-color-5-hsl: var(--sui-base-hue) 10% 55%;\n    --sui-background-color-1-hsl: var(--sui-base-hue) 10% 4%;\n    --sui-background-color-2-hsl: var(--sui-base-hue) 10% 7%;\n    --sui-background-color-3-hsl: var(--sui-base-hue) 10% 12%;\n    --sui-background-color-4-hsl: var(--sui-base-hue) 10% 18%;\n    --sui-background-color-5-hsl: var(--sui-base-hue) 10% 40%;\n    --sui-border-color-1-hsl: var(--sui-base-hue) 10% 60%;\n    --sui-border-color-2-hsl: var(--sui-base-hue) 10% 50%;\n    --sui-border-color-3-hsl: var(--sui-base-hue) 10% 40%;\n    --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 100% 70%);\n    --sui-focus-ring-color: var(--sui-primary-accent-color-text);\n    --sui-alert-foreground-color-lightness: 85%;\n    --sui-alert-border-color-saturation: 55%;\n    --sui-alert-border-color-lightness: 55%;\n    --sui-hover-background-color: hsl(var(--sui-background-color-5-hsl) / 60%);\n    --sui-selected-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-active-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl));\n    --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl));\n    --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl));\n    --sui-popup-shadow-color: hsl(var(--sui-shadow-color) / 70%);\n    --sui-popup-backdrop-color: hsl(var(--sui-shadow-color) / 60%);\n    --sui-textbox-border-color: hsl(var(--sui-border-color-1-hsl));\n    --sui-textbox-placeholder-foreground-color: var(--sui-tertiary-foreground-color);\n    --sui-textbox-placeholder-opacity: 1;\n    --sui-disabled-opacity: 0.6;\n    --sui-modal-border-width: 1px;\n  }\n}\n@media (prefers-contrast: more) {\n  :global(:root:not([data-contrast])[data-theme=light]),\n  :global(:host:not([data-contrast])[data-theme=light]) {\n    --sui-foreground-color-2-hsl: var(--sui-base-hue) 5% 10%;\n    --sui-foreground-color-3-hsl: var(--sui-base-hue) 5% 18%;\n    --sui-foreground-color-4-hsl: var(--sui-base-hue) 5% 28%;\n    --sui-foreground-color-5-hsl: var(--sui-base-hue) 5% 45%;\n    --sui-background-color-3-hsl: var(--sui-base-hue) 5% 93%;\n    --sui-background-color-4-hsl: var(--sui-base-hue) 5% 88%;\n    --sui-background-color-5-hsl: var(--sui-base-hue) 5% 70%;\n    --sui-border-color-1-hsl: var(--sui-base-hue) 5% 40%;\n    --sui-border-color-2-hsl: var(--sui-base-hue) 5% 55%;\n    --sui-border-color-3-hsl: var(--sui-base-hue) 5% 65%;\n    --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 80% 32%);\n    --sui-primary-accent-color-light: hsl(var(--sui-base-hue) 80% 37%);\n    --sui-primary-accent-color: hsl(var(--sui-base-hue) 80% 32%);\n    --sui-primary-accent-color-dark: hsl(var(--sui-base-hue) 80% 26%);\n    --sui-alert-foreground-color-lightness: 18%;\n    --sui-alert-border-color-saturation: 55%;\n    --sui-alert-border-color-lightness: 40%;\n    --sui-error-border-color-lightness: 40%;\n    --sui-hover-background-color: hsl(var(--sui-background-color-5-hsl) / 60%);\n    --sui-selected-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-active-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl));\n    --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl));\n    --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl));\n    --sui-popup-shadow-color: hsl(var(--sui-shadow-color) / 70%);\n    --sui-popup-backdrop-color: hsl(var(--sui-shadow-color) / 60%);\n    --sui-textbox-border-color: hsl(var(--sui-border-color-1-hsl));\n    --sui-textbox-placeholder-foreground-color: var(--sui-tertiary-foreground-color);\n    --sui-textbox-placeholder-opacity: 1;\n    --sui-disabled-opacity: 0.6;\n    --sui-modal-border-width: 1px;\n  }\n  :global(:root:not([data-contrast])[data-theme=dark]),\n  :global(:host:not([data-contrast])[data-theme=dark]) {\n    --sui-foreground-color-2-hsl: var(--sui-base-hue) 10% 92%;\n    --sui-foreground-color-3-hsl: var(--sui-base-hue) 10% 85%;\n    --sui-foreground-color-4-hsl: var(--sui-base-hue) 10% 75%;\n    --sui-foreground-color-5-hsl: var(--sui-base-hue) 10% 55%;\n    --sui-background-color-1-hsl: var(--sui-base-hue) 10% 4%;\n    --sui-background-color-2-hsl: var(--sui-base-hue) 10% 7%;\n    --sui-background-color-3-hsl: var(--sui-base-hue) 10% 12%;\n    --sui-background-color-4-hsl: var(--sui-base-hue) 10% 18%;\n    --sui-background-color-5-hsl: var(--sui-base-hue) 10% 40%;\n    --sui-border-color-1-hsl: var(--sui-base-hue) 10% 60%;\n    --sui-border-color-2-hsl: var(--sui-base-hue) 10% 50%;\n    --sui-border-color-3-hsl: var(--sui-base-hue) 10% 40%;\n    --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 100% 70%);\n    --sui-focus-ring-color: var(--sui-primary-accent-color-text);\n    --sui-alert-foreground-color-lightness: 85%;\n    --sui-alert-border-color-saturation: 55%;\n    --sui-alert-border-color-lightness: 55%;\n    --sui-hover-background-color: hsl(var(--sui-background-color-5-hsl) / 60%);\n    --sui-selected-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-active-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl));\n    --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl));\n    --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl));\n    --sui-popup-shadow-color: hsl(var(--sui-shadow-color) / 70%);\n    --sui-popup-backdrop-color: hsl(var(--sui-shadow-color) / 60%);\n    --sui-textbox-border-color: hsl(var(--sui-border-color-1-hsl));\n    --sui-textbox-placeholder-foreground-color: var(--sui-tertiary-foreground-color);\n    --sui-textbox-placeholder-opacity: 1;\n    --sui-disabled-opacity: 0.6;\n    --sui-modal-border-width: 1px;\n  }\n}\n@media (prefers-contrast: more) and (prefers-color-scheme: light) {\n  :global(:root:not([data-contrast]):not([data-theme])),\n  :global(:host:not([data-contrast]):not([data-theme])) {\n    --sui-foreground-color-2-hsl: var(--sui-base-hue) 5% 10%;\n    --sui-foreground-color-3-hsl: var(--sui-base-hue) 5% 18%;\n    --sui-foreground-color-4-hsl: var(--sui-base-hue) 5% 28%;\n    --sui-foreground-color-5-hsl: var(--sui-base-hue) 5% 45%;\n    --sui-background-color-3-hsl: var(--sui-base-hue) 5% 93%;\n    --sui-background-color-4-hsl: var(--sui-base-hue) 5% 88%;\n    --sui-background-color-5-hsl: var(--sui-base-hue) 5% 70%;\n    --sui-border-color-1-hsl: var(--sui-base-hue) 5% 40%;\n    --sui-border-color-2-hsl: var(--sui-base-hue) 5% 55%;\n    --sui-border-color-3-hsl: var(--sui-base-hue) 5% 65%;\n    --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 80% 32%);\n    --sui-primary-accent-color-light: hsl(var(--sui-base-hue) 80% 37%);\n    --sui-primary-accent-color: hsl(var(--sui-base-hue) 80% 32%);\n    --sui-primary-accent-color-dark: hsl(var(--sui-base-hue) 80% 26%);\n    --sui-alert-foreground-color-lightness: 18%;\n    --sui-alert-border-color-saturation: 55%;\n    --sui-alert-border-color-lightness: 40%;\n    --sui-error-border-color-lightness: 40%;\n    --sui-hover-background-color: hsl(var(--sui-background-color-5-hsl) / 60%);\n    --sui-selected-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-active-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl));\n    --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl));\n    --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl));\n    --sui-popup-shadow-color: hsl(var(--sui-shadow-color) / 70%);\n    --sui-popup-backdrop-color: hsl(var(--sui-shadow-color) / 60%);\n    --sui-textbox-border-color: hsl(var(--sui-border-color-1-hsl));\n    --sui-textbox-placeholder-foreground-color: var(--sui-tertiary-foreground-color);\n    --sui-textbox-placeholder-opacity: 1;\n    --sui-disabled-opacity: 0.6;\n    --sui-modal-border-width: 1px;\n  }\n}\n@media (prefers-contrast: more) and (prefers-color-scheme: dark) {\n  :global(:root:not([data-contrast]):not([data-theme])),\n  :global(:host:not([data-contrast]):not([data-theme])) {\n    --sui-foreground-color-2-hsl: var(--sui-base-hue) 10% 92%;\n    --sui-foreground-color-3-hsl: var(--sui-base-hue) 10% 85%;\n    --sui-foreground-color-4-hsl: var(--sui-base-hue) 10% 75%;\n    --sui-foreground-color-5-hsl: var(--sui-base-hue) 10% 55%;\n    --sui-background-color-1-hsl: var(--sui-base-hue) 10% 4%;\n    --sui-background-color-2-hsl: var(--sui-base-hue) 10% 7%;\n    --sui-background-color-3-hsl: var(--sui-base-hue) 10% 12%;\n    --sui-background-color-4-hsl: var(--sui-base-hue) 10% 18%;\n    --sui-background-color-5-hsl: var(--sui-base-hue) 10% 40%;\n    --sui-border-color-1-hsl: var(--sui-base-hue) 10% 60%;\n    --sui-border-color-2-hsl: var(--sui-base-hue) 10% 50%;\n    --sui-border-color-3-hsl: var(--sui-base-hue) 10% 40%;\n    --sui-primary-accent-color-text: hsl(var(--sui-base-hue) 100% 70%);\n    --sui-focus-ring-color: var(--sui-primary-accent-color-text);\n    --sui-alert-foreground-color-lightness: 85%;\n    --sui-alert-border-color-saturation: 55%;\n    --sui-alert-border-color-lightness: 55%;\n    --sui-hover-background-color: hsl(var(--sui-background-color-5-hsl) / 60%);\n    --sui-selected-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-active-background-color: hsl(var(--sui-background-color-5-hsl));\n    --sui-primary-background-color-translucent: hsl(var(--sui-background-color-2-hsl));\n    --sui-secondary-background-color-translucent: hsl(var(--sui-background-color-3-hsl));\n    --sui-tertiary-background-color-translucent: hsl(var(--sui-background-color-4-hsl));\n    --sui-popup-shadow-color: hsl(var(--sui-shadow-color) / 70%);\n    --sui-popup-backdrop-color: hsl(var(--sui-shadow-color) / 60%);\n    --sui-textbox-border-color: hsl(var(--sui-border-color-1-hsl));\n    --sui-textbox-placeholder-foreground-color: var(--sui-tertiary-foreground-color);\n    --sui-textbox-placeholder-opacity: 1;\n    --sui-disabled-opacity: 0.6;\n    --sui-modal-border-width: 1px;\n  }\n}\n\n:global(.material-symbols-outlined) {\n  font-variation-settings: \"FILL\" 0, \"wght\" 300, \"GRAD\" 0, \"opsz\" 24;\n}\n:global(*),\n:global(::before),\n:global(::after) {\n  overflow-anchor: none;\n  scroll-behavior: smooth;\n  box-sizing: border-box;\n  outline-offset: 0px;\n  outline-width: var(--sui-focus-ring-width) !important;\n  outline-style: solid;\n  outline-color: transparent;\n  border-width: 0;\n  border-style: solid;\n  vertical-align: top;\n  font-size-adjust: inherit;\n}\n@media (prefers-reduced-motion) {\n  :global(*),\n  :global(::before),\n  :global(::after) {\n    scroll-behavior: auto;\n    transition-duration: 1ms !important;\n  }\n}\n:global(::selection) {\n  background-color: var(--sui-primary-accent-color-translucent-light);\n}\n:global(*) {\n  -webkit-tap-highlight-color: transparent;\n}\n:global(:focus) {\n  z-index: 1;\n  outline-width: 0;\n}\n:global(:focus-visible) {\n  outline-color: var(--sui-focus-ring-color);\n  outline-offset: var(--sui-focus-ring-offset, 0);\n  z-index: 2;\n}\n:global(h1) {\n  margin: var(--sui-h1-margin, var(--sui-heading-margin));\n  font-size: var(--sui-h1-font-size, 34px);\n  font-family: var(--sui-h1-font-family, var(--sui-heading-font-family));\n  font-weight: var(--sui-h1-font-weight, var(--sui-heading-font-weight));\n  line-height: var(--sui-h1-line-height, var(--sui-heading-line-height));\n}\n:global(h2) {\n  margin: var(--sui-h2-margin, var(--sui-heading-margin));\n  font-size: var(--sui-h2-font-size, 30px);\n  font-family: var(--sui-h2-font-family, var(--sui-heading-font-family));\n  font-weight: var(--sui-h2-font-weight, var(--sui-heading-font-weight));\n  line-height: var(--sui-h2-line-height, var(--sui-heading-line-height));\n}\n:global(h3) {\n  margin: var(--sui-h3-margin, var(--sui-heading-margin));\n  font-size: var(--sui-h3-font-size, 26px);\n  font-family: var(--sui-h3-font-family, var(--sui-heading-font-family));\n  font-weight: var(--sui-h3-font-weight, var(--sui-heading-font-weight));\n  line-height: var(--sui-h3-line-height, var(--sui-heading-line-height));\n}\n:global(h4) {\n  margin: var(--sui-h4-margin, var(--sui-heading-margin));\n  font-size: var(--sui-h4-font-size, 22px);\n  font-family: var(--sui-h4-font-family, var(--sui-heading-font-family));\n  font-weight: var(--sui-h4-font-weight, var(--sui-heading-font-weight));\n  line-height: var(--sui-h4-line-height, var(--sui-heading-line-height));\n}\n:global(h5) {\n  margin: var(--sui-h5-margin, var(--sui-heading-margin));\n  font-size: var(--sui-h5-font-size, 18px);\n  font-family: var(--sui-h5-font-family, var(--sui-heading-font-family));\n  font-weight: var(--sui-h5-font-weight, var(--sui-heading-font-weight));\n  line-height: var(--sui-h5-line-height, var(--sui-heading-line-height));\n}\n:global(h6) {\n  margin: var(--sui-h6-margin, var(--sui-heading-margin));\n  font-size: var(--sui-h6-font-size, 14px);\n  font-family: var(--sui-h6-font-family, var(--sui-heading-font-family));\n  font-weight: var(--sui-h6-font-weight, var(--sui-heading-font-weight));\n  line-height: var(--sui-h6-line-height, var(--sui-heading-line-height));\n}\n:global(strong) {\n  font-weight: var(--sui-font-weight-bold, bold);\n}\n:global(a) {\n  color: var(--sui-primary-accent-color-text);\n  text-decoration: none;\n  text-underline-offset: 2px;\n}\n:global(a:is(:hover, :focus, :active)) {\n  text-decoration: underline;\n}\n:global(:is(:root, :host)[data-underline-links=\"true\"]) :global(a) {\n  text-decoration: underline;\n}\n:global(:is(p, ul, ol, dl)) {\n  margin: var(--sui-paragraph-margin) 0;\n  line-height: var(--sui-line-height-comfortable);\n}\n:global(:is(ul, ol)) {\n  padding-inline: 2em;\n}\n:global(:is(code, pre)) {\n  border-radius: 4px;\n  background-color: var(--sui-code-background-color);\n  font-family: var(--sui-font-family-monospace);\n  font-size: var(--sui-font-size-monospace);\n  vertical-align: -0.05em;\n}\n:global(pre) {\n  padding: 8px;\n  line-height: var(--sui-line-height-compact);\n  -webkit-user-select: text;\n  user-select: text;\n}\n:global(code) {\n  padding: 2px 4px;\n}\n:global(table) {\n  border-collapse: collapse;\n}\n:global(:is(th, td)) {\n  border: 1px solid var(--sui-textbox-border-color);\n  padding: 8px;\n}\n:global(blockquote) {\n  margin-inline: 16px 0;\n  border-inline-start: 4px solid var(--sui-textbox-border-color);\n  padding-inline-start: 12px;\n}\n:global(:is(.disabled, [aria-disabled=true], [inert]):not(body)) {\n  cursor: default;\n  pointer-events: none;\n  -webkit-user-select: none;\n  user-select: none;\n  filter: grayscale(1) opacity(var(--sui-disabled-opacity, 0.35));\n}\n:global(:is(.disabled, [aria-disabled=true], [inert]):not(body)) :global(*) {\n  filter: grayscale(0) opacity(1);\n}\n:global(:is(.disabled, [aria-disabled=true], [inert])) :global(*) {\n  cursor: default;\n  pointer-events: none;\n  -webkit-user-select: none;\n  user-select: none;\n}\n:global(:is(.readonly, [aria-readonly=true]):not(body)) {\n  cursor: default;\n}\n:global(:is(.readonly, [aria-readonly=true]):not(body)) :global(*) {\n  cursor: default;\n}\n\n.font-loader {\n  position: absolute;\n  inset-inline-start: -99999px;\n  font-family: var(--sui-font-family-default);\n}\n\n.app-shell {\n  position: fixed;\n  inset: 0;\n  overflow: hidden;\n  width: 100%;\n  height: 100%;\n  color: var(--sui-primary-foreground-color);\n  background-color: var(--sui-primary-background-color);\n  font-family: var(--sui-font-family-default);\n  font-size: var(--sui-font-size-default);\n  font-weight: var(--sui-font-weight-normal, normal);\n  word-spacing: var(--sui-word-spacing-normal);\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n  -webkit-user-select: none;\n  user-select: none;\n  touch-action: none;\n  cursor: default;\n}\n.app-shell.horizontal {\n  display: flex;\n  flex-direction: row;\n  overflow: hidden;\n}\n.app-shell.vertical {\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}</style>\n","<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Snippet} [children] Slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    children = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div role=\"none\" class=\"sui empty-state\">\n  {@render children?.()}\n</div>\n\n<style>.empty-state {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  gap: 16px;\n  padding: 16px;\n  width: 100%;\n  height: 100%;\n  text-align: center;\n}</style>\n","<!--\n  @component\n  A generic group layout.\n  @see https://w3c.github.io/aria/#group\n-->\n<script>\n  /**\n   * @import { ContainerProps, WidgetStateProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   */\n\n  /**\n   * @type {ContainerProps & WidgetStateProps & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    hidden = false,\n    disabled = false,\n    ariaLabel = undefined,\n    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div\n  {...restProps}\n  role=\"group\"\n  class=\"sui group {className}\"\n  {hidden}\n  aria-hidden={hidden}\n  aria-disabled={disabled}\n  aria-label={ariaLabel}\n>\n  <div role=\"none\" class=\"inner\" inert={disabled}>\n    {@render children?.()}\n  </div>\n</div>\n\n<style>.inner {\n  display: contents;\n}</style>\n","<script>\n  import { removeVisibilityResolver, waitForVisibility } from '@sveltia/utils/element';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [eager] Whether to render the content right away rather than once it comes\n   * into view, such as an item just added to a list, which is then scrolled into view and focused.\n   * Only the value at mount is used, as the content stays rendered anyway.\n   * @property {Snippet} children Slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    eager = false,\n    children,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {HTMLElement | null} */\n  let placeholder = $state(null);\n  /** @type {boolean} */\n  // svelte-ignore state_referenced_locally\n  let visible = $state(eager);\n\n  $effect(() => {\n    if (placeholder) {\n      (async () => {\n        await waitForVisibility(placeholder);\n        visible = true;\n      })();\n    }\n\n    // Clean up\n    return () => {\n      if (placeholder) {\n        removeVisibilityResolver(placeholder);\n      }\n    };\n  });\n</script>\n\n{#if visible}\n  {@render children()}\n{:else}\n  <div class=\"placeholder\" bind:this={placeholder}></div>\n{/if}\n\n<style>\n  .placeholder {\n    height: 64px;\n  }\n\n</style>\n","export default {\"ok\":\"OK\",\"cancel\":\"Cancel\",\"close\":\"Close\",\"clear\":\"Clear\",\"insert\":\"Insert\",\"update\":\"Update\",\"remove\":\"Remove\",\"collapse\":\"Collapse\",\"expand\":\"Expand\",\"dismiss\":\"Dismiss\",\"alert\":{\"error\":\"Error\",\"warning\":\"Warning\",\"info\":\"Information\",\"success\":\"Success\"},\"role_descriptions\":{\"disclosure\":\"disclosure\",\"option_group\":\"option group\",\"menu_item_group\":\"menu item group\",\"checkbox_group\":\"checkbox group\",\"table_head\":\"table head\",\"table_body\":\"table body\",\"table_foot\":\"table foot\",\"grid_head\":\"grid head\",\"grid_body\":\"grid body\",\"grid_foot\":\"grid foot\"},\"emoji_suggestions\":\"Emoji Suggestions\",\"calendar\":{\"year\":\"Year\",\"previous_decade\":\"Previous Decade\",\"next_decade\":\"Next Decade\",\"month\":\"Month\",\"previous_month\":\"Previous Month\",\"next_month\":\"Next Month\",\"today\":\"Today\"},\"copy_button\":{\"copy\":\"Copy\",\"copied\":\"Copied\"},\"split_button\":{\"x_options\":\"{$name} Options\",\"more_options\":\"More Options\"},\"combobox\":{\"select_an_option\":\"Select an option…\",\"filter_options\":\"Filter Options\",\"no_matching_options\":\"No matching options found\"},\"number_input\":{\"increase\":\"Increase\",\"decrease\":\"Decrease\",\"range\":\"From {$min} to {$max}\",\"min\":\"Minimum {$min}\",\"max\":\"Maximum {$max}\"},\"password_input\":{\"show_password\":\"Show Password\",\"hide_password\":\"Hide Password\"},\"secret_input\":{\"show_secret\":\"Show Secret\",\"hide_secret\":\"Hide Secret\"},\"select_tags\":{\"selected_options\":\"Selected Options\",\"remove_x\":\"Remove {$name}\"},\"text_editor\":{\"text_editor\":\"Text Editor\",\"code_editor\":\"Code Editor\",\"text_style_options\":\"Text Style Options\",\"show_text_style_options\":\"Show Text Style Options\",\"paragraph\":\"Paragraph\",\"heading_1\":\"Heading 1\",\"heading_2\":\"Heading 2\",\"heading_3\":\"Heading 3\",\"heading_4\":\"Heading 4\",\"heading_5\":\"Heading 5\",\"heading_6\":\"Heading 6\",\"bulleted_list\":\"Bulleted List\",\"numbered_list\":\"Numbered List\",\"task_list\":\"Task List\",\"blockquote\":\"Block Quote\",\"code_block\":\"Code Block\",\"bold\":\"Bold\",\"italic\":\"Italic\",\"underline\":\"Underline\",\"strikethrough\":\"Strikethrough\",\"code\":\"Code\",\"link\":\"Link\",\"insert_link\":\"Insert Link\",\"edit_link\":\"Edit Link\",\"remove_link\":\"Remove Link\",\"text\":\"Text\",\"url\":\"URL\",\"open_in_new_tab\":\"Open in New Tab\",\"insert_table\":\"Insert Table\",\"rows\":\"Rows\",\"columns\":\"Columns\",\"table_options\":\"Table Options\",\"show_table_options\":\"Show Table Options\",\"insert_row_above\":\"Insert Row Above\",\"insert_row_below\":\"Insert Row Below\",\"insert_column_left\":\"Insert Column Left\",\"insert_column_right\":\"Insert Column Right\",\"delete_row\":\"Delete Row\",\"delete_column\":\"Delete Column\",\"delete_table\":\"Delete Table\",\"insert_horizontal_rule\":\"Insert Horizontal Rule\",\"alignment_options\":\"Alignment Options\",\"show_alignment_options\":\"Show Alignment Options\",\"align_left\":\"Left Align\",\"align_center\":\"Center Align\",\"align_right\":\"Right Align\",\"align_justify\":\"Justify Align\",\"edit_in_markdown\":\"Edit in Markdown\",\"edit_in_html\":\"Edit in HTML\",\"converter_error\":\"Unable to enable rich text mode. Please use the plain text editor instead.\",\"language\":\"Language\",\"plain_text\":\"Plain Text\"}};","import { uuidPattern } from './crypto.js';\nimport { escapeRegExp } from './string.js';\n\n/**\n * Get a regular expression that matches a blob URL.\n * @param {string} flags Flags for `RegExp`.\n * @returns {RegExp} Regular expression.\n */\n// NOTE: deliberately *not* cached. A `g`- or `y`-flagged `RegExp` carries a mutable `lastIndex`,\n// so handing the same instance to multiple callers would make `test()`/`exec()` results depend on\n// previous calls. Constructing a fresh pattern here is cheap next to that hazard.\nconst getBlobRegex = (flags = '') =>\n  new RegExp(\n    `\\\\bblob:${escapeRegExp(globalThis.location.origin)}\\\\/${uuidPattern.source}\\\\b`,\n    flags,\n  );\n\n/**\n * A regular expression to match a file path. Chained extensions of tarballs like `archive.tar.gz`\n * are treated as a special case.\n */\nconst filePathRegEx = /(?:(.+?)\\/)?(([^/]+?)(?:\\.((?:[Tt][Aa][Rr]\\.)?[a-zA-Z0-9]+))?)$/;\n\n/**\n * List of MIME types that can be considered as plaintext.\n */\nconst textFileTypes = [\n  'application/atom+xml',\n  'application/javascript',\n  'application/json',\n  'application/ld+json',\n  'application/rss+xml',\n  'application/xhtml+xml',\n  'application/xml',\n  'application/yaml', // RFC 9512\n  'image/svg+xml',\n];\n\n/**\n * Whether the given MIME type is plaintext.\n * @param {string} type MIME type.\n * @returns {boolean} Result.\n */\nconst isTextFileType = (type) => type.startsWith('text/') || textFileTypes.includes(type);\n\n/**\n * Get information about a file path. If the path has no file name, like an empty string, `basename`\n * and `filename` are empty strings.\n * @param {string} path Path to be parsed.\n * @returns {{ dirname?: string, basename: string, filename: string, extension?: string }} Result.\n * @see https://www.php.net/manual/en/function.pathinfo.php\n */\nconst getPathInfo = (path) => {\n  let end = path.length;\n\n  // Like PHP, ignore trailing slashes, so `foo/bar/` gives `bar` rather than nothing at all. Scan\n  // instead of using `/\\/+$/`, which backtracks quadratically over a long run of inner slashes\n  while (path[end - 1] === '/') {\n    end -= 1;\n  }\n\n  const [, dirname, basename = '', filename = '', extension] =\n    path.slice(0, end).match(filePathRegEx) ?? [];\n\n  return { dirname, basename, filename, extension };\n};\n\n/**\n * Encode the given (partial) file path or file name. Since {@link encodeURIComponent} encodes\n * slashes, we need to split and join.\n * @param {string} path Original path.\n * @returns {string} Encoded path.\n */\nconst encodeFilePath = (path) => path.split('/').map(encodeURIComponent).join('/');\n/**\n * Decode the given (partial) file path or file name.\n * @param {string} path Encoded path.\n * @returns {string} Decoded path.\n */\nconst decodeFilePath = (path) => decodeURIComponent(path);\n\n/**\n * Check if the given file matches one of the unique file type specifiers.\n * @param {File} file File to be evaluated.\n * @param {string[]} specifiers List of file type specifiers.\n * @returns {boolean} Result.\n * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/accept\n */\nconst isValidFileType = (file, specifiers) => {\n  if (!specifiers.length) {\n    return true;\n  }\n\n  // Lowercase the file name once rather than once per specifier.\n  const fileName = file.name.toLowerCase();\n\n  return specifiers.some((rawSpecifier) => {\n    const specifier = rawSpecifier.toLowerCase();\n\n    if (specifier.startsWith('.')) {\n      return fileName.endsWith(specifier);\n    }\n\n    const [type, subtype] = specifier.split('/');\n\n    if (subtype === '*') {\n      return file.type.split('/')[0] === type;\n    }\n\n    return file.type === specifier;\n  });\n};\n\n/**\n * Scan local files in nested folders and return them in a flat array, sorted by name.\n * @param {DataTransfer} dataTransfer From `drop` event.\n * @param {object} [options] Options.\n * @param {string} [options.accept] Accepted file types, which is the same as the `accept`\n * property for HTML `<input type=\"file\">`.\n * @returns {Promise<File[]>} Files.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry\n */\nconst scanFiles = async ({ items }, { accept } = {}) => {\n  const specifiers = accept\n    ? accept\n        .split(',')\n        .map((specifier) => specifier.trim())\n        .filter(Boolean)\n    : [];\n\n  /**\n   * Read a file entry, resolving with `null` if the file is inaccessible.\n   * @param {FileSystemFileEntry} entry File entry.\n   * @returns {Promise<File | null>} File.\n   */\n  const getFile = (entry) =>\n    new Promise((resolve) => {\n      entry.file(\n        resolve,\n        // Skip inaccessible files\n        /* v8 ignore next */\n        () => resolve(null),\n      );\n    });\n\n  /**\n   * Read one batch of entries from a directory, resolving with an empty array if the directory is\n   * unreadable so the caller doesn’t wait forever.\n   * @param {FileSystemDirectoryReader} reader Directory reader.\n   * @returns {Promise<FileSystemEntry[]>} Entries; empty when the directory is exhausted.\n   */\n  const readEntries = (reader) =>\n    new Promise((resolve) => {\n      reader.readEntries(\n        resolve,\n        /* v8 ignore next */\n        () => resolve([]),\n      );\n    });\n\n  /**\n   * Read files recursively from the filesystem.\n   * @param {FileSystemEntry} entry Either a file or directory entry.\n   * @returns {Promise<File[]>} Files.\n   */\n  const readEntry = async (entry) => {\n    // Skip hidden files\n    if (entry.name.startsWith('.')) {\n      return [];\n    }\n\n    if (entry.isFile) {\n      const file = await getFile(/** @type {FileSystemFileEntry} */ (entry));\n\n      return file && isValidFileType(file, specifiers) ? [file] : [];\n    }\n\n    const reader = /** @type {FileSystemDirectoryEntry} */ (entry).createReader();\n    /** @type {FileSystemEntry[]} */\n    const entries = [];\n\n    // `readEntries()` returns entries in batches, so call it until it returns an empty batch\n    for (;;) {\n      // eslint-disable-next-line no-await-in-loop\n      const batch = await readEntries(reader);\n\n      if (!batch.length) {\n        break;\n      }\n\n      entries.push(...batch);\n    }\n\n    return (await Promise.all(entries.map(readEntry))).flat();\n  };\n\n  // Get all the entries synchronously; `DataTransfer` items are cleared once the event handler\n  // returns\n  const entries = [...items]\n    .map((item) => item.webkitGetAsEntry())\n    .filter((entry) => entry !== null);\n\n  const files = (await Promise.all(entries.map(readEntry))).flat();\n\n  return files.sort((a, b) => a.name.localeCompare(b.name));\n};\n\n/**\n * Read the given file as plaintext. On Windows, the result may include CRLF line breaks, and some\n * legacy files use lone CR. Convert any CRLF/CR to LF to parse entries properly.\n * @param {File | Blob} file File.\n * @returns {Promise<string>} Content.\n */\nconst readAsText = async (file) => (await file.text()).replace(/\\r\\n?/g, '\\n');\n\n/**\n * Wrap the given string in a plaintext `Blob`, or return the given file as is.\n * @param {File | Blob | string} input Input file or string.\n * @returns {Blob} Blob.\n */\nconst toBlob = (input) =>\n  typeof input === 'string' ? new Blob([input], { type: 'text/plain' }) : input;\n\n/**\n * Get the data URL of the given input.\n * @param {File | Blob | string} input Input file or string.\n * @returns {Promise<string>} Data URL like `data:text/plain;base64,...`.\n */\nconst getDataURL = async (input) => {\n  const blob = toBlob(input);\n  const reader = new FileReader();\n\n  return new Promise((resolve, reject) => {\n    /**\n     * Return the result once the content is read.\n     */\n    reader.onload = () => {\n      resolve(/** @type {string} */ (reader.result));\n    };\n\n    /**\n     * Reject the promise when the file read fails.\n     */\n    reader.onerror = () => {\n      reject(reader.error);\n    };\n\n    reader.readAsDataURL(blob);\n  });\n};\n\n/**\n * Encode the given input, either a file or a string, as a Base64-encoded string.\n * @param {File | Blob | string} input Input file or string.\n * @returns {Promise<string>} Base64.\n */\nconst encodeBase64 = async (input) => {\n  const blob = toBlob(input);\n\n  // Encode the bytes directly rather than going through `getDataURL()`. The data URL route holds\n  // the whole Base64 payload as a string and then allocates a second full-size copy when splitting\n  // off the `data:...;base64,` prefix — roughly 2× the encoded size at peak, on top of a\n  // `FileReader` event-loop round trip.\n  return new Uint8Array(await blob.arrayBuffer()).toBase64();\n};\n\n/**\n * Decode a Base64-encoded string as a plaintext UTF-8 string. Uses `Promise` to be consistent with\n * {@link encodeBase64}.\n * @param {string} base64 Base64-encoded string.\n * @returns {Promise<string>} Decoded string.\n * @see https://stackoverflow.com/q/21797299\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/fromBase64\n */\nconst decodeBase64 = async (base64) => {\n  const buffer = Uint8Array.fromBase64(base64);\n\n  return new TextDecoder().decode(buffer);\n};\n\n/**\n * File extensions for MIME types whose subtype isn’t their usual extension.\n * @type {Map<string, string>}\n */\nconst typeExtensions = new Map([\n  ['application/gzip', 'gz'],\n  ['application/javascript', 'js'],\n  ['application/ld+json', 'jsonld'],\n  ['audio/mpeg', 'mp3'],\n  ['text/javascript', 'js'],\n  ['text/markdown', 'md'],\n  ['text/plain', 'txt'],\n  ['video/quicktime', 'mov'],\n]);\n\n/**\n * Get a file extension for the given MIME type, to name a file that has no name.\n * @param {string} type MIME type, e.g. `image/svg+xml`. Can be empty.\n * @returns {string | undefined} Extension, e.g. `svg`, or `undefined` if the type doesn’t suggest\n * one, like the generic `application/octet-stream`, or vendor-specific and experimental types such\n * as `application/vnd.ms-excel` and `application/x-tar`.\n */\nconst getExtensionForType = (type) => {\n  // A type may carry parameters like `text/plain;charset=utf-8`\n  const essence = type.toLowerCase().split(';')[0].trim();\n  const mapped = typeExtensions.get(essence);\n\n  if (mapped) {\n    return mapped;\n  }\n\n  // A subtype may carry a suffix like `svg+xml`\n  const subtype = essence.split('/')[1]?.split('+')[0];\n\n  if (!subtype || /[.-]/.test(subtype)) {\n    return undefined;\n  }\n\n  return subtype;\n};\n\n/**\n * Save the given file locally.\n * @param {File | Blob} file File to be saved.\n * @param {string} [name] File name. Required if the `file` param is a `Blob`.\n */\nconst saveFile = (file, name) => {\n  const link = document.createElement('a');\n  const blobURL = URL.createObjectURL(file);\n  // A `Blob` may have an empty `type`\n  const extension = getExtensionForType(file.type);\n\n  link.download =\n    name || /** @type {File} */ (file).name || [Date.now(), extension].filter(Boolean).join('.');\n  link.href = blobURL;\n  link.click();\n\n  // Revoke asynchronously so the browser has time to initiate the download. Revoking synchronously\n  // can cancel the download in some browsers (e.g. Firefox/Safari).\n  globalThis.setTimeout(() => {\n    URL.revokeObjectURL(blobURL);\n  }, 0);\n};\n\nexport {\n  decodeBase64,\n  decodeFilePath,\n  encodeBase64,\n  encodeFilePath,\n  getBlobRegex,\n  getDataURL,\n  getPathInfo,\n  isTextFileType,\n  isValidFileType,\n  readAsText,\n  saveFile,\n  scanFiles,\n};\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n  if (a === b) return true;\n\n  if (a && b && typeof a == 'object' && typeof b == 'object') {\n    if (a.constructor !== b.constructor) return false;\n\n    var length, i, keys;\n    if (Array.isArray(a)) {\n      length = a.length;\n      if (length != b.length) return false;\n      for (i = length; i-- !== 0;)\n        if (!equal(a[i], b[i])) return false;\n      return true;\n    }\n\n\n\n    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n    keys = Object.keys(a);\n    length = keys.length;\n    if (length !== Object.keys(b).length) return false;\n\n    for (i = length; i-- !== 0;)\n      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n    for (i = length; i-- !== 0;) {\n      var key = keys[i];\n\n      if (!equal(a[key], b[key])) return false;\n    }\n\n    return true;\n  }\n\n  // true if both NaN, false otherwise\n  return a!==a && b!==b;\n};\n","import { UNPKG_BASE_URL } from '$lib/services/app';\n\n/**\n * The URL of the JSON schema for Sveltia CMS configuration files. This is used to validate the\n * configuration file and provide helpful error messages when the configuration is invalid.\n * @see https://sveltiacms.app/en/docs/config-basics#validation-and-autocomplete\n */\nexport const SCHEMA_URL = `${UNPKG_BASE_URL}/schema/sveltia-cms.json`;\n\nconst { DEV, VITE_SITE_URL } = import.meta.env;\n\n/**\n * The local live site URL. Local development can be done by loading a CMS config file from a\n * separate dev server. By default, this assumes a local SvelteKit site is running on port 5174\n * along with Sveltia CMS on port 5173. The site URL can be specified with the `VITE_SITE_URL`\n * environment variable. For example, run `VITE_SITE_URL=http://localhost:3000 pnpm dev` for\n * Next.js. You probably need to define the `Access-Control-Allow-Origin: *` HTTP response header\n * with the dev server’s middleware, or loading the CMS config file may fail due to a CORS error.\n */\nexport const DEV_SITE_URL = DEV\n  ? VITE_SITE_URL || 'http://localhost:5174'\n  : /* v8 ignore next */ undefined;\n\n/**\n * Path of the CMS config file on the local live site during development.\n */\nexport const DEV_CONFIG_PATH = '/admin/config.yml';\n\n/**\n * Supported MIME types for configuration files.\n */\nexport const SUPPORTED_TYPES = [\n  'text/yaml', // legacy\n  'application/x-yaml', // legacy\n  'application/yaml', // default\n  'application/toml',\n  'application/json',\n];\n","import equal from 'fast-deep-equal';\nimport { untrack } from 'svelte';\n\n/**\n * Wrap the given plain object in a deeply reactive `$state` proxy. Runes are only available in\n * Svelte-compiled modules, so this lets a plain service module create reactive state, e.g. an\n * entry draft, that Svelte components can then read and mutate reactively.\n * @template {object} T\n * @param {T} value Plain object to wrap. A value that is already a `$state` proxy is returned as\n * is.\n * @param {string[]} [staticKeys] Properties holding data that never changes while the state\n * object is alive, such as the collection configuration in an entry draft. Svelte’s proxy leaves a\n * read-only property alone, so these are handed out as they are: the reader gets the original\n * object rather than a proxy of it, and doesn’t depend on anything in it.\n *\n * This is not just an optimization. A proxy is created per state object, so two state objects\n * built from the same configuration hand out two different proxies of it. Replacing one with the\n * other — which is what saving an entry with the editor left open does — then looks like a new\n * value to every keyed `{#each}` block iterating the fields, and Svelte answers a write made while\n * an effect is running by walking the derived graph below it in search of the effect itself. That\n * walk doesn’t memoize, so in a deeply nested entry editor, where every level multiplies the\n * number of paths to the same derived, it takes exponentially longer with each level of nesting\n * and eventually hangs the browser.\n * @returns {T} Reactive proxy.\n * @see https://github.com/sveltia/sveltia-cms/issues/1006\n */\nexport const createState = (value, staticKeys = []) => {\n  staticKeys.forEach((key) => {\n    // A key the object doesn’t carry is skipped rather than defined as `undefined`, so that one\n    // list can be shared by callers that assemble the object slightly differently\n    if (Object.hasOwn(value, key)) {\n      Object.defineProperty(value, key, {\n        value: /** @type {any} */ (value)[key],\n        writable: false,\n        enumerable: true,\n        configurable: true,\n      });\n    }\n  });\n\n  const state = $state(value);\n\n  return state;\n};\n\n/**\n * Take a static, deeply cloned snapshot of the given value, detached from any `$state` proxy. Same\n * as `$state.snapshot()`, made available to plain service modules.\n * @template T\n * @param {T} value Value to clone.\n * @returns {T} Snapshot.\n */\nexport const getSnapshot = (value) => /** @type {T} */ ($state.snapshot(value));\n\n/**\n * Create a reactive box holding a value that is replaced as a whole, e.g. a list of entries that\n * is reloaded, or a flag. The value is held in `$state.raw`, so it’s not proxied: reading\n * `current` from a component or a `$derived` tracks the box, and assigning `current` notifies the\n * readers, but mutating the value in place doesn’t. Because the value is not proxied, it can be\n * safely passed to APIs that can’t handle a proxy, such as `structuredClone()` or IndexedDB.\n * @template T\n * @param {T} [initialValue] Initial value.\n * @returns {{ current: T }} Reactive box.\n */\nexport const createRawState = (initialValue) => {\n  let current = $state.raw(/** @type {T} */ (initialValue));\n\n  return {\n    /**\n     * Get the current value.\n     * @returns {T} Value.\n     */\n    get current() {\n      return current;\n    },\n    /**\n     * Set a new value.\n     * @param {T} value Value.\n     */\n    set current(value) {\n      current = value;\n    },\n  };\n};\n\n/**\n * Create a reactive box holding a deeply reactive value, like `$state`. Unlike\n * {@link createRawState}, the value is proxied, so a property of it can be mutated in place, or\n * bound to with `bind:`, and the readers are notified. Use it for a small object like a dialog or\n * toast state, not for data that is passed to APIs that can’t handle a proxy.\n * @template T\n * @param {T} initialValue Initial value.\n * @returns {{ current: T }} Reactive box.\n */\nexport const createDeepState = (initialValue) => {\n  const state = $state({ current: initialValue });\n\n  return state;\n};\n\n/**\n * Create a read-only reactive box whose value is derived from other reactive state. The getter is\n * re-evaluated lazily, only when one of the values it read has changed since the last read.\n * @template T\n * @param {() => T} getter Function computing the value.\n * @returns {{ readonly current: T }} Reactive box.\n */\nexport const createDerivedState = (getter) => {\n  const current = $derived.by(getter);\n\n  return {\n    /**\n     * Get the current value.\n     * @returns {T} Value.\n     */\n    get current() {\n      return current;\n    },\n  };\n};\n\n/**\n * Create a read-only reactive box like {@link createDerivedState}, but keep handing out the\n * previous value as long as the new one is deeply equal to it. A derived value only notifies what\n * depends on it when it’s a different object, so this stops a change that leaves the value as it\n * was from rippling any further. For example, the sort conditions picked out of a view object stay\n * the same object when the view is replaced to switch from list to grid, so the sorted list isn’t\n * recomputed.\n * @template T\n * @param {() => T} getter Function computing the value.\n * @returns {{ readonly current: T }} Reactive box.\n */\nexport const createStableDerivedState = (getter) => {\n  /** @type {T | undefined} */\n  let previous;\n\n  return createDerivedState(() => {\n    const value = getter();\n\n    if (!equal(value, previous)) {\n      previous = value;\n    }\n\n    return /** @type {T} */ (previous);\n  });\n};\n\n/**\n * Put a request the UI answers, e.g. with a confirmation dialog, in the given box, and wait for the\n * answer. The request gets a `respond` method that answers it and takes it down. An earlier request\n * still in the box is answered with the fallback first, as leaving it unresolved would hang\n * whatever awaits it.\n * @template {{ respond: (answer: A) => void }} R\n * @template A\n * @param {{ current: R | undefined }} state Box holding the pending request.\n * @param {Omit<R, 'respond'>} props Properties of the request other than `respond`.\n * @param {A} fallback Answer given to an earlier request.\n * @returns {Promise<A>} Answer.\n */\nexport const requestAnswer = (state, props, fallback) => {\n  state.current?.respond(fallback);\n\n  return new Promise((resolve) => {\n    const request = /** @type {R} */ ({\n      ...props,\n      /**\n       * Answer the request.\n       * @param {A} answer Answer.\n       */\n      respond: (answer) => {\n        // Only take down the dialog that belongs to this request, so answering a stale one can’t\n        // dismiss a newer one. Resolving an already settled promise does nothing\n        if (state.current === request) {\n          state.current = undefined;\n        }\n\n        resolve(answer);\n      },\n    });\n\n    state.current = request;\n  });\n};\n\n/**\n * Run the given function whenever the reactive state it reads has changed, like `$effect` in a\n * component, but for a service module that lives as long as the app. The function is first run\n * asynchronously, after the current task, and never synchronously on state changes, so a service\n * that needs a value updated right away should do so directly rather than in an effect.\n * @param {() => void | (() => void)} fn Function to run. It can return a cleanup function, which\n * is called before the next run.\n * @returns {() => void} Function to stop the effect.\n */\nexport const createRootEffect = (fn) =>\n  $effect.root(() => {\n    $effect(fn);\n  });\n\n/**\n * Run the given function whenever the given dependencies have changed, like `$effect`, but without\n * tracking the state the function itself reads. Use it in a component for a function that reads\n * more state than it should react to, e.g. one syncing two values in both directions, where\n * tracking the target would set off an infinite loop.\n * @param {() => unknown} getDependencies Function reading the reactive state to be tracked. Its\n * return value is ignored; wrap several values in an array, e.g. `() => [a, b]`.\n * @param {() => void | (() => void)} fn Function to run. It can return a cleanup function, which\n * is called before the next run.\n */\nexport const watch = (getDependencies, fn) => {\n  $effect(() => {\n    getDependencies();\n\n    return untrack(fn);\n  });\n};\n\n/**\n * Run an async function whenever the reactive state it reads before its first `await` has changed,\n * like `$effect`, and pass the result on, unless the function has been run again in the meantime.\n * This keeps the result of a slow run for an earlier state from replacing the result for a later\n * one. Use it in a component.\n * @template T\n * @param {() => Promise<T> | undefined} fn Function to run. It can return `undefined` instead of a\n * `Promise` to skip the run, e.g. while a required value is missing.\n * @param {(result: T) => void} onResult Function receiving the result of the latest run.\n * @param {(error: unknown) => void} [onError] Function receiving the error the latest run has been\n * rejected with. An error of a run that has been superseded is ignored. Without this, the error is\n * left unhandled.\n */\nexport const watchAsync = (fn, onResult, onError) => {\n  $effect(() => {\n    const promise = fn();\n\n    if (!promise) {\n      return undefined;\n    }\n\n    let stale = false;\n\n    promise.then(\n      (result) => {\n        if (!stale) {\n          onResult(result);\n        }\n      },\n      onError &&\n        ((error) => {\n          if (!stale) {\n            onError(error);\n          }\n        }),\n    );\n\n    return () => {\n      stale = true;\n    };\n  });\n};\n\n/**\n * Keep a field value and the value of its input in sync in both directions, like a bindable prop\n * and the local state bound to an input widget. A change to either side is converted and written to\n * the other side, but only if the converted value is different, so that the other side’s watcher\n * doesn’t set off an infinite loop. Each side is watched with {@link watch}, so the converters can\n * read other state, e.g. the field configuration, without being rerun on changes to it. The\n * arguments are positional because an arrow function in an object literal would need a JSDoc\n * comment of its own at every call site.\n *\n * The field value is only written once the user has edited the input, so that it differs from what\n * the field value was last converted to. A value the input can’t represent, like a decimal number\n * in an integer field, converts to an input that doesn’t convert back to the same value, so writing\n * it back right away would replace the stored value as soon as the editor is opened, without any\n * user action, and the next save would lose it.\n * @template V, I\n * @param {() => V} getValue Function returning the field value.\n * @param {(value: V) => void} setValue Function updating the field value.\n * @param {() => I} getInput Function returning the input value.\n * @param {(input: I) => void} setInput Function updating the input value.\n * @param {(value: V) => I} [toInput] Function converting a field value to an input value. Defaults\n * to returning the value as is.\n * @param {(input: I) => V} [toValue] Function converting an input value to a field value. Defaults\n * to returning the value as is.\n * @returns {{ updateInput: () => void, updateValue: () => void }} Functions to sync the input\n * value with the field value and vice versa on demand, e.g. when the input loses focus.\n */\nexport const syncValues = (\n  getValue,\n  setValue,\n  getInput,\n  setInput,\n  toInput = (value) => /** @type {I} */ (/** @type {unknown} */ (value)),\n  toValue = (input) => /** @type {V} */ (/** @type {unknown} */ (input)),\n) => {\n  /**\n   * Input value converted from the field value the last time the input was synced with it.\n   * @type {I | undefined}\n   */\n  let syncedInput;\n\n  /**\n   * Update the input value based on the field value.\n   */\n  const updateInput = () => {\n    const input = toInput(getValue());\n\n    if (getInput() !== input) {\n      setInput(input);\n    }\n\n    syncedInput = input;\n  };\n\n  /**\n   * Update the field value based on the input value.\n   */\n  const updateValue = () => {\n    const value = toValue(getInput());\n\n    if (getValue() !== value) {\n      setValue(value);\n    }\n  };\n\n  watch(getValue, updateInput);\n  watch(getInput, () => {\n    // Skip the input that merely reflects the field value, including the one set on the first run\n    if (getInput() !== syncedInput) {\n      updateValue();\n    }\n  });\n\n  return { updateInput, updateValue };\n};\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { InternalCmsConfig } from '$lib/types/private';\n */\n\n/**\n * Parsed CMS configuration. This lives in its own module, apart from the loader and parser in\n * `$lib/services/config`, so that a service object created at module evaluation time, such as an\n * S3-compatible media library service, can read the configuration without a circular dependency:\n * the config parser imports the list of media library services. Note that a test mocking\n * `$lib/services/config` doesn’t affect the modules that import the state from here; mock this\n * module instead when testing those.\n * @type {{ current: InternalCmsConfig | undefined }}\n */\nexport const cmsConfig = createRawState();\n","import { DEV_SITE_URL } from '$lib/services/config/constants';\nimport { cmsConfig as parsedCmsConfig } from '$lib/services/config/state';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { ConfigParserCollectors, InternalCmsConfig } from '$lib/types/private';\n * @import { CmsConfig } from '$lib/types/public';\n */\n\nexport { DEV_SITE_URL };\n\n/**\n * Parsed CMS configuration. The state box is defined in the `state` module so that modules the\n * config parser depends on can read it without a circular import. It’s exported here as a constant\n * rather than a re-export, because tests assign `cmsConfig` through the module namespace, which\n * type-checks differently for an alias.\n * @type {{ current: InternalCmsConfig | undefined }}\n */\nexport const cmsConfig = parsedCmsConfig;\n\n/**\n * @type {Partial<CmsConfig>}\n */\nexport const rawCmsConfig = {};\n\n/**\n * @type {{ current: string | undefined }}\n */\nexport const cmsConfigVersion = createRawState();\n\n/**\n * @type {{ current: string[] }}\n */\nexport const cmsConfigErrors = createRawState([]);\n\n/**\n * Whether the CMS configuration has been loaded, regardless of whether it contains errors.\n */\nexport const cmsConfigLoaded = createDerivedState(\n  () => !!cmsConfig.current || !!cmsConfigErrors.current.length,\n);\n\n/**\n * Collectors used during config parsing.\n * @type {ConfigParserCollectors}\n */\nexport const collectors = {\n  errors: new Set(),\n  warnings: new Set(),\n  mediaFields: new Set(),\n  relationFields: new Set(),\n  formatLocales: new Set(),\n};\n","/**\n * @import {\n * CollectionType,\n * InternalCollection,\n * } from '$lib/types/private';\n * @import {\n * Collection,\n * CollectionDivider,\n * CollectionFile,\n * EntryCollection,\n * FileCollection,\n * } from '$lib/types/public';\n */\n\n/**\n * Check if the given collection is an entry collection. An entry collection is defined as one that\n * has the `fields` property that is an array and does not have the `files` property. Its entries\n * are stored in the `folder`, or in the single `file`, which the config parser requires one of.\n * @param {Collection} collection Collection definition.\n * @returns {collection is EntryCollection} Whether the collection is an entry collection.\n */\nexport const isEntryCollection = (collection) =>\n  // @ts-ignore\n  Array.isArray(collection.fields) && !Array.isArray(collection.files);\n\n/**\n * Check if the given collection is a file collection. A file collection is defined as one that has\n * the `files` property that is an array.\n * @param {Collection} collection Collection definition.\n * @returns {collection is FileCollection} Whether the collection is a file collection.\n */\nexport const isFileCollection = (collection) =>\n  // @ts-ignore\n  Array.isArray(collection.files);\n\n/**\n * Check if the given collection is a singleton collection. A singleton collection is a special type\n * of file collection that has the name `_singletons`.\n * @param {Collection} collection Collection definition.\n * @returns {collection is FileCollection} Whether the collection is a singleton collection.\n */\nexport const isSingletonCollection = (collection) =>\n  isFileCollection(collection) && collection.name === '_singletons';\n\n/**\n * Check if the given collection is an entry collection storing all the entries in one file, defined\n * with the `file` option, as an array of objects.\n * @param {InternalCollection | undefined} collection Collection.\n * @returns {boolean} Result.\n */\nexport const isArrayFileCollection = (collection) =>\n  collection?._type === 'entry' && !!collection._file.arrayFile;\n\n/**\n * Check if the given collection is a valid entry or file collection. A valid collection must have a\n * `fields` property for entry collections or a `files` property for file collections. It must not\n * be a divider.\n * @param {Collection | CollectionDivider} collection Collection definition or divider.\n * @param {object} [options] Filter options.\n * @param {boolean} [options.visible] Whether to filter out hidden collections. Defaults to `false`.\n * @param {CollectionType} [options.type] Type of collections to filter by. If provided, only\n * collections of this type will be returned.\n * @returns {collection is Collection} Whether the collection is valid.\n */\nexport const isValidCollection = (collection, { visible = undefined, type = undefined } = {}) => {\n  if ('divider' in collection) {\n    return false;\n  }\n\n  if (visible && collection.hide) {\n    return false;\n  }\n\n  if (type === 'entry') {\n    return isEntryCollection(collection);\n  }\n\n  if (type === 'file') {\n    return isFileCollection(collection);\n  }\n\n  if (type === 'singleton') {\n    return isSingletonCollection(collection);\n  }\n\n  return isEntryCollection(collection) || isFileCollection(collection);\n};\n\n/**\n * Check if the given collection file is valid. A valid file must have a string `file` property, not\n * be a `divider`, and have `fields` defined as an array.\n * @param {CollectionFile | CollectionDivider} file File definition or divider.\n * @returns {boolean} Whether the file is valid.\n */\nexport const isValidCollectionFile = (file) =>\n  !('divider' in file) && typeof file.file === 'string' && Array.isArray(file.fields);\n\n/**\n * Get a list of valid collection files from the given file definitions. This filters out dividers\n * and invalid files that do not have a string `file` property or do not have `fields` defined as an\n * array.\n * @param {(CollectionFile | CollectionDivider)[]} files File definitions. May include dividers.\n * @returns {CollectionFile[]} List of valid collection files.\n */\nexport const getValidCollectionFiles = (files) =>\n  /** @type {CollectionFile[]} */ (files.filter((file) => isValidCollectionFile(file)));\n","/**\n * @import { BuiltInFieldType } from '$lib/types/public';\n */\n\n/**\n * List of built-in field types.\n * @type {BuiltInFieldType[]}\n */\nexport const BUILTIN_FIELD_TYPES = [\n  'boolean',\n  'code',\n  'color',\n  'compute',\n  'datetime',\n  'file',\n  'hidden',\n  'image',\n  'keyvalue',\n  'list',\n  'map',\n  'markdown',\n  'number',\n  'object',\n  'relation',\n  'richtext',\n  'select',\n  'string',\n  'text',\n  'uuid',\n];\n\n/**\n * List of field types that support a simple value: boolean, number or string.\n * @type {string[]}\n */\nexport const SIMPLE_VALUE_FIELD_TYPES = [\n  'boolean',\n  'color',\n  'compute',\n  'datetime',\n  'map',\n  'markdown',\n  'number',\n  'richtext',\n  'string',\n  'text',\n  'uuid',\n];\n\n/**\n * List of field types whose value is always a string. Unlike the Number, Select and Relation field\n * types, which accept numeric values, anything stored in these fields can be safely stringified.\n * @type {string[]}\n */\nexport const STRING_VALUE_FIELD_TYPES = SIMPLE_VALUE_FIELD_TYPES.filter(\n  (type) => !['boolean', 'number'].includes(type),\n);\n\n/**\n * List of field types that support media files.\n * @type {string[]}\n */\nexport const MEDIA_FIELD_TYPES = ['file', 'image'];\n\n/**\n * List of field types that hold Markdown text, which can embed images.\n * @type {string[]}\n */\nexport const RICH_TEXT_FIELD_TYPES = ['richtext', 'markdown'];\n\n/**\n * List of field types that hold free text, which can be translated.\n * @type {string[]}\n */\nexport const TEXT_FIELD_TYPES = ['text', 'string', ...RICH_TEXT_FIELD_TYPES];\n\n/**\n * List of field types that support the `multiple` option.\n * @type {string[]}\n */\nexport const MULTI_VALUE_FIELD_TYPES = [...MEDIA_FIELD_TYPES, 'relation', 'select'];\n\n/**\n * List of field types that support the `min` and `max` options.\n * @type {string[]}\n */\nexport const MIN_MAX_VALUE_FIELD_TYPES = [\n  ...MULTI_VALUE_FIELD_TYPES,\n  'datetime',\n  'keyvalue',\n  'list',\n  'number',\n];\n","/** @import { Source } from '#client' */\nimport { DEV } from 'esm-env';\nimport { source, set, state, increment } from '../internal/client/reactivity/sources.js';\nimport { label, tag } from '../internal/client/dev/tracing.js';\nimport { get, update_version } from '../internal/client/runtime.js';\n\nvar read_methods = ['forEach', 'isDisjointFrom', 'isSubsetOf', 'isSupersetOf'];\nvar set_like_methods = ['difference', 'intersection', 'symmetricDifference', 'union'];\n\nvar inited = false;\n\n/**\n * A reactive version of the built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) object.\n * Reading contents of the set (by iterating, or by reading `set.size` or calling `set.has(...)` as in the [example](https://svelte.dev/playground/53438b51194b4882bcc18cddf9f96f15) below) in an [effect](https://svelte.dev/docs/svelte/$effect) or [derived](https://svelte.dev/docs/svelte/$derived)\n * will cause it to be re-evaluated as necessary when the set is updated.\n *\n * Note that values in a reactive set are _not_ made [deeply reactive](https://svelte.dev/docs/svelte/$state#Deep-state).\n *\n * ```svelte\n * <script>\n * \timport { SvelteSet } from 'svelte/reactivity';\n * \tlet monkeys = new SvelteSet();\n *\n * \tfunction toggle(monkey) {\n * \t\tif (monkeys.has(monkey)) {\n * \t\t\tmonkeys.delete(monkey);\n * \t\t} else {\n * \t\t\tmonkeys.add(monkey);\n * \t\t}\n * \t}\n * </script>\n *\n * {#each ['🙈', '🙉', '🙊'] as monkey}\n * \t<button onclick={() => toggle(monkey)}>{monkey}</button>\n * {/each}\n *\n * <button onclick={() => monkeys.clear()}>clear</button>\n *\n * {#if monkeys.has('🙈')}<p>see no evil</p>{/if}\n * {#if monkeys.has('🙉')}<p>hear no evil</p>{/if}\n * {#if monkeys.has('🙊')}<p>speak no evil</p>{/if}\n * ```\n *\n * @template T\n * @extends {Set<T>}\n */\nexport class SvelteSet extends Set {\n\t/** @type {Map<T, Source<boolean>>} */\n\t#sources = new Map();\n\t#version = state(0);\n\t#size = state(0);\n\t#update_version = update_version || -1;\n\n\t/**\n\t * @param {Iterable<T> | null | undefined} [value]\n\t */\n\tconstructor(value) {\n\t\tsuper();\n\n\t\tif (DEV) {\n\t\t\t// If the value is invalid then the native exception will fire here\n\t\t\tvalue = new Set(value);\n\n\t\t\ttag(this.#version, 'SvelteSet version');\n\t\t\ttag(this.#size, 'SvelteSet.size');\n\t\t}\n\n\t\tif (value) {\n\t\t\tfor (var element of value) {\n\t\t\t\tsuper.add(element);\n\t\t\t}\n\t\t\tthis.#size.v = super.size;\n\t\t}\n\n\t\tif (!inited) this.#init();\n\t}\n\n\t/**\n\t * If the source is being created inside the same reaction as the SvelteSet instance,\n\t * we use `state` so that it will not be a dependency of the reaction. Otherwise we\n\t * use `source` so it will be.\n\t *\n\t * @template T\n\t * @param {T} value\n\t * @returns {Source<T>}\n\t */\n\t#source(value) {\n\t\treturn update_version === this.#update_version ? state(value) : source(value);\n\t}\n\n\t// We init as part of the first instance so that we can treeshake this class\n\t#init() {\n\t\tinited = true;\n\n\t\tvar proto = SvelteSet.prototype;\n\t\tvar set_proto = Set.prototype;\n\n\t\tfor (const method of read_methods) {\n\t\t\t// @ts-ignore\n\t\t\tproto[method] = function (...v) {\n\t\t\t\tget(this.#version);\n\t\t\t\t// @ts-ignore\n\t\t\t\treturn set_proto[method].apply(this, v);\n\t\t\t};\n\t\t}\n\n\t\tfor (const method of set_like_methods) {\n\t\t\t// @ts-ignore\n\t\t\tproto[method] = function (...v) {\n\t\t\t\tget(this.#version);\n\t\t\t\t// @ts-ignore\n\t\t\t\tvar set = /** @type {Set<T>} */ (set_proto[method].apply(this, v));\n\t\t\t\treturn new SvelteSet(set);\n\t\t\t};\n\t\t}\n\t}\n\n\t/** @param {T} value */\n\thas(value) {\n\t\tvar has = super.has(value);\n\t\tvar sources = this.#sources;\n\t\tvar s = sources.get(value);\n\n\t\tif (s === undefined) {\n\t\t\tif (!has) {\n\t\t\t\t// If the value doesn't exist, track the version in case it's added later\n\t\t\t\t// but don't create sources willy-nilly to track all possible values\n\t\t\t\tget(this.#version);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\ts = this.#source(true);\n\n\t\t\tif (DEV) {\n\t\t\t\ttag(s, `SvelteSet has(${label(value)})`);\n\t\t\t}\n\n\t\t\tsources.set(value, s);\n\t\t}\n\n\t\tget(s);\n\t\treturn has;\n\t}\n\n\t/** @param {T} value */\n\tadd(value) {\n\t\tif (!super.has(value)) {\n\t\t\tsuper.add(value);\n\t\t\tset(this.#size, super.size);\n\t\t\tincrement(this.#version);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/** @param {T} value */\n\tdelete(value) {\n\t\tvar deleted = super.delete(value);\n\t\tvar sources = this.#sources;\n\t\tvar s = sources.get(value);\n\n\t\tif (s !== undefined) {\n\t\t\tsources.delete(value);\n\t\t\tset(s, false);\n\t\t}\n\n\t\tif (deleted) {\n\t\t\tset(this.#size, super.size);\n\t\t\tincrement(this.#version);\n\t\t}\n\n\t\treturn deleted;\n\t}\n\n\tclear() {\n\t\tif (super.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\t// Clear first, so we get nice console.log outputs with $inspect\n\t\tsuper.clear();\n\t\tvar sources = this.#sources;\n\n\t\tfor (var s of sources.values()) {\n\t\t\tset(s, false);\n\t\t}\n\n\t\tsources.clear();\n\t\tset(this.#size, 0);\n\t\tincrement(this.#version);\n\t}\n\n\tkeys() {\n\t\treturn this.values();\n\t}\n\n\tvalues() {\n\t\tget(this.#version);\n\t\treturn super.values();\n\t}\n\n\tentries() {\n\t\tget(this.#version);\n\t\treturn super.entries();\n\t}\n\n\t[Symbol.iterator]() {\n\t\treturn this.keys();\n\t}\n\n\tget size() {\n\t\treturn get(this.#size);\n\t}\n}\n","/** @import { Source } from '#client' */\nimport { DEV } from 'esm-env';\nimport { set, source, state, increment } from '../internal/client/reactivity/sources.js';\nimport { label, tag } from '../internal/client/dev/tracing.js';\nimport { get, update_version } from '../internal/client/runtime.js';\n\n/**\n * A reactive version of the built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) object.\n * Reading contents of the map (by iterating, or by reading `map.size` or calling `map.get(...)` or `map.has(...)` as in the [tic-tac-toe example](https://svelte.dev/playground/0b0ff4aa49c9443f9b47fe5203c78293) below) in an [effect](https://svelte.dev/docs/svelte/$effect) or [derived](https://svelte.dev/docs/svelte/$derived)\n * will cause it to be re-evaluated as necessary when the map is updated.\n *\n * Note that values in a reactive map are _not_ made [deeply reactive](https://svelte.dev/docs/svelte/$state#Deep-state).\n *\n * ```svelte\n * <script>\n * \timport { SvelteMap } from 'svelte/reactivity';\n * \timport { result } from './game.js';\n *\n * \tlet board = new SvelteMap();\n * \tlet player = $state('x');\n * \tlet winner = $derived(result(board));\n *\n * \tfunction reset() {\n * \t\tplayer = 'x';\n * \t\tboard.clear();\n * \t}\n * </script>\n *\n * <div class=\"board\">\n * \t{#each Array(9), i}\n * \t\t<button\n * \t\t\tdisabled={board.has(i) || winner}\n * \t\t\tonclick={() => {\n * \t\t\t\tboard.set(i, player);\n * \t\t\t\tplayer = player === 'x' ? 'o' : 'x';\n * \t\t\t}}\n * \t\t>{board.get(i)}</button>\n * \t{/each}\n * </div>\n *\n * {#if winner}\n * \t<p>{winner} wins!</p>\n * \t<button onclick={reset}>reset</button>\n * {:else}\n * \t<p>{player} is next</p>\n * {/if}\n * ```\n *\n * @template K\n * @template V\n * @extends {Map<K, V>}\n */\nexport class SvelteMap extends Map {\n\t/** @type {Map<K, Source<number>>} */\n\t#sources = new Map();\n\t#version = state(0);\n\t#size = state(0);\n\t#update_version = update_version || -1;\n\n\t/**\n\t * @param {Iterable<readonly [K, V]> | null | undefined} [value]\n\t */\n\tconstructor(value) {\n\t\tsuper();\n\n\t\tif (DEV) {\n\t\t\t// If the value is invalid then the native exception will fire here\n\t\t\tvalue = new Map(value);\n\n\t\t\ttag(this.#version, 'SvelteMap version');\n\t\t\ttag(this.#size, 'SvelteMap.size');\n\t\t}\n\n\t\tif (value) {\n\t\t\tfor (var [key, v] of value) {\n\t\t\t\tsuper.set(key, v);\n\t\t\t}\n\t\t\tthis.#size.v = super.size;\n\t\t}\n\t}\n\n\t/**\n\t * If the source is being created inside the same reaction as the SvelteMap instance,\n\t * we use `state` so that it will not be a dependency of the reaction. Otherwise we\n\t * use `source` so it will be.\n\t *\n\t * @template T\n\t * @param {T} value\n\t * @returns {Source<T>}\n\t */\n\t#source(value) {\n\t\treturn update_version === this.#update_version ? state(value) : source(value);\n\t}\n\n\t/** @param {K} key */\n\thas(key) {\n\t\tvar sources = this.#sources;\n\t\tvar s = sources.get(key);\n\n\t\tif (s === undefined) {\n\t\t\tif (super.has(key)) {\n\t\t\t\ts = this.#source(0);\n\n\t\t\t\tif (DEV) {\n\t\t\t\t\ttag(s, `SvelteMap get(${label(key)})`);\n\t\t\t\t}\n\n\t\t\t\tsources.set(key, s);\n\t\t\t} else {\n\t\t\t\t// We should always track the version in case\n\t\t\t\t// the Set ever gets this value in the future.\n\t\t\t\tget(this.#version);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tget(s);\n\t\treturn true;\n\t}\n\n\t/**\n\t * @param {(value: V, key: K, map: Map<K, V>) => void} callbackfn\n\t * @param {any} [this_arg]\n\t */\n\tforEach(callbackfn, this_arg) {\n\t\tthis.#read_all();\n\t\tsuper.forEach(callbackfn, this_arg);\n\t}\n\n\t/** @param {K} key */\n\tget(key) {\n\t\tvar sources = this.#sources;\n\t\tvar s = sources.get(key);\n\n\t\tif (s === undefined) {\n\t\t\tif (super.has(key)) {\n\t\t\t\ts = this.#source(0);\n\n\t\t\t\tif (DEV) {\n\t\t\t\t\ttag(s, `SvelteMap get(${label(key)})`);\n\t\t\t\t}\n\n\t\t\t\tsources.set(key, s);\n\t\t\t} else {\n\t\t\t\t// We should always track the version in case\n\t\t\t\t// the Set ever gets this value in the future.\n\t\t\t\tget(this.#version);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tget(s);\n\t\treturn super.get(key);\n\t}\n\n\t/**\n\t * @param {K} key\n\t * @param {V} value\n\t * */\n\tgetOrInsert(key, value) {\n\t\tif (!super.has(key)) {\n\t\t\tthis.set(key, value);\n\t\t}\n\t\treturn /** @type {V} */ (this.get(key));\n\t}\n\n\t/**\n\t * @param {K} key\n\t * @param {(key: K) => V} callbackFn\n\t */\n\tgetOrInsertComputed(key, callbackFn) {\n\t\tif (!super.has(key)) {\n\t\t\tthis.set(key, callbackFn(key));\n\t\t}\n\t\treturn /** @type {V} */ (this.get(key));\n\t}\n\n\t/**\n\t * @param {K} key\n\t * @param {V} value\n\t * */\n\tset(key, value) {\n\t\tvar sources = this.#sources;\n\t\tvar s = sources.get(key);\n\t\tvar prev_res = super.get(key);\n\t\tvar res = super.set(key, value);\n\t\tvar version = this.#version;\n\n\t\tif (s === undefined) {\n\t\t\ts = this.#source(0);\n\n\t\t\tif (DEV) {\n\t\t\t\ttag(s, `SvelteMap get(${label(key)})`);\n\t\t\t}\n\n\t\t\tsources.set(key, s);\n\t\t\tset(this.#size, super.size);\n\t\t\tincrement(version);\n\t\t} else if (prev_res !== value) {\n\t\t\tincrement(s);\n\n\t\t\t// if not every reaction of s is a reaction of version we need to also include version\n\t\t\tvar v_reactions = version.reactions === null ? null : new Set(version.reactions);\n\t\t\tvar needs_version_increase =\n\t\t\t\tv_reactions === null ||\n\t\t\t\t!s.reactions?.every((r) =>\n\t\t\t\t\t/** @type {NonNullable<typeof v_reactions>} */ (v_reactions).has(r)\n\t\t\t\t);\n\t\t\tif (needs_version_increase) {\n\t\t\t\tincrement(version);\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\t/** @param {K} key */\n\tdelete(key) {\n\t\tvar sources = this.#sources;\n\t\tvar s = sources.get(key);\n\t\tvar res = super.delete(key);\n\n\t\tif (s !== undefined) {\n\t\t\tsources.delete(key);\n\t\t\tset(s, -1);\n\t\t}\n\n\t\tif (res) {\n\t\t\tset(this.#size, super.size);\n\t\t\tincrement(this.#version);\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tclear() {\n\t\tif (super.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\t// Clear first, so we get nice console.log outputs with $inspect\n\t\tsuper.clear();\n\t\tvar sources = this.#sources;\n\t\tset(this.#size, 0);\n\t\tfor (var s of sources.values()) {\n\t\t\tset(s, -1);\n\t\t}\n\t\tincrement(this.#version);\n\t\tsources.clear();\n\t}\n\n\t#read_all() {\n\t\tget(this.#version);\n\n\t\tvar sources = this.#sources;\n\t\tif (this.#size.v !== sources.size) {\n\t\t\tfor (var key of super.keys()) {\n\t\t\t\tif (!sources.has(key)) {\n\t\t\t\t\tvar s = this.#source(0);\n\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\ttag(s, `SvelteMap get(${label(key)})`);\n\t\t\t\t\t}\n\n\t\t\t\t\tsources.set(key, s);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor ([, s] of this.#sources) {\n\t\t\tget(s);\n\t\t}\n\t}\n\n\tkeys() {\n\t\tget(this.#version);\n\t\treturn super.keys();\n\t}\n\n\tvalues() {\n\t\tthis.#read_all();\n\t\treturn super.values();\n\t}\n\n\tentries() {\n\t\tthis.#read_all();\n\t\treturn super.entries();\n\t}\n\n\t[Symbol.iterator]() {\n\t\treturn this.entries();\n\t}\n\n\tget size() {\n\t\tget(this.#size);\n\t\treturn super.size;\n\t}\n}\n","import { SvelteMap } from 'svelte/reactivity';\n\n/**\n * @import { CustomFileFormat, CustomPage } from '$lib/types/private';\n * @import {\n * AppEventListener,\n * CustomFieldControl,\n * CustomFieldPreview,\n * CustomFieldSchema,\n * CustomFieldSummary,\n * CustomPreviewTemplate,\n * CustomEditorComponentDefinition,\n * StringTransformer,\n * } from '$lib/types/public';\n */\n\n/**\n * Custom components registered using the `CMS.registerEditorComponent` API.\n * @type {Map<string, CustomEditorComponentDefinition>}\n * @see https://decapcms.org/docs/custom-widgets/#registereditorcomponent\n * @see https://sveltiacms.app/en/docs/api/editor-components\n */\nexport const customComponentRegistry = new Map();\n\n/**\n * Custom pages registered with the `CMS.registerCustomPage` API. Unlike the other registries, it’s\n * reactive, as the global toolbar lists the pages, and a page can be registered after the app has\n * been mounted.\n * @type {SvelteMap<string, CustomPage>}\n * @see https://sveltiacms.app/en/docs/api/custom-pages\n */\nexport const customPageRegistry = new SvelteMap();\n\n/**\n * Custom field types registered using the `CMS.registerField` API.\n * @type {Map<string, { control: CustomFieldControl | string, preview?: CustomFieldPreview,\n * summary?: CustomFieldSummary, schema?: CustomFieldSchema }>}\n * @see https://decapcms.org/docs/custom-widgets/#registerwidget\n * @see https://sveltiacms.app/en/docs/api/field-types\n */\nexport const customFieldTypeRegistry = new Map();\n\n/**\n * Custom file formats registered using the `CMS.registerFileFormat` API.\n * @type {Map<string, CustomFileFormat>}\n * @see https://decapcms.org/docs/custom-formatters/\n * @see https://sveltiacms.app/en/docs/api/file-formats\n */\nexport const customFileFormatRegistry = new Map();\n\n/**\n * Custom entry preview stylesheets registered with the `CMS.registerPreviewStyle` API, each with\n * the collection and file it’s limited to, if any.\n * @type {Set<{ url: string, collection?: string, file?: string }>}\n * @see https://decapcms.org/docs/customization/#registerpreviewstyle\n * @see https://sveltiacms.app/en/docs/api/preview-styles\n */\nexport const customPreviewStyleRegistry = new Set();\n\n/**\n * Custom entry preview templates registered with the `CMS.registerPreviewTemplate` API.\n * @type {Map<string, CustomPreviewTemplate>}\n * @see https://decapcms.org/docs/customization/#registerpreviewtemplate\n * @see https://sveltiacms.app/en/docs/api/preview-templates\n */\nexport const customPreviewTemplateRegistry = new Map();\n\n/**\n * Custom string transformations registered with the `CMS.registerStringTransformation` API.\n * @type {Map<string, StringTransformer>}\n * @see https://sveltiacms.app/en/docs/api/string-transformations\n */\nexport const customStringTransformationRegistry = new Map();\n\n/**\n * Custom event listeners registered with the `CMS.registerEventListener` API.\n * @type {Set<AppEventListener>}\n * @see https://decapcms.org/docs/registering-events/\n * @see https://sveltiacms.app/en/docs/api/events\n */\nexport const eventHookRegistry = new Set();\n","/**\n * Simple regex to check if a string contains template tags. This can be used for a quick check\n * before performing more expensive operations like regex replacement. The `g` flag should not be\n * used here because we only need to know if at least one match exists, and using `test()` with a\n * global regex can lead to unexpected results due to the internal state of the regex engine. A tag\n * escaped with a backslash, e.g. `\\{{title}}`, isn’t matched; see `replaceTemplateTags()`.\n */\nexport const TEMPLATE_TAG_REGEX = /(?<!\\\\){{(.+?)}}/;\n\n/**\n * Regex to match and replace template tags like {{slug}}.\n */\nexport const TEMPLATE_TAG_REPLACE_REGEX = new RegExp(TEMPLATE_TAG_REGEX.source, 'g');\n\n/**\n * Placeholder standing in for a template tag in the literal text of a template; see\n * `splitTemplateTags()`. It can’t appear in a template.\n */\nexport const TAG_PLACEHOLDER = '\\0';\n\n/**\n * Date-time field names that are supported as template tags.\n */\nexport const DATE_TIME_FIELDS = ['year', 'month', 'day', 'hour', 'minute', 'second'];\n\n/**\n * Regex to check if a template, such as an entry file path or the `preview_path` option, contains a\n * date and time tag, which can only be filled in from a DateTime field’s value.\n */\nexport const DATE_TIME_TEMPLATE_REGEX = /{{(?:year|month|day|hour|minute|second)}}/;\n\n/**\n * Regex to match the prefix that marks a template tag as an explicit reference to an entry field,\n * e.g. `fields.` in `{{fields.title}}`.\n */\nexport const FIELD_TAG_PREFIX_REGEX = /^fields\\./;\n\n/**\n * Regex to match a `default` transformation, which supplies a value of its own when the tag\n * resolves to nothing, so an undefined field is no longer a problem.\n */\nexport const DEFAULT_TRANSFORMATION_REGEX = /\\|\\s*default\\s*\\(/;\n\n/**\n * UUID tags, keyed by tag name, with the length argument of `generateUUID()` from\n * `@sveltia/utils/crypto` for each one and the source of a regular expression matching the value it\n * generates.\n * @type {Record<string, { length: 'short' | 'shorter' | undefined, pattern: string }>}\n */\nexport const UUID_TYPES = {\n  uuid: {\n    length: undefined,\n    pattern: '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',\n  },\n  uuid_short: { length: 'short', pattern: '[0-9a-f]{12}' },\n  uuid_shorter: { length: 'shorter', pattern: '[0-9a-f]{8}' },\n};\n","import { TAG_PLACEHOLDER, TEMPLATE_TAG_REGEX } from '$lib/services/common/template/constants';\n\n/**\n * Get the closest character before or after the given position that isn’t whitespace.\n * @param {string} str String.\n * @param {number} index Position to start from, excluded.\n * @param {-1 | 1} step `-1` to look backward, `1` to look forward.\n * @returns {string} Character, or an empty string if there is none.\n */\nexport const getAdjacentChar = (str, index, step) => {\n  let cursor = index + step;\n\n  while (/\\s/.test(str[cursor] ?? '')) {\n    cursor += step;\n  }\n\n  return str[cursor] ?? '';\n};\n\n/**\n * Replace template tags in a string while leaving nested template tags inside transformation\n * arguments untouched. For example, this keeps `default('{{title}}')` from being treated as a\n * separate replacement target when the outer template is processed. A tag escaped with a backslash,\n * e.g. `\\{{ title | slugify }}`, is output as is without the backslash, so a template meant for\n * another tool, like a static site generator, can be passed through.\n * @param {string} str The string containing template tags.\n * @param {(match: string, placeholder: string) => string} replacer Replacement callback.\n * @param {object} [options] Options.\n * @param {boolean} [options.unescape] Whether to remove the backslash from an escaped tag. Turn it\n * off to keep the template as it is besides the replacements.\n * @returns {string} Result of the replacements.\n */\nexport const replaceTemplateTags = (str, replacer, { unescape = true } = {}) => {\n  let result = '';\n  let searchIndex = 0;\n\n  while (searchIndex < str.length) {\n    const openIndex = str.indexOf('{{', searchIndex);\n\n    if (openIndex === -1) {\n      result += str.slice(searchIndex);\n      break;\n    }\n\n    result += str.slice(searchIndex, openIndex);\n\n    let cursor = openIndex + 2;\n    let quoteState = false;\n\n    while (cursor < str.length) {\n      const char = str[cursor];\n      const nextChar = str[cursor + 1];\n\n      // Like `splitTransformations()`, a quote only opens a transformation argument after `(` or\n      // `,`, and only closes it before `,` or `)`, so an apostrophe, as in `default('Don't')`,\n      // doesn’t throw off the parsing\n      if (char === \"'\") {\n        if (!quoteState && ['(', ','].includes(getAdjacentChar(str, cursor, -1))) {\n          quoteState = true;\n        } else if (quoteState && [',', ')'].includes(getAdjacentChar(str, cursor, 1))) {\n          quoteState = false;\n        }\n      }\n\n      if (!quoteState && char === '}' && nextChar === '}') {\n        const closeIndex = cursor;\n        const placeholder = str.slice(openIndex + 2, closeIndex);\n\n        // An escaped tag is kept as is, minus the backslash. The backslash is always at the end of\n        // the literal text just added to the result, because a preceding tag ends with `}}`\n        if (str[openIndex - 1] === '\\\\') {\n          result = unescape ? result.slice(0, -1) : result;\n          result += str.slice(openIndex, closeIndex + 2);\n          searchIndex = closeIndex + 2;\n          break;\n        }\n\n        // A tag nested in a transformation argument, as in `default('{{slug}}')`, never gets here:\n        // it’s inside the quotes the outer tag is scanned through, so it’s kept as part of that\n        // tag. A quoted tag found here is in the literal text, e.g. `('{{nickname}}')`, and is\n        // replaced like any other\n        if (!placeholder) {\n          result += str.slice(openIndex, closeIndex + 2);\n        } else {\n          result += replacer(str.slice(openIndex, closeIndex + 2), placeholder);\n        }\n\n        searchIndex = closeIndex + 2;\n        break;\n      }\n\n      cursor += 1;\n    }\n\n    if (cursor >= str.length) {\n      result += str.slice(openIndex);\n      break;\n    }\n  }\n\n  return result;\n};\n\n/**\n * Split a template into the contents of its template tags and the literal text around them, finding\n * the tags like {@link replaceTemplateTags} does.\n * @param {string} str The string containing template tags.\n * @returns {{ tags: string[], literals: string[] }} Content of each tag in the order they appear,\n * e.g. `fields.title | upper` for `{{fields.title | upper}}`, and the literal text before each tag\n * followed by the trailing text, so there is one more literal than tags. Joining the literals with\n * `TAG_PLACEHOLDER` gives the template with each tag replaced by the placeholder.\n */\nexport const splitTemplateTags = (str) => {\n  /** @type {string[]} */\n  const tags = [];\n\n  const literals = replaceTemplateTags(str, (_match, placeholder) => {\n    tags.push(placeholder);\n\n    return TAG_PLACEHOLDER;\n  }).split(TAG_PLACEHOLDER);\n\n  return { tags, literals };\n};\n\n/**\n * Get the template tags in a string, finding them like {@link replaceTemplateTags} does, so a tag\n * escaped with a backslash or nested in a transformation argument isn’t one.\n * @param {string} str The string containing template tags.\n * @returns {{ tag: string, content: string, name: string }[]} Each tag in the order they appear,\n * e.g. `{{ fields.title | upper }}`, with its content between the braces and its name, the content\n * before any transformation, e.g. `fields.title`. A name never contains a pipe, so it’s found even\n * when a transformation argument does.\n */\nexport const getTemplateTags = (str) => {\n  /** @type {{ tag: string, content: string, name: string }[]} */\n  const tags = [];\n\n  replaceTemplateTags(str, (tag, content) => {\n    tags.push({ tag, content, name: content.split('|')[0].trim() });\n\n    return tag;\n  });\n\n  return tags;\n};\n\n/**\n * Checks if a string contains template tags.\n * @param {string} str The string to check.\n * @returns {boolean} True if the string contains template tags, false otherwise.\n */\nexport const hasTemplateTags = (str) => TEMPLATE_TAG_REGEX.test(str);\n","import { escapeRegExp } from '@sveltia/utils/string';\n\nimport { FIELD_TAG_PREFIX_REGEX } from '$lib/services/common/template/constants';\nimport { splitTemplateTags } from '$lib/services/common/template/tags';\n\n/**\n * @import { InternalCollection, InternalCollectionFile } from '$lib/types/private';\n */\n\n/**\n * Remove the `fields.` prefix from a template tag, e.g. `fields.title` becomes `title`. A tag\n * without the prefix is returned as is.\n * @param {string} tag Template tag, without the surrounding braces.\n * @returns {string} Tag without the prefix, which is a field key path.\n */\nexport const stripFieldTagPrefix = (tag) => tag.replace(FIELD_TAG_PREFIX_REGEX, '');\n\n/**\n * Split the name of a file at its last dot into the `{{filename}}` and `{{extension}}` template tag\n * values, as Netlify/Decap CMS does with `basename(path, extname(path))`. A name with several dots\n * like `my.post.md` keeps everything but the last extension, and a name without a dot has no\n * extension. Unlike `getPathInfo()`, any characters can follow the last dot, and `.tar.gz` is not\n * treated as a single extension.\n * @param {string} path File path or name.\n * @param {string[]} [localeSuffixes] Locale codes that can follow the file name, as the\n * `multiple_files` i18n structure names a file like `my-post.en.md`. A matching one is removed\n * from the file name, so it’s the same for every locale.\n * @returns {{ filename: string, extension: string }} File name without the extension, and the\n * extension without the leading dot.\n */\nexport const getFileNameParts = (path, localeSuffixes = []) => {\n  const fileName = /** @type {string} */ (path.split('/').pop());\n  const dotIndex = fileName.lastIndexOf('.');\n  const extension = dotIndex === -1 ? '' : fileName.slice(dotIndex + 1);\n  let filename = dotIndex === -1 ? fileName : fileName.slice(0, dotIndex);\n  const locale = localeSuffixes.find((code) => filename.endsWith(`.${code}`));\n\n  if (locale) {\n    filename = filename.slice(0, -(locale.length + 1));\n  }\n\n  return { filename, extension };\n};\n\n/**\n * Get the locale codes that can follow an entry file name in the given collection or collection\n * file, which are only there with the `multiple_files` i18n structure.\n * @param {InternalCollection | InternalCollectionFile} collection Collection or collection\n * file. Its i18n configuration can be missing from a partial collection object, which is then\n * treated as not localized.\n * @returns {string[]} Locale codes.\n */\nexport const getFileNameLocaleSuffixes = ({ _i18n }) =>\n  _i18n?.structureMap?.i18nMultiFile ? _i18n.allLocales : [];\n\n/**\n * Get a regular expression pattern matching the given path template, with each template tag, e.g.\n * `{{slug}}`, replaced with the given wildcard and anything else matched literally. The tags are\n * found like `fillTemplate()` finds them, so a tag with a nested template in a transformation\n * argument, e.g. `{{fields.slug | default('{{title}}')}}`, is replaced as a whole, and an escaped\n * tag, e.g. `\\{{title}}`, is matched literally without the backslash.\n * @param {string} template Path template, e.g. `images/{{slug}}`.\n * @param {string} wildcard Pattern to match a template tag with, e.g. `[^/]+` for one path segment\n * or `.+?` for any number of them.\n * @returns {string} Pattern.\n */\nexport const getTemplatePattern = (template, wildcard) =>\n  splitTemplateTags(template).literals.map(escapeRegExp).join(wildcard);\n","import { _, locale as appLocale } from '@sveltia/i18n';\n\nimport { isEntryCollection } from '$lib/services/contents/collection/predicates';\n\n/**\n * @import { Entry, InternalCollection, InternalEntryCollection } from '$lib/types/private';\n * @import { Collection, CollectionIndexFile } from '$lib/types/public';\n */\n\n/**\n * Default name of Hugo’s special index file, used when the collection doesn’t specify one.\n */\nconst DEFAULT_INDEX_FILE_NAME = '_index';\n/**\n * Cache of index file configurations, keyed by the collection object. `getCollection()` returns a\n * stable object per collection, so this is effectively per collection for the session.\n * @type {WeakMap<InternalCollection | Collection, { locale: string | undefined, indexFile:\n * CollectionIndexFile | undefined }>}\n */\nconst indexFileCacheMap = new WeakMap();\n\n/**\n * Get the name of the collection’s index file, without building the full configuration object. This\n * is the cheap path for {@link isCollectionIndexFile}, which is called once per entry in several\n * list-wide operations, and for the callers that only need to know whether the collection has an\n * index file at all. Unlike {@link getIndexFile}, it reads no state, so it can be called from a\n * derivation without making it depend on the app locale.\n * @param {InternalCollection | Collection} collection Collection.\n * @returns {string | undefined} Index file name, or `undefined` if index file inclusion is not\n * enabled for the collection.\n */\nexport const getIndexFileName = (collection) => {\n  if (!isEntryCollection(collection)) {\n    return undefined;\n  }\n\n  const { index_file: indexFile } = collection;\n\n  if (!indexFile) {\n    return undefined;\n  }\n\n  return (indexFile === true ? undefined : indexFile.name) ?? DEFAULT_INDEX_FILE_NAME;\n};\n\n/**\n * Get the collection’s index file configuration. This function returns the index file configuration\n * if index file inclusion is enabled for the collection. If no specific configuration is provided,\n * it returns a default configuration with the `_index` file name, which is used for Hugo’s special\n * index file.\n *\n * The result is cached per collection, because the default label is localized and looking it up —\n * along with allocating a fresh object — on every call adds up in the entry list and the editor.\n * @param {InternalCollection | Collection} collection Collection.\n * @returns {CollectionIndexFile | undefined} Index file configuration if index file inclusion is\n * enabled for the collection, otherwise `undefined`.\n * @see https://gohugo.io/content-management/organization/#index-pages-_indexmd\n * @see https://github.com/decaporg/decap-cms/issues/7381\n * @see https://sveltiacms.app/en/docs/collections/entries/listings#managing-hugo-s-special-index-file\n */\nexport const getIndexFile = (collection) => {\n  const cached = indexFileCacheMap.get(collection);\n\n  // The default label is translated, so a cached entry is only valid for the app locale it was\n  // built with\n  if (cached && cached.locale === appLocale.current) {\n    return cached.indexFile;\n  }\n\n  const name = getIndexFileName(collection);\n  /** @type {CollectionIndexFile | undefined} */\n  let indexFile;\n\n  if (name !== undefined) {\n    const { index_file: config } = /** @type {any} */ (collection);\n    const file = config === true ? {} : config;\n\n    // Every option is kept, so a new one needs no change here. The ones left out, such as\n    // `extension`, `fields` and `editor`, are inherited from the collection or global config\n    indexFile = {\n      ...file,\n      name,\n      label: file.label || _('index_file'),\n      icon: file.icon ?? 'home',\n    };\n  }\n\n  indexFileCacheMap.set(collection, { locale: appLocale.current, indexFile });\n\n  return indexFile;\n};\n\n/**\n * Check if index file inclusion is enabled for the collection, and the file at the given path is\n * the special index file. The sub path is taken from the path with the collection’s path matcher.\n * The matcher also tells an index file with an extension of its own from the entries, and leaves\n * out an entry going by its name.\n * @param {InternalCollection} collection Collection.\n * @param {string} path File path.\n * @returns {boolean} Result.\n */\nexport const isCollectionIndexFilePath = (collection, path) => {\n  const name = getIndexFileName(collection);\n\n  if (name === undefined) {\n    return false;\n  }\n\n  const regex = /** @type {InternalEntryCollection} */ (collection)._file?.fullPathRegEx;\n\n  return !!regex && path.match(regex)?.groups?.subPath === name;\n};\n\n/**\n * Check if index file inclusion (for Hugo) is enabled for the collection, and the given entry is\n * the special index file.\n *\n * The entry’s own `slug` can’t answer this. A file belongs to exactly one entry folder — the\n * deepest one matching its path — and the slug was computed there, so when one collection’s folder\n * contains another’s, the inner collection’s `_index.md` carries the slug `_index` into the outer\n * collection, which claims the same file with its own path matcher. The entry’s path is matched\n * against this collection’s matcher instead, giving the sub path as this collection sees it: for\n * `content/posts/_index.md` in a collection on `content`, that’s `posts/_index`, not `_index`. Any\n * locale’s path works, since the matcher accounts for the locale.\n * @param {InternalCollection} collection Collection.\n * @param {Entry} entry Entry. May be a partial object without any locale, for a new entry.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/1005\n */\nexport const isCollectionIndexFile = (collection, entry) => {\n  const name = getIndexFileName(collection);\n\n  if (name === undefined) {\n    return false;\n  }\n\n  const path = Object.values(entry.locales ?? {})[0]?.path;\n\n  if (path === undefined) {\n    return entry.slug === name;\n  }\n\n  return isCollectionIndexFilePath(collection, path);\n};\n","/**\n * @import { FileExtension, FileFormat, FrontMatterFormat } from '$lib/types/public';\n */\n\n/**\n * Markdown file extensions that support front matter formats.\n * @type {string[]}\n */\nexport const MARKDOWN_EXTENSIONS = [\n  'markdown',\n  'md',\n  'mdown',\n  'mdwn',\n  'mdx',\n  'mkd',\n  'mkdn',\n  'html.md',\n];\n\n/**\n * Map of supported file formats to their default extensions.\n * @type {Record<string, FileExtension>}\n */\nexport const FORMAT_EXTENSION_MAP = {\n  raw: 'txt',\n  yaml: 'yml',\n  yml: 'yml',\n  toml: 'toml',\n  json: 'json',\n};\n\n/**\n * Map of file extensions to their corresponding file formats for auto-detection.\n * @type {Record<string, FileFormat>}\n */\nexport const EXTENSION_FORMAT_MAP = {\n  yaml: 'yaml',\n  yml: 'yaml',\n  toml: 'toml',\n  json: 'json',\n  // Astro files default to the `raw` format, which allows editing the entire file content directly.\n  // The front matter in Astro is not YAML but JavaScript, so we cannot use the `yaml-frontmatter`\n  // format. The `raw` format is the best fit for Astro files.\n  astro: 'raw',\n};\n\n/**\n * Map of front matter formats to their default delimiters.\n * @type {Record<string, [string, string]>}\n */\nexport const FRONTMATTER_DELIMITER_MAP = {\n  'json-frontmatter': ['{', '}'],\n  'toml-frontmatter': ['+++', '+++'],\n  'yaml-frontmatter': ['---', '---'],\n};\n\n/**\n * File formats that use front matter syntax, excluding the `frontmatter` auto-detect format.\n * @type {FrontMatterFormat[]}\n */\nexport const FRONTMATTER_FORMATS = ['yaml-frontmatter', 'toml-frontmatter', 'json-frontmatter'];\n\n/**\n * File formats that come with a built-in parser and formatter. A custom format registered under one\n * of these names can leave out either method and fall back to the built-in one.\n * @type {FileFormat[]}\n */\nexport const BUILTIN_FILE_FORMATS = [\n  'yml',\n  'yaml',\n  'toml',\n  'json',\n  'frontmatter',\n  ...FRONTMATTER_FORMATS,\n  'raw',\n];\n\n/**\n * List of file formats that use TOML syntax and thus require special handling, such as native date\n * objects instead of strings for date/datetime fields.\n * @type {FileFormat[]}\n */\nexport const TOML_FORMATS = ['toml', 'toml-frontmatter'];\n\n/**\n * Syntax of a file format: YAML, TOML or JSON.\n * @typedef {'yaml' | 'toml' | 'json'} FormatSyntax\n */\n\n/**\n * Map of the built-in file formats, other than `raw`, to the syntax of the file, or of its front\n * matter block. A new file in the `frontmatter` format gets YAML front matter.\n * @type {Record<string, FormatSyntax>}\n */\nconst FORMAT_SYNTAX_MAP = {\n  yml: 'yaml',\n  yaml: 'yaml',\n  toml: 'toml',\n  json: 'json',\n  frontmatter: 'yaml',\n  'yaml-frontmatter': 'yaml',\n  'toml-frontmatter': 'toml',\n  'json-frontmatter': 'json',\n};\n\n/**\n * Get the syntax of the given file format: that of the whole file, or of its front matter block.\n * @param {string} format File format.\n * @returns {FormatSyntax | undefined} Syntax, or `undefined` for the `raw` format or a format\n * without a built-in parser and formatter.\n */\nexport const getFormatSyntax = (format) =>\n  Object.hasOwn(FORMAT_SYNTAX_MAP, format) ? FORMAT_SYNTAX_MAP[format] : undefined;\n","import { isURL } from '@sveltia/utils/string';\nimport { sanitize } from 'isomorphic-dompurify';\nimport { parseInline } from 'marked';\n\n/**\n * Check if a value is a non-empty string.\n * @param {any} value Value to check.\n * @returns {value is string} Whether the value is a non-empty string.\n */\nexport const isNonEmptyString = (value) => typeof value === 'string' && !!value.trim();\n\n/**\n * Check if a value is an absolute URL starting with `https://` or `http://`, ignoring surrounding\n * whitespace. `isURL()` alone accepts any scheme, so `localhost:8080/api` would pass as a URL with\n * the `localhost:` scheme.\n * @param {any} value Value to check.\n * @returns {boolean} Result.\n */\nexport const isHttpURL = (value) =>\n  typeof value === 'string' && /^https?:\\/\\//i.test(value.trim()) && isURL(value.trim());\n\n/**\n * Escape a string for safe use as an HTML attribute value inside double quotes. Bare `&` characters\n * are encoded as `&amp;`, but pre-existing HTML entities (e.g. `&amp;`, `&quot;`) are left\n * untouched to avoid double-encoding.\n * @param {string} str Raw string.\n * @returns {string} Escaped string.\n */\nexport const escapeAttr = (str) =>\n  str.replace(/&(?![a-zA-Z0-9#]+;)/g, '&amp;').replaceAll('\"', '&quot;');\n\n/**\n * Characters that have to be escaped for plain text to be read as such within HTML.\n * @type {Record<string, string>}\n */\nconst HTML_ESCAPE_MAP = { '&': '&amp;', '<': '&lt;', '>': '&gt;' };\n\n/**\n * Escape plain text so that it’s read as text rather than markup within HTML, e.g. a literal `<b>`\n * or `&amp;`, for example by a translator taking HTML.\n * @param {string} text Plain text.\n * @returns {string} Escaped text.\n */\nexport const escapeHTML = (text) => text.replace(/[&<>]/g, (char) => HTML_ESCAPE_MAP[char]);\n\n/**\n * Sanitization options for anchor tag links.\n */\nexport const LINK_SANITIZE_OPTIONS = {\n  ALLOWED_TAGS: ['a'],\n  ALLOWED_ATTR: ['href', 'target', 'rel'],\n};\n\n/**\n * Replace `<a>` tag in a localization string, and sanitize the result.\n * @param {string} str Localized string containing `<a>` tag.\n * @param {string} href URL to set as the `href` attribute of the `<a>` tag.\n * @returns {string} Linked and sanitized HTML string.\n */\nexport const makeLink = (str, href) =>\n  sanitize(\n    str.replace('<a>', `<a href=\"${escapeAttr(href)}\" target=\"_blank\" rel=\"noopener noreferrer\">`),\n    LINK_SANITIZE_OPTIONS,\n  );\n\n/**\n * Parse the given string as inline Markdown and sanitize the result to only allow certain tags.\n * @param {string} str Original string.\n * @param {object} [options] Options.\n * @param {string[]} [options.allowedTags] Allowed HTML tags. Defaults to the basic inline\n * formatting tags and links.\n * @param {string[]} [options.allowedAttr] Allowed HTML attributes. Defaults to `href`.\n * @returns {string} Sanitized HTML string.\n */\nexport const sanitizeInlineMarkdown = (\n  str,\n  { allowedTags = ['strong', 'em', 'del', 'code', 'a'], allowedAttr = ['href'] } = {},\n) =>\n  sanitize(/** @type {string} */ (parseInline(str)), {\n    ALLOWED_TAGS: allowedTags,\n    ALLOWED_ATTR: allowedAttr,\n  });\n\n/**\n * Parse the given help text from the configuration, such as a field’s `hint`, as inline Markdown\n * and sanitize the result to only allow certain tags. A literal `\\n` is turned into a line break.\n * @param {string} str Original string.\n * @returns {string} Sanitized HTML string.\n */\nexport const sanitizeHelpText = (str) =>\n  sanitizeInlineMarkdown(str.replaceAll('\\\\n', '<br>'), {\n    allowedTags: ['strong', 'em', 'del', 'code', 'a', 'br'],\n  });\n","import { getPathInfo } from '@sveltia/utils/file';\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport { isEntryCollection } from '$lib/services/contents/collection/predicates';\nimport { EXTENSION_FORMAT_MAP, MARKDOWN_EXTENSIONS } from '$lib/services/contents/file/constants';\nimport { createRawState } from '$lib/services/utils/state.svelte';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { Entry, InternalCollection } from '$lib/types/private';\n * @import { Collection, EntryCollection } from '$lib/types/public';\n */\n\n/**\n * Normalized options for a collection with nested entries.\n * @typedef {object} NestedEntryConfig\n * @property {number} depth Maximum number of path segments below the collection folder. Entries\n * deeper than this are not part of the collection. `Infinity` if unlimited.\n * @property {string | undefined} summary Summary template used for tree node labels, which\n * overrides the collection’s `summary` option.\n * @property {boolean} subfolders Whether each entry lives in its own subfolder as an index file. If\n * `false`, entries are regular files placed directly in the folders.\n */\n\n/**\n * Normalized options for the `meta.path` entry path editor. The editor is always a folder picker\n * with a built-in label, so the `widget` and `label` options of Netlify/Decap CMS aren’t supported.\n * @typedef {object} MetaPathConfig\n * @property {string | undefined} indexFileName File name, without an extension, used for every\n * entry in the collection, e.g. `_index`. If `undefined`, the entry’s own file name is used.\n */\n\n/**\n * File names conventionally given to a folder’s own entry when the collection doesn’t configure one\n * with the `meta.path.index_file` option.\n */\nexport const DEFAULT_INDEX_FILE_NAMES = ['index', '_index'];\n\n/**\n * File extensions that can be written by the CMS. Used to spot an `index_file` option that has been\n * given with an extension.\n */\nconst CONTENT_EXTENSIONS = [...MARKDOWN_EXTENSIONS, ...Object.keys(EXTENSION_FORMAT_MAP)];\n\n/**\n * Normalize the `meta.path.index_file` option. The option is a file name without an extension, but\n * it’s easy to write it with one, which would otherwise save every entry as `index.md.md`.\n * @param {string | undefined} name Configured file name.\n * @returns {string | undefined} File name without an extension, or `undefined` if unusable.\n */\nconst normalizeIndexFileName = (name) => {\n  if (typeof name !== 'string' || !name.trim()) {\n    return undefined;\n  }\n\n  const path = stripSlashes(name.trim());\n  const { filename, extension } = getPathInfo(path);\n\n  return extension !== undefined && CONTENT_EXTENSIONS.includes(extension) ? filename : path;\n};\n\n/**\n * Directory path, relative to the selected collection’s folder, that the entry list is currently\n * limited to. An empty string means the collection’s root folder. Only relevant while a nested\n * collection is selected.\n * @type {{ current: string }}\n */\nexport const nestedFilterPath = createRawState('');\n\n/**\n * Get the normalized options for a collection with nested entries.\n * @param {Collection | InternalCollection} collection Collection.\n * @returns {NestedEntryConfig | undefined} Options, or `undefined` if the collection is not a\n * nested entry collection.\n * @see https://decapcms.org/docs/collection-nested/\n */\nexport const getNestedConfig = (collection) => {\n  const rawCollection = /** @type {Collection} */ (collection);\n\n  if (!isEntryCollection(rawCollection)) {\n    return undefined;\n  }\n\n  const { nested } = rawCollection;\n\n  if (!nested || typeof nested !== 'object') {\n    return undefined;\n  }\n\n  const { depth, summary, subfolders } = nested;\n\n  return {\n    depth: typeof depth === 'number' && depth >= 1 ? Math.floor(depth) : Infinity,\n    summary: isNonEmptyString(summary) ? summary : undefined,\n    subfolders: subfolders !== false,\n  };\n};\n\n/**\n * Check if the given collection has nested entries.\n * @param {Collection | InternalCollection} collection Collection.\n * @returns {boolean} Result.\n */\nexport const hasNestedEntries = (collection) => !!getNestedConfig(collection);\n\n/**\n * Get the normalized options for the `meta.path` entry path editor, which lets the user choose\n * where an entry is stored within the collection folder. The option requires the `nested` option:\n * without it, an entry is always a direct child of the collection folder, so there is no hierarchy\n * to place it in.\n * @param {Collection | InternalCollection} collection Collection.\n * @returns {MetaPathConfig | undefined} Options, or `undefined` if the path editor is not enabled\n * for the collection.\n * @see https://decapcms.org/docs/collection-nested/\n */\nexport const getMetaPathConfig = (collection) => {\n  if (!hasNestedEntries(collection)) {\n    return undefined;\n  }\n\n  const path = /** @type {EntryCollection} */ (collection).meta?.path;\n\n  if (!path || typeof path !== 'object') {\n    return undefined;\n  }\n\n  return { indexFileName: normalizeIndexFileName(path.index_file) };\n};\n\n/**\n * Get the name of the index file a collection with nested entries stores its entries as, e.g.\n * `_index`. Unlike the `index_file` collection option, which marks one special entry within a\n * collection, this file name is meaningful throughout a collection with nested entries: it names\n * every entry in the `subfolders` mode, and each folder’s own entry otherwise.\n * @param {Collection | InternalCollection} collection Collection.\n * @returns {string | undefined} File name without an extension, or `undefined` if the collection\n * doesn’t use one.\n */\nexport const getNestedIndexFileName = (collection) =>\n  hasNestedEntries(collection) ? getMetaPathConfig(collection)?.indexFileName : undefined;\n\n/**\n * Get the file name that every entry in the collection is saved as, which is what makes a folder\n * itself an entry. Without the `subfolders` mode there is no such name: entries are regular files\n * that keep their own names, so an `index_file` option only says what a folder’s own entry is\n * called, and forcing it on every entry would save them all over one another.\n * @param {Collection | InternalCollection} collection Collection.\n * @returns {string | undefined} File name without an extension, or `undefined` if each entry has a\n * file name of its own.\n * @see https://github.com/decaporg/decap-cms/issues/7606\n */\nexport const getSharedEntryFileName = (collection) =>\n  getNestedConfig(collection)?.subfolders === false\n    ? undefined\n    : getMetaPathConfig(collection)?.indexFileName;\n\n/**\n * Strip the file name shared by every entry in a collection with nested entries from the given\n * slug, which is the entry’s path within the collection folder. That name is how the content folder\n * stores an entry, not part of how the entry is referred to — in a preview URL, or in another\n * entry’s Relation field — so it’s left out of both.\n * @param {Collection | InternalCollection} collection Collection the entry belongs to.\n * @param {string} slug Entry slug.\n * @returns {string} Slug without the trailing file name. The collection’s own index file is left\n * alone, because there would be nothing left of it.\n * @see https://github.com/decaporg/decap-cms/issues/4963\n */\nexport const stripIndexFileName = (collection, slug) => {\n  const indexFileName = getSharedEntryFileName(collection);\n\n  return indexFileName && slug.endsWith(`/${indexFileName}`)\n    ? slug.slice(0, -indexFileName.length - 1)\n    : slug;\n};\n\n/**\n * Check whether the folder chosen with the path editor is what decides where an entry goes. A blank\n * folder means the entry goes where it would without the editor, so the collection’s own `path`\n * option and slug take over; clearing a folder that was set, on the other hand, deliberately moves\n * the entry up to the collection folder.\n *\n * A new entry in a collection where every entry shares one file name is the exception: the folder\n * is where the entry is created rather than the entry’s own folder, so even the collection folder\n * is a meaningful choice.\n * @param {object} draft Entry draft, or the parts of one that hold the folder.\n * @param {Collection | InternalCollection} draft.collection Collection the entry belongs to.\n * @param {boolean} [draft.isNew] Whether the entry is being created.\n * @param {string} [draft.originalPath] Folder at the time of draft creation.\n * @param {string} [draft.currentPath] Folder as edited with the path editor.\n * @returns {boolean} Whether the path editor decides the entry’s destination.\n * @see https://github.com/decaporg/decap-cms/issues/7094\n */\nexport const usesCustomEntryPath = ({ collection, isNew, originalPath, currentPath }) => {\n  if (currentPath === undefined) {\n    return false;\n  }\n\n  if (isNew && !!getSharedEntryFileName(collection)) {\n    return true;\n  }\n\n  return !!stripSlashes(currentPath) || !!stripSlashes(originalPath ?? '');\n};\n\n/**\n * Get the directory path of an entry within the collection folder.\n * @param {string} subPath Entry’s sub path, which is the file path relative to the collection\n * folder, without the file extension and locale.\n * @returns {string} Directory path without leading and trailing slashes. An empty string if the\n * entry is directly in the collection folder.\n */\nexport const getEntryDirPath = (subPath) => {\n  const index = subPath.lastIndexOf('/');\n\n  return index === -1 ? '' : subPath.slice(0, index);\n};\n\n/**\n * Get the name of an entry within the given folder, which is what a new slug filed in that\n * folder has to differ from: the slug of an entry in a collection with nested entries is its sub\n * path, e.g. `docs/intro`, while a new slug is a bare name, e.g. `intro`.\n * @param {string} subPath Entry’s sub path.\n * @param {string} dirPath Folder path without leading and trailing slashes. An empty string for the\n * collection folder.\n * @returns {string | undefined} Name, or `undefined` if the entry isn’t directly in the folder.\n */\nexport const getNameInFolder = (subPath, dirPath) => {\n  const prefix = dirPath ? `${dirPath}/` : '';\n  const name = subPath.startsWith(prefix) ? subPath.slice(prefix.length) : undefined;\n\n  return name?.includes('/') ? undefined : name;\n};\n\n/**\n * Check if the given entry is stored in the given directory or one of its descendants.\n * @param {string} dirPath Directory path relative to the collection folder. An empty string matches\n * every entry.\n * @param {string} subPath Entry’s sub path.\n * @returns {boolean} Result.\n */\nexport const isDescendantPath = (dirPath, subPath) => !dirPath || subPath.startsWith(`${dirPath}/`);\n\n/**\n * Check whether the given folder is part of the tree of a collection with nested entries, which is\n * what the folder route browses. A folder is there as long as it holds an entry, directly or\n * further down; the collection’s root folder is always there, even while the collection is still\n * empty.\n * @param {object} args Arguments.\n * @param {Collection | InternalCollection} args.collection Collection.\n * @param {Entry[]} args.entries Entries in the collection.\n * @param {string} args.dirPath Directory path relative to the collection folder. An empty string\n * for the collection’s root folder.\n * @returns {boolean} Result. Always `false` for a collection that isn’t nested, which has no\n * folders to browse.\n */\nexport const isNestedFolder = ({ collection, entries, dirPath }) => {\n  if (!hasNestedEntries(collection)) {\n    return false;\n  }\n\n  const basePath = stripSlashes(dirPath);\n\n  return !basePath || entries.some(({ subPath }) => isDescendantPath(basePath, subPath));\n};\n\n/**\n * Limit the given entries to those that should be listed while the user is browsing a folder of a\n * collection with nested entries. Only the immediate children of the folder are listed, because the\n * deeper entries are reachable through the collection tree.\n *\n * In the default `subfolders` mode, each entry is an index file within its own folder, so an\n * immediate child is two segments below the current folder, e.g. `about/_index` below the root. The\n * collection’s own index file, e.g. `_index` at the root, is listed as well, because there is no\n * other place to reach it from.\n * @param {object} args Arguments.\n * @param {Collection | InternalCollection} args.collection Collection.\n * @param {Entry[]} args.entries Entries in the collection.\n * @param {string} args.dirPath Directory path relative to the collection folder. An empty string\n * for the collection’s root folder.\n * @returns {Entry[]} Filtered entries. The given entries are returned as is if the collection is\n * not a collection with nested entries.\n */\nexport const filterNestedEntries = ({ collection, entries, dirPath }) => {\n  const config = getNestedConfig(collection);\n\n  if (!config) {\n    return entries;\n  }\n\n  const { subfolders } = config;\n  const basePath = stripSlashes(dirPath);\n\n  return entries.filter(({ subPath }) => {\n    if (!isDescendantPath(basePath, subPath)) {\n      return false;\n    }\n\n    const restPath = basePath ? subPath.slice(basePath.length + 1) : subPath;\n    const depth = restPath.split('/').length;\n\n    if (subfolders) {\n      // At the root, also list the collection’s own index file, which has no folder of its own\n      return basePath ? depth === 2 : depth <= 2;\n    }\n\n    return depth === 1;\n  });\n};\n","/**\n * Get a value from a cache `Map` or `WeakMap`, creating and storing it if absent.\n * @template K, V\n * @param {Map<K, V> | WeakMap<K & WeakKey, V>} cache The cache to look up.\n * @param {K} key Cache key.\n * @param {() => V} create Factory called once to produce the value when not cached.\n * @returns {V} Cached or newly created value.\n */\nexport const getOrCreate = (cache, key, create) => {\n  // Both types share the `has`/`get`/`set` signatures used here\n  const map = /** @type {Map<K, V>} */ (cache);\n\n  if (!map.has(key)) {\n    map.set(key, create());\n  }\n\n  return /** @type {V} */ (map.get(key));\n};\n\n/**\n * Mark the given entry of a `Map` as the most recently used one. A `Map` iterates in insertion\n * order, so re-inserting the key moves it to the end.\n * @template K, V\n * @param {Map<K, V>} map Map.\n * @param {K} key Key of an existing entry.\n * @returns {V} Value of the entry.\n */\nconst touchEntry = (map, key) => {\n  const value = /** @type {V} */ (map.get(key));\n\n  map.delete(key);\n  map.set(key, value);\n\n  return value;\n};\n\n/**\n * Store a value in a `Map` as its most recently used entry, then evict the least recently used one,\n * which is the first key, if the map holds more than `maxSize` entries.\n * @template K, V\n * @param {Map<K, V>} map Map.\n * @param {K} key Key.\n * @param {V} value Value.\n * @param {number} maxSize Maximum number of entries to retain.\n */\nconst setEntry = (map, key, value, maxSize) => {\n  map.delete(key);\n  map.set(key, value);\n\n  if (map.size > maxSize) {\n    map.delete(/** @type {K} */ (map.keys().next().value));\n  }\n};\n\n/**\n * @template K, V\n * @typedef {object} LRUMap\n * @property {(key: K) => boolean} has Check if the key has an entry.\n * @property {(key: K) => V | undefined} get Get the value of the key, marking it as recently used.\n * @property {(key: K, value: V) => void} set Store a value, evicting the least recently used entry\n * if the map is full.\n * @property {() => void} clear Remove all the entries.\n */\n\n/**\n * Create a map holding at most `maxSize` entries, which evicts the least recently used one once the\n * limit is exceeded. Reading an entry with `get` marks it as recently used; `has` doesn’t.\n * @template K, V\n * @param {number} maxSize Maximum number of entries to retain.\n * @returns {LRUMap<K, V>} Map.\n */\nexport const createLRUMap = (maxSize) => {\n  /** @type {Map<K, V>} */\n  const map = new Map();\n\n  return {\n    /**\n     * Check if the key has an entry, without marking it as recently used.\n     * @param {K} key Key.\n     * @returns {boolean} Result.\n     */\n    has: (key) => map.has(key),\n    /**\n     * Get the value of the key, marking the entry as recently used.\n     * @param {K} key Key.\n     * @returns {V | undefined} Value, if any.\n     */\n    get: (key) => (map.has(key) ? touchEntry(map, key) : undefined),\n    /**\n     * Store a value, evicting the least recently used entry if the map is full.\n     * @param {K} key Key.\n     * @param {V} value Value.\n     */\n    set: (key, value) => {\n      setEntry(map, key, value, maxSize);\n    },\n    /**\n     * Remove all the entries.\n     */\n    clear: () => {\n      map.clear();\n    },\n  };\n};\n\n/**\n * Get a value from a cache `Map` holding at most `maxSize` entries, creating and storing it if\n * absent. The least recently used entry is evicted once the limit is exceeded, as in\n * {@link createLRUMap}.\n *\n * Use this instead of {@link getOrCreate} whenever the cache key includes something the user can\n * keep changing — a field value, a resolved filter, an object identity that is replaced every time\n * the entry list is loaded again. Such a cache never sees the same key twice, so an unbounded `Map`\n * would grow for as long as the page is open.\n * @template K, V\n * @param {Map<K, V>} cache The cache to look up.\n * @param {K} key Cache key.\n * @param {() => V} create Factory called once to produce the value when not cached.\n * @param {number} maxSize Maximum number of entries to retain.\n * @returns {V} Cached or newly created value.\n */\nexport const getOrCreateBounded = (cache, key, create, maxSize) => {\n  if (cache.has(key)) {\n    return touchEntry(cache, key);\n  }\n\n  const value = create();\n\n  setEntry(cache, key, value, maxSize);\n\n  return value;\n};\n\n/**\n * Run an asynchronous task, letting concurrent callers with the same key share it. The promise is\n * only cached while the task is in flight, so a caller coming after it has settled starts anew.\n * @template K, V\n * @param {Map<K, Promise<V>>} cache Cache of the tasks in flight.\n * @param {K} key Cache key.\n * @param {() => Promise<V>} create Function starting the task.\n * @returns {Promise<V>} Result of the task.\n */\nexport const shareInFlight = (cache, key, create) =>\n  getOrCreate(cache, key, () =>\n    create().finally(() => {\n      cache.delete(key);\n    }),\n  );\n\n/**\n * Run an asynchronous task once per key and remember its result. A failure isn’t remembered, so a\n * later caller can try again.\n * @template K, V\n * @param {Map<K, Promise<V>> | WeakMap<K & WeakKey, Promise<V>>} cache Cache of the tasks.\n * @param {K} key Cache key.\n * @param {() => Promise<V>} create Function starting the task.\n * @returns {Promise<V>} Result of the task.\n */\nexport const getOrCreateAsync = (cache, key, create) =>\n  getOrCreate(cache, key, () =>\n    create().catch((ex) => {\n      /** @type {Map<K, Promise<V>>} */ (cache).delete(key);\n\n      throw ex;\n    }),\n  );\n\n/**\n * Create a getter for a value built from a source, such as the array in a store, that is only built\n * again once the source has been replaced. A store is replaced rather than modified when it\n * changes, so the source’s identity tells whether the value is still valid. This is how an index\n * of a store, e.g. assets by path, is kept without rebuilding it on every lookup.\n * @template S, V\n * @param {() => S} getSource Function returning the current source.\n * @param {(source: S) => V} build Function building the value from the source.\n * @returns {() => V} Function returning the value for the current source.\n */\nexport const memoizeOnSource = (getSource, build) => {\n  /** @type {{ source: S, value: V } | undefined} */\n  let cache;\n\n  return () => {\n    const source = getSource();\n\n    if (!cache || cache.source !== source) {\n      cache = { source, value: build(source) };\n    }\n\n    return cache.value;\n  };\n};\n\n/**\n * Create a getter like {@link memoizeOnSource}’s for a value built from several sources, which is\n * only built again once any of them has been replaced.\n * @template {unknown[]} S, V\n * @param {() => [...S]} getSources Function returning the current sources.\n * @param {(...sources: S) => V} build Function building the value from the sources.\n * @returns {() => V} Function returning the value for the current sources.\n */\nexport const memoizeOnSources = (getSources, build) => {\n  /** @type {{ sources: S, value: V } | undefined} */\n  let cache;\n\n  return () => {\n    const sources = /** @type {S} */ (getSources());\n\n    if (!cache || sources.some((source, index) => source !== cache?.sources[index])) {\n      cache = { sources, value: build(...sources) };\n    }\n\n    return cache.value;\n  };\n};\n","import { escapeRegExp } from '@sveltia/utils/string';\n\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * Placeholder for a locale code in the `folder` option of an entry collection or the `file` option\n * of a file/singleton collection. Where it sits in the path is where each locale’s folder or file\n * name goes, which the fixed i18n structures can’t always express: Hugo’s translation by content\n * directory, for example, keeps the locale folders below `content` but above the sections, as in\n * `content/{{locale}}/posts`.\n * @see https://sveltiacms.app/en/docs/i18n/structures\n * @see https://github.com/sveltia/sveltia-cms/issues/780\n */\nexport const LOCALE_PLACEHOLDER = '{{locale}}';\n\n/**\n * Regular expression matching the `{{locale}}` placeholder as a whole path segment of a folder\n * path. A placeholder that shares a segment with other characters, like `content-{{locale}}`, isn’t\n * supported, because a locale folder is what the placeholder stands for.\n */\nconst LOCALE_FOLDER_REGEX = /(?:^|\\/){{locale}}(?:\\/|$)/;\n\n/**\n * Check whether the given path includes the `{{locale}}` placeholder.\n * @param {string} path Path.\n * @returns {boolean} Result.\n */\nexport const hasLocalePlaceholder = (path) => path.includes(LOCALE_PLACEHOLDER);\n\n/**\n * Check whether the `{{locale}}` placeholder in the given folder path is usable: it must appear\n * exactly once, as a whole path segment. A second occurrence would make the entry path matcher\n * declare a second `locale` capture group, which is a syntax error, and a partial segment has no\n * locale folder to stand for.\n * @param {string} folderPath Folder path with the placeholder.\n * @returns {boolean} Result.\n */\nexport const isValidLocaleFolderPath = (folderPath) =>\n  folderPath.split(LOCALE_PLACEHOLDER).length === 2 && LOCALE_FOLDER_REGEX.test(folderPath);\n\n/**\n * Remove the first `{{locale}}` placeholder from the given path, as the\n * `omit_default_locale_from_file_path` and `omit_default_locale_from_preview_path` i18n options do\n * for the default locale. That’s only possible where the placeholder can go without breaking the\n * rest of the path. As a whole path segment, it’s dropped along with the slash after it, or the\n * slash before it at the end of the path: `content/{{locale}}/about.md` → `content/about.md`,\n * `content/{{locale}}` → `content`, `/{{locale}}` → `/`. As a dot-separated part of a segment after\n * the first one, it’s dropped along with the dot before it: `about.{{locale}}.md` → `about.md`,\n * `about.{{locale}}` → `about`. As the first dot-separated part of a segment, it’s dropped along\n * with the dot after it, as long as a name is left in front of an extension, or another template\n * placeholder follows: `{{locale}}.about.md` → `about.md`, `/posts/{{locale}}.{{slug}}` →\n * `/posts/{{slug}}`. Anywhere else, the rest of the path would turn into something else:\n * `i18n/{{locale}}.yaml` would become `i18n/yaml`, and `settings_{{locale}}.json` would become\n * `settings_json`. Any other occurrence of the placeholder is left as is.\n * @param {string} path Path with the placeholder.\n * @returns {string | undefined} Path without the placeholder, or `undefined` if the path has no\n * placeholder or the first one can’t be removed.\n */\nexport const omitLocalePlaceholder = (path) => {\n  const index = path.indexOf(LOCALE_PLACEHOLDER);\n\n  if (index === -1) {\n    return undefined;\n  }\n\n  const before = path.slice(0, index);\n  const after = path.slice(index + LOCALE_PLACEHOLDER.length);\n\n  if (before === '' || before.endsWith('/')) {\n    // A whole path segment\n    if (after.startsWith('/')) {\n      return `${before}${after.slice(1)}`;\n    }\n\n    if (after === '') {\n      // A host name, like in the `https://{{locale}}` preview path, can’t be removed\n      if (before.endsWith('//')) {\n        return undefined;\n      }\n\n      // Keep a root slash, so a preview path like `/{{locale}}` points at the root\n      return before.length > 1 ? before.slice(0, -1) : before;\n    }\n\n    // The first part of a segment, followed by a name and an extension, or by another template\n    // placeholder standing for a name, like `{{slug}}` in a preview path\n    if (/^\\.(?:[^./][^/]*\\.|{{)/.test(after)) {\n      return `${before}${after.slice(1)}`;\n    }\n\n    return undefined;\n  }\n\n  // A later part of a segment, like a locale suffix in a file name\n  if (/[^/]\\.$/.test(before) && /^(?:[./]|$)/.test(after)) {\n    return `${before.slice(0, -1)}${after}`;\n  }\n\n  return undefined;\n};\n\n/**\n * Check whether the first `{{locale}}` placeholder in the given path can be removed for the\n * default locale. See {@link omitLocalePlaceholder} for the supported positions.\n * @param {string} path Path with the placeholder.\n * @returns {boolean} Result.\n */\nexport const canOmitLocalePlaceholder = (path) => omitLocalePlaceholder(path) !== undefined;\n\n/**\n * Fill the `{{locale}}` placeholder in the given path.\n * @param {object} args Arguments.\n * @param {string} args.path Path with the placeholder.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {boolean} [args.omitLocale] Whether to leave the locale out of the path altogether, as\n * the `omit_default_locale_from_file_path` i18n option does for the default locale. The locale is\n * filled in anyway if the placeholder isn’t in a position where it can be removed, which the config\n * parser warns about.\n * @returns {string} Path with the locale.\n */\nexport const fillLocalePlaceholder = ({ path, locale, omitLocale = false }) => {\n  if (omitLocale) {\n    // @see https://github.com/sveltia/sveltia-cms/discussions/394\n    path = omitLocalePlaceholder(path) ?? path;\n  }\n\n  // The placeholder may appear multiple times in a file path\n  // @see https://github.com/sveltia/sveltia-cms/issues/462\n  return path.replaceAll(LOCALE_PLACEHOLDER, locale);\n};\n\n/**\n * Build a regular expression pattern matching the given folder path, where the `{{locale}}`\n * placeholder is replaced with the given matcher. The pattern ends with a slash, so the file path\n * below the folder can follow.\n * @param {string} folderPath Folder path with the placeholder, e.g. `content/{{locale}}/posts`.\n * @param {string} localeFolderMatcher Pattern matching a locale folder name and the slash after it,\n * e.g. `(?<locale>en|fr)\\/`. It can make the folder optional if the default locale is omitted from\n * the file path.\n * @returns {string} Pattern, e.g. `content/(?<locale>en|fr)\\/posts/`.\n */\nexport const getLocaleFolderPattern = (folderPath, localeFolderMatcher) =>\n  `${folderPath}/`.split(`${LOCALE_PLACEHOLDER}/`).map(escapeRegExp).join(localeFolderMatcher);\n\n/**\n * Cache of the regular expressions used by {@link stripLocaleFolderPath}, keyed by folder path. A\n * folder path comes from the configuration, so the cache stays small.\n * @type {Map<string, RegExp>}\n */\nconst localeFolderPrefixRegExpCache = new Map();\n\n/**\n * Strip the given folder path, and the slash after it, from the start of the given file path. The\n * `{{locale}}` placeholder in the folder path stands for any single folder, or none, because the\n * default locale may be omitted from the file path.\n * @param {string} filePath File path, e.g. `content/en/posts/2026/hello.md`.\n * @param {string} folderPath Folder path with the placeholder, e.g. `content/{{locale}}/posts`.\n * @returns {string} Path below the folder, e.g. `2026/hello.md`, or the file path as is if it’s not\n * below the folder.\n */\nexport const stripLocaleFolderPath = (filePath, folderPath) =>\n  filePath.replace(\n    getOrCreate(\n      localeFolderPrefixRegExpCache,\n      folderPath,\n      () => new RegExp(`^${getLocaleFolderPattern(folderPath, '(?:[^/]+\\\\/)?')}`),\n    ),\n    '',\n  );\n","import { locale as appLocale, isRTL } from '@sveltia/i18n';\n\nimport { fillLocalePlaceholder } from '$lib/services/contents/i18n/placeholder';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { InternalI18nOptions, InternalLocaleCode, } from '$lib/types/private';\n * @import { LocaleCode } from '$lib/types/public';\n */\n\n/**\n * Default options for `Intl.DisplayNames()`. Use `English (US)` instead of `American English` for a\n * better language listing.\n * @type {Intl.DisplayNamesOptions}\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames\n */\nconst LANG_FORMATTER_OPTIONS = {\n  type: 'language',\n  languageDisplay: 'standard',\n  style: 'short',\n  fallback: 'none',\n};\n\n/**\n * Get the canonical locale of the given locale that can be used for various `Intl` methods.\n * @param {InternalLocaleCode} locale Locale.\n * @returns {LocaleCode | undefined} Locale or `undefined` if not determined.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument\n */\nexport const getCanonicalLocale = (locale) => {\n  let canonicalLocale = undefined;\n\n  if (locale !== '_default') {\n    try {\n      [canonicalLocale] = Intl.getCanonicalLocales(locale);\n    } catch {\n      //\n    }\n  }\n\n  return canonicalLocale;\n};\n\n/**\n * Get the text direction for the given locale.\n * @param {InternalLocaleCode} locale Locale.\n * @returns {'ltr' | 'rtl' | 'auto'} Text direction. Returns `auto` if i18n is disabled (i.e.\n * `locale` is `_default`), `rtl` if the locale is a right-to-left language, and `ltr` otherwise.\n */\nexport const getDirection = (locale) =>\n  locale === '_default' ? 'auto' : isRTL(locale) ? 'rtl' : 'ltr';\n\n/**\n * Cache of {@link Intl.DisplayNames} instances, keyed by `displayLocale`.\n * @type {Map<string, Intl.DisplayNames>}\n */\nconst displayNamesCache = new Map();\n\n/**\n * Translate the given locale code in the application UI locale.\n * @param {InternalLocaleCode} locale Locale code like `en`.\n * @param {object} [options] Options.\n * @param {InternalLocaleCode} [options.displayLocale] Locale code to display the locale name. If\n * not given, use the current application locale. Default is `en`.\n * @param {Intl.DisplayNamesOptions} [options.formatterOptions] Options for `Intl.DisplayNames()`.\n * @returns {string | undefined} Locale label like `English`. If the locale is not valid, returns\n * `undefined`.\n */\nexport const getLocaleLabel = (\n  locale,\n  {\n    displayLocale = getCanonicalLocale(appLocale.current ?? 'en'),\n    formatterOptions = LANG_FORMATTER_OPTIONS,\n  } = {},\n) => {\n  const canonicalLocale = getCanonicalLocale(locale);\n\n  if (!canonicalLocale) {\n    return undefined;\n  }\n\n  const formatter = displayLocale\n    ? getOrCreate(\n        displayNamesCache,\n        displayLocale,\n        () => new Intl.DisplayNames(displayLocale, formatterOptions),\n      )\n    : new Intl.DisplayNames(undefined, formatterOptions);\n\n  try {\n    const label = formatter.of(canonicalLocale);\n\n    if (!label) {\n      return undefined;\n    }\n\n    const [firstLetter, ...rest] = label;\n\n    // Capitalize the label because the native `of()` method returns all lowercase in some languages\n    return [firstLetter.toLocaleUpperCase(displayLocale), ...rest].join('');\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n\n    return undefined;\n  }\n};\n\n/**\n * List formatter that, unlike {@link Intl.ListFormat}, accepts items of any type.\n * @typedef {{ format: (list: Iterable<any>) => string }} ListFormatter\n */\n\n/**\n * Cache of list formatters, keyed by `\"${locale}|${serializedOptions}\"`.\n * @type {Map<string, ListFormatter>}\n */\nconst listFormatterCache = new Map();\n\n/**\n * Get a simple list formatter. `Intl.ListFormat` throws on any item that isn’t a string, while a\n * value read from a file, e.g. a Select or Relation field value, may be a number or `null`, so the\n * items are stringified, and `null` and `undefined` dropped, before they are formatted.\n * @param {InternalLocaleCode} locale Locale code.\n * @param {Partial<Intl.ListFormatOptions>} options Format options.\n * @returns {ListFormatter} Formatter.\n */\nexport const getListFormatter = (locale, options = {}) => {\n  const effectiveOptions = /** @type {Intl.ListFormatOptions} */ ({\n    style: 'narrow',\n    type: 'conjunction',\n    ...options,\n  });\n\n  const cacheKey = `${locale}|${effectiveOptions.style}|${effectiveOptions.type}`;\n\n  return getOrCreate(listFormatterCache, cacheKey, () => {\n    const formatter = new Intl.ListFormat(getCanonicalLocale(locale), effectiveOptions);\n\n    return {\n      /**\n       * Format the given list.\n       * @param {Iterable<any>} list List items.\n       * @returns {string} Formatted list.\n       */\n      format: (list) =>\n        formatter.format(\n          [...list].filter((item) => item !== null && item !== undefined).map((item) => `${item}`),\n        ),\n    };\n  });\n};\n\n/**\n * Get the complete path for the given collection folder or file, including the locale.\n * @param {object} args Arguments.\n * @param {InternalI18nOptions} args._i18n I18n configuration.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {string} args.path Collection folder or file path with the `{{locale}}` placeholder.\n * @returns {string} Complete path, including the locale.\n */\nexport const getLocalePath = ({ _i18n, locale, path }) => {\n  const { defaultLocale, omitDefaultLocaleFromFilePath } = _i18n;\n\n  return fillLocalePlaceholder({\n    path,\n    locale,\n    // Remove the default locale from the path (for Zola compatibility)\n    omitLocale: omitDefaultLocaleFromFilePath && locale === defaultLocale,\n  });\n};\n","import { getPathInfo } from '@sveltia/utils/file';\nimport { escapeRegExp, stripSlashes } from '@sveltia/utils/string';\n\nimport { customFileFormatRegistry } from '$lib/services/api/registries';\nimport { getTemplatePattern } from '$lib/services/common/template/utils';\nimport { getIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getNestedConfig } from '$lib/services/contents/collection/nested';\nimport { isEntryCollection } from '$lib/services/contents/collection/predicates';\nimport {\n  EXTENSION_FORMAT_MAP,\n  FORMAT_EXTENSION_MAP,\n  FRONTMATTER_DELIMITER_MAP,\n  MARKDOWN_EXTENSIONS,\n} from '$lib/services/contents/file/constants';\nimport { getLocalePath } from '$lib/services/contents/i18n';\nimport {\n  getLocaleFolderPattern,\n  hasLocalePlaceholder,\n} from '$lib/services/contents/i18n/placeholder';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import {\n * FileConfig,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalEntryCollection,\n * InternalI18nOptions,\n * } from '$lib/types/private';\n * @import {\n * Collection,\n * CollectionFile,\n * CollectionIndexFile,\n * FileExtension,\n * FileFormat,\n * } from '$lib/types/public';\n */\n\n/**\n * Detect a file extension from the given entry file configuration.\n * @param {object} args Arguments.\n * @param {FileExtension} [args.extension] Developer-defined file extension.\n * @param {FileFormat} [args.format] Developer-defined file format.\n * @returns {FileExtension} Determined extension.\n * @see https://decapcms.org/docs/configuration-options/#extension-and-format\n * @see https://sveltiacms.app/en/docs/collections/entries/formats\n */\nexport const detectFileExtension = ({ extension, format }) => {\n  const customExtension = format ? customFileFormatRegistry.get(format)?.extension : undefined;\n\n  if (customExtension) {\n    return customExtension;\n  }\n\n  if (extension) {\n    return extension;\n  }\n\n  if (format) {\n    return FORMAT_EXTENSION_MAP[format] ?? 'md';\n  }\n\n  return 'md';\n};\n\n/**\n * Detect a file format from the given entry file configuration.\n * @param {object} args Arguments.\n * @param {FileExtension} args.extension File extension.\n * @param {FileFormat} [args.format] Developer-defined file format.\n * @returns {FileFormat} Determined format.\n * @see https://decapcms.org/docs/configuration-options/#extension-and-format\n * @see https://sveltiacms.app/en/docs/collections/entries/formats\n */\nexport const detectFileFormat = ({ extension, format }) => {\n  if (format) {\n    return format; // supported or custom format\n  }\n\n  if (MARKDOWN_EXTENSIONS.includes(extension)) {\n    return 'frontmatter'; // auto detect\n  }\n\n  return EXTENSION_FORMAT_MAP[extension] ?? 'yaml-frontmatter';\n};\n\n/**\n * Get the file path matcher pattern for the regex. The path pattern in the middle should match the\n * filename (without extension), possibly with the parent directory. If the collection’s `path` is\n * configured, use it to generate a pattern, so that unrelated files are excluded. Note that the\n * `path` may contain `{{variable}}` placeholders, which should be replaced with a non-greedy\n * wildcard that excludes slashes. It may also contain brackets, like `app/(pages)`, which are used\n * for route groups in frameworks like SvelteKit or Next.js, and should be matched literally.\n * @param {object} args Arguments.\n * @param {string} [args.subPath] Normalized `path` collection option.\n * @param {string} [args.indexFileName] File name for index file inclusion. Typically `_index`.\n * @param {number} [args.nestedDepth] Maximum number of path segments below the collection folder,\n * for a collection with nested entries. `undefined` for a regular collection, where an entry is\n * always a direct child of the collection folder.\n * @param {string} [args.entrySuffix] Lookahead pattern for what follows an entry’s sub path (the\n * locale and extension) when the index file has an extension of its own.\n * @param {string} [args.indexSuffix] Lookahead pattern for what follows the index file’s sub path,\n * when the index file has an extension of its own.\n * @returns {string} File path matcher pattern.\n * @see https://decapcms.org/docs/collection-folder/#folder-collections-path\n * @see https://decapcms.org/docs/collection-nested/\n * @see https://sveltiacms.app/en/docs/collections/entries/slugs#file-paths\n */\nconst getFilePathMatcher = ({\n  subPath,\n  indexFileName,\n  nestedDepth,\n  entrySuffix = '',\n  indexSuffix = '',\n}) => {\n  const escapedIndexFileName = indexFileName ? escapeRegExp(indexFileName) : '';\n  // An index file with an extension of its own is told apart from the entries by that extension,\n  // and it can only be right under the collection folder, where the special index file is\n  const separateIndex = !!escapedIndexFileName && !!indexSuffix;\n  const indexAlternative = escapedIndexFileName && !separateIndex ? `|${escapedIndexFileName}` : '';\n  /** @type {string} */\n  let entryMatcher;\n\n  if (!subPath) {\n    if (nestedDepth === undefined) {\n      entryMatcher = '[^/]+?';\n    } else {\n      // An entry can be stored in any folder below the collection folder, down to the configured\n      // depth. The depth is the number of path segments, the last of which is the file name.\n      const extraSegments = Number.isFinite(nestedDepth)\n        ? `{0,${Math.max(0, nestedDepth - 1)}}`\n        : '*';\n\n      entryMatcher = `[^/]+?(?:\\\\/[^/]+?)${extraSegments}`;\n    }\n  } else {\n    const escapedSubPath = getTemplatePattern(subPath, '[^/]+?');\n    const fileMatcher = `${escapedSubPath}${indexAlternative}`;\n\n    if (nestedDepth === undefined) {\n      entryMatcher = fileMatcher;\n    } else {\n      // In a collection with nested entries, the `path` option says where an entry sits within the\n      // folder holding it, not within the collection folder, so any number of folders can come\n      // first — down to the configured depth, which the `path` option itself already takes some of\n      const remainingDepth = Number.isFinite(nestedDepth)\n        ? Math.max(0, nestedDepth - subPath.split('/').length)\n        : undefined;\n\n      const folderMatcher =\n        remainingDepth === undefined ? '(?:[^/]+\\\\/)*' : `(?:[^/]+\\\\/){0,${remainingDepth}}`;\n\n      entryMatcher = `${folderMatcher}(?:${fileMatcher})`;\n    }\n  }\n\n  if (!separateIndex) {\n    return `(?<subPath>${entryMatcher})`;\n  }\n\n  // The index file’s name is reserved: an entry going by the same name, like `posts.md` beside\n  // `posts.json`, would get the same sub path and be opened in its place, so it’s left out of the\n  // collection altogether\n  const reservedNameMatcher = `(?!${escapedIndexFileName}${entrySuffix})`;\n\n  return (\n    `(?<subPath>${reservedNameMatcher}(?:${entryMatcher})${entrySuffix}` +\n    `|${escapedIndexFileName}${indexSuffix})`\n  );\n};\n\n/**\n * Get a regular expression that matches the entry paths of the given entry collection, taking the\n * i18n structure into account.\n * @param {object} args Arguments.\n * @param {FileExtension} args.extension File extension.\n * @param {FileFormat} args.format File format.\n * @param {string} args.basePath Normalized `folder` collection option.\n * @param {string} [args.subPath] Normalized `path` collection option.\n * @param {string} [args.indexFileName] File name for index file inclusion. Typically `_index`.\n * @param {FileExtension} [args.indexFileExtension] File extension of the index file, if it can\n * differ from the entries’. Default: `extension`.\n * @param {number} [args.nestedDepth] Maximum number of path segments below the collection folder,\n * for a collection with nested entries.\n * @param {InternalI18nOptions} args._i18n I18n configuration.\n * @returns {RegExp} Regular expression.\n */\nexport const getEntryPathRegEx = ({\n  extension,\n  format,\n  basePath,\n  subPath,\n  indexFileName,\n  indexFileExtension,\n  nestedDepth,\n  _i18n,\n}) => {\n  const {\n    allLocales,\n    defaultLocale,\n    omitDefaultLocaleFromFilePath,\n    structureMap: { i18nMultiFile, i18nMultiFolder, i18nMultiRootFolder },\n  } = _i18n;\n\n  // Locale codes aren’t validated, so one with a character special to regular expressions, like\n  // `zh+`, mustn’t break the pattern\n  const joinedLocales = allLocales.map(escapeRegExp).join('|');\n\n  const joinedNonDefaultLocales = allLocales\n    .filter((locale) => locale !== defaultLocale)\n    .map(escapeRegExp)\n    .join('|');\n\n  const localeMatcher = `(?<locale>${joinedLocales})`;\n\n  const localeFolderMatcher = omitDefaultLocaleFromFilePath\n    ? `(?:(?<locale>${joinedNonDefaultLocales})\\\\/)?`\n    : `${localeMatcher}\\\\/`;\n\n  const localeFileMatcher = omitDefaultLocaleFromFilePath\n    ? `(?:\\\\.(?<locale>${joinedNonDefaultLocales}))?`\n    : `\\\\.${localeMatcher}`;\n\n  // The `{{locale}}` placeholder in the `folder` option says where the locale folder goes, so the\n  // locale folder matcher replaces it rather than coming before or after the whole base path\n  const localeInBasePath = !!basePath && hasLocalePlaceholder(basePath);\n\n  const basePathMatcher = localeInBasePath\n    ? getLocaleFolderPattern(basePath, localeFolderMatcher)\n    : basePath\n      ? `${escapeRegExp(basePath)}\\\\/`\n      : '';\n\n  const entryExtension = detectFileExtension({ format, extension });\n\n  // An index file with an extension of its own, like Eleventy’s `posts/posts.json` beside `.md`\n  // entries, is matched by its extension: each alternative of the sub path matcher looks ahead for\n  // its own extension, so an unrelated file with either extension is left out. The lookahead can’t\n  // declare the `locale` group a second time, so it uses a capture-free copy of the locale matcher\n  const indexExtension =\n    indexFileName && indexFileExtension !== undefined && indexFileExtension !== entryExtension\n      ? indexFileExtension\n      : undefined;\n\n  /**\n   * Build a lookahead for the end of a file path with the given extension.\n   * @param {string} ext File extension.\n   * @returns {string} Pattern.\n   */\n  const getSuffixMatcher = (ext) => {\n    const localeMatcherCopy = omitDefaultLocaleFromFilePath\n      ? `(?:\\\\.(?:${joinedNonDefaultLocales}))?`\n      : `\\\\.(?:${joinedLocales})`;\n\n    return `(?=${i18nMultiFile ? localeMatcherCopy : ''}\\\\.${escapeRegExp(ext)}$)`;\n  };\n\n  const pattern = [\n    '^',\n    i18nMultiRootFolder && !localeInBasePath ? localeFolderMatcher : '',\n    basePathMatcher,\n    i18nMultiFolder && !localeInBasePath ? localeFolderMatcher : '',\n    getFilePathMatcher({\n      subPath,\n      indexFileName,\n      nestedDepth,\n      entrySuffix: indexExtension ? getSuffixMatcher(entryExtension) : '',\n      indexSuffix: indexExtension ? getSuffixMatcher(indexExtension) : '',\n    }),\n    i18nMultiFile ? localeFileMatcher : '',\n    '\\\\.',\n    indexExtension\n      ? `(?:${escapeRegExp(entryExtension)}|${escapeRegExp(indexExtension)})`\n      : escapeRegExp(entryExtension),\n    '$',\n  ].join('');\n\n  return new RegExp(pattern);\n};\n\n/**\n * Detect the front matter format’s delimiters from the given entry file configuration.\n * @param {object} args Arguments.\n * @param {FileFormat} args.format File format.\n * @param {string | string[]} [args.delimiter] Configured delimiter.\n * @returns {[string, string] | undefined} Start and end delimiters. If `undefined`, the parser\n * automatically detects the delimiters, while the formatter uses the YAML delimiters.\n * @see https://decapcms.org/docs/configuration-options/#frontmatter_delimiter\n * @see https://sveltiacms.app/en/docs/collections/entries/formats#front-matter-delimiter\n */\nexport const getFrontMatterDelimiters = ({ format, delimiter }) => {\n  if (isNonEmptyString(delimiter)) {\n    return [delimiter, delimiter];\n  }\n\n  if (Array.isArray(delimiter) && delimiter.length === 2) {\n    return /** @type {[string, string]} */ (delimiter);\n  }\n\n  return FRONTMATTER_DELIMITER_MAP[format] ?? undefined;\n};\n\n/**\n * Get the extension and format of the collection’s special index file, when it has its own. An\n * Eleventy directory data file, for example, is a `posts/posts.json` file in a folder of Markdown\n * entries.\n * @param {object} args Arguments.\n * @param {CollectionIndexFile} [args.indexFile] Normalized index file configuration.\n * @param {FileExtension} [args.extension] Developer-defined collection file extension.\n * @param {FileFormat} [args.format] Developer-defined collection file format.\n * @returns {{ extension: FileExtension, format: FileFormat } | undefined} Extension and format,\n * or `undefined` if the index file has the same extension and format as the entries.\n */\nexport const getIndexFileFormat = ({ indexFile, extension, format }) => {\n  if (!indexFile) {\n    return undefined;\n  }\n\n  const { extension: _indexExtension, format: _indexFormat } = indexFile;\n\n  if (_indexExtension === undefined && _indexFormat === undefined) {\n    return undefined;\n  }\n\n  const indexExtension = detectFileExtension({ extension: _indexExtension, format: _indexFormat });\n  const indexFormat = detectFileFormat({ extension: indexExtension, format: _indexFormat });\n  const entryExtension = detectFileExtension({ extension, format });\n  const entryFormat = detectFileFormat({ extension: entryExtension, format });\n\n  if (indexExtension === entryExtension && indexFormat === entryFormat) {\n    return undefined;\n  }\n\n  return { extension: indexExtension, format: indexFormat };\n};\n\n/**\n * Get the normalized entry file configuration for the given collection or collection file.\n * @param {object} args Arguments.\n * @param {Collection} args.rawCollection Developer-defined collection.\n * @param {CollectionFile} [args.file] Developer-defined collection file.\n * @param {InternalI18nOptions} args._i18n I18n configuration.\n * @returns {FileConfig} Entry file configuration.\n */\nexport const getFileConfig = ({ rawCollection, file, _i18n }) => {\n  const {\n    // @ts-ignore\n    folder,\n    // @ts-ignore\n    file: dataFile,\n    // @ts-ignore\n    path: subPath,\n    // @ts-ignore\n    extension: _extension,\n    format: _format,\n    frontmatter_delimiter: _delimiter,\n    body_field: bodyField,\n    yaml_quote: yamlQuote,\n  } = rawCollection;\n\n  const _isEntryCollection = isEntryCollection(rawCollection);\n  // An entry collection can store all the entries in one file instead of a folder\n  const arrayFile = _isEntryCollection && typeof dataFile === 'string';\n\n  const filePath = file?.file\n    ? stripSlashes(file.file)\n    : arrayFile\n      ? stripSlashes(dataFile)\n      : undefined;\n\n  const __extension = filePath ? getPathInfo(filePath).extension : _extension;\n  const __format = file?.format ?? _format;\n  const extension = detectFileExtension({ format: __format, extension: __extension });\n  const format = detectFileFormat({ format: __format, extension });\n  const delimiter = file?.frontmatter_delimiter ?? _delimiter;\n  const _isFolderCollection = _isEntryCollection && !arrayFile;\n  const basePath = _isFolderCollection ? stripSlashes(/** @type {string} */ (folder)) : undefined;\n  const indexFile = _isFolderCollection ? getIndexFile(rawCollection) : undefined;\n  const indexFileName = indexFile?.name;\n  const nestedDepth = _isFolderCollection ? getNestedConfig(rawCollection)?.depth : undefined;\n\n  const indexFileFormat = getIndexFileFormat({\n    indexFile,\n    extension: _extension,\n    format: _format,\n  });\n\n  /** @type {FileConfig} */\n  const config = {\n    extension,\n    format,\n    basePath,\n    subPath: _isFolderCollection ? subPath : undefined,\n    fullPathRegEx:\n      basePath !== undefined\n        ? getEntryPathRegEx({\n            extension,\n            format,\n            basePath,\n            subPath,\n            indexFileName,\n            indexFileExtension: indexFileFormat?.extension,\n            nestedDepth,\n            _i18n,\n          })\n        : undefined,\n    fullPath: filePath\n      ? getLocalePath({ _i18n, locale: _i18n.defaultLocale, path: filePath })\n      : undefined,\n    fmDelimiters: getFrontMatterDelimiters({ format, delimiter }),\n    bodyField: file?.body_field ?? bodyField,\n    yamlQuote: !!yamlQuote,\n  };\n\n  if (arrayFile) {\n    config.arrayFile = true;\n  }\n\n  if (indexFileFormat) {\n    // The index file shares the rest of the configuration with the entries, including the path\n    // matcher, which matches both\n    config.indexFile = {\n      ...config,\n      ...indexFileFormat,\n      fmDelimiters: getFrontMatterDelimiters({ format: indexFileFormat.format, delimiter }),\n    };\n  }\n\n  return config;\n};\n\n/**\n * Get the file configuration that applies to an entry: a collection file’s for a file/singleton\n * collection, the index file’s for an entry collection’s special index file with an extension or\n * format of its own, or the collection’s.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s special index file.\n * @returns {FileConfig} File configuration.\n */\nexport const resolveFileConfig = ({ collection, collectionFile, isIndexFile = false }) => {\n  const { _file } = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  return (isIndexFile ? _file.indexFile : undefined) ?? _file;\n};\n","/**\n * @import { I18nFileStructure } from '$lib/types/public';\n */\n\n/**\n * I18n structure types.\n * @type {Record<string, I18nFileStructure>}\n * @todo Remove the legacy `MULTIPLE_FOLDERS_I18N_ROOT` structure prior to the 1.0 release.\n */\nexport const I18N_STRUCTURES = {\n  SINGLE_FILE: 'single_file',\n  SINGLE_FILE_DEFAULT_ROOT: 'single_file_default_root',\n  MULTIPLE_FILES: 'multiple_files',\n  MULTIPLE_FOLDERS: 'multiple_folders',\n  MULTIPLE_FOLDERS_I18N_ROOT: 'multiple_folders_i18n_root', // deprecated\n  MULTIPLE_ROOT_FOLDERS: 'multiple_root_folders', // new name\n};\n\n/**\n * I18n structures that store each locale’s copy of the whole site below a folder named after it, so\n * a locale name comes in front of a collection’s own folder. The other structures either keep one\n * file per entry or put the locale folder inside the collection folder.\n * @type {I18nFileStructure[]}\n */\nexport const LOCALE_ROOT_FOLDER_STRUCTURES = [\n  I18N_STRUCTURES.MULTIPLE_FOLDERS_I18N_ROOT,\n  I18N_STRUCTURES.MULTIPLE_ROOT_FOLDERS,\n];\n\n/**\n * Default locale identifier.\n */\nexport const DEFAULT_LOCALE_KEY = '_default';\n\n/**\n * Default canonical slug configuration.\n */\nexport const DEFAULT_CANONICAL_SLUG = {\n  key: 'translationKey',\n  value: '{{slug}}',\n};\n","import { isObject } from '@sveltia/utils/object';\n\n/**\n * @import { InternalSingletonCollection } from '$lib/types/private';\n * @import {\n * CmsConfig,\n * Collection,\n * CollectionDivider,\n * CollectionFile,\n * I18nOptions,\n * } from '$lib/types/public';\n */\n\n/**\n * Merge the i18n configuration from the site, collection and file levels. The site configuration is\n * passed in rather than read from the `cmsConfig` store, so the function can also be used by the\n * config parser, which runs before the store is populated.\n * @param {object} args Arguments.\n * @param {CmsConfig | undefined} args.cmsConfig The site configuration.\n * @param {Collection | CollectionDivider | InternalSingletonCollection} args.collection The\n * collection configuration.\n * @param {CollectionFile} [args.file] The collection file configuration.\n * @returns {I18nOptions | undefined} Merged configuration or `undefined` if i18n is not enabled.\n */\nexport const mergeI18nConfigs = ({ cmsConfig, collection, file }) => {\n  const siteConfig = cmsConfig?.i18n;\n\n  if (!isObject(siteConfig)) {\n    return undefined;\n  }\n\n  const config = structuredClone(/** @type {I18nOptions} */ (siteConfig));\n  const { name, i18n: collectionI18n } = /** @type {Collection} */ (collection);\n\n  // Check if the collection has its own i18n configuration. The singleton collection doesn’t have\n  // its own i18n configuration, so it will inherit the global one if defined.\n  if (!collectionI18n && name !== '_singletons') {\n    return undefined;\n  }\n\n  if (isObject(collectionI18n)) {\n    Object.assign(config, collectionI18n);\n  }\n\n  if (file) {\n    if (!file.i18n) {\n      return undefined;\n    }\n\n    if (isObject(file.i18n)) {\n      Object.assign(config, file.i18n);\n    }\n  }\n\n  return config;\n};\n\n/**\n * Get the `omit_default_locale_from_file_path` option from the given merged i18n configuration,\n * falling back to its deprecated `omit_default_locale_from_filename` alias.\n * @param {I18nOptions | undefined} config Merged configuration.\n * @returns {boolean} Whether to omit the default locale from file paths.\n */\nexport const getOmitDefaultLocaleOption = (config) =>\n  config?.omit_default_locale_from_file_path ?? config?.omit_default_locale_from_filename ?? false;\n","import { cmsConfig } from '$lib/services/config';\nimport {\n  DEFAULT_CANONICAL_SLUG,\n  DEFAULT_LOCALE_KEY,\n  I18N_STRUCTURES,\n} from '$lib/services/contents/i18n/config/constants';\nimport { mergeI18nConfigs } from '$lib/services/contents/i18n/config/merge';\nimport {\n  canOmitLocalePlaceholder,\n  hasLocalePlaceholder,\n} from '$lib/services/contents/i18n/placeholder';\n\n/**\n * @import {\n * EntryDraft,\n * I18nFileStructureMap,\n * InternalCmsConfig,\n * InternalI18nOptions,\n * } from '$lib/types/private';\n * @import { Collection, CollectionFile, I18nFileStructure } from '$lib/types/public';\n */\n\n/**\n * The default, normalized i18n configuration with no locales defined.\n * @type {InternalI18nOptions}\n */\nexport const DEFAULT_I18N_CONFIG = {\n  i18nEnabled: false,\n  saveAllLocales: true,\n  allLocales: [DEFAULT_LOCALE_KEY],\n  initialLocales: [DEFAULT_LOCALE_KEY],\n  defaultLocale: DEFAULT_LOCALE_KEY,\n  structure: I18N_STRUCTURES.SINGLE_FILE,\n  structureMap: {\n    i18nSingleFile: false,\n    i18nSingleFileDefaultRoot: false,\n    i18nMultiFile: false,\n    i18nMultiFolder: false,\n    i18nMultiRootFolder: false,\n  },\n  canonicalSlug: { ...DEFAULT_CANONICAL_SLUG },\n  omitDefaultLocaleFromFilePath: false,\n  omitDefaultLocaleFromPreviewPath: false,\n};\n\n/**\n * Get the normalized i18n configuration of the collection or collection file an entry draft\n * belongs to.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {InternalI18nOptions} I18n configuration, or the default one if there is no draft.\n */\nexport const getDraftI18nConfig = (draft) =>\n  (draft?.collectionFile ?? draft?.collection)?._i18n ?? DEFAULT_I18N_CONFIG;\n\n/**\n * Determines the appropriate structure based on the collection or file configuration.\n * @param {I18nFileStructure} defaultStructure The default structure from config.\n * @param {CollectionFile} [file] The collection file configuration.\n * @param {string} [folder] The `folder` option of an entry collection.\n * @param {string} [dataFile] The `file` option of an entry collection, which stores all the entries\n * in one file.\n * @returns {I18nFileStructure} The determined structure.\n */\nexport const determineStructure = (defaultStructure, file, folder, dataFile) => {\n  if (!file && typeof dataFile !== 'string') {\n    // The `{{locale}}` placeholder says where the locale folder goes, so the collection has one\n    // folder per locale wherever the configured structure would put it\n    if (typeof folder === 'string' && hasLocalePlaceholder(folder)) {\n      return I18N_STRUCTURES.MULTIPLE_FOLDERS;\n    }\n\n    return defaultStructure;\n  }\n\n  if (file?.file.includes('{{locale}}')) {\n    return I18N_STRUCTURES.MULTIPLE_FILES;\n  }\n\n  // For file collections without `{{locale}}`, and entry collections storing all the entries in\n  // one file, preserve `single_file_default_root` if set; otherwise fall back to `single_file`.\n  if (defaultStructure === I18N_STRUCTURES.SINGLE_FILE_DEFAULT_ROOT) {\n    return I18N_STRUCTURES.SINGLE_FILE_DEFAULT_ROOT;\n  }\n\n  return I18N_STRUCTURES.SINGLE_FILE;\n};\n\n/**\n * Creates the structure map based on i18n status and structure.\n * @param {boolean} i18nEnabled Whether i18n is enabled.\n * @param {string} structure The current structure.\n * @returns {I18nFileStructureMap} The structure map.\n */\nexport const createStructureMap = (i18nEnabled, structure) => ({\n  i18nSingleFile: i18nEnabled && structure === I18N_STRUCTURES.SINGLE_FILE,\n  i18nSingleFileDefaultRoot: i18nEnabled && structure === I18N_STRUCTURES.SINGLE_FILE_DEFAULT_ROOT,\n  i18nMultiFile: i18nEnabled && structure === I18N_STRUCTURES.MULTIPLE_FILES,\n  i18nMultiFolder: i18nEnabled && structure === I18N_STRUCTURES.MULTIPLE_FOLDERS,\n  i18nMultiRootFolder:\n    i18nEnabled &&\n    (structure === I18N_STRUCTURES.MULTIPLE_FOLDERS_I18N_ROOT || // deprecated\n      structure === I18N_STRUCTURES.MULTIPLE_ROOT_FOLDERS), // new name\n});\n\n/**\n * Check if the given i18n structure stores all the locales of an entry in one file: the\n * `single_file` or `single_file_default_root` structure.\n * @param {Partial<I18nFileStructureMap>} structureMap Structure map of the normalized i18n\n * configuration.\n * @returns {boolean} Result.\n */\nexport const usesSingleFileStructure = ({ i18nSingleFile, i18nSingleFileDefaultRoot }) =>\n  !!i18nSingleFile || !!i18nSingleFileDefaultRoot;\n\n/**\n * Check if the given i18n structure stores each locale of an entry in a file of its own: the\n * `multiple_files`, `multiple_folders` or `multiple_root_folders` structure.\n * @param {Partial<I18nFileStructureMap>} structureMap Structure map of the normalized i18n\n * configuration.\n * @returns {boolean} Result.\n */\nexport const usesMultiFileStructure = ({ i18nMultiFile, i18nMultiFolder, i18nMultiRootFolder }) =>\n  !!i18nMultiFile || !!i18nMultiFolder || !!i18nMultiRootFolder;\n\n/**\n * Determines the default locale from the available locales.\n * @param {boolean} i18nEnabled Whether i18n is enabled.\n * @param {string[]} allLocales All available locales.\n * @param {string} [specifiedDefault] The specified default locale.\n * @returns {string} The default locale.\n */\nexport const determineDefaultLocale = (i18nEnabled, allLocales, specifiedDefault) => {\n  if (!i18nEnabled) {\n    return DEFAULT_LOCALE_KEY;\n  }\n\n  return specifiedDefault && allLocales.includes(specifiedDefault)\n    ? specifiedDefault\n    : allLocales[0];\n};\n\n/**\n * Determines the initial locales based on configuration.\n * @param {string | string[] | undefined} initialLocalesConfig The initial locales configuration.\n * @param {string[]} allLocales All available locales.\n * @param {string} defaultLocale The default locale.\n * @returns {string[]} The initial locales.\n */\nexport const determineInitialLocales = (initialLocalesConfig, allLocales, defaultLocale) => {\n  if (initialLocalesConfig === 'all') {\n    return allLocales;\n  }\n\n  if (initialLocalesConfig === 'default') {\n    return [defaultLocale];\n  }\n\n  return allLocales.filter(\n    (locale) =>\n      // Default locale cannot be disabled\n      locale === defaultLocale ||\n      (Array.isArray(initialLocalesConfig) ? initialLocalesConfig.includes(locale) : true),\n  );\n};\n\n/**\n * Determines whether the default locale should be omitted from the file path.\n * @param {boolean} omitDefaultLocale The raw `omit_default_locale_from_file_path` config value.\n * @param {I18nFileStructureMap} structureMap The structure map.\n * @param {CollectionFile} [file] The collection file configuration.\n * @returns {boolean} Whether to omit the default locale from the file path.\n */\nexport const determineOmitDefaultLocale = (omitDefaultLocale, structureMap, file) => {\n  if (!omitDefaultLocale) {\n    return false;\n  }\n\n  // The placeholder has to be where it can be removed without breaking the rest of the path. In any\n  // other position the locale is kept, which the config parser warns about\n  if (file) {\n    return canOmitLocalePlaceholder(file.file);\n  }\n\n  return usesMultiFileStructure(structureMap);\n};\n\n/**\n * Get the normalized i18n configuration for the given collection or collection file.\n * @param {Collection} collection Developer-defined collection.\n * @param {CollectionFile} [file] Developer-defined collection file.\n * @returns {InternalI18nOptions} Config.\n * @see https://decapcms.org/docs/i18n/\n * @see https://sveltiacms.app/en/docs/i18n\n */\nexport const normalizeI18nConfig = (collection, file) => {\n  const config = mergeI18nConfigs({\n    cmsConfig: /** @type {InternalCmsConfig} */ (cmsConfig.current),\n    collection,\n    file,\n  });\n\n  const {\n    structure: defaultStructure = I18N_STRUCTURES.SINGLE_FILE,\n    locales = [],\n    default_locale: specifiedDefaultLocale,\n    initial_locales: initialLocalesConfig,\n    save_all_locales: saveAllLocalesConfig = true,\n    canonical_slug: canonicalSlugConfig = { key: undefined, value: undefined },\n    omit_default_locale_from_filename: omitDefaultLocaleLegacy,\n    omit_default_locale_from_file_path: omitDefaultLocale = omitDefaultLocaleLegacy ?? false,\n    omit_default_locale_from_preview_path: omitDefaultLocaleFromPreviewPath = false,\n  } = config ?? {};\n\n  const {\n    key: canonicalSlugKey = DEFAULT_CANONICAL_SLUG.key,\n    value: canonicalSlugTemplate = DEFAULT_CANONICAL_SLUG.value,\n  } = canonicalSlugConfig;\n\n  const i18nEnabled = locales.length > 0;\n  const allLocales = i18nEnabled ? locales : [DEFAULT_LOCALE_KEY];\n  const defaultLocale = determineDefaultLocale(i18nEnabled, allLocales, specifiedDefaultLocale);\n  const { folder, file: dataFile } = /** @type {{ folder?: string, file?: string }} */ (collection);\n  const structure = determineStructure(defaultStructure, file, folder, dataFile);\n  const structureMap = createStructureMap(i18nEnabled, structure);\n\n  const saveAllLocales = i18nEnabled\n    ? saveAllLocalesConfig === true && initialLocalesConfig === undefined\n    : true;\n\n  const initialLocales = determineInitialLocales(initialLocalesConfig, allLocales, defaultLocale);\n\n  const omitDefaultLocaleFromFilePath = determineOmitDefaultLocale(\n    omitDefaultLocale,\n    structureMap,\n    file,\n  );\n\n  return {\n    i18nEnabled,\n    saveAllLocales,\n    allLocales,\n    defaultLocale,\n    initialLocales,\n    structure,\n    structureMap,\n    canonicalSlug: {\n      key: canonicalSlugKey,\n      value: canonicalSlugTemplate,\n    },\n    omitDefaultLocaleFromFilePath,\n    omitDefaultLocaleFromPreviewPath,\n  };\n};\n","import { cmsConfig } from '$lib/services/config';\n\n/**\n * @import {\n * FieldLegacyMediaLibrary,\n * FieldMediaLibraries,\n * GlobalLegacyMediaLibrary,\n * MediaField,\n * MediaLibraries,\n * } from '$lib/types/public';\n */\n\n/**\n * Helper to check `multiple` option in media libraries config.\n * @param {MediaLibraries | FieldMediaLibraries | undefined} mediaLibraries Media libraries\n * configuration.\n * @returns {boolean | undefined} Result of checking if any media library allows multiple files.\n */\nexport const hasMultipleInMediaLibraries = (mediaLibraries) => {\n  if (!mediaLibraries) {\n    return undefined;\n  }\n\n  const libs = Object.values(mediaLibraries);\n\n  // @ts-ignore\n  if (libs.some((lib) => lib.config?.multiple === true)) {\n    return true;\n  }\n\n  // @ts-ignore\n  if (libs.some((lib) => lib.config?.multiple === false)) {\n    return false;\n  }\n\n  return undefined;\n};\n\n/**\n * Helper to check `multiple` option in media library config.\n * @param {GlobalLegacyMediaLibrary | FieldLegacyMediaLibrary | undefined} mediaLibrary Media\n * library configuration.\n * @returns {boolean | undefined} Result of checking if any media library allows multiple files.\n */\nexport const hasMultipleInMediaLibrary = (mediaLibrary) => {\n  // @ts-ignore Stock Asset library doesn’t have `config` property\n  if (!mediaLibrary?.config) {\n    return undefined;\n  }\n\n  // @ts-ignore Stock Asset library doesn’t have `config` property\n  const { multiple } = mediaLibrary.config;\n\n  if (typeof multiple === 'boolean') {\n    return multiple;\n  }\n\n  return undefined;\n};\n\n/**\n * Check if the field configuration allows multiple files.\n * @param {MediaField} fieldConfig Field configuration to check.\n * @returns {boolean} `true` if the field allows multiple files, `false` otherwise.\n */\nexport const isMultiple = (fieldConfig) => {\n  const _cmsConfig = cmsConfig.current;\n\n  return (\n    fieldConfig.multiple ??\n    hasMultipleInMediaLibraries(fieldConfig.media_libraries) ??\n    hasMultipleInMediaLibrary(fieldConfig.media_library) ??\n    hasMultipleInMediaLibraries(_cmsConfig?.media_libraries) ??\n    hasMultipleInMediaLibrary(_cmsConfig?.media_library) ??\n    false\n  );\n};\n","import { _ } from '@sveltia/i18n';\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport { cmsConfig } from '$lib/services/config';\nimport {\n  getValidCollectionFiles,\n  isEntryCollection,\n  isFileCollection,\n  isSingletonCollection,\n  isValidCollection,\n  isValidCollectionFile,\n} from '$lib/services/contents/collection/predicates';\nimport { MEDIA_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getFileConfig } from '$lib/services/contents/file/config';\nimport { normalizeI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isMultiple } from '$lib/services/integrations/media-libraries/multiple';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * CollectionType,\n * InternalCollection,\n * InternalEntryCollection,\n * InternalFileCollection,\n * InternalI18nOptions,\n * } from '$lib/types/private';\n * @import {\n * Collection,\n * CollectionDivider,\n * CollectionFile,\n * EntryCollection,\n * FieldKeyPath,\n * FileCollection,\n * MediaField,\n * } from '$lib/types/public';\n */\n\n/**\n * Currently selected collection.\n * @type {{ current: InternalCollection | undefined }}\n */\nexport const selectedCollection = createRawState();\n\n/**\n * @type {Map<string, InternalCollection | undefined>}\n */\nexport const collectionCacheMap = new Map();\n\n/**\n * Get a list of valid collections from the given collection definitions. This filters out dividers\n * and invalid collections that do not have a `fields` property for entry collections or a `files`\n * property for file collections.\n * @param {object} [options] Options.\n * @param {(Collection | CollectionDivider)[]} [options.collections] Collection definitions. May\n * include dividers. Defaults to the collections defined in the CMS configuration.\n * @param {boolean} [options.visible] Whether to filter out hidden collections. Defaults to `false`.\n * @param {CollectionType} [options.type] Type of collections to filter by. If provided, only\n * collections of this type will be returned.\n * @returns {Collection[]} List of valid collections.\n */\nexport const getValidCollections = ({\n  /* v8 ignore next */\n  collections = cmsConfig.current?.collections ?? [],\n  visible,\n  type,\n} = {}) =>\n  /** @type {Collection[]} */ (\n    collections.filter((collection) => isValidCollection(collection, { visible, type }))\n  );\n\n/**\n * Get the first visible entry collection or file collection in the collection list.\n * @returns {Collection | undefined} Found collection.\n */\nexport const getFirstCollection = () => getValidCollections({ visible: true })[0];\n\n/**\n * Get a list of field key paths, or file path templates starting with a slash, to be used to find\n * an entry thumbnail.\n * @param {Collection} rawCollection Raw collection definition.\n * @returns {FieldKeyPath[]} Key path list.\n */\nexport const getThumbnailFieldNames = (rawCollection) => {\n  if (!isEntryCollection(rawCollection)) {\n    return [];\n  }\n\n  const { fields, thumbnail = true } = rawCollection;\n\n  // Disable thumbnails\n  if (thumbnail === false) {\n    return [];\n  }\n\n  if (typeof thumbnail === 'string') {\n    return [thumbnail];\n  }\n\n  // Support multiple field names\n  if (Array.isArray(thumbnail)) {\n    return thumbnail;\n  }\n\n  // Collect the names of all non-nested Image/File fields for inference\n  if (fields?.length) {\n    return /** @type {MediaField[]} */ (\n      fields.filter(({ widget: fieldType = 'string' }) => MEDIA_FIELD_TYPES.includes(fieldType))\n    ).map((field) =>\n      // If the field takes multiple files, append `.*` to the name to indicate that it’s an array.\n      // The option can also come from the media library configuration\n      isMultiple(field) ? `${field.name}.*` : field.name,\n    );\n  }\n\n  return [];\n};\n\n/**\n * Parse an entry collection and add additional properties.\n * @param {EntryCollection} rawCollection Raw collection definition.\n * @param {InternalI18nOptions} _i18n I18n options of the collection.\n * @returns {InternalEntryCollection} Parsed entry collection with additional properties.\n */\nexport const parseEntryCollection = (rawCollection, _i18n) => ({\n  ...rawCollection,\n  _i18n,\n  _type: 'entry',\n  _file: getFileConfig({ rawCollection, _i18n }),\n  _thumbnailFieldNames: getThumbnailFieldNames(rawCollection),\n});\n\n/**\n * Parse a file/singleton collection and add additional properties.\n * @param {FileCollection} rawCollection Raw collection definition.\n * @param {InternalI18nOptions} _i18n I18n options of the collection.\n * @param {CollectionFile[]} files List of files in the collection.\n * @returns {InternalFileCollection} Parsed file/singleton collection with additional properties.\n */\nexport const parseFileCollection = (rawCollection, _i18n, files) => ({\n  ...rawCollection,\n  _i18n,\n  _type: isSingletonCollection(rawCollection) ? 'singleton' : 'file',\n  _fileMap: Object.fromEntries(\n    files.filter(isValidCollectionFile).map((file) => {\n      const __i18n = normalizeI18nConfig(rawCollection, file);\n      const __file = getFileConfig({ rawCollection, file, _i18n: __i18n });\n\n      return [file.name, { ...file, _file: __file, _i18n: __i18n }];\n    }),\n  ),\n});\n\n/**\n * Get the pseudo singleton file collection. This is a collection that contains all singleton files\n * defined in the CMS configuration. It is used to handle singletons as a collection, allowing for\n * easier access and management.\n * @returns {InternalCollection | undefined} Singleton collection, or `undefined` if no singletons\n * are defined.\n */\nexport const getSingletonCollection = () => {\n  const singletons = cmsConfig.current?.singletons;\n\n  if (!Array.isArray(singletons)) {\n    return undefined;\n  }\n\n  const files = getValidCollectionFiles(singletons) //\n    .map((file) => ({ ...file, file: stripSlashes(file.file) }));\n\n  if (!files.length) {\n    return undefined;\n  }\n\n  /** @type {Collection} */\n  const rawCollection = { name: '_singletons', files };\n  const _i18n = normalizeI18nConfig(rawCollection);\n\n  return parseFileCollection(rawCollection, _i18n, files);\n};\n\n/**\n * Get a collection by name.\n * @param {string} name Collection name.\n * @returns {InternalCollection | undefined} Collection, including some extra, normalized\n * properties.\n */\nexport const getCollection = (name) => {\n  const cache = collectionCacheMap.get(name);\n\n  if (cache) {\n    return cache;\n  }\n\n  if (name === '_singletons') {\n    const collection = getSingletonCollection();\n\n    collectionCacheMap.set(name, collection);\n\n    return collection;\n  }\n\n  const rawCollection = getValidCollections().find((c) => c.name === name);\n\n  // Ignore invalid collection\n  if (!rawCollection) {\n    collectionCacheMap.set(name, undefined);\n\n    return undefined;\n  }\n\n  const entryCollection = isEntryCollection(rawCollection) ? rawCollection : undefined;\n  const fileCollection = isFileCollection(rawCollection) ? rawCollection : undefined;\n\n  /* v8 ignore next 4 */\n  if (!entryCollection && !fileCollection) {\n    collectionCacheMap.set(name, undefined);\n\n    return undefined;\n  }\n\n  // Normalize folder/file paths by removing leading/trailing slashes\n  if (entryCollection) {\n    if (typeof entryCollection.folder === 'string') {\n      entryCollection.folder = stripSlashes(entryCollection.folder);\n    }\n\n    if (typeof entryCollection.file === 'string') {\n      entryCollection.file = stripSlashes(entryCollection.file);\n    }\n  } else {\n    fileCollection?.files.forEach((f) => {\n      if (f.file) {\n        f.file = stripSlashes(f.file);\n      }\n    });\n  }\n\n  const _i18n = normalizeI18nConfig(rawCollection);\n\n  const collection = entryCollection\n    ? parseEntryCollection(entryCollection, _i18n)\n    : parseFileCollection(\n        /** @type {FileCollection} */ (fileCollection),\n        _i18n,\n        /** @type {FileCollection} */ (fileCollection).files,\n      );\n\n  collectionCacheMap.set(name, collection);\n\n  return collection;\n};\n\n/**\n * Get the label for a collection. If the collection is a singleton, it returns a localized label\n * for files. Otherwise, it returns the collection’s label or name.\n * @param {InternalCollection} collection Collection object.\n * @param {object} [options] Options for label formatting.\n * @param {boolean} [options.useSingular] Whether to use a singular form of the label.\n * @returns {string} Human-readable label for the collection.\n */\nexport const getCollectionLabel = (collection, { useSingular = false } = {}) => {\n  const { _type, name, label, label_singular: singularLabel } = collection;\n\n  if (_type === 'singleton') {\n    return _('files');\n  }\n\n  if (useSingular && singularLabel) {\n    return singularLabel;\n  }\n\n  return label || name;\n};\n\n/**\n * Get the index of a collection with the given name.\n * @param {string | undefined} collectionName Collection name.\n * @returns {number} Index.\n */\nexport const getCollectionIndex = (collectionName) => {\n  if (!collectionName) {\n    return -1;\n  }\n\n  // Singleton collection is always at the end\n  if (collectionName === '_singletons') {\n    return 9999999;\n  }\n\n  return cmsConfig.current?.collections?.findIndex(({ name }) => name === collectionName) ?? -1;\n};\n","'use strict';\n\nfunction isHighSurrogate(codePoint) {\n  return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n  return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function truncate(getLength, string, byteLength) {\n  if (typeof string !== \"string\") {\n    throw new Error(\"Input must be string\");\n  }\n\n  var charLength = string.length;\n  var curByteLength = 0;\n  var codePoint;\n  var segment;\n\n  for (var i = 0; i < charLength; i += 1) {\n    codePoint = string.charCodeAt(i);\n    segment = string[i];\n\n    if (isHighSurrogate(codePoint) && isLowSurrogate(string.charCodeAt(i + 1))) {\n      i += 1;\n      segment += string[i];\n    }\n\n    curByteLength += getLength(segment);\n\n    if (curByteLength === byteLength) {\n      return string.slice(0, i + 1);\n    }\n    else if (curByteLength > byteLength) {\n      return string.slice(0, i - segment.length + 1);\n    }\n  }\n\n  return string;\n};\n\n","'use strict';\n\nfunction isHighSurrogate(codePoint) {\n  return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n  return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function getByteLength(string) {\n  if (typeof string !== \"string\") {\n    throw new Error(\"Input must be string\");\n  }\n\n  var charLength = string.length;\n  var byteLength = 0;\n  var codePoint = null;\n  var prevCodePoint = null;\n  for (var i = 0; i < charLength; i++) {\n    codePoint = string.charCodeAt(i);\n    // handle 4-byte non-BMP chars\n    // low surrogate\n    if (isLowSurrogate(codePoint)) {\n      // when parsing previous hi-surrogate, 3 is added to byteLength\n      if (prevCodePoint != null && isHighSurrogate(prevCodePoint)) {\n        byteLength += 1;\n      }\n      else {\n        byteLength += 3;\n      }\n    }\n    else if (codePoint <= 0x7f ) {\n      byteLength += 1;\n    }\n    else if (codePoint >= 0x80 && codePoint <= 0x7ff) {\n      byteLength += 2;\n    }\n    else if (codePoint >= 0x800 && codePoint <= 0xffff) {\n      byteLength += 3;\n    }\n    prevCodePoint = codePoint;\n  }\n\n  return byteLength;\n};\n","'use strict';\n\nvar truncate = require(\"./lib/truncate\");\nvar getLength = require(\"utf8-byte-length/browser\");\nmodule.exports = truncate.bind(null, getLength);\n","/*jshint node:true*/\n'use strict';\n\n/**\n * Replaces characters in strings that are illegal/unsafe for filenames.\n * Unsafe characters are either removed or replaced by a substitute set\n * in the optional `options` object.\n *\n * Illegal Characters on Various Operating Systems\n * / ? < > \\ : * | \"\n * https://kb.acronis.com/content/39790\n *\n * Unicode Control codes\n * C0 0x00-0x1f & C1 (0x80-0x9f)\n * http://en.wikipedia.org/wiki/C0_and_C1_control_codes\n *\n * Reserved filenames on Unix-based systems (\".\", \"..\")\n * Reserved filenames in Windows (\"CON\", \"PRN\", \"AUX\", \"NUL\", \"COM1\",\n * \"COM2\", \"COM3\", \"COM4\", \"COM5\", \"COM6\", \"COM7\", \"COM8\", \"COM9\",\n * \"LPT1\", \"LPT2\", \"LPT3\", \"LPT4\", \"LPT5\", \"LPT6\", \"LPT7\", \"LPT8\", and\n * \"LPT9\", \"COM¹\", \"COM²\", \"COM³\", \"LPT¹\", \"LPT²\", and \"LPT³\")\n * case-insensitively and with or without filename extensions.\n *\n * Capped at 255 characters in length.\n * http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs\n *\n * @param  {String} input   Original filename\n * @param  {Object} options {replacement: String | Function }\n * @return {String}         Sanitized filename\n */\n\nvar truncate = require(\"truncate-utf8-bytes\");\n\nvar illegalRe = /[\\/\\?<>\\\\:\\*\\|\"]/g;\nvar controlRe = /[\\x00-\\x1f\\x80-\\x9f]/g;\nvar reservedRe = /^\\.+$/;\nvar windowsReservedRe = /^(con|prn|aux|nul|com[0-9\\u00b9\\u00b2\\u00b3]|lpt[0-9\\u00b9\\u00b2\\u00b3])(\\..*)?$/i;\n\n/**\n * Strip trailing spaces and dots, which are not allowed on some Windows file\n * systems. Does not use a regex to avoid a quadratic ReDoS vulnerability\n * (CWE-1333).\n */\nfunction replaceTrailingDotsAndSpaces(str, replacement) {\n  var end = str.length;\n  while (end > 0 && (str[end - 1] === '.' || str[end - 1] === ' ')) end--;\n  if (end === str.length) return str;\n  if (typeof replacement === 'function') {\n    return str.slice(0, end) + replacement(str.slice(end), end, str);\n  }\n  return str.slice(0, end) + replacement;\n}\n\nfunction sanitize(input, replacement) {\n  if (typeof input !== 'string') {\n    throw new Error('Input must be string');\n  }\n  var sanitized = input\n    .replace(illegalRe, replacement)\n    .replace(controlRe, replacement)\n    .replace(reservedRe, replacement)\n    .replace(windowsReservedRe, replacement);\n  sanitized = replaceTrailingDotsAndSpaces(sanitized, replacement);\n  sanitized = truncate(sanitized, 255);\n  // Stripping and truncating can expose a trailing dot/space or reserved name\n  return replaceTrailingDotsAndSpaces(sanitized, '').replace(windowsReservedRe, '');\n}\n\nmodule.exports = function (input, options) {\n  var replacement = (options && options.replacement) || '';\n  var output = sanitize(input, replacement);\n  if (replacement === '') {\n    return output;\n  }\n  return sanitize(output, '');\n};\n","/**\n * Decode the given string with the given decoder. A malformed escape sequence, e.g. the `%` sign in\n * a `50%off.jpg` file name, would make the decoder throw, so in that case only the valid escape\n * sequences are decoded and anything else is left as is.\n * @param {string} str Encoded string.\n * @param {(str: string) => string} decoder `decodeURI` or `decodeURIComponent`.\n * @returns {string} Decoded string.\n */\nconst decodeSafely = (str, decoder) => {\n  try {\n    return decoder(str);\n  } catch {\n    return str.replace(/(?:%[\\da-f]{2})+/gi, (sequence) => {\n      try {\n        return decoder(sequence);\n      } catch {\n        return sequence;\n      }\n    });\n  }\n};\n\n/**\n * Decode the given URI or path like `decodeURI()`, but without throwing on a malformed escape\n * sequence, e.g. the `%` sign in `/images/50%off.jpg`, which is left as is.\n * @param {string} uri Encoded URI or path.\n * @returns {string} Decoded URI or path.\n */\nexport const decodeURISafely = (uri) => decodeSafely(uri, decodeURI);\n\n/**\n * Decode the given URI component like `decodeURIComponent()`, but without throwing on a malformed\n * escape sequence, e.g. the `%` sign in `50%off.jpg`, which is left as is.\n * @param {string} component Encoded URI component.\n * @returns {string} Decoded URI component.\n */\nexport const decodeURIComponentSafely = (component) => decodeSafely(component, decodeURIComponent);\n\n/**\n * Encode the given URL for an `href` or `src` attribute. Unlike `encodeURI()`, an escape sequence\n * already in the URL is kept as is rather than encoded again, so that `https://example.com/caf%C3%A9`\n * doesn’t become `https://example.com/caf%25C3%25A9`. A URL that can’t be parsed is decoded first,\n * then encoded with `encodeURI()`.\n * @param {string} url URL, e.g. `https://example.com/café` or `mailto:alice@example.com`.\n * @returns {string} Encoded URL.\n */\nexport const encodeURLSafely = (url) => {\n  try {\n    return new URL(url).href;\n  } catch {\n    // A lone surrogate would make `encodeURI()` throw\n    return encodeURI(decodeURISafely(url).toWellFormed());\n  }\n};\n\n/**\n * Percent-encode a string as RFC 3986 requires. Unlike `encodeURIComponent()`, the characters\n * `!'()*` are encoded as well: they are reserved as sub-delimiters, and they affect the Markdown\n * syntax of images and links, while Signature Version 4 of AWS requires every character other\n * than the unreserved ones to be encoded.\n * @param {string} str String to encode.\n * @returns {string} Encoded string.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent#encoding_for_rfc3986\n * @see https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html\n */\nexport const encodeRFC3986 = (str) =>\n  encodeURIComponent(str).replace(\n    /[!'()*]/g,\n    (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,\n  );\n\n/**\n * Percent-encode a slash-separated value, such as a file path, an object key, a route path or a Git\n * branch name, segment by segment, keeping the slashes. `encodeURI()` would leave `#` and `?` as\n * they are, which end a URL path, so a value containing them would be cut short — a branch name\n * like `cms/posts/c#` would become `cms/posts/c`, for example — and a `%` sign in a file name\n * wouldn’t be decoded back to the same name.\n * @param {string} path Value to encode, e.g. `/assets/images/50%off.jpg`.\n * @param {(segment: string) => string} [encodeSegment] Function to encode each segment. Default:\n * `encodeURIComponent`.\n * @returns {string} Encoded value, e.g. `/assets/images/50%25off.jpg`.\n */\nexport const encodePathSegments = (path, encodeSegment = encodeURIComponent) =>\n  path\n    .split('/')\n    .map((segment) => encodeSegment(segment))\n    .join('/');\n\n/**\n * Remove any trailing slashes from the given URL or path, so another segment can be appended after\n * a single slash. Unlike `stripSlashes()` from `@sveltia/utils/string`, a leading slash is kept.\n * @param {string} url URL or path, e.g. `https://example.com/media/`.\n * @returns {string} Trimmed URL or path, e.g. `https://example.com/media`.\n */\nexport const trimTrailingSlashes = (url) => url.replace(/\\/+$/, '');\n","import { getHash } from '@sveltia/utils/crypto';\nimport { getPathInfo } from '@sveltia/utils/file';\nimport { escapeRegExp, stripSlashes } from '@sveltia/utils/string';\nimport sanitize from 'sanitize-filename';\n\nimport { getOrCreateAsync } from '$lib/services/utils/cache';\nimport { encodePathSegments, encodeRFC3986 } from '$lib/services/utils/url';\n\n/**\n * Create a regular expression that matches the given path.\n * @param {string} path Path.\n * @param {(segment: string) => string} replacer Function to replace each path segment.\n * @returns {RegExp} Regular expression.\n */\nexport const createPathRegEx = (path, replacer) =>\n  new RegExp(`^${path.split('/').map(replacer).join('\\\\/')}(?=\\\\/|$)`);\n\n/**\n * Encode the given (partial) file path or file name segment by segment, keeping the slashes. Some\n * more characters than `encodeURIComponent()` does are encoded, including `!`, `(` and `)`, which\n * affect the Markdown syntax like images and links. The `@` prefix is an exception; it shouldn’t be\n * encoded.\n * @param {string} path Original path.\n * @returns {string} Encoded path.\n */\nexport const encodeFilePath = (path) => {\n  const hasAtPrefix = path.startsWith('@');\n\n  if (hasAtPrefix) {\n    path = path.slice(1);\n  }\n\n  path = encodePathSegments(path, encodeRFC3986);\n\n  if (hasAtPrefix) {\n    return `@${path}`;\n  }\n\n  return path;\n};\n\n/**\n * Fold a file or folder name for a comparison that ignores case and the Unicode normalization form,\n * the way a case-insensitive file system like macOS’s or Windows’s does: `Photo.jpg` and\n * `photo.jpg` clash there, and so do names spelled in NFC and NFD, e.g. a name typed in the browser\n * and the same name read from a macOS disk.\n * @param {string} name File or folder name.\n * @returns {string} Folded name.\n */\nexport const foldFileName = (name) => name.normalize().toLowerCase();\n\n/**\n * Fold a file or folder path like {@link foldFileName} does a name, after stripping the leading and\n * trailing slashes, to tell whether two paths can refer to the same file.\n * @param {string} path File or folder path.\n * @returns {string} Folded path.\n */\nexport const foldPath = (path) => foldFileName(stripSlashes(path));\n\n/**\n * Remove a leading `./` from the given folder path, or turn `.` into an empty string, as both\n * mean the folder the path is relative to: `./images` becomes `images`, while `../images` and\n * `.images` are left alone.\n * @param {string} path Folder path.\n * @returns {string} Path without a leading `./`.\n */\nexport const stripLeadingDotSlash = (path) => path.replace(/^\\.(?:\\/|$)/, '');\n\n/**\n * Normalize the given folder option by removing the leading and trailing slashes, then a leading\n * `./`, so an empty string, `/`, `.` and `./` all become an empty string, meaning the root folder,\n * and `./static/images/` becomes `static/images`.\n * @param {string} path Folder path.\n * @returns {string} Normalized path.\n */\nexport const normalizeFolderPath = (path) => stripLeadingDotSlash(stripSlashes(path));\n\n/**\n * Check if the given file name or slug is already taken in the other names. If so, rename it by\n * appending a number higher than any variant already used, like `summer-beach-2.jpg`. A name that\n * is free is returned as is, even if numbered variants of it exist.\n * @param {string} name Original name.\n * @param {string[]} otherNames Other names (of files in the same folder).\n * @param {object} [options] Options.\n * @param {boolean} [options.hasExtension] Whether the name ends with a file extension, which the\n * number goes before. Pass `false` for a slug, whose dot is part of the name, so `release-2.0` is\n * renamed `release-2.0-1` rather than `release-2-1.0`.\n * @param {Set<string>} [options.foldedNames] `otherNames` folded with {@link foldFileName}, for a\n * caller naming many files against the same list, which would otherwise be folded for each file.\n * @returns {string} Determined name.\n */\nexport const renameIfNeeded = (name, otherNames, { hasExtension = true, foldedNames } = {}) => {\n  const foldedName = foldFileName(name);\n\n  // Case-insensitive and Unicode-normalized, since `Photo.jpg` and `photo.jpg` clash on a\n  // case-insensitive file system like macOS’s or Windows’s, and a name read from disk may be\n  // spelled in another normalization form than one typed in the browser\n  const taken = foldedNames\n    ? foldedNames.has(foldedName)\n    : otherNames.some((otherName) => foldFileName(otherName) === foldedName);\n\n  if (!taken) {\n    return name;\n  }\n\n  const { filename: slug, extension } = hasExtension\n    ? getPathInfo(name)\n    : { filename: name, extension: undefined };\n\n  const suffix = extension ? `\\\\.${extension.normalize()}` : '';\n  const regex = new RegExp(`^${escapeRegExp(slug.normalize())}-(?<num>\\\\d+)${suffix}$`, 'i');\n  let highest = 0;\n\n  // Only the highest number already taken matters, so the names are scanned once rather than\n  // sorted. The caller’s array is left alone: it’s typically every name in the folder, reused for\n  // each of the files being added. The numbered variants are matched in either normalization form\n  // as well\n  otherNames.forEach((otherName) => {\n    const match = otherName.normalize().match(regex);\n\n    if (match) {\n      highest = Math.max(highest, Number(/** @type {Record<string, string>} */ (match.groups).num));\n    }\n  });\n\n  return `${slug}-${highest + 1}${extension ? `.${extension}` : ''}`;\n};\n\n/**\n * Regular expression matching the start of a file or folder name that Windows reserves for a\n * device, like `con` or `aux.png`: the reserved word followed by nothing or a dot, as Windows only\n * looks at the part before the first dot. The list is the one `sanitize-filename` uses, including\n * the superscript digits.\n */\nconst WINDOWS_RESERVED_NAME_REGEX =\n  /^(?:con|prn|aux|nul|com[0-9\\u00B9\\u00B2\\u00B3]|lpt[0-9\\u00B9\\u00B2\\u00B3])(?=\\.|$)/i;\n\n/**\n * Rename a file or folder name that Windows reserves for a device, like `aux.png`, by numbering it\n * the way a duplicate name is numbered, as `aux-1.png`, so it can be checked out on Windows while\n * keeping its extension. Any other name is returned as is.\n * @param {string} name Name.\n * @returns {string} Name that isn’t reserved.\n */\nexport const renameReservedFileName = (name) => name.replace(WINDOWS_RESERVED_NAME_REGEX, '$&-1');\n\n/**\n * Sanitize a file or folder name: normalize it to NFC (composed characters), replace every kind of\n * whitespace — non-breaking spaces, tabs, newlines and so on — with a regular space, collapsing\n * consecutive ones, then drop the characters a file system won’t take. A name Windows reserves for\n * a device is renamed with {@link renameReservedFileName}.\n * @param {string} name Name.\n * @returns {string} Sanitized name. An empty string if nothing usable is left.\n */\nexport const sanitizeFileName = (name) => {\n  const normalizedName = name.normalize().replace(/[\\s\\u00A0\\u202F]+/g, ' ');\n\n  // `sanitize-filename` reduces a reserved name to an empty string, extension included, so\n  // `aux.png` would leave nothing to name the file with. When nothing is left, sanitize the name\n  // again with a character in front, which keeps the package from seeing a reserved name: without\n  // that character, what comes back is the reserved name, if it is one, with the unsafe characters\n  // dropped, which can be what makes a name reserved, as in `aux?.png`. It’s then renamed, and\n  // sanitized once more to stay within the length limit\n  return (\n    sanitize(normalizedName) ||\n    sanitize(renameReservedFileName(sanitize(`_${normalizedName}`).slice(1)))\n  );\n};\n\n/**\n * Groups of file extensions that refer to the same file format, meaning that replacing one with\n * another doesn’t change how the file is handled.\n * @type {string[][]}\n */\nconst EQUIVALENT_FILE_EXTENSIONS = [\n  ['jpg', 'jpeg', 'jpe', 'jfif'],\n  ['tif', 'tiff'],\n  ['htm', 'html'],\n  ['yml', 'yaml'],\n  ['md', 'markdown'],\n  ['mpg', 'mpeg'],\n  ['mid', 'midi'],\n  ['aif', 'aiff'],\n];\n\n/**\n * Check if the given two file extensions refer to the same file format. The comparison is\n * case-insensitive, so `PNG` and `png` are equivalent. Well-known aliases, such as `jpeg` and\n * `jpg`, are also considered equivalent.\n * @param {string} [a] File extension without a leading dot.\n * @param {string} [b] File extension without a leading dot.\n * @returns {boolean} Result. `true` if both extensions are omitted.\n */\nexport const isEquivalentFileExtension = (a, b) => {\n  const _a = a?.toLowerCase() ?? '';\n  const _b = b?.toLowerCase() ?? '';\n\n  if (_a === _b) {\n    return true;\n  }\n\n  return EQUIVALENT_FILE_EXTENSIONS.some((group) => group.includes(_a) && group.includes(_b));\n};\n\n/**\n * Join the given path segments while ignoring any falsy value.\n * @param {(string | null | undefined)[]} segments List of path segments.\n * @returns {string} Path.\n */\nexport const createPath = (segments) => segments.filter(Boolean).join('/');\n\n/**\n * Get the directory part of a file path. Unlike `getPathInfo()`, which has no directory for a file\n * at the root, this is always a string, so a root file’s directory compares equal to the root path.\n * @param {string} path File path.\n * @returns {string} Directory path, which is an empty string for a file at the root.\n */\nexport const getDirName = (path) => getPathInfo(path).dirname ?? '';\n\n/**\n * Get the last segment of a path, e.g. the file name of a file path. Unlike `getPathInfo()`, which\n * ignores trailing slashes, this is an empty string for a path ending with a slash.\n * @param {string} path Path.\n * @returns {string} Last path segment, or the path itself if it has no slash.\n */\nexport const getBaseName = (path) => path.slice(path.lastIndexOf('/') + 1);\n\n/**\n * Remove the given directory from the start of a path, if the path sits below it.\n * @param {string} path Path, e.g. `images/photo.jpg`.\n * @param {string | undefined} dir Directory path, e.g. `images`. An empty string or `undefined`\n * leaves the path as is.\n * @returns {string} Path relative to the directory, e.g. `photo.jpg`, or the original path if it\n * doesn’t sit below the directory.\n */\nexport const stripPathPrefix = (path, dir) =>\n  dir && path.startsWith(`${dir}/`) ? path.slice(dir.length + 1) : path;\n\n/**\n * Sanitize a path by removing potentially dangerous path traversal segments (`.` and `..`). This\n * prevents path traversal attacks when paths are constructed from user input.\n * @param {string} path Path to sanitize, e.g. `../../../secret` or `images/../config`.\n * @returns {string} Sanitized path with `.` and `..` segments removed, e.g. `secret` or\n * `images/config`.\n */\nexport const sanitizePath = (path) =>\n  path\n    .split('/')\n    .filter((segment) => segment !== '.' && segment !== '..')\n    .join('/');\n\n/**\n * Resolve the given file path. This processes only dot(s) in the middle of the path; leading dots\n * like `../../foo/image.jpg` will be untouched. A `..` that goes up past the named segments before\n * it is kept as well, so the path still points outside the starting folder: `a/../../b` resolves to\n * `../b`, and `../a/../../b` to `../../b`. Empty segments are dropped.\n * @param {string} path Unresolved path, e.g. `foo/bar/baz/../../image.jpg`.\n * @returns {string} Resolved path, e.g. `foo/image.jpg`.\n */\nexport const resolvePath = (path) => {\n  /** @type {string[]} */\n  const segments = [];\n  let nameFound = false;\n\n  path.split('/').forEach((segment) => {\n    if (!segment) {\n      return;\n    }\n\n    if (!nameFound || (segment !== '.' && segment !== '..')) {\n      nameFound ||= segment !== '.' && segment !== '..';\n      segments.push(segment);\n\n      return;\n    }\n\n    if (segment === '..') {\n      const last = segments.at(-1);\n\n      // Only a named segment can be cancelled out; a leading dot stays, and the `..` with it\n      if (last !== undefined && last !== '.' && last !== '..') {\n        segments.pop();\n      } else {\n        segments.push(segment);\n      }\n    }\n  });\n\n  return segments.join('/');\n};\n\n/**\n * Get the Blob object from the given file or blob input. If the input is a string, it is treated as\n * the file content and converted to a Blob with `text/plain` MIME type.\n * @param {File | Blob | string} input File or Blob object, or a string representing the file\n * content.\n * @returns {Blob} Blob object representing the file.\n */\nexport const getBlob = (input) =>\n  typeof input === 'string' ? new Blob([input], { type: 'text/plain' }) : input;\n\n/**\n * Get the size of the given file or blob in bytes. A string is measured as UTF-8, the encoding a\n * `Blob` created from it would use.\n * @param {File | Blob | string} input File or Blob object, or a string representing the file\n * content.\n * @returns {number} Size in bytes.\n */\nexport const getByteSize = (input) =>\n  typeof input === 'string' ? new TextEncoder().encode(input).length : input.size;\n\n/**\n * Compute the Git object ID (SHA-1 hash) of the given blob.\n * @param {Blob} blob File or Blob object.\n * @returns {Promise<string>} Git object ID (SHA-1 hash) of the blob.\n * @see https://stackoverflow.com/a/68806436\n * @see https://github.com/Richienb/git-hash-object/blob/master/index.js\n */\nconst computeGitHash = async (blob) => {\n  const buffer = await blob.arrayBuffer();\n\n  return getHash(new Blob([`blob ${buffer.byteLength}\\0`, buffer]));\n};\n\n/**\n * Git object IDs of the blobs hashed so far. A `File` picked by the user is hashed for every\n * duplicate check, listing and save it takes part in, and each hash reads the whole file again, so\n * a batch of uploads would otherwise read every file once per file in the batch. That many reads\n * in flight at once make Chrome fail them with `NotReadableError`. A blob’s content never changes,\n * so the promise is kept for the blob’s lifetime, and concurrent callers share the one read.\n * @type {WeakMap<Blob, Promise<string>>}\n */\nconst gitHashCache = new WeakMap();\n\n/**\n * Get the Git object ID (SHA-1 hash) of the given file or blob.\n * @param {File | Blob | string} input File or Blob object, or a string representing the file\n * content.\n * @returns {Promise<string>} Git object ID (SHA-1 hash) of the file.\n */\nexport const getGitHash = (input) => {\n  if (typeof input === 'string') {\n    return computeGitHash(getBlob(input));\n  }\n\n  // A failure isn’t remembered, leaving room for a retry, e.g. once the file is readable again\n  return getOrCreateAsync(gitHashCache, input, () => computeGitHash(input));\n};\n\n/**\n * Read a blob into a new file of the given name, with its bytes read up front. A blob backed by the\n * file system, like an asset in a local repository, points at a file that may be moved or deleted\n * before the new file is read, e.g. to be written elsewhere or hashed, and can’t be read then.\n * @param {Blob} blob Blob.\n * @param {string} name File name.\n * @returns {Promise<File>} File.\n */\nexport const readBlobAsFile = async (blob, name) =>\n  new File([await blob.arrayBuffer()], name, { type: blob.type });\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport {\n  hasLocalePlaceholder,\n  stripLocaleFolderPath,\n} from '$lib/services/contents/i18n/placeholder';\nimport { getDirName, stripPathPrefix } from '$lib/services/utils/file';\n\n/**\n * @import {\n * Entry,\n * FileConfig,\n * InternalLocaleCode,\n * LocalizedEntry,\n * UnpublishedEntry,\n * } from '$lib/types/private';\n */\n\n/**\n * Get the locale to show an entry in when no locale is asked for: the default locale, or the first\n * locale the entry has if it doesn’t have the default one. A multi-file i18n entry can be missing\n * its default locale file, e.g. when only `hello.fr.md` exists.\n * @param {Record<InternalLocaleCode, any>} locales Locales of the entry, keyed by locale code.\n * @param {InternalLocaleCode} [defaultLocale] Default locale of the entry’s collection. Without it,\n * the first locale the entry has is used.\n * @returns {InternalLocaleCode | undefined} Locale, or `undefined` if there are no locales.\n */\nexport const getEntryDisplayLocale = (locales, defaultLocale) =>\n  defaultLocale && locales[defaultLocale] ? defaultLocale : Object.keys(locales)[0];\n\n/**\n * Get the given locale’s file of an entry. When no locale is given or the entry doesn’t have the\n * locale yet, falls back to the file of the locale the entry is listed in: the default locale’s\n * file if a default locale is given, or else the first file. A multi-file i18n entry can be missing\n * its default locale file, e.g. when only `hello.fr.md` exists, in which case another locale stands\n * in for it. See {@link getEntryDisplayLocale}.\n * @param {Entry | UnpublishedEntry} entry Entry.\n * @param {object} [options] Options.\n * @param {InternalLocaleCode} [options.locale] Locale.\n * @param {InternalLocaleCode} [options.defaultLocale] Default locale of the entry’s collection.\n * @returns {LocalizedEntry | undefined} Localized entry, including the file path and content, or\n * `undefined` if the entry has no files at all.\n */\nexport const getEntryLocaleFile = (entry, { locale, defaultLocale } = {}) =>\n  (locale ? entry.locales[locale] : undefined) ??\n  entry.locales[\n    /** @type {InternalLocaleCode} */ (getEntryDisplayLocale(entry.locales, defaultLocale))\n  ];\n\n/**\n * List the distinct paths of the files an entry is made of. A single-file i18n entry lists the same\n * path under every locale.\n * @param {Entry | UnpublishedEntry} entry Entry.\n * @param {object} [options] Options.\n * @param {boolean} [options.includePrevious] Whether to also include the paths an unpublished entry\n * occupied before its pull request renamed it, which is where the published version still lives.\n * @returns {string[]} Paths.\n */\nexport const getEntryPaths = (entry, { includePrevious = false } = {}) => [\n  ...new Set([\n    ...Object.values(entry.locales).map(({ path }) => path),\n    ...((includePrevious && /** @type {UnpublishedEntry} */ (entry).workflow?.previousPaths) || []),\n  ]),\n];\n\n/**\n * Get the folder an entry file is stored in, relative to the collection folder, which is what the\n * `{{dirname}}` template tag stands for. The locale folder added by the `multiple_folders` and\n * `multiple_root_folders` i18n structures, or by the `{{locale}}` placeholder in the `folder`\n * option, isn’t part of it, so the value is the same for every locale of an entry. The collection’s\n * entry path matcher knows where the locale folder goes, and whether the default locale is omitted\n * from the path, so the folder is taken from the sub path it captures. A path the matcher doesn’t\n * cover, like a file collection’s, falls back to removing the base path from the start.\n * @param {string} entryPath Entry file path, e.g. `content/posts/en/2024/hello.md`.\n * @param {Pick<FileConfig, 'basePath' | 'fullPathRegEx'>} [fileConfig] Entry collection’s file\n * configuration: the normalized `folder` option and the entry path matcher.\n * @returns {string} Folder path, e.g. `2024`, or an empty string if the entry is right under the\n * collection folder.\n */\nexport const getEntryDirName = (entryPath, { basePath, fullPathRegEx } = {}) => {\n  const subPath = fullPathRegEx ? entryPath.match(fullPathRegEx)?.groups?.subPath : undefined;\n\n  if (subPath !== undefined) {\n    return getDirName(subPath);\n  }\n\n  const _basePath = stripSlashes(basePath ?? '');\n\n  // The placeholder stands for any locale folder, or none if the default locale is omitted\n  return getDirName(\n    hasLocalePlaceholder(_basePath)\n      ? stripLocaleFolderPath(entryPath, _basePath)\n      : stripPathPrefix(entryPath, _basePath),\n  );\n};\n","import { getPathInfo } from '@sveltia/utils/file';\n\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getSharedEntryFileName } from '$lib/services/contents/collection/nested';\nimport { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\nimport { getBaseName, getDirName } from '$lib/services/utils/file';\n\n/**\n * @import {\n * Entry,\n * InternalCollection,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * LocalizedEntry,\n * } from '$lib/types/private';\n */\n\n/**\n * Regex to extract the folder path from an entry file path. For example, it extracts `blog/post`\n * from `blog/post.md` or `blog/post/index.md`.\n * @type {RegExp}\n */\nconst FOLDER_PATH_REGEX = /(?<path>.+?)(?:\\/[^/]+)?$/;\n\n/**\n * Check whether an entry file is the index file that every entry in a collection with nested\n * entries is stored as, which makes the folder holding it the entry’s own.\n * @param {string} filePath Entry file path without its extension.\n * @param {string | undefined} indexFileName Shared index file name, if the collection has one.\n * @returns {boolean} Result.\n */\nconst isSharedIndexFile = (filePath, indexFileName) => {\n  if (!indexFileName) {\n    return false;\n  }\n\n  const fileName = getBaseName(filePath);\n\n  // The `multiple_files` i18n structure appends the locale to the file name, e.g. `_index.en`\n  return fileName === indexFileName || fileName.startsWith(`${indexFileName}.`);\n};\n\n/*\n * The rules here decide where an entry’s relative assets are stored, so the code that saves them\n * and the code that finds them for a stored field value have to share them.\n */\n\n/**\n * Get the path of the folder an entry occupies, which holds the entry’s relative assets along with\n * anything else stored below it. Only some file structures give an entry a folder of its own; in\n * the others, an entry is a file sharing a folder with the rest of the collection, so its relative\n * assets are shared as well.\n * @param {InternalCollection} collection Collection the entry belongs to.\n * @param {string} entryFilePath Entry file path, e.g. `content/blog/hello-world/index.md`.\n * @returns {string | undefined} Folder path, e.g. `content/blog/hello-world`. `undefined` if the\n * entry has no folder of its own.\n * @example\n * // A `path` option ending in a fixed file name gives the entry a folder\n * getOwnedEntryFolderPath(collection, 'content/blog/hello-world/index.md') // `{{slug}}/index`\n * // => 'content/blog/hello-world'\n * @example\n * // Every entry in a collection with nested entries is an index file, with or without a `path`\n * // option, e.g. `index_file: _index`\n * getOwnedEntryFolderPath(collection, 'content/pages/about/_index.md')\n * // => 'content/pages/about'\n * @example\n * // The slug is the last segment here, so the entry file sits next to the folder named after it\n * // with a `{{year}}/{{month}}/{{slug}}` path option\n * getOwnedEntryFolderPath(collection, 'content/blog/2025/06/hello-world.md')\n * // => 'content/blog/2025/06/hello-world'\n * @example\n * // A plain file collection shares one folder, so there’s nothing the entry owns\n * getOwnedEntryFolderPath(collection, 'content/blog/hello-world.md') // no `path` option\n * // => undefined\n */\nexport const getOwnedEntryFolderPath = (collection, entryFilePath) => {\n  if (collection._type !== 'entry') {\n    return undefined;\n  }\n\n  const { subPath } = /** @type {InternalEntryCollection} */ (collection)._file;\n  // Remove the file extension, which is always present\n  const filePath = entryFilePath.substring(0, entryFilePath.lastIndexOf('.'));\n  const lastSubPathSegment = subPath?.includes('/') ? getBaseName(subPath) : undefined;\n\n  // The entry file has a fixed name within the folder holding it, either because the `path` option\n  // ends in one, or because the collection stores every entry as an index file. Either way the\n  // folder is the entry, so strip the file name off\n  if (\n    (!!lastSubPathSegment && !lastSubPathSegment.includes('{{')) ||\n    isSharedIndexFile(filePath, getSharedEntryFileName(collection))\n  ) {\n    return /** @type {string} */ (filePath.match(FOLDER_PATH_REGEX)?.groups?.path);\n  }\n\n  // The `path` option puts the entry in a folder of its own, such as `{{year}}/{{month}}/{{slug}}`,\n  // and the entry file is named after the slug, so a folder of the same name sits next to it. A\n  // locale folder doesn’t count: it holds every entry of that locale, not this one\n  if (subPath?.includes('/')) {\n    return filePath;\n  }\n\n  return undefined;\n};\n\n/**\n * Get the folder that holds an entry’s relative assets: the folder the entry occupies if it has one\n * of its own, and otherwise the folder its file is stored in, which it shares with the rest of the\n * collection. With a `multiple_folders` i18n structure that shared folder is the locale’s own, so\n * the assets sit beside the entry either way.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {string} args.entryFilePath Entry file path.\n * @param {string} args.internalPath Internal path from folder config.\n * @returns {string} Folder path.\n */\nexport const getEntryAssetFolderPath = ({ collection, entryFilePath, internalPath }) =>\n  getOwnedEntryFolderPath(collection, entryFilePath) ??\n  // A file collection has no folder of its own to fall back on\n  (collection._type === 'entry'\n    ? (getPathInfo(entryFilePath).dirname ?? internalPath)\n    : internalPath);\n\n/**\n * Get the folder that holds the relative assets of an existing entry, like\n * {@link getEntryAssetFolderPath} does when they are saved, so an asset is listed, referenced and\n * found in the same place it’s stored.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry.\n * @param {InternalLocaleCode} [args.locale] Locale whose entry file is used. With the\n * `multiple_folders` or `multiple_root_folders` i18n structure, each locale’s file has a folder of\n * its own. Default: the entry’s first locale.\n * @param {string} [args.collectionName] Name of the collection the asset folder belongs to. Without\n * it, or for a collection that can’t be found, the folder of the entry file is used.\n * @returns {string} Folder path, or an empty string for an entry file at the repository root.\n */\nexport const getExistingEntryAssetFolderPath = ({ entry, locale, collectionName }) => {\n  const entryFilePath = /** @type {LocalizedEntry} */ (getEntryLocaleFile(entry, { locale })).path;\n  const entryFolderPath = getDirName(entryFilePath);\n  const collection = collectionName ? getCollection(collectionName) : undefined;\n\n  return collection\n    ? getEntryAssetFolderPath({ collection, entryFilePath, internalPath: entryFolderPath })\n    : entryFolderPath;\n};\n","import { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Asset, AssetMoveRequest, UploadingAssets } from '$lib/types/private';\n */\n\n/**\n * List of all assets.\n * @type {{ current: Asset[] }}\n */\nexport const allAssets = createRawState([]);\n\n/**\n * List of the assets that exist on the configured branch, which is {@link allAssets} minus the ones\n * committed to an Editorial Workflow branch. The Asset Library and the asset search use this,\n * because most asset actions — renaming, moving, deleting — can’t operate on a file that only lives\n * on a pull request branch. Entry previews still resolve against {@link allAssets}, so an image\n * attached to an unpublished entry is displayed where it’s used.\n */\nexport const publishedAssets = createDerivedState(() =>\n  // Keep the same array reference when there’s nothing to filter out, to avoid needless downstream\n  // recomputation\n  allAssets.current.some(({ workflow }) => workflow)\n    ? allAssets.current.filter(({ workflow }) => !workflow)\n    : allAssets.current,\n);\n\n/**\n * Selected assets.\n * @type {{ current: Asset[] }}\n */\nexport const selectedAssets = createRawState([]);\n\n/**\n * Set of selected asset paths, for O(1) membership checks in list items.\n */\nexport const selectedAssetPathSet = createDerivedState(\n  () => new Set(selectedAssets.current.map((asset) => asset.path)),\n);\n\n/**\n * Asset currently focused in the UI.\n * @type {{ current: Asset | undefined }}\n */\nexport const focusedAsset = createRawState();\n\n/**\n * Assets the toolbar actions operate on: the selected assets, or else the focused asset, if any.\n * @type {{ readonly current: Asset[] }}\n */\nexport const selectedOrFocusedAssets = createDerivedState(() => {\n  if (selectedAssets.current.length) {\n    return [...selectedAssets.current];\n  }\n\n  return focusedAsset.current ? [focusedAsset.current] : [];\n});\n\n/**\n * Asset to be displayed in `<AssetDetailsOverlay>`.\n * @type {{ current: Asset | undefined }}\n */\nexport const overlaidAsset = createRawState();\n\n/**\n * Assets currently being uploaded.\n * @type {{ current: UploadingAssets }}\n */\nexport const uploadingAssets = createRawState({ folder: undefined, files: [] });\n\n/**\n * Asset currently being edited.\n * @type {{ current: Asset | undefined }}\n */\nexport const editingAsset = createRawState();\n\n/**\n * Asset currently being renamed.\n * @type {{ current: Asset | undefined }}\n */\nexport const renamingAsset = createRawState();\n\n/**\n * Assets to be moved to another folder with the Move dialog, which is open while this is set.\n * @type {{ current: AssetMoveRequest | undefined }}\n */\nexport const assetMoveRequest = createRawState();\n\n/**\n * Files being dragged from the asset list, repository assets or files on a cloud storage service,\n * which a folder in the sidebar or a subfolder in the list can be dropped on. `undefined` while\n * nothing is dragged. The drag data can’t be read until the drop, so this is what tells a folder\n * whether it can take the drop while it’s dragged over.\n * @type {{ current: AssetMoveRequest | undefined }}\n */\nexport const draggedFiles = createRawState();\n","import { allAssets } from '$lib/services/assets/state';\nimport { memoizeOnSource } from '$lib/services/utils/cache';\n\n/**\n * @import { Asset } from '$lib/types/private';\n */\n\n/**\n * Get a Map from asset path to Asset, used for O(1) path lookups. Rebuilt only when `allAssets` is\n * replaced.\n * @type {() => Map<string, Asset>}\n */\nexport const getAssetPathMap = memoizeOnSource(\n  () => allAssets.current,\n  (_allAssets) => new Map(_allAssets.map((asset) => [asset.path, asset])),\n);\n","/** @type {Intl.DateTimeFormatOptions} */\nconst partOptions = {\n  year: 'numeric',\n  month: '2-digit',\n  day: '2-digit',\n  hour: '2-digit',\n  minute: '2-digit',\n  second: '2-digit',\n  timeZoneName: 'longOffset',\n};\n\n/**\n * Cache of `Intl.DateTimeFormat` instances keyed by time zone. Constructing a formatter is roughly\n * an order of magnitude more expensive than using one, and every option other than `timeZone` is\n * constant here, so instances are safe to share and worth reusing.\n * @type {Map<string, Intl.DateTimeFormat>}\n */\nconst formatterCache = new Map();\n\n/**\n * Get a cached `Intl.DateTimeFormat` for the given time zone.\n * @param {string} [timeZone] Time zone, e.g. `UTC`. Defaults to the runtime’s local zone.\n * @returns {Intl.DateTimeFormat} Formatter.\n */\nconst getFormatter = (timeZone) => {\n  // `undefined` (local zone) needs a distinct key from any named zone.\n  const key = timeZone ?? '';\n  let formatter = formatterCache.get(key);\n\n  if (!formatter) {\n    formatter = new Intl.DateTimeFormat('en-US', { ...partOptions, hourCycle: 'h23', timeZone });\n    formatterCache.set(key, formatter);\n  }\n\n  return formatter;\n};\n\n/**\n * Get an object containing date parts that can be used for the `YYYY-MM-DD` format, especially in\n * the local time zone.\n * @param {object} [options] Options.\n * @param {Date} [options.date] Date to use.\n * @param {string} [options.timeZone] Time zone, e.g. `UTC`.\n * @returns {{ [key: string]: string }} Result like `{ year: '2023', month: '01', day: '23', ... }`.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts\n */\nconst getDateTimeParts = ({ date = new Date(), timeZone = undefined } = {}) =>\n  Object.fromEntries(\n    getFormatter(timeZone)\n      .formatToParts(date)\n      .filter(({ type }) => type in partOptions)\n      .map(({ type, value }) => [type, value]),\n  );\n\nexport { getDateTimeParts };\n","/**\n * Characters that can’t be used in a slug with the default `unicode` encoding: space, control,\n * delimiter, reserved and unwise characters. The zero-width non-joiner (U+200C) and joiner (U+200D)\n * are format characters like the bidi controls, but they are kept: they are part of the spelling of\n * words in Persian and Indic scripts, and join the code points of an emoji sequence, e.g. a family\n * emoji. The pattern uses the `v` flag for the set subtraction, so a global variant has to be\n * created with `gv`, not `gu`. The `&` is written as `\\x26`: TypeScript rejects a bare one in a\n * `v`-flag class, and ESLint flags `\\&` as a useless escape.\n * @see https://stackoverflow.com/q/1547899\n */\nexport const UNSAFE_UNICODE_SLUG_CHARS_REGEX =\n  /[\\p{Z}[\\p{C}--[\\u200C\\u200D]]!\"#$%\\x26'\\(\\)*+,\\/:;<=>?@\\[\\\\\\]^`\\{\\|\\}]/v;\n\n/**\n * Characters that can’t be used in a slug with the `ascii` encoding: anything but ASCII letters,\n * digits, underscores, hyphens and tildes.\n */\nexport const UNSAFE_ASCII_SLUG_CHARS_REGEX = /[^\\w-~]/;\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @template T\n * @typedef {object} LazyModule\n * @property {{ current: boolean }} loaded Whether the module has been loaded. Components that\n * render synchronously can depend on this to know when they can render.\n * @property {() => Promise<T>} load Load the module. Calling this again returns the same promise;\n * a failed load isn’t remembered, so a later call can try again, e.g. once the network is back.\n * @property {() => void} preload Start loading the module in the background, so that it’s ready by\n * the time a component needs it. A failure is left for the eventual `load` call to report, where it\n * can be handled, rather than surfacing as an unhandled rejection.\n * @property {() => T} get Get the loaded module. The caller is responsible for awaiting `load`\n * first. Throws if the module hasn’t been loaded yet.\n * @property {() => void} reset Forget the loaded module. Used in tests.\n */\n\n/**\n * Create a loader for a library that’s kept out of the main bundle and fetched on demand.\n * @template T\n * @param {object} args Arguments.\n * @param {() => Promise<T>} args.loader Function fetching the module.\n * @param {string} args.notLoadedMessage Error message thrown by `get` before the module is loaded.\n * @returns {LazyModule<T>} Loader.\n */\nexport const createLazyModule = ({ loader, notLoadedMessage }) => {\n  /** @type {T | undefined} */\n  let module;\n  /** @type {Promise<T> | undefined} */\n  let loadPromise;\n  const loaded = createRawState(false);\n\n  /**\n   * Load the module.\n   * @returns {Promise<T>} The module.\n   */\n  const load = async () => {\n    loadPromise ??= (async () => {\n      /** @type {T} */\n      let result;\n\n      try {\n        result = await loader();\n      } catch (error) {\n        loadPromise = undefined;\n        throw error;\n      }\n\n      module = result;\n      loaded.current = true;\n\n      return result;\n    })();\n\n    return loadPromise;\n  };\n\n  /**\n   * Start loading the module in the background.\n   */\n  const preload = () => {\n    load().catch(() => {\n      // Reported when the library is actually needed\n    });\n  };\n\n  /**\n   * Get the loaded module.\n   * @returns {T} The module.\n   * @throws {Error} If the module hasn’t been loaded yet.\n   */\n  const get = () => {\n    if (!module) {\n      throw new Error(notLoadedMessage);\n    }\n\n    return /** @type {T} */ (module);\n  };\n\n  /**\n   * Forget the loaded module.\n   */\n  const reset = () => {\n    module = undefined;\n    loadPromise = undefined;\n    loaded.current = false;\n  };\n\n  return { loaded, load, preload, get, reset };\n};\n","import { dependencies, UNPKG_BASE_URL, version } from '$lib/services/app';\nimport { BUNDLED_MARKER_ICON_URL, BUNDLED_MODULE_LOADERS } from '$lib/services/app/bundled-modules';\n\n/**\n * URL of the script the CMS was loaded from, captured while it’s running. `document.currentScript`\n * is only set for a classic script, which the IIFE build is; the ES module build has\n * `import.meta.url` instead, which the bundler turns into `undefined` in the IIFE build. Neither is\n * available if the IIFE is given `type=\"module\"`, which the CMS warns against.\n * @type {string | undefined}\n */\nconst scriptURL =\n  (typeof document === 'undefined'\n    ? undefined\n    : /** @type {HTMLScriptElement | null} */ (document.currentScript)?.src) || import.meta.url;\n\n/**\n * Get the UNPKG CDN URL for the given dependency.\n * @param {string} name Dependency name.\n * @returns {string} URL.\n */\nexport const getUnpkgURL = (name) => {\n  const url = `https://unpkg.com/${name}`;\n  const libVersion = /** @type {Record<string, string>} */ (dependencies)[name]?.replace(/^\\D/, '');\n\n  return libVersion ? `${url}@${libVersion}` : url;\n};\n\n/**\n * Load an ES module of a third-party library from UNPKG.\n * @param {string} library Library name.\n * @param {string} path Absolute path of the module file to be loaded without the leading slash.\n * @returns {Promise<any>} Module.\n */\nexport const loadModule = async (library, path) =>\n  // The npm build has no fallback to UNPKG: webpack would take the variable specifier as a request\n  // to bundle every file in the package\n  import.meta.env.NPM_BUILD\n    ? BUNDLED_MODULE_LOADERS[library]()\n    : import(/* @vite-ignore */ `${getUnpkgURL(library)}/${path}`);\n\n/**\n * Get the URL of the Leaflet map marker icon, which is bundled with the npm build as an asset.\n * @returns {Promise<string>} URL.\n */\nexport const getLeafletMarkerIconURL = async () =>\n  BUNDLED_MARKER_ICON_URL ?? `${getUnpkgURL('leaflet')}/dist/images/marker-icon-2x.png`;\n\n/**\n * Hosts of the npm CDNs the CMS is typically loaded from, which serve the latest release when a URL\n * has no version.\n */\nconst NPM_CDN_HOSTS = ['unpkg.com', 'cdn.jsdelivr.net'];\n\n/**\n * Parse the URL of the CMS script if it’s a CDN URL of the package without the exact version, e.g.\n * `https://unpkg.com/@sveltia/cms/dist/sveltia-cms.js` or\n * `https://cdn.jsdelivr.net/npm/@sveltia/cms@0/dist/sveltia-cms.js`. Such a URL serves the latest\n * matching release. A version range or tag counts on any host, as only a CDN would serve one, but a\n * URL without a version only on a known CDN, as a self-hosted copy can be anywhere, e.g. in\n * `node_modules/@sveltia/cms/dist`.\n * @param {string} url Script URL.\n * @returns {{ url: URL, packagePath: string, versionSpec?: string, filePath: string } | undefined}\n * Parsed URL with its parts, or `undefined` if it’s pinned to the running version or not a CDN URL.\n */\nconst parseUnpinnedScriptURL = (url) => {\n  const parsedURL = new URL(url);\n  const match = parsedURL.pathname.match(/^(.*\\/@sveltia\\/cms)(?:@([^/]*))?(\\/.*)$/);\n\n  if (!match) {\n    return undefined;\n  }\n\n  const [, packagePath, versionSpec, filePath] = match;\n\n  if (\n    versionSpec === version ||\n    (versionSpec === undefined && !NPM_CDN_HOSTS.includes(parsedURL.host))\n  ) {\n    return undefined;\n  }\n\n  return { url: parsedURL, packagePath, versionSpec, filePath };\n};\n\n/**\n * Pin the URL of the CMS script to the running version if it’s a CDN URL of the package without the\n * exact version (see {@link parseUnpinnedScriptURL}). Such a URL serves the latest matching\n * release, so a chunk resolved against it could come from a newer release than the script, e.g.\n * one cached in the browser from before the release.\n * @param {string} url Script URL.\n * @returns {string} Pinned URL, or the given one if it’s already pinned or not a CDN URL.\n */\nconst pinScriptURL = (url) => {\n  const parsed = parseUnpinnedScriptURL(url);\n\n  if (!parsed) {\n    return url;\n  }\n\n  const { url: pinnedURL, packagePath, filePath } = parsed;\n\n  // Only replace the path, so that the host stays the same whatever the path looks like\n  pinnedURL.pathname = `${packagePath}@${version}${filePath}`;\n\n  return pinnedURL.href;\n};\n\n/**\n * Get the version the CDN resolves the URL of the CMS script with, if it’s not pinned to the\n * running version (see {@link parseUnpinnedScriptURL}), so a reload may load a newer release.\n * @param {string} [url] Script URL. Defaults to the running script’s URL, if known.\n * @returns {string | undefined} Version range or tag as it appears in the URL, e.g. `^1` (which\n * may be percent-encoded) or `latest`, an empty string for a URL without a version, which serves\n * the latest release, or `undefined` if the URL is pinned, not a CDN URL or unknown, e.g. with the\n * npm package bundled into a site.\n */\nexport const getScriptVersionSpec = (url = scriptURL) => {\n  const parsed = url ? parseUnpinnedScriptURL(url) : undefined;\n\n  return parsed ? (parsed.versionSpec ?? '') : undefined;\n};\n\n/**\n * Get the URLs a chunk of the CMS bundle can be loaded from, in order of preference: next to the\n * script the CMS itself was loaded from — which is where the npm package and the CDNs have it — and\n * failing that, the same release on UNPKG, for a site that only copied the main script. A CDN URL\n * without the exact version is pinned to the running version first, so that the chunk comes from\n * the same release as the script.\n * @param {string} name Chunk name, e.g. `react-dom`.\n * @param {string} [base] URL of the CMS script, to resolve the sibling against. Defaults to the\n * running script’s URL, if known.\n * @returns {string[]} URLs.\n */\nexport const getChunkURLs = (name, base = scriptURL) => {\n  const fileName = `chunks/${name}.js`;\n  const fallback = `${UNPKG_BASE_URL}@${version}/dist/${fileName}`;\n\n  if (!base) {\n    return [fallback];\n  }\n\n  const sibling = new URL(fileName, pinScriptURL(base)).href;\n\n  // Loaded from UNPKG in the first place, the two are the same\n  return sibling === fallback ? [fallback] : [sibling, fallback];\n};\n\n/**\n * Source entry of each chunk, keyed by chunk name: the file name of an entry in `src/lib/chunks`.\n * For the development server, which serves the app as source modules rather than a built bundle,\n * there’s no built chunk next to the script, so the entry is imported through Vite instead; the npm\n * build leaves the entries to the consumer’s bundler likewise. Empty in a CDN build, where this is\n * removed along with the imports, so the chunks stay out of the bundle.\n * @type {Record<string, () => Promise<any>>}\n */\nconst devChunkLoaders =\n  import.meta.env.DEV || import.meta.env.NPM_BUILD\n    ? Object.fromEntries(\n        Object.entries(import.meta.glob(['$lib/chunks/*.js', '!$lib/chunks/constants.js'])).map(\n          ([path, loader]) => [path.replace(/^.*\\/|\\.js$/g, ''), loader],\n        ),\n      )\n    : /* v8 ignore next */ {};\n\n/**\n * Load a chunk of the CMS bundle: a part of the app that’s built separately and only fetched when\n * it’s needed, such as `react-dom` for the Netlify/Decap CMS-compatible API, `qrcode` for the\n * mobile sign-in dialog, `git` for the local backend’s Git commits, `gitlab` and `gitea` for those\n * backends, or `map` for the Map field.\n * @param {string} name Chunk name, e.g. `react-dom`.\n * @returns {Promise<any>} Module.\n * @throws {Error} If the chunk can’t be loaded from any location.\n */\nexport const loadChunk = async (name) => {\n  if (import.meta.env.NPM_BUILD || name in devChunkLoaders) {\n    return devChunkLoaders[name]();\n  }\n\n  /** @type {unknown} */\n  let lastError;\n\n  // eslint-disable-next-line no-restricted-syntax\n  for (const url of getChunkURLs(name)) {\n    try {\n      // eslint-disable-next-line no-await-in-loop\n      return await import(/* @vite-ignore */ url);\n    } catch (error) {\n      lastError = error;\n    }\n  }\n\n  throw new Error(`Failed to load the ${name} chunk.`, { cause: lastError });\n};\n","import { createLazyModule } from '$lib/services/api/lazy-module';\nimport { loadModule } from '$lib/services/app/dependencies';\n\n/**\n * @typedef {(string: string, options?: { locale?: string }) => string} TransliterateFunction\n */\n\n/**\n * Regular expression to match the combining marks a decomposed string has for its accents.\n */\nconst COMBINING_MARKS_REGEX = /\\p{M}/gu;\n\n/**\n * Loader for the transliterate library. Only the `clean_accents` slug option uses it, so it’s kept\n * out of the main bundle and fetched from the CDN.\n * @see https://www.npmjs.com/package/@sindresorhus/transliterate\n */\nconst transliterator = createLazyModule({\n  /**\n   * Fetch the library.\n   * @returns {Promise<TransliterateFunction>} The `transliterate` function.\n   */\n  loader: async () => (await loadModule('@sindresorhus/transliterate', 'index.js')).default,\n  notLoadedMessage: 'The transliterate library is not loaded yet.',\n});\n\n/**\n * Load the transliterate library. It’s loaded with the configuration that enables the\n * `clean_accents` slug option, as slugs are made synchronously. Calling this again does nothing\n * once it has loaded. A failure is logged rather than thrown, and {@link transliterateString} then\n * falls back to stripping accents.\n * @returns {Promise<void>} Promise that resolves once the library has been loaded or failed.\n */\nexport const loadTransliterator = async () => {\n  try {\n    await transliterator.load();\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to load the transliterate library', ex);\n  }\n};\n\n/**\n * Transliterate the given string to ASCII. The library takes a BCP 47 tag and picks the rules for\n * its language, e.g. `tr` for `tr-TR`, and `nb` for `no`, while ignoring a locale it has no rules\n * for. An underscore, as in `pt_BR`, is turned into a hyphen it understands. If the library failed\n * to load, the accents are only stripped from the letters, so `é` becomes `e` but `ß` is kept.\n * @param {string} string String to be transliterated.\n * @param {string} [locale] Locale code, e.g. `de` or `pt_BR`.\n * @returns {string} Transliterated string.\n */\nexport const transliterateString = (string, locale) => {\n  const decomposed = string.normalize('NFD');\n\n  return transliterator.loaded.current\n    ? transliterator.get()(decomposed, { locale: locale?.replaceAll('_', '-') })\n    : decomposed.replaceAll(COMBINING_MARKS_REGEX, '');\n};\n\n/**\n * Forget the loaded library. Used in tests.\n */\nexport const _resetTransliterator = transliterator.reset;\n","import { generateUUID } from '@sveltia/utils/crypto';\nimport { escapeRegExp, truncate } from '@sveltia/utils/string';\n\nimport {\n  UNSAFE_ASCII_SLUG_CHARS_REGEX,\n  UNSAFE_UNICODE_SLUG_CHARS_REGEX,\n} from '$lib/services/common/slug/constants';\nimport { transliterateString } from '$lib/services/common/slug/transliterate';\nimport { cmsConfig } from '$lib/services/config';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { foldFileName } from '$lib/services/utils/file';\n\n/**\n * @import { InternalCmsConfig } from '$lib/types/private';\n */\n\n/**\n * Regular expression to match the dots at the beginning of a slug.\n */\nconst LEADING_DOTS_REGEX = /^\\.+/;\n/**\n * Regular expression to match the dots at the end of a slug.\n */\nconst TRAILING_DOTS_REGEX = /\\.+$/;\n\n/**\n * Global variants of the unsafe character patterns, keyed by the `encoding` option, to replace\n * every unsafe character in a string at once.\n */\nconst UNSAFE_CHARS_REGEXES = {\n  unicode: new RegExp(UNSAFE_UNICODE_SLUG_CHARS_REGEX, 'gv'),\n  ascii: new RegExp(UNSAFE_ASCII_SLUG_CHARS_REGEX, 'g'),\n};\n\n/**\n * Regular expressions to consolidate and trim the replacement characters, keyed by the escaped\n * replacement.\n * @type {Map<string, Record<'consecutivePattern' | 'trimPattern' | 'leadingDotsPattern' |\n * 'trailingDotsPattern', RegExp>>}\n */\nconst slugReplacementRegexCache = new Map();\n\n/**\n * Get the regular expressions to consolidate and trim the given replacement character.\n * @param {string} replacement Non-empty `sanitize_replacement` option value.\n * @returns {Record<'consecutivePattern' | 'trimPattern' | 'leadingDotsPattern' |\n * 'trailingDotsPattern', RegExp>} Regular expressions.\n */\nconst getReplacementRegexes = (replacement) => {\n  const escapedReplacement = escapeRegExp(replacement);\n\n  return getOrCreate(slugReplacementRegexCache, escapedReplacement, () => ({\n    // Group the replacement so that a multi-character one is repeated as a whole\n    consecutivePattern: new RegExp(`(?:${escapedReplacement})+`, 'g'),\n    trimPattern: new RegExp(`^(?:${escapedReplacement})+|(?:${escapedReplacement})+$`, 'g'),\n    leadingDotsPattern: new RegExp(`^(?:\\\\.|${escapedReplacement})+`),\n    trailingDotsPattern: new RegExp(`(?:\\\\.|${escapedReplacement})+$`),\n  }));\n};\n\n/**\n * Get the regular expression that matches what a slug can’t end with: dots, which a Git branch name\n * can’t end with, and replacement characters, unless the `slug.trim` option is turned off, so a\n * slug can still end with a replacement character then.\n * @param {InternalCmsConfig['slug']} [slugOptions] Global slug options.\n * @returns {RegExp} Regular expression.\n */\nconst getTrailingDotsPattern = ({ sanitize_replacement: replacement = '-', trim = true } = {}) =>\n  replacement && trim\n    ? getReplacementRegexes(replacement).trailingDotsPattern\n    : TRAILING_DOTS_REGEX;\n\n/**\n * Remove the dots and replacement characters from the end of a slug, e.g. one cut down to a maximum\n * length, or filled from a template ending with a dot. It follows the global `slug` options, like\n * {@link slugify}: with `slug.trim` turned off, only dots are removed.\n * @param {string} slug Slug.\n * @returns {string} Slug.\n */\nexport const trimSlugEnd = (slug) =>\n  slug.replace(\n    getTrailingDotsPattern(/** @type {InternalCmsConfig} */ (cmsConfig.current)?.slug),\n    '',\n  );\n\n/**\n * Get the time zone the date/time tags of a slug, entry path or file name template are filled in,\n * according to the global `slug.timezone` option: UTC by default, for compatibility with\n * Netlify/Decap CMS, or the user’s local time zone with `local`.\n * @returns {'UTC' | undefined} Time zone to pass to `getDateTimeParts()`, where `undefined` stands\n * for the local time zone.\n */\nexport const getSlugTimeZone = () =>\n  /** @type {InternalCmsConfig} */ (cmsConfig.current)?.slug?.timezone === 'local'\n    ? undefined\n    : 'UTC';\n\n/**\n * Slugify the given string to be used as a filename or URL slug, based on the `slug` configuration.\n * This function can be used for both entry slugs and asset file names.\n * @param {string} string String to be normalized.\n * @param {object} [options] Options.\n * @param {boolean} [options.fallback] Whether to return a fallback value if the slug is empty.\n * Defaults to `true`, which returns a part of a UUID.\n * @param {string} [options.locale] Locale of the entry, as a BCP 47 language tag, passed to the\n * transliterate library when `clean_accents` is enabled. The global `transliterate_locale` option\n * stands in for it where there is none: a site without i18n support, a collection without it\n * (`_default`), a slug shared by every locale (`_`), or an asset file name.\n * @param {number} [options.maxLength] Maximum length of the slug.\n * @returns {string} Slug.\n * @see https://decapcms.org/docs/configuration-options/#slug-type\n * @see https://sveltiacms.app/en/docs/collections/entries/slugs#global-slug-options\n */\nexport const slugify = (\n  string,\n  { fallback = true, locale = undefined, maxLength: maxLengthParam = undefined } = {},\n) => {\n  const {\n    slug: {\n      encoding = 'unicode',\n      clean_accents: cleanAccents = false,\n      transliterate_locale: transliterateLocale = undefined,\n      sanitize_replacement: sanitizeReplacement = '-',\n      maxlength: maxLengthOption = undefined,\n      trim: trimReplacement = true,\n      lowercase = true,\n    } = {},\n  } = /** @type {InternalCmsConfig} */ (cmsConfig.current) ?? {};\n\n  const maxLength = maxLengthParam ?? maxLengthOption;\n  let slug = string;\n\n  if (cleanAccents) {\n    // Remove any accented characters by transliterating them to their ASCII equivalents\n    slug = transliterateString(\n      slug,\n      locale && !locale.startsWith('_') ? locale : transliterateLocale,\n    );\n  }\n\n  // Turn every unsafe character into a space, which is then replaced below\n  slug = slug.replaceAll(UNSAFE_CHARS_REGEXES[encoding === 'ascii' ? 'ascii' : 'unicode'], ' ');\n\n  // Replace all the spaces with replacers (hyphens by default)\n  slug = slug.trim().replaceAll(/\\s+/g, sanitizeReplacement);\n\n  let leadingDotsPattern = LEADING_DOTS_REGEX;\n\n  // Consolidate consecutive replacement characters into a single one and trim them from ends\n  if (sanitizeReplacement) {\n    const cachedSlugRegexes = getReplacementRegexes(sanitizeReplacement);\n\n    slug = slug.replace(cachedSlugRegexes.consecutivePattern, sanitizeReplacement);\n\n    // Trim replacement characters from the beginning and end\n    if (trimReplacement) {\n      slug = slug.replace(cachedSlugRegexes.trimPattern, '');\n      ({ leadingDotsPattern } = cachedSlugRegexes);\n    }\n  }\n\n  const trailingDotsPattern = getTrailingDotsPattern({\n    sanitize_replacement: sanitizeReplacement,\n    trim: trimReplacement,\n  });\n\n  // Remove leading dots, which the `unicode` encoding allows: a slug starting with one, e.g. from a\n  // title like `.NET Tips`, would make a dot file, which is hidden and skipped when the repository\n  // files are listed, so the entry would be lost from sight once saved. When trimming is enabled,\n  // the replacement characters a dot leaves at the beginning go too, as in `. NET` or `.-.NET`\n  slug = slug.replace(leadingDotsPattern, '');\n\n  // Remove trailing dots as well, e.g. from a title like `Hello world.`: a Git branch name can’t\n  // end with one, so the entry couldn’t be saved with Editorial Workflow, and Windows drops it from\n  // a file name, which would no longer match the path in the repository. When trimming is enabled,\n  // the replacement characters a dot leaves at the end go too, as in `Wait .`\n  slug = slug.replace(trailingDotsPattern, '');\n\n  if (!slug && fallback) {\n    slug = generateUUID('short');\n  }\n\n  if (typeof maxLength === 'number' && slug.length > maxLength) {\n    slug = truncate(slug, maxLength, { ellipsis: '' });\n\n    // Trim the dots and replacement characters the cut may leave at the end\n    slug = slug.replace(trailingDotsPattern, '');\n  }\n\n  if (lowercase) {\n    // Not `toLocaleLowerCase()`, which can follow the browser’s locale, e.g. turning `I` into `ı`\n    // without a dot in Turkish, so the same title would get a different slug for another user\n    slug = slug.toLowerCase();\n  }\n\n  return slug;\n};\n\n/**\n * Turn what was typed in the new folder dialog into the name the folder is actually given. The name\n * goes through the same slugification as an entry slug, so a folder created by hand looks like one\n * created by saving an entry into it. The random fallback is turned off: a name made up entirely of\n * characters that can’t be used would otherwise become a random string, which is no one’s idea of a\n * folder name, so nothing is returned and the name is rejected instead.\n * @param {string} name Name as typed.\n * @returns {string} Folder name. An empty string if slugification leaves nothing behind.\n */\nexport const getNewFolderName = (name) => slugify(name.trim(), { fallback: false });\n\n/**\n * Check whether a folder can be given the name typed in: an entry folder, while creating one with\n * the parent folder picker or renaming one with the slug editor, or an asset subfolder, with its\n * own formatting and reserved names.\n * @param {object} args Arguments.\n * @param {string[]} args.takenNames Names already taken in the parent folder.\n * @param {string} args.name Name to check, as typed.\n * @param {(name: string) => string} [args.format] Function turning the trimmed name into the folder\n * name. Default: {@link getNewFolderName}.\n * @param {(folderName: string) => boolean} [args.isReserved] Function telling whether a folder name\n * is reserved.\n * @returns {'empty' | 'invalid' | 'reserved' | 'duplicate' | undefined} What stops the name from\n * being used, or `undefined` if it can be used.\n */\nexport const validateNewFolderName = ({\n  takenNames,\n  name,\n  format = getNewFolderName,\n  isReserved = undefined,\n}) => {\n  const trimmedName = name.trim();\n\n  if (!trimmedName) {\n    return 'empty';\n  }\n\n  const folderName = format(trimmedName);\n\n  // A name has to stay a single folder, a leading dot would hide the folder from the site and from\n  // most file listings, and formatting can leave nothing to name the folder with. The dot is looked\n  // for in what was typed as well: slugification removes it, but a name meant to be hidden is\n  // rejected rather than silently given another one\n  if (\n    !folderName ||\n    trimmedName.includes('/') ||\n    trimmedName.startsWith('.') ||\n    folderName.startsWith('.')\n  ) {\n    return 'invalid';\n  }\n\n  if (isReserved?.(folderName)) {\n    return 'reserved';\n  }\n\n  // A repository is often checked out on a file system that ignores case, where `Docs` and `docs`\n  // would be the same folder\n  const foldedName = foldFileName(folderName);\n\n  return takenNames.some((taken) => foldFileName(taken) === foldedName) ? 'duplicate' : undefined;\n};\n","/**\n * List of legacy HTML named character references that don’t need a trailing semicolon.\n *\n * @type {Array<string>}\n */\nexport const characterEntitiesLegacy = [\n  'AElig',\n  'AMP',\n  'Aacute',\n  'Acirc',\n  'Agrave',\n  'Aring',\n  'Atilde',\n  'Auml',\n  'COPY',\n  'Ccedil',\n  'ETH',\n  'Eacute',\n  'Ecirc',\n  'Egrave',\n  'Euml',\n  'GT',\n  'Iacute',\n  'Icirc',\n  'Igrave',\n  'Iuml',\n  'LT',\n  'Ntilde',\n  'Oacute',\n  'Ocirc',\n  'Ograve',\n  'Oslash',\n  'Otilde',\n  'Ouml',\n  'QUOT',\n  'REG',\n  'THORN',\n  'Uacute',\n  'Ucirc',\n  'Ugrave',\n  'Uuml',\n  'Yacute',\n  'aacute',\n  'acirc',\n  'acute',\n  'aelig',\n  'agrave',\n  'amp',\n  'aring',\n  'atilde',\n  'auml',\n  'brvbar',\n  'ccedil',\n  'cedil',\n  'cent',\n  'copy',\n  'curren',\n  'deg',\n  'divide',\n  'eacute',\n  'ecirc',\n  'egrave',\n  'eth',\n  'euml',\n  'frac12',\n  'frac14',\n  'frac34',\n  'gt',\n  'iacute',\n  'icirc',\n  'iexcl',\n  'igrave',\n  'iquest',\n  'iuml',\n  'laquo',\n  'lt',\n  'macr',\n  'micro',\n  'middot',\n  'nbsp',\n  'not',\n  'ntilde',\n  'oacute',\n  'ocirc',\n  'ograve',\n  'ordf',\n  'ordm',\n  'oslash',\n  'otilde',\n  'ouml',\n  'para',\n  'plusmn',\n  'pound',\n  'quot',\n  'raquo',\n  'reg',\n  'sect',\n  'shy',\n  'sup1',\n  'sup2',\n  'sup3',\n  'szlig',\n  'thorn',\n  'times',\n  'uacute',\n  'ucirc',\n  'ugrave',\n  'uml',\n  'uuml',\n  'yacute',\n  'yen',\n  'yuml'\n]\n","/**\n * Map of invalid numeric character references to their replacements, according to HTML.\n *\n * @type {Record<number, string>}\n */\nexport const characterReferenceInvalid = {\n  0: '�',\n  128: '€',\n  130: '‚',\n  131: 'ƒ',\n  132: '„',\n  133: '…',\n  134: '†',\n  135: '‡',\n  136: 'ˆ',\n  137: '‰',\n  138: 'Š',\n  139: '‹',\n  140: 'Œ',\n  142: 'Ž',\n  145: '‘',\n  146: '’',\n  147: '“',\n  148: '”',\n  149: '•',\n  150: '–',\n  151: '—',\n  152: '˜',\n  153: '™',\n  154: 'š',\n  155: '›',\n  156: 'œ',\n  158: 'ž',\n  159: 'Ÿ'\n}\n","/**\n * Check if the given character code, or the character code at the first\n * character, is decimal.\n *\n * @param {string|number} character\n * @returns {boolean} Whether `character` is a decimal\n */\nexport function isDecimal(character) {\n  const code =\n    typeof character === 'string' ? character.charCodeAt(0) : character\n\n  return code >= 48 && code <= 57 /* 0-9 */\n}\n","/**\n * Check if the given character code, or the character code at the first\n * character, is hexadecimal.\n *\n * @param {string|number} character\n * @returns {boolean} Whether `character` is hexadecimal\n */\nexport function isHexadecimal(character) {\n  const code =\n    typeof character === 'string' ? character.charCodeAt(0) : character\n\n  return (\n    (code >= 97 /* a */ && code <= 102) /* z */ ||\n    (code >= 65 /* A */ && code <= 70) /* Z */ ||\n    (code >= 48 /* A */ && code <= 57) /* Z */\n  )\n}\n","/**\n * Check if the given character code, or the character code at the first\n * character, is alphabetical.\n *\n * @param {string|number} character\n * @returns {boolean} Whether `character` is alphabetical.\n */\nexport function isAlphabetical(character) {\n  const code =\n    typeof character === 'string' ? character.charCodeAt(0) : character\n\n  return (\n    (code >= 97 && code <= 122) /* a-z */ ||\n    (code >= 65 && code <= 90) /* A-Z */\n  )\n}\n","import {isAlphabetical} from 'is-alphabetical'\nimport {isDecimal} from 'is-decimal'\n\n/**\n * Check if the given character code, or the character code at the first\n * character, is alphanumerical.\n *\n * @param {string|number} character\n * @returns {boolean} Whether `character` is alphanumerical.\n */\nexport function isAlphanumerical(character) {\n  return isAlphabetical(character) || isDecimal(character)\n}\n","/// <reference lib=\"dom\" />\n\n/* global document */\n\nconst element = document.createElement('i')\n\n/**\n * @param {string} value\n * @returns {string | false}\n */\nexport function decodeNamedCharacterReference(value) {\n  const characterReference = '&' + value + ';'\n  element.innerHTML = characterReference\n  const character = element.textContent\n\n  // Some named character references do not require the closing semicolon\n  // (`&not`, for instance), which leads to situations where parsing the assumed\n  // named reference of `&notit;` will result in the string `¬it;`.\n  // When we encounter a trailing semicolon after parsing, and the character\n  // reference to decode was not a semicolon (`&semi;`), we can assume that the\n  // matching was not complete.\n  if (\n    character.charCodeAt(character.length - 1) === 59 /* `;` */ &&\n    value !== 'semi'\n  ) {\n    return false\n  }\n\n  // If the decoded string is equal to the input, the character reference was\n  // not valid.\n  return character === characterReference ? false : character\n}\n","/**\n * @import {Point} from 'unist'\n * @import {Options} from '../index.js'\n */\n\nimport {characterEntitiesLegacy} from 'character-entities-legacy'\nimport {characterReferenceInvalid} from 'character-reference-invalid'\nimport {isDecimal} from 'is-decimal'\nimport {isHexadecimal} from 'is-hexadecimal'\nimport {isAlphanumerical} from 'is-alphanumerical'\nimport {decodeNamedCharacterReference} from 'decode-named-character-reference'\n\n// Warning messages.\nconst messages = [\n  '',\n  /* 1: Non terminated (named) */\n  'Named character references must be terminated by a semicolon',\n  /* 2: Non terminated (numeric) */\n  'Numeric character references must be terminated by a semicolon',\n  /* 3: Empty (named) */\n  'Named character references cannot be empty',\n  /* 4: Empty (numeric) */\n  'Numeric character references cannot be empty',\n  /* 5: Unknown (named) */\n  'Named character references must be known',\n  /* 6: Disallowed (numeric) */\n  'Numeric character references cannot be disallowed',\n  /* 7: Prohibited (numeric) */\n  'Numeric character references cannot be outside the permissible Unicode range'\n]\n\n/**\n * Parse HTML character references.\n *\n * @param {string} value\n * @param {Readonly<Options> | null | undefined} [options]\n */\nexport function parseEntities(value, options) {\n  const settings = options || {}\n  const additional =\n    typeof settings.additional === 'string'\n      ? settings.additional.charCodeAt(0)\n      : settings.additional\n  /** @type {Array<string>} */\n  const result = []\n  let index = 0\n  let lines = -1\n  let queue = ''\n  /** @type {Point | undefined} */\n  let point\n  /** @type {Array<number>|undefined} */\n  let indent\n\n  if (settings.position) {\n    if ('start' in settings.position || 'indent' in settings.position) {\n      // @ts-expect-error: points don’t have indent.\n      indent = settings.position.indent\n      // @ts-expect-error: points don’t have indent.\n      point = settings.position.start\n    } else {\n      point = settings.position\n    }\n  }\n\n  let line = (point ? point.line : 0) || 1\n  let column = (point ? point.column : 0) || 1\n\n  // Cache the current point.\n  let previous = now()\n  /** @type {number|undefined} */\n  let character\n\n  // Ensure the algorithm walks over the first character (inclusive).\n  index--\n\n  while (++index <= value.length) {\n    // If the previous character was a newline.\n    if (character === 10 /* `\\n` */) {\n      column = (indent ? indent[lines] : 0) || 1\n    }\n\n    character = value.charCodeAt(index)\n\n    if (character === 38 /* `&` */) {\n      const following = value.charCodeAt(index + 1)\n\n      // The behavior depends on the identity of the next character.\n      if (\n        following === 9 /* `\\t` */ ||\n        following === 10 /* `\\n` */ ||\n        following === 12 /* `\\f` */ ||\n        following === 32 /* ` ` */ ||\n        following === 38 /* `&` */ ||\n        following === 60 /* `<` */ ||\n        Number.isNaN(following) ||\n        (additional && following === additional)\n      ) {\n        // Not a character reference.\n        // No characters are consumed, and nothing is returned.\n        // This is not an error, either.\n        queue += String.fromCharCode(character)\n        column++\n        continue\n      }\n\n      const start = index + 1\n      let begin = start\n      let end = start\n      /** @type {string} */\n      let type\n\n      if (following === 35 /* `#` */) {\n        // Numerical reference.\n        end = ++begin\n\n        // The behavior further depends on the next character.\n        const following = value.charCodeAt(end)\n\n        if (following === 88 /* `X` */ || following === 120 /* `x` */) {\n          // ASCII hexadecimal digits.\n          type = 'hexadecimal'\n          end = ++begin\n        } else {\n          // ASCII decimal digits.\n          type = 'decimal'\n        }\n      } else {\n        // Named reference.\n        type = 'named'\n      }\n\n      let characterReferenceCharacters = ''\n      let characterReference = ''\n      let characters = ''\n      // Each type of character reference accepts different characters.\n      // This test is used to detect whether a reference has ended (as the semicolon\n      // is not strictly needed).\n      const test =\n        type === 'named'\n          ? isAlphanumerical\n          : type === 'decimal'\n            ? isDecimal\n            : isHexadecimal\n\n      end--\n\n      while (++end <= value.length) {\n        const following = value.charCodeAt(end)\n\n        if (!test(following)) {\n          break\n        }\n\n        characters += String.fromCharCode(following)\n\n        // Check if we can match a legacy named reference.\n        // If so, we cache that as the last viable named reference.\n        // This ensures we do not need to walk backwards later.\n        if (type === 'named' && characterEntitiesLegacy.includes(characters)) {\n          characterReferenceCharacters = characters\n          // @ts-expect-error: always able to decode.\n          characterReference = decodeNamedCharacterReference(characters)\n        }\n      }\n\n      let terminated = value.charCodeAt(end) === 59 /* `;` */\n\n      if (terminated) {\n        end++\n\n        const namedReference =\n          type === 'named' ? decodeNamedCharacterReference(characters) : false\n\n        if (namedReference) {\n          characterReferenceCharacters = characters\n          characterReference = namedReference\n        }\n      }\n\n      let diff = 1 + end - start\n      let reference = ''\n\n      if (!terminated && settings.nonTerminated === false) {\n        // Empty.\n      } else if (!characters) {\n        // An empty (possible) reference is valid, unless it’s numeric (thus an\n        // ampersand followed by an octothorp).\n        if (type !== 'named') {\n          warning(4 /* Empty (numeric) */, diff)\n        }\n      } else if (type === 'named') {\n        // An ampersand followed by anything unknown, and not terminated, is\n        // invalid.\n        if (terminated && !characterReference) {\n          warning(5 /* Unknown (named) */, 1)\n        } else {\n          // If there’s something after an named reference which is not known,\n          // cap the reference.\n          if (characterReferenceCharacters !== characters) {\n            end = begin + characterReferenceCharacters.length\n            diff = 1 + end - begin\n            terminated = false\n          }\n\n          // If the reference is not terminated, warn.\n          if (!terminated) {\n            const reason = characterReferenceCharacters\n              ? 1 /* Non terminated (named) */\n              : 3 /* Empty (named) */\n\n            if (settings.attribute) {\n              const following = value.charCodeAt(end)\n\n              if (following === 61 /* `=` */) {\n                warning(reason, diff)\n                characterReference = ''\n              } else if (isAlphanumerical(following)) {\n                characterReference = ''\n              } else {\n                warning(reason, diff)\n              }\n            } else {\n              warning(reason, diff)\n            }\n          }\n        }\n\n        reference = characterReference\n      } else {\n        if (!terminated) {\n          // All nonterminated numeric references are not rendered, and emit a\n          // warning.\n          warning(2 /* Non terminated (numeric) */, diff)\n        }\n\n        // When terminated and numerical, parse as either hexadecimal or\n        // decimal.\n        let referenceCode = Number.parseInt(\n          characters,\n          type === 'hexadecimal' ? 16 : 10\n        )\n\n        // Emit a warning when the parsed number is prohibited, and replace with\n        // replacement character.\n        if (prohibited(referenceCode)) {\n          warning(7 /* Prohibited (numeric) */, diff)\n          reference = String.fromCharCode(65533 /* `�` */)\n        } else if (referenceCode in characterReferenceInvalid) {\n          // Emit a warning when the parsed number is disallowed, and replace by\n          // an alternative.\n          warning(6 /* Disallowed (numeric) */, diff)\n          reference = characterReferenceInvalid[referenceCode]\n        } else {\n          // Parse the number.\n          let output = ''\n\n          // Emit a warning when the parsed number should not be used.\n          if (disallowed(referenceCode)) {\n            warning(6 /* Disallowed (numeric) */, diff)\n          }\n\n          // Serialize the number.\n          if (referenceCode > 0xffff) {\n            referenceCode -= 0x10000\n            output += String.fromCharCode(\n              (referenceCode >>> (10 & 0x3ff)) | 0xd800\n            )\n            referenceCode = 0xdc00 | (referenceCode & 0x3ff)\n          }\n\n          reference = output + String.fromCharCode(referenceCode)\n        }\n      }\n\n      // Found it!\n      // First eat the queued characters as normal text, then eat a reference.\n      if (reference) {\n        flush()\n\n        previous = now()\n        index = end - 1\n        column += end - start + 1\n        result.push(reference)\n        const next = now()\n        next.offset++\n\n        if (settings.reference) {\n          settings.reference.call(\n            settings.referenceContext || undefined,\n            reference,\n            {start: previous, end: next},\n            value.slice(start - 1, end)\n          )\n        }\n\n        previous = next\n      } else {\n        // If we could not find a reference, queue the checked characters (as\n        // normal characters), and move the pointer to their end.\n        // This is possible because we can be certain neither newlines nor\n        // ampersands are included.\n        characters = value.slice(start - 1, end)\n        queue += characters\n        column += characters.length\n        index = end - 1\n      }\n    } else {\n      // Handle anything other than an ampersand, including newlines and EOF.\n      if (character === 10 /* `\\n` */) {\n        line++\n        lines++\n        column = 0\n      }\n\n      if (Number.isNaN(character)) {\n        flush()\n      } else {\n        queue += String.fromCharCode(character)\n        column++\n      }\n    }\n  }\n\n  // Return the reduced nodes.\n  return result.join('')\n\n  // Get current position.\n  function now() {\n    return {\n      line,\n      column,\n      offset: index + ((point ? point.offset : 0) || 0)\n    }\n  }\n\n  /**\n   * Handle the warning.\n   *\n   * @param {1|2|3|4|5|6|7} code\n   * @param {number} offset\n   */\n  function warning(code, offset) {\n    /** @type {ReturnType<now>} */\n    let position\n\n    if (settings.warning) {\n      position = now()\n      position.column += offset\n      position.offset += offset\n\n      settings.warning.call(\n        settings.warningContext || undefined,\n        messages[code],\n        position,\n        code\n      )\n    }\n  }\n\n  /**\n   * Flush `queue` (normal text).\n   * Macro invoked before each reference and at the end of `value`.\n   * Does nothing when `queue` is empty.\n   */\n  function flush() {\n    if (queue) {\n      result.push(queue)\n\n      if (settings.text) {\n        settings.text.call(settings.textContext || undefined, queue, {\n          start: previous,\n          end: now()\n        })\n      }\n\n      queue = ''\n    }\n  }\n}\n\n/**\n * Check if `character` is outside the permissible unicode range.\n *\n * @param {number} code\n * @returns {boolean}\n */\nfunction prohibited(code) {\n  return (code >= 0xd800 && code <= 0xdfff) || code > 0x10ffff\n}\n\n/**\n * Check if `character` is disallowed.\n *\n * @param {number} code\n * @returns {boolean}\n */\nfunction disallowed(code) {\n  return (\n    (code >= 0x0001 && code <= 0x0008) ||\n    code === 0x000b ||\n    (code >= 0x000d && code <= 0x001f) ||\n    (code >= 0x007f && code <= 0x009f) ||\n    (code >= 0xfdd0 && code <= 0xfdef) ||\n    (code & 0xffff) === 0xffff ||\n    (code & 0xffff) === 0xfffe\n  )\n}\n","import { replaceTemplateTags } from '$lib/services/common/template/tags';\n\n/**\n * @import { StringTransformation } from '$lib/types/private';\n */\n\n/**\n * Resolve the nested template tags in a transformation argument, e.g. `{{fields.title}}` or\n * `{{fields.first_name}} {{fields.last_name}}`, keeping the text around them. An escaped tag, e.g.\n * `\\{{title}}`, is kept without the backslash.\n * @param {string} value The transformation argument value.\n * @param {(tag: string) => string} resolveTag Function to resolve a nested tag.\n * @returns {string} Resolved value.\n */\nconst resolveNestedTemplateValues = (value, resolveTag) =>\n  replaceTemplateTags(value, (_match, innerTag) => String(resolveTag(innerTag) ?? ''));\n\n/**\n * Process nested template tags in transformation arguments (e.g., `default('{{fields.title}}')`).\n * This handles nested templates in `default`, `ternary`, and custom transformations that accept\n * string arguments which may contain template tags.\n * @param {StringTransformation[]} transformations Transformation entries.\n * @param {(tag: string) => string} resolveTag Function to resolve a tag to its value.\n * @returns {StringTransformation[]} Processed transformations with nested templates resolved.\n */\nexport const processNestedTemplates = (transformations, resolveTag) =>\n  transformations.map((tf) => {\n    const { defaultValue, truthyValue, falsyValue } = tf.args;\n    const newArgs = { ...tf.args };\n    let hasChanges = false;\n\n    // Handle nested template in default transformation\n    if (defaultValue !== undefined) {\n      const resolvedDefaultValue = resolveNestedTemplateValues(defaultValue, resolveTag);\n\n      if (resolvedDefaultValue !== defaultValue) {\n        newArgs.defaultValue = resolvedDefaultValue;\n        hasChanges = true;\n      }\n    }\n\n    // Handle nested templates in ternary transformation\n    if (truthyValue !== undefined) {\n      const resolvedTruthyValue = resolveNestedTemplateValues(truthyValue, resolveTag);\n\n      if (resolvedTruthyValue !== truthyValue) {\n        newArgs.truthyValue = resolvedTruthyValue;\n        hasChanges = true;\n      }\n    }\n\n    if (falsyValue !== undefined) {\n      const resolvedFalsyValue = resolveNestedTemplateValues(falsyValue, resolveTag);\n\n      if (resolvedFalsyValue !== falsyValue) {\n        newArgs.falsyValue = resolvedFalsyValue;\n        hasChanges = true;\n      }\n    }\n\n    // Handle nested templates in the string arguments of a custom transformation\n    const { customArgs } = tf;\n    /** @type {(string | number)[] | undefined} */\n    let newCustomArgs;\n\n    if (customArgs?.some((arg) => typeof arg === 'string' && arg.includes('{{'))) {\n      newCustomArgs = customArgs.map((arg) =>\n        typeof arg === 'string' ? resolveNestedTemplateValues(arg, resolveTag) : arg,\n      );\n    }\n\n    if (!hasChanges && !newCustomArgs) {\n      return tf;\n    }\n\n    return { ...tf, args: newArgs, ...(newCustomArgs ? { customArgs: newCustomArgs } : {}) };\n  });\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){\"use strict\";var t=1e3,e=6e4,n=36e5,r=\"millisecond\",i=\"second\",s=\"minute\",u=\"hour\",a=\"day\",o=\"week\",c=\"month\",f=\"quarter\",h=\"year\",d=\"date\",l=\"Invalid Date\",$=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,y=/\\[([^\\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(t){var e=[\"th\",\"st\",\"nd\",\"rd\"],n=t%100;return\"[\"+t+(e[(n-20)%10]||e[n]||e[0])+\"]\"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:\"\"+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?\"+\":\"-\")+m(r,2,\"0\")+\":\"+m(i,2,\"0\")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,c),s=n-i<0,u=e.clone().add(r+(s?-1:1),c);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:c,y:h,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:f}[t]||String(t||\"\").toLowerCase().replace(/s$/,\"\")},u:function(t){return void 0===t}},g=\"en\",D={};D[g]=M;var p=\"$isDayjsObject\",S=function(t){return t instanceof _||!(!t||!t[p])},w=function t(e,n,r){var i;if(!e)return g;if(\"string\"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split(\"-\");if(!i&&u.length>1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n=\"object\"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if(\"string\"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||\"0\").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return b},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<O(t)},m.$g=function(t,e,n){return b.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!b.u(e)||e,f=b.p(t),l=function(t,e){var i=b.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},$=function(t,e){return b.w(n.toDate()[t].apply(n.toDate(\"s\"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,v=\"set\"+(this.$u?\"UTC\":\"\");switch(f){case h:return r?l(1,0):l(31,11);case c:return r?l(1,M):l(0,M+1);case o:var g=this.$locale().weekStart||0,D=(y<g?y+7:y)-g;return l(r?m-D:m+(6-D),M);case a:case d:return $(v+\"Hours\",0);case u:return $(v+\"Minutes\",1);case s:return $(v+\"Seconds\",2);case i:return $(v+\"Milliseconds\",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=b.p(t),f=\"set\"+(this.$u?\"UTC\":\"\"),l=(n={},n[a]=f+\"Date\",n[d]=f+\"Date\",n[c]=f+\"Month\",n[h]=f+\"FullYear\",n[u]=f+\"Hours\",n[s]=f+\"Minutes\",n[i]=f+\"Seconds\",n[r]=f+\"Milliseconds\",n)[o],$=o===a?this.$D+(e-this.$W):e;if(o===c||o===h){var y=this.clone().set(d,1);y.$d[l]($),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d}else l&&this.$d[l]($);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[b.p(t)]()},m.add=function(r,f){var d,l=this;r=Number(r);var $=b.p(f),y=function(t){var e=O(l);return b.w(e.date(e.date()+Math.round(t*r)),l)};if($===c)return this.set(c,this.$M+r);if($===h)return this.set(h,this.$y+r);if($===a)return y(1);if($===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[$]||1,m=this.$d.getTime()+r*M;return b.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||\"YYYY-MM-DDTHH:mm:ssZ\",i=b.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,c=n.months,f=n.meridiem,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},d=function(t){return b.s(s%12||12,t,\"0\")},$=f||function(t,e,n){var r=t<12?\"AM\":\"PM\";return n?r.toLowerCase():r};return r.replace(y,(function(t,r){return r||function(t){switch(t){case\"YY\":return String(e.$y).slice(-2);case\"YYYY\":return b.s(e.$y,4,\"0\");case\"M\":return a+1;case\"MM\":return b.s(a+1,2,\"0\");case\"MMM\":return h(n.monthsShort,a,c,3);case\"MMMM\":return h(c,a);case\"D\":return e.$D;case\"DD\":return b.s(e.$D,2,\"0\");case\"d\":return String(e.$W);case\"dd\":return h(n.weekdaysMin,e.$W,o,2);case\"ddd\":return h(n.weekdaysShort,e.$W,o,3);case\"dddd\":return o[e.$W];case\"H\":return String(s);case\"HH\":return b.s(s,2,\"0\");case\"h\":return d(1);case\"hh\":return d(2);case\"a\":return $(s,u,!0);case\"A\":return $(s,u,!1);case\"m\":return String(u);case\"mm\":return b.s(u,2,\"0\");case\"s\":return String(e.$s);case\"ss\":return b.s(e.$s,2,\"0\");case\"SSS\":return b.s(e.$ms,3,\"0\");case\"Z\":return i}return null}(t)||i.replace(\":\",\"\")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,l){var $,y=this,M=b.p(d),m=O(r),v=(m.utcOffset()-this.utcOffset())*e,g=this-m,D=function(){return b.m(y,m)};switch(M){case h:$=D()/12;break;case c:$=D();break;case f:$=D()/3;break;case o:$=(g-v)/6048e5;break;case a:$=(g-v)/864e5;break;case u:$=g/n;break;case s:$=g/e;break;case i:$=g/t;break;default:$=g}return l?$:b.a($)},m.daysInMonth=function(){return this.endOf(c).$D},m.$locale=function(){return D[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=w(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return b.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),Y=_.prototype;return O.prototype=Y,[[\"$ms\",r],[\"$s\",i],[\"$m\",s],[\"$H\",u],[\"$W\",a],[\"$M\",c],[\"$y\",h],[\"$D\",d]].forEach((function(t){Y[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),O.extend=function(t,e){return t.$i||(t(e,_,O),t.$i=!0),O},O.locale=w,O.isDayjs=S,O.unix=function(t){return O(1e3*t)},O.en=D[g],O.Ls=D,O.p={},O}));","!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_plugin_customParseFormat=t()}(this,(function(){\"use strict\";var e={LTS:\"h:mm:ss A\",LT:\"h:mm A\",L:\"MM/DD/YYYY\",LL:\"MMMM D, YYYY\",LLL:\"MMMM D, YYYY h:mm A\",LLLL:\"dddd, MMMM D, YYYY h:mm A\"},t=/(\\[[^[]*\\])|([-_:/.,()\\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,n=/\\d/,r=/\\d\\d/,i=/\\d\\d?/,o=/\\d*[^-_:/,()\\s\\d]+/,s={},a=function(e){return(e=+e)+(e>68?1900:2e3)};var f=function(e){return function(t){this[e]=+t}},h=[/[+-]\\d\\d:?(\\d\\d)?|Z/,function(e){(this.zone||(this.zone={})).offset=function(e){if(!e)return 0;if(\"Z\"===e)return 0;var t=e.match(/([+-]|\\d\\d)/g),n=60*t[1]+(+t[2]||0);return 0===n?0:\"+\"===t[0]?-n:n}(e)}],u=function(e){var t=s[e];return t&&(t.indexOf?t:t.s.concat(t.f))},d=function(e,t){var n,r=s.meridiem;if(r){for(var i=1;i<=24;i+=1)if(e.indexOf(r(i,0,t))>-1){n=i>12;break}}else n=e===(t?\"pm\":\"PM\");return n},c={A:[o,function(e){this.afternoon=d(e,!1)}],a:[o,function(e){this.afternoon=d(e,!0)}],Q:[n,function(e){this.month=3*(e-1)+1}],S:[n,function(e){this.milliseconds=100*+e}],SS:[r,function(e){this.milliseconds=10*+e}],SSS:[/\\d{3}/,function(e){this.milliseconds=+e}],s:[i,f(\"seconds\")],ss:[i,f(\"seconds\")],m:[i,f(\"minutes\")],mm:[i,f(\"minutes\")],H:[i,f(\"hours\")],h:[i,f(\"hours\")],HH:[i,f(\"hours\")],hh:[i,f(\"hours\")],D:[i,f(\"day\")],DD:[r,f(\"day\")],Do:[o,function(e){var t=s.ordinal,n=e.match(/\\d+/);if(this.day=n[0],t)for(var r=1;r<=31;r+=1)t(r).replace(/\\[|\\]/g,\"\")===e&&(this.day=r)}],w:[i,f(\"week\")],ww:[r,f(\"week\")],M:[i,f(\"month\")],MM:[r,f(\"month\")],MMM:[o,function(e){var t=u(\"months\"),n=(u(\"monthsShort\")||t.map((function(e){return e.slice(0,3)}))).indexOf(e)+1;if(n<1)throw new Error;this.month=n%12||n}],MMMM:[o,function(e){var t=u(\"months\").indexOf(e)+1;if(t<1)throw new Error;this.month=t%12||t}],Y:[/[+-]?\\d+/,f(\"year\")],YY:[r,function(e){this.year=a(e)}],YYYY:[/\\d{4}/,f(\"year\")],Z:h,ZZ:h};function l(n){var r,i;r=n,i=s&&s.formats;for(var o=(n=r.replace(/(\\[[^\\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(t,n,r){var o=r&&r.toUpperCase();return n||i[r]||e[r]||i[o].replace(/(\\[[^\\]]+])|(MMMM|MM|DD|dddd)/g,(function(e,t,n){return t||n.slice(1)}))}))).match(t),a=o.length,f=0;f<a;f+=1){var h=o[f],u=c[h],d=u&&u[0],l=u&&u[1];o[f]=l?{regex:d,parser:l}:h.replace(/^\\[|\\]$/g,\"\")}return function(e){for(var t={},n=0,r=0;n<a;n+=1){var i=o[n];if(\"string\"==typeof i)r+=i.length;else{var s=i.regex,f=i.parser,h=e.slice(r),u=s.exec(h)[0];f.call(t,u),e=e.replace(u,\"\")}}return function(e){var t=e.afternoon;if(void 0!==t){var n=e.hours;t?n<12&&(e.hours+=12):12===n&&(e.hours=0),delete e.afternoon}}(t),t}}return function(e,t,n){n.p.customParseFormat=!0,e&&e.parseTwoDigitYear&&(a=e.parseTwoDigitYear);var r=t.prototype,i=r.parse;r.parse=function(e){var t=e.date,r=e.utc,o=e.args;this.$u=r;var a=o[1];if(\"string\"==typeof a){var f=!0===o[2],h=!0===o[3],u=f||h,d=o[2];h&&(d=o[2]),s=this.$locale(),!f&&d&&(s=n.Ls[d]),this.$d=function(e,t,n,r){try{if([\"x\",\"X\"].indexOf(t)>-1)return new Date((\"X\"===t?1e3:1)*e);var i=l(t)(e),o=i.year,s=i.month,a=i.day,f=i.hours,h=i.minutes,u=i.seconds,d=i.milliseconds,c=i.zone,m=i.week,M=new Date,Y=a||(o||s?1:M.getDate()),p=o||M.getFullYear(),v=0;o&&!s||(v=s>0?s-1:M.getMonth());var D,w=f||0,g=h||0,y=u||0,L=d||0;return c?new Date(Date.UTC(p,v,Y,w,g,y,L+60*c.offset*1e3)):n?new Date(Date.UTC(p,v,Y,w,g,y,L)):(D=new Date(p,v,Y,w,g,y,L),m&&(D=r(D).week(m).toDate()),D)}catch(e){return new Date(\"\")}}(t,a,r,n),this.init(),d&&!0!==d&&(this.$L=this.locale(d).$L),u&&t!=this.format(a)&&(this.$d=new Date(\"\")),s={}}else if(a instanceof Array)for(var c=a.length,m=1;m<=c;m+=1){o[1]=a[m-1];var M=n.apply(this,o);if(M.isValid()){this.$d=M.$d,this.$L=M.$L,this.init();break}m===c&&(this.$d=new Date(\"\"))}else i.call(this,e)}}}));","!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_plugin_localizedFormat=t()}(this,(function(){\"use strict\";var e={LTS:\"h:mm:ss A\",LT:\"h:mm A\",L:\"MM/DD/YYYY\",LL:\"MMMM D, YYYY\",LLL:\"MMMM D, YYYY h:mm A\",LLLL:\"dddd, MMMM D, YYYY h:mm A\"};return function(t,o,n){var r=o.prototype,i=r.format;n.en.formats=e,r.format=function(t){void 0===t&&(t=\"YYYY-MM-DDTHH:mm:ssZ\");var o=this.$locale().formats,n=function(t,o){return t.replace(/(\\[[^\\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(t,n,r){var i=r&&r.toUpperCase();return n||o[r]||e[r]||o[i].replace(/(\\[[^\\]]+])|(MMMM|MM|DD|dddd)/g,(function(e,t,o){return t||o.slice(1)}))}))}(t,void 0===o?{}:o);return i.call(this,n)}}}));","!function(t,i){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=i():\"function\"==typeof define&&define.amd?define(i):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_utc=i()}(this,(function(){\"use strict\";var t=\"minute\",i=/[+-]\\d\\d(?::?\\d\\d)?/g,e=/([+-]|\\d\\d)/g;return function(s,f,n){var u=f.prototype;n.utc=function(t){var i={date:t,utc:!0,args:arguments};return new f(i)},u.utc=function(i){var e=n(this.toDate(),{locale:this.$L,utc:!0});return i?e.add(this.utcOffset(),t):e},u.local=function(){return n(this.toDate(),{locale:this.$L,utc:!1})};var r=u.parse;u.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),r.call(this,t)};var o=u.init;u.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else o.call(this)};var a=u.utcOffset;u.utcOffset=function(s,f){var n=this.$utils().u;if(n(s))return this.$u?0:n(this.$offset)?a.call(this):this.$offset;if(\"string\"==typeof s&&(s=function(t){void 0===t&&(t=\"\");var s=t.match(i);if(!s)return null;var f=(\"\"+s[0]).match(e)||[\"-\",0,0],n=f[0],u=60*+f[1]+ +f[2];return 0===u?0:\"+\"===n?u:-u}(s),null===s))return this;var u=Math.abs(s)<=16?60*s:s;if(0===u)return this.utc(f);var r=this.clone();if(f)return r.$offset=u,r.$u=!1,r;var o=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();return(r=this.local().add(u+o,t)).$offset=u,r.$x.$localOffset=o,r};var h=u.format;u.format=function(t){var i=t||(this.$u?\"YYYY-MM-DDTHH:mm:ss[Z]\":\"\");return h.call(this,i)},u.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},u.isUTC=function(){return!!this.$u},u.toISOString=function(){return this.toDate().toISOString()},u.toString=function(){return this.toDate().toUTCString()};var l=u.toDate;u.toDate=function(t){return\"s\"===t&&this.$offset?n(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\")).toDate():l.call(this)};var c=u.diff;u.diff=function(t,i,e){if(t&&this.$u===t.$u)return c.call(this,t,i,e);var s=this.local(),f=n(t).local();return c.call(s,f,i,e)}}}));","/**\n * @import { DateTimeFieldNormalizedProps } from '$lib/types/private';\n * @import { DateTimeField } from '$lib/types/public';\n */\n\nconst TIMEZONE_ENUM = new Set(['local', 'utc']);\n/**\n * Cache normalized date-time field configurations by field config reference.\n * @type {WeakMap<DateTimeField, DateTimeFieldNormalizedProps>}\n */\nconst configCacheMap = new WeakMap();\n\n/**\n * Check if a timezone string is a custom IANA timezone (not a special value). No need to validate\n * the timezone here because that’s handled by `validateTimeZone` in the field parser, and this\n * function is only used to determine if the timezone should be passed to Day.js for\n * parsing/formatting.\n * @param {any} timeZone Timezone string to check.\n * @returns {timeZone is string} True if custom IANA timezone, false otherwise.\n */\nexport const isCustomTimeZone = (timeZone) =>\n  typeof timeZone === 'string' && !TIMEZONE_ENUM.has(timeZone);\n\n/**\n * Parse the DateTime field configuration and return as normalized format.\n * @param {DateTimeField} fieldConfig Field config.\n * @returns {DateTimeFieldNormalizedProps} Normalized properties.\n */\nexport const parseDateTimeConfig = (fieldConfig) => {\n  const cache = configCacheMap.get(fieldConfig);\n\n  if (cache) {\n    return cache;\n  }\n\n  const {\n    type = 'datetime-local',\n    min = undefined,\n    max = undefined,\n    step = undefined,\n    format,\n    date_format: dateFormat = undefined,\n    time_format: timeFormat = undefined,\n    picker_utc: pickerUTC = false,\n    input_timezone: inputTimeZone = 'local',\n    output_utc: outputUTC = false,\n  } = fieldConfig;\n\n  const normalizedInputTimeZone =\n    typeof inputTimeZone === 'string' && inputTimeZone !== 'any' ? inputTimeZone : 'local';\n\n  const dateFormatStr = typeof dateFormat === 'string' ? dateFormat : '';\n  const timeFormatStr = typeof timeFormat === 'string' ? timeFormat : '';\n  const dateOnly = type === 'date' || timeFormat === false;\n  const timeOnly = type === 'time' || dateFormat === false;\n  const defaultMax = dateOnly ? '9999-12-31' : timeOnly ? undefined : '9999-12-31T23:59';\n\n  const _inputTimeZone =\n    fieldConfig.input_timezone !== undefined\n      ? normalizedInputTimeZone\n      : pickerUTC\n        ? 'utc'\n        : 'local';\n\n  const normalizedConfig = /** @type {DateTimeFieldNormalizedProps} */ ({\n    type: dateOnly ? 'date' : timeOnly ? 'time' : 'datetime-local',\n    min: typeof min === 'string' && min ? min : undefined,\n    max: typeof max === 'string' && max ? max : defaultMax,\n    step:\n      (typeof step === 'number' && Number.isInteger(step) && step > 0) || step === 'any'\n        ? step\n        : undefined,\n    format: format || [dateFormatStr, timeFormatStr].join(' ').trim() || undefined,\n    dateOnly,\n    timeOnly,\n    inputTimeZone: _inputTimeZone,\n    outputUTC: fieldConfig.output_utc !== undefined ? outputUTC : pickerUTC,\n    utc: _inputTimeZone === 'utc',\n    singleCustomTimeZone: isCustomTimeZone(_inputTimeZone) ? _inputTimeZone : undefined,\n  });\n\n  configCacheMap.set(fieldConfig, normalizedConfig);\n\n  return normalizedConfig;\n};\n","import { loadModule } from '$lib/services/app/dependencies';\n\n/**\n * Load the data of a Day.js locale from UNPKG. The npm build replaces this module with\n * `locale-loader.npm.js`, which bundles the locale files instead. The ES module registers the\n * locale with the copy of Day.js it imports itself, which isn’t the bundled one, so the data is\n * taken from its default export.\n * @param {string} key Day.js locale key, e.g. `de` or `pt-br`.\n * @returns {Promise<ILocale>} Locale data.\n */\nexport const loadLocaleData = async (key) =>\n  (await loadModule('dayjs', `esm/locale/${key}.js`)).default;\n","import dayjs from 'dayjs';\n\nimport { getOrCreate } from '$lib/services/utils/cache';\n\nimport { loadLocaleData } from './locale-loader.js';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { DateTimeField } from '$lib/types/public';\n */\n\n/**\n * Keys of the locales Day.js provides, e.g. `de` or `pt-br`, listed at build time.\n * @type {Set<string>}\n */\nconst DAYJS_LOCALE_KEYS = new Set(import.meta.env.VITE_DAYJS_LOCALES.split(','));\n/**\n * Keys of the locales registered with Day.js. English is built in.\n * @type {Set<string>}\n */\nconst loadedLocaleKeys = new Set(['en']);\n/**\n * Pending loads of the Day.js locales, keyed with the locale key, so a locale is only requested\n * once.\n * @type {Map<string, Promise<void>>}\n */\nconst pendingLoads = new Map();\n/**\n * Cache of {@link getDayjsLocaleKey} results, keyed with the locale code. The codes come from the\n * configuration, so there are only a few of them.\n * @type {Map<string, string | undefined>}\n */\nconst localeKeyCache = new Map();\n\n/**\n * Get the Day.js locale that best matches the given locale code. The code is tried as is, then\n * with its parts removed from the end, e.g. `pt-BR`, then `pt`. A code with a script but no\n * region, like `zh-Hant`, is also tried with the region the script is most used in, `zh-TW`, before\n * the language alone, as Day.js has regional locales for the scripts rather than script ones.\n * @param {string} locale Locale code, e.g. `de` or `pt-BR`.\n * @returns {string | undefined} Day.js locale key, e.g. `de` or `pt-br`, or `undefined` if Day.js\n * doesn’t have the locale or the code is invalid.\n */\nconst findDayjsLocaleKey = (locale) => {\n  /** @type {Intl.Locale} */\n  let intlLocale;\n\n  try {\n    intlLocale = new Intl.Locale(locale);\n  } catch {\n    return undefined;\n  }\n\n  const { language, script, region } = intlLocale;\n  const candidates = [locale.toLowerCase()];\n\n  if (script && region) {\n    candidates.push(`${language}-${script}-${region}`);\n  }\n\n  if (script) {\n    candidates.push(`${language}-${script}`);\n  }\n\n  if (region) {\n    candidates.push(`${language}-${region}`);\n  }\n\n  if (script && !region) {\n    candidates.push(`${language}-${intlLocale.maximize().region}`);\n  }\n\n  candidates.push(language);\n\n  return candidates\n    .map((candidate) => candidate.toLowerCase())\n    .find((candidate) => DAYJS_LOCALE_KEYS.has(candidate));\n};\n\n/**\n * Get the Day.js locale that best matches the given locale code, as {@link findDayjsLocaleKey}\n * does, with the result cached.\n * @param {string} locale Locale code, e.g. `de` or `pt-BR`.\n * @returns {string | undefined} Day.js locale key, or `undefined` if Day.js doesn’t have the locale\n * or the code is invalid.\n */\nexport const getDayjsLocaleKey = (locale) =>\n  getOrCreate(localeKeyCache, locale, () => findDayjsLocaleKey(locale));\n\n/**\n * Load and register the Day.js locale for the given key, if it hasn’t been yet. English is built\n * in, so it’s never loaded.\n * @param {string} key Day.js locale key.\n * @returns {Promise<void>} Promise that resolves once the locale is registered, or has failed to\n * load, in which case dates are written in English.\n */\nconst loadDayjsLocale = (key) => {\n  if (loadedLocaleKeys.has(key)) {\n    return Promise.resolve();\n  }\n\n  let promise = pendingLoads.get(key);\n\n  if (!promise) {\n    promise = (async () => {\n      try {\n        dayjs.locale(await loadLocaleData(key), undefined, true);\n        loadedLocaleKeys.add(key);\n      } catch (ex) {\n        // eslint-disable-next-line no-console\n        console.error(`Failed to load the Day.js locale “${key}”`, ex);\n      } finally {\n        pendingLoads.delete(key);\n      }\n    })();\n\n    pendingLoads.set(key, promise);\n  }\n\n  return promise;\n};\n\n/**\n * Load the Day.js locales for the given locale codes, so dates can be formatted and parsed in them.\n * A code Day.js doesn’t have a locale for is ignored.\n * @param {Iterable<string>} locales Locale codes, e.g. `de` or `pt-BR`.\n * @returns {Promise<void>} Promise that resolves once all the locales have been loaded or failed.\n */\nexport const loadDayjsLocales = async (locales) => {\n  const keys = new Set([...locales].map(getDayjsLocaleKey).filter((key) => key !== undefined));\n\n  await Promise.all([...keys].map(loadDayjsLocale));\n};\n\n/**\n * Get the Day.js locale a DateTime field’s value is formatted and parsed in, as set with the\n * `localize_format` option: the given locale if `true`, or the one given as the option. A locale\n * that hasn’t been loaded, which Day.js doesn’t have or failed to load, falls back to English.\n * @param {DateTimeField} fieldConfig Field configuration.\n * @param {InternalLocaleCode} [locale] Locale of the content the value belongs to. `_default` if\n * i18n isn’t enabled for the content.\n * @returns {string | undefined} Day.js locale key, or `undefined` for English.\n */\nexport const getFormatLocale = (fieldConfig, locale) => {\n  const { localize_format: localizeFormat } = fieldConfig;\n\n  const code =\n    typeof localizeFormat === 'string'\n      ? localizeFormat\n      : localizeFormat === true && locale && locale !== '_default'\n        ? locale\n        : undefined;\n\n  if (!code) {\n    return undefined;\n  }\n\n  const key = getDayjsLocaleKey(code);\n\n  return key && key !== 'en' && loadedLocaleKeys.has(key) ? key : undefined;\n};\n","!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_plugin_advancedFormat=t()}(this,(function(){\"use strict\";return function(e,t){var r=t.prototype,n=r.format;r.format=function(e){var t=this,r=this.$locale();if(!this.isValid())return n.bind(this)(e);var s=this.$utils(),a=(e||\"YYYY-MM-DDTHH:mm:ssZ\").replace(/\\[([^\\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,(function(e){switch(e){case\"Q\":return Math.ceil((t.$M+1)/3);case\"Do\":return r.ordinal(t.$D);case\"gggg\":return t.weekYear();case\"GGGG\":return t.isoWeekYear();case\"wo\":return r.ordinal(t.week(),\"W\");case\"w\":case\"ww\":return s.s(t.week(),\"w\"===e?1:2,\"0\");case\"W\":case\"WW\":return s.s(t.isoWeek(),\"W\"===e?1:2,\"0\");case\"k\":case\"kk\":return s.s(String(0===t.$H?24:t.$H),\"k\"===e?1:2,\"0\");case\"X\":return Math.floor(t.$d.getTime()/1e3);case\"x\":return t.$d.getTime();case\"z\":return\"[\"+t.offsetName()+\"]\";case\"zzz\":return\"[\"+t.offsetName(\"long\")+\"]\";default:return e}}));return n.bind(this)(a)}}}));","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_timezone=e()}(this,(function(){\"use strict\";var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,i,r){var o,a=function(t,n,i){void 0===i&&(i={});var r=new Date(t),o=function(t,n){void 0===n&&(n={});var i=n.timeZoneName||\"short\",r=t+\"|\"+i,o=e[r];return o||(o=new Intl.DateTimeFormat(\"en-US\",{hour12:!1,timeZone:t,year:\"numeric\",month:\"2-digit\",day:\"2-digit\",hour:\"2-digit\",minute:\"2-digit\",second:\"2-digit\",timeZoneName:i}),e[r]=o),o}(n,i);return o.formatToParts(r)},u=function(e,n){for(var i=a(e,n),o=[],u=0;u<i.length;u+=1){var f=i[u],s=f.type,m=f.value,c=t[s];c>=0&&(o[c]=parseInt(m,10))}var l=o[3],d=24===l?0:l,h=o[0]+\"-\"+o[1]+\"-\"+o[2]+\" \"+d+\":\"+o[4]+\":\"+o[5]+\":000\",v=+e;return(r.utc(h).valueOf()-(v-=v%1e3))/6e4},f=i.prototype;f.tz=function(t,e){if(void 0===t&&(t=o),!this.isValid())return this;var n,i=this.utcOffset(),a=this.toDate(),f=a.toLocaleString(\"en-US\",{timeZone:t}),s=u(+a,t);if(!Number(s))n=this.utcOffset(0,e);else if(n=r(f,{locale:this.$L}).$set(\"millisecond\",this.$ms).utcOffset(s,!0),e){var m=n.utcOffset();n=n.add(i-m,\"minute\")}return n.$x.$timezone=t,n},f.offsetName=function(t){var e=this.$x.$timezone||r.tz.guess(),n=a(this.valueOf(),e,{timeZoneName:t}).find((function(t){return\"timezonename\"===t.type.toLowerCase()}));return n&&n.value};var s=f.startOf;f.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return s.call(this,t,e);var n=r(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\"),{locale:this.$L});return s.call(n,t,e).tz(this.$x.$timezone,!0)},r.tz=function(t,e,n){var i=n&&e,a=n||e||o,f=u(+r(),a);if(\"string\"!=typeof t)return r(t).tz(a);var s=r.utc(t,i).valueOf();if(Number.isNaN(s)){var m=r(NaN);return m.$x.$timezone=a,m}var c=function(t,e,n){var i=t-60*e*1e3,r=u(i,n);if(e===r)return[i,e];var o=u(i-=60*(r-e)*1e3,n);return r===o?[i,r]:[t-60*Math.min(r,o)*1e3,Math.max(r,o)]}(s,f,a),l=c[0],d=c[1],h=r(l).utcOffset(d);return h.$x.$timezone=a,h},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(t){o=t}}}));","import dayjs from 'dayjs';\nimport dayjsAdvancedFormat from 'dayjs/plugin/advancedFormat';\nimport dayjsCustomParseFormat from 'dayjs/plugin/customParseFormat';\nimport dayjsLocalizedFormat from 'dayjs/plugin/localizedFormat';\nimport dayjsTimeZone from 'dayjs/plugin/timezone';\nimport dayjsUTC from 'dayjs/plugin/utc';\n\nimport { parseDateTimeConfig } from './config.js';\nimport { getFormatLocale } from './locales.js';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { DateTimeField } from '$lib/types/public';\n */\n\ndayjs.extend(dayjsAdvancedFormat);\ndayjs.extend(dayjsCustomParseFormat);\ndayjs.extend(dayjsLocalizedFormat);\ndayjs.extend(dayjsUTC);\ndayjs.extend(dayjsTimeZone);\n\n/**\n * Check if the given value is a valid `Date` object.\n * @param {any} input Value to check.\n * @returns {input is Date} `true` if valid `Date`, `false` otherwise.\n */\nexport const isValidDate = (input) => input instanceof Date && !Number.isNaN(input.getTime());\n\n/**\n * Get the Day.js parser based on UTC setting.\n * @param {boolean} utc UTC flag.\n * @returns {dayjs.utc | dayjs} Day.js parser.\n */\nexport const getParser = (utc) => (utc ? dayjs.utc : dayjs);\n\n/**\n * Match a value ending in a time followed by a UTC offset, like `10:30:00Z` or `10:30+09:00`. A\n * date-only value like `2026-01-15` has no time before its last hyphen, so it doesn’t match.\n */\nconst OFFSET_SUFFIX_REGEX = /\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}(?::?\\d{2})?)$/i;\n/**\n * Match an offset token (`Z` or `ZZ`) or a Unix timestamp token (`X` or `x`), which is an instant\n * on its own too, in a Day.js format, once the escaped text in square brackets has been removed.\n */\nconst FORMAT_OFFSET_TOKEN_REGEX = /[XxZ]/;\n/**\n * Match a time token in a Day.js format, including a localized format with a time and a Unix\n * timestamp, once the escaped text in square brackets has been removed.\n */\n// cspell:disable-next-line\nconst FORMAT_TIME_TOKEN_REGEX = /[AaHhkmSsXx]|LT|LLL|lll/;\n/**\n * Remove the escaped text in square brackets from a Day.js format, leaving its tokens.\n * @param {string} format Format string.\n * @returns {string} Tokens.\n */\nconst getFormatTokens = (format) => format.replaceAll(/\\[.*?]/g, '');\n\n/**\n * Check if the given Day.js format has a UTC offset token.\n * @param {string} format Format string.\n * @returns {boolean} Result.\n */\nexport const hasOffsetToken = (format) => FORMAT_OFFSET_TOKEN_REGEX.test(getFormatTokens(format));\n\n/**\n * Check if a value has a UTC offset that the given Day.js format, which has a time, can’t hold,\n * like an ISO 8601 value written before the format was set. Such a value is only parsed with the\n * format if it’s written in it exactly, e.g. with an escaped `[Z]`: the parser would otherwise read\n * the time and drop the offset, shifting the instant by it. A date in a format without a time is\n * read as written.\n * @param {string} value Value to parse.\n * @param {string} format Format string.\n * @returns {boolean} Result.\n */\nexport const hasOffsetOutsideFormat = (value, format) =>\n  OFFSET_SUFFIX_REGEX.test(value) &&\n  FORMAT_TIME_TOKEN_REGEX.test(getFormatTokens(format)) &&\n  !hasOffsetToken(format);\n\n/**\n * Parse a value in the given format with a Day.js parser. A value with a UTC offset is parsed\n * strictly in a format with a time but no offset, see {@link hasOffsetOutsideFormat}.\n * @param {dayjs.utc | dayjs} parse Day.js parser, as returned by {@link getParser}.\n * @param {string} value Value to parse.\n * @param {string} format Format string.\n * @param {string} [localeKey] Day.js locale the value is written in.\n * @returns {dayjs.Dayjs} Parsed dayjs instance.\n */\nconst parseWithFormat = (parse, value, format, localeKey) =>\n  // The UTC parser takes a locale like `dayjs()` does, though its type doesn’t say so\n  /** @type {typeof dayjs} */ (parse)(\n    value,\n    format,\n    localeKey,\n    hasOffsetOutsideFormat(value, format),\n  );\n\n/**\n * Parse a value with Day.js, falling back to the default parser when the supplied format fails.\n * @param {object} args Arguments.\n * @param {string} args.value Value to parse.\n * @param {string} args.format Format string.\n * @param {boolean} args.parseAsUTC Whether to parse as UTC.\n * @param {string} [args.localeKey] Day.js locale the value is written in, as returned by\n * `getFormatLocale()`. English if omitted. The parsed instance formats in the same locale.\n * @returns {dayjs.Dayjs} Parsed dayjs instance.\n */\nexport const parseWithFormatFallback = ({ value, format, parseAsUTC, localeKey }) => {\n  const parse = getParser(parseAsUTC);\n  const parsed = parseWithFormat(parse, value, format, localeKey);\n\n  return parsed.isValid() ? parsed : parse(value);\n};\n\n/**\n * Format a Day.js instance in the given locale.\n * @param {dayjs.Dayjs} instance Day.js instance.\n * @param {string} format Format string.\n * @param {string} [localeKey] Day.js locale, as returned by `getFormatLocale()`. If omitted, the\n * instance’s own locale is used, which is English unless it was parsed in another.\n * @returns {string} Formatted value.\n */\nexport const formatInLocale = (instance, format, localeKey) =>\n  (localeKey ? instance.locale(localeKey) : instance).format(format);\n\n/**\n * Get the instant of a wall-clock time in the given time zone.\n * @param {dayjs.Dayjs} wallTime Wall-clock time, parsed as UTC.\n * @param {string} timeZone `UTC` or an IANA time zone name.\n * @returns {Date} Date.\n */\nconst getDateInTimeZone = (wallTime, timeZone) =>\n  timeZone === 'UTC'\n    ? wallTime.toDate()\n    : dayjs.tz(wallTime.format('YYYY-MM-DDTHH:mm:ss.SSS'), timeZone).toDate();\n\n/**\n * Parse an ISO 8601 value. A value with a UTC offset is an instant on its own, while one without\n * an offset is read in the given time zone, or the browser’s if none is given.\n * @param {string} value Value to parse.\n * @param {string} [timeZone] `UTC` or an IANA time zone name.\n * @returns {Date | undefined} Date, which can be invalid, or `undefined` if the value can’t be\n * parsed in the time zone.\n */\nconst parseISODate = (value, timeZone) => {\n  if (!timeZone || OFFSET_SUFFIX_REGEX.test(value)) {\n    return new Date(value);\n  }\n\n  const wallTime = dayjs.utc(value);\n\n  return wallTime.isValid() ? getDateInTimeZone(wallTime, timeZone) : undefined;\n};\n\n/**\n * Get the time zone a stored value without a UTC offset is read in. See {@link getDate}.\n * @param {DateTimeField} fieldConfig Field configuration.\n * @returns {string | undefined} `UTC`, an IANA time zone name, or `undefined` for the browser’s.\n */\nexport const getStoredValueTimeZone = (fieldConfig) => {\n  const { format, dateOnly, utc, outputUTC, singleCustomTimeZone } =\n    parseDateTimeConfig(fieldConfig);\n\n  return utc || (format && outputUTC) ? 'UTC' : dateOnly ? undefined : singleCustomTimeZone;\n};\n\n/**\n * Get a `Date` object given the current value. A stored value without a UTC offset is read in the\n * time zone of the field: UTC with `input_timezone: utc`, the deprecated `picker_utc` or, in a\n * custom format, `output_utc`, which stores the value in UTC; an IANA time zone with\n * `input_timezone` set to one; and the browser’s otherwise. A date without a time is read as is.\n * @param {string | undefined} currentValue Value in the entry draft datastore.\n * @param {DateTimeField} fieldConfig Field configuration.\n * @param {InternalLocaleCode} [locale] Locale of the content the value belongs to, which a value in\n * a custom format is written in with `localize_format: true`.\n * @returns {Date | undefined} Date or `undefined` if invalid.\n */\nexport const getDate = (currentValue, fieldConfig, locale) => {\n  const { format, timeOnly } = parseDateTimeConfig(fieldConfig);\n\n  if (!currentValue) {\n    return undefined;\n  }\n\n  const timeZone = getStoredValueTimeZone(fieldConfig);\n  /** @type {Date | undefined} */\n  let date;\n\n  if (format) {\n    const localeKey = getFormatLocale(fieldConfig, locale);\n\n    if (timeZone === 'UTC' || !timeZone) {\n      // A value stored in the custom format carries no time zone, so it has to be parsed in the\n      // field’s explicitly — otherwise the browser’s local offset is applied and the epoch is wrong\n      const parsed = parseWithFormatFallback({\n        value: currentValue,\n        format,\n        parseAsUTC: timeZone === 'UTC',\n        localeKey,\n      });\n\n      date = parsed.isValid() ? parsed.toDate() : undefined;\n    } else {\n      const wallTime = parseWithFormat(getParser(true), currentValue, format, localeKey);\n\n      date = !wallTime.isValid()\n        ? // The value isn’t in the custom format, e.g. an ISO 8601 value written before the format\n          // was set\n          parseISODate(currentValue, timeZone)\n        : hasOffsetToken(format)\n          ? wallTime.toDate()\n          : getDateInTimeZone(wallTime, timeZone);\n    }\n  } else if (timeOnly) {\n    // Use the current date\n    date = parseISODate(`${new Date().toJSON().split('T')[0]}T${currentValue}`, timeZone);\n  } else {\n    date = parseISODate(currentValue, timeZone);\n  }\n\n  if (isValidDate(date)) {\n    return date;\n  }\n\n  // eslint-disable-next-line no-console\n  console.error('Invalid Date', currentValue);\n\n  return undefined;\n};\n","import { sanitize } from 'isomorphic-dompurify';\nimport { Marked } from 'marked';\nimport { parseEntities } from 'parse-entities';\n\nimport { getOrCreateBounded } from '$lib/services/utils/cache';\n\n/**\n * Remove some inline Markdown syntax from the given string. This covers bold, italic, strikethrough\n * and code. This function does not remove single characters like the `_` prefix in `_redirects`.\n * @param {string} str Original string.\n * @returns {string} Modified string.\n */\nexport const removeMarkdownSyntax = (str) => {\n  let result = str;\n  let changed = true;\n\n  // Keep processing until no more changes are made to handle nested cases\n  while (changed) {\n    const before = result;\n\n    // Process from innermost to outermost by trying single character patterns first\n    result = result.replaceAll(/([_*`~])([^_*`~]+)\\1/g, '$2');\n\n    // Then handle multi-character patterns (like ** or __ or ~~). The delimiter is capped at three\n    // characters: with an unbounded run, a long stretch of mixed delimiters without a closing run,\n    // e.g. `*_*_*_…`, tries every run length against the rest of the string, which takes minutes\n    // on a title of a few dozen kilobytes. A longer run, e.g. `****`, is removed over several\n    // passes of the loop instead.\n    result = result.replaceAll(/([_*`~]{2,3})(.+?)\\1/g, '$2');\n\n    changed = result !== before;\n  }\n\n  return result;\n};\n\n/**\n * Private Markdown parser for {@link stripMarkdown}, which is unaffected by the extensions a site\n * adds to the shared `window.marked` instance, e.g. an async one that makes `parse()` return a\n * `Promise`.\n */\nconst markdownParser = new Marked();\n\n/**\n * Line breaks, thematic breaks and the end tags of block elements, which separate words without any\n * whitespace in HTML, e.g. `<p>First</p><p>Second</p>`.\n */\nconst HTML_BLOCK_BOUNDARY_REGEX = new RegExp(\n  '<(?:br|hr)\\\\b[^>]*>|</(?:address|article|aside|blockquote|caption|dd|details|div|dl|dt|' +\n    'figcaption|figure|footer|h[1-6]|header|li|main|nav|ol|p|pre|section|summary|table|tbody|td|' +\n    'tfoot|th|thead|tr|ul)\\\\s*>',\n  'gi',\n);\n\n/**\n * Cache of {@link stripMarkdown} results, keyed by the original string. A Compute field is resolved\n * again when any field of the entry changes, e.g. on every keystroke in the title, while the\n * Markdown it’s computed from mostly stays the same and is slow to parse once it runs to several\n * kilobytes. It’s large enough to hold the Rich Text values of a long List field, whose summaries\n * are read in order, which would otherwise evict each value before it’s read again.\n * @type {Map<string, string>}\n */\nconst plainTextCache = new Map();\n\n/**\n * Convert the given Markdown or HTML string to plain text by removing the Markdown syntax and HTML\n * tags, e.g. to show a Rich Text field value in a summary. Line breaks are collapsed into spaces.\n * Character references are decoded, so the result can contain markup, e.g. `&lt;img&gt;` becomes\n * `<img>`: it’s only safe as text, never with Svelte’s `@html` tag or `innerHTML`.\n * @param {string} str Original string.\n * @returns {string} Plain text.\n */\nexport const stripMarkdown = (str) =>\n  getOrCreateBounded(\n    plainTextCache,\n    str,\n    () => {\n      const html = /** @type {string} */ (markdownParser.parse(str)).replaceAll(\n        HTML_BLOCK_BOUNDARY_REGEX,\n        '$& ',\n      );\n\n      return parseEntities(sanitize(html, { ALLOWED_TAGS: [] }))\n        .replaceAll(/\\s+/g, ' ')\n        .trim();\n    },\n    100,\n  );\n","import { truncate } from '@sveltia/utils/string';\nimport dayjs from 'dayjs';\nimport dayjsCustomParseFormat from 'dayjs/plugin/customParseFormat';\nimport dayjsLocalizedFormat from 'dayjs/plugin/localizedFormat';\nimport dayjsUTC from 'dayjs/plugin/utc';\n\nimport { customStringTransformationRegistry } from '$lib/services/api/registries';\nimport { slugify } from '$lib/services/common/slug';\nimport { getAdjacentChar } from '$lib/services/common/template/tags';\nimport { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\nimport { getFormatLocale } from '$lib/services/contents/fields/date-time/locales';\nimport {\n  formatInLocale,\n  getParser,\n  parseWithFormatFallback,\n} from '$lib/services/contents/fields/date-time/parse';\nimport { getOrCreate, getOrCreateBounded } from '$lib/services/utils/cache';\nimport { stripMarkdown } from '$lib/services/utils/markdown';\n\n/**\n * @import { InternalLocaleCode, StringTransformation } from '$lib/types/private';\n * @import { DateTimeField, Field, StringTransformer } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} DateTimeTransformationArgs\n * @property {string} format The date format string to use for output.\n * @property {string} [timeZone] The time zone to use (`utc` for UTC, otherwise local).\n */\n\n/**\n * @typedef {object} DefaultTransformationArgs\n * @property {string} defaultValue The default value to return if the input value is falsy.\n */\n\n/**\n * @typedef {object} TernaryTransformationArgs\n * @property {string} truthyValue The value to return if the input value is truthy.\n * @property {string} falsyValue The value to return if the input value is falsy.\n */\n\n/**\n * @typedef {object} TruncateTransformationArgs\n * @property {string} max The maximum length of the string.\n * @property {string} [ellipsis] The string to append if truncation occurs.\n */\n\ndayjs.extend(dayjsCustomParseFormat);\ndayjs.extend(dayjsLocalizedFormat);\ndayjs.extend(dayjsUTC);\n\nconst DATE_ONLY_REGEX = /^\\d{4}-[01]\\d-[0-3]\\d$/;\nconst DATE_PART_REGEX = /T\\d{2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?Z$/;\n\n/**\n * Names of the built-in string transformations, which can’t be used for a custom transformation.\n * `localize` is not a transformation but a flag in a slug template, e.g. `{{title | localize}}`.\n * @see https://sveltiacms.app/en/docs/string-transformations\n */\nexport const BUILTIN_STRING_TRANSFORMATIONS = Object.freeze([\n  'date',\n  'default',\n  'localize',\n  'lower',\n  'plainify',\n  'slugify',\n  'ternary',\n  'truncate',\n  'upper',\n]);\n\n/**\n * Regular expression matching a valid custom transformation name: letters, digits and underscores,\n * not starting with a digit.\n */\nexport const STRING_TRANSFORMATION_NAME_REGEX = /^[A-Za-z_]\\w*$/;\n\n/**\n * Regular expression matching a transformation that isn’t built-in, which may be a custom one, with\n * or without arguments, e.g. `reverse` or `wrap('[', ']')`.\n */\nconst OTHER_TRANSFORMATION_REGEX = new RegExp(\n  `^(?<method>${STRING_TRANSFORMATION_NAME_REGEX.source.slice(1, -1)})(?:\\\\((?<args>.*)\\\\))?$`,\n  's',\n);\n\n/**\n * Regular expression matching an argument of a transformation that isn’t built-in, along with the\n * following comma, if any. A string argument is quoted with single quotes, and like\n * {@link splitTransformations}, a quote only closes the argument before `,` or the end, so it can\n * contain an apostrophe. A numeric argument is not quoted.\n */\nconst OTHER_TRANSFORMATION_ARG_REGEX =\n  /\\s*(?:'(?<string>.*?)'|(?<number>-?\\d+(?:\\.\\d+)?))\\s*(?<separator>,|$)/sy;\n\nconst TRANSFORMATION_PARSERS = Object.entries({\n  date: /^date\\('(?<format>.+?)'(?:,\\s*'(?<timeZone>.+?)')?\\)$/,\n  default: /^default\\('(?<defaultValue>.*?)'\\)$/,\n  ternary: /^ternary\\('(?<truthyValue>.*?)',\\s*'(?<falsyValue>.*?)'\\)$/,\n  truncate: /^truncate\\((?<max>\\d+)(?:,\\s*'(?<ellipsis>.*?)')?\\)$/,\n});\n\n/**\n * Parse the arguments of a transformation that isn’t built-in, e.g. `10, '…'` for `shorten(10,\n * '…')`.\n * @param {string} string Arguments within the parentheses.\n * @returns {(string | number)[] | undefined} Parsed arguments: a string for a quoted argument and a\n * number for an unquoted one. `undefined` if any of the arguments is invalid.\n */\nconst parseOtherTransformationArgs = (string) => {\n  /** @type {(string | number)[]} */\n  const args = [];\n\n  if (!string.trim()) {\n    return args;\n  }\n\n  const regex = new RegExp(OTHER_TRANSFORMATION_ARG_REGEX);\n  /** @type {string | undefined} */\n  let separator;\n\n  do {\n    const groups = regex.exec(string)?.groups;\n\n    if (!groups) {\n      return undefined;\n    }\n\n    args.push(groups.string ?? Number(groups.number));\n    ({ separator } = groups);\n  } while (separator);\n\n  return args;\n};\n\n/**\n * Parse a single transformation string into a structured object.\n * @param {string} transformation The transformation string.\n * @returns {StringTransformation} Parsed transformation.\n */\nconst parseTransformation = (transformation) => {\n  // eslint-disable-next-line no-restricted-syntax\n  for (const [method, regex] of TRANSFORMATION_PARSERS) {\n    const entries = Object.entries(transformation.match(regex)?.groups ?? {});\n\n    if (entries.length) {\n      return {\n        method,\n        args: Object.fromEntries(entries.filter(([, value]) => value !== undefined)),\n      };\n    }\n  }\n\n  const { method, args } = transformation.match(OTHER_TRANSFORMATION_REGEX)?.groups ?? {};\n\n  // A built-in transformation with invalid arguments, e.g. `truncate('a')`, is left unparsed, so it\n  // doesn’t run with arguments it can’t use\n  if (method && !BUILTIN_STRING_TRANSFORMATIONS.includes(method)) {\n    if (args === undefined) {\n      return { method, args: {} };\n    }\n\n    const customArgs = parseOtherTransformationArgs(args);\n\n    if (customArgs) {\n      return { method, args: {}, customArgs };\n    }\n  }\n\n  return { method: transformation, args: {} };\n};\n\n/**\n * Split a string containing a value and transformations at the pipe (`|`) characters, except for\n * those within a quoted transformation argument like `default('Untitled | Draft')`. A single quote\n * only opens an argument after `(` or `,`, and only closes it before `,` or `)`, so an apostrophe\n * within an argument, as in `default('Don't')`, doesn’t throw off the parsing. Only the whitespace\n * next to each quote is looked at, so the string is parsed in linear time.\n * @param {string} string The string to be split.\n * @returns {string[]} Trimmed segments.\n */\nexport const splitTransformations = (string) => {\n  /** @type {string[]} */\n  const segments = [];\n  let segment = '';\n  let quoted = false;\n\n  // Go through the UTF-16 code units, which the quote lookups index into. A surrogate pair is\n  // never a quote or a pipe, so its halves are just added to the segment one after the other\n  for (let index = 0; index < string.length; index += 1) {\n    const char = string[index];\n\n    if (char === \"'\") {\n      if (!quoted && ['(', ','].includes(getAdjacentChar(string, index, -1))) {\n        quoted = true;\n      } else if (quoted && [',', ')'].includes(getAdjacentChar(string, index, 1))) {\n        quoted = false;\n      }\n    }\n\n    if (char === '|' && !quoted) {\n      segments.push(segment.trim());\n      segment = '';\n    } else {\n      segment += char;\n    }\n  }\n\n  segments.push(segment.trim());\n\n  return segments;\n};\n\n/**\n * Cache of parsed placeholders, keyed by the placeholder string. Summary and slug templates are\n * applied to every entry, e.g. on every keystroke of an entry search, but only have a few\n * placeholders, which are parsed once here instead of once per entry.\n * @type {Map<string, { value: string, transformations: StringTransformation[] }>}\n */\nconst parsedTransformationsCache = new Map();\n\n/**\n * Parse a string containing a value and multiple transformations separated by the pipe (`|`)\n * character. The result is cached and shared between callers, so it’s frozen.\n * @param {string} string The string containing a value and transformations.\n * @returns {{ value: string, transformations: StringTransformation[] }} Parsed value and\n * transformation entries.\n */\nexport const parseTransformations = (string) =>\n  getOrCreateBounded(\n    parsedTransformationsCache,\n    string,\n    () => {\n      const [value, ...rawTransformations] = splitTransformations(string.trim());\n\n      return Object.freeze({\n        value,\n        transformations: /** @type {StringTransformation[]} */ (\n          Object.freeze(\n            rawTransformations.map((tf) => {\n              const { method, args, customArgs } = parseTransformation(tf);\n\n              return Object.freeze({\n                method,\n                args: Object.freeze(args),\n                ...(customArgs ? { customArgs: Object.freeze(customArgs) } : {}),\n              });\n            }),\n          )\n        ),\n      });\n    },\n    500,\n  );\n\n/**\n * Transform the input value to its uppercase string representation.\n * @param {any} value The value to be transformed to uppercase.\n * @returns {string} The uppercase string representation of the input value.\n */\nexport const applyUpperCaseTransformation = (value) => String(value ?? '').toUpperCase();\n\n/**\n * Transform the input value to a string and returns it in lowercase.\n * @param {any} value The value to be transformed to lowercase.\n * @returns {string} The lowercase string representation of the input value.\n */\nexport const applyLowerCaseTransformation = (value) => String(value ?? '').toLowerCase();\n\n/**\n * Transform the input value to a formatted string based on the provided format and time zone\n * options. A value other than a `Date` is parsed in the field’s own `format` if it has one,\n * falling back to the default parsing if the value doesn’t match the format. With the field’s\n * `localize_format` option, the value is parsed and formatted in the locale the field writes it in.\n * @param {any} value The input value to be transformed into a date string.\n * @param {DateTimeTransformationArgs} args Transformation arguments.\n * @param {DateTimeField} fieldConfig Field configuration containing date and time settings.\n * @param {InternalLocaleCode} [locale] Locale of the content the value belongs to.\n * @returns {string} The formatted date string if valid, otherwise an empty string.\n */\nexport const applyDateTransformation = (value, { format, timeZone }, fieldConfig, locale) => {\n  const sValue = String(value);\n  const { format: storedFormat, dateOnly, utc } = parseDateTimeConfig(fieldConfig);\n  const localeKey = storedFormat ? getFormatLocale(fieldConfig, locale) : undefined;\n\n  const useUTC =\n    timeZone === 'utc' ||\n    utc ||\n    (dateOnly && !!sValue.match(DATE_ONLY_REGEX)) ||\n    (dateOnly && !!sValue.match(DATE_PART_REGEX));\n\n  const date =\n    // A value in a format like `X` (Unix timestamp) can come as a number from the front matter\n    storedFormat && !(value instanceof Date)\n      ? parseWithFormatFallback({\n          value: sValue,\n          format: storedFormat,\n          parseAsUTC: useUTC,\n          localeKey,\n        })\n      : getParser(useUTC)(sValue);\n\n  if (date.isValid()) {\n    return formatInLocale(date, format, localeKey);\n  }\n\n  return '';\n};\n\n/**\n * Return the string representation of the given value if it is truthy; otherwise, returns the\n * provided default value.\n * @param {any} value The value to evaluate for truthiness.\n * @param {DefaultTransformationArgs} args Transformation arguments.\n * @returns {string} The stringified value or the default value.\n */\nexport const applyDefaultTransformation = (value, { defaultValue }) =>\n  value ? String(value) : defaultValue;\n\n/**\n * Return one of two values based on the truthiness of the input value.\n * @param {any} value The value to evaluate for truthiness.\n * @param {TernaryTransformationArgs} args Transformation arguments.\n * @returns {string} Returns `truthyValue` if `value` is truthy, otherwise returns `falsyValue`.\n */\nexport const ternaryTransformation = (value, { truthyValue, falsyValue }) =>\n  value ? truthyValue : falsyValue;\n\n/**\n * Truncate a string to a specified maximum length and append an ellipsis if truncation occurs.\n * @param {any} value The value to be truncated.\n * @param {TruncateTransformationArgs} args Transformation arguments.\n * @returns {string} The truncated string with ellipsis if applicable.\n */\nexport const applyTruncateTransformation = (value, { max, ellipsis = '…' }) =>\n  truncate(String(value ?? ''), Number(max), { ellipsis });\n\n/**\n * Convert a Markdown or HTML value to plain text. The result can contain markup, e.g. `&lt;img&gt;`\n * becomes `<img>`, so it’s only safe as text; see {@link stripMarkdown}.\n * @param {any} value The value to be converted.\n * @returns {string} The plain text.\n */\nexport const applyPlainifyTransformation = (value) => stripMarkdown(String(value ?? ''));\n\n/**\n * Names of the custom transformations that have failed, keyed by the function, so the error is\n * logged only once for each, rather than for every entry summary or keystroke. A different\n * function, e.g. a fixed one registered under the same name, starts over.\n * @type {WeakMap<StringTransformer, Set<string>>}\n */\nconst failedCustomTransformations = new WeakMap();\n\n/**\n * Apply a custom string transformation registered with `CMS.registerStringTransformation()`. An\n * error thrown by the function, or a Promise returned by it, is logged once per function and\n * name, and the value is returned as is, so a broken transformation doesn’t break the UI.\n * @param {object} args Arguments.\n * @param {string} args.method Transformation name.\n * @param {StringTransformer} args.transform Transformation function.\n * @param {any} args.value Original value to be transformed.\n * @param {readonly (string | number)[]} [args.customArgs] Transformation arguments.\n * @param {string} [args.locale] Locale code of the entry content.\n * @returns {string} Transformed value.\n */\nexport const applyCustomTransformation = ({ method, transform, value, customArgs, locale }) => {\n  try {\n    const result = transform(value, {\n      args: [...(customArgs ?? [])],\n      locale: locale === '_default' ? undefined : locale,\n    });\n\n    // Check for any thenable, not only a native Promise\n    if (typeof (/** @type {any} */ (result)?.then) === 'function') {\n      // Avoid an unhandled rejection\n      /** @type {PromiseLike<any>} */ (result).then(undefined, () => undefined);\n\n      throw new TypeError('The function must return a string, not a Promise');\n    }\n\n    return String(result ?? '');\n  } catch (ex) {\n    const failedNames = getOrCreate(failedCustomTransformations, transform, () => new Set());\n\n    if (!failedNames.has(method)) {\n      failedNames.add(method);\n      // eslint-disable-next-line no-console\n      console.error(\n        `The custom “${method}” string transformation failed. Further errors are not logged:`,\n        ex,\n      );\n    }\n\n    return String(value ?? '');\n  }\n};\n\n/**\n * Apply a single string transformation to the value based on the specified transformation type.\n * @param {object} args Arguments.\n * @param {Field} [args.fieldConfig] Field configuration, used for date transformations.\n * @param {any} args.value Original value to be transformed.\n * @param {StringTransformation} args.transformation Transformation entry.\n * @param {string} [args.locale] BCP 47 language tag passed to the `slugify` transformation and\n * custom transformations.\n * @returns {string} Transformed value.\n * @see https://decapcms.org/docs/summary-strings/\n * @see https://sveltiacms.app/en/docs/string-transformations\n */\nexport const applyTransformation = ({ fieldConfig, value, transformation, locale }) => {\n  const { method, args, customArgs } = transformation;\n\n  switch (method) {\n    case 'upper':\n      return applyUpperCaseTransformation(value);\n    case 'lower':\n      return applyLowerCaseTransformation(value);\n    case 'plainify':\n      return applyPlainifyTransformation(value);\n    case 'slugify':\n      // Don’t fall back to a random UUID for an empty value; the transformation is used in Compute\n      // fields, where a value that changes on every render causes an infinite update loop\n      // @see https://github.com/sveltia/sveltia-cms/issues/946\n      return slugify(String(value ?? ''), { fallback: false, locale });\n    case 'date':\n      return applyDateTransformation(\n        value,\n        /** @type {DateTimeTransformationArgs} */ (args),\n        /** @type {DateTimeField} */ (fieldConfig ?? {}),\n        locale,\n      );\n    case 'default':\n      return applyDefaultTransformation(value, /** @type {DefaultTransformationArgs} */ (args));\n    case 'ternary':\n      return ternaryTransformation(value, /** @type {TernaryTransformationArgs} */ (args));\n    case 'truncate':\n      return applyTruncateTransformation(value, /** @type {TruncateTransformationArgs} */ (args));\n\n    default: {\n      const transform = customStringTransformationRegistry.get(method);\n\n      if (transform) {\n        return applyCustomTransformation({ method, transform, value, customArgs, locale });\n      }\n\n      return String(value);\n    }\n  }\n};\n\n/**\n * Apply string transformations to the value.\n * @param {object} args Arguments.\n * @param {Field} [args.fieldConfig] Field configuration.\n * @param {any} args.value Original value.\n * @param {StringTransformation[]} args.transformations Transformation entries.\n * @param {string} [args.locale] BCP 47 language tag passed to the `slugify` transformation.\n * @returns {string} Transformed value.\n */\nexport const applyTransformations = ({ fieldConfig, value, transformations, locale }) => {\n  transformations.forEach((transformation) => {\n    value = applyTransformation({ fieldConfig, value, transformation, locale });\n  });\n\n  return value;\n};\n","import { memoizeOnSource } from '$lib/services/utils/cache';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * Entry,\n * EntryFolderInfo,\n * } from '$lib/types/private';\n */\n\n/**\n * Whether the entries and assets have been loaded from the backend.\n * @type {{ current: boolean }}\n */\nexport const dataLoaded = createRawState(false);\n\n/**\n * Number of files loaded so far, if the backend reports the loading progress.\n * @type {{ current: number | undefined }}\n */\nexport const dataLoadedProgress = createRawState();\n\n/**\n * @type {{ current: EntryFolderInfo[] }}\n */\nexport const allEntryFolders = createRawState([]);\n\n/**\n * @type {{ current: Entry[] }}\n */\nexport const allEntries = createRawState([]);\n\n/**\n * Index of {@link allEntries} by locale file path, rebuilt when the store is replaced. Each path\n * points to the first entry holding a file there, along with its position in the store.\n */\nconst getEntriesByPath = memoizeOnSource(\n  () => allEntries.current,\n  (entries) => {\n    /** @type {Map<string, { entry: Entry, index: number }>} */\n    const map = new Map();\n\n    entries.forEach((entry, index) => {\n      Object.values(entry.locales).forEach(({ path }) => {\n        if (!map.has(path)) {\n          map.set(path, { entry, index });\n        }\n      });\n    });\n\n    return map;\n  },\n);\n\n/**\n * Find the first entry in {@link allEntries} that has a locale file at any of the given paths. The\n * Editorial Workflow looks up the published version of every unpublished entry this way, once per\n * pull request and once per card on the board, so the store is indexed rather than scanned.\n * @param {Iterable<string>} paths File paths.\n * @returns {Entry | undefined} Entry, or `undefined` if none is found.\n */\nexport const findEntryByPaths = (paths) => {\n  const entriesByPath = getEntriesByPath();\n  /** @type {{ entry: Entry, index: number } | undefined} */\n  let found;\n\n  // The entry that comes first in the store wins, whichever path it was found by\n  [...paths].forEach((path) => {\n    const item = entriesByPath.get(path);\n\n    if (item && (!found || item.index < found.index)) {\n      found = item;\n    }\n  });\n\n  return found?.entry;\n};\n\n/**\n * @type {{ current: Error[] }}\n */\nexport const entryParseErrors = createRawState([]);\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { cmsConfig } from '$lib/services/config';\nimport { allEntryFolders, findEntryByPaths } from '$lib/services/contents';\nimport { getCollection, getValidCollections } from '$lib/services/contents/collection';\nimport { getValidCollectionFiles } from '$lib/services/contents/collection/predicates';\nimport { getLocalePath } from '$lib/services/contents/i18n';\n\n/**\n * @import {\n * Entry,\n * InternalCmsConfig,\n * InternalCollection,\n * InternalCollectionFile,\n * } from '$lib/types/private';\n * @import { CollectionFile } from '$lib/types/public';\n */\n\n/**\n * Get a file in a file/singleton collection by its name.\n * @param {InternalCollection | string} collection Collection or collection name.\n * @param {string} fileName File name.\n * @returns {InternalCollectionFile | undefined} Collection file.\n */\nexport const getCollectionFile = (collection, fileName) => {\n  /** @type {InternalCollection | undefined} */\n  const _collection = typeof collection === 'string' ? getCollection(collection) : collection;\n\n  // The file name may come from the URL, so it may be the name of an `Object.prototype` member\n  if (\n    !_collection ||\n    !('_fileMap' in _collection) ||\n    !Object.hasOwn(_collection._fileMap, fileName)\n  ) {\n    return undefined;\n  }\n\n  return _collection._fileMap[fileName];\n};\n\n/**\n * Look up a collection and, if a file name is given, one of its files.\n * @param {string} collectionName Collection name.\n * @param {string | undefined} fileName File name. Given only for a file/singleton collection.\n * @returns {{ collection: InternalCollection, collectionFile: InternalCollectionFile | undefined }\n * | undefined} Collection and collection file, the latter `undefined` when no file name is given.\n * `undefined` when the collection is not found, or a file name is given but the file is not found,\n * which includes the case where the collection is an entry collection.\n */\nexport const resolveCollectionAndFile = (collectionName, fileName) => {\n  const collection = getCollection(collectionName);\n\n  if (!collection) {\n    return undefined;\n  }\n\n  const collectionFile = fileName ? getCollectionFile(collection, fileName) : undefined;\n\n  if (fileName && !collectionFile) {\n    return undefined;\n  }\n\n  return { collection, collectionFile };\n};\n\n/**\n * Get a human-readable label for a collection file. If the file has a `label` property, it is used;\n * otherwise, the `name` property is used.\n * @param {InternalCollectionFile} file Collection file.\n * @returns {string} File label.\n */\nexport const getCollectionFileLabel = (file) => file.label || file.name;\n\n/**\n * Get a file/singleton collection’s file configurations that matches the given entry. One file can\n * theoretically appear in multiple collections files depending on the configuration, so that the\n * result is an array. A file is matched by the path of any locale of the entry, as the file of the\n * default locale may not exist when the locales are stored in separate files.\n * @param {InternalCollection} collection Collection.\n * @param {Entry} entry Entry.\n * @returns {InternalCollectionFile[]} Collection files.\n */\nexport const getCollectionFilesByEntry = (collection, entry) => {\n  if (!('_fileMap' in collection)) {\n    // It’s an entry collection\n    return [];\n  }\n\n  return Object.values(collection._fileMap).filter(({ file, _file, _i18n }) =>\n    Object.entries(entry.locales).some(\n      ([locale, { path }]) =>\n        path ===\n        (locale === _i18n.defaultLocale\n          ? _file.fullPath\n          : getLocalePath({ _i18n, locale, path: stripSlashes(file) })),\n    ),\n  );\n};\n\n/**\n * Get a file/singleton collection entry that matches the given collection name and file name.\n * @param {string} collectionName Collection name.\n * @param {string} fileName Collection file name.\n * @returns {Entry | undefined} File.\n * @see https://decapcms.org/docs/collection-file/\n * @see https://sveltiacms.app/en/docs/collections/files\n */\nexport const getCollectionFileEntry = (collectionName, fileName) => {\n  // Pre-find the valid file paths from `allEntryFolders` to avoid calling\n  // `getAssociatedCollections()` per entry, which iterates `allEntryFolders` internally for each\n  // entry.\n  const folderInfo = allEntryFolders.current.find(\n    ({ collectionName: cn, fileName: fn }) => cn === collectionName && fn === fileName,\n  );\n\n  if (!folderInfo?.filePathMap) {\n    return undefined;\n  }\n\n  // Relation fields look this up for every option list they build, so the entries are found\n  // through the path index rather than by going through all of them\n  return findEntryByPaths(Object.values(folderInfo.filePathMap));\n};\n\n/**\n * Get the index of a collection file with the given name.\n * @param {string | undefined} collectionName Collection name.\n * @param {string | undefined} fileName Collection file name.\n * @returns {number} Index.\n */\nexport const getCollectionFileIndex = (collectionName, fileName) => {\n  if (collectionName && fileName) {\n    const { collections, singletons } = /** @type {InternalCmsConfig} */ (cmsConfig.current);\n\n    if (collectionName === '_singletons') {\n      if (Array.isArray(singletons)) {\n        return getValidCollectionFiles(singletons).findIndex((file) => file.name === fileName);\n      }\n\n      return -1;\n    }\n\n    const collection = getValidCollections({ collections }).find(\n      ({ name }) => name === collectionName,\n    );\n\n    if (collection && 'files' in collection) {\n      return collection.files.findIndex(({ name }) => name === fileName);\n    }\n  }\n\n  return -1;\n};\n","/**\n * Name of the field an entry is identified by when the `identifier_field` option isn’t set. The\n * default slug template is `{{title}}` accordingly.\n */\nexport const DEFAULT_IDENTIFIER_FIELD = 'title';\n\n/**\n * Get the name of the field an entry collection identifies its entries by: the `identifier_field`\n * option, or `title` by default.\n * @param {{ identifier_field?: string } | undefined} collection Entry collection, or its raw\n * configuration. `undefined` for anything that isn’t an entry collection.\n * @returns {string} Field name.\n * @see https://decapcms.org/docs/configuration-options/#identifier_field\n */\nexport const getIdentifierFieldName = (collection) =>\n  collection?.identifier_field ?? DEFAULT_IDENTIFIER_FIELD;\n","import { escapeRegExp } from '@sveltia/utils/string';\n\n/**\n * @import { FlattenedEntryContent } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Our internal representation of an entry is a flat map from key path to value, so anything that\n * needs the values *under* a key path — a list’s items, an object’s subfields, a multi-value\n * field’s entries — has to look them up by key path shape.\n *\n * Doing that with a scan is O(keys) per field, and the editor renders one component per field, so a\n * large entry ends up O(fields × keys) on every keystroke. The helpers here index each value map\n * once instead, keyed by the map object itself: the draft hands out a fresh snapshot per update, so\n * an index is built at most once per keystroke and shared by every field reading from it, then\n * garbage-collected with the snapshot.\n *\n * An index is therefore only valid while the map it was built from is left alone. A caller reading\n * a map it also mutates — a draft’s live content rather than a snapshot of it — has to pass the\n * `live` option, or it would keep getting the key paths the map had the first time it was read.\n */\n\n/**\n * Turn a key path that may contain `*` wildcards into a regular expression source matching its\n * concrete key paths, where each wildcard stands for a list item index, e.g. `list\\.\\d+\\.title`\n * for `list.*.title`. The source carries no anchors, so callers can add their own.\n * @param {FieldKeyPath} keyPath Key path that may contain wildcards.\n * @returns {string} Regular expression source.\n */\nexport const getWildcardKeyPathPattern = (keyPath) =>\n  escapeRegExp(keyPath).replaceAll('\\\\*', '\\\\d+');\n\n/**\n * Check whether a key path is the given root key path or sits under it. A plain `startsWith()`\n * check isn’t enough, as it would also match a sibling whose name merely begins with the root’s,\n * e.g. `tags` or `tagline` for `tag`.\n * @param {FieldKeyPath} keyPath Key path to check, e.g. `authors.0.name`.\n * @param {FieldKeyPath} root Root key path, e.g. `authors`.\n * @returns {boolean} Whether `keyPath` is `root` or one of its descendants.\n */\nexport const isKeyPathWithin = (keyPath, root) =>\n  keyPath === root || keyPath.startsWith(`${root}.`);\n\n/**\n * Cache of key path indexes, keyed by the value map object. Each entry is the map’s key paths\n * sorted lexicographically and paired with their original position, so {@link getKeysByPrefix} can\n * binary-search a prefix range and still hand the matches back in insertion order.\n * @type {WeakMap<FlattenedEntryContent, [FieldKeyPath, number][]>}\n */\nconst sortedKeyCacheMap = new WeakMap();\n\n/**\n * Get the value map’s key paths sorted lexicographically, each paired with its original position.\n * @param {FlattenedEntryContent} valueMap Flattened entry content.\n * @returns {[FieldKeyPath, number][]} Sorted key path/position pairs.\n */\nconst getSortedKeys = (valueMap) => {\n  let sorted = sortedKeyCacheMap.get(valueMap);\n\n  if (!sorted) {\n    sorted = Object.keys(valueMap)\n      .map((key, index) => /** @type {[FieldKeyPath, number]} */ ([key, index]))\n      // Object keys are unique, so the two arguments are never equal\n      .sort(([a], [b]) => (a < b ? -1 : 1));\n\n    sortedKeyCacheMap.set(valueMap, sorted);\n  }\n\n  return sorted;\n};\n\n/**\n * Get the key paths starting with the given prefix, in the value map’s own (insertion) order.\n *\n * Lexicographic order puts every matching key in one contiguous run, so the first one can be found\n * by binary search; the matches are then restored to insertion order, which is what callers mean by\n * the “first” field under a key path.\n * @param {FlattenedEntryContent} valueMap Flattened entry content.\n * @param {string} prefix Key path prefix, e.g. `authors.0.`.\n * @param {object} [options] Options.\n * @param {boolean} [options.live] Whether the value map may be mutated after this call, in which\n * case the key paths are scanned instead of being read from — and memoized in — the index.\n * @returns {FieldKeyPath[]} Matching key paths.\n */\nexport const getKeysByPrefix = (valueMap, prefix, { live = false } = {}) => {\n  if (live) {\n    return Object.keys(valueMap).filter((key) => key.startsWith(prefix));\n  }\n\n  const sorted = getSortedKeys(valueMap);\n  let low = 0;\n  let high = sorted.length;\n\n  // Find the leftmost key that isn’t ordered before the prefix\n  while (low < high) {\n    const mid = Math.floor((low + high) / 2);\n\n    if (sorted[mid][0] < prefix) {\n      low = mid + 1;\n    } else {\n      high = mid;\n    }\n  }\n\n  /** @type {[FieldKeyPath, number][]} */\n  const matches = [];\n\n  for (let i = low; i < sorted.length && sorted[i][0].startsWith(prefix); i += 1) {\n    matches.push(sorted[i]);\n  }\n\n  return matches.sort(([, a], [, b]) => a - b).map(([key]) => key);\n};\n\n/**\n * Regular expression to match the index suffix of a list item key path, e.g. `.1` in `tags.1` or\n * `blocks.0.images.1`, but not in `blocks.0.title`.\n */\nexport const ITEM_INDEX_SUFFIX_REGEX = /\\.\\d+$/;\n\n/**\n * Regular expression to split a list item key path into its parent key path and item index, e.g.\n * `authors.0` into `authors` and `0`. The parent is matched greedily, so `authors.0.tags.2` yields\n * `authors.0.tags`.\n */\nconst LIST_ITEM_KEY_REGEX = /^(?<parent>.+)\\.\\d+$/;\n/**\n * Cache of list item key paths grouped by parent key path, keyed by the value map object.\n * @type {WeakMap<FlattenedEntryContent, Map<FieldKeyPath, FieldKeyPath[]>>}\n */\nconst listItemKeyCacheMap = new WeakMap();\n\n/**\n * Get the key paths of the direct list items under the given key path, in value map order.\n *\n * This is the shape every multi-value field stores its values in — a List field’s items, but also a\n * multiple Relation or Select field — so the same index serves all of them.\n * @param {FlattenedEntryContent} valueMap Flattened entry content.\n * @param {FieldKeyPath} keyPath Key path of the list field.\n * @param {object} [options] Options.\n * @param {boolean} [options.live] Whether the value map may be mutated after this call, in which\n * case the key paths are scanned instead of being read from — and memoized in — the index.\n * @returns {FieldKeyPath[]} Item key paths, e.g. `['authors.0', 'authors.1']`.\n */\nexport const getListItemKeys = (valueMap, keyPath, { live = false } = {}) => {\n  if (live) {\n    return Object.keys(valueMap).filter(\n      (key) => key.match(LIST_ITEM_KEY_REGEX)?.groups?.parent === keyPath,\n    );\n  }\n\n  let index = listItemKeyCacheMap.get(valueMap);\n\n  if (!index) {\n    index = new Map();\n\n    Object.keys(valueMap).forEach((key) => {\n      const { parent } = key.match(LIST_ITEM_KEY_REGEX)?.groups ?? {};\n\n      if (parent === undefined) {\n        return;\n      }\n\n      const keys = /** @type {Map<FieldKeyPath, FieldKeyPath[]>} */ (index).get(parent);\n\n      if (keys) {\n        keys.push(key);\n      } else {\n        /** @type {Map<FieldKeyPath, FieldKeyPath[]>} */ (index).set(parent, [key]);\n      }\n    });\n\n    listItemKeyCacheMap.set(valueMap, index);\n  }\n\n  return index.get(keyPath) ?? [];\n};\n","function isBuffer (obj) {\n  return obj &&\n    obj.constructor &&\n    (typeof obj.constructor.isBuffer === 'function') &&\n    obj.constructor.isBuffer(obj)\n}\n\nfunction keyIdentity (key) {\n  return key\n}\n\nexport function flatten (target, opts) {\n  opts = opts || {}\n\n  const delimiter = opts.delimiter || '.'\n  const maxDepth = opts.maxDepth\n  const transformKey = opts.transformKey || keyIdentity\n  const output = {}\n\n  function step (object, prev, currentDepth) {\n    currentDepth = currentDepth || 1\n    Object.keys(object).forEach(function (key) {\n      const value = object[key]\n      const isarray = opts.safe && Array.isArray(value)\n      const type = Object.prototype.toString.call(value)\n      const isbuffer = isBuffer(value)\n      const isobject = (\n        type === '[object Object]' ||\n        type === '[object Array]'\n      )\n\n      const newKey = prev\n        ? prev + delimiter + transformKey(key)\n        : transformKey(key)\n\n      if (!isarray && !isbuffer && isobject && Object.keys(value).length &&\n        (!opts.maxDepth || currentDepth < maxDepth)) {\n        return step(value, newKey, currentDepth + 1)\n      }\n\n      output[newKey] = value\n    })\n  }\n\n  step(target)\n\n  return output\n}\n\nexport function unflatten (target, opts) {\n  opts = opts || {}\n\n  const delimiter = opts.delimiter || '.'\n  const overwrite = opts.overwrite || false\n  const transformKey = opts.transformKey || keyIdentity\n  const result = {}\n\n  const isbuffer = isBuffer(target)\n  if (isbuffer || Object.prototype.toString.call(target) !== '[object Object]') {\n    return target\n  }\n\n  // safely ensure that the key is\n  // an integer.\n  function getkey (key) {\n    const parsedKey = Number(key)\n\n    return (\n      isNaN(parsedKey) ||\n      key.indexOf('.') !== -1 ||\n      opts.object\n    )\n      ? key\n      : parsedKey\n  }\n\n  function addKeys (keyPrefix, recipient, target) {\n    return Object.keys(target).reduce(function (result, key) {\n      result[keyPrefix + delimiter + key] = target[key]\n\n      return result\n    }, recipient)\n  }\n\n  function isEmpty (val) {\n    const type = Object.prototype.toString.call(val)\n    const isArray = type === '[object Array]'\n    const isObject = type === '[object Object]'\n\n    if (!val) {\n      return true\n    } else if (isArray) {\n      return !val.length\n    } else if (isObject) {\n      return !Object.keys(val).length\n    }\n  }\n\n  target = Object.keys(target).reduce(function (result, key) {\n    const type = Object.prototype.toString.call(target[key])\n    const isObject = (type === '[object Object]' || type === '[object Array]')\n    if (!isObject || isEmpty(target[key])) {\n      result[key] = target[key]\n      return result\n    } else {\n      return addKeys(\n        key,\n        result,\n        flatten(target[key], opts)\n      )\n    }\n  }, {})\n\n  Object.keys(target).forEach(function (key) {\n    const split = key.split(delimiter).map(transformKey)\n    let key1 = getkey(split.shift())\n    let key2 = getkey(split[0])\n    let recipient = result\n\n    while (key2 !== undefined) {\n      if (key1 === '__proto__') {\n        return\n      }\n\n      const type = Object.prototype.toString.call(recipient[key1])\n      const isobject = (\n        type === '[object Object]' ||\n        type === '[object Array]'\n      )\n\n      // do not write over falsey, non-undefined values if overwrite is false\n      if (!overwrite && !isobject && typeof recipient[key1] !== 'undefined') {\n        return\n      }\n\n      if ((overwrite && !isobject) || (!overwrite && recipient[key1] == null)) {\n        recipient[key1] = (\n          typeof key2 === 'number' &&\n          !opts.object\n            ? []\n            : {}\n        )\n      }\n\n      recipient = recipient[key1]\n      if (split.length > 0) {\n        key1 = getkey(split.shift())\n        key2 = getkey(split[0])\n      }\n    }\n\n    // unflatten again for 'messy objects'\n    recipient[key1] = unflatten(target[key], opts)\n  })\n\n  return result\n}\n","import { isObject } from '@sveltia/utils/object';\nimport { compare } from '@sveltia/utils/string';\nimport { unflatten } from 'flat';\n\n/**\n * Character that replaces a dot in an object key when the key becomes a key path segment, so that\n * a key like `example.com`, which a KeyValue field or any data the configuration doesn’t cover can\n * hold, isn’t split into nested objects on save. A Private Use Area character is unlikely to appear\n * in a key, and it leaves the dot as the only key path delimiter, so a key path can still be split\n * with `.` and its segments matched with `[^.]`. The UI only shows unescaped keys.\n */\nconst ESCAPED_DOT = '\\uE000';\n/**\n * Character that precedes a literal {@link ESCAPED_DOT} or itself in an escaped key segment, so any\n * key round-trips unchanged.\n */\nconst ESCAPE_CHAR = '\\uE001';\n/**\n * Regular expression matching the characters to escape in a key segment.\n */\nconst ESCAPE_REGEX = /[.\\uE000\\uE001]/g;\n/**\n * Regular expression matching an escape sequence in a key segment.\n */\nconst UNESCAPE_REGEX = /\\uE001([\\uE000\\uE001])|\\uE000/g;\n/**\n * Regular expression testing whether a key segment or path holds an escape sequence.\n */\nconst ESCAPED_KEY_REGEX = /[\\uE000\\uE001]/;\n/**\n * Prefix temporarily added to a key segment that {@link unflattenKeys} must keep as a string key.\n * A NUL character can’t start a list index, and a key starting with it is not a number.\n */\nconst STRING_KEY_PREFIX = '\\u0000';\n/**\n * Regular expression matching a key segment that is a list index.\n */\nconst INDEX_KEY_REGEX = /^(?:0|[1-9]\\d*)$/;\n/**\n * Check whether the given key segment is not a list index but still parsed as a number by the\n * `flat` library, e.g. an empty string or `01`.\n * @param {string} key Key segment.\n * @returns {boolean} Result.\n */\nconst isNumericStringKey = (key) => !Number.isNaN(Number(key)) && !INDEX_KEY_REGEX.test(key);\n/**\n * Add {@link STRING_KEY_PREFIX} to the given key segment if it’s a numeric string key.\n * @param {string} key Key segment.\n * @returns {string} Key segment.\n */\nconst prefixStringKey = (key) => (isNumericStringKey(key) ? `${STRING_KEY_PREFIX}${key}` : key);\n\n/**\n * Check whether the given value is a plain object: an object created with an object literal or\n * `Object.create(null)`, not an array or a class instance such as a `Date` or a `TomlDate`.\n * @param {any} value Value.\n * @returns {value is Record<string, any>} Result.\n */\nexport const isPlainObject = (value) =>\n  isObject(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value));\n\n/**\n * Remove {@link STRING_KEY_PREFIX} from the object keys in the given value, recursively.\n * @param {any} value Value unflattened with prefixed key segments.\n * @returns {any} Value with the original keys. Arrays are updated in place, while plain objects are\n * rebuilt to keep their key order.\n */\nconst restoreStringKeys = (value) => {\n  if (Array.isArray(value)) {\n    value.forEach((item, index) => {\n      value[index] = restoreStringKeys(item);\n    });\n\n    return value;\n  }\n\n  // Leave class instances, such as a `Date`, as they are\n  if (isPlainObject(value)) {\n    return Object.fromEntries(\n      Object.entries(value).map(([key, val]) => [\n        key.startsWith(STRING_KEY_PREFIX) ? key.slice(STRING_KEY_PREFIX.length) : key,\n        restoreStringKeys(val),\n      ]),\n    );\n  }\n\n  return value;\n};\n\n/**\n * Escape an object key to be used as a key path segment, so a dot in it isn’t taken as a delimiter.\n * @param {string} key Object key, e.g. `example.com`.\n * @returns {string} Key path segment without any dot.\n */\nexport const escapeKeySegment = (key) =>\n  // Testing first is faster than always replacing, as hardly any key needs escaping\n  key.includes('.') || ESCAPED_KEY_REGEX.test(key)\n    ? key.replace(ESCAPE_REGEX, (char) => (char === '.' ? ESCAPED_DOT : `${ESCAPE_CHAR}${char}`))\n    : key;\n\n/**\n * Restore an object key from a key path segment escaped with {@link escapeKeySegment}.\n * @param {string} segment Key path segment.\n * @returns {string} Object key.\n */\nexport const unescapeKeySegment = (segment) =>\n  ESCAPED_KEY_REGEX.test(segment)\n    ? segment.replace(UNESCAPE_REGEX, (_match, char) => char ?? '.')\n    : segment;\n\n/**\n * Check whether the given value is a plain object or array with any key, which the `flat` library\n * flattens itself when it finds one in a map to unflatten.\n * @param {any} value Value.\n * @returns {boolean} Result.\n */\nconst isNonEmptyCollection = (value) =>\n  ['[object Object]', '[object Array]'].includes(Object.prototype.toString.call(value)) &&\n  !!Object.keys(value).length;\n\n/**\n * Check whether the given value is a plain object, not an array, with a key that looks like a list\n * index, e.g. `{ \"2024\": \"a\" }`. A key path doesn’t tell an object key from a list index, so the\n * `flat` library would unflatten the object into an array.\n * @param {any} value Value.\n * @returns {boolean} Result.\n */\nconst hasIndexLikeKey = (value) =>\n  Object.prototype.toString.call(value) === '[object Object]' &&\n  Object.keys(value).some((key) => INDEX_KEY_REGEX.test(key));\n\n/**\n * Check whether the given flattened map holds a property of the object at the given key path whose\n * key looks like a list index, e.g. `years.2024` for `years`. Unless the map also holds a\n * placeholder at the key path, as {@link flattenKeys} adds, the object would be unflattened into an\n * array.\n * @param {Record<string, any>} map Flattened map.\n * @param {string} keyPath Key path of the object.\n * @returns {boolean} Result.\n */\nexport const hasIndexLikeChildKey = (map, keyPath) => {\n  const prefix = `${keyPath}.`;\n\n  return Object.keys(map).some(\n    (key) => key.startsWith(prefix) && INDEX_KEY_REGEX.test(key.slice(prefix.length).split('.')[0]),\n  );\n};\n\n/**\n * Flatten an object or array into a map of dot-notated key paths, like the `flat` library does,\n * escaping every object key with {@link escapeKeySegment}, so that {@link unflattenKeys} restores\n * the same structure even if a key contains a dot.\n *\n * A plain object with a key that looks like a list index, e.g. `{ \"2024\": \"a\" }`, also gets an\n * empty object at its own key path, ahead of its properties, e.g. `years: {}` before `years.2024`.\n * When unflattening, the placeholder makes the parent an object rather than an array, while the key\n * paths stay the same, so the value can still be found by the key path of a field named `2024`.\n * @param {Record<string, any> | any[]} value Object or array to flatten.\n * @param {string} [prefix] Key path to prepend to every key path, e.g. `list.0`. It must be escaped\n * already, if needed. An empty value is then stored at the prefix itself, as `flatten()` does with\n * `{ [prefix]: value }`.\n * @returns {Record<string, any>} Flattened map.\n */\nexport const flattenKeys = (value, prefix) => {\n  /** @type {Record<string, any>} */\n  const map = {};\n\n  /**\n   * Add the properties of an object or array to the map.\n   * @param {Record<string, any> | any[]} object Object or array.\n   * @param {string} [parentKeyPath] Key path of the object or array.\n   */\n  const step = (object, parentKeyPath) => {\n    if (parentKeyPath !== undefined && hasIndexLikeKey(object)) {\n      map[parentKeyPath] = {};\n    }\n\n    Object.entries(object).forEach(([key, val]) => {\n      const segment = escapeKeySegment(key);\n      const keyPath = parentKeyPath === undefined ? segment : `${parentKeyPath}.${segment}`;\n\n      if (isNonEmptyCollection(val)) {\n        step(val, keyPath);\n      } else {\n        map[keyPath] = val;\n      }\n    });\n  };\n\n  if (isNonEmptyCollection(value)) {\n    step(value, prefix);\n  } else if (prefix !== undefined) {\n    map[prefix] = value;\n  }\n\n  return map;\n};\n\n/**\n * Transform a key path segment while unflattening: unescape it, then add {@link STRING_KEY_PREFIX}\n * if it’s a numeric string key.\n * @param {string} segment Key path segment.\n * @returns {string} Transformed segment.\n */\nconst transformSegment = (segment) => prefixStringKey(unescapeKeySegment(segment));\n\n/**\n * Unflatten a map of dot-notated keys with the `flat` library, while keeping every key segment that\n * isn’t a list index as a string key, and restoring the keys escaped with {@link escapeKeySegment}.\n *\n * The library turns any segment that `Number()` can parse into a number, so an empty key, which a\n * KeyValue field can hold, becomes `0`, and a key like `01` becomes `1`, which also makes an array\n * out of a new parent object. Such segments are prefixed while unflattening, then restored. A key\n * that looks like a list index, e.g. `2024`, is a list index unless the map holds an empty object\n * at the parent key path first, as {@link flattenKeys} adds for an object with such a key.\n * @param {Record<string, any>} map Map of dot-notated keys.\n * @returns {Record<string, any>} Unflattened map.\n * @see https://github.com/hughsk/flat/issues/103\n */\nexport const unflattenKeys = (map) => {\n  const entries = Object.entries(map);\n\n  // The library flattens a nested object or array value itself, without escaping its keys, and\n  // would apply the transformation below to them. Flatten it here instead, at the same position\n  if (entries.some(([, value]) => isNonEmptyCollection(value))) {\n    return unflattenKeys(\n      Object.fromEntries(\n        entries.flatMap(([key, value]) =>\n          isNonEmptyCollection(value) ? Object.entries(flattenKeys(value, key)) : [[key, value]],\n        ),\n      ),\n    );\n  }\n\n  if (\n    !entries.some(([key]) => ESCAPED_KEY_REGEX.test(key) || key.split('.').some(isNumericStringKey))\n  ) {\n    return unflatten(map);\n  }\n\n  return restoreStringKeys(unflatten(map, { transformKey: transformSegment }));\n};\n\n/**\n * Unflatten a map of dot-notated keys, sorting the keys first so that a parent key always precedes\n * its own children.\n *\n * A map may hold an empty object or array at a key that also has children, as a placeholder for the\n * value the children make up. The `flat` library fills such a placeholder in from the children, but\n * only when it comes first; encountered last, it overwrites everything below it and the children\n * are silently lost. A parent key is a prefix of its children, hence shorter, so sorting puts it\n * first. The comparison is numeric, so indexed keys are ordered `2` before `10` rather than\n * lexicographically.\n * @param {Record<string, any> | null | undefined} map Map of dot-notated keys. A nullish value is\n * passed through, just like the `flat` library does.\n * @returns {Record<string, any>} Unflattened map.\n */\nexport const unflattenMap = (map) =>\n  map\n    ? unflattenKeys(Object.fromEntries(Object.entries(map).sort(([a], [b]) => compare(a, b))))\n    : unflatten(map);\n\n/**\n * Check whether a value is empty, such as `undefined`, `null`, an empty string, an empty array, or\n * an empty object.\n * @param {any} value Value to check.\n * @returns {boolean} Whether the value is empty. An array or object holding only empty values is\n * not empty. Only a plain object counts as an object, as a `Date`, including a `TomlDate`, is an\n * object without any keys.\n */\nexport const isValueEmpty = (value) =>\n  // Don’t use `!value` as `false` and `0` are valid values\n  value === undefined ||\n  value === null ||\n  value === '' ||\n  (Array.isArray(value) && !value.length) ||\n  (isPlainObject(value) && !Object.keys(value).length);\n","import { isObject } from '@sveltia/utils/object';\n\nimport { getKeysByPrefix, isKeyPathWithin } from '$lib/services/contents/entry/key-paths';\nimport { flattenKeys, unflattenMap } from '$lib/services/utils/object';\n\n/**\n * @import { FlattenedEntryContent } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Check whether the value is an empty object or array, which a field holding a non-primitive value\n * stores at its own key path as a placeholder for the value its children make up.\n *\n * The placeholder is not redundant: `unflatten()` infers an array from numeric key segments, so it\n * is the placeholder that tells an object with the keys `0` and `1` apart from a two-item array. It\n * also keeps the field visible to validation when it holds no children at all.\n * @param {any} value Value to check.\n * @returns {boolean} Result.\n */\nexport const isPlaceholder = (value) =>\n  (Array.isArray(value) && !value.length) || (isObject(value) && !Object.keys(value).length);\n\n/**\n * Build the flat entries for a non-primitive value stored at the given key path: the placeholder\n * first, then one entry per leaf.\n *\n * The placeholder has to come first. `unflatten()` fills it in from the children when it is\n * encountered before them, but lets it overwrite them when it comes last.\n * @param {FieldKeyPath} keyPath Key path of the field.\n * @param {any[] | Record<string, any>} value Value to store.\n * @returns {FlattenedEntryContent} Flat entries.\n */\nexport const getSubtreeEntries = (keyPath, value) => ({\n  [keyPath]: Array.isArray(value) ? [] : {},\n  // Escape the object keys, so a key with a dot, e.g. in a KeyValue field in a list item, isn’t\n  // split into nested objects on save\n  ...flattenKeys(value, keyPath),\n});\n\n/**\n * Assemble the non-primitive value stored under the given key path from its child key paths.\n * @param {FlattenedEntryContent} valueMap Flattened entry content.\n * @param {FieldKeyPath} keyPath Key path of the field.\n * @param {object} [options] Options.\n * @param {boolean} [options.live] Whether the value map may be mutated after this call. See\n * {@link getKeysByPrefix}.\n * @returns {any} Assembled value, or `undefined` if the key path has no children.\n */\nexport const getSubtree = (valueMap, keyPath, { live = false } = {}) => {\n  const keys = getKeysByPrefix(valueMap, `${keyPath}.`, { live });\n\n  if (!keys.length) {\n    return undefined;\n  }\n\n  // Wrap everything under a single root key, because `unflatten()` only builds an array from\n  // numeric key segments when they are nested, not when they are at the top level\n  const entries = keys.map((key) => [`_${key.slice(keyPath.length)}`, valueMap[key]]);\n  const placeholder = valueMap[keyPath];\n\n  if (isPlaceholder(placeholder)) {\n    entries.push(['_', placeholder]);\n  }\n\n  return unflattenMap(Object.fromEntries(entries))._;\n};\n\n/**\n * What {@link getMemoizedSubtree} last built, and from what.\n * @typedef {object} SubtreeMemo\n * @property {FieldKeyPath} [keyPath] Key path of the field.\n * @property {FieldKeyPath[]} [keys] Child key paths.\n * @property {any[]} [values] Values of the child key paths and the field’s own key path, in that\n * order, with an object or array replaced with its kind, as {@link getSubtree} fills a placeholder\n * in place.\n * @property {any} [subtree] Assembled value.\n */\n\n/**\n * Get a value of the given key path that can be compared across calls: an object or array, such as\n * a placeholder, is replaced with its kind.\n * @param {any} value Value.\n * @returns {any} Comparable value.\n */\nconst getComparableValue = (value) =>\n  value !== null && typeof value === 'object' ? (Array.isArray(value) ? '\\0[]' : '\\0{}') : value;\n\n/**\n * Same as {@link getSubtree}, but hands back the value assembled last time, as the same object, if\n * nothing under the key path has changed since. A List field’s editor and preview read the items\n * from the value map snapshot, which is replaced whenever any value in the entry changes, e.g. on\n * every keystroke in another field; assembling the items again each time is the bulk of the work in\n * a long entry, and a new object would make everything that reads them update as well.\n * @param {SubtreeMemo} memo Object holding what was built last time, kept by the caller and updated\n * in place.\n * @param {FlattenedEntryContent} valueMap Flattened entry content. A snapshot, as with\n * {@link getSubtree} without the `live` option.\n * @param {FieldKeyPath} keyPath Key path of the field.\n * @returns {any} Assembled value, or `undefined` if the key path has no children.\n */\nexport const getMemoizedSubtree = (memo, valueMap, keyPath) => {\n  const keys = getKeysByPrefix(valueMap, `${keyPath}.`);\n  const values = [...keys, keyPath].map((key) => getComparableValue(valueMap[key]));\n  // The key paths and values are set along with the key path\n  const lastKeys = /** @type {FieldKeyPath[]} */ (memo.keys);\n  const lastValues = /** @type {any[]} */ (memo.values);\n\n  if (\n    memo.keyPath === keyPath &&\n    lastKeys.length === keys.length &&\n    keys.every((key, index) => key === lastKeys[index]) &&\n    values.every((value, index) => value === lastValues[index])\n  ) {\n    return memo.subtree;\n  }\n\n  Object.assign(memo, { keyPath, keys, values, subtree: getSubtree(valueMap, keyPath) });\n\n  return memo.subtree;\n};\n\n/**\n * Delete the value stored at the given key path along with everything below it. The map is modified\n * in place.\n * @param {FlattenedEntryContent} valueMap Flattened entry content.\n * @param {FieldKeyPath} keyPath Key path of the field.\n */\nexport const deleteSubtree = (valueMap, keyPath) => {\n  Object.keys(valueMap).forEach((key) => {\n    if (isKeyPathWithin(key, keyPath)) {\n      delete valueMap[key];\n    }\n  });\n};\n\n/**\n * Replace the non-primitive value stored at the given key path. The existing subtree is dropped\n * first, so that keys the new value doesn’t have don’t linger. The map is modified in place.\n * @param {FlattenedEntryContent} valueMap Flattened entry content.\n * @param {FieldKeyPath} keyPath Key path of the field.\n * @param {any[] | Record<string, any>} value Value to store.\n */\nexport const setSubtree = (valueMap, keyPath, value) => {\n  deleteSubtree(valueMap, keyPath);\n  Object.assign(valueMap, getSubtreeEntries(keyPath, value));\n};\n","import { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { InlinePatternOptions, ResolvedEditorComponentDefinition } from '$lib/types/private';\n * @import {\n * CustomEditorComponentDefinition,\n * InlineEditorComponentDefinition,\n * } from '$lib/types/public';\n */\n\n/**\n * Check if the given component definition is a pattern-based inline component, compatible with\n * Decap CMS, which has the `type` option set to `inline`.\n * @param {{ type?: string } | CustomEditorComponentDefinition | undefined} definition Definition\n * passed to the `CMS.registerEditorComponent()` API.\n * @returns {definition is InlineEditorComponentDefinition} Result.\n */\nexport const isInlinePatternComponent = (definition) =>\n  !!definition && 'type' in definition && definition.type === 'inline';\n\n/**\n * Get the pattern of an inline component as it’s matched within a paragraph: without a leading `^`,\n * which Decap CMS ignores as well, and without the `g` and `y` flags.\n * @param {RegExp} pattern Pattern given in the definition.\n * @returns {RegExp} Pattern.\n */\nexport const getInlinePattern = ({ source, flags }) =>\n  new RegExp(source.startsWith('^') ? source.slice(1) : source, flags.replace(/[gy]/g, ''));\n\n/**\n * Convert a pattern-based inline component definition to the shape of a field-based one, so the\n * editor and the preview can handle it like any other component: it has no fields, `fromInline`\n * and `toInline` take the place of `fromBlock` and `toBlock`, and the options the editor handles\n * on its own are kept in `inlinePattern`. Decap CMS falls back to `fromBlock` and `toBlock` if the\n * inline counterparts are missing, and so does this. The `trigger` option, which is the text the\n * instances start with, is moved there too, as it would otherwise be taken for the toolbar UI.\n * @param {InlineEditorComponentDefinition} definition Definition passed to the\n * `CMS.registerEditorComponent()` API.\n * @returns {ResolvedEditorComponentDefinition} Resolved definition, with the same `id` and `label`.\n */\nexport const resolveInlinePatternComponent = (definition) => {\n  const { id, label, icon, pattern, trigger, toPreview, onInsert, onEdit } = definition;\n  // Field-based options a definition may have anyway\n  const { fromBlock, toBlock } = /** @type {Record<string, any>} */ (definition);\n  const fromInline = definition.fromInline ?? fromBlock;\n  const toInline = definition.toInline ?? toBlock;\n\n  return {\n    id,\n    label,\n    icon,\n    fields: [],\n    pattern: getInlinePattern(pattern),\n    fromBlock: fromInline,\n    toBlock: toInline,\n    toPreview,\n    inlinePattern: { trigger: trigger || undefined, onInsert, onEdit },\n  };\n};\n\n/**\n * Cache of the patterns {@link findInlineMatches} searches with, so they’re not compiled again for\n * every text node Lexical imports.\n * @type {WeakMap<RegExp, { global?: RegExp, sticky?: RegExp }>}\n */\nconst searchPatternCache = new WeakMap();\n\n/**\n * Get the global or sticky version of the given pattern, which is searched with `lastIndex`.\n * @param {RegExp} pattern Pattern returned by {@link getInlinePattern}.\n * @param {boolean} sticky Whether to get the sticky version, which only matches at `lastIndex`.\n * @returns {RegExp} Pattern.\n */\nconst getSearchPattern = (pattern, sticky) => {\n  const key = sticky ? 'sticky' : 'global';\n\n  const cache = getOrCreate(\n    searchPatternCache,\n    pattern,\n    () => /** @type {{ global?: RegExp, sticky?: RegExp }} */ ({}),\n  );\n\n  cache[key] ??= new RegExp(pattern.source, `${pattern.flags}${sticky ? 'y' : 'g'}`);\n\n  return cache[key];\n};\n\n/**\n * Find the instances of an inline component in the given string. With the `trigger` option, the\n * pattern is only matched where the trigger text is found, like Decap CMS does; otherwise, it’s\n * matched across the string. An empty match is never an instance.\n * @param {string} string String to search, e.g. the text of a paragraph.\n * @param {RegExp} pattern Pattern returned by {@link getInlinePattern}.\n * @param {InlinePatternOptions} [options] Options of the component.\n * @param {number} [limit] Maximum number of matches to find. Default: all of them.\n * @returns {RegExpExecArray[]} Non-overlapping matches in the order they appear.\n */\nexport const findInlineMatches = (string, pattern, { trigger } = {}, limit = Infinity) => {\n  const searchPattern = getSearchPattern(pattern, !!trigger);\n  /** @type {RegExpExecArray[]} */\n  const matches = [];\n  // Without a trigger, the pattern looks for the next instance from the index on its own\n  let index = trigger ? string.indexOf(trigger) : 0;\n\n  while (index !== -1 && matches.length < limit) {\n    searchPattern.lastIndex = index;\n\n    const match = searchPattern.exec(string);\n\n    // A sticky pattern only matches at the trigger, so look for the next one; a global one has\n    // found no instance after the index\n    if (!match && !trigger) {\n      break;\n    }\n\n    /** @type {number} */\n    let nextIndex;\n\n    if (match?.[0]) {\n      matches.push(match);\n      nextIndex = match.index + match[0].length;\n    } else {\n      // Move past the trigger, or an empty match so it’s not found again\n      nextIndex = (match?.index ?? index) + 1;\n    }\n\n    if (trigger) {\n      index = string.indexOf(trigger, nextIndex);\n    } else {\n      index = nextIndex <= string.length ? nextIndex : -1;\n    }\n  }\n\n  return matches;\n};\n\n/**\n * Create the regular expression a text match transformer imports an inline component with. Lexical\n * matches the text with `String.prototype.match()`, which calls the `Symbol.match` method, so the\n * method is replaced to find the first instance with {@link findInlineMatches}, honoring the\n * `trigger` option.\n * @param {RegExp} pattern Pattern returned by {@link getInlinePattern}.\n * @param {InlinePatternOptions} options Options of the component.\n * @returns {RegExp} Regular expression.\n */\nexport const createInlineMatcher = (pattern, options) =>\n  Object.assign(new RegExp(pattern), {\n    /**\n     * Find the first instance in the given text.\n     * @param {string} text Text.\n     * @returns {RegExpMatchArray | null} Match.\n     */\n    [Symbol.match]: (text) => findInlineMatches(text, pattern, options, 1)[0] ?? null,\n  });\n","/**\n * Prefix of the names of the internal properties the CMS adds to list items and rich text editor\n * component values, like `__sc_item_id`, which are excluded from the output.\n */\nexport const INTERNAL_PROP_PREFIX = '__sc_';\n\n/**\n * Check whether the given property name is an internal property.\n * @param {string} name Property name, not a key path.\n * @returns {boolean} Result.\n */\nexport const isInternalPropKey = (name) => name.startsWith(INTERNAL_PROP_PREFIX);\n","import { isInternalPropKey } from '$lib/services/contents/fields/internal-props';\nimport { flattenKeys, unflattenKeys } from '$lib/services/utils/object';\n\n/**\n * @import { ResolvedEditorComponentDefinition } from '$lib/types/private';\n * @import { EditorComponentDefinition } from '$lib/types/public';\n */\n\n/**\n * Check if the given pattern is multiline.\n * @param {RegExp} pattern Pattern.\n * @returns {boolean} Result.\n */\nexport const isMultiLinePattern = ({ multiline, dotAll, source }) =>\n  multiline || dotAll || source.includes('[\\\\s\\\\S]') || source.includes('[\\\\S\\\\s]');\n\n/**\n * Check if the given component is inline, which means it’s matched within a paragraph and rendered\n * within the text. A pattern-based inline component always is; any other component is if its\n * pattern is not multiline.\n * @param {Pick<ResolvedEditorComponentDefinition, 'pattern' | 'inlinePattern'>} componentDef\n * Component definition.\n * @returns {boolean} Result.\n */\nexport const isInlineComponentDef = ({ pattern, inlinePattern }) =>\n  !!inlinePattern || !isMultiLinePattern(pattern);\n\n/**\n * Get the subject of each complex selector in the given selector list, the compound selector after\n * the last combinator that the matched element itself is checked against, e.g. `img.wide` for\n * `figure > img.wide`. Commas, whitespace and combinators within parentheses, brackets or quotes,\n * as in `a:has(> img)` or `[title=\"a, b\"]`, are part of a compound selector.\n * @param {string} selector Selector list.\n * @returns {string[]} Compound selectors.\n */\nconst getSelectorSubjects = (selector) => {\n  /** @type {string[]} */\n  const subjects = [];\n  let depth = 0;\n  let quote = '';\n  let start = 0;\n  let afterCombinator = false;\n\n  // Add a comma to end the last selector\n  [...selector, ','].forEach((char, index) => {\n    if (quote) {\n      if (char === quote) {\n        quote = '';\n      }\n\n      return;\n    }\n\n    if (depth === 0 && char === ',') {\n      subjects.push(selector.slice(start, index).trim());\n      start = index + 1;\n      afterCombinator = false;\n\n      return;\n    }\n\n    if (depth === 0 && /[\\s>+~]/.test(char)) {\n      afterCombinator = true;\n\n      return;\n    }\n\n    if (afterCombinator) {\n      start = index;\n      afterCombinator = false;\n    }\n\n    if (char === '\"' || char === \"'\") {\n      quote = char;\n    } else if (char === '(' || char === '[') {\n      depth += 1;\n    } else if (char === ')' || char === ']') {\n      depth -= 1;\n    }\n  });\n\n  return subjects;\n};\n\n/**\n * Get the names of the elements the given `htmlSelector` of an editor component matches, e.g. `a`\n * and `img` for `a:has(> img), figure > img`. The editor imports the component from these\n * elements, so each selector in the list has to name the element type it matches.\n * @param {string} selector Selector list.\n * @returns {string[] | undefined} Lowercase tag names, without duplicates, or `undefined` if any of\n * the selectors doesn’t start its last compound selector with a type selector, e.g. `.note` or\n * `:is(aside, div)`.\n */\nexport const getSelectorTagNames = (selector) => {\n  const names = getSelectorSubjects(selector).map(\n    (subject) => /^[a-z][a-z\\d-]*(?![\\w-])/i.exec(subject)?.[0].toLowerCase() ?? '',\n  );\n\n  return names.every(Boolean) ? [...new Set(names)] : undefined;\n};\n\n/**\n * Check if the given string is a valid CSS selector list.\n * @param {string} selector Selector list.\n * @returns {boolean} Result.\n */\nexport const isValidSelector = (selector) => {\n  try {\n    document.createDocumentFragment().querySelector(selector);\n\n    return true;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Check if the given component definition supports the HTML format of the RichText field, which\n * requires the `htmlSelector`, `fromBlockHTML` and `toBlockHTML` options.\n * @param {EditorComponentDefinition} componentDef Component definition.\n * @returns {boolean} Result.\n */\nexport const supportsHTML = ({ htmlSelector, fromBlockHTML, toBlockHTML }) =>\n  typeof htmlSelector === 'string' &&\n  typeof fromBlockHTML === 'function' &&\n  typeof toBlockHTML === 'function';\n\n/**\n * Normalize properties by removing internal properties.\n * @param {Record<string, any>} props Properties to normalize.\n * @returns {Record<string, any>} Properties excluding those starting with `__sc_`, which are used\n * for internal purposes.\n */\nexport const normalizeProps = (props) =>\n  unflattenKeys(\n    Object.fromEntries(\n      Object.entries(flattenKeys(props)).filter(\n        ([key]) => !isInternalPropKey(/** @type {string} */ (key.split('.').pop())),\n      ),\n    ),\n  );\n\n/**\n * Get the names of the rich text editor components the given component is nested in. Lexical mounts\n * each component outside the Svelte component tree, so the names can’t come from the context; each\n * component instead lists its own name and those of its parents in the `data-component-path`\n * attribute of the element holding its fields, which this reads from the closest one.\n * @param {Element | undefined} element Element of a component.\n * @returns {string[]} Component names, the outermost first.\n */\nexport const getParentComponentNames = (element) => {\n  /** @type {HTMLElement | null | undefined} */\n  const container = element?.parentElement?.closest('[data-component-path]');\n\n  return container ? JSON.parse(/** @type {string} */ (container.dataset.componentPath)) : [];\n};\n\n/**\n * Follow whether the rich text editor the given component is in can’t be edited, which its textbox\n * tells with the `aria-readonly` attribute. Lexical mounts each component outside the Svelte\n * component tree, so the state can’t come from the context. Lexical also keeps applying updates\n * while the editor isn’t editable, so the component has to hold back the changes itself.\n * @param {Element | undefined} element Element of a component.\n * @param {(readonly: boolean) => void} callback Function called with the state right away, and\n * again whenever it changes.\n * @returns {MutationObserver | undefined} Observer to disconnect once the component is gone, or\n * `undefined` if the component isn’t in an editor.\n */\nexport const observeReadonly = (element, callback) => {\n  const textbox = element?.closest('[role=\"textbox\"]');\n\n  if (!textbox) {\n    return undefined;\n  }\n\n  /**\n   * Call the function with the current state.\n   */\n  const update = () => {\n    callback(textbox.getAttribute('aria-readonly') === 'true');\n  };\n\n  const observer = new MutationObserver(update);\n\n  update();\n  observer.observe(textbox, { attributes: true, attributeFilter: ['aria-readonly'] });\n\n  return observer;\n};\n\n/**\n * Follow the read-only state of the rich text editor the given component is in, like\n * {@link observeReadonly}, from the next frame on: Lexical mounts the component before putting it\n * in the editor, so the textbox can’t be found right away.\n * @param {Element | undefined} element Element of a component.\n * @param {(readonly: boolean) => void} callback Function called with the state once the frame has\n * come, and again whenever it changes.\n * @returns {() => void} Function to stop following the state once the component is gone. If the\n * frame hasn’t come by then, the callback is never called.\n */\nexport const followReadonly = (element, callback) => {\n  /** @type {MutationObserver | undefined} */\n  let observer;\n\n  const frame = window.requestAnimationFrame(() => {\n    observer = observeReadonly(element, callback);\n  });\n\n  return () => {\n    window.cancelAnimationFrame(frame);\n    observer?.disconnect();\n  };\n};\n\n/**\n * Unescape the title of a Markdown image, like `T \\\"q\\\"` in `![a](/a.png \"T \\\"q\\\"\")`, so the\n * field shows `T \"q\"`. A backslash before an ASCII punctuation character escapes it, as anywhere\n * else in Markdown, while one before any other character is a literal backslash. The alt text,\n * like `Figure \\[1` in `![Figure \\[1](/a.png)`, is unescaped the same way.\n * @param {string} title Title or alt text as it appears in Markdown, between the quotes or the\n * brackets.\n * @returns {string} Unescaped title or alt text.\n * @see https://spec.commonmark.org/0.31.2/#link-title\n * @see https://spec.commonmark.org/0.31.2/#backslash-escapes\n */\nexport const unescapeTitle = (title) => title.replace(/\\\\([!-/:-@[-`{-~])/g, '$1');\n\n/**\n * Escape the title of a Markdown image, the counterpart of `unescapeTitle()`, so it can be put\n * between double quotes: a double quote is escaped, as well as a backslash that would otherwise\n * escape the next character or the closing quote.\n * @param {string} title Title.\n * @returns {string} Escaped title.\n */\nexport const escapeTitle = (title) =>\n  title.replace(/\\\\(?=[!-/:-@[-`{-~]|$)/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n\n/**\n * Escape the alt text of a Markdown image, the counterpart of `unescapeTitle()`, so it can be put\n * between the brackets of `![…]`: a bracket is escaped, so an unbalanced one doesn’t end the alt\n * text early or keep it open, as well as a backslash that would otherwise escape the next character\n * or the closing bracket.\n * @param {string} alt Alt text.\n * @returns {string} Escaped alt text.\n */\nexport const escapeAlt = (alt) =>\n  alt.replace(/\\\\(?=[!-/:-@[-`{-~]|$)/g, '\\\\\\\\').replace(/[[\\]]/g, '\\\\$&');\n","/**\n * Pattern matching the alt text of a Markdown image, which can contain balanced brackets, e.g.\n * `Photo [1]` in `![Photo [1]](photo.jpg)`, as CommonMark allows. See {@link IMAGE_REGEX}.\n */\nconst ALT_PATTERN = [\n  String.raw`(?:[^\\][\\\\!]|\\\\(?!!\\[).|!(?!\\[)`,\n  String.raw`|\\[(?:[^\\][\\\\!]|\\\\(?!!\\[).|!(?!\\[))*\\])*`,\n].join('');\n\n/**\n * Pattern matching the source of a Markdown image. See {@link IMAGE_REGEX}.\n */\nconst SRC_PATTERN = [\n  String.raw`(?:[^\"()\\\\!]|\\\\(?!!\\[).|!(?!\\[)`,\n  String.raw`|\\((?:[^)!]|!(?!\\[))*\\)|\"(?:[^\"!]|!(?!\\[))*\")*?`,\n].join('');\n\n/**\n * Get the pattern matching the title of a Markdown image between the given quotes, without them.\n * @param {string} quote Double or single quote.\n * @returns {string} Pattern.\n */\nconst getTitlePattern = (quote) => String.raw`(?:[^${quote}\\\\!]|\\\\(?!!\\[).|!(?!\\[))*`;\n\n/**\n * Get the pattern matching a Markdown image, with the named groups suffixed as given, so the\n * pattern can be used twice in one regular expression.\n * @param {string} [suffix] Suffix of the group names.\n * @returns {string} Pattern.\n */\nexport const getImagePattern = (suffix = '') =>\n  [\n    String.raw`!\\[(?<alt${suffix}>${ALT_PATTERN})\\]\\((?<src${suffix}>${SRC_PATTERN})`,\n    String.raw`(?:(?<![^\\\\]\\s)\\s+(?:\"(?<title${suffix}>${getTitlePattern('\"')})\"`,\n    String.raw`|'(?<singleQuotedTitle${suffix}>${getTitlePattern(\"'\")})'))?\\)`,\n  ].join('');\n\n/**\n * Regular expression to match Markdown images, including those with spaces and brackets in the src,\n * e.g. `![alt text](image.jpg \"Image title\")`. It also matches images with empty alt text, e.g.\n * `![](image.jpg)`, images with parentheses in the filename, e.g. `![alt](image (1).jpg)`, alt text\n * with balanced brackets, e.g. `![Photo [1]](image.jpg)`, and supports escaped characters like\n * `![alt](image\\(1\\).jpg)` and titles with escaped quotes. The title can be in double or single\n * quotes, captured as `title` or `singleQuotedTitle`; one in parentheses can’t be told apart from\n * parentheses in the filename, so it’s read as part of the source.\n *\n * The pattern runs on untrusted Markdown, so it’s written to match in linear time, like\n * `MARKDOWN_IMAGE_REGEX` in `rich-text/previews/media-sources`, which shares the pattern. Every\n * part can only be matched one\n * way, and none of the alt text, source, parenthesized or quoted parts of the source, or title can\n * contain `![`, so a failed match at one `![` doesn’t read the text after the next one again. A\n * title is only looked for at the start of a run of whitespace after the source, so the run isn’t\n * read again from each of its characters. An image nested in another one is matched on its own.\n * @type {RegExp}\n */\nexport const IMAGE_REGEX = new RegExp(getImagePattern());\n\n/**\n * Regular expression to match Markdown linked images, including those with spaces and brackets in\n * the src, e.g. `[![alt text](image.jpg \"Image title\")](link)`. It also matches linked images with\n * parentheses in the filename, e.g. `[![alt](image (1).jpg)](https://example.com)`. The image\n * part is matched like {@link IMAGE_REGEX}, in linear time, and the link can contain one pair of\n * parentheses, which is looked for only from the link’s first `(`.\n * @type {RegExp}\n */\nexport const LINKED_IMAGE_REGEX = new RegExp(\n  String.raw`\\[${getImagePattern('2')}\\](?:\\((?<link>[^()]*(?:\\([^)]*\\)[^)]*|\\([^)]*)?)\\))`,\n);\n\n/**\n * Regular expression to match either a Markdown image or a linked image.\n * @type {RegExp}\n */\nexport const IMAGE_OR_LINKED_IMAGE_REGEX = new RegExp(\n  `${IMAGE_REGEX.source}|${LINKED_IMAGE_REGEX.source}`,\n);\n\n/**\n * Pattern matching the attributes of an HTML start tag, each value in double quotes, as written by\n * the image components. A value can contain `>`, like an alt text, but not a double quote, which\n * is escaped. An attribute name can’t contain whitespace, so the pattern matches in linear time.\n */\nconst HTML_ATTRS_PATTERN = String.raw`(?:\\s+[^\\s\"'<>=/]+(?:=\"[^\"]*\")?)*\\s*`;\n/**\n * Pattern matching an HTML `<img>` element. See {@link getFigurePattern}.\n */\nconst HTML_IMAGE_PATTERN = String.raw`<img${HTML_ATTRS_PATTERN}\\/?>`;\n\n/**\n * Get the pattern matching an image with a caption, written as an HTML `<figure>` element on a\n * single line, e.g. `<figure><img src=\"a.jpg\" alt=\"\"><figcaption>Caption</figcaption></figure>`.\n * Markdown has no syntax for a caption, so the built-in image components write one this way. The\n * image is captured as `figureContent`, and the caption HTML as `caption`.\n * @param {object} [options] Options.\n * @param {boolean} [options.linked] Whether the image can be wrapped in a link.\n * @returns {string} Pattern.\n */\nexport const getFigurePattern = ({ linked = false } = {}) => {\n  const content = linked\n    ? String.raw`(?:<a${HTML_ATTRS_PATTERN}>${HTML_IMAGE_PATTERN}<\\/a>|${HTML_IMAGE_PATTERN})`\n    : HTML_IMAGE_PATTERN;\n\n  return [\n    String.raw`<figure>(?<figureContent>${content})`,\n    // The caption can’t close the figure, which the browser would take as the end of the caption\n    String.raw`<figcaption>(?<caption>(?:[^<\\n]|<(?!\\/fig(?:caption|ure)>))*)<\\/figcaption>`,\n    String.raw`<\\/figure>`,\n  ].join('');\n};\n","import { sanitize } from 'isomorphic-dompurify';\n\n/**\n * Sanitization options for DOMPurify to allow `blob` URLs for images, which are commonly used for\n * local previews of uploaded images. Also allow `iframe` tags with strict sandboxing for embedded\n * media previews.\n *\n * The preview is rendered in the app’s own document, so content written by other users must not be\n * able to restyle or cover the app, e.g. with a fake sign-in form asking for an access token. A\n * `<style>` element would apply to the whole app, and form controls could collect and send data, so\n * they’re removed, except the disabled check boxes of a task list, which {@link filterInputs}\n * enforces. Inline styles are kept, because the syntax highlighting relies on them, but filtered by\n * {@link filterInlineStyle}.\n * @see https://github.com/cure53/DOMPurify/issues/549\n * @see https://github.com/cure53/DOMPurify#control-permitted-attribute-values.\n * @see https://github.com/cure53/DOMPurify/wiki/Default-TAGs-ATTRIBUTEs-allow-list-&-blocklist\n */\nexport const SANITIZE_OPTIONS = {\n  ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|blob):|[^a-z]|[a-z+.-]+(?:[^a-z+.\\-:]|$))/i,\n  ADD_TAGS: ['iframe'],\n  ADD_ATTR: ['allow', 'allowfullscreen', 'referrerpolicy', 'sandbox'],\n  FORBID_TAGS: ['style', 'form', 'button', 'textarea', 'select', 'option'],\n};\n\n/**\n * Attributes the check box of a task list item can keep in the preview.\n */\nconst ALLOWED_CHECKBOX_ATTRIBUTES = ['type', 'checked', 'disabled'];\n\n/**\n * Remove every `<input>` element but a check box, which a task list item has, e.g. `- [x] Done` in\n * Markdown is rendered as `<li><input checked=\"\" disabled=\"\" type=\"checkbox\"> Done</li>`. A check\n * box is disabled, and loses any attribute other than {@link ALLOWED_CHECKBOX_ATTRIBUTES}, like\n * `name`, `form` or `autofocus`, so it can’t send data, join a form in the app or take the focus.\n * @param {HTMLElement} body Sanitized content.\n */\nconst filterInputs = (body) => {\n  body.querySelectorAll('input').forEach((input) => {\n    if (input.getAttribute('type')?.trim().toLowerCase() !== 'checkbox') {\n      input.remove();\n\n      return;\n    }\n\n    [...input.attributes].forEach(({ name }) => {\n      if (!ALLOWED_CHECKBOX_ATTRIBUTES.includes(name)) {\n        input.removeAttribute(name);\n      }\n    });\n\n    input.setAttribute('type', 'checkbox');\n    input.disabled = true;\n  });\n};\n\n/**\n * CSS properties an element can keep in its inline style in the preview. These cover the output of\n * the Shiki syntax highlighter (colors and font styles) and the sizing and alignment commonly used\n * in content, e.g. `<img style=\"width: 50%\">`. Anything else is dropped, including `position`,\n * `inset`, `transform`, `z-index` and `background-image`, which could move content over the app or\n * load a remote resource. The browser expands a shorthand like `background` into its individual\n * properties when parsing the style, so only the harmless part of a shorthand is kept.\n * `text-decoration` is also listed for a DOM implementation that doesn’t expand it; it can’t load\n * anything either way. Likewise, `text-align` is a shorthand for `text-align-all` and\n * `text-align-last` in CSS Text Level 4, which jsdom implements but browsers don’t yet, so all\n * three are listed.\n */\nconst ALLOWED_STYLE_PROPERTIES = [\n  'color',\n  'background-color',\n  'font-style',\n  'font-weight',\n  'text-decoration',\n  'text-decoration-line',\n  'text-decoration-style',\n  'text-decoration-color',\n  'text-decoration-thickness',\n  'text-align',\n  'text-align-all',\n  'text-align-last',\n  'width',\n  'height',\n  'max-width',\n  'max-height',\n];\n\n/**\n * Remove any CSS property that’s not in {@link ALLOWED_STYLE_PROPERTIES} from the inline style of\n * the given element, and remove the `style` attribute altogether if nothing is left.\n * @param {HTMLElement} element Element with a `style` attribute.\n */\nconst filterInlineStyle = (element) => {\n  const { style } = element;\n\n  Array.from(style)\n    .filter((name) => !ALLOWED_STYLE_PROPERTIES.includes(name))\n    .forEach((name) => {\n      style.removeProperty(name);\n    });\n\n  if (!style.length) {\n    element.removeAttribute('style');\n  }\n};\n\n/**\n * Sandbox tokens an embedded iframe can keep in the preview. Any other token supplied in the\n * content is dropped, including `allow-top-navigation`, which would let the embed take over the\n * CMS tab, and `allow-popups-to-escape-sandbox`, `allow-modals` and `allow-downloads`. It’s an\n * allowlist, so a token added to browsers in the future is dropped until it’s been reviewed.\n * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/iframe#sandbox\n */\nconst ALLOWED_SANDBOX_TOKENS = [\n  'allow-forms',\n  'allow-orientation-lock',\n  'allow-pointer-lock',\n  'allow-popups',\n  'allow-presentation',\n  'allow-same-origin',\n  'allow-scripts',\n  'allow-storage-access-by-user-activation',\n];\n\n/**\n * Permissions Policy features an embedded iframe can be granted in the preview with the `allow`\n * attribute. These cover the embed codes of common media services such as YouTube and Vimeo. Other\n * features, like `camera`, `microphone` and `geolocation`, are dropped, because the permission\n * prompt would name the CMS origin, and a permission the user has already granted to the CMS would\n * pass to the embed without a prompt.\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Permissions-Policy\n */\nconst ALLOWED_PERMISSIONS_POLICY_FEATURES = [\n  'accelerometer',\n  'autoplay',\n  'clipboard-write',\n  'encrypted-media',\n  'fullscreen',\n  'gyroscope',\n  'picture-in-picture',\n  'web-share',\n];\n\n/**\n * Filter the `allow` attribute of an iframe, keeping only the directives for the features in\n * {@link ALLOWED_PERMISSIONS_POLICY_FEATURES}. A directive can have an allowlist of origins after\n * the feature name, e.g. `autoplay 'self' https://example.com`, which is kept as is.\n * @param {HTMLIFrameElement} iframe The iframe element to update.\n */\nconst filterPermissionsPolicy = (iframe) => {\n  const allow = iframe.getAttribute('allow');\n\n  if (allow === null) {\n    return;\n  }\n\n  const directives = allow\n    .split(';')\n    .map((directive) => directive.trim())\n    .filter((directive) =>\n      ALLOWED_PERMISSIONS_POLICY_FEATURES.includes(directive.split(/\\s+/)[0].toLowerCase()),\n    );\n\n  if (directives.length) {\n    iframe.setAttribute('allow', directives.join('; '));\n  } else {\n    iframe.removeAttribute('allow');\n  }\n};\n\n/**\n * Validate and secure an iframe element.\n * @param {HTMLIFrameElement} iframe The iframe element to validate.\n * @returns {boolean} `true` if the iframe is safe and should be kept, `false` if it should be\n * removed.\n */\nconst validateIframe = (iframe) => {\n  const src = iframe.getAttribute('src')?.trim() || '';\n\n  // Require HTTPS (blocks dangerous schemes, relative paths, and HTTP)\n  if (!src.startsWith('https://')) {\n    return false;\n  }\n\n  try {\n    const url = new URL(src);\n\n    // Get current origin (handle cases where window might not be fully initialized)\n    const currentOrigin =\n      typeof window !== 'undefined' && window.location ? window.location.origin : '';\n\n    // Block same-origin iframes to prevent parent window access\n    if (currentOrigin && url.origin === currentOrigin) {\n      return false;\n    }\n  } catch {\n    // Invalid URL\n    return false;\n  }\n\n  // Enforce restrictive sandbox for cross-origin iframes. Since we already block same-origin\n  // iframes above, it’s safe to allow both `allow-scripts` and `allow-same-origin` here: the iframe\n  // can only access its own origin’s APIs (like Cache Storage for YouTube embeds), not the parent\n  // window. Sandbox tokens are ASCII case-insensitive, so they’re compared in lowercase.\n  const currentSandbox = iframe.getAttribute('sandbox') || '';\n\n  const sandboxTokens = new Set(\n    currentSandbox\n      .toLowerCase()\n      .split(/\\s+/)\n      .filter((token) => ALLOWED_SANDBOX_TOKENS.includes(token)),\n  );\n\n  // Required for embed functionality\n  sandboxTokens.add('allow-scripts');\n  sandboxTokens.add('allow-same-origin');\n\n  // Set the enforced sandbox attribute\n  iframe.setAttribute('sandbox', Array.from(sandboxTokens).join(' '));\n  filterPermissionsPolicy(iframe);\n\n  return true;\n};\n\n/**\n * Sanitize HTML with DOMPurify and enforce iframe security policies. This wrapper function handles\n * post-processing of iframes to ensure they are secure.\n * @param {string} html The HTML string to sanitize.\n * @param {object} [options] Additional DOMPurify options.\n * @returns {string} The sanitized HTML string with secure iframes.\n */\nexport const sanitizeRichTextHTML = (html, options = {}) => {\n  // First pass: sanitize with DOMPurify, returning a DOM element\n  const body = /** @type {HTMLBodyElement} */ (\n    sanitize(html, { ...SANITIZE_OPTIONS, ...options, RETURN_DOM: true })\n  );\n\n  // Second pass: validate and secure all iframes\n  const iframes = Array.from(body.querySelectorAll('iframe'));\n\n  iframes.forEach((iframe) => {\n    if (!validateIframe(iframe)) {\n      iframe.remove();\n    }\n  });\n\n  // Third pass: keep only the disabled check boxes of task lists\n  filterInputs(body);\n\n  // Fourth pass: remove any CSS that could move content outside the preview\n  body.querySelectorAll('[style]').forEach((element) => {\n    filterInlineStyle(/** @type {HTMLElement} */ (element));\n  });\n\n  // Return the body’s HTML\n  return body.innerHTML;\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { customComponentRegistry } from '$lib/services/api/registries';\nimport {\n  isInlinePatternComponent,\n  resolveInlinePatternComponent,\n} from '$lib/services/contents/fields/rich-text/components/inline-pattern';\nimport {\n  escapeAlt,\n  escapeTitle,\n  unescapeTitle,\n} from '$lib/services/contents/fields/rich-text/components/utils';\nimport {\n  getFigurePattern,\n  IMAGE_OR_LINKED_IMAGE_REGEX,\n  IMAGE_REGEX,\n} from '$lib/services/contents/fields/rich-text/constants';\nimport { sanitizeRichTextHTML } from '$lib/services/contents/fields/rich-text/sanitize';\nimport { escapeAttr } from '$lib/services/utils/string';\n\n/**\n * @import { ResolvedEditorComponentDefinition } from '$lib/types/private';\n * @import { EditorComponentDefinition } from '$lib/types/public';\n */\n\n/**\n * Get the image field values from an `<img>` element.\n * @param {Element} img Image element.\n * @returns {{ src: string, alt: string, title: string }} Values.\n */\nconst getImageProps = (img) => ({\n  src: img.getAttribute('src') ?? '',\n  alt: img.getAttribute('alt') ?? '',\n  title: img.getAttribute('title') ?? '',\n});\n\n/**\n * Create an `<img>` element from the image field values. The values are set as attributes, so they\n * don’t have to be escaped.\n * @param {Record<string, any>} props Field values.\n * @returns {HTMLImageElement | string} Element, or an empty string if the source is not set.\n */\nconst createImageElement = ({ src = '', alt = '', title = '' }) => {\n  if (!src) {\n    return '';\n  }\n\n  const img = document.createElement('img');\n\n  img.setAttribute('src', src);\n  // The alt text is always there for accessibility, even if empty\n  img.setAttribute('alt', alt);\n\n  if (title) {\n    img.setAttribute('title', title);\n  }\n\n  return img;\n};\n\n/**\n * Create the Markdown image syntax from the image field values.\n * @param {Record<string, any>} props Field values.\n * @returns {string} Markdown, or an empty string if the source is not set.\n */\nconst toImageMarkdown = ({ src = '', alt = '', title = '' }) =>\n  src ? `![${escapeAlt(alt)}](${src}${title ? ` \"${escapeTitle(title)}\"` : ''})` : '';\n\n/**\n * Create the HTML of an image preview from the image field values.\n * @param {Record<string, any>} props Field values.\n * @returns {string} HTML.\n */\nconst toImagePreview = ({ src = '', alt = '', title = '' }) =>\n  `<img src=\"${escapeAttr(src)}\" alt=\"${escapeAttr(alt)}\" title=\"${escapeAttr(title)}\">`;\n\n/**\n * Get the image field values from a `<figure>` element holding an image, which can be wrapped in a\n * link, and its caption, e.g. `<figure><img src=\"a.jpg\" alt=\"\"><figcaption>…</figcaption>\n * </figure>`.\n * @param {Element} figure Figure element.\n * @param {object} [options] Options.\n * @param {boolean} [options.linked] Whether the image can be wrapped in a link.\n * @returns {Record<string, string> | undefined} Values, or `undefined` if the element doesn’t hold\n * just an image and a caption.\n */\nconst getFigureProps = (figure, { linked = false } = {}) => {\n  const [content, figcaption, ...rest] = figure.children;\n\n  // Text outside the image and the caption would be lost, so such a figure is left as it is\n  const hasOtherText = [...figure.childNodes].some(\n    (node) => node.nodeType === Node.TEXT_NODE && !!node.textContent?.trim(),\n  );\n\n  if (!content || figcaption?.localName !== 'figcaption' || rest.length || hasOtherText) {\n    return undefined;\n  }\n\n  const anchor =\n    linked &&\n    content.localName === 'a' &&\n    content.children.length === 1 &&\n    !content.textContent?.trim()\n      ? content\n      : undefined;\n\n  const img = anchor ? anchor.children[0] : content;\n\n  if (img.localName !== 'img') {\n    return undefined;\n  }\n\n  const props = { ...getImageProps(img), caption: figcaption.innerHTML.trim() };\n\n  return linked ? { ...props, link: anchor?.getAttribute('href') ?? '' } : props;\n};\n\n/**\n * Get the image field values from a Markdown image, or a `<figure>` element matched with\n * {@link getFigurePattern}.\n * @param {RegExpMatchArray} match Match.\n * @param {(match: RegExpMatchArray) => Record<string, any>} fromImage Function to get the values\n * from a Markdown image.\n * @param {object} [options] Options.\n * @param {boolean} [options.linked] Whether the image can be wrapped in a link.\n * @returns {Record<string, any>} Values.\n */\nconst getMatchProps = (match, fromImage, { linked = false } = {}) => {\n  if (match.groups?.figureContent === undefined) {\n    return fromImage(match);\n  }\n\n  // The pattern makes sure the element holds an image and a caption\n  const { body } = new DOMParser().parseFromString(match[0], 'text/html');\n\n  const props = /** @type {Record<string, string>} */ (\n    getFigureProps(/** @type {Element} */ (body.firstElementChild), { linked })\n  );\n\n  // Keep the caption as written rather than as the parser serializes it, e.g. `&` as `&amp;`, so\n  // the figure is written back unchanged\n  return { ...props, caption: /** @type {string} */ (match.groups.caption) };\n};\n\n/**\n * Create the HTML of an image with a caption, which Markdown has no syntax for.\n * @param {Record<string, any>} props Field values.\n * @returns {string} HTML.\n */\nconst toFigureHTML = ({ src = '', alt = '', title = '', link = '', caption = '' }) => {\n  const img = `<img src=\"${escapeAttr(src)}\" alt=\"${escapeAttr(alt)}\"${\n    title ? ` title=\"${escapeAttr(title)}\"` : ''\n  }>`;\n\n  // The figure is written on a single line, so a line break in the caption becomes a space\n  return [\n    '<figure>',\n    link ? `<a href=\"${escapeAttr(link)}\">${img}</a>` : img,\n    `<figcaption>${String(caption).replace(/\\s*\\n\\s*/g, ' ')}</figcaption>`,\n    '</figure>',\n  ].join('');\n};\n\n/**\n * Wrap the given image or linked image element in a `<figure>` element with a caption.\n * @param {HTMLElement} content Image or link element.\n * @param {string} caption Caption HTML.\n * @returns {HTMLElement} Figure element.\n */\nconst createFigureElement = (content, caption) => {\n  const figure = document.createElement('figure');\n  const figcaption = document.createElement('figcaption');\n  const template = document.createElement('template');\n\n  // The caption is sanitized before being added to the document, where an image in it would load\n  template.innerHTML = sanitizeRichTextHTML(caption);\n  figcaption.append(template.content);\n  figure.append(content, figcaption);\n\n  return figure;\n};\n\n/**\n * English labels of the built-in image components, localized in `getBuiltInComponentDefs()`.\n * @type {Record<string, string>}\n */\nconst IMAGE_COMPONENT_LABELS = {\n  image: 'Image',\n  src: 'Source',\n  alt: 'Alt Text',\n  title: 'Title',\n  link: 'Link',\n  caption: 'Caption',\n};\n\n/**\n * Get the image field values from a Markdown image matched with `IMAGE_REGEX`.\n * @param {RegExpMatchArray} match Match.\n * @returns {Record<string, any>} Values.\n */\nconst getImageMatchProps = ({ groups }) => {\n  const { src, alt, title = groups?.singleQuotedTitle } = groups ?? {};\n\n  return { src, alt: alt && unescapeTitle(alt), title: title && unescapeTitle(title) };\n};\n\n/**\n * Get the image field values from a Markdown image or linked image matched with\n * `IMAGE_OR_LINKED_IMAGE_REGEX`.\n * @param {RegExpMatchArray} match Match.\n * @returns {Record<string, any>} Values.\n */\nconst getLinkedImageMatchProps = ({ groups }) => {\n  const { src, alt, title, singleQuotedTitle, src2, alt2, title2, singleQuotedTitle2, link } =\n    groups ?? {};\n\n  return {\n    src: (src || src2 || '').trim(),\n    alt: unescapeTitle(alt || alt2 || '').trim(),\n    title: unescapeTitle(title || singleQuotedTitle || title2 || singleQuotedTitle2 || '').trim(),\n    link: (link || '').trim(),\n  };\n};\n\n/**\n * Get the ID of a built-in image component.\n * @param {object} args Arguments.\n * @param {boolean} args.linked Whether the image can be wrapped in a link.\n * @param {boolean} args.captioned Whether the image can have a caption.\n * @returns {string} ID: `image`, `linked-image`, `uncaptioned-image` or `uncaptioned-linked-image`.\n */\nexport const getImageComponentId = ({ linked, captioned }) =>\n  `${captioned ? '' : 'uncaptioned-'}${linked ? 'linked-image' : 'image'}`;\n\n/**\n * Variants of the built-in image components.\n */\nconst IMAGE_COMPONENT_VARIANTS = [false, true].flatMap((captioned) =>\n  [false, true].map((linked) => ({ linked, captioned })),\n);\n\n/**\n * IDs of all the built-in image components.\n */\nexport const IMAGE_COMPONENT_IDS = IMAGE_COMPONENT_VARIANTS.map(getImageComponentId);\n\n/**\n * Create the definition of a built-in image component. The linked image component, enabled with\n * the `linked_images` option, is the image component with a link around the image. The uncaptioned\n * components, enabled by disabling the `captioned_images` option, have no Caption field and leave\n * an HTML `<figure>` element as it is.\n * @param {object} args Arguments.\n * @param {boolean} args.linked Whether the image can be wrapped in a link.\n * @param {boolean} [args.captioned] Whether the image can have a caption.\n * @param {(key: string) => string} args.getLabel Function to get the label of the component or a\n * field, given its key in {@link IMAGE_COMPONENT_LABELS}.\n * @returns {EditorComponentDefinition} Definition.\n */\nconst createImageComponentDef = ({ linked, captioned = true, getLabel }) => ({\n  /* eslint-disable jsdoc/require-jsdoc */\n  id: getImageComponentId({ linked, captioned }),\n  label: getLabel('image'),\n  fields: [\n    { name: 'src', label: getLabel('src'), widget: 'image' },\n    { name: 'alt', label: getLabel('alt'), required: false },\n    { name: 'title', label: getLabel('title'), required: false },\n    ...(linked ? [{ name: 'link', label: getLabel('link'), required: false }] : []),\n    ...(captioned ? [{ name: 'caption', label: getLabel('caption'), required: false }] : []),\n  ],\n  pattern: new RegExp(\n    [\n      ...(captioned ? [getFigurePattern({ linked })] : []),\n      (linked ? IMAGE_OR_LINKED_IMAGE_REGEX : IMAGE_REGEX).source,\n    ].join('|'),\n  ),\n  fromBlock: (match) =>\n    getMatchProps(match, linked ? getLinkedImageMatchProps : getImageMatchProps, { linked }),\n  toBlock: (props) => {\n    const link = linked ? (props.link ?? '') : '';\n    const img = toImageMarkdown(props);\n\n    if (img && props.caption) {\n      return toFigureHTML({ ...props, link });\n    }\n\n    return img && link ? `[${img}](${link})` : img;\n  },\n  toPreview: (props) => {\n    const link = linked ? (props.link ?? '') : '';\n\n    if (props.src && props.caption) {\n      return toFigureHTML({ ...props, link });\n    }\n\n    const img = toImagePreview(props);\n\n    return link ? `<a href=\"${escapeAttr(link)}\">${img}</a>` : img;\n  },\n  // An image with a caption, an image within a link that has nothing else, or a bare image\n  htmlSelector: [\n    ...(captioned ? ['figure'] : []),\n    ...(linked ? ['a:has(> img:only-child)'] : []),\n    'img',\n  ].join(', '),\n  fromBlockHTML: (element) => {\n    if (element.localName === 'figure') {\n      return getFigureProps(element, { linked });\n    }\n\n    if (element.localName === 'img') {\n      return linked ? { ...getImageProps(element), link: '' } : getImageProps(element);\n    }\n\n    // A selector cannot tell if a link has any text besides the image\n    if (element.textContent?.trim()) {\n      return undefined;\n    }\n\n    return {\n      // The selector makes sure the link has an image\n      ...getImageProps(/** @type {Element} */ (element.querySelector('img'))),\n      link: element.getAttribute('href') ?? '',\n    };\n  },\n  toBlockHTML: (props) => {\n    const link = linked ? (props.link ?? '') : '';\n    const img = createImageElement(props);\n\n    if (!img) {\n      return img;\n    }\n\n    /** @type {HTMLElement} */\n    let content = /** @type {HTMLImageElement} */ (img);\n\n    if (link) {\n      content = document.createElement('a');\n      content.setAttribute('href', link);\n      content.append(img);\n    }\n\n    return props.caption ? createFigureElement(content, props.caption) : content;\n  },\n  /* eslint-enable jsdoc/require-jsdoc */\n});\n\n/**\n * Get the English label of the built-in image components or one of their fields.\n * @param {string} key Key in {@link IMAGE_COMPONENT_LABELS}.\n * @returns {string} Label.\n */\nconst getEnglishImageLabel = (key) => IMAGE_COMPONENT_LABELS[key];\n\n/**\n * Built-in image component definition. The labels are localized in `getBuiltInComponentDefs()`.\n * @type {EditorComponentDefinition}\n * @see https://decapcms.org/docs/widgets/#Markdown\n * @see https://sveltiacms.app/en/docs/fields/richtext\n */\nexport const IMAGE_COMPONENT = createImageComponentDef({\n  linked: false,\n  getLabel: getEnglishImageLabel,\n});\n\n/**\n * Built-in linked image component definition. The labels are localized in\n * `getBuiltInComponentDefs()`.\n * @type {EditorComponentDefinition}\n */\nexport const LINKED_IMAGE_COMPONENT = createImageComponentDef({\n  linked: true,\n  getLabel: getEnglishImageLabel,\n});\n\n/**\n * Get the localized label of the built-in image components or one of their fields.\n * @param {string} key Key in {@link IMAGE_COMPONENT_LABELS}.\n * @returns {string} Label.\n */\nconst getLocalizedImageLabel = (key) => _(`editor_components.${key}`);\n\n/**\n * Get all built-in component definitions with localized labels. This has to be a function due to\n * localized labels.\n * @returns {EditorComponentDefinition[]} Array of built-in component definitions.\n */\nexport const getBuiltInComponentDefs = () =>\n  IMAGE_COMPONENT_VARIANTS.map((variant) => ({\n    ...createImageComponentDef({ ...variant, getLabel: getLocalizedImageLabel }),\n    icon: 'image',\n    trigger: /** @type {'button'} */ ('button'),\n    /**\n     * Create the Markdown inserted in the plain text mode. A new image has no source yet, for which\n     * `toBlock()` returns an empty string, so nothing would be inserted.\n     * @returns {string} Empty image.\n     */\n    createMarkdown: () => '![]()',\n  }));\n\n/**\n * Resolve a custom component name, which is either the name registered with the\n * `CMS.registerEditorComponent()` API, like `youtube`, or the ID of its definition returned by\n * {@link getComponentDef}, like `x-youtube`. The latter is stored as the `__sc_component_name`\n * value of a component in an entry draft, and passed to the fields within the component.\n * @param {string | undefined} name Component name or ID.\n * @returns {string | undefined} Name registered with the API, or `undefined` if the name doesn’t\n * belong to a custom component, e.g. a built-in component name.\n */\nexport const getCustomComponentName = (name) => {\n  if (!name) {\n    return undefined;\n  }\n\n  if (customComponentRegistry.has(name)) {\n    return name;\n  }\n\n  const unprefixedName = name.replace(/^x-/, '');\n\n  return unprefixedName !== name && customComponentRegistry.has(unprefixedName)\n    ? unprefixedName\n    : undefined;\n};\n\n/**\n * Get a component definition.\n * @param {string} name Component name. For a custom component, this can be either the name\n * registered with the API or the prefixed ID of its definition. See {@link getCustomComponentName}.\n * @returns {ResolvedEditorComponentDefinition | undefined} Definition. A pattern-based inline\n * component is converted to the shape of a field-based one with `resolveInlinePatternComponent()`.\n */\nexport const getComponentDef = (name) => {\n  const customComponentName = getCustomComponentName(name);\n\n  if (customComponentName) {\n    const registeredDef = customComponentRegistry.get(customComponentName);\n\n    const customComponentDef = isInlinePatternComponent(registeredDef)\n      ? resolveInlinePatternComponent(registeredDef)\n      : /** @type {EditorComponentDefinition} */ (registeredDef);\n\n    // Add a prefix to the component ID to avoid conflicts with built-in components and Lexical’s\n    // built-in node types, such as `code`.\n    return {\n      ...customComponentDef,\n      id: `x-${customComponentName}`,\n      // The label is optional; fall back to the registered name\n      label: customComponentDef.label ?? customComponentName,\n    };\n  }\n\n  return getBuiltInComponentDefs().find(({ id }) => id === name);\n};\n","const NUMERIC_VALUE_REGEX = /^\\d+$/;\n\n/**\n * Check if the given value is a numeric string, consisting of one or more digits only.\n * @param {string} value Value to check.\n * @returns {boolean} True if the value is numeric, false otherwise.\n */\nexport const isNumeric = (value) => NUMERIC_VALUE_REGEX.test(value);\n\n/**\n * Drop the error of binary floating-point arithmetic from the given number by rounding a fraction\n * to 15 significant digits, e.g. `0.3` rather than `0.30000000000000004` for `0.1 * 3`. An integer\n * is exact, and may have more digits, so it’s returned as is, as rounding would change a large one.\n * So is a number with 16 or more integer digits, as rounding would change its integer part, e.g.\n * `1234567890123456.5` would become `1234567890123460`.\n * @param {number} number Finite number.\n * @returns {number} Number.\n */\nexport const roundFloatError = (number) =>\n  Number.isInteger(number) || Math.abs(number) >= 1e15 ? number : Number(number.toPrecision(15));\n\n/**\n * Move the decimal point of the given number without a floating-point error, by changing the\n * exponent of its string representation.\n * @param {number} number Finite number.\n * @param {number} places Number of places to move the decimal point to the right. A negative\n * number moves it to the left.\n * @returns {number} Number multiplied by `10 ** places`.\n */\nconst shiftDecimalPoint = (number, places) => {\n  const [mantissa, exponent = '0'] = String(number).split('e');\n\n  return Number(`${mantissa}e${Number(exponent) + places}`);\n};\n\n/**\n * Convert a number to a fixed decimal string.\n * @param {number} number Number to convert.\n * @param {number} decimals Number of decimal places to keep.\n * @returns {number} Number with fixed decimal places.\n */\nexport const toFixed = (number, decimals) => {\n  // Handle non-numeric inputs\n  if (typeof number !== 'number') {\n    return NaN;\n  }\n\n  // Handle special cases\n  if (!Number.isFinite(number)) {\n    // Returns NaN or Infinity as-is\n    return number;\n  }\n\n  // Use proper mathematical rounding instead of JavaScript’s native `toFixed`, rounding halves\n  // away from zero, so `-1.005` gives `-1.01` like `1.005` gives `1.01`. The floating-point error\n  // of an arithmetic result like `8.7 * 1.15`, i.e. `10.004999999999999`, is first dropped. The\n  // decimal point is then moved in the exponent of the string representation rather than by\n  // multiplying, which would bring in another error: `1.005 * 100` is `100.49999999999999`\n  const value = Math.abs(roundFloatError(number));\n  const rounded = shiftDecimalPoint(Math.round(shiftDecimalPoint(value, decimals)), -decimals);\n\n  // Adding zero turns `-0` into `0`\n  return Math.sign(number) * rounded + 0;\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { customFieldTypeRegistry } from '$lib/services/api/registries';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getCollectionFile } from '$lib/services/contents/collection/files';\nimport { getListItemKeys } from '$lib/services/contents/entry/key-paths';\nimport { getSubtree } from '$lib/services/contents/entry/subtree';\nimport {\n  BUILTIN_FIELD_TYPES,\n  MEDIA_FIELD_TYPES,\n  MULTI_VALUE_FIELD_TYPES,\n} from '$lib/services/contents/fields';\nimport { getComponentDef } from '$lib/services/contents/fields/rich-text/components/definitions';\nimport { isMultiple } from '$lib/services/integrations/media-libraries/multiple';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * FieldWithSubFields,\n * FieldWithTypes,\n * ListFieldWithSubField,\n * MediaField,\n * MultiValueField,\n * ObjectFieldWithSubFields,\n * } from '$lib/types/public';\n */\n\nconst TYPE_MATCH_REGEX = /^(.*?)<([^>]+)>(.*)$/;\n\n/**\n * @type {Map<string, Field | undefined>}\n */\nexport const fieldConfigCacheMap = new Map();\n\n/**\n * Check if the given fields contain a single List or KeyValue field with the `root` option enabled.\n * @param {Field[]} fields Field list.\n * @param {'list' | 'keyvalue'} fieldType Field type to check.\n * @returns {boolean} Result.\n */\nexport const hasRootField = (fields, fieldType) => {\n  if (fields.length !== 1) {\n    return false;\n  }\n\n  const [field] = fields;\n\n  return field.widget === fieldType && 'root' in field && field.root === true;\n};\n\n/**\n * Check if multi selection is enabled for the given field configuration.\n * @param {Field} fieldConfig Field configuration.\n * @returns {boolean} Result.\n */\nexport const isFieldMultiple = (fieldConfig) => {\n  const fieldType = fieldConfig.widget ?? 'string';\n\n  if (MEDIA_FIELD_TYPES.includes(fieldType)) {\n    return isMultiple(/** @type {MediaField} */ (fieldConfig));\n  }\n\n  if (MULTI_VALUE_FIELD_TYPES.includes(fieldType)) {\n    return !!(/** @type {MultiValueField} */ (fieldConfig).multiple);\n  }\n\n  return false;\n};\n\n/**\n * Extract explicit type from a key segment with syntax like `<typeName>` or `*<typeName>`.\n * @param {string} key The key segment to parse.\n * @returns {{ cleanKey: string; typeName?: string }} Object with cleaned key and optional type.\n */\nconst parseExplicitType = (key) => {\n  // Match patterns like \"*<type>\", \"<type>\", or \"0<type>\" or \"fieldName<type>\"\n  const match = key.match(TYPE_MATCH_REGEX);\n\n  if (!match) {\n    return { cleanKey: key };\n  }\n\n  const [, prefix, typeName, suffix] = match;\n\n  // If there’s content after the closing bracket, it’s malformed\n  if (suffix) {\n    return { cleanKey: key };\n  }\n\n  // Return the prefix (which might be *, a number, or field name) and the type\n  return { cleanKey: prefix || '', typeName };\n};\n\n/**\n * Advance the field traversal by one key-path segment.\n * @param {object} args Arguments.\n * @param {Field} args.field The current (parent) field being traversed.\n * @param {string} args.key Raw key-path segment (may contain `<typeName>` syntax).\n * @param {string[]} args.keyPathArray Full split key path.\n * @param {number} args.segmentIndex Index of the current segment in {@link keyPathArray}.\n * @param {string | undefined} args.pendingExplicitType Accumulated explicit type from a prior\n * segment.\n * @param {FlattenedEntryContent} args.valueMap Entry values (for variable-type lookup).\n * @returns {{ field: Field | undefined, explicitType: string | undefined }} The resolved child\n * field and updated explicit type.\n */\nconst resolveNextSegment = ({\n  field,\n  key,\n  keyPathArray,\n  segmentIndex,\n  pendingExplicitType,\n  valueMap,\n}) => {\n  const { cleanKey, typeName } = parseExplicitType(key);\n  const { widget: fieldType = 'text' } = field;\n  const explicitType = typeName != null ? typeName : pendingExplicitType;\n  const isNumericKey = isNumeric(cleanKey);\n  const isWildcardKey = cleanKey === '*';\n\n  // Handle multi-value field types with numeric keys, e.g. `authors.0`\n  if ((isNumericKey || isWildcardKey) && MULTI_VALUE_FIELD_TYPES.includes(fieldType)) {\n    // For single value field, numeric access is not allowed\n    return { field: isFieldMultiple(field) ? field : undefined, explicitType };\n  }\n\n  const { field: subField } = /** @type {ListFieldWithSubField} */ (field);\n  const { fields: subFields } = /** @type {FieldWithSubFields} */ (field);\n  const { types, typeKey = 'type' } = /** @type {FieldWithTypes} */ (field);\n\n  if (subField) {\n    const subFieldName = isNumericKey || isWildcardKey ? keyPathArray[segmentIndex + 1] : undefined;\n\n    // It’s possible to get a single-subfield List field with or without a subfield name (e.g.\n    // `image.0` or `image.0.src`), but when a subfield name is specified, check if it’s valid.\n    // The field could be nested (object inside object), so check recursively.\n    const validSubField =\n      !subFieldName ||\n      subField.name === subFieldName ||\n      (subField.widget === 'object' &&\n        'fields' in subField &&\n        /** @type {ObjectFieldWithSubFields} */ (subField).fields?.some(\n          (f) => f.name === subFieldName,\n        ));\n\n    return { field: validSubField ? subField : undefined, explicitType };\n  }\n\n  if (subFields && (isNumericKey || isWildcardKey)) {\n    // For list field types with multiple fields, numeric keys (like \"0\") should be skipped.\n    // Keep the current field (the list field type) and continue to the next part of the path.\n    return { field, explicitType };\n  }\n\n  if (subFields && !isNumericKey && cleanKey !== '') {\n    return { field: subFields.find(({ name }) => name === cleanKey), explicitType };\n  }\n\n  if (types && (isNumericKey || isWildcardKey)) {\n    // List field type variable types - check for explicit type first, then fall back to valueMap\n    const resolvedType =\n      explicitType ??\n      valueMap[[keyPathArray.slice(0, segmentIndex).join('.'), cleanKey, typeKey].join('.')];\n\n    const nextField = /** @type {Field | undefined} */ (\n      types.find(({ name }) => name === resolvedType)\n    );\n\n    // Clear explicit type after using it for wildcard\n    return { field: nextField, explicitType: isWildcardKey ? undefined : explicitType };\n  }\n\n  if (types && key !== typeKey && cleanKey !== typeKey && cleanKey !== '') {\n    // Object field variable types - check for explicit type first, then fall back to valueMap\n    const resolvedType =\n      explicitType ?? valueMap[[keyPathArray.slice(0, segmentIndex).join('.'), typeKey].join('.')];\n\n    const nextField = types\n      .find(({ name }) => name === resolvedType)\n      ?.fields?.find(({ name }) => name === cleanKey);\n\n    // Clear explicit type after using it\n    return { field: nextField, explicitType: undefined };\n  }\n\n  // If we reach here, the list field is malformed (no `field`, `fields`, or `types`) and\n  // we’re trying to access a nested path, so return undefined\n  return { field: undefined, explicitType };\n};\n\n/**\n * Get the {@link getField} arguments for a field of an entry draft: the draft’s collection, file\n * and index file flag, along with the other arguments given.\n * @template {Partial<Pick<GetFieldArgs, 'keyPath' | 'valueMap' | 'componentName'>>} T\n * @param {Pick<EntryDraft, 'collectionName' | 'fileName' | 'isIndexFile'>} draft Entry draft.\n * @param {T} [args] Other arguments. The key path can be left out, to be added later by the\n * caller.\n * @returns {Pick<GetFieldArgs, 'collectionName' | 'fileName' | 'isIndexFile'> & T} Arguments.\n */\nexport const getDraftFieldArgs = (\n  { collectionName, fileName, isIndexFile },\n  args = /** @type {T} */ ({}),\n) => ({ collectionName, fileName, isIndexFile, ...args });\n\n/**\n * Get a field’s config object that matches the given field name (key path).\n * @param {GetFieldArgs} args Arguments.\n * @returns {Field | undefined} Field configuration.\n */\nexport const getField = (args) => {\n  const {\n    collectionName,\n    fileName = undefined,\n    componentName = undefined,\n    valueMap = {},\n    keyPath,\n    isIndexFile = false,\n  } = args;\n\n  const cacheKey = [\n    collectionName,\n    fileName ?? '',\n    componentName ?? '',\n    keyPath,\n    isIndexFile ? '1' : '0',\n  ].join('|');\n\n  if (fieldConfigCacheMap.has(cacheKey)) {\n    return fieldConfigCacheMap.get(cacheKey);\n  }\n\n  const collection = getCollection(collectionName);\n\n  const collectionFile =\n    collection && fileName ? getCollectionFile(collection, fileName) : undefined;\n\n  // For entry collections, `fileName` is ignored and `collectionFile` will be `undefined`\n  // Only fail if we explicitly need a file/singleton collection but can’t find the file\n  if (!collection || (fileName && collection?._type !== 'entry' && !collectionFile)) {\n    fieldConfigCacheMap.set(cacheKey, undefined);\n\n    return undefined;\n  }\n\n  const { fields: regularFields = [] } =\n    collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  const indexFile = isIndexFile ? getIndexFile(collection) : undefined;\n\n  const fields = componentName\n    ? (getComponentDef(componentName)?.fields ?? [])\n    : (indexFile?.fields ?? regularFields);\n\n  const keyPathArray = keyPath.split('.');\n  /** @type {Field | undefined} */\n  let field;\n  /** @type {string | undefined} - Track explicit type for current nesting level */\n  let currentExplicitType;\n  let hasVariableTypeField = false;\n\n  keyPathArray.forEach((key, index) => {\n    if (index === 0) {\n      // First, try to parse explicit type from the field name itself (for object fields like\n      // \"field<button>\")\n      const { cleanKey, typeName } = parseExplicitType(key);\n\n      field = fields.find(({ name }) => name === cleanKey);\n\n      // If using index file and field not found, try regular fields as fallback\n      if (!field && indexFile?.fields) {\n        field = regularFields.find(({ name }) => name === cleanKey);\n      }\n\n      // Store explicit type for later use\n      if (typeName) {\n        currentExplicitType = typeName;\n      }\n    } else if (field) {\n      const result = resolveNextSegment({\n        field,\n        key,\n        keyPathArray,\n        segmentIndex: index,\n        pendingExplicitType: currentExplicitType,\n        valueMap,\n      });\n\n      field = result.field;\n      currentExplicitType = result.explicitType;\n    }\n\n    if (field && 'types' in field) {\n      hasVariableTypeField = true;\n    }\n  });\n\n  // If we have an explicit type but haven’t applied it yet (e.g., for \"field<button>\" with no\n  // further navigation), apply it now\n  if (currentExplicitType && field && 'types' in field) {\n    const { types } = /** @type {FieldWithTypes} */ (field);\n\n    // @ts-ignore\n    field = types.find(({ name }) => name === currentExplicitType);\n  }\n\n  // Cache the field config if no variable type list/object field is found\n  if (!hasVariableTypeField) {\n    fieldConfigCacheMap.set(cacheKey, field);\n  }\n\n  return field;\n};\n\n/**\n * Convert a field key path to the typed key path a field-level asset folder is registered under: a\n * list index becomes `*`, followed by the subfield name in a single-subfield List field, and a\n * variable type is spelled out. The index of a multi-value field, like an Image field with the\n * `multiple` option, is dropped, because the folder belongs to the field itself.\n * @param {GetFieldArgs} args Arguments. A `valueMap` is required to resolve variable types.\n * @returns {TypedFieldKeyPath} Typed key path.\n * @example\n * // A variable type List field, with `valueMap: { 'blocks.0.type': 'image' }`\n * getTypedKeyPath({ collectionName, keyPath: 'blocks.0.src', valueMap })\n * // => 'blocks.*<image>.src'\n * @example\n * // A variable type Object field, with `valueMap: { 'banner.type': 'hero' }`\n * getTypedKeyPath({ collectionName, keyPath: 'banner.src', valueMap })\n * // => 'banner<hero>.src'\n * @example\n * // A single-subfield List field, `field: { name: 'src', widget: 'image' }`\n * getTypedKeyPath({ collectionName, keyPath: 'photos.0' })\n * // => 'photos.*.src'\n * @example\n * // An Image field with the `multiple` option\n * getTypedKeyPath({ collectionName, keyPath: 'images.1' })\n * // => 'images'\n */\nexport const getTypedKeyPath = ({ keyPath, valueMap = {}, ...args }) => {\n  const keyPathArray = keyPath.split('.');\n\n  return keyPathArray\n    .map((key, index) => {\n      const parentKeyPath = keyPathArray.slice(0, index).join('.');\n      const currentKeyPath = index ? `${parentKeyPath}.${key}` : key;\n\n      if (isNumeric(key)) {\n        const parentField = getField({ ...args, valueMap, keyPath: parentKeyPath });\n        const { widget: parentFieldType = 'text' } = parentField ?? {};\n\n        if (MULTI_VALUE_FIELD_TYPES.includes(parentFieldType)) {\n          return undefined;\n        }\n\n        const { field: subField } = /** @type {ListFieldWithSubField} */ (parentField ?? {});\n        const { types, typeKey = 'type' } = /** @type {FieldWithTypes} */ (parentField ?? {});\n\n        if (subField) {\n          return `*.${subField.name}`;\n        }\n\n        const type = types ? valueMap[`${currentKeyPath}.${typeKey}`] : undefined;\n\n        return type ? `*<${type}>` : '*';\n      }\n\n      const field = getField({ ...args, valueMap, keyPath: currentKeyPath });\n      const { types, typeKey = 'type' } = /** @type {FieldWithTypes} */ (field ?? {});\n\n      const type =\n        field?.widget === 'object' && types ? valueMap[`${currentKeyPath}.${typeKey}`] : undefined;\n\n      return type ? `${key}<${type}>` : key;\n    })\n    .filter((segment) => segment !== undefined)\n    .join('.');\n};\n\n/**\n * Determine the given field’s kind: one of the built-in field types, custom field type or unknown.\n * @param {Field} fieldConfig Field configuration.\n * @returns {'builtin' | 'custom' | 'unknown'} Result.\n */\nexport const getFieldKind = (fieldConfig) => {\n  const fieldType = fieldConfig.widget ?? 'string';\n\n  if (/** @type {string[]} */ (BUILTIN_FIELD_TYPES).includes(fieldType)) {\n    return 'builtin';\n  }\n\n  if (customFieldTypeRegistry.has(fieldType)) {\n    return 'custom';\n  }\n\n  return 'unknown';\n};\n\n/**\n * Check if the field requires data input (and data output if the `omit_empty_optional_fields`\n * option is `true`).\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {InternalLocaleCode} args.locale Current pane’s locale.\n * @returns {boolean} Result.\n */\n// @ts-ignore Hidden field doesn’t have `required` property\nexport const isFieldRequired = ({ fieldConfig: { required = true }, locale }) =>\n  Array.isArray(required) ? required.includes(locale) : !!required;\n\n/**\n * Get the current value of a field, taking into account whether it’s a single or multi-value field.\n * Our internal representation of multi-value fields is a flattened object, so we need to gather all\n * the values for a given key path into an array.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.valueMap Flattened entry content.\n * @param {FieldKeyPath} args.keyPath Key path of the field.\n * @param {boolean} args.isList Whether the field is a list field.\n * @param {boolean} [args.isCustomFieldType] Whether the field is a custom field type. It may have\n * arbitrary data structures, so we can’t assume they are multi-value fields.\n * @returns {any} Current value of the field. For multi-value fields, returns an array of values;\n * for single-value fields, returns the value directly.\n */\nexport const getCurrentValue = ({ valueMap, keyPath, isList, isCustomFieldType = false }) => {\n  const value = valueMap[keyPath];\n\n  // Single value field: custom field requires the list check below as we don’t know the shape\n  if (!isList && !isCustomFieldType) {\n    // An object field stores an empty object placeholder at its own key path\n    return isObject(value) ? (getSubtree(valueMap, keyPath) ?? value) : value;\n  }\n\n  // Multiple values are flattened in the value map object\n  const itemKeys = getListItemKeys(valueMap, keyPath);\n\n  // Multi-value field\n  if (itemKeys.length) {\n    return itemKeys.map((key) => valueMap[key]).filter((val) => val !== undefined);\n  }\n\n  // Single value custom field: an object value is stored under its child key paths, and the\n  // placeholder at the field’s own key path can be missing, since `flatten()` doesn’t write one\n  // when an entry is loaded or a list item is manipulated. Assemble the value from the children\n  // either way rather than handing the control nothing\n  // @see https://github.com/sveltia/sveltia-cms/issues/969\n  if (isCustomFieldType) {\n    return value === undefined || isObject(value)\n      ? (getSubtree(valueMap, keyPath) ?? value)\n      : value;\n  }\n\n  return [];\n};\n","import { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { LocaleCode } from '$lib/types/public';\n */\n\nexport const DATE_REGEX = /^\\d{4}-[01]\\d-[0-3]\\d$/;\nexport const TIME_SUFFIX_REGEX = /T00:00(?::00)?(?:\\.000)?Z$/;\n\n/**\n * Standard date format options.\n * @type {Intl.DateTimeFormatOptions}\n */\nexport const DATE_FORMAT_OPTIONS = { year: 'numeric', month: 'short', day: 'numeric' };\n\n/**\n * Standard time format options.\n * @type {Intl.DateTimeFormatOptions}\n */\nexport const TIME_FORMAT_OPTIONS = { hour: 'numeric', minute: 'numeric', hour12: true };\n\n/**\n * Standard date/time format options.\n * @type {Intl.DateTimeFormatOptions}\n */\nexport const DATE_TIME_FORMAT_OPTIONS = { ...DATE_FORMAT_OPTIONS, ...TIME_FORMAT_OPTIONS };\n\n/**\n * Formatters used by {@link formatDate}, keyed by locale. Creating a formatter is far slower than\n * using one, and a list of dates, such as the commit history, formats many with the same locale.\n * @type {Map<string, Intl.DateTimeFormat>}\n */\nconst dateTimeFormatterCache = new Map();\n\n/**\n * Format the date to a localized string.\n * @param {Date} date Date to format.\n * @param {LocaleCode | null} [locale] Optional locale to use for formatting.\n * @returns {string} Formatted date string.\n */\nexport const formatDate = (date, locale) => {\n  // Same as what `toLocaleString()` gives, where `format()` would throw\n  if (Number.isNaN(date.getTime())) {\n    return 'Invalid Date';\n  }\n\n  return getOrCreate(\n    dateTimeFormatterCache,\n    locale ?? '',\n    () => new Intl.DateTimeFormat(locale ?? undefined, DATE_TIME_FORMAT_OPTIONS),\n  ).format(date);\n};\n\n/**\n * Format a recent date and time briefly, e.g. when a draft backup was made or someone started\n * editing an entry. The date is omitted for today, and the year for this year. Both dates are\n * compared in the user’s time zone, which the time is formatted in as well.\n * @param {object} args Arguments.\n * @param {Date} args.timestamp Date and time.\n * @param {LocaleCode} [args.locale] Locale to format the time in, e.g. the app locale.\n * @param {Date} [args.now] Current time, which defaults to the time of the call.\n * @returns {string} Formatted date and time.\n */\nexport const formatRecentDateTime = ({ timestamp, locale, now = new Date() }) => {\n  const sameYear = now.getFullYear() === timestamp.getFullYear();\n\n  const sameDay =\n    sameYear && now.getMonth() === timestamp.getMonth() && now.getDate() === timestamp.getDate();\n\n  return timestamp.toLocaleString(locale, {\n    year: sameYear ? undefined : 'numeric',\n    month: sameDay ? undefined : 'short',\n    day: sameDay ? undefined : 'numeric',\n    hour: 'numeric',\n    minute: 'numeric',\n  });\n};\n","import { getOrCreate } from '$lib/services/utils/cache';\n\nimport { parseDateTimeConfig } from './config.js';\n\n/**\n * @import { DateTimeField } from '$lib/types/public';\n */\n\nconst TIMEZONE_OFFSET_REGEX =\n  /(?<hours>[+-]\\d{2})(?::?(?<minutes>\\d{2}))?(?::?(?<seconds>\\d{2}))?(?:\\.\\d+)?$|Z$/;\n\n/**\n * Format a string representing a number with leading zeros.\n * @param {string | undefined} str String to format.\n * @returns {string} Formatted string.\n */\nconst formatPart = (str) => String(Math.abs(Number(str))).padStart(2, '0');\n/**\n * Formatters telling the offset of a time zone, keyed by the time zone. A field with the\n * `input_time_zone` option looks the offset up whenever its value is read.\n * @type {Map<string, Intl.DateTimeFormat>}\n */\nconst offsetFormatterCache = new Map();\n\n/**\n * Get a formatter of the offset of a time zone, cached per time zone, as a DateTime field gets the\n * offset each time it’s rendered.\n * @param {string} timeZone IANA time zone identifier.\n * @returns {Intl.DateTimeFormat} Formatter.\n * @throws {RangeError} When the time zone is invalid.\n */\nconst getOffsetFormatter = (timeZone) =>\n  getOrCreate(\n    offsetFormatterCache,\n    timeZone,\n    () => new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' }),\n  );\n\n/**\n * Find the configured IANA timezone whose offset matches the stored value’s explicit offset. This\n * is used to restore the most appropriate timezone when the field allows multiple choices.\n * @param {string | undefined} currentValue Stored value.\n * @param {DateTimeField} fieldConfig Field config.\n * @returns {string | undefined} Matching timezone name, if any.\n */\nexport const getTimeZoneForStoredValue = (currentValue, fieldConfig) => {\n  if (typeof currentValue !== 'string' || !currentValue.trim()) {\n    return undefined;\n  }\n\n  const { inputTimeZone } = parseDateTimeConfig(fieldConfig);\n\n  if (inputTimeZone === 'local' || inputTimeZone === 'utc') {\n    return undefined;\n  }\n\n  const date = new Date(currentValue);\n\n  if (Number.isNaN(date.getTime())) {\n    return undefined;\n  }\n\n  const offsetMatch = currentValue.match(TIMEZONE_OFFSET_REGEX);\n\n  if (!offsetMatch?.groups) {\n    return undefined;\n  }\n\n  const { hours, minutes = '0' } = offsetMatch.groups;\n\n  const storedOffset =\n    offsetMatch[0] === 'Z'\n      ? '+00:00'\n      : `${hours.startsWith('-') ? '-' : '+'}${formatPart(hours)}:${formatPart(minutes)}`;\n\n  const offset =\n    getOffsetFormatter(inputTimeZone)\n      .formatToParts(date)\n      .find((part) => part.type === 'timeZoneName')?.value ?? '';\n\n  return offset.replace('GMT', '') === storedOffset ? inputTimeZone : undefined;\n};\n\n/**\n * Resolve the initial timezone for the editor.\n * @param {string | undefined} currentValue Stored value.\n * @param {DateTimeField} fieldConfig Field configuration.\n * @returns {string | undefined} Initial timezone, if any.\n */\nexport const getInitialTimeZone = (currentValue, fieldConfig) => {\n  const storedTimeZone = getTimeZoneForStoredValue(currentValue, fieldConfig);\n\n  if (storedTimeZone) {\n    return storedTimeZone;\n  }\n\n  const { inputTimeZone, singleCustomTimeZone } = parseDateTimeConfig(fieldConfig);\n\n  if (singleCustomTimeZone) {\n    return singleCustomTimeZone;\n  }\n\n  try {\n    const browserTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n    if (inputTimeZone === 'local') {\n      return browserTimeZone;\n    }\n  } catch {\n    return inputTimeZone === 'local' ? '' : undefined;\n  }\n\n  return undefined;\n};\n\n/**\n * Get a formatted timezone label for display.\n * @param {string} timeZone IANA timezone identifier.\n * @param {Date} [date] Date to calculate offset from. Defaults to current date.\n * @returns {string} Formatted label like `(−05:00) New York`.\n */\nexport const getTimeZoneLabel = (timeZone, date = new Date()) => {\n  try {\n    const offset =\n      getOffsetFormatter(timeZone)\n        .formatToParts(date)\n        .find((part) => part.type === 'timeZoneName')?.value ?? '';\n\n    const cityName = timeZone.split('/').pop()?.replaceAll('_', ' ') ?? timeZone;\n\n    return `(${offset.replace('GMT', '')}) ${cityName}`;\n  } catch {\n    return timeZone;\n  }\n};\n","import { getDateTimeParts } from '@sveltia/utils/datetime';\nimport dayjs from 'dayjs';\nimport dayjsAdvancedFormat from 'dayjs/plugin/advancedFormat';\nimport dayjsCustomParseFormat from 'dayjs/plugin/customParseFormat';\nimport dayjsLocalizedFormat from 'dayjs/plugin/localizedFormat';\nimport dayjsTimeZone from 'dayjs/plugin/timezone';\nimport dayjsUTC from 'dayjs/plugin/utc';\n\nimport { parseDateTimeConfig } from './config.js';\nimport { getFormatLocale } from './locales.js';\nimport {\n  formatInLocale,\n  getDate,\n  getParser,\n  getStoredValueTimeZone,\n  parseWithFormatFallback,\n} from './parse.js';\nimport { getTimeZoneForStoredValue } from './timezone.js';\n\n/**\n * @import { DateTimeFieldNormalizedProps, InternalLocaleCode } from '$lib/types/private';\n * @import { DateTimeField, Field } from '$lib/types/public';\n */\n\ndayjs.extend(dayjsAdvancedFormat);\ndayjs.extend(dayjsCustomParseFormat);\ndayjs.extend(dayjsLocalizedFormat);\ndayjs.extend(dayjsUTC);\ndayjs.extend(dayjsTimeZone);\n\n/**\n * Match a date, alone or at UTC midnight. The entry list shows such a value as the date it’s\n * written with, and any other value as an instant in the browser’s time zone, like the input does.\n */\nconst DATE_ONLY_MATCH_REGEX = /^(?<date>\\d{4}-[01]\\d-[0-3]\\d)(?:T00:00(?::00)?(?:\\.000)?Z)?$/;\nconst TIME_SUFFIX_MATCH_REGEX = /(?:^|T)(?<time>[0-2]\\d:[0-5]\\d)(?!\\d)/;\nconst TIME_WITH_SECONDS_REGEX = /(?:^|T)[0-2]\\d:[0-5]\\d:[0-5]\\d/;\n\n/**\n * Build the display-ready date/time strings from the current parts.\n * @param {object} args Arguments.\n * @param {Date} [args.date] Date to derive parts from.\n * @param {string} [args.timeZone] IANA timezone name.\n * @param {DateTimeFieldNormalizedProps['inputTimeZone']} [args.inputTimeZone] Input timezone\n * setting.\n * @param {boolean} [args.dateOnly] Whether the field is date-only.\n * @param {boolean} [args.timeOnly] Whether the field is time-only.\n * @param {boolean} [args.includeUTCSeconds] Whether to append UTC seconds/milliseconds.\n * @param {boolean} [args.includeSeconds] Whether to include the actual seconds rather than\n * truncating the time to the minute, as the input does with its default `step`.\n * @returns {string} Formatted display string.\n */\nconst formatDateTimeValue = ({\n  date,\n  timeZone,\n  inputTimeZone,\n  dateOnly,\n  timeOnly,\n  includeUTCSeconds = false,\n  includeSeconds = false,\n}) => {\n  const tz = timeZone || (inputTimeZone === 'utc' ? 'UTC' : undefined);\n  const { year, month, day, hour, minute, second } = getDateTimeParts({ date, timeZone: tz });\n  const dateStr = `${year}-${month}-${day}`;\n  const timeStr = `${hour}:${minute}${includeSeconds ? `:${second}` : ''}`;\n\n  if (dateOnly) {\n    return dateStr;\n  }\n\n  if (timeOnly) {\n    return timeStr;\n  }\n\n  if (includeUTCSeconds && tz === 'UTC') {\n    return `${dateStr}T${timeStr}${includeSeconds ? '' : ':00'}.000Z`;\n  }\n\n  return `${dateStr}T${timeStr}`;\n};\n\n/**\n * Whether the value the editor derived from its input should replace the stored value. It shouldn’t\n * when both resolve to the same instant: a user editing an existing entry in a different location\n * than where it was originally written gets an input value shifted to their own time zone, but the\n * epoch doesn’t change. The dates are compared rather than the epochs, because {@link getDate}\n * returns `undefined` for a value it can’t parse, and `NaN !== NaN` would report every such value\n * as a change.\n * @param {object} args Arguments.\n * @param {string | undefined} args.newValue Value derived from the input.\n * @param {string | undefined} args.currentValue Value in the entry draft datastore.\n * @param {DateTimeField} args.fieldConfig Field configuration.\n * @param {InternalLocaleCode} [args.locale] Locale of the content the value belongs to.\n * @returns {boolean} `true` if the stored value should be replaced.\n */\nexport const shouldUpdateValue = ({ newValue, currentValue, fieldConfig, locale }) => {\n  if (newValue === undefined || newValue === currentValue) {\n    return false;\n  }\n\n  const newDate = getDate(newValue, fieldConfig, locale);\n  const oldDate = getDate(currentValue, fieldConfig, locale);\n\n  if (newDate !== undefined && oldDate !== undefined) {\n    return newDate.getTime() !== oldDate.getTime();\n  }\n\n  // Neither value resolves to a date, so there’s no epoch to compare and nothing to tell the two\n  // apart. Writing one unusable string over another would let the editor’s effects syncing the\n  // input and the stored value keep waking each other. Clearing the field is the exception: an\n  // empty value settles on the next run\n  if (newDate === undefined && oldDate === undefined && newValue !== '') {\n    return false;\n  }\n\n  return true;\n};\n\n/**\n * Get the current date/time.\n * @param {DateTimeField} fieldConfig Field configuration.\n * @param {string} [timeZone] IANA timezone name.\n * @param {object} [options] Options.\n * @param {Date} [options.date] Date to use instead of the current date/time.\n * @param {boolean} [options.includeSeconds] Whether to include the seconds.\n * @returns {string} Current date/time in the ISO 8601 format.\n */\nexport const getCurrentDateTime = (\n  fieldConfig,\n  timeZone,\n  { date = undefined, includeSeconds = false } = {},\n) => {\n  const { dateOnly, timeOnly, inputTimeZone } = parseDateTimeConfig(fieldConfig);\n\n  return formatDateTimeValue({\n    date,\n    timeZone,\n    inputTimeZone,\n    dateOnly,\n    timeOnly,\n    includeUTCSeconds: true,\n    includeSeconds,\n  });\n};\n\n/**\n * Format an instant in a time zone, as returned by `dayjs.tz()`, with its wall time and offset in\n * the zone. Day.js keeps such an instance as a `Date` in the browser’s time zone shifted by the\n * offsets, so formatting it directly shifts a wall time in the browser’s DST gap by an hour. The\n * wall time is therefore read as UTC, and the offset applied without converting it again. The\n * Unix timestamp tokens would read that shifted wall time, so the instant’s timestamp is written in\n * their place.\n * @param {dayjs.Dayjs} instant Instant in a time zone.\n * @param {string} format Format string.\n * @param {string} [localeKey] Day.js locale, as returned by `getFormatLocale()`.\n * @returns {string} Formatted value.\n */\nexport const formatInTimeZone = (instant, format, localeKey) => {\n  const epoch = instant.valueOf();\n  const offset = instant.utcOffset();\n  const wallTime = dayjs.utc(epoch + offset * 60_000);\n\n  const _format = format.replaceAll(/\\[[^\\]]+]|X|x/g, (token) =>\n    token === 'X' ? `[${Math.floor(epoch / 1000)}]` : token === 'x' ? `[${epoch}]` : token,\n  );\n\n  return (localeKey ? wallTime.locale(localeKey) : wallTime)\n    .utcOffset(offset, true)\n    .format(_format);\n};\n\n/**\n * Format an instant in the time zone a stored value is read in, so it’s shown with the wall time\n * and offset the field’s input has. See `getStoredValueTimeZone()`. Only the zone’s offset is taken\n * from `.tz()`, which creates its instance from the wall time in the browser’s time zone, shifting\n * one in the browser’s DST gap by an hour.\n * @param {dayjs.Dayjs} instant Instant.\n * @param {string} format Format string.\n * @param {DateTimeField} fieldConfig Field configuration.\n * @param {string} [localeKey] Day.js locale, as returned by `getFormatLocale()`.\n * @returns {string} Formatted value.\n */\nexport const formatInFieldTimeZone = (instant, format, fieldConfig, localeKey) => {\n  const timeZone = getStoredValueTimeZone(fieldConfig);\n\n  return timeZone\n    ? formatInTimeZone(instant.utcOffset(instant.tz(timeZone).utcOffset()), format, localeKey)\n    : formatInLocale(instant, format, localeKey);\n};\n\n/**\n * Get the final storable value from the input value.\n * @param {object} args Arguments.\n * @param {string | undefined} args.inputValue Raw value from the input field.\n * @param {string | undefined} args.currentValue Current value in the entry.\n * @param {DateTimeField} args.fieldConfig Field configuration.\n * @param {string | undefined} [args.timeZone] IANA timezone name.\n * @param {boolean} [args.outputUTC] Whether to output UTC time.\n * @param {InternalLocaleCode} [args.locale] Locale of the content the value belongs to, which a\n * value in a custom format is written in with `localize_format: true`.\n * @returns {string | undefined} The final value.\n */\nexport const getCurrentValue = ({\n  inputValue,\n  currentValue,\n  fieldConfig,\n  timeZone,\n  outputUTC,\n  locale,\n}) => {\n  const {\n    format,\n    dateOnly,\n    timeOnly,\n    inputTimeZone,\n    outputUTC: configOutputUTC,\n  } = parseDateTimeConfig(fieldConfig);\n\n  const _outputUTC = outputUTC ?? configOutputUTC;\n  // Check for a seconds component. The input element omits it with the default `step` of 60,\n  // yielding `HH:mm` or `YYYY-MM-DDTHH:mm`\n  const hasSeconds = !!inputValue && TIME_WITH_SECONDS_REGEX.test(inputValue);\n  const timeFormat = hasSeconds ? 'HH:mm:ss' : 'HH:mm';\n  const inputFormat = dateOnly ? 'YYYY-MM-DD' : timeOnly ? timeFormat : `YYYY-MM-DDT${timeFormat}`;\n\n  const effectiveTimeZone =\n    inputTimeZone === 'utc'\n      ? 'UTC'\n      : inputTimeZone === 'local'\n        ? _outputUTC\n          ? timeZone\n          : undefined\n        : timeZone || inputTimeZone;\n\n  if (inputValue === '') {\n    return '';\n  }\n\n  if (!inputValue) {\n    return undefined;\n  }\n\n  if (format) {\n    const localeKey = getFormatLocale(fieldConfig, locale);\n    // Parse the wall time as UTC when the input is in UTC or in a time zone it’s converted from\n    // below, so a time in the browser’s DST gap isn’t shifted; otherwise parse it as local\n    const parse = getParser(!!effectiveTimeZone);\n    let parsed = parse(inputValue, inputFormat);\n\n    if (!parsed.isValid()) {\n      parsed = parse(inputValue);\n    }\n\n    // Return empty string for invalid dates to avoid storing 'Invalid Date'\n    if (!parsed.isValid()) {\n      return '';\n    }\n\n    // A date has no time zone, so store it as is: converting the midnight it was parsed as would\n    // shift it to the previous day east of UTC\n    if (dateOnly) {\n      return formatInLocale(parsed, format, localeKey);\n    }\n\n    if (!effectiveTimeZone) {\n      return formatInLocale(_outputUTC ? parsed.utc() : parsed, format, localeKey);\n    }\n\n    // Read the wall time in the zone rather than keeping it with `.tz(zone, true)`, which uses the\n    // zone’s offset at the instant the time was parsed as in the browser’s zone, a different one\n    // around a DST change; then optionally convert to UTC\n    const instant = dayjs.tz(parsed.format('YYYY-MM-DDTHH:mm:ss'), effectiveTimeZone);\n\n    return _outputUTC\n      ? formatInLocale(instant.utc(), format, localeKey)\n      : formatInTimeZone(instant, format, localeKey);\n  }\n\n  if (dateOnly) {\n    return inputValue;\n  }\n\n  // Append seconds (and milliseconds) for data format & framework compatibility\n  const timeSuffix = currentValue ? `:00${currentValue.endsWith('.000') ? '.000' : ''}` : ':00';\n\n  if (timeOnly) {\n    const timeValue = hasSeconds ? inputValue : `${inputValue}${timeSuffix}`;\n\n    // Input is already in UTC; store with a `Z` suffix (no conversion needed)\n    return inputTimeZone === 'utc' ? `${timeValue}Z` : timeValue;\n  }\n\n  if (inputTimeZone === 'utc') {\n    // Input is already in UTC; store with `Z` suffix (no conversion needed)\n    return dayjs.utc(inputValue).format();\n  }\n\n  if (_outputUTC) {\n    // Convert the local/custom-timezone input to UTC for storage.\n    const dt = timeZone ? dayjs.tz(inputValue, timeZone) : dayjs(inputValue);\n\n    return dt.utc().format();\n  }\n\n  if (timeZone && inputTimeZone !== 'local') {\n    // Preserve the configured custom timezone offset when output_utc is false.\n    return formatInTimeZone(dayjs.tz(inputValue, timeZone), 'YYYY-MM-DDTHH:mm:ssZ');\n  }\n\n  return hasSeconds ? inputValue : `${inputValue}${timeSuffix}`;\n};\n\n/**\n * Get the current date/time as a value to be stored in the given field, formatted the same way as\n * the field’s input would store it. Used for the `{{now}}` default value and the `auto_now` option.\n * @param {DateTimeField} fieldConfig Field configuration.\n * @param {object} [options] Options.\n * @param {Date} [options.date] Date to use instead of the current date/time.\n * @param {boolean} [options.includeSeconds] Whether to keep the seconds, which the input drops\n * with its default `step`. The `{{now}}` default value is filled in the input, so it doesn’t, while\n * a timestamp set on save does.\n * @param {InternalLocaleCode} [options.locale] Locale of the content the value is stored in.\n * @returns {string} Current date/time.\n */\nexport const getCurrentStorableValue = (\n  fieldConfig,\n  { date = undefined, includeSeconds = false, locale = undefined } = {},\n) => {\n  const { singleCustomTimeZone: timeZone, outputUTC } = parseDateTimeConfig(fieldConfig);\n\n  return /** @type {string} */ (\n    getCurrentValue({\n      inputValue: getCurrentDateTime(fieldConfig, timeZone, { date, includeSeconds }),\n      currentValue: '',\n      fieldConfig,\n      timeZone,\n      outputUTC,\n      locale,\n    })\n  );\n};\n\n/**\n * Get the input value given the current value.\n * @param {object} args Arguments.\n * @param {string | undefined} args.currentValue Value in the entry draft datastore.\n * @param {DateTimeField} args.fieldConfig Field configuration.\n * @param {string} [args.timeZone] IANA timezone name.\n * @param {InternalLocaleCode} [args.locale] Locale of the content the value belongs to.\n * @returns {string | undefined} New value.\n */\nexport const getInputValue = ({ currentValue, fieldConfig, timeZone, locale }) => {\n  const { dateOnly, timeOnly, inputTimeZone, format } = parseDateTimeConfig(fieldConfig);\n  const displayTimeZone = getTimeZoneForStoredValue(currentValue, fieldConfig) ?? timeZone;\n  const localeKey = format ? getFormatLocale(fieldConfig, locale) : undefined;\n\n  // If the default value is an empty string, the input will be blank by default\n  if (!currentValue) {\n    return '';\n  }\n\n  // If the current value is the standard format, return it as is. A value in the custom format has\n  // to be parsed with it instead: a 12-hour time like `02:30 PM` starts with the same digits as\n  // `02:30` but means `14:30`\n  const value =\n    format && dayjs(currentValue, format, localeKey, true).isValid()\n      ? undefined\n      : dateOnly\n        ? currentValue.match(DATE_ONLY_MATCH_REGEX)?.groups?.date\n        : timeOnly\n          ? // Match both `YYYY-MM-DDTHH:mm(:ss)` and `HH:mm(:ss)` formats\n            currentValue.match(TIME_SUFFIX_MATCH_REGEX)?.groups?.time\n          : undefined;\n\n  if (value) {\n    return value;\n  }\n\n  // A date stored in the custom format has no time zone either, so read it as is. Parsing it as UTC\n  // midnight with `output_utc` and showing it in a time zone west of UTC would shift it to the\n  // previous day\n  if (dateOnly && format) {\n    const parsed = parseWithFormatFallback({\n      value: currentValue,\n      format,\n      parseAsUTC: false,\n      localeKey,\n    });\n\n    return parsed.isValid() ? parsed.format('YYYY-MM-DD') : '';\n  }\n\n  // `getDate()` reads a value without an offset in the field’s time zone, which the input shows\n  const dateForParts = getDate(currentValue, fieldConfig, locale);\n\n  // If `getDate` returned `undefined` (parsing failed), return empty string\n  if (!dateForParts) {\n    return '';\n  }\n\n  return formatDateTimeValue({\n    date: dateForParts,\n    timeZone: displayTimeZone,\n    inputTimeZone,\n    dateOnly,\n    timeOnly,\n  });\n};\n\n/**\n * Localize a DateTime field value copied from another locale. With `localize_format: true`, a value\n * in a custom format is written in the locale of the content it belongs to, so it’s parsed in the\n * source locale and written again in the target locale. The wall-clock time is read as UTC, so the\n * value is written with the same date and time whatever the field’s time zone; a value with a UTC\n * offset is written in UTC. Any other value, including one that can’t be parsed, is returned as is.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {any} args.value Value copied from the source locale.\n * @param {InternalLocaleCode} args.sourceLocale Source locale.\n * @param {InternalLocaleCode} args.targetLocale Target locale.\n * @returns {any} Localized value.\n */\nexport const getLocalizedDateTimeValue = ({ fieldConfig, value, sourceLocale, targetLocale }) => {\n  if (\n    fieldConfig.widget !== 'datetime' ||\n    /** @type {DateTimeField} */ (fieldConfig).localize_format !== true ||\n    typeof value !== 'string' ||\n    !value\n  ) {\n    return value;\n  }\n\n  const config = /** @type {DateTimeField} */ (fieldConfig);\n  const { format } = parseDateTimeConfig(config);\n  const sourceLocaleKey = getFormatLocale(config, sourceLocale);\n  const targetLocaleKey = getFormatLocale(config, targetLocale);\n\n  if (!format || sourceLocaleKey === targetLocaleKey) {\n    return value;\n  }\n\n  const parsed = parseWithFormatFallback({\n    value,\n    format,\n    parseAsUTC: true,\n    localeKey: sourceLocaleKey,\n  });\n\n  // English is Day.js’ default locale, which has to be set explicitly on a value parsed in another\n  return parsed.isValid() ? formatInLocale(parsed, format, targetLocaleKey ?? 'en') : value;\n};\n","import dayjs from 'dayjs';\nimport dayjsAdvancedFormat from 'dayjs/plugin/advancedFormat';\nimport dayjsCustomParseFormat from 'dayjs/plugin/customParseFormat';\nimport dayjsLocalizedFormat from 'dayjs/plugin/localizedFormat';\nimport dayjsTimeZone from 'dayjs/plugin/timezone';\nimport dayjsUTC from 'dayjs/plugin/utc';\n\nimport { getCanonicalLocale } from '$lib/services/contents/i18n';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport {\n  DATE_FORMAT_OPTIONS,\n  DATE_REGEX,\n  TIME_FORMAT_OPTIONS,\n  TIME_SUFFIX_REGEX,\n} from '$lib/services/utils/date';\n\nimport { parseDateTimeConfig } from './config.js';\nimport { getFormatLocale } from './locales.js';\nimport {\n  getDate,\n  hasOffsetOutsideFormat,\n  hasOffsetToken,\n  isValidDate,\n  parseWithFormatFallback,\n} from './parse.js';\nimport { formatInFieldTimeZone, formatInTimeZone } from './value.js';\n\n/**\n * @import { Dayjs } from 'dayjs';\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { DateTimeField } from '$lib/types/public';\n */\n\ndayjs.extend(dayjsAdvancedFormat);\ndayjs.extend(dayjsCustomParseFormat);\ndayjs.extend(dayjsLocalizedFormat);\ndayjs.extend(dayjsUTC);\ndayjs.extend(dayjsTimeZone);\n\n/**\n * Cache of the formatters used by {@link getDateTimeFieldDisplayValue}, keyed by locale, the parts\n * shown and time zone. `Date.prototype.toLocaleString()` and the like create a new formatter on\n * each call when options are given, which is an order of magnitude slower than reusing one, and a\n * display value is resolved for every referenced entry when the options of a Relation field are\n * built. The keys come from the site configuration, so the cache stays small.\n * @type {Map<string, Intl.DateTimeFormat>}\n */\nconst displayFormatterCache = new Map();\n\n/**\n * Get a cached formatter for {@link getDateTimeFieldDisplayValue}. The options are the same as the\n * ones the `Date` locale methods would be given, so the output is identical.\n * @param {object} args Arguments.\n * @param {string | undefined} args.locale Canonical locale.\n * @param {'date' | 'time' | 'datetime'} args.parts Parts to be shown.\n * @param {string | undefined} args.timeZone Time zone.\n * @returns {Intl.DateTimeFormat} Formatter.\n */\nconst getDisplayFormatter = ({ locale, parts, timeZone }) =>\n  getOrCreate(displayFormatterCache, [locale, parts, timeZone].join('|'), () => {\n    if (parts === 'time') {\n      return new Intl.DateTimeFormat(locale, { ...TIME_FORMAT_OPTIONS, timeZone });\n    }\n\n    if (parts === 'date') {\n      return new Intl.DateTimeFormat(locale, { ...DATE_FORMAT_OPTIONS, timeZone });\n    }\n\n    return new Intl.DateTimeFormat(locale, {\n      ...DATE_FORMAT_OPTIONS,\n      ...TIME_FORMAT_OPTIONS,\n      timeZone,\n      timeZoneName: undefined,\n    });\n  });\n\n/**\n * Match a UTC offset written in a value, like `+09:00` or `-0800`.\n */\nconst OFFSET_TEXT_REGEX = /[+-]\\d{2}:?\\d{2}/g;\n\n/**\n * Check if a value in a format with a UTC offset token is written in the format exactly, with one\n * of the offsets it contains. Day.js reads such a value as an instant in the browser’s time zone,\n * so its strict mode would only accept a value written with the browser’s offset.\n * @param {string} value Stored value.\n * @param {Dayjs} instant Instant the value was parsed as.\n * @param {string} format Format string.\n * @param {string} [localeKey] Day.js locale, as returned by `getFormatLocale()`.\n * @returns {boolean} Result.\n */\nconst isWrittenWithOffset = (value, instant, format, localeKey) =>\n  [...new Set(value.match(OFFSET_TEXT_REGEX))].some(\n    (offset) => formatInTimeZone(instant.utcOffset(offset), format, localeKey) === value,\n  );\n\n/**\n * Get the display value of a DateTime field.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {DateTimeField} args.fieldConfig Field configuration.\n * @param {string | undefined} args.currentValue Stored value.\n * @returns {string} Display value.\n */\nexport const getDateTimeFieldDisplayValue = ({ locale, fieldConfig, currentValue }) => {\n  const { format, dateOnly, timeOnly, utc, singleCustomTimeZone } =\n    parseDateTimeConfig(fieldConfig);\n\n  const displayTimeZone = utc ? 'UTC' : singleCustomTimeZone;\n\n  if (typeof currentValue !== 'string' || !currentValue.trim()) {\n    return '';\n  }\n\n  if (format) {\n    const localeKey = getFormatLocale(fieldConfig, locale);\n\n    // A value with an offset the format can’t hold, like an ISO 8601 value written before the\n    // format was set, is an instant shown in the field’s time zone. Any other value is shown as\n    // written, which is also much faster than converting it to a time zone\n    if (hasOffsetOutsideFormat(currentValue, format)) {\n      const date = getDate(currentValue, fieldConfig, locale);\n\n      return date ? formatInFieldTimeZone(dayjs(date), format, fieldConfig, localeKey) : '';\n    }\n\n    const parsed = parseWithFormatFallback({\n      value: currentValue,\n      format,\n      parseAsUTC: utc,\n      localeKey,\n    });\n\n    if (parsed.isValid()) {\n      if (!hasOffsetToken(format)) {\n        return parsed.format(format);\n      }\n\n      // Day.js reads a value with an offset, or a Unix timestamp, as an instant in the browser’s\n      // time zone. One written in the format is shown as written; any other, like an ISO 8601 value\n      // written before the format was set, is shown in the field’s time zone, like the input does\n      return isWrittenWithOffset(currentValue, parsed, format, localeKey)\n        ? currentValue\n        : formatInFieldTimeZone(parsed, format, fieldConfig, localeKey);\n    }\n\n    // eslint-disable-next-line no-console\n    console.error('Invalid Date', currentValue);\n\n    return '';\n  }\n\n  const date = getDate(currentValue, fieldConfig, locale);\n  const canonicalLocale = getCanonicalLocale(locale);\n\n  if (!isValidDate(date)) {\n    return '';\n  }\n\n  if (timeOnly) {\n    return getDisplayFormatter({\n      locale: canonicalLocale,\n      parts: 'time',\n      timeZone: displayTimeZone,\n    }).format(date);\n  }\n\n  if (dateOnly) {\n    // `getDate()` reads a date as UTC midnight, which the custom time zone would show as the\n    // previous day west of UTC, so only a value with a time is shown in that zone\n    return getDisplayFormatter({\n      locale: canonicalLocale,\n      parts: 'date',\n      timeZone:\n        utc || DATE_REGEX.test(currentValue) || TIME_SUFFIX_REGEX.test(currentValue)\n          ? 'UTC'\n          : displayTimeZone,\n    }).format(date);\n  }\n\n  return getDisplayFormatter({\n    locale: canonicalLocale,\n    parts: 'datetime',\n    timeZone: displayTimeZone,\n  }).format(date);\n};\n","import { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { ComputeField, Field, LocaleCode, NumberField } from '$lib/types/public';\n */\n\n/**\n * Cache of {@link Intl.NumberFormat} instances for {@link getNumberFormatter}, keyed by canonical\n * locale.\n * @type {Map<LocaleCode | undefined, Intl.NumberFormat>}\n */\nconst numberFormatterCache = new Map();\n\n/**\n * Get a formatter to display a Number field value. It keeps every fraction digit the value has:\n * the default of {@link Intl.NumberFormat} rounds the value to 3 digits, showing `35.681236` as\n * `35.681` and `0.0004` as `0`.\n * @param {LocaleCode | undefined} canonicalLocale Canonical locale code.\n * @returns {Intl.NumberFormat} Formatter.\n */\nexport const getNumberFormatter = (canonicalLocale) =>\n  getOrCreate(numberFormatterCache, canonicalLocale, () =>\n    Intl.NumberFormat(canonicalLocale, { maximumFractionDigits: 20 }),\n  );\n\n/**\n * Get the `value_type` option of a Number or Compute field, with its default: `int` for a Number\n * field, and `string` for a Compute field.\n * @param {NumberField | ComputeField} fieldConfig Field configuration.\n * @returns {string} Value type.\n */\nexport const getValueType = ({ widget, value_type: valueType }) =>\n  valueType ?? (widget === 'compute' ? 'string' : 'int');\n\n/**\n * Whether the field stores its value as a floating-point number rather than an integer. A Compute\n * field with a numeric `value_type` means the same as a Number field’s.\n * @param {NumberField | ComputeField} fieldConfig Field configuration.\n * @returns {boolean} `true` if the `value_type` is `float` or `float/string`.\n */\nexport const isFloatType = (fieldConfig) =>\n  ['float', 'float/string'].includes(getValueType(fieldConfig));\n\n/**\n * Whether the field stores its value as a string rather than a number. That’s the case for the\n * `int/string` and `float/string` types, as well as any custom `value_type`, which includes the\n * `string` type of a Compute field.\n * @param {NumberField | ComputeField} fieldConfig Field configuration.\n * @returns {boolean} `true` if the stored value is a string.\n */\nexport const isStringOutput = (fieldConfig) =>\n  !['int', 'float'].includes(getValueType(fieldConfig));\n\n/**\n * Whether the given field yields a number: a Number field, or a Compute field whose `value_type` is\n * anything but `string`, which makes its `value` an arithmetic expression. The number may still be\n * stored as a string; see {@link storesNumber}.\n * @param {Field} fieldConfig Field configuration.\n * @returns {boolean} Result.\n */\nexport const yieldsNumber = (fieldConfig) =>\n  fieldConfig.widget === 'number' ||\n  (fieldConfig.widget === 'compute' &&\n    getValueType(/** @type {ComputeField} */ (fieldConfig)) !== 'string');\n\n/**\n * Whether the given field stores its value as a number: a Number field or a Compute field with the\n * `int` or `float` value type.\n * @param {Field} fieldConfig Field configuration.\n * @returns {boolean} Result.\n */\nexport const storesNumber = (fieldConfig) =>\n  (fieldConfig.widget === 'number' || fieldConfig.widget === 'compute') &&\n  !isStringOutput(/** @type {NumberField | ComputeField} */ (fieldConfig));\n\n/**\n * Parse the given value as a number, the way a number input does: a number is taken as is, and a\n * string is parsed as a whole, not just its leading digits like `parseInt()` does, which reads\n * `12abc` as `12` and `1e3` as `1`.\n * @param {unknown} value Value.\n * @returns {number} Number, or `NaN` if the value is a blank string or isn’t a number or a string.\n */\nexport const parseNumber = (value) =>\n  typeof value === 'number'\n    ? value\n    : typeof value === 'string' && value.trim()\n      ? Number(value)\n      : Number.NaN;\n\n/**\n * Cast the given number according to the field’s `value_type`: an integer type drops the fraction.\n * @param {number} number Number, which can be `NaN`.\n * @param {NumberField} fieldConfig Field configuration.\n * @returns {number} Number to be stored, or `NaN` if the field can’t store it: it isn’t a finite\n * number, or it’s an integer beyond the range JavaScript can represent exactly.\n */\nconst castNumber = (number, fieldConfig) => {\n  // Adding zero turns `-0` into `0`, which is what `-0` or `-0.4` in an integer field means\n  if (isFloatType(fieldConfig)) {\n    return Number.isFinite(number) ? number + 0 : NaN;\n  }\n\n  const integer = Math.trunc(number);\n\n  return Number.isSafeInteger(integer) ? integer + 0 : NaN;\n};\n\n/**\n * Whether the given stored value of a Number field is something other than a number the field can\n * store, like the text of an input that couldn’t be parsed, which the editor stores so it can be\n * reported as invalid rather than lost.\n * @param {any} value Value in the entry draft.\n * @param {NumberField} fieldConfig Field configuration.\n * @returns {boolean} `true` if the value is invalid. An empty value is not.\n */\nexport const isInvalidNumberValue = (value, fieldConfig) => {\n  if (value === null || value === undefined || (typeof value === 'string' && !value.trim())) {\n    return false;\n  }\n\n  return Number.isNaN(castNumber(Number(value), fieldConfig));\n};\n\n/**\n * Get the value to be stored in the entry draft for the given number input value, cast according\n * to the field’s `value_type`.\n * @param {object} args Arguments.\n * @param {number | string | undefined} args.inputValue Value of the number input. `undefined` if\n * the input is empty, or a string holding the text in the input if it can’t be parsed as a number.\n * @param {NumberField} args.fieldConfig Field configuration.\n * @returns {string | number | null} Value to be stored. An empty input is stored as `null` for the\n * number types, or an empty string for the string types. Text that isn’t a number, a non-finite\n * number like `Infinity` and an integer beyond the safe range are stored as a string, which the\n * validation reports as invalid, instead of being silently dropped or changed: `Infinity` would be\n * written as `.inf` in YAML or `null` in JSON, and `1e21` would be read as `1` by `parseInt()`.\n */\nexport const getNumberFieldValue = ({ inputValue, fieldConfig }) => {\n  if (typeof inputValue === 'string') {\n    return inputValue;\n  }\n\n  if (inputValue === undefined || Number.isNaN(inputValue)) {\n    return isStringOutput(fieldConfig) ? '' : null;\n  }\n\n  const value = castNumber(inputValue, fieldConfig);\n\n  if (Number.isNaN(value)) {\n    return String(inputValue);\n  }\n\n  return isStringOutput(fieldConfig) ? String(value) : value;\n};\n\n/**\n * Get the value to be shown in the editor’s number input for the given stored value.\n * @param {object} args Arguments.\n * @param {string | number | null | undefined} args.currentValue Value in the entry draft.\n * @param {NumberField} args.fieldConfig Field configuration.\n * @param {number | string | undefined} [args.inputValue] Current input value. If the stored value\n * is the invalid value it converts to, the input is kept as is, so the text the user is typing\n * isn’t replaced.\n * @returns {number | string | undefined} Number to be shown. `undefined` if there is no stored\n * value, or it is blank or can’t be parsed, which empties the input.\n */\nexport const getNumberInputValue = ({ currentValue, fieldConfig, inputValue = undefined }) => {\n  if (\n    isInvalidNumberValue(currentValue, fieldConfig) &&\n    currentValue === getNumberFieldValue({ inputValue, fieldConfig })\n  ) {\n    return inputValue;\n  }\n\n  if (typeof currentValue === 'number') {\n    return currentValue;\n  }\n\n  if (typeof currentValue !== 'string' || !currentValue.trim()) {\n    return undefined;\n  }\n\n  // Parse the whole string, not just its leading digits like `parseInt()` does, which reads `1e21`\n  // as `1`\n  const value = castNumber(Number(currentValue), fieldConfig);\n\n  return Number.isNaN(value) ? undefined : value;\n};\n","import { getEntryDisplayLocale } from '$lib/services/contents/entry/paths';\nimport { getPropertyValue } from '$lib/services/contents/entry/values';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * Check whether a raw field value is empty, so that the entry has nothing to sort or group by.\n * @param {any} value Raw value.\n * @returns {boolean} Whether the value is `undefined`, `null` or an empty string.\n */\nexport const isEmptyValue = (value) => value === undefined || value === null || value === '';\n\n/**\n * Get an entry’s field value in the locale the entry is listed in, for the collection’s `filter`\n * option and the entry list’s sorting, filtering and grouping. That’s the default locale, or the\n * first locale the entry has if it lacks the default one, e.g. a multi-file i18n entry with only\n * `hello.fr.md`, like its summary. See `getEntryDisplayLocale()`.\n * @param {Parameters<typeof getPropertyValue>[0]} args Arguments for `getPropertyValue()`, where\n * `locale` is the default locale of the collection.\n * @returns {any} Value.\n */\nexport const getListedEntryValue = ({ entry, locale, ...rest }) =>\n  getPropertyValue({\n    ...rest,\n    entry,\n    // An entry without any locale has no value, so the locale doesn’t matter\n    locale: /** @type {InternalLocaleCode} */ (getEntryDisplayLocale(entry.locales, locale)),\n  });\n\n/**\n * Normalize the value of a multi-value field, which comes as an array of the item values: a List\n * field, or a Relation, Select or media field with `multiple: true`. The empty items are dropped,\n * and an array left without any item is no value at all, rather than an empty string once\n * stringified, so the entry sorts last and falls into the “Other” group like any entry without a\n * value. Any other value is returned as is.\n * @param {any} value Value from {@link getListedEntryValue}.\n * @returns {any} Normalized value.\n */\nexport const normalizeMultiValue = (value) => {\n  if (!Array.isArray(value)) {\n    return value;\n  }\n\n  const items = value.filter((item) => !isEmptyValue(item));\n\n  return items.length ? items : undefined;\n};\n","import { allEntryFolders } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getOrCreate, memoizeOnSource } from '$lib/services/utils/cache';\n\n/**\n * @import { EntryFolderInfo, InternalEntryCollection } from '$lib/types/private';\n */\n\n/**\n * Index of `allEntryFolders` for {@link getEntryFoldersByPath} to avoid rescanning it on every\n * call, rebuilt when the store is replaced.\n * `fileMap`: maps each locale-specific file path to the matching `EntryFolderInfo` objects\n * (file/singleton collections). Provides O(1) lookup instead of O(n×m) linear scan.\n * `regexFolders`: entry collections that use `fullPathRegEx`; regex is pre-fetched once.\n * @type {() => {\n * fileMap: Map<string, EntryFolderInfo[]>,\n * regexFolders: Array<[EntryFolderInfo, RegExp | undefined]>,\n * }}\n */\nconst getEntryFolderCache = memoizeOnSource(\n  () => allEntryFolders.current,\n  (_allEntryFolders) => {\n    /** @type {Map<string, EntryFolderInfo[]>} */\n    const fileMap = new Map();\n    /** @type {Array<[EntryFolderInfo, RegExp | undefined]>} */\n    const regexFolders = [];\n\n    _allEntryFolders.forEach((folder) => {\n      if (folder.filePathMap) {\n        // Pre-index every locale-specific path so lookups are O(1).\n        // Deduplicate paths first: multiple locales can share the same physical file path, and\n        // we only want the folder to appear once per path in the results.\n        [...new Set(Object.values(folder.filePathMap))].forEach((filePath) => {\n          getOrCreate(fileMap, filePath, () => []).push(folder);\n        });\n      } else {\n        // Pre-fetch the regex so we avoid calling getCollection() per path per call\n        regexFolders.push([\n          folder,\n          /** @type {InternalEntryCollection} */ (getCollection(folder.collectionName))?._file\n            ?.fullPathRegEx,\n        ]);\n      }\n    });\n\n    return { fileMap, regexFolders };\n  },\n);\n\n/**\n * Get collection entry folders that match the given path.\n * @param {string} path Entry path.\n * @returns {EntryFolderInfo[]} Entry folders. Sometimes it’s hard to find the right folder because\n * multiple collections can have the same folder or partially overlapping folder paths, but the\n * first one is most likely what you need. The ones declaring the exact path, if any, are returned\n * alone.\n */\nexport const getEntryFoldersByPath = (path) => {\n  const { fileMap, regexFolders } = getEntryFolderCache();\n  const fileFolders = fileMap.get(path);\n\n  // A file/singleton collection declares the exact path, so it claims the file over an entry\n  // collection, whose folder may happen to contain the same file. This notably applies to Hugo’s\n  // special index file: `content/blog/_index.md` can be declared as a file collection item while\n  // `content/blog` is also an entry collection’s folder. The entry collection doesn’t list the file\n  // then, or it could be edited with the wrong fields or deleted from there\n  if (fileFolders) {\n    return fileFolders;\n  }\n\n  // Deeper folder paths are more specific, so sort them in descending order\n  return regexFolders\n    .filter(([, regex]) => regex?.test(path))\n    .map(([folder]) => folder)\n    .sort((a, b) => (b.folderPath ?? '').localeCompare(a.folderPath ?? ''));\n};\n","import { allEntryFolders } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getEntryFoldersByPath } from '$lib/services/contents/folders';\nimport { getOrCreate, memoizeOnSource } from '$lib/services/utils/cache';\n\n/**\n * @import { Entry, EntryFolderInfo, InternalCollection } from '$lib/types/private';\n */\n\n/**\n * Cache of {@link getEntryFolders} results, dropped whenever `allEntryFolders` changes. The lookup\n * tests the entry’s path against every entry collection’s folder and sorts the matches, and it’s\n * repeated for every entry on each search keystroke, asset reference scan and so on. An entry is\n * replaced rather than modified when its files change, so its object is a safe key.\n */\nconst getEntryFoldersCache = memoizeOnSource(\n  () => allEntryFolders.current,\n  () => /** @type {WeakMap<Entry, EntryFolderInfo[]>} */ (new WeakMap()),\n);\n\n/**\n * Get the collection entry folders matching the given entry’s path.\n * @param {Entry} entry Entry.\n * @returns {EntryFolderInfo[]} Entry folders.\n */\nconst getEntryFolders = (entry) =>\n  getOrCreate(getEntryFoldersCache(), entry, () =>\n    getEntryFoldersByPath(Object.values(entry.locales)[0].path),\n  );\n\n/**\n * Get a list of collections the given entry belongs to. One entry can theoretically appear in\n * multiple collections depending on the configuration, so that the result is an array.\n * @param {Entry} entry Entry.\n * @returns {InternalCollection[]} Collections.\n */\nexport const getAssociatedCollections = (entry) =>\n  getEntryFolders(entry)\n    .map(({ collectionName }) => getCollection(collectionName))\n    .filter((collection) => !!collection);\n","/**\n * @import { FlattenedEntryContent } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * ListFieldWithSubField,\n * ListFieldWithSubFields,\n * ListFieldWithTypes,\n * VariableFieldType,\n * } from '$lib/types/public';\n */\n\n/**\n * Get the subfields of an Object field or a List field item whose value is stored in flattened\n * content: the field’s `fields`, or, with the `types` option, those of the variable type whose\n * name is stored under the type key, e.g. `blocks.0.type`.\n * @param {Field} field Field configuration.\n * @param {FlattenedEntryContent} valueMap Flattened entry content.\n * @param {FieldKeyPath} keyPath Key path of the object or list item.\n * @returns {Field[] | undefined} Subfields, or `undefined` if the field has none, or the stored\n * type name matches no variable type with subfields.\n */\nexport const getFlatSubFields = (field, valueMap, keyPath) => {\n  const {\n    fields,\n    types,\n    typeKey = 'type',\n  } = /** @type {{ fields?: Field[], types?: VariableFieldType[], typeKey?: string }} */ (field);\n\n  return fields ?? types?.find(({ name }) => name === valueMap[`${keyPath}.${typeKey}`])?.fields;\n};\n\n/**\n * Get the subfields of the variable type with the given name.\n * @param {VariableFieldType[]} types Variable types.\n * @param {string | undefined} typeName Type name.\n * @returns {Field[] | undefined} Subfields, or `undefined` if there is no such type.\n */\nexport const getTypeSubFields = (types, typeName) => {\n  const typeConfig = types.find(({ name }) => name === typeName);\n\n  return typeConfig ? (typeConfig.fields ?? []) : undefined;\n};\n\n/**\n * Get the subfields of an Object field value or a list item, resolving the variable type against\n * the type name stored in the value.\n * @param {object} args Arguments.\n * @param {Record<string, any> | undefined} args.value Object value.\n * @param {Field[]} [args.fields] Subfields, if the field has them.\n * @param {VariableFieldType[]} [args.types] Variable types, if the field has them.\n * @param {string} [args.typeKey] Property name holding the variable type name.\n * @returns {Field[]} Subfields.\n */\nexport const getValueSubFields = ({ value, fields, types, typeKey = 'type' }) =>\n  fields ?? (types ? getTypeSubFields(types, value?.[typeKey]) : undefined) ?? [];\n\n/**\n * Map the values nested in the given Object or List field value: the object itself, or each list\n * item, either with the list’s single subfield or as an object with its own subfields, resolving\n * the variable type against the type name stored in the value.\n * @param {any} value Field value.\n * @param {Field} fieldConfig Field configuration.\n * @param {(obj: any, fields: Field[], index?: number) => any} mapObject Function called for an\n * Object field value, and each item of a List field without a single subfield, with its subfields\n * and its index if it’s a list item. The value isn’t necessarily an object.\n * @param {(item: any, field: Field, index: number) => any} mapItem Function called for each item\n * of a List field with a single subfield.\n * @returns {any} Result of `mapObject` for an Object field, a new array of the results for the\n * items of a List field, or the value as is for anything else, e.g. a List field value that isn’t\n * an array.\n */\nexport const mapSubValues = (value, fieldConfig, mapObject, mapItem) => {\n  const { widget } = fieldConfig;\n  const { field } = /** @type {ListFieldWithSubField} */ (fieldConfig);\n\n  const { fields, types, typeKey } = /** @type {ListFieldWithSubFields & ListFieldWithTypes} */ (\n    fieldConfig\n  );\n\n  if (widget === 'object') {\n    return mapObject(value, getValueSubFields({ value, fields, types, typeKey }));\n  }\n\n  if (widget !== 'list' || !Array.isArray(value)) {\n    return value;\n  }\n\n  return value.map((item, index) =>\n    field\n      ? mapItem(item, field, index)\n      : mapObject(item, getValueSubFields({ value: item, fields, types, typeKey }), index),\n  );\n};\n\n/**\n * Get all the subfields of the given field: the `field` of a List field, its `fields`, and the\n * `fields` of every variable type, whichever it has.\n * @param {Field} field Field configuration.\n * @returns {Field[]} Subfields.\n */\nexport const getAllSubFields = (field) => {\n  const {\n    field: subField,\n    fields = [],\n    types = [],\n  } = /** @type {{ field?: Field, fields?: Field[], types?: VariableFieldType[] }} */ (field);\n\n  return [\n    ...(subField ? [subField] : []),\n    ...fields,\n    ...types.flatMap((type) => type.fields ?? []),\n  ];\n};\n\n/**\n * Call the given function for each subfield of the given Object or List field configuration, one\n * level down: the single subfield of a List field, which takes the item’s own key path, the\n * subfields, and those of every variable type. Anything that isn’t a list is skipped, so a raw\n * configuration can be walked before it’s validated.\n * @param {Field} field Field configuration.\n * @param {string} keyPath Key path of the field.\n * @param {(subField: Field, keyPath: string) => void} callback Function called with each subfield\n * and its key path, e.g. `blocks.*.src`.\n * @param {boolean} [typed] Whether to add the variable type name to the key path of its subfields,\n * e.g. `blocks.*<image>.src`.\n */\nexport const forEachSubFieldConfig = (field, keyPath, callback, typed = false) => {\n  const { widget, field: subField, fields, types } = /** @type {any} */ (field);\n\n  if (widget !== 'object' && widget !== 'list') {\n    return;\n  }\n\n  const prefix = widget === 'list' ? `${keyPath}.*` : keyPath;\n\n  /**\n   * Call the function for each field in the given list.\n   * @param {any} list Field list.\n   * @param {string} path Key path of the object holding the fields.\n   */\n  const visit = (list, path) => {\n    if (Array.isArray(list)) {\n      list.forEach((_field) => callback(_field, `${path}.${_field?.name}`));\n    }\n  };\n\n  if (widget === 'list' && subField) {\n    callback(subField, prefix);\n  }\n\n  visit(fields, prefix);\n\n  if (Array.isArray(types)) {\n    types.forEach((type) => visit(type?.fields, typed ? `${prefix}<${type?.name}>` : prefix));\n  }\n};\n\n/**\n * Check whether the given field or any field below it, at any depth, satisfies the predicate.\n * @param {Field} field Field configuration.\n * @param {(field: Field) => boolean} predicate Function that checks a single field.\n * @param {WeakMap<Field, boolean>} [cache] Cache of results keyed by the field configuration, for\n * a predicate that depends on nothing but the configuration. Use one cache per predicate.\n * @returns {boolean} Result.\n */\nexport const someSubField = (field, predicate, cache) => {\n  const cached = cache?.get(field);\n\n  if (cached !== undefined) {\n    return cached;\n  }\n\n  const result =\n    predicate(field) ||\n    getAllSubFields(field).some((subField) => someSubField(subField, predicate, cache));\n\n  cache?.set(field, result);\n\n  return result;\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { mapSubValues, someSubField } from '$lib/services/contents/fields/list/subfields';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import { FlattenedEntryContent, GetFieldArgs } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * ListFieldWithSubFields,\n * ListFieldWithTypes,\n * RawEntryContent,\n * } from '$lib/types/public';\n */\n\n/**\n * Regular expression matching a canonical array index, which a JavaScript object enumerates before\n * any other key, in ascending order, whatever order it was added in. Larger numbers are ordinary\n * keys, see {@link isArrayIndexKey}.\n */\nconst ARRAY_INDEX_REGEX = /^(?:0|[1-9]\\d*)$/;\n/**\n * Regular expression matching the key path of a subfield of a List field item, e.g.\n * `references.0.key`, capturing the list’s key path and the subfield name.\n */\nconst ITEM_SUBFIELD_KEY_PATH_REGEX = /^(.+)\\.\\d+\\.([^.]+)$/;\n\n/**\n * Get the name of the subfield whose value becomes the key of each item of the given field, if\n * it’s a List field with subfields or variable types stored as a map with the `map_key_field`\n * option.\n * @param {Field} fieldConfig Field configuration.\n * @returns {string | undefined} Subfield name.\n * @see https://github.com/sveltia/sveltia-cms/issues/1077\n */\nexport const getMapKeyField = (fieldConfig) => {\n  if (fieldConfig.widget !== 'list' || !('fields' in fieldConfig || 'types' in fieldConfig)) {\n    return undefined;\n  }\n\n  const { map_key_field: keyField } = /** @type {ListFieldWithSubFields | ListFieldWithTypes} */ (\n    fieldConfig\n  );\n\n  return typeof keyField === 'string' && keyField ? keyField : undefined;\n};\n\n/**\n * Check if the given map key is a canonical array index, which a JavaScript object, and therefore\n * every parsed file, moves to the front of the map, so the items wouldn’t keep their order.\n * @param {string} key Map key.\n * @returns {boolean} Result.\n */\nexport const isArrayIndexKey = (key) => ARRAY_INDEX_REGEX.test(key) && Number(key) < 2 ** 32 - 1;\n\n/**\n * Convert a map of keys to items, as stored in a file, to the list items the editor works with,\n * adding each key to its item as the given subfield. An array, e.g. a list saved before the option\n * was added, is returned as is, and so is anything else that isn’t a map of objects, which the List\n * field can’t edit either way.\n * @param {any} value Stored value.\n * @param {string} keyField Name of the subfield holding the key.\n * @returns {any} List items, or the value as is.\n */\nexport const mapToItems = (value, keyField) => {\n  if (!isObject(value) || !Object.values(value).every((item) => item === null || isObject(item))) {\n    return value;\n  }\n\n  // The map key wins over a property of the same name, which can’t be saved anyway\n  return Object.entries(value).map(([key, item]) => ({ ...item, [keyField]: key }));\n};\n\n/**\n * Convert list items to a map of keys to items for the file, taking each key from the given\n * subfield, which is left out of the item. Anything other than an array is returned as is.\n * @param {any} value List items.\n * @param {string} keyField Name of the subfield holding the key.\n * @returns {any} Map, or the value as is.\n */\nexport const itemsToMap = (value, keyField) => {\n  if (!Array.isArray(value)) {\n    return value;\n  }\n\n  return Object.fromEntries(\n    value.map((item) => {\n      const { [keyField]: key = '', ...rest } = isObject(item) ? item : {};\n\n      return [String(key), rest];\n    }),\n  );\n};\n\n/**\n * Cache of whether a field is, or contains at any depth, a List field stored as a map.\n * @type {WeakMap<Field, boolean>}\n */\nconst mapListCache = new WeakMap();\n\n/**\n * Check whether the given field is, or contains at any depth, a List field with the\n * `map_key_field` option, so content without any can skip the conversion entirely.\n * @param {Field} fieldConfig Field configuration.\n * @returns {boolean} Result.\n */\nconst hasMapList = (fieldConfig) =>\n  someSubField(fieldConfig, (field) => !!getMapKeyField(field), mapListCache);\n\n/**\n * Convert the keyed List fields in the given value of a field, at any depth.\n * @param {any} value Field value.\n * @param {Field} fieldConfig Field configuration.\n * @param {boolean} toItems Whether to convert maps to list items, as when a file is loaded, rather\n * than list items to maps, as when it’s saved.\n * @returns {any} Converted value. It’s the same value if nothing has changed.\n */\nconst convertValue = (value, fieldConfig, toItems) => {\n  if (!hasMapList(fieldConfig)) {\n    return value;\n  }\n\n  const keyField = getMapKeyField(fieldConfig);\n  const source = keyField && toItems ? mapToItems(value, keyField) : value;\n\n  const converted = mapSubValues(\n    source,\n    fieldConfig,\n    // eslint-disable-next-line no-use-before-define\n    (obj, fields) => convertMapLists(obj, fields, toItems),\n    (item, field) => convertValue(item, field, toItems),\n  );\n\n  // Keep the same array if none of the items has changed\n  const result =\n    Array.isArray(converted) && converted.every((item, index) => item === source[index])\n      ? source\n      : converted;\n\n  return keyField && !toItems ? itemsToMap(result, keyField) : result;\n};\n\n/**\n * Convert the List fields with the `map_key_field` option in the given content, at any depth: a\n * map of keys to items, as stored in a file, to the list items the editor works with, or the other\n * way around. The content isn’t modified; an object is copied only if something in it changes.\n * @param {RawEntryContent} content Unflattened entry content.\n * @param {Field[]} fields Fields the content is made of.\n * @param {boolean} toItems Whether to convert maps to list items, as when a file is loaded, rather\n * than list items to maps, as when it’s saved.\n * @returns {RawEntryContent} Converted content.\n * @see https://github.com/sveltia/sveltia-cms/issues/1077\n */\nexport const convertMapLists = (content, fields, toItems) => {\n  if (!isObject(content)) {\n    return content;\n  }\n\n  /** @type {RawEntryContent} */\n  let result = content;\n\n  fields.forEach((fieldConfig) => {\n    const { name } = fieldConfig;\n\n    if (!Object.hasOwn(content, name)) {\n      return;\n    }\n\n    const value = convertValue(content[name], fieldConfig, toItems);\n\n    if (value !== content[name]) {\n      if (result === content) {\n        result = { ...content };\n      }\n\n      result[name] = value;\n    }\n  });\n\n  return result;\n};\n\n/**\n * Get the List field the given key path is the key subfield of, if any, e.g. `references` for\n * `references.0.key` when the list has `map_key_field: key`.\n * @param {GetFieldArgs} getFieldArgs Arguments for {@link getField}, with the key path of the\n * subfield.\n * @returns {{ listKeyPath: FieldKeyPath, keyField: string } | undefined} The list’s key path and\n * the subfield name, or `undefined` if the key path isn’t a key subfield.\n */\nexport const getMapKeyInfo = (getFieldArgs) => {\n  // A List field in a rich text editor component is saved with the component, not as a map\n  if (getFieldArgs.componentName) {\n    return undefined;\n  }\n\n  const [, listKeyPath, name] = getFieldArgs.keyPath.match(ITEM_SUBFIELD_KEY_PATH_REGEX) ?? [];\n\n  if (!listKeyPath) {\n    return undefined;\n  }\n\n  const listField = getField({ ...getFieldArgs, keyPath: listKeyPath });\n\n  if (!listField || getMapKeyField(listField) !== name) {\n    return undefined;\n  }\n\n  return { listKeyPath, keyField: name };\n};\n\n/**\n * Get the key paths of the key subfield of every item of a keyed List field, e.g.\n * `references.0.key`, `references.1.key` and so on.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.valueMap Entry values.\n * @param {FieldKeyPath} args.listKeyPath Key path of the list.\n * @param {string} args.keyField Name of the key subfield.\n * @returns {FieldKeyPath[]} Key paths.\n */\nexport const getMapKeyPaths = ({ valueMap, listKeyPath, keyField }) => {\n  const prefix = `${listKeyPath}.`;\n  const suffix = `.${keyField}`;\n\n  // This runs as the user types a key, so the cheap string tests are done first\n  return Object.keys(valueMap).filter(\n    (keyPath) =>\n      keyPath.startsWith(prefix) &&\n      keyPath.endsWith(suffix) &&\n      isNumeric(keyPath.slice(prefix.length, -suffix.length)),\n  );\n};\n\n/**\n * Check whether another item of the same keyed List field has the same key.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.valueMap Entry values.\n * @param {FieldKeyPath} args.keyPath Key path of the key subfield being checked.\n * @param {FieldKeyPath} args.listKeyPath Key path of the list.\n * @param {string} args.keyField Name of the key subfield.\n * @param {any} args.value Key.\n * @returns {boolean} Result.\n */\nexport const isMapKeyTaken = ({ valueMap, keyPath, listKeyPath, keyField, value }) =>\n  getMapKeyPaths({ valueMap, listKeyPath, keyField }).some(\n    (otherKeyPath) =>\n      otherKeyPath !== keyPath &&\n      valueMap[otherKeyPath] !== undefined &&\n      valueMap[otherKeyPath] !== null &&\n      String(valueMap[otherKeyPath]) === String(value),\n  );\n","const ALIAS = Symbol.for('yaml.alias');\nconst DOC = Symbol.for('yaml.document');\nconst MAP = Symbol.for('yaml.map');\nconst PAIR = Symbol.for('yaml.pair');\nconst SCALAR = Symbol.for('yaml.scalar');\nconst SEQ = Symbol.for('yaml.seq');\nconst NODE_TYPE = Symbol.for('yaml.node.type');\nconst isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;\nconst isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;\nconst isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;\nconst isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;\nconst isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;\nconst isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;\nfunction isCollection(node) {\n    if (node && typeof node === 'object')\n        switch (node[NODE_TYPE]) {\n            case MAP:\n            case SEQ:\n                return true;\n        }\n    return false;\n}\nfunction isNode(node) {\n    if (node && typeof node === 'object')\n        switch (node[NODE_TYPE]) {\n            case ALIAS:\n            case MAP:\n            case SCALAR:\n            case SEQ:\n                return true;\n        }\n    return false;\n}\nconst hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;\n\nexport { ALIAS, DOC, MAP, NODE_TYPE, PAIR, SCALAR, SEQ, hasAnchor, isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq };\n","import { isDocument, isNode, isPair, isCollection, isMap, isSeq, isScalar, isAlias } from './nodes/identity.js';\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove node');\n/**\n * Apply a visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n *   - `key`: For sequence values and map `Pair`, the node's index in the\n *     collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n *     `null` for the root node.\n *   - `node`: The current node.\n *   - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this node, continue with next\n *     sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current node, then continue with the next one\n *   - `Node`: Replace the current node, then continue by visiting it\n *   - `number`: While iterating the items of a sequence or map, set the index\n *     of the next step. This is useful especially if the index of the current\n *     node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nfunction visit(node, visitor) {\n    const visitor_ = initVisitor(visitor);\n    if (isDocument(node)) {\n        const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));\n        if (cd === REMOVE)\n            node.contents = null;\n    }\n    else\n        visit_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisit.SKIP = SKIP;\n/** Remove the current node */\nvisit.REMOVE = REMOVE;\nfunction visit_(key, node, visitor, path) {\n    const ctrl = callVisitor(key, node, visitor, path);\n    if (isNode(ctrl) || isPair(ctrl)) {\n        replaceNode(key, path, ctrl);\n        return visit_(key, ctrl, visitor, path);\n    }\n    if (typeof ctrl !== 'symbol') {\n        if (isCollection(node)) {\n            path = Object.freeze(path.concat(node));\n            for (let i = 0; i < node.items.length; ++i) {\n                const ci = visit_(i, node.items[i], visitor, path);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    node.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n        }\n        else if (isPair(node)) {\n            path = Object.freeze(path.concat(node));\n            const ck = visit_('key', node.key, visitor, path);\n            if (ck === BREAK)\n                return BREAK;\n            else if (ck === REMOVE)\n                node.key = null;\n            const cv = visit_('value', node.value, visitor, path);\n            if (cv === BREAK)\n                return BREAK;\n            else if (cv === REMOVE)\n                node.value = null;\n        }\n    }\n    return ctrl;\n}\n/**\n * Apply an async visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n *   - `key`: For sequence values and map `Pair`, the node's index in the\n *     collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n *     `null` for the root node.\n *   - `node`: The current node.\n *   - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `Promise`: Must resolve to one of the following values\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this node, continue with next\n *     sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current node, then continue with the next one\n *   - `Node`: Replace the current node, then continue by visiting it\n *   - `number`: While iterating the items of a sequence or map, set the index\n *     of the next step. This is useful especially if the index of the current\n *     node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nasync function visitAsync(node, visitor) {\n    const visitor_ = initVisitor(visitor);\n    if (isDocument(node)) {\n        const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));\n        if (cd === REMOVE)\n            node.contents = null;\n    }\n    else\n        await visitAsync_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisitAsync.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisitAsync.SKIP = SKIP;\n/** Remove the current node */\nvisitAsync.REMOVE = REMOVE;\nasync function visitAsync_(key, node, visitor, path) {\n    const ctrl = await callVisitor(key, node, visitor, path);\n    if (isNode(ctrl) || isPair(ctrl)) {\n        replaceNode(key, path, ctrl);\n        return visitAsync_(key, ctrl, visitor, path);\n    }\n    if (typeof ctrl !== 'symbol') {\n        if (isCollection(node)) {\n            path = Object.freeze(path.concat(node));\n            for (let i = 0; i < node.items.length; ++i) {\n                const ci = await visitAsync_(i, node.items[i], visitor, path);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    node.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n        }\n        else if (isPair(node)) {\n            path = Object.freeze(path.concat(node));\n            const ck = await visitAsync_('key', node.key, visitor, path);\n            if (ck === BREAK)\n                return BREAK;\n            else if (ck === REMOVE)\n                node.key = null;\n            const cv = await visitAsync_('value', node.value, visitor, path);\n            if (cv === BREAK)\n                return BREAK;\n            else if (cv === REMOVE)\n                node.value = null;\n        }\n    }\n    return ctrl;\n}\nfunction initVisitor(visitor) {\n    if (typeof visitor === 'object' &&\n        (visitor.Collection || visitor.Node || visitor.Value)) {\n        return Object.assign({\n            Alias: visitor.Node,\n            Map: visitor.Node,\n            Scalar: visitor.Node,\n            Seq: visitor.Node\n        }, visitor.Value && {\n            Map: visitor.Value,\n            Scalar: visitor.Value,\n            Seq: visitor.Value\n        }, visitor.Collection && {\n            Map: visitor.Collection,\n            Seq: visitor.Collection\n        }, visitor);\n    }\n    return visitor;\n}\nfunction callVisitor(key, node, visitor, path) {\n    if (typeof visitor === 'function')\n        return visitor(key, node, path);\n    if (isMap(node))\n        return visitor.Map?.(key, node, path);\n    if (isSeq(node))\n        return visitor.Seq?.(key, node, path);\n    if (isPair(node))\n        return visitor.Pair?.(key, node, path);\n    if (isScalar(node))\n        return visitor.Scalar?.(key, node, path);\n    if (isAlias(node))\n        return visitor.Alias?.(key, node, path);\n    return undefined;\n}\nfunction replaceNode(key, path, node) {\n    const parent = path[path.length - 1];\n    if (isCollection(parent)) {\n        parent.items[key] = node;\n    }\n    else if (isPair(parent)) {\n        if (key === 'key')\n            parent.key = node;\n        else\n            parent.value = node;\n    }\n    else if (isDocument(parent)) {\n        parent.contents = node;\n    }\n    else {\n        const pt = isAlias(parent) ? 'alias' : 'scalar';\n        throw new Error(`Cannot replace node with ${pt} parent`);\n    }\n}\n\nexport { visit, visitAsync };\n","import { isNode } from '../nodes/identity.js';\nimport { visit } from '../visit.js';\n\nconst escapeChars = {\n    '!': '%21',\n    ',': '%2C',\n    '[': '%5B',\n    ']': '%5D',\n    '{': '%7B',\n    '}': '%7D'\n};\nconst escapeTagName = (tn) => tn.replace(/[!,[\\]{}]/g, ch => escapeChars[ch]);\nclass Directives {\n    constructor(yaml, tags) {\n        /**\n         * The directives-end/doc-start marker `---`. If `null`, a marker may still be\n         * included in the document's stringified representation.\n         */\n        this.docStart = null;\n        /** The doc-end marker `...`.  */\n        this.docEnd = false;\n        this.yaml = Object.assign({}, Directives.defaultYaml, yaml);\n        this.tags = Object.assign({}, Directives.defaultTags, tags);\n    }\n    clone() {\n        const copy = new Directives(this.yaml, this.tags);\n        copy.docStart = this.docStart;\n        return copy;\n    }\n    /**\n     * During parsing, get a Directives instance for the current document and\n     * update the stream state according to the current version's spec.\n     */\n    atDocument() {\n        const res = new Directives(this.yaml, this.tags);\n        switch (this.yaml.version) {\n            case '1.1':\n                this.atNextDocument = true;\n                break;\n            case '1.2':\n                this.atNextDocument = false;\n                this.yaml = {\n                    explicit: Directives.defaultYaml.explicit,\n                    version: '1.2'\n                };\n                this.tags = Object.assign({}, Directives.defaultTags);\n                break;\n        }\n        return res;\n    }\n    /**\n     * @param onError - May be called even if the action was successful\n     * @returns `true` on success\n     */\n    add(line, onError) {\n        if (this.atNextDocument) {\n            this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };\n            this.tags = Object.assign({}, Directives.defaultTags);\n            this.atNextDocument = false;\n        }\n        const parts = line.trim().split(/[ \\t]+/);\n        const name = parts.shift();\n        switch (name) {\n            case '%TAG': {\n                if (parts.length !== 2) {\n                    onError(0, '%TAG directive should contain exactly two parts');\n                    if (parts.length < 2)\n                        return false;\n                }\n                const [handle, prefix] = parts;\n                this.tags[handle] = prefix;\n                return true;\n            }\n            case '%YAML': {\n                this.yaml.explicit = true;\n                if (parts.length !== 1) {\n                    onError(0, '%YAML directive should contain exactly one part');\n                    return false;\n                }\n                const [version] = parts;\n                if (version === '1.1' || version === '1.2') {\n                    this.yaml.version = version;\n                    return true;\n                }\n                else {\n                    const isValid = /^\\d+\\.\\d+$/.test(version);\n                    onError(6, `Unsupported YAML version ${version}`, isValid);\n                    return false;\n                }\n            }\n            default:\n                onError(0, `Unknown directive ${name}`, true);\n                return false;\n        }\n    }\n    /**\n     * Resolves a tag, matching handles to those defined in %TAG directives.\n     *\n     * @returns Resolved tag, which may also be the non-specific tag `'!'` or a\n     *   `'!local'` tag, or `null` if unresolvable.\n     */\n    tagName(source, onError) {\n        if (source === '!')\n            return '!'; // non-specific tag\n        if (source[0] !== '!') {\n            onError(`Not a valid tag: ${source}`);\n            return null;\n        }\n        if (source[1] === '<') {\n            const verbatim = source.slice(2, -1);\n            if (verbatim === '!' || verbatim === '!!') {\n                onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);\n                return null;\n            }\n            if (source[source.length - 1] !== '>')\n                onError('Verbatim tags must end with a >');\n            return verbatim;\n        }\n        const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);\n        if (!suffix)\n            onError(`The ${source} tag has no suffix`);\n        const prefix = this.tags[handle];\n        if (prefix) {\n            try {\n                return prefix + decodeURIComponent(suffix);\n            }\n            catch (error) {\n                onError(String(error));\n                return null;\n            }\n        }\n        if (handle === '!')\n            return source; // local tag\n        onError(`Could not resolve tag: ${source}`);\n        return null;\n    }\n    /**\n     * Given a fully resolved tag, returns its printable string form,\n     * taking into account current tag prefixes and defaults.\n     */\n    tagString(tag) {\n        for (const [handle, prefix] of Object.entries(this.tags)) {\n            if (tag.startsWith(prefix))\n                return handle + escapeTagName(tag.substring(prefix.length));\n        }\n        return tag[0] === '!' ? tag : `!<${tag}>`;\n    }\n    toString(doc) {\n        const lines = this.yaml.explicit\n            ? [`%YAML ${this.yaml.version || '1.2'}`]\n            : [];\n        const tagEntries = Object.entries(this.tags);\n        let tagNames;\n        if (doc && tagEntries.length > 0 && isNode(doc.contents)) {\n            const tags = {};\n            visit(doc.contents, (_key, node) => {\n                if (isNode(node) && node.tag)\n                    tags[node.tag] = true;\n            });\n            tagNames = Object.keys(tags);\n        }\n        else\n            tagNames = [];\n        for (const [handle, prefix] of tagEntries) {\n            if (handle === '!!' && prefix === 'tag:yaml.org,2002:')\n                continue;\n            if (!doc || tagNames.some(tn => tn.startsWith(prefix)))\n                lines.push(`%TAG ${handle} ${prefix}`);\n        }\n        return lines.join('\\n');\n    }\n}\nDirectives.defaultYaml = { explicit: false, version: '1.2' };\nDirectives.defaultTags = { '!!': 'tag:yaml.org,2002:' };\n\nexport { Directives };\n","import { isScalar, isCollection } from '../nodes/identity.js';\nimport { visit } from '../visit.js';\n\n/**\n * Verify that the input string is a valid anchor.\n *\n * Will throw on errors.\n */\nfunction anchorIsValid(anchor) {\n    if (/[\\x00-\\x19\\s,[\\]{}]/.test(anchor)) {\n        const sa = JSON.stringify(anchor);\n        const msg = `Anchor must not contain whitespace or control characters: ${sa}`;\n        throw new Error(msg);\n    }\n    return true;\n}\nfunction anchorNames(root) {\n    const anchors = new Set();\n    visit(root, {\n        Value(_key, node) {\n            if (node.anchor)\n                anchors.add(node.anchor);\n        }\n    });\n    return anchors;\n}\n/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */\nfunction findNewAnchor(prefix, exclude) {\n    for (let i = 1; true; ++i) {\n        const name = `${prefix}${i}`;\n        if (!exclude.has(name))\n            return name;\n    }\n}\nfunction createNodeAnchors(doc, prefix) {\n    const aliasObjects = [];\n    const sourceObjects = new Map();\n    let prevAnchors = null;\n    return {\n        onAnchor: (source) => {\n            aliasObjects.push(source);\n            prevAnchors ?? (prevAnchors = anchorNames(doc));\n            const anchor = findNewAnchor(prefix, prevAnchors);\n            prevAnchors.add(anchor);\n            return anchor;\n        },\n        /**\n         * With circular references, the source node is only resolved after all\n         * of its child nodes are. This is why anchors are set only after all of\n         * the nodes have been created.\n         */\n        setAnchors: () => {\n            for (const source of aliasObjects) {\n                const ref = sourceObjects.get(source);\n                if (typeof ref === 'object' &&\n                    ref.anchor &&\n                    (isScalar(ref.node) || isCollection(ref.node))) {\n                    ref.node.anchor = ref.anchor;\n                }\n                else {\n                    const error = new Error('Failed to resolve repeated object (this should not happen)');\n                    error.source = source;\n                    throw error;\n                }\n            }\n        },\n        sourceObjects\n    };\n}\n\nexport { anchorIsValid, anchorNames, createNodeAnchors, findNewAnchor };\n","/**\n * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,\n * in section 24.5.1.1 \"Runtime Semantics: InternalizeJSONProperty\" of the\n * 2021 edition: https://tc39.es/ecma262/#sec-json.parse\n *\n * Includes extensions for handling Map and Set objects.\n */\nfunction applyReviver(reviver, obj, key, val) {\n    if (val && typeof val === 'object') {\n        if (Array.isArray(val)) {\n            for (let i = 0, len = val.length; i < len; ++i) {\n                const v0 = val[i];\n                const v1 = applyReviver(reviver, val, String(i), v0);\n                // eslint-disable-next-line @typescript-eslint/no-array-delete\n                if (v1 === undefined)\n                    delete val[i];\n                else if (v1 !== v0)\n                    val[i] = v1;\n            }\n        }\n        else if (val instanceof Map) {\n            for (const k of Array.from(val.keys())) {\n                const v0 = val.get(k);\n                const v1 = applyReviver(reviver, val, k, v0);\n                if (v1 === undefined)\n                    val.delete(k);\n                else if (v1 !== v0)\n                    val.set(k, v1);\n            }\n        }\n        else if (val instanceof Set) {\n            for (const v0 of Array.from(val)) {\n                const v1 = applyReviver(reviver, val, v0, v0);\n                if (v1 === undefined)\n                    val.delete(v0);\n                else if (v1 !== v0) {\n                    val.delete(v0);\n                    val.add(v1);\n                }\n            }\n        }\n        else {\n            for (const [k, v0] of Object.entries(val)) {\n                const v1 = applyReviver(reviver, val, k, v0);\n                if (v1 === undefined)\n                    delete val[k];\n                else if (v1 !== v0)\n                    val[k] = v1;\n            }\n        }\n    }\n    return reviver.call(obj, key, val);\n}\n\nexport { applyReviver };\n","import { hasAnchor } from './identity.js';\n\n/**\n * Recursively convert any node or its contents to native JavaScript\n *\n * @param value - The input value\n * @param arg - If `value` defines a `toJSON()` method, use this\n *   as its first argument\n * @param ctx - Conversion context, originally set in Document#toJS(). If\n *   `{ keep: true }` is not set, output should be suitable for JSON\n *   stringification.\n */\nfunction toJS(value, arg, ctx) {\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n    if (Array.isArray(value))\n        return value.map((v, i) => toJS(v, String(i), ctx));\n    if (value && typeof value.toJSON === 'function') {\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n        if (!ctx || !hasAnchor(value))\n            return value.toJSON(arg, ctx);\n        const data = { aliasCount: 0, count: 1, res: undefined };\n        ctx.anchors.set(value, data);\n        ctx.onCreate = res => {\n            data.res = res;\n            delete ctx.onCreate;\n        };\n        const res = value.toJSON(arg, ctx);\n        if (ctx.onCreate)\n            ctx.onCreate(res);\n        return res;\n    }\n    if (typeof value === 'bigint' && !ctx?.keep)\n        return Number(value);\n    return value;\n}\n\nexport { toJS };\n","import { applyReviver } from '../doc/applyReviver.js';\nimport { NODE_TYPE, isDocument } from './identity.js';\nimport { toJS } from './toJS.js';\n\nclass NodeBase {\n    constructor(type) {\n        Object.defineProperty(this, NODE_TYPE, { value: type });\n    }\n    /** Create a copy of this node.  */\n    clone() {\n        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /** A plain JavaScript representation of this node. */\n    toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n        if (!isDocument(doc))\n            throw new TypeError('A document argument is required');\n        const ctx = {\n            anchors: new Map(),\n            doc,\n            keep: true,\n            mapAsMap: mapAsMap === true,\n            mapKeyWarned: false,\n            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n        };\n        const res = toJS(this, '', ctx);\n        if (typeof onAnchor === 'function')\n            for (const { count, res } of ctx.anchors.values())\n                onAnchor(res, count);\n        return typeof reviver === 'function'\n            ? applyReviver(reviver, { '': res }, '', res)\n            : res;\n    }\n}\n\nexport { NodeBase };\n","import { anchorIsValid } from '../doc/anchors.js';\nimport { visit } from '../visit.js';\nimport { ALIAS, isAlias, isCollection, isPair, hasAnchor } from './identity.js';\nimport { NodeBase } from './Node.js';\nimport { toJS } from './toJS.js';\n\nclass Alias extends NodeBase {\n    constructor(source) {\n        super(ALIAS);\n        this.source = source;\n        Object.defineProperty(this, 'tag', {\n            set() {\n                throw new Error('Alias nodes cannot have tags');\n            }\n        });\n    }\n    /**\n     * Resolve the value of this alias within `doc`, finding the last\n     * instance of the `source` anchor before this node.\n     */\n    resolve(doc, ctx) {\n        if (ctx?.maxAliasCount === 0)\n            throw new ReferenceError('Alias resolution is disabled');\n        let nodes;\n        if (ctx?.aliasResolveCache) {\n            nodes = ctx.aliasResolveCache;\n        }\n        else {\n            nodes = [];\n            visit(doc, {\n                Node: (_key, node) => {\n                    if (isAlias(node) || hasAnchor(node))\n                        nodes.push(node);\n                }\n            });\n            if (ctx)\n                ctx.aliasResolveCache = nodes;\n        }\n        let found = undefined;\n        for (const node of nodes) {\n            if (node === this)\n                break;\n            if (node.anchor === this.source)\n                found = node;\n        }\n        if (found && ctx) {\n            const { anchors, doc, maxAliasCount } = ctx;\n            let data = anchors.get(found);\n            if (!data) {\n                // Resolve anchors for Node.prototype.toJS()\n                toJS(found, null, ctx);\n                data = anchors.get(found);\n            }\n            /* istanbul ignore if */\n            if (data?.res === undefined) {\n                const msg = 'This should not happen: Alias anchor was not resolved?';\n                throw new ReferenceError(msg);\n            }\n            if (maxAliasCount >= 0) {\n                data.count += 1;\n                if (data.aliasCount === 0)\n                    data.aliasCount = getAliasCount(doc, found, anchors);\n                if (data.count * data.aliasCount > maxAliasCount) {\n                    const msg = 'Excessive alias count indicates a resource exhaustion attack';\n                    throw new ReferenceError(msg);\n                }\n            }\n        }\n        return found;\n    }\n    toJSON(_arg, ctx) {\n        if (!ctx)\n            return { source: this.source };\n        const source = this.resolve(ctx.doc, ctx);\n        if (!source) {\n            const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n            throw new ReferenceError(msg);\n        }\n        return ctx.anchors.get(source).res;\n    }\n    toString(ctx, _onComment, _onChompKeep) {\n        const src = `*${this.source}`;\n        if (ctx) {\n            anchorIsValid(this.source);\n            if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {\n                const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n                throw new Error(msg);\n            }\n            if (ctx.implicitKey)\n                return `${src} `;\n        }\n        return src;\n    }\n}\nfunction getAliasCount(doc, node, anchors) {\n    if (isAlias(node)) {\n        const source = node.resolve(doc);\n        const anchor = anchors && source && anchors.get(source);\n        return anchor ? anchor.count * anchor.aliasCount : 0;\n    }\n    else if (isCollection(node)) {\n        let count = 0;\n        for (const item of node.items) {\n            const c = getAliasCount(doc, item, anchors);\n            if (c > count)\n                count = c;\n        }\n        return count;\n    }\n    else if (isPair(node)) {\n        const kc = getAliasCount(doc, node.key, anchors);\n        const vc = getAliasCount(doc, node.value, anchors);\n        return Math.max(kc, vc);\n    }\n    return 1;\n}\n\nexport { Alias };\n","import { SCALAR } from './identity.js';\nimport { NodeBase } from './Node.js';\nimport { toJS } from './toJS.js';\n\nconst isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');\nclass Scalar extends NodeBase {\n    constructor(value) {\n        super(SCALAR);\n        this.value = value;\n    }\n    toJSON(arg, ctx) {\n        return ctx?.keep ? this.value : toJS(this.value, arg, ctx);\n    }\n    toString() {\n        return String(this.value);\n    }\n}\nScalar.BLOCK_FOLDED = 'BLOCK_FOLDED';\nScalar.BLOCK_LITERAL = 'BLOCK_LITERAL';\nScalar.PLAIN = 'PLAIN';\nScalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';\nScalar.QUOTE_SINGLE = 'QUOTE_SINGLE';\n\nexport { Scalar, isScalarValue };\n","import { Alias } from '../nodes/Alias.js';\nimport { isNode, isPair, MAP, SEQ, isDocument } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\n\nconst defaultTagPrefix = 'tag:yaml.org,2002:';\nfunction findTagObject(value, tagName, tags) {\n    if (tagName) {\n        const match = tags.filter(t => t.tag === tagName);\n        const tagObj = match.find(t => !t.format) ?? match[0];\n        if (!tagObj)\n            throw new Error(`Tag ${tagName} not found`);\n        return tagObj;\n    }\n    return tags.find(t => t.identify?.(value) && !t.format);\n}\nfunction createNode(value, tagName, ctx) {\n    if (isDocument(value))\n        value = value.contents;\n    if (isNode(value))\n        return value;\n    if (isPair(value)) {\n        const map = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);\n        map.items.push(value);\n        return map;\n    }\n    if (value instanceof String ||\n        value instanceof Number ||\n        value instanceof Boolean ||\n        (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere\n    ) {\n        // https://tc39.es/ecma262/#sec-serializejsonproperty\n        value = value.valueOf();\n    }\n    const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;\n    // Detect duplicate references to the same object & use Alias nodes for all\n    // after first. The `ref` wrapper allows for circular references to resolve.\n    let ref = undefined;\n    if (aliasDuplicateObjects && value && typeof value === 'object') {\n        ref = sourceObjects.get(value);\n        if (ref) {\n            ref.anchor ?? (ref.anchor = onAnchor(value));\n            return new Alias(ref.anchor);\n        }\n        else {\n            ref = { anchor: null, node: null };\n            sourceObjects.set(value, ref);\n        }\n    }\n    if (tagName?.startsWith('!!'))\n        tagName = defaultTagPrefix + tagName.slice(2);\n    let tagObj = findTagObject(value, tagName, schema.tags);\n    if (!tagObj) {\n        if (value && typeof value.toJSON === 'function') {\n            // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n            value = value.toJSON();\n        }\n        if (!value || typeof value !== 'object') {\n            const node = new Scalar(value);\n            if (ref)\n                ref.node = node;\n            return node;\n        }\n        tagObj =\n            value instanceof Map\n                ? schema[MAP]\n                : Symbol.iterator in Object(value)\n                    ? schema[SEQ]\n                    : schema[MAP];\n    }\n    if (onTagObj) {\n        onTagObj(tagObj);\n        delete ctx.onTagObj;\n    }\n    const node = tagObj?.createNode\n        ? tagObj.createNode(ctx.schema, value, ctx)\n        : typeof tagObj?.nodeClass?.from === 'function'\n            ? tagObj.nodeClass.from(ctx.schema, value, ctx)\n            : new Scalar(value);\n    if (tagName)\n        node.tag = tagName;\n    else if (!tagObj.default)\n        node.tag = tagObj.tag;\n    if (ref)\n        ref.node = node;\n    return node;\n}\n\nexport { createNode };\n","import { createNode } from '../doc/createNode.js';\nimport { isNode, isPair, isCollection, isScalar } from './identity.js';\nimport { NodeBase } from './Node.js';\n\nfunction collectionFromPath(schema, path, value) {\n    let v = value;\n    for (let i = path.length - 1; i >= 0; --i) {\n        const k = path[i];\n        if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {\n            const a = [];\n            a[k] = v;\n            v = a;\n        }\n        else {\n            v = new Map([[k, v]]);\n        }\n    }\n    return createNode(v, undefined, {\n        aliasDuplicateObjects: false,\n        keepUndefined: false,\n        onAnchor: () => {\n            throw new Error('This should not happen, please report a bug.');\n        },\n        schema,\n        sourceObjects: new Map()\n    });\n}\n// Type guard is intentionally a little wrong so as to be more useful,\n// as it does not cover untypable empty non-string iterables (e.g. []).\nconst isEmptyPath = (path) => path == null ||\n    (typeof path === 'object' && !!path[Symbol.iterator]().next().done);\nclass Collection extends NodeBase {\n    constructor(type, schema) {\n        super(type);\n        Object.defineProperty(this, 'schema', {\n            value: schema,\n            configurable: true,\n            enumerable: false,\n            writable: true\n        });\n    }\n    /**\n     * Create a copy of this collection.\n     *\n     * @param schema - If defined, overwrites the original's schema\n     */\n    clone(schema) {\n        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n        if (schema)\n            copy.schema = schema;\n        copy.items = copy.items.map(it => isNode(it) || isPair(it) ? it.clone(schema) : it);\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /**\n     * Adds a value to the collection. For `!!map` and `!!omap` the value must\n     * be a Pair instance or a `{ key, value }` object, which may not have a key\n     * that already exists in the map.\n     */\n    addIn(path, value) {\n        if (isEmptyPath(path))\n            this.add(value);\n        else {\n            const [key, ...rest] = path;\n            const node = this.get(key, true);\n            if (isCollection(node))\n                node.addIn(rest, value);\n            else if (node === undefined && this.schema)\n                this.set(key, collectionFromPath(this.schema, rest, value));\n            else\n                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n        }\n    }\n    /**\n     * Removes a value from the collection.\n     * @returns `true` if the item was found and removed.\n     */\n    deleteIn(path) {\n        const [key, ...rest] = path;\n        if (rest.length === 0)\n            return this.delete(key);\n        const node = this.get(key, true);\n        if (isCollection(node))\n            return node.deleteIn(rest);\n        else\n            throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n    }\n    /**\n     * Returns item at `key`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    getIn(path, keepScalar) {\n        const [key, ...rest] = path;\n        const node = this.get(key, true);\n        if (rest.length === 0)\n            return !keepScalar && isScalar(node) ? node.value : node;\n        else\n            return isCollection(node) ? node.getIn(rest, keepScalar) : undefined;\n    }\n    hasAllNullValues(allowScalar) {\n        return this.items.every(node => {\n            if (!isPair(node))\n                return false;\n            const n = node.value;\n            return (n == null ||\n                (allowScalar &&\n                    isScalar(n) &&\n                    n.value == null &&\n                    !n.commentBefore &&\n                    !n.comment &&\n                    !n.tag));\n        });\n    }\n    /**\n     * Checks if the collection includes a value with the key `key`.\n     */\n    hasIn(path) {\n        const [key, ...rest] = path;\n        if (rest.length === 0)\n            return this.has(key);\n        const node = this.get(key, true);\n        return isCollection(node) ? node.hasIn(rest) : false;\n    }\n    /**\n     * Sets a value in this collection. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    setIn(path, value) {\n        const [key, ...rest] = path;\n        if (rest.length === 0) {\n            this.set(key, value);\n        }\n        else {\n            const node = this.get(key, true);\n            if (isCollection(node))\n                node.setIn(rest, value);\n            else if (node === undefined && this.schema)\n                this.set(key, collectionFromPath(this.schema, rest, value));\n            else\n                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n        }\n    }\n}\n\nexport { Collection, collectionFromPath, isEmptyPath };\n","/**\n * Stringifies a comment.\n *\n * Empty comment lines are left empty,\n * lines consisting of a single space are replaced by `#`,\n * and all other lines are prefixed with a `#`.\n */\nconst stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');\nfunction indentComment(comment, indent) {\n    if (/^\\n+$/.test(comment))\n        return comment.substring(1);\n    return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;\n}\nconst lineComment = (str, indent, comment) => str.endsWith('\\n')\n    ? indentComment(comment, indent)\n    : comment.includes('\\n')\n        ? '\\n' + indentComment(comment, indent)\n        : (str.endsWith(' ') ? '' : ' ') + comment;\n\nexport { indentComment, lineComment, stringifyComment };\n","const FOLD_FLOW = 'flow';\nconst FOLD_BLOCK = 'block';\nconst FOLD_QUOTED = 'quoted';\n/**\n * Tries to keep input at up to `lineWidth` characters, splitting only on spaces\n * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are\n * terminated with `\\n` and started with `indent`.\n */\nfunction foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {\n    if (!lineWidth || lineWidth < 0)\n        return text;\n    if (lineWidth < minContentWidth)\n        minContentWidth = 0;\n    const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);\n    if (text.length <= endStep)\n        return text;\n    const folds = [];\n    const escapedFolds = {};\n    let end = lineWidth - indent.length;\n    if (typeof indentAtStart === 'number') {\n        if (indentAtStart > lineWidth - Math.max(2, minContentWidth))\n            folds.push(0);\n        else\n            end = lineWidth - indentAtStart;\n    }\n    let split = undefined;\n    let prev = undefined;\n    let overflow = false;\n    let i = -1;\n    let escStart = -1;\n    let escEnd = -1;\n    if (mode === FOLD_BLOCK) {\n        i = consumeMoreIndentedLines(text, i, indent.length);\n        if (i !== -1)\n            end = i + endStep;\n    }\n    for (let ch; (ch = text[(i += 1)]);) {\n        if (mode === FOLD_QUOTED && ch === '\\\\') {\n            escStart = i;\n            switch (text[i + 1]) {\n                case 'x':\n                    i += 3;\n                    break;\n                case 'u':\n                    i += 5;\n                    break;\n                case 'U':\n                    i += 9;\n                    break;\n                default:\n                    i += 1;\n            }\n            escEnd = i;\n        }\n        if (ch === '\\n') {\n            if (mode === FOLD_BLOCK)\n                i = consumeMoreIndentedLines(text, i, indent.length);\n            end = i + indent.length + endStep;\n            split = undefined;\n        }\n        else {\n            if (ch === ' ' &&\n                prev &&\n                prev !== ' ' &&\n                prev !== '\\n' &&\n                prev !== '\\t') {\n                // space surrounded by non-space can be replaced with newline + indent\n                const next = text[i + 1];\n                if (next && next !== ' ' && next !== '\\n' && next !== '\\t')\n                    split = i;\n            }\n            if (i >= end) {\n                if (split) {\n                    folds.push(split);\n                    end = split + endStep;\n                    split = undefined;\n                }\n                else if (mode === FOLD_QUOTED) {\n                    // white-space collected at end may stretch past lineWidth\n                    while (prev === ' ' || prev === '\\t') {\n                        prev = ch;\n                        ch = text[(i += 1)];\n                        overflow = true;\n                    }\n                    // Account for newline escape, but don't break preceding escape\n                    const j = i > escEnd + 1 ? i - 2 : escStart - 1;\n                    // Bail out if lineWidth & minContentWidth are shorter than an escape string\n                    if (escapedFolds[j])\n                        return text;\n                    folds.push(j);\n                    escapedFolds[j] = true;\n                    end = j + endStep;\n                    split = undefined;\n                }\n                else {\n                    overflow = true;\n                }\n            }\n        }\n        prev = ch;\n    }\n    if (overflow && onOverflow)\n        onOverflow();\n    if (folds.length === 0)\n        return text;\n    if (onFold)\n        onFold();\n    let res = text.slice(0, folds[0]);\n    for (let i = 0; i < folds.length; ++i) {\n        const fold = folds[i];\n        const end = folds[i + 1] || text.length;\n        if (fold === 0)\n            res = `\\n${indent}${text.slice(0, end)}`;\n        else {\n            if (mode === FOLD_QUOTED && escapedFolds[fold])\n                res += `${text[fold]}\\\\`;\n            res += `\\n${indent}${text.slice(fold + 1, end)}`;\n        }\n    }\n    return res;\n}\n/**\n * Presumes `i + 1` is at the start of a line\n * @returns index of last newline in more-indented block\n */\nfunction consumeMoreIndentedLines(text, i, indent) {\n    let end = i;\n    let start = i + 1;\n    let ch = text[start];\n    while (ch === ' ' || ch === '\\t') {\n        if (i < start + indent) {\n            ch = text[++i];\n        }\n        else {\n            do {\n                ch = text[++i];\n            } while (ch && ch !== '\\n');\n            end = i;\n            start = i + 1;\n            ch = text[start];\n        }\n    }\n    return end;\n}\n\nexport { FOLD_BLOCK, FOLD_FLOW, FOLD_QUOTED, foldFlowLines };\n","import { Scalar } from '../nodes/Scalar.js';\nimport { foldFlowLines, FOLD_FLOW, FOLD_QUOTED, FOLD_BLOCK } from './foldFlowLines.js';\n\nconst getFoldOptions = (ctx, isBlock) => ({\n    indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,\n    lineWidth: ctx.options.lineWidth,\n    minContentWidth: ctx.options.minContentWidth\n});\n// Also checks for lines starting with %, as parsing the output as YAML 1.1 will\n// presume that's starting a new document.\nconst containsDocumentMarker = (str) => /^(%|---|\\.\\.\\.)/m.test(str);\nfunction lineLengthOverLimit(str, lineWidth, indentLength) {\n    if (!lineWidth || lineWidth < 0)\n        return false;\n    const limit = lineWidth - indentLength;\n    const strLen = str.length;\n    if (strLen <= limit)\n        return false;\n    for (let i = 0, start = 0; i < strLen; ++i) {\n        if (str[i] === '\\n') {\n            if (i - start > limit)\n                return true;\n            start = i + 1;\n            if (strLen - start <= limit)\n                return false;\n        }\n    }\n    return true;\n}\nfunction doubleQuotedString(value, ctx) {\n    const json = JSON.stringify(value);\n    if (ctx.options.doubleQuotedAsJSON)\n        return json;\n    const { implicitKey } = ctx;\n    const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;\n    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');\n    let str = '';\n    let start = 0;\n    for (let i = 0, ch = json[i]; ch; ch = json[++i]) {\n        if (ch === ' ' && json[i + 1] === '\\\\' && json[i + 2] === 'n') {\n            // space before newline needs to be escaped to not be folded\n            str += json.slice(start, i) + '\\\\ ';\n            i += 1;\n            start = i;\n            ch = '\\\\';\n        }\n        if (ch === '\\\\')\n            switch (json[i + 1]) {\n                case 'u':\n                    {\n                        str += json.slice(start, i);\n                        const code = json.substr(i + 2, 4);\n                        switch (code) {\n                            case '0000':\n                                str += '\\\\0';\n                                break;\n                            case '0007':\n                                str += '\\\\a';\n                                break;\n                            case '000b':\n                                str += '\\\\v';\n                                break;\n                            case '001b':\n                                str += '\\\\e';\n                                break;\n                            case '0085':\n                                str += '\\\\N';\n                                break;\n                            case '00a0':\n                                str += '\\\\_';\n                                break;\n                            case '2028':\n                                str += '\\\\L';\n                                break;\n                            case '2029':\n                                str += '\\\\P';\n                                break;\n                            default:\n                                if (code.substr(0, 2) === '00')\n                                    str += '\\\\x' + code.substr(2);\n                                else\n                                    str += json.substr(i, 6);\n                        }\n                        i += 5;\n                        start = i + 1;\n                    }\n                    break;\n                case 'n':\n                    if (implicitKey ||\n                        json[i + 2] === '\"' ||\n                        json.length < minMultiLineLength) {\n                        i += 1;\n                    }\n                    else {\n                        // folding will eat first newline\n                        str += json.slice(start, i) + '\\n\\n';\n                        while (json[i + 2] === '\\\\' &&\n                            json[i + 3] === 'n' &&\n                            json[i + 4] !== '\"') {\n                            str += '\\n';\n                            i += 2;\n                        }\n                        str += indent;\n                        // space after newline needs to be escaped to not be folded\n                        if (json[i + 2] === ' ')\n                            str += '\\\\';\n                        i += 1;\n                        start = i + 1;\n                    }\n                    break;\n                default:\n                    i += 1;\n            }\n    }\n    str = start ? str + json.slice(start) : json;\n    return implicitKey\n        ? str\n        : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));\n}\nfunction singleQuotedString(value, ctx) {\n    if (ctx.options.singleQuote === false ||\n        (ctx.implicitKey && value.includes('\\n')) ||\n        /[ \\t]\\n|\\n[ \\t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline\n    )\n        return doubleQuotedString(value, ctx);\n    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');\n    const res = \"'\" + value.replace(/'/g, \"''\").replace(/\\n+/g, `$&\\n${indent}`) + \"'\";\n    return ctx.implicitKey\n        ? res\n        : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction quotedString(value, ctx) {\n    const { singleQuote } = ctx.options;\n    let qs;\n    if (singleQuote === false)\n        qs = doubleQuotedString;\n    else {\n        const hasDouble = value.includes('\"');\n        const hasSingle = value.includes(\"'\");\n        if (hasDouble && !hasSingle)\n            qs = singleQuotedString;\n        else if (hasSingle && !hasDouble)\n            qs = doubleQuotedString;\n        else\n            qs = singleQuote ? singleQuotedString : doubleQuotedString;\n    }\n    return qs(value, ctx);\n}\n// The negative lookbehind avoids a polynomial search,\n// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind\nlet blockEndNewlines;\ntry {\n    blockEndNewlines = new RegExp('(^|(?<!\\n))\\n+(?!\\n|$)', 'g');\n}\ncatch {\n    blockEndNewlines = /\\n+(?!\\n|$)/g;\n}\nfunction blockString({ comment, type, value }, ctx, onComment, onChompKeep) {\n    const { blockQuote, commentString, lineWidth } = ctx.options;\n    // 1. Block can't end in whitespace unless the last line is non-empty.\n    // 2. Strings consisting of only whitespace are best rendered explicitly.\n    if (!blockQuote || /\\n[\\t ]+$/.test(value)) {\n        return quotedString(value, ctx);\n    }\n    const indent = ctx.indent ||\n        (ctx.forceBlockIndent || containsDocumentMarker(value) ? '  ' : '');\n    const literal = blockQuote === 'literal'\n        ? true\n        : blockQuote === 'folded' || type === Scalar.BLOCK_FOLDED\n            ? false\n            : type === Scalar.BLOCK_LITERAL\n                ? true\n                : !lineLengthOverLimit(value, lineWidth, indent.length);\n    if (!value)\n        return literal ? '|\\n' : '>\\n';\n    // determine chomping from whitespace at value end\n    let chomp;\n    let endStart;\n    for (endStart = value.length; endStart > 0; --endStart) {\n        const ch = value[endStart - 1];\n        if (ch !== '\\n' && ch !== '\\t' && ch !== ' ')\n            break;\n    }\n    let end = value.substring(endStart);\n    const endNlPos = end.indexOf('\\n');\n    if (endNlPos === -1) {\n        chomp = '-'; // strip\n    }\n    else if (value === end || endNlPos !== end.length - 1) {\n        chomp = '+'; // keep\n        if (onChompKeep)\n            onChompKeep();\n    }\n    else {\n        chomp = ''; // clip\n    }\n    if (end) {\n        value = value.slice(0, -end.length);\n        if (end[end.length - 1] === '\\n')\n            end = end.slice(0, -1);\n        end = end.replace(blockEndNewlines, `$&${indent}`);\n    }\n    // determine indent indicator from whitespace at value start\n    let startWithSpace = false;\n    let startEnd;\n    let startNlPos = -1;\n    for (startEnd = 0; startEnd < value.length; ++startEnd) {\n        const ch = value[startEnd];\n        if (ch === ' ')\n            startWithSpace = true;\n        else if (ch === '\\n')\n            startNlPos = startEnd;\n        else\n            break;\n    }\n    let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);\n    if (start) {\n        value = value.substring(start.length);\n        start = start.replace(/\\n+/g, `$&${indent}`);\n    }\n    const indentSize = indent ? '2' : '1'; // root is at -1\n    // Leading | or > is added later\n    let header = (startWithSpace ? indentSize : '') + chomp;\n    if (comment) {\n        header += ' ' + commentString(comment.replace(/ ?[\\r\\n]+/g, ' '));\n        if (onComment)\n            onComment();\n    }\n    if (!literal) {\n        const foldedValue = value\n            .replace(/\\n+/g, '\\n$&')\n            .replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g, '$1$2') // more-indented lines aren't folded\n            //                ^ more-ind. ^ empty     ^ capture next empty lines only at end of indent\n            .replace(/\\n+/g, `$&${indent}`);\n        let literalFallback = false;\n        const foldOptions = getFoldOptions(ctx, true);\n        if (blockQuote !== 'folded' && type !== Scalar.BLOCK_FOLDED) {\n            foldOptions.onOverflow = () => {\n                literalFallback = true;\n            };\n        }\n        const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions);\n        if (!literalFallback)\n            return `>${header}\\n${indent}${body}`;\n    }\n    value = value.replace(/\\n+/g, `$&${indent}`);\n    return `|${header}\\n${indent}${start}${value}${end}`;\n}\nfunction plainString(item, ctx, onComment, onChompKeep) {\n    const { type, value } = item;\n    const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;\n    if ((implicitKey && value.includes('\\n')) ||\n        (inFlow && /[[\\]{},]/.test(value))) {\n        return quotedString(value, ctx);\n    }\n    if (/^[\\n\\t ,[\\]{}#&*!|>'\"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(value)) {\n        // not allowed:\n        // - '-' or '?'\n        // - start with an indicator character (except [?:-]) or /[?-] /\n        // - '\\n ', ': ' or ' \\n' anywhere\n        // - '#' not preceded by a non-space char\n        // - end with ' ' or ':'\n        return implicitKey || inFlow || !value.includes('\\n')\n            ? quotedString(value, ctx)\n            : blockString(item, ctx, onComment, onChompKeep);\n    }\n    if (!implicitKey &&\n        !inFlow &&\n        type !== Scalar.PLAIN &&\n        value.includes('\\n')) {\n        // Where allowed & type not set explicitly, prefer block style for multiline strings\n        return blockString(item, ctx, onComment, onChompKeep);\n    }\n    if (containsDocumentMarker(value)) {\n        if (indent === '') {\n            ctx.forceBlockIndent = true;\n            return blockString(item, ctx, onComment, onChompKeep);\n        }\n        else if (implicitKey && indent === indentStep) {\n            return quotedString(value, ctx);\n        }\n    }\n    const str = value.replace(/\\n+/g, `$&\\n${indent}`);\n    // Verify that output will be parsed as a string, as e.g. plain numbers and\n    // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),\n    // and others in v1.1.\n    if (actualString) {\n        const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);\n        const { compat, tags } = ctx.doc.schema;\n        if (tags.some(test) || compat?.some(test))\n            return quotedString(value, ctx);\n    }\n    return implicitKey\n        ? str\n        : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction stringifyString(item, ctx, onComment, onChompKeep) {\n    const { implicitKey, inFlow } = ctx;\n    const ss = typeof item.value === 'string'\n        ? item\n        : Object.assign({}, item, { value: String(item.value) });\n    let { type } = item;\n    if (type !== Scalar.QUOTE_DOUBLE) {\n        // force double quotes on control characters & unpaired surrogates\n        if (/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(ss.value))\n            type = Scalar.QUOTE_DOUBLE;\n    }\n    const _stringify = (_type) => {\n        switch (_type) {\n            case Scalar.BLOCK_FOLDED:\n            case Scalar.BLOCK_LITERAL:\n                return implicitKey || inFlow\n                    ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers\n                    : blockString(ss, ctx, onComment, onChompKeep);\n            case Scalar.QUOTE_DOUBLE:\n                return doubleQuotedString(ss.value, ctx);\n            case Scalar.QUOTE_SINGLE:\n                return singleQuotedString(ss.value, ctx);\n            case Scalar.PLAIN:\n                return plainString(ss, ctx, onComment, onChompKeep);\n            default:\n                return null;\n        }\n    };\n    let res = _stringify(type);\n    if (res === null) {\n        const { defaultKeyType, defaultStringType } = ctx.options;\n        const t = (implicitKey && defaultKeyType) || defaultStringType;\n        res = _stringify(t);\n        if (res === null)\n            throw new Error(`Unsupported default string type ${t}`);\n    }\n    return res;\n}\n\nexport { stringifyString };\n","import { anchorIsValid } from '../doc/anchors.js';\nimport { isPair, isAlias, isNode, isScalar, isCollection } from '../nodes/identity.js';\nimport { stringifyComment } from './stringifyComment.js';\nimport { stringifyString } from './stringifyString.js';\n\nfunction createStringifyContext(doc, options) {\n    const opt = Object.assign({\n        blockQuote: true,\n        commentString: stringifyComment,\n        defaultKeyType: null,\n        defaultStringType: 'PLAIN',\n        directives: null,\n        doubleQuotedAsJSON: false,\n        doubleQuotedMinMultiLineLength: 40,\n        falseStr: 'false',\n        flowCollectionPadding: true,\n        indentSeq: true,\n        lineWidth: 80,\n        minContentWidth: 20,\n        nullStr: 'null',\n        simpleKeys: false,\n        singleQuote: null,\n        trailingComma: false,\n        trueStr: 'true',\n        verifyAliasOrder: true\n    }, doc.schema.toStringOptions, options);\n    let inFlow;\n    switch (opt.collectionStyle) {\n        case 'block':\n            inFlow = false;\n            break;\n        case 'flow':\n            inFlow = true;\n            break;\n        default:\n            inFlow = null;\n    }\n    return {\n        anchors: new Set(),\n        doc,\n        flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',\n        indent: '',\n        indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : '  ',\n        inFlow,\n        options: opt\n    };\n}\nfunction getTagObject(tags, item) {\n    if (item.tag) {\n        const match = tags.filter(t => t.tag === item.tag);\n        if (match.length > 0)\n            return match.find(t => t.format === item.format) ?? match[0];\n    }\n    let tagObj = undefined;\n    let obj;\n    if (isScalar(item)) {\n        obj = item.value;\n        let match = tags.filter(t => t.identify?.(obj));\n        if (match.length > 1) {\n            const testMatch = match.filter(t => t.test);\n            if (testMatch.length > 0)\n                match = testMatch;\n        }\n        tagObj =\n            match.find(t => t.format === item.format) ?? match.find(t => !t.format);\n    }\n    else {\n        obj = item;\n        tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);\n    }\n    if (!tagObj) {\n        const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);\n        throw new Error(`Tag not resolved for ${name} value`);\n    }\n    return tagObj;\n}\n// needs to be called before value stringifier to allow for circular anchor refs\nfunction stringifyProps(node, tagObj, { anchors, doc }) {\n    if (!doc.directives)\n        return '';\n    const props = [];\n    const anchor = (isScalar(node) || isCollection(node)) && node.anchor;\n    if (anchor && anchorIsValid(anchor)) {\n        anchors.add(anchor);\n        props.push(`&${anchor}`);\n    }\n    const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);\n    if (tag)\n        props.push(doc.directives.tagString(tag));\n    return props.join(' ');\n}\nfunction stringify(item, ctx, onComment, onChompKeep) {\n    if (isPair(item))\n        return item.toString(ctx, onComment, onChompKeep);\n    if (isAlias(item)) {\n        if (ctx.doc.directives)\n            return item.toString(ctx);\n        if (ctx.resolvedAliases?.has(item)) {\n            throw new TypeError(`Cannot stringify circular structure without alias nodes`);\n        }\n        else {\n            if (ctx.resolvedAliases)\n                ctx.resolvedAliases.add(item);\n            else\n                ctx.resolvedAliases = new Set([item]);\n            item = item.resolve(ctx.doc);\n        }\n    }\n    let tagObj = undefined;\n    const node = isNode(item)\n        ? item\n        : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });\n    tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));\n    const props = stringifyProps(node, tagObj, ctx);\n    if (props.length > 0)\n        ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;\n    const str = typeof tagObj.stringify === 'function'\n        ? tagObj.stringify(node, ctx, onComment, onChompKeep)\n        : isScalar(node)\n            ? stringifyString(node, ctx, onComment, onChompKeep)\n            : node.toString(ctx, onComment, onChompKeep);\n    if (!props)\n        return str;\n    return isScalar(node) || str[0] === '{' || str[0] === '['\n        ? `${props} ${str}`\n        : `${props}\\n${ctx.indent}${str}`;\n}\n\nexport { createStringifyContext, stringify };\n","import { isCollection, isNode, isScalar, isSeq } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\nimport { stringify } from './stringify.js';\nimport { lineComment, indentComment } from './stringifyComment.js';\n\nfunction stringifyPair({ key, value }, ctx, onComment, onChompKeep) {\n    const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;\n    let keyComment = (isNode(key) && key.comment) || null;\n    if (simpleKeys) {\n        if (keyComment) {\n            throw new Error('With simple keys, key nodes cannot have comments');\n        }\n        if (isCollection(key) || (!isNode(key) && typeof key === 'object')) {\n            const msg = 'With simple keys, collection cannot be used as a key value';\n            throw new Error(msg);\n        }\n    }\n    let explicitKey = !simpleKeys &&\n        (!key ||\n            (keyComment && value == null && !ctx.inFlow) ||\n            isCollection(key) ||\n            (isScalar(key)\n                ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL\n                : typeof key === 'object'));\n    ctx = Object.assign({}, ctx, {\n        allNullValues: false,\n        implicitKey: !explicitKey && (simpleKeys || !allNullValues),\n        indent: indent + indentStep\n    });\n    let keyCommentDone = false;\n    let chompKeep = false;\n    let str = stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));\n    if (!explicitKey && !ctx.inFlow && str.length > 1024) {\n        if (simpleKeys)\n            throw new Error('With simple keys, single line scalar must not span more than 1024 characters');\n        explicitKey = true;\n    }\n    if (ctx.inFlow) {\n        if (allNullValues || value == null) {\n            if (keyCommentDone && onComment)\n                onComment();\n            return str === '' ? '?' : explicitKey ? `? ${str}` : str;\n        }\n    }\n    else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {\n        str = `? ${str}`;\n        if (keyComment && !keyCommentDone) {\n            str += lineComment(str, ctx.indent, commentString(keyComment));\n        }\n        else if (chompKeep && onChompKeep)\n            onChompKeep();\n        return str;\n    }\n    if (keyCommentDone)\n        keyComment = null;\n    if (explicitKey) {\n        if (keyComment)\n            str += lineComment(str, ctx.indent, commentString(keyComment));\n        str = `? ${str}\\n${indent}:`;\n    }\n    else {\n        str = `${str}:`;\n        if (keyComment)\n            str += lineComment(str, ctx.indent, commentString(keyComment));\n    }\n    let vsb, vcb, valueComment;\n    if (isNode(value)) {\n        vsb = !!value.spaceBefore;\n        vcb = value.commentBefore;\n        valueComment = value.comment;\n    }\n    else {\n        vsb = false;\n        vcb = null;\n        valueComment = null;\n        if (value && typeof value === 'object')\n            value = doc.createNode(value);\n    }\n    ctx.implicitKey = false;\n    if (!explicitKey && !keyComment && isScalar(value))\n        ctx.indentAtStart = str.length + 1;\n    chompKeep = false;\n    if (!indentSeq &&\n        indentStep.length >= 2 &&\n        !ctx.inFlow &&\n        !explicitKey &&\n        isSeq(value) &&\n        !value.flow &&\n        !value.tag &&\n        !value.anchor) {\n        // If indentSeq === false, consider '- ' as part of indentation where possible\n        ctx.indent = ctx.indent.substring(2);\n    }\n    let valueCommentDone = false;\n    const valueStr = stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));\n    let ws = ' ';\n    if (keyComment || vsb || vcb) {\n        ws = vsb ? '\\n' : '';\n        if (vcb) {\n            const cs = commentString(vcb);\n            ws += `\\n${indentComment(cs, ctx.indent)}`;\n        }\n        if (valueStr === '' && !ctx.inFlow) {\n            if (ws === '\\n' && valueComment)\n                ws = '\\n\\n';\n        }\n        else {\n            ws += `\\n${ctx.indent}`;\n        }\n    }\n    else if (!explicitKey && isCollection(value)) {\n        const vs0 = valueStr[0];\n        const nl0 = valueStr.indexOf('\\n');\n        const hasNewline = nl0 !== -1;\n        const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;\n        if (hasNewline || !flow) {\n            let hasPropsLine = false;\n            if (hasNewline && (vs0 === '&' || vs0 === '!')) {\n                let sp0 = valueStr.indexOf(' ');\n                if (vs0 === '&' &&\n                    sp0 !== -1 &&\n                    sp0 < nl0 &&\n                    valueStr[sp0 + 1] === '!') {\n                    sp0 = valueStr.indexOf(' ', sp0 + 1);\n                }\n                if (sp0 === -1 || nl0 < sp0)\n                    hasPropsLine = true;\n            }\n            if (!hasPropsLine)\n                ws = `\\n${ctx.indent}`;\n        }\n    }\n    else if (valueStr === '' || valueStr[0] === '\\n') {\n        ws = '';\n    }\n    str += ws + valueStr;\n    if (ctx.inFlow) {\n        if (valueCommentDone && onComment)\n            onComment();\n    }\n    else if (valueComment && !valueCommentDone) {\n        str += lineComment(str, ctx.indent, commentString(valueComment));\n    }\n    else if (chompKeep && onChompKeep) {\n        onChompKeep();\n    }\n    return str;\n}\n\nexport { stringifyPair };\n","function debug(logLevel, ...messages) {\n    if (logLevel === 'debug')\n        console.log(...messages);\n}\nfunction warn(logLevel, warning) {\n    if (logLevel === 'debug' || logLevel === 'warn') {\n        console.warn(warning);\n    }\n}\n\nexport { debug, warn };\n","import { isScalar, isSeq, isAlias, isMap } from '../../nodes/identity.js';\nimport { Scalar } from '../../nodes/Scalar.js';\n\n// If the value associated with a merge key is a single mapping node, each of\n// its key/value pairs is inserted into the current mapping, unless the key\n// already exists in it. If the value associated with the merge key is a\n// sequence, then this sequence is expected to contain mapping nodes and each\n// of these nodes is merged in turn according to its order in the sequence.\n// Keys in mapping nodes earlier in the sequence override keys specified in\n// later mapping nodes. -- http://yaml.org/type/merge.html\nconst MERGE_KEY = '<<';\nconst merge = {\n    identify: value => value === MERGE_KEY ||\n        (typeof value === 'symbol' && value.description === MERGE_KEY),\n    default: 'key',\n    tag: 'tag:yaml.org,2002:merge',\n    test: /^<<$/,\n    resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), {\n        addToJSMap: addMergeToJSMap\n    }),\n    stringify: () => MERGE_KEY\n};\nconst isMergeKey = (ctx, key) => (merge.identify(key) ||\n    (isScalar(key) &&\n        (!key.type || key.type === Scalar.PLAIN) &&\n        merge.identify(key.value))) &&\n    ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);\nfunction addMergeToJSMap(ctx, map, value) {\n    const source = resolveAliasValue(ctx, value);\n    if (isSeq(source))\n        for (const it of source.items)\n            mergeValue(ctx, map, it);\n    else if (Array.isArray(source))\n        for (const it of source)\n            mergeValue(ctx, map, it);\n    else\n        mergeValue(ctx, map, source);\n}\nfunction mergeValue(ctx, map, value) {\n    const source = resolveAliasValue(ctx, value);\n    if (!isMap(source))\n        throw new Error('Merge sources must be maps or map aliases');\n    const srcMap = source.toJSON(null, ctx, Map);\n    for (const [key, value] of srcMap) {\n        if (map instanceof Map) {\n            if (!map.has(key))\n                map.set(key, value);\n        }\n        else if (map instanceof Set) {\n            map.add(key);\n        }\n        else if (!Object.prototype.hasOwnProperty.call(map, key)) {\n            Object.defineProperty(map, key, {\n                value,\n                writable: true,\n                enumerable: true,\n                configurable: true\n            });\n        }\n    }\n    return map;\n}\nfunction resolveAliasValue(ctx, value) {\n    return ctx && isAlias(value) ? value.resolve(ctx.doc, ctx) : value;\n}\n\nexport { addMergeToJSMap, isMergeKey, merge };\n","import { warn } from '../log.js';\nimport { isMergeKey, addMergeToJSMap } from '../schema/yaml-1.1/merge.js';\nimport { createStringifyContext } from '../stringify/stringify.js';\nimport { isNode } from './identity.js';\nimport { toJS } from './toJS.js';\n\nfunction addPairToJSMap(ctx, map, { key, value }) {\n    if (isNode(key) && key.addToJSMap)\n        key.addToJSMap(ctx, map, value);\n    // TODO: Should drop this special case for bare << handling\n    else if (isMergeKey(ctx, key))\n        addMergeToJSMap(ctx, map, value);\n    else {\n        const jsKey = toJS(key, '', ctx);\n        if (map instanceof Map) {\n            map.set(jsKey, toJS(value, jsKey, ctx));\n        }\n        else if (map instanceof Set) {\n            map.add(jsKey);\n        }\n        else {\n            const stringKey = stringifyKey(key, jsKey, ctx);\n            const jsValue = toJS(value, stringKey, ctx);\n            if (stringKey in map)\n                Object.defineProperty(map, stringKey, {\n                    value: jsValue,\n                    writable: true,\n                    enumerable: true,\n                    configurable: true\n                });\n            else\n                map[stringKey] = jsValue;\n        }\n    }\n    return map;\n}\nfunction stringifyKey(key, jsKey, ctx) {\n    if (jsKey === null)\n        return '';\n    // eslint-disable-next-line @typescript-eslint/no-base-to-string\n    if (typeof jsKey !== 'object')\n        return String(jsKey);\n    if (isNode(key) && ctx?.doc) {\n        const strCtx = createStringifyContext(ctx.doc, {});\n        strCtx.anchors = new Set();\n        for (const node of ctx.anchors.keys())\n            strCtx.anchors.add(node.anchor);\n        strCtx.inFlow = true;\n        strCtx.inStringifyKey = true;\n        const strKey = key.toString(strCtx);\n        if (!ctx.mapKeyWarned) {\n            let jsonStr = JSON.stringify(strKey);\n            if (jsonStr.length > 40)\n                jsonStr = jsonStr.substring(0, 36) + '...\"';\n            warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);\n            ctx.mapKeyWarned = true;\n        }\n        return strKey;\n    }\n    return JSON.stringify(jsKey);\n}\n\nexport { addPairToJSMap };\n","import { createNode } from '../doc/createNode.js';\nimport { stringifyPair } from '../stringify/stringifyPair.js';\nimport { addPairToJSMap } from './addPairToJSMap.js';\nimport { NODE_TYPE, PAIR, isNode } from './identity.js';\n\nfunction createPair(key, value, ctx) {\n    const k = createNode(key, undefined, ctx);\n    const v = createNode(value, undefined, ctx);\n    return new Pair(k, v);\n}\nclass Pair {\n    constructor(key, value = null) {\n        Object.defineProperty(this, NODE_TYPE, { value: PAIR });\n        this.key = key;\n        this.value = value;\n    }\n    clone(schema) {\n        let { key, value } = this;\n        if (isNode(key))\n            key = key.clone(schema);\n        if (isNode(value))\n            value = value.clone(schema);\n        return new Pair(key, value);\n    }\n    toJSON(_, ctx) {\n        const pair = ctx?.mapAsMap ? new Map() : {};\n        return addPairToJSMap(ctx, pair, this);\n    }\n    toString(ctx, onComment, onChompKeep) {\n        return ctx?.doc\n            ? stringifyPair(this, ctx, onComment, onChompKeep)\n            : JSON.stringify(this);\n    }\n}\n\nexport { Pair, createPair };\n","import { isNode, isPair } from '../nodes/identity.js';\nimport { stringify } from './stringify.js';\nimport { lineComment, indentComment } from './stringifyComment.js';\n\nfunction stringifyCollection(collection, ctx, options) {\n    const flow = ctx.inFlow ?? collection.flow;\n    const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;\n    return stringify(collection, ctx, options);\n}\nfunction stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {\n    const { indent, options: { commentString } } = ctx;\n    const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });\n    let chompKeep = false; // flag for the preceding node's status\n    const lines = [];\n    for (let i = 0; i < items.length; ++i) {\n        const item = items[i];\n        let comment = null;\n        if (isNode(item)) {\n            if (!chompKeep && item.spaceBefore)\n                lines.push('');\n            addCommentBefore(ctx, lines, item.commentBefore, chompKeep);\n            if (item.comment)\n                comment = item.comment;\n        }\n        else if (isPair(item)) {\n            const ik = isNode(item.key) ? item.key : null;\n            if (ik) {\n                if (!chompKeep && ik.spaceBefore)\n                    lines.push('');\n                addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);\n            }\n        }\n        chompKeep = false;\n        let str = stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));\n        if (comment)\n            str += lineComment(str, itemIndent, commentString(comment));\n        if (chompKeep && comment)\n            chompKeep = false;\n        lines.push(blockItemPrefix + str);\n    }\n    let str;\n    if (lines.length === 0) {\n        str = flowChars.start + flowChars.end;\n    }\n    else {\n        str = lines[0];\n        for (let i = 1; i < lines.length; ++i) {\n            const line = lines[i];\n            str += line ? `\\n${indent}${line}` : '\\n';\n        }\n    }\n    if (comment) {\n        str += '\\n' + indentComment(commentString(comment), indent);\n        if (onComment)\n            onComment();\n    }\n    else if (chompKeep && onChompKeep)\n        onChompKeep();\n    return str;\n}\nfunction stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {\n    const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;\n    itemIndent += indentStep;\n    const itemCtx = Object.assign({}, ctx, {\n        indent: itemIndent,\n        inFlow: true,\n        type: null\n    });\n    let reqNewline = false;\n    let linesAtValue = 0;\n    const lines = [];\n    for (let i = 0; i < items.length; ++i) {\n        const item = items[i];\n        let comment = null;\n        if (isNode(item)) {\n            if (item.spaceBefore)\n                lines.push('');\n            addCommentBefore(ctx, lines, item.commentBefore, false);\n            if (item.comment)\n                comment = item.comment;\n        }\n        else if (isPair(item)) {\n            const ik = isNode(item.key) ? item.key : null;\n            if (ik) {\n                if (ik.spaceBefore)\n                    lines.push('');\n                addCommentBefore(ctx, lines, ik.commentBefore, false);\n                if (ik.comment)\n                    reqNewline = true;\n            }\n            const iv = isNode(item.value) ? item.value : null;\n            if (iv) {\n                if (iv.comment)\n                    comment = iv.comment;\n                if (iv.commentBefore)\n                    reqNewline = true;\n            }\n            else if (item.value == null && ik?.comment) {\n                comment = ik.comment;\n            }\n        }\n        if (comment)\n            reqNewline = true;\n        let str = stringify(item, itemCtx, () => (comment = null));\n        reqNewline || (reqNewline = lines.length > linesAtValue || str.includes('\\n'));\n        if (i < items.length - 1) {\n            str += ',';\n        }\n        else if (ctx.options.trailingComma) {\n            if (ctx.options.lineWidth > 0) {\n                reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) +\n                    (str.length + 2) >\n                    ctx.options.lineWidth);\n            }\n            if (reqNewline) {\n                str += ',';\n            }\n        }\n        if (comment)\n            str += lineComment(str, itemIndent, commentString(comment));\n        lines.push(str);\n        linesAtValue = lines.length;\n    }\n    const { start, end } = flowChars;\n    if (lines.length === 0) {\n        return start + end;\n    }\n    else {\n        if (!reqNewline) {\n            const len = lines.reduce((sum, line) => sum + line.length + 2, 2);\n            reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;\n        }\n        if (reqNewline) {\n            let str = start;\n            for (const line of lines)\n                str += line ? `\\n${indentStep}${indent}${line}` : '\\n';\n            return `${str}\\n${indent}${end}`;\n        }\n        else {\n            return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;\n        }\n    }\n}\nfunction addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {\n    if (comment && chompKeep)\n        comment = comment.replace(/^\\n+/, '');\n    if (comment) {\n        const ic = indentComment(commentString(comment), indent);\n        lines.push(ic.trimStart()); // Avoid double indent on first line\n    }\n}\n\nexport { stringifyCollection };\n","import { stringifyCollection } from '../stringify/stringifyCollection.js';\nimport { addPairToJSMap } from './addPairToJSMap.js';\nimport { Collection } from './Collection.js';\nimport { MAP, isPair, isScalar } from './identity.js';\nimport { Pair, createPair } from './Pair.js';\nimport { isScalarValue } from './Scalar.js';\n\nfunction findPair(items, key) {\n    const k = isScalar(key) ? key.value : key;\n    for (const it of items) {\n        if (isPair(it)) {\n            if (it.key === key || it.key === k)\n                return it;\n            if (isScalar(it.key) && it.key.value === k)\n                return it;\n        }\n    }\n    return undefined;\n}\nclass YAMLMap extends Collection {\n    static get tagName() {\n        return 'tag:yaml.org,2002:map';\n    }\n    constructor(schema) {\n        super(MAP, schema);\n        this.items = [];\n    }\n    /**\n     * A generic collection parsing method that can be extended\n     * to other node classes that inherit from YAMLMap\n     */\n    static from(schema, obj, ctx) {\n        const { keepUndefined, replacer } = ctx;\n        const map = new this(schema);\n        const add = (key, value) => {\n            if (typeof replacer === 'function')\n                value = replacer.call(obj, key, value);\n            else if (Array.isArray(replacer) && !replacer.includes(key))\n                return;\n            if (value !== undefined || keepUndefined)\n                map.items.push(createPair(key, value, ctx));\n        };\n        if (obj instanceof Map) {\n            for (const [key, value] of obj)\n                add(key, value);\n        }\n        else if (obj && typeof obj === 'object') {\n            for (const key of Object.keys(obj))\n                add(key, obj[key]);\n        }\n        if (typeof schema.sortMapEntries === 'function') {\n            map.items.sort(schema.sortMapEntries);\n        }\n        return map;\n    }\n    /**\n     * Adds a value to the collection.\n     *\n     * @param overwrite - If not set `true`, using a key that is already in the\n     *   collection will throw. Otherwise, overwrites the previous value.\n     */\n    add(pair, overwrite) {\n        let _pair;\n        if (isPair(pair))\n            _pair = pair;\n        else if (!pair || typeof pair !== 'object' || !('key' in pair)) {\n            // In TypeScript, this never happens.\n            _pair = new Pair(pair, pair?.value);\n        }\n        else\n            _pair = new Pair(pair.key, pair.value);\n        const prev = findPair(this.items, _pair.key);\n        const sortEntries = this.schema?.sortMapEntries;\n        if (prev) {\n            if (!overwrite)\n                throw new Error(`Key ${_pair.key} already set`);\n            // For scalars, keep the old node & its comments and anchors\n            if (isScalar(prev.value) && isScalarValue(_pair.value))\n                prev.value.value = _pair.value;\n            else\n                prev.value = _pair.value;\n        }\n        else if (sortEntries) {\n            const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);\n            if (i === -1)\n                this.items.push(_pair);\n            else\n                this.items.splice(i, 0, _pair);\n        }\n        else {\n            this.items.push(_pair);\n        }\n    }\n    delete(key) {\n        const it = findPair(this.items, key);\n        if (!it)\n            return false;\n        const del = this.items.splice(this.items.indexOf(it), 1);\n        return del.length > 0;\n    }\n    get(key, keepScalar) {\n        const it = findPair(this.items, key);\n        const node = it?.value;\n        return (!keepScalar && isScalar(node) ? node.value : node) ?? undefined;\n    }\n    has(key) {\n        return !!findPair(this.items, key);\n    }\n    set(key, value) {\n        this.add(new Pair(key, value), true);\n    }\n    /**\n     * @param ctx - Conversion context, originally set in Document#toJS()\n     * @param {Class} Type - If set, forces the returned collection type\n     * @returns Instance of Type, Map, or Object\n     */\n    toJSON(_, ctx, Type) {\n        const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};\n        if (ctx?.onCreate)\n            ctx.onCreate(map);\n        for (const item of this.items)\n            addPairToJSMap(ctx, map, item);\n        return map;\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        for (const item of this.items) {\n            if (!isPair(item))\n                throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);\n        }\n        if (!ctx.allNullValues && this.hasAllNullValues(false))\n            ctx = Object.assign({}, ctx, { allNullValues: true });\n        return stringifyCollection(this, ctx, {\n            blockItemPrefix: '',\n            flowChars: { start: '{', end: '}' },\n            itemIndent: ctx.indent || '',\n            onChompKeep,\n            onComment\n        });\n    }\n}\n\nexport { YAMLMap, findPair };\n","import { isMap } from '../../nodes/identity.js';\nimport { YAMLMap } from '../../nodes/YAMLMap.js';\n\nconst map = {\n    collection: 'map',\n    default: true,\n    nodeClass: YAMLMap,\n    tag: 'tag:yaml.org,2002:map',\n    resolve(map, onError) {\n        if (!isMap(map))\n            onError('Expected a mapping for this tag');\n        return map;\n    },\n    createNode: (schema, obj, ctx) => YAMLMap.from(schema, obj, ctx)\n};\n\nexport { map };\n","import { createNode } from '../doc/createNode.js';\nimport { stringifyCollection } from '../stringify/stringifyCollection.js';\nimport { Collection } from './Collection.js';\nimport { SEQ, isScalar } from './identity.js';\nimport { isScalarValue } from './Scalar.js';\nimport { toJS } from './toJS.js';\n\nclass YAMLSeq extends Collection {\n    static get tagName() {\n        return 'tag:yaml.org,2002:seq';\n    }\n    constructor(schema) {\n        super(SEQ, schema);\n        this.items = [];\n    }\n    add(value) {\n        this.items.push(value);\n    }\n    /**\n     * Removes a value from the collection.\n     *\n     * `key` must contain a representation of an integer for this to succeed.\n     * It may be wrapped in a `Scalar`.\n     *\n     * @returns `true` if the item was found and removed.\n     */\n    delete(key) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            return false;\n        const del = this.items.splice(idx, 1);\n        return del.length > 0;\n    }\n    get(key, keepScalar) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            return undefined;\n        const it = this.items[idx];\n        return !keepScalar && isScalar(it) ? it.value : it;\n    }\n    /**\n     * Checks if the collection includes a value with the key `key`.\n     *\n     * `key` must contain a representation of an integer for this to succeed.\n     * It may be wrapped in a `Scalar`.\n     */\n    has(key) {\n        const idx = asItemIndex(key);\n        return typeof idx === 'number' && idx < this.items.length;\n    }\n    /**\n     * Sets a value in this collection. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     *\n     * If `key` does not contain a representation of an integer, this will throw.\n     * It may be wrapped in a `Scalar`.\n     */\n    set(key, value) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            throw new Error(`Expected a valid index, not ${key}.`);\n        const prev = this.items[idx];\n        if (isScalar(prev) && isScalarValue(value))\n            prev.value = value;\n        else\n            this.items[idx] = value;\n    }\n    toJSON(_, ctx) {\n        const seq = [];\n        if (ctx?.onCreate)\n            ctx.onCreate(seq);\n        let i = 0;\n        for (const item of this.items)\n            seq.push(toJS(item, String(i++), ctx));\n        return seq;\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        return stringifyCollection(this, ctx, {\n            blockItemPrefix: '- ',\n            flowChars: { start: '[', end: ']' },\n            itemIndent: (ctx.indent || '') + '  ',\n            onChompKeep,\n            onComment\n        });\n    }\n    static from(schema, obj, ctx) {\n        const { replacer } = ctx;\n        const seq = new this(schema);\n        if (obj && Symbol.iterator in Object(obj)) {\n            let i = 0;\n            for (let it of obj) {\n                if (typeof replacer === 'function') {\n                    const key = obj instanceof Set ? it : String(i++);\n                    it = replacer.call(obj, key, it);\n                }\n                seq.items.push(createNode(it, undefined, ctx));\n            }\n        }\n        return seq;\n    }\n}\nfunction asItemIndex(key) {\n    let idx = isScalar(key) ? key.value : key;\n    if (idx && typeof idx === 'string')\n        idx = Number(idx);\n    return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0\n        ? idx\n        : null;\n}\n\nexport { YAMLSeq };\n","import { isSeq } from '../../nodes/identity.js';\nimport { YAMLSeq } from '../../nodes/YAMLSeq.js';\n\nconst seq = {\n    collection: 'seq',\n    default: true,\n    nodeClass: YAMLSeq,\n    tag: 'tag:yaml.org,2002:seq',\n    resolve(seq, onError) {\n        if (!isSeq(seq))\n            onError('Expected a sequence for this tag');\n        return seq;\n    },\n    createNode: (schema, obj, ctx) => YAMLSeq.from(schema, obj, ctx)\n};\n\nexport { seq };\n","import { stringifyString } from '../../stringify/stringifyString.js';\n\nconst string = {\n    identify: value => typeof value === 'string',\n    default: true,\n    tag: 'tag:yaml.org,2002:str',\n    resolve: str => str,\n    stringify(item, ctx, onComment, onChompKeep) {\n        ctx = Object.assign({ actualString: true }, ctx);\n        return stringifyString(item, ctx, onComment, onChompKeep);\n    }\n};\n\nexport { string };\n","import { Scalar } from '../../nodes/Scalar.js';\n\nconst nullTag = {\n    identify: value => value == null,\n    createNode: () => new Scalar(null),\n    default: true,\n    tag: 'tag:yaml.org,2002:null',\n    test: /^(?:~|[Nn]ull|NULL)?$/,\n    resolve: () => new Scalar(null),\n    stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)\n        ? source\n        : ctx.options.nullStr\n};\n\nexport { nullTag };\n","import { Scalar } from '../../nodes/Scalar.js';\n\nconst boolTag = {\n    identify: value => typeof value === 'boolean',\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,\n    resolve: str => new Scalar(str[0] === 't' || str[0] === 'T'),\n    stringify({ source, value }, ctx) {\n        if (source && boolTag.test.test(source)) {\n            const sv = source[0] === 't' || source[0] === 'T';\n            if (value === sv)\n                return source;\n        }\n        return value ? ctx.options.trueStr : ctx.options.falseStr;\n    }\n};\n\nexport { boolTag };\n","function stringifyNumber({ format, minFractionDigits, tag, value }) {\n    if (typeof value === 'bigint')\n        return String(value);\n    const num = typeof value === 'number' ? value : Number(value);\n    if (!isFinite(num))\n        return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';\n    let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);\n    if (!format &&\n        minFractionDigits &&\n        (!tag || tag === 'tag:yaml.org,2002:float') &&\n        /^-?\\d/.test(n) &&\n        !n.includes('e')) {\n        let i = n.indexOf('.');\n        if (i < 0) {\n            i = n.length;\n            n += '.';\n        }\n        let d = minFractionDigits - (n.length - i - 1);\n        while (d-- > 0)\n            n += '0';\n    }\n    return n;\n}\n\nexport { stringifyNumber };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst floatNaN = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n    resolve: str => str.slice(-3).toLowerCase() === 'nan'\n        ? NaN\n        : str[0] === '-'\n            ? Number.NEGATIVE_INFINITY\n            : Number.POSITIVE_INFINITY,\n    stringify: stringifyNumber\n};\nconst floatExp = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'EXP',\n    test: /^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,\n    resolve: str => parseFloat(str),\n    stringify(node) {\n        const num = Number(node.value);\n        return isFinite(num) ? num.toExponential() : stringifyNumber(node);\n    }\n};\nconst float = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,\n    resolve(str) {\n        const node = new Scalar(parseFloat(str));\n        const dot = str.indexOf('.');\n        if (dot !== -1 && str[str.length - 1] === '0')\n            node.minFractionDigits = str.length - dot - 1;\n        return node;\n    },\n    stringify: stringifyNumber\n};\n\nexport { float, floatExp, floatNaN };\n","import { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nconst intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));\nfunction intStringify(node, radix, prefix) {\n    const { value } = node;\n    if (intIdentify(value) && value >= 0)\n        return prefix + value.toString(radix);\n    return stringifyNumber(node);\n}\nconst intOct = {\n    identify: value => intIdentify(value) && value >= 0,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'OCT',\n    test: /^0o[0-7]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),\n    stringify: node => intStringify(node, 8, '0o')\n};\nconst int = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    test: /^[-+]?[0-9]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n    stringify: stringifyNumber\n};\nconst intHex = {\n    identify: value => intIdentify(value) && value >= 0,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'HEX',\n    test: /^0x[0-9a-fA-F]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n    stringify: node => intStringify(node, 16, '0x')\n};\n\nexport { int, intHex, intOct };\n","import { map } from '../common/map.js';\nimport { nullTag } from '../common/null.js';\nimport { seq } from '../common/seq.js';\nimport { string } from '../common/string.js';\nimport { boolTag } from './bool.js';\nimport { floatNaN, floatExp, float } from './float.js';\nimport { intOct, int, intHex } from './int.js';\n\nconst schema = [\n    map,\n    seq,\n    string,\n    nullTag,\n    boolTag,\n    intOct,\n    int,\n    intHex,\n    floatNaN,\n    floatExp,\n    float\n];\n\nexport { schema };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { map } from '../common/map.js';\nimport { seq } from '../common/seq.js';\n\nfunction intIdentify(value) {\n    return typeof value === 'bigint' || Number.isInteger(value);\n}\nconst stringifyJSON = ({ value }) => JSON.stringify(value);\nconst jsonScalars = [\n    {\n        identify: value => typeof value === 'string',\n        default: true,\n        tag: 'tag:yaml.org,2002:str',\n        resolve: str => str,\n        stringify: stringifyJSON\n    },\n    {\n        identify: value => value == null,\n        createNode: () => new Scalar(null),\n        default: true,\n        tag: 'tag:yaml.org,2002:null',\n        test: /^null$/,\n        resolve: () => null,\n        stringify: stringifyJSON\n    },\n    {\n        identify: value => typeof value === 'boolean',\n        default: true,\n        tag: 'tag:yaml.org,2002:bool',\n        test: /^true$|^false$/,\n        resolve: str => str === 'true',\n        stringify: stringifyJSON\n    },\n    {\n        identify: intIdentify,\n        default: true,\n        tag: 'tag:yaml.org,2002:int',\n        test: /^-?(?:0|[1-9][0-9]*)$/,\n        resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),\n        stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)\n    },\n    {\n        identify: value => typeof value === 'number',\n        default: true,\n        tag: 'tag:yaml.org,2002:float',\n        test: /^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,\n        resolve: str => parseFloat(str),\n        stringify: stringifyJSON\n    }\n];\nconst jsonError = {\n    default: true,\n    tag: '',\n    test: /^/,\n    resolve(str, onError) {\n        onError(`Unresolved plain scalar ${JSON.stringify(str)}`);\n        return str;\n    }\n};\nconst schema = [map, seq].concat(jsonScalars, jsonError);\n\nexport { schema };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { stringifyString } from '../../stringify/stringifyString.js';\n\nconst binary = {\n    identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array\n    default: false,\n    tag: 'tag:yaml.org,2002:binary',\n    /**\n     * Returns a Buffer in node and an Uint8Array in browsers\n     *\n     * To use the resulting buffer as an image, you'll want to do something like:\n     *\n     *   const blob = new Blob([buffer], { type: 'image/jpeg' })\n     *   document.querySelector('#photo').src = URL.createObjectURL(blob)\n     */\n    resolve(src, onError) {\n        if (typeof atob === 'function') {\n            // On IE 11, atob() can't handle newlines\n            const str = atob(src.replace(/[\\n\\r]/g, ''));\n            const buffer = new Uint8Array(str.length);\n            for (let i = 0; i < str.length; ++i)\n                buffer[i] = str.charCodeAt(i);\n            return buffer;\n        }\n        else {\n            onError('This environment does not support reading binary tags; either Buffer or atob is required');\n            return src;\n        }\n    },\n    stringify({ comment, type, value }, ctx, onComment, onChompKeep) {\n        if (!value)\n            return '';\n        const buf = value; // checked earlier by binary.identify()\n        let str;\n        if (typeof btoa === 'function') {\n            let s = '';\n            for (let i = 0; i < buf.length; ++i)\n                s += String.fromCharCode(buf[i]);\n            str = btoa(s);\n        }\n        else {\n            throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');\n        }\n        type ?? (type = Scalar.BLOCK_LITERAL);\n        if (type !== Scalar.QUOTE_DOUBLE) {\n            const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);\n            const n = Math.ceil(str.length / lineWidth);\n            const lines = new Array(n);\n            for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {\n                lines[i] = str.substr(o, lineWidth);\n            }\n            str = lines.join(type === Scalar.BLOCK_LITERAL ? '\\n' : ' ');\n        }\n        return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);\n    }\n};\n\nexport { binary };\n","import { isSeq, isPair, isMap } from '../../nodes/identity.js';\nimport { createPair, Pair } from '../../nodes/Pair.js';\nimport { Scalar } from '../../nodes/Scalar.js';\nimport { YAMLSeq } from '../../nodes/YAMLSeq.js';\n\nfunction resolvePairs(seq, onError) {\n    if (isSeq(seq)) {\n        for (let i = 0; i < seq.items.length; ++i) {\n            let item = seq.items[i];\n            if (isPair(item))\n                continue;\n            else if (isMap(item)) {\n                if (item.items.length > 1)\n                    onError('Each pair must have its own sequence indicator');\n                const pair = item.items[0] || new Pair(new Scalar(null));\n                if (item.commentBefore)\n                    pair.key.commentBefore = pair.key.commentBefore\n                        ? `${item.commentBefore}\\n${pair.key.commentBefore}`\n                        : item.commentBefore;\n                if (item.comment) {\n                    const cn = pair.value ?? pair.key;\n                    cn.comment = cn.comment\n                        ? `${item.comment}\\n${cn.comment}`\n                        : item.comment;\n                }\n                item = pair;\n            }\n            seq.items[i] = isPair(item) ? item : new Pair(item);\n        }\n    }\n    else\n        onError('Expected a sequence for this tag');\n    return seq;\n}\nfunction createPairs(schema, iterable, ctx) {\n    const { replacer } = ctx;\n    const pairs = new YAMLSeq(schema);\n    pairs.tag = 'tag:yaml.org,2002:pairs';\n    let i = 0;\n    if (iterable && Symbol.iterator in Object(iterable))\n        for (let it of iterable) {\n            if (typeof replacer === 'function')\n                it = replacer.call(iterable, String(i++), it);\n            let key, value;\n            if (Array.isArray(it)) {\n                if (it.length === 2) {\n                    key = it[0];\n                    value = it[1];\n                }\n                else\n                    throw new TypeError(`Expected [key, value] tuple: ${it}`);\n            }\n            else if (it && it instanceof Object) {\n                const keys = Object.keys(it);\n                if (keys.length === 1) {\n                    key = keys[0];\n                    value = it[key];\n                }\n                else {\n                    throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);\n                }\n            }\n            else {\n                key = it;\n            }\n            pairs.items.push(createPair(key, value, ctx));\n        }\n    return pairs;\n}\nconst pairs = {\n    collection: 'seq',\n    default: false,\n    tag: 'tag:yaml.org,2002:pairs',\n    resolve: resolvePairs,\n    createNode: createPairs\n};\n\nexport { createPairs, pairs, resolvePairs };\n","import { isScalar, isPair } from '../../nodes/identity.js';\nimport { toJS } from '../../nodes/toJS.js';\nimport { YAMLMap } from '../../nodes/YAMLMap.js';\nimport { YAMLSeq } from '../../nodes/YAMLSeq.js';\nimport { resolvePairs, createPairs } from './pairs.js';\n\nclass YAMLOMap extends YAMLSeq {\n    constructor() {\n        super();\n        this.add = YAMLMap.prototype.add.bind(this);\n        this.delete = YAMLMap.prototype.delete.bind(this);\n        this.get = YAMLMap.prototype.get.bind(this);\n        this.has = YAMLMap.prototype.has.bind(this);\n        this.set = YAMLMap.prototype.set.bind(this);\n        this.tag = YAMLOMap.tag;\n    }\n    /**\n     * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,\n     * but TypeScript won't allow widening the signature of a child method.\n     */\n    toJSON(_, ctx) {\n        if (!ctx)\n            return super.toJSON(_);\n        const map = new Map();\n        if (ctx?.onCreate)\n            ctx.onCreate(map);\n        for (const pair of this.items) {\n            let key, value;\n            if (isPair(pair)) {\n                key = toJS(pair.key, '', ctx);\n                value = toJS(pair.value, key, ctx);\n            }\n            else {\n                key = toJS(pair, '', ctx);\n            }\n            if (map.has(key))\n                throw new Error('Ordered maps must not include duplicate keys');\n            map.set(key, value);\n        }\n        return map;\n    }\n    static from(schema, iterable, ctx) {\n        const pairs = createPairs(schema, iterable, ctx);\n        const omap = new this();\n        omap.items = pairs.items;\n        return omap;\n    }\n}\nYAMLOMap.tag = 'tag:yaml.org,2002:omap';\nconst omap = {\n    collection: 'seq',\n    identify: value => value instanceof Map,\n    nodeClass: YAMLOMap,\n    default: false,\n    tag: 'tag:yaml.org,2002:omap',\n    resolve(seq, onError) {\n        const pairs = resolvePairs(seq, onError);\n        const seenKeys = [];\n        for (const { key } of pairs.items) {\n            if (isScalar(key)) {\n                if (seenKeys.includes(key.value)) {\n                    onError(`Ordered maps must not include duplicate keys: ${key.value}`);\n                }\n                else {\n                    seenKeys.push(key.value);\n                }\n            }\n        }\n        return Object.assign(new YAMLOMap(), pairs);\n    },\n    createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)\n};\n\nexport { YAMLOMap, omap };\n","import { Scalar } from '../../nodes/Scalar.js';\n\nfunction boolStringify({ value, source }, ctx) {\n    const boolObj = value ? trueTag : falseTag;\n    if (source && boolObj.test.test(source))\n        return source;\n    return value ? ctx.options.trueStr : ctx.options.falseStr;\n}\nconst trueTag = {\n    identify: value => value === true,\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,\n    resolve: () => new Scalar(true),\n    stringify: boolStringify\n};\nconst falseTag = {\n    identify: value => value === false,\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,\n    resolve: () => new Scalar(false),\n    stringify: boolStringify\n};\n\nexport { falseTag, trueTag };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst floatNaN = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n    resolve: (str) => str.slice(-3).toLowerCase() === 'nan'\n        ? NaN\n        : str[0] === '-'\n            ? Number.NEGATIVE_INFINITY\n            : Number.POSITIVE_INFINITY,\n    stringify: stringifyNumber\n};\nconst floatExp = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'EXP',\n    test: /^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,\n    resolve: (str) => parseFloat(str.replace(/_/g, '')),\n    stringify(node) {\n        const num = Number(node.value);\n        return isFinite(num) ? num.toExponential() : stringifyNumber(node);\n    }\n};\nconst float = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,\n    resolve(str) {\n        const node = new Scalar(parseFloat(str.replace(/_/g, '')));\n        const dot = str.indexOf('.');\n        if (dot !== -1) {\n            const f = str.substring(dot + 1).replace(/_/g, '');\n            if (f[f.length - 1] === '0')\n                node.minFractionDigits = f.length;\n        }\n        return node;\n    },\n    stringify: stringifyNumber\n};\n\nexport { float, floatExp, floatNaN };\n","import { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nfunction intResolve(str, offset, radix, { intAsBigInt }) {\n    const sign = str[0];\n    if (sign === '-' || sign === '+')\n        offset += 1;\n    str = str.substring(offset).replace(/_/g, '');\n    if (intAsBigInt) {\n        switch (radix) {\n            case 2:\n                str = `0b${str}`;\n                break;\n            case 8:\n                str = `0o${str}`;\n                break;\n            case 16:\n                str = `0x${str}`;\n                break;\n        }\n        const n = BigInt(str);\n        return sign === '-' ? BigInt(-1) * n : n;\n    }\n    const n = parseInt(str, radix);\n    return sign === '-' ? -1 * n : n;\n}\nfunction intStringify(node, radix, prefix) {\n    const { value } = node;\n    if (intIdentify(value)) {\n        const str = value.toString(radix);\n        return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;\n    }\n    return stringifyNumber(node);\n}\nconst intBin = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'BIN',\n    test: /^[-+]?0b[0-1_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),\n    stringify: node => intStringify(node, 2, '0b')\n};\nconst intOct = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'OCT',\n    test: /^[-+]?0[0-7_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),\n    stringify: node => intStringify(node, 8, '0')\n};\nconst int = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    test: /^[-+]?[0-9][0-9_]*$/,\n    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n    stringify: stringifyNumber\n};\nconst intHex = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'HEX',\n    test: /^[-+]?0x[0-9a-fA-F_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n    stringify: node => intStringify(node, 16, '0x')\n};\n\nexport { int, intBin, intHex, intOct };\n","import { isMap, isPair, isScalar } from '../../nodes/identity.js';\nimport { Pair, createPair } from '../../nodes/Pair.js';\nimport { YAMLMap, findPair } from '../../nodes/YAMLMap.js';\n\nclass YAMLSet extends YAMLMap {\n    constructor(schema) {\n        super(schema);\n        this.tag = YAMLSet.tag;\n    }\n    add(key) {\n        let pair;\n        if (isPair(key))\n            pair = key;\n        else if (key &&\n            typeof key === 'object' &&\n            'key' in key &&\n            'value' in key &&\n            key.value === null)\n            pair = new Pair(key.key, null);\n        else\n            pair = new Pair(key, null);\n        const prev = findPair(this.items, pair.key);\n        if (!prev)\n            this.items.push(pair);\n    }\n    /**\n     * If `keepPair` is `true`, returns the Pair matching `key`.\n     * Otherwise, returns the value of that Pair's key.\n     */\n    get(key, keepPair) {\n        const pair = findPair(this.items, key);\n        return !keepPair && isPair(pair)\n            ? isScalar(pair.key)\n                ? pair.key.value\n                : pair.key\n            : pair;\n    }\n    set(key, value) {\n        if (typeof value !== 'boolean')\n            throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);\n        const prev = findPair(this.items, key);\n        if (prev && !value) {\n            this.items.splice(this.items.indexOf(prev), 1);\n        }\n        else if (!prev && value) {\n            this.items.push(new Pair(key));\n        }\n    }\n    toJSON(_, ctx) {\n        return super.toJSON(_, ctx, Set);\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        if (this.hasAllNullValues(true))\n            return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);\n        else\n            throw new Error('Set items must all have null values');\n    }\n    static from(schema, iterable, ctx) {\n        const { replacer } = ctx;\n        const set = new this(schema);\n        if (iterable && Symbol.iterator in Object(iterable))\n            for (let value of iterable) {\n                if (typeof replacer === 'function')\n                    value = replacer.call(iterable, value, value);\n                set.items.push(createPair(value, null, ctx));\n            }\n        return set;\n    }\n}\nYAMLSet.tag = 'tag:yaml.org,2002:set';\nconst set = {\n    collection: 'map',\n    identify: value => value instanceof Set,\n    nodeClass: YAMLSet,\n    default: false,\n    tag: 'tag:yaml.org,2002:set',\n    createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),\n    resolve(map, onError) {\n        if (isMap(map)) {\n            if (map.hasAllNullValues(true))\n                return Object.assign(new YAMLSet(), map);\n            else\n                onError('Set items must all have null values');\n        }\n        else\n            onError('Expected a mapping for this tag');\n        return map;\n    }\n};\n\nexport { YAMLSet, set };\n","import { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\n/** Internal types handle bigint as number, because TS can't figure it out. */\nfunction parseSexagesimal(str, asBigInt) {\n    const sign = str[0];\n    const parts = sign === '-' || sign === '+' ? str.substring(1) : str;\n    const num = (n) => asBigInt ? BigInt(n) : Number(n);\n    const res = parts\n        .replace(/_/g, '')\n        .split(':')\n        .reduce((res, p) => res * num(60) + num(p), num(0));\n    return (sign === '-' ? num(-1) * res : res);\n}\n/**\n * hhhh:mm:ss.sss\n *\n * Internal types handle bigint as number, because TS can't figure it out.\n */\nfunction stringifySexagesimal(node) {\n    let { value } = node;\n    let num = (n) => n;\n    if (typeof value === 'bigint')\n        num = n => BigInt(n);\n    else if (isNaN(value) || !isFinite(value))\n        return stringifyNumber(node);\n    let sign = '';\n    if (value < 0) {\n        sign = '-';\n        value *= num(-1);\n    }\n    const _60 = num(60);\n    const parts = [value % _60]; // seconds, including ms\n    if (value < 60) {\n        parts.unshift(0); // at least one : is required\n    }\n    else {\n        value = (value - parts[0]) / _60;\n        parts.unshift(value % _60); // minutes\n        if (value >= 60) {\n            value = (value - parts[0]) / _60;\n            parts.unshift(value); // hours\n        }\n    }\n    return (sign +\n        parts\n            .map(n => String(n).padStart(2, '0'))\n            .join(':')\n            .replace(/000000\\d*$/, '') // % 60 may introduce error\n    );\n}\nconst intTime = {\n    identify: value => typeof value === 'bigint' || Number.isInteger(value),\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'TIME',\n    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,\n    resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),\n    stringify: stringifySexagesimal\n};\nconst floatTime = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'TIME',\n    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,\n    resolve: str => parseSexagesimal(str, false),\n    stringify: stringifySexagesimal\n};\nconst timestamp = {\n    identify: value => value instanceof Date,\n    default: true,\n    tag: 'tag:yaml.org,2002:timestamp',\n    // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part\n    // may be omitted altogether, resulting in a date format. In such a case, the time part is\n    // assumed to be 00:00:00Z (start of day, UTC).\n    test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd\n        '(?:' + // time is optional\n        '(?:t|T|[ \\\\t]+)' + // t | T | whitespace\n        '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?\n        '(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30\n        ')?$'),\n    resolve(str) {\n        const match = str.match(timestamp.test);\n        if (!match)\n            throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');\n        const [, year, month, day, hour, minute, second] = match.map(Number);\n        const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;\n        let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);\n        const tz = match[8];\n        if (tz && tz !== 'Z') {\n            let d = parseSexagesimal(tz, false);\n            if (Math.abs(d) < 30)\n                d *= 60;\n            date -= 60000 * d;\n        }\n        return new Date(date);\n    },\n    stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\\.000Z$/, '') ?? ''\n};\n\nexport { floatTime, intTime, timestamp };\n","import { map } from '../common/map.js';\nimport { nullTag } from '../common/null.js';\nimport { seq } from '../common/seq.js';\nimport { string } from '../common/string.js';\nimport { binary } from './binary.js';\nimport { trueTag, falseTag } from './bool.js';\nimport { floatNaN, floatExp, float } from './float.js';\nimport { intBin, intOct, int, intHex } from './int.js';\nimport { merge } from './merge.js';\nimport { omap } from './omap.js';\nimport { pairs } from './pairs.js';\nimport { set } from './set.js';\nimport { intTime, floatTime, timestamp } from './timestamp.js';\n\nconst schema = [\n    map,\n    seq,\n    string,\n    nullTag,\n    trueTag,\n    falseTag,\n    intBin,\n    intOct,\n    int,\n    intHex,\n    floatNaN,\n    floatExp,\n    float,\n    binary,\n    merge,\n    omap,\n    pairs,\n    set,\n    intTime,\n    floatTime,\n    timestamp\n];\n\nexport { schema };\n","import { map } from './common/map.js';\nimport { nullTag } from './common/null.js';\nimport { seq } from './common/seq.js';\nimport { string } from './common/string.js';\nimport { boolTag } from './core/bool.js';\nimport { floatNaN, floatExp, float } from './core/float.js';\nimport { intOct, intHex, int } from './core/int.js';\nimport { schema } from './core/schema.js';\nimport { schema as schema$1 } from './json/schema.js';\nimport { binary } from './yaml-1.1/binary.js';\nimport { merge } from './yaml-1.1/merge.js';\nimport { omap } from './yaml-1.1/omap.js';\nimport { pairs } from './yaml-1.1/pairs.js';\nimport { schema as schema$2 } from './yaml-1.1/schema.js';\nimport { set } from './yaml-1.1/set.js';\nimport { timestamp, intTime, floatTime } from './yaml-1.1/timestamp.js';\n\nconst schemas = new Map([\n    ['core', schema],\n    ['failsafe', [map, seq, string]],\n    ['json', schema$1],\n    ['yaml11', schema$2],\n    ['yaml-1.1', schema$2]\n]);\nconst tagsByName = {\n    binary,\n    bool: boolTag,\n    float,\n    floatExp,\n    floatNaN,\n    floatTime,\n    int,\n    intHex,\n    intOct,\n    intTime,\n    map,\n    merge,\n    null: nullTag,\n    omap,\n    pairs,\n    seq,\n    set,\n    timestamp\n};\nconst coreKnownTags = {\n    'tag:yaml.org,2002:binary': binary,\n    'tag:yaml.org,2002:merge': merge,\n    'tag:yaml.org,2002:omap': omap,\n    'tag:yaml.org,2002:pairs': pairs,\n    'tag:yaml.org,2002:set': set,\n    'tag:yaml.org,2002:timestamp': timestamp\n};\nfunction getTags(customTags, schemaName, addMergeTag) {\n    const schemaTags = schemas.get(schemaName);\n    if (schemaTags && !customTags) {\n        return addMergeTag && !schemaTags.includes(merge)\n            ? schemaTags.concat(merge)\n            : schemaTags.slice();\n    }\n    let tags = schemaTags;\n    if (!tags) {\n        if (Array.isArray(customTags))\n            tags = [];\n        else {\n            const keys = Array.from(schemas.keys())\n                .filter(key => key !== 'yaml11')\n                .map(key => JSON.stringify(key))\n                .join(', ');\n            throw new Error(`Unknown schema \"${schemaName}\"; use one of ${keys} or define customTags array`);\n        }\n    }\n    if (Array.isArray(customTags)) {\n        for (const tag of customTags)\n            tags = tags.concat(tag);\n    }\n    else if (typeof customTags === 'function') {\n        tags = customTags(tags.slice());\n    }\n    if (addMergeTag)\n        tags = tags.concat(merge);\n    return tags.reduce((tags, tag) => {\n        const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;\n        if (!tagObj) {\n            const tagName = JSON.stringify(tag);\n            const keys = Object.keys(tagsByName)\n                .map(key => JSON.stringify(key))\n                .join(', ');\n            throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);\n        }\n        if (!tags.includes(tagObj))\n            tags.push(tagObj);\n        return tags;\n    }, []);\n}\n\nexport { coreKnownTags, getTags };\n","import { MAP, SCALAR, SEQ } from '../nodes/identity.js';\nimport { map } from './common/map.js';\nimport { seq } from './common/seq.js';\nimport { string } from './common/string.js';\nimport { getTags, coreKnownTags } from './tags.js';\n\nconst sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;\nclass Schema {\n    constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {\n        this.compat = Array.isArray(compat)\n            ? getTags(compat, 'compat')\n            : compat\n                ? getTags(null, compat)\n                : null;\n        this.name = (typeof schema === 'string' && schema) || 'core';\n        this.knownTags = resolveKnownTags ? coreKnownTags : {};\n        this.tags = getTags(customTags, this.name, merge);\n        this.toStringOptions = toStringDefaults ?? null;\n        Object.defineProperty(this, MAP, { value: map });\n        Object.defineProperty(this, SCALAR, { value: string });\n        Object.defineProperty(this, SEQ, { value: seq });\n        // Used by createMap()\n        this.sortMapEntries =\n            typeof sortMapEntries === 'function'\n                ? sortMapEntries\n                : sortMapEntries === true\n                    ? sortMapEntriesByKey\n                    : null;\n    }\n    clone() {\n        const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));\n        copy.tags = this.tags.slice();\n        return copy;\n    }\n}\n\nexport { Schema };\n","import { isNode } from '../nodes/identity.js';\nimport { createStringifyContext, stringify } from './stringify.js';\nimport { indentComment, lineComment } from './stringifyComment.js';\n\nfunction stringifyDocument(doc, options) {\n    const lines = [];\n    let hasDirectives = options.directives === true;\n    if (options.directives !== false && doc.directives) {\n        const dir = doc.directives.toString(doc);\n        if (dir) {\n            lines.push(dir);\n            hasDirectives = true;\n        }\n        else if (doc.directives.docStart)\n            hasDirectives = true;\n    }\n    if (hasDirectives)\n        lines.push('---');\n    const ctx = createStringifyContext(doc, options);\n    const { commentString } = ctx.options;\n    if (doc.commentBefore) {\n        if (lines.length !== 1)\n            lines.unshift('');\n        const cs = commentString(doc.commentBefore);\n        lines.unshift(indentComment(cs, ''));\n    }\n    let chompKeep = false;\n    let contentComment = null;\n    if (doc.contents) {\n        if (isNode(doc.contents)) {\n            if (doc.contents.spaceBefore && hasDirectives)\n                lines.push('');\n            if (doc.contents.commentBefore) {\n                const cs = commentString(doc.contents.commentBefore);\n                lines.push(indentComment(cs, ''));\n            }\n            // top-level block scalars need to be indented if followed by a comment\n            ctx.forceBlockIndent = !!doc.comment;\n            contentComment = doc.contents.comment;\n        }\n        const onChompKeep = contentComment ? undefined : () => (chompKeep = true);\n        let body = stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);\n        if (contentComment)\n            body += lineComment(body, '', commentString(contentComment));\n        if ((body[0] === '|' || body[0] === '>') &&\n            lines[lines.length - 1] === '---') {\n            // Top-level block scalars with a preceding doc marker ought to use the\n            // same line for their header.\n            lines[lines.length - 1] = `--- ${body}`;\n        }\n        else\n            lines.push(body);\n    }\n    else {\n        lines.push(stringify(doc.contents, ctx));\n    }\n    if (doc.directives?.docEnd) {\n        if (doc.comment) {\n            const cs = commentString(doc.comment);\n            if (cs.includes('\\n')) {\n                lines.push('...');\n                lines.push(indentComment(cs, ''));\n            }\n            else {\n                lines.push(`... ${cs}`);\n            }\n        }\n        else {\n            lines.push('...');\n        }\n    }\n    else {\n        let dc = doc.comment;\n        if (dc && chompKeep)\n            dc = dc.replace(/^\\n+/, '');\n        if (dc) {\n            if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')\n                lines.push('');\n            lines.push(indentComment(commentString(dc), ''));\n        }\n    }\n    return lines.join('\\n') + '\\n';\n}\n\nexport { stringifyDocument };\n","import { Alias } from '../nodes/Alias.js';\nimport { isEmptyPath, collectionFromPath } from '../nodes/Collection.js';\nimport { NODE_TYPE, DOC, isNode, isCollection, isScalar } from '../nodes/identity.js';\nimport { Pair } from '../nodes/Pair.js';\nimport { toJS } from '../nodes/toJS.js';\nimport { Schema } from '../schema/Schema.js';\nimport { stringifyDocument } from '../stringify/stringifyDocument.js';\nimport { anchorNames, findNewAnchor, createNodeAnchors } from './anchors.js';\nimport { applyReviver } from './applyReviver.js';\nimport { createNode } from './createNode.js';\nimport { Directives } from './directives.js';\n\nclass Document {\n    constructor(value, replacer, options) {\n        /** A comment before this Document */\n        this.commentBefore = null;\n        /** A comment immediately after this Document */\n        this.comment = null;\n        /** Errors encountered during parsing. */\n        this.errors = [];\n        /** Warnings encountered during parsing. */\n        this.warnings = [];\n        Object.defineProperty(this, NODE_TYPE, { value: DOC });\n        let _replacer = null;\n        if (typeof replacer === 'function' || Array.isArray(replacer)) {\n            _replacer = replacer;\n        }\n        else if (options === undefined && replacer) {\n            options = replacer;\n            replacer = undefined;\n        }\n        const opt = Object.assign({\n            intAsBigInt: false,\n            keepSourceTokens: false,\n            logLevel: 'warn',\n            prettyErrors: true,\n            strict: true,\n            stringKeys: false,\n            uniqueKeys: true,\n            version: '1.2'\n        }, options);\n        this.options = opt;\n        let { version } = opt;\n        if (options?._directives) {\n            this.directives = options._directives.atDocument();\n            if (this.directives.yaml.explicit)\n                version = this.directives.yaml.version;\n        }\n        else\n            this.directives = new Directives({ version });\n        this.setSchema(version, options);\n        // @ts-expect-error We can't really know that this matches Contents.\n        this.contents =\n            value === undefined ? null : this.createNode(value, _replacer, options);\n    }\n    /**\n     * Create a deep copy of this Document and its contents.\n     *\n     * Custom Node values that inherit from `Object` still refer to their original instances.\n     */\n    clone() {\n        const copy = Object.create(Document.prototype, {\n            [NODE_TYPE]: { value: DOC }\n        });\n        copy.commentBefore = this.commentBefore;\n        copy.comment = this.comment;\n        copy.errors = this.errors.slice();\n        copy.warnings = this.warnings.slice();\n        copy.options = Object.assign({}, this.options);\n        if (this.directives)\n            copy.directives = this.directives.clone();\n        copy.schema = this.schema.clone();\n        // @ts-expect-error We can't really know that this matches Contents.\n        copy.contents = isNode(this.contents)\n            ? this.contents.clone(copy.schema)\n            : this.contents;\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /** Adds a value to the document. */\n    add(value) {\n        if (assertCollection(this.contents))\n            this.contents.add(value);\n    }\n    /** Adds a value to the document. */\n    addIn(path, value) {\n        if (assertCollection(this.contents))\n            this.contents.addIn(path, value);\n    }\n    /**\n     * Create a new `Alias` node, ensuring that the target `node` has the required anchor.\n     *\n     * If `node` already has an anchor, `name` is ignored.\n     * Otherwise, the `node.anchor` value will be set to `name`,\n     * or if an anchor with that name is already present in the document,\n     * `name` will be used as a prefix for a new unique anchor.\n     * If `name` is undefined, the generated anchor will use 'a' as a prefix.\n     */\n    createAlias(node, name) {\n        if (!node.anchor) {\n            const prev = anchorNames(this);\n            node.anchor =\n                // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n                !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name;\n        }\n        return new Alias(node.anchor);\n    }\n    createNode(value, replacer, options) {\n        let _replacer = undefined;\n        if (typeof replacer === 'function') {\n            value = replacer.call({ '': value }, '', value);\n            _replacer = replacer;\n        }\n        else if (Array.isArray(replacer)) {\n            const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;\n            const asStr = replacer.filter(keyToStr).map(String);\n            if (asStr.length > 0)\n                replacer = replacer.concat(asStr);\n            _replacer = replacer;\n        }\n        else if (options === undefined && replacer) {\n            options = replacer;\n            replacer = undefined;\n        }\n        const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};\n        const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this, \n        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n        anchorPrefix || 'a');\n        const ctx = {\n            aliasDuplicateObjects: aliasDuplicateObjects ?? true,\n            keepUndefined: keepUndefined ?? false,\n            onAnchor,\n            onTagObj,\n            replacer: _replacer,\n            schema: this.schema,\n            sourceObjects\n        };\n        const node = createNode(value, tag, ctx);\n        if (flow && isCollection(node))\n            node.flow = true;\n        setAnchors();\n        return node;\n    }\n    /**\n     * Convert a key and a value into a `Pair` using the current schema,\n     * recursively wrapping all values as `Scalar` or `Collection` nodes.\n     */\n    createPair(key, value, options = {}) {\n        const k = this.createNode(key, null, options);\n        const v = this.createNode(value, null, options);\n        return new Pair(k, v);\n    }\n    /**\n     * Removes a value from the document.\n     * @returns `true` if the item was found and removed.\n     */\n    delete(key) {\n        return assertCollection(this.contents) ? this.contents.delete(key) : false;\n    }\n    /**\n     * Removes a value from the document.\n     * @returns `true` if the item was found and removed.\n     */\n    deleteIn(path) {\n        if (isEmptyPath(path)) {\n            if (this.contents == null)\n                return false;\n            // @ts-expect-error Presumed impossible if Strict extends false\n            this.contents = null;\n            return true;\n        }\n        return assertCollection(this.contents)\n            ? this.contents.deleteIn(path)\n            : false;\n    }\n    /**\n     * Returns item at `key`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    get(key, keepScalar) {\n        return isCollection(this.contents)\n            ? this.contents.get(key, keepScalar)\n            : undefined;\n    }\n    /**\n     * Returns item at `path`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    getIn(path, keepScalar) {\n        if (isEmptyPath(path))\n            return !keepScalar && isScalar(this.contents)\n                ? this.contents.value\n                : this.contents;\n        return isCollection(this.contents)\n            ? this.contents.getIn(path, keepScalar)\n            : undefined;\n    }\n    /**\n     * Checks if the document includes a value with the key `key`.\n     */\n    has(key) {\n        return isCollection(this.contents) ? this.contents.has(key) : false;\n    }\n    /**\n     * Checks if the document includes a value at `path`.\n     */\n    hasIn(path) {\n        if (isEmptyPath(path))\n            return this.contents !== undefined;\n        return isCollection(this.contents) ? this.contents.hasIn(path) : false;\n    }\n    /**\n     * Sets a value in this document. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    set(key, value) {\n        if (this.contents == null) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = collectionFromPath(this.schema, [key], value);\n        }\n        else if (assertCollection(this.contents)) {\n            this.contents.set(key, value);\n        }\n    }\n    /**\n     * Sets a value in this document. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    setIn(path, value) {\n        if (isEmptyPath(path)) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = value;\n        }\n        else if (this.contents == null) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = collectionFromPath(this.schema, Array.from(path), value);\n        }\n        else if (assertCollection(this.contents)) {\n            this.contents.setIn(path, value);\n        }\n    }\n    /**\n     * Change the YAML version and schema used by the document.\n     * A `null` version disables support for directives, explicit tags, anchors, and aliases.\n     * It also requires the `schema` option to be given as a `Schema` instance value.\n     *\n     * Overrides all previously set schema options.\n     */\n    setSchema(version, options = {}) {\n        if (typeof version === 'number')\n            version = String(version);\n        let opt;\n        switch (version) {\n            case '1.1':\n                if (this.directives)\n                    this.directives.yaml.version = '1.1';\n                else\n                    this.directives = new Directives({ version: '1.1' });\n                opt = { resolveKnownTags: false, schema: 'yaml-1.1' };\n                break;\n            case '1.2':\n            case 'next':\n                if (this.directives)\n                    this.directives.yaml.version = version;\n                else\n                    this.directives = new Directives({ version });\n                opt = { resolveKnownTags: true, schema: 'core' };\n                break;\n            case null:\n                if (this.directives)\n                    delete this.directives;\n                opt = null;\n                break;\n            default: {\n                const sv = JSON.stringify(version);\n                throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);\n            }\n        }\n        // Not using `instanceof Schema` to allow for duck typing\n        if (options.schema instanceof Object)\n            this.schema = options.schema;\n        else if (opt)\n            this.schema = new Schema(Object.assign(opt, options));\n        else\n            throw new Error(`With a null YAML version, the { schema: Schema } option is required`);\n    }\n    // json & jsonArg are only used from toJSON()\n    toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n        const ctx = {\n            anchors: new Map(),\n            doc: this,\n            keep: !json,\n            mapAsMap: mapAsMap === true,\n            mapKeyWarned: false,\n            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n        };\n        const res = toJS(this.contents, jsonArg ?? '', ctx);\n        if (typeof onAnchor === 'function')\n            for (const { count, res } of ctx.anchors.values())\n                onAnchor(res, count);\n        return typeof reviver === 'function'\n            ? applyReviver(reviver, { '': res }, '', res)\n            : res;\n    }\n    /**\n     * A JSON representation of the document `contents`.\n     *\n     * @param jsonArg Used by `JSON.stringify` to indicate the array index or\n     *   property name.\n     */\n    toJSON(jsonArg, onAnchor) {\n        return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });\n    }\n    /** A YAML representation of the document. */\n    toString(options = {}) {\n        if (this.errors.length > 0)\n            throw new Error('Document with errors cannot be stringified');\n        if ('indent' in options &&\n            (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {\n            const s = JSON.stringify(options.indent);\n            throw new Error(`\"indent\" option must be a positive integer, not ${s}`);\n        }\n        return stringifyDocument(this, options);\n    }\n}\nfunction assertCollection(contents) {\n    if (isCollection(contents))\n        return true;\n    throw new Error('Expected a YAML collection as document contents');\n}\n\nexport { Document };\n","class YAMLError extends Error {\n    constructor(name, pos, code, message) {\n        super();\n        this.name = name;\n        this.code = code;\n        this.message = message;\n        this.pos = pos;\n    }\n}\nclass YAMLParseError extends YAMLError {\n    constructor(pos, code, message) {\n        super('YAMLParseError', pos, code, message);\n    }\n}\nclass YAMLWarning extends YAMLError {\n    constructor(pos, code, message) {\n        super('YAMLWarning', pos, code, message);\n    }\n}\nconst prettifyError = (src, lc) => (error) => {\n    if (error.pos[0] === -1)\n        return;\n    error.linePos = error.pos.map(pos => lc.linePos(pos));\n    const { line, col } = error.linePos[0];\n    error.message += ` at line ${line}, column ${col}`;\n    let ci = col - 1;\n    let lineStr = src\n        .substring(lc.lineStarts[line - 1], lc.lineStarts[line])\n        .replace(/[\\n\\r]+$/, '');\n    // Trim to max 80 chars, keeping col position near the middle\n    if (ci >= 60 && lineStr.length > 80) {\n        const trimStart = Math.min(ci - 39, lineStr.length - 79);\n        lineStr = '…' + lineStr.substring(trimStart);\n        ci -= trimStart - 1;\n    }\n    if (lineStr.length > 80)\n        lineStr = lineStr.substring(0, 79) + '…';\n    // Include previous line in context if pointing at line start\n    if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {\n        // Regexp won't match if start is trimmed\n        let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);\n        if (prev.length > 80)\n            prev = prev.substring(0, 79) + '…\\n';\n        lineStr = prev + lineStr;\n    }\n    if (/[^ ]/.test(lineStr)) {\n        let count = 1;\n        const end = error.linePos[1];\n        if (end?.line === line && end.col > col) {\n            count = Math.max(1, Math.min(end.col - col, 80 - ci));\n        }\n        const pointer = ' '.repeat(ci) + '^'.repeat(count);\n        error.message += `:\\n\\n${lineStr}\\n${pointer}\\n`;\n    }\n};\n\nexport { YAMLError, YAMLParseError, YAMLWarning, prettifyError };\n","function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {\n    let spaceBefore = false;\n    let atNewline = startOnNewline;\n    let hasSpace = startOnNewline;\n    let comment = '';\n    let commentSep = '';\n    let hasNewline = false;\n    let reqSpace = false;\n    let tab = null;\n    let anchor = null;\n    let tag = null;\n    let newlineAfterProp = null;\n    let comma = null;\n    let found = null;\n    let start = null;\n    for (const token of tokens) {\n        if (reqSpace) {\n            if (token.type !== 'space' &&\n                token.type !== 'newline' &&\n                token.type !== 'comma')\n                onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n            reqSpace = false;\n        }\n        if (tab) {\n            if (atNewline && token.type !== 'comment' && token.type !== 'newline') {\n                onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n            }\n            tab = null;\n        }\n        switch (token.type) {\n            case 'space':\n                // At the doc level, tabs at line start may be parsed\n                // as leading white space rather than indentation.\n                // In a flow collection, only the parser handles indent.\n                if (!flow &&\n                    (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&\n                    token.source.includes('\\t')) {\n                    tab = token;\n                }\n                hasSpace = true;\n                break;\n            case 'comment': {\n                if (!hasSpace)\n                    onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n                const cb = token.source.substring(1) || ' ';\n                if (!comment)\n                    comment = cb;\n                else\n                    comment += commentSep + cb;\n                commentSep = '';\n                atNewline = false;\n                break;\n            }\n            case 'newline':\n                if (atNewline) {\n                    if (comment)\n                        comment += token.source;\n                    else if (!found || indicator !== 'seq-item-ind')\n                        spaceBefore = true;\n                }\n                else\n                    commentSep += token.source;\n                atNewline = true;\n                hasNewline = true;\n                if (anchor || tag)\n                    newlineAfterProp = token;\n                hasSpace = true;\n                break;\n            case 'anchor':\n                if (anchor)\n                    onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');\n                if (token.source.endsWith(':'))\n                    onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);\n                anchor = token;\n                start ?? (start = token.offset);\n                atNewline = false;\n                hasSpace = false;\n                reqSpace = true;\n                break;\n            case 'tag': {\n                if (tag)\n                    onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');\n                tag = token;\n                start ?? (start = token.offset);\n                atNewline = false;\n                hasSpace = false;\n                reqSpace = true;\n                break;\n            }\n            case indicator:\n                // Could here handle preceding comments differently\n                if (anchor || tag)\n                    onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);\n                if (found)\n                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);\n                found = token;\n                atNewline =\n                    indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';\n                hasSpace = false;\n                break;\n            case 'comma':\n                if (flow) {\n                    if (comma)\n                        onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);\n                    comma = token;\n                    atNewline = false;\n                    hasSpace = false;\n                    break;\n                }\n            // else fallthrough\n            default:\n                onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);\n                atNewline = false;\n                hasSpace = false;\n        }\n    }\n    const last = tokens[tokens.length - 1];\n    const end = last ? last.offset + last.source.length : offset;\n    if (reqSpace &&\n        next &&\n        next.type !== 'space' &&\n        next.type !== 'newline' &&\n        next.type !== 'comma' &&\n        (next.type !== 'scalar' || next.source !== '')) {\n        onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n    }\n    if (tab &&\n        ((atNewline && tab.indent <= parentIndent) ||\n            next?.type === 'block-map' ||\n            next?.type === 'block-seq'))\n        onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n    return {\n        comma,\n        found,\n        spaceBefore,\n        comment,\n        hasNewline,\n        anchor,\n        tag,\n        newlineAfterProp,\n        end,\n        start: start ?? end\n    };\n}\n\nexport { resolveProps };\n","function containsNewline(key) {\n    if (!key)\n        return null;\n    switch (key.type) {\n        case 'alias':\n        case 'scalar':\n        case 'double-quoted-scalar':\n        case 'single-quoted-scalar':\n            if (key.source.includes('\\n'))\n                return true;\n            if (key.end)\n                for (const st of key.end)\n                    if (st.type === 'newline')\n                        return true;\n            return false;\n        case 'flow-collection':\n            for (const it of key.items) {\n                for (const st of it.start)\n                    if (st.type === 'newline')\n                        return true;\n                if (it.sep)\n                    for (const st of it.sep)\n                        if (st.type === 'newline')\n                            return true;\n                if (containsNewline(it.key) || containsNewline(it.value))\n                    return true;\n            }\n            return false;\n        default:\n            return true;\n    }\n}\n\nexport { containsNewline };\n","import { containsNewline } from './util-contains-newline.js';\n\nfunction flowIndentCheck(indent, fc, onError) {\n    if (fc?.type === 'flow-collection') {\n        const end = fc.end[0];\n        if (end.indent === indent &&\n            (end.source === ']' || end.source === '}') &&\n            containsNewline(fc)) {\n            const msg = 'Flow end indicator should be more indented than parent';\n            onError(end, 'BAD_INDENT', msg, true);\n        }\n    }\n}\n\nexport { flowIndentCheck };\n","import { isScalar } from '../nodes/identity.js';\n\nfunction mapIncludes(ctx, items, search) {\n    const { uniqueKeys } = ctx.options;\n    if (uniqueKeys === false)\n        return false;\n    const isEqual = typeof uniqueKeys === 'function'\n        ? uniqueKeys\n        : (a, b) => a === b || (isScalar(a) && isScalar(b) && a.value === b.value);\n    return items.some(pair => isEqual(pair.key, search));\n}\n\nexport { mapIncludes };\n","import { Pair } from '../nodes/Pair.js';\nimport { YAMLMap } from '../nodes/YAMLMap.js';\nimport { resolveProps } from './resolve-props.js';\nimport { containsNewline } from './util-contains-newline.js';\nimport { flowIndentCheck } from './util-flow-indent-check.js';\nimport { mapIncludes } from './util-map-includes.js';\n\nconst startColMsg = 'All mapping items must start at the same column';\nfunction resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {\n    const NodeClass = tag?.nodeClass ?? YAMLMap;\n    const map = new NodeClass(ctx.schema);\n    if (ctx.atRoot)\n        ctx.atRoot = false;\n    let offset = bm.offset;\n    let commentEnd = null;\n    for (const collItem of bm.items) {\n        const { start, key, sep, value } = collItem;\n        // key properties\n        const keyProps = resolveProps(start, {\n            indicator: 'explicit-key-ind',\n            next: key ?? sep?.[0],\n            offset,\n            onError,\n            parentIndent: bm.indent,\n            startOnNewline: true\n        });\n        const implicitKey = !keyProps.found;\n        if (implicitKey) {\n            if (key) {\n                if (key.type === 'block-seq')\n                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');\n                else if ('indent' in key && key.indent !== bm.indent)\n                    onError(offset, 'BAD_INDENT', startColMsg);\n            }\n            if (!keyProps.anchor && !keyProps.tag && !sep) {\n                commentEnd = keyProps.end;\n                if (keyProps.comment) {\n                    if (map.comment)\n                        map.comment += '\\n' + keyProps.comment;\n                    else\n                        map.comment = keyProps.comment;\n                }\n                continue;\n            }\n            if (keyProps.newlineAfterProp || containsNewline(key)) {\n                onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');\n            }\n        }\n        else if (keyProps.found?.indent !== bm.indent) {\n            onError(offset, 'BAD_INDENT', startColMsg);\n        }\n        // key value\n        ctx.atKey = true;\n        const keyStart = keyProps.end;\n        const keyNode = key\n            ? composeNode(ctx, key, keyProps, onError)\n            : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);\n        if (ctx.schema.compat)\n            flowIndentCheck(bm.indent, key, onError);\n        ctx.atKey = false;\n        if (mapIncludes(ctx, map.items, keyNode))\n            onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n        // value properties\n        const valueProps = resolveProps(sep ?? [], {\n            indicator: 'map-value-ind',\n            next: value,\n            offset: keyNode.range[2],\n            onError,\n            parentIndent: bm.indent,\n            startOnNewline: !key || key.type === 'block-scalar'\n        });\n        offset = valueProps.end;\n        if (valueProps.found) {\n            if (implicitKey) {\n                if (value?.type === 'block-map' && !valueProps.hasNewline)\n                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');\n                if (ctx.options.strict &&\n                    keyProps.start < valueProps.found.offset - 1024)\n                    onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');\n            }\n            // value value\n            const valueNode = value\n                ? composeNode(ctx, value, valueProps, onError)\n                : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);\n            if (ctx.schema.compat)\n                flowIndentCheck(bm.indent, value, onError);\n            offset = valueNode.range[2];\n            const pair = new Pair(keyNode, valueNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            map.items.push(pair);\n        }\n        else {\n            // key with no value\n            if (implicitKey)\n                onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');\n            if (valueProps.comment) {\n                if (keyNode.comment)\n                    keyNode.comment += '\\n' + valueProps.comment;\n                else\n                    keyNode.comment = valueProps.comment;\n            }\n            const pair = new Pair(keyNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            map.items.push(pair);\n        }\n    }\n    if (commentEnd && commentEnd < offset)\n        onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');\n    map.range = [bm.offset, offset, commentEnd ?? offset];\n    return map;\n}\n\nexport { resolveBlockMap };\n","import { YAMLSeq } from '../nodes/YAMLSeq.js';\nimport { resolveProps } from './resolve-props.js';\nimport { flowIndentCheck } from './util-flow-indent-check.js';\n\nfunction resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {\n    const NodeClass = tag?.nodeClass ?? YAMLSeq;\n    const seq = new NodeClass(ctx.schema);\n    if (ctx.atRoot)\n        ctx.atRoot = false;\n    if (ctx.atKey)\n        ctx.atKey = false;\n    let offset = bs.offset;\n    let commentEnd = null;\n    for (const { start, value } of bs.items) {\n        const props = resolveProps(start, {\n            indicator: 'seq-item-ind',\n            next: value,\n            offset,\n            onError,\n            parentIndent: bs.indent,\n            startOnNewline: true\n        });\n        if (!props.found) {\n            if (props.anchor || props.tag || value) {\n                if (value?.type === 'block-seq')\n                    onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');\n                else\n                    onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');\n            }\n            else {\n                commentEnd = props.end;\n                if (props.comment)\n                    seq.comment = props.comment;\n                continue;\n            }\n        }\n        const node = value\n            ? composeNode(ctx, value, props, onError)\n            : composeEmptyNode(ctx, props.end, start, null, props, onError);\n        if (ctx.schema.compat)\n            flowIndentCheck(bs.indent, value, onError);\n        offset = node.range[2];\n        seq.items.push(node);\n    }\n    seq.range = [bs.offset, offset, commentEnd ?? offset];\n    return seq;\n}\n\nexport { resolveBlockSeq };\n","function resolveEnd(end, offset, reqSpace, onError) {\n    let comment = '';\n    if (end) {\n        let hasSpace = false;\n        let sep = '';\n        for (const token of end) {\n            const { source, type } = token;\n            switch (type) {\n                case 'space':\n                    hasSpace = true;\n                    break;\n                case 'comment': {\n                    if (reqSpace && !hasSpace)\n                        onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n                    const cb = source.substring(1) || ' ';\n                    if (!comment)\n                        comment = cb;\n                    else\n                        comment += sep + cb;\n                    sep = '';\n                    break;\n                }\n                case 'newline':\n                    if (comment)\n                        sep += source;\n                    hasSpace = true;\n                    break;\n                default:\n                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);\n            }\n            offset += source.length;\n        }\n    }\n    return { comment, offset };\n}\n\nexport { resolveEnd };\n","import { isPair } from '../nodes/identity.js';\nimport { Pair } from '../nodes/Pair.js';\nimport { YAMLMap } from '../nodes/YAMLMap.js';\nimport { YAMLSeq } from '../nodes/YAMLSeq.js';\nimport { resolveEnd } from './resolve-end.js';\nimport { resolveProps } from './resolve-props.js';\nimport { containsNewline } from './util-contains-newline.js';\nimport { mapIncludes } from './util-map-includes.js';\n\nconst blockMsg = 'Block collections are not allowed within flow collections';\nconst isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');\nfunction resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {\n    const isMap = fc.start.source === '{';\n    const fcName = isMap ? 'flow map' : 'flow sequence';\n    const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap : YAMLSeq));\n    const coll = new NodeClass(ctx.schema);\n    coll.flow = true;\n    const atRoot = ctx.atRoot;\n    if (atRoot)\n        ctx.atRoot = false;\n    if (ctx.atKey)\n        ctx.atKey = false;\n    let offset = fc.offset + fc.start.source.length;\n    for (let i = 0; i < fc.items.length; ++i) {\n        const collItem = fc.items[i];\n        const { start, key, sep, value } = collItem;\n        const props = resolveProps(start, {\n            flow: fcName,\n            indicator: 'explicit-key-ind',\n            next: key ?? sep?.[0],\n            offset,\n            onError,\n            parentIndent: fc.indent,\n            startOnNewline: false\n        });\n        if (!props.found) {\n            if (!props.anchor && !props.tag && !sep && !value) {\n                if (i === 0 && props.comma)\n                    onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n                else if (i < fc.items.length - 1)\n                    onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);\n                if (props.comment) {\n                    if (coll.comment)\n                        coll.comment += '\\n' + props.comment;\n                    else\n                        coll.comment = props.comment;\n                }\n                offset = props.end;\n                continue;\n            }\n            if (!isMap && ctx.options.strict && containsNewline(key))\n                onError(key, // checked by containsNewline()\n                'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n        }\n        if (i === 0) {\n            if (props.comma)\n                onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n        }\n        else {\n            if (!props.comma)\n                onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);\n            if (props.comment) {\n                let prevItemComment = '';\n                loop: for (const st of start) {\n                    switch (st.type) {\n                        case 'comma':\n                        case 'space':\n                            break;\n                        case 'comment':\n                            prevItemComment = st.source.substring(1);\n                            break loop;\n                        default:\n                            break loop;\n                    }\n                }\n                if (prevItemComment) {\n                    let prev = coll.items[coll.items.length - 1];\n                    if (isPair(prev))\n                        prev = prev.value ?? prev.key;\n                    if (prev.comment)\n                        prev.comment += '\\n' + prevItemComment;\n                    else\n                        prev.comment = prevItemComment;\n                    props.comment = props.comment.substring(prevItemComment.length + 1);\n                }\n            }\n        }\n        if (!isMap && !sep && !props.found) {\n            // item is a value in a seq\n            // → key & sep are empty, start does not include ? or :\n            const valueNode = value\n                ? composeNode(ctx, value, props, onError)\n                : composeEmptyNode(ctx, props.end, sep, null, props, onError);\n            coll.items.push(valueNode);\n            offset = valueNode.range[2];\n            if (isBlock(value))\n                onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n        }\n        else {\n            // item is a key+value pair\n            // key value\n            ctx.atKey = true;\n            const keyStart = props.end;\n            const keyNode = key\n                ? composeNode(ctx, key, props, onError)\n                : composeEmptyNode(ctx, keyStart, start, null, props, onError);\n            if (isBlock(key))\n                onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);\n            ctx.atKey = false;\n            // value properties\n            const valueProps = resolveProps(sep ?? [], {\n                flow: fcName,\n                indicator: 'map-value-ind',\n                next: value,\n                offset: keyNode.range[2],\n                onError,\n                parentIndent: fc.indent,\n                startOnNewline: false\n            });\n            if (valueProps.found) {\n                if (!isMap && !props.found && ctx.options.strict) {\n                    if (sep)\n                        for (const st of sep) {\n                            if (st === valueProps.found)\n                                break;\n                            if (st.type === 'newline') {\n                                onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n                                break;\n                            }\n                        }\n                    if (props.start < valueProps.found.offset - 1024)\n                        onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');\n                }\n            }\n            else if (value) {\n                if ('source' in value && value.source?.[0] === ':')\n                    onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);\n                else\n                    onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);\n            }\n            // value value\n            const valueNode = value\n                ? composeNode(ctx, value, valueProps, onError)\n                : valueProps.found\n                    ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)\n                    : null;\n            if (valueNode) {\n                if (isBlock(value))\n                    onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n            }\n            else if (valueProps.comment) {\n                if (keyNode.comment)\n                    keyNode.comment += '\\n' + valueProps.comment;\n                else\n                    keyNode.comment = valueProps.comment;\n            }\n            const pair = new Pair(keyNode, valueNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            if (isMap) {\n                const map = coll;\n                if (mapIncludes(ctx, map.items, keyNode))\n                    onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n                map.items.push(pair);\n            }\n            else {\n                const map = new YAMLMap(ctx.schema);\n                map.flow = true;\n                map.items.push(pair);\n                const endRange = (valueNode ?? keyNode).range;\n                map.range = [keyNode.range[0], endRange[1], endRange[2]];\n                coll.items.push(map);\n            }\n            offset = valueNode ? valueNode.range[2] : valueProps.end;\n        }\n    }\n    const expectedEnd = isMap ? '}' : ']';\n    const [ce, ...ee] = fc.end;\n    let cePos = offset;\n    if (ce?.source === expectedEnd)\n        cePos = ce.offset + ce.source.length;\n    else {\n        const name = fcName[0].toUpperCase() + fcName.substring(1);\n        const msg = atRoot\n            ? `${name} must end with a ${expectedEnd}`\n            : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;\n        onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);\n        if (ce && ce.source.length !== 1)\n            ee.unshift(ce);\n    }\n    if (ee.length > 0) {\n        const end = resolveEnd(ee, cePos, ctx.options.strict, onError);\n        if (end.comment) {\n            if (coll.comment)\n                coll.comment += '\\n' + end.comment;\n            else\n                coll.comment = end.comment;\n        }\n        coll.range = [fc.offset, cePos, end.offset];\n    }\n    else {\n        coll.range = [fc.offset, cePos, cePos];\n    }\n    return coll;\n}\n\nexport { resolveFlowCollection };\n","import { isNode } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\nimport { YAMLMap } from '../nodes/YAMLMap.js';\nimport { YAMLSeq } from '../nodes/YAMLSeq.js';\nimport { resolveBlockMap } from './resolve-block-map.js';\nimport { resolveBlockSeq } from './resolve-block-seq.js';\nimport { resolveFlowCollection } from './resolve-flow-collection.js';\n\nfunction resolveCollection(CN, ctx, token, onError, tagName, tag) {\n    const coll = token.type === 'block-map'\n        ? resolveBlockMap(CN, ctx, token, onError, tag)\n        : token.type === 'block-seq'\n            ? resolveBlockSeq(CN, ctx, token, onError, tag)\n            : resolveFlowCollection(CN, ctx, token, onError, tag);\n    const Coll = coll.constructor;\n    // If we got a tagName matching the class, or the tag name is '!',\n    // then use the tagName from the node class used to create it.\n    if (tagName === '!' || tagName === Coll.tagName) {\n        coll.tag = Coll.tagName;\n        return coll;\n    }\n    if (tagName)\n        coll.tag = tagName;\n    return coll;\n}\nfunction composeCollection(CN, ctx, token, props, onError) {\n    const tagToken = props.tag;\n    const tagName = !tagToken\n        ? null\n        : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));\n    if (token.type === 'block-seq') {\n        const { anchor, newlineAfterProp: nl } = props;\n        const lastProp = anchor && tagToken\n            ? anchor.offset > tagToken.offset\n                ? anchor\n                : tagToken\n            : (anchor ?? tagToken);\n        if (lastProp && (!nl || nl.offset < lastProp.offset)) {\n            const message = 'Missing newline after block sequence props';\n            onError(lastProp, 'MISSING_CHAR', message);\n        }\n    }\n    const expType = token.type === 'block-map'\n        ? 'map'\n        : token.type === 'block-seq'\n            ? 'seq'\n            : token.start.source === '{'\n                ? 'map'\n                : 'seq';\n    // shortcut: check if it's a generic YAMLMap or YAMLSeq\n    // before jumping into the custom tag logic.\n    if (!tagToken ||\n        !tagName ||\n        tagName === '!' ||\n        (tagName === YAMLMap.tagName && expType === 'map') ||\n        (tagName === YAMLSeq.tagName && expType === 'seq')) {\n        return resolveCollection(CN, ctx, token, onError, tagName);\n    }\n    let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);\n    if (!tag) {\n        const kt = ctx.schema.knownTags[tagName];\n        if (kt?.collection === expType) {\n            ctx.schema.tags.push(Object.assign({}, kt, { default: false }));\n            tag = kt;\n        }\n        else {\n            if (kt) {\n                onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true);\n            }\n            else {\n                onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);\n            }\n            return resolveCollection(CN, ctx, token, onError, tagName);\n        }\n    }\n    const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);\n    const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;\n    const node = isNode(res)\n        ? res\n        : new Scalar(res);\n    node.range = coll.range;\n    node.tag = tagName;\n    if (tag?.format)\n        node.format = tag.format;\n    return node;\n}\n\nexport { composeCollection };\n","import { Scalar } from '../nodes/Scalar.js';\n\nfunction resolveBlockScalar(ctx, scalar, onError) {\n    const start = scalar.offset;\n    const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);\n    if (!header)\n        return { value: '', type: null, comment: '', range: [start, start, start] };\n    const type = header.mode === '>' ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL;\n    const lines = scalar.source ? splitLines(scalar.source) : [];\n    // determine the end of content & start of chomping\n    let chompStart = lines.length;\n    for (let i = lines.length - 1; i >= 0; --i) {\n        const content = lines[i][1];\n        if (content === '' || content === '\\r')\n            chompStart = i;\n        else\n            break;\n    }\n    // shortcut for empty contents\n    if (chompStart === 0) {\n        const value = header.chomp === '+' && lines.length > 0\n            ? '\\n'.repeat(Math.max(1, lines.length - 1))\n            : '';\n        let end = start + header.length;\n        if (scalar.source)\n            end += scalar.source.length;\n        return { value, type, comment: header.comment, range: [start, end, end] };\n    }\n    // find the indentation level to trim from start\n    let trimIndent = scalar.indent + header.indent;\n    let offset = scalar.offset + header.length;\n    let contentStart = 0;\n    for (let i = 0; i < chompStart; ++i) {\n        const [indent, content] = lines[i];\n        if (content === '' || content === '\\r') {\n            if (header.indent === 0 && indent.length > trimIndent)\n                trimIndent = indent.length;\n        }\n        else {\n            if (indent.length < trimIndent) {\n                const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';\n                onError(offset + indent.length, 'MISSING_CHAR', message);\n            }\n            if (header.indent === 0)\n                trimIndent = indent.length;\n            contentStart = i;\n            if (trimIndent === 0 && !ctx.atRoot) {\n                const message = 'Block scalar values in collections must be indented';\n                onError(offset, 'BAD_INDENT', message);\n            }\n            break;\n        }\n        offset += indent.length + content.length + 1;\n    }\n    // include trailing more-indented empty lines in content\n    for (let i = lines.length - 1; i >= chompStart; --i) {\n        if (lines[i][0].length > trimIndent)\n            chompStart = i + 1;\n    }\n    let value = '';\n    let sep = '';\n    let prevMoreIndented = false;\n    // leading whitespace is kept intact\n    for (let i = 0; i < contentStart; ++i)\n        value += lines[i][0].slice(trimIndent) + '\\n';\n    for (let i = contentStart; i < chompStart; ++i) {\n        let [indent, content] = lines[i];\n        offset += indent.length + content.length + 1;\n        const crlf = content[content.length - 1] === '\\r';\n        if (crlf)\n            content = content.slice(0, -1);\n        /* istanbul ignore if already caught in lexer */\n        if (content && indent.length < trimIndent) {\n            const src = header.indent\n                ? 'explicit indentation indicator'\n                : 'first line';\n            const message = `Block scalar lines must not be less indented than their ${src}`;\n            onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);\n            indent = '';\n        }\n        if (type === Scalar.BLOCK_LITERAL) {\n            value += sep + indent.slice(trimIndent) + content;\n            sep = '\\n';\n        }\n        else if (indent.length > trimIndent || content[0] === '\\t') {\n            // more-indented content within a folded block\n            if (sep === ' ')\n                sep = '\\n';\n            else if (!prevMoreIndented && sep === '\\n')\n                sep = '\\n\\n';\n            value += sep + indent.slice(trimIndent) + content;\n            sep = '\\n';\n            prevMoreIndented = true;\n        }\n        else if (content === '') {\n            // empty line\n            if (sep === '\\n')\n                value += '\\n';\n            else\n                sep = '\\n';\n        }\n        else {\n            value += sep + content;\n            sep = ' ';\n            prevMoreIndented = false;\n        }\n    }\n    switch (header.chomp) {\n        case '-':\n            break;\n        case '+':\n            for (let i = chompStart; i < lines.length; ++i)\n                value += '\\n' + lines[i][0].slice(trimIndent);\n            if (value[value.length - 1] !== '\\n')\n                value += '\\n';\n            break;\n        default:\n            value += '\\n';\n    }\n    const end = start + header.length + scalar.source.length;\n    return { value, type, comment: header.comment, range: [start, end, end] };\n}\nfunction parseBlockScalarHeader({ offset, props }, strict, onError) {\n    /* istanbul ignore if should not happen */\n    if (props[0].type !== 'block-scalar-header') {\n        onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');\n        return null;\n    }\n    const { source } = props[0];\n    const mode = source[0];\n    let indent = 0;\n    let chomp = '';\n    let error = -1;\n    for (let i = 1; i < source.length; ++i) {\n        const ch = source[i];\n        if (!chomp && (ch === '-' || ch === '+'))\n            chomp = ch;\n        else {\n            const n = Number(ch);\n            if (!indent && n)\n                indent = n;\n            else if (error === -1)\n                error = offset + i;\n        }\n    }\n    if (error !== -1)\n        onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);\n    let hasSpace = false;\n    let comment = '';\n    let length = source.length;\n    for (let i = 1; i < props.length; ++i) {\n        const token = props[i];\n        switch (token.type) {\n            case 'space':\n                hasSpace = true;\n            // fallthrough\n            case 'newline':\n                length += token.source.length;\n                break;\n            case 'comment':\n                if (strict && !hasSpace) {\n                    const message = 'Comments must be separated from other tokens by white space characters';\n                    onError(token, 'MISSING_CHAR', message);\n                }\n                length += token.source.length;\n                comment = token.source.substring(1);\n                break;\n            case 'error':\n                onError(token, 'UNEXPECTED_TOKEN', token.message);\n                length += token.source.length;\n                break;\n            /* istanbul ignore next should not happen */\n            default: {\n                const message = `Unexpected token in block scalar header: ${token.type}`;\n                onError(token, 'UNEXPECTED_TOKEN', message);\n                const ts = token.source;\n                if (ts && typeof ts === 'string')\n                    length += ts.length;\n            }\n        }\n    }\n    return { mode, indent, chomp, comment, length };\n}\n/** @returns Array of lines split up as `[indent, content]` */\nfunction splitLines(source) {\n    const split = source.split(/\\n( *)/);\n    const first = split[0];\n    const m = first.match(/^( *)/);\n    const line0 = m?.[1]\n        ? [m[1], first.slice(m[1].length)]\n        : ['', first];\n    const lines = [line0];\n    for (let i = 1; i < split.length; i += 2)\n        lines.push([split[i], split[i + 1]]);\n    return lines;\n}\n\nexport { resolveBlockScalar };\n","import { Scalar } from '../nodes/Scalar.js';\nimport { resolveEnd } from './resolve-end.js';\n\nfunction resolveFlowScalar(scalar, strict, onError) {\n    const { offset, type, source, end } = scalar;\n    let _type;\n    let value;\n    const _onError = (rel, code, msg) => onError(offset + rel, code, msg);\n    switch (type) {\n        case 'scalar':\n            _type = Scalar.PLAIN;\n            value = plainValue(source, _onError);\n            break;\n        case 'single-quoted-scalar':\n            _type = Scalar.QUOTE_SINGLE;\n            value = singleQuotedValue(source, _onError);\n            break;\n        case 'double-quoted-scalar':\n            _type = Scalar.QUOTE_DOUBLE;\n            value = doubleQuotedValue(source, _onError);\n            break;\n        /* istanbul ignore next should not happen */\n        default:\n            onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);\n            return {\n                value: '',\n                type: null,\n                comment: '',\n                range: [offset, offset + source.length, offset + source.length]\n            };\n    }\n    const valueEnd = offset + source.length;\n    const re = resolveEnd(end, valueEnd, strict, onError);\n    return {\n        value,\n        type: _type,\n        comment: re.comment,\n        range: [offset, valueEnd, re.offset]\n    };\n}\nfunction plainValue(source, onError) {\n    let badChar = '';\n    switch (source[0]) {\n        /* istanbul ignore next should not happen */\n        case '\\t':\n            badChar = 'a tab character';\n            break;\n        case ',':\n            badChar = 'flow indicator character ,';\n            break;\n        case '%':\n            badChar = 'directive indicator character %';\n            break;\n        case '|':\n        case '>': {\n            badChar = `block scalar indicator ${source[0]}`;\n            break;\n        }\n        case '@':\n        case '`': {\n            badChar = `reserved character ${source[0]}`;\n            break;\n        }\n    }\n    if (badChar)\n        onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);\n    return unfoldLines(source);\n}\nfunction singleQuotedValue(source, onError) {\n    if (source[source.length - 1] !== \"'\" || source.length === 1)\n        onError(source.length, 'MISSING_CHAR', \"Missing closing 'quote\");\n    return unfoldLines(source.slice(1, -1)).replace(/''/g, \"'\");\n}\nfunction unfoldLines(source) {\n    const line = /(.*?)\\r?\\n/sy;\n    let match = line.exec(source);\n    if (!match)\n        return source;\n    /**\n     * The negative lookbehinds in these RegExps are to\n     * prevent causing a polynomial search time in certain cases.\n     *\n     * The try-catch is for Safari < 16.4 and other old browsers:\n     * https://caniuse.com/js-regexp-lookbehind\n     */\n    let trimEnd, trimBoth;\n    try {\n        trimEnd = new RegExp('(?<![ \\t])[ \\t]+$');\n        trimBoth = new RegExp('^[ \\t]+|(?<![ \\t])[ \\t]+$', 'g');\n    }\n    catch {\n        trimEnd = /[ \\t]+$/;\n        trimBoth = /^[ \\t]+|[ \\t]+$/g;\n    }\n    let res = match[1].replace(trimEnd, '');\n    let sep = ' ';\n    let pos = line.lastIndex;\n    while ((match = line.exec(source))) {\n        const lm = match[1].replace(trimBoth, '');\n        if (lm === '') {\n            if (sep === '\\n')\n                res += sep;\n            else\n                sep = '\\n';\n        }\n        else {\n            res += sep + lm;\n            sep = ' ';\n        }\n        pos = line.lastIndex;\n    }\n    const last = /[ \\t]*(.*)/sy;\n    last.lastIndex = pos;\n    match = last.exec(source);\n    return res + sep + (match?.[1] ?? '');\n}\nfunction doubleQuotedValue(source, onError) {\n    let res = '';\n    for (let i = 1; i < source.length - 1; ++i) {\n        const ch = source[i];\n        if (ch === '\\r' && source[i + 1] === '\\n')\n            continue;\n        if (ch === '\\n') {\n            const { fold, offset } = foldNewline(source, i);\n            res += fold;\n            i = offset;\n        }\n        else if (ch === '\\\\') {\n            let next = source[++i];\n            const cc = escapeCodes[next];\n            if (cc)\n                res += cc;\n            else if (next === '\\n') {\n                // skip escaped newlines, but still trim the following line\n                next = source[i + 1];\n                while (next === ' ' || next === '\\t')\n                    next = source[++i + 1];\n            }\n            else if (next === '\\r' && source[i + 1] === '\\n') {\n                // skip escaped CRLF newlines, but still trim the following line\n                next = source[++i + 1];\n                while (next === ' ' || next === '\\t')\n                    next = source[++i + 1];\n            }\n            else if (next === 'x' || next === 'u' || next === 'U') {\n                const length = next === 'x' ? 2 : next === 'u' ? 4 : 8;\n                res += parseCharCode(source, i + 1, length, onError);\n                i += length;\n            }\n            else {\n                const raw = source.substr(i - 1, 2);\n                onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n                res += raw;\n            }\n        }\n        else if (ch === ' ' || ch === '\\t') {\n            // trim trailing whitespace\n            const wsStart = i;\n            let next = source[i + 1];\n            while (next === ' ' || next === '\\t')\n                next = source[++i + 1];\n            if (next !== '\\n' && !(next === '\\r' && source[i + 2] === '\\n'))\n                res += i > wsStart ? source.slice(wsStart, i + 1) : ch;\n        }\n        else {\n            res += ch;\n        }\n    }\n    if (source[source.length - 1] !== '\"' || source.length === 1)\n        onError(source.length, 'MISSING_CHAR', 'Missing closing \"quote');\n    return res;\n}\n/**\n * Fold a single newline into a space, multiple newlines to N - 1 newlines.\n * Presumes `source[offset] === '\\n'`\n */\nfunction foldNewline(source, offset) {\n    let fold = '';\n    let ch = source[offset + 1];\n    while (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') {\n        if (ch === '\\r' && source[offset + 2] !== '\\n')\n            break;\n        if (ch === '\\n')\n            fold += '\\n';\n        offset += 1;\n        ch = source[offset + 1];\n    }\n    if (!fold)\n        fold = ' ';\n    return { fold, offset };\n}\nconst escapeCodes = {\n    '0': '\\0', // null character\n    a: '\\x07', // bell character\n    b: '\\b', // backspace\n    e: '\\x1b', // escape character\n    f: '\\f', // form feed\n    n: '\\n', // line feed\n    r: '\\r', // carriage return\n    t: '\\t', // horizontal tab\n    v: '\\v', // vertical tab\n    N: '\\u0085', // Unicode next line\n    _: '\\u00a0', // Unicode non-breaking space\n    L: '\\u2028', // Unicode line separator\n    P: '\\u2029', // Unicode paragraph separator\n    ' ': ' ',\n    '\"': '\"',\n    '/': '/',\n    '\\\\': '\\\\',\n    '\\t': '\\t'\n};\nfunction parseCharCode(source, offset, length, onError) {\n    const cc = source.substr(offset, length);\n    const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);\n    const code = ok ? parseInt(cc, 16) : NaN;\n    try {\n        return String.fromCodePoint(code);\n    }\n    catch {\n        const raw = source.substr(offset - 2, length + 2);\n        onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n        return raw;\n    }\n}\n\nexport { resolveFlowScalar };\n","import { isScalar, SCALAR } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\nimport { resolveBlockScalar } from './resolve-block-scalar.js';\nimport { resolveFlowScalar } from './resolve-flow-scalar.js';\n\nfunction composeScalar(ctx, token, tagToken, onError) {\n    const { value, type, comment, range } = token.type === 'block-scalar'\n        ? resolveBlockScalar(ctx, token, onError)\n        : resolveFlowScalar(token, ctx.options.strict, onError);\n    const tagName = tagToken\n        ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))\n        : null;\n    let tag;\n    if (ctx.options.stringKeys && ctx.atKey) {\n        tag = ctx.schema[SCALAR];\n    }\n    else if (tagName)\n        tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);\n    else if (token.type === 'scalar')\n        tag = findScalarTagByTest(ctx, value, token, onError);\n    else\n        tag = ctx.schema[SCALAR];\n    let scalar;\n    try {\n        const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);\n        scalar = isScalar(res) ? res : new Scalar(res);\n    }\n    catch (error) {\n        const msg = error instanceof Error ? error.message : String(error);\n        onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);\n        scalar = new Scalar(value);\n    }\n    scalar.range = range;\n    scalar.source = value;\n    if (type)\n        scalar.type = type;\n    if (tagName)\n        scalar.tag = tagName;\n    if (tag.format)\n        scalar.format = tag.format;\n    if (comment)\n        scalar.comment = comment;\n    return scalar;\n}\nfunction findScalarTagByName(schema, value, tagName, tagToken, onError) {\n    if (tagName === '!')\n        return schema[SCALAR]; // non-specific tag\n    const matchWithTest = [];\n    for (const tag of schema.tags) {\n        if (!tag.collection && tag.tag === tagName) {\n            if (tag.default && tag.test)\n                matchWithTest.push(tag);\n            else\n                return tag;\n        }\n    }\n    for (const tag of matchWithTest)\n        if (tag.test?.test(value))\n            return tag;\n    const kt = schema.knownTags[tagName];\n    if (kt && !kt.collection) {\n        // Ensure that the known tag is available for stringifying,\n        // but does not get used by default.\n        schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));\n        return kt;\n    }\n    onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');\n    return schema[SCALAR];\n}\nfunction findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {\n    const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) &&\n        tag.test?.test(value)) || schema[SCALAR];\n    if (schema.compat) {\n        const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??\n            schema[SCALAR];\n        if (tag.tag !== compat.tag) {\n            const ts = directives.tagString(tag.tag);\n            const cs = directives.tagString(compat.tag);\n            const msg = `Value may be parsed as either ${ts} or ${cs}`;\n            onError(token, 'TAG_RESOLVE_FAILED', msg, true);\n        }\n    }\n    return tag;\n}\n\nexport { composeScalar };\n","function emptyScalarPosition(offset, before, pos) {\n    if (before) {\n        pos ?? (pos = before.length);\n        for (let i = pos - 1; i >= 0; --i) {\n            let st = before[i];\n            switch (st.type) {\n                case 'space':\n                case 'comment':\n                case 'newline':\n                    offset -= st.source.length;\n                    continue;\n            }\n            // Technically, an empty scalar is immediately after the last non-empty\n            // node, but it's more useful to place it after any whitespace.\n            st = before[++i];\n            while (st?.type === 'space') {\n                offset += st.source.length;\n                st = before[++i];\n            }\n            break;\n        }\n    }\n    return offset;\n}\n\nexport { emptyScalarPosition };\n","import { Alias } from '../nodes/Alias.js';\nimport { isScalar } from '../nodes/identity.js';\nimport { composeCollection } from './compose-collection.js';\nimport { composeScalar } from './compose-scalar.js';\nimport { resolveEnd } from './resolve-end.js';\nimport { emptyScalarPosition } from './util-empty-scalar-position.js';\n\nconst CN = { composeNode, composeEmptyNode };\nfunction composeNode(ctx, token, props, onError) {\n    const atKey = ctx.atKey;\n    const { spaceBefore, comment, anchor, tag } = props;\n    let node;\n    let isSrcToken = true;\n    switch (token.type) {\n        case 'alias':\n            node = composeAlias(ctx, token, onError);\n            if (anchor || tag)\n                onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');\n            break;\n        case 'scalar':\n        case 'single-quoted-scalar':\n        case 'double-quoted-scalar':\n        case 'block-scalar':\n            node = composeScalar(ctx, token, tag, onError);\n            if (anchor)\n                node.anchor = anchor.source.substring(1);\n            break;\n        case 'block-map':\n        case 'block-seq':\n        case 'flow-collection':\n            try {\n                node = composeCollection(CN, ctx, token, props, onError);\n                if (anchor)\n                    node.anchor = anchor.source.substring(1);\n            }\n            catch (error) {\n                // Almost certainly here due to a stack overflow\n                const message = error instanceof Error ? error.message : String(error);\n                onError(token, 'RESOURCE_EXHAUSTION', message);\n            }\n            break;\n        default: {\n            const message = token.type === 'error'\n                ? token.message\n                : `Unsupported token (type: ${token.type})`;\n            onError(token, 'UNEXPECTED_TOKEN', message);\n            isSrcToken = false;\n        }\n    }\n    node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));\n    if (anchor && node.anchor === '')\n        onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n    if (atKey &&\n        ctx.options.stringKeys &&\n        (!isScalar(node) ||\n            typeof node.value !== 'string' ||\n            (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) {\n        const msg = 'With stringKeys, all keys must be strings';\n        onError(tag ?? token, 'NON_STRING_KEY', msg);\n    }\n    if (spaceBefore)\n        node.spaceBefore = true;\n    if (comment) {\n        if (token.type === 'scalar' && token.source === '')\n            node.comment = comment;\n        else\n            node.commentBefore = comment;\n    }\n    // @ts-expect-error Type checking misses meaning of isSrcToken\n    if (ctx.options.keepSourceTokens && isSrcToken)\n        node.srcToken = token;\n    return node;\n}\nfunction composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {\n    const token = {\n        type: 'scalar',\n        offset: emptyScalarPosition(offset, before, pos),\n        indent: -1,\n        source: ''\n    };\n    const node = composeScalar(ctx, token, tag, onError);\n    if (anchor) {\n        node.anchor = anchor.source.substring(1);\n        if (node.anchor === '')\n            onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n    }\n    if (spaceBefore)\n        node.spaceBefore = true;\n    if (comment) {\n        node.comment = comment;\n        node.range[2] = end;\n    }\n    return node;\n}\nfunction composeAlias({ options }, { offset, source, end }, onError) {\n    const alias = new Alias(source.substring(1));\n    if (alias.source === '')\n        onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');\n    if (alias.source.endsWith(':'))\n        onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);\n    const valueEnd = offset + source.length;\n    const re = resolveEnd(end, valueEnd, options.strict, onError);\n    alias.range = [offset, valueEnd, re.offset];\n    if (re.comment)\n        alias.comment = re.comment;\n    return alias;\n}\n\nexport { composeEmptyNode, composeNode };\n","import { Document } from '../doc/Document.js';\nimport { composeNode, composeEmptyNode } from './compose-node.js';\nimport { resolveEnd } from './resolve-end.js';\nimport { resolveProps } from './resolve-props.js';\n\nfunction composeDoc(options, directives, { offset, start, value, end }, onError) {\n    const opts = Object.assign({ _directives: directives }, options);\n    const doc = new Document(undefined, opts);\n    const ctx = {\n        atKey: false,\n        atRoot: true,\n        directives: doc.directives,\n        options: doc.options,\n        schema: doc.schema\n    };\n    const props = resolveProps(start, {\n        indicator: 'doc-start',\n        next: value ?? end?.[0],\n        offset,\n        onError,\n        parentIndent: 0,\n        startOnNewline: true\n    });\n    if (props.found) {\n        doc.directives.docStart = true;\n        if (value &&\n            (value.type === 'block-map' || value.type === 'block-seq') &&\n            !props.hasNewline)\n            onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');\n    }\n    // @ts-expect-error If Contents is set, let's trust the user\n    doc.contents = value\n        ? composeNode(ctx, value, props, onError)\n        : composeEmptyNode(ctx, props.end, start, null, props, onError);\n    const contentEnd = doc.contents.range[2];\n    const re = resolveEnd(end, contentEnd, false, onError);\n    if (re.comment)\n        doc.comment = re.comment;\n    doc.range = [offset, contentEnd, re.offset];\n    return doc;\n}\n\nexport { composeDoc };\n","import { Directives } from '../doc/directives.js';\nimport { Document } from '../doc/Document.js';\nimport { YAMLWarning, YAMLParseError } from '../errors.js';\nimport { isCollection, isPair } from '../nodes/identity.js';\nimport { composeDoc } from './compose-doc.js';\nimport { resolveEnd } from './resolve-end.js';\n\nfunction getErrorPos(src) {\n    if (typeof src === 'number')\n        return [src, src + 1];\n    if (Array.isArray(src))\n        return src.length === 2 ? src : [src[0], src[1]];\n    const { offset, source } = src;\n    return [offset, offset + (typeof source === 'string' ? source.length : 1)];\n}\nfunction parsePrelude(prelude) {\n    let comment = '';\n    let atComment = false;\n    let afterEmptyLine = false;\n    for (let i = 0; i < prelude.length; ++i) {\n        const source = prelude[i];\n        switch (source[0]) {\n            case '#':\n                comment +=\n                    (comment === '' ? '' : afterEmptyLine ? '\\n\\n' : '\\n') +\n                        (source.substring(1) || ' ');\n                atComment = true;\n                afterEmptyLine = false;\n                break;\n            case '%':\n                if (prelude[i + 1]?.[0] !== '#')\n                    i += 1;\n                atComment = false;\n                break;\n            default:\n                // This may be wrong after doc-end, but in that case it doesn't matter\n                if (!atComment)\n                    afterEmptyLine = true;\n                atComment = false;\n        }\n    }\n    return { comment, afterEmptyLine };\n}\n/**\n * Compose a stream of CST nodes into a stream of YAML Documents.\n *\n * ```ts\n * import { Composer, Parser } from 'yaml'\n *\n * const src: string = ...\n * const tokens = new Parser().parse(src)\n * const docs = new Composer().compose(tokens)\n * ```\n */\nclass Composer {\n    constructor(options = {}) {\n        this.doc = null;\n        this.atDirectives = false;\n        this.prelude = [];\n        this.errors = [];\n        this.warnings = [];\n        this.onError = (source, code, message, warning) => {\n            const pos = getErrorPos(source);\n            if (warning)\n                this.warnings.push(new YAMLWarning(pos, code, message));\n            else\n                this.errors.push(new YAMLParseError(pos, code, message));\n        };\n        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n        this.directives = new Directives({ version: options.version || '1.2' });\n        this.options = options;\n    }\n    decorate(doc, afterDoc) {\n        const { comment, afterEmptyLine } = parsePrelude(this.prelude);\n        //console.log({ dc: doc.comment, prelude, comment })\n        if (comment) {\n            const dc = doc.contents;\n            if (afterDoc) {\n                doc.comment = doc.comment ? `${doc.comment}\\n${comment}` : comment;\n            }\n            else if (afterEmptyLine || doc.directives.docStart || !dc) {\n                doc.commentBefore = comment;\n            }\n            else if (isCollection(dc) && !dc.flow && dc.items.length > 0) {\n                let it = dc.items[0];\n                if (isPair(it))\n                    it = it.key;\n                const cb = it.commentBefore;\n                it.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n            }\n            else {\n                const cb = dc.commentBefore;\n                dc.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n            }\n        }\n        if (afterDoc) {\n            for (let i = 0; i < this.errors.length; ++i)\n                doc.errors.push(this.errors[i]);\n            for (let i = 0; i < this.warnings.length; ++i)\n                doc.warnings.push(this.warnings[i]);\n        }\n        else {\n            doc.errors = this.errors;\n            doc.warnings = this.warnings;\n        }\n        this.prelude = [];\n        this.errors = [];\n        this.warnings = [];\n    }\n    /**\n     * Current stream status information.\n     *\n     * Mostly useful at the end of input for an empty stream.\n     */\n    streamInfo() {\n        return {\n            comment: parsePrelude(this.prelude).comment,\n            directives: this.directives,\n            errors: this.errors,\n            warnings: this.warnings\n        };\n    }\n    /**\n     * Compose tokens into documents.\n     *\n     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n     */\n    *compose(tokens, forceDoc = false, endOffset = -1) {\n        for (const token of tokens)\n            yield* this.next(token);\n        yield* this.end(forceDoc, endOffset);\n    }\n    /** Advance the composer by one CST token. */\n    *next(token) {\n        switch (token.type) {\n            case 'directive':\n                this.directives.add(token.source, (offset, message, warning) => {\n                    const pos = getErrorPos(token);\n                    pos[0] += offset;\n                    this.onError(pos, 'BAD_DIRECTIVE', message, warning);\n                });\n                this.prelude.push(token.source);\n                this.atDirectives = true;\n                break;\n            case 'document': {\n                const doc = composeDoc(this.options, this.directives, token, this.onError);\n                if (this.atDirectives && !doc.directives.docStart)\n                    this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');\n                this.decorate(doc, false);\n                if (this.doc)\n                    yield this.doc;\n                this.doc = doc;\n                this.atDirectives = false;\n                break;\n            }\n            case 'byte-order-mark':\n            case 'space':\n                break;\n            case 'comment':\n            case 'newline':\n                this.prelude.push(token.source);\n                break;\n            case 'error': {\n                const msg = token.source\n                    ? `${token.message}: ${JSON.stringify(token.source)}`\n                    : token.message;\n                const error = new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);\n                if (this.atDirectives || !this.doc)\n                    this.errors.push(error);\n                else\n                    this.doc.errors.push(error);\n                break;\n            }\n            case 'doc-end': {\n                if (!this.doc) {\n                    const msg = 'Unexpected doc-end without preceding document';\n                    this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));\n                    break;\n                }\n                this.doc.directives.docEnd = true;\n                const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);\n                this.decorate(this.doc, true);\n                if (end.comment) {\n                    const dc = this.doc.comment;\n                    this.doc.comment = dc ? `${dc}\\n${end.comment}` : end.comment;\n                }\n                this.doc.range[2] = end.offset;\n                break;\n            }\n            default:\n                this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));\n        }\n    }\n    /**\n     * Call at end of input to yield any remaining document.\n     *\n     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n     */\n    *end(forceDoc = false, endOffset = -1) {\n        if (this.doc) {\n            this.decorate(this.doc, true);\n            yield this.doc;\n            this.doc = null;\n        }\n        else if (forceDoc) {\n            const opts = Object.assign({ _directives: this.directives }, this.options);\n            const doc = new Document(undefined, opts);\n            if (this.atDirectives)\n                this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');\n            doc.range = [0, endOffset, endOffset];\n            this.decorate(doc, false);\n            yield doc;\n        }\n    }\n}\n\nexport { Composer };\n","const BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove item');\n/**\n * Apply a visitor to a CST document or item.\n *\n * Walks through the tree (depth-first) starting from the root, calling a\n * `visitor` function with two arguments when entering each item:\n *   - `item`: The current item, which included the following members:\n *     - `start: SourceToken[]` – Source tokens before the key or value,\n *       possibly including its anchor or tag.\n *     - `key?: Token | null` – Set for pair values. May then be `null`, if\n *       the key before the `:` separator is empty.\n *     - `sep?: SourceToken[]` – Source tokens between the key and the value,\n *       which should include the `:` map value indicator if `value` is set.\n *     - `value?: Token` – The value of a sequence item, or of a map pair.\n *   - `path`: The steps from the root to the current node, as an array of\n *     `['key' | 'value', number]` tuples.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this token, continue with\n *      next sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current item, then continue with the next one\n *   - `number`: Set the index of the next step. This is useful especially if\n *     the index of the current token has changed.\n *   - `function`: Define the next visitor for this item. After the original\n *     visitor is called on item entry, next visitors are called after handling\n *     a non-empty `key` and when exiting the item.\n */\nfunction visit(cst, visitor) {\n    if ('type' in cst && cst.type === 'document')\n        cst = { start: cst.start, value: cst.value };\n    _visit(Object.freeze([]), cst, visitor);\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current item */\nvisit.SKIP = SKIP;\n/** Remove the current item */\nvisit.REMOVE = REMOVE;\n/** Find the item at `path` from `cst` as the root */\nvisit.itemAtPath = (cst, path) => {\n    let item = cst;\n    for (const [field, index] of path) {\n        const tok = item?.[field];\n        if (tok && 'items' in tok) {\n            item = tok.items[index];\n        }\n        else\n            return undefined;\n    }\n    return item;\n};\n/**\n * Get the immediate parent collection of the item at `path` from `cst` as the root.\n *\n * Throws an error if the collection is not found, which should never happen if the item itself exists.\n */\nvisit.parentCollection = (cst, path) => {\n    const parent = visit.itemAtPath(cst, path.slice(0, -1));\n    const field = path[path.length - 1][0];\n    const coll = parent?.[field];\n    if (coll && 'items' in coll)\n        return coll;\n    throw new Error('Parent collection not found');\n};\nfunction _visit(path, item, visitor) {\n    let ctrl = visitor(item, path);\n    if (typeof ctrl === 'symbol')\n        return ctrl;\n    for (const field of ['key', 'value']) {\n        const token = item[field];\n        if (token && 'items' in token) {\n            for (let i = 0; i < token.items.length; ++i) {\n                const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    token.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n            if (typeof ctrl === 'function' && field === 'key')\n                ctrl = ctrl(item, path);\n        }\n    }\n    return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;\n}\n\nexport { visit };\n","export { createScalarToken, resolveAsScalar, setScalarValue } from './cst-scalar.js';\nexport { stringify } from './cst-stringify.js';\nexport { visit } from './cst-visit.js';\n\n/** The byte order mark */\nconst BOM = '\\u{FEFF}';\n/** Start of doc-mode */\nconst DOCUMENT = '\\x02'; // C0: Start of Text\n/** Unexpected end of flow-mode */\nconst FLOW_END = '\\x18'; // C0: Cancel\n/** Next token is a scalar value */\nconst SCALAR = '\\x1f'; // C0: Unit Separator\n/** @returns `true` if `token` is a flow or block collection */\nconst isCollection = (token) => !!token && 'items' in token;\n/** @returns `true` if `token` is a flow or block scalar; not an alias */\nconst isScalar = (token) => !!token &&\n    (token.type === 'scalar' ||\n        token.type === 'single-quoted-scalar' ||\n        token.type === 'double-quoted-scalar' ||\n        token.type === 'block-scalar');\n/* istanbul ignore next */\n/** Get a printable representation of a lexer token */\nfunction prettyToken(token) {\n    switch (token) {\n        case BOM:\n            return '<BOM>';\n        case DOCUMENT:\n            return '<DOC>';\n        case FLOW_END:\n            return '<FLOW_END>';\n        case SCALAR:\n            return '<SCALAR>';\n        default:\n            return JSON.stringify(token);\n    }\n}\n/** Identify the type of a lexer token. May return `null` for unknown tokens. */\nfunction tokenType(source) {\n    switch (source) {\n        case BOM:\n            return 'byte-order-mark';\n        case DOCUMENT:\n            return 'doc-mode';\n        case FLOW_END:\n            return 'flow-error-end';\n        case SCALAR:\n            return 'scalar';\n        case '---':\n            return 'doc-start';\n        case '...':\n            return 'doc-end';\n        case '':\n        case '\\n':\n        case '\\r\\n':\n            return 'newline';\n        case '-':\n            return 'seq-item-ind';\n        case '?':\n            return 'explicit-key-ind';\n        case ':':\n            return 'map-value-ind';\n        case '{':\n            return 'flow-map-start';\n        case '}':\n            return 'flow-map-end';\n        case '[':\n            return 'flow-seq-start';\n        case ']':\n            return 'flow-seq-end';\n        case ',':\n            return 'comma';\n    }\n    switch (source[0]) {\n        case ' ':\n        case '\\t':\n            return 'space';\n        case '#':\n            return 'comment';\n        case '%':\n            return 'directive-line';\n        case '*':\n            return 'alias';\n        case '&':\n            return 'anchor';\n        case '!':\n            return 'tag';\n        case \"'\":\n            return 'single-quoted-scalar';\n        case '\"':\n            return 'double-quoted-scalar';\n        case '|':\n        case '>':\n            return 'block-scalar-header';\n    }\n    return null;\n}\n\nexport { BOM, DOCUMENT, FLOW_END, SCALAR, isCollection, isScalar, prettyToken, tokenType };\n","import { BOM, DOCUMENT, FLOW_END, SCALAR } from './cst.js';\n\n/*\nSTART -> stream\n\nstream\n  directive -> line-end -> stream\n  indent + line-end -> stream\n  [else] -> line-start\n\nline-end\n  comment -> line-end\n  newline -> .\n  input-end -> END\n\nline-start\n  doc-start -> doc\n  doc-end -> stream\n  [else] -> indent -> block-start\n\nblock-start\n  seq-item-start -> block-start\n  explicit-key-start -> block-start\n  map-value-start -> block-start\n  [else] -> doc\n\ndoc\n  line-end -> line-start\n  spaces -> doc\n  anchor -> doc\n  tag -> doc\n  flow-start -> flow -> doc\n  flow-end -> error -> doc\n  seq-item-start -> error -> doc\n  explicit-key-start -> error -> doc\n  map-value-start -> doc\n  alias -> doc\n  quote-start -> quoted-scalar -> doc\n  block-scalar-header -> line-end -> block-scalar(min) -> line-start\n  [else] -> plain-scalar(false, min) -> doc\n\nflow\n  line-end -> flow\n  spaces -> flow\n  anchor -> flow\n  tag -> flow\n  flow-start -> flow -> flow\n  flow-end -> .\n  seq-item-start -> error -> flow\n  explicit-key-start -> flow\n  map-value-start -> flow\n  alias -> flow\n  quote-start -> quoted-scalar -> flow\n  comma -> flow\n  [else] -> plain-scalar(true, 0) -> flow\n\nquoted-scalar\n  quote-end -> .\n  [else] -> quoted-scalar\n\nblock-scalar(min)\n  newline + peek(indent < min) -> .\n  [else] -> block-scalar(min)\n\nplain-scalar(is-flow, min)\n  scalar-end(is-flow) -> .\n  peek(newline + (indent < min)) -> .\n  [else] -> plain-scalar(min)\n*/\nfunction isEmpty(ch) {\n    switch (ch) {\n        case undefined:\n        case ' ':\n        case '\\n':\n        case '\\r':\n        case '\\t':\n            return true;\n        default:\n            return false;\n    }\n}\nconst hexDigits = new Set('0123456789ABCDEFabcdef');\nconst tagChars = new Set(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()\");\nconst flowIndicatorChars = new Set(',[]{}');\nconst invalidAnchorChars = new Set(' ,[]{}\\n\\r\\t');\nconst isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);\n/**\n * Splits an input string into lexical tokens, i.e. smaller strings that are\n * easily identifiable by `tokens.tokenType()`.\n *\n * Lexing starts always in a \"stream\" context. Incomplete input may be buffered\n * until a complete token can be emitted.\n *\n * In addition to slices of the original input, the following control characters\n * may also be emitted:\n *\n * - `\\x02` (Start of Text): A document starts with the next token\n * - `\\x18` (Cancel): Unexpected end of flow-mode (indicates an error)\n * - `\\x1f` (Unit Separator): Next token is a scalar value\n * - `\\u{FEFF}` (Byte order mark): Emitted separately outside documents\n */\nclass Lexer {\n    constructor() {\n        /**\n         * Flag indicating whether the end of the current buffer marks the end of\n         * all input\n         */\n        this.atEnd = false;\n        /**\n         * Explicit indent set in block scalar header, as an offset from the current\n         * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not\n         * explicitly set.\n         */\n        this.blockScalarIndent = -1;\n        /**\n         * Block scalars that include a + (keep) chomping indicator in their header\n         * include trailing empty lines, which are otherwise excluded from the\n         * scalar's contents.\n         */\n        this.blockScalarKeep = false;\n        /** Current input */\n        this.buffer = '';\n        /**\n         * Flag noting whether the map value indicator : can immediately follow this\n         * node within a flow context.\n         */\n        this.flowKey = false;\n        /** Count of surrounding flow collection levels. */\n        this.flowLevel = 0;\n        /**\n         * Minimum level of indentation required for next lines to be parsed as a\n         * part of the current scalar value.\n         */\n        this.indentNext = 0;\n        /** Indentation level of the current line. */\n        this.indentValue = 0;\n        /** Position of the next \\n character. */\n        this.lineEndPos = null;\n        /** Stores the state of the lexer if reaching the end of incpomplete input */\n        this.next = null;\n        /** A pointer to `buffer`; the current position of the lexer. */\n        this.pos = 0;\n    }\n    /**\n     * Generate YAML tokens from the `source` string. If `incomplete`,\n     * a part of the last line may be left as a buffer for the next call.\n     *\n     * @returns A generator of lexical tokens\n     */\n    *lex(source, incomplete = false) {\n        if (source) {\n            if (typeof source !== 'string')\n                throw TypeError('source is not a string');\n            this.buffer = this.buffer ? this.buffer + source : source;\n            this.lineEndPos = null;\n        }\n        this.atEnd = !incomplete;\n        let next = this.next ?? 'stream';\n        while (next && (incomplete || this.hasChars(1)))\n            next = yield* this.parseNext(next);\n    }\n    atLineEnd() {\n        let i = this.pos;\n        let ch = this.buffer[i];\n        while (ch === ' ' || ch === '\\t')\n            ch = this.buffer[++i];\n        if (!ch || ch === '#' || ch === '\\n')\n            return true;\n        if (ch === '\\r')\n            return this.buffer[i + 1] === '\\n';\n        return false;\n    }\n    charAt(n) {\n        return this.buffer[this.pos + n];\n    }\n    continueScalar(offset) {\n        let ch = this.buffer[offset];\n        if (this.indentNext > 0) {\n            let indent = 0;\n            while (ch === ' ')\n                ch = this.buffer[++indent + offset];\n            if (ch === '\\r') {\n                const next = this.buffer[indent + offset + 1];\n                if (next === '\\n' || (!next && !this.atEnd))\n                    return offset + indent + 1;\n            }\n            return ch === '\\n' || indent >= this.indentNext || (!ch && !this.atEnd)\n                ? offset + indent\n                : -1;\n        }\n        if (ch === '-' || ch === '.') {\n            const dt = this.buffer.substr(offset, 3);\n            if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))\n                return -1;\n        }\n        return offset;\n    }\n    getLine() {\n        let end = this.lineEndPos;\n        if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {\n            end = this.buffer.indexOf('\\n', this.pos);\n            this.lineEndPos = end;\n        }\n        if (end === -1)\n            return this.atEnd ? this.buffer.substring(this.pos) : null;\n        if (this.buffer[end - 1] === '\\r')\n            end -= 1;\n        return this.buffer.substring(this.pos, end);\n    }\n    hasChars(n) {\n        return this.pos + n <= this.buffer.length;\n    }\n    setNext(state) {\n        this.buffer = this.buffer.substring(this.pos);\n        this.pos = 0;\n        this.lineEndPos = null;\n        this.next = state;\n        return null;\n    }\n    peek(n) {\n        return this.buffer.substr(this.pos, n);\n    }\n    *parseNext(next) {\n        switch (next) {\n            case 'stream':\n                return yield* this.parseStream();\n            case 'line-start':\n                return yield* this.parseLineStart();\n            case 'block-start':\n                return yield* this.parseBlockStart();\n            case 'doc':\n                return yield* this.parseDocument();\n            case 'flow':\n                return yield* this.parseFlowCollection();\n            case 'quoted-scalar':\n                return yield* this.parseQuotedScalar();\n            case 'block-scalar':\n                return yield* this.parseBlockScalar();\n            case 'plain-scalar':\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseStream() {\n        let line = this.getLine();\n        if (line === null)\n            return this.setNext('stream');\n        if (line[0] === BOM) {\n            yield* this.pushCount(1);\n            line = line.substring(1);\n        }\n        if (line[0] === '%') {\n            let dirEnd = line.length;\n            let cs = line.indexOf('#');\n            while (cs !== -1) {\n                const ch = line[cs - 1];\n                if (ch === ' ' || ch === '\\t') {\n                    dirEnd = cs - 1;\n                    break;\n                }\n                else {\n                    cs = line.indexOf('#', cs + 1);\n                }\n            }\n            while (true) {\n                const ch = line[dirEnd - 1];\n                if (ch === ' ' || ch === '\\t')\n                    dirEnd -= 1;\n                else\n                    break;\n            }\n            const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));\n            yield* this.pushCount(line.length - n); // possible comment\n            this.pushNewline();\n            return 'stream';\n        }\n        if (this.atLineEnd()) {\n            const sp = yield* this.pushSpaces(true);\n            yield* this.pushCount(line.length - sp);\n            yield* this.pushNewline();\n            return 'stream';\n        }\n        yield DOCUMENT;\n        return yield* this.parseLineStart();\n    }\n    *parseLineStart() {\n        const ch = this.charAt(0);\n        if (!ch && !this.atEnd)\n            return this.setNext('line-start');\n        if (ch === '-' || ch === '.') {\n            if (!this.atEnd && !this.hasChars(4))\n                return this.setNext('line-start');\n            const s = this.peek(3);\n            if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {\n                yield* this.pushCount(3);\n                this.indentValue = 0;\n                this.indentNext = 0;\n                return s === '---' ? 'doc' : 'stream';\n            }\n        }\n        this.indentValue = yield* this.pushSpaces(false);\n        if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))\n            this.indentNext = this.indentValue;\n        return yield* this.parseBlockStart();\n    }\n    *parseBlockStart() {\n        const [ch0, ch1] = this.peek(2);\n        if (!ch1 && !this.atEnd)\n            return this.setNext('block-start');\n        if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {\n            const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));\n            this.indentNext = this.indentValue + 1;\n            this.indentValue += n;\n            return 'block-start';\n        }\n        return 'doc';\n    }\n    *parseDocument() {\n        yield* this.pushSpaces(true);\n        const line = this.getLine();\n        if (line === null)\n            return this.setNext('doc');\n        let n = yield* this.pushIndicators();\n        switch (line[n]) {\n            case '#':\n                yield* this.pushCount(line.length - n);\n            // fallthrough\n            case undefined:\n                yield* this.pushNewline();\n                return yield* this.parseLineStart();\n            case '{':\n            case '[':\n                yield* this.pushCount(1);\n                this.flowKey = false;\n                this.flowLevel = 1;\n                return 'flow';\n            case '}':\n            case ']':\n                // this is an error\n                yield* this.pushCount(1);\n                return 'doc';\n            case '*':\n                yield* this.pushUntil(isNotAnchorChar);\n                return 'doc';\n            case '\"':\n            case \"'\":\n                return yield* this.parseQuotedScalar();\n            case '|':\n            case '>':\n                n += yield* this.parseBlockScalarHeader();\n                n += yield* this.pushSpaces(true);\n                yield* this.pushCount(line.length - n);\n                yield* this.pushNewline();\n                return yield* this.parseBlockScalar();\n            default:\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseFlowCollection() {\n        let nl, sp;\n        let indent = -1;\n        do {\n            nl = yield* this.pushNewline();\n            if (nl > 0) {\n                sp = yield* this.pushSpaces(false);\n                this.indentValue = indent = sp;\n            }\n            else {\n                sp = 0;\n            }\n            sp += yield* this.pushSpaces(true);\n        } while (nl + sp > 0);\n        const line = this.getLine();\n        if (line === null)\n            return this.setNext('flow');\n        if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||\n            (indent === 0 &&\n                (line.startsWith('---') || line.startsWith('...')) &&\n                isEmpty(line[3]))) {\n            // Allowing for the terminal ] or } at the same (rather than greater)\n            // indent level as the initial [ or { is technically invalid, but\n            // failing here would be surprising to users.\n            const atFlowEndMarker = indent === this.indentNext - 1 &&\n                this.flowLevel === 1 &&\n                (line[0] === ']' || line[0] === '}');\n            if (!atFlowEndMarker) {\n                // this is an error\n                this.flowLevel = 0;\n                yield FLOW_END;\n                return yield* this.parseLineStart();\n            }\n        }\n        let n = 0;\n        while (line[n] === ',') {\n            n += yield* this.pushCount(1);\n            n += yield* this.pushSpaces(true);\n            this.flowKey = false;\n        }\n        n += yield* this.pushIndicators();\n        switch (line[n]) {\n            case undefined:\n                return 'flow';\n            case '#':\n                yield* this.pushCount(line.length - n);\n                return 'flow';\n            case '{':\n            case '[':\n                yield* this.pushCount(1);\n                this.flowKey = false;\n                this.flowLevel += 1;\n                return 'flow';\n            case '}':\n            case ']':\n                yield* this.pushCount(1);\n                this.flowKey = true;\n                this.flowLevel -= 1;\n                return this.flowLevel ? 'flow' : 'doc';\n            case '*':\n                yield* this.pushUntil(isNotAnchorChar);\n                return 'flow';\n            case '\"':\n            case \"'\":\n                this.flowKey = true;\n                return yield* this.parseQuotedScalar();\n            case ':': {\n                const next = this.charAt(1);\n                if (this.flowKey || isEmpty(next) || next === ',') {\n                    this.flowKey = false;\n                    yield* this.pushCount(1);\n                    yield* this.pushSpaces(true);\n                    return 'flow';\n                }\n            }\n            // fallthrough\n            default:\n                this.flowKey = false;\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseQuotedScalar() {\n        const quote = this.charAt(0);\n        let end = this.buffer.indexOf(quote, this.pos + 1);\n        if (quote === \"'\") {\n            while (end !== -1 && this.buffer[end + 1] === \"'\")\n                end = this.buffer.indexOf(\"'\", end + 2);\n        }\n        else {\n            // double-quote\n            while (end !== -1) {\n                let n = 0;\n                while (this.buffer[end - 1 - n] === '\\\\')\n                    n += 1;\n                if (n % 2 === 0)\n                    break;\n                end = this.buffer.indexOf('\"', end + 1);\n            }\n        }\n        // Only looking for newlines within the quotes\n        const qb = this.buffer.substring(0, end);\n        let nl = qb.indexOf('\\n', this.pos);\n        if (nl !== -1) {\n            while (nl !== -1) {\n                const cs = this.continueScalar(nl + 1);\n                if (cs === -1)\n                    break;\n                nl = qb.indexOf('\\n', cs);\n            }\n            if (nl !== -1) {\n                // this is an error caused by an unexpected unindent\n                end = nl - (qb[nl - 1] === '\\r' ? 2 : 1);\n            }\n        }\n        if (end === -1) {\n            if (!this.atEnd)\n                return this.setNext('quoted-scalar');\n            end = this.buffer.length;\n        }\n        yield* this.pushToIndex(end + 1, false);\n        return this.flowLevel ? 'flow' : 'doc';\n    }\n    *parseBlockScalarHeader() {\n        this.blockScalarIndent = -1;\n        this.blockScalarKeep = false;\n        let i = this.pos;\n        while (true) {\n            const ch = this.buffer[++i];\n            if (ch === '+')\n                this.blockScalarKeep = true;\n            else if (ch > '0' && ch <= '9')\n                this.blockScalarIndent = Number(ch) - 1;\n            else if (ch !== '-')\n                break;\n        }\n        return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');\n    }\n    *parseBlockScalar() {\n        let nl = this.pos - 1; // may be -1 if this.pos === 0\n        let indent = 0;\n        let ch;\n        loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {\n            switch (ch) {\n                case ' ':\n                    indent += 1;\n                    break;\n                case '\\n':\n                    nl = i;\n                    indent = 0;\n                    break;\n                case '\\r': {\n                    const next = this.buffer[i + 1];\n                    if (!next && !this.atEnd)\n                        return this.setNext('block-scalar');\n                    if (next === '\\n')\n                        break;\n                } // fallthrough\n                default:\n                    break loop;\n            }\n        }\n        if (!ch && !this.atEnd)\n            return this.setNext('block-scalar');\n        if (indent >= this.indentNext) {\n            if (this.blockScalarIndent === -1)\n                this.indentNext = indent;\n            else {\n                this.indentNext =\n                    this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);\n            }\n            do {\n                const cs = this.continueScalar(nl + 1);\n                if (cs === -1)\n                    break;\n                nl = this.buffer.indexOf('\\n', cs);\n            } while (nl !== -1);\n            if (nl === -1) {\n                if (!this.atEnd)\n                    return this.setNext('block-scalar');\n                nl = this.buffer.length;\n            }\n        }\n        // Trailing insufficiently indented tabs are invalid.\n        // To catch that during parsing, we include them in the block scalar value.\n        let i = nl + 1;\n        ch = this.buffer[i];\n        while (ch === ' ')\n            ch = this.buffer[++i];\n        if (ch === '\\t') {\n            while (ch === '\\t' || ch === ' ' || ch === '\\r' || ch === '\\n')\n                ch = this.buffer[++i];\n            nl = i - 1;\n        }\n        else if (!this.blockScalarKeep) {\n            do {\n                let i = nl - 1;\n                let ch = this.buffer[i];\n                if (ch === '\\r')\n                    ch = this.buffer[--i];\n                const lastChar = i; // Drop the line if last char not more indented\n                while (ch === ' ')\n                    ch = this.buffer[--i];\n                if (ch === '\\n' && i >= this.pos && i + 1 + indent > lastChar)\n                    nl = i;\n                else\n                    break;\n            } while (true);\n        }\n        yield SCALAR;\n        yield* this.pushToIndex(nl + 1, true);\n        return yield* this.parseLineStart();\n    }\n    *parsePlainScalar() {\n        const inFlow = this.flowLevel > 0;\n        let end = this.pos - 1;\n        let i = this.pos - 1;\n        let ch;\n        while ((ch = this.buffer[++i])) {\n            if (ch === ':') {\n                const next = this.buffer[i + 1];\n                if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))\n                    break;\n                end = i;\n            }\n            else if (isEmpty(ch)) {\n                let next = this.buffer[i + 1];\n                if (ch === '\\r') {\n                    if (next === '\\n') {\n                        i += 1;\n                        ch = '\\n';\n                        next = this.buffer[i + 1];\n                    }\n                    else\n                        end = i;\n                }\n                if (next === '#' || (inFlow && flowIndicatorChars.has(next)))\n                    break;\n                if (ch === '\\n') {\n                    const cs = this.continueScalar(i + 1);\n                    if (cs === -1)\n                        break;\n                    i = Math.max(i, cs - 2); // to advance, but still account for ' #'\n                }\n            }\n            else {\n                if (inFlow && flowIndicatorChars.has(ch))\n                    break;\n                end = i;\n            }\n        }\n        if (!ch && !this.atEnd)\n            return this.setNext('plain-scalar');\n        yield SCALAR;\n        yield* this.pushToIndex(end + 1, true);\n        return inFlow ? 'flow' : 'doc';\n    }\n    *pushCount(n) {\n        if (n > 0) {\n            yield this.buffer.substr(this.pos, n);\n            this.pos += n;\n            return n;\n        }\n        return 0;\n    }\n    *pushToIndex(i, allowEmpty) {\n        const s = this.buffer.slice(this.pos, i);\n        if (s) {\n            yield s;\n            this.pos += s.length;\n            return s.length;\n        }\n        else if (allowEmpty)\n            yield '';\n        return 0;\n    }\n    *pushIndicators() {\n        let n = 0;\n        loop: while (true) {\n            switch (this.charAt(0)) {\n                case '!':\n                    n += yield* this.pushTag();\n                    n += yield* this.pushSpaces(true);\n                    continue loop;\n                case '&':\n                    n += yield* this.pushUntil(isNotAnchorChar);\n                    n += yield* this.pushSpaces(true);\n                    continue loop;\n                case '-': // this is an error\n                case '?': // this is an error outside flow collections\n                case ':': {\n                    const inFlow = this.flowLevel > 0;\n                    const ch1 = this.charAt(1);\n                    if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {\n                        if (!inFlow)\n                            this.indentNext = this.indentValue + 1;\n                        else if (this.flowKey)\n                            this.flowKey = false;\n                        n += yield* this.pushCount(1);\n                        n += yield* this.pushSpaces(true);\n                        continue loop;\n                    }\n                }\n            }\n            break loop;\n        }\n        return n;\n    }\n    *pushTag() {\n        if (this.charAt(1) === '<') {\n            let i = this.pos + 2;\n            let ch = this.buffer[i];\n            while (!isEmpty(ch) && ch !== '>')\n                ch = this.buffer[++i];\n            return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);\n        }\n        else {\n            let i = this.pos + 1;\n            let ch = this.buffer[i];\n            while (ch) {\n                if (tagChars.has(ch))\n                    ch = this.buffer[++i];\n                else if (ch === '%' &&\n                    hexDigits.has(this.buffer[i + 1]) &&\n                    hexDigits.has(this.buffer[i + 2])) {\n                    ch = this.buffer[(i += 3)];\n                }\n                else\n                    break;\n            }\n            return yield* this.pushToIndex(i, false);\n        }\n    }\n    *pushNewline() {\n        const ch = this.buffer[this.pos];\n        if (ch === '\\n')\n            return yield* this.pushCount(1);\n        else if (ch === '\\r' && this.charAt(1) === '\\n')\n            return yield* this.pushCount(2);\n        else\n            return 0;\n    }\n    *pushSpaces(allowTabs) {\n        let i = this.pos - 1;\n        let ch;\n        do {\n            ch = this.buffer[++i];\n        } while (ch === ' ' || (allowTabs && ch === '\\t'));\n        const n = i - this.pos;\n        if (n > 0) {\n            yield this.buffer.substr(this.pos, n);\n            this.pos = i;\n        }\n        return n;\n    }\n    *pushUntil(test) {\n        let i = this.pos;\n        let ch = this.buffer[i];\n        while (!test(ch))\n            ch = this.buffer[++i];\n        return yield* this.pushToIndex(i, false);\n    }\n}\n\nexport { Lexer };\n","/**\n * Tracks newlines during parsing in order to provide an efficient API for\n * determining the one-indexed `{ line, col }` position for any offset\n * within the input.\n */\nclass LineCounter {\n    constructor() {\n        this.lineStarts = [];\n        /**\n         * Should be called in ascending order. Otherwise, call\n         * `lineCounter.lineStarts.sort()` before calling `linePos()`.\n         */\n        this.addNewLine = (offset) => this.lineStarts.push(offset);\n        /**\n         * Performs a binary search and returns the 1-indexed { line, col }\n         * position of `offset`. If `line === 0`, `addNewLine` has never been\n         * called or `offset` is before the first known newline.\n         */\n        this.linePos = (offset) => {\n            let low = 0;\n            let high = this.lineStarts.length;\n            while (low < high) {\n                const mid = (low + high) >> 1; // Math.floor((low + high) / 2)\n                if (this.lineStarts[mid] < offset)\n                    low = mid + 1;\n                else\n                    high = mid;\n            }\n            if (this.lineStarts[low] === offset)\n                return { line: low + 1, col: 1 };\n            if (low === 0)\n                return { line: 0, col: offset };\n            const start = this.lineStarts[low - 1];\n            return { line: low, col: offset - start + 1 };\n        };\n    }\n}\n\nexport { LineCounter };\n","import { tokenType } from './cst.js';\nimport { Lexer } from './lexer.js';\n\nfunction includesToken(list, type) {\n    for (let i = 0; i < list.length; ++i)\n        if (list[i].type === type)\n            return true;\n    return false;\n}\nfunction findNonEmptyIndex(list) {\n    for (let i = 0; i < list.length; ++i) {\n        switch (list[i].type) {\n            case 'space':\n            case 'comment':\n            case 'newline':\n                break;\n            default:\n                return i;\n        }\n    }\n    return -1;\n}\nfunction isFlowToken(token) {\n    switch (token?.type) {\n        case 'alias':\n        case 'scalar':\n        case 'single-quoted-scalar':\n        case 'double-quoted-scalar':\n        case 'flow-collection':\n            return true;\n        default:\n            return false;\n    }\n}\nfunction getPrevProps(parent) {\n    switch (parent.type) {\n        case 'document':\n            return parent.start;\n        case 'block-map': {\n            const it = parent.items[parent.items.length - 1];\n            return it.sep ?? it.start;\n        }\n        case 'block-seq':\n            return parent.items[parent.items.length - 1].start;\n        /* istanbul ignore next should not happen */\n        default:\n            return [];\n    }\n}\n/** Note: May modify input array */\nfunction getFirstKeyStartProps(prev) {\n    if (prev.length === 0)\n        return [];\n    let i = prev.length;\n    loop: while (--i >= 0) {\n        switch (prev[i].type) {\n            case 'doc-start':\n            case 'explicit-key-ind':\n            case 'map-value-ind':\n            case 'seq-item-ind':\n            case 'newline':\n                break loop;\n        }\n    }\n    while (prev[++i]?.type === 'space') {\n        /* loop */\n    }\n    return prev.splice(i, prev.length);\n}\nfunction arrayPushArray(target, source) {\n    // May exhaust call stack with large `source` array\n    if (source.length < 1e5)\n        Array.prototype.push.apply(target, source);\n    else\n        for (let i = 0; i < source.length; ++i)\n            target.push(source[i]);\n}\nfunction fixFlowSeqItems(fc) {\n    if (fc.start.type === 'flow-seq-start') {\n        for (const it of fc.items) {\n            if (it.sep &&\n                !it.value &&\n                !includesToken(it.start, 'explicit-key-ind') &&\n                !includesToken(it.sep, 'map-value-ind')) {\n                if (it.key)\n                    it.value = it.key;\n                delete it.key;\n                if (isFlowToken(it.value)) {\n                    if (it.value.end)\n                        arrayPushArray(it.value.end, it.sep);\n                    else\n                        it.value.end = it.sep;\n                }\n                else\n                    arrayPushArray(it.start, it.sep);\n                delete it.sep;\n            }\n        }\n    }\n}\n/**\n * A YAML concrete syntax tree (CST) parser\n *\n * ```ts\n * const src: string = ...\n * for (const token of new Parser().parse(src)) {\n *   // token: Token\n * }\n * ```\n *\n * To use the parser with a user-provided lexer:\n *\n * ```ts\n * function* parse(source: string, lexer: Lexer) {\n *   const parser = new Parser()\n *   for (const lexeme of lexer.lex(source))\n *     yield* parser.next(lexeme)\n *   yield* parser.end()\n * }\n *\n * const src: string = ...\n * const lexer = new Lexer()\n * for (const token of parse(src, lexer)) {\n *   // token: Token\n * }\n * ```\n */\nclass Parser {\n    /**\n     * @param onNewLine - If defined, called separately with the start position of\n     *   each new line (in `parse()`, including the start of input).\n     */\n    constructor(onNewLine) {\n        /** If true, space and sequence indicators count as indentation */\n        this.atNewLine = true;\n        /** If true, next token is a scalar value */\n        this.atScalar = false;\n        /** Current indentation level */\n        this.indent = 0;\n        /** Current offset since the start of parsing */\n        this.offset = 0;\n        /** On the same line with a block map key */\n        this.onKeyLine = false;\n        /** Top indicates the node that's currently being built */\n        this.stack = [];\n        /** The source of the current token, set in parse() */\n        this.source = '';\n        /** The type of the current token, set in parse() */\n        this.type = '';\n        // Must be defined after `next()`\n        this.lexer = new Lexer();\n        this.onNewLine = onNewLine;\n    }\n    /**\n     * Parse `source` as a YAML stream.\n     * If `incomplete`, a part of the last line may be left as a buffer for the next call.\n     *\n     * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.\n     *\n     * @returns A generator of tokens representing each directive, document, and other structure.\n     */\n    *parse(source, incomplete = false) {\n        if (this.onNewLine && this.offset === 0)\n            this.onNewLine(0);\n        for (const lexeme of this.lexer.lex(source, incomplete))\n            yield* this.next(lexeme);\n        if (!incomplete)\n            yield* this.end();\n    }\n    /**\n     * Advance the parser by the `source` of one lexical token.\n     */\n    *next(source) {\n        this.source = source;\n        if (this.atScalar) {\n            this.atScalar = false;\n            yield* this.step();\n            this.offset += source.length;\n            return;\n        }\n        const type = tokenType(source);\n        if (!type) {\n            const message = `Not a YAML token: ${source}`;\n            yield* this.pop({ type: 'error', offset: this.offset, message, source });\n            this.offset += source.length;\n        }\n        else if (type === 'scalar') {\n            this.atNewLine = false;\n            this.atScalar = true;\n            this.type = 'scalar';\n        }\n        else {\n            this.type = type;\n            yield* this.step();\n            switch (type) {\n                case 'newline':\n                    this.atNewLine = true;\n                    this.indent = 0;\n                    if (this.onNewLine)\n                        this.onNewLine(this.offset + source.length);\n                    break;\n                case 'space':\n                    if (this.atNewLine && source[0] === ' ')\n                        this.indent += source.length;\n                    break;\n                case 'explicit-key-ind':\n                case 'map-value-ind':\n                case 'seq-item-ind':\n                    if (this.atNewLine)\n                        this.indent += source.length;\n                    break;\n                case 'doc-mode':\n                case 'flow-error-end':\n                    return;\n                default:\n                    this.atNewLine = false;\n            }\n            this.offset += source.length;\n        }\n    }\n    /** Call at end of input to push out any remaining constructions */\n    *end() {\n        while (this.stack.length > 0)\n            yield* this.pop();\n    }\n    get sourceToken() {\n        const st = {\n            type: this.type,\n            offset: this.offset,\n            indent: this.indent,\n            source: this.source\n        };\n        return st;\n    }\n    *step() {\n        const top = this.peek(1);\n        if (this.type === 'doc-end' && top?.type !== 'doc-end') {\n            while (this.stack.length > 0)\n                yield* this.pop();\n            this.stack.push({\n                type: 'doc-end',\n                offset: this.offset,\n                source: this.source\n            });\n            return;\n        }\n        if (!top)\n            return yield* this.stream();\n        switch (top.type) {\n            case 'document':\n                return yield* this.document(top);\n            case 'alias':\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return yield* this.scalar(top);\n            case 'block-scalar':\n                return yield* this.blockScalar(top);\n            case 'block-map':\n                return yield* this.blockMap(top);\n            case 'block-seq':\n                return yield* this.blockSequence(top);\n            case 'flow-collection':\n                return yield* this.flowCollection(top);\n            case 'doc-end':\n                return yield* this.documentEnd(top);\n        }\n        /* istanbul ignore next should not happen */\n        yield* this.pop();\n    }\n    peek(n) {\n        return this.stack[this.stack.length - n];\n    }\n    *pop(error) {\n        const token = error ?? this.stack.pop();\n        /* istanbul ignore if should not happen */\n        if (!token) {\n            const message = 'Tried to pop an empty stack';\n            yield { type: 'error', offset: this.offset, source: '', message };\n        }\n        else if (this.stack.length === 0) {\n            yield token;\n        }\n        else {\n            const top = this.peek(1);\n            if (token.type === 'block-scalar') {\n                // Block scalars use their parent rather than header indent\n                token.indent = 'indent' in top ? top.indent : 0;\n            }\n            else if (token.type === 'flow-collection' && top.type === 'document') {\n                // Ignore all indent for top-level flow collections\n                token.indent = 0;\n            }\n            if (token.type === 'flow-collection')\n                fixFlowSeqItems(token);\n            switch (top.type) {\n                case 'document':\n                    top.value = token;\n                    break;\n                case 'block-scalar':\n                    top.props.push(token); // error\n                    break;\n                case 'block-map': {\n                    const it = top.items[top.items.length - 1];\n                    if (it.value) {\n                        top.items.push({ start: [], key: token, sep: [] });\n                        this.onKeyLine = true;\n                        return;\n                    }\n                    else if (it.sep) {\n                        it.value = token;\n                    }\n                    else {\n                        Object.assign(it, { key: token, sep: [] });\n                        this.onKeyLine = !it.explicitKey;\n                        return;\n                    }\n                    break;\n                }\n                case 'block-seq': {\n                    const it = top.items[top.items.length - 1];\n                    if (it.value)\n                        top.items.push({ start: [], value: token });\n                    else\n                        it.value = token;\n                    break;\n                }\n                case 'flow-collection': {\n                    const it = top.items[top.items.length - 1];\n                    if (!it || it.value)\n                        top.items.push({ start: [], key: token, sep: [] });\n                    else if (it.sep)\n                        it.value = token;\n                    else\n                        Object.assign(it, { key: token, sep: [] });\n                    return;\n                }\n                /* istanbul ignore next should not happen */\n                default:\n                    yield* this.pop();\n                    yield* this.pop(token);\n            }\n            if ((top.type === 'document' ||\n                top.type === 'block-map' ||\n                top.type === 'block-seq') &&\n                (token.type === 'block-map' || token.type === 'block-seq')) {\n                const last = token.items[token.items.length - 1];\n                if (last &&\n                    !last.sep &&\n                    !last.value &&\n                    last.start.length > 0 &&\n                    findNonEmptyIndex(last.start) === -1 &&\n                    (token.indent === 0 ||\n                        last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {\n                    if (top.type === 'document')\n                        top.end = last.start;\n                    else\n                        top.items.push({ start: last.start });\n                    token.items.splice(-1, 1);\n                }\n            }\n        }\n    }\n    *stream() {\n        switch (this.type) {\n            case 'directive-line':\n                yield { type: 'directive', offset: this.offset, source: this.source };\n                return;\n            case 'byte-order-mark':\n            case 'space':\n            case 'comment':\n            case 'newline':\n                yield this.sourceToken;\n                return;\n            case 'doc-mode':\n            case 'doc-start': {\n                const doc = {\n                    type: 'document',\n                    offset: this.offset,\n                    start: []\n                };\n                if (this.type === 'doc-start')\n                    doc.start.push(this.sourceToken);\n                this.stack.push(doc);\n                return;\n            }\n        }\n        yield {\n            type: 'error',\n            offset: this.offset,\n            message: `Unexpected ${this.type} token in YAML stream`,\n            source: this.source\n        };\n    }\n    *document(doc) {\n        if (doc.value)\n            return yield* this.lineEnd(doc);\n        switch (this.type) {\n            case 'doc-start': {\n                if (findNonEmptyIndex(doc.start) !== -1) {\n                    yield* this.pop();\n                    yield* this.step();\n                }\n                else\n                    doc.start.push(this.sourceToken);\n                return;\n            }\n            case 'anchor':\n            case 'tag':\n            case 'space':\n            case 'comment':\n            case 'newline':\n                doc.start.push(this.sourceToken);\n                return;\n        }\n        const bv = this.startBlockValue(doc);\n        if (bv)\n            this.stack.push(bv);\n        else {\n            yield {\n                type: 'error',\n                offset: this.offset,\n                message: `Unexpected ${this.type} token in YAML document`,\n                source: this.source\n            };\n        }\n    }\n    *scalar(scalar) {\n        if (this.type === 'map-value-ind') {\n            const prev = getPrevProps(this.peek(2));\n            const start = getFirstKeyStartProps(prev);\n            let sep;\n            if (scalar.end) {\n                sep = scalar.end;\n                sep.push(this.sourceToken);\n                delete scalar.end;\n            }\n            else\n                sep = [this.sourceToken];\n            const map = {\n                type: 'block-map',\n                offset: scalar.offset,\n                indent: scalar.indent,\n                items: [{ start, key: scalar, sep }]\n            };\n            this.onKeyLine = true;\n            this.stack[this.stack.length - 1] = map;\n        }\n        else\n            yield* this.lineEnd(scalar);\n    }\n    *blockScalar(scalar) {\n        switch (this.type) {\n            case 'space':\n            case 'comment':\n            case 'newline':\n                scalar.props.push(this.sourceToken);\n                return;\n            case 'scalar':\n                scalar.source = this.source;\n                // block-scalar source includes trailing newline\n                this.atNewLine = true;\n                this.indent = 0;\n                if (this.onNewLine) {\n                    let nl = this.source.indexOf('\\n') + 1;\n                    while (nl !== 0) {\n                        this.onNewLine(this.offset + nl);\n                        nl = this.source.indexOf('\\n', nl) + 1;\n                    }\n                }\n                yield* this.pop();\n                break;\n            /* istanbul ignore next should not happen */\n            default:\n                yield* this.pop();\n                yield* this.step();\n        }\n    }\n    *blockMap(map) {\n        const it = map.items[map.items.length - 1];\n        // it.sep is true-ish if pair already has key or : separator\n        switch (this.type) {\n            case 'newline':\n                this.onKeyLine = false;\n                if (it.value) {\n                    const end = 'end' in it.value ? it.value.end : undefined;\n                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n                    if (last?.type === 'comment')\n                        end?.push(this.sourceToken);\n                    else\n                        map.items.push({ start: [this.sourceToken] });\n                }\n                else if (it.sep) {\n                    it.sep.push(this.sourceToken);\n                }\n                else {\n                    it.start.push(this.sourceToken);\n                }\n                return;\n            case 'space':\n            case 'comment':\n                if (it.value) {\n                    map.items.push({ start: [this.sourceToken] });\n                }\n                else if (it.sep) {\n                    it.sep.push(this.sourceToken);\n                }\n                else {\n                    if (this.atIndentedComment(it.start, map.indent)) {\n                        const prev = map.items[map.items.length - 2];\n                        const end = prev?.value?.end;\n                        if (Array.isArray(end)) {\n                            arrayPushArray(end, it.start);\n                            end.push(this.sourceToken);\n                            map.items.pop();\n                            return;\n                        }\n                    }\n                    it.start.push(this.sourceToken);\n                }\n                return;\n        }\n        if (this.indent >= map.indent) {\n            const atMapIndent = !this.onKeyLine && this.indent === map.indent;\n            const atNextItem = atMapIndent &&\n                (it.sep || it.explicitKey) &&\n                this.type !== 'seq-item-ind';\n            // For empty nodes, assign newline-separated not indented empty tokens to following node\n            let start = [];\n            if (atNextItem && it.sep && !it.value) {\n                const nl = [];\n                for (let i = 0; i < it.sep.length; ++i) {\n                    const st = it.sep[i];\n                    switch (st.type) {\n                        case 'newline':\n                            nl.push(i);\n                            break;\n                        case 'space':\n                            break;\n                        case 'comment':\n                            if (st.indent > map.indent)\n                                nl.length = 0;\n                            break;\n                        default:\n                            nl.length = 0;\n                    }\n                }\n                if (nl.length >= 2)\n                    start = it.sep.splice(nl[1]);\n            }\n            switch (this.type) {\n                case 'anchor':\n                case 'tag':\n                    if (atNextItem || it.value) {\n                        start.push(this.sourceToken);\n                        map.items.push({ start });\n                        this.onKeyLine = true;\n                    }\n                    else if (it.sep) {\n                        it.sep.push(this.sourceToken);\n                    }\n                    else {\n                        it.start.push(this.sourceToken);\n                    }\n                    return;\n                case 'explicit-key-ind':\n                    if (!it.sep && !it.explicitKey) {\n                        it.start.push(this.sourceToken);\n                        it.explicitKey = true;\n                    }\n                    else if (atNextItem || it.value) {\n                        start.push(this.sourceToken);\n                        map.items.push({ start, explicitKey: true });\n                    }\n                    else {\n                        this.stack.push({\n                            type: 'block-map',\n                            offset: this.offset,\n                            indent: this.indent,\n                            items: [{ start: [this.sourceToken], explicitKey: true }]\n                        });\n                    }\n                    this.onKeyLine = true;\n                    return;\n                case 'map-value-ind':\n                    if (it.explicitKey) {\n                        if (!it.sep) {\n                            if (includesToken(it.start, 'newline')) {\n                                Object.assign(it, { key: null, sep: [this.sourceToken] });\n                            }\n                            else {\n                                const start = getFirstKeyStartProps(it.start);\n                                this.stack.push({\n                                    type: 'block-map',\n                                    offset: this.offset,\n                                    indent: this.indent,\n                                    items: [{ start, key: null, sep: [this.sourceToken] }]\n                                });\n                            }\n                        }\n                        else if (it.value) {\n                            map.items.push({ start: [], key: null, sep: [this.sourceToken] });\n                        }\n                        else if (includesToken(it.sep, 'map-value-ind')) {\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start, key: null, sep: [this.sourceToken] }]\n                            });\n                        }\n                        else if (isFlowToken(it.key) &&\n                            !includesToken(it.sep, 'newline')) {\n                            const start = getFirstKeyStartProps(it.start);\n                            const key = it.key;\n                            const sep = it.sep;\n                            sep.push(this.sourceToken);\n                            // @ts-expect-error type guard is wrong here\n                            delete it.key;\n                            // @ts-expect-error type guard is wrong here\n                            delete it.sep;\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start, key, sep }]\n                            });\n                        }\n                        else if (start.length > 0) {\n                            // Not actually at next item\n                            it.sep = it.sep.concat(start, this.sourceToken);\n                        }\n                        else {\n                            it.sep.push(this.sourceToken);\n                        }\n                    }\n                    else {\n                        if (!it.sep) {\n                            Object.assign(it, { key: null, sep: [this.sourceToken] });\n                        }\n                        else if (it.value || atNextItem) {\n                            map.items.push({ start, key: null, sep: [this.sourceToken] });\n                        }\n                        else if (includesToken(it.sep, 'map-value-ind')) {\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start: [], key: null, sep: [this.sourceToken] }]\n                            });\n                        }\n                        else {\n                            it.sep.push(this.sourceToken);\n                        }\n                    }\n                    this.onKeyLine = true;\n                    return;\n                case 'alias':\n                case 'scalar':\n                case 'single-quoted-scalar':\n                case 'double-quoted-scalar': {\n                    const fs = this.flowScalar(this.type);\n                    if (atNextItem || it.value) {\n                        map.items.push({ start, key: fs, sep: [] });\n                        this.onKeyLine = true;\n                    }\n                    else if (it.sep) {\n                        this.stack.push(fs);\n                    }\n                    else {\n                        Object.assign(it, { key: fs, sep: [] });\n                        this.onKeyLine = true;\n                    }\n                    return;\n                }\n                default: {\n                    const bv = this.startBlockValue(map);\n                    if (bv) {\n                        if (bv.type === 'block-seq') {\n                            if (!it.explicitKey &&\n                                it.sep &&\n                                !includesToken(it.sep, 'newline')) {\n                                yield* this.pop({\n                                    type: 'error',\n                                    offset: this.offset,\n                                    message: 'Unexpected block-seq-ind on same line with key',\n                                    source: this.source\n                                });\n                                return;\n                            }\n                        }\n                        else if (atMapIndent) {\n                            map.items.push({ start });\n                        }\n                        this.stack.push(bv);\n                        return;\n                    }\n                }\n            }\n        }\n        yield* this.pop();\n        yield* this.step();\n    }\n    *blockSequence(seq) {\n        const it = seq.items[seq.items.length - 1];\n        switch (this.type) {\n            case 'newline':\n                if (it.value) {\n                    const end = 'end' in it.value ? it.value.end : undefined;\n                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n                    if (last?.type === 'comment')\n                        end?.push(this.sourceToken);\n                    else\n                        seq.items.push({ start: [this.sourceToken] });\n                }\n                else\n                    it.start.push(this.sourceToken);\n                return;\n            case 'space':\n            case 'comment':\n                if (it.value)\n                    seq.items.push({ start: [this.sourceToken] });\n                else {\n                    if (this.atIndentedComment(it.start, seq.indent)) {\n                        const prev = seq.items[seq.items.length - 2];\n                        const end = prev?.value?.end;\n                        if (Array.isArray(end)) {\n                            arrayPushArray(end, it.start);\n                            end.push(this.sourceToken);\n                            seq.items.pop();\n                            return;\n                        }\n                    }\n                    it.start.push(this.sourceToken);\n                }\n                return;\n            case 'anchor':\n            case 'tag':\n                if (it.value || this.indent <= seq.indent)\n                    break;\n                it.start.push(this.sourceToken);\n                return;\n            case 'seq-item-ind':\n                if (this.indent !== seq.indent)\n                    break;\n                if (it.value || includesToken(it.start, 'seq-item-ind'))\n                    seq.items.push({ start: [this.sourceToken] });\n                else\n                    it.start.push(this.sourceToken);\n                return;\n        }\n        if (this.indent > seq.indent) {\n            const bv = this.startBlockValue(seq);\n            if (bv) {\n                this.stack.push(bv);\n                return;\n            }\n        }\n        yield* this.pop();\n        yield* this.step();\n    }\n    *flowCollection(fc) {\n        const it = fc.items[fc.items.length - 1];\n        if (this.type === 'flow-error-end') {\n            let top;\n            do {\n                yield* this.pop();\n                top = this.peek(1);\n            } while (top?.type === 'flow-collection');\n        }\n        else if (fc.end.length === 0) {\n            switch (this.type) {\n                case 'comma':\n                case 'explicit-key-ind':\n                    if (!it || it.sep)\n                        fc.items.push({ start: [this.sourceToken] });\n                    else\n                        it.start.push(this.sourceToken);\n                    return;\n                case 'map-value-ind':\n                    if (!it || it.value)\n                        fc.items.push({ start: [], key: null, sep: [this.sourceToken] });\n                    else if (it.sep)\n                        it.sep.push(this.sourceToken);\n                    else\n                        Object.assign(it, { key: null, sep: [this.sourceToken] });\n                    return;\n                case 'space':\n                case 'comment':\n                case 'newline':\n                case 'anchor':\n                case 'tag':\n                    if (!it || it.value)\n                        fc.items.push({ start: [this.sourceToken] });\n                    else if (it.sep)\n                        it.sep.push(this.sourceToken);\n                    else\n                        it.start.push(this.sourceToken);\n                    return;\n                case 'alias':\n                case 'scalar':\n                case 'single-quoted-scalar':\n                case 'double-quoted-scalar': {\n                    const fs = this.flowScalar(this.type);\n                    if (!it || it.value)\n                        fc.items.push({ start: [], key: fs, sep: [] });\n                    else if (it.sep)\n                        this.stack.push(fs);\n                    else\n                        Object.assign(it, { key: fs, sep: [] });\n                    return;\n                }\n                case 'flow-map-end':\n                case 'flow-seq-end':\n                    fc.end.push(this.sourceToken);\n                    return;\n            }\n            const bv = this.startBlockValue(fc);\n            /* istanbul ignore else should not happen */\n            if (bv)\n                this.stack.push(bv);\n            else {\n                yield* this.pop();\n                yield* this.step();\n            }\n        }\n        else {\n            const parent = this.peek(2);\n            if (parent.type === 'block-map' &&\n                ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||\n                    (this.type === 'newline' &&\n                        !parent.items[parent.items.length - 1].sep))) {\n                yield* this.pop();\n                yield* this.step();\n            }\n            else if (this.type === 'map-value-ind' &&\n                parent.type !== 'flow-collection') {\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                fixFlowSeqItems(fc);\n                const sep = fc.end.splice(1, fc.end.length);\n                sep.push(this.sourceToken);\n                const map = {\n                    type: 'block-map',\n                    offset: fc.offset,\n                    indent: fc.indent,\n                    items: [{ start, key: fc, sep }]\n                };\n                this.onKeyLine = true;\n                this.stack[this.stack.length - 1] = map;\n            }\n            else {\n                yield* this.lineEnd(fc);\n            }\n        }\n    }\n    flowScalar(type) {\n        if (this.onNewLine) {\n            let nl = this.source.indexOf('\\n') + 1;\n            while (nl !== 0) {\n                this.onNewLine(this.offset + nl);\n                nl = this.source.indexOf('\\n', nl) + 1;\n            }\n        }\n        return {\n            type,\n            offset: this.offset,\n            indent: this.indent,\n            source: this.source\n        };\n    }\n    startBlockValue(parent) {\n        switch (this.type) {\n            case 'alias':\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return this.flowScalar(this.type);\n            case 'block-scalar-header':\n                return {\n                    type: 'block-scalar',\n                    offset: this.offset,\n                    indent: this.indent,\n                    props: [this.sourceToken],\n                    source: ''\n                };\n            case 'flow-map-start':\n            case 'flow-seq-start':\n                return {\n                    type: 'flow-collection',\n                    offset: this.offset,\n                    indent: this.indent,\n                    start: this.sourceToken,\n                    items: [],\n                    end: []\n                };\n            case 'seq-item-ind':\n                return {\n                    type: 'block-seq',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start: [this.sourceToken] }]\n                };\n            case 'explicit-key-ind': {\n                this.onKeyLine = true;\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                start.push(this.sourceToken);\n                return {\n                    type: 'block-map',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start, explicitKey: true }]\n                };\n            }\n            case 'map-value-ind': {\n                this.onKeyLine = true;\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                return {\n                    type: 'block-map',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start, key: null, sep: [this.sourceToken] }]\n                };\n            }\n        }\n        return null;\n    }\n    atIndentedComment(start, indent) {\n        if (this.type !== 'comment')\n            return false;\n        if (this.indent <= indent)\n            return false;\n        return start.every(st => st.type === 'newline' || st.type === 'space');\n    }\n    *documentEnd(docEnd) {\n        if (this.type !== 'doc-mode') {\n            if (docEnd.end)\n                docEnd.end.push(this.sourceToken);\n            else\n                docEnd.end = [this.sourceToken];\n            if (this.type === 'newline')\n                yield* this.pop();\n        }\n    }\n    *lineEnd(token) {\n        switch (this.type) {\n            case 'comma':\n            case 'doc-start':\n            case 'doc-end':\n            case 'flow-seq-end':\n            case 'flow-map-end':\n            case 'map-value-ind':\n                yield* this.pop();\n                yield* this.step();\n                break;\n            case 'newline':\n                this.onKeyLine = false;\n            // fallthrough\n            case 'space':\n            case 'comment':\n            default:\n                // all other values are errors\n                if (token.end)\n                    token.end.push(this.sourceToken);\n                else\n                    token.end = [this.sourceToken];\n                if (this.type === 'newline')\n                    yield* this.pop();\n        }\n    }\n}\n\nexport { Parser };\n","import { Composer } from './compose/composer.js';\nimport { Document } from './doc/Document.js';\nimport { prettifyError, YAMLParseError } from './errors.js';\nimport { warn } from './log.js';\nimport { isDocument } from './nodes/identity.js';\nimport { LineCounter } from './parse/line-counter.js';\nimport { Parser } from './parse/parser.js';\n\nfunction parseOptions(options) {\n    const prettyErrors = options.prettyErrors !== false;\n    const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null;\n    return { lineCounter, prettyErrors };\n}\n/**\n * Parse the input as a stream of YAML documents.\n *\n * Documents should be separated from each other by `...` or `---` marker lines.\n *\n * @returns If an empty `docs` array is returned, it will be of type\n *   EmptyStream and contain additional stream information. In\n *   TypeScript, you should use `'empty' in docs` as a type guard for it.\n */\nfunction parseAllDocuments(source, options = {}) {\n    const { lineCounter, prettyErrors } = parseOptions(options);\n    const parser = new Parser(lineCounter?.addNewLine);\n    const composer = new Composer(options);\n    const docs = Array.from(composer.compose(parser.parse(source)));\n    if (prettyErrors && lineCounter)\n        for (const doc of docs) {\n            doc.errors.forEach(prettifyError(source, lineCounter));\n            doc.warnings.forEach(prettifyError(source, lineCounter));\n        }\n    if (docs.length > 0)\n        return docs;\n    return Object.assign([], { empty: true }, composer.streamInfo());\n}\n/** Parse an input string into a single YAML.Document */\nfunction parseDocument(source, options = {}) {\n    const { lineCounter, prettyErrors } = parseOptions(options);\n    const parser = new Parser(lineCounter?.addNewLine);\n    const composer = new Composer(options);\n    // `doc` is always set by compose.end(true) at the very latest\n    let doc = null;\n    for (const _doc of composer.compose(parser.parse(source), true, source.length)) {\n        if (!doc)\n            doc = _doc;\n        else if (doc.options.logLevel !== 'silent') {\n            doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));\n            break;\n        }\n    }\n    if (prettyErrors && lineCounter) {\n        doc.errors.forEach(prettifyError(source, lineCounter));\n        doc.warnings.forEach(prettifyError(source, lineCounter));\n    }\n    return doc;\n}\nfunction parse(src, reviver, options) {\n    let _reviver = undefined;\n    if (typeof reviver === 'function') {\n        _reviver = reviver;\n    }\n    else if (options === undefined && reviver && typeof reviver === 'object') {\n        options = reviver;\n    }\n    const doc = parseDocument(src, options);\n    if (!doc)\n        return null;\n    doc.warnings.forEach(warning => warn(doc.options.logLevel, warning));\n    if (doc.errors.length > 0) {\n        if (doc.options.logLevel !== 'silent')\n            throw doc.errors[0];\n        else\n            doc.errors = [];\n    }\n    return doc.toJS(Object.assign({ reviver: _reviver }, options));\n}\nfunction stringify(value, replacer, options) {\n    let _replacer = null;\n    if (typeof replacer === 'function' || Array.isArray(replacer)) {\n        _replacer = replacer;\n    }\n    else if (options === undefined && replacer) {\n        options = replacer;\n    }\n    if (typeof options === 'string')\n        options = options.length;\n    if (typeof options === 'number') {\n        const indent = Math.round(options);\n        options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };\n    }\n    if (value === undefined) {\n        const { keepUndefined } = options ?? replacer ?? {};\n        if (!keepUndefined)\n            return undefined;\n    }\n    if (isDocument(value) && !_replacer)\n        return value.toString(options);\n    return new Document(value, _replacer, options).toString(options);\n}\n\nexport { parse, parseAllDocuments, parseDocument, stringify };\n","/**\n * @import { FileState } from '$lib/types/private';\n */\n\n/**\n * What is remembered about each file when it’s read, keyed by file path, so the file is saved back\n * the way it was written: the front matter format detected in it, the source text of the values the\n * parsed content can’t tell apart from others, and the comments at the top of it. See\n * {@link FileState}.\n * @type {Map<string, FileState>}\n */\nexport const fileStates = new Map();\n\n/**\n * Set what is remembered about the given file, replacing what was. A property set to `undefined` is\n * left out, and the file is forgotten once nothing is remembered about it.\n * @param {string} path File path.\n * @param {FileState} state What is remembered.\n */\nexport const setFileState = (path, state) => {\n  const props = Object.entries(state).filter(([, value]) => value !== undefined);\n\n  if (props.length) {\n    fileStates.set(path, Object.fromEntries(props));\n  } else {\n    fileStates.delete(path);\n  }\n};\n\n/**\n * Update what is remembered about the given file. A property set to `undefined` is forgotten, and\n * so is the file once nothing is remembered about it.\n * @param {string} path File path.\n * @param {FileState} props Properties to update.\n */\nexport const updateFileState = (path, props) => {\n  setFileState(path, { ...fileStates.get(path), ...props });\n};\n\n/**\n * Get what is remembered about a file before a save, and let the file after the save, which may\n * have been renamed, take it over, so it’s saved the same way next time as well. A new file doesn’t\n * take over what was remembered about a file deleted from the same path.\n * @param {object} args Arguments.\n * @param {string} [args.previousPath] Path of the file before the save, if it exists.\n * @param {string} args.path Path of the file after the save.\n * @returns {FileState} What is remembered. Empty if nothing is.\n */\nexport const takeOverFileState = ({ previousPath, path }) => {\n  const state = previousPath ? fileStates.get(previousPath) : undefined;\n\n  if (state) {\n    fileStates.set(path, state);\n  } else {\n    fileStates.delete(path);\n  }\n\n  return state ?? {};\n};\n","import { isObject } from '@sveltia/utils/object';\nimport { isMap, isScalar, isSeq } from 'yaml';\n\nimport { updateFileState } from '$lib/services/contents/file/state';\nimport { isPlainObject } from '$lib/services/utils/object';\n\n/**\n * @import { Document, ScalarTag } from 'yaml';\n * @import { ValueSource, ValueSourceMap } from '$lib/types/private';\n */\n\n/**\n * Regular expression testing whether a document may hold a float that is a whole number: a number\n * with a fractional part of zeros or a number with an exponent. Testing first saves looking for one\n * in a document that has none.\n */\nconst WHOLE_NUMBER_FLOAT_REGEX = /(?:^|[^\\d])\\.0|\\d\\.0*(?!\\d)|\\d[eE][-+]?\\d/;\n/**\n * Regular expression matching the source text of an integer in a YAML 1.2 document: a decimal,\n * octal or hexadecimal one.\n * @see https://yaml.org/spec/1.2.2/#1032-tag-resolution\n */\nconst YAML_INTEGER_REGEX = /^[-+]?(?:\\d+|0o[0-7]+|0x[\\da-fA-F]+)$/;\n/**\n * Regular expression matching the source text of a float in a YAML 1.2 document, other than an\n * infinity or a NaN.\n * @see https://yaml.org/spec/1.2.2/#1032-tag-resolution\n */\nconst YAML_FLOAT_REGEX = /^[-+]?(?:\\.\\d+|\\d+(?:\\.\\d*)?)(?:[eE][-+]?\\d+)?$/;\n/**\n * Regular expression matching the source text of a number in a JSON document.\n * @see https://www.json.org/json-en.html\n */\nconst JSON_NUMBER_REGEX = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][-+]?\\d+)?$/;\n\n/**\n * Regular expression matching the source text of a decimal integer in a JSON document.\n */\nexport const JSON_INTEGER_REGEX = /^-?\\d+$/;\n\n/**\n * Check whether the given document may hold a float that is a whole number.\n * @param {string} str Document.\n * @returns {boolean} Result.\n */\nexport const mayHaveWholeNumberFloat = (str) => WHOLE_NUMBER_FLOAT_REGEX.test(str);\n\n/**\n * Check whether the given value is a `number` that is a whole number, which a formatter writes as\n * an integer.\n * @param {any} value Value.\n * @returns {value is number} Result.\n */\nconst isWholeNumber = (value) => typeof value === 'number' && Number.isInteger(value);\n\n/**\n * Get the text of the given whole number written as a float.\n * @param {number} value Whole number.\n * @returns {string} Text, e.g. `10.0`, or `1e+21` for a number written with an exponent anyway.\n */\nexport const getFloatText = (value) => {\n  const text = Object.is(value, -0) ? '-0' : String(value);\n\n  return /[.e]/.test(text) ? text : `${text}.0`;\n};\n\n/**\n * Remember the given source text of a value under the given key, or `null` if another source text\n * has been remembered for it, as the value’s source text then can’t be told.\n * @template K\n * @param {Map<K, string | null>} sources Source text keyed by value.\n * @param {K} key Key, e.g. the value as it’s read.\n * @param {string} source Source text.\n */\nexport const rememberUniqueSource = (sources, key, source) => {\n  const knownSource = sources.get(key);\n\n  sources.set(key, knownSource === undefined || knownSource === source ? source : null);\n};\n\n/**\n * Join a key path and a key. A dot or a backslash in the key is escaped with a backslash, so a key\n * containing a dot can be told from a nested key: `a\\.b` for `a.b`, and `a.b` for `b` in `a`.\n * @param {string} keyPath Key path of the parent, or an empty string for the document itself.\n * @param {string | number} key Property name or array index.\n * @returns {string} Key path.\n */\nexport const joinKeyPath = (keyPath, key) => {\n  const escapedKey = String(key).replace(/[\\\\.]/g, '\\\\$&');\n\n  return keyPath ? `${keyPath}.${escapedKey}` : escapedKey;\n};\n\n/**\n * Collect the source text of the floats that are whole numbers in the given YAML document. A float\n * reached through an alias is left out, as are the keys, which the parsed content holds as strings.\n * @param {Document} doc Document parsed by the YAML library.\n * @returns {ValueSourceMap} Source map. Empty if the document has no such float.\n */\nexport const collectYAMLFloatSources = (doc) => {\n  /** @type {ValueSourceMap} */\n  const sourceMap = {};\n\n  /**\n   * Add the source text of the floats in the given node to the map.\n   * @param {unknown} node YAML node.\n   * @param {string} keyPath Key path of the node.\n   */\n  const collect = (node, keyPath) => {\n    if (isScalar(node)) {\n      const { value, source, tag } = node;\n\n      // A number is a float unless it’s written as an integer. The library reads a float with an\n      // integer’s text and the `!!float` tag, e.g. `!!float 10`, as a string, while a float tag is\n      // left out from the saved text, e.g. `!!float 10.0` is saved as `10.0`\n      if (\n        keyPath &&\n        isWholeNumber(value) &&\n        (!tag || tag === 'tag:yaml.org,2002:float') &&\n        typeof source === 'string' &&\n        !YAML_INTEGER_REGEX.test(source)\n      ) {\n        sourceMap[keyPath] = { value, source };\n      }\n    } else if (isMap(node)) {\n      node.items.forEach(({ key, value }) => {\n        if (isScalar(key)) {\n          collect(value, joinKeyPath(keyPath, String(key.value)));\n        }\n      });\n    } else if (isSeq(node)) {\n      node.items.forEach((item, index) => {\n        collect(item, joinKeyPath(keyPath, index));\n      });\n    }\n  };\n\n  collect(doc.contents, '');\n\n  return sourceMap;\n};\n\n/**\n * A value to be written as the given source text, which tells more than the value itself, e.g. a\n * float that is a whole number. A formatter that doesn’t know about it writes the value.\n */\nexport class SourcedValue {\n  /**\n   * Create a value.\n   * @param {number} value Value.\n   * @param {string} source Source text.\n   */\n  constructor(value, source) {\n    this.value = value;\n    this.source = source;\n  }\n\n  /**\n   * Get the value, which `JSON.stringify()` and the YAML library write without a replacer or a tag\n   * that knows about the source text.\n   * @returns {number} Value.\n   */\n  toJSON() {\n    return this.value;\n  }\n}\n\n/**\n * A `JSON.parse()` reviver that marks a float that is a whole number with a {@link SourcedValue},\n * held in the parsed content until its key path is known, so its source text can be collected with\n * {@link collectJSONFloatSources}. A browser that doesn’t give the reviver the source text reads\n * the number as usual.\n * @param {string} _key Property name.\n * @param {any} value Parsed value.\n * @param {{ source?: string }} [context] Context, which holds the source text of a primitive value.\n * @returns {any} Value.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter\n */\nexport const reviveWholeNumberFloat = (_key, value, context) => {\n  const source = context?.source;\n\n  return isWholeNumber(value) && typeof source === 'string' && !JSON_INTEGER_REGEX.test(source)\n    ? new SourcedValue(value, source)\n    : value;\n};\n\n/**\n * Replace every float marked by {@link reviveWholeNumberFloat} in the given parsed JSON document\n * with its number, and collect the source text of those floats.\n * @param {any} parsed Parsed document. Arrays and plain objects are updated in place.\n * @returns {{ value: any, sourceMap: ValueSourceMap }} Document without a marked float, and the\n * source map, which is empty if the document has no such float.\n */\nexport const collectJSONFloatSources = (parsed) => {\n  /** @type {ValueSourceMap} */\n  const sourceMap = {};\n\n  /**\n   * Replace the marked floats in the given value.\n   * @param {any} value Value.\n   * @param {string} keyPath Key path of the value.\n   * @returns {any} Value without a marked float.\n   */\n  const collect = (value, keyPath) => {\n    if (value instanceof SourcedValue) {\n      if (keyPath) {\n        sourceMap[keyPath] = { value: value.value, source: value.source };\n      }\n\n      return value.value;\n    }\n\n    if (Array.isArray(value) || isObject(value)) {\n      Object.entries(value).forEach(([key, val]) => {\n        /** @type {Record<string, any>} */ (value)[key] = collect(val, joinKeyPath(keyPath, key));\n      });\n    }\n\n    return value;\n  };\n\n  return { value: collect(parsed, ''), sourceMap };\n};\n\n/**\n * Remember the given source map of a file, if it’s not empty. A float that is a whole number, e.g.\n * `10.0`, `-3.0` or `1e3`, is read as the same `number` as an integer, e.g. `10`, which a formatter\n * would write. Hugo, written in Go, and other typed consumers then read an integer instead of a\n * float, so e.g. `eq .Params.price 10.0` turns false. A TOML native date or time is held as a\n * string, see `toml-sources.js`.\n *\n * The formatter writes such a value back as it was read, as long as it hasn’t been edited, so\n * saving an entry doesn’t change the type of a value. An edited value is saved like any other.\n * @param {string} path File path.\n * @param {ValueSourceMap} sourceMap Source map.\n */\nexport const rememberValueSources = (path, sourceMap) => {\n  if (Object.keys(sourceMap).length) {\n    updateFileState(path, { valueSources: sourceMap });\n  }\n};\n\n/**\n * Move the source map of a file storing all the entries of an entry collection along with its\n * items, which can have been added, removed or reordered.\n * @param {ValueSourceMap} sourceMap Source map of the file.\n * @param {(number | undefined)[]} positions Position of each item in the array before the changes.\n * `undefined` for a new item.\n * @returns {ValueSourceMap} Source map of the items at their new positions.\n */\nexport const moveArrayItemSources = (sourceMap, positions) => {\n  /** @type {Map<string, [string, ValueSourceMap[string]][]>} */\n  const itemSources = new Map();\n\n  Object.entries(sourceMap).forEach(([keyPath, valueSource]) => {\n    const [index, ...rest] = keyPath.split('.');\n\n    if (!itemSources.has(index)) {\n      itemSources.set(index, []);\n    }\n\n    /** @type {[string, ValueSourceMap[string]][]} */ (itemSources.get(index)).push([\n      rest.join('.'),\n      valueSource,\n    ]);\n  });\n\n  return Object.fromEntries(\n    positions.flatMap((from, index) =>\n      from === undefined\n        ? []\n        : (itemSources.get(String(from)) ?? []).map(([subPath, valueSource]) => [\n            subPath ? `${index}.${subPath}` : String(index),\n            valueSource,\n          ]),\n    ),\n  );\n};\n\n/**\n * Replace a number to be saved with a {@link SourcedValue}, which the JSON and YAML formatters\n * write as its source text, if it hasn’t changed since it was read from the file.\n * @param {any} value Value to be saved.\n * @param {ValueSource} valueSource Value read from the file at the same key path.\n * @returns {SourcedValue | undefined} Replacement, or `undefined` if the value has changed or is\n * not a number.\n */\nconst replaceUnchangedValue = (value, { value: parsedValue, source }) =>\n  typeof value === 'number' && value === parsedValue ? new SourcedValue(value, source) : undefined;\n\n/**\n * Copy the given content to be saved, replacing every value that hasn’t changed since it was read\n * from the file with one that the formatter writes as its source text.\n * @param {any} value Content, or a value in it.\n * @param {ValueSourceMap} sourceMap Source map of the file.\n * @param {(value: any, valueSource: ValueSource) => any} [replace] Function returning the\n * replacement of a value that has a source, or `undefined` if the value has changed. The default\n * one gives a {@link SourcedValue}.\n * @param {string} [keyPath] Key path of the value.\n * @returns {any} Copy of arrays and plain objects; any other value as is, or replaced.\n */\nexport const restoreValueSources = (\n  value,\n  sourceMap,\n  replace = replaceUnchangedValue,\n  keyPath = '',\n) => {\n  const valueSource = keyPath && Object.hasOwn(sourceMap, keyPath) ? sourceMap[keyPath] : undefined;\n  const replacement = valueSource ? replace(value, valueSource) : undefined;\n\n  if (replacement !== undefined) {\n    return replacement;\n  }\n\n  if (Array.isArray(value)) {\n    return value.map((val, index) =>\n      restoreValueSources(val, sourceMap, replace, joinKeyPath(keyPath, index)),\n    );\n  }\n\n  // Leave class instances, such as a `TomlDate`, as they are\n  if (isPlainObject(value)) {\n    return Object.fromEntries(\n      Object.entries(value).map(([key, val]) => [\n        key,\n        restoreValueSources(val, sourceMap, replace, joinKeyPath(keyPath, key)),\n      ]),\n    );\n  }\n\n  return value;\n};\n\n/**\n * Check whether the given source text is a float representing the given number in a document of\n * the given format, so it can be written as it is.\n * @param {string} source Source text.\n * @param {number} value Value.\n * @param {RegExp} regex Regular expression matching a number in the format. An underscore it lets\n * through, as in a TOML number, is ignored when reading the number.\n * @returns {boolean} Result.\n */\nexport const isFloatSource = (source, value, regex) =>\n  regex.test(source) && /[.eE]/.test(source) && Number(source.replaceAll('_', '')) === value;\n\n/**\n * Get the text to write a {@link SourcedValue} as in a JSON document.\n * @param {SourcedValue} sourcedValue Value.\n * @returns {string | undefined} Source text, or `undefined` if it’s not a JSON number representing\n * the value.\n */\nexport const getJSONSourceText = ({ value, source }) =>\n  isFloatSource(source, value, JSON_NUMBER_REGEX) ? source : undefined;\n\n/**\n * YAML tag writing a {@link SourcedValue} as its source text, or as the value if the text is not a\n * YAML float representing the value. It’s the default float tag, so the tag isn’t written.\n * @type {ScalarTag}\n */\nexport const sourcedValueYAMLTag = {\n  /**\n   * Check whether the tag applies to the given value.\n   * @param {unknown} value Value.\n   * @returns {boolean} Result.\n   */\n  identify: (value) => value instanceof SourcedValue,\n  default: true,\n  tag: 'tag:yaml.org,2002:float',\n  /**\n   * Read the text of a scalar node, which the tag isn’t used for, as it’s only given to the\n   * formatter.\n   * @param {string} str Text.\n   * @returns {number} Number.\n   */\n  resolve: (str) => Number(str),\n  /**\n   * Write the value of a scalar node.\n   * @param {{ value: unknown }} node Scalar node.\n   * @returns {string} Text.\n   */\n  stringify: ({ value: sourcedValue }) => {\n    const { value, source } = /** @type {SourcedValue} */ (sourcedValue);\n\n    return isFloatSource(source, value, YAML_FLOAT_REGEX) ? source : getFloatText(value);\n  },\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport {\n  JSON_INTEGER_REGEX,\n  rememberUniqueSource,\n} from '$lib/services/contents/file/value-sources';\nimport { isPlainObject } from '$lib/services/utils/object';\n\n/**\n * Source text of the integers read from files that a `number` can’t represent exactly, keyed by the\n * number they’re read as, e.g. `12345678901234567890` for `12345678901234567000`. The value is\n * `null` if different integers are read as the same number, so neither can be told from the other.\n *\n * Such an integer is read as the closest number rather than as a `BigInt`, which the entry draft,\n * its backup and the Number field can’t handle: they copy values with `JSON.stringify()`, which\n * throws on a `BigInt`. The formatters write the source text back instead of the number, so the\n * integer is saved exactly as long as it hasn’t been edited, which would give it another value.\n * @type {Map<number, string | null>}\n */\nconst unsafeIntegerSources = new Map();\n/**\n * Regular expression testing whether a document may hold an integer that a `number` can’t represent\n * exactly. Any such integer has more than 15 digits, as `2 ** 53` is `9007199254740992`. Testing\n * first saves parsing the document in a slower way, which is hardly ever needed.\n */\nconst LONG_DIGIT_RUN_REGEX = /\\d{16}/;\n\n/**\n * Check whether the given document may hold an integer that a `number` can’t represent exactly.\n * @param {string} str Document.\n * @returns {boolean} Result.\n */\nexport const mayHaveUnsafeInteger = (str) => LONG_DIGIT_RUN_REGEX.test(str);\n\n/**\n * Remember the source text of an integer read as a number that is not a safe integer. The source\n * text of an integer that the number represents exactly is remembered as well, so another integer\n * read as the same number can’t be taken for it.\n * @param {number} number Number the integer is read as.\n * @param {string} source Source text of the integer.\n */\nconst rememberSource = (number, source) => {\n  rememberUniqueSource(unsafeIntegerSources, number, source);\n};\n\n/**\n * Convert an integer to a `number`, remembering its source text if the number is not a safe\n * integer, as it may not represent the integer exactly.\n * @param {bigint} value Integer.\n * @returns {number} Number.\n */\nexport const toNumber = (value) => {\n  const number = Number(value);\n\n  if (!Number.isSafeInteger(number)) {\n    rememberSource(number, String(value));\n  }\n\n  return number;\n};\n\n/**\n * Replace every `BigInt` in the given parsed document with a `number` using {@link toNumber}, and\n * remember the source text of any number that is an integer but not a safe one.\n * @param {any} value Parsed document or a value in it. Arrays and plain objects are updated in\n * place.\n * @returns {any} Value without a `BigInt`.\n */\nexport const replaceBigInts = (value) => {\n  if (typeof value === 'bigint') {\n    return toNumber(value);\n  }\n\n  // A parser may read an integer that the number represents exactly as a number\n  if (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n    rememberSource(value, String(BigInt(value)));\n\n    return value;\n  }\n\n  if (Array.isArray(value) || isObject(value)) {\n    Object.entries(value).forEach(([key, val]) => {\n      /** @type {Record<string, any>} */ (value)[key] = replaceBigInts(val);\n    });\n  }\n\n  return value;\n};\n\n/**\n * A `JSON.parse()` reviver that reads an integer a `number` can’t represent exactly from its source\n * text with {@link toNumber}. A browser that doesn’t give the reviver the source text reads the\n * number as usual.\n * @param {string} _key Property name.\n * @param {any} value Parsed value.\n * @param {{ source?: string }} [context] Context, which holds the source text of a primitive value.\n * @returns {any} Value.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter\n */\nexport const reviveUnsafeInteger = (_key, value, context) => {\n  const source = context?.source;\n\n  return typeof value === 'number' &&\n    !Number.isSafeInteger(value) &&\n    typeof source === 'string' &&\n    JSON_INTEGER_REGEX.test(source)\n    ? toNumber(BigInt(source))\n    : value;\n};\n\n/**\n * Get the source text of the integer read as the given value, if a `number` can’t represent the\n * integer exactly.\n * @param {any} value Value.\n * @returns {string | undefined} Source text, or `undefined` if the value is not such a number or\n * its source text is not known for sure.\n */\nexport const getUnsafeIntegerSource = (value) =>\n  typeof value === 'number' && !Number.isSafeInteger(value)\n    ? (unsafeIntegerSources.get(value) ?? undefined)\n    : undefined;\n\n/**\n * Check whether any integer that a `number` can’t represent exactly has been read, so a formatter\n * can skip looking for one.\n * @returns {boolean} Result.\n */\nexport const hasUnsafeIntegerSources = () => unsafeIntegerSources.size > 0;\n\n/**\n * Copy the given value, replacing every number read from an integer that a `number` can’t represent\n * exactly with a `BigInt` of the integer, for a formatter that writes a `BigInt` as an integer.\n * @param {any} value Value to be formatted.\n * @returns {any} Copy of arrays and plain objects; any other value as is.\n */\nexport const restoreBigInts = (value) => {\n  const source = getUnsafeIntegerSource(value);\n\n  if (source !== undefined) {\n    return BigInt(source);\n  }\n\n  if (Array.isArray(value)) {\n    return value.map(restoreBigInts);\n  }\n\n  // Leave class instances, such as a `TomlDate`, as they are\n  if (isPlainObject(value)) {\n    return Object.fromEntries(\n      Object.entries(value).map(([key, val]) => [key, restoreBigInts(val)]),\n    );\n  }\n\n  return value;\n};\n\n/**\n * Clear the source text of the integers read so far. Used in tests.\n */\nexport const _resetUnsafeIntegerSources = () => {\n  unsafeIntegerSources.clear();\n};\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n *    may be used to endorse or promote products derived from this software without\n *    specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nfunction getLineColFromPtr(string, ptr) {\n    let lines = string.slice(0, ptr).split(/\\r?\\n/);\n    return [lines.length, lines.pop().length + 1];\n}\nfunction makeCodeBlock(string, line, column) {\n    let lines = string.split(/\\r?\\n/);\n    let codeblock = '';\n    let numberLen = (Math.log10(line + 1) | 0) + 1;\n    for (let i = line - 1; i <= line + 1; i++) {\n        let l = lines[i - 1];\n        if (!l)\n            continue;\n        codeblock += i.toString().padEnd(numberLen, ' ');\n        codeblock += ':  ';\n        codeblock += l;\n        codeblock += '\\n';\n        if (i === line) {\n            codeblock += ' '.repeat(numberLen + column + 2);\n            codeblock += '^\\n';\n        }\n    }\n    return codeblock;\n}\nexport class TomlError extends Error {\n    line;\n    column;\n    codeblock;\n    constructor(message, options) {\n        const [line, column] = getLineColFromPtr(options.toml, options.ptr);\n        const codeblock = makeCodeBlock(options.toml, line, column);\n        super(`Invalid TOML document: ${message}\\n\\n${codeblock}`, options);\n        this.line = line;\n        this.column = column;\n        this.codeblock = codeblock;\n    }\n    /** @internal */\n    static x(message, ctx, ptr) {\n        throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });\n    }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n *    may be used to endorse or promote products derived from this software without\n *    specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { TomlError } from './error.js';\n/** @internal */\nexport function parseString(ctx) {\n    let startPtr = ctx.p;\n    let c = ctx.s.charCodeAt(ctx.p++);\n    let first = c;\n    let isLiteral = c === 0x27; /* ' */\n    let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);\n    if (isMultiline) {\n        // Trim initial newline\n        if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 0xa /* \\n */)\n            ctx.p++;\n        else if (c === 0xd /* \\r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \\n */)\n            ctx.p += 2;\n    }\n    // For the record: it is not worth it to use a fast-path for literal strings using `indexOf`.\n    // Doing a char-by-char iteration ends up dispatching less instructions, for the same wall-clock runtime.\n    let parsed = '';\n    let sliceStart = ctx.p;\n    // states:\n    //   0 - decoding\n    //   1 - decoding escape\n    //   2 - whitespace escape (no newline encountered yet, must fail on non-whitespace)\n    //   3 - whitespace escape (newline encountered, allowed to transition back to normal decode)\n    let state = 0;\n    for (; ctx.p < ctx.s.length; ctx.p++) {\n        c = ctx.s.charCodeAt(ctx.p);\n        // Deal with newlines first, since that simplifies control character checking and handling across all states\n        if (isMultiline && (c === 0xa /* \\n */ || (c === 0xd /* \\r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \\n */))) {\n            state = state && 3;\n        }\n        // Control characters are banned in TOML, so we throw an error if we encounter them\n        else if ((c < 0x20 && c !== 0x9 /* \\t */) || c === 0x7f) {\n            TomlError.x('control characters are not allowed in strings', ctx);\n        }\n        // The string might terminate while we're parsing through a newline escape.\n        // It must have encountered a newline; otherwise, it'll simply fail in another branch.\n        else if ((!state || state === 3) && c === first && (!isMultiline || (ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first))) {\n            if (isMultiline) {\n                // If the string ends with 4-5 quotes, then the first 1-2 are part of the string\n                if (ctx.s.charCodeAt(ctx.p + 3) === first)\n                    ctx.p++;\n                if (ctx.s.charCodeAt(ctx.p + 3) === first)\n                    ctx.p++;\n            }\n            // If we're in a newline escape still, then there's nothing to add.\n            if (!state) {\n                // Avoid a useless concat operation if the string can be used as-is.\n                let s = ctx.s.slice(sliceStart, ctx.p);\n                parsed = parsed ? parsed + s : s;\n            }\n            ctx.p += isMultiline ? 3 : 1;\n            return parsed;\n        }\n        // Baseline state; keep moving forward unless an escape sequence starts\n        else if (!state) {\n            if (!isLiteral && c === 0x5c /* \\ */) {\n                parsed += ctx.s.slice(sliceStart, (sliceStart = ctx.p));\n                state = 1;\n            }\n        }\n        else if (state === 1) {\n            if (c === 0x78 /* x */ || c === 0x75 /* u */ || c === 0x55 /* U */) { // Unicode escape\n                let errPtr = ctx.p++ - 1;\n                let value = 0;\n                let len = c === 0x78 /* x */ ? 2 : c === 0x75 /* u */ ? 4 : 8;\n                for (let j = 0; j < len; j++, ctx.p++) {\n                    let hex = ctx.s.charCodeAt(ctx.p);\n                    let digit = \n                    /* 0-9 */ hex >= 0x30 && hex <= 0x39 ? hex - 0x30 :\n                        /* A-F */ hex >= 0x41 && hex <= 0x46 ? hex - 0x41 + 10 :\n                            /* a-f */ hex >= 0x61 && hex <= 0x66 ? hex - 0x61 + 10 : -1;\n                    if (digit < 0)\n                        TomlError.x('invalid non-hex character in unicode escape', ctx);\n                    value = (value << 4) | digit;\n                }\n                // Because JS does bitwise on signed 32bit integers, all 0xfzzzzzzz values are actually seen as negative\n                if (value < 0 || value > 0x10ffff || (value >= 0xd800 && value <= 0xdfff)) {\n                    TomlError.x('invalid unicode escape', ctx, errPtr);\n                }\n                parsed += String.fromCodePoint(value);\n                sliceStart = ctx.p--;\n                state = 0;\n            }\n            // Newline escape sequence. We only need to care about spaces and tabs; newlines are dealt with earlier\n            else if (isMultiline && (c === 0x20 || c === 0x9 /* \\t */)) {\n                state = 2;\n            }\n            // Basic escape sequence\n            else {\n                if (c === 0x62 /* b */)\n                    parsed += '\\b';\n                else if (c === 0x74 /* t */)\n                    parsed += '\\t';\n                else if (c === 0x6e /* n */)\n                    parsed += '\\n';\n                else if (c === 0x66 /* f */)\n                    parsed += '\\f';\n                else if (c === 0x72 /* r */)\n                    parsed += '\\r';\n                else if (c === 0x65 /* e */)\n                    parsed += '\\x1b';\n                else if (c === 0x22 /* \" */)\n                    parsed += '\"';\n                else if (c === 0x5c /* \\ */)\n                    parsed += '\\\\';\n                else\n                    TomlError.x('unrecognised escape sequence', ctx);\n                sliceStart = ctx.p + 1;\n                state = 0;\n            }\n        }\n        // Newline escape continuation: keep moving forward until the first non-whitespace char\n        else if (c !== 0x20 && c !== 0x9 /* \\t */) {\n            if (state === 2)\n                TomlError.x('invalid escape: only line-ending whitespace may be escaped', ctx, sliceStart);\n            // State cannot be zero, or we'd have branched earlier already.\n            // If it's a backslash, immediately transition to the escape state so it can be processed.\n            state = !isLiteral && c === 0x5c /* \\ */ ? 1 : 0;\n            sliceStart = ctx.p;\n        }\n    }\n    TomlError.x('unfinished string', ctx, startPtr);\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n *    may be used to endorse or promote products derived from this software without\n *    specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet DATE_TIME_RE = /^(\\d{4}-\\d{2}-\\d{2})?[Tt ]?(?:(\\d{2}):\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)?(Z|z|[-+]\\d{2}:\\d{2})?$/i;\nexport class TomlDate extends Date {\n    #hasDate = false;\n    #hasTime = false;\n    #offset = null;\n    constructor(date, fasttype, unsafeDelim) {\n        let hasDate = true;\n        let hasTime = true;\n        let offset = 'Z';\n        let c;\n        if (typeof date === 'string') {\n            if (fasttype)\n                prep: {\n                    // Date-time\n                    if (fasttype < 3) {\n                        if (+date.slice(11, 13) > 23) {\n                            date = '';\n                            break prep;\n                        }\n                        // Local\n                        if (fasttype === 2) {\n                            offset = null;\n                            date += 'Z';\n                        }\n                        // Offset; keep track of offset if not Z\n                        else if ((c = date.charCodeAt(date.length - 1)) !== 0x5a /* Z */ && c !== 0x7a /* z */) {\n                            offset = date.slice(date.length - 6);\n                        }\n                        if (unsafeDelim)\n                            date = date.slice(0, 10) + 'T' + date.slice(11);\n                    }\n                    // Time\n                    else if (fasttype === 4) {\n                        date = +date.slice(0, 2) > 23 ? '' : `0000-01-01T${date}Z`;\n                    }\n                    hasDate = fasttype !== 4;\n                    hasTime = fasttype !== 3;\n                }\n            else {\n                let match = date.match(DATE_TIME_RE);\n                if (match) {\n                    if (!match[1]) {\n                        hasDate = false;\n                        date = `0000-01-01T${date}`;\n                    }\n                    hasTime = !!match[2];\n                    // Make sure to use T instead of a space. Breaks in case of extreme values otherwise.\n                    hasTime && date[10] === ' ' && (date = date.replace(' ', 'T'));\n                    // Do not allow rollover hours.\n                    if (match[2] && +match[2] > 23) {\n                        date = '';\n                    }\n                    else {\n                        offset = match[3] || null;\n                        if (!offset && hasTime)\n                            date += 'Z';\n                    }\n                }\n                else {\n                    date = '';\n                }\n            }\n        }\n        super(date);\n        if (!isNaN(this.getTime())) {\n            this.#hasDate = hasDate;\n            this.#hasTime = hasTime;\n            this.#offset = offset;\n        }\n    }\n    isDateTime() {\n        return this.#hasDate && this.#hasTime;\n    }\n    isLocal() {\n        return !this.#hasDate || !this.#hasTime || !this.#offset;\n    }\n    isDate() {\n        return this.#hasDate && !this.#hasTime;\n    }\n    isTime() {\n        return this.#hasTime && !this.#hasDate;\n    }\n    isValid() {\n        return this.#hasDate || this.#hasTime;\n    }\n    toISOString() {\n        let iso = super.toISOString();\n        // Local Date\n        if (this.isDate())\n            return iso.slice(0, 10);\n        // Local Time\n        if (this.isTime())\n            return iso.slice(11, 23);\n        // Local DateTime\n        if (this.#offset === null)\n            return iso.slice(0, -1);\n        // Offset DateTime\n        if (this.#offset === 'Z' || this.#offset === 'z')\n            return iso;\n        // This part is quite annoying: JS strips the original timezone from the ISO string representation\n        // Instead of using a \"modified\" date and \"Z\", we restore the representation \"as authored\"\n        let offset = (+(this.#offset.slice(1, 3)) * 60) + +(this.#offset.slice(4, 6));\n        offset = this.#offset[0] === '-' ? offset : -offset;\n        let offsetDate = new Date(this.getTime() - (offset * 60e3));\n        return offsetDate.toISOString().slice(0, -1) + this.#offset;\n    }\n    static wrapAsOffsetDateTime(jsDate, offset = 'Z') {\n        let date = new TomlDate(jsDate);\n        date.#offset = offset;\n        return date;\n    }\n    static wrapAsLocalDateTime(jsDate) {\n        let date = new TomlDate(jsDate);\n        date.#offset = null;\n        return date;\n    }\n    static wrapAsLocalDate(jsDate) {\n        let date = new TomlDate(jsDate);\n        date.#hasTime = false;\n        date.#offset = null;\n        return date;\n    }\n    static wrapAsLocalTime(jsDate) {\n        let date = new TomlDate(jsDate);\n        date.#hasDate = false;\n        date.#offset = null;\n        return date;\n    }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n *    may be used to endorse or promote products derived from this software without\n *    specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString } from './primitive.js';\nimport { parseArray, parseInlineTable } from './struct.js';\nimport { TomlError } from './error.js';\nimport { TomlDate } from './date.js';\nfunction isDigit(char, base = 10) {\n    return base === 16\n        ? (char > 0x2f && char < 0x3a) || (char > 0x40 && char < 0x47) || (char > 0x60 && char < 0x67)\n        : (char > 0x2f && char < 0x30 + base);\n}\nfunction isEndOfValue(char, delim) {\n    // Whitespace -- we're permissive on `\\r` for performance; it'll be dealt with later anyway\n    return char === 0x20 || char === 0x9 /* \\t */ || char === 0xa /* \\n */ || char === 0xd /* \\r */ ||\n        // Structure end or next value delimiter\n        (delim && (char === delim || char === 0x2c /* , */)) ||\n        // Comment\n        char === 0x23; /* # */\n}\n/** @internal */\nexport function extractValue(ctx, end) {\n    let errPtr = ctx.p;\n    let c = ctx.s.charCodeAt(ctx.p);\n    // Structs\n    if (c === 0x5b /* [ */ || c === 0x7b /* { */) {\n        ctx.d-- || TomlError.x('document contains excessively nested structures. aborting.', ctx);\n        let value = c === 0x5b /* [ */\n            ? parseArray(ctx)\n            : parseInlineTable(ctx);\n        ctx.d++;\n        return value;\n    }\n    // Strings\n    if (c === 0x22 /* \" */ || c === 0x27 /* ' */) {\n        return parseString(ctx);\n    }\n    // Booleans\n    // We can fast-path because the first character is enough to know the only possible value\n    if (c === 0x74 /* t */) { // Only possible valid value is `true`\n        if (ctx.s.charCodeAt(++ctx.p) !== 0x72 || ctx.s.charCodeAt(++ctx.p) !== 0x75 || ctx.s.charCodeAt(++ctx.p) !== 0x65)\n            TomlError.x('invalid value', ctx, errPtr);\n        return ctx.p++, true;\n    }\n    if (c === 0x66 /* f */) { // Only possible valid value is `false`\n        if (ctx.s.charCodeAt(++ctx.p) !== 0x61 || ctx.s.charCodeAt(++ctx.p) !== 0x6c || ctx.s.charCodeAt(++ctx.p) !== 0x73 || ctx.s.charCodeAt(++ctx.p) !== 0x65)\n            TomlError.x('invalid value', ctx, errPtr);\n        return ctx.p++, false;\n    }\n    if (c === 0x2b /* + */ || c === 0x2d /* - */) {\n        return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 0x2c - c, end);\n    }\n    // Rough heuristic, but `parseDate` falls back to number parsing if it's a false positive.\n    // e.g.: `a = 1\\n-------------- = 1` would match this heuristic, but gracefully fallback to numbers.\n    if (ctx.s.charCodeAt(ctx.p + 4) === 0x2d /* - */ && ctx.s.charCodeAt(ctx.p + 7) === 0x2d /* - */) {\n        return parseDate(ctx, c, end);\n    }\n    // Same logic as above; `parseTime` falls back to number parsing if it's a false positive.\n    if (ctx.s.charCodeAt(ctx.p + 2) === 0x3a /* : */) {\n        return parseTime(ctx, c, end);\n    }\n    return parseNumber(ctx, ctx.p, c, 0, end);\n}\n// State:\n// 0: init\n// 1: integer\n// 2: fractional dot\n// 3: fractional\n// 4: exponent letter\n// 5: exponent\n// 6: exponent sign\n// 7: exponent with sign\n// >9: underscore; see below\n//     -> 12: was integer\n//     -> 14: was fractional\n//     -> 16: was exponent\n// states 2-5, 14, 16 are ONLY permitted iif base === 10\nfunction parseNumber(ctx, startPtr, startChr, sign, endChr) {\n    let c = startChr;\n    let state = 0;\n    let hasUnderscores = false;\n    // (+/-)inf\n    if (c === 0x69 /* i */) {\n        if (ctx.s.charCodeAt(++ctx.p) !== 0x6e || ctx.s.charCodeAt(++ctx.p) !== 0x66)\n            TomlError.x('invalid value', ctx, startPtr);\n        return ctx.p++, (sign || 1) / 0;\n    }\n    // (+/-)nan\n    if (c === 0x6e /* n */) {\n        if (ctx.s.charCodeAt(++ctx.p) !== 0x61 || ctx.s.charCodeAt(++ctx.p) !== 0x6e)\n            TomlError.x('invalid value', ctx, startPtr);\n        return ctx.p++, NaN;\n    }\n    // Leading zero\n    // Only allowed cases: `0<EOV>`, `0.(...)`, `0e(...)`, `0x(...)`, `0b(...)`, `0o(...)`\n    // FWIW, `0e(...)` is a stupid case, but it's not banned per-se so we have to parse it\n    if (c === 0x30 /* 0 */) {\n        if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))\n            return ctx.bi === true ? 0n : 0; // note: conveniently deals with `-0`\n        if (!sign) {\n            if (c === 0x78 /* x */)\n                return parseIntegerBaseN(ctx, startPtr, 16, endChr);\n            else if (c === 0x62 /* b */)\n                return parseIntegerBaseN(ctx, startPtr, 2, endChr);\n            else if (c === 0x6f /* o */)\n                return parseIntegerBaseN(ctx, startPtr, 8, endChr);\n        }\n        if (c === 0x2e /* . */)\n            state = 2;\n        else if (c === 0x65 /* e */ || c === 0x45 /* E */)\n            state = 4;\n        else\n            TomlError.x('illegal leading zero', ctx, startPtr);\n    }\n    // If the 1st char is not a digit by now, then it's not a valid TOML value at all\n    else if (!isDigit(c))\n        TomlError.x('invalid value', ctx, startPtr);\n    while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {\n        if (!state)\n            state = 1; // Detects single-digit numbers we can use a fast parse path for\n        // The way the states are numbered is not random: underscores are always permitted in odd-numbered states and\n        // never permitted in even-numbered ones.\n        if (c === 0x5f /* _ */) {\n            if (!(state & 1))\n                TomlError.x('illegal underscore', ctx);\n            state += 11; // 11 is a marker that makes the state even and greater than 9; see the numbering + rationale above\n            hasUnderscores = true;\n        }\n        // Transition to fractional part.\n        else if (state === 1 && c === 0x2e /* . */)\n            state = 2;\n        // Transition to exponent part.\n        else if ((state === 1 || state === 3) && (c === 0x65 /* e */ || c === 0x45 /* E */))\n            state = 4;\n        // + and - are permitted in state 4 only (handled before entering the function for state 0)\n        else if (state === 4 && (c === 0x2b /* + */ || c === 0x2d /* - */)) {\n            state = 6;\n        }\n        // All special cases have been handled; only digits are allowed here\n        else if (!isDigit(c))\n            TomlError.x(`illegal character in numeric literal`, ctx);\n        // Clear state flags\n        else if (state > 9)\n            state -= 11;\n        else if (!(state & 1))\n            state++;\n    }\n    // Single-char number; we can fast-path these very easily.\n    if (!state) {\n        let val = (startChr - 0x30 /* 0 */) * (sign || 1);\n        return ctx.bi === true ? BigInt(val) : val;\n    }\n    // Even-numbered states absolutely require a digit next; not even end of value is permitted\n    if (!(state & 1))\n        TomlError.x('unfinished numeric value', ctx, startPtr);\n    let str = ctx.s.slice(startPtr, ctx.p);\n    if (hasUnderscores)\n        str = str.replaceAll('_', ''); // perf: replaceAll 1.25x faster than replace with a regex\n    return state > 1\n        ? parseFloat(str)\n        : parseInteger(ctx, str, 10, startPtr);\n}\nfunction parseIntegerBaseN(ctx, startPtr, base, endChr) {\n    let c, underscore = 1;\n    while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {\n        if (c === 0x5f /* _ */) {\n            if (underscore & 1)\n                TomlError.x('illegal underscore', ctx);\n            underscore = 3;\n        }\n        // We only need to check if the number is a valid digit, nothing else is permitted\n        else if (!isDigit(c, base))\n            TomlError.x(`illegal character in numeric literal`, ctx);\n        // Clear underscore flag\n        else if (underscore & 1)\n            underscore--;\n    }\n    // Trailing underscore is not allowed\n    if (underscore & 1)\n        TomlError.x('unfinished numeric value', ctx);\n    let str = ctx.s.slice(startPtr + 2, ctx.p);\n    if (underscore)\n        str = str.replaceAll('_', ''); // perf: replaceAll 1.25x faster than replace with a regex\n    return parseInteger(ctx, str, base, startPtr);\n}\nfunction parseInteger(ctx, str, base, startPtr) {\n    if (ctx.bi !== true)\n        int: {\n            let val = parseInt(str, base);\n            if (!Number.isSafeInteger(val)) {\n                if (ctx.bi)\n                    break int;\n                TomlError.x('integer value cannot be represented losslessly', ctx, startPtr);\n            }\n            return val;\n        }\n    return base === 10 ? BigInt(str) : BigInt((base === 2 ? '0b' : base === 8 ? '0o' : '0x') + str);\n}\nfunction parseDate(ctx, c, endChr) {\n    let startPtr = ctx.p++, unsafeSeparator;\n    if (!isDigit(c) ||\n        !isDigit(ctx.s.charCodeAt(ctx.p++)) ||\n        !isDigit(ctx.s.charCodeAt(ctx.p++)) ||\n        !isDigit(ctx.s.charCodeAt(ctx.p++))) {\n        return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);\n    }\n    ctx.p += 5;\n    if (!isDigit(ctx.s.charCodeAt(ctx.p++)))\n        TomlError.x('invalid date-time: date part is malformed', ctx, startPtr);\n    if (ctx.p >= ctx.s.length || (((c = ctx.s.charCodeAt(ctx.p)) !== 0x20 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 0x54 /* T */ && c !== 0x74 /* t */)) {\n        let t = ctx.s.slice(startPtr, ctx.p);\n        return readDate(ctx, t, 3, false, startPtr);\n    }\n    if (ctx.s.charCodeAt(ctx.p += 3) !== 0x3a /* : */)\n        TomlError.x('invalid date-time: time part is malformed', ctx, startPtr);\n    if (ctx.s.charCodeAt(ctx.p += 3) === 0x3a /* : */)\n        ctx.p += 3;\n    if (ctx.s.charCodeAt(ctx.p) === 0x2e /* . */)\n        while (isDigit(ctx.s.charCodeAt(++ctx.p)))\n            ;\n    if (c = ctx.s.charCodeAt(ctx.p)) {\n        if (c === 0x5a /* Z */ || c === 0x7a /* z */) {\n            let t = ctx.s.slice(startPtr, ++ctx.p);\n            return readDate(ctx, t, 1, unsafeSeparator, startPtr, '[+00:00]');\n        }\n        if (c === 0x2b /* + */ || c === 0x2d /* - */) {\n            // Temporal's ZonedDateTime is weird asf when it comes to dealing with traditional offsets...\n            // It's 1.2x faster to allocate a new string to pass to ZDT than use Instant.toZonedDateTimeISO\n            let t = ctx.s.slice(startPtr, ctx.p += 6);\n            return readDate(ctx, t, 1, unsafeSeparator, startPtr, !ctx.ld && ('[' + ctx.s.slice(ctx.p - 6, ctx.p) + ']'));\n        }\n    }\n    let t = ctx.s.slice(startPtr, ctx.p);\n    return readDate(ctx, t, 2, unsafeSeparator, startPtr);\n}\nfunction parseTime(ctx, c, endChr) {\n    let start = ctx.p;\n    if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {\n        return parseNumber(ctx, --ctx.p, c, 0, endChr);\n    }\n    if (ctx.s.charCodeAt(ctx.p += 4) === 0x3a /* : */)\n        ctx.p += 3;\n    if (ctx.s.charCodeAt(ctx.p) === 0x2e /* . */)\n        while (isDigit(ctx.s.charCodeAt(++ctx.p)))\n            ;\n    let t = ctx.s.slice(start, ctx.p);\n    return readDate(ctx, t, 4, false, start);\n}\nfunction readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {\n    if (ctx.ld) {\n        let date = new TomlDate(str, type, unsafeDelim);\n        if (!date.isValid())\n            TomlError.x('invalid date', ctx, errPtr);\n        return date;\n    }\n    try {\n        if (temporalSuffix)\n            str += temporalSuffix;\n        switch (type) {\n            case 1: return Temporal.ZonedDateTime.from(str);\n            case 2: return Temporal.PlainDateTime.from(str);\n            case 3: return Temporal.PlainDate.from(str);\n            case 4: return Temporal.PlainTime.from(str);\n        }\n    }\n    catch (e) {\n        TomlError.x(e instanceof Error ? e.message : '' + e, ctx, errPtr);\n    }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n *    may be used to endorse or promote products derived from this software without\n *    specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { TomlError } from './error.js';\n/** @internal */\nexport function skipComment(ctx) {\n    for (; ctx.p < ctx.s.length; ctx.p++) {\n        let c = ctx.s.charCodeAt(ctx.p);\n        if (c === 0xa /* \\n */)\n            break;\n        if (c === 0xd /* \\r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \\n */) {\n            ctx.p++;\n            break;\n        }\n        if ((c < 0x20 && c !== 0x9 /* \\t */) || c === 0x7f) {\n            TomlError.x('control characters are not allowed in comments', ctx);\n        }\n    }\n}\n/** @internal */\nexport function skipVoid(ctx, banNewLines, banComments) {\n    let c;\n    while (ctx.p < ctx.s.length) {\n        while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 0x20 ||\n            c === 0x9 /* \\t */ ||\n            (!banNewLines &&\n                (c === 0xa /* \\n */ || (c === 0xd /* \\r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \\n */)))))\n            ctx.p++;\n        if (banComments || c !== 0x23 /* # */)\n            break;\n        skipComment(ctx);\n    }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n *    may be used to endorse or promote products derived from this software without\n *    specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString } from './primitive.js';\nimport { extractValue } from './extract.js';\nimport { skipVoid } from './util.js';\nimport { TomlError } from './error.js';\n/** @internal */\nexport function parseKey(ctx, end = 0x3d /* = */) {\n    // States:\n    // 0: before first char\n    // 1: parsing bare key\n    // 2: after key component\n    let startPtr;\n    let state = 0;\n    let parsed = [];\n    let sliceStart;\n    let c = ctx.s.charCodeAt(startPtr = ctx.p);\n    do {\n        // End of key\n        if (c === end) {\n            if (!state)\n                TomlError.x('unexpected end of key', ctx);\n            if (state === 1)\n                parsed.push(ctx.s.slice(sliceStart, ctx.p));\n            return ctx.p++, parsed;\n        }\n        // Dotted key separator\n        else if (c === 0x2e /* . */) {\n            if (!state)\n                TomlError.x('illegal empty bare key', ctx);\n            if (state === 1)\n                parsed.push(ctx.s.slice(sliceStart, ctx.p));\n            state = 0;\n        }\n        // Quoted key\n        else if (!state && (c === 0x22 /* \" */ || c === 0x27 /* ' */)) {\n            if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))\n                TomlError.x('illegal quoted key: multiline strings are not allowed', ctx);\n            parsed.push(parseString(ctx));\n            state = 2;\n            ctx.p--;\n        }\n        // Whitespace; no-op in state 0 and 2, end of bare key in state 1\n        else if (c === 0x20 || c === 0x9 /* \\t */) {\n            if (state === 1) {\n                parsed.push(ctx.s.slice(sliceStart, ctx.p));\n                state = 2;\n            }\n        }\n        // If state is post-key, no character is allowed; otherwise ensure it's a bare-key component\n        else if (state === 2 || (c < 0x30 && c !== 0x2d /* - */) || (c > 0x39 && c < 0x41) || (c > 0x5a && c < 0x61 && c !== 0x5f /* _ */) || c > 0x7a) {\n            TomlError.x('illegal character in key', ctx);\n        }\n        // Illegal character\n        else if (!state) {\n            state = 1;\n            sliceStart = ctx.p;\n        }\n    } while (c = ctx.s.charCodeAt(++ctx.p));\n    TomlError.x('incomplete key-value: cannot find end of key', ctx, startPtr);\n}\n/** @internal */\nexport function parseInlineTable(ctx) {\n    let startPtr = ctx.p++;\n    let res = Object.create(null);\n    let seen = new Set();\n    let c;\n    while (ctx.p < ctx.s.length) {\n        skipVoid(ctx);\n        if ((c = ctx.s.charCodeAt(ctx.p)) === 0x7d /* } */) {\n            ctx.p++;\n            return res;\n        }\n        let k;\n        let t = res;\n        let hasOwn = false;\n        let errPtr = ctx.p;\n        let key = parseKey(ctx);\n        for (let i = 0; i < key.length; i++) {\n            if (i)\n                t = hasOwn ? t[k] : (t[k] = Object.create(null));\n            k = key[i];\n            if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== 'object' || seen.has(t[k]))) {\n                TomlError.x('trying to redefine an already defined value', ctx, errPtr);\n            }\n            let unsafe = k === '__proto__';\n            if (ctx.uk && (unsafe || k === 'constructor')) {\n                t = ctx.uk !== 1 && TomlError.x('document contains an unsafe property', ctx, errPtr);\n                break;\n            }\n            if (!hasOwn && unsafe) {\n                Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n            }\n        }\n        if (hasOwn) {\n            TomlError.x('trying to redefine an already defined value', ctx, errPtr);\n        }\n        skipVoid(ctx, true, true);\n        let value = extractValue(ctx, 0x7d /* } */);\n        if (t && typeof (t[k] = value) === 'object')\n            seen.add(value);\n        skipVoid(ctx);\n        if ((c = ctx.s.charCodeAt(ctx.p++)) === 0x7d /* } */) {\n            return res;\n        }\n        if (c !== 0x2c /* , */)\n            TomlError.x('expected comma or end of structure', ctx, ctx.p - 1);\n    }\n    TomlError.x('unfinished table', ctx, startPtr);\n}\n/** @internal */\nexport function parseArray(ctx) {\n    let startPtr = ctx.p++;\n    let res = [];\n    let c;\n    while (ctx.p < ctx.s.length) {\n        skipVoid(ctx);\n        if ((c = ctx.s.charCodeAt(ctx.p)) === 0x5d /* ] */) {\n            ctx.p++;\n            return res;\n        }\n        res.push(extractValue(ctx, 0x5d /* ] */));\n        skipVoid(ctx);\n        if ((c = ctx.s.charCodeAt(ctx.p++)) === 0x5d /* ] */) {\n            return res;\n        }\n        if (c !== 0x2c /* , */)\n            TomlError.x('expected comma or end of structure', ctx, ctx.p - 1);\n    }\n    TomlError.x('unfinished array', ctx, startPtr);\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n *    may be used to endorse or promote products derived from this software without\n *    specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseKey } from './struct.js';\nimport { extractValue } from './extract.js';\nimport { skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nfunction peekTable(ctx, key, table, meta, type) {\n    let t = table;\n    let m = meta;\n    let k;\n    let hasOwn = false;\n    let state;\n    for (let i = 0; i < key.length; i++) {\n        if (i) {\n            t = hasOwn ? t[k] : (t[k] = Object.create(null));\n            m = (state = m[k]).c;\n            if (type === 0 /* Type.DOTTED */ && (state.t === 1 /* Type.EXPLICIT */ || state.t === 2 /* Type.ARRAY */)) {\n                return null;\n            }\n            if (state.t === 2 /* Type.ARRAY */) {\n                let l = t.length - 1;\n                t = t[l];\n                m = m[l].c;\n            }\n        }\n        k = key[i];\n        if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 /* Type.DOTTED */ && m[k]?.d) {\n            return null;\n        }\n        if (!hasOwn) {\n            let unsafe = k === '__proto__';\n            if (ctx.uk && (unsafe || k === 'constructor'))\n                return false;\n            if (unsafe) {\n                Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n                Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });\n            }\n            m[k] = {\n                t: i < key.length - 1 && type === 2 /* Type.ARRAY */\n                    ? 3 /* Type.ARRAY_DOTTED */ : type,\n                d: false,\n                i: 0,\n                c: Object.create(null),\n            };\n        }\n    }\n    state = m[k];\n    if (state.t !== type && !(type === 1 /* Type.EXPLICIT */ && state.t === 3 /* Type.ARRAY_DOTTED */)) {\n        // Bad key type!\n        return null;\n    }\n    if (type === 2 /* Type.ARRAY */) {\n        if (!state.d) {\n            state.d = true;\n            t[k] = [];\n        }\n        t[k].push(t = Object.create(null));\n        state.c[state.i++] = (state = { t: 1 /* Type.EXPLICIT */, d: false, i: 0, c: Object.create(null) });\n    }\n    if (state.d) {\n        // Redefining a table!\n        return null;\n    }\n    state.d = true;\n    if (type === 1 /* Type.EXPLICIT */) {\n        t = hasOwn ? t[k] : (t[k] = Object.create(null));\n    }\n    else if (type === 0 /* Type.DOTTED */ && hasOwn) {\n        return null;\n    }\n    return [k, t, state.c];\n}\nfunction validateTablePeek(ctx, peek, ptr) {\n    if (peek === null || ctx.uk === 2)\n        TomlError.x(peek === null\n            ? 'trying to redefine an already defined table or value'\n            : 'document contains an unsafe property', ctx, ptr);\n}\nexport function parse(toml, options = {}) {\n    let ctx = {\n        s: toml,\n        p: 0,\n        d: options.maxDepth ?? 1000,\n        bi: options.integersAsBigInt ?? false,\n        ld: options.useLegacyDate ?? true,\n        uk: options.unsafeKeyBehaviour === 'throw' ? 2 : options.unsafeKeyBehaviour === 'drop' ? 1 : 0,\n    };\n    let res = Object.create(null);\n    let meta = Object.create(null);\n    let tmp;\n    let skipping = false;\n    let tbl = res;\n    let m = meta;\n    // BOM is allowed, skip.\n    // JS is UTF-16, so we have to check for the UTF-16 BOM instead of the UTF-8 BOM sequence!\n    if (toml.charCodeAt(0) === 0xfeff)\n        ctx.p++;\n    skipVoid(ctx);\n    while (ctx.p < toml.length) {\n        if (toml.charCodeAt(ctx.p) === 0x5b /* [ */) {\n            let isTableArray = toml.charCodeAt(++ctx.p) === 0x5b; /* [ */\n            tmp = ctx.p += +isTableArray;\n            skipping = false;\n            let k = parseKey(ctx, 0x5d /* ] */);\n            if (isTableArray) {\n                if (toml.charCodeAt(ctx.p) !== 0x5d /* ] */) {\n                    TomlError.x('expected end of table array declaration', ctx);\n                }\n                ctx.p++;\n            }\n            let p = peekTable(ctx, k, res, meta, isTableArray ? 2 /* Type.ARRAY */ : 1 /* Type.EXPLICIT */);\n            if (!p) {\n                validateTablePeek(ctx, p, tmp);\n                skipping = true;\n            }\n            else {\n                m = p[2];\n                tbl = p[1];\n            }\n        }\n        else {\n            tmp = ctx.p;\n            let k = parseKey(ctx);\n            let p = peekTable(ctx, k, tbl, m, 0 /* Type.DOTTED */);\n            if (!p && !skipping)\n                validateTablePeek(ctx, p, tmp);\n            skipVoid(ctx, true, true);\n            let v = extractValue(ctx, void 0);\n            if (p && !skipping)\n                p[1][p[0]] = v;\n        }\n        skipVoid(ctx, true);\n        if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 0xa /* \\n */ && (tmp !== 0xd /* \\r */ || toml.charCodeAt(ctx.p + 1) !== 0xa /* \\n */)) {\n            TomlError.x('each key-value declaration must be followed by an end-of-line', ctx);\n        }\n        skipVoid(ctx);\n    }\n    return res;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n *    may be used to endorse or promote products derived from this software without\n *    specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet BARE_KEY = /^[a-z0-9-_]+$/i;\nlet HAS_WELLFORMED = !!(''.isWellFormed);\nfunction extendedTypeOf(obj) {\n    let type = typeof obj;\n    if (type === 'object') {\n        if (Array.isArray(obj))\n            return 'array';\n        if (typeof obj.getUTCDate === 'function' && obj instanceof Date)\n            return 'date';\n        if (globalThis.Temporal) {\n            if (obj.until) {\n                if (obj instanceof Temporal.ZonedDateTime)\n                    return 'temporal/tz+uc';\n                if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate)\n                    return 'temporal/uc';\n                if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant)\n                    return 'temporal';\n                if (obj instanceof Temporal.PlainYearMonth)\n                    return 'temporal/x';\n            }\n            else if ((obj.toPlainDate && obj instanceof Temporal.PlainMonthDay) ||\n                (obj.negated && obj instanceof Temporal.Duration)) {\n                return 'temporal/x';\n            }\n        }\n    }\n    return type;\n}\nfunction isArrayOfTables(obj) {\n    for (let i = 0; i < obj.length; i++) {\n        if (extendedTypeOf(obj[i]) !== 'object')\n            return false;\n    }\n    return obj.length != 0;\n}\nfunction formatWellFormedStringUnchecked(s) {\n    return JSON.stringify(s).replaceAll('\\x7f', '\\\\u007f');\n}\nfunction formatString(s) {\n    return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);\n}\nfunction formatKey(s) {\n    if (BARE_KEY.test(s))\n        return s;\n    if (HAS_WELLFORMED && !s.isWellFormed())\n        throw new RangeError('key contains illegal lone surrogates');\n    return formatWellFormedStringUnchecked(s);\n}\nfunction stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {\n    if (depth === 0) {\n        throw new Error('Could not stringify the object: maximum object depth exceeded');\n    }\n    switch (type) {\n        // @ts-expect-error -- intentional fallthrough case\n        case 'number':\n            if (isNaN(val))\n                return 'nan';\n            if (val === Infinity)\n                return 'inf';\n            if (val === -Infinity)\n                return '-inf';\n            if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val)))\n                return val.toFixed(1);\n        case 'bigint':\n        case 'boolean':\n        case 'temporal':\n            return val.toString();\n        case 'string':\n            return formatString(val);\n        case 'date':\n            if (isNaN(val.getTime()))\n                throw new TypeError('cannot serialize invalid date');\n            return val.toISOString();\n        case 'object':\n            return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);\n        case 'array':\n            return stringifyArray(val, depth, numberAsFloat, strictTemporal);\n        // @ts-expect-error -- intentional fallthrough case\n        case 'temporal/tz+uc':\n            if (strictTemporal) {\n                let tz = val.timeZoneId;\n                let tzc = tz.charCodeAt(0);\n                if (\n                // Classic offset\n                tzc !== 0x2b /* + */ && tzc !== 0x2d /* - */ &&\n                    (\n                    // Fast pre-check pass; see below for the actually accepted values\n                    (tzc !== 0x55 /* U */ && tzc !== 0x47 /* G */ && tzc !== 0x5a /* Z */ && tzc !== 0x45 /* E */) ||\n                        (\n                        // UTC and its aliases; Temporal implementations don't all canonicalise unfortunately\n                        tz !== 'UTC' && tz !== 'UCT' && tz !== 'Universal' && tz !== 'Zulu' &&\n                            // GMT is a TZ but it's for all intents and purposes equivalent to UTC. Safe to downgrade.\n                            !tz.startsWith('GMT') && tz !== 'Greenwich' &&\n                            // Etc/* are all safe to downgrade to offset (either UTC, GMT, or offset)\n                            !tz.startsWith('Etc/')))) {\n                    throw new TypeError('Temporal objects with an IANA timezone are not allowed in Temporal strict mode');\n                }\n            }\n        case 'temporal/uc':\n            if (strictTemporal && val.calendarId !== 'iso8601')\n                throw new TypeError('Temporal objects with a non-default calendar are not allowed in Temporal strict mode');\n            return val.toString({\n                calendarName: 'never',\n                timeZoneName: 'never',\n            });\n        case 'temporal/x':\n            throw new TypeError('Unsupported ' + val[Symbol.toStringTag]);\n    }\n}\nfunction stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {\n    let keys = Object.keys(obj);\n    if (keys.length === 0)\n        return '{}';\n    let res = '{ ';\n    for (let i = 0; i < keys.length; i++) {\n        let k = keys[i];\n        if (i)\n            res += ', ';\n        res += formatKey(k) + ' = ' + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);\n    }\n    return res + ' }';\n}\nfunction stringifyArray(array, depth, numberAsFloat, strictTemporal) {\n    if (array.length === 0)\n        return '[]';\n    let res = '[ ';\n    for (let i = 0; i < array.length; i++) {\n        if (i)\n            res += ', ';\n        if (array[i] === null || array[i] === void 0) {\n            throw new TypeError('arrays cannot contain null or undefined values');\n        }\n        res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat, strictTemporal);\n    }\n    return res + ' ]';\n}\nfunction stringifyArrayTable(array, key, depth, numberAsFloat, strictTemporal) {\n    if (depth === 0) {\n        throw new Error('Could not stringify the object: maximum object depth exceeded');\n    }\n    let res = '';\n    for (let i = 0; i < array.length; i++) {\n        res += `${res && '\\n'}[[${key}]]\\n`;\n        res += stringifyTable(0, array[i], key, depth, numberAsFloat, strictTemporal);\n    }\n    return res;\n}\nfunction stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {\n    if (depth === 0) {\n        throw new Error('Could not stringify the object: maximum object depth exceeded');\n    }\n    let preamble = '';\n    let tables = '';\n    let keys = Object.keys(obj);\n    for (let i = 0; i < keys.length; i++) {\n        let k = keys[i];\n        if (obj[k] !== null && obj[k] !== void 0) {\n            let type = extendedTypeOf(obj[k]);\n            if (type === 'symbol' || type === 'function') {\n                throw new TypeError(`cannot serialize values of type '${type}'`);\n            }\n            let key = formatKey(k);\n            if (type === 'array' && isArrayOfTables(obj[k])) {\n                tables += (tables && '\\n') + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);\n            }\n            else if (type === 'object') {\n                let tblKey = prefix ? `${prefix}.${key}` : key;\n                tables += (tables && '\\n') + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);\n            }\n            else {\n                preamble += key;\n                preamble += ' = ';\n                preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);\n                preamble += '\\n';\n            }\n        }\n    }\n    if (tableKey && (preamble || !tables)) // Create table only if necessary\n        preamble = preamble ? `[${tableKey}]\\n${preamble}` : `[${tableKey}]`;\n    return preamble && tables\n        ? `${preamble}\\n${tables}`\n        : preamble || tables;\n}\nexport function stringify(obj, { maxDepth = 1000, numbersAsFloat = false, strictTemporal = false } = {}) {\n    if (extendedTypeOf(obj) !== 'object') {\n        throw new TypeError('stringify can only be called with an object');\n    }\n    let str = stringifyTable(0, obj, '', maxDepth, numbersAsFloat, strictTemporal);\n    if (str[str.length - 1] !== '\\n')\n        return str + '\\n';\n    return str;\n}\n","import { fileStates, updateFileState } from '$lib/services/contents/file/state';\n\n/**\n * Regular expression matching the lines at the top of a YAML or TOML document that are blank or\n * hold only a comment.\n */\nconst COMMENT_OR_BLANK_LINES_REGEX = /^(?:[ \\t]*(?:#.*)?(?:\\n|$))*/;\n\n/**\n * Get the comments at the top of the given YAML or TOML document: the comment lines, along with the\n * blank lines between them, up to the last blank line before the first line of data. A blank line\n * is required: a comment right above the first line of data is taken as a comment on it and left\n * out, as the one written for the `comment` field option would otherwise be repeated on every save.\n * A document holding nothing else keeps all of its comments.\n * @param {string} str Document.\n * @returns {string | undefined} Comments, or `undefined` if there are none.\n */\nexport const getLeadingComment = (str) => {\n  // Most documents have no comments; skip looking for them\n  if (!str.trimStart().startsWith('#')) {\n    return undefined;\n  }\n\n  const [prefix] = /** @type {RegExpMatchArray} */ (str.match(COMMENT_OR_BLANK_LINES_REGEX));\n\n  // The comments end at the last blank line above the first line of data. Without one, they all\n  // belong to that line\n  const comment =\n    prefix.length === str.length ? str : (prefix.match(/^[\\s\\S]*\\n[ \\t]*\\n/)?.[0] ?? '');\n\n  return comment.trim() || undefined;\n};\n\n/**\n * Remember the comments at the top of the given document read from the given file, or forget the\n * ones remembered for the file if it has none. The CMS writes the whole file from the entry content\n * on every save, which drops the comments, so the ones at the top, typically a note about the file,\n * are written back.\n * @param {string} path File path.\n * @param {string} str YAML or TOML document, which is the whole file or its front matter.\n * @see https://github.com/decaporg/decap-cms/issues/5099\n */\nexport const rememberLeadingComment = (path, str) => {\n  const leadingComment = getLeadingComment(str);\n\n  // Most files have none to remember or forget; skip updating their state\n  if (leadingComment || fileStates.get(path)?.leadingComment) {\n    updateFileState(path, { leadingComment });\n  }\n};\n\n/**\n * Add the given comments at the top of the given document, followed by a blank line, so they’re\n * read back as the comments at the top rather than as the comment of the first line of data.\n * @param {string} str YAML or TOML document.\n * @param {string} [comment] Comments.\n * @returns {string} Document.\n */\nexport const prependLeadingComment = (str, comment) =>\n  comment ? (str ? `${comment}\\n\\n${str}` : comment) : str;\n","import { isObject } from '@sveltia/utils/object';\nimport { TomlDate } from 'smol-toml';\n\nimport {\n  getFloatText,\n  isFloatSource,\n  joinKeyPath,\n  mayHaveWholeNumberFloat,\n  rememberUniqueSource,\n  rememberValueSources,\n  restoreValueSources,\n} from '$lib/services/contents/file/value-sources';\n\n/**\n * @import { ValueSource, ValueSourceMap } from '$lib/types/private';\n */\n\n// The source text of the TOML values that the parsed content holds in another type is remembered\n// in the file state, like that of the values in a JSON or YAML file. A native date or time, e.g.\n// `2024-01-01T10:00:00Z`, `1979-05-27` or `12:30:00`, is held as a string, e.g.\n// `2024-01-01T10:00:00.000Z`, like a date in a JSON or YAML file, as the entry draft, its backup\n// and the fields handle strings. Writing it back as it was read means saving an entry neither turns\n// a date into a string nor changes how it’s written, e.g. by adding milliseconds or dropping\n// microseconds. A float that is a whole number, e.g. `10.0`, is held as the same `number` as an\n// integer, and is written back as a float rather than as an integer.\n\n/**\n * Regular expression matching the text of a TOML date, time or date-time, with or without an\n * offset. TOML 1.1 allows leaving out the seconds.\n * @see https://toml.io/en/v1.0.0#offset-date-time\n */\nconst TOML_DATE_TIME_REGEX =\n  /(?<![\\w.:+-])(?:\\d{4}-\\d{2}-\\d{2}(?:[Tt ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:[Zz]|[+-]\\d{2}:\\d{2})?)?|\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)(?![\\w.:+-])/g;\n\n/**\n * Regular expression matching the text of a TOML integer or float other than an infinity or a NaN.\n * A number in a date, a time, a bare key or a string counts as well.\n * @see https://toml.io/en/v1.0.0#integer\n * @see https://toml.io/en/v1.0.0#float\n */\nconst TOML_NUMBER_REGEX =\n  /(?<![\\w.:+-])[-+]?(?:0x[\\da-fA-F_]+|0o[0-7_]+|0b[01_]+|\\d[\\d_]*(?:\\.\\d[\\d_]*)?(?:[eE][-+]?\\d[\\d_]*)?)(?![\\w.:+-])/g;\n\n/**\n * Regular expression matching a TOML string, including a multiline one, or a comment, which can\n * hold text looking like a number.\n * @see https://toml.io/en/v1.0.0#string\n */\nconst TOML_STRING_OR_COMMENT_REGEX =\n  /\"\"\"[\\s\\S]*?\"\"\"(?!\")|'''[\\s\\S]*?'''(?!')|\"(?:[^\"\\\\\\n]|\\\\.)*\"|'[^'\\n]*'|#[^\\n]*/g;\n\n/**\n * Regular expression matching the text of a decimal TOML float, other than an infinity or a NaN.\n */\nconst TOML_FLOAT_REGEX = /^[-+]?\\d[\\d_]*(?:\\.\\d[\\d_]*)?(?:[eE][-+]?\\d[\\d_]*)?$/;\n\n/**\n * A TOML date written as the given source text, which tells more than the date itself: how the\n * date and the time are delimited and the fractional seconds beyond milliseconds.\n */\nclass SourcedTomlDate extends TomlDate {\n  /** @type {string} */\n  #source;\n\n  /**\n   * Create a date.\n   * @param {string} value Date as it’s held in the parsed content.\n   * @param {string} source Source text.\n   */\n  constructor(value, source) {\n    super(value);\n    this.#source = source;\n  }\n\n  /**\n   * Get the source text, which the TOML formatter writes.\n   * @returns {string} Source text.\n   */\n  toISOString() {\n    return this.#source;\n  }\n}\n\n/**\n * Create a TOML float that is a whole number, written as the given source text. The TOML formatter\n * writes a number that is an integer as an integer, but it writes a date as what `toISOString()`\n * returns, so the float is handed over as a date.\n * @param {number} value Number as it’s held in the parsed content.\n * @param {string} source Source text. Only a float representing the value is written as it is.\n * @returns {Date} Float.\n */\nconst createSourcedTomlFloat = (value, source) => {\n  const text = isFloatSource(source, value, TOML_FLOAT_REGEX) ? source : getFloatText(value);\n\n  return Object.assign(new Date(0), {\n    /**\n     * Get the source text, which the TOML formatter writes.\n     * @returns {string} Source text.\n     */\n    toISOString: () => text,\n  });\n};\n\n/**\n * Find the source text of each float in a TOML document that is a whole number, keyed by the number\n * the parsed content holds it as. Such a float can’t be told from an integer read as the same\n * number, so a number that is also written as an integer is left out. A float written in different\n * ways, e.g. `10.0` and `1e1`, is mapped to `null`. Strings and comments are left out, so e.g. a\n * title like `\"Top 10\"` doesn’t count as an integer.\n * @param {string} str TOML document.\n * @returns {Map<number, string | null>} Source text keyed by number.\n */\nconst findWholeNumberFloatSources = (str) => {\n  /** @type {Map<number, string | null>} */\n  const sources = new Map();\n  /** @type {Set<number>} */\n  const integers = new Set();\n\n  str\n    .replace(TOML_STRING_OR_COMMENT_REGEX, ' ')\n    .match(TOML_NUMBER_REGEX)\n    ?.forEach((source) => {\n      const isFloat = !/^[-+]?0[xob]/.test(source) && /[.eE]/.test(source);\n      const value = Number(source.replaceAll('_', ''));\n\n      if (!isFloat) {\n        integers.add(value);\n      } else if (Number.isInteger(value)) {\n        rememberUniqueSource(sources, value, source);\n      }\n    });\n\n  integers.forEach((value) => {\n    sources.delete(value);\n  });\n\n  return sources;\n};\n\n/**\n * Find the source text of each date, time and date-time in a TOML document, keyed by the string\n * the parsed content holds it as. Text that reads as the same value but is written in another way,\n * e.g. `2024-01-01T10:00:00Z` and `2024-01-01T10:00:00.000Z`, can’t be told apart, so such a value\n * is mapped to `null`. Text in a string or a comment counts as well, which only risks the same.\n * @param {string} str TOML document.\n * @returns {Map<string, string | null>} Source text keyed by value.\n */\nconst findDateSources = (str) => {\n  /** @type {Map<string, string | null>} */\n  const sources = new Map();\n\n  str.match(TOML_DATE_TIME_REGEX)?.forEach((source) => {\n    const date = new TomlDate(source);\n\n    if (date.isValid()) {\n      rememberUniqueSource(sources, date.toISOString(), source);\n    }\n  });\n\n  return sources;\n};\n\n/**\n * Collect the source text of the native dates and the floats that are whole numbers in the given\n * parsed TOML document.\n * @param {string} str TOML document.\n * @param {any} parsed Document parsed by the TOML library, which holds a native date as a\n * `TomlDate`.\n * @returns {ValueSourceMap} Source map. Empty if the document has no such value.\n */\nconst collectSources = (str, parsed) => {\n  /** @type {ValueSourceMap} */\n  const sourceMap = {};\n  /** @type {Map<string, string | null> | undefined} */\n  let dateSources;\n  /** @type {Map<number, string | null> | undefined} */\n  let floatSources;\n\n  /**\n   * Add the source text of the dates and floats in the given value to the map.\n   * @param {any} value Value.\n   * @param {string} keyPath Key path of the value.\n   */\n  const collect = (value, keyPath) => {\n    if (value instanceof TomlDate) {\n      const iso = value.toISOString();\n\n      dateSources ??= findDateSources(str);\n\n      // A date whose source text can’t be told is still written as a native date\n      sourceMap[keyPath] = { value: iso, source: dateSources.get(iso) ?? iso };\n    } else if (Number.isInteger(value)) {\n      floatSources ??= mayHaveWholeNumberFloat(str) ? findWholeNumberFloatSources(str) : new Map();\n\n      // A float written in different ways is still written as a float\n      if (floatSources.has(value)) {\n        sourceMap[keyPath] = { value, source: floatSources.get(value) ?? getFloatText(value) };\n      }\n    } else if (Array.isArray(value) || isObject(value)) {\n      Object.entries(value).forEach(([key, val]) => {\n        collect(val, joinKeyPath(keyPath, key));\n      });\n    }\n  };\n\n  collect(parsed, '');\n\n  return sourceMap;\n};\n\n/**\n * Remember the source text of the TOML values in the given file that the parsed content holds in\n * another type or can’t tell apart from others, if there are any.\n * @param {object} args Arguments.\n * @param {string} args.path File path.\n * @param {string} args.str TOML document, which is the front matter for a Markdown file.\n * @param {any} args.parsed Document parsed by the TOML library.\n */\nexport const rememberTomlValueSources = ({ path, str, parsed }) => {\n  rememberValueSources(path, collectSources(str, parsed));\n};\n\n/**\n * Check whether the given date to be saved is the one read from a TOML file. A Date & Time field\n * gives a native date, while any other field gives the string the parsed content holds.\n * @param {any} value Value to be saved.\n * @param {any} parsedValue Value in the parsed content.\n * @returns {boolean} Result.\n */\nconst isUnchanged = (value, parsedValue) =>\n  value === parsedValue || (value instanceof TomlDate && value.toISOString() === parsedValue);\n\n/**\n * Replace a value to be saved as a TOML document with one that the TOML formatter writes as its\n * source text, if it hasn’t changed since it was read from the file.\n * @param {any} value Value to be saved.\n * @param {ValueSource} valueSource Value read from the file at the same key path.\n * @returns {SourcedTomlDate | Date | undefined} Replacement, or `undefined` if the value has\n * changed.\n */\nconst replaceUnchangedTomlValue = (value, { value: parsedValue, source }) => {\n  if (typeof parsedValue === 'number') {\n    return value === parsedValue ? createSourcedTomlFloat(parsedValue, source) : undefined;\n  }\n\n  return isUnchanged(value, parsedValue) ? new SourcedTomlDate(parsedValue, source) : undefined;\n};\n\n/**\n * Copy the given content to be saved as a TOML document, replacing every value that hasn’t changed\n * since it was read from the file with one that the TOML formatter writes as its source text.\n * @param {any} content Content.\n * @param {ValueSourceMap} sourceMap Source map of the file.\n * @returns {any} Copy of the content.\n */\nexport const restoreTomlValueSources = (content, sourceMap) =>\n  restoreValueSources(content, sourceMap, replaceUnchangedTomlValue);\n","import { toRaw } from '@sveltia/utils/object';\nimport { escapeRegExp } from '@sveltia/utils/string';\nimport { parse as libParseTOML } from 'smol-toml';\nimport { parse as libParseYAML, parseDocument } from 'yaml';\n\nimport { customFileFormatRegistry } from '$lib/services/api/registries';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { isCollectionIndexFilePath } from '$lib/services/contents/collection/entries/index-file';\nimport { getCollectionFile } from '$lib/services/contents/collection/files';\nimport { getFrontMatterDelimiters, resolveFileConfig } from '$lib/services/contents/file/config';\nimport {\n  FRONTMATTER_DELIMITER_MAP,\n  FRONTMATTER_FORMATS,\n  getFormatSyntax,\n} from '$lib/services/contents/file/constants';\nimport {\n  mayHaveUnsafeInteger,\n  replaceBigInts,\n  reviveUnsafeInteger,\n} from '$lib/services/contents/file/integers';\nimport { rememberLeadingComment } from '$lib/services/contents/file/leading-comments';\nimport { fileStates, updateFileState } from '$lib/services/contents/file/state';\nimport { rememberTomlValueSources } from '$lib/services/contents/file/toml-sources';\nimport {\n  collectJSONFloatSources,\n  collectYAMLFloatSources,\n  mayHaveWholeNumberFloat,\n  rememberValueSources,\n  reviveWholeNumberFloat,\n} from '$lib/services/contents/file/value-sources';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import {\n * BaseEntryListItem,\n * InternalCollection,\n * InternalCollectionFile,\n * } from '$lib/types/private';\n * @import { FormatSyntax } from '$lib/services/contents/file/constants';\n * @import { FileFormat, FrontMatterFormat } from '$lib/types/public';\n */\n\n/**\n * A `JSON.parse()` reviver combining {@link reviveUnsafeInteger} and\n * {@link reviveWholeNumberFloat}.\n * @param {string} key Property name.\n * @param {any} value Parsed value.\n * @param {{ source?: string }} [context] Context, which holds the source text of a primitive value.\n * @returns {any} Value.\n */\nconst reviveNumber = (key, value, context) =>\n  reviveWholeNumberFloat(key, reviveUnsafeInteger(key, value, context), context);\n\n/**\n * Parse a JSON document using the built-in method. An integer that a `number` can’t represent\n * exactly is remembered, so it can be saved as it was. So is the source text of a float that is a\n * whole number, e.g. `10.0`, if the document is read from a file.\n * @param {string} str JSON document.\n * @param {string} [path] Path of the file the document is read from.\n * @returns {any} Parsed object.\n * @see {@link reviveUnsafeInteger}\n * @see {@link reviveWholeNumberFloat}\n */\nexport const parseJSON = (str, path) => {\n  if (path === undefined || !mayHaveWholeNumberFloat(str)) {\n    return mayHaveUnsafeInteger(str) ? JSON.parse(str, reviveUnsafeInteger) : JSON.parse(str);\n  }\n\n  const { value, sourceMap } = collectJSONFloatSources(JSON.parse(str, reviveNumber));\n\n  rememberValueSources(path, sourceMap);\n\n  return value;\n};\n\n/**\n * Parse a TOML document using a library. The TOML parser returns date fields as `Date` objects, but\n * we need strings to match the JSON and YAML parsers, so we have to parse twice. An integer that a\n * `number` can’t represent exactly, which the parser would otherwise reject, is remembered, so it\n * can be saved as it was. So is the source text of a date, and of a float that is a whole number,\n * e.g. `10.0`, if the document is read from a file.\n * @param {string} str TOML document.\n * @param {string} [path] Path of the file the document is read from.\n * @returns {any} Parsed object.\n * @see {@link replaceBigInts}\n * @see {@link rememberTomlValueSources}\n */\nexport const parseTOML = (str, path) => {\n  const parsed = replaceBigInts(libParseTOML(str, { integersAsBigInt: 'asNeeded' }));\n\n  if (path !== undefined) {\n    rememberTomlValueSources({ path, str, parsed });\n  }\n\n  return toRaw(parsed);\n};\n\n/**\n * Parse a YAML document using a library, like its `parse()` method, and remember the source text of\n * the floats in it that are whole numbers.\n * @param {string} str YAML document.\n * @param {Record<string, any> | undefined} options Parsing options.\n * @param {string} path Path of the file the document is read from.\n * @returns {any} Parsed object.\n * @throws {Error} When the document could not be parsed.\n * @see https://github.com/eemeli/yaml/blob/main/src/public-api.ts\n */\nconst parseYAMLWithFloatSources = (str, options, path) => {\n  const doc = parseDocument(str, options);\n\n  // eslint-disable-next-line no-console\n  doc.warnings.forEach((warning) => console.warn(warning));\n\n  if (doc.errors.length) {\n    throw doc.errors[0];\n  }\n\n  rememberValueSources(path, collectYAMLFloatSources(doc));\n\n  return doc.toJS(options);\n};\n\n/**\n * Parse a YAML document using a library. An integer that a `number` can’t represent exactly is\n * remembered, so it can be saved as it was. So is the source text of a float that is a whole\n * number, e.g. `10.0`, if the document is read from a file.\n * @param {string} str YAML document.\n * @param {object} [options] Parsing options.\n * @param {string} [path] Path of the file the document is read from.\n * @returns {any} Parsed object.\n * @see {@link replaceBigInts}\n * @see {@link collectYAMLFloatSources}\n */\nexport const parseYAML = (str, options, path) => {\n  const hasUnsafeInteger = mayHaveUnsafeInteger(str);\n  const _options = hasUnsafeInteger ? { ...options, intAsBigInt: true } : options;\n\n  const parsed =\n    path !== undefined && mayHaveWholeNumberFloat(str)\n      ? parseYAMLWithFloatSources(str, _options, path)\n      : libParseYAML(str, _options);\n\n  return hasUnsafeInteger ? replaceBigInts(parsed) : parsed;\n};\n\n/**\n * Detect the Markdown front matter serialization format by checking the first line of the content,\n * which is the opening delimiter of a front matter block, as Netlify/Decap CMS does. A line that\n * only starts with a delimiter, e.g. a Hugo shortcode like `{{< figure >}}`, doesn’t count.\n * @param {string} text File content.\n * @returns {FrontMatterFormat} Determined format.\n */\nexport const detectFrontMatterFormat = (text) => {\n  const firstLine = text.split('\\n', 1)[0].trim();\n\n  return (\n    FRONTMATTER_FORMATS.find((format) => firstLine === FRONTMATTER_DELIMITER_MAP[format][0]) ??\n    'yaml-frontmatter'\n  );\n};\n\n/**\n * Regular expression to match JSON front matter written by an earlier version of Sveltia CMS, which\n * wrapped a complete JSON object in the `{` and `}` delimiters, doubling the braces. The object is\n * followed by the closing delimiter on a line of its own, then by the end of the file or a blank\n * line and the body. A line break inside a JSON value is always escaped, so this can’t match\n * within the object.\n */\nconst DOUBLE_BRACE_JSON_FRONT_MATTER_REGEX =\n  /^\\{\\n(?<head>\\{[\\s\\S]*?\\})\\n\\}(?:\\n\\n(?<body>[\\s\\S]*))?$/;\n\n/**\n * Parse the head of JSON front matter. Like Netlify/Decap CMS, the formatter strips the outer\n * braces of the object when they double as the delimiters, so add them back if they are missing. A\n * complete object, which can come within custom delimiters, is parsed as is.\n * @param {string} head Front matter head.\n * @param {string} [path] Path of the file the front matter is read from.\n * @returns {any} Parsed object.\n */\nconst parseJSONFrontMatterHead = (head, path) => {\n  const trimmedHead = head.trim();\n\n  return parseJSON(trimmedHead.startsWith('{') ? trimmedHead : `{${trimmedHead}}`, path);\n};\n\n/**\n * Wrap the given parser so it also remembers the comments at the top of a document read from a\n * file.\n * @param {(str: string, path?: string) => any} parser YAML or TOML parser.\n * @returns {(str: string, path?: string) => any} Parser.\n */\nconst withLeadingComment = (parser) => (str, path) => {\n  const parsed = parser(str, path);\n\n  if (path !== undefined) {\n    rememberLeadingComment(path, str);\n  }\n\n  return parsed;\n};\n\n/**\n * Parser for each syntax, taking a document and the path of the file it’s read from.\n * @type {Record<FormatSyntax, (str: string, path?: string) => any>}\n */\nconst PARSERS = {\n  yaml: withLeadingComment((str, path) => parseYAML(str, undefined, path)),\n  toml: withLeadingComment(parseTOML),\n  json: parseJSON,\n};\n\n/**\n * Parser for the head of front matter in each syntax.\n * @type {Record<FormatSyntax, (head: string, path?: string) => any>}\n */\nconst FRONT_MATTER_PARSERS = { ...PARSERS, json: parseJSONFrontMatterHead };\n/**\n * Cache for front matter regexes, keyed by `${sd}|${ed}` (escaped delimiter pair). Avoids\n * rebuilding the same regex for every entry in a collection (all entries share identical\n * delimiters).\n * @type {Map<string, RegExp>}\n */\nconst frontMatterRegexCache = new Map();\n\n/**\n * Parse front matter from a Markdown file, and tell whether the file has a front matter block.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only.\n * @param {boolean} [args.isIndexFile] Whether the file is the collection’s special index file,\n * which can have a format of its own.\n * @param {FrontMatterFormat} args.format Front matter format.\n * @param {string} args.text File content.\n * @param {string} [args.path] File path, given to remember the source text of the floats that are\n * whole numbers.\n * @returns {{ content: Record<string, any>, hasFrontMatter: boolean }} Parsed front matter and\n * body, and whether the file has a front matter block.\n * @throws {Error} When the front matter block could not be parsed.\n */\nconst parseFrontMatterBlock = ({ collection, collectionFile, isIndexFile, format, text, path }) => {\n  const {\n    format: _format,\n    fmDelimiters,\n    bodyField: { key: bodyKey = 'body', inline: bodyInline = false } = {},\n  } = resolveFileConfig({ collection, collectionFile, isIndexFile });\n\n  const [startDelimiter, endDelimiter] =\n    (_format === 'frontmatter'\n      ? getFrontMatterDelimiters({ format, delimiter: fmDelimiters })\n      : fmDelimiters) ?? FRONTMATTER_DELIMITER_MAP['yaml-frontmatter'];\n\n  const sd = escapeRegExp(startDelimiter);\n  const ed = escapeRegExp(endDelimiter);\n  const cacheKey = `${sd}|${ed}`;\n\n  // Front matter matching: allow an empty head, including no line at all between the delimiters\n  // (e.g. Jekyll’s `---\\n---`), and only match a block at the start of the file. Trailing spaces or\n  // tabs after a delimiter are ignored, as other front matter parsers do.\n  const regex = getOrCreate(\n    frontMatterRegexCache,\n    cacheKey,\n    () =>\n      new RegExp(\n        `^${sd}[ \\t]*\\n(?:(?<head>[\\\\s\\\\S]*?)\\n)?${ed}[ \\t]*(?:\\n(?<body>[\\\\s\\\\S]*))?$`,\n        's',\n      ),\n  );\n\n  // Blank lines or spaces before the front matter block are ignored\n  const trimmedText = text.trimStart();\n\n  const groups =\n    (format === 'json-frontmatter' && startDelimiter === '{' && endDelimiter === '}'\n      ? trimmedText.match(DOUBLE_BRACE_JSON_FRONT_MATTER_REGEX)?.groups\n      : undefined) ?? trimmedText.match(regex)?.groups;\n\n  if (!groups) {\n    // Support Markdown without a front matter block, particularly for VitePress. The body keeps its\n    // leading whitespace, e.g. an indented code block. The text can be an empty string, but it’s\n    // okay to return an empty body\n    return { content: { [bodyKey]: text }, hasFrontMatter: false };\n  }\n\n  const { head = '', body } = groups;\n  const syntax = FRONTMATTER_FORMATS.includes(format) ? getFormatSyntax(format) : undefined;\n  let parsedHead = syntax ? FRONT_MATTER_PARSERS[syntax](head, path) : {};\n\n  // A Markdown file starting with blank lines or spaces before a delimiter line, e.g. a thematic\n  // break, could be saved without front matter by an earlier version, which only protected a body\n  // starting with the delimiter itself. What lies between that line and the next one is then text,\n  // which YAML reads as a string. A front matter block is a map, so such a file is read as having\n  // no front matter, as it was meant to\n  if (\n    text !== trimmedText &&\n    head.trim() &&\n    parsedHead !== null &&\n    parsedHead !== undefined &&\n    (typeof parsedHead !== 'object' || Array.isArray(parsedHead))\n  ) {\n    // Forget what parsing the text remembered about the file as its front matter, e.g. a heading\n    // taken as a comment, which would otherwise be written in a new front matter block on a save\n    if (path !== undefined) {\n      updateFileState(path, { leadingComment: undefined, valueSources: undefined });\n    }\n\n    return { content: { [bodyKey]: text }, hasFrontMatter: false };\n  }\n\n  if (!parsedHead || typeof parsedHead !== 'object' || Array.isArray(parsedHead)) {\n    parsedHead = {};\n  }\n\n  const content = {\n    ...parsedHead,\n    // The formatter inserts a blank line between the closing delimiter and the body, so the regex\n    // above leaves that blank line as a leading line break. Strip it to make the value a faithful\n    // round-trip of what was written; otherwise a freshly-opened draft looks modified. The front\n    // matter takes precedence over the text below it. With `body_field.inline` on, text below is\n    // still read when the front matter lacks the key, so it’s moved inline on a Save rather than\n    // lost, but no empty body is added to a file that has none.\n    ...(!Object.hasOwn(parsedHead, bodyKey) && (!bodyInline || body?.trim())\n      ? { [bodyKey]: body?.replace(/^\\n/, '') }\n      : {}),\n  };\n\n  return { content, hasFrontMatter: true };\n};\n\n/**\n * Parse front matter from a Markdown file.\n * @param {Parameters<typeof parseFrontMatterBlock>[0]} args Arguments. See\n * {@link parseFrontMatterBlock}.\n * @returns {Record<string, any>} Parsed front matter and body.\n * @throws {Error} When the front matter block could not be parsed.\n */\nexport const parseFrontMatter = (args) => parseFrontMatterBlock(args).content;\n\n/**\n * Resolve the collection, collection file and format of the given entry file.\n * @param {Pick<BaseEntryListItem, 'path' | 'folder'>} file Entry file list item.\n * @returns {{ collection: InternalCollection, collectionFile: InternalCollectionFile | undefined,\n * isIndexFile: boolean, format: FileFormat }} Collection, collection file, whether the file is the\n * collection’s special index file, and the format.\n * @throws {Error} When the collection or the collection file can’t be found.\n */\nconst resolveEntryFile = ({ path, folder: { collectionName, fileName } }) => {\n  const collection = getCollection(collectionName);\n\n  const collectionFile =\n    collection && fileName ? getCollectionFile(collection, fileName) : undefined;\n\n  if (!collection) {\n    throw new Error('Collection not found');\n  }\n\n  if (fileName && !collectionFile) {\n    throw new Error('Collection file not found');\n  }\n\n  // The collection’s special index file can have a format of its own\n  const isIndexFile = !collectionFile && isCollectionIndexFilePath(collection, path);\n  const { format } = resolveFileConfig({ collection, collectionFile, isIndexFile });\n\n  return { collection, collectionFile, isIndexFile, format };\n};\n\n/**\n * Check whether the given entry file is read with a parser registered with\n * `CMS.registerCustomFormat()`. What such a parser returns can change from one load to the next\n * without the configuration changing, so its results are never cached.\n * @param {Pick<BaseEntryListItem, 'path' | 'folder'>} file Entry file list item.\n * @returns {boolean} Result. `false` if the file’s collection can’t be found, as it’s then not\n * parsed at all.\n */\nexport const hasCustomParser = (file) => {\n  try {\n    return !!customFileFormatRegistry.get(resolveEntryFile(file).format)?.parser;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Parse raw content with given file details.\n * @param {BaseEntryListItem} entry Entry file list item.\n * @returns {Promise<any>} Parsed content.\n * @throws {Error} When the content could not be parsed.\n */\nexport const parseEntryFile = async ({ text = '', path, folder }) => {\n  const resolved = resolveEntryFile({ path, folder });\n  const { collection, collectionFile, isIndexFile } = resolved;\n  let { format } = resolved;\n\n  // Forget what was read from an earlier version of the file\n  fileStates.delete(path);\n\n  // Normalize line breaks. The leading whitespace is only dropped where it’s meaningless: the\n  // content of a raw file, and the body of a file without front matter, keep theirs, e.g. an\n  // indented code block at the start of a Markdown file, as a save keeps it\n  text = text.trimEnd().replace(/\\r\\n?/g, '\\n');\n\n  const trimmedText = text.trimStart();\n  const customParser = customFileFormatRegistry.get(format)?.parser;\n\n  if (customParser) {\n    return customParser(trimmedText);\n  }\n\n  // Raw format: return the content as-is\n  if (format === 'raw') {\n    return { body: text };\n  }\n\n  try {\n    const isDetected = format === 'frontmatter';\n\n    if (isDetected) {\n      format = detectFrontMatterFormat(trimmedText);\n    }\n\n    if (FRONTMATTER_FORMATS.includes(/** @type {any} */ (format))) {\n      const { content, hasFrontMatter } = parseFrontMatterBlock({\n        collection,\n        collectionFile,\n        isIndexFile,\n        format: /** @type {FrontMatterFormat} */ (format),\n        text,\n        path,\n      });\n\n      // Remembered, so the file is saved back in the same format. A file without a front matter\n      // block gets the default one, as a new file does\n      if (isDetected && hasFrontMatter) {\n        updateFileState(path, { format: /** @type {FrontMatterFormat} */ (format) });\n      }\n\n      return content;\n    }\n\n    // Any other format with a syntax is read as a whole\n    const syntax = getFormatSyntax(format);\n\n    if (syntax) {\n      return PARSERS[syntax](trimmedText, path);\n    }\n  } catch (/** @type {any} */ ex) {\n    throw new Error(`${path} could not be parsed due to ${ex.name}: ${ex.message}`);\n  }\n\n  if (customFileFormatRegistry.has(format)) {\n    throw new Error(\n      `${path} could not be parsed, as no \\`fromFile\\` method was registered for the custom ` +\n        `“${format}” format with \\`CMS.registerCustomFormat()\\``,\n    );\n  }\n\n  throw new Error(`${path} could not be parsed due to an unknown format: ${format}`);\n};\n","import { sleep } from '@sveltia/utils/misc';\n\n/**\n * @import { ConcurrencyLimiter, ConcurrencyLimiterTaskOptions } from '$lib/types/private';\n */\n\n/**\n * Hand control back to the browser so it can paint and handle input, then continue. Long\n * CPU-bound loops call this between chunks of work, which keeps the tab responsive and the progress\n * indicator moving. `scheduler.yield()` resumes ahead of other queued tasks where it’s supported;\n * a zero-delay timeout is used elsewhere.\n * @returns {Promise<void>} Resolves once the browser has had a chance to run other work.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Scheduler/yield\n */\nexport const yieldToMain = async () => {\n  const { scheduler } = /** @type {{ scheduler?: { yield?: () => Promise<void> } }} */ (globalThis);\n\n  if (typeof scheduler?.yield === 'function') {\n    await scheduler.yield();\n  } else {\n    await sleep();\n  }\n};\n\n/**\n * Run the given task for each item, one after another, yielding to the browser whenever the tasks\n * have kept the main thread busy for a while. Use this for a large batch of synchronous work that\n * would otherwise block the main thread for the whole batch. The work is split by time rather than\n * by a number of items, as items can take very different times: a large file takes much longer to\n * parse than a small one. The tasks may be asynchronous as well.\n * @template T\n * @param {T[]} items Items to process.\n * @param {(item: T) => Promise<void> | void} task Task to be performed for each item.\n * @param {object} [options] Options.\n * @param {number} [options.budget] How long to keep the main thread busy before yielding, in\n * milliseconds. The default is the threshold of a long task: yielding more often would slow the\n * work down where `scheduler.yield()` isn’t supported, as a timeout takes a few milliseconds.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/PerformanceLongTaskTiming\n */\nexport const runInChunks = async (items, task, { budget = 50 } = {}) => {\n  let start = performance.now();\n\n  for (let index = 0; index < items.length; index += 1) {\n    if (performance.now() - start >= budget) {\n      // eslint-disable-next-line no-await-in-loop\n      await yieldToMain();\n      start = performance.now();\n    }\n\n    // eslint-disable-next-line no-await-in-loop\n    await task(items[index]);\n  }\n};\n\n/**\n * Create a guard telling whether an async call is still the latest one. A slow call made earlier,\n * e.g. a lookup for an asset focused before, can finish after a later one, and its result must not\n * replace the later one’s. Call `next()` at the start of each call, and check the function it\n * returns after every `await`.\n * @returns {{ next: () => () => boolean }} Guard. `next()` starts a new call and returns a function\n * telling whether no call has been started since.\n * @example\n * const guard = createLatestGuard();\n *\n * const update = async () => {\n *   const isLatest = guard.next();\n *   const result = await fetchSomething();\n *\n *   if (!isLatest()) {\n *     return;\n *   }\n *\n *   // Use the result\n * };\n */\nexport const createLatestGuard = () => {\n  let count = 0;\n\n  return {\n    /**\n     * Start a new call.\n     * @returns {() => boolean} Function telling whether no call has been started since.\n     */\n    next: () => {\n      count += 1;\n\n      const call = count;\n\n      return () => call === count;\n    },\n  };\n};\n\n/**\n * Create a function that runs the tasks given to it with at most a certain number of them in flight\n * at the same time, starting each queued task as soon as an earlier one has settled. Use this for\n * memory-heavy work requested from many places at once, such as decoding full-size images, which\n * would otherwise all be held in memory together.\n * @param {number} concurrency Maximum number of tasks in flight.\n * @param {object} [options] Options.\n * @param {boolean} [options.lastInFirstOut] Whether to start the most recently queued task first,\n * rather than the oldest one. This suits work requested for what’s on screen, like the thumbnails\n * of a list being scrolled: what was asked for last is what the user is looking at now.\n * @returns {ConcurrencyLimiter} Function running a task when there is room, and resolving or\n * rejecting with its outcome. Its `prioritize()` method makes the queued task with the given key,\n * if any, the next one to start, e.g. when it’s asked for again.\n */\nexport const createConcurrencyLimiter = (concurrency, { lastInFirstOut = false } = {}) => {\n  let running = 0;\n  /** @type {{ start: () => void, key: any }[]} */\n  const queue = [];\n\n  /**\n   * Run the given task when there is room.\n   * @template T\n   * @param {() => Promise<T>} task Task.\n   * @param {ConcurrencyLimiterTaskOptions} [options] Options.\n   * @returns {Promise<T>} Outcome of the task.\n   */\n  const limit = async (task, { key = undefined } = {}) => {\n    if (running >= concurrency) {\n      await /** @type {Promise<void>} */ (\n        new Promise((resolve) => {\n          queue.push({ start: resolve, key });\n        })\n      );\n    } else {\n      running += 1;\n    }\n\n    try {\n      return await task();\n    } finally {\n      // Hand the slot straight to the next task in the queue, if any, so the count stays the same\n      const next = lastInFirstOut ? queue.pop() : queue.shift();\n\n      if (next) {\n        next.start();\n      } else {\n        running -= 1;\n      }\n    }\n  };\n\n  /**\n   * Make the queued task with the given key, if any, the next one to start.\n   * @param {any} key Task key.\n   */\n  const prioritize = (key) => {\n    // A task queued without a key can’t be singled out\n    const index = key === undefined ? -1 : queue.findIndex((item) => item.key === key);\n\n    if (index > -1) {\n      const [item] = queue.splice(index, 1);\n\n      if (lastInFirstOut) {\n        queue.push(item);\n      } else {\n        queue.unshift(item);\n      }\n    }\n  };\n\n  return Object.assign(limit, { prioritize });\n};\n","import { generateUUID } from '@sveltia/utils/crypto';\nimport { isObject } from '@sveltia/utils/object';\nimport { escapeRegExp } from '@sveltia/utils/string';\n\nimport { version } from '$lib/services/app';\nimport { cmsConfigVersion } from '$lib/services/config';\nimport {\n  getIndexFile,\n  isCollectionIndexFilePath,\n} from '$lib/services/contents/collection/entries/index-file';\nimport { resolveCollectionAndFile } from '$lib/services/contents/collection/files';\nimport { getNestedIndexFileName } from '$lib/services/contents/collection/nested';\nimport { hasRootField } from '$lib/services/contents/entry/fields';\nimport { convertMapLists, getMapKeyField } from '$lib/services/contents/fields/list/map';\nimport { mayHaveUnsafeInteger } from '$lib/services/contents/file/integers';\nimport { hasCustomParser, parseEntryFile } from '$lib/services/contents/file/parse';\nimport { fileStates, setFileState } from '$lib/services/contents/file/state';\nimport {\n  usesMultiFileStructure,\n  usesSingleFileStructure,\n} from '$lib/services/contents/i18n/config';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { flattenKeys } from '$lib/services/utils/object';\nimport { runInChunks } from '$lib/services/utils/scheduling';\n\n/**\n * @import {\n * BaseEntryListItem,\n * Entry,\n * InternalCollection,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * ParsedFileContent,\n * RepositoryFileMetadata,\n * } from '$lib/types/private';\n * @import { Field, RawEntryContent } from '$lib/types/public';\n */\n\n/**\n * Check if the given file path is Hugo’s special index file: `_index.md` or `_index.{{locale}}.md`.\n * @param {string} path File path to be tested.\n * @returns {boolean} Result.\n */\nexport const isIndexFile = (path) => /\\/_index(?:\\.[\\w-]+)?\\.md$/.test(path);\n\n/**\n * Regex to split a `subPath` template into literal text and template tags. Unlike\n * `TEMPLATE_TAG_REGEX`, it also matches an empty `{{}}` tag and a tag spanning a line break.\n */\nconst SLUG_TEMPLATE_TAG_REGEX = /{{([^]*?)}}/;\n/** @type {Map<string, RegExp>} */\nconst slugRegexCache = new Map();\n\n/**\n * Determine the slug for the given entry content.\n * @param {object} args Arguments.\n * @param {string} args.subPath File path without the collection folder, locale and extension. It’s\n * a slug in most cases, but it may be a path containing slash(es) when the entry collection’s\n * subpath is configured.\n * @param {string | undefined} args.subPathTemplate Collection’s `subPath` configuration.\n * @returns {string} Slug.\n * @see https://decapcms.org/docs/configuration-options/#slug\n * @see https://decapcms.org/docs/collection-folder/#folder-collections-path\n * @see https://sveltiacms.app/en/docs/collections/entries\n */\nexport const getSlug = ({ subPath, subPathTemplate }) => {\n  if (subPathTemplate?.includes('{{slug}}')) {\n    const regex = getOrCreate(slugRegexCache, subPathTemplate, () => {\n      const regexPattern = subPathTemplate\n        .split(SLUG_TEMPLATE_TAG_REGEX)\n        .map((part, index) => {\n          // The odd parts are the tags captured by the split; an unclosed `{{` stays literal\n          if (index % 2 === 0) {\n            return escapeRegExp(part);\n          }\n\n          return part === 'slug' ? '([^/]+)' : '[^/]+?';\n        })\n        .join('');\n\n      return new RegExp(`^${regexPattern}$`);\n    });\n\n    const [, slug] = subPath.match(regex) ?? [];\n\n    if (slug) {\n      return slug;\n    }\n  }\n\n  return subPath;\n};\n\n/**\n * Check if the given value refers back to itself, e.g. through a YAML alias pointing at one of its\n * own ancestors like `meta: &m { self: *m }`. Such content can’t be flattened or saved. A value\n * referred to from several places, which isn’t circular, is fine.\n * @param {unknown} value Parsed value.\n * @param {Set<object>} [ancestors] Objects on the path from the root to the value.\n * @returns {boolean} Result.\n */\nexport const hasCircularReference = (value, ancestors = new Set()) => {\n  if (value === null || typeof value !== 'object') {\n    return false;\n  }\n\n  if (ancestors.has(value)) {\n    return true;\n  }\n\n  ancestors.add(value);\n\n  const found = Object.values(value).some((child) => hasCircularReference(child, ancestors));\n\n  ancestors.delete(value);\n\n  return found;\n};\n\n/**\n * Map of entry file paths to the content parsed from them, collected while the files are parsed so\n * it can be cached along with the files.\n * @typedef {Map<string, ParsedFileContent>} ParsedFileMap\n */\n\n/**\n * Get the key identifying what a file’s content is parsed for: the CMS version, as a new version\n * may parse a file differently, and the CMS configuration, which sets the format of each file.\n * @returns {string} Key.\n */\nexport const getParsedContentKey = () => `${version}\\n${cmsConfigVersion.current}`;\n\n/**\n * Add the content parsed from a file to the given map, so it can be cached.\n * @param {object} args Arguments.\n * @param {ParsedFileMap} args.parsedFileMap Map to add the content to.\n * @param {string} args.path File path.\n * @param {string} args.key What the content was parsed for. See {@link getParsedContentKey}.\n * @param {RawEntryContent} args.content Parsed content.\n */\nconst cacheParsedContent = ({ parsedFileMap, path, key, content }) => {\n  try {\n    parsedFileMap.set(path, {\n      key,\n      // Copied, as the content is processed further, and the copy has to be cached as parsed\n      content: structuredClone(content),\n      // Along with what is remembered about the file, so it’s saved back the same way\n      ...fileStates.get(path),\n    });\n  } catch {\n    // Content the database can’t store either; the file is just parsed again next time\n  }\n};\n\n/**\n * Parse the raw content from the file and handle any errors. Content cached from a previous load\n * is used instead if it was parsed for the same CMS version and configuration, as parsing every\n * file is the bulk of the work of loading the site data.\n * @param {BaseEntryListItem} file Entry file list item.\n * @param {Error[]} errors List of parse errors.\n * @param {ParsedFileMap} [parsedFileMap] Map to add the content parsed from the file to, so it can\n * be cached. A file whose content comes from the cache isn’t added.\n * @returns {Promise<RawEntryContent | undefined>} Parsed content or undefined if parsing failed.\n */\nexport const parseFileContent = async (file, errors, parsedFileMap) => {\n  const { path, parsed } = file;\n  const key = getParsedContentKey();\n  const customParser = hasCustomParser(file);\n\n  if (parsed?.key === key && !customParser) {\n    const { key: _key, content, ...state } = parsed;\n\n    // Remembered, so the file is saved back the way it was written, as when it was parsed: in the\n    // same front matter format, with the floats that are whole numbers and the comments at the top\n    setFileState(path, state);\n\n    return content;\n  }\n\n  try {\n    // A file whose content couldn’t be read, e.g. because it’s too large, has no text. Parsing it\n    // as an empty file would load an empty entry, and saving that would wipe the file\n    if (file.text === undefined) {\n      throw new Error(`${path} could not be read.`);\n    }\n\n    const content = await parseEntryFile(file);\n\n    if (hasCircularReference(content)) {\n      throw new Error(`${path} could not be parsed, as it contains a circular reference.`);\n    }\n\n    // Parsing a file remembers the source text of any integer a `number` can’t represent exactly,\n    // which is what the integer is saved as, so such a file has to be parsed every time\n    if (parsedFileMap && !customParser && !mayHaveUnsafeInteger(file.text)) {\n      cacheParsedContent({ parsedFileMap, path, key, content });\n    }\n\n    return content;\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n    errors.push(ex);\n    return undefined;\n  }\n};\n\n/**\n * Transform root field content.\n * @param {object} args Arguments.\n * @param {RawEntryContent} args.rawContent Raw content from the file.\n * @param {Field[]} args.fields Collection fields.\n * @param {boolean} args.i18nSingleFile Whether i18n single file structure is used.\n * @param {(value: any) => boolean} args.validate Function to validate content items.\n * @returns {RawEntryContent | undefined} Transformed content.\n */\nexport const transformRoot = ({ rawContent, fields, i18nSingleFile, validate }) => {\n  const fieldName = fields[0].name;\n\n  if (i18nSingleFile) {\n    if (!isObject(rawContent) || !Object.values(rawContent).every(validate)) {\n      return undefined;\n    }\n\n    return Object.fromEntries(\n      Object.entries(rawContent).map(([locale, content]) => [locale, { [fieldName]: content }]),\n    );\n  }\n\n  if (!validate(rawContent)) {\n    return undefined;\n  }\n\n  return { [fieldName]: rawContent };\n};\n\n/**\n * Normalize `single_file_default_root` content into the standard locale-keyed format used by the\n * `single_file` structure. Root-level entries (excluding non-default locale keys) become the\n * default locale’s content, and each non-default locale key becomes that locale’s content.\n * @param {RawEntryContent} rawContent Raw content from the file.\n * @param {InternalLocaleCode[]} allLocales All available locales.\n * @param {InternalLocaleCode} defaultLocale The default locale.\n * @returns {RawEntryContent | undefined} Normalized locale-keyed content or undefined if invalid.\n */\nexport const normalizeDefaultRootContent = (rawContent, allLocales, defaultLocale) => {\n  if (!isObject(rawContent)) {\n    return undefined;\n  }\n\n  const nonDefaultLocales = allLocales.filter((locale) => locale !== defaultLocale);\n\n  // Root-level entries excluding non-default locale keys = default locale content\n  const defaultContent = Object.fromEntries(\n    Object.entries(rawContent).filter(([key]) => !nonDefaultLocales.includes(key)),\n  );\n\n  /** @type {RawEntryContent} */\n  const result = { [defaultLocale]: defaultContent };\n\n  nonDefaultLocales.forEach((locale) => {\n    if (isObject(rawContent[locale])) {\n      result[locale] = rawContent[locale];\n    }\n  });\n\n  return result;\n};\n\n/**\n * Wrap the content of a top-level field in an object under the field name, as if the field were\n * stored like any other field.\n * @param {RawEntryContent} rawContent Raw content from the file.\n * @param {Field[]} fields Collection fields.\n * @param {boolean} i18nSingleFile Whether i18n single file structure is used.\n * @returns {RawEntryContent | undefined} Transformed content or undefined if invalid.\n */\nconst transformRootContent = (rawContent, fields, i18nSingleFile) => {\n  const args = { rawContent, fields, i18nSingleFile };\n\n  // Handle a special case: top-level List field\n  if (hasRootField(fields, 'list')) {\n    // A keyed list is stored as a map, but a list saved before the option was added is an array\n    return transformRoot({\n      ...args,\n      validate: getMapKeyField(fields[0])\n        ? (value) => isObject(value) || Array.isArray(value)\n        : Array.isArray,\n    });\n  }\n\n  // Handle a special case: top-level KeyValue field\n  if (hasRootField(fields, 'keyvalue')) {\n    return transformRoot({\n      ...args,\n      // Check if the key-value pairs are in an object format and each value is a string\n      // eslint-disable-next-line jsdoc/require-jsdoc\n      validate: (value) =>\n        isObject(value) && Object.values(value).every((val) => typeof val === 'string'),\n    });\n  }\n\n  return isObject(rawContent) ? rawContent : undefined;\n};\n\n/**\n * Transform raw content to handle special cases like root List and root KeyValue fields, as well\n * as List fields stored as a map, which become list items like those of any other List field.\n * @param {RawEntryContent} rawContent Raw content from the file.\n * @param {Field[]} fields Collection fields.\n * @param {boolean} i18nSingleFile Whether i18n single file structure is used.\n * @returns {RawEntryContent | undefined} Transformed content or undefined if invalid.\n */\nexport const transformRawContent = (rawContent, fields, i18nSingleFile) => {\n  const content = transformRootContent(rawContent, fields, i18nSingleFile);\n\n  if (!content) {\n    return undefined;\n  }\n\n  if (!i18nSingleFile) {\n    return convertMapLists(content, fields, true);\n  }\n\n  return Object.fromEntries(\n    Object.entries(content).map(([locale, localizedContent]) => [\n      locale,\n      convertMapLists(localizedContent, fields, true),\n    ]),\n  );\n};\n\n/**\n * Check if the file should be skipped based on Hugo index file rules.\n * @param {string} path File path.\n * @param {string | undefined} fileName Collection file name.\n * @param {InternalCollection} collection Collection configuration.\n * @param {string | undefined} subPathTemplate Sub path template.\n * @param {string} extension File extension.\n * @returns {boolean} True if the file should be skipped.\n */\nexport const shouldSkipIndexFile = (path, fileName, collection, subPathTemplate, extension) => {\n  // Special constraint: if template ends with _index and file follows _index pattern,\n  // only .md files are allowed (Hugo constraint)\n  if (\n    subPathTemplate?.split('/').pop() === '_index' &&\n    /\\/_index(?:\\.[\\w-]+)?\\.[\\w]+$/.test(path) &&\n    extension !== 'md'\n  ) {\n    return true;\n  }\n\n  if (!isIndexFile(path)) {\n    return false;\n  }\n\n  // Skip Hugo’s special `_index.md` file that shouldn’t appear in a collection. Localized index\n  // files like `_index.en.md` are also excluded by default. Exceptions:\n  // 1. The collection is a file/singleton collection\n  // 2. The collection is an entry collection and index file inclusion is enabled\n  // 3. The collection is an entry collection and the `path` option value ends with `_index` and\n  // the extension is `md`\n  // 4. The collection has nested entries, and every entry is stored as `_index.md`\n  return !(\n    !!fileName ||\n    getIndexFile(collection)?.name === '_index' ||\n    (subPathTemplate?.split('/').pop() === '_index' && extension === 'md') ||\n    getNestedIndexFileName(collection) === '_index'\n  );\n};\n\n/**\n * Extract subPath and locale information from the file path.\n * @param {object} args Arguments.\n * @param {BaseEntryListItem} args.file Entry file list item.\n * @param {string} [args.fileName] Collection file name.\n * @param {RegExp} [args.fullPathRegEx] Full path regex for parsing.\n * @param {InternalLocaleCode} args.defaultLocale Default locale.\n * @param {boolean} args.isMultiFileStructure Whether using multi-file i18n structure.\n * @returns {{ subPath: string | undefined, locale: InternalLocaleCode | undefined }} Path info.\n */\nexport const extractPathInfo = ({\n  file,\n  fileName,\n  fullPathRegEx,\n  defaultLocale,\n  isMultiFileStructure,\n}) => {\n  const {\n    path,\n    folder: { filePathMap },\n  } = file;\n\n  if (fileName) {\n    if (isMultiFileStructure) {\n      const [locale, subPath] =\n        Object.entries(filePathMap ?? {}).find(([, locPath]) => locPath === path) ?? [];\n\n      return { subPath, locale };\n    }\n\n    return { subPath: path, locale: undefined };\n  }\n\n  if (!fullPathRegEx) {\n    return { subPath: undefined, locale: undefined };\n  }\n\n  // If the `omit_default_locale_from_file_path` i18n option is enabled, the matching comes with\n  // the `locale` group being `undefined` for the default locale, so we need a fallback for it\n  const match = path.match(fullPathRegEx);\n\n  if (!match?.groups) {\n    return { subPath: undefined, locale: undefined };\n  }\n\n  const { subPath, locale = defaultLocale } = match.groups;\n\n  return { subPath, locale };\n};\n\n/**\n * Process entry for non-i18n collections.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry object to populate.\n * @param {RawEntryContent} args.rawContent Raw content.\n * @param {string} args.path File path.\n * @param {string} [args.fileName] Collection file name.\n * @param {string} args.subPath Sub path.\n * @param {string} [args.subPathTemplate] Sub path template.\n */\nexport const processNonI18nEntry = ({\n  entry,\n  rawContent,\n  path,\n  fileName,\n  subPath,\n  subPathTemplate,\n}) => {\n  const slug = fileName || getSlug({ subPath, subPathTemplate });\n\n  entry.slug = slug;\n  entry.locales._default = { slug, path, content: flattenKeys(rawContent) };\n};\n\n/**\n * Process entry for single-file i18n structure.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry object to populate.\n * @param {RawEntryContent} args.rawContent Raw content.\n * @param {string} args.path File path.\n * @param {string} [args.fileName] Collection file name.\n * @param {string} args.subPath Sub path.\n * @param {string} [args.subPathTemplate] Sub path template.\n * @param {InternalLocaleCode[]} args.allLocales All available locales.\n */\nexport const processI18nSingleFileEntry = ({\n  entry,\n  rawContent,\n  path,\n  fileName,\n  subPath,\n  subPathTemplate,\n  allLocales,\n}) => {\n  const slug = fileName || getSlug({ subPath, subPathTemplate });\n\n  entry.slug = slug;\n  entry.locales = Object.fromEntries(\n    allLocales\n      // A locale key without an object, e.g. an empty `fr:` stub, has no content to read\n      .filter((_locale) => isObject(rawContent[_locale]))\n      .map((_locale) => [_locale, { slug, path, content: flattenKeys(rawContent[_locale]) }]),\n  );\n};\n\n/**\n * Process entry for multi-file i18n structure.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry object to populate.\n * @param {RawEntryContent} args.rawContent Raw content.\n * @param {string} args.path File path.\n * @param {string} [args.fileName] Collection file name.\n * @param {string} args.subPath Sub path.\n * @param {string} [args.subPathTemplate] Sub path template.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @param {InternalLocaleCode} args.defaultLocale Default locale.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.canonicalSlugKey] Canonical slug key.\n * @param {Map<string, Entry>} args.entryMap Entries prepared so far, keyed by their temporary ID. A\n * new entry is registered here so that its other locales can find it.\n * @returns {boolean} True if entry was added to existing entry, false if new entry should be added.\n */\nexport const processI18nMultiFileEntry = ({\n  entry,\n  rawContent,\n  path,\n  fileName,\n  subPath,\n  subPathTemplate,\n  locale,\n  defaultLocale,\n  collectionName,\n  canonicalSlugKey,\n  entryMap,\n}) => {\n  // Support a canonical slug to link localized files\n  const canonicalSlug =\n    canonicalSlugKey && typeof rawContent[canonicalSlugKey] === 'string'\n      ? rawContent[canonicalSlugKey]\n      : undefined;\n\n  const slug = fileName || getSlug({ subPath, subPathTemplate });\n  const localizedEntry = { slug, path, content: flattenKeys(rawContent) };\n  // Use a temporary ID to locate all the localized files for the entry. The sub path is the same\n  // across locales, while the slug may not be unique, e.g. with the `{{year}}/{{slug}}` path. A\n  // collection file is identified by its name, so a canonical slug in one of its locales can’t\n  // split it into two entries\n  const tempId = `${collectionName}/${fileName || (canonicalSlug ?? subPath)}`;\n  // Check if the entry has already been added for another locale. A lookup in the map rather than\n  // a scan of the entry list keeps this linear over a repository with thousands of localized files\n  const existingEntry = entryMap.get(tempId);\n\n  // If found, add a new locale to the existing entry; don’t add another entry\n  if (existingEntry) {\n    existingEntry.locales[locale] = localizedEntry;\n\n    // The default locale defines the entry’s identity, but any other locale stands in when its file\n    // is absent. Otherwise the entry would have no slug and `prepareEntries()` would drop it, which\n    // happens with Editorial Workflow whenever a pull request touches only a non-default locale\n    if (locale === defaultLocale || !existingEntry.slug) {\n      existingEntry.slug = slug;\n      existingEntry.subPath = subPath;\n    }\n\n    return true; // Entry was merged with existing\n  }\n\n  entry.id = tempId;\n  entry.locales[locale] = localizedEntry;\n  // The default locale file overrides this when it’s processed, in the branch above\n  entry.slug = slug;\n  entryMap.set(tempId, entry);\n\n  return false; // New entry should be added\n};\n\n/**\n * Raw items of the files storing all the entries of an entry collection, keyed by file path, as\n * they were last parsed. A save rewrites the file from these rather than from the entries, so the\n * items that don’t make an entry, and the properties that aren’t defined as fields, are kept as\n * they are. `null` for a file that doesn’t contain a valid array, which can’t be updated.\n * @type {Map<string, any[] | null>}\n */\nexport const arrayFileItems = new Map();\n\n/**\n * Create an entry from an item in a file storing all the entries of an entry collection. With i18n\n * enabled, the item holds all the translations, like a file with the `single_file` or\n * `single_file_default_root` structure does.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Collection.\n * @param {any} args.item Raw item.\n * @param {number} args.index Position of the item in the array.\n * @param {string} args.path File path.\n * @param {RepositoryFileMetadata} [args.meta] File metadata.\n * @returns {Entry | undefined} Entry, or `undefined` if the item doesn’t make one.\n */\nexport const createArrayItemEntry = ({ collection, item, index, path, meta = {} }) => {\n  const {\n    fields,\n    _i18n: {\n      i18nEnabled,\n      allLocales,\n      defaultLocale,\n      structureMap: { i18nSingleFileDefaultRoot },\n    },\n  } = collection;\n\n  const rawContent = i18nSingleFileDefaultRoot\n    ? normalizeDefaultRootContent(item, allLocales, defaultLocale)\n    : item;\n\n  const content = rawContent ? transformRawContent(rawContent, fields, i18nEnabled) : undefined;\n\n  if (!content) {\n    return undefined;\n  }\n\n  // The position is the slug, as an item has no file name to take one from\n  const subPath = String(index);\n  /** @type {Entry} */\n  const entry = { id: '', slug: '', subPath, locales: {}, arrayIndex: index, ...meta };\n\n  if (i18nEnabled) {\n    processI18nSingleFileEntry({ entry, rawContent: content, path, subPath, allLocales });\n  } else {\n    processNonI18nEntry({ entry, rawContent: content, path, subPath });\n  }\n\n  return Object.keys(entry.locales).length ? entry : undefined;\n};\n\n/**\n * Prepare the entries stored in a file of an entry collection that stores all the entries in one\n * file, one for each object in the array.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Collection.\n * @param {BaseEntryListItem} args.file Entry file list item.\n * @param {any} args.rawContent Parsed file content.\n * @param {Entry[]} args.entries List of prepared entries.\n * @param {Error[]} args.errors List of parse errors.\n */\nexport const prepareArrayFileEntries = ({ collection, file, rawContent, entries, errors }) => {\n  const { path, meta = {} } = file;\n\n  if (!Array.isArray(rawContent)) {\n    arrayFileItems.set(path, null);\n    errors.push(new Error(`${path} could not be parsed, as it doesn’t contain an array.`));\n\n    return;\n  }\n\n  arrayFileItems.set(path, rawContent);\n\n  rawContent.forEach((item, index) => {\n    const entry = createArrayItemEntry({ collection, item, index, path, meta });\n\n    if (entry) {\n      entries.push(entry);\n    }\n  });\n};\n\n/**\n * Prepare a new entry by processing the given file info and raw content.\n * @param {object} args Arguments.\n * @param {BaseEntryListItem} args.file Entry file list item.\n * @param {Entry[]} args.entries List of prepared entries.\n * @param {Map<string, Entry>} args.entryMap Prepared entries keyed by their temporary ID, used to\n * merge the localized files of a multi-file i18n entry.\n * @param {Error[]} args.errors List of parse errors.\n * @param {ParsedFileMap} [args.parsedFileMap] Map to add the content parsed from the file to. See\n * {@link parseFileContent}.\n */\nexport const prepareEntry = async ({ file, entries, entryMap, errors, parsedFileMap }) => {\n  const rawContent = await parseFileContent(file, errors, parsedFileMap);\n\n  const {\n    path,\n    meta = {},\n    folder: { collectionName, fileName },\n  } = file;\n\n  const { collection, collectionFile } = resolveCollectionAndFile(collectionName, fileName) ?? {};\n\n  // A file storing all the entries of an entry collection\n  const isArrayFile =\n    !collectionFile && collection?._type === 'entry' && collection._file.arrayFile;\n\n  if (!rawContent) {\n    // Make sure the array file is not overwritten\n    if (isArrayFile) {\n      arrayFileItems.set(path, null);\n    }\n\n    return;\n  }\n\n  if (!collection) {\n    return;\n  }\n\n  if (isArrayFile) {\n    prepareArrayFileEntries({ collection, file, rawContent, entries, errors });\n\n    return;\n  }\n\n  const {\n    fields: regularFields = [],\n    _file: { fullPathRegEx, subPath: subPathTemplate, extension },\n    _i18n: {\n      i18nEnabled,\n      allLocales,\n      defaultLocale,\n      structureMap,\n      canonicalSlug: { key: canonicalSlugKey },\n    },\n  } = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  // The special index file has fields of its own, which its draft is created and saved with, so its\n  // content has to be read with them too, e.g. to convert a List field stored as a map\n  const fields =\n    (!collectionFile &&\n      isCollectionIndexFilePath(collection, path) &&\n      getIndexFile(collection)?.fields) ||\n    regularFields;\n\n  // Normalize `single_file_default_root` content into the standard locale-keyed format so that the\n  // rest of the processing pipeline can treat it identically to `single_file`.\n  const effectiveRawContent = structureMap.i18nSingleFileDefaultRoot\n    ? normalizeDefaultRootContent(rawContent, allLocales, defaultLocale)\n    : rawContent;\n\n  if (!effectiveRawContent) {\n    return;\n  }\n\n  const isI18nSingleFile = usesSingleFileStructure(structureMap);\n  const transformedContent = transformRawContent(effectiveRawContent, fields, isI18nSingleFile);\n\n  if (!transformedContent) {\n    return;\n  }\n\n  if (shouldSkipIndexFile(path, fileName, collection, subPathTemplate, extension)) {\n    return;\n  }\n\n  const isMultiFileStructure = usesMultiFileStructure(structureMap);\n\n  const { subPath, locale } = extractPathInfo({\n    file,\n    fileName,\n    fullPathRegEx,\n    defaultLocale,\n    isMultiFileStructure,\n  });\n\n  if (!subPath) {\n    return;\n  }\n\n  if (isMultiFileStructure && !locale) {\n    return;\n  }\n\n  /** @type {Entry} */\n  const entry = {\n    id: '',\n    slug: '',\n    subPath,\n    locales: {},\n    ...meta,\n  };\n\n  const entryArgs = {\n    entry,\n    rawContent: transformedContent,\n    path,\n    fileName,\n    subPath,\n    subPathTemplate,\n  };\n\n  if (!i18nEnabled) {\n    processNonI18nEntry(entryArgs);\n  } else if (isI18nSingleFile) {\n    processI18nSingleFileEntry({ ...entryArgs, allLocales });\n  } else {\n    // `isMultiFileStructure` is always true here (the only non-`i18nSingleFile` path), and `locale`\n    // is always set (the guard above returned early if it wasn’t).\n    const wasMerged = processI18nMultiFileEntry({\n      ...entryArgs,\n      locale: /** @type {InternalLocaleCode} */ (locale),\n      defaultLocale,\n      collectionName,\n      canonicalSlugKey,\n      entryMap,\n    });\n\n    if (wasMerged) {\n      return; // Entry was merged with existing, don’t add to entries array\n    }\n  }\n\n  entries.push(entry);\n};\n\n/**\n * Parse the given entry files to create a complete, serialized entry list.\n * @param {BaseEntryListItem[]} entryFiles Entry file list.\n * @param {object} [options] Options.\n * @param {ParsedFileMap} [options.parsedFileMap] Map to add the content parsed from each file to,\n * so it can be cached. See {@link parseFileContent}.\n * @returns {Promise<{ entries: Entry[], errors: Error[] }>} Entry list and error list.\n */\nexport const prepareEntries = async (entryFiles, { parsedFileMap } = {}) => {\n  /** @type {Entry[]} */\n  const entries = [];\n  /** @type {Map<string, Entry>} */\n  const entryMap = new Map();\n  /** @type {Error[]} */\n  const errors = [];\n\n  // Parsing is synchronous, so a large repository would freeze the tab for the whole batch while\n  // the progress indicator stalls. Yield between chunks instead\n  await runInChunks(entryFiles, async (file) => {\n    // A file that can’t be processed is reported like a parse error, rather than stopping the whole\n    // list from loading\n    try {\n      await prepareEntry({ file, entries, entryMap, errors, parsedFileMap });\n    } catch (/** @type {any} */ ex) {\n      // eslint-disable-next-line no-console\n      console.error(ex);\n      errors.push(ex);\n    }\n  });\n\n  return {\n    entries: entries.filter((entry) => {\n      // Override a temporary ID\n      entry.id = generateUUID();\n\n      return !!entry.slug && !!Object.keys(entry.locales).length;\n    }),\n    errors,\n  };\n};\n","/**\n * Regular expression to match a complete regular expression string with delimiters and optional\n * flags, e.g. `/^.{0,280}$/s`.\n */\n// cspell:disable-next-line\nconst FULL_REGEX_PATTERN = /^\\/(?<pattern>.+)\\/(?<flags>[dgimsuvy]*)$/;\n/**\n * Regular expression to match the `g` (global) and `y` (sticky) flags.\n */\nconst STATEFUL_FLAGS_REGEX = /[gy]/g;\n\n/**\n * Check whether the given regular expression flags can be used together, e.g. not `mm` or `uv`.\n * @param {string} flags Flags.\n * @returns {boolean} Result.\n */\nconst areValidFlags = (flags) => {\n  try {\n    // eslint-disable-next-line no-new\n    new RegExp('', flags);\n\n    return true;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Return a RegExp object based on the provided pattern. If the pattern is already a RegExp, it\n * returns it as is, unless a stateful flag has to be dropped. If the pattern is a string, it\n * converts it to a RegExp. If the pattern is neither, it returns undefined.\n *\n * The `g` and `y` flags are always stripped, because they make the returned object stateful:\n * `RegExp.test()` resumes from `lastIndex` and updates it on every call, so a regex reused across a\n * list of values — a collection `filter`, a view filter, a field validation `pattern` — would match\n * only some of them. None of the callers iterate over matches, so the flags have no upside here.\n * @param {any} input Input pattern which can be a string or RegExp.\n * @returns {RegExp | undefined} The RegExp object or undefined if the pattern is invalid.\n */\nexport const getRegex = (input) => {\n  if (input instanceof RegExp) {\n    const flags = input.flags.replace(STATEFUL_FLAGS_REGEX, '');\n\n    return flags === input.flags ? input : new RegExp(input.source, flags);\n  }\n\n  if (typeof input === 'string' && input) {\n    // Parse the regex to support simple pattern, e.g `.{12,}`, and complete expression, e.g.\n    // `/^.{0,280}$/s`. A string without both delimiters is used as a pattern in its entirety, like\n    // Netlify/Decap CMS does, so a slash at either end of `^/blog/` or `^https?://` is kept\n    const { pattern, flags } = input.match(FULL_REGEX_PATTERN)?.groups ?? {};\n\n    if (pattern !== undefined) {\n      try {\n        // Compile with the flags as written, so a duplicate stateful flag isn’t missed, then drop\n        // the stateful flags as for a `RegExp` input\n        return getRegex(new RegExp(pattern, flags));\n      } catch {\n        // With valid flags, the pattern itself is invalid, which is a config error to report rather\n        // than to hide by matching the string literally\n        if (areValidFlags(flags)) {\n          return undefined;\n        }\n\n        // The flags are invalid, so the string is likely a plain pattern that just happens to look\n        // like a delimited one, e.g. `/posts/dummy`, whose `dummy` repeats the `m` flag. Fall back\n        // to using it in its entirety below\n      }\n    }\n\n    try {\n      return new RegExp(input);\n    } catch {\n      // Ignore invalid regex\n    }\n  }\n\n  return undefined;\n};\n","import { allEntries, allEntryFolders } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport {\n  getIndexFile,\n  getIndexFileName,\n  isCollectionIndexFile,\n} from '$lib/services/contents/collection/entries/index-file';\nimport { getListedEntryValue } from '$lib/services/contents/collection/view/values';\nimport { getAssociatedCollections } from '$lib/services/contents/entry/collections';\nimport { getEntryDisplayLocale } from '$lib/services/contents/entry/paths';\nimport { getSlug } from '$lib/services/contents/file/process';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { getRegex } from '$lib/services/utils/regex';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * Entry,\n * EntryFolderInfo,\n * InternalCollection,\n * } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Currently selected entries.\n * @type {{ current: Entry[] }}\n */\nexport const selectedEntries = createRawState([]);\n\n/**\n * Set of selected entry IDs, for O(1) membership checks in list items.\n */\nexport const selectedEntryIdSet = createDerivedState(\n  () => new Set(selectedEntries.current.map((entry) => entry.id)),\n);\n\n/**\n * @typedef {object} EntryFilterCondition\n * @property {FieldKeyPath} field Field key path to look at.\n * @property {RegExp} [pattern] Compiled `pattern` option, if any. It takes precedence over\n * {@link EntryFilterCondition.values}.\n * @property {any[]} values Normalized `value` option.\n */\n\n/**\n * Cache for {@link getFilterCondition}, so the `pattern` regex is compiled once per collection\n * rather than once per entry. Keyed by the collection object, which is replaced whenever the\n * configuration is loaded again, so the stale conditions can be garbage collected.\n * @type {WeakMap<InternalCollection, EntryFilterCondition | undefined>}\n */\nconst filterConditionCache = new WeakMap();\n\n/**\n * Get the normalized `filter` option of the given collection.\n * @param {InternalCollection} collection Collection.\n * @returns {EntryFilterCondition | undefined} Condition, or `undefined` if the collection is not an\n * entry collection or defines no usable filter.\n */\nconst getFilterCondition = (collection) =>\n  getOrCreate(filterConditionCache, collection, () => {\n    const { filter } = collection._type === 'entry' ? collection : {};\n    const field = filter?.field;\n\n    if (field === undefined) {\n      return undefined;\n    }\n\n    return {\n      field,\n      pattern: getRegex(filter?.pattern),\n      values:\n        filter?.value === undefined\n          ? []\n          : Array.isArray(filter.value)\n            ? filter.value\n            : [filter.value],\n    };\n  });\n\n/**\n * Check if the given entry passes the given collection’s `filter` option. An entry that doesn’t is\n * excluded from the collection’s entry list and can’t be opened in the content editor, so it must\n * not be offered anywhere else either, such as in the search results.\n *\n * This doesn’t check that the entry belongs to the collection in the first place. Use\n * {@link getListedCollections} to get the collections an entry is actually listed in.\n * @param {InternalCollection} collection Collection.\n * @param {Entry} entry Entry.\n * @returns {boolean} Result.\n * @see https://decapcms.org/docs/collection-folder/#filtered-folder-collections\n * @see https://sveltiacms.app/en/docs/collections/entries/listings#filtering-entries\n */\nexport const matchesCollectionFilter = (collection, entry) => {\n  const condition = getFilterCondition(collection);\n\n  // The `filter` option is defined against the collection’s regular fields, while Hugo’s special\n  // index file has its own `index_file.fields` schema. The index file is identified by its path,\n  // not by its content, so the filter must not apply to it\n  if (!condition || isCollectionIndexFile(collection, entry)) {\n    return true;\n  }\n\n  const { field, pattern, values } = condition;\n\n  // The filter is matched against the stored value, like Decap CMS does, so a Relation field isn’t\n  // resolved to the label of the referenced entry. Resolving it would also look up the entries of\n  // the referenced collection, which loops forever if that’s this collection. A multi-file i18n\n  // entry can lack its default locale file, in which case it’s listed in another locale, and so the\n  // filter reads the value from that locale\n  const value = getListedEntryValue({\n    entry,\n    locale: collection._i18n.defaultLocale,\n    collectionName: collection.name,\n    key: field,\n    resolveRef: false,\n  });\n\n  // A multi-value field, such as a List field or a Relation field with `multiple: true`, yields an\n  // array of its items, and the entry passes when any of them does. An entry without a value only\n  // passes when `null` is one of the filter values, which is how it’s stored in YAML\n  // @see https://github.com/sveltia/sveltia-cms/issues/997\n  const items = Array.isArray(value) ? value : [value ?? null];\n\n  if (pattern) {\n    // A missing value never matches a pattern, like Decap CMS’s view filters do. `RegExp.test()`\n    // would coerce `null` to the string `null`, which `.+` or `^n` would match\n    return items.some((item) => item !== null && item !== undefined && pattern.test(String(item)));\n  }\n\n  return items.some((item) => values.includes(item));\n};\n\n/**\n * Get a list of collections the given entry is listed in, which are the collections the entry\n * belongs to, minus any whose `filter` option the entry doesn’t pass and any hidden with the `hide`\n * option. A hidden collection can’t be opened, so its entries mustn’t be linked from anywhere, such\n * as the search results or the “Used in” section of an asset.\n * @param {Entry} entry Entry.\n * @returns {InternalCollection[]} Collections.\n */\nexport const getListedCollections = (entry) =>\n  getAssociatedCollections(entry).filter(\n    (collection) => !collection.hide && matchesCollectionFilter(collection, entry),\n  );\n\n/**\n * Cache for {@link getEntriesByCollection}, keyed by collection name and invalidated whenever\n * `allEntries` or `allEntryFolders` is replaced.\n * @type {{\n * entrySource: Entry[] | undefined,\n * folderSource: EntryFolderInfo[] | undefined,\n * buckets: Map<string, Entry[]> | undefined,\n * map: Map<string, Entry[]>,\n * folderMap: Map<string, Entry[]>,\n * }}\n */\nconst entriesByCollectionCache = {\n  entrySource: undefined,\n  folderSource: undefined,\n  buckets: undefined,\n  map: new Map(),\n  folderMap: new Map(),\n};\n\n/**\n * Sort every entry into the collections it belongs to, in one pass over `allEntries`. The sidebar\n * asks for the entries of every collection whenever the entry list changes, so looking each one up\n * with its own scan would cost a pass per collection. The collections of an entry are cached with\n * the entry object, which survives a save or a refresh unless the entry itself has changed, so this\n * is mostly lookups.\n * @returns {Map<string, Entry[]>} Entries by collection name, in the order of `allEntries`.\n */\nconst getCollectionBuckets = () => {\n  if (!entriesByCollectionCache.buckets) {\n    /** @type {Map<string, Entry[]>} */\n    const buckets = new Map();\n\n    allEntries.current.forEach((entry) => {\n      // A collection can match an entry through more than one of its folders\n      new Set(getAssociatedCollections(entry).map(({ name }) => name)).forEach((name) => {\n        getOrCreate(buckets, name, () => []).push(entry);\n      });\n    });\n\n    entriesByCollectionCache.buckets = buckets;\n  }\n\n  return entriesByCollectionCache.buckets;\n};\n\n/**\n * Get the entries belonging to the given collection. This is the uncached implementation of\n * {@link getEntriesByCollection}.\n * @param {string} collectionName Collection name.\n * @returns {Entry[]} Entries.\n */\nconst queryEntriesByCollection = (collectionName) => {\n  const collection = getCollection(collectionName);\n\n  if (!collection) {\n    return [];\n  }\n\n  return (getCollectionBuckets().get(collectionName) ?? []).filter((entry) =>\n    matchesCollectionFilter(collection, entry),\n  );\n};\n\n/**\n * Reset {@link entriesByCollectionCache}. Used in tests, where the stores are mocked and therefore\n * don’t change identity between cases.\n */\nexport const _resetEntriesByCollectionCache = () => {\n  entriesByCollectionCache.entrySource = undefined;\n  entriesByCollectionCache.folderSource = undefined;\n  entriesByCollectionCache.buckets = undefined;\n  entriesByCollectionCache.map = new Map();\n  entriesByCollectionCache.folderMap = new Map();\n};\n\n/**\n * Drop the cached entries of {@link getEntriesByCollection} and\n * {@link getEntriesInCollectionFolder} once the entry stores have been replaced.\n */\nconst syncEntriesByCollectionCache = () => {\n  const entrySource = allEntries.current;\n  const folderSource = allEntryFolders.current;\n\n  if (\n    entrySource !== entriesByCollectionCache.entrySource ||\n    folderSource !== entriesByCollectionCache.folderSource\n  ) {\n    entriesByCollectionCache.entrySource = entrySource;\n    entriesByCollectionCache.folderSource = folderSource;\n    entriesByCollectionCache.buckets = undefined;\n    entriesByCollectionCache.map = new Map();\n    entriesByCollectionCache.folderMap = new Map();\n  }\n};\n\n/**\n * Get entries by the given collection name, while applying a filer if needed.\n *\n * The result is memoized until the entry stores are replaced. Scanning every entry once per call\n * adds up quickly — the sidebar asks for a count per collection, and a Relation field resolves its\n * referenced collection once per entry being sorted, filtered or listed. Just as importantly, the\n * returned array keeps a stable reference, which is what lets the Relation field’s option cache hit\n * at all; it keys on the identity of the entry list the options were built from.\n *\n * The returned array is shared between callers, so treat it as read-only.\n * @param {string} collectionName Collection name.\n * @returns {Entry[]} Entries.\n * @see https://decapcms.org/docs/collection-folder/#filtered-folder-collections\n * @see https://sveltiacms.app/en/docs/collections/entries/listings#filtering-entries\n */\nexport const getEntriesByCollection = (collectionName) => {\n  syncEntriesByCollectionCache();\n\n  const cache = entriesByCollectionCache.map.get(collectionName);\n\n  if (cache) {\n    return cache;\n  }\n\n  const entries = queryEntriesByCollection(collectionName);\n\n  entriesByCollectionCache.map.set(collectionName, entries);\n\n  return entries;\n};\n\n/**\n * Get the entries another collection claims although their files are stored in the folder of the\n * given entry collection, e.g. Hugo’s `_index.md` declared as a file collection’s file, as they\n * would be read in the entry collection: with the slugs and sub paths it would give them.\n * @param {InternalCollection} collection Entry collection.\n * @param {Entry[]} ownEntries Entries the collection already has.\n * @returns {Entry[]} Entries.\n */\nconst getForeignEntriesInFolder = (collection, ownEntries) => {\n  const { _file: { fullPathRegEx = undefined, subPath: subPathTemplate = undefined } = {} } =\n    collection._type === 'entry' ? collection : {};\n\n  if (!fullPathRegEx) {\n    return [];\n  }\n\n  const { defaultLocale } = collection._i18n;\n  const ownEntrySet = new Set(ownEntries);\n\n  return allEntries.current.flatMap((entry) => {\n    if (ownEntrySet.has(entry)) {\n      return [];\n    }\n\n    /** @type {Entry['locales']} */\n    const locales = {};\n    /** @type {Record<string, string>} */\n    const subPaths = {};\n\n    Object.values(entry.locales).forEach((localizedEntry) => {\n      const { subPath, locale = defaultLocale } =\n        localizedEntry.path.match(fullPathRegEx)?.groups ?? {};\n\n      if (subPath) {\n        locales[locale] = { ...localizedEntry, slug: getSlug({ subPath, subPathTemplate }) };\n        subPaths[locale] = subPath;\n      }\n    });\n\n    // The default locale’s file may not be in the folder, e.g. with the `multiple_root_folders`\n    // i18n structure\n    const locale = getEntryDisplayLocale(locales, defaultLocale);\n\n    if (!locale) {\n      return [];\n    }\n\n    const { slug } = locales[locale];\n    const subPath = subPaths[locale];\n\n    return [{ ...entry, slug, subPath, locales }];\n  });\n};\n\n/**\n * Get every entry stored in the folder of the given collection, whether it passes the collection’s\n * `filter` option or not, and even if another collection claims it. Collections can share a folder\n * and tell their entries apart with a filter, and a file collection can declare a file in the\n * folder, such as Hugo’s `_index.md`, so a file name has to be unique among all of these entries,\n * not only the listed ones: a new entry taking the slug of an entry another collection lists would\n * overwrite its file. An entry another collection claims comes with the slug and sub path this\n * collection would give it.\n *\n * The returned array is shared between callers, so treat it as read-only.\n * @param {string} collectionName Collection name.\n * @returns {Entry[]} Entries.\n */\nexport const getEntriesInCollectionFolder = (collectionName) => {\n  syncEntriesByCollectionCache();\n\n  return getOrCreate(entriesByCollectionCache.folderMap, collectionName, () => {\n    const collection = getCollection(collectionName);\n    const entries = getCollectionBuckets().get(collectionName) ?? [];\n\n    return collection ? [...entries, ...getForeignEntriesInFolder(collection, entries)] : entries;\n  });\n};\n\n/**\n * Count the entries in the collection, leaving out Hugo’s special index file. The index file stands\n * for the collection’s own page rather than for one of the entries in it, so it’s not part of the\n * count shown next to the collection in the sidebar. It’s still listed in the entry list, where it\n * has an icon and a label of its own that tell it from the entries.\n *\n * The entries are passed in rather than looked up, because the caller merges the pending changes\n * into them, so an entry that only exists in a pull request is counted as well. The collection is\n * looked up so that the index file can be told by the entry’s path in this collection, as another\n * collection’s index file can be listed here — see {@link isCollectionIndexFile}.\n * @param {string} collectionName Collection name.\n * @param {Entry[]} entries Entries in the collection.\n * @returns {number} Count.\n * @see https://github.com/sveltia/sveltia-cms/issues/1005\n */\nexport const countCollectionEntries = (collectionName, entries) => {\n  const collection = getCollection(collectionName);\n\n  // A collection without an index file has nothing to leave out, which is the common case, so skip\n  // the pass over the entries rather than testing each one\n  if (!collection || getIndexFileName(collection) === undefined) {\n    return entries.length;\n  }\n\n  return entries.filter((entry) => !isCollectionIndexFile(collection, entry)).length;\n};\n\n/**\n * Check if index file creation is allowed in the collection. The listed entries can include another\n * collection’s index file, when that collection’s folder sits below this one’s, so each entry is\n * tested by its path rather than by the slug the owning collection computed for it.\n * @param {InternalCollection} collection Collection.\n * @returns {boolean} Result. It returns `false` if the index file already exists.\n * @see https://github.com/sveltia/sveltia-cms/issues/1005\n */\nexport const canCreateIndexFile = (collection) => {\n  if (!getIndexFile(collection)) {\n    return false;\n  }\n\n  return !getEntriesByCollection(collection.name).some((entry) =>\n    isCollectionIndexFile(collection, entry),\n  );\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\n\n/**\n * The default field key used to store an entry’s display order when reordering is enabled and no\n * custom key is configured.\n * @type {string}\n */\nconst DEFAULT_ORDER_FIELD_KEY = 'order';\n\n/**\n * Check if the entries of the given collection are kept in a manual order: an entry collection with\n * the `reorder` option, or one storing all the entries in one file, which keeps them in the order\n * of the array.\n * @param {any} collection Collection. Anything other than an entry collection returns `false`.\n * @returns {boolean} Result.\n */\nexport const isManuallyOrdered = (collection) =>\n  collection?._type === 'entry' && (!!collection.reorder || isArrayFileCollection(collection));\n\n/**\n * Get the field key used to persist an entry’s display order for the given collection.\n * @param {any} collection Collection (typically an entry collection). Anything else returns\n * `undefined`.\n * @returns {string | undefined} Field key, or `undefined` if reordering is not enabled.\n */\nexport const getOrderFieldKey = (collection) => {\n  const reorder = collection?.reorder;\n\n  // An entry collection storing all the entries in one file keeps them in the order of the array\n  if (!reorder || typeof collection.file === 'string') {\n    return undefined;\n  }\n\n  if (isObject(reorder) && typeof reorder.key === 'string' && reorder.key) {\n    return reorder.key;\n  }\n\n  return DEFAULT_ORDER_FIELD_KEY;\n};\n\n/**\n * Check if the given sort key sorts entries by their manual order: the special `_manual` key, or\n * the collection’s order field itself.\n * @param {any} collection Collection (typically an entry collection).\n * @param {string | undefined} key Sort key.\n * @returns {boolean} Result. `false` for an empty key, even if the collection has no order field.\n */\nexport const isManualOrderKey = (collection, key) =>\n  !!key && (key === '_manual' || key === getOrderFieldKey(collection));\n\n/**\n * Get the name of the view group that entries should be grouped by while the given collection is in\n * reorder mode, as configured with `reorder: { group: '…' }`. The group is named explicitly rather\n * than reusing whatever grouping the user has active, because the order field is renumbered group\n * by group: an arbitrary grouping would produce a different numbering every time and the values\n * would conflict.\n * @param {any} collection Collection (typically an entry collection). Anything else returns\n * `undefined`.\n * @returns {string | undefined} Group name, or `undefined` if reorder grouping is not configured.\n */\nexport const getReorderGroupName = (collection) => {\n  const reorder = collection?.reorder;\n\n  if (isObject(reorder) && typeof reorder.group === 'string' && reorder.group) {\n    return reorder.group;\n  }\n\n  return undefined;\n};\n","import { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\n\n/**\n * @import { Entry, InternalEntryCollection } from '$lib/types/private';\n */\n\n/**\n * Get a function that returns an entry’s position in the manual order: the value of the\n * collection’s `order` field, or the position in the array for a collection storing all the entries\n * in one file.\n * @param {InternalEntryCollection} collection Entry collection.\n * @returns {(entry: Entry) => number | undefined} Order value getter. It returns `undefined` for an\n * entry lacking a valid numeric value, or for every entry if the collection has no `order` field.\n */\nexport const getOrderValueGetter = (collection) => {\n  // An entry collection storing all the entries in one file keeps them in the order of the array\n  if (isArrayFileCollection(collection)) {\n    return (entry) => entry.arrayIndex ?? 0;\n  }\n\n  const orderKey = getOrderFieldKey(collection);\n\n  if (!orderKey) {\n    return () => undefined;\n  }\n\n  const { defaultLocale } = collection._i18n;\n\n  return (entry) => {\n    // An entry lacking the default locale, e.g. a multi-file i18n entry with only `hello.fr.md`,\n    // has the value in the locale it’s listed in\n    const raw = getEntryLocaleFile(entry, { defaultLocale })?.content?.[orderKey];\n\n    // `Number()` turns `null` and a blank string into `0`, so only a number or a non-blank string\n    // counts as a value; anything else is missing and sorts last\n    const v =\n      typeof raw === 'number' || (typeof raw === 'string' && raw.trim()) ? Number(raw) : NaN;\n\n    return Number.isFinite(v) ? v : undefined;\n  };\n};\n\n/**\n * Sort entries by the collection’s `order` field, or by their position in the array for a\n * collection storing all the entries in one file. Entries lacking a valid numeric value are placed\n * at the end while preserving their relative input order.\n * @param {Entry[]} entries Entries to sort.\n * @param {InternalEntryCollection} collection Entry collection.\n * @returns {Entry[]} New, sorted array.\n */\nexport const sortEntriesByOrderField = (entries, collection) => {\n  const getOrderValue = getOrderValueGetter(collection);\n  // Pre-compute each entry’s numeric order value once so the comparator — which runs O(N log N)\n  // times — only does a cheap numeric comparison rather than re-walking the property chain.\n  const keyed = entries.map((entry) => ({ entry, v: getOrderValue(entry) }));\n\n  keyed.sort((a, b) => {\n    if (a.v !== undefined && b.v !== undefined) return a.v - b.v;\n    if (a.v !== undefined) return -1;\n    if (b.v !== undefined) return 1;\n    return 0;\n  });\n\n  return keyed.map(({ entry }) => entry);\n};\n","import { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { RelationOption } from '$lib/types/private';\n */\n\n/**\n * Cache indexed labels for each cached option array so multi-value relations don’t scan all\n * relation options for every stored value.\n * @type {WeakMap<RelationOption[], Map<any, string>>}\n */\nconst optionLabelMapCache = new WeakMap();\n\n/**\n * Create or retrieve a value-to-label index for the given relation options.\n * @param {RelationOption[]} options Relation options.\n * @returns {Map<any, string>} Option labels keyed by option value.\n */\nexport const getOptionLabelMap = (options) =>\n  getOrCreate(optionLabelMapCache, options, () => {\n    /** @type {Map<any, string>} */\n    const labelMap = new Map();\n\n    options.forEach(({ value, label }) => {\n      if (!labelMap.has(value)) {\n        labelMap.set(value, label);\n      }\n    });\n\n    return labelMap;\n  });\n\n/**\n * `WeakMap` used to assign stable numeric identities to objects for cheap cache key building,\n * avoiding the need to `JSON.stringify` large objects like `fieldConfig` or `refEntries` arrays.\n * @type {WeakMap<object, number>}\n */\nconst objectIdentityMap = new WeakMap();\nlet nextObjectId = 0;\n\n/**\n * Get a stable numeric identity for the given object (by reference).\n * @param {object} obj Object.\n * @returns {number} Numeric identity.\n */\nexport const getObjectId = (obj) =>\n  getOrCreate(objectIdentityMap, obj, () => {\n    const id = nextObjectId;\n\n    nextObjectId += 1;\n\n    return id;\n  });\n","import { hasTemplateTags } from '$lib/services/common/template/tags';\n\n/**\n * @import { Field, ListField } from '$lib/types/public';\n */\n\n/**\n * Enclose the given field name in brackets if it doesn’t contain any brackets.\n * @param {string} fieldName Field name e.g. `{{name.first}}` or `name.first`.\n * @returns {string} Bracketed field name, e.g. `{{name.first}}`.\n */\nexport const normalizeFieldName = (fieldName) => {\n  if (hasTemplateTags(fieldName)) {\n    return fieldName;\n  }\n\n  if (fieldName === 'slug') {\n    // Avoid confusion with `{{slug}}`, which is the entry slug, not the `slug` field\n    return '{{fields.slug}}';\n  }\n\n  return `{{${fieldName}}}`;\n};\n\n/**\n * Check if the given field configuration is a complex list field with subfields (e.g.\n * `cities.*.name`) and not just a simple list field (e.g. `skills.*`).\n * @param {Field | undefined} fieldConfig Field configuration object.\n * @returns {boolean} Whether the field is a complex list field.\n */\nexport const isComplexListField = (fieldConfig) => {\n  if (!fieldConfig || fieldConfig.widget !== 'list') {\n    return false;\n  }\n\n  const hasFields = 'fields' in /** @type {ListField} */ (fieldConfig);\n  const hasTypes = 'types' in /** @type {ListField} */ (fieldConfig);\n\n  return hasFields || hasTypes;\n};\n","import { unique } from '@sveltia/utils/array';\n\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { getEntrySummaryFromContent } from '$lib/services/contents/entry/summary';\nimport { normalizeFieldName } from '$lib/services/contents/fields/relation/helpers/field-names';\n\n/**\n * @import { FlattenedEntryContent, InternalLocaleCode, RelationOption } from '$lib/types/private';\n * @import { FieldKeyPath, RelationField } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} ReplacementContext\n * @property {string} slug The slug of the entry.\n * @property {InternalLocaleCode} locale The current locale.\n * @property {(keyPath: FieldKeyPath, _locale?: InternalLocaleCode) => string} getDisplayValue\n * Function to get the display value of a field.\n */\n\n/**\n * @typedef {object} FallbackContext\n * @property {FlattenedEntryContent} content Content of the entry.\n * @property {Record<InternalLocaleCode, FlattenedEntryContent>} locales Locales of the entry.\n * @property {InternalLocaleCode} defaultLocale Default locale of the entry.\n * @property {FieldKeyPath} identifierField Identifier field for the entry.\n */\n\n/**\n * @typedef {object} TemplateStrings\n * @property {string} _valueField Normalized value field template.\n * @property {string} _displayField Normalized display field template.\n * @property {string} _searchField Normalized search field template.\n * @property {string[]} allFieldNames All field names extracted from templates.\n * @property {boolean} hasListFields Whether any field names include a list wildcard (*).\n */\n\n/**\n * Get the stored value of a field as a string, for the `value_field` template.\n * @param {FlattenedEntryContent | undefined} valueMap Entry content.\n * @param {FieldKeyPath} keyPath Field key path.\n * @returns {string} Stored value, or an empty string if the field has none. A `0` or `false` is a\n * value, not an empty field.\n */\nconst getStoredValue = (valueMap, keyPath) => {\n  const value = valueMap?.[keyPath];\n\n  return value === undefined || value === null ? '' : String(value);\n};\n\n/**\n * Get the replacement value for a field name based on standard field types. An empty field is\n * replaced with an empty string: falling back to the entry summary or slug here would put them in\n * the `value_field` template, storing a reference that doesn’t identify the entry, or repeat them\n * in a `display_fields` template. A label that comes out empty falls back to them instead; see\n * {@link getLabelFallback}.\n * @param {string} fieldName The field name to get replacement for.\n * @param {ReplacementContext} context Context object containing `slug`, `locale`, and\n * `getDisplayValue` function.\n * @param {FallbackContext} fallbackContext Fallback context for additional content.\n * @param {object} [options] Options.\n * @param {boolean} [options.stored] Whether to get the stored value rather than the display value.\n * The `value_field` template takes the stored value, so a reference matches the referenced field\n * as saved: a number without the thousands separators, the value of a Select field option rather\n * than its label, a date in its stored format, and so on.\n * @returns {string} The replacement value.\n */\nexport const getFieldReplacement = (\n  fieldName,\n  context,\n  fallbackContext,\n  { stored = false } = {},\n) => {\n  const { slug, locale, getDisplayValue } = context;\n  const { content, locales, defaultLocale } = fallbackContext;\n\n  if (fieldName === 'slug') {\n    return slug;\n  }\n\n  if (fieldName === 'locale') {\n    return locale;\n  }\n\n  const keyPath = stripFieldTagPrefix(fieldName);\n\n  if (stored) {\n    return (\n      getStoredValue(content, keyPath) ||\n      // A multi-file entry can lack a locale’s file, including the default locale’s\n      getStoredValue(locales[defaultLocale]?.content, keyPath)\n    );\n  }\n\n  return getDisplayValue(keyPath) || getDisplayValue(keyPath, defaultLocale) || '';\n};\n\n/**\n * Get the label of an option whose `display_fields` template comes out empty: the entry summary,\n * or the slug if the entry has none.\n * @param {ReplacementContext} context Replacement context.\n * @param {FallbackContext} fallbackContext Fallback context.\n * @returns {string} Label.\n */\nexport const getLabelFallback = (context, fallbackContext) => {\n  const { content, locales, defaultLocale, identifierField } = fallbackContext;\n\n  return (\n    getEntrySummaryFromContent(content, { identifierField }) ||\n    getEntrySummaryFromContent(locales[defaultLocale]?.content || {}, { identifierField }) ||\n    context.slug\n  );\n};\n\n/**\n * Replace all template tags in the given strings with actual values: the stored field values in the\n * value, and the display values in the label and search value. The value is left empty if\n * any tag in its template has no value, as such a value can’t identify the entry; the caller\n * leaves out an option without a value. The label and search value are trimmed, and the label\n * falls back to {@link getLabelFallback} if it comes out empty.\n * @param {RelationOption} templates Object containing `label`, `value`, and `searchValue`\n * templates.\n * @param {string[]} fieldNames Array of field names to replace.\n * @param {ReplacementContext} context Context object for replacements.\n * @param {FallbackContext} fallbackContext Fallback context for additional content.\n * @returns {RelationOption} Object with replaced `label`, `value`, and `searchValue`.\n */\nexport const replaceTemplateFields = (templates, fieldNames, context, fallbackContext) => {\n  let { label, value, searchValue } = templates;\n  let hasEmptyValueTag = false;\n\n  fieldNames.forEach((fieldName) => {\n    const tag = `{{${fieldName}}}`;\n    const replacement = getFieldReplacement(fieldName, context, fallbackContext);\n\n    if (value.includes(tag)) {\n      const storedValue = getFieldReplacement(fieldName, context, fallbackContext, {\n        stored: true,\n      });\n\n      if (!storedValue) {\n        hasEmptyValueTag = true;\n      }\n\n      value = value.replaceAll(tag, () => storedValue);\n    }\n\n    label = label.replaceAll(tag, () => replacement);\n    searchValue = searchValue?.replaceAll(tag, () => replacement) ?? '';\n  });\n\n  return {\n    // Trim the spaces around an empty field, e.g. the second of the `display_fields` joined with\n    // a space\n    label: label.trim() || getLabelFallback(context, fallbackContext),\n    value: hasEmptyValueTag ? '' : value,\n    searchValue: searchValue.trim(),\n  };\n};\n\n/**\n * Extract field names from template strings.\n * @param {string} template Template string with field names in {{}} brackets.\n * @returns {string[]} Array of field names.\n */\nexport const extractFieldNames = (template) => {\n  /** @type {string[]} */\n  const names = [];\n\n  replaceTemplateTags(template, (_match, placeholder) => {\n    names.push(placeholder);\n    return '';\n  });\n\n  return names;\n};\n\n/**\n * Normalize and prepare field templates for processing.\n * @param {RelationField} fieldConfig Field configuration.\n * @param {string} identifierField Default identifier field.\n * @returns {TemplateStrings} Normalized field templates.\n */\nexport const prepareFieldTemplates = (fieldConfig, identifierField) => {\n  /**\n   * @example 'userId'\n   * @example 'name.first'\n   * @example 'cities.*.id'\n   * @example '{{cities.*.id}}'\n   * @example 'slug' (`slug` field)\n   * @example '{{slug}}' (entry slug)\n   * @example '{{locale}}/{{slug}}'\n   * @example '{{fields.slug}}' (not mentioned in the Netlify/Decap CMS doc but Sveltia CMS supports\n   * the `fields.` prefix for compatibility with other config options)\n   */\n  const valueField = fieldConfig.value_field;\n  /**\n   * Canonical, templatized value field.\n   * @example '{{name.first}}'\n   * @example '{{route}}#{{sections.*.name}}'\n   */\n  const _valueField = normalizeFieldName(valueField || '{{slug}}');\n\n  /**\n   * The entry slug isn’t meant to be shown, so the identifier field is shown by default with the\n   * default value field, whether it’s omitted or written explicitly.\n   * @example ['userId']\n   * @example ['name.first'] (nested)\n   * @example ['cities.*.id', 'cities.*.name'] (with wildcard, multiple)\n   * @example ['{{twitterHandle}} - {{followerCount}}'] (template)\n   */\n  const displayFields = fieldConfig.display_fields ?? [\n    _valueField === '{{slug}}' ? `{{${identifierField}}}` : _valueField,\n  ];\n\n  /**\n   * The format is the same as {@link displayFields}.\n   */\n  const searchFields = fieldConfig.search_fields ?? displayFields;\n  /**\n   * Canonical, templatized display field.\n   * @example '{{twitterHandle}} {{followerCount}}'\n   * @example '{{sections.*.name}}'\n   * @example '{{route}}: {{sections.*.name}} ({{sections.*.id}})'\n   */\n  const _displayField = displayFields.map(normalizeFieldName).join(' ');\n  /**\n   * Canonical, templatized search field.\n   */\n  const _searchField = searchFields.map(normalizeFieldName).join(' ');\n\n  const allFieldNames = unique([\n    ...extractFieldNames(_displayField),\n    ...extractFieldNames(_valueField),\n    ...extractFieldNames(_searchField),\n  ]);\n\n  return {\n    _valueField,\n    _displayField,\n    _searchField,\n    allFieldNames,\n    hasListFields: allFieldNames.some((name) => name.includes('*')),\n  };\n};\n","import { escapeRegExp } from '@sveltia/utils/string';\n\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { isComplexListField } from '$lib/services/contents/fields/relation/helpers/field-names';\nimport { replaceTemplateFields } from '$lib/services/contents/fields/relation/helpers/templates';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import {\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalLocaleCode,\n * RelationOption,\n * } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} ReplacementContext\n * @property {string} slug The slug of the entry.\n * @property {InternalLocaleCode} locale The current locale.\n * @property {(keyPath: string, _locale?: InternalLocaleCode) => string} getDisplayValue\n * Function to get the display value of a field.\n */\n\n/**\n * @typedef {object} FallbackContext\n * @property {FlattenedEntryContent} content Content of the entry.\n * @property {Record<InternalLocaleCode, FlattenedEntryContent>} locales Locales of the entry.\n * @property {InternalLocaleCode} defaultLocale Default locale of the entry.\n * @property {string} identifierField Identifier field for the entry.\n */\n\n/**\n * @typedef {object} TemplateStrings\n * @property {string} _valueField Normalized value field template.\n * @property {string} _displayField Normalized display field template.\n * @property {string} _searchField Normalized search field template.\n * @property {string[]} allFieldNames All field names extracted from templates.\n * @property {boolean} hasListFields Whether any field names include a list wildcard (*).\n */\n\nconst LIST_KEY_PATH_MATCH_REGEX = /\\.(\\d+)$/;\n\n/**\n * Analyze list field configurations and group them by base field name.\n * @param {string[]} allFieldNames All field names.\n * @param {GetFieldArgs} getFieldArgs Arguments for getField function.\n * @returns {Map<string, [string, any][]>} Grouped list field configurations.\n */\nexport const analyzeListFields = (allFieldNames, getFieldArgs) => {\n  const listFieldConfigs = new Map();\n\n  // Analyze all list fields and get their configurations\n  allFieldNames\n    .filter((fieldName) => fieldName.includes('*'))\n    .forEach((fieldName) => {\n      const baseFieldName = fieldName.replace(/\\.\\*.*$/, '');\n      const fieldConfigForList = getField({ ...getFieldArgs, keyPath: baseFieldName });\n\n      listFieldConfigs.set(fieldName, {\n        baseFieldName,\n        fieldConfig: fieldConfigForList,\n        isComplexListField: isComplexListField(fieldConfigForList),\n      });\n    });\n\n  // Group entries by base field name\n  return Map.groupBy(listFieldConfigs.entries(), ([, { baseFieldName }]) => baseFieldName);\n};\n\n/**\n * Build the relation option for one list item: the given list wildcards in the templates are\n * replaced with the item’s values, then the remaining non-list fields are resolved.\n * @param {object} params Parameters.\n * @param {TemplateStrings} params.templates Template strings.\n * @param {[string, any][]} params.replacements Pairs of wildcard field name and item value.\n * @param {string[]} params.staticFieldNames Field names without a list wildcard.\n * @param {ReplacementContext} params.context Replacement context.\n * @param {FallbackContext} params.fallbackContext Fallback context.\n * @returns {RelationOption} Option.\n */\nconst buildListItemOption = ({\n  templates,\n  replacements,\n  staticFieldNames,\n  context,\n  fallbackContext,\n}) => {\n  const { _displayField, _valueField, _searchField } = templates;\n\n  /**\n   * Replace all the list wildcards in a template with the item values.\n   * @param {string} template Template string.\n   * @returns {string} Processed template.\n   */\n  const replaceWildcards = (template) =>\n    replacements.reduce(\n      (result, [fieldName, itemValue]) => result.replaceAll(`{{${fieldName}}}`, () => itemValue),\n      template,\n    );\n\n  const { label, value, searchValue } = replaceTemplateFields(\n    {\n      label: replaceWildcards(_displayField),\n      value: replaceWildcards(_valueField),\n      searchValue: replaceWildcards(_searchField),\n    },\n    staticFieldNames,\n    context,\n    fallbackContext,\n  );\n\n  // Like an empty field, an empty list item value can’t identify the item\n  const hasEmptyValueTag = replacements.some(\n    ([fieldName, itemValue]) =>\n      _valueField.includes(`{{${fieldName}}}`) && String(itemValue ?? '') === '',\n  );\n\n  return {\n    label,\n    value: hasEmptyValueTag ? '' : value,\n    searchValue: searchValue || label,\n  };\n};\n\n/**\n * Cache of pre-compiled regexes for {@link processSingleSubfieldList}, keyed by base field name.\n * @type {Map<string, RegExp>}\n */\nconst singleSubfieldRegexCache = new Map();\n\n/**\n * Collect the values of an indexed list from the flattened entry content, in list order.\n * @param {FlattenedEntryContent} content Entry content.\n * @param {RegExp} filterRegex Regular expression matching the key paths of the list’s items.\n * @param {RegExp} [indexRegex] Regular expression whose first capture group is the item index,\n * when it differs from {@link filterRegex}.\n * @returns {{ index: number, value: any }[]} Values, sorted by index.\n */\nconst collectIndexedValues = (content, filterRegex, indexRegex = filterRegex) =>\n  Object.entries(content)\n    .filter(([k]) => filterRegex.test(k))\n    .map(([k, v]) => {\n      // The filter above guarantees the regex matches, so `indexMatch` is always non-null\n      const indexMatch = /** @type {RegExpMatchArray} */ (k.match(indexRegex));\n\n      return { index: parseInt(indexMatch[1], 10), value: v };\n    })\n    .sort((a, b) => a.index - b.index);\n\n/**\n * Process single subfield list fields (e.g., `skills.*`).\n * @param {object} params Parameters.\n * @param {string} params.baseFieldName Base field name.\n * @param {[string, any][]} params.groupEntries Group entries.\n * @param {FlattenedEntryContent} params.content Entry content.\n * @param {TemplateStrings} params.templates Template strings.\n * @param {string[]} params.allFieldNames All field names.\n * @param {ReplacementContext} params.context Replacement context.\n * @param {FallbackContext} params.fallbackContext Fallback context.\n * @returns {RelationOption[]} One option per list item.\n */\nexport const processSingleSubfieldList = ({\n  baseFieldName,\n  groupEntries,\n  content,\n  templates,\n  allFieldNames,\n  context,\n  fallbackContext,\n}) => {\n  const regex = getOrCreate(\n    singleSubfieldRegexCache,\n    baseFieldName,\n    () => new RegExp(`^${escapeRegExp(baseFieldName)}\\\\.\\\\d+$`),\n  );\n\n  const items = collectIndexedValues(content, regex, LIST_KEY_PATH_MATCH_REGEX);\n  const staticFieldNames = allFieldNames.filter((name) => !name.includes('*'));\n\n  return items.map(({ value: itemValue }) =>\n    buildListItemOption({\n      templates,\n      // Replace all wildcards for this base field with the current item value\n      replacements: groupEntries.map(([fieldName]) => [fieldName, itemValue]),\n      staticFieldNames,\n      context,\n      fallbackContext,\n    }),\n  );\n};\n\n/**\n * Regex to match complex list fields with subfields.\n * Examples: `cities.*.name` or `colors.customColors.*.colorName`.\n * @type {RegExp}\n */\nconst COMPLEX_LIST_FIELD_REGEX = /^(.+)\\.\\*\\.(.+)$/;\n/**\n * Cache of index-matching regexes for {@link processComplexListField}, keyed by\n * `\"${baseFieldName}:${subKey}\"`.\n * @type {Map<string, RegExp>}\n */\nconst complexListIndexRegexCache = new Map();\n\n/**\n * Get the subfield match from group entries.\n * @param {[string, any][]} groupEntries Group entries.\n * @returns {RegExpMatchArray | null} Subfield match.\n */\nexport const getSubFieldMatch = (groupEntries) => {\n  /** @type {RegExpMatchArray | null} */\n  let subFieldMatch = null;\n\n  groupEntries.some(([fieldName]) => {\n    subFieldMatch = fieldName.match(COMPLEX_LIST_FIELD_REGEX);\n\n    return !!subFieldMatch;\n  });\n\n  return subFieldMatch;\n};\n\n/**\n * Process complex list fields (e.g., `cities.*.name`).\n * @param {object} params Parameters.\n * @param {[string, any][]} params.groupEntries Group entries.\n * @param {FlattenedEntryContent} params.content Entry content.\n * @param {TemplateStrings} params.templates Template strings.\n * @param {string[]} params.allFieldNames All field names.\n * @param {ReplacementContext} params.context Replacement context.\n * @param {FallbackContext} params.fallbackContext Fallback context.\n * @returns {RelationOption[]} Array of options, one for each list item.\n */\nexport const processComplexListField = ({\n  groupEntries,\n  content,\n  templates,\n  allFieldNames,\n  context,\n  fallbackContext,\n}) => {\n  const [, baseFieldNameForList, subKey] = getSubFieldMatch(groupEntries) ?? [];\n\n  if (!baseFieldNameForList) {\n    return [];\n  }\n\n  const cacheKey = `${baseFieldNameForList}:${subKey}`;\n\n  const indexRegex = getOrCreate(complexListIndexRegexCache, cacheKey, () => {\n    const escapedBase = escapeRegExp(baseFieldNameForList);\n    const escapedSub = escapeRegExp(subKey);\n\n    // indexRegex subsumes the old filter-only `regex` (same semantics; `[0-9]+` ≡ `\\d+` in JS\n    // without the `u` flag), so one regex construction per call is saved.\n    return new RegExp(`^${escapedBase}\\\\.([0-9]+)\\\\.${escapedSub}$`);\n  });\n\n  const listValues = collectIndexedValues(content, indexRegex);\n  const staticFieldNames = allFieldNames.filter((name) => !name.includes('*'));\n\n  return listValues.map(({ index }) =>\n    buildListItemOption({\n      templates,\n      // Replace all wildcards for this base field with the current list item’s subfield values\n      replacements: groupEntries.flatMap(([wildcardFieldName]) => {\n        const [, baseFieldName, subFieldKey] =\n          wildcardFieldName.match(COMPLEX_LIST_FIELD_REGEX) ?? [];\n\n        return baseFieldName\n          ? [[wildcardFieldName, content[`${baseFieldName}.${index}.${subFieldKey}`] ?? '']]\n          : [];\n      }),\n      staticFieldNames,\n      context,\n      fallbackContext,\n    }),\n  );\n};\n\n/**\n * Process all list fields for an entry.\n * @param {object} params Parameters.\n * @param {Map<string, [string, any][]>} params.baseFieldGroups Grouped configs.\n * @param {FlattenedEntryContent} params.content Entry content.\n * @param {TemplateStrings} params.templates Template strings.\n * @param {string[]} params.allFieldNames All field names.\n * @param {ReplacementContext} params.context Replacement context.\n * @param {FallbackContext} params.fallbackContext Fallback context.\n * @returns {{ results: RelationOption[], hasProcessedListFields: boolean }} Results.\n */\nexport const processListFields = ({\n  baseFieldGroups,\n  content,\n  templates,\n  allFieldNames,\n  context,\n  fallbackContext,\n}) => {\n  /** @type {RelationOption[]} */\n  const results = [];\n  let hasProcessedListFields = false;\n\n  baseFieldGroups.forEach((groupEntries, baseFieldName) => {\n    if (groupEntries.length === 0) {\n      return;\n    }\n\n    const [, firstConfig] = groupEntries[0];\n\n    const args = {\n      groupEntries,\n      content,\n      templates,\n      allFieldNames,\n      context,\n      fallbackContext,\n    };\n\n    const options = firstConfig.isComplexListField\n      ? processComplexListField({ ...args })\n      : processSingleSubfieldList({ ...args, baseFieldName });\n\n    results.push(...options);\n    hasProcessedListFields = true;\n  });\n\n  return { results, hasProcessedListFields };\n};\n","import { replaceTemplateFields } from '$lib/services/contents/fields/relation/helpers/templates';\n\n/**\n * @import { FlattenedEntryContent, InternalLocaleCode, RelationOption } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} ReplacementContext\n * @property {string} slug The slug of the entry.\n * @property {InternalLocaleCode} locale The current locale.\n * @property {(keyPath: FieldKeyPath, _locale?: InternalLocaleCode) => string} getDisplayValue\n * Function to get the display value of a field.\n */\n\n/**\n * @typedef {object} FallbackContext\n * @property {FlattenedEntryContent} content Content of the entry.\n * @property {Record<InternalLocaleCode, FlattenedEntryContent>} locales Locales of the entry.\n * @property {InternalLocaleCode} defaultLocale Default locale of the entry.\n * @property {FieldKeyPath} identifierField Identifier field for the entry.\n */\n\n/**\n * @typedef {object} TemplateStrings\n * @property {string} _valueField Normalized value field template.\n * @property {string} _displayField Normalized display field template.\n * @property {string} _searchField Normalized search field template.\n * @property {string[]} allFieldNames All field names extracted from templates.\n * @property {boolean} hasListFields Whether any field names include a list wildcard (*).\n */\n\n/**\n * Create a single relation option for non-list fields.\n * @param {object} params Parameters.\n * @param {TemplateStrings} params.templates Template strings.\n * @param {string[]} params.allFieldNames All field names to replace.\n * @param {ReplacementContext} params.context Replacement context.\n * @param {FallbackContext} params.fallbackContext Fallback context.\n * @returns {RelationOption} Single relation option. Its `value` is empty if the entry lacks a\n * field in the `value_field` template, so the option can’t refer to the entry.\n */\nexport const createSimpleOption = ({ templates, allFieldNames, context, fallbackContext }) => {\n  const { _displayField, _valueField, _searchField } = templates;\n\n  const { label, value, searchValue } = replaceTemplateFields(\n    { label: _displayField, value: _valueField, searchValue: _searchField },\n    allFieldNames,\n    context,\n    fallbackContext,\n  );\n\n  return { label, value, searchValue: searchValue || label };\n};\n","import { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { stripIndexFileName } from '$lib/services/contents/collection/nested';\nimport { getFieldDisplayValue } from '$lib/services/contents/entry/values';\nimport {\n  analyzeListFields,\n  processListFields,\n} from '$lib/services/contents/fields/relation/helpers/list-fields';\nimport { createSimpleOption } from '$lib/services/contents/fields/relation/helpers/options';\nimport { replaceTemplateFields } from '$lib/services/contents/fields/relation/helpers/templates';\n\n/**\n * @import {\n * Entry,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalCollection,\n * InternalLocaleCode,\n * RelationOption,\n * UnlistedEntry,\n * } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} ReplacementContext\n * @property {string} slug The slug of the entry.\n * @property {InternalLocaleCode} locale The current locale.\n * @property {(keyPath: FieldKeyPath, _locale?: InternalLocaleCode) => string} getDisplayValue\n * Function to get the display value of a field.\n */\n\n/**\n * @typedef {object} FallbackContext\n * @property {FlattenedEntryContent} content Content of the entry.\n * @property {Record<InternalLocaleCode, FlattenedEntryContent>} locales Locales of the entry.\n * @property {InternalLocaleCode} defaultLocale Default locale of the entry.\n * @property {FieldKeyPath} identifierField Identifier field for the entry.\n */\n\n/**\n * @typedef {object} TemplateStrings\n * @property {string} _valueField Normalized value field template.\n * @property {string} _displayField Normalized display field template.\n * @property {string} _searchField Normalized search field template.\n * @property {string[]} allFieldNames All field names extracted from templates.\n * @property {boolean} hasListFields Whether any field names include a list wildcard (*).\n */\n\n/**\n * Leave out options without a value. The value is empty when the entry lacks a field in the\n * `value_field` template, and such an option can’t refer to the entry: falling back to another\n * value, like the entry summary, would store a reference that doesn’t match the entry.\n * @param {RelationOption[]} options Options.\n * @returns {RelationOption[]} Options with a value.\n */\nconst excludeOptionsWithoutValue = (options) => options.filter(({ value }) => !!value);\n\n/**\n * Process a single entry to generate relation options.\n * @param {object} params Parameters.\n * @param {Entry} params.refEntry Reference entry.\n * @param {FlattenedEntryContent} params.content Entry content.\n * @param {InternalCollection} params.collection Collection configuration.\n * @param {TemplateStrings} params.templates Template strings.\n * @param {string} [params.fileName] File name.\n * @param {InternalLocaleCode} params.locale Current locale.\n * @param {string} params.identifierField Identifier field.\n * @param {UnlistedEntry[]} [params.pendingEntries] Entries not yet among the saved ones, which a\n * Relation field of the entry can refer to.\n * @returns {RelationOption[]} Array of relation options.\n */\nexport const processEntry = ({\n  refEntry,\n  content,\n  collection,\n  templates,\n  fileName,\n  locale,\n  identifierField,\n  pendingEntries = undefined,\n}) => {\n  const { locales } = refEntry;\n\n  const {\n    name: collectionName,\n    _i18n: { defaultLocale },\n  } = collection;\n\n  const { allFieldNames, hasListFields } = templates;\n  // In a collection with nested entries an entry’s slug is its path within the collection folder,\n  // ending with the file name shared by every entry. A reference to the entry leaves that name out,\n  // the same way a preview path does\n  const slug = stripIndexFileName(collection, refEntry.slug);\n  const isIndexFile = isCollectionIndexFile(collection, refEntry);\n  /** @type {GetFieldArgs} */\n  const getFieldArgs = { collectionName, fileName, isIndexFile, keyPath: '' };\n\n  /**\n   * Wrapper for {@link getFieldDisplayValue}.\n   * @param {FieldKeyPath} keyPath Field key path.\n   * @param {InternalLocaleCode} [_locale] Target locale.\n   * @returns {string} Display value.\n   */\n  const getDisplayValue = (keyPath, _locale) =>\n    getFieldDisplayValue({\n      ...getFieldArgs,\n      keyPath,\n      // A multi-file entry can lack a locale’s file, including the default locale’s\n      valueMap: _locale ? (locales[_locale]?.content ?? {}) : content,\n      locale: _locale ?? locale,\n      pendingEntries,\n    });\n\n  const context = { slug, locale, getDisplayValue };\n  const fallbackContext = { content, locales, defaultLocale, identifierField };\n\n  if (!hasListFields) {\n    return excludeOptionsWithoutValue([\n      createSimpleOption({ templates, allFieldNames, context, fallbackContext }),\n    ]);\n  }\n\n  // Handle list fields\n  const baseFieldGroups = analyzeListFields(allFieldNames, getFieldArgs);\n\n  const { results, hasProcessedListFields } = processListFields({\n    baseFieldGroups,\n    content,\n    templates,\n    allFieldNames,\n    context,\n    fallbackContext,\n  });\n\n  if (hasProcessedListFields) {\n    return excludeOptionsWithoutValue(results);\n  }\n\n  const { _displayField, _valueField, _searchField } = templates;\n\n  // Fallback for complex multi-list scenarios or unhandled cases\n  const processedTemplates = {\n    label: _displayField,\n    value: _valueField,\n    searchValue: _searchField,\n  };\n\n  const { label, value, searchValue } = replaceTemplateFields(\n    processedTemplates,\n    allFieldNames.filter((name) => !name.includes('*')),\n    context,\n    fallbackContext,\n  );\n\n  return excludeOptionsWithoutValue([{ label, value, searchValue: searchValue || label }]);\n};\n","/**\n * @import { Field } from '$lib/types/public';\n */\n\n/**\n * Check if a field is translatable, i.e. Its field-level `i18n` option is `true`, its alias\n * `translate` or `duplicate_if_empty`, so the field can be edited in every locale. The last one\n * also fills in the other locales’ empty values with the default locale’s value.\n * @param {Field['i18n']} i18n Field-level `i18n` option.\n * @returns {boolean} Result.\n */\nexport const isFieldTranslatable = (i18n) =>\n  i18n === true || i18n === 'translate' || i18n === 'duplicate_if_empty';\n\n/**\n * Check if a field holds the same value in every locale, i.e. Its field-level `i18n` option is\n * `duplicate`, where the default locale’s value is copied to the other locales, which can’t edit\n * it, or `sync`, where a value edited in any locale is copied to the others.\n * @param {Field['i18n']} i18n Field-level `i18n` option.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/1128\n */\nexport const isFieldMirrored = (i18n) => i18n === 'duplicate' || i18n === 'sync';\n\n/**\n * Check if a field holds a value in every locale, i.e. Its field-level `i18n` option is one of the\n * translatable ones (see {@link isFieldTranslatable}) or mirrored ones (see\n * {@link isFieldMirrored}).\n * @param {Field['i18n']} i18n Field-level `i18n` option.\n * @returns {boolean} Result.\n */\nexport const isFieldLocalized = (i18n) => isFieldTranslatable(i18n) || isFieldMirrored(i18n);\n\n/**\n * Check if i18n is disabled for a field, i.e. Its field-level `i18n` option is `false`, its alias\n * `none` or not defined, so the field only exists in the default locale.\n * @param {Field['i18n']} i18n Field-level `i18n` option.\n * @returns {boolean} Result.\n */\nexport const isFieldI18nDisabled = (i18n) =>\n  i18n === undefined || i18n === false || i18n === 'none';\n","import { getDraftFieldArgs, getField } from '$lib/services/contents/entry/fields';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isFieldLocalized, isFieldMirrored } from '$lib/services/contents/i18n/fields';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { Field } from '$lib/types/public';\n */\n\n/**\n * Values of the fields that aren’t localized, which are only stored in the default locale, as\n * given by {@link getDraftSharedValues}.\n * @typedef {object} SharedValues\n * @property {FlattenedEntryContent} values Content of the default locale.\n * @property {(keyPath: string) => boolean} isShared Whether the field at the given key path isn’t\n * localized, so its value is to be read from {@link SharedValues.values}.\n */\n\n/**\n * Get the `i18n` option that applies to the given field: its own, or, if the field has none, that\n * of the nearest ancestor that has one, such as the List or Object field it belongs to.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the key\n * path of the field.\n * @returns {Field['i18n']} Option, or `undefined` if neither the field nor its ancestors have one.\n */\nexport const getInheritedI18nOption = ({ fieldConfig, getFieldArgs }) => {\n  if (fieldConfig.i18n !== undefined) {\n    return fieldConfig.i18n;\n  }\n\n  const segments = getFieldArgs.keyPath.split('.');\n\n  // Look at the ancestors from the nearest one, skipping the list item indexes, which aren’t fields\n  // of their own, e.g. `items` for `items.0.name`\n  for (let index = segments.length - 2; index >= 0; index -= 1) {\n    if (!isNumeric(segments[index])) {\n      const { i18n } =\n        getField({ ...getFieldArgs, keyPath: segments.slice(0, index + 1).join('.') }) ?? {};\n\n      if (i18n !== undefined) {\n        return i18n;\n      }\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Check if the given field holds the same value in every locale. That is the case when the field\n * has the `duplicate` or `sync` i18n strategy, or, if the field has no `i18n` option of its own,\n * when the nearest ancestor that has one, such as the List or Object field it belongs to, has\n * either strategy. A duplicated List or Object field then holds the same items and values in every\n * locale, the way `normalizeContentMap()` copies it when an entry is loaded, while a subfield\n * explicitly made translatable keeps a value of its own in each locale.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the key\n * path of the field.\n * @returns {boolean} Whether the value is duplicated.\n */\nexport const isDuplicatedField = (args) => isFieldMirrored(getInheritedI18nOption(args));\n\n/**\n * Check if the given field uses the `sync` i18n strategy, either with an `i18n` option of its own\n * or along with the nearest ancestor that has one. Unlike a `duplicate` field, which can only be\n * edited in the default locale, such a field can be edited in any locale, and the value is copied\n * from there to the others.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the key\n * path of the field.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/1128\n */\nexport const isSyncedField = (args) => getInheritedI18nOption(args) === 'sync';\n\n/**\n * Check whether the field at the given key path belongs in a locale’s content. Every field does in\n * the default locale, but in another locale, only one that is localized along with all of its\n * ancestors, as the others are left out of that locale’s content when it’s saved.\n * @param {object} args Arguments.\n * @param {Omit<GetFieldArgs, 'keyPath'>} args.getFieldArgs Arguments for the `getField` function,\n * without the key path.\n * @param {InternalLocaleCode} args.locale Locale.\n * @param {InternalLocaleCode} args.defaultLocale Default locale.\n * @param {string} args.keyPath Concrete key path of the field.\n * @returns {boolean} Result.\n */\nexport const isFieldInLocale = ({ getFieldArgs, locale, defaultLocale, keyPath }) => {\n  if (locale === defaultLocale) {\n    return true;\n  }\n\n  const segments = keyPath.split('.');\n  let hasAncestor = false;\n  /**\n   * `i18n` option of the nearest field so far that has one, which a field without one of its own\n   * goes along with. See {@link getInheritedI18nOption}, which looks the ancestors up instead.\n   * @type {Field['i18n']}\n   */\n  let inheritedI18n;\n\n  // Skip the list item indexes, which aren’t fields of their own, e.g. `items.0` in `items.0.kv`\n  return segments.every((segment, index) => {\n    if (index < segments.length - 1 && isNumeric(segment)) {\n      return true;\n    }\n\n    const fieldConfig = getField({\n      ...getFieldArgs,\n      keyPath: segments.slice(0, index + 1).join('.'),\n    });\n\n    // A value without a field of its own, e.g. an item of a List field without subfields like\n    // `tags.1`, or a KeyValue pair like `kv.a`, goes along with the nearest ancestor that has one,\n    // which is in the locale if we get here\n    if (!fieldConfig) {\n      return hasAncestor;\n    }\n\n    hasAncestor = true;\n    inheritedI18n = fieldConfig.i18n !== undefined ? fieldConfig.i18n : inheritedI18n;\n\n    return isFieldLocalized(inheritedI18n);\n  });\n};\n\n/**\n * Cache of the values {@link addSharedValues} takes from the default locale, keyed by the content\n * of the default locale, then by the collection, file and locale. The content is a saved entry’s or\n * a draft snapshot, which is replaced rather than changed, so a Compute field updated on every\n * keystroke doesn’t look up every field of the default locale each time.\n * @type {WeakMap<FlattenedEntryContent, Map<string, FlattenedEntryContent>>}\n */\nconst sharedValueCache = new WeakMap();\n\n/**\n * Add the values of the fields that aren’t localized, which are only stored in the default locale,\n * to a locale’s content, so that anything reading the content of a locale, like a Compute field or\n * a `preview_path` template, finds them there as well.\n * @param {object} args Arguments.\n * @param {Omit<GetFieldArgs, 'keyPath' | 'valueMap'>} args.getFieldArgs Arguments for the\n * `getField` function, without the key path and the value map.\n * @param {InternalLocaleCode} args.locale Locale.\n * @param {InternalLocaleCode} args.defaultLocale Default locale.\n * @param {FlattenedEntryContent} args.content Content of the locale.\n * @param {FlattenedEntryContent | undefined} args.defaultContent Content of the default locale. It\n * mustn’t be changed in place, as what’s taken from it is cached: pass a draft’s snapshot rather\n * than its live values.\n * @returns {FlattenedEntryContent} Content of the locale with the shared values, or the given\n * content as is for the default locale.\n */\nexport const addSharedValues = ({\n  getFieldArgs,\n  locale,\n  defaultLocale,\n  content,\n  defaultContent,\n}) => {\n  if (locale === defaultLocale || !defaultContent) {\n    return content;\n  }\n\n  const { collectionName, fileName, isIndexFile } = getFieldArgs;\n  const cacheKey = JSON.stringify([collectionName, fileName, isIndexFile, locale, defaultLocale]);\n\n  const sharedValues = getOrCreate(\n    getOrCreate(sharedValueCache, defaultContent, () => new Map()),\n    cacheKey,\n    () => {\n      const args = { ...getFieldArgs, valueMap: defaultContent };\n\n      return Object.fromEntries(\n        Object.entries(defaultContent).filter(\n          ([keyPath]) => !isFieldInLocale({ getFieldArgs: args, locale, defaultLocale, keyPath }),\n        ),\n      );\n    },\n  );\n\n  return { ...sharedValues, ...content };\n};\n\n/**\n * Get the values of an entry draft’s fields that aren’t localized, for reading them while another\n * locale than the default is edited. Unlike {@link addSharedValues}, no value is read until it’s\n * asked for, so a reactive caller only depends on the values it actually uses.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @param {InternalLocaleCode} locale Locale being edited.\n * @returns {SharedValues | undefined} Shared values, or `undefined` for the default locale.\n */\nexport const getDraftSharedValues = (draft, locale) => {\n  const { defaultLocale } = getDraftI18nConfig(draft);\n  const values = draft?.currentValues[defaultLocale];\n\n  if (!draft || !values || locale === defaultLocale) {\n    return undefined;\n  }\n\n  const getFieldArgs = getDraftFieldArgs(draft, { valueMap: values });\n\n  return {\n    values,\n    /**\n     * Check whether the field at the given key path isn’t localized.\n     * @param {string} keyPath Key path.\n     * @returns {boolean} Result.\n     */\n    isShared: (keyPath) => !isFieldInLocale({ getFieldArgs, locale, defaultLocale, keyPath }),\n  };\n};\n","import { escapeRegExp } from '@sveltia/utils/string';\n\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { stripIndexFileName } from '$lib/services/contents/collection/nested';\nimport { isFieldInLocale } from '$lib/services/contents/i18n/shared-values';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { Entry, FlattenedEntryContent, InternalCollection } from '$lib/types/private';\n * @import { SharedValues } from '$lib/services/contents/i18n/shared-values';\n * @import { RelationFieldFilterOptions } from '$lib/types/public';\n */\n\nconst FIELD_TEMPLATE_REGEX = /^{{fields\\.(.+?)}}$/;\n/**\n * Cache of pre-compiled regexes matching the item keys of a list, keyed by field key path.\n * @type {Map<string, RegExp>}\n */\nconst listItemRegexCache = new Map();\n\n/**\n * Get the value of a field from flattened entry content. A list value, such as that of a Select\n * field with `multiple: true` or a List field without subfields, is flattened into `field.0`,\n * `field.1` and so on, often next to an empty placeholder at `field`, so its items are collected\n * into an array. The content is only read, never written, as it can be the live state of an entry\n * draft, which the Relation field editor reads within `$derived()`.\n * @param {FlattenedEntryContent} content Flattened entry content.\n * @param {string} keyPath Field key path.\n * @returns {any} Field value, or an array of list items.\n */\nconst getFieldValue = (content, keyPath) => {\n  const value = content[keyPath];\n\n  // Return a plain value as is. Only a list, whose placeholder is an empty array, needs its item\n  // keys looked up; reading the key names alone keeps a draft’s other values untracked\n  if (value !== undefined && !Array.isArray(value)) {\n    return value;\n  }\n\n  const regex = getOrCreate(\n    listItemRegexCache,\n    keyPath,\n    () => new RegExp(`^${escapeRegExp(keyPath)}\\\\.\\\\d+$`),\n  );\n\n  const items = Object.keys(content)\n    .filter((key) => regex.test(key))\n    .map((key) => content[key]);\n\n  return items.length ? items : value;\n};\n\n/**\n * Resolve `{{fields.fieldName}}` and `{{slug}}` template strings in filter values against the entry\n * currently being edited. Unresolvable templates are dropped from the values array so they do not\n * accidentally match `undefined` content fields.\n * @param {RelationFieldFilterOptions[]} filters Entry filters.\n * @param {FlattenedEntryContent | undefined} currentLocaleValues Current locale field values of the\n * entry being edited, or `undefined` when not available (e.g. backlink resolution).\n * @param {string | undefined} currentSlug Current slug of the entry being edited, or `undefined`\n * when not yet determined (e.g. new entry draft).\n * @param {SharedValues} [sharedValues] Values of the fields of the entry being edited that aren’t\n * localized, which are missing from `currentLocaleValues` in another locale than the default.\n * @returns {RelationFieldFilterOptions[]} Filters with template values resolved.\n */\nexport const resolveFilterValues = (\n  filters,\n  currentLocaleValues,\n  currentSlug = undefined,\n  sharedValues = undefined,\n) =>\n  filters.map(({ field, values, exclude }) => ({\n    field,\n    exclude,\n    values: values.flatMap((v) => {\n      if (typeof v !== 'string') return [v];\n\n      if (v === '{{slug}}') {\n        // Drop if slug not yet determined (new entry draft)\n        return currentSlug ? [currentSlug] : [];\n      }\n\n      const match = v.match(FIELD_TEMPLATE_REGEX);\n\n      if (!match) return [v];\n\n      // Template found — resolve against current entry values\n      let resolved = currentLocaleValues ? getFieldValue(currentLocaleValues, match[1]) : undefined;\n\n      // A field that isn’t localized only has a value in the default locale\n      if (resolved === undefined && sharedValues?.isShared(match[1])) {\n        resolved = getFieldValue(sharedValues.values, match[1]);\n      }\n\n      // Expand a list value into its items, so an entry matches when it shares any of them\n      if (Array.isArray(resolved)) return resolved;\n\n      // Drop unresolvable templates to avoid false matches\n      return resolved !== undefined ? [resolved] : [];\n    }),\n  }));\n\n/**\n * Filter entries based on file name and entry filters.\n * @param {object} args Arguments.\n * @param {Entry[]} args.refEntries Reference entries.\n * @param {InternalCollection} args.collection Collection the entries belong to.\n * @param {string} args.locale Current locale.\n * @param {string} [args.fileName] File name to filter by.\n * @param {RelationFieldFilterOptions[]} [args.entryFilters] Entry filters to apply.\n * @param {string} [args.defaultLocale] Default locale from collection’s i18n configuration.\n * @returns {{ refEntry: Entry, content: FlattenedEntryContent }[]} Filtered entries with content.\n */\nexport const filterAndPrepareEntries = ({\n  refEntries,\n  collection,\n  locale,\n  fileName = undefined,\n  entryFilters = [],\n  defaultLocale = undefined,\n}) => {\n  /**\n   * Whether each filtered field is localized, keyed by key path, so the fields aren’t looked up\n   * again for every referenced entry.\n   * @type {Map<string, boolean>}\n   */\n  const localizedFieldCache = new Map();\n\n  /**\n   * Get the value of a field to filter a referenced entry by. A field that isn’t localized is only\n   * stored in the default locale, so its value is read from there in another locale.\n   * @param {Entry} refEntry Referenced entry.\n   * @param {FlattenedEntryContent} content Content of the entry in the locale.\n   * @param {string} keyPath Field key path.\n   * @returns {any} Field value, or an array of list items.\n   */\n  const getFilterFieldValue = (refEntry, content, keyPath) => {\n    const value = getFieldValue(content, keyPath);\n    const defaultContent = defaultLocale ? refEntry.locales[defaultLocale]?.content : undefined;\n\n    if (\n      value !== undefined ||\n      !defaultContent ||\n      defaultContent === content ||\n      getOrCreate(localizedFieldCache, keyPath, () =>\n        isFieldInLocale({\n          getFieldArgs: { collectionName: collection.name, fileName, valueMap: defaultContent },\n          locale,\n          defaultLocale: /** @type {string} */ (defaultLocale),\n          keyPath,\n        }),\n      )\n    ) {\n      return value;\n    }\n\n    return getFieldValue(defaultContent, keyPath);\n  };\n\n  return refEntries\n    .filter((refEntry) => !fileName || fileName === refEntry.slug)\n    .map((refEntry) => {\n      // Fall back to the collection’s default locale, then `_default` (no i18n) as a final fallback\n      const { content } =\n        refEntry.locales[locale] ??\n        (defaultLocale ? refEntry.locales[defaultLocale] : undefined) ??\n        refEntry.locales._default ??\n        {};\n\n      return {\n        refEntry,\n        hasContent: !!content && Object.keys(content).length > 0,\n        content: content ?? {},\n      };\n    })\n    .filter(\n      ({ hasContent, content, refEntry }) =>\n        hasContent &&\n        entryFilters.every(({ field, values, exclude = false }) => {\n          // An empty values array means no constraint — skip this filter\n          if (values.length === 0) return true;\n\n          // `slug` refers to the entry’s slug, not a regular content field.\n          // `fields.fieldName` strips the prefix so a field literally named `slug` can be\n          // targeted via `fields.slug` without ambiguity.\n          const isEntrySlug = field === 'slug';\n          const fieldKey = stripFieldTagPrefix(field);\n\n          // Match the slug in the same shape a reference to the entry uses\n          const fieldValue = isEntrySlug\n            ? stripIndexFileName(collection, refEntry.slug)\n            : getFilterFieldValue(refEntry, content, fieldKey);\n\n          // A list value matches when any of its items is included in the filter values\n          const matches = Array.isArray(fieldValue)\n            ? fieldValue.some((item) => values.includes(item))\n            : values.includes(fieldValue);\n\n          return exclude ? !matches : matches;\n        }),\n    );\n};\n","import { IndexedDB } from '@sveltia/utils/storage';\n\n/**\n * Open a store in the IndexedDB database associated with the given repository. Each repository has\n * its own database, named after the backend and the repository path, so the stores, such as the\n * file cache and UI settings, are kept apart between sites.\n * @param {{ databaseName?: string } | undefined} repository Repository info.\n * @param {string} storeName Store name, e.g. `file-cache`.\n * @returns {IndexedDB | undefined} Database handle, or `undefined` if the repository has no\n * database, e.g. when the backend is not initialized yet.\n */\nexport const getRepositoryDatabase = (repository, storeName) => {\n  const { databaseName } = repository ?? {};\n\n  return databaseName ? new IndexedDB(databaseName, storeName) : undefined;\n};\n\n/**\n * Read all the records in a cache store.\n * @template T\n * @param {IndexedDB | null | undefined} db Cache store.\n * @returns {Promise<Map<string, T>>} Records keyed as in the store. Empty if there is no store or\n * it can’t be read, e.g. in a private window, so the caller computes everything again.\n */\nexport const readCacheEntries = async (db) => {\n  try {\n    return new Map((await db?.entries()) ?? []);\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n\n    return new Map();\n  }\n};\n\n/**\n * Save new records in a cache store, and delete the ones no longer in use. Nothing is written if\n * there is nothing to save or delete. A failure is only logged, as the cache is a nicety: the next\n * load computes the records again.\n * @template T\n * @param {IndexedDB | null | undefined} db Cache store.\n * @param {Map<string, T>} newEntries Records to save.\n * @param {string[]} staleKeys Keys of the records to delete.\n */\nexport const updateCacheEntries = async (db, newEntries, staleKeys) => {\n  if (!db) {\n    return;\n  }\n\n  try {\n    if (newEntries.size) {\n      await db.saveEntries([...newEntries]);\n    }\n\n    if (staleKeys.length) {\n      await db.deleteEntries(staleKeys);\n    }\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  }\n};\n","import { _ } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\nimport { compare } from '@sveltia/utils/string';\nimport equal from 'fast-deep-equal';\n\nimport { getRepositoryDatabase } from '$lib/services/utils/database';\nimport { getRegex } from '$lib/services/utils/regex';\nimport { createRootEffect } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { FilteringConditions, GroupingConditions } from '$lib/types/private';\n * @import { ViewFilter, ViewGroup } from '$lib/types/public';\n */\n\n/**\n * Conditions of a view filter or group: the target field, and what its value is matched against.\n * @typedef {FilteringConditions | GroupingConditions} ViewConditions\n */\n\n/**\n * Comparison operators a view filter or group can define in addition to, or instead of, `pattern`.\n * Listed in the order the operators are written to a condition key by {@link getConditionKey}.\n * @type {('eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'in' | 'not_in' | 'empty')[]}\n * @see https://sveltiacms.app/en/docs/collections/entries/views#filtering\n */\nexport const COMPARISON_OPERATORS = ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'in', 'not_in', 'empty'];\n\n/**\n * Get the conditions a view filter or group option defines, leaving out the `name` and `label`,\n * which identify the option in the menu but not what it matches. This is what the view settings\n * hold for an applied filter or group, so an option is applied by looking up its conditions with\n * {@link getConditionKey}.\n * @param {ViewFilter | ViewGroup} option View filter or group option.\n * @returns {ViewConditions} Conditions, with only the properties the option defines.\n */\nexport const getViewConditions = (option) => {\n  const { field, pattern } = option;\n  /** @type {ViewConditions} */\n  const conditions = { field };\n\n  if (pattern !== undefined) {\n    conditions.pattern = pattern;\n  }\n\n  COMPARISON_OPERATORS.forEach((operator) => {\n    if (option[operator] !== undefined) {\n      conditions[operator] = /** @type {any} */ (option[operator]);\n    }\n  });\n\n  return conditions;\n};\n\n/**\n * Check whether the conditions include a comparison operator, as opposed to a plain `pattern`, or\n * nothing but the field in the case of a group.\n * @param {ViewConditions | null | undefined} conditions Conditions.\n * @returns {boolean} Whether at least one of the {@link COMPARISON_OPERATORS} is defined.\n */\nexport const hasComparison = (conditions) =>\n  !!conditions && COMPARISON_OPERATORS.some((operator) => conditions[operator] !== undefined);\n\n/**\n * Get a key identifying the conditions of a view filter or group, so that an applied condition can\n * be matched with the option it came from, and the collapsed groups of a view can be saved per\n * condition. Two conditions get the same key when they match the same entries.\n * @param {ViewConditions} conditions Conditions.\n * @returns {string} JSON array of the field, the pattern if any, and the comparison operators if\n * any, e.g. `[\"date\",\"\\\\d{4}\"]` or `[\"date\",null,{\"gte\":\"{{today}}\"}]`. A pattern is a regular\n * expression that can hold any character, so joining the parts with a separator could be\n * ambiguous. A pattern given as a `RegExp` object is written as its string form, which is how the\n * view settings saved before the object was supported hold it, and the operators are written in\n * the order of {@link COMPARISON_OPERATORS} rather than the order they were configured in.\n */\nexport const getConditionKey = (conditions) => {\n  const { field, pattern } = conditions;\n  /** @type {any[]} */\n  const parts = [field];\n\n  const operators = Object.fromEntries(\n    COMPARISON_OPERATORS.filter((operator) => conditions[operator] !== undefined).map(\n      (operator) => [operator, conditions[operator]],\n    ),\n  );\n\n  if (pattern !== undefined) {\n    parts.push(String(pattern));\n  } else if (Object.keys(operators).length) {\n    parts.push(null);\n  }\n\n  if (Object.keys(operators).length) {\n    parts.push(operators);\n  }\n\n  return JSON.stringify(parts);\n};\n\n/**\n * View settings with the properties that the group expanders read and write. Any other property,\n * such as the view type, is carried over untouched.\n * @typedef {{\n * group?: GroupingConditions | null,\n * collapsedGroups?: Record<string, string[]>,\n * expandedGroups?: Record<string, string[]>,\n * } & Record<string, unknown>} ViewWithGroups\n */\n\n/**\n * Name of the group holding the items that have no value for the grouping field, or no match for\n * its pattern. A stable token rather than the localized “Other” label, so that anything keyed by\n * the group name — the collapsed state saved in the view — survives a change of the UI locale.\n * Display it with {@link getGroupLabel}.\n */\nexport const OTHER_GROUP_NAME = '*other';\n\n/**\n * Get the label of a group as it’s shown in the list.\n * @param {string} name Group name.\n * @returns {string} The localized “Other” label for {@link OTHER_GROUP_NAME}, otherwise the name.\n */\nexport const getGroupLabel = (name) => (name === OTHER_GROUP_NAME ? _('other') : name);\n\n/**\n * Build a sorted group map from a list of items.\n * @template T\n * @param {T[]} items Items to group.\n * @param {string | RegExp | boolean | undefined} pattern Pattern to extract the group key from each\n * value. When provided, the first match is used as the key; unmatched items fall back to\n * {@link OTHER_GROUP_NAME}.\n * @param {(item: T) => any} getValue Function to get the groupable field value from an item.\n * @returns {[string, T[]][]} Array of `[groupKey, items]` pairs, sorted by the group labels.\n */\nexport const buildGroupMap = (items, pattern, getValue) => {\n  const regex = getRegex(pattern);\n\n  // Grouped into a `Map` rather than a plain object, as a value like `constructor` or `__proto__`\n  // would otherwise hit an inherited property\n  const groups = Map.groupBy(items, (item) => {\n    const value = getValue(item);\n\n    return value === null || value === undefined\n      ? OTHER_GROUP_NAME\n      : regex\n        ? (String(value).match(regex)?.[0] ?? OTHER_GROUP_NAME)\n        : String(value);\n  });\n\n  return [...groups].sort(([a], [b]) => compare(getGroupLabel(a), getGroupLabel(b)));\n};\n\n/**\n * Group the given items by a view group’s conditions.\n * @template T\n * @param {T[]} items Items to group.\n * @param {GroupingConditions | null | undefined} conditions Grouping conditions.\n * @param {(item: T, field: string) => any} getValue Function to get the groupable field value from\n * an item.\n * @returns {Record<string, T[]>} Grouped items, where the key is a group name, displayed with\n * {@link getGroupLabel}, and the value is an item list. Without a field to group by, all the items\n * are in a single group named `*`.\n */\nexport const groupItems = (items, conditions, getValue) => {\n  const { field, pattern } = conditions ?? {};\n\n  if (!field) {\n    return items.length ? { '*': items } : {};\n  }\n\n  return Object.fromEntries(buildGroupMap(items, pattern, (item) => getValue(item, field)));\n};\n\n/**\n * Check whether a value matches a filter condition.\n * @param {any} value The value to test.\n * @param {any} pattern Expected value.\n * @param {RegExp | null | undefined} regex Compiled regex derived from the pattern, if any.\n * @returns {boolean} Whether the value matches the condition.\n */\nexport const matchesFilter = (value, pattern, regex) => {\n  if (regex) {\n    return regex.test(String(value ?? ''));\n  }\n\n  return value === pattern;\n};\n\n/**\n * Compare two sort keys in ascending order.\n * @param {string | number} a First key.\n * @param {string | number} b Second key.\n * @param {boolean} isStringType Whether the keys should be compared as strings (locale-aware); if\n * `false`, numeric subtraction is used instead.\n * @returns {number} Negative if `a` comes first, positive if `b` comes first, `0` if they are\n * equal.\n */\nexport const compareSortKeys = (a, b, isStringType) =>\n  isStringType\n    ? compare(/** @type {string} */ (a), /** @type {string} */ (b))\n    : /** @type {number} */ (a) - /** @type {number} */ (b);\n\n/**\n * Sort an array of items using a key function and apply ascending/descending order. An item whose\n * key is `undefined` has no value to sort by, so it goes last in either order, keeping its place\n * among the other such items.\n * @template T\n * @param {T[]} items Items to sort in place.\n * @param {(item: T) => string | number | undefined} getKey Returns the sort key for an item, or\n * `undefined` if the item has no value. Called once per item.\n * @param {boolean} isStringType Whether keys should be compared as strings (locale-aware); if\n * `false`, numeric subtraction is used instead.\n * @param {string | undefined} [order] Sort order; reverses the array when `'descending'`.\n * @returns {T[]} The sorted array (same reference).\n */\nexport const sortItemsByKey = (items, getKey, isStringType, order) => {\n  const keyedItems = items.map((item) => ({ item, key: getKey(item) }));\n  const valuedItems = keyedItems.filter(({ key }) => key !== undefined);\n  const emptyItems = keyedItems.filter(({ key }) => key === undefined);\n\n  valuedItems.sort(({ key: aKey }, { key: bKey }) =>\n    compareSortKeys(\n      /** @type {string | number} */ (aKey),\n      /** @type {string | number} */ (bKey),\n      isStringType,\n    ),\n  );\n\n  if (order === 'descending') {\n    valuedItems.reverse();\n  }\n\n  // Write the order back in place. Spreading the list into `splice()` would pass every item as an\n  // argument, which throws a `RangeError` once the list is large enough\n  [...valuedItems, ...emptyItems].forEach(({ item }, index) => {\n    items[index] = item;\n  });\n\n  return items;\n};\n\n/**\n * Get the names of the groups that can be collapsed. The `*` group, which holds every item when\n * the list isn’t grouped, has no caption and so no expander.\n * @param {string[]} names Names of all the groups in the list.\n * @returns {string[]} Names of the captioned groups.\n */\nexport const getCollapsibleGroupNames = (names) => names.filter((name) => name !== '*');\n\n/**\n * Get the key under which the collapsed groups of a view are saved. Each grouping condition\n * produces its own set of groups, so the collapsed state is kept per condition.\n * @param {GroupingConditions | null | undefined} conditions Grouping conditions.\n * @returns {string | undefined} Condition key from {@link getConditionKey}, or `undefined` when\n * the list isn’t grouped.\n */\nexport const getGroupingKey = (conditions) =>\n  conditions ? getConditionKey(conditions) : undefined;\n\n/**\n * Check whether the groups produced by the given grouping conditions start collapsed, because the\n * view group option they came from has the `collapsed` option enabled.\n * @param {ViewGroup[] | undefined} options View group options.\n * @param {GroupingConditions | null | undefined} conditions Grouping conditions of the view.\n * @returns {boolean} Whether the groups are collapsed unless the user has expanded them.\n * @see https://github.com/sveltia/sveltia-cms/issues/1151\n */\nexport const isCollapsedByDefault = (options, conditions) => {\n  const key = getGroupingKey(conditions);\n\n  return (\n    key !== undefined &&\n    !!options?.some(\n      (option) => option.collapsed === true && getConditionKey(getViewConditions(option)) === key,\n    )\n  );\n};\n\n/**\n * Get the property of the view settings that holds the names of the groups the user has toggled\n * from their default state, under each grouping condition’s key: the collapsed groups when groups\n * start expanded, and the expanded groups when they start collapsed. Saving the exceptions rather\n * than the full state means a group that appears later starts in the default state too.\n * @param {boolean} collapsedByDefault Whether the groups start collapsed.\n * @returns {'collapsedGroups' | 'expandedGroups'} Property name.\n */\nconst getToggledGroupsProp = (collapsedByDefault) =>\n  collapsedByDefault ? 'expandedGroups' : 'collapsedGroups';\n\n/**\n * Check whether a group is collapsed in the given view.\n * @param {ViewWithGroups} view View settings.\n * @param {string} name Group name.\n * @param {boolean} [collapsedByDefault] Whether the groups start collapsed. See\n * {@link isCollapsedByDefault}.\n * @returns {boolean} Whether the group’s items are hidden.\n */\nexport const isGroupCollapsed = (view, name, collapsedByDefault = false) => {\n  const key = getGroupingKey(view.group);\n\n  // The `*` group has no expander, so it’s always expanded\n  if (key === undefined || name === '*') {\n    return false;\n  }\n\n  const toggled = !!view[getToggledGroupsProp(collapsedByDefault)]?.[key]?.includes(name);\n\n  return toggled !== collapsedByDefault;\n};\n\n/**\n * Get the view settings with the toggled groups of the current grouping condition replaced.\n * @template {ViewWithGroups} T\n * @param {T} view View settings.\n * @param {string[]} names Names of the groups toggled from their default state. The condition is\n * dropped from the saved state when there is none, and so is the whole property once it’s empty.\n * @param {boolean} collapsedByDefault Whether the groups start collapsed.\n * @returns {T} New view settings.\n */\nconst setToggledGroups = (view, names, collapsedByDefault) => {\n  const key = getGroupingKey(view.group);\n\n  // The list isn’t grouped, so there is nothing to collapse\n  if (key === undefined) {\n    return view;\n  }\n\n  const prop = getToggledGroupsProp(collapsedByDefault);\n  const { [key]: _current, ...others } = view[prop] ?? {};\n  const groups = names.length ? { ...others, [key]: names } : others;\n  const { [prop]: _previous, ...rest } = view;\n\n  return /** @type {T} */ (Object.keys(groups).length ? { ...rest, [prop]: groups } : rest);\n};\n\n/**\n * Get the view settings with one group collapsed or expanded.\n * @template {ViewWithGroups} T\n * @param {T} view View settings.\n * @param {string} name Group name.\n * @param {boolean} collapsed Whether to hide the group’s items.\n * @param {boolean} [collapsedByDefault] Whether the groups start collapsed. See\n * {@link isCollapsedByDefault}.\n * @returns {T} New view settings.\n */\nexport const setGroupCollapsed = (view, name, collapsed, collapsedByDefault = false) => {\n  const key = getGroupingKey(view.group);\n  const prop = getToggledGroupsProp(collapsedByDefault);\n  const current = key === undefined ? [] : (view[prop]?.[key] ?? []);\n  const names = current.filter((_name) => _name !== name);\n\n  if (collapsed !== collapsedByDefault) {\n    names.push(name);\n  }\n\n  return setToggledGroups(view, names, collapsedByDefault);\n};\n\n/**\n * Get the view settings with all the given groups collapsed or expanded.\n * @template {ViewWithGroups} T\n * @param {T} view View settings.\n * @param {string[]} names Names of the collapsible groups.\n * @param {boolean} collapsed Whether to hide the groups’ items.\n * @param {boolean} [collapsedByDefault] Whether the groups start collapsed. See\n * {@link isCollapsedByDefault}.\n * @returns {T} New view settings.\n */\nexport const setAllGroupsCollapsed = (view, names, collapsed, collapsedByDefault = false) =>\n  setToggledGroups(view, collapsed === collapsedByDefault ? [] : [...names], collapsedByDefault);\n\n/**\n * Initialize a view settings state backed by IndexedDB and persist any changes to it.\n * @param {{ databaseName?: string } | undefined} repository Repository info.\n * @param {string} storageKey Key used to store/retrieve settings in the database.\n * @param {{ current: Record<string, any> | undefined }} settingsState State to initialize and\n * persist.\n * @param {object} [options] Options.\n * @param {Record<string, any>} [options.defaults] Default settings, overridden by the saved ones.\n * @returns {Promise<() => void>} Function to stop persisting the settings, so that the effect\n * doesn’t pile up when the settings are initialized again.\n */\nexport const initViewSettingsStorage = async (\n  repository,\n  storageKey,\n  settingsState,\n  { defaults = {} } = {},\n) => {\n  const settingsDB = getRepositoryDatabase(repository, 'ui-settings');\n  /** @type {any} */\n  let saved;\n\n  // The saved settings are optional, so an IndexedDB failure mustn’t leave the view unset\n  try {\n    saved = await settingsDB?.get(storageKey);\n  } catch {\n    //\n  }\n\n  const initial = { ...defaults, ...(isObject(saved) ? saved : {}) };\n\n  settingsState.current = initial;\n\n  // Track the last persisted value in memory so we can skip redundant IndexedDB reads and writes\n  // every time the state changes (list views update this state frequently as users sort/filter).\n  /** @type {Record<string, any> | undefined} */\n  let lastSaved = initial;\n\n  return createRootEffect(() => {\n    const { current: _settings } = settingsState;\n\n    if (equal(_settings, lastSaved)) {\n      return;\n    }\n\n    lastSaved = _settings;\n\n    (async () => {\n      try {\n        await settingsDB?.set(storageKey, _settings);\n      } catch {\n        //\n      }\n    })();\n  });\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { getViewConditions } from '$lib/services/common/view';\n\n/**\n * @import {\n * FilteringConditions,\n * GroupingConditions,\n * ParsedSortableFields,\n * } from '$lib/types/private';\n * @import { SortableField, SortableFields, ViewFilter, ViewGroup } from '$lib/types/public';\n */\n\n/**\n * Parse a view configuration that supports both an array (Netlify/Decap CMS compatible) and an\n * object (Static CMS compatible) format.\n * @template {ViewFilter | ViewGroup} T\n * @param {T[] | Record<string, any> | undefined} config Raw configuration value.\n * @param {string} optionsKey Property name to extract the options array from when config is an\n * object.\n * @returns {{ options: T[], default?: FilteringConditions | GroupingConditions }} Parsed config.\n */\nexport const parseViewOptions = (config, optionsKey) => {\n  if (Array.isArray(config)) {\n    return { options: config };\n  }\n\n  if (isObject(config)) {\n    const options = config[optionsKey];\n    const defaultName = config.default;\n\n    if (Array.isArray(options)) {\n      const defaultItem = defaultName\n        ? options.find(({ name }) => name === defaultName)\n        : undefined;\n\n      return {\n        options,\n        default: defaultItem ? getViewConditions(defaultItem) : undefined,\n      };\n    }\n  }\n\n  return { options: [] };\n};\n\n/**\n * Check if the given value is a valid array of strings.\n * @param {unknown} arr Value to check.\n * @returns {arr is string[]} Whether the value is a valid array of strings.\n */\nexport const isValidArray = (arr) =>\n  Array.isArray(arr) && arr.every((item) => typeof item === 'string');\n\n/**\n * Check if the given `sortable_fields` list item is a Decap CMS sortable field object with the\n * `default_sort` option enabled.\n * @param {unknown} item List item.\n * @returns {item is SortableField} Result.\n */\nexport const hasDefaultSort = (item) => {\n  const value = isObject(item) ? /** @type {SortableField} */ (item).default_sort : undefined;\n\n  return value === true || value === 'asc' || value === 'desc';\n};\n\n/**\n * Parse a `sortable_fields` list, in which each item is either a field key path or a Decap CMS\n * sortable field object with the `field`, `label` and `default_sort` options. Invalid items are\n * ignored; they are reported by the configuration validator.\n * @param {(string | SortableField)[]} items List items.\n * @returns {ParsedSortableFields} Parsed sortable fields configuration.\n */\nconst parseSortableFieldList = (items) => {\n  /** @type {string[]} */\n  const keys = [];\n  /** @type {Record<string, string>} */\n  const labels = {};\n  /** @type {SortableField | undefined} */\n  let defaultItem;\n\n  items.forEach((item) => {\n    if (typeof item === 'string') {\n      keys.push(item);\n\n      return;\n    }\n\n    if (!isObject(item) || typeof item.field !== 'string') {\n      return;\n    }\n\n    const { field, label } = item;\n\n    keys.push(field);\n\n    if (typeof label === 'string' && label.trim()) {\n      labels[field] = label;\n    }\n\n    // Only one item may have `default_sort`; the validator reports any other, and the first wins\n    if (!defaultItem && hasDefaultSort(item)) {\n      defaultItem = item;\n    }\n  });\n\n  return {\n    keys,\n    ...(Object.keys(labels).length ? { labels } : {}),\n    ...(defaultItem\n      ? {\n          defaultKey: defaultItem.field,\n          defaultOrder: defaultItem.default_sort === 'desc' ? 'descending' : 'ascending',\n        }\n      : {}),\n  };\n};\n\n/**\n * Parse custom sortable fields configuration.\n * @param {(string | SortableField)[] | SortableFields} customSortableFields Custom sortable fields\n * configuration.\n * @returns {ParsedSortableFields} Parsed sortable fields configuration.\n */\nexport const parseCustomSortableFields = (customSortableFields) => {\n  // Netlify/Decap CMS compatibility: if `sortable_fields` is an array, it should be treated as a\n  // list of field keys, or sortable field objects as supported by Decap CMS 3.10\n  if (Array.isArray(customSortableFields)) {\n    return parseSortableFieldList(customSortableFields);\n  }\n\n  // Static CMS compatibility: if `sortable_fields` is an object, it should be treated as a\n  // definition object with `fields` and `default` properties\n  if (isObject(customSortableFields)) {\n    const { fields: keys, default: settings } = customSortableFields;\n\n    if (!isValidArray(keys)) {\n      return { keys: [] };\n    }\n\n    if (!isObject(settings)) {\n      return { keys };\n    }\n\n    return {\n      keys,\n      defaultKey: settings.field,\n      defaultOrder:\n        // Allow title case for Static CMS compatibility\n        ['descending', 'Descending'].includes(settings.direction ?? '')\n          ? 'descending'\n          : 'ascending',\n    };\n  }\n\n  // Invalid configuration\n  return { keys: [] };\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\n\n/**\n * @import { EntryCollection } from '$lib/types/public';\n */\n\n/**\n * Key of the column holding the entry summary, the same as the sort key for it.\n */\nexport const SUMMARY_COLUMN_KEY = '_summary';\n\n/**\n * Entry metadata property keys that can be used in place of a field key path: in the `filter`,\n * `sortable_fields`, `view_groups`, `view_filters` and `table_columns` options, and as sort keys.\n * These are resolved from the entry itself rather than the collection’s `fields`.\n * @type {string[]}\n */\nexport const METADATA_KEYS = ['slug', 'commit_author', 'commit_date'];\n\n/**\n * Template tags for entry metadata that a template column can use, the same as in the `summary`\n * option, besides the special keys, which have localized labels of their own.\n */\nexport const METADATA_TEMPLATE_TAGS = ['dirname', 'filename', 'extension', 'locales'];\n\n/**\n * Regular expression matching a template made of a single tag without transformations, e.g.\n * `{{locales}}` or `{{fields.date}}`, capturing the tag name.\n */\nexport const SINGLE_TAG_REGEX = /^\\{\\{\\s*(?:fields\\.)?([^\\s|{}]+)\\s*\\}\\}$/;\n\n/**\n * Check whether a column key is a template, like a `summary` template, e.g. `{{locales}}` or\n * `{{dirname}}/{{filename}}.{{extension}}`, rather than a field name or a special key.\n * @param {string} key Column key.\n * @returns {boolean} Result.\n */\nexport const isTemplateColumnKey = (key) => hasTemplateTags(key);\n\n/**\n * Get the columns configured for a collection’s table view with the `table_columns` option, or its\n * Static CMS alias `summary_fields`, where `summary` stands for the entry summary.\n * @param {Pick<EntryCollection, 'table_columns' | 'summary_fields'>} collection Entry collection,\n * or its raw configuration.\n * @returns {{ key: string, label?: string }[] | undefined} Columns, as configured. `undefined` if\n * neither option is defined.\n */\nexport const getConfiguredTableColumns = (collection) => {\n  const { table_columns: tableColumns, summary_fields: summaryFields } = collection;\n\n  if (Array.isArray(tableColumns)) {\n    return tableColumns.map((column) =>\n      isObject(column)\n        ? { key: /** @type {any} */ (column).field, label: /** @type {any} */ (column).label }\n        : { key: column },\n    );\n  }\n\n  if (Array.isArray(summaryFields)) {\n    return summaryFields.map((name) => ({ key: name === 'summary' ? SUMMARY_COLUMN_KEY : name }));\n  }\n\n  return undefined;\n};\n","import { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * Cache of {@link getLikelyLocale} results, keyed by locale code. The codes come from the\n * configuration, the UI locale and the APIs’ supported locales, so there are only a few of them,\n * while some are looked up often, e.g. a label on every render.\n * @type {Map<string, Intl.Locale | undefined>}\n */\nconst likelyLocaleCache = new Map();\n\n/**\n * Get the given locale with its likely subtags added, e.g. `zh-Hant-TW` for `zh-TW` and\n * `pa-Arab-PK` for `pa-PK`.\n * @param {string} locale Locale code.\n * @returns {Intl.Locale | undefined} Maximized locale, or `undefined` if the locale code is\n * invalid.\n */\nexport const getLikelyLocale = (locale) =>\n  getOrCreate(likelyLocaleCache, locale, () => {\n    try {\n      return new Intl.Locale(locale).maximize();\n    } catch {\n      return undefined;\n    }\n  });\n\n/**\n * Get the language and the likely script of a locale, e.g. `zh-Hant` for `zh-TW` or `zh-HK`, and\n * `zh-Hans` for `zh` or `zh-SG`, so locales written in different scripts don’t match.\n * @param {string} locale Locale code.\n * @returns {string | undefined} Language and script, or `undefined` if the locale code is invalid.\n */\nexport const getLanguageScript = (locale) => {\n  const likelyLocale = getLikelyLocale(locale);\n\n  return likelyLocale && `${likelyLocale.language}-${likelyLocale.script}`;\n};\n","import { locale as appLocale } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { isFieldMirrored } from '$lib/services/contents/i18n/fields';\nimport { getLanguageScript } from '$lib/services/utils/locale';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { Field } from '$lib/types/public';\n */\n\n/**\n * Option of a field or a variable type that can have localized values, given as a map keyed by\n * locale in an option of the same name with the `_localized` suffix, e.g. `label_localized`.\n * @typedef {'label' | 'hint' | 'label_singular' | 'default'} LocalizableOption\n */\n\n/**\n * Configuration that can hold localized options: a field or a variable type of a List/Object field.\n * @typedef {Record<string, any>} LocalizableConfig\n */\n\n/**\n * Get the language and script of the given locale code, e.g. `zh-Hant` for `zh-TW`, so locales\n * written in different scripts don’t match.\n * @param {string} locale Locale code.\n * @returns {string} Language and script, or the code in lowercase if it’s not a valid locale.\n */\nconst getLanguageScriptOrCode = (locale) => getLanguageScript(locale) ?? locale.toLowerCase();\n\n/**\n * Find the key of a localized value map that matches the given application UI locale. The UI locale\n * comes with a region, e.g. `en-CA`, while the map is keyed with the content locales of the site,\n * which may not, so a key for the same language and script matches as well, the bare language\n * first. A Traditional Chinese UI therefore never gets a Simplified Chinese value.\n * @param {Record<string, any>} map Localized value map.\n * @param {string} uiLocale Application UI locale.\n * @returns {string | undefined} Matching key.\n */\nconst findUiLocaleKey = (map, uiLocale) => {\n  if (Object.hasOwn(map, uiLocale)) {\n    return uiLocale;\n  }\n\n  const languageScript = getLanguageScriptOrCode(uiLocale);\n  const keys = Object.keys(map).filter((key) => getLanguageScriptOrCode(key) === languageScript);\n\n  return keys.find((key) => !key.includes('-')) ?? keys[0];\n};\n\n/**\n * Get the localized value map of the given option, if it’s defined.\n * @param {LocalizableConfig} config Field or variable type configuration.\n * @param {LocalizableOption} option Option name.\n * @returns {Record<string, any> | undefined} Localized value map.\n */\nconst getLocalizedValueMap = (config, option) => {\n  const map = config[`${option}_localized`];\n\n  return isObject(map) ? map : undefined;\n};\n\n/**\n * Get the value of a UI text option, such as `label` or `hint`, for the given content locale. The\n * localized value for the locale, given with the `_localized` counterpart of the option, comes\n * first; where the locale isn’t known (`_default` or `undefined`, as with a collection without\n * i18n, or outside of the entry editor) or has no localized value, the application UI locale is\n * matched instead. The option itself is the fallback.\n * @param {object} args Arguments.\n * @param {LocalizableConfig | undefined} args.config Field or variable type configuration. It can\n * be missing, e.g. for a key path that names no field, in which case there is no value.\n * @param {Exclude<LocalizableOption, 'default'>} args.option Option name.\n * @param {InternalLocaleCode} [args.locale] Content locale, e.g. the locale of the editor pane.\n * @returns {string | undefined} Option value.\n */\nexport const getLocalizedOption = ({ config, option, locale }) => {\n  if (!config) {\n    return undefined;\n  }\n\n  const map = getLocalizedValueMap(config, option);\n\n  if (map) {\n    if (locale && locale !== '_default' && Object.hasOwn(map, locale)) {\n      return map[locale];\n    }\n\n    const uiLocaleKey = appLocale.current ? findUiLocaleKey(map, appLocale.current) : undefined;\n\n    if (uiLocaleKey !== undefined) {\n      return map[uiLocaleKey];\n    }\n  }\n\n  return config[option];\n};\n\n/**\n * Get the label of a field or a variable type for the given content locale, falling back to its\n * name.\n * @param {object} args Arguments.\n * @param {LocalizableConfig} args.config Field or variable type configuration.\n * @param {InternalLocaleCode} [args.locale] Content locale. See {@link getLocalizedOption}.\n * @returns {string} Label.\n */\nexport const getFieldLabel = ({ config, locale }) =>\n  getLocalizedOption({ config, option: 'label', locale }) || config.name || '';\n\n/**\n * Apply the localized default value of a field for the given content locale. Unlike the UI text\n * options, a default value is content, so only the content locale is matched. A field using the\n * `duplicate` or `sync` i18n strategy takes the default locale’s value, as it holds the same value\n * in every locale.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {InternalLocaleCode} args.locale Content locale.\n * @param {InternalLocaleCode} args.defaultLocale Default locale of the entry draft.\n * @returns {Field} Field configuration with the `default` option replaced by the localized value\n * and the `default_localized` option removed, or the given configuration as is if it has no\n * localized value for the locale.\n */\nexport const localizeDefaultValue = ({ fieldConfig, locale, defaultLocale }) => {\n  const map = getLocalizedValueMap(fieldConfig, 'default');\n\n  if (!map) {\n    return fieldConfig;\n  }\n\n  const { default_localized: _localized, ...rest } = /** @type {Record<string, any>} */ (\n    fieldConfig\n  );\n\n  const targetLocale = isFieldMirrored(fieldConfig.i18n) ? defaultLocale : locale;\n\n  return /** @type {Field} */ (\n    Object.hasOwn(map, targetLocale) ? { ...rest, default: map[targetLocale] } : rest\n  );\n};\n","import { _ } from '@sveltia/i18n';\nimport { unique } from '@sveltia/utils/array';\n\nimport { allEntries } from '$lib/services/contents';\nimport { selectedCollection } from '$lib/services/contents/collection';\nimport { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { parseCustomSortableFields } from '$lib/services/contents/collection/view/options';\nimport { SUMMARY_COLUMN_KEY } from '$lib/services/contents/collection/view/table-keys';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { storesNumber } from '$lib/services/contents/fields/number/helpers';\nimport { getLocalizedOption } from '$lib/services/contents/i18n/options';\nimport { isNumeric } from '$lib/services/utils/number';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * InternalEntryCollection,\n * ParsedSortableFields,\n * SortingConditions,\n * SortKey,\n * SortOrder,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Default sort keys for the entry collection. In addition to the `title`, `date`, `author` and\n * `description` fields supported by Netlify/Decap CMS, it also includes `name` for the entry name\n * field, which is used by Sveltia CMS to infer the entry title.\n * @see https://decapcms.org/docs/configuration-options/#sortable_fields\n * @see https://sveltiacms.app/en/docs/collections/entries/views#sorting\n */\nexport const DEFAULT_SORT_KEYS = ['title', 'name', 'date', 'author', 'description'];\n\n/**\n * Supported sort orders.\n * @type {SortOrder[]}\n */\nexport const SORT_ORDERS = ['ascending', 'descending'];\n\n/**\n * Common date field keys that require special handling in sorting.\n * @type {string[]}\n */\nexport const DATE_FIELDS = ['date', 'commit_date'];\n\n/**\n * Map of special sort keys and their types.\n * @type {Record<string, StringConstructor | DateConstructor>}\n */\nexport const SPECIAL_SORT_KEY_TYPES = {\n  slug: String,\n  commit_author: String,\n  commit_date: Date,\n  [SUMMARY_COLUMN_KEY]: String,\n  _manual: String,\n};\n\n/**\n * List of special sort keys.\n * @type {string[]}\n */\nexport const SPECIAL_SORT_KEYS = Object.keys(SPECIAL_SORT_KEY_TYPES);\n\n/**\n * Get default sort keys for the entry collection.\n * @param {FieldKeyPath | undefined} customIdField Custom ID field key path.\n * @returns {ParsedSortableFields} Parsed sortable fields configuration.\n */\nexport const getDefaultSortKeys = (customIdField) => {\n  if (customIdField) {\n    // Filter out the custom ID field from DEFAULT_SORT_KEYS to avoid duplicates\n    const filteredDefaultKeys = DEFAULT_SORT_KEYS.filter((key) => key !== customIdField);\n\n    return {\n      keys: [customIdField, ...filteredDefaultKeys],\n      defaultKey: customIdField,\n    };\n  }\n\n  return { keys: [...DEFAULT_SORT_KEYS] };\n};\n\n/**\n * Get sort configuration for the given collection.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Collection.\n * @param {boolean} args.isCommitAuthorAvailable Whether the entries in the collection have a commit\n * author. Available for some Git-based backends.\n * @param {boolean} args.isCommitDateAvailable Whether the entries in the collection have a commit\n * date. Available for some Git-based backends.\n * @returns {{ keys: string[], labels?: Record<string, string>, default: SortingConditions }} A list\n * of sortable fields, custom labels given in the configuration, and default sort conditions.\n */\nexport const getSortConfig = ({ collection, isCommitAuthorAvailable, isCommitDateAvailable }) => {\n  const {\n    name: collectionName,\n    identifier_field: customIdField,\n    sortable_fields: customSortableFields,\n    summary: summaryTemplate,\n    _i18n: { i18nEnabled, canonicalSlug },\n  } = collection;\n\n  const parsed = customSortableFields\n    ? parseCustomSortableFields(customSortableFields)\n    : getDefaultSortKeys(customIdField);\n\n  // Copy the keys, which can be the configured `sortable_fields` array itself, before adding any\n  let keys = [...parsed.keys];\n  let { defaultKey, defaultOrder } = parsed;\n  const { labels } = parsed;\n\n  // Special handling for summary field: if the collection has a summary template defined, we add\n  // `_summary` as a special sort key, which uses the generated summary value\n  if (summaryTemplate) {\n    keys.unshift(SUMMARY_COLUMN_KEY);\n  }\n\n  // Make sure the keys are valid field keys or special keys. The canonical slug key,\n  // `translationKey` by default, is part of the content of each localized entry without being a\n  // field, so it can be used as a sort key when i18n is enabled. This has to come first: the\n  // default `date` and `author` keys only stand in for the commit date and author when the\n  // collection has such fields\n  const specialKeys = i18nEnabled ? [...SPECIAL_SORT_KEYS, canonicalSlug.key] : SPECIAL_SORT_KEYS;\n\n  keys = unique(keys).filter(\n    (key) => !!key && (specialKeys.includes(key) || !!getField({ collectionName, keyPath: key })),\n  );\n\n  const hasCommitAuthorKey = keys.includes('commit_author');\n  const hasCommitDateKey = keys.includes('commit_date');\n  // An entry stored in a file with the other entries of the collection carries the file’s last\n  // commit, which is about whichever entry was changed last, so it doesn’t tell the entries apart\n  const isArrayFile = isArrayFileCollection(collection);\n\n  if (isCommitAuthorAvailable && !isArrayFile) {\n    if (!keys.includes('author') && !hasCommitAuthorKey) {\n      keys.push('commit_author');\n    }\n  } else if (hasCommitAuthorKey) {\n    keys = keys.filter((key) => key !== 'commit_author');\n  }\n\n  if (isCommitDateAvailable && !isArrayFile) {\n    if (!keys.includes('date') && !hasCommitDateKey) {\n      keys.push('commit_date');\n    }\n  } else if (hasCommitDateKey) {\n    keys = keys.filter((key) => key !== 'commit_date');\n  }\n\n  // If the collection allows reordering, expose a single special `_manual` sort key that maps to\n  // the order field. We hide the raw order field key from the dropdown — even if the user listed it\n  // in `sortable_fields` — to avoid showing two equivalent options.\n  const orderKey = getOrderFieldKey(collection);\n\n  // An entry collection storing all the entries in one file keeps them in the order of the array,\n  // so the manual order is always available there\n  if (orderKey || isArrayFileCollection(collection)) {\n    keys = keys.filter((key) => key !== orderKey);\n\n    if (!keys.includes('_manual')) {\n      keys.unshift('_manual');\n    }\n\n    defaultKey = '_manual';\n    defaultOrder = 'ascending';\n  }\n\n  defaultKey = defaultKey && keys.includes(defaultKey) ? defaultKey : keys[0];\n  defaultOrder ??= defaultKey ? 'ascending' : undefined;\n\n  return {\n    keys,\n    labels,\n    default: {\n      key: defaultKey,\n      order: defaultOrder,\n    },\n  };\n};\n\n/**\n * Get the type of the given key, which can be a field key path or one of the entry metadata keys.\n * @param {object} args Arguments.\n * @param {string} args.key Key.\n * @param {Field | undefined} args.fieldConfig Field configuration object.\n * @returns {StringConstructor | BooleanConstructor | NumberConstructor | DateConstructor} Type of\n * the key.\n */\nexport const getSortKeyType = ({ key, fieldConfig }) => {\n  // A field named after an `Object.prototype` member, e.g. `constructor`, isn’t a special key\n  if (Object.hasOwn(SPECIAL_SORT_KEY_TYPES, key)) {\n    return SPECIAL_SORT_KEY_TYPES[key];\n  }\n\n  if (fieldConfig?.widget === 'boolean') {\n    return Boolean;\n  }\n\n  // A Compute field yielding a number has the same `value_type` option, but defaults to `string`\n  if (fieldConfig && storesNumber(fieldConfig)) {\n    return Number;\n  }\n\n  return String;\n};\n\n/**\n * Resolve the given sort key to the key of the field it sorts by. The `_manual` key stands for the\n * order field when that is a configured field, e.g. a Number field named `weight`, so it’s labelled\n * and typed like the field.\n * @param {InternalEntryCollection} collection Collection.\n * @param {string} key Sort key.\n * @returns {string} Order field key for `_manual` backed by a configured field, otherwise `key`.\n * @see https://github.com/sveltia/sveltia-cms/issues/1169\n */\nexport const resolveSortFieldKey = (collection, key) => {\n  const orderKey = key === '_manual' ? getOrderFieldKey(collection) : undefined;\n\n  return orderKey && getField({ collectionName: collection.name, keyPath: orderKey })\n    ? orderKey\n    : key;\n};\n\n/**\n * Get a field’s label by key.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Collection.\n * @param {FieldKeyPath | string} args.key Field key path or one of other entry metadata property\n * keys: `slug`, `commit_author` and `commit_date`.\n * @returns {string} Label. For a nested field, it would be something like `Name – English`.\n */\nexport const getSortKeyLabel = ({ collection, key }) => {\n  if ([...SPECIAL_SORT_KEYS, 'name'].includes(key)) {\n    return _(`sort_keys.${key}`);\n  }\n\n  if (key.includes('.')) {\n    return key\n      .split('.')\n      .map((_key, index, arr) => {\n        if (isNumeric(_key)) {\n          return undefined;\n        }\n\n        const keyPath = arr.slice(0, index + 1).join('.');\n        const field = getField({ collectionName: collection.name, keyPath });\n\n        return getLocalizedOption({ config: field, option: 'label' }) || _key;\n      })\n      .filter(Boolean)\n      .join(' – ');\n  }\n\n  const field = collection.fields?.find(({ name }) => name === key);\n\n  return getLocalizedOption({ config: field, option: 'label' }) || key;\n};\n\n/**\n * List of available sort keys for the selected entry collection. A key is labelled with the\n * `label` given in the `sortable_fields` option, if any. `getSortKeyLabel()` may return a localized\n * label, and it reads the current app locale, so the list is also recomputed when the locale\n * changes. A key sorted as a number is marked as such, so that the sort menu words its orders for\n * one, e.g. “small to large”.\n * @type {{ readonly current: SortKey[] }}\n */\nexport const sortKeys = createDerivedState(() => {\n  const collection = selectedCollection.current;\n\n  // Disable sorting for file/singleton collection\n  if (collection?._type !== 'entry') {\n    return [];\n  }\n\n  const { current: _allEntries } = allEntries;\n\n  const { keys, labels } = getSortConfig({\n    collection,\n    isCommitAuthorAvailable: _allEntries.some((entry) => !!entry.commitAuthor),\n    isCommitDateAvailable: _allEntries.some((entry) => !!entry.commitDate),\n  });\n\n  return keys.map((key) => {\n    const fieldKey = resolveSortFieldKey(collection, key);\n    const fieldConfig = getField({ collectionName: collection.name, keyPath: fieldKey });\n\n    const label =\n      labels?.[key] ?? labels?.[fieldKey] ?? getSortKeyLabel({ collection, key: fieldKey });\n\n    /** @type {SortKey} */\n    const sortKey = { key, label };\n\n    if (getSortKeyType({ key: fieldKey, fieldConfig }) === Number) {\n      sortKey.type = 'number';\n    }\n\n    return sortKey;\n  });\n});\n","import { sortItemsByKey } from '$lib/services/common/view';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { isManualOrderKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { getOrderValueGetter } from '$lib/services/contents/collection/entries/reorder/sort';\nimport { getSortKeyType } from '$lib/services/contents/collection/view/sort-keys';\nimport { SUMMARY_COLUMN_KEY } from '$lib/services/contents/collection/view/table-keys';\nimport {\n  getListedEntryValue,\n  isEmptyValue,\n  normalizeMultiValue,\n} from '$lib/services/contents/collection/view/values';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { RICH_TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getDate } from '$lib/services/contents/fields/date-time/parse';\nimport { removeMarkdownSyntax } from '$lib/services/utils/markdown';\n\n/**\n * @import {\n * Entry,\n * InternalCollection,\n * InternalEntryCollection,\n * SortingConditions,\n * } from '$lib/types/private';\n * @import { DateTimeField } from '$lib/types/public';\n */\n\n/**\n * Maximum length of a Markdown value used as a sort key, before its syntax is removed.\n */\nconst MARKDOWN_SORT_KEY_LENGTH = 1000;\n\n/**\n * List of fields that may contain Markdown syntax and should be stripped before sorting. This\n * includes `title`, `summary`, and `description`, which are commonly used in entry collections.\n * @type {string[]}\n */\nexport const MARKDOWN_FIELD_KEYS = ['title', 'summary', 'description'];\n\n/**\n * Get a function that computes the sort key for a single entry. Pre-computing this once (O(n))\n * instead of re-computing inside the comparator (O(n log n)) avoids re-parsing dates and stripping\n * Markdown syntax on every comparison. An entry without a value gets `undefined`, which\n * `sortItemsByKey()` puts last in either order, so empty numbers, dates and strings alike end up\n * at the bottom, rather than among the negative numbers, at the epoch or before `a`. A Boolean\n * field without a value is taken as `false`, as the editor shows it.\n * @param {object} args Arguments.\n * @param {string} args.key Sort key field path.\n * @param {StringConstructor | NumberConstructor | DateConstructor | BooleanConstructor} args.type\n * Sort key type.\n * @param {InternalCollection} args.collection Collection.\n * @param {string} args.locale Locale.\n * @param {string} args.collectionName Collection name.\n * @param {DateTimeField | undefined} args.dateFieldConfig DateTime field config, or `undefined` if\n * the field is not a DateTime field.\n * @param {boolean} args.isMarkdownField Whether the field may contain Markdown syntax.\n * @returns {(entry: Entry) => string | number | undefined} Sort key getter for one entry.\n */\nexport const getSortKeyGetter = ({\n  key,\n  type,\n  collection,\n  locale,\n  collectionName,\n  dateFieldConfig,\n  isMarkdownField,\n}) => {\n  // Special handling for summary, which uses a generated value instead of a raw field value\n  if (key === SUMMARY_COLUMN_KEY) {\n    return (/** @type {Entry} */ entry) =>\n      getEntrySummary(collection, entry, { locale, useTemplate: true });\n  }\n\n  if (dateFieldConfig) {\n    return (/** @type {Entry} */ entry) => {\n      const raw = getListedEntryValue({ entry, locale, collectionName, key });\n      const time = getDate(raw, dateFieldConfig, locale)?.getTime() ?? NaN;\n\n      // A date that can’t be parsed is no better than a missing one\n      return Number.isNaN(time) ? undefined : time;\n    };\n  }\n\n  if (type === String) {\n    return (/** @type {Entry} */ entry) => {\n      const raw = normalizeMultiValue(getListedEntryValue({ entry, locale, collectionName, key }));\n\n      if (isEmptyValue(raw)) {\n        return undefined;\n      }\n\n      const str = String(raw);\n\n      // Only the beginning of a long Markdown value tells entries apart, and stripping the syntax\n      // takes time that grows faster than the length on a value crafted to be nested deeply\n      return isMarkdownField ? removeMarkdownSyntax(str.slice(0, MARKDOWN_SORT_KEY_LENGTH)) : str;\n    };\n  }\n\n  if (type === Boolean) {\n    return (/** @type {Entry} */ entry) => {\n      const raw = getListedEntryValue({ entry, locale, collectionName, key });\n\n      return raw === true ? 1 : 0;\n    };\n  }\n\n  // A number, or the commit date, which is a `Date`\n  return (/** @type {Entry} */ entry) => {\n    const raw = normalizeMultiValue(getListedEntryValue({ entry, locale, collectionName, key }));\n    const num = isEmptyValue(raw) ? NaN : Number(raw);\n\n    return Number.isNaN(num) ? undefined : num;\n  };\n};\n\n/**\n * Get a function that computes the sort key of an entry for the given field, along with how the\n * keys are compared. It doesn’t support the `_manual` key, which sorts by the reorder field.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection that the entries belong to.\n * @param {string} args.key Sort key field path, or one of the special sort keys like `slug`.\n * @param {string} args.locale Locale of the content to read the values from.\n * @returns {{ getSortKey: (entry: Entry) => string | number | undefined, isStringType: boolean }}\n * Sort key getter, and whether the keys are strings to be compared in a locale-aware manner rather\n * than numbers.\n */\nexport const getEntrySortKeyGetter = ({ collection, key, locale }) => {\n  const { name: collectionName } = collection;\n  const fieldConfig = getField({ collectionName, keyPath: key });\n  const type = getSortKeyType({ key, fieldConfig });\n\n  const dateFieldConfig =\n    fieldConfig?.widget === 'datetime' ? /** @type {DateTimeField} */ (fieldConfig) : undefined;\n\n  // Check if the field is a Markdown-enabled field: we use both the field config and a hardcoded\n  // key list to determine this, as some fields may be text fields that contain Markdown syntax.\n  const isMarkdownField =\n    RICH_TEXT_FIELD_TYPES.includes(fieldConfig?.widget ?? '') || MARKDOWN_FIELD_KEYS.includes(key);\n\n  const getSortKey = getSortKeyGetter({\n    key,\n    type,\n    collection,\n    locale,\n    collectionName,\n    dateFieldConfig,\n    isMarkdownField,\n  });\n\n  return { getSortKey, isStringType: !dateFieldConfig && type === String };\n};\n\n/**\n * Move the collection’s index file to the top of the sorted entries, where it should always be.\n * It’s told by its path rather than by its slug, because another collection’s index file within\n * this collection’s folder carries the same slug.\n * @param {Entry[]} entries Sorted entries, which are modified in place.\n * @param {InternalCollection} collection Collection that the entries belong to.\n * @returns {Entry[]} The given entries.\n */\nconst moveIndexFileToTop = (entries, collection) => {\n  const index = entries.findIndex((entry) => isCollectionIndexFile(collection, entry));\n\n  if (index > -1) {\n    entries.unshift(entries.splice(index, 1)[0]);\n  }\n\n  return entries;\n};\n\n/**\n * Sort the given entries.\n * @param {Entry[]} entries Entry list.\n * @param {InternalCollection} collection Collection that the entries belong to.\n * @param {SortingConditions} [conditions] Sorting conditions.\n * @returns {Entry[]} Sorted entry list.\n * @see https://decapcms.org/docs/configuration-options/#sortable_fields\n * @see https://sveltiacms.app/en/docs/collections/entries/views#sorting\n */\nexport const sortEntries = (entries, collection, { key, order } = {}) => {\n  const _entries = [...entries];\n\n  if (key === undefined) {\n    return _entries;\n  }\n\n  const {\n    _i18n: { defaultLocale: locale },\n  } = collection;\n\n  // The `_manual` special key sorts by the collection’s reorder field, or by the position in the\n  // array. Either way, the entries are sorted the same as in the reorder UI and when they are\n  // renumbered: an entry without a valid number goes last in either order, keeping its place among\n  // the others, as with any other key. The field may not be defined under the collection’s\n  // `fields`, so it would otherwise default to a string sort, and a missing value would come first\n  const { getSortKey, isStringType } = isManualOrderKey(collection, key)\n    ? {\n        getSortKey: getOrderValueGetter(/** @type {InternalEntryCollection} */ (collection)),\n        isStringType: false,\n      }\n    : getEntrySortKeyGetter({ collection, key, locale });\n\n  // `sortItemsByKey()` computes the key once per entry, so there’s no need for a lookup table here\n  sortItemsByKey(_entries, getSortKey, isStringType, order);\n\n  return moveIndexFileToTop(_entries, collection);\n};\n","import { compare } from '@sveltia/utils/string';\n\nimport { compareSortKeys } from '$lib/services/common/view';\nimport { isManualOrderKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { getOrderValueGetter } from '$lib/services/contents/collection/entries/reorder/sort';\nimport { getEntrySortKeyGetter } from '$lib/services/contents/collection/view/sort';\nimport { SPECIAL_SORT_KEYS } from '$lib/services/contents/collection/view/sort-keys';\nimport { isFieldInLocale } from '$lib/services/contents/i18n/shared-values';\n\n/**\n * @import {\n * Entry,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * RelationOption,\n * RelationOptionGroup,\n * } from '$lib/types/private';\n * @import { RelationFieldSortOptions } from '$lib/types/public';\n */\n\n/**\n * Get a function that computes the sort key of a referenced entry. The value is read from the\n * locale the options are built from: the current locale, falling back to the collection’s default\n * locale as the option labels do, so the options are sorted by the values the user\n * sees. The `_manual` key and the collection’s reorder field sort by the manual order, which is\n * always a number.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Referenced collection.\n * @param {string} args.key Sort key field path, or one of the special sort keys.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @returns {{ getSortKey: (entry: Entry) => string | number | undefined, isStringType: boolean }}\n * Sort key getter, and whether the keys are compared as strings.\n */\nconst getRelationSortKeyGetter = ({ collection, key, locale }) => {\n  if (isManualOrderKey(collection, key)) {\n    return { getSortKey: getOrderValueGetter(collection), isStringType: false };\n  }\n\n  const { defaultLocale } = collection._i18n;\n  const current = getEntrySortKeyGetter({ collection, key, locale });\n\n  const fallback =\n    locale === defaultLocale\n      ? current\n      : getEntrySortKeyGetter({ collection, key, locale: defaultLocale });\n\n  // A field that isn’t localized is only stored in the default locale, so it’s always read there\n  const isSharedField =\n    locale !== defaultLocale &&\n    !SPECIAL_SORT_KEYS.includes(key) &&\n    !isFieldInLocale({\n      getFieldArgs: { collectionName: collection.name, valueMap: {} },\n      locale,\n      defaultLocale,\n      keyPath: key,\n    });\n\n  /**\n   * Get the sort key of an entry from the current locale, or the default locale if the entry has no\n   * content in the current locale or the field isn’t localized.\n   * @param {Entry} entry Referenced entry.\n   * @returns {string | number | undefined} Sort key.\n   */\n  const getSortKey = (entry) =>\n    entry.locales[locale] && !isSharedField\n      ? current.getSortKey(entry)\n      : fallback.getSortKey(entry);\n\n  return { getSortKey, isStringType: current.isStringType };\n};\n\n/**\n * Sort the options of a Relation field by a field of the referenced entries, as the `sort_by`\n * option defines. An entry without a value goes last in either direction, as in the entry list, and\n * options with the same value are sorted by label, so they don’t follow the arbitrary order of the\n * entries. The options generated from the same entry share its value.\n * @param {object} args Arguments.\n * @param {RelationOptionGroup[]} args.groups Options grouped by referenced entry.\n * @param {InternalEntryCollection} args.collection Referenced collection.\n * @param {RelationFieldSortOptions} args.sortBy Sort options.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @returns {RelationOption[]} Sorted options.\n * @see https://github.com/sveltia/sveltia-cms/issues/572\n */\nexport const sortOptions = ({ groups, collection, sortBy, locale }) => {\n  const { field: key, direction } = sortBy;\n  const { getSortKey, isStringType } = getRelationSortKeyGetter({ collection, key, locale });\n  const sign = direction === 'descending' ? -1 : 1;\n\n  // Compute the key once per entry rather than in the comparator\n  const items = groups.flatMap(({ refEntry, options }) => {\n    const sortKey = getSortKey(refEntry);\n\n    return options.map((option) => ({ option, sortKey }));\n  });\n\n  items.sort((a, b) => {\n    if (a.sortKey !== b.sortKey) {\n      if (a.sortKey === undefined) return 1;\n      if (b.sortKey === undefined) return -1;\n\n      const diff = compareSortKeys(a.sortKey, b.sortKey, isStringType);\n\n      if (diff) {\n        return diff * sign;\n      }\n    }\n\n    return compare(a.option.label, b.option.label);\n  });\n\n  return items.map(({ option }) => option);\n};\n","import { compare } from '@sveltia/utils/string';\n\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { isManuallyOrdered } from '$lib/services/contents/collection/entries/reorder/config';\nimport { sortEntriesByOrderField } from '$lib/services/contents/collection/entries/reorder/sort';\nimport { getCollectionFileEntry } from '$lib/services/contents/collection/files';\nimport { getIdentifierFieldName } from '$lib/services/contents/collection/identifier';\nimport { getListItemKeys } from '$lib/services/contents/entry/key-paths';\nimport {\n  getObjectId,\n  getOptionLabelMap,\n} from '$lib/services/contents/fields/relation/helpers/cache';\nimport { processEntry } from '$lib/services/contents/fields/relation/helpers/entries';\nimport {\n  filterAndPrepareEntries,\n  resolveFilterValues,\n} from '$lib/services/contents/fields/relation/helpers/filters';\nimport { sortOptions } from '$lib/services/contents/fields/relation/helpers/sort';\nimport { prepareFieldTemplates } from '$lib/services/contents/fields/relation/helpers/templates';\nimport { getOrCreateBounded } from '$lib/services/utils/cache';\n\n/**\n * @import {\n * Entry,\n * FlattenedEntryContent,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * RelationOption,\n * RelationOptionGroup,\n * UnlistedEntry,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, RelationField, RelationFieldFilterOptions } from '$lib/types/public';\n * @import { SharedValues } from '$lib/services/contents/i18n/shared-values';\n */\n\n/**\n * @type {Map<string, RelationOption[]>}\n */\nexport const optionCacheMap = new Map();\n\n/**\n * Maximum number of option sets to retain in {@link optionCacheMap}.\n *\n * Two parts of the cache key keep changing while the app is running: the identity of the referenced\n * entry list, which is replaced every time the entries are loaded again or an entry is saved, and\n * the resolved `{{fields.*}}` filter values, which change on every keystroke in the field they\n * point at. Without a limit, each of those would add an options array — one entry per referenced\n * entry, potentially thousands — that is never read again and never released.\n *\n * The live working set is only a few option sets (one per visible relation field per locale), so\n * this is generous headroom; eviction is least-recently-used, keeping the hot ones cached.\n */\nconst MAX_OPTION_CACHE_SIZE = 100;\n/**\n * Cache keys of the option sets being built. A label template can refer to another Relation field\n * of the referenced entry, which resolves its own options; if that field leads back to the one\n * being built, e.g. a `parent` field showing the parent’s `parent`, the same options would be\n * requested again before they are cached, recursing until the stack overflows.\n * @type {Set<string>}\n */\nconst optionsInProgress = new Set();\n/**\n * Maximum number of merged entry lists kept for each saved entry list by\n * {@link withPendingEntries}.\n */\nconst MAX_MERGED_ENTRIES_CACHE_SIZE = 10;\n/**\n * Cache of the saved entries merged with the pending ones by {@link withPendingEntries}, keyed by\n * the saved entry list, then by the identities of the pending entries. A nested Relation field\n * resolves a label for each entry its parent field references, and a new merged array on each call\n * would give the option cache a new key every time, building the whole option list again for every\n * label. The pending entries are keyed by their identities rather than by the list, which can be\n * put together anew on each call.\n * @type {WeakMap<Entry[], Map<string, Entry[]>>}\n */\nconst mergedEntriesCache = new WeakMap();\n\n/**\n * Get a key telling the given pending entries apart from another set, or the same array after a\n * change, by the identities of the entries.\n * @param {UnlistedEntry[]} [pendingEntries] Entries not yet among the saved ones.\n * @returns {string} Key.\n */\nconst getPendingEntriesKey = (pendingEntries = []) =>\n  pendingEntries.map((pendingEntry) => getObjectId(pendingEntry)).join(',');\n\n/**\n * Merge the given entries not yet among the saved ones that belong to the given collection into the\n * saved entries. An existing entry takes the place of its saved version, and the later of two\n * versions of the same entry wins.\n * @param {Entry[]} entries Saved entries.\n * @param {string} collectionName Collection name.\n * @param {UnlistedEntry[]} pendingEntries Entries not yet among the saved ones, of any collection.\n * @returns {Entry[]} Entries.\n */\nconst mergeEntries = (entries, collectionName, pendingEntries) => {\n  const pending = pendingEntries\n    .filter((pendingEntry) => pendingEntry.collectionName === collectionName)\n    .map(({ entry }) => entry);\n\n  // An existing entry edited from a Relation field takes the place of its saved version\n  const pendingMap = new Map(pending.map((entry) => [entry.id, entry]));\n\n  return pending.length\n    ? [\n        ...entries.map((entry) => {\n          const edited = pendingMap.get(entry.id);\n\n          pendingMap.delete(entry.id);\n\n          return edited ?? entry;\n        }),\n        ...pendingMap.values(),\n      ]\n    : entries;\n};\n\n/**\n * Add the entries not yet among the saved ones that belong to the given collection to the given\n * saved entries, so a reference to one of them resolves: the entries pending on the draft being\n * edited, and those in the pull request its host entry has been saved to. The saved entries are\n * returned as they are when there’s nothing to add, keeping their identity for the option cache;\n * otherwise the merged list is kept as long as the pending entries stay the same.\n * @param {Entry[]} entries Saved entries.\n * @param {string} collectionName Collection name.\n * @param {UnlistedEntry[]} [pendingEntries] Entries not yet among the saved ones, of any\n * collection.\n * @returns {Entry[]} Entries.\n */\nconst withPendingEntries = (entries, collectionName, pendingEntries = []) => {\n  if (!pendingEntries.length) {\n    return entries;\n  }\n\n  let pendingCache = mergedEntriesCache.get(entries);\n\n  if (!pendingCache) {\n    pendingCache = new Map();\n    mergedEntriesCache.set(entries, pendingCache);\n  }\n\n  // The pending entries of a draft are held in a reactive array that changes in place, so the\n  // entries’ own identities tell a change apart: an entry opened again and changed is replaced with\n  // a new object\n  return getOrCreateBounded(\n    pendingCache,\n    getPendingEntriesKey(pendingEntries),\n    () => mergeEntries(entries, collectionName, pendingEntries),\n    MAX_MERGED_ENTRIES_CACHE_SIZE,\n  );\n};\n\n/**\n * Build the options for a Relation field from the given referenced entries, grouped by entry. This\n * is the uncached core shared by {@link getOptions} and {@link getEntryOptions}.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {Entry[]} args.refEntries Referenced entries.\n * @param {RelationFieldFilterOptions[]} [args.entryFilters] Entry filters with any template strings\n * already resolved.\n * @param {UnlistedEntry[]} [args.pendingEntries] Entries not yet among the saved ones. A label\n * template can refer to another Relation field of the referenced entry, and the entry that one\n * points at may be one of them too.\n * @returns {RelationOptionGroup[]} Options grouped by referenced entry, unsorted.\n */\nconst buildOptionGroups = ({\n  locale,\n  fieldConfig,\n  refEntries,\n  entryFilters = [],\n  pendingEntries = undefined,\n}) => {\n  const { collection: collectionName, file: fileName } = fieldConfig;\n  const collection = getCollection(collectionName);\n\n  if (!collection) {\n    return [];\n  }\n\n  const {\n    _type,\n    _i18n: { defaultLocale },\n  } = collection;\n\n  const identifierField = getIdentifierFieldName(_type === 'entry' ? collection : undefined);\n  const templates = prepareFieldTemplates(fieldConfig, identifierField);\n\n  const filteredEntries = filterAndPrepareEntries({\n    refEntries,\n    collection,\n    locale,\n    fileName,\n    entryFilters,\n    defaultLocale,\n  });\n\n  return filteredEntries.map(({ refEntry, content }) => ({\n    refEntry,\n    options: processEntry({\n      refEntry,\n      content,\n      collection,\n      templates,\n      fileName,\n      locale,\n      identifierField,\n      pendingEntries,\n    }),\n  }));\n};\n\n/**\n * Build the option list for a Relation field from the given referenced entries.\n * @param {Parameters<typeof buildOptionGroups>[0]} args Arguments. See {@link buildOptionGroups}.\n * @returns {RelationOption[]} Options, unsorted.\n */\nconst buildOptions = (args) => buildOptionGroups(args).flatMap(({ options }) => options);\n\n/**\n * Get the entries a Relation field can reference: the entries of the referenced collection, or the\n * referenced file of a file collection.\n * @param {RelationField} fieldConfig Field configuration.\n * @returns {Entry[]} Entries. Empty if the referenced file is not found.\n */\nexport const getRefEntries = ({ collection: collectionName, file: fileName }) => {\n  if (fileName) {\n    const entry = getCollectionFileEntry(collectionName, fileName);\n\n    return entry ? [entry] : [];\n  }\n\n  return getEntriesByCollection(collectionName);\n};\n\n/**\n * Get options for a Relation field.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {Entry[]} args.refEntries Referenced entries.\n * @param {FlattenedEntryContent} [args.currentLocaleValues] Flattened field values of the entry\n * currently being edited. Required to resolve `{{fields.fieldName}}` template strings in filter\n * `values`. When omitted, those template strings are ignored.\n * @param {string} [args.currentSlug] Current slug of the entry being edited. Required to resolve\n * `{{slug}}` template strings in filter `values`. When omitted (e.g. new entry draft), `{{slug}}`\n * templates are ignored.\n * @param {UnlistedEntry[]} [args.pendingEntries] Entries not yet among the saved ones, so the\n * labels referring to one of them through another Relation field resolve.\n * @param {SharedValues} [args.sharedValues] Values of the fields of the entry being edited that\n * aren’t localized, to resolve `{{fields.fieldName}}` template strings referring to one of them in\n * another locale than the default.\n * @returns {RelationOption[]} Options, sorted as the `sort_by` option defines, or by label unless\n * the field references a file or a collection kept in a manual order.\n */\nexport const getOptions = ({\n  locale,\n  fieldConfig,\n  refEntries,\n  currentLocaleValues = undefined,\n  currentSlug = undefined,\n  pendingEntries = undefined,\n  sharedValues = undefined,\n}) => {\n  const { collection: collectionName, file: fileName, filters, sort_by: sortBy } = fieldConfig;\n\n  // Resolve template strings in filter values against the current entry’s locale content and slug.\n  // The resolved values are also baked into the cache key so stale options are not returned when\n  // the relevant field value changes while the user is editing.\n  const resolvedFilters = resolveFilterValues(\n    filters ?? [],\n    currentLocaleValues,\n    currentSlug,\n    sharedValues,\n  );\n\n  // Use object identity for `fieldConfig` and `refEntries` instead of `JSON.stringify`, which would\n  // serialize the entire entries array (potentially hundreds of entries × many fields). The\n  // resolved template values are included as a plain string so the cache is invalidated when the\n  // current entry’s relevant field value changes. They’re kept apart by filter, as a list value\n  // can move from one filter to another, and by type, as a number doesn’t match its string.\n  const resolvedKey = JSON.stringify(resolvedFilters.map(({ values }) => values));\n  const ids = `${getObjectId(fieldConfig)}|${getObjectId(refEntries)}`;\n  // The pending entries are held in a reactive array that changes in place, so its identity doesn’t\n  // tell them apart; theirs do, as an entry opened again and changed is replaced with a new object\n  const cacheKey = `${locale}|${ids}|${getPendingEntriesKey(pendingEntries)}|${resolvedKey}`;\n\n  // The options are requested again while being built: no option is available at this level, so\n  // a reference is shown with its stored value\n  if (optionsInProgress.has(cacheKey)) {\n    return [];\n  }\n\n  return getOrCreateBounded(\n    optionCacheMap,\n    cacheKey,\n    () => {\n      optionsInProgress.add(cacheKey);\n\n      try {\n        const collection = getCollection(collectionName);\n\n        // The options taken from a list in a single file follow the order of the list items, so\n        // the `sort_by` option doesn’t apply to them\n        if (collection && !fileName && sortBy?.field) {\n          return sortOptions({\n            groups: buildOptionGroups({\n              locale,\n              fieldConfig,\n              refEntries,\n              entryFilters: resolvedFilters,\n              pendingEntries,\n            }),\n            collection: /** @type {InternalEntryCollection} */ (collection),\n            sortBy,\n            locale,\n          });\n        }\n\n        // Without the `sort_by` option, the options from the entries of a collection the user can\n        // reorder follow the manual order; the others are sorted by label\n        const manuallyOrdered = !fileName && isManuallyOrdered(collection);\n\n        const options = buildOptions({\n          locale,\n          fieldConfig,\n          refEntries: manuallyOrdered\n            ? sortEntriesByOrderField(\n                refEntries,\n                /** @type {InternalEntryCollection} */ (collection),\n              )\n            : refEntries,\n          entryFilters: resolvedFilters,\n          pendingEntries,\n        });\n\n        return fileName || manuallyOrdered\n          ? options\n          : options.sort((a, b) => compare(a.label, b.label));\n      } finally {\n        optionsInProgress.delete(cacheKey);\n      }\n    },\n    MAX_OPTION_CACHE_SIZE,\n  );\n};\n\n/**\n * Get the option(s) representing a single entry in a Relation field, in other words the value(s)\n * that would be stored when the entry is selected. Unlike {@link getOptions}, the field’s `filters`\n * are not applied — a reference to the entry can exist regardless of whether the entry still\n * qualifies as a choice — and the result is not cached, because callers ask for a one-off entry\n * rather than the list backing a field.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Locale of the entry holding the Relation field.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {Entry} args.refEntry Referenced entry.\n * @param {UnlistedEntry[]} [args.pendingEntries] Entries not yet among the saved ones. See\n * {@link buildOptions}.\n * @returns {RelationOption[]} Options, in the order the templates produce them. Empty if the\n * referenced collection is gone or the entry has no content in any usable locale.\n */\nexport const getEntryOptions = ({ locale, fieldConfig, refEntry, pendingEntries = undefined }) =>\n  buildOptions({ locale, fieldConfig, refEntries: [refEntry], pendingEntries });\n\n/**\n * Resolve the display value(s) for a relation field.\n * @param {object} args Arguments.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {FlattenedEntryContent} args.valueMap Object holding current entry values.\n * @param {FieldKeyPath} args.keyPath Field key path, e.g. `author.name`.\n * @param {InternalLocaleCode} args.locale Locale.\n * @param {UnlistedEntry[]} [args.pendingEntries] Entries not yet among the saved ones, which the\n * value can refer to.\n * @returns {any | any[]} Resolved field value(s).\n */\nexport const getReferencedOptionLabel = ({\n  fieldConfig,\n  valueMap,\n  keyPath,\n  locale,\n  pendingEntries = undefined,\n}) => {\n  const { multiple, collection } = fieldConfig;\n\n  const refEntries = withPendingEntries(\n    getEntriesByCollection(collection),\n    collection,\n    pendingEntries,\n  );\n\n  const refOptions = getOptions({ locale, fieldConfig, refEntries, pendingEntries });\n  const optionLabelMap = getOptionLabelMap(refOptions);\n\n  /**\n   * Get the label by value. The option values are strings, while a stored value can be a number\n   * read from a file, e.g. `author: 3`, so it’s looked up as a string, like the preview does.\n   * @param {any} _value Stored value.\n   * @returns {string} Label.\n   */\n  const getLabel = (_value) =>\n    (_value !== null && _value !== undefined && optionLabelMap.get(String(_value))) || _value;\n\n  if (multiple) {\n    return getListItemKeys(valueMap, keyPath).map((key) => getLabel(valueMap[key]));\n  }\n\n  return getLabel(valueMap[keyPath]);\n};\n","import { isObjectArray } from '@sveltia/utils/array';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { getListItemKeys } from '$lib/services/contents/entry/key-paths';\nimport { getOrCreate, getOrCreateBounded } from '$lib/services/utils/cache';\n\n/**\n * @import { FlattenedEntryContent } from '$lib/types/private';\n * @import {\n * FieldKeyPath,\n * SelectField,\n * SelectFieldOption,\n * SelectFieldValue,\n * } from '$lib/types/public';\n */\n\n/**\n * @type {Map<string, any | any[]>}\n */\nconst labelCacheMap = new Map();\n/**\n * Maximum number of labels to retain in {@link labelCacheMap}. The cache key includes the field’s\n * current value, so every edit adds an entry that is never read again — a limit is what stops the\n * map from growing for the whole session. Labels are small, and the live working set is one entry\n * per rendered select field, so this leaves plenty of headroom.\n */\nconst MAX_LABEL_CACHE_SIZE = 1000;\n/**\n * Cache of stringified `options` arrays, keyed on the array reference itself so the expensive\n * serialization only runs once per field configuration.\n * @type {WeakMap<object[], string>}\n */\nconst optionsKeyCache = new WeakMap();\n\n/**\n * Get a stable cache key fragment for a field’s `options` array.\n * @param {any[]} options Field options.\n * @returns {string} Cache key.\n */\nconst getOptionsKey = (options) =>\n  getOrCreate(optionsKeyCache, options, () => JSON.stringify(options));\n\n/**\n * Get the display value for an option.\n * @param {object} args Arguments.\n * @param {SelectField} args.fieldConfig Field configuration.\n * @param {FlattenedEntryContent} args.valueMap Object holding current entry values.\n * @param {FieldKeyPath} args.keyPath Field key path, e.g. `author.name`.\n * @returns {any | any[]} Resolved field value(s).\n */\nexport const getOptionLabel = ({ fieldConfig, valueMap, keyPath }) => {\n  const { multiple, options } = fieldConfig;\n  const hasLabels = isObjectArray(options);\n  // Extract only the values relevant to this field from `valueMap`, avoiding serialization of the\n  // entire entry content (which would cause cache misses on any unrelated field change).\n  /** @type {any[] | undefined} */\n  let rawValues;\n\n  if (multiple) {\n    rawValues = getListItemKeys(valueMap, keyPath).map((key) => valueMap[key]);\n  }\n\n  const optionsKey = getOptionsKey(options);\n  // Serialize the value with its type, so `1` and `'1'`, which can be options with different\n  // labels, don’t share a cache entry\n  const valueKey = JSON.stringify(multiple ? rawValues : valueMap[keyPath]);\n  const cacheKey = `${keyPath}|${optionsKey}|${valueKey}`;\n\n  /**\n   * Get the label by value.\n   * @param {any} _value Stored value.\n   * @returns {string} Label.\n   */\n  const getLabel = (_value) =>\n    /** @type {{ label: string, value: string }[]} */ (options).find((o) => o.value === _value)\n      ?.label || _value;\n\n  return getOrCreateBounded(\n    labelCacheMap,\n    cacheKey,\n    () => {\n      if (multiple) {\n        return hasLabels ? /** @type {any[]} */ (rawValues).map(getLabel) : rawValues;\n      }\n\n      const value = valueMap[keyPath];\n\n      return hasLabels ? getLabel(value) : value;\n    },\n    MAX_LABEL_CACHE_SIZE,\n  );\n};\n\n/**\n * Get the value of a Select field option, which is either a plain value or an object with the\n * `label` and `value` properties. A `default` option can be given in either form too, as\n * documented by Decap CMS.\n * @param {SelectFieldValue | SelectFieldOption | undefined} option Option or default value.\n * `undefined` is passed through.\n * @returns {SelectFieldValue | undefined} Value.\n */\nexport const getOptionValue = (option) => (isObject(option) ? option.value : option);\n\n/**\n * Check whether a value is one of the options of a Select field. `null`, `false` and an empty\n * string can be valid choices, so this tells a selected option apart from a missing value.\n * @param {object} args Arguments.\n * @param {SelectField} args.fieldConfig Field configuration.\n * @param {any} args.value Stored value.\n * @returns {boolean} Whether the value is one of the options.\n */\nexport const isOptionValue = ({ fieldConfig, value }) =>\n  fieldConfig.options.some((option) => getOptionValue(option) === value);\n\n/**\n * Get the labels to be shown in the preview of a Select field. A value is shown by its label if\n * the options have labels; otherwise, or if the value is not found in the options, it’s shown as\n * is.\n * @param {object} args Arguments.\n * @param {SelectField} args.fieldConfig Field configuration.\n * @param {SelectFieldValue | SelectFieldValue[] | undefined} args.currentValue Stored value(s).\n * @returns {string[]} Labels, sorted if there are multiple values. Empty if there is no value,\n * including `null` unless it’s one of the options.\n */\nexport const getPreviewLabels = ({ fieldConfig, currentValue }) => {\n  const { options, multiple = false } = fieldConfig;\n  const hasLabels = isObjectArray(options);\n\n  /**\n   * Get the label by value.\n   * @param {SelectFieldValue} value Stored value.\n   * @returns {string} Label.\n   */\n  const getLabel = (value) =>\n    hasLabels\n      ? /** @type {{ label: string, value: SelectFieldValue }[]} */ (options).find(\n          (o) => o.value === value,\n        )?.label || String(value)\n      : String(value);\n\n  if (multiple) {\n    return Array.isArray(currentValue) ? currentValue.map(getLabel).sort() : [];\n  }\n\n  return currentValue === undefined ||\n    (currentValue === null && !isOptionValue({ fieldConfig, value: null }))\n    ? []\n    : [getLabel(/** @type {SelectFieldValue} */ (currentValue))];\n};\n\n/**\n * Get the data type of a Select field option value, which `@sveltia/ui` uses to cast the value\n * read from the option element’s `data-value` attribute back to the original type. `null` is typed\n * as a number: the attribute is omitted for `null`, and a missing number is cast to `null`.\n * @param {SelectFieldValue} value Option value.\n * @returns {string} Data type.\n */\nexport const getOptionValueType = (value) => (value === null ? 'number' : typeof value);\n\n/**\n * Get the value that clears a single Select field, which the “unselected” option holds and a new\n * entry starts with: an empty string if the options are strings, or `null` if they are another\n * type, e.g. numbers or booleans, for which an empty string would be a type mismatch. The type is\n * taken from the first option.\n * @param {SelectFieldValue | undefined} firstValue Value of the first option, or `undefined` if\n * there are no options.\n * @returns {'' | null} Empty value.\n */\nexport const getEmptyOptionValue = (firstValue) =>\n  firstValue === undefined || typeof firstValue === 'string' ? '' : null;\n","/**\n * @import { CommitAuthor } from '$lib/types/private';\n */\n\n/**\n * Get the name to show for the author of a commit: the displayed name, falling back to the account\n * name and then the email address.\n * @param {Partial<CommitAuthor> | undefined} author Commit author.\n * @returns {string | undefined} Name, which is empty or `undefined` if the author has none.\n */\nexport const getCommitAuthorName = (author) => author?.name || author?.login || author?.email;\n\n/**\n * A `Co-authored-by` trailer line, with the name and the email.\n * @see https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors\n */\nconst CO_AUTHOR_TRAILER_REGEX = /^Co-authored-by:[^\\S\\r\\n]*([^<\\r\\n]+?)[^\\S\\r\\n]*<([^<>\\r\\n]*)>/im;\n\n/**\n * Get the person an app made a commit for, e.g. a Sveltia CMS Additions user whose changes are\n * committed by its GitHub App, which credits them in a `Co-authored-by` trailer. A commit an app\n * authors carries the app’s bot account name, e.g. `my-app[bot]`, which says nothing about who made\n * the change.\n * @param {{ name?: string | null } | null | undefined} author Commit author.\n * @param {string | null | undefined} message Commit message, or its body.\n * @returns {{ name: string, email: string } | undefined} The first co-author, if the commit was\n * authored by a bot and credits one.\n */\nexport const getBotCoAuthor = (author, message) => {\n  if (!author?.name?.endsWith('[bot]')) {\n    return undefined;\n  }\n\n  const [, name, email] = CO_AUTHOR_TRAILER_REGEX.exec(message ?? '') ?? [];\n\n  return name ? { name, email } : undefined;\n};\n","import { applyTransformations } from '$lib/services/common/transformations';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getField, isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { getKeysByPrefix, getListItemKeys } from '$lib/services/contents/entry/key-paths';\nimport { RICH_TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getDateTimeFieldDisplayValue } from '$lib/services/contents/fields/date-time/display';\nimport { getNumberFormatter, storesNumber } from '$lib/services/contents/fields/number/helpers';\nimport { getReferencedOptionLabel } from '$lib/services/contents/fields/relation/helpers';\nimport { getOptionLabel } from '$lib/services/contents/fields/select/helpers';\nimport { getCanonicalLocale, getListFormatter } from '$lib/services/contents/i18n';\nimport { getCommitAuthorName } from '$lib/services/utils/commit-author';\nimport { stripMarkdown } from '$lib/services/utils/markdown';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import {\n * Entry,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalLocaleCode,\n * StringTransformation,\n * UnlistedEntry,\n * } from '$lib/types/private';\n * @import {\n * DateTimeField,\n * Field,\n * FieldKeyPath,\n * ListFieldWithSubField,\n * ListFieldWithSubFields,\n * ListFieldWithTypes,\n * RelationField,\n * SelectField,\n * } from '$lib/types/public';\n */\n\n/**\n * Check whether the given field is a Rich Text field.\n * @param {Field | undefined} fieldConfig Field configuration.\n * @returns {boolean} Result.\n */\nconst isRichTextField = (fieldConfig) =>\n  RICH_TEXT_FIELD_TYPES.includes(/** @type {string} */ (fieldConfig?.widget));\n\n/**\n * Get a field’s display value that matches the given field name (key path).\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} [args.componentName] Name of the rich text editor component whose field the key\n * path points to. The key path and the value map then come without the component’s key path\n * prefix.\n * @param {FlattenedEntryContent} [args.valueMap] Object holding current entry values.\n * @param {FieldKeyPath} args.keyPath Key path, e.g. `author.name`.\n * @param {InternalLocaleCode} args.locale Locale.\n * @param {StringTransformation[]} [args.transformations] String transformations.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @param {UnlistedEntry[]} [args.pendingEntries] Entries not yet among the saved ones, which a\n * Relation field value can refer to.\n * @param {boolean} [args.plainText] Whether to remove the Markdown syntax and HTML tags from a Rich\n * Text field value, e.g. for a summary.\n * @returns {string} Resolved display value.\n */\nexport const getFieldDisplayValue = ({\n  collectionName,\n  fileName,\n  componentName = undefined,\n  valueMap = {},\n  keyPath,\n  locale,\n  transformations,\n  isIndexFile = false,\n  pendingEntries = undefined,\n  plainText = false,\n}) => {\n  const fieldConfig = getField({\n    collectionName,\n    fileName,\n    componentName,\n    valueMap,\n    keyPath,\n    isIndexFile,\n  });\n\n  // A field named after an `Object.prototype` member, e.g. `constructor`, mustn’t resolve to that\n  // member when the entry lacks the field\n  let value = Object.hasOwn(valueMap, keyPath) ? valueMap[keyPath] : undefined;\n\n  // If the field doesn’t exist in `valueMap` and transformations are applied, apply them to an\n  // empty string, like an entry summary does, so that `default()` can fill in the missing value\n  if (value === undefined && transformations?.length) {\n    return String(applyTransformations({ fieldConfig, value: '', transformations, locale }));\n  }\n\n  if (fieldConfig?.widget === 'datetime') {\n    // If the `date` transformation is provided, do nothing; it should be used instead of the field\n    // `format` option, so the keep the original value for `applyTransformations()`\n    if (!transformations?.some(({ method }) => method === 'date')) {\n      value = getDateTimeFieldDisplayValue({\n        locale,\n        fieldConfig: /** @type {DateTimeField} */ (fieldConfig),\n        currentValue: value,\n      });\n    }\n  }\n\n  if (fieldConfig?.widget === 'relation') {\n    value = getReferencedOptionLabel({\n      fieldConfig: /** @type {RelationField} */ (fieldConfig),\n      valueMap,\n      keyPath,\n      locale,\n      pendingEntries,\n    });\n  }\n\n  if (fieldConfig?.widget === 'select') {\n    value = getOptionLabel({\n      fieldConfig: /** @type {SelectField} */ (fieldConfig),\n      valueMap,\n      keyPath,\n    });\n  }\n\n  if (fieldConfig?.widget === 'list') {\n    const { field } = /** @type {ListFieldWithSubField} */ (fieldConfig);\n    const { fields } = /** @type {ListFieldWithSubFields} */ (fieldConfig);\n    const { types } = /** @type {ListFieldWithTypes} */ (fieldConfig);\n\n    if (fields || types) {\n      // Ignore\n    } else {\n      const itemKeys = getListItemKeys(valueMap, keyPath);\n\n      // Concat values of single field list or simple list. An item of the former is resolved like\n      // its subfield, which can hold a number, a boolean or the value of a Select option, while the\n      // latter holds strings\n      value = getListFormatter(locale).format(\n        (field\n          ? itemKeys.map((key) =>\n              getFieldDisplayValue({\n                collectionName,\n                fileName,\n                componentName,\n                valueMap,\n                keyPath: key,\n                locale,\n                isIndexFile,\n                pendingEntries,\n                plainText,\n              }),\n            )\n          : itemKeys.map((key) => valueMap[key]).filter((val) => typeof val === 'string')\n        ).filter((val) => !!val),\n      );\n    }\n  }\n\n  // A number stored by a Number field or a Compute field is formatted for display. An empty field,\n  // stored as `null` or an empty string, or missing, is left empty rather than formatted as `0` or\n  // `NaN`\n  if (\n    fieldConfig &&\n    storesNumber(fieldConfig) &&\n    value !== null &&\n    value !== undefined &&\n    value !== ''\n  ) {\n    const number = Number(value);\n\n    // Text that isn’t a number, which the editor stores so it can be reported as invalid, is shown\n    // as is rather than as `NaN`\n    if (!Number.isNaN(number)) {\n      value = getNumberFormatter(getCanonicalLocale(locale)).format(number);\n    }\n  }\n\n  if (plainText && isRichTextField(fieldConfig) && typeof value === 'string') {\n    value = stripMarkdown(value);\n  }\n\n  if (Array.isArray(value)) {\n    value = getListFormatter(locale).format(value);\n  }\n\n  if (transformations?.length) {\n    value = applyTransformations({ fieldConfig, value, transformations, locale });\n  }\n\n  // Return an empty string if the value is null or undefined\n  return String(value ?? '');\n};\n\n/**\n * Get the display value of the first visible field that has a non-empty value.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.valueMap Entry content.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for `getField`.\n * @param {string} args.keyPathPrefix Key path prefix that a candidate must start with, e.g.\n * `authors.0.`.\n * @param {boolean} [args.plainText] Whether to remove the Markdown syntax and HTML tags from a Rich\n * Text field value.\n * @returns {string} Display value of the first visible field that has a non-empty value. If no such\n * field is found, returns an empty string.\n */\nexport const getVisibleFieldDisplayValue = ({\n  valueMap,\n  locale,\n  keyPath,\n  keyPathPrefix,\n  getFieldArgs,\n  plainText = false,\n}) => {\n  // Find the first visible item key path that has a non-empty value. `title` and `name` are\n  // preferred, so they’re tried ahead of the map’s own order.\n  const visibleItemKeyPath = [\n    `${keyPath}.title`,\n    `${keyPath}.name`,\n    ...getKeysByPrefix(valueMap, keyPathPrefix),\n  ].find((_keyPath) => {\n    const value = valueMap[_keyPath];\n\n    if (\n      !_keyPath.startsWith(keyPathPrefix) ||\n      !(isNonEmptyString(value) || (typeof value === 'number' && !Number.isNaN(value)))\n    ) {\n      return false;\n    }\n\n    const fieldConfig = getField({ ...getFieldArgs, keyPath: _keyPath });\n\n    return !!fieldConfig && fieldConfig.widget !== 'hidden';\n  });\n\n  if (visibleItemKeyPath) {\n    return getFieldDisplayValue({\n      ...getFieldArgs,\n      keyPath: visibleItemKeyPath,\n      locale,\n      plainText,\n    });\n  }\n\n  return '';\n};\n\n/**\n * Get an entry’s field value by locale and key.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {string} args.collectionName Name of a collection that the entry belongs to.\n * @param {FieldKeyPath | string} args.key Field key path or one of other entry metadata property\n * keys: `slug`, `commit_author` and `commit_date`.\n * @param {boolean} [args.resolveRef] Whether to resolve the referenced value if the target field is\n * a relation field.\n * @returns {any} Value. An array of the item values for a multi-value field — a List field, or a\n * Relation, Select or media field with `multiple: true` — or of the subfield values for an Object\n * field or a List field with subfields, which are stored flattened, so nothing lives at the field’s\n * own key path.\n */\nexport const getPropertyValue = ({ entry, locale, collectionName, key, resolveRef = true }) => {\n  const { slug, locales, commitAuthor, commitDate } = entry;\n\n  if (key === 'slug') {\n    return slug;\n  }\n\n  if (key === 'commit_author') {\n    return getCommitAuthorName(commitAuthor);\n  }\n\n  if (key === 'commit_date') {\n    return commitDate;\n  }\n\n  const { content } = locales[locale] ?? {};\n\n  if (content === undefined) {\n    return undefined;\n  }\n\n  const collection = getCollection(collectionName);\n\n  if (!collection) {\n    return undefined;\n  }\n\n  const isIndexFile = isCollectionIndexFile(collection, entry);\n  const fieldConfig = getField({ collectionName, keyPath: key, isIndexFile });\n\n  // Resolve the displayed value for a relation field\n  if (resolveRef && fieldConfig?.widget === 'relation') {\n    return getReferencedOptionLabel({\n      fieldConfig: /** @type {RelationField} */ (fieldConfig),\n      valueMap: content,\n      keyPath: key,\n      locale,\n    });\n  }\n\n  // Gather the items of a multi-value field, which are flattened under `key.0`, `key.1` and so on,\n  // so a view filter can match any of them\n  // @see https://github.com/sveltia/sveltia-cms/issues/997\n  if (fieldConfig && (fieldConfig.widget === 'list' || isFieldMultiple(fieldConfig))) {\n    const itemKeys = getListItemKeys(content, key);\n\n    if (itemKeys.length) {\n      return itemKeys.map((itemKey) => content[itemKey]);\n    }\n  }\n\n  // A field named after an `Object.prototype` member, e.g. `constructor`, mustn’t resolve to that\n  // member when the entry lacks the field\n  const ownValue = Object.hasOwn(content, key) ? content[key] : undefined;\n\n  // Gather the subfield values of an Object field, or a List field with subfields, which are\n  // flattened under `key.name`, `key.0.name` and so on, so nothing lives at the field’s own key\n  // path unless it’s `null`. A view filter can then tell whether it has a value, or match any of\n  // the subfield values\n  // @see https://github.com/sveltia/sveltia-cms/issues/1004\n  if (\n    ownValue === undefined &&\n    (fieldConfig?.widget === 'object' || fieldConfig?.widget === 'list')\n  ) {\n    const subKeys = getKeysByPrefix(content, `${key}.`);\n\n    if (subKeys.length) {\n      return subKeys.map((subKey) => content[subKey]);\n    }\n  }\n\n  return ownValue;\n};\n","import { locale as appLocale } from '@sveltia/i18n';\nimport { getDateTimeParts } from '@sveltia/utils/datetime';\nimport { sanitize } from 'isomorphic-dompurify';\nimport { parseInline } from 'marked';\nimport { parseEntities } from 'parse-entities';\n\nimport { processNestedTemplates } from '$lib/services/common/template/nested';\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport {\n  getFileNameLocaleSuffixes,\n  getFileNameParts,\n  stripFieldTagPrefix,\n} from '$lib/services/common/template/utils';\nimport { applyTransformations, parseTransformations } from '$lib/services/common/transformations';\nimport { allEntries } from '$lib/services/contents';\nimport {\n  getIndexFile,\n  isCollectionIndexFile,\n} from '$lib/services/contents/collection/entries/index-file';\nimport {\n  getCollectionFile,\n  getCollectionFileEntry,\n  getCollectionFileLabel,\n} from '$lib/services/contents/collection/files';\nimport { getIdentifierFieldName } from '$lib/services/contents/collection/identifier';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getEntryDirName } from '$lib/services/contents/entry/paths';\nimport { getFieldDisplayValue } from '$lib/services/contents/entry/values';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { getCommitAuthorName } from '$lib/services/utils/commit-author';\n\n/**\n * @import {\n * CommitAuthor,\n * Entry,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import {\n * Field,\n * ListFieldWithSubField,\n * ListFieldWithSubFields,\n * ListFieldWithTypes,\n * RawEntryContent,\n * } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} ReplacerSubContext\n * @property {string} slug Entry slug.\n * @property {string} entryPath Entry path.\n * @property {string | undefined} basePath Base path for the entry.\n * @property {RegExp} [fullPathRegEx] Entry collection’s entry path matcher, which tells the\n * `{{dirname}}` tag where the locale folder is.\n * @property {string[]} locales Enabled locales for the entry.\n * @property {string[]} [localeSuffixes] Locale codes that can follow the entry file name, with the\n * `multiple_files` i18n structure.\n * @property {Date | undefined} commitDate Commit date.\n * @property {CommitAuthor | undefined} commitAuthor Commit author.\n */\n\n/**\n * @typedef {object} ReplaceContext\n * @property {FlattenedEntryContent} content Entry content.\n * @property {string} collectionName Collection name.\n * @property {string} [fileName] Collection file name, whose fields the tags refer to. File\n * collection only.\n * @property {boolean} [isIndexFile] Whether the tags refer to the fields of the collection’s index\n * file.\n * @property {ReplacerSubContext} replaceSubContext Context for the `replaceSub` function.\n * @property {InternalLocaleCode} locale Locale of the content, which a field value is displayed\n * and transformed in: a DateTime field value may be written in it.\n * @property {string | undefined} [fallbackSummary] Fallback summary for the entry.\n */\n\n/**\n * @typedef {object} CachedSummary\n * @property {string} summary Formatted summary.\n * @property {number} [generation] {@link entriesGeneration} the summary was formatted in, if it\n * contains a Relation field label and has to be regenerated once other entries change.\n */\n\n/**\n * Regular expression to match each line of Markdown, so the lines can be read one by one until a\n * heading is found.\n */\nconst LINE_REGEX = /^.*$/gm;\n/**\n * Regular expression to match the start of an ATX heading line in Markdown: up to three spaces of\n * indentation, one to six `#` characters, then spaces or tabs or the end of the line. The body is\n * untrusted, so the heading text is read with string operations rather than captured; see\n * {@link getBodyHeader}.\n * @see https://spec.commonmark.org/0.31.2/#atx-headings\n */\nconst ATX_HEADING_START_REGEX = /^ {0,3}#{1,6}(?:[ \\t]+|$)/;\n/**\n * Regular expression to match the start of a code fence line in Markdown: up to three spaces of\n * indentation, then three or more backticks or tildes, which are captured.\n * @see https://spec.commonmark.org/0.31.2/#fenced-code-blocks\n */\nconst CODE_FENCE_START_REGEX = /^ {0,3}(`{3,}|~{3,})/;\n\n/**\n * Remove the optional closing sequence of `#` characters at the end of the given ATX heading text,\n * which has to be preceded by a space or tab unless it’s all the heading has, like `Title` in\n * `## Title ##`.\n * @param {string} text Heading text without leading and trailing whitespace.\n * @returns {string} Heading text without the closing sequence.\n * @see https://spec.commonmark.org/0.31.2/#atx-headings\n */\nconst removeClosingSequence = (text) => {\n  let end = text.length;\n\n  while (end > 0 && text[end - 1] === '#') {\n    end -= 1;\n  }\n\n  return end === 0 || /[ \\t]/.test(text[end - 1]) ? text.slice(0, end).trimEnd() : text;\n};\n\n/**\n * Remove a custom anchor like `{#my-anchor}` at the end of the given heading text.\n * @param {string} text Heading text without leading and trailing whitespace.\n * @returns {string} Heading text without the anchor.\n * @see https://vitepress.dev/guide/markdown#custom-anchors\n */\nconst removeHeadingAnchor = (text) => {\n  if (!text.endsWith('}')) {\n    return text;\n  }\n\n  // The anchor starts at the first `{#` that follows whitespace and has a name before the last `}`\n  for (let index = text.indexOf('{#', 1); index > 0; index = text.indexOf('{#', index + 1)) {\n    if (index + 2 >= text.length - 1) {\n      break;\n    }\n\n    if (/\\s/.test(text[index - 1])) {\n      return text.slice(0, index).trimEnd();\n    }\n  }\n\n  return text;\n};\n\n/**\n * Get the text of the given line of Markdown if it’s an ATX heading.\n * @param {string} line Line.\n * @returns {string} Heading text without a closing sequence and a custom anchor, or an empty string\n * if the line is not a heading or has no text.\n */\nconst getHeadingText = (line) => {\n  const [prefix] = line.match(ATX_HEADING_START_REGEX) ?? [];\n\n  return prefix ? removeHeadingAnchor(removeClosingSequence(line.slice(prefix.length).trim())) : '';\n};\n\n/**\n * Find the first ATX heading with text in the given Markdown, skipping fenced code blocks, where a\n * line starting with `#` is often a comment, like a shell one.\n * @param {string} markdown Markdown string.\n * @returns {string} Heading text without a closing sequence and a custom anchor, or an empty string\n * if there is no heading.\n */\nconst getBodyHeader = (markdown) => {\n  /** @type {string | undefined} */\n  let openingFence;\n\n  return (\n    markdown\n      .matchAll(LINE_REGEX)\n      .map(([line]) => {\n        const fence = line.match(CODE_FENCE_START_REGEX);\n\n        if (openingFence) {\n          // A closing fence is at least as long as the opening one, uses the same character, and\n          // is followed only by spaces or tabs. An unclosed code block runs to the end\n          if (fence?.[1].startsWith(openingFence) && /^[ \\t]*$/.test(line.slice(fence[0].length))) {\n            openingFence = undefined;\n          }\n\n          return '';\n        }\n\n        // The info string of a backtick fence can’t contain a backtick, or it’s inline code\n        if (fence && (fence[1][0] === '~' || !line.includes('`', fence[0].length))) {\n          [, openingFence] = fence;\n\n          return '';\n        }\n\n        return getHeadingText(line);\n      })\n      .find((header) => !!header) ?? ''\n  );\n};\n\n/**\n * Character standing in for a `<` that doesn’t start one of the formatting tags a summary can\n * contain, from the Private Use Area, so it’s neither parsed as Markdown nor as HTML.\n */\nconst LT_PLACEHOLDER = '\\uE000';\n/**\n * Match a `<` that doesn’t start a `strong`, `em` or `code` tag. Any other tag in a field value is\n * text, like `<T>` in `Vec<T> in Rust` or `<script>` in a title about it, which would otherwise be\n * sanitized away, and an unclosed one would take the rest of the summary with it.\n */\nconst NON_FORMATTING_TAG_REGEX = /<(?!\\/?(?:strong|em|code)(?:\\s[^>]*)?>)/g;\n\n/**\n * Parse the given entry summary as Markdown and sanitize HTML with a few exceptions if the Markdown\n * option is enabled. Also, parse HTML character references (entities).\n * Without the Markdown option, the references are decoded after sanitizing, so the result can\n * contain markup, e.g. `&lt;img&gt;` becomes `<img>`: it’s only safe as text, never with Svelte’s\n * `@html` tag or `innerHTML`. A raw `<` that doesn’t start a formatting tag is kept as text.\n * @param {string} str Original string.\n * @param {object} [options] Options.\n * @param {boolean} [options.allowMarkdown] Whether to allow Markdown and return HTML string.\n * @returns {string} Parsed string.\n */\nexport const sanitizeEntrySummary = (str, { allowMarkdown = false } = {}) => {\n  str = /** @type {string} */ (parseInline(str.replace(NON_FORMATTING_TAG_REGEX, LT_PLACEHOLDER)));\n\n  if (allowMarkdown) {\n    str = parseEntities(str);\n  }\n\n  // Attributes are dropped, so an entry value cannot restyle the app with `style`, e.g. a title\n  // wrapped in `<strong style=\"position: fixed; inset: 0\">` covering the whole page\n  str = sanitize(str, {\n    ALLOWED_TAGS: allowMarkdown ? ['strong', 'em', 'code'] : [],\n    ALLOWED_ATTR: [],\n  });\n\n  if (!allowMarkdown) {\n    str = parseEntities(str);\n  }\n\n  return str.replaceAll(LT_PLACEHOLDER, allowMarkdown ? '&lt;' : '<').trim();\n};\n\n/**\n * Determine an entry summary from the given content. Fields other than `title` should be defined\n * with the `identifier_field` collection option as per the Netlify/Decap CMS document. We also look\n * for the `name` and `label` properties as well as a header in the Markdown `body` as a fallback.\n * @param {FlattenedEntryContent | RawEntryContent} content Content.\n * @param {object} options Options.\n * @param {string} [options.identifierField] Field name to identify the title.\n * @param {boolean} [options.useBody] Whether to fall back to a header in the Markdown `body`.\n * @returns {string} Entry summary. Can be an empty string if it cannot be determined.\n * @see https://decapcms.org/docs/configuration-options/#identifier_field\n */\nexport const getEntrySummaryFromContent = (\n  content,\n  { identifierField = 'title', useBody = true } = {},\n) => {\n  const idField = [identifierField, 'title', 'name', 'label'].find(\n    (fieldName) => typeof content[fieldName] === 'string' && !!content[fieldName].trim(),\n  );\n\n  if (idField) {\n    return content[idField].trim();\n  }\n\n  // Find a header in Markdown, excluding an anchor suffix\n  // https://vitepress.dev/guide/markdown#custom-anchors\n  if (useBody && typeof content.body === 'string') {\n    return getBodyHeader(content.body);\n  }\n\n  return '';\n};\n\n/**\n * Replacer subroutine.\n * @param {string} tag Field name or one of special tags.\n * @param {ReplacerSubContext} context Context.\n * @returns {string | Date | undefined} Replaced value or `undefined` if the tag is not recognized.\n */\nexport const replaceSub = (tag, context) => {\n  const {\n    slug,\n    entryPath,\n    basePath,\n    fullPathRegEx,\n    locales,\n    localeSuffixes,\n    commitDate,\n    commitAuthor,\n  } = context;\n\n  if (tag === 'slug') {\n    return slug;\n  }\n\n  if (tag === 'locales') {\n    return locales.sort((a, b) => a.localeCompare(b)).join(', ');\n  }\n\n  if (tag === 'dirname') {\n    return getEntryDirName(entryPath, { basePath, fullPathRegEx });\n  }\n\n  if (tag === 'filename' || tag === 'extension') {\n    return getFileNameParts(entryPath, localeSuffixes)[tag];\n  }\n\n  if (tag === 'commit_date') {\n    return commitDate ?? '';\n  }\n\n  if (tag === 'commit_author') {\n    return getCommitAuthorName(commitAuthor);\n  }\n\n  return undefined;\n};\n\n/**\n * Whether a Relation field label has been resolved since the flag was last reset. Set by\n * {@link replace}, so {@link getEntrySummary} can tell whether the summary it has just formatted\n * depends on other entries.\n */\nlet relationLabelResolved = false;\n\n/**\n * Check whether the display value of the given field is resolved from other entries: a Relation\n * field shows a label taken from the referenced entry, and so does each item of a List field with a\n * Relation field as its single subfield, as {@link getFieldDisplayValue} resolves those items like\n * the subfield itself.\n * @param {Field | undefined} field Field configuration.\n * @returns {boolean} Result.\n */\nexport const isDisplayValueFromOtherEntries = (field) => {\n  if (field?.widget === 'relation') {\n    return true;\n  }\n\n  if (field?.widget === 'list') {\n    const { field: subField } = /** @type {ListFieldWithSubField} */ (field);\n    const { fields } = /** @type {ListFieldWithSubFields} */ (field);\n    const { types } = /** @type {ListFieldWithTypes} */ (field);\n\n    return !fields && !types && isDisplayValueFromOtherEntries(subField);\n  }\n\n  return false;\n};\n\n/**\n * Replacer.\n * @param {string} placeholder Field name or one of special tags. May contain transformations.\n * @param {ReplaceContext} context Context.\n * @returns {string} Replaced string.\n */\nexport const replace = (placeholder, context) => {\n  const {\n    content: valueMap,\n    collectionName,\n    fileName,\n    isIndexFile,\n    replaceSubContext,\n    locale,\n    fallbackSummary,\n  } = context;\n\n  const { value: tag, transformations: parsedTransformations } = parseTransformations(placeholder);\n  const keyPath = stripFieldTagPrefix(tag);\n  const getFieldArgs = { collectionName, fileName, valueMap, keyPath, isIndexFile };\n  let value = replaceSub(tag, replaceSubContext);\n\n  // Process nested templates in transformation arguments\n  const transformations = processNestedTemplates(parsedTransformations, (innerTag) =>\n    replace(innerTag, context),\n  );\n\n  if (value === undefined) {\n    // If the `date` transformation is defined, e.g. `{{publish_date | date('YYYY-MM')}}`, use the\n    // raw field value from the entry content. Otherwise, use the field display value. This is to\n    // avoid applying the transformation to the display value, which leads to unexpected results.\n    // Also use raw value for ternary transformations to preserve boolean truthiness.\n    if (transformations.some(({ method }) => method === 'date' || method === 'ternary')) {\n      value = Object.hasOwn(valueMap, keyPath) ? valueMap[keyPath] : undefined;\n    } else {\n      // A Relation field is displayed with a label taken from the referenced entry\n      if (isDisplayValueFromOtherEntries(getField(getFieldArgs))) {\n        relationLabelResolved = true;\n      }\n\n      value = getFieldDisplayValue({ ...getFieldArgs, locale });\n    }\n\n    // If the field is `title` and the value is empty, use the fallback summary if available\n    if (keyPath === 'title' && !value) {\n      value = fallbackSummary;\n    }\n  }\n\n  if (value === undefined) {\n    return '';\n  }\n\n  if (value instanceof Date && !transformations.length) {\n    const { year, month, day } = getDateTimeParts({ date: value });\n\n    return `${year}-${month}-${day}`;\n  }\n\n  if (transformations.length) {\n    value = applyTransformations({\n      fieldConfig: getField({ ...getFieldArgs }),\n      value,\n      transformations,\n      locale,\n    });\n  }\n\n  return String(value);\n};\n\n/**\n * Cache of formatted entry summaries, keyed by the `Entry` and `InternalCollection` objects, then\n * by the remaining inputs. Object identity is used for the two outer keys so the cache is\n * invalidated for free: the entry store always receives freshly-built objects when entries are\n * loaded or saved, and {@link getCollection} returns a stable object per collection. The entries\n * are garbage-collected along with the objects they belong to.\n * @type {WeakMap<Entry, WeakMap<InternalCollection, Map<string, CachedSummary>>>}\n */\nconst summaryCacheMap = new WeakMap();\n/**\n * Last seen `allEntries` array, used to detect changes for {@link getEntriesGeneration}.\n * @type {Entry[] | undefined}\n */\nlet lastAllEntries;\n/**\n * Number of times `allEntries` has changed. Recorded with a cached summary containing a Relation\n * field label, so it’s regenerated when the referenced entries change, which does not necessarily\n * replace the referencing entry itself. Other summaries only depend on their own entry, so they\n * survive a change to the rest of the store, such as a save or a remote refresh.\n */\nlet entriesGeneration = 0;\n\n/**\n * Get the current `allEntries` generation, incrementing it when the store’s array is replaced.\n * @returns {number} Generation number.\n */\nconst getEntriesGeneration = () => {\n  const entries = allEntries.current;\n\n  if (entries !== lastAllEntries) {\n    lastAllEntries = entries;\n    entriesGeneration += 1;\n  }\n\n  return entriesGeneration;\n};\n\n/**\n * Get the label and the `summary` template of the collection file or index file the given entry\n * is, which are used in place of the collection’s.\n * @param {InternalCollection} collection Entry’s collection.\n * @param {Entry} entry Entry.\n * @param {string} [fileName] Collection file name. File collection only.\n * @returns {{ collectionFile?: InternalCollectionFile, isIndexFile: boolean, label?: string,\n * template?: string }} The collection file, whether the entry is the index file, and its label and\n * template. The label is `undefined` for a regular entry.\n */\nconst getOwnSummaryOptions = (collection, entry, fileName) => {\n  const collectionFile = fileName ? getCollectionFile(collection, fileName) : undefined;\n\n  if (collectionFile) {\n    return {\n      collectionFile,\n      isIndexFile: false,\n      label: getCollectionFileLabel(collectionFile),\n      template: collectionFile.summary,\n    };\n  }\n\n  const isIndexFile = isCollectionIndexFile(collection, entry);\n  const { label, summary: template } = (isIndexFile && getIndexFile(collection)) || {};\n\n  return { isIndexFile, label, template };\n};\n\n/**\n * Format the given entry’s summary. This is the uncached implementation of\n * {@link getEntrySummary}.\n * @param {InternalCollection} collection Entry’s collection.\n * @param {Entry} entry Entry.\n * @param {object} [options] Options.\n * @param {InternalLocaleCode} [options.locale] Target locale. The default locale is used if\n * omitted.\n * @param {boolean} [options.useTemplate] Whether to use the collection’s `summary` template if\n * available.\n * @param {boolean} [options.allowMarkdown] Whether to allow Markdown and return HTML string.\n * @param {string} [options.template] Summary template that overrides the collection’s `summary`\n * option.\n * @param {boolean} [options.useIndexFileLabel] Whether to use the label of the collection’s index\n * file as its summary. Default: `true`.\n * @param {string} [options.fileName] Name of the collection file the entry belongs to. File\n * collection only.\n * @returns {string} Formatted entry summary.\n */\nconst formatEntrySummary = (\n  collection,\n  entry,\n  {\n    locale,\n    useTemplate = false,\n    allowMarkdown = false,\n    template,\n    useIndexFileLabel = true,\n    fileName,\n  } = {},\n) => {\n  const { _type, name: collectionName } = collection;\n\n  const {\n    collectionFile,\n    isIndexFile,\n    label,\n    template: ownTemplate,\n  } = getOwnSummaryOptions(collection, entry, fileName);\n\n  const useOwnTemplate = useTemplate && template === undefined && !!ownTemplate;\n\n  // A collection file or index file is labelled unless its own summary template is requested. A\n  // given template, such as `nested.summary` for the tree folder labels, doesn’t apply to it\n  if ((collectionFile || (isIndexFile && useIndexFileLabel)) && !useOwnTemplate) {\n    return /** @type {string} */ (label);\n  }\n\n  // A collection file has an i18n configuration of its own\n  const { defaultLocale } = (collectionFile ?? collection)._i18n;\n\n  const { _file: { basePath, fullPathRegEx } = {}, summary: collectionSummaryTemplate } =\n    _type === 'entry' ? collection : {};\n\n  const identifierField = getIdentifierFieldName(_type === 'entry' ? collection : undefined);\n  const summaryTemplate = template ?? ownTemplate ?? collectionSummaryTemplate;\n  const { locales, slug, commitDate, commitAuthor } = entry;\n  const requestedLocale = locale ?? defaultLocale;\n\n  // An entry may lack the locale, e.g. one only written in another locale\n  const contentLocale = Object.hasOwn(locales, requestedLocale)\n    ? requestedLocale\n    : (Object.keys(locales)[0] ?? requestedLocale);\n\n  const { content = {}, path: entryPath = '' } = locales[contentLocale] ?? {};\n\n  const fallbackSummary =\n    getEntrySummaryFromContent(content, { identifierField }) || label || slug.replaceAll('-', ' ');\n\n  if (!useTemplate || !summaryTemplate) {\n    return sanitizeEntrySummary(fallbackSummary, { allowMarkdown });\n  }\n\n  /** @type {ReplaceContext} */\n  const replaceContext = {\n    content,\n    collectionName,\n    fileName: collectionFile?.name,\n    isIndexFile,\n    replaceSubContext: {\n      slug,\n      entryPath,\n      basePath,\n      fullPathRegEx,\n      locales: Object.keys(locales),\n      localeSuffixes: getFileNameLocaleSuffixes(collectionFile ?? collection),\n      commitDate,\n      commitAuthor,\n    },\n    locale: contentLocale,\n    fallbackSummary,\n  };\n\n  return sanitizeEntrySummary(\n    replaceTemplateTags(summaryTemplate, (_match, placeholder) =>\n      replace(placeholder, replaceContext),\n    ),\n    { allowMarkdown },\n  );\n};\n\n/**\n * Get the given entry’s summary that can be displayed in the entry list and other places. Format it\n * with the summary template if necessary, or simply use the `title` or similar field in the entry.\n *\n * The result is memoized, because formatting always ends with a Markdown parse and an HTML\n * sanitization pass, and the entry list, the search results and the `_summary` sort all call this\n * once per entry — the list cells on every re-render.\n * @param {InternalCollection} collection Entry’s collection.\n * @param {Entry} entry Entry.\n * @param {object} [options] Options.\n * @param {InternalLocaleCode} [options.locale] Target locale. The default locale is used if\n * omitted.\n * @param {boolean} [options.useTemplate] Whether to use the collection’s `summary` template if\n * available.\n * @param {boolean} [options.allowMarkdown] Whether to allow Markdown and return HTML string.\n * @param {string} [options.template] Summary template that overrides the collection’s `summary`\n * option. Used for the folder labels in the tree of nested entries, which have their own\n * `nested.summary` option, and the template columns of the entry list’s table view.\n * @param {boolean} [options.useIndexFileLabel] Whether to use the label of the collection’s index\n * file as its summary, instead of formatting it. Default: `true`. A table view column showing a\n * template, such as `{{filename}}`, formats it for the index file too. With `useTemplate`, the\n * index file’s own `summary` template is used instead of the label if defined.\n * @param {string} [options.fileName] Name of the collection file the entry belongs to. File\n * collection only. The file’s label is returned, or with `useTemplate`, the file’s own `summary`\n * template is formatted with its fields if defined.\n * @returns {string} Formatted entry summary.\n * @see https://decapcms.org/docs/configuration-options/#summary\n * @see https://sveltiacms.app/en/docs/collections/entries/listings#summaries\n */\nexport const getEntrySummary = (collection, entry, options = {}) => {\n  const {\n    locale,\n    useTemplate = false,\n    allowMarkdown = false,\n    template,\n    useIndexFileLabel = true,\n    fileName,\n  } = options;\n\n  const optionCache = getOrCreate(\n    getOrCreate(summaryCacheMap, entry, () => new WeakMap()),\n    collection,\n    () => new Map(),\n  );\n\n  // The app locale is part of the key because a summary can contain a localized index file label\n  // or Relation field label\n  const cacheKey = [\n    locale ?? '',\n    useTemplate ? '1' : '0',\n    allowMarkdown ? '1' : '0',\n    template ?? '',\n    useIndexFileLabel ? '1' : '0',\n    fileName ?? '',\n    // `Array.join()` turns an unset locale into an empty string\n    appLocale.current,\n  ].join('\\n');\n\n  const generation = getEntriesGeneration();\n  const cached = optionCache.get(cacheKey);\n\n  if (cached && (cached.generation === undefined || cached.generation === generation)) {\n    return cached.summary;\n  }\n\n  // Resolving a Relation field label may format a summary of the referenced entry, so the flag is\n  // saved and restored around this one, passing on whether it has been set\n  const outerFlag = relationLabelResolved;\n\n  relationLabelResolved = false;\n\n  const summary = formatEntrySummary(collection, entry, options);\n  const dependsOnEntries = relationLabelResolved;\n\n  relationLabelResolved = outerFlag || dependsOnEntries;\n  optionCache.set(cacheKey, { summary, generation: dependsOnEntries ? generation : undefined });\n\n  return summary;\n};\n\n/**\n * Get the summary of a file in a file collection, formatted with the file’s own `summary` template\n * to be displayed in the file list.\n * @param {InternalCollection} collection File collection.\n * @param {string} fileName Collection file name.\n * @returns {string | undefined} Summary as HTML, which can contain Markdown formatting, or\n * `undefined` if the file has no `summary` template or doesn’t exist in the repository yet, so the\n * file label is displayed instead.\n */\nexport const getCollectionFileSummary = (collection, fileName) => {\n  if (!getCollectionFile(collection, fileName)?.summary) {\n    return undefined;\n  }\n\n  const entry = getCollectionFileEntry(collection.name, fileName);\n\n  return entry\n    ? getEntrySummary(collection, entry, { fileName, useTemplate: true, allowMarkdown: true })\n    : undefined;\n};\n","import { generateUUID } from '@sveltia/utils/crypto';\n\nimport { DATE_TIME_FIELDS, UUID_TYPES } from '$lib/services/common/template/constants';\nimport { getFileNameParts } from '$lib/services/common/template/utils';\nimport {\n  getSharedEntryFileName,\n  stripIndexFileName,\n} from '$lib/services/contents/collection/nested';\nimport { getEntryDirName } from '$lib/services/contents/entry/paths';\nimport { getEntrySummaryFromContent } from '$lib/services/contents/entry/summary';\n\n/**\n * @import { ReplaceSubContext } from '$lib/services/common/template/replacers';\n */\n\n/**\n * Handles date-time related template tags.\n * @param {string} tag The template tag.\n * @param {Record<string, string>} dateTimeParts Date-time parts object.\n * @returns {string | undefined} The date-time value or undefined if not a date-time tag.\n */\nexport const handleDateTimeTag = (tag, dateTimeParts) =>\n  DATE_TIME_FIELDS.includes(tag) ? dateTimeParts[tag] : undefined;\n\n/**\n * Handles UUID-related template tags.\n * @param {string} tag The template tag.\n * @returns {string | undefined} The UUID value or undefined if not a UUID tag.\n */\nexport const handleUuidTag = (tag) =>\n  Object.hasOwn(UUID_TYPES, tag) ? generateUUID(UUID_TYPES[tag].length) : undefined;\n\n/**\n * Handles slug-related template tags.\n * @param {string} tag Field name or special tag.\n * @param {ReplaceSubContext} context Replacement context.\n * @returns {string | undefined} The slug value or undefined if not a slug tag.\n */\nexport const handleSlugTag = (tag, context) => {\n  if (tag !== 'slug') {\n    return undefined;\n  }\n\n  const { type, isIndexFile, currentSlug, content, identifierField, collection } = context;\n\n  // Return an empty string instead of `_index` when generating the preview path for an index file\n  // @see https://github.com/sveltia/sveltia-cms/issues/468\n  if (type === 'preview_path' && isIndexFile) {\n    return '';\n  }\n\n  const slug = currentSlug ?? getEntrySummaryFromContent(content, { identifierField });\n\n  // In a collection with nested entries, an entry’s slug is its path within the collection folder,\n  // which ends with the file name shared by every entry, e.g. `guides/intro/_index`. That file name\n  // is an implementation detail of the content folder, not part of the entry’s URL.\n  // @see https://github.com/decaporg/decap-cms/issues/4963\n  if (type === 'preview_path' && collection) {\n    // The collection’s own index file stands for the root of the preview path, so nothing is left\n    if (slug === getSharedEntryFileName(collection)) {\n      return '';\n    }\n\n    return stripIndexFileName(collection, slug);\n  }\n\n  return slug;\n};\n\n/**\n * Handles file path related template tags.\n * @param {string} tag The template tag.\n * @param {string | undefined} entryFilePath Entry file path.\n * @param {string | undefined} basePath Base path.\n * @param {string[]} [localeSuffixes] Locale codes that can follow the file name, with the\n * `multiple_files` i18n structure.\n * @param {RegExp} [fullPathRegEx] Entry collection’s entry path matcher, which tells the\n * `{{dirname}}` tag where the locale folder is.\n * @returns {string | undefined} The file path value or undefined if not a file path tag.\n */\nexport const handleFilePathTag = (\n  tag,\n  entryFilePath,\n  basePath,\n  localeSuffixes = [],\n  fullPathRegEx = undefined,\n) => {\n  if (!entryFilePath) {\n    return '';\n  }\n\n  switch (tag) {\n    case 'dirname':\n      // @see https://github.com/decaporg/decap-cms/issues/7752\n      return getEntryDirName(entryFilePath, { basePath, fullPathRegEx });\n\n    case 'filename':\n    case 'extension':\n      return getFileNameParts(entryFilePath, localeSuffixes)[tag];\n\n    default:\n      return undefined;\n  }\n};\n","import { generateUUID } from '@sveltia/utils/crypto';\nimport { getPathInfo } from '@sveltia/utils/file';\n\nimport { customStringTransformationRegistry } from '$lib/services/api/registries';\nimport { slugify } from '$lib/services/common/slug';\nimport { UUID_TYPES } from '$lib/services/common/template/constants';\nimport {\n  handleDateTimeTag,\n  handleFilePathTag,\n  handleSlugTag,\n  handleUuidTag,\n} from '$lib/services/common/template/handlers';\nimport { processNestedTemplates } from '$lib/services/common/template/nested';\nimport {\n  getFileNameLocaleSuffixes,\n  stripFieldTagPrefix,\n} from '$lib/services/common/template/utils';\nimport { applyTransformations, parseTransformations } from '$lib/services/common/transformations';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { sanitizePath } from '$lib/services/utils/file';\n\n/**\n * @import { FillTemplateOptions, GetFieldArgs } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} ReplaceSubContextBase\n * @property {string} identifierField Field name to identify the title.\n * @property {string | undefined} basePath Base path for the entry file.\n * @property {RegExp} [fullPathRegEx] Entry path matcher of the entry collection.\n */\n\n/**\n * @typedef {FillTemplateOptions & ReplaceSubContextBase} ReplaceSubContext\n */\n\n/**\n * @typedef {object} ReplaceContext\n * @property {ReplaceSubContext} replaceSubContext Context for `replaceSub`.\n * @property {GetFieldArgs} getFieldArgs Arguments for `getField`.\n */\n\n/**\n * Get a random value, reusing the one generated earlier for the same key if the context carries a\n * cache of them. A new entry’s slug is filled while it’s being edited to show what it will be, so a\n * random ID has to stay the same from one fill to the next, and until the entry is saved.\n * @param {ReplaceSubContext} context Replacement context.\n * @param {string} key What the value stands for, e.g. a tag in a locale.\n * @param {() => string} generate Function to generate a new value.\n * @returns {string} Value.\n */\nconst getRandomValue = ({ randomValues }, key, generate) => {\n  if (!randomValues) {\n    return generate();\n  }\n\n  return getOrCreate(randomValues, key, generate);\n};\n\n/**\n * Template tag replacer subroutine.\n * @param {string} tag Field name or special tag.\n * @param {ReplaceSubContext} context Replacement context.\n * @returns {any} Replaced value.\n */\nexport const replaceTemplateTag = (tag, context) => {\n  const {\n    type,\n    collection,\n    collectionFile,\n    content,\n    entryFilePath,\n    locale,\n    dateTimeParts,\n    basePath,\n    fullPathRegEx,\n    assetFileName,\n  } = context;\n\n  // Handle date-time fields. Parts are pre-calculated in `fillTemplate` to avoid redundant\n  // calculations for multiple date-time tags in the same template.\n  const _dateTimeParts = /** @type {Record<string, string>} */ (dateTimeParts);\n  const dateTimeValue = handleDateTimeTag(tag, _dateTimeParts);\n\n  if (dateTimeValue !== undefined) {\n    return dateTimeValue;\n  }\n\n  // Handle slug tag\n  const slugValue = handleSlugTag(tag, context);\n\n  if (slugValue !== undefined) {\n    return slugValue;\n  }\n\n  // Handle UUID tags\n  if (Object.hasOwn(UUID_TYPES, tag)) {\n    return getRandomValue(\n      context,\n      `${locale}:${tag}`,\n      () => /** @type {string} */ (handleUuidTag(tag)),\n    );\n  }\n\n  // Handle the original file name tags when naming an asset file\n  if (assetFileName !== undefined && (tag === 'filename' || tag === 'extension')) {\n    return getPathInfo(assetFileName)[tag] ?? '';\n  }\n\n  // Handle locale tag for preview path\n  if (type === 'preview_path' && tag === 'locale') {\n    return locale;\n  }\n\n  // Handle file path related tags. A collection file can be localized differently from its\n  // collection, e.g. as multiple files, so its own i18n configuration decides the locale suffix\n  if (type === 'preview_path' || type === 'media_folder') {\n    const filePathValue = handleFilePathTag(\n      tag,\n      entryFilePath,\n      basePath,\n      getFileNameLocaleSuffixes(collectionFile ?? collection),\n      fullPathRegEx,\n    );\n\n    if (filePathValue !== undefined) {\n      return filePathValue;\n    }\n\n    // `{{fields.*}}` tags are supported in the preview path template, but not in the media folder\n    // path template, so we return `undefined` instead of the field value there to avoid generating\n    // invalid paths.\n    if (type === 'media_folder') {\n      return undefined;\n    }\n  }\n\n  const keyPath = stripFieldTagPrefix(tag);\n\n  // Handle field values. A field named after an `Object.prototype` member, e.g. `constructor`,\n  // mustn’t resolve to that member when the content lacks the field\n  return Object.hasOwn(content, keyPath) ? content[keyPath] : undefined;\n};\n\n/**\n * Template placeholder replacer.\n * @param {string} placeholder Field name or one of special tags. May contain transformations.\n * @param {ReplaceContext} context Context for replacement.\n * @returns {string} Replaced string.\n */\nexport const replaceTemplatePlaceholder = (placeholder, context) => {\n  const { replaceSubContext, getFieldArgs } = context;\n  const { value: tag, transformations: parsedTransformations } = parseTransformations(placeholder);\n  let value = replaceTemplateTag(tag, replaceSubContext);\n\n  // Process nested templates in transformation arguments\n  const transformations = processNestedTemplates(parsedTransformations, (innerTag) =>\n    String(replaceTemplateTag(innerTag, replaceSubContext) ?? ''),\n  );\n\n  // Fall back with a random ID unless the `default` or `ternary` transformation, or a custom one,\n  // is defined, which may give a value for a missing one. `ternary` always gives one of its values,\n  // so a missing value, e.g. of a Boolean field added after the entry was saved, gets the falsy one\n  const hasValueTransformation = parsedTransformations.some(\n    (tf) => tf.args.defaultValue !== undefined || tf.method === 'ternary',\n  );\n\n  const hasCustomTransformation = parsedTransformations.some((tf) =>\n    customStringTransformationRegistry.has(tf.method),\n  );\n\n  // An empty number field holds `null`, which mustn’t become the word `null`\n  const isMissingValue = value === undefined || value === null;\n  const { type, locale } = replaceSubContext;\n\n  // A random fallback keeps generated slugs and paths unique, but a `preview_path` is recomputed on\n  // every render and its result feeds a URL that an effect watches, so a value that changes on each\n  // pass sends the entry editor into an infinite render loop. There is nothing sensible to put in a\n  // preview URL for a tag that resolves to nothing anyway, so give up on the path instead and let\n  // `getPreviewPath()` render no link at all.\n  // @see https://github.com/sveltia/sveltia-cms/issues/943\n  /**\n   * Give up on a preview path whose tag resolves to nothing, so the caller can drop the link\n   * instead of building a URL around a value that changes on every render. A media library prefix\n   * also needs the real value: a random one would scatter the files in folders of their own.\n   * @throws {Error} If the template is a `preview_path` or a media library prefix.\n   */\n  const bailOnUnresolvableTag = () => {\n    if (type === 'preview_path' || type === 'library_prefix') {\n      throw new Error(`Unresolvable template tag: ${tag}`);\n    }\n  };\n\n  /**\n   * Get a random ID for an unresolvable tag, which is reused like the other random values.\n   * @returns {string} Random ID.\n   */\n  const getFallbackValue = () => {\n    bailOnUnresolvableTag();\n\n    return getRandomValue(replaceSubContext, `${locale}:fallback:${placeholder}`, () =>\n      generateUUID('short'),\n    );\n  };\n\n  if (isMissingValue && !hasValueTransformation && !hasCustomTransformation) {\n    return getFallbackValue();\n  }\n\n  if (transformations.length) {\n    value = applyTransformations({\n      fieldConfig: getField({ ...getFieldArgs, keyPath: stripFieldTagPrefix(tag) }),\n      value,\n      transformations,\n      locale,\n    });\n  }\n\n  // A custom transformation may give nothing for a missing value after all. The result of `default`\n  // or `ternary` is kept as is, even if its nested template resolves to nothing\n  if (isMissingValue && !hasValueTransformation && value === '') {\n    return getFallbackValue();\n  }\n\n  // A value stands for a single folder of a media library prefix, so it can’t add path segments.\n  // Unlike a slug, an empty value doesn’t get a random ID\n  if (type === 'library_prefix') {\n    const slug = slugify(sanitizePath(String(value)), {\n      locale,\n      maxLength: Infinity,\n      fallback: false,\n    });\n\n    return slug || getFallbackValue();\n  }\n\n  // Sanitize path traversal attempts first by removing `.` and `..` segments to prevent writing\n  // outside the intended directory structure. This must happen before slugification to ensure that\n  // inputs like `../foo` don’t become `..-foo` (with `/` converted to `-`).\n  value = sanitizePath(String(value));\n\n  // Return the value as-is when generating the preview path or media folder path\n  if (type) {\n    return value;\n  }\n\n  // Slugify the value for a slug or filename. Don’t limit the length here; it will be handled later\n  // in `fillTemplate`. A value that leaves nothing, e.g. an empty field, falls back to a random ID,\n  // which is reused like the other random values\n  return (\n    slugify(value, { locale, maxLength: Infinity, fallback: false }) ||\n    getRandomValue(replaceSubContext, `${locale}:fallback:${placeholder}`, () =>\n      generateUUID('short'),\n    )\n  );\n};\n","import { createLazyModule } from '$lib/services/api/lazy-module';\nimport { loadChunk } from '$lib/services/app/dependencies';\nimport { cmsConfig } from '$lib/services/config';\n\n/**\n * @import { InternalCmsConfig } from '$lib/types/private';\n * @import { GitHubBackend } from '$lib/types/public';\n */\n\n/**\n * The `additions` chunk: the UI and services of Sveltia CMS Additions.\n * @typedef {typeof import('$lib/chunks/additions.js')} AdditionsChunk\n */\n\n/**\n * Check whether the CMS works with Sveltia CMS Additions, which replaces GitHub sign-in with its\n * own accounts and hands out GitHub tokens. It’s turned on with `auth_type: additions` on the\n * GitHub backend.\n * @param {InternalCmsConfig | undefined} [config] CMS configuration. Default: the current one.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/918\n */\nexport const isAdditionsEnabled = (config = cmsConfig.current) => {\n  const backend = /** @type {GitHubBackend | undefined} */ (config?.backend);\n\n  return backend?.name === 'github' && backend.auth_type === 'additions';\n};\n\n/**\n * Get the base URL of the Sveltia CMS Additions service, which is the backend’s `base_url`.\n * @returns {string} URL without a trailing slash.\n */\nexport const getAdditionsURL = () =>\n  /** @type {string} */ (\n    /** @type {GitHubBackend} */ (/** @type {InternalCmsConfig} */ (cmsConfig.current).backend)\n      .base_url\n  ).replace(/\\/+$/, '');\n\n/**\n * Loader of the `additions` chunk, which holds everything Sveltia CMS Additions needs, so a site\n * without it never downloads it.\n */\nconst additionsChunk = createLazyModule({\n  /**\n   * Fetch the chunk.\n   * @returns {Promise<AdditionsChunk>} Chunk.\n   */\n  loader: () => loadChunk('additions'),\n  notLoadedMessage: 'The additions chunk is not loaded yet.',\n});\n\n/**\n * Load the `additions` chunk if the CMS works with Sveltia CMS Additions. It’s loaded along with\n * the backend, so it’s there before the sign-in page offers anything, and the rest of the app can\n * use it with {@link getAdditions} once the user is signed in.\n * @returns {Promise<AdditionsChunk | undefined>} Chunk, or `undefined` without Sveltia CMS\n * Additions.\n * @throws {Error} If the chunk can’t be loaded.\n */\nexport const loadAdditions = async () => (isAdditionsEnabled() ? additionsChunk.load() : undefined);\n\n/**\n * Get the `additions` chunk, if the CMS works with Sveltia CMS Additions and the chunk has been\n * loaded. Reading this in a reaction, e.g. a `$derived`, runs it again once the chunk is loaded.\n * @returns {AdditionsChunk | undefined} Chunk.\n */\nexport const getAdditions = () =>\n  additionsChunk.loaded.current && isAdditionsEnabled() ? additionsChunk.get() : undefined;\n\n/**\n * Get the `additions` chunk where it must have been loaded: in a feature only offered with Sveltia\n * CMS Additions, whose chunk is loaded along with the backend, before the user can sign in.\n * @returns {AdditionsChunk} Chunk.\n * @throws {Error} If it hasn’t been loaded, which would be a bug.\n */\nexport const requireAdditions = () => additionsChunk.get();\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\n\n/**\n * @import { GitFileSystem, GitFilterRule } from '$lib/types/private';\n */\n\n/**\n * Convert a `.gitattributes` pattern to a regular expression. A pattern with a slash is matched\n * against the path relative to the directory of the file, and one without against the file name at\n * any depth, like a `.gitignore` pattern.\n * @param {string} pattern Pattern.\n * @param {object} [options] Options.\n * @param {boolean} [options.ignoreCase] Whether to match the path case-insensitively, like Git does\n * when `core.ignorecase` is `true`.\n * @returns {RegExp} Regular expression.\n * @see https://git-scm.com/docs/gitattributes#_description\n * @see https://git-scm.com/docs/gitignore#_pattern_format\n */\nexport const globToRegExp = (pattern, { ignoreCase = false } = {}) => {\n  const anchored = pattern.includes('/');\n  const glob = pattern.replace(/^\\//, '');\n  let source = '';\n\n  for (let index = 0; index < glob.length; index += 1) {\n    const char = glob[index];\n\n    if (glob.startsWith('**/', index)) {\n      source += '(?:.*/)?';\n      index += 2;\n    } else if (glob.startsWith('/**', index) && index + 3 === glob.length) {\n      source += '/.*';\n      index += 2;\n    } else if (char === '*') {\n      source += '[^/]*';\n    } else if (char === '?') {\n      source += '[^/]';\n    } else if (char === '[' && glob.indexOf(']', index + 2) > 0) {\n      const end = glob.indexOf(']', index + 2);\n\n      const body = glob\n        .slice(index + 1, end)\n        .replace(/^!/, '^')\n        .replaceAll('\\\\', '\\\\\\\\');\n\n      source += `[${body}]`;\n      index = end;\n    } else {\n      source += char.replace(/[$()+.[\\\\\\]^{|}]/, '\\\\$&');\n    }\n  }\n\n  return new RegExp(anchored ? `^${source}$` : `(?:^|/)${source}$`, ignoreCase ? 'i' : '');\n};\n\n/**\n * Parse the rules in a `.gitattributes` file that set or unset the `filter` attribute, which Git\n * LFS uses with the `lfs` value.\n * @param {string} text Content of the file.\n * @param {object} [options] Options.\n * @param {boolean} [options.ignoreCase] Whether to match the paths case-insensitively.\n * @returns {GitFilterRule[]} Rules.\n */\nexport const parseFilterRules = (text, { ignoreCase = false } = {}) =>\n  text.split(/\\r?\\n/).flatMap((line) => {\n    const [pattern, ...attributes] = line.trim().split(/\\s+/);\n\n    // Skip empty lines, comments, macro definitions, quoted patterns that would need unescaping,\n    // and directory patterns, which never apply to the files inside\n    if (!pattern || /^[#\"]|^\\[attr\\]/.test(pattern) || pattern.endsWith('/')) {\n      return [];\n    }\n\n    const attribute = attributes.findLast((attr) => /^[-!]?filter(?:=|$)/.test(attr));\n\n    return attribute\n      ? [{ regex: globToRegExp(pattern, { ignoreCase }), lfs: attribute === 'filter=lfs' }]\n      : [];\n  });\n\n/**\n * Find a file that’s tracked with Git LFS among the given ones, according to the `.gitattributes`\n * files in the repository and `.git/info/attributes`. Such a file has to be committed as a pointer\n * to the actual file, which only Git LFS can create.\n * @param {GitFileSystem} fs File system.\n * @param {string[]} paths File paths, relative to the repository root.\n * @param {object} [options] Options.\n * @param {boolean} [options.ignoreCase] Whether to match the paths case-insensitively, like Git\n * does when `core.ignorecase` is `true`, e.g. `IMG_1234.JPG` with a `*.jpg` pattern.\n * @returns {Promise<string | undefined>} Path of the first file tracked with Git LFS, if any.\n */\nexport const findLfsTrackedPath = async (fs, paths, { ignoreCase = false } = {}) => {\n  /** @type {Map<string, Promise<GitFilterRule[]>>} */\n  const cache = new Map();\n\n  /**\n   * Read the filter rules in a file, if it exists.\n   * @param {string} path File path.\n   * @returns {Promise<GitFilterRule[]>} Rules.\n   */\n  const getRules = (path) => {\n    let rules = cache.get(path);\n\n    if (!rules) {\n      rules = /** @type {Promise<string>} */ (fs.readFile(path, { encoding: 'utf8' })).then(\n        (text) => parseFilterRules(text, { ignoreCase }),\n        () => [],\n      );\n      cache.set(path, rules);\n    }\n\n    return rules;\n  };\n\n  for (const path of paths) {\n    const segments = path.split('/');\n    let lfs = false;\n\n    // A file in a deeper directory takes precedence, and `.git/info/attributes` over all of them,\n    // while within a file, a later line takes precedence\n    const sources = [\n      ...segments.map((_, depth) => {\n        const dir = segments.slice(0, depth).join('/');\n\n        return {\n          file: dir ? `${dir}/.gitattributes` : '.gitattributes',\n          relativePath: segments.slice(depth).join('/'),\n        };\n      }),\n      { file: '.git/info/attributes', relativePath: path },\n    ];\n\n    for (const { file, relativePath } of sources) {\n      for (const rule of await getRules(file)) {\n        if (rule.regex.test(relativePath)) {\n          ({ lfs } = rule);\n        }\n      }\n    }\n\n    if (lfs) {\n      return path;\n    }\n  }\n\n  return undefined;\n};\n","/**\n * @import { LocalGitOperation } from '$lib/types/private';\n */\n\n/**\n * Root directory of the repository in the file system given to isomorphic-git.\n */\nexport const DIR = '/';\n\n/**\n * Lock file Git creates while it updates the index. Git refuses to touch the index while it exists,\n * so the CMS creates it as well while it commits, and doesn’t commit while another Git process has\n * created it.\n */\nexport const INDEX_LOCK_PATH = '.git/index.lock';\n\n/**\n * Index file, which lists the files staged for the next commit.\n */\nexport const INDEX_PATH = '.git/index';\n\n/**\n * Files and directories in `.git` that exist while an operation that has to be finished or aborted\n * on the command line is in progress, along with the operation. A commit made in the meantime would\n * get in the way. `rebase-apply` is also used by `git am`, which marks it with an `applying` file.\n * @type {[string, LocalGitOperation][]}\n */\nexport const OPERATION_MARKERS = [\n  ['MERGE_HEAD', 'merge'],\n  ['CHERRY_PICK_HEAD', 'cherry_pick'],\n  ['REVERT_HEAD', 'revert'],\n  ['rebase-merge', 'rebase'],\n  ['rebase-apply', 'rebase'],\n  ['sequencer', 'cherry_pick'],\n];\n\n/**\n * Object ID Git uses in a reflog for a branch that didn’t exist before.\n */\nexport const ZERO_OID = '0'.repeat(40);\n\n/**\n * Size of an object ID in bytes: a SHA-1 hash. The checksum at the end of an index or pack file is\n * the same size.\n */\nexport const OID_SIZE = 20;\n\n/**\n * Mode of an index entry for a regular file.\n */\nexport const REGULAR_FILE_MODE = 0o100644;\n\n/**\n * Mode of an index entry for an executable file.\n */\nexport const EXECUTABLE_FILE_MODE = 0o100755;\n\n/**\n * Mode of an index entry for a submodule, whose object ID is a commit in another repository.\n */\nexport const GITLINK_MODE = 0o160000;\n\n/**\n * Mode of a directory, as a number.\n */\nexport const DIRECTORY_MODE = 0o40000;\n\n/**\n * Mode of a tree entry for a subtree, as Git writes it in a tree object, without a leading zero.\n */\nexport const TREE_MODE = '40000';\n","import { cmsConfig } from '$lib/services/config';\nimport { resolvePath } from '$lib/services/utils/file';\n\n/**\n * @import { FileChange } from '$lib/types/private';\n */\n\n/**\n * Normalize the value of the `root_dir` backend option: the empty segments and `.` segments are\n * dropped, so `/apps/site/`, `./apps/site` and `apps//site` all become `apps/site`, while an empty\n * string, `.` and `/` mean the repository root.\n * @param {unknown} value Option value.\n * @returns {string} Directory path relative to the repository root, without a leading or trailing\n * slash, or an empty string for the repository root.\n */\nexport const normalizeRootDir = (value) =>\n  typeof value === 'string'\n    ? value\n        .split('/')\n        .filter((segment) => segment && segment !== '.')\n        .join('/')\n    : '';\n\n/**\n * Get the directory the CMS treats as the root of the repository, configured with the `root_dir`\n * backend option. In a monorepo, it’s the directory of the site the CMS is for, and every path the\n * CMS deals with, including the ones in the configuration, is relative to it. The rest of the\n * repository is out of sight.\n * @returns {string} Directory path relative to the repository root, or an empty string when the\n * option isn’t set.\n */\nexport const getRootDir = () => normalizeRootDir(cmsConfig.current?.backend?.root_dir);\n\n/**\n * Convert a path relative to the root directory to a path relative to the repository root.\n * @param {string} path Path relative to the root directory. It may start with `../` to address a\n * file outside the directory, as {@link fromRepoPath} returns for one.\n * @param {string} [rootDir] Root directory. Default: the configured one.\n * @returns {string} Path relative to the repository root.\n */\nexport const toRepoPath = (path, rootDir = getRootDir()) =>\n  rootDir ? resolvePath(`${rootDir}/${path}`) : path;\n\n/**\n * Convert a path relative to the repository root to a path relative to the root directory. A file\n * outside the directory gets a path starting with `../`, which no entry or asset can have, so it’s\n * never mistaken for one, while {@link toRepoPath} can still turn it back.\n * @param {string} path Path relative to the repository root.\n * @param {string} [rootDir] Root directory. Default: the configured one.\n * @returns {string} Path relative to the root directory.\n */\nexport const fromRepoPath = (path, rootDir = getRootDir()) => {\n  if (!rootDir) {\n    return path;\n  }\n\n  if (path.startsWith(`${rootDir}/`)) {\n    return path.slice(rootDir.length + 1);\n  }\n\n  const rootSegments = rootDir.split('/');\n  const pathSegments = path.split('/');\n  let common = 0;\n\n  while (\n    common < rootSegments.length &&\n    common < pathSegments.length - 1 &&\n    rootSegments[common] === pathSegments[common]\n  ) {\n    common += 1;\n  }\n\n  return [...rootSegments.slice(common).map(() => '..'), ...pathSegments.slice(common)].join('/');\n};\n\n/**\n * Check whether the given path, relative to the root directory, addresses a file in the directory.\n * @param {string} path Path returned by {@link fromRepoPath}.\n * @returns {boolean} Result.\n */\nexport const isInRootDir = (path) => !path.startsWith('../');\n\n/**\n * Convert the paths of the given file changes to paths relative to the repository root.\n * @param {FileChange[]} changes File changes, with paths relative to the root directory.\n * @returns {FileChange[]} New file changes, or the same array when no root directory is configured.\n */\nexport const toRepoChanges = (changes) => {\n  const rootDir = getRootDir();\n\n  if (!rootDir) {\n    return changes;\n  }\n\n  return changes.map(({ previousPath, ...change }) => ({\n    ...change,\n    path: toRepoPath(change.path, rootDir),\n    ...(previousPath !== undefined && { previousPath: toRepoPath(previousPath, rootDir) }),\n  }));\n};\n","/* eslint-disable no-restricted-syntax */\n\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport { getRootDir } from '$lib/services/backends/root-dir';\n\n/**\n * Check if the given error says a file or directory doesn’t exist.\n * @param {unknown} ex Error.\n * @returns {boolean} `true` for a `NotFoundError`.\n */\nexport const isNotFoundError = (ex) => /** @type {DOMException} */ (ex)?.name === 'NotFoundError';\n\n/**\n * Check if the given error says a file was expected where there’s a directory, or the other way\n * round.\n * @param {unknown} ex Error.\n * @returns {boolean} `true` for a `TypeMismatchError`.\n */\nexport const isTypeMismatchError = (ex) =>\n  /** @type {DOMException} */ (ex)?.name === 'TypeMismatchError';\n\n/**\n * Check if a file or folder name can be spelled in more than one Unicode normalization form, like\n * `café`, whose `é` is one character in form C and two in form D.\n * @param {string} name Name or path.\n * @returns {boolean} Result.\n */\nexport const hasOtherSpellings = (name) => name.normalize('NFC') !== name.normalize('NFD');\n\n/**\n * Pick the name a file or folder has among the names of the entries in a directory, which can be\n * spelled in another Unicode normalization form than the given one. The exact spelling wins.\n * @param {string[]} names Names of the entries in the directory.\n * @param {string} name Name to look for.\n * @returns {string | undefined} Name of the file or folder in the directory, or `undefined` if\n * there’s none.\n */\nexport const pickEntryName = (names, name) => {\n  if (names.includes(name)) {\n    return name;\n  }\n\n  const normalizedName = name.normalize();\n\n  return names.find((entryName) => entryName.normalize() === normalizedName);\n};\n\n/**\n * Find the name a file or folder has in a directory, which can be spelled in another Unicode\n * normalization form than the given one. The CMS works with names in form C, while a file added on\n * Linux, or by a program on macOS, can have a name in form D, and a file system that compares names\n * byte for byte, like ext4, NTFS or the origin private file system, wouldn’t find the file by the\n * other spelling. On macOS, which ignores the normalization, the name is found as it is.\n * @param {FileSystemDirectoryHandle} dirHandle Directory handle.\n * @param {string} name Name.\n * @returns {Promise<string>} Name of the file or folder in the directory, or the given name if\n * there’s none.\n */\nexport const findEntryName = async (dirHandle, name) => {\n  if (!hasOtherSpellings(name)) {\n    return name;\n  }\n\n  try {\n    await dirHandle.getFileHandle(name);\n\n    return name;\n  } catch (ex) {\n    if (isTypeMismatchError(ex)) {\n      // It’s a folder\n      return name;\n    }\n\n    if (!isNotFoundError(ex)) {\n      throw ex;\n    }\n  }\n\n  return pickEntryName(await Array.fromAsync(dirHandle.keys()), name) ?? name;\n};\n\n/**\n * Get a file or directory handle at the given path. A file or folder whose name is spelled in\n * another Unicode normalization form is found too, and a missing one is created with the given\n * spelling.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {string | undefined} path Path to the file/directory.\n * @param {'file' | 'directory'} [type] Type of the handle to retrieve.\n * @param {object} [options] Options.\n * @param {boolean} [options.create] Whether to create the file/directory, along with any missing\n * parent directory, if it doesn’t exist. Default: `true`.\n * @returns {Promise<FileSystemFileHandle | FileSystemDirectoryHandle>} Handle.\n * @throws {Error} If the path is empty and the type is `file`, or if the file/directory doesn’t\n * exist and `create` is `false`.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryHandle/getFileHandle\n * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryHandle/getDirectoryHandle\n */\nexport const getHandleByPath = async (\n  rootDirHandle,\n  path,\n  type = 'file',\n  { create = true } = {},\n) => {\n  const normalizedPath = stripSlashes(path ?? '');\n  /** @type {FileSystemFileHandle | FileSystemDirectoryHandle} */\n  let handle = rootDirHandle;\n\n  if (!normalizedPath) {\n    if (type === 'directory') {\n      return handle;\n    }\n\n    throw new Error('Path is required for file handle retrieval');\n  }\n\n  const pathParts = normalizedPath.split('/');\n  const lastIndex = pathParts.length - 1;\n\n  for await (const [index, part] of pathParts.entries()) {\n    const name = await findEntryName(/** @type {FileSystemDirectoryHandle} */ (handle), part);\n\n    // If the part is the last one and the type is `file`, we need to ensure that we get a file\n    // handle. Otherwise, we can get a directory handle.\n    handle = await (index === lastIndex && type === 'file'\n      ? /** @type {FileSystemDirectoryHandle} */ (handle).getFileHandle(name, { create })\n      : /** @type {FileSystemDirectoryHandle} */ (handle).getDirectoryHandle(name, { create }));\n  }\n\n  return handle;\n};\n\n/**\n * Get a file handle at the given path. This function is used to retrieve a file handle for reading\n * or writing a file. If the file does not exist, it will be created.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {string} path Path to the file.\n * @returns {Promise<FileSystemFileHandle>} Handle.\n * @throws {Error} If the path is empty.\n */\nexport const getFileHandle = (rootDirHandle, path) =>\n  /** @type {Promise<FileSystemFileHandle>} */ (getHandleByPath(rootDirHandle, path, 'file'));\n\n/**\n * Get a directory handle at the given path. This function is used to retrieve a directory handle\n * for reading or writing files within a directory. If the directory does not exist, it will be\n * created.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {string | undefined} path Path to the directory.\n * @returns {Promise<FileSystemDirectoryHandle>} Handle.\n */\nexport const getDirectoryHandle = (rootDirHandle, path) =>\n  /** @type {Promise<FileSystemDirectoryHandle>} */ (\n    getHandleByPath(rootDirHandle, path, 'directory')\n  );\n\n/**\n * Read a file at the given path.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {string} path Path to the file.\n * @returns {Promise<File>} File.\n * @throws {Error} If the file doesn’t exist.\n */\nexport const readFile = async (rootDirHandle, path) => {\n  const handle = /** @type {FileSystemFileHandle} */ (\n    await getHandleByPath(rootDirHandle, path, 'file', { create: false })\n  );\n\n  return handle.getFile();\n};\n\n/**\n * Read a file at the given path, if it exists.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {string} path Path to the file.\n * @returns {Promise<File | undefined>} File, or `undefined` if it doesn’t exist.\n * @throws {Error} If the file can’t be read for any other reason.\n */\nexport const readFileIfExists = async (rootDirHandle, path) => {\n  try {\n    return await readFile(rootDirHandle, path);\n  } catch (ex) {\n    if (isNotFoundError(ex)) {\n      return undefined;\n    }\n\n    throw ex;\n  }\n};\n\n/**\n * Get the handle of the directory the CMS treats as the root of the repository, configured with the\n * `root_dir` backend option, so every path read or written through it is relative to that\n * directory.\n * @param {FileSystemDirectoryHandle} repoRootDirHandle Handle of the repository’s root directory.\n * @param {object} [options] Options.\n * @param {boolean} [options.create] Whether to create the directory if it doesn’t exist. Default:\n * `false`.\n * @returns {Promise<FileSystemDirectoryHandle>} Handle of the configured root directory, or the\n * given handle itself when the option isn’t set.\n * @throws {Error} If the directory doesn’t exist and `create` is `false`.\n */\nexport const getScopedRootDirHandle = async (repoRootDirHandle, { create = false } = {}) =>\n  /** @type {Promise<FileSystemDirectoryHandle>} */ (\n    getHandleByPath(repoRootDirHandle, getRootDir(), 'directory', { create })\n  );\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\n\nimport { DIRECTORY_MODE, REGULAR_FILE_MODE } from '$lib/services/backends/fs/git/constants';\nimport { isTypeMismatchError } from '$lib/services/backends/fs/shared/handles';\n\n/**\n * @import { GitFileSystem, GitFileStats } from '$lib/types/private';\n */\n\n/**\n * Node error codes for the `DOMException` names the File System API throws. Isomorphic-git tells\n * the errors apart by the code, e.g. to create a missing directory or to treat a missing file as\n * nonexistent.\n * @type {Record<string, string>}\n */\nconst ERROR_CODES = {\n  NotFoundError: 'ENOENT',\n  TypeMismatchError: 'ENOTDIR',\n  InvalidModificationError: 'ENOTEMPTY',\n};\n\n/**\n * Create an error that looks like one thrown by Node’s `fs` module.\n * @param {string} code Error code, e.g. `ENOENT`.\n * @param {string} path Path the operation failed on.\n * @returns {Error & { code: string, path: string }} Error.\n */\nexport const createFileSystemError = (code, path) =>\n  Object.assign(new Error(`${code}: ${path}`), { code, path });\n\n/**\n * Convert an error thrown by the File System API to one that looks like Node’s.\n * @param {unknown} ex Error.\n * @param {string} path Path the operation failed on.\n * @returns {unknown} Converted error, or the given error if it has no Node equivalent.\n */\nconst toFileSystemError = (ex, path) => {\n  const code = ERROR_CODES[/** @type {DOMException} */ (ex)?.name];\n\n  return code ? createFileSystemError(code, path) : ex;\n};\n\n/**\n * Split a path into its segments, dropping the empty and `.` ones, so `/a//b/./c` becomes\n * `['a', 'b', 'c']`.\n * @param {string} path Path, relative to the root directory, with or without a leading slash.\n * @returns {string[]} Segments.\n */\nexport const splitPath = (path) => path.split('/').filter((segment) => segment && segment !== '.');\n\n/**\n * Get the handle of a directory.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {string[]} segments Path segments of the directory.\n * @returns {Promise<FileSystemDirectoryHandle>} Handle.\n */\nconst getDirectory = async (rootDirHandle, segments) => {\n  let handle = rootDirHandle;\n\n  for (const name of segments) {\n    handle = await handle.getDirectoryHandle(name);\n  }\n\n  return handle;\n};\n\n/**\n * Get the handle of a file or directory, whichever exists at the given path.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {string[]} segments Path segments of the file or directory.\n * @returns {Promise<FileSystemFileHandle | FileSystemDirectoryHandle>} Handle.\n */\nconst getEntry = async (rootDirHandle, segments) => {\n  if (!segments.length) {\n    return rootDirHandle;\n  }\n\n  const parentHandle = await getDirectory(rootDirHandle, segments.slice(0, -1));\n  const name = /** @type {string} */ (segments.at(-1));\n\n  try {\n    return await parentHandle.getFileHandle(name);\n  } catch (ex) {\n    if (!isTypeMismatchError(ex)) {\n      throw ex;\n    }\n\n    return parentHandle.getDirectoryHandle(name);\n  }\n};\n\n/**\n * Open a writable stream to a file.\n * @param {FileSystemFileHandle} handle File handle.\n * @param {string} path File path, for the error.\n * @param {FileSystemCreateWritableOptions} [options] Options.\n * @returns {Promise<FileSystemWritableFileStream>} Stream.\n * @throws {Error} If the browser can’t write files, which an older version of Safari can’t.\n */\nconst openWritable = async (handle, path, options) => {\n  const writable = await handle.createWritable?.(options);\n\n  if (!writable) {\n    throw createFileSystemError('ENOTSUP', path);\n  }\n\n  return writable;\n};\n\n/**\n * Create the stats of a file or directory. The File System API only knows the size and the last\n * modified time, so the other values are zero. Git compares them to the actual ones the next time\n * it checks the working tree, finds the files that were staged here changed, and hashes them again\n * to be sure, which takes a moment but gives the right answer.\n * @param {FileSystemFileHandle | FileSystemDirectoryHandle} handle Handle.\n * @returns {Promise<GitFileStats>} Stats.\n */\nconst getStats = async (handle) => {\n  const isDirectory = handle.kind === 'directory';\n\n  const { size, lastModified } = isDirectory\n    ? { size: 0, lastModified: 0 }\n    : await /** @type {FileSystemFileHandle} */ (handle).getFile();\n\n  return {\n    mode: isDirectory ? DIRECTORY_MODE : REGULAR_FILE_MODE,\n    size,\n    mtimeMs: lastModified,\n    ctimeMs: lastModified,\n    ino: 0,\n    uid: 0,\n    gid: 0,\n    dev: 0,\n    /**\n     * Check if it’s a file.\n     * @returns {boolean} Result.\n     */\n    isFile: () => !isDirectory,\n    /**\n     * Check if it’s a directory.\n     * @returns {boolean} Result.\n     */\n    isDirectory: () => isDirectory,\n    /**\n     * Check if it’s a symbolic link, which it never is.\n     * @returns {boolean} `false`.\n     */\n    isSymbolicLink: () => false,\n  };\n};\n\n/**\n * Create a file system that isomorphic-git can work with, on top of a directory the user has picked\n * with the File System Access API. It has the subset of the promise-based API of Node’s `fs` module\n * that isomorphic-git uses. The paths are relative to the directory, which is `/`.\n * @param {FileSystemDirectoryHandle} rootDirHandle Handle of the repository’s root directory.\n * @param {object} context Context.\n * @param {typeof import('buffer').Buffer} context.Buffer `Buffer` class to return the binary file\n * content as, which isomorphic-git requires.\n * @returns {GitFileSystem} File system.\n * @see https://isomorphic-git.org/docs/en/fs\n */\nexport const createGitFileSystem = (rootDirHandle, { Buffer }) => {\n  /**\n   * Run a file system operation, converting the error it throws to one that looks like Node’s.\n   * @template T\n   * @param {string} path Path the operation is for.\n   * @param {(segments: string[]) => Promise<T>} operation Operation.\n   * @returns {Promise<T>} Result.\n   */\n  const run = async (path, operation) => {\n    try {\n      return await operation(splitPath(path));\n    } catch (ex) {\n      throw toFileSystemError(ex, path);\n    }\n  };\n\n  /**\n   * Get the handle of the parent directory of a file or directory, along with its name.\n   * @param {string[]} segments Path segments.\n   * @returns {Promise<{ parentHandle: FileSystemDirectoryHandle, name: string }>} Parent handle\n   * and name.\n   */\n  const getParent = async (segments) => ({\n    parentHandle: await getDirectory(rootDirHandle, segments.slice(0, -1)),\n    name: /** @type {string} */ (segments.at(-1)),\n  });\n\n  /**\n   * Open a writable stream to a file, write to it and close it, aborting the stream on a failure.\n   * @param {FileSystemFileHandle} handle File handle.\n   * @param {string} path File path, for the error.\n   * @param {FileSystemCreateWritableOptions | undefined} options Options for the stream.\n   * @param {(writable: FileSystemWritableFileStream) => Promise<void>} write Writer.\n   * @returns {Promise<void>} Nothing.\n   */\n  const writeThrough = async (handle, path, options, write) => {\n    const writable = await openWritable(handle, path, options);\n\n    try {\n      await write(writable);\n      await writable.close();\n    } catch (ex) {\n      // The stream may be unusable already, which mustn’t hide the actual error\n      await writable.abort().catch(() => undefined);\n      throw ex;\n    }\n  };\n\n  /**\n   * Get the stats of a file or directory.\n   * @param {string} path Path.\n   * @returns {Promise<GitFileStats>} Stats.\n   */\n  const stat = (path) =>\n    run(path, async (segments) => getStats(await getEntry(rootDirHandle, segments)));\n\n  return {\n    /**\n     * Read a file.\n     * @param {string} path Path.\n     * @param {string | { encoding?: string }} [options] Encoding, or options containing it.\n     * @returns {Promise<any>} Content: a `Buffer`, or a string if the `utf8` encoding is given.\n     */\n    readFile: (path, options) =>\n      run(path, async (segments) => {\n        const handle = await getEntry(rootDirHandle, segments);\n\n        if (handle.kind !== 'file') {\n          throw createFileSystemError('EISDIR', path);\n        }\n\n        const file = await /** @type {FileSystemFileHandle} */ (handle).getFile();\n        const encoding = typeof options === 'string' ? options : options?.encoding;\n\n        return encoding === 'utf8' ? file.text() : Buffer.from(await file.arrayBuffer());\n      }),\n    /**\n     * Write a file, replacing its content. The parent directory must exist.\n     * @param {string} path Path.\n     * @param {string | Uint8Array} data Content.\n     * @returns {Promise<void>} Nothing.\n     */\n    writeFile: (path, data) =>\n      run(path, async (segments) => {\n        const { parentHandle, name } = await getParent(segments);\n        const handle = await parentHandle.getFileHandle(name, { create: true });\n\n        // The new content replaces the file only once the stream is closed, so a failed write\n        // leaves the file as it was\n        await writeThrough(handle, path, undefined, async (writable) => {\n          await writable.write(/** @type {FileSystemWriteChunkType} */ (data));\n        });\n      }),\n    /**\n     * Add to the end of a file, creating it if needed. The parent directory must exist.\n     * @param {string} path Path.\n     * @param {string} data Content to add.\n     * @returns {Promise<void>} Nothing.\n     */\n    appendFile: (path, data) =>\n      run(path, async (segments) => {\n        const { parentHandle, name } = await getParent(segments);\n        const handle = await parentHandle.getFileHandle(name, { create: true });\n        const { size } = await handle.getFile();\n\n        await writeThrough(handle, path, { keepExistingData: true }, async (writable) => {\n          await writable.write({ type: 'write', position: size, data });\n        });\n      }),\n    /**\n     * Create a directory, unless it exists. The parent directory must exist.\n     * @param {string} path Path.\n     * @returns {Promise<void>} Nothing.\n     */\n    mkdir: (path) =>\n      run(path, async (segments) => {\n        const { parentHandle, name } = await getParent(segments);\n\n        await parentHandle.getDirectoryHandle(name, { create: true });\n      }),\n    /**\n     * Remove an empty directory.\n     * @param {string} path Path.\n     * @returns {Promise<void>} Nothing.\n     */\n    rmdir: (path) =>\n      run(path, async (segments) => {\n        const { parentHandle, name } = await getParent(segments);\n\n        // Make sure it’s a directory, as `removeEntry()` would remove a file just as well\n        await parentHandle.getDirectoryHandle(name);\n        await parentHandle.removeEntry(name);\n      }),\n    /**\n     * Remove a file.\n     * @param {string} path Path.\n     * @returns {Promise<void>} Nothing.\n     */\n    unlink: (path) =>\n      run(path, async (segments) => {\n        const { parentHandle, name } = await getParent(segments);\n\n        // Make sure it’s a file, as `removeEntry()` would remove an empty directory just as well\n        await parentHandle.getFileHandle(name);\n        await parentHandle.removeEntry(name);\n      }),\n    /**\n     * List the names in a directory.\n     * @param {string} path Path.\n     * @returns {Promise<string[]>} Names.\n     */\n    readdir: (path) =>\n      run(path, async (segments) => {\n        const handle = await getEntry(rootDirHandle, segments);\n\n        if (handle.kind !== 'directory') {\n          throw createFileSystemError('ENOTDIR', path);\n        }\n\n        /** @type {string[]} */\n        const names = [];\n\n        for await (const name of /** @type {FileSystemDirectoryHandle} */ (handle).keys()) {\n          names.push(name);\n        }\n\n        return names;\n      }),\n    stat,\n    // The same as `stat`, as there are no symbolic links\n    lstat: stat,\n    /**\n     * Read a symbolic link, which isn’t supported.\n     * @param {string} path Path.\n     * @returns {Promise<never>} Never.\n     */\n    readlink: async (path) => {\n      throw createFileSystemError('ENOTSUP', path);\n    },\n    /**\n     * Create a symbolic link, which isn’t supported.\n     * @param {string} _target Target.\n     * @param {string} path Path.\n     * @returns {Promise<never>} Never.\n     */\n    symlink: async (_target, path) => {\n      throw createFileSystemError('ENOTSUP', path);\n    },\n  };\n};\n\n/**\n * Check if an error thrown by the file system says a file or directory doesn’t exist.\n * @param {unknown} ex Error.\n * @returns {boolean} Result.\n */\nexport const isMissingError = (ex) => ['ENOENT', 'ENOTDIR'].includes(/** @type {any} */ (ex)?.code);\n\n/**\n * Check if a file or directory exists.\n * @param {GitFileSystem} fs File system.\n * @param {string} path Path.\n * @returns {Promise<boolean>} Result.\n * @throws {Error} If it can’t be told, e.g. the parent directory can’t be read.\n */\nexport const exists = async (fs, path) => {\n  try {\n    await fs.stat(path);\n\n    return true;\n  } catch (ex) {\n    if (isMissingError(ex)) {\n      return false;\n    }\n\n    throw ex;\n  }\n};\n","/**\n * Shared UTF-8 encoder.\n */\nexport const textEncoder = new TextEncoder();\n\n/**\n * Shared UTF-8 decoder.\n */\nexport const textDecoder = new TextDecoder();\n\n/**\n * Compare two byte arrays.\n * @param {Uint8Array} a One.\n * @param {Uint8Array} b The other.\n * @returns {number} A negative number if `a` comes first, a positive number if `b` comes first, or\n * zero if they’re equal.\n */\nexport const compareBytes = (a, b) => {\n  const length = Math.min(a.length, b.length);\n\n  for (let index = 0; index < length; index += 1) {\n    if (a[index] !== b[index]) {\n      return a[index] - b[index];\n    }\n  }\n\n  return a.length - b.length;\n};\n\n/**\n * Concatenate byte arrays into one.\n * @param {Uint8Array[]} parts Byte arrays.\n * @returns {Uint8Array} Joined bytes.\n */\nexport const concatBytes = (parts) => {\n  const bytes = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));\n  let position = 0;\n\n  parts.forEach((part) => {\n    bytes.set(part, position);\n    position += part.length;\n  });\n\n  return bytes;\n};\n","/**\n * Encode the given bytes as a lowercase hexadecimal string.\n * @param {ArrayBuffer | Uint8Array} bytes Bytes to encode.\n * @returns {string} Hex string.\n */\nexport const toHex = (bytes) =>\n  Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');\n\n/**\n * Convert a hexadecimal string to bytes.\n * @param {string} hex Hexadecimal string.\n * @returns {Uint8Array} Bytes.\n */\nexport const fromHex = (hex) =>\n  Uint8Array.from(hex.match(/../g) ?? [], (pair) => Number.parseInt(pair, 16));\n\n/**\n * Create an HMAC-SHA256 signature.\n * @param {string | Uint8Array} key Secret key.\n * @param {string} data Data to sign.\n * @returns {Promise<Uint8Array>} Raw signature bytes.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/sign\n */\nexport const hmacSha256 = async (key, data) => {\n  const encoder = new TextEncoder();\n\n  const cryptoKey = await crypto.subtle.importKey(\n    'raw',\n    /** @type {BufferSource} */ (typeof key === 'string' ? encoder.encode(key) : key),\n    { name: 'HMAC', hash: 'SHA-256' },\n    false,\n    ['sign'],\n  );\n\n  const signature = await crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(data));\n\n  return new Uint8Array(signature);\n};\n","/* eslint-disable no-bitwise */\n\nimport { getHash } from '@sveltia/utils/crypto';\n\nimport { OID_SIZE } from '$lib/services/backends/fs/git/constants';\nimport { compareBytes, concatBytes, textDecoder, textEncoder } from '$lib/services/utils/bytes';\nimport { fromHex, toHex } from '$lib/services/utils/crypto';\n\n/**\n * @import { GitIndex, GitIndexEntry, GitTreeNode } from '$lib/types/private';\n */\n\n/**\n * Size of an index entry before its path, in version 2: ten 32-bit stat fields, the object ID and\n * 16-bit flags.\n */\nconst ENTRY_HEADER_SIZE = 62;\n\n/**\n * Parse the cache tree extension of an index, where Git keeps the object IDs of the trees the\n * entries make up, as of when it last wrote them. A tree whose entries have changed since is\n * invalidated rather than updated, so only the valid ones are returned.\n * @param {Uint8Array} bytes Data of the extension.\n * @returns {Map<string, string>} Object IDs of the valid trees, keyed by directory path, which is\n * an empty string for the root.\n * @see https://git-scm.com/docs/index-format#_cache_tree\n */\nexport const parseCacheTree = (bytes) => {\n  /** @type {Map<string, string>} */\n  const trees = new Map();\n  let position = 0;\n\n  /**\n   * Read the text up to the given byte, and move past it.\n   * @param {number} terminator Byte the text ends with.\n   * @returns {string} Text.\n   */\n  const readUntil = (terminator) => {\n    const end = bytes.indexOf(terminator, position);\n    const text = textDecoder.decode(bytes.subarray(position, end));\n\n    position = end + 1;\n\n    return text;\n  };\n\n  /**\n   * Read a tree, followed by its subtrees, which are listed depth first.\n   * @param {string | undefined} parentPath Path of the parent directory, or `undefined` for the\n   * root.\n   */\n  const readTree = (parentPath) => {\n    const name = readUntil(0);\n    const path = parentPath ? `${parentPath}/${name}` : name;\n    // The number of index entries the tree covers, or -1 if it’s invalid, and of its subtrees\n    const [entryCount, subtreeCount] = readUntil(0x0a).split(' ').map(Number);\n\n    if (entryCount >= 0) {\n      trees.set(path, toHex(bytes.subarray(position, position + OID_SIZE)));\n      position += OID_SIZE;\n    }\n\n    for (let index = 0; index < subtreeCount; index += 1) {\n      readTree(path);\n    }\n  };\n\n  if (bytes.length) {\n    readTree(undefined);\n  }\n\n  return trees;\n};\n\n/**\n * Parse a Git index file, also known as the staging area, which lists the files in the next commit.\n * Only version 2 is parsed, as it’s the only version the CMS writes; a later version is used when a\n * feature that needs extended flags or path compression is in use, such as sparse-checkout, `git\n * add -N`, or `feature.manyFiles`, so the entries of one are left empty.\n * @param {ArrayBuffer} buffer Content of the index file.\n * @returns {GitIndex} Parsed index.\n * @throws {Error} If the file isn’t an index file.\n * @see https://git-scm.com/docs/index-format\n */\nexport const parseIndex = (buffer) => {\n  const view = new DataView(buffer);\n  const bytes = new Uint8Array(buffer);\n\n  if (textDecoder.decode(bytes.subarray(0, 4)) !== 'DIRC') {\n    throw new Error('Invalid index file');\n  }\n\n  const version = view.getUint32(4);\n  /** @type {GitIndexEntry[]} */\n  const entries = [];\n  /** @type {string[]} */\n  const extensions = [];\n\n  if (version !== 2) {\n    return { version, entries, extensions };\n  }\n\n  const count = view.getUint32(8);\n  let position = 12;\n\n  for (let index = 0; index < count; index += 1) {\n    const flags = view.getUint16(position + 60);\n    const pathStart = position + ENTRY_HEADER_SIZE;\n\n    // The flags have the path length, unless it’s too long to fit in 12 bits\n    const pathLength =\n      (flags & 0xfff) < 0xfff ? flags & 0xfff : bytes.indexOf(0, pathStart) - pathStart;\n\n    // An entry is padded with 1 to 8 null bytes to a multiple of 8 bytes\n    const end = position + ((ENTRY_HEADER_SIZE + pathLength + 8) & ~7);\n\n    entries.push({\n      path: textDecoder.decode(bytes.subarray(pathStart, pathStart + pathLength)),\n      mode: view.getUint32(position + 24),\n      oid: toHex(bytes.subarray(position + 40, position + 40 + OID_SIZE)),\n      stage: (flags >> 12) & 0x3,\n      raw: bytes.subarray(position, end),\n    });\n\n    position = end;\n  }\n\n  /** @type {Map<string, string> | undefined} */\n  let cacheTree;\n\n  // Each extension has a 4-byte signature and a 32-bit size, followed by the data\n  while (position < bytes.length - OID_SIZE) {\n    const signature = textDecoder.decode(bytes.subarray(position, position + 4));\n    const size = view.getUint32(position + 4);\n\n    extensions.push(signature);\n\n    if (signature === 'TREE') {\n      cacheTree = parseCacheTree(bytes.subarray(position + 8, position + 8 + size));\n    }\n\n    position += 8 + size;\n  }\n\n  return { version, entries, extensions, ...(cacheTree ? { cacheTree } : {}) };\n};\n\n/**\n * Check if an index has an extension that Git requires a reader to understand. Git marks such an\n * extension with a signature starting with a lowercase letter, e.g. `link` for a split index or\n * `sdir` for a sparse index, while the others, starting with an uppercase letter, are optional\n * caches that can be dropped, which {@link serializeIndex} does.\n * @param {GitIndex} index Parsed index.\n * @returns {boolean} Result.\n * @see https://git-scm.com/docs/index-format#_extensions\n */\nexport const hasRequiredExtension = ({ extensions }) =>\n  extensions.some((signature) => /^[a-z]/.test(signature));\n\n/**\n * Create an index entry for a file, in the shape Git writes it in a version 2 index.\n * @param {object} args Arguments.\n * @param {string} args.path File path, relative to the repository root.\n * @param {number} args.mode File mode, e.g. `REGULAR_FILE_MODE`.\n * @param {string} args.oid Object ID of the file content.\n * @param {number} args.size File size in bytes.\n * @param {number} args.mtimeMs Last modified time. It also stands in for the time the file’s\n * status changed, which the File System API doesn’t tell; the other stats, like the device and\n * inode numbers, are zero. Git finds them different from the actual ones the next time it checks\n * the working tree, and hashes the file again to be sure, which takes a moment but gives the right\n * answer.\n * @returns {GitIndexEntry} Entry.\n * @see https://git-scm.com/docs/index-format\n */\nexport const createIndexEntry = ({ path, mode, oid, size, mtimeMs }) => {\n  const pathBytes = textEncoder.encode(path);\n  // The path is followed by 1 to 8 null bytes, to a multiple of 8 bytes\n  const raw = new Uint8Array((ENTRY_HEADER_SIZE + pathBytes.length + 8) & ~7);\n  const view = new DataView(raw.buffer);\n  const seconds = Math.floor(mtimeMs / 1000);\n  const nanoseconds = Math.round((mtimeMs - seconds * 1000) * 1e6);\n\n  // The change time, then the modification time, in seconds and nanoseconds\n  [0, 8].forEach((offset) => {\n    view.setUint32(offset, seconds % 2 ** 32);\n    view.setUint32(offset + 4, nanoseconds);\n  });\n\n  view.setUint32(24, mode);\n  view.setUint32(36, size % 2 ** 32);\n  raw.set(fromHex(oid), 40);\n  // The flags have the path length, unless it’s too long to fit in 12 bits\n  view.setUint16(60, Math.min(pathBytes.length, 0xfff));\n  raw.set(pathBytes, ENTRY_HEADER_SIZE);\n\n  return { path, mode, oid, stage: 0, raw };\n};\n\n/**\n * Compare two paths in the order Git sorts the index entries: by their UTF-8 bytes.\n * @param {string} a One.\n * @param {string} b The other.\n * @returns {number} A negative number if `a` comes first, a positive number if `b` comes first, or\n * zero if they’re equal.\n */\nconst comparePaths = (a, b) => compareBytes(textEncoder.encode(a), textEncoder.encode(b));\n\n/**\n * Find where an entry for a path is, or would be, among the sorted entries of an index.\n * @param {GitIndexEntry[]} entries Entries, all at stage 0.\n * @param {string} path File path.\n * @returns {{ position: number, found: boolean }} Position of the entry, or where it would be\n * inserted, and whether there’s an entry for the path.\n */\nexport const findIndexEntry = (entries, path) => {\n  let low = 0;\n  let high = entries.length;\n\n  while (low < high) {\n    const middle = (low + high) >>> 1;\n    const comparison = comparePaths(entries[middle].path, path);\n\n    if (!comparison) {\n      return { position: middle, found: true };\n    }\n\n    if (comparison < 0) {\n      low = middle + 1;\n    } else {\n      high = middle;\n    }\n  }\n\n  return { position: low, found: false };\n};\n\n/**\n * Update the entries of an index, keeping them in Git’s order.\n * @param {GitIndexEntry[]} entries Entries, all at stage 0, in Git’s order.\n * @param {object} changes Changes.\n * @param {Set<string>} changes.removedPaths Paths of the files to remove.\n * @param {GitIndexEntry[]} changes.addedEntries Entries to add, or to replace the existing entry\n * for the same path with.\n * @returns {GitIndexEntry[]} New entries. The given array is left as it was.\n */\nexport const updateIndexEntries = (entries, { removedPaths, addedEntries }) => {\n  const result = entries.filter(({ path }) => !removedPaths.has(path));\n\n  addedEntries.forEach((entry) => {\n    const { position, found } = findIndexEntry(result, entry.path);\n\n    result.splice(position, found ? 1 : 0, entry);\n  });\n\n  return result;\n};\n\n/**\n * Serialize a tree into the data of the cache tree extension of an index, so Git and the next save\n * can use the object IDs rather than hash the trees again. Each tree is followed by its subtrees,\n * depth first, and says how many index entries it covers: its files and those of its subtrees.\n * @param {GitTreeNode} tree Root tree built from the entries of the index.\n * @returns {Uint8Array} Data.\n * @see https://git-scm.com/docs/index-format#_cache_tree\n */\nexport const serializeCacheTree = (tree) => {\n  /** @type {Map<GitTreeNode, number>} */\n  const entryCounts = new Map();\n\n  /**\n   * Count the index entries a tree covers.\n   * @param {GitTreeNode} node Tree.\n   * @returns {number} Count.\n   */\n  const count = (node) => {\n    let entryCount = node.entries.filter(({ type }) => type !== 'tree').length;\n\n    node.subtrees.forEach((subtree) => {\n      entryCount += count(subtree);\n    });\n\n    entryCounts.set(node, entryCount);\n\n    return entryCount;\n  };\n\n  /** @type {Uint8Array[]} */\n  const parts = [];\n\n  /**\n   * Write a tree, followed by its subtrees.\n   * @param {GitTreeNode} node Tree.\n   * @param {string} name Directory name, which is empty for the root.\n   */\n  const write = (node, name) => {\n    parts.push(\n      textEncoder.encode(`${name}\\0${entryCounts.get(node)} ${node.subtrees.size}\\n`),\n      fromHex(node.oid),\n    );\n\n    node.subtrees.forEach((subtree, subtreeName) => {\n      write(subtree, subtreeName);\n    });\n  };\n\n  count(tree);\n  write(tree, '');\n\n  return concatBytes(parts);\n};\n\n/**\n * Serialize index entries into the content of a version 2 index file. Each entry is written as it\n * was read, stats included, so only the entries left out change. The extensions of the index read\n * are dropped, as they’re optional caches that Git rebuilds, apart from the cache tree, which is\n * written from the given tree.\n * @param {GitIndexEntry[]} entries Entries, in the order they were read.\n * @param {object} [options] Options.\n * @param {GitTreeNode} [options.tree] Tree built from the entries, to write the cache tree from.\n * @returns {Promise<Uint8Array>} Content of the index file.\n * @see https://git-scm.com/docs/index-format\n */\nexport const serializeIndex = async (entries, { tree } = {}) => {\n  const cacheTree = tree ? serializeCacheTree(tree) : undefined;\n  const entriesSize = entries.reduce((total, { raw }) => total + raw.length, 12);\n  const size = entriesSize + (cacheTree ? 8 + cacheTree.length : 0);\n  const bytes = new Uint8Array(size + OID_SIZE);\n  const view = new DataView(bytes.buffer);\n  let position = 12;\n\n  bytes.set(textEncoder.encode('DIRC'));\n  view.setUint32(4, 2);\n  view.setUint32(8, entries.length);\n\n  entries.forEach(({ raw }) => {\n    bytes.set(raw, position);\n    position += raw.length;\n  });\n\n  if (cacheTree) {\n    bytes.set(textEncoder.encode('TREE'), position);\n    view.setUint32(position + 4, cacheTree.length);\n    bytes.set(cacheTree, position + 8);\n  }\n\n  // The file ends with the SHA-1 hash of everything before it\n  bytes.set(fromHex(await getHash(bytes.subarray(0, size))), size);\n\n  return bytes;\n};\n","/* eslint-disable no-bitwise */\n/* eslint-disable no-continue */\n/* eslint-disable no-restricted-syntax */\n\nimport { getHash } from '@sveltia/utils/crypto';\n\nimport { OID_SIZE } from '$lib/services/backends/fs/git/constants';\nimport { isMissingError } from '$lib/services/backends/fs/git/file-system';\nimport { readFileIfExists } from '$lib/services/backends/fs/shared/handles';\nimport { concatBytes, textDecoder, textEncoder } from '$lib/services/utils/bytes';\nimport { fromHex, toHex } from '$lib/services/utils/crypto';\n\n/**\n * @import {\n * GitFileSystem,\n * GitObject,\n * GitObjectType,\n * GitPack,\n * GitPackIndex,\n * } from '$lib/types/private';\n */\n\n/**\n * Types of the objects in a pack file, by the number in an object header. 5 is reserved, and 6 and\n * 7 are deltas against another object, which has the actual type.\n * @type {Record<number, GitObjectType>}\n * @see https://git-scm.com/docs/gitformat-pack#_object_types\n */\nconst PACKED_OBJECT_TYPES = { 1: 'commit', 2: 'tree', 3: 'blob', 4: 'tag' };\nconst OFS_DELTA = 6;\nconst REF_DELTA = 7;\n/**\n * How deep a chain of deltas is followed before it’s considered broken. Git’s default limit is 50,\n * and `git gc --aggressive` uses 50 as well, so a longer chain is unlikely to be legitimate.\n */\nconst MAX_DELTA_DEPTH = 1000;\n\n/**\n * Prefix the content of an object with its header, as Git hashes and stores it.\n * @param {GitObjectType} type Object type.\n * @param {Uint8Array} content Object content.\n * @returns {Uint8Array} Header and content.\n */\nconst encodeObject = (type, content) =>\n  concatBytes([textEncoder.encode(`${type} ${content.length}\\0`), content]);\n\n/**\n * Calculate the Git object ID of an object.\n * @param {GitObjectType} type Object type.\n * @param {Uint8Array} content Object content.\n * @returns {Promise<string>} Object ID: SHA-1 hash in hexadecimal.\n * @see https://git-scm.com/book/en/v2/Git-Internals-Git-Objects\n */\nexport const hashObject = (type, content) => getHash(encodeObject(type, content));\n\n/**\n * Decompress zlib data, which Git objects are stored as.\n * @param {Uint8Array} bytes Compressed data.\n * @returns {Promise<Uint8Array>} Decompressed data.\n */\nexport const inflate = async (bytes) => {\n  const stream = new Blob([/** @type {Uint8Array<ArrayBuffer>} */ (bytes)])\n    .stream()\n    .pipeThrough(new DecompressionStream('deflate'));\n\n  return new Uint8Array(await new Response(stream).arrayBuffer());\n};\n\n/**\n * Compress data with zlib, which Git objects are stored as, using the browser’s native\n * implementation.\n * @param {Uint8Array} bytes Data.\n * @returns {Promise<Uint8Array>} Compressed data.\n */\nexport const deflate = async (bytes) => {\n  const { readable, writable } = new CompressionStream('deflate');\n  const writer = writable.getWriter();\n\n  // The data is written to the stream as it is rather than copied into a `Blob` first, which\n  // matters for a large asset. It’s read at the same time, or the writing would wait forever\n  const [, , compressed] = await Promise.all([\n    writer.write(/** @type {Uint8Array<ArrayBuffer>} */ (bytes)),\n    writer.close(),\n    new Response(readable).arrayBuffer(),\n  ]);\n\n  return new Uint8Array(compressed);\n};\n\n/**\n * Write an object to the repository as a loose object, unless one with the same ID exists. The\n * hashing and compression are native, which matters for a large asset.\n * @param {GitFileSystem} fs File system.\n * @param {GitObjectType} type Object type.\n * @param {Uint8Array} content Object content.\n * @returns {Promise<string>} Object ID.\n */\nexport const writeLooseObject = async (fs, type, content) => {\n  const bytes = encodeObject(type, content);\n  const oid = await getHash(bytes);\n  const dir = `.git/objects/${oid.slice(0, 2)}`;\n  const path = `${dir}/${oid.slice(2)}`;\n  let size = 0;\n\n  try {\n    ({ size } = await fs.stat(path));\n  } catch (ex) {\n    if (!isMissingError(ex)) {\n      throw ex;\n    }\n  }\n\n  // A file is created empty before its content is written, so a write cut short, e.g. by the tab\n  // being closed, leaves an empty file behind. Git never writes an empty object, so it’s missing\n  if (!size) {\n    await fs.mkdir(dir);\n    await fs.writeFile(path, await deflate(bytes));\n  }\n\n  return oid;\n};\n\n/**\n * Apply a delta to its base object, as found in a pack file.\n * @param {Uint8Array} base Content of the base object.\n * @param {Uint8Array} delta Delta.\n * @returns {Uint8Array} Content of the resulting object.\n * @throws {Error} If the delta doesn’t fit the base.\n * @see https://git-scm.com/docs/gitformat-pack#_deltified_representation\n */\nexport const applyDelta = (base, delta) => {\n  let position = 0;\n\n  /**\n   * Read a size from the delta header, encoded in 7-bit groups, least significant first.\n   * @returns {number} Size.\n   */\n  const readSize = () => {\n    let size = 0;\n    let factor = 1;\n    let byte;\n\n    do {\n      byte = delta[position];\n      position += 1;\n      size += (byte & 0x7f) * factor;\n      factor *= 128;\n    } while (byte & 0x80);\n\n    return size;\n  };\n\n  if (readSize() !== base.length) {\n    throw new Error('Delta base size mismatch');\n  }\n\n  const result = new Uint8Array(readSize());\n  let length = 0;\n\n  while (position < delta.length) {\n    const instruction = delta[position];\n\n    position += 1;\n\n    if (instruction & 0x80) {\n      // Copy a range of the base: the bits say which bytes of the offset and size follow\n      let offset = 0;\n      let size = 0;\n\n      for (let index = 0; index < 4; index += 1) {\n        if (instruction & (1 << index)) {\n          offset += delta[position] * 2 ** (8 * index);\n          position += 1;\n        }\n      }\n\n      for (let index = 0; index < 3; index += 1) {\n        if (instruction & (0x10 << index)) {\n          size += delta[position] * 2 ** (8 * index);\n          position += 1;\n        }\n      }\n\n      size ||= 0x10000;\n      result.set(base.subarray(offset, offset + size), length);\n      length += size;\n    } else if (instruction) {\n      // Insert the given number of bytes from the delta\n      result.set(delta.subarray(position, position + instruction), length);\n      position += instruction;\n      length += instruction;\n    } else {\n      throw new Error('Invalid delta instruction');\n    }\n  }\n\n  if (length !== result.length) {\n    throw new Error('Delta result size mismatch');\n  }\n\n  return result;\n};\n\n/**\n * Parse a loose object file’s decompressed content.\n * @param {Uint8Array} bytes Decompressed content: a header followed by the object content.\n * @returns {GitObject} Object.\n * @throws {Error} If the header is invalid.\n */\nexport const parseLooseObject = (bytes) => {\n  const nullIndex = bytes.indexOf(0);\n  const [type, size] = textDecoder.decode(bytes.subarray(0, nullIndex)).split(' ');\n  const content = bytes.subarray(nullIndex + 1);\n\n  if (!Object.values(PACKED_OBJECT_TYPES).includes(/** @type {any} */ (type))) {\n    throw new Error(`Invalid object type: ${type}`);\n  }\n\n  if (Number(size) !== content.length) {\n    throw new Error('Object size mismatch');\n  }\n\n  return { type: /** @type {GitObjectType} */ (type), content };\n};\n\n/**\n * Parse a pack index file, version 2, which lists the objects in the pack file of the same name\n * along with their positions in it.\n * @param {ArrayBuffer} buffer Content of the index file.\n * @returns {GitPackIndex} Parsed index.\n * @throws {Error} If the file isn’t a version 2 pack index. Version 1 hasn’t been written by\n * default since Git 1.5.2.\n * @see https://git-scm.com/docs/gitformat-pack#_version_2_pack_idx_files_support_packs_larger_than_4_gib_and\n */\nexport const parsePackIndex = (buffer) => {\n  const view = new DataView(buffer);\n\n  // `\\377tOc` followed by the version number\n  if (view.getUint32(0) !== 0xff744f63 || view.getUint32(4) !== 2) {\n    throw new Error('Unsupported pack index version');\n  }\n\n  const fanoutStart = 8;\n  const count = view.getUint32(fanoutStart + 255 * 4);\n  const oidsStart = fanoutStart + 256 * 4;\n  const offsetsStart = oidsStart + count * OID_SIZE + count * 4;\n  const largeOffsetsStart = offsetsStart + count * 4;\n  const fanout = Array.from({ length: 256 }, (_, index) => view.getUint32(fanoutStart + index * 4));\n  const offsets = new Float64Array(count);\n\n  for (let index = 0; index < count; index += 1) {\n    const value = view.getUint32(offsetsStart + index * 4);\n\n    // A pack larger than 2 GiB has the offsets that don’t fit in 31 bits in a separate table\n    offsets[index] =\n      value & 0x80000000\n        ? view.getUint32(largeOffsetsStart + (value & 0x7fffffff) * 8) * 2 ** 32 +\n          view.getUint32(largeOffsetsStart + (value & 0x7fffffff) * 8 + 4)\n        : value;\n  }\n\n  return { fanout, oids: new Uint8Array(buffer, oidsStart, count * OID_SIZE), offsets };\n};\n\n/**\n * Find the position of an object in a pack file.\n * @param {GitPackIndex} index Pack index.\n * @param {Uint8Array} oid Object ID.\n * @returns {number | undefined} Offset of the object in the pack file, or `undefined` if the pack\n * doesn’t have it.\n */\nexport const findPackedObject = ({ fanout, oids, offsets }, oid) => {\n  // The fanout table says how many objects have an ID starting with a byte up to the given one\n  let low = oid[0] ? fanout[oid[0] - 1] : 0;\n  let high = fanout[oid[0]];\n\n  while (low < high) {\n    const middle = (low + high) >>> 1;\n    let comparison = 0;\n\n    for (let byteIndex = 0; byteIndex < OID_SIZE && !comparison; byteIndex += 1) {\n      comparison = oids[middle * OID_SIZE + byteIndex] - oid[byteIndex];\n    }\n\n    if (!comparison) {\n      return offsets[middle];\n    }\n\n    if (comparison < 0) {\n      low = middle + 1;\n    } else {\n      high = middle;\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Get the position where the object at the given position ends in a pack file, which is where the\n * next object starts, or where the trailing checksum starts for the last object.\n * @param {GitPack} pack Pack.\n * @param {number} offset Offset of the object.\n * @returns {number} End offset.\n */\nconst getPackedObjectEnd = (pack, offset) => {\n  pack.sortedOffsets ??= Float64Array.from(pack.index.offsets).sort();\n\n  const { sortedOffsets } = pack;\n  let low = 0;\n  let high = sortedOffsets.length;\n\n  // Find the first offset greater than the given one\n  while (low < high) {\n    const middle = (low + high) >>> 1;\n\n    if (sortedOffsets[middle] <= offset) {\n      low = middle + 1;\n    } else {\n      high = middle;\n    }\n  }\n\n  return low < sortedOffsets.length ? sortedOffsets[low] : pack.file.size - OID_SIZE;\n};\n\n/**\n * Create a reader for the objects in a Git repository’s object database: the loose objects, and the\n * objects in pack files. A packed object is read by its position in the file, so a pack file is\n * never loaded as a whole, which matters for a repository with a long history of images. The\n * reader caches the pack indexes, so it’s meant for one operation; create another for the next one,\n * as `git gc` may have repacked the objects in the meantime.\n * @param {FileSystemDirectoryHandle} gitDirHandle Handle of the `.git` directory.\n * @returns {{ readObject: (oid: string) => Promise<GitObject | undefined> }} Reader.\n * `readObject` resolves with `undefined` if the object doesn’t exist.\n */\nexport const createObjectReader = (gitDirHandle) => {\n  /** @type {Promise<GitPack[]> | undefined} */\n  let packsPromise;\n\n  /**\n   * Load the pack indexes, along with the pack files they’re for.\n   * @returns {Promise<GitPack[]>} Packs.\n   */\n  const loadPacks = async () => {\n    /** @type {GitPack[]} */\n    const packs = [];\n    /** @type {FileSystemDirectoryHandle} */\n    let packDirHandle;\n\n    try {\n      packDirHandle = await (\n        await gitDirHandle.getDirectoryHandle('objects')\n      ).getDirectoryHandle('pack');\n    } catch {\n      return packs;\n    }\n\n    for await (const [name, handle] of packDirHandle.entries()) {\n      if (handle.kind !== 'file' || !name.endsWith('.idx')) {\n        continue;\n      }\n\n      const indexFile = await /** @type {FileSystemFileHandle} */ (handle).getFile();\n      const packHandle = await packDirHandle.getFileHandle(name.replace(/\\.idx$/, '.pack'));\n\n      packs.push({\n        index: parsePackIndex(await indexFile.arrayBuffer()),\n        file: await packHandle.getFile(),\n      });\n    }\n\n    return packs;\n  };\n\n  /**\n   * Find the pack containing an object.\n   * @param {string} oid Object ID.\n   * @returns {Promise<{ pack: GitPack, offset: number } | undefined>} Pack and the object’s offset\n   * in it, or `undefined` if no pack has the object.\n   */\n  const findInPacks = async (oid) => {\n    packsPromise ??= loadPacks();\n\n    const oidBytes = fromHex(oid);\n\n    for (const pack of await packsPromise) {\n      const offset = findPackedObject(pack.index, oidBytes);\n\n      if (offset !== undefined) {\n        return { pack, offset };\n      }\n    }\n\n    return undefined;\n  };\n\n  /**\n   * Read a loose object.\n   * @param {string} oid Object ID.\n   * @returns {Promise<GitObject | undefined>} Object, or `undefined` if it’s not a loose object.\n   */\n  const readLooseObject = async (oid) => {\n    const file = await readFileIfExists(gitDirHandle, `objects/${oid.slice(0, 2)}/${oid.slice(2)}`);\n\n    if (!file) {\n      return undefined;\n    }\n\n    return parseLooseObject(await inflate(new Uint8Array(await file.arrayBuffer())));\n  };\n\n  /**\n   * Read an object from a pack file.\n   * @param {GitPack} pack Pack.\n   * @param {number} offset Offset of the object in the pack file.\n   * @param {number} depth How many deltas deep the object is.\n   * @returns {Promise<GitObject>} Object.\n   * @throws {Error} If the object is invalid, or its delta base is missing.\n   */\n  const readPackedObject = async (pack, offset, depth) => {\n    if (depth > MAX_DELTA_DEPTH) {\n      throw new Error('Delta chain too long');\n    }\n\n    const end = getPackedObjectEnd(pack, offset);\n    const bytes = new Uint8Array(await pack.file.slice(offset, end).arrayBuffer());\n    let position = 0;\n    let byte = bytes[position];\n    const typeNumber = (byte >> 4) & 0x7;\n\n    // Skip the size, which the decompressed data tells anyway\n    while (byte & 0x80) {\n      position += 1;\n      byte = bytes[position];\n    }\n\n    position += 1;\n\n    /** @type {GitObject | undefined} */\n    let base;\n\n    if (typeNumber === OFS_DELTA) {\n      // The base is at a negative offset from this object, encoded in 7-bit groups, most\n      // significant first, with one added to every group but the last\n      byte = bytes[position];\n      position += 1;\n\n      let distance = byte & 0x7f;\n\n      while (byte & 0x80) {\n        byte = bytes[position];\n        position += 1;\n        distance = (distance + 1) * 128 + (byte & 0x7f);\n      }\n\n      base = await readPackedObject(pack, offset - distance, depth + 1);\n    } else if (typeNumber === REF_DELTA) {\n      const baseOid = toHex(bytes.subarray(position, position + OID_SIZE));\n\n      position += OID_SIZE;\n      // eslint-disable-next-line no-use-before-define\n      base = await readObjectAtDepth(baseOid, depth + 1);\n\n      if (!base) {\n        throw new Error(`Delta base not found: ${baseOid}`);\n      }\n    }\n\n    const data = await inflate(bytes.subarray(position));\n\n    if (base) {\n      return { type: base.type, content: applyDelta(base.content, data) };\n    }\n\n    const type = PACKED_OBJECT_TYPES[typeNumber];\n\n    if (!type) {\n      throw new Error(`Invalid packed object type: ${typeNumber}`);\n    }\n\n    return { type, content: data };\n  };\n\n  /**\n   * Read an object, loose or packed.\n   * @param {string} oid Object ID.\n   * @param {number} depth How many deltas deep the object is.\n   * @returns {Promise<GitObject | undefined>} Object, or `undefined` if it doesn’t exist.\n   */\n  const readObjectAtDepth = async (oid, depth) => {\n    const looseObject = await readLooseObject(oid);\n\n    if (looseObject) {\n      return looseObject;\n    }\n\n    const found = await findInPacks(oid);\n\n    return found ? readPackedObject(found.pack, found.offset, depth) : undefined;\n  };\n\n  return {\n    /**\n     * Read an object, loose or packed.\n     * @param {string} oid Object ID.\n     * @returns {Promise<GitObject | undefined>} Object, or `undefined` if it doesn’t exist.\n     */\n    readObject: (oid) => readObjectAtDepth(oid, 0),\n  };\n};\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\n\nimport { GITLINK_MODE, OID_SIZE, TREE_MODE } from '$lib/services/backends/fs/git/constants';\nimport { hashObject } from '$lib/services/backends/fs/git/objects';\nimport { compareBytes, concatBytes, textDecoder, textEncoder } from '$lib/services/utils/bytes';\nimport { fromHex, toHex } from '$lib/services/utils/crypto';\n\n/**\n * @import { GitIndexEntry, GitTreeDirectory, GitTreeEntry, GitTreeNode } from '$lib/types/private';\n */\n\n/**\n * Sort tree entries in the order Git requires: by the UTF-8 bytes of the name, where the name of a\n * subtree is compared as if it ended with a slash.\n * @param {GitTreeEntry[]} entries Entries.\n * @returns {GitTreeEntry[]} Sorted entries.\n */\nconst sortTreeEntries = (entries) => {\n  const keys = new Map(\n    entries.map((entry) => [\n      entry,\n      textEncoder.encode(entry.type === 'tree' ? `${entry.path}/` : entry.path),\n    ]),\n  );\n\n  return entries.toSorted((a, b) =>\n    compareBytes(/** @type {Uint8Array} */ (keys.get(a)), /** @type {Uint8Array} */ (keys.get(b))),\n  );\n};\n\n/**\n * Serialize tree entries into the content of a tree object.\n * @param {GitTreeEntry[]} entries Entries, in Git’s order.\n * @returns {Uint8Array} Content.\n * @see https://git-scm.com/book/en/v2/Git-Internals-Git-Objects#_tree_objects\n */\nexport const serializeTree = (entries) =>\n  concatBytes(\n    entries.flatMap(({ mode, path, oid }) => [\n      textEncoder.encode(`${mode} ${path}\\0`),\n      fromHex(oid),\n    ]),\n  );\n\n/**\n * Parse the content of a tree object.\n * @param {Uint8Array} content Content.\n * @returns {Map<string, { mode: string, oid: string }>} Entries, keyed by name.\n */\nexport const parseTree = (content) => {\n  /** @type {Map<string, { mode: string, oid: string }>} */\n  const entries = new Map();\n  let position = 0;\n\n  while (position < content.length) {\n    const spaceIndex = content.indexOf(0x20, position);\n    const nullIndex = content.indexOf(0, spaceIndex);\n\n    entries.set(textDecoder.decode(content.subarray(spaceIndex + 1, nullIndex)), {\n      mode: textDecoder.decode(content.subarray(position, spaceIndex)),\n      oid: toHex(content.subarray(nullIndex + 1, nullIndex + 1 + OID_SIZE)),\n    });\n\n    position = nullIndex + 1 + OID_SIZE;\n  }\n\n  return entries;\n};\n\n/**\n * Get the tree object ID a commit points to.\n * @param {Uint8Array} content Content of the commit object.\n * @returns {string | undefined} Object ID.\n */\nexport const getCommitTree = (content) =>\n  /^tree ([0-9a-f]{40})\\n/.exec(textDecoder.decode(content))?.[1];\n\n/**\n * Get the paths of the directories a file is in, from the root, which is an empty string.\n * @param {string} path File path.\n * @returns {string[]} Directory paths, e.g. `['', 'content', 'content/posts']` for\n * `content/posts/a.md`.\n */\nconst getAncestorDirs = (path) => {\n  const segments = path.split('/').slice(0, -1);\n\n  return ['', ...segments.map((_, index) => segments.slice(0, index + 1).join('/'))];\n};\n\n/**\n * Build the trees that the entries of an index make up, the way `git write-tree` does, and\n * calculate their object IDs, without writing anything. Hashing every directory is the costly part\n * in a large repository, so the trees of a previous build can be reused for the directories that\n * haven’t changed since.\n * @param {GitIndexEntry[]} indexEntries Index entries, all at stage 0.\n * @param {object} [options] Options.\n * @param {GitTreeNode} [options.previous] Tree built from the index before the given paths\n * changed.\n * @param {string[]} [options.changedPaths] Paths of the files added, updated or removed since. The\n * directories they’re in are built again, and the other directories are taken from `previous`.\n * @param {Map<string, string>} [options.cacheTree] Object IDs of the trees Git has cached in the\n * index the entries come from, keyed by directory path. A directory with one isn’t hashed again.\n * @returns {Promise<GitTreeNode>} Root tree.\n */\nexport const buildTree = async (indexEntries, { previous, changedPaths = [], cacheTree } = {}) => {\n  const changedDirs = new Set(changedPaths.flatMap(getAncestorDirs));\n  /** @type {GitTreeDirectory} */\n  const root = { files: [], dirs: new Map() };\n\n  indexEntries.forEach(({ path, mode, oid }) => {\n    const segments = path.split('/');\n    const name = /** @type {string} */ (segments.pop());\n    let dir = root;\n\n    segments.forEach((segment) => {\n      let subdir = dir.dirs.get(segment);\n\n      if (!subdir) {\n        subdir = { files: [], dirs: new Map() };\n        dir.dirs.set(segment, subdir);\n      }\n\n      dir = subdir;\n    });\n\n    dir.files.push({\n      mode: mode.toString(8),\n      path: name,\n      oid,\n      type: mode === GITLINK_MODE ? 'commit' : 'blob',\n    });\n  });\n\n  /**\n   * Build the tree for a directory, or reuse the previous one if the directory hasn’t changed.\n   * @param {GitTreeDirectory} dir Directory.\n   * @param {string} dirPath Directory path, or an empty string for the root.\n   * @param {GitTreeNode | undefined} previousTree Previous tree of the directory, if any.\n   * @returns {Promise<GitTreeNode>} Tree.\n   */\n  const build = async ({ files, dirs }, dirPath, previousTree) => {\n    if (previousTree && !changedDirs.has(dirPath)) {\n      return previousTree;\n    }\n\n    // The subtrees are hashed concurrently, as hashing is asynchronous\n    /** @type {Map<string, GitTreeNode>} */\n    const subtrees = new Map(\n      await Promise.all(\n        [...dirs].map(\n          async ([name, subdir]) =>\n            /** @type {[string, GitTreeNode]} */ ([\n              name,\n              await build(\n                subdir,\n                dirPath ? `${dirPath}/${name}` : name,\n                previousTree?.subtrees.get(name),\n              ),\n            ]),\n        ),\n      ),\n    );\n\n    const entries = sortTreeEntries([\n      ...files,\n      ...[...subtrees].map(([name, { oid }]) => ({\n        mode: TREE_MODE,\n        path: name,\n        oid,\n        type: /** @type {const} */ ('tree'),\n      })),\n    ]);\n\n    const oid = cacheTree?.get(dirPath) ?? (await hashObject('tree', serializeTree(entries)));\n\n    return { oid, entries, subtrees };\n  };\n\n  return build(root, '', previous);\n};\n\n/**\n * Write the trees that don’t exist in the repository yet. A tree is compared with the one at the\n * same path in the current commit, and only a tree that differs is written, along with the\n * subtrees that differ in turn, so a commit only writes the trees on the paths to the changed\n * files, like Git does. The trees of the current commit are read one by one, so a pack file is\n * never loaded as a whole.\n * @param {GitTreeNode} tree Tree to write.\n * @param {string | undefined} baseOid ID of the tree at the same path in the current commit, if\n * any.\n * @param {object} context Context.\n * @param {(oid: string) => Promise<{ type: string, content: Uint8Array } | undefined>}\n * context.readObject Function to read an object.\n * @param {(entries: GitTreeEntry[]) => Promise<string>} context.writeTree Function to write a tree\n * object, which returns its ID.\n * @throws {Error} If a written tree doesn’t have the expected ID, which would mean the commit\n * doesn’t have the content of the index.\n */\nexport const writeChangedTrees = async (tree, baseOid, { readObject, writeTree }) => {\n  if (tree.oid === baseOid) {\n    return;\n  }\n\n  const baseObject = baseOid ? await readObject(baseOid) : undefined;\n  const baseEntries = baseObject?.type === 'tree' ? parseTree(baseObject.content) : new Map();\n\n  for (const [name, subtree] of tree.subtrees) {\n    const baseEntry = baseEntries.get(name);\n\n    await writeChangedTrees(subtree, baseEntry?.mode === TREE_MODE ? baseEntry.oid : undefined, {\n      readObject,\n      writeTree,\n    });\n  }\n\n  const oid = await writeTree(tree.entries);\n\n  if (oid !== tree.oid) {\n    throw new Error(`Tree object ID mismatch: expected ${tree.oid}, got ${oid}`);\n  }\n};\n","import { getHash } from '@sveltia/utils/crypto';\n\nimport { loadChunk } from '$lib/services/app/dependencies';\nimport {\n  DIR,\n  INDEX_LOCK_PATH,\n  OID_SIZE,\n  OPERATION_MARKERS,\n} from '$lib/services/backends/fs/git/constants';\nimport { createGitFileSystem, exists } from '$lib/services/backends/fs/git/file-system';\nimport { hasRequiredExtension, parseIndex } from '$lib/services/backends/fs/git/index-file';\nimport { createObjectReader } from '$lib/services/backends/fs/git/objects';\nimport { buildTree, getCommitTree } from '$lib/services/backends/fs/git/tree';\nimport { isTypeMismatchError, readFileIfExists } from '$lib/services/backends/fs/shared/handles';\nimport { toHex } from '$lib/services/utils/crypto';\n\n/**\n * @import {\n * GitFileSystem,\n * GitIndex,\n * GitTreeNode,\n * LocalGitInspection,\n * LocalGitOperation,\n * } from '$lib/types/private';\n */\n\n/**\n * Index as of the last save, parsed, along with the tree built from it and the checksum the index\n * file ends with. Parsing the index and hashing every directory are the costly parts of a save in\n * a large repository, so they’re reused as long as the index hasn’t changed, e.g. between two saves\n * without any Git command in between. Both only depend on the index content, so they’re right for\n * any repository.\n * @type {{ checksum: string, index: GitIndex, tree?: GitTreeNode } | undefined}\n */\nlet indexCache;\n\n/**\n * Forget the cached index and tree, e.g. once the user has signed out, so the memory they take in a\n * large repository is freed.\n */\nexport const clearLocalGitCache = () => {\n  indexCache = undefined;\n};\n\n/**\n * Cache an index along with its tree, e.g. once the CMS has written it.\n * @param {{ checksum: string, index: GitIndex, tree: GitTreeNode }} cache Checksum of the index\n * file, parsed index and tree.\n */\nexport const setIndexCache = (cache) => {\n  indexCache = cache;\n};\n\n/**\n * Get the checksum an index file ends with: the SHA-1 hash of the rest of the file. Git writes\n * zeros instead with the `index.skipHash` option, which `feature.manyFiles` also turns on, to save\n * the time hashing a large index takes; every such index would then have the same checksum, and\n * one cached under it would be taken for any other, so the hash is computed as Git would have.\n * @param {Uint8Array} bytes Content of the index file.\n * @returns {Promise<string>} Checksum.\n * @see https://git-scm.com/docs/git-config#Documentation/git-config.txt-indexskipHash\n */\nexport const getIndexChecksum = async (bytes) => {\n  const checksum = bytes.subarray(-OID_SIZE);\n\n  return checksum.some((byte) => byte !== 0)\n    ? toHex(checksum)\n    : getHash(bytes.subarray(0, -OID_SIZE));\n};\n\n/**\n * Get the commit a branch points to.\n * @param {any} git Isomorphic-git module.\n * @param {GitFileSystem} fs File system.\n * @param {string} branch Full name of the branch.\n * @returns {Promise<string | undefined>} Object ID of the commit, or `undefined` if the branch has\n * no commits yet.\n * @throws {Error} If the branch couldn’t be read.\n */\nexport const resolveBranchHead = async (git, fs, branch) => {\n  try {\n    return await git.resolveRef({ fs, dir: DIR, ref: branch });\n  } catch (ex) {\n    if (/** @type {any} */ (ex)?.code === 'NotFoundError') {\n      return undefined;\n    }\n\n    throw ex;\n  }\n};\n\n/**\n * Build the tree of an index, reusing the cached one if the index hasn’t changed, and cache it.\n * @param {GitIndex} index Index.\n * @param {string} checksum Checksum of the index file.\n * @returns {Promise<GitTreeNode>} Tree.\n */\nconst getIndexTree = async (index, checksum) => {\n  if (indexCache?.checksum === checksum && indexCache.tree) {\n    return indexCache.tree;\n  }\n\n  // The trees Git has cached in an index it wrote don’t have to be hashed again\n  const tree = await buildTree(index.entries, { cacheTree: index.cacheTree });\n\n  indexCache = { checksum, index, tree };\n\n  return tree;\n};\n\n/**\n * Read the index of a repository, reusing the cached parsed index if it hasn’t changed.\n * @param {FileSystemDirectoryHandle} gitDirHandle Handle of the `.git` directory.\n * @returns {Promise<{ index: GitIndex, buffer?: ArrayBuffer, checksum: string }>} Parsed index,\n * which is empty if the repository doesn’t have one yet, the content of the file, if any, and its\n * checksum, which is an empty string without a file.\n * @throws {Error} If the file exists but can’t be read.\n */\nconst readIndex = async (gitDirHandle) => {\n  const buffer = await (await readFileIfExists(gitDirHandle, 'index'))?.arrayBuffer();\n  const checksum = buffer ? await getIndexChecksum(new Uint8Array(buffer)) : '';\n\n  if (indexCache?.checksum === checksum) {\n    return { index: indexCache.index, buffer, checksum };\n  }\n\n  /** @type {GitIndex} */\n  const index = buffer ? parseIndex(buffer) : { version: 2, entries: [], extensions: [] };\n\n  // The index is only cached along with its tree, once it’s known to be one the CMS can work with\n  return { index, buffer, checksum };\n};\n\n/**\n * Tell which operation a marker in `.git` is for, where it can be more than one.\n * @param {GitFileSystem} fs File system.\n * @param {string} marker Marker found.\n * @param {LocalGitOperation} operation Operation the marker usually stands for.\n * @returns {Promise<LocalGitOperation>} Operation.\n */\nconst identifyOperation = async (fs, marker, operation) => {\n  // `git am` uses the same directory as the apply backend of `git rebase`, and marks it\n  if (marker === 'rebase-apply' && (await exists(fs, '.git/rebase-apply/applying'))) {\n    return 'am';\n  }\n\n  // A cherry-pick or revert of several commits leaves the rest of its list here once a conflict has\n  // been resolved and committed, until the user continues it\n  if (marker === 'sequencer' && (await exists(fs, '.git/sequencer/todo'))) {\n    const todo = /** @type {string} */ (\n      await fs.readFile('.git/sequencer/todo', { encoding: 'utf8' })\n    );\n\n    return todo.trimStart().startsWith('revert') ? 'revert' : 'cherry_pick';\n  }\n\n  return operation;\n};\n\n/**\n * Check whether a configuration value is true the way Git reads a boolean: `true`, `yes`, `on` and\n * a number other than zero are true, in any case, as is an option without a value, which the\n * isomorphic-git library reads as `true`.\n * @param {any} value Value.\n * @returns {boolean} Whether the value is true.\n * @see https://git-scm.com/docs/git-config#Documentation/git-config.txt-boolean\n */\nconst isTrueConfigValue = (value) =>\n  value === true || /^(?:true|yes|on|[+-]?0*[1-9]\\d*)$/i.test(String(value).trim());\n\n/**\n * Read a boolean option from the repository’s configuration the way Git does: `true`, `yes`, `on`\n * and a number other than zero are true, in any case, and an option that isn’t set is false.\n * The isomorphic-git library converts the value of a few options, such as `core.ignorecase`, to a\n * boolean, but throws on a number or an empty value, which Git never writes itself; such a value is\n * read as false.\n * @param {any} git Isomorphic-git module.\n * @param {GitFileSystem} fs File system.\n * @param {string} path Name of the option.\n * @returns {Promise<boolean>} Value.\n * @see https://git-scm.com/docs/git-config#Documentation/git-config.txt-boolean\n */\nconst getBooleanConfig = async (git, fs, path) => {\n  try {\n    const value = await git.getConfig({ fs, dir: DIR, path });\n\n    return isTrueConfigValue(value);\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Check whether the CMS can commit to a repository on the user’s computer right now, and gather\n * what it needs to do so. It can if it understands the repository’s format, knows who the author\n * is, and the index, the files staged for the next commit, matches the current commit: a commit\n * includes everything in the index, so anything the user has staged themselves would end up in the\n * CMS’s commit. Changes that aren’t staged don’t matter, as the CMS only stages the files it saves.\n * @param {FileSystemDirectoryHandle} repoRootDirHandle Handle of the repository’s root directory.\n * @param {object} [options] Options.\n * @param {(fs: GitFileSystem) => void} [options.onLock] Function to call once the index has been\n * locked. If given, the index is locked as soon as it’s known not to be, so the rest of the\n * inspection and anything after it see an index no other Git process can change. The caller has to\n * remove the lock.\n * @returns {Promise<LocalGitInspection>} Result.\n */\nexport const inspectRepository = async (repoRootDirHandle, { onLock } = {}) => {\n  /** @type {FileSystemDirectoryHandle} */\n  let gitDirHandle;\n\n  try {\n    gitDirHandle = await repoRootDirHandle.getDirectoryHandle('.git');\n  } catch (ex) {\n    // `.git` is a file in a linked worktree or a submodule, pointing to a directory elsewhere, out\n    // of reach of the browser\n    if (isTypeMismatchError(ex)) {\n      return { ready: false, reason: 'unsupported_repository' };\n    }\n\n    throw ex;\n  }\n\n  const git = await loadChunk('git');\n  const fs = createGitFileSystem(repoRootDirHandle, { Buffer: git.Buffer });\n\n  // isomorphic-git only reads the repository’s own configuration, not the user’s global one\n  const [[objectFormat, refStorage, name, email, autocrlf], ignoreCase] = await Promise.all([\n    Promise.all(\n      [\n        'extensions.objectformat',\n        'extensions.refstorage',\n        'user.name',\n        'user.email',\n        'core.autocrlf',\n      ].map((path) => git.getConfig({ fs, dir: DIR, path })),\n    ),\n    getBooleanConfig(git, fs, 'core.ignorecase'),\n  ]);\n\n  if ((objectFormat && objectFormat !== 'sha1') || (refStorage && refStorage !== 'files')) {\n    return { ready: false, reason: 'unsupported_repository' };\n  }\n\n  if (!name || !email) {\n    return { ready: false, reason: 'missing_identity' };\n  }\n\n  const author = { name, email };\n\n  if (await exists(fs, INDEX_LOCK_PATH)) {\n    return { ready: false, reason: 'locked', author };\n  }\n\n  if (onLock) {\n    await fs.writeFile(INDEX_LOCK_PATH, '');\n    onLock(fs);\n  }\n\n  const markers = await Promise.all(\n    OPERATION_MARKERS.map(([marker]) => exists(fs, `.git/${marker}`)),\n  );\n\n  const foundMarker = OPERATION_MARKERS.find((_, index) => markers[index]);\n\n  if (foundMarker) {\n    return {\n      ready: false,\n      reason: 'operation_in_progress',\n      detail: await identifyOperation(fs, ...foundMarker),\n      author,\n    };\n  }\n\n  /** @type {string | undefined} */\n  const branch = await git.currentBranch({ fs, dir: DIR, fullname: true });\n\n  if (!branch) {\n    return { ready: false, reason: 'detached_head', author };\n  }\n\n  const { index, buffer: indexBuffer, checksum: indexChecksum } = await readIndex(gitDirHandle);\n\n  if (index.version !== 2 || hasRequiredExtension(index)) {\n    return { ready: false, reason: 'unsupported_repository', author, branch };\n  }\n\n  // A file with a conflict has an entry for each side of the merge\n  if (index.entries.some(({ stage }) => stage)) {\n    return {\n      ready: false,\n      reason: 'operation_in_progress',\n      detail: 'conflict',\n      author,\n      branch,\n    };\n  }\n\n  const reader = createObjectReader(gitDirHandle);\n  const headOid = await resolveBranchHead(git, fs, branch);\n  /** @type {string | undefined} */\n  let headTreeOid;\n\n  if (headOid) {\n    const commit = await reader.readObject(headOid);\n\n    headTreeOid = commit?.type === 'commit' ? getCommitTree(commit.content) : undefined;\n\n    // The commit may be in another repository whose objects this one borrows, or not downloaded\n    // yet in a partial clone\n    if (!headTreeOid) {\n      return { ready: false, reason: 'unsupported_repository', author, branch };\n    }\n  }\n\n  const indexTree = await getIndexTree(index, indexChecksum);\n\n  if (headTreeOid ? indexTree.oid !== headTreeOid : index.entries.length > 0) {\n    return { ready: false, reason: 'staged_changes', author, branch };\n  }\n\n  return {\n    ready: true,\n    author,\n    branch,\n    repository: {\n      git,\n      fs,\n      gitDirHandle,\n      reader,\n      branch,\n      author,\n      headOid,\n      headTreeOid,\n      index,\n      indexBuffer,\n      indexTree,\n      // Git converts the line endings when adding a file with `input` as well as a true value\n      autocrlf: /^input$/i.test(String(autocrlf).trim()) || isTrueConfigValue(autocrlf),\n      // Git matches the patterns in `.gitattributes` case-insensitively with the option, which it\n      // sets when the repository is cloned or created on a case-insensitive file system\n      ignoreCase,\n    },\n  };\n};\n","/**\n * Maximum number of API requests to have in flight at the same time. GitHub’s secondary rate limit\n * rejects more than 100 concurrent requests, and other services throttle bursts as well, so keep\n * well below that. Anything under this number is unaffected, because the whole list starts at once.\n * @see https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits\n */\nexport const MAX_CONCURRENT_REQUESTS = 10;\n\n/**\n * Run the given task for each item, keeping at most a certain number of them in flight, so a long\n * list doesn’t trigger a Too Many Requests error. Unlike a chunked loop, a worker picks up the next\n * item as soon as it’s free, so one slow task doesn’t stall the others.\n * @template T\n * @param {T[]} items Items to process.\n * @param {(item: T) => Promise<void>} task Task to be performed for each item.\n * @param {object} [options] Options.\n * @param {number} [options.concurrency] Maximum number of tasks in flight. Defaults to\n * {@link MAX_CONCURRENT_REQUESTS}; a lower number suits requests that are heavy on the server.\n */\nexport const runConcurrently = async (\n  items,\n  task,\n  { concurrency = MAX_CONCURRENT_REQUESTS } = {},\n) => {\n  let cursor = 0;\n\n  /**\n   * Take items off the list until it’s exhausted.\n   */\n  const work = async () => {\n    while (cursor < items.length) {\n      const item = items[cursor];\n\n      cursor += 1;\n      // eslint-disable-next-line no-await-in-loop\n      await task(item);\n    }\n  };\n\n  await Promise.all(\n    Array(Math.min(concurrency, items.length))\n      .fill(undefined)\n      .map(() => work()),\n  );\n};\n\n/**\n * Run the given task for each item with {@link runConcurrently}, and collect the results.\n * @template T, R\n * @param {T[]} items Items to process.\n * @param {(item: T) => Promise<R>} task Task to be performed for each item.\n * @param {object} [options] Options.\n * @param {number} [options.concurrency] Maximum number of tasks in flight. Defaults to\n * {@link MAX_CONCURRENT_REQUESTS}.\n * @returns {Promise<R[]>} Results, in the same order as the given items.\n */\nexport const mapConcurrently = async (items, task, options) => {\n  /** @type {R[]} */\n  const results = Array(items.length);\n\n  // Store the results by index so they come out in the same order as the items\n  await runConcurrently(\n    [...items.keys()],\n    async (index) => {\n      results[index] = await task(items[index]);\n    },\n    options,\n  );\n\n  return results;\n};\n","import { _ } from '@sveltia/i18n';\n\n/**\n * @import { RepositoryPath } from '$lib/types/private';\n */\n\n/**\n * Message of the error thrown when the signed-in user doesn’t have access to the repository. The\n * sign-in flow checks for it to clear the cached credentials, so it has to stay the same across all\n * backends.\n */\nexport const NOT_COLLABORATOR_ERROR_MESSAGE = 'Not a collaborator of the repository';\n\n/**\n * Error whose message is localized, to be shown to the user as is. It’s the `cause` of an error\n * created with {@link createLocalizedError}, which tells it apart from the `cause` of an API error:\n * a plain object with the response status and the server’s own message, in English.\n */\nclass LocalizedError extends Error {}\n\n/**\n * Create an error whose message is meant for developers and whose cause carries a localized message\n * to be shown to the user.\n * @param {string} message Error message in English.\n * @param {string} key Localized string key for the cause.\n * @param {Record<string, any>} [values] Values to be interpolated into the localized string.\n * @returns {Error} Error.\n */\nexport const createLocalizedError = (message, key, values) =>\n  new Error(message, { cause: new LocalizedError(values ? _(key, { values }) : _(key)) });\n\n/**\n * Get the message to show the user when something has failed. An error created with\n * {@link createLocalizedError} says what went wrong, which may be something trying again wouldn’t\n * change. An API error’s own message isn’t meant for the user, so any other error gets the generic\n * message given.\n * @param {any} ex Error.\n * @param {string} fallback I18n key of the message for any other error.\n * @returns {string} Localized message.\n */\nexport const getErrorMessage = (ex, fallback) =>\n  (ex?.cause instanceof LocalizedError && ex.cause.message) || _(fallback);\n\n/**\n * Create the error to throw when the signed-in user can’t see the configured repository, or their\n * token can’t be used to read it. It carries the shared message, which the sign-in flow looks for\n * to drop the cached credentials, so the user gets the sign-in form rather than the same error on\n * every reload.\n * @param {string} repo Repository name.\n * @returns {Error} Error to throw.\n */\nexport const createNoAccessError = (repo) =>\n  createLocalizedError(NOT_COLLABORATOR_ERROR_MESSAGE, 'repository_no_access', { repo });\n\n/**\n * Create the error to throw when the signed-in user can read the configured repository but can’t\n * push to it, e.g. a collaborator with the read or triage role on GitHub, or the Reporter role on\n * GitLab. It carries the shared message, so the sign-in flow drops the cached credentials just like\n * it does when the user has no access at all, but tells the user it’s write access that’s missing.\n * @param {string} repo Repository name.\n * @returns {Error} Error to throw.\n */\nexport const createNoWriteAccessError = (repo) =>\n  createLocalizedError(NOT_COLLABORATOR_ERROR_MESSAGE, 'repository_no_write_access', { repo });\n\n/**\n * Create the error to throw when the signed-in user can’t push to the configured repository: one\n * saying write access is missing if they can at least read it, or one saying there is no access at\n * all otherwise. See {@link createNoWriteAccessError} and {@link createNoAccessError}.\n * @param {string} repo Repository name.\n * @param {boolean} [canRead] Whether the user can read the repository.\n * @returns {Error} Error to throw.\n */\nexport const createPermissionError = (repo, canRead) =>\n  canRead ? createNoWriteAccessError(repo) : createNoAccessError(repo);\n\n/**\n * Create the error to throw when the configured repository couldn’t be read while checking the\n * signed-in user’s access to it. A refusal means the user has no access, and the shared message is\n * what the sign-in flow looks for to drop the cached credentials, so the user gets the sign-in form\n * rather than the same error on every reload. Anything else, like a rate limit, an outage or a\n * network error, leaves the question unanswered. Reading that as “no access” would clear the\n * credentials and sign the user out over something passing, so it’s reported as a failed check.\n * @param {RepositoryPath} repository Configured repository.\n * @param {number | undefined} status HTTP status the request was refused with. `undefined` for a\n * request that wasn’t answered, or one whose status doesn’t tell, like a rate limit answered with a\n * 403.\n * @returns {Error} Error.\n */\nexport const toRepositoryAccessError = ({ owner, repo }, status) => {\n  // A 401 means the token has expired or been revoked, and a 403 that it lacks the scope. A private\n  // repository answers someone without access with a 404, so its existence isn’t leaked; a mistyped\n  // name can’t be told apart from that, but the message names the repository it looked for\n  if (status === 401 || status === 403 || status === 404) {\n    return createNoAccessError(repo);\n  }\n\n  return createLocalizedError(\n    'Failed to check the repository permission.',\n    'open_authoring.permission_check_failed',\n    { repo: `${owner}/${repo}` },\n  );\n};\n","/**\n * Local storage key of the signed-in user.\n */\nexport const USER_STORAGE_KEY = 'sveltia-cms.user';\n\n/**\n * Local storage keys of the signed-in user written by Netlify/Decap CMS. The CMS reads these for\n * backward compatibility, so they have to be removed along with its own key.\n * @type {string[]}\n */\nexport const LEGACY_USER_STORAGE_KEYS = ['decap-cms-user', 'netlify-cms-user'];\n","import { LocalStorage } from '@sveltia/utils/storage';\n\nimport { USER_STORAGE_KEY } from '$lib/services/user/constants';\n\n/**\n * @import { User } from '$lib/types/private';\n */\n\n/**\n * @type {{ account: User | null | undefined }}\n */\nexport const user = $state({ account: undefined });\n\n$effect.root(() => {\n  $effect(() => {\n    const _user = user.account;\n\n    (async () => {\n      try {\n        if (_user) {\n          await LocalStorage.set(USER_STORAGE_KEY, _user);\n        } else if (_user === null) {\n          await LocalStorage.delete(USER_STORAGE_KEY);\n        }\n      } catch {\n        //\n      }\n    })();\n  });\n});\n","import {\n  createDerivedState,\n  createRawState,\n  requestAnswer,\n} from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * ForkPermissionRequest,\n * RepositoryInfo,\n * RepositoryPath,\n * } from '$lib/types/private';\n */\n\n/**\n * The signed-in user’s fork of the configured repository, which holds the branches their changes\n * are committed to. It’s `undefined` unless the current session is an Open Authoring one.\n * @type {{ current: RepositoryPath | undefined }}\n */\nexport const forkedRepository = createRawState();\n\n/**\n * Whether the signed-in user is contributing through a forked repository. Such a user can’t write\n * to the configured repository, so every change goes to their fork and reaches the site through a\n * pull request that a maintainer merges.\n */\nexport const openAuthoring = createDerivedState(() => !!forkedRepository.current);\n\n/**\n * Whether the Open Authoring set-up has completed for the current session, so that it’s known\n * whether the user works on a fork or, having write access, on the configured repository itself.\n * Anything that depends on that — such as where to look for the user’s pull requests — has to wait\n * for this rather than for a fork, which a maintainer never gets.\n * @type {{ current: boolean }}\n */\nexport const openAuthoringInitialized = createRawState(false);\n\n/**\n * Message of the error thrown when an Open Authoring contributor moves an entry whose request a\n * maintainer has merged since the board was loaded, with nothing committed to its branch since: the\n * entry is published, and there’s nothing left to review.\n */\nexport const ENTRY_ALREADY_PUBLISHED = 'entry_already_published';\n\n/**\n * Check whether the given error says that an entry turned out to have been published when its\n * status was changed.\n * @param {any} ex Error thrown by the status change.\n * @returns {boolean} Result.\n */\nexport const isEntryAlreadyPublished = (ex) => ex?.message === ENTRY_ALREADY_PUBLISHED;\n\n/**\n * Get the path of the signed-in user’s fork, e.g. `contributor/site`, which is what the UI names\n * when it says where their changes are saved.\n * @param {RepositoryPath | undefined} fork Fork, from {@link forkedRepository}.\n * @returns {string} Path, or an empty string when the session isn’t an Open Authoring one.\n */\nexport const getForkPath = (fork) => (fork ? `${fork.owner}/${fork.repo}` : '');\n\n/**\n * Get the URL of the signed-in user’s fork on the backend service, which can be a GitHub Enterprise\n * Server or self-hosted GitLab instance rather than github.com or gitlab.com. The configured\n * repository’s URL ends with its path, which the fork’s path takes the place of. Resolving the fork\n * against the origin instead would drop a path prefix the instance itself sits under — what GitLab\n * calls a relative URL root — and a GitLab fork lands directly under the contributor’s namespace,\n * so the configured path can’t be swapped segment by segment either.\n * @param {RepositoryInfo | undefined} repository Configured repository.\n * @param {RepositoryPath | undefined} fork Fork, from {@link forkedRepository}.\n * @returns {string} URL, or an empty string while the repository isn’t known yet, or when the\n * session isn’t an Open Authoring one.\n */\nexport const getForkURL = (repository, fork) => {\n  const { repoURL, owner, repo } = repository ?? {};\n\n  if (!fork || !repoURL) {\n    return '';\n  }\n\n  return repoURL.slice(0, -`${owner}/${repo}`.length) + getForkPath(fork);\n};\n\n/**\n * The pending request for permission to fork the configured repository, which the UI turns into a\n * confirmation dialog. It’s `undefined` while no request is outstanding.\n * @type {{ current: ForkPermissionRequest | undefined }}\n */\nexport const forkPermissionRequest = createRawState();\n\n/**\n * Ask the user for permission to create a fork of the configured repository, and wait for the\n * answer. Creating a repository on someone’s account is not something to do behind their back, so\n * the sign-in stops here until they decide.\n * @param {string} repo Repository path to be forked, e.g. `owner/repo`.\n * @returns {Promise<boolean>} `true` if the user granted permission.\n */\nexport const requestForkPermission = async (repo) =>\n  // A second request can’t be outstanding, because the sign-in flow awaits the first one, but an\n  // earlier one is answered just in case\n  requestAnswer(forkPermissionRequest, { repo }, false);\n","import { mapConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { cmsConfig } from '$lib/services/config';\nimport { getCollectionLabel } from '$lib/services/contents/collection';\nimport { user } from '$lib/services/user/account.svelte';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { CommitOptions, FileChange, FileCommit, User } from '$lib/types/private';\n * @import { GitBackend } from '$lib/types/public';\n */\n\n/**\n * Default commit message templates.\n * @see https://decapcms.org/docs/configuration-options/#commit-message-templates\n * @see https://sveltiacms.app/en/docs/backends#commit-messages\n */\nconst DEFAULT_COMMIT_MESSAGES = {\n  create: 'Create {{collection}} “{{slug}}”',\n  update: 'Update {{collection}} “{{slug}}”',\n  delete: 'Delete {{collection}} “{{slug}}”',\n  uploadMedia: 'Upload “{{path}}”',\n  deleteMedia: 'Delete “{{path}}”',\n  openAuthoring: '{{message}}',\n};\n\n/**\n * Markers that tell a CI/CD provider not to build a commit. GitHub Actions and Gitea Actions honour\n * `[skip ci]`, `[ci skip]`, `[no ci]`, `[skip actions]` and `[actions skip]`, GitLab CI honours\n * `[skip ci]` and `[ci skip]`, and Cloudflare Pages accepts the same words hyphenated as well as\n * `[cf-pages-skip]`. They all match case-insensitively anywhere in the message, so this does too:\n * the marker is written as a prefix here, but a commit made elsewhere can carry it in the body.\n * @see https://docs.github.com/en/actions/managing-workflow-runs/skipping-workflow-runs\n * @see https://docs.gitlab.com/ee/ci/pipelines/#skip-a-pipeline\n * @see https://developers.cloudflare.com/pages/platform/branch-build-controls/#skip-builds\n */\nconst SKIP_CI_REGEX =\n  /\\[(?:skip[ -](?:ci|actions)|(?:ci|actions)[ -]skip|no[ -]ci|cf-pages-skip)\\]/i;\n\n/**\n * Check if a commit message carries a marker that keeps the connected CI/CD provider from building\n * the commit. It says what the author asked for, not what the provider did: a repository with no CI\n * at all never builds an unmarked commit either.\n * @param {string} message Commit message.\n * @returns {boolean} Result.\n */\nexport const hasSkipCIMarker = (message) => SKIP_CI_REGEX.test(message);\n\n/**\n * Replace the `{{name}}` placeholders in the given commit message template with the given values,\n * in a single pass. The values are inserted as they are: `$&` and the like aren’t read as\n * replacement patterns, and a placeholder that happens to appear in a value, e.g. in a slug, isn’t\n * expanded. A placeholder without a value is left as it is.\n * @param {string} template Template.\n * @param {Record<string, string>} values Values keyed by placeholder name.\n * @returns {string} Filled message.\n */\nconst fillTemplate = (template, values) =>\n  template.replace(/\\{\\{([\\w-]+)\\}\\}/g, (placeholder, key) =>\n    Object.hasOwn(values, key) ? values[key] : placeholder,\n  );\n\n/**\n * Get the backend options of the current configuration.\n * @returns {GitBackend} Options, which are empty if there is no configuration.\n */\nconst getBackendOptions = () => /** @type {GitBackend} */ (cmsConfig.current?.backend ?? {});\n\n/**\n * Get the values of the author placeholders in a commit message template.\n * @returns {Record<string, string>} Values keyed by placeholder name.\n */\nconst getAuthorValues = () => {\n  const { email = '', login = '', name = '' } = /** @type {User} */ (user.account);\n\n  return { 'author-email': email, 'author-login': login, 'author-name': name };\n};\n\n/**\n * Create the part of a Git commit message that comes from the `commit_messages` template: the\n * template filled in, followed by the number of the other files changed, if any. It’s what the\n * user is shown when asked for a commit message.\n * @param {FileChange[]} changes File changes to be saved.\n * @param {CommitOptions} options Commit options.\n * @param {GitBackend} [backendOptions] Backend options. Default: those of the current\n * configuration.\n * @returns {string} Formatted message.\n */\nexport const createBaseCommitMessage = (\n  changes,\n  { commitType = 'update', collection },\n  backendOptions = getBackendOptions(),\n) => {\n  const { commit_messages: customCommitMessages = {} } = backendOptions;\n  const [firstSlug = ''] = changes.map((item) => item.slug).filter(Boolean);\n  const [firstPath, ...remainingPaths] = changes.map(({ path }) => path);\n  const collectionLabel = collection ? getCollectionLabel(collection, { useSingular: true }) : '';\n  // @ts-ignore\n  let message = customCommitMessages[commitType] || DEFAULT_COMMIT_MESSAGES[commitType] || '';\n  const authorValues = getAuthorValues();\n\n  if (['create', 'update', 'delete'].includes(commitType)) {\n    message = fillTemplate(message, {\n      slug: firstSlug,\n      collection: collectionLabel,\n      path: firstPath,\n      ...authorValues,\n    });\n  }\n\n  if (['uploadMedia', 'deleteMedia'].includes(commitType)) {\n    message = fillTemplate(message, { path: firstPath, ...authorValues });\n  }\n\n  if (remainingPaths.length) {\n    message += ` +${remainingPaths.length}`;\n  }\n\n  return message;\n};\n\n/**\n * Combine the message made from the template with the text the user has entered when asked for a\n * commit message, as the `prompt_commit_messages` backend option says.\n * @param {string} message Message made from the template.\n * @param {string | undefined} userMessage Text the user has entered.\n * @param {GitBackend['prompt_commit_messages']} mode Value of the `prompt_commit_messages` option.\n * @returns {string} Combined message.\n */\nconst applyUserMessage = (message, userMessage, mode) => {\n  const text = userMessage?.trim();\n\n  if (!text) {\n    return message;\n  }\n\n  if (mode === true) {\n    return text;\n  }\n\n  if (mode === 'prefix') {\n    return `${text} ${message}`;\n  }\n\n  if (mode === 'suffix') {\n    return `${message} ${text}`;\n  }\n\n  return message;\n};\n\n/**\n * Check whether a commit is expected to start a deployment, which is when its message goes without\n * the skip-CI marker added by {@link createCommitMessage}. The commit’s own `skipCI` option takes\n * precedence over the `skip_ci` and `automatic_deployments` backend options. To avoid unexpected\n * data retention, deletions are always deployed.\n * @param {Partial<CommitOptions>} options Commit options.\n * @returns {boolean} Result.\n */\nexport const isDeployingCommit = ({ commitType, skipCI }) => {\n  // Read the options rather than `skipCIEnabled`, whose module imports the backends using this one\n  const { skip_ci: skipCIEnabled, automatic_deployments: autoDeploy } = getBackendOptions();\n\n  return (\n    commitType === 'delete' ||\n    commitType === 'deleteMedia' ||\n    !(skipCI ?? (skipCIEnabled === true || autoDeploy === false))\n  );\n};\n\n/**\n * Create a Git commit message.\n * @param {FileChange[]} changes File changes to be saved.\n * @param {CommitOptions} options Commit options.\n * @returns {string} Formatted message.\n */\nexport const createCommitMessage = (changes, options) => {\n  const { userMessage } = options;\n  const backendOptions = getBackendOptions();\n\n  const { commit_messages: customCommitMessages = {}, prompt_commit_messages: promptMode } =\n    backendOptions;\n\n  let message = applyUserMessage(\n    createBaseCommitMessage(changes, options, backendOptions),\n    userMessage,\n    promptMode,\n  );\n\n  // With Open Authoring the commit is made by an outside contributor, so the message can be wrapped\n  // to record who wrote it. The default template is the message on its own, which changes nothing\n  if (openAuthoring.current) {\n    message = fillTemplate(\n      customCommitMessages.openAuthoring || DEFAULT_COMMIT_MESSAGES.openAuthoring,\n      { message, ...getAuthorValues() },\n    );\n  }\n\n  // If requested, disable automatic deployments by using the standard `[skip ci]` prefix supported\n  // by major CI/CD providers, including GitHub Actions and Cloudflare Pages\n  // https://docs.github.com/en/actions/managing-workflow-runs/skipping-workflow-runs\n  // https://docs.gitlab.com/ee/ci/pipelines/#skip-a-pipeline\n  // https://developers.cloudflare.com/pages/platform/branch-build-controls/#skip-builds\n  if (!isDeployingCommit(options)) {\n    message = `[skip ci] ${message}`;\n  }\n\n  return message;\n};\n\n/**\n * A Git trailer line: a token of letters, digits and hyphens, a colon and a value.\n * @see https://git-scm.com/docs/git-interpret-trailers\n */\nconst TRAILER_LINE_REGEX = /^[A-Za-z0-9-]+:\\s*\\S/;\n/**\n * Clean up a user profile value for a commit trailer. Line breaks and angle brackets would break\n * the trailer, though a Git host doesn’t allow them in a name or an email.\n * @param {string | null | undefined} value Value. A field the host leaves empty can be `null`.\n * @returns {string} Cleaned value.\n */\nconst cleanTrailerValue = (value) => (value ?? '').replace(/[\\s<>]+/g, ' ').trim();\n\n/**\n * Format a trailer that credits a person, e.g. `Co-authored-by: Name <email>`. Their name and email\n * are kept on the line, whatever they hold.\n * @param {string} token Trailer token, e.g. `Co-authored-by`.\n * @param {{ name: string, email: string }} person Person.\n * @returns {string} Trailer line.\n */\nexport const formatPersonTrailer = (token, { name, email }) =>\n  `${token}: ${cleanTrailerValue(name)} <${cleanTrailerValue(email)}>`;\n\n/**\n * Add a trailer line to a commit message. It joins the trailer block the message already ends with,\n * if any, and otherwise follows a blank line.\n * @param {string} message Commit message.\n * @param {string} trailer Trailer line, e.g. `Co-authored-by: Name <email>`.\n * @returns {string} Message with the trailer.\n */\nexport const addCommitTrailer = (message, trailer) => {\n  const text = message.trimEnd();\n  const paragraphs = text.split(/\\r?\\n\\s*\\r?\\n/);\n  const lastParagraph = /** @type {string} */ (paragraphs.at(-1));\n\n  const endsWithTrailers =\n    paragraphs.length > 1 &&\n    lastParagraph.split(/\\r?\\n/).every((line) => TRAILER_LINE_REGEX.test(line));\n\n  return `${text}${endsWithTrailers ? '\\n' : '\\n\\n'}${trailer}`;\n};\n\n/**\n * Signed-in user accounts that have been warned about their missing email, so the warning is only\n * shown once per sign-in rather than for every commit.\n * @type {WeakSet<User>}\n */\nconst accountsWarnedAboutEmail = new WeakSet();\n\n/**\n * Add a `Signed-off-by` trailer with the signed-in user’s name and email to the given commit\n * message, if the `signoff_commits` backend option is enabled. The trailer joins the trailer block\n * the message already ends with, if any, and otherwise follows a blank line. A message that already\n * carries a sign-off with the user’s email, e.g. from a custom `commit_messages` template, is left\n * as it is. When the Git host doesn’t share the user’s email, as GitHub does for a user without a\n * public email, the trailer is left out with a warning, shown once per sign-in.\n * @param {string} message Commit message.\n * @returns {string} Message, possibly with the trailer.\n * @see https://github.com/decaporg/decap-cms/pull/7766\n */\nexport const signOffCommitMessage = (message) => {\n  if (!getBackendOptions().signoff_commits) {\n    return message;\n  }\n\n  const { account } = /** @type {{ account: User }} */ (user);\n  const { email, login, name } = account;\n  const cleanEmail = cleanTrailerValue(email);\n\n  if (!cleanEmail) {\n    if (!accountsWarnedAboutEmail.has(account)) {\n      accountsWarnedAboutEmail.add(account);\n      // eslint-disable-next-line no-console\n      console.warn(\n        'The `signoff_commits` option is enabled, but the Git host doesn’t share your email ' +\n          'address, so commits are made without a `Signed-off-by` trailer.',\n      );\n    }\n\n    return message;\n  }\n\n  const author = cleanTrailerValue(name) || cleanTrailerValue(login) || cleanEmail;\n  const text = message.trimEnd();\n  const emailSuffix = `<${cleanEmail}>`.toLowerCase();\n\n  // The user has already signed off if a trailer has their email, whichever name it goes with\n  if (\n    text.split(/\\r?\\n/).some((line) => {\n      const normalized = line.trim().toLowerCase();\n\n      return normalized.startsWith('signed-off-by:') && normalized.endsWith(emailSuffix);\n    })\n  ) {\n    return message;\n  }\n\n  return addCommitTrailer(\n    message,\n    formatPersonTrailer('Signed-off-by', { name: author, email: cleanEmail }),\n  );\n};\n\n/**\n * Merge the commit histories of several files into one list. A commit touching more than one of the\n * files appears in each history, so only its first occurrence is kept.\n * @param {FileCommit[]} commits Commits, possibly with duplicates.\n * @returns {FileCommit[]} Unique commits, newest first.\n */\nexport const dedupeFileCommits = (commits) => {\n  /** @type {Map<string, FileCommit>} */\n  const commitMap = new Map();\n\n  commits.forEach((commit) => {\n    if (!commitMap.has(commit.sha)) {\n      commitMap.set(commit.sha, commit);\n    }\n  });\n\n  return [...commitMap.values()].sort((a, b) => b.date.getTime() - a.date.getTime());\n};\n\n/**\n * Create the error to throw when the last commit on the configured branch can’t be retrieved,\n * because the repository or the branch can’t be found.\n * @param {'repository_not_found' | 'branch_not_found'} key I18n key of the message to show.\n * @param {{ repo: string, branch?: string }} values Repository name, and the branch name for a\n * missing branch, to show in the message.\n * @returns {Error} Error.\n */\nexport const createLastCommitError = (key, values) =>\n  createLocalizedError('Failed to retrieve the last commit hash.', key, values);\n\n/**\n * Throw an error telling the user that the branch has moved, if its head is no longer the one a\n * refused commit was based on. This tells a commit refused over a moved head from any other\n * failure, so the user is told what happened and to try again, which picks up the other change\n * first. The head is looked up rather than the wording of the error relied upon. A failed lookup\n * returns quietly, leaving the original error to be reported.\n * @param {string} expectedHead SHA of the head commit the refused commit was based on.\n * @param {() => Promise<{ hash: string }>} fetchLastCommit Function to fetch the branch’s head.\n * @throws {Error} When the branch has moved.\n */\nexport const assertBranchNotMoved = async (expectedHead, fetchLastCommit) => {\n  const head = await fetchLastCommit().catch(() => undefined);\n\n  if (head && head.hash !== expectedHead) {\n    throw createLocalizedError(\n      'The branch has moved since the site data was loaded.',\n      'save_conflict.branch_moved',\n    );\n  }\n};\n\n/**\n * Maximum number of commits to fetch for a file’s history, the same on every service.\n */\nexport const MAX_FILE_COMMITS = 100;\n\n/**\n * Fetch the commit history of each of the given files with a separate request, keeping only a few\n * requests in flight at a time so a long list doesn’t trigger a Too Many Requests error, then merge\n * the histories into one list.\n * @param {string[]} paths File paths to fetch commit history for.\n * @param {(path: string) => Promise<any[]>} fetchHistory Function to fetch the raw commit list of a\n * file from the backend’s API.\n * @param {(commit: any) => FileCommit} parseCommit Function to convert a raw commit to a\n * {@link FileCommit}.\n * @returns {Promise<FileCommit[]>} Unique commits, newest first.\n */\nexport const fetchPerPathCommits = async (paths, fetchHistory, parseCommit) => {\n  const results = await mapConcurrently(paths, fetchHistory);\n\n  return dedupeFileCommits(results.flat().map(parseCommit));\n};\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\n\nimport {\n  DIR,\n  EXECUTABLE_FILE_MODE,\n  INDEX_PATH,\n  REGULAR_FILE_MODE,\n  ZERO_OID,\n} from '$lib/services/backends/fs/git/constants';\nimport { exists, splitPath } from '$lib/services/backends/fs/git/file-system';\nimport {\n  createIndexEntry,\n  findIndexEntry,\n  serializeIndex,\n  updateIndexEntries,\n} from '$lib/services/backends/fs/git/index-file';\nimport { writeLooseObject } from '$lib/services/backends/fs/git/objects';\nimport {\n  getIndexChecksum,\n  resolveBranchHead,\n  setIndexCache,\n} from '$lib/services/backends/fs/git/repository';\nimport { buildTree, serializeTree, writeChangedTrees } from '$lib/services/backends/fs/git/tree';\nimport { hasOtherSpellings, pickEntryName } from '$lib/services/backends/fs/shared/handles';\nimport { createCommitMessage } from '$lib/services/backends/git/shared/commits';\nimport { mapConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { textEncoder } from '$lib/services/utils/bytes';\n\n/**\n * @import {\n * CommitOptions,\n * FileChange,\n * GitFileSystem,\n * GitIndexEntry,\n * GitTreeEntry,\n * LocalGitRepository,\n * LocalGitSignature,\n * } from '$lib/types/private';\n */\n\n/**\n * How many saved files are read, hashed and stored at the same time.\n */\nconst STAGING_CONCURRENCY = 4;\n\n/**\n * Create a function that gives the path a file has, or would have, in the index. The CMS works with\n * paths in Unicode normalization form C, while Git keeps a path as it was added, which can be in\n * form D, e.g. a file added on Linux with a decomposed name. Using the index’s own spelling makes a\n * change update or remove the file’s entry rather than add another one next to it, and puts a new\n * file in the folder its siblings are in rather than in a second one that looks the same.\n * @param {GitIndexEntry[]} entries Index entries.\n * @returns {(path: string) => string} Function that takes a path in form C.\n */\nconst getIndexPathResolver = (entries) => {\n  /**\n   * Spelling in the index of each file or folder path that’s spelled differently in form C.\n   * @type {Map<string, string>}\n   */\n  const spellings = new Map();\n\n  entries.forEach(({ path }) => {\n    if (path === path.normalize()) {\n      return;\n    }\n\n    const segments = path.split('/');\n\n    segments.forEach((_, index) => {\n      const spelling = segments.slice(0, index + 1).join('/');\n\n      if (spelling !== spelling.normalize()) {\n        spellings.set(spelling.normalize(), spelling);\n      }\n    });\n  });\n\n  return (path) => {\n    const segments = path.split('/');\n\n    // Use the spelling of the longest leading part the index has, the whole path for a known file\n    for (let index = segments.length; index > 0; index -= 1) {\n      const spelling = spellings.get(segments.slice(0, index).join('/'));\n\n      if (spelling) {\n        return [spelling, ...segments.slice(index)].join('/');\n      }\n    }\n\n    return path;\n  };\n};\n\n/**\n * Get the path a saved file that isn’t in the index has in the working tree. The file the CMS has\n * saved keeps the name it has on the disk, which can be in Unicode normalization form D, as can the\n * name of a folder on its path, and a file system that compares names byte for byte, like ext4,\n * doesn’t find it by the path in form C. Git adds a file with the name it has on the disk there.\n * On macOS, which ignores the normalization, the path is kept as it is, the way Git adds it there\n * by default.\n * @param {GitFileSystem} fs File system.\n * @param {GitIndexEntry[]} entries Index entries.\n * @param {string} path Path, as spelled in the index if the file or a folder on its path is there.\n * @returns {Promise<string>} Path in the working tree, or the given path if it can’t be found.\n */\nconst getWorkingTreePath = async (fs, entries, path) => {\n  if (!hasOtherSpellings(path) || findIndexEntry(entries, path).found || (await exists(fs, path))) {\n    return path;\n  }\n\n  /** @type {string[]} */\n  const names = [];\n\n  for (const segment of splitPath(path)) {\n    const name = pickEntryName(await fs.readdir(names.join('/')), segment);\n\n    if (!name) {\n      return path;\n    }\n\n    names.push(name);\n  }\n\n  return names.join('/');\n};\n\n/**\n * Get the paths of the files a list of changes adds or updates.\n * @param {FileChange[]} changes Changes, with paths relative to the repository root.\n * @returns {string[]} Paths.\n */\nexport const getAddedPaths = (changes) =>\n  changes\n    .filter(({ action }) => ['create', 'update', 'move'].includes(action))\n    .map(({ path }) => path);\n\n/**\n * Get the paths of the files a list of changes removes, including the old paths of moved files.\n * @param {FileChange[]} changes Changes, with paths relative to the repository root.\n * @returns {string[]} Paths.\n */\nconst getRemovedPaths = (changes) =>\n  changes.flatMap(({ action, path, previousPath }) => {\n    if (action === 'delete') {\n      return [path];\n    }\n\n    if (action === 'move' && previousPath) {\n      return [previousPath];\n    }\n\n    return [];\n  });\n\n/**\n * Convert CRLF line endings to LF, as Git does for text when `core.autocrlf` is `true` or `input`.\n * Content that isn’t valid UTF-8 is taken as binary and left as it is.\n * @param {Uint8Array} content File content.\n * @returns {Uint8Array} Converted content.\n */\nexport const convertToLF = (content) => {\n  /** @type {string} */\n  let text;\n\n  try {\n    text = new TextDecoder('utf-8', { fatal: true }).decode(content);\n  } catch {\n    return content;\n  }\n\n  return textEncoder.encode(text.replaceAll('\\r\\n', '\\n'));\n};\n\n/**\n * Prepare the index entries for files that have been saved, the way `git add` does: the content is\n * written as a blob, and an untracked file that Git ignores is skipped. A file that’s tracked\n * keeps its mode, so an executable file stays executable.\n * @param {LocalGitRepository} repository Repository.\n * @param {string[]} paths File paths, as spelled in the index.\n * @returns {Promise<GitIndexEntry[]>} Entries.\n * @throws {Error} If a file can’t be read.\n */\nconst stageFiles = async ({ git, fs, index, autocrlf }, paths) => {\n  // A few files at a time, so a bulk upload isn’t read back into memory all at once\n  const entries = await mapConcurrently(\n    paths,\n    async (path) => {\n      const { position, found } = findIndexEntry(index.entries, path);\n\n      if (!found && (await git.isIgnored({ fs, dir: DIR, filepath: path }))) {\n        return undefined;\n      }\n\n      const { size, mtimeMs } = await fs.stat(path);\n      /** @type {Uint8Array} */\n      let content = await fs.readFile(path);\n\n      // Store the text with LF line endings, like Git does with the option\n      if (autocrlf) {\n        content = convertToLF(content);\n      }\n\n      return createIndexEntry({\n        path,\n        mode:\n          found && index.entries[position].mode === EXECUTABLE_FILE_MODE\n            ? EXECUTABLE_FILE_MODE\n            : REGULAR_FILE_MODE,\n        oid: await writeLooseObject(fs, 'blob', content),\n        size,\n        mtimeMs,\n      });\n    },\n    { concurrency: STAGING_CONCURRENCY },\n  );\n\n  return /** @type {GitIndexEntry[]} */ (entries.filter(Boolean));\n};\n\n/**\n * Format a time zone offset the way Git does, e.g. `+0900` for Japan.\n * @param {number} offset Offset in minutes, as returned by `Date.prototype.getTimezoneOffset()`,\n * which is positive for a time zone behind UTC.\n * @returns {string} Formatted offset.\n */\nexport const formatTimezoneOffset = (offset) => {\n  const minutes = Math.abs(offset);\n  const hours = String(Math.floor(minutes / 60)).padStart(2, '0');\n\n  return `${offset > 0 ? '-' : '+'}${hours}${String(minutes % 60).padStart(2, '0')}`;\n};\n\n/**\n * Record a commit in the reflogs of `HEAD` and the branch, so the user can find it with `git\n * reflog`, like a commit made with Git. A reflog is only added to, not created: Git creates them\n * unless they’re disabled.\n * @param {GitFileSystem} fs File system.\n * @param {object} args Arguments.\n * @param {string} args.branch Full name of the branch.\n * @param {string | undefined} args.oldOid ID of the previous commit, if any.\n * @param {string} args.newOid ID of the new commit.\n * @param {LocalGitSignature} args.signature Author and time of the commit.\n * @param {string} args.message Commit message.\n */\nconst addToReflogs = async (fs, { branch, oldOid, newOid, signature, message }) => {\n  const { name, email, timestamp, timezoneOffset } = signature;\n  const action = oldOid ? 'commit' : 'commit (initial)';\n  const subject = message.split('\\n')[0];\n  const identity = `${name} <${email}> ${timestamp} ${formatTimezoneOffset(timezoneOffset)}`;\n  const line = `${oldOid ?? ZERO_OID} ${newOid} ${identity}\\t${action}: ${subject}\\n`;\n\n  for (const path of ['.git/logs/HEAD', `.git/logs/${branch}`]) {\n    if (await exists(fs, path)) {\n      await fs.appendFile(path, line);\n    }\n  }\n};\n\n/**\n * Stage and commit changes that have been saved to the working tree.\n * @param {LocalGitRepository} repository Repository, as inspected before the changes were saved.\n * @param {FileChange[]} changes Changes, with paths relative to the repository root.\n * @param {CommitOptions} options Commit options.\n * @returns {Promise<{ oid: string, signature: LocalGitSignature, message: string } | undefined>}\n * ID, author, time and message of the new commit, or `undefined` if the changes didn’t change\n * anything Git tracks, e.g. a file saved without changes, or a file Git ignores.\n * @throws {Error} If the changes couldn’t be committed.\n */\nconst stageAndCommit = async (repository, changes, options) => {\n  const { git, fs, reader, branch, author, headOid, headTreeOid } = repository;\n  let { index, indexTree: tree } = repository;\n  const toIndexPath = getIndexPathResolver(index.entries);\n  const removedPaths = new Set(getRemovedPaths(changes).map(toIndexPath));\n\n  const addedPaths = await mapConcurrently(\n    getAddedPaths(changes),\n    (path) => getWorkingTreePath(fs, index.entries, toIndexPath(path)),\n    { concurrency: STAGING_CONCURRENCY },\n  );\n\n  const addedEntries = await stageFiles(repository, addedPaths);\n\n  // The index is updated in memory and written once, rather than with `git.add()` and\n  // `git.remove()`, which would read, verify and write the whole index for each call\n  if (addedEntries.length || index.entries.some(({ path }) => removedPaths.has(path))) {\n    const entries = updateIndexEntries(index.entries, { removedPaths, addedEntries });\n\n    // Only the directories of the changed files have to be hashed again\n    tree = await buildTree(entries, {\n      previous: tree,\n      changedPaths: [...removedPaths, ...addedPaths],\n    });\n\n    // The trees are written to the index as a cache tree, which Git and the next save can use\n    const bytes = await serializeIndex(entries, { tree });\n\n    await fs.writeFile(INDEX_PATH, bytes);\n    index = { version: 2, entries, extensions: ['TREE'] };\n    setIndexCache({ checksum: await getIndexChecksum(bytes), index, tree });\n  }\n\n  if (headTreeOid ? tree.oid === headTreeOid : !index.entries.length) {\n    return undefined;\n  }\n\n  // isomorphic-git would write every tree in the repository that isn’t a loose object, as it\n  // doesn’t look into pack files, so the trees are written here, and only the changed ones\n  await writeChangedTrees(tree, headTreeOid, {\n    readObject: reader.readObject,\n    /**\n     * Write a tree object.\n     * @param {GitTreeEntry[]} treeEntries Entries.\n     * @returns {Promise<string>} Object ID.\n     */\n    writeTree: (treeEntries) => writeLooseObject(fs, 'tree', serializeTree(treeEntries)),\n  });\n\n  const currentHeadOid = await resolveBranchHead(git, fs, branch);\n\n  // Git can’t update the branch while the index is locked, but a tool that doesn’t check the lock\n  // could have, and the new commit would undo its commit\n  if (currentHeadOid !== headOid) {\n    throw new Error('The branch has been updated by another program.');\n  }\n\n  const timestamp = Math.floor(Date.now() / 1000);\n\n  /** @type {LocalGitSignature} */\n  const signature = {\n    ...author,\n    timestamp,\n    timezoneOffset: new Date(timestamp * 1000).getTimezoneOffset(),\n  };\n\n  const message = createCommitMessage(changes, options);\n\n  /** @type {string} */\n  const oid = await git.commit({\n    fs,\n    dir: DIR,\n    ref: branch,\n    message,\n    tree: tree.oid,\n    author: signature,\n    committer: signature,\n  });\n\n  return { oid, signature, message };\n};\n\n/**\n * Commit changes that have been saved to the working tree. If the commit fails, the index is put\n * back as it was, so the changes staged for it don’t look like the user’s own the next time and\n * stop every later commit.\n * @param {LocalGitRepository} repository Repository, as inspected before the changes were saved.\n * @param {FileChange[]} changes Changes, with paths relative to the repository root.\n * @param {CommitOptions} options Commit options.\n * @returns {Promise<{ oid: string, date: Date } | undefined>} ID and date of the new commit, or\n * `undefined` if the changes didn’t change anything Git tracks.\n * @throws {Error} If the changes couldn’t be committed.\n */\nexport const commitSavedChanges = async (repository, changes, options) => {\n  const { fs, indexBuffer, branch, headOid } = repository;\n  let commit;\n\n  try {\n    commit = await stageAndCommit(repository, changes, options);\n  } catch (ex) {\n    if (indexBuffer) {\n      await fs.writeFile(INDEX_PATH, new Uint8Array(indexBuffer));\n    } else if (await exists(fs, INDEX_PATH)) {\n      await fs.unlink(INDEX_PATH);\n    }\n\n    throw ex;\n  }\n\n  if (!commit) {\n    return undefined;\n  }\n\n  const { oid, signature, message } = commit;\n\n  // The commit has been made by now, so the index mustn’t be put back if the reflogs can’t be\n  // written: it would undo the commit the next time the user commits\n  try {\n    await addToReflogs(fs, { branch, oldOid: headOid, newOid: oid, signature, message });\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  }\n\n  return { oid, date: new Date(signature.timestamp * 1000) };\n};\n","import { findLfsTrackedPath } from '$lib/services/backends/fs/git/attributes';\nimport { commitSavedChanges, getAddedPaths } from '$lib/services/backends/fs/git/commit';\nimport { INDEX_LOCK_PATH } from '$lib/services/backends/fs/git/constants';\nimport { inspectRepository } from '$lib/services/backends/fs/git/repository';\nimport { toRepoChanges } from '$lib/services/backends/root-dir';\nimport { createConcurrencyLimiter } from '$lib/services/utils/scheduling';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * CommitOptions,\n * CommitResults,\n * FileChange,\n * GitFileSystem,\n * LocalGitInspection,\n * LocalGitNotice,\n * LocalGitStatus,\n * } from '$lib/types/private';\n */\n\nexport { clearLocalGitCache } from '$lib/services/backends/fs/git/repository';\n\n/**\n * Notice for the user when their changes have been saved but not committed. A new object is\n * assigned every time, so the same notice is shown again for the next save.\n * @type {{ current: LocalGitNotice | undefined }}\n */\nexport const localGitNotice = createRawState();\n\n/**\n * Add an operation to the queue. The operations run one at a time, so a commit doesn’t find the\n * changes another one has just staged.\n */\nconst enqueue = createConcurrencyLimiter(1);\n\n/**\n * Get the message of an error.\n * @param {unknown} ex Error.\n * @returns {string} Message.\n */\nconst describeError = (ex) => {\n  // isomorphic-git wraps an internal error in a request to report it, keeping the cause in `data`\n  const { message, data } = Object(ex);\n\n  return data?.message ?? message ?? String(ex);\n};\n\n/**\n * Check whether the CMS can commit to a repository on the user’s computer right now. The check\n * waits for a save in progress, so the lock the CMS holds while committing isn’t taken for another\n * Git process’s.\n * @param {FileSystemDirectoryHandle} repoRootDirHandle Handle of the repository’s root directory.\n * @returns {Promise<LocalGitStatus>} Status.\n */\nexport const getLocalGitStatus = (repoRootDirHandle) =>\n  enqueue(async () => {\n    try {\n      const { repository: _repository, ...status } = await inspectRepository(repoRootDirHandle);\n\n      return status;\n    } catch (ex) {\n      return { ready: false, reason: 'error', detail: describeError(ex) };\n    }\n  });\n\n/**\n * Save changes to the working tree of a repository on the user’s computer, and commit them to the\n * current branch, as a Git backend would to the remote repository. The changes are committed only\n * if the repository allows, so the user’s own work in progress isn’t mixed in; otherwise they’re\n * only saved, and the user is told why. A failure to commit doesn’t fail the save either. The index\n * is locked from the inspection to the commit, so Git can’t change it in between.\n * @param {object} args Arguments.\n * @param {FileSystemDirectoryHandle} args.repoRootDirHandle Handle of the repository’s root\n * directory.\n * @param {FileChange[]} args.changes Changes, with paths relative to the configured root\n * directory.\n * @param {CommitOptions} args.options Commit options.\n * @param {() => Promise<CommitResults>} args.save Function to save the changes to the files.\n * @returns {Promise<CommitResults>} Results of the save, with the ID and date of the commit if one\n * was made.\n * @throws {Error} If the changes couldn’t be saved.\n */\nexport const saveAndCommitChanges = ({ repoRootDirHandle, changes, options, save }) =>\n  enqueue(async () => {\n    const repoChanges = toRepoChanges(changes);\n    /**\n     * File system the index has been locked with, if the inspection got that far. Only this lock\n     * is removed, never one another Git process holds.\n     * @type {GitFileSystem | undefined}\n     */\n    let lockedFs;\n\n    try {\n      /** @type {LocalGitInspection} */\n      let inspection;\n\n      try {\n        inspection = await inspectRepository(repoRootDirHandle, {\n          /**\n           * Remember the file system the index has been locked with.\n           * @param {GitFileSystem} fs File system.\n           */\n          onLock: (fs) => {\n            lockedFs = fs;\n          },\n        });\n\n        if (inspection.repository) {\n          const { fs, ignoreCase } = inspection.repository;\n          const lfsPath = await findLfsTrackedPath(fs, getAddedPaths(repoChanges), { ignoreCase });\n\n          if (lfsPath) {\n            inspection = { ready: false, reason: 'lfs', detail: lfsPath };\n          }\n        }\n      } catch (ex) {\n        inspection = { ready: false, reason: 'error', detail: describeError(ex) };\n      }\n\n      const { repository, reason = 'error', detail } = inspection;\n      const results = await save();\n\n      if (!repository) {\n        localGitNotice.current = { reason, detail };\n\n        return results;\n      }\n\n      try {\n        const commit = await commitSavedChanges(repository, repoChanges, options);\n\n        return commit ? { ...results, sha: commit.oid, date: commit.date } : results;\n      } catch (ex) {\n        // eslint-disable-next-line no-console\n        console.error(ex);\n        localGitNotice.current = { reason: 'error', detail: describeError(ex) };\n\n        return results;\n      }\n    } finally {\n      try {\n        await lockedFs?.unlink(INDEX_LOCK_PATH);\n      } catch {\n        //\n      }\n    }\n  });\n","const types = {\n    'application/andrew-inset': ['ez'],\n    'application/appinstaller': ['appinstaller'],\n    'application/applixware': ['aw'],\n    'application/appx': ['appx'],\n    'application/appxbundle': ['appxbundle'],\n    'application/atom+xml': ['atom'],\n    'application/atomcat+xml': ['atomcat'],\n    'application/atomdeleted+xml': ['atomdeleted'],\n    'application/atomsvc+xml': ['atomsvc'],\n    'application/atsc-dwd+xml': ['dwd'],\n    'application/atsc-held+xml': ['held'],\n    'application/atsc-rsat+xml': ['rsat'],\n    'application/automationml-aml+xml': ['aml'],\n    'application/automationml-amlx+zip': ['amlx'],\n    'application/bdoc': ['bdoc'],\n    'application/calendar+xml': ['xcs'],\n    'application/ccxml+xml': ['ccxml'],\n    'application/cdfx+xml': ['cdfx'],\n    'application/cdmi-capability': ['cdmia'],\n    'application/cdmi-container': ['cdmic'],\n    'application/cdmi-domain': ['cdmid'],\n    'application/cdmi-object': ['cdmio'],\n    'application/cdmi-queue': ['cdmiq'],\n    'application/cpl+xml': ['cpl'],\n    'application/cu-seeme': ['cu'],\n    'application/cwl': ['cwl'],\n    'application/dash+xml': ['mpd'],\n    'application/dash-patch+xml': ['mpp'],\n    'application/davmount+xml': ['davmount'],\n    'application/dicom': ['dcm'],\n    'application/docbook+xml': ['dbk'],\n    'application/dssc+der': ['dssc'],\n    'application/dssc+xml': ['xdssc'],\n    'application/ecmascript': ['ecma'],\n    'application/emma+xml': ['emma'],\n    'application/emotionml+xml': ['emotionml'],\n    'application/epub+zip': ['epub'],\n    'application/exi': ['exi'],\n    'application/express': ['exp'],\n    'application/fdf': ['fdf'],\n    'application/fdt+xml': ['fdt'],\n    'application/font-tdpfr': ['pfr'],\n    'application/geo+json': ['geojson'],\n    'application/gml+xml': ['gml'],\n    'application/gpx+xml': ['gpx'],\n    'application/gxf': ['gxf'],\n    'application/gzip': ['gz'],\n    'application/hjson': ['hjson'],\n    'application/hyperstudio': ['stk'],\n    'application/inkml+xml': ['ink', 'inkml'],\n    'application/ipfix': ['ipfix'],\n    'application/its+xml': ['its'],\n    'application/java-archive': ['jar', 'war', 'ear'],\n    'application/java-serialized-object': ['ser'],\n    'application/java-vm': ['class'],\n    'application/javascript': ['*js'],\n    'application/json': ['json', 'map'],\n    'application/json5': ['json5'],\n    'application/jsonml+json': ['jsonml'],\n    'application/ld+json': ['jsonld'],\n    'application/lgr+xml': ['lgr'],\n    'application/lost+xml': ['lostxml'],\n    'application/mac-binhex40': ['hqx'],\n    'application/mac-compactpro': ['cpt'],\n    'application/mads+xml': ['mads'],\n    'application/manifest+json': ['webmanifest'],\n    'application/marc': ['mrc'],\n    'application/marcxml+xml': ['mrcx'],\n    'application/mathematica': ['ma', 'nb', 'mb'],\n    'application/mathml+xml': ['mathml'],\n    'application/mbox': ['mbox'],\n    'application/media-policy-dataset+xml': ['mpf'],\n    'application/mediaservercontrol+xml': ['mscml'],\n    'application/metalink+xml': ['metalink'],\n    'application/metalink4+xml': ['meta4'],\n    'application/mets+xml': ['mets'],\n    'application/mmt-aei+xml': ['maei'],\n    'application/mmt-usd+xml': ['musd'],\n    'application/mods+xml': ['mods'],\n    'application/mp21': ['m21', 'mp21'],\n    'application/mp4': ['*mp4', '*mpg4', 'mp4s', 'm4p'],\n    'application/msix': ['msix'],\n    'application/msixbundle': ['msixbundle'],\n    'application/msword': ['doc', 'dot'],\n    'application/mxf': ['mxf'],\n    'application/n-quads': ['nq'],\n    'application/n-triples': ['nt'],\n    'application/node': ['cjs'],\n    'application/octet-stream': [\n        'bin',\n        'dms',\n        'lrf',\n        'mar',\n        'so',\n        'dist',\n        'distz',\n        'pkg',\n        'bpk',\n        'dump',\n        'elc',\n        'deploy',\n        'exe',\n        'dll',\n        'deb',\n        'dmg',\n        'iso',\n        'img',\n        'msi',\n        'msp',\n        'msm',\n        'buffer',\n    ],\n    'application/oda': ['oda'],\n    'application/oebps-package+xml': ['opf'],\n    'application/ogg': ['ogx'],\n    'application/omdoc+xml': ['omdoc'],\n    'application/onenote': [\n        'onetoc',\n        'onetoc2',\n        'onetmp',\n        'onepkg',\n        'one',\n        'onea',\n    ],\n    'application/oxps': ['oxps'],\n    'application/p2p-overlay+xml': ['relo'],\n    'application/patch-ops-error+xml': ['xer'],\n    'application/pdf': ['pdf'],\n    'application/pgp-encrypted': ['pgp'],\n    'application/pgp-keys': ['asc'],\n    'application/pgp-signature': ['sig', '*asc'],\n    'application/pics-rules': ['prf'],\n    'application/pkcs10': ['p10'],\n    'application/pkcs7-mime': ['p7m', 'p7c'],\n    'application/pkcs7-signature': ['p7s'],\n    'application/pkcs8': ['p8'],\n    'application/pkix-attr-cert': ['ac'],\n    'application/pkix-cert': ['cer'],\n    'application/pkix-crl': ['crl'],\n    'application/pkix-pkipath': ['pkipath'],\n    'application/pkixcmp': ['pki'],\n    'application/pls+xml': ['pls'],\n    'application/postscript': ['ai', 'eps', 'ps'],\n    'application/provenance+xml': ['provx'],\n    'application/pskc+xml': ['pskcxml'],\n    'application/raml+yaml': ['raml'],\n    'application/rdf+xml': ['rdf', 'owl'],\n    'application/reginfo+xml': ['rif'],\n    'application/relax-ng-compact-syntax': ['rnc'],\n    'application/resource-lists+xml': ['rl'],\n    'application/resource-lists-diff+xml': ['rld'],\n    'application/rls-services+xml': ['rs'],\n    'application/route-apd+xml': ['rapd'],\n    'application/route-s-tsid+xml': ['sls'],\n    'application/route-usd+xml': ['rusd'],\n    'application/rpki-ghostbusters': ['gbr'],\n    'application/rpki-manifest': ['mft'],\n    'application/rpki-roa': ['roa'],\n    'application/rsd+xml': ['rsd'],\n    'application/rss+xml': ['rss'],\n    'application/rtf': ['rtf'],\n    'application/sbml+xml': ['sbml'],\n    'application/scvp-cv-request': ['scq'],\n    'application/scvp-cv-response': ['scs'],\n    'application/scvp-vp-request': ['spq'],\n    'application/scvp-vp-response': ['spp'],\n    'application/sdp': ['sdp'],\n    'application/senml+xml': ['senmlx'],\n    'application/sensml+xml': ['sensmlx'],\n    'application/set-payment-initiation': ['setpay'],\n    'application/set-registration-initiation': ['setreg'],\n    'application/shf+xml': ['shf'],\n    'application/sieve': ['siv', 'sieve'],\n    'application/smil+xml': ['smi', 'smil'],\n    'application/sparql-query': ['rq'],\n    'application/sparql-results+xml': ['srx'],\n    'application/sql': ['sql'],\n    'application/srgs': ['gram'],\n    'application/srgs+xml': ['grxml'],\n    'application/sru+xml': ['sru'],\n    'application/ssdl+xml': ['ssdl'],\n    'application/ssml+xml': ['ssml'],\n    'application/swid+xml': ['swidtag'],\n    'application/tei+xml': ['tei', 'teicorpus'],\n    'application/thraud+xml': ['tfi'],\n    'application/timestamped-data': ['tsd'],\n    'application/toml': ['toml'],\n    'application/trig': ['trig'],\n    'application/ttml+xml': ['ttml'],\n    'application/ubjson': ['ubj'],\n    'application/urc-ressheet+xml': ['rsheet'],\n    'application/urc-targetdesc+xml': ['td'],\n    'application/voicexml+xml': ['vxml'],\n    'application/wasm': ['wasm'],\n    'application/watcherinfo+xml': ['wif'],\n    'application/widget': ['wgt'],\n    'application/winhlp': ['hlp'],\n    'application/wsdl+xml': ['wsdl'],\n    'application/wspolicy+xml': ['wspolicy'],\n    'application/xaml+xml': ['xaml'],\n    'application/xcap-att+xml': ['xav'],\n    'application/xcap-caps+xml': ['xca'],\n    'application/xcap-diff+xml': ['xdf'],\n    'application/xcap-el+xml': ['xel'],\n    'application/xcap-ns+xml': ['xns'],\n    'application/xenc+xml': ['xenc'],\n    'application/xfdf': ['xfdf'],\n    'application/xhtml+xml': ['xhtml', 'xht'],\n    'application/xliff+xml': ['xlf'],\n    'application/xml': ['xml', 'xsl', 'xsd', 'rng'],\n    'application/xml-dtd': ['dtd'],\n    'application/xop+xml': ['xop'],\n    'application/xproc+xml': ['xpl'],\n    'application/xslt+xml': ['*xsl', 'xslt'],\n    'application/xspf+xml': ['xspf'],\n    'application/xv+xml': ['mxml', 'xhvml', 'xvml', 'xvm'],\n    'application/yang': ['yang'],\n    'application/yin+xml': ['yin'],\n    'application/zip': ['zip'],\n    'application/zip+dotlottie': ['lottie'],\n    'audio/3gpp': ['*3gpp'],\n    'audio/aac': ['adts', 'aac'],\n    'audio/adpcm': ['adp'],\n    'audio/amr': ['amr'],\n    'audio/basic': ['au', 'snd'],\n    'audio/midi': ['mid', 'midi', 'kar', 'rmi'],\n    'audio/mobile-xmf': ['mxmf'],\n    'audio/mp3': ['*mp3'],\n    'audio/mp4': ['m4a', 'mp4a', 'm4b'],\n    'audio/mpeg': ['mpga', 'mp2', 'mp2a', 'mp3', 'm2a', 'm3a'],\n    'audio/ogg': ['oga', 'ogg', 'spx', 'opus'],\n    'audio/s3m': ['s3m'],\n    'audio/silk': ['sil'],\n    'audio/wav': ['wav'],\n    'audio/wave': ['*wav'],\n    'audio/webm': ['weba'],\n    'audio/xm': ['xm'],\n    'font/collection': ['ttc'],\n    'font/otf': ['otf'],\n    'font/ttf': ['ttf'],\n    'font/woff': ['woff'],\n    'font/woff2': ['woff2'],\n    'image/aces': ['exr'],\n    'image/apng': ['apng'],\n    'image/avci': ['avci'],\n    'image/avcs': ['avcs'],\n    'image/avif': ['avif'],\n    'image/bmp': ['bmp', 'dib'],\n    'image/cgm': ['cgm'],\n    'image/dicom-rle': ['drle'],\n    'image/dpx': ['dpx'],\n    'image/emf': ['emf'],\n    'image/fits': ['fits'],\n    'image/g3fax': ['g3'],\n    'image/gif': ['gif'],\n    'image/heic': ['heic'],\n    'image/heic-sequence': ['heics'],\n    'image/heif': ['heif'],\n    'image/heif-sequence': ['heifs'],\n    'image/hej2k': ['hej2'],\n    'image/ief': ['ief'],\n    'image/jaii': ['jaii'],\n    'image/jais': ['jais'],\n    'image/jls': ['jls'],\n    'image/jp2': ['jp2', 'jpg2'],\n    'image/jpeg': ['jpg', 'jpeg', 'jpe'],\n    'image/jph': ['jph'],\n    'image/jphc': ['jhc'],\n    'image/jpm': ['jpm', 'jpgm'],\n    'image/jpx': ['jpx', 'jpf'],\n    'image/jxl': ['jxl'],\n    'image/jxr': ['jxr'],\n    'image/jxra': ['jxra'],\n    'image/jxrs': ['jxrs'],\n    'image/jxs': ['jxs'],\n    'image/jxsc': ['jxsc'],\n    'image/jxsi': ['jxsi'],\n    'image/jxss': ['jxss'],\n    'image/ktx': ['ktx'],\n    'image/ktx2': ['ktx2'],\n    'image/pjpeg': ['jfif'],\n    'image/png': ['png'],\n    'image/sgi': ['sgi'],\n    'image/svg+xml': ['svg', 'svgz'],\n    'image/t38': ['t38'],\n    'image/tiff': ['tif', 'tiff'],\n    'image/tiff-fx': ['tfx'],\n    'image/webp': ['webp'],\n    'image/wmf': ['wmf'],\n    'message/disposition-notification': ['disposition-notification'],\n    'message/global': ['u8msg'],\n    'message/global-delivery-status': ['u8dsn'],\n    'message/global-disposition-notification': ['u8mdn'],\n    'message/global-headers': ['u8hdr'],\n    'message/rfc822': ['eml', 'mime', 'mht', 'mhtml'],\n    'model/3mf': ['3mf'],\n    'model/gltf+json': ['gltf'],\n    'model/gltf-binary': ['glb'],\n    'model/iges': ['igs', 'iges'],\n    'model/jt': ['jt'],\n    'model/mesh': ['msh', 'mesh', 'silo'],\n    'model/mtl': ['mtl'],\n    'model/obj': ['obj'],\n    'model/prc': ['prc'],\n    'model/step': ['step', 'stp', 'stpnc', 'p21', '210'],\n    'model/step+xml': ['stpx'],\n    'model/step+zip': ['stpz'],\n    'model/step-xml+zip': ['stpxz'],\n    'model/stl': ['stl'],\n    'model/u3d': ['u3d'],\n    'model/vrml': ['wrl', 'vrml'],\n    'model/x3d+binary': ['*x3db', 'x3dbz'],\n    'model/x3d+fastinfoset': ['x3db'],\n    'model/x3d+vrml': ['*x3dv', 'x3dvz'],\n    'model/x3d+xml': ['x3d', 'x3dz'],\n    'model/x3d-vrml': ['x3dv'],\n    'text/cache-manifest': ['appcache', 'manifest'],\n    'text/calendar': ['ics', 'ifb'],\n    'text/coffeescript': ['coffee', 'litcoffee'],\n    'text/css': ['css'],\n    'text/csv': ['csv'],\n    'text/html': ['html', 'htm', 'shtml'],\n    'text/jade': ['jade'],\n    'text/javascript': ['js', 'mjs'],\n    'text/jsx': ['jsx'],\n    'text/less': ['less'],\n    'text/markdown': ['md', 'markdown'],\n    'text/mathml': ['mml'],\n    'text/mdx': ['mdx'],\n    'text/n3': ['n3'],\n    'text/plain': ['txt', 'text', 'conf', 'def', 'list', 'log', 'in', 'ini'],\n    'text/richtext': ['rtx'],\n    'text/rtf': ['*rtf'],\n    'text/sgml': ['sgml', 'sgm'],\n    'text/shex': ['shex'],\n    'text/slim': ['slim', 'slm'],\n    'text/spdx': ['spdx'],\n    'text/stylus': ['stylus', 'styl'],\n    'text/tab-separated-values': ['tsv'],\n    'text/troff': ['t', 'tr', 'roff', 'man', 'me', 'ms'],\n    'text/turtle': ['ttl'],\n    'text/uri-list': ['uri', 'uris', 'urls'],\n    'text/vcard': ['vcard'],\n    'text/vtt': ['vtt'],\n    'text/wgsl': ['wgsl'],\n    'text/xml': ['*xml'],\n    'text/yaml': ['yaml', 'yml'],\n    'video/3gpp': ['3gp', '3gpp'],\n    'video/3gpp2': ['3g2'],\n    'video/h261': ['h261'],\n    'video/h263': ['h263'],\n    'video/h264': ['h264'],\n    'video/iso.segment': ['m4s'],\n    'video/jpeg': ['jpgv'],\n    'video/jpm': ['*jpm', '*jpgm'],\n    'video/mj2': ['mj2', 'mjp2'],\n    'video/mp2t': ['ts', 'm2t', 'm2ts', 'mts'],\n    'video/mp4': ['mp4', 'mp4v', 'mpg4'],\n    'video/mpeg': ['mpeg', 'mpg', 'mpe', 'm1v', 'm2v'],\n    'video/ogg': ['ogv'],\n    'video/quicktime': ['qt', 'mov'],\n    'video/webm': ['webm'],\n};\nObject.freeze(types);\nexport default types;\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions;\nclass Mime {\n    constructor(...args) {\n        _Mime_extensionToType.set(this, new Map());\n        _Mime_typeToExtension.set(this, new Map());\n        _Mime_typeToExtensions.set(this, new Map());\n        for (const arg of args) {\n            this.define(arg);\n        }\n    }\n    define(typeMap, force = false) {\n        for (let [type, extensions] of Object.entries(typeMap)) {\n            type = type.toLowerCase();\n            extensions = extensions.map((ext) => ext.toLowerCase());\n            let allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").get(type);\n            if (!allExtensions) {\n                allExtensions = new Set();\n                __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").set(type, allExtensions);\n            }\n            let first = true;\n            for (let extension of extensions) {\n                const starred = extension.startsWith('*');\n                extension = starred ? extension.slice(1) : extension;\n                allExtensions.add(extension);\n                if (first) {\n                    __classPrivateFieldGet(this, _Mime_typeToExtension, \"f\").set(type, extension);\n                }\n                first = false;\n                if (starred)\n                    continue;\n                const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, \"f\").get(extension);\n                if (currentType && currentType != type && !force) {\n                    throw new Error(`\"${type} -> ${extension}\" conflicts with \"${currentType} -> ${extension}\". Pass \\`force=true\\` to override this definition.`);\n                }\n                __classPrivateFieldGet(this, _Mime_extensionToType, \"f\").set(extension, type);\n            }\n        }\n        return this;\n    }\n    getType(path) {\n        if (typeof path !== 'string')\n            return null;\n        const last = path.replace(/^.*[/\\\\]/s, '').toLowerCase();\n        const ext = last.replace(/^.*\\./s, '').toLowerCase();\n        const hasPath = last.length < path.length;\n        const hasDot = ext.length < last.length - 1;\n        if (!hasDot && hasPath)\n            return null;\n        return __classPrivateFieldGet(this, _Mime_extensionToType, \"f\").get(ext) ?? null;\n    }\n    getExtension(type) {\n        if (typeof type !== 'string')\n            return null;\n        type = type?.split?.(';')[0];\n        return ((type && __classPrivateFieldGet(this, _Mime_typeToExtension, \"f\").get(type.trim().toLowerCase())) ?? null);\n    }\n    getAllExtensions(type) {\n        if (typeof type !== 'string')\n            return null;\n        type = type.split(';')[0].trim().toLowerCase();\n        const extensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").get(type);\n        return extensions ? new Set(extensions) : null;\n    }\n    _freeze() {\n        this.define = () => {\n            throw new Error('define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances');\n        };\n        Object.freeze(this);\n        return this;\n    }\n    _getTestState() {\n        return {\n            types: __classPrivateFieldGet(this, _Mime_extensionToType, \"f\"),\n            extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, \"f\"),\n        };\n    }\n}\n_Mime_extensionToType = new WeakMap(), _Mime_typeToExtension = new WeakMap(), _Mime_typeToExtensions = new WeakMap();\nexport default Mime;\n","import standardTypes from '../types/standard.js';\nimport Mime from './Mime.js';\nexport { default as Mime } from './Mime.js';\nexport default new Mime(standardTypes)._freeze();\n","import { Mime } from 'mime/lite';\nimport standardTypes from 'mime/types/standard.js';\nimport otherTypes from 'virtual:mime-other-types';\n\n/**\n * Media type lookup, with the standard types and the vendor and experimental types the CMS can\n * tell apart: images, videos, audio and text files, and the documents it lists as such, e.g.\n * `.ico`, `.mkv`, `.flac` or `.docx`. The full table of the `mime` package holds hundreds of others\n * the CMS has no use for, so the `bundleMimeTypes` Vite plugin picks these out at build time.\n */\nexport default new Mime(standardTypes, otherTypes)._freeze();\n","import { isTextFileType } from '@sveltia/utils/file';\nimport { isURL } from '@sveltia/utils/string';\n\nimport mime from '$lib/services/utils/mime';\n\n/**\n * @import { Asset, AssetKind } from '$lib/types/private';\n */\n\n/**\n * List of media kinds.\n * @type {AssetKind[]}\n */\nexport const MEDIA_KINDS = ['image', 'video', 'audio'];\n\n/**\n * List of media kinds that support thumbnails.\n * @type {AssetKind[]}\n */\nexport const THUMBNAIL_KINDS = ['image', 'video'];\n\n/**\n * Whether the given file is a PDF document, judging by its extension, which is matched\n * case-insensitively, as in `Brochure.PDF`.\n * @param {string} fileName File name or path, e.g. `files/brochure.pdf`.\n * @returns {boolean} Result.\n */\nexport const isPDF = (fileName) => /\\.pdf$/i.test(fileName);\n\n/**\n * Whether a thumbnail can be generated for the given asset: an image, a video, or a PDF document,\n * whose first page is rendered with PDF.js.\n * @param {Asset} asset Asset.\n * @returns {boolean} Result.\n */\nexport const canCreateThumbnail = (asset) =>\n  THUMBNAIL_KINDS.includes(asset.kind) || isPDF(asset.name);\n\n/**\n * List of all asset kinds.\n * @type {AssetKind[]}\n */\nexport const ASSET_KINDS = [...MEDIA_KINDS, 'document', 'other'];\n\n/**\n * Regular expression that matches common document file extensions.\n * @type {RegExp}\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types\n */\nexport const DOC_EXTENSION_REGEX = /\\.(?:csv|docx?|odp|ods|odt|pdf|pptx?|rtf|xlsx?)$/i;\n\nconst MEDIA_TYPE_REGEX = /^(?<type>image|video|audio)\\//;\n\n/**\n * Check if the given asset kind is media.\n * @param {string} kind Kind, e.g. `image` or `video`.\n * @returns {boolean} Result.\n */\nexport const isMediaKind = (kind) => /** @type {string[]} */ (MEDIA_KINDS).includes(kind);\n\n/**\n * Whether a file of the given kind and name can be previewed: a media file, a PDF document or a\n * plaintext file.\n * @param {string} kind Kind, e.g. `image` or `document`.\n * @param {string} fileName File name or path, e.g. `images/photo.jpg`.\n * @returns {boolean} Result.\n */\nexport const canPreviewFile = (kind, fileName) => {\n  const type = mime.getType(fileName);\n\n  return isMediaKind(kind) || type === 'application/pdf' || (!!type && isTextFileType(type));\n};\n\n/**\n * Whether the given asset is previewable.\n * @param {Asset} asset Asset.\n * @returns {boolean} Result.\n */\nexport const canPreviewAsset = (asset) => canPreviewFile(asset.kind, asset.path);\n\n/**\n * Get the media kind of the given MIME type.\n * @param {string} mimeType MIME type, e.g. `image/png`.\n * @returns {AssetKind | undefined} Kind.\n */\nexport const getMediaKindFromType = (mimeType) => {\n  if (!mimeType) {\n    return undefined;\n  }\n\n  const [type, subType] = mimeType.split('/');\n\n  // A malformed type without a subtype, e.g. from `data:image;base64,…`, is not a media type\n  if (isMediaKind(type) && !!subType && !subType.startsWith('x-')) {\n    return /** @type {AssetKind} */ (type);\n  }\n\n  return undefined;\n};\n\n/**\n * Get the media kind of the given path or URL from its extension, without loading anything.\n * @param {string} source Asset path, complete URL or data URL.\n * @returns {AssetKind | undefined} Kind.\n */\nexport const getMediaKindFromPath = (source) => {\n  // A data URL carries its own MIME type, e.g. `data:image/png;base64,…`\n  if (source.startsWith('data:')) {\n    return getMediaKindFromType(source.slice(5).split(/[;,]/)[0]);\n  }\n\n  if (isURL(source)) {\n    const { hostname, pathname } = new URL(source);\n\n    // Handle common image CDN hostnames, e.g. images.unsplash.com\n    if (hostname.startsWith('images.')) {\n      return 'image';\n    }\n\n    // Remove query string and hash\n    source = pathname;\n  }\n\n  return getMediaKindFromType(mime.getType(source) ?? '');\n};\n\n/**\n * Get the media type of the given blob or path.\n * @param {Blob | string} source Blob, blob URL, or asset path.\n * @returns {Promise<AssetKind | undefined>} Kind.\n */\nexport const getMediaKind = async (source) => {\n  if (typeof source === 'string') {\n    if (!source.startsWith('blob:')) {\n      return getMediaKindFromPath(source);\n    }\n\n    try {\n      return getMediaKindFromType((await (await fetch(source)).blob()).type);\n    } catch {\n      return undefined;\n    }\n  }\n\n  if (source instanceof Blob) {\n    return getMediaKindFromType(source.type);\n  }\n\n  return undefined;\n};\n\n/**\n * Whether the given asset is editable.\n * @param {Asset} asset Asset.\n * @returns {boolean} Result.\n * @todo Support image editing.\n */\nexport const canEditAsset = (asset) => {\n  const type = mime.getType(asset.path);\n\n  return !!type && isTextFileType(type);\n};\n\n/**\n * Determine the asset’s kind from the file extension.\n * @param {string} name File name or path.\n * @returns {AssetKind} One of {@link ASSET_KINDS}.\n */\nexport const getAssetKind = (name) =>\n  /** @type {AssetKind} */ (\n    mime.getType(name)?.match(MEDIA_TYPE_REGEX)?.groups?.type ??\n      (DOC_EXTENSION_REGEX.test(name) ? 'document' : 'other')\n  );\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { BaseConfigListItem } from '$lib/types/private';\n */\n\n/**\n * Regular expression to match Git configuration files.\n * @type {RegExp}\n */\nexport const GIT_CONFIG_FILE_REGEX = /^(?:.+\\/)?(\\.git(?:attributes|ignore|keep))$/;\n\n/**\n * List of Git configuration files in the repository that we need, such as `.gitattributes`,\n * `.gitkeep`, etc. `.gitkeep` is not technically a config file, but it’s used to keep an empty\n * directory in the repository, which is needed to create a new asset folder in the CMS.\n * @type {{ current: BaseConfigListItem[] }}\n */\nexport const gitConfigFiles = createRawState([]);\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport { cmsConfig } from '$lib/services/config/state';\nimport { foldPath, normalizeFolderPath } from '$lib/services/utils/file';\n\n/**\n * Names of the folders the CMS itself is usually served from, e.g. `static/admin/index.html` along\n * with its `config.yml`. With a media folder at the root of the public folder, such as `static` or\n * `public`, those files are listed as assets, and replacing the admin page would hand the next\n * user’s sign-in to whoever wrote it. So the files in such a folder are read-only in the Asset\n * Library, and no asset change made through the CMS can touch them. Deployment configuration such\n * as `_redirects` can be edited as an entry of a file collection, so it isn’t ruled out here.\n */\nconst CMS_FOLDER_NAMES = ['admin', 'cms'];\n/**\n * Folders a site is usually served from: the repository root, as with Jekyll, and the public\n * folders of most frameworks, e.g. `static` for Hugo and SvelteKit or `public` for Astro and\n * Next.js.\n */\nconst SITE_ROOT_FOLDERS = ['', 'static', 'public'];\n\n/**\n * Check whether the given folder name is one the CMS itself is usually served from.\n * @param {string} name Folder name.\n * @returns {boolean} Result.\n */\nexport const isCmsFolderName = (name) => CMS_FOLDER_NAMES.includes(foldPath(name));\n\n/**\n * Get the folder the site is served from, as told by the global `media_folder` and\n * `public_folder` options: `static` for `static/images` published at `/images`, for example.\n * @param {unknown} mediaFolder `media_folder` option.\n * @param {unknown} publicFolder `public_folder` option.\n * @returns {string | undefined} Folder path, or `undefined` if it can’t be told.\n */\nconst getConfiguredSiteRootFolder = (mediaFolder, publicFolder) => {\n  if (typeof mediaFolder !== 'string' || typeof publicFolder !== 'string') {\n    return undefined;\n  }\n\n  const media = normalizeFolderPath(mediaFolder);\n  const pub = stripSlashes(publicFolder);\n\n  // A relative or framework-specific public folder, like `../images` or `@assets/images`, isn’t a\n  // URL path\n  if (hasTemplateTags(media) || hasTemplateTags(pub) || /^[.@]/.test(pub)) {\n    return undefined;\n  }\n\n  if (!pub || media === pub) {\n    return pub ? '' : media;\n  }\n\n  return media.endsWith(`/${pub}`) ? media.slice(0, -pub.length - 1) : undefined;\n};\n\n/**\n * Get the folder of the admin page the CMS is running on, from its URL path: `admin` for `/admin/`,\n * `/admin` or `/admin/index.html`. The site may be served below a base path, like a GitHub Pages\n * project site at `/repo/`, so each trailing part of the folder path is returned as well:\n * `repo/dashboard` and `dashboard` for `/repo/dashboard/`.\n * @param {string} pathname URL path of the page.\n * @returns {string[]} Folder paths. Empty if the page is at the root or the path can’t be read.\n */\nconst getAdminPageFolders = (pathname) => {\n  const segments = pathname.split('/').filter(Boolean);\n\n  // A last segment with a dot is the page file itself\n  if (segments.at(-1)?.includes('.')) {\n    segments.pop();\n  }\n\n  try {\n    const decoded = segments.map(decodeURIComponent);\n\n    return decoded.map((_segment, index) => decoded.slice(index).join('/'));\n  } catch {\n    return [];\n  }\n};\n\n/**\n * Cache of {@link getCmsFolderPaths}, which is called for every asset path checked, keyed by the\n * global folder options and the URL path of the page it depends on.\n * @type {{ key: string, paths: string[] } | undefined}\n */\nlet cmsFolderPathsCache;\n\n/**\n * Get the folders the CMS itself may be served from: an `admin` or `cms` folder, or the folder of\n * the current admin page, at the top of the repository or right below a folder the site is served\n * from. The same name deeper down, like a Hugo page bundle `content/posts/cms`, is just a folder.\n * @returns {string[]} Normalized folder paths.\n */\nconst getCmsFolderPaths = () => {\n  const { media_folder: mediaFolder, public_folder: publicFolder } = cmsConfig.current ?? {};\n  const pathname = globalThis.location?.pathname ?? '';\n  const key = JSON.stringify([mediaFolder, publicFolder, pathname]);\n\n  if (cmsFolderPathsCache?.key !== key) {\n    const siteRootFolder = getConfiguredSiteRootFolder(mediaFolder, publicFolder);\n\n    const roots =\n      siteRootFolder === undefined ? SITE_ROOT_FOLDERS : [...SITE_ROOT_FOLDERS, siteRootFolder];\n\n    const names = [...CMS_FOLDER_NAMES, ...getAdminPageFolders(pathname)];\n\n    cmsFolderPathsCache = {\n      key,\n      paths: roots.flatMap((root) => names.map((name) => foldPath(`${root}/${name}`))),\n    };\n  }\n\n  return cmsFolderPathsCache.paths;\n};\n\n/**\n * Check whether the given folder is, or is below, a folder the CMS itself may be served from.\n * @param {string} dirPath Folder path. An empty string for the root.\n * @returns {boolean} Result.\n */\nexport const isCmsFolderPath = (dirPath) => {\n  const path = foldPath(dirPath);\n\n  return getCmsFolderPaths().some((folder) => path === folder || path.startsWith(`${folder}/`));\n};\n\n/**\n * Regular expression matching the name of a file that would take over the CMS if replaced: the\n * admin page and its configuration file.\n */\nconst CMS_FILE_NAME_REGEX = /^(?:index\\.html|config\\.(?:ya?ml|toml|json))$/;\n\n/**\n * Check whether the given file is the admin page or its configuration file in a folder named like\n * one the CMS is served from, at any depth. The site root can’t always be told from the\n * configuration, so these files are refused wherever such a folder is, while other files in a\n * folder like `content/posts/cms` are left editable.\n * @param {string} dirPath Folder path.\n * @param {string} fileName File name.\n * @returns {boolean} Result.\n */\nconst isCmsFile = (dirPath, fileName) => {\n  if (!CMS_FILE_NAME_REGEX.test(foldPath(fileName))) {\n    return false;\n  }\n\n  const names = [\n    ...CMS_FOLDER_NAMES,\n    ...getAdminPageFolders(globalThis.location?.pathname ?? '')\n      .slice(-1)\n      .map(foldPath),\n  ];\n\n  return foldPath(dirPath)\n    .split('/')\n    .some((segment) => names.includes(segment));\n};\n\n/**\n * Check whether the given file is below a folder the CMS itself may be served from, or is the admin\n * page or its configuration file in a folder named like one.\n * @param {string} path File path.\n * @returns {boolean} Result.\n */\nexport const isInCmsFolder = (path) => {\n  const index = path.lastIndexOf('/');\n  const dirPath = path.slice(0, Math.max(index, 0));\n\n  return isCmsFolderPath(dirPath) || isCmsFile(dirPath, path.slice(index + 1));\n};\n\n/**\n * Make sure none of the given files is below a folder the CMS itself may be served from, or is the\n * admin page or its configuration file in a folder named like one. The Asset Library doesn’t offer\n * to change those files, so this is only a safeguard.\n * @param {string[]} paths File paths.\n * @throws {Error} When one of them is.\n */\nexport const assertOutsideCmsFolders = (paths) => {\n  if (paths.some(isInCmsFolder)) {\n    throw new Error('Cannot change a file in a folder the CMS is served from');\n  }\n};\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { WorkflowPullRequest } from '$lib/types/private';\n */\n\n/**\n * The configured branch, if the signed-in user can’t push to it, e.g. because it’s protected and\n * only Maintainers are allowed to push on GitLab. Everything that commits to the branch directly,\n * namely entries in a collection with the simple publish mode and assets, is then read-only, while\n * Editorial Workflow still works, as it commits to a branch of its own. It’s `undefined` when the\n * user can push to the branch, or when the backend doesn’t tell.\n * @type {{ current: string | undefined }}\n */\nexport const lockedBranch = createRawState();\n\n/**\n * The configured branch, if the signed-in user can’t merge pull requests into it, e.g. because\n * it’s protected on Gitea and only some users are allowed to merge. Publishing an unpublished\n * entry merges its pull request, so the control isn’t offered then. It’s `undefined` when the user\n * can merge, or when the backend doesn’t tell for the branch as a whole: GitLab tells for each\n * merge request instead, with {@link WorkflowPullRequest.canMerge}.\n * @type {{ current: string | undefined }}\n */\nexport const mergeLockedBranch = createRawState();\n\n/**\n * Check what the user can do on the configured branch, and record it in {@link lockedBranch} and\n * {@link mergeLockedBranch}. A failed request leaves the branch writable and mergeable, as the\n * backend still refuses a push or merge the user isn’t allowed to make.\n * @param {string | undefined} branch Configured branch.\n * @param {(branch: string) => Promise<{ canPush?: boolean, canMerge?: boolean }>} fetchAccess\n * Function to fetch the user’s access to the branch. A permission it doesn’t tell is assumed.\n */\nexport const recordBranchAccess = async (branch, fetchAccess) => {\n  /** @type {{ canPush?: boolean, canMerge?: boolean }} */\n  let access = {};\n\n  if (branch) {\n    try {\n      access = await fetchAccess(branch);\n    } catch {\n      // Keep the branch writable, as said above\n    }\n  }\n\n  lockedBranch.current = access.canPush === false ? branch : undefined;\n  mergeLockedBranch.current = access.canMerge === false ? branch : undefined;\n};\n","/**\n * @import { WorkflowStatus } from '$lib/types/private';\n */\n\n/**\n * Default pull request label prefix, which can be overridden with the backend’s `cms_label_prefix`\n * option. The prefix is used to distinguish CMS-managed pull requests from others.\n * @see https://decapcms.org/docs/editorial-workflows/\n */\nexport const DEFAULT_CMS_LABEL_PREFIX = 'sveltia-cms/';\n\n/**\n * Pull request label prefixes used by Netlify CMS and Decap CMS. They are recognized when reading\n * labels, so unpublished entries created with those CMSes remain editable after migrating to\n * Sveltia CMS. New labels are always written with the configured prefix.\n */\nexport const LEGACY_CMS_LABEL_PREFIXES = ['netlify-cms/', 'decap-cms/'];\n\n/**\n * The review stages an unpublished entry moves through, ordered from the earliest to the latest.\n * These are the board columns and the options in the editor’s status menu.\n * @type {WorkflowStatus[]}\n */\nexport const WORKFLOW_STAGES = ['draft', 'pending_review', 'pending_publish'];\n\n/**\n * The review stages available to an Open Authoring contributor. They can’t merge a pull request on\n * the configured repository, so there’s no point in marking an entry ready to be published: the\n * last thing they can do is hand it over for review.\n * @type {WorkflowStatus[]}\n * @see https://sveltiacms.app/en/docs/workflows/open\n */\nexport const OPEN_AUTHORING_STAGES = ['draft', 'pending_review'];\n\n/**\n * All the Editorial Workflow statuses, including the one for a pending removal. A removal has no\n * stages to move through — it’s either carried out or called off — so it’s absent from\n * {@link WORKFLOW_STAGES}, which drives the board columns and the editor’s status menu.\n * @type {WorkflowStatus[]}\n */\nexport const WORKFLOW_STATUSES = [...WORKFLOW_STAGES, 'pending_deletion'];\n\n/**\n * Map of Editorial Workflow statuses to i18n string keys used for UI labels.\n * @type {Record<WorkflowStatus, string>}\n */\nexport const WORKFLOW_STATUS_LABELS = {\n  draft: 'status.draft',\n  pending_review: 'status.in_review',\n  pending_publish: 'status.ready',\n  pending_deletion: 'status.pending_deletion',\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { WORKFLOW_STAGES } from '$lib/services/workflow/constants';\n\n/**\n * @import { WorkflowStatus } from '$lib/types/private';\n * @import { CmsConfig, Collection, PublishModeOptions } from '$lib/types/public';\n */\n\n/**\n * Publish modes an entry can be saved with.\n * @typedef {'simple' | 'preview' | 'editorial_workflow'} PublishMode\n */\n\n/**\n * Publish mode options resolved for a collection, with the defaults filled in.\n * @typedef {object} ResolvedPublishMode\n * @property {PublishMode} type Publish mode.\n * @property {WorkflowStatus[]} stages Review stages an unpublished entry moves through, ordered\n * from the earliest to the latest. Always starts with `draft`. An entry can be published from the\n * last one. Preview mode has the drafting stage only, so an entry can be published right away.\n * @property {boolean} directPublish Whether an entry can be saved and published in one go,\n * bypassing the pull request.\n * @property {boolean} allowIncompleteDrafts Whether an entry in the drafting stage can be saved\n * with its required fields left empty.\n */\n\n/**\n * Publish modes that save a change to a pull request rather than to the configured branch.\n * @type {PublishMode[]}\n */\nconst WORKFLOW_MODES = ['preview', 'editorial_workflow'];\n\n/**\n * Turn the given `publish_mode` option value into its object form. The string form is a shorthand\n * for `{ type }`, and an empty string or a missing option says nothing at all.\n * @param {CmsConfig['publish_mode'] | Collection['publish_mode']} value Option value.\n * @returns {PublishModeOptions} Options.\n */\nconst normalizePublishMode = (value) => {\n  if (typeof value === 'string') {\n    return value ? { type: /** @type {PublishMode} */ (value) } : {};\n  }\n\n  return isObject(value) ? /** @type {PublishModeOptions} */ (value) : {};\n};\n\n/**\n * Get the review stages configured with the `stages` option, in the canonical order. The drafting\n * stage is always included: it’s where a new pull request starts. Unknown values are dropped; the\n * configuration parser reports them.\n * @param {unknown} stages Option value.\n * @returns {WorkflowStatus[]} Stages. All of them if the option isn’t a list.\n */\nconst getConfiguredStages = (stages) =>\n  Array.isArray(stages)\n    ? WORKFLOW_STAGES.filter((stage) => stage === 'draft' || stages.includes(stage))\n    : WORKFLOW_STAGES;\n\n/**\n * Get the publish mode options a collection uses. The collection-level `publish_mode` option\n * overrides the site-level one option by option, so Editorial Workflow can be enabled for some\n * collections only, or turned off for a collection while it’s enabled everywhere else, and a\n * collection can change one option while inheriting the others. Options that don’t apply to the\n * resulting publish mode are ignored.\n * @param {object} args Arguments.\n * @param {CmsConfig | undefined} args.cmsConfig Site configuration.\n * @param {Collection} [args.collection] Collection. Omit it for the site-level options, which is\n * what a collection without the option, such as the singleton collection, falls back to.\n * @returns {ResolvedPublishMode} Options.\n * @see https://github.com/decaporg/decap-cms/issues/1571\n * @see https://github.com/decaporg/decap-cms/issues/942\n */\nexport const getPublishModeOptions = ({ cmsConfig, collection }) => {\n  const {\n    type,\n    stages,\n    direct_publish: directPublish = false,\n    allow_incomplete_drafts: allowIncompleteDrafts = true,\n  } = {\n    ...normalizePublishMode(cmsConfig?.publish_mode),\n    ...normalizePublishMode(collection?.publish_mode),\n  };\n\n  // An unknown mode is reported by the configuration parser; until then, it’s the same as `simple`\n  /** @type {PublishMode} */\n  const mode = type && WORKFLOW_MODES.includes(type) ? type : 'simple';\n\n  return {\n    type: mode,\n    // A simple collection may still have pull requests, e.g. one opened by an Open Authoring\n    // contributor or before the option was changed, so they keep all the stages\n    stages: mode === 'preview' ? ['draft'] : getConfiguredStages(stages),\n    directPublish: mode !== 'simple' && directPublish === true,\n    allowIncompleteDrafts: allowIncompleteDrafts !== false,\n  };\n};\n\n/**\n * Get the publish mode a collection uses. See {@link getPublishModeOptions} for details.\n * @param {object} args Arguments.\n * @param {CmsConfig | undefined} args.cmsConfig Site configuration.\n * @param {Collection} [args.collection] Collection. Omit it for the site-level publish mode.\n * @returns {PublishMode} Publish mode. An empty string at the site level is the same as `simple`.\n */\nexport const getPublishMode = ({ cmsConfig, collection }) =>\n  getPublishModeOptions({ cmsConfig, collection }).type;\n\n/**\n * Check whether the given publish mode saves changes to a pull request: Editorial Workflow, or its\n * single-stage variant, Preview Workflow.\n * @param {PublishMode} mode Publish mode.\n * @returns {boolean} Result.\n */\nexport const isWorkflowMode = (mode) => WORKFLOW_MODES.includes(mode);\n\n/**\n * Get the scopes a publish mode can be configured for: the whole site, represented by `undefined`,\n * followed by each collection. A divider has no publish mode, so it’s left out.\n * @param {CmsConfig | undefined} cmsConfig Site configuration.\n * @returns {(Collection | undefined)[]} Scopes, to pass as `collection` to\n * {@link getPublishModeOptions}.\n */\nexport const getPublishModeScopes = (cmsConfig) => [\n  undefined,\n  // The parser runs on the raw configuration, where the collections may not be a list of objects\n  ...(Array.isArray(cmsConfig?.collections)\n    ? /** @type {Collection[]} */ (\n        cmsConfig.collections.filter(\n          (collection) => isObject(collection) && !('divider' in collection),\n        )\n      )\n    : []),\n];\n\n/**\n * Check whether a workflow is configured anywhere: for the whole site, or for at least one\n * collection. This is about the configuration alone; whether the backend implements the feature is\n * a separate matter.\n * @param {CmsConfig | undefined} cmsConfig Site configuration.\n * @returns {boolean} `true` if some content goes through Editorial Workflow or Preview Workflow.\n */\nexport const isWorkflowConfigured = (cmsConfig) =>\n  getPublishModeScopes(cmsConfig).some((collection) =>\n    isWorkflowMode(getPublishMode({ cmsConfig, collection })),\n  );\n","import { getRootDir } from '$lib/services/backends/root-dir';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { RepositoryPath } from '$lib/types/private';\n */\n\n/**\n * Prefix for Editorial Workflow branch names. Branches are named\n * `cms/[COLLECTION_NAME]/[SLUG]`, which is compatible with Netlify/Decap CMS.\n * @see https://decapcms.org/docs/editorial-workflows/\n */\nconst WORKFLOW_BRANCH_PREFIX = 'cms';\n/**\n * Maximum length of a newly generated entry slug in UTF-8 bytes, unless the `slug.maxlength` option\n * (or the legacy `slug_length` collection option) is set. It’s the default of Decap CMS 3.17,\n * which leaves 55 bytes of the common 255-byte file name limit (`NAME_MAX`) for the rest of the\n * file name: a locale suffix like `.zh-Hant` (`multiple_files` i18n structure), an extension like\n * `.markdown` and a prefix from a `path` template like `2026-10-26-` fit in there with plenty of\n * room.\n * @see https://github.com/decaporg/decap-cms/pull/7983\n */\nconst MAX_SLUG_BYTES = 200;\n/**\n * Maximum length of a branch name in UTF-8 bytes. Git itself has no limit, but GitHub refuses a ref\n * longer than 255 bytes, `refs/heads/` included, as Decap CMS notes.\n */\nconst MAX_BRANCH_BYTES = 255 - 'refs/heads/'.length;\n/**\n * Minimum length of a newly generated entry slug in UTF-8 bytes, however long the branch name\n * prefix is. Only an absurdly long collection name or `root_dir` option gets there, and a shorter\n * slug would hardly tell entries apart.\n */\nconst MIN_SLUG_BYTES = 32;\n/**\n * Text encoder to count the UTF-8 bytes of a string.\n */\nconst encoder = new TextEncoder();\n/**\n * Grapheme segmenter to cut a slug without breaking a character apart: neither a multi-byte UTF-8\n * sequence nor a sequence of code points shown as one character, like an emoji with a skin tone or\n * a letter with a combining accent.\n */\nconst segmenter = new Intl.Segmenter();\n\n/**\n * Join the segments of an Editorial Workflow branch name prefix.\n * @param {string} rootDir Root directory, or an empty string to leave it out.\n * @param {RepositoryPath | null} [fork] Fork whose path goes in the prefix, or `null` for none.\n * Default: the signed-in contributor’s fork with Open Authoring.\n * @returns {string} Prefix, including the trailing slash.\n */\nconst joinPrefix = (rootDir, fork = forkedRepository.current) =>\n  [WORKFLOW_BRANCH_PREFIX, fork?.owner, fork?.repo, rootDir]\n    .filter(Boolean)\n    .map((segment) => `${segment}/`)\n    .join('');\n\n/**\n * Get the name a branch of an Open Authoring contributor’s fork would have in the configured\n * repository, which is how the collection and the entry are read from it: the fork’s path, which\n * {@link getBranchPrefix} inserts in the contributor’s session, is taken off, so\n * `cms/alice/website/posts/hello` becomes `cms/posts/hello`. A branch named without the path is\n * taken as it is. The fork is matched regardless of case, like GitHub user and repository names.\n * @param {string} branch Branch name in the fork.\n * @param {RepositoryPath} fork Fork the branch is in.\n * @returns {string} Branch name.\n */\nexport const toUpstreamBranchName = (branch, fork) => {\n  const forkPrefix = joinPrefix('', fork);\n\n  return branch.toLowerCase().startsWith(forkPrefix.toLowerCase())\n    ? `${joinPrefix('', null)}${branch.slice(forkPrefix.length)}`\n    : branch;\n};\n\n/**\n * Get the prefix that every Editorial Workflow branch name starts with, including the trailing\n * slash. With Open Authoring the branches live in the contributor’s fork, which can hold the\n * branches of more than one project, so the fork’s path is inserted to keep them apart. That’s the\n * naming Netlify/Decap CMS uses as well, so a contributor who has used another CMS on the same fork\n * keeps their work in progress. Likewise, with the `root_dir` backend option, the directory is\n * inserted, so the sites of a monorepo don’t share a branch for collections of the same name, nor\n * list each other’s unpublished entries.\n * @returns {string} Branch name prefix, e.g. `cms/`, `cms/contributor/repo/` or\n * `cms/apps/blog/`.\n */\nconst getBranchPrefix = () => joinPrefix(getRootDir());\n\n/**\n * Get the prefix shared by every Editorial Workflow branch the CMS may have to read, which leaves\n * the `root_dir` backend option out. A branch created before the option was set doesn’t have the\n * directory in its name, but it’s still an entry of the site if its files are all in the\n * directory. Used to list the branches of a fork, which are checked one by one afterwards.\n * @returns {string} Branch name prefix, e.g. `cms/` or `cms/contributor/repo/`.\n */\nexport const getBranchListPrefix = () => joinPrefix('');\n\n/**\n * Encode an entry slug for use in a branch name. A slug in a collection with nested entries is a\n * path, and Git can’t hold a branch `cms/pages/about` alongside `cms/pages/about/us`, because the\n * former would have to be both a ref and a directory. So the slashes are percent-encoded, which\n * keeps each entry to a single path segment. `%` is encoded as well, so the encoding can be\n * reversed exactly.\n * @param {string} slug Entry slug, e.g. `about/us`.\n * @returns {string} Encoded slug, e.g. `about%2Fus`.\n */\nconst encodeSlug = (slug) => slug.replaceAll('%', '%25').replaceAll('/', '%2F');\n/**\n * Reverse {@link encodeSlug}. A slash that wasn’t encoded, as in a branch created by Netlify/Decap\n * CMS or an earlier version of Sveltia CMS, is left as it is, so such a branch still addresses its\n * entry.\n * @param {string} slug Encoded slug, e.g. `about%2Fus`.\n * @returns {string} Entry slug, e.g. `about/us`.\n */\nconst decodeSlug = (slug) => slug.replaceAll('%2F', '/').replaceAll('%25', '%');\n\n/**\n * Count the UTF-8 bytes the given slug takes up in an Editorial Workflow branch name, where a slash\n * or percent sign is encoded in three bytes.\n * @param {string} slug Entry slug.\n * @returns {number} Number of bytes.\n */\nexport const getSlugByteLength = (slug) => encoder.encode(encodeSlug(slug)).length;\n\n/**\n * Get the default maximum length of a newly generated entry slug, in the bytes counted by\n * {@link getSlugByteLength}. It’s {@link MAX_SLUG_BYTES}, or fewer if the Editorial Workflow branch\n * name, e.g. `cms/[COLLECTION_NAME]/[SLUG]`, would otherwise be too long, like Decap CMS 3.17. The\n * cap applies whether Editorial Workflow is enabled or not, so a slug doesn’t depend on the publish\n * mode, which may be changed later. Sveltia CMS also counts the prefixes Decap CMS doesn’t have —\n * the `root_dir` backend option and the folder of an entry in a collection with nested entries —\n * and counts the fork’s owner and repository with Open Authoring instead of the upstream\n * repository, as that’s what the branch name contains.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.dirPath] Folder within the collection folder the new entry goes to, as\n * chosen with the path editor of a collection with nested entries. It becomes part of the slug.\n * @returns {number} Number of bytes.\n */\nexport const getMaxSlugBytes = ({ collectionName, dirPath }) => {\n  const prefix = `${getBranchPrefix()}${collectionName}/`;\n  const dirBytes = dirPath ? getSlugByteLength(`${dirPath}/`) : 0;\n  const budget = MAX_BRANCH_BYTES - encoder.encode(prefix).length - dirBytes;\n\n  return Math.max(Math.min(MAX_SLUG_BYTES, budget), MIN_SLUG_BYTES);\n};\n\n/**\n * Cut the given slug down to the given number of bytes, counted by {@link getSlugByteLength},\n * without breaking a character apart.\n * @param {string} slug Entry slug.\n * @param {number} maxBytes Maximum number of bytes.\n * @returns {string} Slug, which is the given one if it’s short enough.\n */\nexport const truncateSlugBytes = (slug, maxBytes) => {\n  const segments = Array.from(segmenter.segment(slug), ({ segment }) => segment);\n  let bytes = 0;\n\n  const index = segments.findIndex((segment) => {\n    bytes += getSlugByteLength(segment);\n\n    return bytes > maxBytes;\n  });\n\n  return index === -1 ? slug : segments.slice(0, index).join('');\n};\n\n/**\n * Get the Editorial Workflow branch name for the given entry.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} args.slug Entry slug. It can be a path containing slashes, which are encoded.\n * @returns {string} Branch name, e.g. `cms/posts/hello-world` or `cms/pages/about%2Fus`.\n */\nexport const getBranchName = ({ collectionName, slug }) =>\n  `${getBranchPrefix()}${collectionName}/${encodeSlug(slug)}`;\n\n/**\n * Parse an Editorial Workflow branch name to get the collection name and entry slug. The slug part\n * may contain slashes when the branch was created before they were encoded, so everything after the\n * collection name belongs to it. With the `root_dir` backend option, a branch named without the\n * directory, as before the option was set, is parsed as well, but marked as `legacy`: whether it\n * belongs to the site depends on its files, as another site in the monorepo may have created it.\n * @param {string} branch Branch name.\n * @returns {{ collectionName: string, slug: string, legacy?: boolean } | undefined} Parsed result,\n * or `undefined` if the branch name is not managed by the CMS.\n */\nexport const parseBranchName = (branch) => {\n  const prefix = getBranchPrefix();\n  const listPrefix = getBranchListPrefix();\n  const legacy = !branch.startsWith(prefix);\n\n  if (legacy && (prefix === listPrefix || !branch.startsWith(listPrefix))) {\n    return undefined;\n  }\n\n  const rest = branch.slice(legacy ? listPrefix.length : prefix.length);\n  const index = rest.indexOf('/');\n\n  // Both parts have to be non-empty for the branch to address an entry\n  if (index < 1 || index === rest.length - 1) {\n    return undefined;\n  }\n\n  return {\n    collectionName: rest.slice(0, index),\n    slug: decodeSlug(rest.slice(index + 1)),\n    ...(legacy && { legacy }),\n  };\n};\n\n/**\n * Check whether the given Editorial Workflow branch addresses the given entry. The branch name is\n * parsed rather than compared with a freshly generated one, so a branch that spells the slug\n * differently, with the slashes left as they are, is matched as well.\n * @param {object} args Arguments.\n * @param {string} args.branch Branch name.\n * @param {string} args.collectionName Collection name.\n * @param {string} args.slug Entry slug.\n * @returns {boolean} `true` if the branch holds the entry.\n */\nexport const isEntryBranch = ({ branch, collectionName, slug }) => {\n  const parsed = parseBranchName(branch);\n\n  return parsed?.collectionName === collectionName && parsed.slug === slug;\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { toUpstreamBranchName } from '$lib/services/workflow/branch';\n\n/**\n * @import { Entry, ForkHead, UnpublishedEntry } from '$lib/types/private';\n */\n\n/**\n * Character that separates the fork from the branch name in the name a fork request’s branch is\n * known by. Git doesn’t allow it in a ref name, so the name can’t be mistaken for a branch of the\n * configured repository: a request that still sends it to the Git service as a ref is refused\n * rather than carried out on a branch of the same name there.\n * @see https://git-scm.com/docs/git-check-ref-format\n */\nconst SEPARATOR = ':';\n\n/**\n * Get the name a pull request opened from a fork is known by in the CMS, which qualifies its head\n * branch with the fork, e.g. `alice/website:cms/posts/hello`. Contributors working on forks name\n * their branches after the entries just like the CMS does, so the same branch name can be in use in\n * the configured repository and in any number of forks at once; the entries are told apart by it.\n * @param {object} args Arguments.\n * @param {string} args.owner Owner of the fork.\n * @param {string} args.repo Name of the fork.\n * @param {string} args.branch Head branch name in the fork.\n * @returns {string} Qualified branch name.\n */\nexport const getForkBranchName = ({ owner, repo, branch }) =>\n  `${owner}/${repo}${SEPARATOR}${branch}`;\n\n/**\n * Parse a name given by {@link getForkBranchName}. The owner can be a namespace of its own, like a\n * GitLab group with subgroups, e.g. `acme/docs/website:cms/posts/hello`, so the fork’s name is\n * whatever follows its last slash.\n * @param {string} name Branch name.\n * @returns {{ owner: string, repo: string, branch: string } | undefined} Fork and branch, or\n * `undefined` if the name is that of a branch in the repository holding the workflow branches.\n */\nexport const parseForkBranchName = (name) => {\n  const index = name.indexOf(SEPARATOR);\n\n  if (index < 0) {\n    return undefined;\n  }\n\n  const path = name.slice(0, index);\n  const slash = path.lastIndexOf('/');\n  const owner = path.slice(0, slash);\n  const repo = path.slice(slash + 1);\n  const branch = name.slice(index + 1);\n\n  if (slash < 0 || !repo || !branch || owner.split('/').some((segment) => !segment)) {\n    return undefined;\n  }\n\n  return { owner, repo, branch };\n};\n\n/**\n * Get the name a workflow branch would have in the configured repository, which is how the\n * collection and the entry are read from it. A contributor’s branch is known by a name qualified\n * with the fork (see {@link getForkBranchName}), and Open Authoring inserts the fork’s path after\n * the prefix, as Netlify/Decap CMS does, so both are taken off: `alice/website:cms/alice/website/\n * posts/hello` becomes `cms/posts/hello`. See {@link toUpstreamBranchName}.\n * @param {string} name Branch name as the CMS knows it.\n * @returns {string} Branch name.\n */\nexport const getUpstreamBranchName = (name) => {\n  const fork = parseForkBranchName(name);\n\n  return fork ? toUpstreamBranchName(fork.branch, fork) : name;\n};\n\n/**\n * Get the fork the given entry’s pull request comes from, if it’s one a contributor opened from\n * their fork and the signed-in user is reviewing it as a maintainer.\n * @param {Entry | null | undefined} entry Entry, published or not.\n * @returns {ForkHead | undefined} Fork, or `undefined` if the entry isn’t from a fork.\n */\nexport const getForkHead = (entry) =>\n  /** @type {UnpublishedEntry | undefined} */ (entry)?.workflow?.pullRequest?.fork;\n\n/**\n * Check whether the given entry comes from a pull request a contributor opened from their fork.\n * Such an entry is only reached from the Editorial Workflow board: the rest of the CMS keeps\n * showing the published version, or the maintainers’ own pull request, so a maintainer editing an\n * entry never commits to a contributor’s branch without meaning to, and a contributor can’t take an\n * entry over by opening a pull request for it.\n * @param {Entry | null | undefined} entry Entry, published or not.\n * @returns {boolean} Result.\n */\nexport const isForkEntry = (entry) => !!getForkHead(entry);\n\n/**\n * Check whether the given fork’s pull request doesn’t let maintainers push to its branch, in which\n * case its entry can only be viewed.\n * @param {ForkHead | undefined} fork Fork, or `undefined` for a pull request not from a fork.\n * @returns {boolean} Result.\n */\nexport const isLockedFork = (fork) => fork?.editable === false;\n\n/**\n * Check whether the given entry comes from a fork whose pull request doesn’t let maintainers push\n * to its branch, in which case it can only be viewed. See {@link isLockedFork}.\n * @param {Entry | null | undefined} entry Entry, published or not.\n * @returns {boolean} Result.\n */\nexport const isLockedForkEntry = (entry) => isLockedFork(getForkHead(entry));\n\n/**\n * Get the message the editor shows for an entry from a fork, which says where a save goes, or why\n * the entry can’t be saved.\n * @param {Entry | null | undefined} entry Entry being edited.\n * @returns {string | undefined} Message, or `undefined` if the entry isn’t from a fork.\n */\nexport const getForkEntryNotice = (entry) => {\n  const fork = getForkHead(entry);\n\n  if (!fork) {\n    return undefined;\n  }\n\n  const values = { fork: `${fork.owner}/${fork.repo}` };\n\n  return fork.editable\n    ? _('workflow.fork_entry_editable', { values })\n    : _('workflow.fork_entry_locked', { values });\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { getAdditions } from '$lib/services/app/additions';\nimport { lockedBranch } from '$lib/services/backends/branch-access';\nimport { cmsConfig } from '$lib/services/config/state';\nimport { user } from '$lib/services/user/account.svelte';\nimport { getPublishMode, isWorkflowMode } from '$lib/services/workflow/config';\nimport { isLockedForkEntry } from '$lib/services/workflow/forks';\n\n/**\n * @import { AssetFolderInfo, EntryDraft, InternalCmsConfig } from '$lib/types/private';\n * @import { AssetCollection, Collection, CollectionFile } from '$lib/types/public';\n */\n\n/**\n * Check whether the signed-in user is a viewer, a role given by Sveltia CMS Additions. A viewer\n * can see everything but change nothing, as if the whole CMS had the `readonly` option, and\n * GitHub refuses their writes too, as their token can only read. The role can change while the\n * user is signed in, when a token refresh reports a new one, so this is read live.\n * @returns {boolean} Result.\n */\nexport const isViewer = () => user.account?.role === 'viewer';\n\n/**\n * Check whether a collection, a collection file or the whole CMS is made read-only with the\n * `readonly` option. The option can be set globally, on a collection and on a collection file, and\n * any of them makes everything below it read-only: a collection can’t opt out while the whole CMS\n * is locked for maintenance, for example, and a file can’t while its collection is locked.\n * @param {object} [args] Arguments.\n * @param {InternalCmsConfig} [args.config] CMS configuration. Default: the current one.\n * @param {Collection | AssetCollection} [args.collection] Entry, file or asset collection.\n * @param {CollectionFile} [args.collectionFile] Collection file. File/singleton collection only.\n * @returns {boolean} Result.\n */\nexport const isConfigReadonly = ({ config = cmsConfig.current, collection, collectionFile } = {}) =>\n  !!(config?.readonly || collection?.readonly || collectionFile?.readonly);\n\n/**\n * Check whether a collection is read-only because the signed-in user can’t push to the configured\n * branch. A collection with the simple publish mode commits to the branch directly, while one with\n * Editorial Workflow or Preview Workflow commits to a branch of its own and still works.\n * @param {Collection} [collection] Collection.\n * @returns {boolean} Result.\n */\nexport const isLockedByBranch = (collection) =>\n  !!lockedBranch.current &&\n  !!collection &&\n  !isWorkflowMode(getPublishMode({ cmsConfig: cmsConfig.current, collection }));\n\n/**\n * Check whether a collection, a collection file or the whole CMS is read-only, either with the\n * `readonly` option (see {@link isConfigReadonly}), because the signed-in user can’t push to the\n * configured branch (see {@link isLockedByBranch}), or because they’re a viewer (see\n * {@link isViewer}). The role is only known once the user has signed in, so it’s checked here\n * rather than with the `readonly` option, which asset folders read while parsing the\n * configuration.\n * @param {object} [args] Arguments.\n * @param {Collection} [args.collection] Entry or file collection.\n * @param {CollectionFile} [args.collectionFile] Collection file. File/singleton collection only.\n * @returns {boolean} Result.\n */\nexport const isReadonly = ({ collection, collectionFile } = {}) =>\n  isConfigReadonly({ collection, collectionFile }) || isLockedByBranch(collection) || isViewer();\n\n/**\n * Check whether someone else is editing an entry draft: another user, or the same user in another\n * tab, holds its Sveltia CMS Additions entry lock.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {boolean} Result.\n */\nexport const isDraftLockedByOthers = (draft) => {\n  const additions = getAdditions();\n\n  return !!additions?.getOthersLock(additions.getDraftLockKey(draft));\n};\n\n/**\n * Check whether an entry draft is read-only because its collection or collection file is, or the\n * whole CMS is.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {boolean} Result.\n */\nexport const isDraftConfigReadonly = (draft) =>\n  !!draft && isReadonly({ collection: draft.collection, collectionFile: draft.collectionFile });\n\n/**\n * Check whether an entry draft is read-only, which is when its collection or collection file is,\n * or the whole CMS is (see {@link isDraftConfigReadonly}), while the user is being asked whether to\n * restore a backup of it, when it comes from a contributor’s pull request that doesn’t let\n * maintainers push to its branch, or while someone else is editing the entry (see\n * {@link isDraftLockedByOthers}). The draft can be viewed but not changed or saved.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {boolean} Result.\n */\nexport const isDraftReadonly = (draft) =>\n  !!draft?.restorePending ||\n  isDraftConfigReadonly(draft) ||\n  isLockedForkEntry(draft?.originalEntry) ||\n  isDraftLockedByOthers(draft);\n\n/**\n * Get the message that says something is read-only. The whole CMS being read-only is what users\n * most need to know, e.g. during maintenance, so that message takes precedence. Otherwise a target\n * made read-only with the `readonly` option gets the message for its scope, and one that is only\n * read-only because the user can’t push to the branch gets a message naming the branch.\n * @param {'collection' | 'entry' | 'asset_folder'} scope What is read-only.\n * @param {object} [target] What is read-only.\n * @param {Collection} [target.collection] Collection of the collection or entry.\n * @param {CollectionFile} [target.collectionFile] Collection file of the entry.\n * @param {AssetFolderInfo} [target.folder] Asset folder.\n * @returns {string} Message.\n */\nexport const getReadonlyMessage = (scope, { collection, collectionFile, folder } = {}) => {\n  if (cmsConfig.current?.readonly) {\n    return _('readonly_cms');\n  }\n\n  if (isViewer()) {\n    return _('readonly_role');\n  }\n\n  const configReadonly =\n    scope === 'asset_folder'\n      ? !!folder?.readonly\n      : isConfigReadonly({ collection, collectionFile });\n\n  if (!configReadonly && lockedBranch.current) {\n    return _('readonly_branch', { values: { branch: lockedBranch.current } });\n  }\n\n  return _(`readonly_${scope}`);\n};\n","import { getPathInfo } from '@sveltia/utils/file';\nimport { escapeRegExp } from '@sveltia/utils/string';\n\nimport { isInCmsFolder } from '$lib/services/assets/reserved';\nimport { lockedBranch } from '$lib/services/backends/branch-access';\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport { getTemplatePattern } from '$lib/services/common/template/utils';\nimport { isViewer } from '$lib/services/config/readonly';\nimport { getCustomComponentName } from '$lib/services/contents/fields/rich-text/components/definitions';\nimport {\n  getLocaleFolderPattern,\n  hasLocalePlaceholder,\n} from '$lib/services/contents/i18n/placeholder';\nimport { memoizeOnSource } from '$lib/services/utils/cache';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { Asset, AssetFolderInfo, TypedFieldKeyPath } from '$lib/types/private';\n */\n\n/**\n * List of all asset folders.\n * @type {{ current: AssetFolderInfo[] }}\n */\nexport const allAssetFolders = createRawState([]);\n\n/**\n * Global asset folder. A field-level folder in a custom editor component doesn’t belong to a\n * collection either, and comes first when the global `media_folder` option isn’t configured.\n */\nexport const globalAssetFolder = createDerivedState(\n  () =>\n    /** @type {AssetFolderInfo | undefined} */ (\n      allAssetFolders.current.find(\n        ({ collectionName, componentName, typedKeyPath, internalPath }) =>\n          collectionName === undefined &&\n          componentName === undefined &&\n          typedKeyPath === undefined &&\n          internalPath !== undefined,\n      )\n    ),\n);\n\n/**\n * Selected asset folder.\n * @type {{ current: AssetFolderInfo | undefined }}\n */\nexport const selectedAssetFolder = createRawState();\n\n/**\n * Upload target asset folder.\n */\nexport const targetAssetFolder = createDerivedState(() => {\n  const { current: _selectedAssetFolder } = selectedAssetFolder;\n\n  // When selecting All Assets folder, the `internalPath` will be `undefined`\n  return _selectedAssetFolder?.internalPath !== undefined\n    ? _selectedAssetFolder\n    : globalAssetFolder.current;\n});\n\n/**\n * Get an asset folder that matches the given conditions.\n * @param {object} cond Conditions.\n * @param {string} [cond.collectionName] Collection name.\n * @param {string} [cond.fileName] Collection file name. File/singleton collection only.\n * @param {string} [cond.componentName] Custom editor component name for a field-level asset folder.\n * @param {TypedFieldKeyPath} [cond.typedKeyPath] Field key path. Required for field-level media\n * folders.\n * @param {boolean} [cond.isIndexFile] Whether the asset folder is for the special index file used\n * specifically in Hugo. It works only for field-level media folders in an entry collection.\n * @returns {AssetFolderInfo | undefined} Asset folder information if found.\n */\nexport const getAssetFolder = (cond) => {\n  const typedKeyPath =\n    'typedKeyPath' in cond\n      ? // Extract the actual key path, e.g. `body:c55:content` -> `content`\n        cond.typedKeyPath?.match(/[^:]+$/)?.[0]\n      : cond.typedKeyPath;\n\n  return allAssetFolders.current.find((folder) => {\n    if (!('typedKeyPath' in cond ? folder.typedKeyPath === typedKeyPath : !folder.typedKeyPath)) {\n      return false;\n    }\n\n    // If the condition has a `componentName`, it is a field-level media folder for a custom editor\n    // component. In that case, the `collectionName` and `fileName` are not relevant for the match.\n    // The folder is registered with the component name, while the fields within the component get\n    // the prefixed component ID, e.g. `x-youtube`, so resolve it first. Callers pass the key even\n    // when there is no component, so check the value rather than the key\n    if (cond.componentName) {\n      return (\n        folder.componentName === (getCustomComponentName(cond.componentName) ?? cond.componentName)\n      );\n    }\n\n    // A field-level folder stores `isIndexFile: false`, while callers may pass `undefined`\n    return (\n      folder.collectionName === cond.collectionName &&\n      folder.fileName === cond.fileName &&\n      !!folder.isIndexFile === !!cond.isIndexFile\n    );\n  });\n};\n\n/**\n * Build a regular expression matching the paths below an entry-relative folder, which are the\n * collection’s own files and the assets stored alongside them. With the `multiple_root_folders`\n * i18n structure the collection folder sits below a folder named after the locale, so a locale name\n * is allowed in front of it — optionally, because `omit_default_locale_from_file_path` leaves the\n * default locale’s files where they would be without i18n. A collection `folder` with the\n * `{{locale}}` placeholder says where the locale name goes instead.\n * @param {AssetFolderInfo} folder Asset folder.\n * @returns {RegExp} Regular expression.\n */\nconst getEntryRelativePathRegEx = ({ internalPath, internalSubPath, localeFolderNames }) => {\n  const localeMatcher = localeFolderNames?.length\n    ? `(?:(?:${localeFolderNames.map(escapeRegExp).join('|')})\\\\/)?`\n    : '';\n\n  const folderPath = /** @type {string} */ (internalPath);\n\n  if (hasLocalePlaceholder(folderPath)) {\n    return new RegExp(`^${getLocaleFolderPattern(folderPath, localeMatcher)}`);\n  }\n\n  if (folderPath) {\n    return new RegExp(`^${localeMatcher}${escapeRegExp(folderPath)}\\\\/`);\n  }\n\n  // A collection at the repository root, e.g. `folder: .`, has an empty folder path, below which\n  // every file in the repository would count as its asset. Limit the folder to its media subfolder\n  // instead, e.g. `images/` and the folders below it for `media_folder: images`. An entry in a\n  // subfolder of a collection with nested entries keeps its own `images` folder there, which is\n  // left out, since any folder named like that would match. Media stored next to the entries (no\n  // subfolder), out of the repository (`../`) or in a folder named after each entry (a leading tag\n  // like `{{slug}}`) can’t be told apart from the other files in the repository, so the folder\n  // matches nothing then\n  const subPath = /** @type {string} */ (internalSubPath);\n  const [firstSegment] = subPath.split('/');\n\n  if (!firstSegment || firstSegment === '..' || hasTemplateTags(firstSegment)) {\n    return /(?!)/;\n  }\n\n  // A template tag further down matches one folder name, e.g. `images/{{slug}}`\n  const subPathPattern = getTemplatePattern(subPath, '[^/]+');\n\n  return new RegExp(`^${localeMatcher}${subPathPattern}\\\\/`);\n};\n\n/**\n * Index of `allAssetFolders` for {@link getAssetFoldersByPath} to avoid recreating regexes on every\n * call, rebuilt when the store is replaced.\n * `items`: non-entry-relative folders with both regex variants pre-compiled.\n * `entryRelative`: folders whose paths are relative to their parent entry.\n * `matchesByDir`: the `items` folders matching a directory, keyed by whether subfolders are\n * matched, then by the directory. Thousands of files share a few hundred directories, and every\n * file is looked up on each load, so the regexes are only tested once per directory.\n * @type {() => {\n * items: Array<{ folder: AssetFolderInfo, regexSub: RegExp, regexExact: RegExp }>,\n * entryRelative: Array<{ folder: AssetFolderInfo, regex: RegExp }>,\n * matchesByDir: { sub: Map<string, AssetFolderInfo[]>, exact: Map<string, AssetFolderInfo[]> },\n * }}\n */\nconst getAssetFolderPathCache = memoizeOnSource(\n  () => allAssetFolders.current,\n  (_allAssetFolders) => {\n    /** @type {Array<{ folder: AssetFolderInfo, regexSub: RegExp, regexExact: RegExp }>} */\n    const items = [];\n    /** @type {Array<{ folder: AssetFolderInfo, regex: RegExp }>} */\n    const entryRelative = [];\n\n    _allAssetFolders.forEach((folder) => {\n      const { internalPath, entryRelative: isRelative } = folder;\n\n      if (internalPath === undefined) {\n        return;\n      }\n\n      if (isRelative) {\n        entryRelative.push({ folder, regex: getEntryRelativePathRegEx(folder) });\n      } else {\n        // Pre-compile both regex variants so we don’t recreate them on every path lookup.\n        // The internal path can contain template tags like `{{slug}}`, which we normalize to `.+?`.\n        const normalizedPath = getTemplatePattern(internalPath, '.+?');\n\n        items.push({\n          folder,\n          // Match the end of the folder segment for sub-folder matching.\n          regexSub: new RegExp(`^${normalizedPath}${internalPath ? '(?=\\\\/|$)' : '$'}`),\n          regexExact: new RegExp(`^${normalizedPath}$`),\n        });\n      }\n    });\n\n    return { items, entryRelative, matchesByDir: { sub: new Map(), exact: new Map() } };\n  },\n);\n\n/**\n * Get collection asset folders that match the given path.\n * @param {string} path Asset path.\n * @param {object} [options] Options.\n * @param {boolean} [options.matchSubFolders] Whether to match assets stored in the subfolders of a\n * global/collection internal path. Default: `true`. If `false`, for example, if the given `path` is\n * `images/products/image.jpg`, it matches the `images/products` folder but not `images`.\n * @returns {AssetFolderInfo[]} Asset folders.\n */\nexport const getAssetFoldersByPath = (path, { matchSubFolders = true } = {}) => {\n  const { filename, dirname } = getPathInfo(path);\n\n  // Exclude files with a leading `+` sign, which are Svelte page/layout files\n  if (filename.startsWith('+')) {\n    return [];\n  }\n\n  const { items, entryRelative, matchesByDir } = getAssetFolderPathCache();\n  const dir = dirname ?? '';\n  const dirMatches = matchSubFolders ? matchesByDir.sub : matchesByDir.exact;\n  let itemMatches = dirMatches.get(dir);\n\n  if (!itemMatches) {\n    // Compare that the enclosing directory is exactly the same as the internal path, and ignore\n    // any subdirectories, unless the `matchSubFolders` option is specified.\n    itemMatches = items\n      .filter(({ regexSub, regexExact }) => (matchSubFolders ? regexSub : regexExact).test(dir))\n      .map(({ folder }) => folder);\n    dirMatches.set(dir, itemMatches);\n  }\n\n  const results = [\n    ...entryRelative.filter(({ regex }) => regex.test(path)).map(({ folder }) => folder),\n    ...itemMatches,\n  ];\n\n  // `internalPath` is always a string for items in results (entry-relative items are filtered to\n  // those with defined `internalPath`, and global-folder items always have `internalPath` set).\n  return results.sort((a, b) =>\n    /** @type {string} */ (b.internalPath).localeCompare(/** @type {string} */ (a.internalPath)),\n  );\n};\n\n/**\n * Get a key that identifies an asset folder in a list. The All Assets folder has no internal path,\n * while the Global Assets folder has an empty one when the global `media_folder` is the root\n * folder, so the values are serialized as JSON, which tells `undefined` and `''` apart. Every\n * property that can tell two folders apart is included, e.g. a custom editor component’s folder\n * can share the internal path of the Global Assets folder with a different public path.\n * @param {AssetFolderInfo} assetFolder Asset folder.\n * @returns {string} Key.\n * @see https://github.com/sveltia/sveltia-cms/issues/1078\n */\nexport const getAssetFolderKey = ({\n  collectionName,\n  fileName,\n  componentName,\n  typedKeyPath,\n  isIndexFile,\n  internalPath,\n  internalSubPath,\n  publicPath,\n}) =>\n  JSON.stringify([\n    collectionName,\n    fileName,\n    componentName,\n    typedKeyPath,\n    isIndexFile,\n    internalPath,\n    internalSubPath,\n    publicPath,\n  ]);\n\n/**\n * Check if asset creation is allowed in the folder. Can’t upload assets if collection assets are\n * saved at entry-relative paths, the asset folder contains template tags, or the folder is\n * read-only.\n * @param {AssetFolderInfo | undefined} assetFolder Asset folder.\n * @returns {boolean} Result.\n */\nexport const canCreateAsset = (assetFolder) =>\n  !!assetFolder &&\n  !assetFolder.entryRelative &&\n  !assetFolder.hasTemplateTags &&\n  !assetFolder.readonly;\n\n/**\n * Whether the media library can’t be changed. Uploading, replacing, renaming, moving and deleting\n * assets, and creating folders, commit straight to the configured branch rather than going through\n * review, which neither an Open Authoring contributor nor a user who can’t push to the branch can\n * do. An asset attached to an entry is committed with that entry, so it’s unaffected. A viewer\n * can’t change anything at all.\n */\nexport const assetsLocked = createDerivedState(\n  () => openAuthoring.current || !!lockedBranch.current || isViewer(),\n);\n\n/**\n * Paths of the read-only asset folders with a fixed path, rebuilt when the store is replaced.\n * @type {() => Set<string>}\n */\nconst getReadonlyFolderPaths = memoizeOnSource(\n  () => allAssetFolders.current,\n  (_allAssetFolders) =>\n    new Set(\n      _allAssetFolders\n        .filter(({ readonly, entryRelative }) => readonly && !entryRelative)\n        .map(({ internalPath }) => /** @type {string} */ (internalPath)),\n    ),\n);\n\n/**\n * Check if any of the given assets is stored in a read-only folder, in which case none of them can\n * be changed, renamed, replaced or deleted along with the others. An asset is assigned to one\n * folder only, but it’s also listed in the other folders with the same path, so it’s read-only when\n * any of them is, e.g. a read-only asset collection sharing a collection’s folder. A file in a\n * folder the CMS itself is served from, such as `admin`, is read-only as well, wherever the media\n * folder is.\n * @param {Asset[]} assets Assets.\n * @returns {boolean} Result.\n */\nexport const hasReadonlyAsset = (assets) =>\n  assets.some(\n    ({ folder, path }) =>\n      !!folder?.readonly ||\n      (!folder?.entryRelative &&\n        getReadonlyFolderPaths().has(/** @type {string} */ (folder?.internalPath))) ||\n      isInCmsFolder(path),\n  );\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { allAssetFolders } from '$lib/services/assets/folders';\nimport { allEntryFolders } from '$lib/services/contents';\n\n/**\n * The parts of the repository the CMS manages: the folders holding entries and assets, and the\n * files of file collections. Paths are relative to the configured root directory.\n * @typedef {object} ManagedPaths\n * @property {string[]} dirs Folders to list recursively. None of them is inside another.\n * @property {string[]} files Files outside those folders.\n */\n\n/**\n * Get the part of the given path before its first template tag, such as `{{locale}}`, which is\n * the folder all the paths it stands for share.\n * @param {string} path Path, possibly with template tags.\n * @returns {string} Static part of the path, without a trailing slash. Empty if the path starts\n * with a tag.\n */\nconst getStaticPrefix = (path) => {\n  const segments = path.split('/');\n  const index = segments.findIndex((segment) => segment.includes('{{'));\n\n  return (index === -1 ? segments : segments.slice(0, index)).join('/');\n};\n\n/**\n * Check whether the given path is the given folder or inside it.\n * @param {string} path Path.\n * @param {string} dir Folder path.\n * @returns {boolean} Result.\n */\nconst isWithin = (path, dir) => path === dir || path.startsWith(`${dir}/`);\n\n/**\n * Collect the paths of the files and folders the CMS manages, as the collections and the asset\n * folders configure them. The paths are not normalized and may have template tags.\n * @returns {{ filePaths: string[], folderPaths: string[] }} Paths of the files of file\n * collections, and of the folders holding entries and assets.\n */\nexport const collectConfiguredPaths = () => {\n  /** @type {string[]} */\n  const filePaths = [];\n  /** @type {string[]} */\n  const folderPaths = [];\n\n  allEntryFolders.current.forEach(({ filePathMap, folderPathMap }) => {\n    if (filePathMap) {\n      filePaths.push(...Object.values(filePathMap));\n    } else {\n      folderPaths.push(...Object.values(folderPathMap ?? {}));\n    }\n  });\n\n  allAssetFolders.current.forEach(({ internalPath }) => {\n    // The All Assets folder has no path of its own\n    if (internalPath !== undefined) {\n      folderPaths.push(internalPath);\n    }\n  });\n\n  return { filePaths, folderPaths };\n};\n\n/**\n * Work out which parts of the repository hold what the CMS manages, so a backend that lists files\n * a page at a time can list just those rather than the whole repository. Everything else, such as\n * the site’s templates, source code or dependencies, is left out of the file list anyway. This is\n * what the local backend scans as well.\n * @returns {ManagedPaths | undefined} Folders and files to list, or `undefined` if one of the\n * folders is the root directory itself, in which case the whole of it has to be listed.\n */\nexport const getManagedPaths = () => {\n  const { filePaths: configuredFilePaths, folderPaths } = collectConfiguredPaths();\n  // A file path with a template tag left in it stands for files in more than one folder\n  const filePaths = configuredFilePaths.filter((path) => !path.includes('{{'));\n  const dirPaths = [...configuredFilePaths.filter((path) => path.includes('{{')), ...folderPaths];\n  const prefixes = dirPaths.map((path) => getStaticPrefix(stripSlashes(path)));\n\n  if (prefixes.some((prefix) => !prefix)) {\n    return undefined;\n  }\n\n  const dirs = [...new Set(prefixes)]\n    // A folder outside the root directory isn’t listed, as its files are dropped from the list\n    .filter((prefix) => !prefix.startsWith('../'))\n    .sort()\n    // Sorted, a folder comes right before the ones inside it, which are listed along with it\n    .filter((prefix, index, list) => !list.slice(0, index).some((dir) => isWithin(prefix, dir)));\n\n  const files = [...new Set(filePaths.map((path) => stripSlashes(path)))].filter(\n    (path) => !path.startsWith('../') && !dirs.some((dir) => isWithin(path, dir)),\n  );\n\n  return { dirs, files };\n};\n","/* eslint-disable no-continue */\n/* eslint-disable no-restricted-syntax */\n\nimport { unique } from '@sveltia/utils/array';\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport { TEMP_FILE_PREFIX } from '$lib/services/backends/fs/shared/constants';\nimport { GIT_CONFIG_FILE_REGEX } from '$lib/services/backends/git/shared/config';\nimport { collectConfiguredPaths } from '$lib/services/backends/git/shared/managed-paths';\nimport { getTemplatePattern } from '$lib/services/common/template/utils';\nimport { createPathRegEx } from '$lib/services/utils/file';\nimport { createConcurrencyLimiter } from '$lib/services/utils/scheduling';\n\n/**\n * @import { BaseFileListItemProps } from '$lib/types/private';\n */\n\n/**\n * File handle item containing metadata and handle reference.\n * @typedef {object} FileHandleItem\n * @property {FileSystemFileHandle} handle File system handle.\n * @property {string} path Path to the file.\n */\n\n/**\n * How old a temporary file has to be, in milliseconds, before it’s considered left behind by a save\n * that never finished, e.g. because a dev server reloaded the page in the middle of it. A younger\n * one may belong to a save in progress in another tab.\n */\nconst STALE_TEMP_FILE_AGE = 60 * 1000;\n/**\n * Limit the directories being listed at the same time. A site with a directory per entry, such as\n * Hugo page bundles, has thousands of them, which would otherwise all be listed at once.\n */\nconst limitDirListing = createConcurrencyLimiter(8);\n\n/**\n * Create a regular expression that matches the given path, taking template tags into account.\n * @param {string} path Path.\n * @returns {RegExp} RegEx.\n */\nexport const getPathRegex = (path) => {\n  // Handle empty path (root folder) - match any file\n  if (!path) {\n    return /^.+$/;\n  }\n\n  return createPathRegEx(path, (segment) => getTemplatePattern(segment, '.+?'));\n};\n\n/**\n * Create a regular expression that matches the given path and each of the folders leading to it,\n * e.g. `static`, `static/posts` and `static/posts/images` for `static/{{dirname}}/images`. A\n * template tag can stand for more than one segment, e.g. `{{dirname}}` for `blog/2024`, so a\n * folder of any depth matches where a segment has one.\n * @param {string} path Path.\n * @returns {RegExp} RegEx.\n */\nexport const getPathPrefixRegex = (path) => {\n  const pattern = path\n    .split('/')\n    .map((segment) => getTemplatePattern(segment, '.+?'))\n    // Each segment after the first is optional, along with all the segments after it\n    .reduceRight(\n      (rest, segment, index) => (index === 0 ? `${segment}${rest}` : `(?:\\\\/${segment}${rest})?`),\n      '',\n    );\n\n  return new RegExp(`^${pattern}$`);\n};\n\n/**\n * Check whether the given folder leads to one of the scanning paths, being the path itself or one\n * of the folders on the way to it.\n * @param {string} path Folder path, in Unicode normalization form C.\n * @param {string[]} scanningPaths Scanning paths.\n * @param {Map<string, RegExp>} pathRegexCache Cache for the regexes of the scanning paths.\n * @returns {boolean} Result.\n */\nconst leadsToScanningPath = (path, scanningPaths, pathRegexCache) =>\n  scanningPaths.some((scanningPath) => {\n    // Cache regex creation to avoid recreating for the same path\n    let regex = pathRegexCache.get(scanningPath);\n\n    if (!regex) {\n      regex = getPathPrefixRegex(scanningPath);\n      pathRegexCache.set(scanningPath, regex);\n    }\n\n    return regex.test(path);\n  });\n\n/**\n * Delete a temporary file left behind by a save that never finished. When the page is reloaded in\n * the middle of a save, e.g. by a dev server that watches the content files, the temporary file\n * isn’t renamed to its final name, and nothing else would ever remove it. The content isn’t lost,\n * because the draft backup is only deleted once the save is complete.\n * @param {FileSystemDirectoryHandle} dirHandle Directory containing the file.\n * @param {FileSystemFileHandle} fileHandle Temporary file handle.\n */\nconst deleteStaleTempFile = async (dirHandle, fileHandle) => {\n  try {\n    const { lastModified } = await fileHandle.getFile();\n\n    if (Date.now() - lastModified >= STALE_TEMP_FILE_AGE) {\n      await dirHandle.removeEntry(fileHandle.name);\n    }\n  } catch {\n    // The file may have been renamed or removed in the meantime, e.g. by a save in another tab\n  }\n};\n\n/**\n * Retrieve all the files under the given directory recursively. The subdirectories are scanned at\n * the same time rather than one after another, while the files are still listed in the order they\n * are found in, with the files of a subdirectory where the subdirectory is.\n * @param {FileSystemDirectoryHandle} dirHandle Directory handle.\n * @param {object} context Context object.\n * @param {FileSystemDirectoryHandle} context.rootDirHandle Root directory handle.\n * @param {string[]} context.scanningPaths Scanning paths.\n * @param {RegExp[]} context.scanningPathsRegEx Regular expressions for scanning paths.\n * @param {FileHandleItem[]} context.fileHandles List of available file handles, appended to once\n * the directory has been scanned.\n * @param {Map<string, RegExp>} context.pathRegexCache Cache for the regexes matching the folders\n * leading to each scanning path.\n * @param {string} [currentPath] Current directory path (for recursion).\n */\nexport const scanDir = async (dirHandle, context, currentPath = '') => {\n  const { scanningPaths, scanningPathsRegEx, fileHandles, pathRegexCache } = context;\n  /**\n   * The files found, in order, with the files of each subdirectory in a list of their own, which\n   * is filled in as the subdirectory is scanned.\n   * @type {(FileHandleItem | FileHandleItem[])[]}\n   */\n  const items = [];\n  /**\n   * Subdirectories to scan, each with the list its files go to.\n   * @type {{ handle: FileSystemDirectoryHandle, path: string, fileHandles: FileHandleItem[] }[]}\n   */\n  const subdirectories = [];\n\n  // The subdirectories are only scanned once the directory has been listed, so a directory doesn’t\n  // hold a listing slot while waiting for its subdirectories, which could use up every slot\n  await limitDirListing(async () => {\n    for await (const [name, handle] of dirHandle.entries()) {\n      // Skip hidden files and directories, except for Git configuration files and a directory a\n      // configured path names, e.g. `.vuepress` in `docs/.vuepress/public/images`, which the Git\n      // backends list as well. Others, like `.git`, are never scanned, even under a folder at the\n      // root of the repository\n      if (\n        name.startsWith('.') &&\n        !GIT_CONFIG_FILE_REGEX.test(name) &&\n        !(handle.kind === 'directory' && scanningPaths.some((p) => p.split('/').includes(name)))\n      ) {\n        if (handle.kind === 'file' && name.startsWith(TEMP_FILE_PREFIX)) {\n          await deleteStaleTempFile(dirHandle, /** @type {FileSystemFileHandle} */ (handle));\n        }\n\n        continue;\n      }\n\n      const path = currentPath ? `${currentPath}/${name}` : name;\n      // The configured paths are matched in Unicode normalization form C, so a file or folder whose\n      // name is in form D on the disk is found as well\n      const normalizedPath = path.normalize();\n      const hasMatchingPath = scanningPathsRegEx.some((regex) => regex.test(normalizedPath));\n\n      if (handle.kind === 'file' && hasMatchingPath) {\n        // Store only the handle and path. Metadata will be extracted later when needed, avoiding\n        // memory leaks from holding multiple file references during directory scanning.\n        items.push({\n          handle: /** @type {FileSystemFileHandle} */ (handle),\n          path,\n        });\n      }\n\n      // Descend into a folder inside a scanning path, or one leading to a scanning path, which can\n      // have template tags in the middle, e.g. `static/posts` for `static/{{dirname}}/images`\n      if (\n        handle.kind === 'directory' &&\n        (hasMatchingPath || leadsToScanningPath(normalizedPath, scanningPaths, pathRegexCache))\n      ) {\n        /** @type {FileHandleItem[]} */\n        const subdirFileHandles = [];\n\n        items.push(subdirFileHandles);\n        subdirectories.push({\n          handle: /** @type {FileSystemDirectoryHandle} */ (handle),\n          path,\n          fileHandles: subdirFileHandles,\n        });\n      }\n    }\n  });\n\n  await Promise.all(\n    subdirectories.map(({ handle, path, fileHandles: subdirFileHandles }) =>\n      scanDir(handle, { ...context, fileHandles: subdirFileHandles }, path),\n    ),\n  );\n\n  items.forEach((item) => {\n    // Appended one by one, as spreading a long list into `push()` can overflow the call stack\n    (Array.isArray(item) ? item : [item]).forEach((fileHandle) => {\n      fileHandles.push(fileHandle);\n    });\n  });\n};\n\n/**\n * Collect all scanning paths from entry and asset folders.\n * @returns {string[]} Unique list of scanning paths, without leading and trailing slashes, in\n * Unicode normalization form C.\n */\nexport const collectScanningPaths = () => {\n  const { filePaths, folderPaths } = collectConfiguredPaths();\n\n  return unique([...filePaths, ...folderPaths].map((path) => stripSlashes(path).normalize()));\n};\n\n/**\n * Retrieve all files under the static directory.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @returns {Promise<BaseFileListItemProps[]>} File list.\n */\nexport const getAllFiles = async (rootDirHandle) => {\n  /** @type {FileHandleItem[]} */\n  const fileHandles = [];\n  const scanningPaths = collectScanningPaths();\n\n  await scanDir(rootDirHandle, {\n    rootDirHandle,\n    scanningPaths,\n    scanningPathsRegEx: scanningPaths.map(getPathRegex),\n    fileHandles,\n    pathRegexCache: new Map(),\n  });\n\n  return fileHandles.map(({ handle, path }) => ({\n    handle,\n    path: path.normalize(),\n    name: handle.name.normalize(),\n    size: 0, // Will be populated later\n    sha: '', // Will be populated later\n  }));\n};\n","/**\n * Keep a promise that is awaited later from being reported as an unhandled rejection in the\n * meantime. The rejection is still delivered to whoever awaits the promise.\n * @template T\n * @param {Promise<T>} promise Promise.\n * @returns {Promise<T>} The same promise.\n */\nexport const deferRejection = (promise) => {\n  promise.catch(() => {\n    // Handled where the promise is awaited\n  });\n\n  return promise;\n};\n","import { getAssetFoldersByPath } from '$lib/services/assets/folders';\nimport { GIT_CONFIG_FILE_REGEX } from '$lib/services/backends/git/shared/config';\nimport { isIndexFile } from '$lib/services/contents/file/process';\nimport { getEntryFoldersByPath } from '$lib/services/contents/folders';\n\n/**\n * @import {\n * BaseAssetListItem,\n * BaseConfigListItem,\n * BaseEntryListItem,\n * BaseFileList,\n * BaseFileListItemProps,\n * } from '$lib/types/private';\n */\n\n/**\n * Parse a list of all files on the repository/filesystem to create entry and asset lists, with the\n * relevant collection/file configuration added.\n * @param {BaseFileListItemProps[]} files Unfiltered file list.\n * @returns {BaseFileList} File list, including both entries and assets.\n */\nexport const createFileList = (files) => {\n  /** @type {BaseEntryListItem[]} */\n  const entryFiles = [];\n  /** @type {BaseAssetListItem[]} */\n  const assetFiles = [];\n  /** @type {BaseConfigListItem[]} */\n  const configFiles = [];\n  /**\n   * Paths already listed as entries. This runs over every file in the repository, so membership\n   * needs to be O(1); scanning `entryFiles` per file would make the initial load O(files²).\n   * @type {Set<string>}\n   */\n  const entryPaths = new Set();\n\n  files.forEach((fileInfo) => {\n    const { path, name } = fileInfo;\n\n    if (name.startsWith('.')) {\n      // Correct Git config files that we need, such as `.gitattributes` and `.gitkeep`, to enable\n      // some features like Git LFS tracking and assets folder creation\n      if (GIT_CONFIG_FILE_REGEX.test(name)) {\n        configFiles.push({ ...fileInfo, type: 'config' });\n      }\n    } else {\n      const [entryFolder] = getEntryFoldersByPath(path);\n\n      // Correct entry files\n      if (entryFolder) {\n        entryFiles.push({ ...fileInfo, type: 'entry', folder: entryFolder });\n        entryPaths.add(path);\n\n        return;\n      }\n\n      // Correct asset files while excluding files already listed as entries. These files can appear\n      // in the file list when a relative media path is configured for a collection. Also exclude\n      // Hugo’s special index files. The asset folder is only looked up once the file is known not\n      // to be an entry, as the lookup tests the path against every asset folder\n      if (entryPaths.has(path) || isIndexFile(path)) {\n        return;\n      }\n\n      const [assetFolder] = getAssetFoldersByPath(path);\n\n      if (assetFolder) {\n        assetFiles.push({ ...fileInfo, type: 'asset', folder: assetFolder });\n      }\n    }\n  });\n\n  const allFiles = [...entryFiles, ...assetFiles, ...configFiles];\n\n  return { entryFiles, assetFiles, configFiles, allFiles, count: allFiles.length };\n};\n\n/**\n * Describe a file list for a debug message, e.g. `10 entry files, 2 asset files, 1 config files`.\n * @param {Pick<BaseFileList, 'entryFiles' | 'assetFiles' | 'configFiles'>} fileList File list.\n * @returns {string} Description.\n */\nexport const describeFileList = ({ entryFiles, assetFiles, configFiles }) =>\n  `${entryFiles.length} entry files, ${assetFiles.length} asset files, ` +\n  `${configFiles.length} config files`;\n","/**\n * @typedef {(message: string, ...details: any[]) => void} DebugLogger Function that logs one step\n * of a process to the browser console, with any extra details appended as they are.\n */\n\n/**\n * Create a logger that traces a long-running process, such as the initial site data loading, in\n * the browser console. Every message goes out at the `debug` level, which the console hides until\n * it’s set to show verbose output, so the trace costs nothing unless someone is looking for it —\n * typically a user asked to report where a slow start spends its time. Each message is prefixed\n * with the scope and suffixed with the time since the previous message and since the logger was\n * created, so the slow step stands out without a stopwatch.\n * @param {string} scope Label for the process, prefixed to every message.\n * @returns {DebugLogger} Logger.\n */\nexport const createDebugLogger = (scope) => {\n  const startTime = performance.now();\n  let lastTime = startTime;\n\n  return (message, ...details) => {\n    const now = performance.now();\n    const step = Math.round(now - lastTime);\n    const total = Math.round(now - startTime);\n\n    lastTime = now;\n\n    // eslint-disable-next-line no-console\n    console.debug(`[${scope}] ${message} (+${step} ms, ${total} ms total)`, ...details);\n  };\n};\n","import { readAsText } from '@sveltia/utils/file';\n\nimport { getAssetKind } from '$lib/services/assets/kinds';\nimport { allAssets } from '$lib/services/assets/state';\nimport { getAllFiles } from '$lib/services/backends/fs/shared/scan';\nimport { mapConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { gitConfigFiles } from '$lib/services/backends/git/shared/config';\nimport { deferRejection } from '$lib/services/backends/git/shared/defer';\nimport { createFileList, describeFileList } from '$lib/services/backends/process';\nimport { allEntries, dataLoaded, entryParseErrors } from '$lib/services/contents';\nimport { prepareEntries } from '$lib/services/contents/file/process';\nimport { readCacheEntries, updateCacheEntries } from '$lib/services/utils/database';\nimport { getGitHash } from '$lib/services/utils/file';\nimport { createDebugLogger } from '$lib/services/utils/logging';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * Asset,\n * BaseAssetListItem,\n * BaseConfigListItem,\n * BaseEntryListItem,\n * BaseFileListItem,\n * } from '$lib/types/private';\n */\n\n/**\n * Cached Git object ID of an asset file, along with the file’s size and modification time at the\n * time it was hashed. The hash is reused as long as both still match, so an unchanged file isn’t\n * read again on the next load.\n * @typedef {object} AssetHashCacheRecord\n * @property {string} sha Git object ID (SHA-1 hash) of the file.\n * @property {number} size File size in bytes.\n * @property {number} lastModified Modification time of the file, in milliseconds since the epoch.\n */\n\n/**\n * Maximum file size in bytes to read content from. (10 MB).\n */\nconst MAX_FILE_SIZE = 10 * 1024 * 1024;\n/**\n * Maximum number of files processed at the same time, to balance performance with memory safety.\n * Unlike fixed batches, a new file is picked up as soon as a slot frees up, so one large file\n * doesn’t stall the others.\n * @see https://github.com/sveltia/sveltia-cms/issues/224\n */\nconst FILE_PROCESS_CONCURRENCY = 10;\n\n/**\n * Parse text file info to create a complete entry or config file object.\n * @param {BaseFileListItem} fileInfo Entry or config file info.\n * @returns {Promise<BaseFileListItem>} Entry or config file with text content. We don’t populate\n * `size` and `sha` for entries and config files, as they are not needed. The text is left out if\n * the file is too large or can’t be read, rather than made empty, so the file isn’t loaded as an\n * empty entry that would wipe its content when saved.\n */\nexport const parseTextFileInfo = async (fileInfo) => {\n  const { name, handle } = fileInfo;\n\n  // Skip `.gitkeep` file, as we don’t need to read its content\n  if (name === '.gitkeep') {\n    return fileInfo;\n  }\n\n  try {\n    const file = await /** @type {FileSystemFileHandle} */ (handle).getFile();\n\n    if (file.size > MAX_FILE_SIZE) {\n      // eslint-disable-next-line no-console\n      console.warn(`File ${name} is too large (${file.size} bytes), skipping content read`);\n\n      return fileInfo;\n    }\n\n    const text = await readAsText(file);\n\n    return { ...fileInfo, text };\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n\n    return fileInfo;\n  }\n};\n\n/**\n * Parse asset file info to create a complete asset object.\n * @param {BaseAssetListItem} fileInfo Asset file info.\n * @param {object} [options] Options.\n * @param {Map<string, AssetHashCacheRecord>} [options.cachedHashes] Hashes from a previous load,\n * keyed by file path. A file whose size and modification time still match its record is not read\n * again; hashing means reading the whole file, which adds up with a lot of media.\n * @param {Map<string, AssetHashCacheRecord>} [options.newHashes] Map to collect the hashes computed\n * in this load in, keyed by file path, so they can be cached for the next one.\n * @returns {Promise<Asset>} Asset object.\n */\nexport const parseAssetFileInfo = async (fileInfo, { cachedHashes, newHashes } = {}) => {\n  const { name, path, handle } = fileInfo;\n  const kind = getAssetKind(name);\n\n  try {\n    const file = await /** @type {FileSystemFileHandle} */ (handle).getFile();\n    const { size, lastModified } = file;\n    const cached = cachedHashes?.get(path);\n    /** @type {string} */\n    let sha;\n\n    if (cached && cached.size === size && cached.lastModified === lastModified) {\n      ({ sha } = cached);\n    } else {\n      sha = await getGitHash(file);\n      newHashes?.set(path, { sha, size, lastModified });\n    }\n\n    return { ...fileInfo, kind, size, sha };\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n\n    return { ...fileInfo, kind };\n  }\n};\n\n/**\n * Load file list and all the entry files from the file system, then cache them in the stores.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {object} [options] Options.\n * @param {IndexedDB | null} [options.hashCacheDB] Store holding the asset hashes computed by\n * previous loads, keyed by file path, so unchanged files don’t have to be read and hashed again.\n * Without one, every asset file is read in full on every load.\n */\nexport const loadFiles = async (rootDirHandle, { hashCacheDB = null } = {}) => {\n  const log = createDebugLogger('Loading site data');\n\n  log(`Started: local repository ${rootDirHandle.name}`);\n\n  // Start reading the cache right away, as it’s only needed once the directory has been scanned\n  /** @type {Promise<Map<string, AssetHashCacheRecord>>} */\n  const cachedHashesPromise = readCacheEntries(hashCacheDB);\n  const fileList = createFileList(await getAllFiles(rootDirHandle));\n  const { entryFiles, assetFiles, configFiles } = fileList;\n\n  log(`Scanned the directory: ${describeFileList(fileList)}`);\n\n  /** @type {Map<string, AssetHashCacheRecord>} */\n  const newHashes = new Map();\n\n  // Each asset file is read in full to hash it, so this can take a while with large media, unless\n  // the hash is still cached from a previous load. It’s started now, so it goes on while the entry\n  // files are read and parsed rather than after\n  const assetsPromise = deferRejection(\n    cachedHashesPromise.then((cachedHashes) =>\n      mapConcurrently(\n        assetFiles,\n        (fileInfo) => parseAssetFileInfo(fileInfo, { cachedHashes, newHashes }),\n        { concurrency: FILE_PROCESS_CONCURRENCY },\n      ),\n    ),\n  );\n\n  const entryFileItems = /** @type {BaseEntryListItem[]} */ (\n    await mapConcurrently(entryFiles, parseTextFileInfo, { concurrency: FILE_PROCESS_CONCURRENCY })\n  );\n\n  log(`Read ${entryFileItems.length} entry files`);\n\n  const configFileItems = /** @type {BaseConfigListItem[]} */ (\n    await mapConcurrently(configFiles, parseTextFileInfo, { concurrency: FILE_PROCESS_CONCURRENCY })\n  );\n\n  log(`Read ${configFileItems.length} config files`);\n\n  const { entries, errors } = await prepareEntries(entryFileItems);\n\n  log(`Parsed ${entries.length} entries (${errors.length} errors)`);\n\n  /** @type {Asset[]} */\n  const assets = await assetsPromise;\n  const cachedHashes = await cachedHashesPromise;\n\n  log(`Hashed ${newHashes.size} of ${assets.length} asset files (${cachedHashes.size} cached)`);\n\n  allEntries.current = entries;\n  allAssets.current = assets;\n  gitConfigFiles.current = configFileItems;\n  entryParseErrors.current = errors;\n  dataLoaded.current = true;\n\n  log('The site data is ready');\n\n  // The app is usable at this point, so the cache is updated afterwards\n  // Save the hashes computed in this load, and drop the records of files that are gone. The records\n  // of unchanged files stay as they are, so a load that reused every hash writes nothing.\n  const currentPaths = new Set(assetFiles.map(({ path }) => path));\n\n  await updateCacheEntries(\n    hashCacheDB,\n    newHashes,\n    [...cachedHashes.keys()].filter((path) => !currentPaths.has(path)),\n  );\n};\n","import { sleep } from '@sveltia/utils/misc';\nimport { isObject } from '@sveltia/utils/object';\n\n/**\n * @import { AuthTokens } from '$lib/types/private';\n */\n\n/**\n * Regular expression to match `localhost` and its subdomains like `mysite.localhost`.\n */\nconst LOCALHOST_REGEX = /^(.+\\.)?localhost$/;\n\n/**\n * Check if a hostname refers to the local computer, which browsers treat as a secure context over\n * HTTP: `localhost` and its subdomains like `mysite.localhost`, and the IPv4 and IPv6 loopback\n * addresses, the latter written in brackets as `URL` and `location` give it.\n * @param {string} hostname Hostname, e.g. `location.hostname`.\n * @returns {boolean} Whether the hostname is local.\n * @see https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts\n */\nexport const isLocalHostname = (hostname) =>\n  ['127.0.0.1', '[::1]'].includes(hostname) || LOCALHOST_REGEX.test(hostname);\n\n/**\n * Check if a URL can be requested without exposing credentials over an insecure transport.\n * @param {string} url URL to check.\n * @param {string} [baseURL] Base URL for relative URLs.\n * @returns {boolean} Whether the URL uses HTTPS or local HTTP.\n */\nexport const isSecureURL = (\n  url,\n  baseURL = globalThis.window?.location?.origin ??\n    globalThis.location?.origin ??\n    'https://localhost',\n) => {\n  try {\n    const { hostname, protocol } = new URL(url, baseURL);\n\n    return protocol === 'https:' || isLocalHostname(hostname);\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Check if a request can be sent again after a transient error without side effects: a `GET` or\n * `HEAD` request, or a GraphQL query, which is sent with `POST` but only reads data. Any other\n * request, including a GraphQL mutation, may have taken effect behind a gateway that still answered\n * with an error, so sending it again could create a duplicate commit or deployment, or report a\n * false conflict.\n * @param {RequestInit} init Request options, with the body serialized or not.\n * @returns {boolean} Whether the request is safe to retry.\n */\nconst isRetryableRequest = ({ method = 'GET', body }) => {\n  if (['GET', 'HEAD'].includes(method.toUpperCase())) {\n    return true;\n  }\n\n  /** @type {any} */\n  let data = body;\n\n  if (typeof body === 'string') {\n    try {\n      data = JSON.parse(body);\n    } catch {\n      return false;\n    }\n  }\n\n  // `fetchGraphQL` sends the query as a JSON `query` property, with line breaks removed. An\n  // operation without a keyword, e.g. `{ viewer { login } }`, is a query\n  return (\n    isObject(data) &&\n    typeof data.query === 'string' &&\n    !/^\\s*(?:#[^\\n]*\\n\\s*)*mutation\\b/.test(data.query)\n  );\n};\n\n/**\n * Statuses of a transient server error, other than 502 Bad Gateway, that a request without side\n * effects is retried once for: 429 Too Many Requests, 503 Service Unavailable and 504 Gateway\n * Timeout, which a rate limit or a self-hosted instance under load answers with. A write that opts\n * in with `retryable` is only retried on 502: a gateway can time out with 504 after a large commit\n * has landed, and the repeat would be refused as a conflict.\n * @see https://github.com/sveltia/sveltia-cms/issues/1143\n */\nconst TRANSIENT_STATUSES = [429, 503, 504];\n/**\n * Wait before a retry when the server doesn’t say how long to wait, in milliseconds.\n */\nconst DEFAULT_RETRY_DELAY = 1000;\n\n/**\n * Longest wait before a retry, in milliseconds. A request the server asks to send again later than\n * that isn’t retried, as the wait would look like a hang.\n */\nexport const MAX_RETRY_DELAY = 10 * 1000;\n\n/**\n * Get how long to wait before sending a request again after a transient error, from the\n * `Retry-After` header of the response, which gives either a number of seconds or an HTTP date. A\n * request isn’t to be sent again sooner than the server asks: GitHub may ban an integration that\n * keeps sending requests while it’s rate limited. A rate limit that doesn’t say how long to wait\n * typically lasts a minute or more, until the limit resets, so it isn’t retried either.\n * @param {number} status Response status.\n * @param {Headers} [headers] Response headers.\n * @returns {number | undefined} Delay in milliseconds, between `0` and {@link MAX_RETRY_DELAY}, or\n * `undefined` if the request is not to be retried now.\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After\n * @see https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api#exceeding-the-rate-limit\n */\nexport const getRetryDelay = (status, headers) => {\n  const value = headers?.get('Retry-After')?.trim();\n\n  if (value) {\n    const delay = /^\\d+$/.test(value) ? Number(value) * 1000 : Date.parse(value) - Date.now();\n\n    if (!Number.isNaN(delay)) {\n      return delay > MAX_RETRY_DELAY ? undefined : Math.max(delay, 0);\n    }\n  }\n\n  return status === 429 ? undefined : DEFAULT_RETRY_DELAY;\n};\n\n/**\n * Send a request with `fetch()`, taking the same arguments, and make sure the response status is\n * OK.\n * @param {Parameters<typeof fetch>} args Resource and request options.\n * @returns {Promise<Response>} Response.\n * @throws {Error} When the request fails, or the response status is not OK.\n */\nexport const fetchOK = async (...args) => {\n  const response = await fetch(...args);\n\n  if (!response.ok) {\n    throw new Error(`HTTP ${response.status}`);\n  }\n\n  return response;\n};\n\n/**\n * A `fetch` wrapper to send an HTTP request to an API endpoint, parse the response as JSON or other\n * specified format, and handle errors gracefully.\n * @param {string} url URL.\n * @param {RequestInit} [init] Request options.\n * @param {object} [options] Options.\n * @param {'json' | 'text' | 'blob' | 'raw'} [options.responseType] Response parser type. The\n * default is `json`. Use `raw` to return a `Response` object as is.\n * @param {() => Promise<AuthTokens>} [options.refreshAccessToken] A function to refresh the OAuth\n * access token when the request fails with a 401 Unauthorized status. If this function is provided,\n * the request will be retried with the new token.\n * @param {number} [options.retries] Number of remaining retries for transient server errors.\n * Defaults to `1`. Used internally for recursive retries.\n * @param {boolean} [options.retryable] Whether the request can be sent again after a transient\n * error. The default is `true` for a request without side effects, as determined by\n * {@link isRetryableRequest}. A request that writes data can opt in when the server refuses a\n * repeat of a request that has already taken effect, like a commit guarded by the expected head.\n * @returns {Promise<object | string | Blob | Response>} Response data or `Response` itself,\n * depending on the `responseType` option.\n * @throws {Error} When there was an error in the request or response.\n */\nexport const sendRequest = async (\n  url,\n  init = {},\n  {\n    responseType = 'json',\n    refreshAccessToken = undefined,\n    retries = 1,\n    retryable = isRetryableRequest(init),\n  } = {},\n) => {\n  /** @type {Response} */\n  let response;\n  const headers = new Headers(init.headers);\n\n  init.cache = 'no-cache';\n  init.headers = headers;\n\n  if (headers.has('Authorization') && !isSecureURL(url)) {\n    throw new Error('Refusing to send credentials over an insecure connection');\n  }\n\n  if (responseType === 'json') {\n    headers.set('Accept', 'application/json');\n  }\n\n  // Serialize a plain object body for any method that accepts one, e.g. `POST`, `PUT` and `PATCH`\n  if (isObject(init.body)) {\n    headers.set('Content-Type', 'application/json');\n    init.body = JSON.stringify(init.body);\n  }\n\n  try {\n    response = await fetch(url, init);\n  } catch (ex) {\n    throw new Error('Failed to send the request', { cause: ex });\n  }\n\n  const { ok, status } = response;\n\n  /**\n   * Refresh the OAuth access token and send the request again with the new token.\n   * @returns {Promise<object | string | Blob | Response>} Response data or `Response` itself.\n   */\n  const retryWithNewToken = async () => {\n    const [scheme] = headers.get('Authorization')?.split(' ') ?? ['token'];\n    const { token } = await /** @type {() => Promise<AuthTokens>} */ (refreshAccessToken)();\n\n    headers.set('Authorization', `${scheme} ${token}`);\n\n    // Retry the request with the new token. Omit `refreshAccessToken` to avoid infinite loops.\n    return sendRequest(url, init, { responseType, retryable });\n  };\n\n  // A transient error that may succeed on retry: 502 Bad Gateway, which the GitHub GraphQL API is\n  // known to occasionally answer with, and, for a request without side effects only, a rate limit\n  // or a self-hosted instance under load\n  // @see https://github.com/sveltia/sveltia-cms/issues/695\n  const retryDelay =\n    retries > 0 &&\n    retryable &&\n    (status === 502 || (TRANSIENT_STATUSES.includes(status) && isRetryableRequest(init)))\n      ? getRetryDelay(status, response.headers)\n      : undefined;\n\n  const shouldRetry = retryDelay !== undefined;\n\n  /**\n   * Send the request again after the delay the server asks for, or a short one.\n   * @returns {Promise<object | string | Blob | Response>} Response data or `Response` itself.\n   */\n  const retryAfterDelay = async () => {\n    await sleep(/** @type {number} */ (retryDelay));\n\n    return sendRequest(url, init, {\n      responseType,\n      refreshAccessToken,\n      retries: retries - 1,\n      retryable,\n    });\n  };\n\n  // A raw response is returned as is for the caller to check the status, but a transient error is\n  // still retried and an expired token refreshed, the same as for the other response types\n  if (responseType === 'raw') {\n    if (shouldRetry) {\n      return retryAfterDelay();\n    }\n\n    return status === 401 && refreshAccessToken ? retryWithNewToken() : response;\n  }\n\n  /** @type {any} */\n  let result;\n\n  if (ok) {\n    try {\n      if (responseType === 'blob') {\n        return await response.blob();\n      }\n\n      if (responseType === 'text') {\n        return await response.text();\n      }\n\n      result = await response.json();\n    } catch (ex) {\n      throw new Error('Failed to parse the response', { cause: ex });\n    }\n  } else {\n    try {\n      result = await response.json();\n    } catch {\n      // An error response doesn’t always come with a JSON body, e.g. a gateway’s HTML error page,\n      // but its status still decides whether to retry, refresh the token or report the error\n      result = undefined;\n    }\n  }\n\n  // Return the parsed result for a successful response, but a GraphQL error is typically returned\n  // with 200 OK so we need to check the content for the `errors` key\n  if (ok && !(url.endsWith('/graphql') && isObject(result) && result.errors)) {\n    return result;\n  }\n\n  if (shouldRetry) {\n    return retryAfterDelay();\n  }\n\n  if (status === 401 && refreshAccessToken) {\n    return retryWithNewToken();\n  }\n\n  if (!isObject(result)) {\n    throw new Error('Server responded with an error', { cause: { status } });\n  }\n\n  let message = '';\n\n  if (typeof result.error === 'string') {\n    message = result.error;\n  }\n\n  // Typical REST\n  if (typeof result.message === 'string') {\n    message = result.message;\n  }\n\n  if (Array.isArray(result.errors)) {\n    if (typeof result.errors[0] === 'string') {\n      message = result.errors.join(', ');\n    }\n\n    // Typical GraphQL\n    if (isObject(result.errors[0]) && typeof result.errors[0].message === 'string') {\n      message = /** @type {any[]} */ (result.errors).map((e) => e.message).join(', ');\n    }\n  }\n\n  throw new Error('Server responded with an error', { cause: { status, message } });\n};\n\n/**\n * Throw an error with the response body appended to the given message if the request failed.\n * @param {Response} response Response.\n * @param {string} message Error message, such as `Failed to list objects`.\n * @param {object} [options] Options.\n * @param {boolean} [options.allowNotFound] Whether to accept a `404 Not Found` response.\n * @returns {Promise<void>}\n * @throws {Error} When the response status is not OK.\n */\nexport const assertResponseOK = async (response, message, { allowNotFound = false } = {}) => {\n  if (!response.ok && !(allowNotFound && response.status === 404)) {\n    const errorText = await response.text();\n\n    throw new Error(`${message}: ${errorText}`);\n  }\n};\n","import { isLocalHostname } from '$lib/services/utils/networking';\n\n/**\n * Reactive environment detection state for the CMS.\n */\nexport const env = $state({\n  /** Whether the app is running on localhost. */\n  isLocalHost: false,\n  /** Whether the local backend is supported. */\n  isLocalBackendSupported: false,\n  /** Whether the test backend is supported. */\n  isTestBackendSupported: true,\n  /** Whether the browser is Brave. */\n  isBrave: false,\n  /** Whether the operating system is macOS. */\n  isMacOS: false,\n  /** Whether the app is displayed on a small screen (mobile). */\n  isSmallScreen: false,\n  /** Whether the app is displayed on a medium screen (tablet). */\n  isMediumScreen: false,\n  /** Whether the app is displayed on a large screen (desktop). */\n  isLargeScreen: false,\n  /** Whether the user has a mouse. */\n  hasMouse: true,\n});\n\n/**\n * Initialize the screen size detection. This should be called within `onMount()` due to the access\n * to the DOM APIs.\n */\nexport const initUserEnvDetection = () => {\n  const {\n    location: { hostname },\n    navigator: { userAgentData, platform },\n    matchMedia,\n  } = globalThis;\n\n  // Local editing needs a secure context, e.g. `http://localhost`, `http://*.localhost` or\n  // `http://[::1]`\n  env.isLocalHost = isLocalHostname(hostname);\n  env.isLocalBackendSupported = 'showDirectoryPicker' in globalThis;\n  // The test backend saves files to the origin private file system (OPFS), which Safari before\n  // version 26 can create but not write to, so the files would be left empty. Without the OPFS,\n  // e.g. in an insecure context, the files are only kept in memory, which works anywhere\n  env.isTestBackendSupported =\n    !globalThis.FileSystemFileHandle ||\n    'createWritable' in globalThis.FileSystemFileHandle.prototype;\n  env.isBrave = userAgentData?.brands.some(({ brand }) => brand === 'Brave') ?? false;\n  env.isMacOS = userAgentData?.platform === 'macOS' || platform.startsWith('Mac');\n\n  const mqlSmall = matchMedia('(width < 768px)');\n  const mqlMedium = matchMedia('(768px <= width < 1024px)');\n  const mqlLarge = matchMedia('(1024px <= width)');\n  const mqlPointer = matchMedia('(pointer: fine)');\n\n  /* eslint-disable jsdoc/require-jsdoc */\n  const isSmallScreenSetter = () => {\n    env.isSmallScreen = mqlSmall.matches;\n  };\n\n  const isMediumScreenSetter = () => {\n    env.isMediumScreen = mqlMedium.matches;\n  };\n\n  const isLargeScreenSetter = () => {\n    env.isLargeScreen = mqlLarge.matches;\n  };\n\n  const hasMouseSetter = () => {\n    env.hasMouse = mqlPointer.matches;\n  };\n  /* eslint-enable jsdoc/require-jsdoc */\n\n  isSmallScreenSetter();\n  isMediumScreenSetter();\n  isLargeScreenSetter();\n  hasMouseSetter();\n\n  mqlSmall.addEventListener('change', isSmallScreenSetter);\n  mqlMedium.addEventListener('change', isMediumScreenSetter);\n  mqlLarge.addEventListener('change', isLargeScreenSetter);\n  mqlPointer.addEventListener('change', hasMouseSetter);\n};\n\n/**\n * Whether a click on a list item opens it right away, as there is no double-click to wait for: on\n * a small or medium screen, where the selection checkbox is hidden, and on a touch screen of any\n * size, e.g. a tablet in landscape, because Safari never fires `dblclick` for a double tap.\n * `pointerType` tells a tap from a mouse click where the browser dispatches `click` as a\n * `PointerEvent`; elsewhere, the lack of a fine pointer does. A click with no pointer at all — one\n * synthesized for the Enter key — opens the item as well, so it can be opened from the keyboard.\n * @param {MouseEvent} event `click` event.\n * @returns {boolean} Result.\n */\nexport const opensOnClick = (event) =>\n  env.isSmallScreen ||\n  env.isMediumScreen ||\n  event.detail === 0 ||\n  /** @type {PointerEvent} */ (event).pointerType === 'touch' ||\n  !env.hasMouse;\n","/* eslint-disable no-await-in-loop */\n\n/* eslint-disable no-restricted-syntax */\n\nimport { getPathInfo } from '@sveltia/utils/file';\nimport { sleep } from '@sveltia/utils/misc';\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport { TEMP_FILE_PREFIX } from '$lib/services/backends/fs/shared/constants';\nimport {\n  findEntryName,\n  getDirectoryHandle,\n  getFileHandle,\n  getHandleByPath,\n  isNotFoundError,\n} from '$lib/services/backends/fs/shared/handles';\nimport { env } from '$lib/services/user/env.svelte';\nimport { foldPath, getBlob, getDirName, getGitHash } from '$lib/services/utils/file';\n\n/**\n * @import {\n * CommitResults,\n * FileChange,\n * } from '$lib/types/private';\n */\n\n/**\n * How many times renaming a temporary file to its final name is attempted, and how long to wait\n * between attempts, in milliseconds. A rename can fail for a moment while another program has the\n * file open, e.g. an antivirus scanner or a dev server’s file watcher reading the new file.\n */\nconst RENAME_ATTEMPTS = 3;\nconst RENAME_RETRY_DELAY = 150;\n\n/**\n * Check if the `move` method is supported by the current browser. The `move` method is not\n * implemented in older browsers, and Brave supports the `move` method but throws an error for some\n * reason, so we need to check it by actually trying to use it.\n * @returns {boolean} `true` if the `move` method is supported, `false` otherwise.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/File_System_API#browser_compatibility\n * @see https://github.com/sveltia/sveltia-cms/discussions/676\n */\nexport const canMoveFile = () => 'move' in FileSystemFileHandle.prototype && !env.isBrave;\n\n/**\n * Write data to a file using the provided file handle. This function is used to write data to a\n * file when we already have a file handle reference, such as when moving a file without changes. It\n * handles the case where the `createWritable` method is not supported by older versions of Safari.\n * @param {FileSystemFileHandle} fileHandle File handle to write to.\n * @param {FileSystemWriteChunkType} data Data to write to the file.\n * @throws {Error} If the data couldn’t be written or the file couldn’t be closed.\n */\nexport const writeFile = async (fileHandle, data) => {\n  // The `createWritable` method is not supported by older versions of Safari\n  const writer = await fileHandle.createWritable?.();\n\n  if (!writer) {\n    return;\n  }\n\n  try {\n    // Can throw if the file has just been moved/renamed without any change, and then the `data` is\n    // no longer available\n    await writer.write(data);\n  } catch (ex) {\n    // Release the file; closing a stream that has failed fails too, but the write error is the one\n    // that tells what went wrong\n    try {\n      await writer.close();\n    } catch {\n      //\n    }\n\n    throw ex;\n  }\n\n  // The data is only committed to the file when the stream is closed: Chrome writes to a swap file\n  // and moves it into place then. If that fails, e.g. because another program has locked the file,\n  // the file hasn’t been written, which the caller has to know rather than treat it as saved\n  await writer.close();\n};\n\n/**\n * Create a temporary file with a unique name in the given directory. Its name starts with\n * `TEMP_FILE_PREFIX`, so it’s hidden, and a stale one is deleted when the files are scanned.\n * @param {FileSystemDirectoryHandle} dirHandle Directory handle.\n * @returns {Promise<FileSystemFileHandle>} Handle of the new, empty file.\n */\nconst createTempFile = (dirHandle) =>\n  dirHandle.getFileHandle(`${TEMP_FILE_PREFIX}${crypto.randomUUID()}`, { create: true });\n\n/**\n * Move a file from a previous path to a new path within the file system. A file or folder whose\n * name is spelled in another Unicode normalization form than the path’s is moved or moved to as it\n * is, rather than missed, on a file system that compares names byte for byte.\n * @param {object} args Arguments.\n * @param {FileSystemDirectoryHandle} args.rootDirHandle Root directory handle.\n * @param {string} args.previousPath The current path of the file to move.\n * @param {string} args.path The new path where the file should be moved.\n * @returns {Promise<FileSystemFileHandle>} Moved file handle.\n */\nexport const moveFile = async ({ rootDirHandle, previousPath, path }) => {\n  const { dirname: newDirname, basename: newBasename } = getPathInfo(path);\n  const { dirname: oldDirname } = getPathInfo(previousPath);\n  const fileHandle = await getFileHandle(rootDirHandle, previousPath);\n\n  // Use the native `move` method if supported, as it’s more efficient and preserves file metadata.\n  // If not, fall back to copying the file to the new location and deleting the old file.\n  if (canMoveFile()) {\n    const newDirHandle = await getDirectoryHandle(rootDirHandle, newDirname);\n\n    // @ts-ignore\n    await fileHandle.move(newDirHandle, await findEntryName(newDirHandle, newBasename));\n\n    return fileHandle;\n  }\n\n  const oldDirHandle = await getDirectoryHandle(rootDirHandle, oldDirname);\n  const newDirHandle = await getDirectoryHandle(rootDirHandle, newDirname);\n  let newFileHandle = await getFileHandle(rootDirHandle, path);\n\n  // On a case-insensitive file system, a file renamed only in case, e.g. `Photo.jpg` to\n  // `photo.jpg`, is still the same file under the new name, as is one renamed only in its Unicode\n  // normalization form where the file system or the name lookup ignores it. The browser doesn’t\n  // always tell, as it may compare the paths it has, so the paths are compared here too. Copying\n  // the file onto itself and deleting the old name would delete the file, so it’s copied to a\n  // temporary file first, which also gives it the new spelling\n  if (!(await newFileHandle.isSameEntry(fileHandle)) && foldPath(previousPath) !== foldPath(path)) {\n    await writeFile(newFileHandle, await fileHandle.getFile());\n    // The name the file has on the disk\n    await oldDirHandle.removeEntry(fileHandle.name);\n\n    return newFileHandle;\n  }\n\n  const tempFileHandle = await createTempFile(newDirHandle);\n\n  await writeFile(tempFileHandle, await fileHandle.getFile());\n  await oldDirHandle.removeEntry(fileHandle.name);\n  newFileHandle = await getFileHandle(rootDirHandle, path);\n  // The temporary file is only removed once the file has been written under the new name, so the\n  // content isn’t lost if that fails\n  await writeFile(newFileHandle, await tempFileHandle.getFile());\n  await newDirHandle.removeEntry(tempFileHandle.name);\n\n  return newFileHandle;\n};\n\n/**\n * Rename a file, trying again a few times if the file system won’t let it go right away.\n * @param {FileSystemFileHandle} fileHandle File handle.\n * @param {FileSystemDirectoryHandle} dirHandle Directory to move the file to.\n * @param {string} name New file name.\n * @throws {Error} The last error, if every attempt fails.\n */\nconst renameFile = async (fileHandle, dirHandle, name) => {\n  for (let attempt = 1; ; attempt += 1) {\n    try {\n      // @ts-ignore\n      await fileHandle.move(dirHandle, name);\n\n      return;\n    } catch (ex) {\n      if (attempt === RENAME_ATTEMPTS) {\n        throw ex;\n      }\n\n      await sleep(RENAME_RETRY_DELAY * attempt);\n    }\n  }\n};\n\n/**\n * Save data to a file at the specified path. An existing file whose name, or the name of a folder\n * on the path, is spelled in another Unicode normalization form is written to, rather than joined\n * by a new one that looks the same on a file system that compares names byte for byte.\n * @param {object} args Arguments.\n * @param {FileSystemDirectoryHandle} args.rootDirHandle Root directory handle.\n * @param {FileSystemFileHandle} [args.fileHandle] File handle to write to. Provided if the file has\n * been moved.\n * @param {string} args.path The relative path to the file within the root directory.\n * @param {string | File} args.data The data to write to the file.\n * @returns {Promise<File>} Written file.\n */\nexport const saveFile = async ({ rootDirHandle, fileHandle, path, data }) => {\n  // When no handle is provided (create/update), write to a temp file first, then rename it to the\n  // final path. This avoids race conditions with file watchers (e.g., Astro dev server) that may\n  // read the new file before its content is fully written.\n  // @see https://github.com/sveltia/sveltia-cms/issues/675\n  /** @type {{ dirHandle: FileSystemDirectoryHandle, basename: string } | undefined} */\n  let pendingRename;\n\n  if (!fileHandle) {\n    // Check if the `move` method is supported before deciding whether to write to a temp file, as\n    // writing to a temp file and then renaming it is only necessary if the `move` method is not\n    // supported. If the `move` method is supported, we have to write directly to the final path.\n    if (canMoveFile()) {\n      const { dirname, basename } = getPathInfo(stripSlashes(path));\n      const dirHandle = await getDirectoryHandle(rootDirHandle, dirname);\n\n      fileHandle = await createTempFile(dirHandle);\n      pendingRename = { dirHandle, basename };\n    } else {\n      fileHandle = await getFileHandle(rootDirHandle, path);\n    }\n  }\n\n  if (!pendingRename) {\n    await writeFile(fileHandle, data);\n\n    return fileHandle.getFile();\n  }\n\n  const { dirHandle, basename } = pendingRename;\n\n  try {\n    await writeFile(fileHandle, data);\n    // Replace the file with the name spelled in another normalization form, if any, rather than\n    // adding another one next to it\n    await renameFile(fileHandle, dirHandle, await findEntryName(dirHandle, basename));\n  } catch (ex) {\n    // Don’t leave the temporary file behind; the error is reported to the user, who can retry\n    try {\n      await dirHandle.removeEntry(fileHandle.name);\n    } catch {\n      //\n    }\n\n    throw ex;\n  }\n\n  return fileHandle.getFile();\n};\n\n/**\n * Recursively delete empty parent directories.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {string[]} pathSegments Array of directory path segments.\n */\nexport const deleteEmptyParentDirs = async (rootDirHandle, pathSegments) => {\n  // Start from the deepest directory\n  for (let i = pathSegments.length; i > 0; i -= 1) {\n    const dirName = pathSegments[i - 1];\n    const parentPath = pathSegments.slice(0, i - 1).join('/');\n\n    try {\n      // Don’t bring back a parent directory that has been removed already\n      const parentHandle = /** @type {FileSystemDirectoryHandle} */ (\n        await getHandleByPath(rootDirHandle, parentPath, 'directory', { create: false })\n      );\n\n      const name = await findEntryName(parentHandle, dirName);\n      const dirHandle = await parentHandle.getDirectoryHandle(name);\n\n      // Use for...of to check if directory is empty with early exit on first entry found\n      // eslint-disable-next-line no-unreachable-loop\n      for await (const _entry of dirHandle.entries()) {\n        // Directory is not empty, stop cleanup\n        return;\n      }\n\n      // Directory is empty, remove it\n      await parentHandle.removeEntry(name);\n    } catch (ex) {\n      // A directory that is already gone, e.g. removed outside the CMS, is as good as removed\n      if (!isNotFoundError(ex)) {\n        throw ex;\n      }\n    }\n  }\n};\n\n/**\n * Delete a file at the specified path within the file system. The directory the file was in is left\n * alone even if it’s now empty; {@link deleteEmptyDirs} cleans up once a whole batch of changes has\n * been saved, because the files in a batch are removed all at once, and a directory can’t be\n * removed while another file is being removed from it. The file is found by its name in Unicode\n * normalization form C or by another spelling of it.\n * @param {object} args Arguments.\n * @param {FileSystemDirectoryHandle} args.rootDirHandle Root directory handle.\n * @param {string} args.path The path to the file to be deleted.\n */\nexport const deleteFile = async ({ rootDirHandle, path }) => {\n  const { dirname: dirPath = '', basename: fileName } = getPathInfo(stripSlashes(path));\n  const dirHandle = await getDirectoryHandle(rootDirHandle, dirPath);\n\n  try {\n    await dirHandle.removeEntry(await findEntryName(dirHandle, fileName));\n  } catch (ex) {\n    // The file may have been removed outside the CMS, e.g. in a file manager or by a Git branch\n    // switch; the point is that it’s gone, so that’s not a failure\n    if (!isNotFoundError(ex)) {\n      throw ex;\n    }\n  }\n};\n\n/**\n * Delete the given directories, and their parents, if they’re empty. The directories are handled\n * one at a time, because the file system won’t let a directory be removed while it’s being\n * modified.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {Iterable<string>} dirPaths Paths to the directories.\n */\nexport const deleteEmptyDirs = async (rootDirHandle, dirPaths) => {\n  for (const dirPath of new Set(dirPaths)) {\n    if (dirPath) {\n      await deleteEmptyParentDirs(rootDirHandle, dirPath.split('/'));\n    }\n  }\n};\n\n/**\n * Save a file to the file system based on the provided change options.\n * @param {FileSystemDirectoryHandle} rootDirHandle Root directory handle.\n * @param {FileChange} change File change options.\n * @returns {Promise<?File>} Created or updated file, if available.\n * @throws {Error} If an error occurs while saving the file.\n */\nexport const saveChange = async (rootDirHandle, { action, path, previousPath, data }) => {\n  /** @type {FileSystemFileHandle | undefined} */\n  let fileHandle;\n\n  if (action === 'move' && previousPath) {\n    fileHandle = await moveFile({ rootDirHandle, previousPath, path });\n  }\n\n  // An empty string is still written, as an emptied file mustn’t keep its old content\n  if (['create', 'update', 'move'].includes(action) && data !== undefined) {\n    // We don’t need to write the file is it’s just been renamed with no change, but the `data` is\n    // always provided for the compatibility with Git backends, so we cannot distinguish between the\n    // two cases\n    return saveFile({ rootDirHandle, fileHandle, path, data });\n  }\n\n  if (action === 'delete') {\n    await deleteFile({ rootDirHandle, path });\n  }\n\n  return null;\n};\n\n/**\n * Check if a change is to an entry file rather than an asset.\n * @param {FileChange} change File change.\n * @returns {boolean} `true` for an entry file.\n */\nconst isEntryChange = ({ slug, data }) => slug !== undefined || typeof data === 'string';\n\n/**\n * Save a batch of changes in the file system at the same time.\n * @param {FileSystemDirectoryHandle | undefined} rootDirHandle Root directory handle. If it’s not\n * available, nothing is written, and the in-memory data stands in for the files.\n * @param {FileChange[]} changes File changes to be saved.\n * @returns {Promise<([string, { file: Blob, sha: string }] | null)[]>} Saved files, each with its\n * path and blob SHA, or `null` for a deleted file.\n * @throws {Error} If a file could not be written. The other files in the batch are still written,\n * because they’re already on their way.\n */\nconst saveChangeBatch = async (rootDirHandle, changes) =>\n  Promise.all(\n    changes.map(async (change) => {\n      const { path, data } = change;\n      /** @type {Blob | null} */\n      let file = rootDirHandle ? await saveChange(rootDirHandle, change) : null;\n\n      if (!file) {\n        if (data === undefined) {\n          return null;\n        }\n\n        file = getBlob(data);\n      }\n\n      return [path, { file, sha: await getGitHash(file) }];\n    }),\n  );\n\n/**\n * Save entries or assets in the file system.\n *\n * The assets are written first, and the entry files last. The site’s dev server typically watches\n * the content files, and one that reloads the page on a content change — Astro does for content\n * collections — would reload the CMS while the assets are still being written if the entry file\n * went first. That left the images as `.sveltia-tmp-*` files and the draft backup in place.\n *\n * A file that can’t be written fails the whole save, so the user is told rather than left with an\n * entry that refers to files that don’t exist; the CMS keeps the draft, so the save can be retried.\n * @param {FileSystemDirectoryHandle | undefined} rootDirHandle Root directory handle. This can be\n * `undefined` if the directory handle could not be acquired earlier for security reasons. If the\n * handle is not available, the changes will not be saved, but the user can still continue using the\n * app without an error thanks to the in-memory cache.\n * @param {FileChange[]} changes File changes to be saved.\n * @returns {Promise<CommitResults>} Commit results, including a pseudo commit SHA, saved files, and\n * their blob SHAs.\n * @throws {Error} If a file could not be written.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/write\n * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryHandle/removeEntry\n */\nexport const saveChanges = async (rootDirHandle, changes) => {\n  const assetChanges = changes.filter((change) => !isEntryChange(change));\n  const entryChanges = changes.filter(isEntryChange);\n\n  const entries = [\n    ...(await saveChangeBatch(rootDirHandle, assetChanges)),\n    ...(await saveChangeBatch(rootDirHandle, entryChanges)),\n  ];\n\n  if (rootDirHandle) {\n    // A directory left empty by the deleted and moved files is removed, as Git doesn’t track empty\n    // directories, so the local checkout matches what a Git backend would end up with\n    await deleteEmptyDirs(\n      rootDirHandle,\n      changes\n        .map(({ action, path, previousPath }) => {\n          if (action === 'delete') {\n            return path;\n          }\n\n          if (action === 'move' && previousPath) {\n            return previousPath;\n          }\n\n          return undefined;\n        })\n        .filter((path) => path !== undefined)\n        .map((path) => getDirName(stripSlashes(path))),\n    );\n  }\n\n  return {\n    // Use a hash of the current date as a pseudo SHA\n    sha: await getGitHash(new Date().toJSON()),\n    files: Object.fromEntries(entries.filter((entry) => !!entry)),\n  };\n};\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { DEFAULT_API_ROOT } from '$lib/services/backends/git/github/constants';\n\n/**\n * Normalize an API base URL for GitHub Enterprise Server: strip any `/api`, `/api/v3` or\n * `/api/graphql` suffix, then append `/api/{suffix}`. The default API root is kept as is because,\n * unlike other backends, the default `api_root` for GitHub does not end with `/api/v3`, which may\n * lead to misconfigured URLs. A GraphQL URL already ending with `/graphql`, e.g. a proxy given as\n * `graphql_api_root`, is kept as is.\n * @param {string} url The base URL to normalize.\n * @param {'v3' | 'graphql'} suffix API endpoint suffix.\n * @returns {string} Normalized API base URL.\n */\nconst normalizeBaseURL = (url, suffix) => {\n  url = stripSlashes(url);\n\n  if (url === DEFAULT_API_ROOT) {\n    // The default REST API root is https://api.github.com, and the GraphQL one appends `/graphql`\n    return suffix === 'v3' ? url : `${url}/graphql`;\n  }\n\n  if (suffix === 'graphql' && url.endsWith('/graphql')) {\n    return url;\n  }\n\n  return `${url.replace(/\\/api(?:\\/v3|\\/graphql)?$/, '')}/api/${suffix}`;\n};\n\n/**\n * Normalize the REST API base URL. Ensures it ends with `/api/v3` for GitHub Enterprise Server.\n * Otherwise, just use the default API root.\n * @param {string} url The base URL to normalize.\n * @returns {string} Normalized REST API base URL.\n * @see https://docs.github.com/en/enterprise-server@3.17/rest/quickstart?tool=javascript\n */\nexport const normalizeRestBaseURL = (url) => normalizeBaseURL(url, 'v3');\n\n/**\n * Normalize the GraphQL API base URL. Ensures it ends with `/api/graphql` for GitHub Enterprise\n * Server. Otherwise, just use the default API root followed by `/graphql`.\n * @param {string} url The base URL to normalize.\n * @returns {string} Normalized GraphQL API base URL.\n * @see https://docs.github.com/en/enterprise-server@3.17/graphql/guides/forming-calls-with-graphql#the-graphql-endpoint\n */\nexport const normalizeGraphQLBaseURL = (url) => normalizeBaseURL(url, 'graphql');\n","import { _ } from '@sveltia/i18n';\nimport { LocalStorage } from '@sveltia/utils/storage';\n\nimport { user } from '$lib/services/user/account.svelte';\nimport { USER_STORAGE_KEY } from '$lib/services/user/constants';\nimport { isSecureURL, sendRequest } from '$lib/services/utils/networking';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { ApiEndpointConfig, AuthTokens, FetchApiOptions, User } from '$lib/types/private';\n */\n\n/**\n * Placeholder for API configuration information.\n * @type {ApiEndpointConfig}\n */\nconst API_CONFIG_INFO_PLACEHOLDER = {\n  clientId: '',\n  authScope: '',\n  authURL: '',\n  tokenURL: '',\n  authScheme: 'token',\n  restBaseURL: '',\n  graphqlBaseURL: '',\n  includeCredentials: false,\n};\n\n/**\n * Configuration for API endpoints.\n * @type {ApiEndpointConfig}\n */\nexport const apiConfig = { ...API_CONFIG_INFO_PLACEHOLDER };\n\n/**\n * Variables to be used in GraphQL queries.\n * @type {Record<string, any>}\n */\nexport const graphqlVars = {};\n\n/**\n * Send a request to an OAuth token endpoint.\n * @param {string} tokenURL OAuth token request URL.\n * @param {Record<string, string>} body Request parameters, including the `grant_type`.\n * @param {object} [options] Options.\n * @param {boolean} [options.includeCredentials] Whether to send cookies with the request.\n * @returns {Promise<Response | undefined>} Response, or `undefined` if the URL isn’t secure or the\n * request couldn’t be sent at all.\n */\nexport const requestAccessToken = async (tokenURL, body, { includeCredentials = false } = {}) => {\n  if (!isSecureURL(tokenURL)) {\n    return undefined;\n  }\n\n  try {\n    return await fetch(tokenURL, {\n      method: 'POST',\n      headers: {\n        Accept: 'application/json',\n        'Content-Type': 'application/json',\n      },\n      body: JSON.stringify(body),\n      ...(includeCredentials && { credentials: 'include' }),\n    });\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Token refreshes in progress, keyed by the refresh token they use.\n * @type {Map<string, Promise<AuthTokens>>}\n */\nconst pendingRefreshes = new Map();\n\n/**\n * Send a request to refresh the OAuth access token.\n * @param {object} args Arguments.\n * @param {string} args.clientId OAuth application ID.\n * @param {string} args.tokenURL OAuth token request URL.\n * @param {string} args.refreshToken OAuth refresh token.\n * @returns {Promise<AuthTokens>} New access token and refresh token.\n */\nconst requestTokenRefresh = async ({ clientId, tokenURL, refreshToken }) => {\n  const sentRefreshToken = refreshToken;\n\n  const response = await requestAccessToken(\n    tokenURL,\n    { grant_type: 'refresh_token', client_id: clientId, refresh_token: refreshToken },\n    { includeCredentials: apiConfig.includeCredentials },\n  );\n\n  if (!response?.ok) {\n    throw new Error(_('sign_in_error.TOKEN_REFRESH_FAILED'));\n  }\n\n  /** @type {Record<string, any> | undefined} */\n  let result;\n\n  try {\n    result = await response.json();\n  } catch {\n    //\n  }\n\n  // Some services, e.g. GitHub, report a failed refresh with `200 OK` and an `error` property, so\n  // the session mustn’t be overwritten unless a new access token came back\n  if (!isNonEmptyString(result?.access_token)) {\n    throw new Error(_('sign_in_error.TOKEN_REFRESH_FAILED'));\n  }\n\n  const token = /** @type {string} */ (result?.access_token);\n\n  // A service that doesn’t rotate refresh tokens doesn’t return a new one\n  if (isNonEmptyString(result?.refresh_token)) {\n    refreshToken = result?.refresh_token;\n  }\n\n  /** @type {{ role?: User['role'] } | undefined} */\n  const account = result?.user;\n  /**\n   * @type {{ kind?: string, commit_author?: User['commitAuthor'], expires_at?: string } |\n   * undefined}\n   */\n  const git = result?.git;\n\n  // Update the user store with the new token and refresh token. Sveltia CMS Additions also returns\n  // the user, whose role may have changed since they signed in, e.g. when an admin made them a\n  // viewer, which revoked the previous token, and how to author their commits, which an admin may\n  // have changed as well. Nothing is updated if the account has moved on meanwhile, e.g. to a new\n  // session after a password change, or another user has signed in, as the tokens are for the\n  // previous one\n  if (user.account && user.account.refreshToken === sentRefreshToken) {\n    user.account = {\n      ...user.account,\n      token,\n      refreshToken,\n      ...(account?.role ? { role: account.role } : {}),\n      // The kind of token can change too: a user’s own token is replaced with the app’s once it\n      // can’t be refreshed any more, and a user’s own token comes without a commit author\n      ...(git\n        ? {\n            commitAuthor: git.commit_author,\n            ownGitHubToken: git.kind === 'user',\n            tokenExpiresAt: git.expires_at,\n          }\n        : {}),\n    };\n\n    // Store them right away, before the lock is released, rather than waiting for the store to be\n    // saved, so another tab whose token has expired as well takes them instead of refreshing with\n    // the old refresh token, which a service like GitLab revokes once it’s used\n    try {\n      await LocalStorage.set(USER_STORAGE_KEY, user.account);\n    } catch {\n      //\n    }\n  }\n\n  return { token, refreshToken };\n};\n\n/**\n * Refresh the OAuth access token using the refresh token. Requests failing at the same time share a\n * single refresh, as a refresh token may only be used once, e.g. with a GitHub App or Gitea, and\n * each of them refreshing on its own would make all but the first fail.\n * @param {object} args Arguments.\n * @param {string} args.clientId OAuth application ID.\n * @param {string} args.tokenURL OAuth token request URL.\n * @param {string} args.refreshToken OAuth refresh token.\n * @returns {Promise<AuthTokens>} New access token and refresh token.\n */\nexport const refreshAccessToken = ({ clientId, tokenURL, refreshToken }) => {\n  let promise = pendingRefreshes.get(refreshToken);\n\n  if (!promise) {\n    promise = requestTokenRefresh({ clientId, tokenURL, refreshToken }).finally(() => {\n      pendingRefreshes.delete(refreshToken);\n    });\n    pendingRefreshes.set(refreshToken, promise);\n  }\n\n  return promise;\n};\n\n/**\n * Name of the Web Lock held while refreshing the OAuth access token, shared by all the tabs.\n */\nconst TOKEN_REFRESH_LOCK_NAME = 'sveltia-cms.token-refresh';\n\n/**\n * Run a function while holding the token refresh lock, so only one tab at a time refreshes the\n * token, as a refresh token may only be used once. Without the Web Locks API, the function simply\n * runs.\n * @template T\n * @param {() => Promise<T>} func Function to run.\n * @returns {Promise<T>} Result of the function.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API\n */\nconst withTokenRefreshLock = (func) => {\n  const locks = globalThis.navigator?.locks;\n\n  return locks ? locks.request(TOKEN_REFRESH_LOCK_NAME, func) : func();\n};\n\n/**\n * Get the tokens of a stored user if it’s the same account as the current user.\n * @param {any} storedUser User stored by any tab.\n * @returns {AuthTokens | undefined} Tokens, or `undefined` if the stored user is another account,\n * has no refresh token while the current user has one, or no one is signed in.\n */\nconst getStoredTokens = (storedUser) => {\n  const { account } = user;\n\n  const refreshToken = isNonEmptyString(storedUser?.refreshToken)\n    ? storedUser.refreshToken\n    : undefined;\n\n  if (\n    !account ||\n    !isNonEmptyString(storedUser?.token) ||\n    storedUser.backendName !== account.backendName ||\n    storedUser.id !== account.id ||\n    // A Sveltia CMS Additions account has no ID here, so the username tells them apart\n    storedUser.login !== account.login ||\n    // Don’t lose the refresh token\n    (!!account.refreshToken && !refreshToken)\n  ) {\n    return undefined;\n  }\n\n  return { token: storedUser.token, refreshToken };\n};\n\n/**\n * Read the tokens of the current user from the storage, where another tab may have saved the ones\n * it has refreshed.\n * @returns {Promise<AuthTokens | undefined>} Tokens, or `undefined` if the stored user is another\n * account, or the storage can’t be read.\n */\nconst readStoredTokens = async () => {\n  try {\n    return getStoredTokens(await LocalStorage.get(USER_STORAGE_KEY));\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Check whether the given tokens have replaced the ones a request was sent with: another request,\n * or another tab, has refreshed them meanwhile, which replaces both.\n * @param {Partial<AuthTokens> | undefined} tokens Current tokens, if any.\n * @param {object} sent Tokens the request was sent with.\n * @param {string | undefined} sent.token OAuth access token.\n * @param {string | undefined} sent.refreshToken OAuth refresh token.\n * @returns {tokens is AuthTokens} Result.\n */\nexport const isRefreshedElsewhere = (tokens, { token, refreshToken }) =>\n  !!tokens?.token && tokens.token !== token && tokens.refreshToken !== refreshToken;\n\n/**\n * Take the tokens another tab has refreshed as soon as it stores them, so this tab doesn’t keep\n * using the old ones, which may have been revoked, or later write them back over the new ones.\n * @param {StorageEvent} event `storage` event.\n */\nconst onUserStorageChange = ({ key, newValue }) => {\n  if (key !== USER_STORAGE_KEY || !newValue) {\n    return;\n  }\n\n  /** @type {any} */\n  let storedUser;\n\n  try {\n    storedUser = JSON.parse(newValue);\n  } catch {\n    return;\n  }\n\n  const tokens = getStoredTokens(storedUser);\n  // The account is there if the tokens are\n  const { account } = /** @type {{ account: User }} */ (user);\n\n  if (tokens && (tokens.token !== account.token || tokens.refreshToken !== account.refreshToken)) {\n    user.account = { ...account, ...tokens };\n  }\n};\n\nglobalThis.addEventListener?.('storage', onUserStorageChange);\n\n/**\n * Send a request to the REST or GraphQL API of a Git-based service with authentication. This\n * function is a wrapper around {@link sendRequest} that automatically adds the `Authorization`\n * header with the OAuth access token. It also handles the case where the access token needs to be\n * refreshed when the request fails with a 401 Unauthorized status.\n * @param {string} path API endpoint path.\n * @param {FetchApiOptions} [options] Fetch options.\n * @returns {Promise<object | string | Blob | Response>} Response data or `Response` itself,\n * depending on the `responseType` option.\n * @throws {Error} When there was an error in the API request, e.g. OAuth app access restrictions.\n * @see https://docs.github.com/en/rest\n * @see https://docs.gitlab.com/api/rest/\n * @see https://gitea.com/api/swagger\n * @see https://codeberg.org/api/swagger\n */\nexport const fetchAPI = async (\n  path,\n  {\n    method = 'GET',\n    headers = {},\n    body = null,\n    isGraphQL = false,\n    responseType = 'json',\n    token = undefined,\n    refreshToken = undefined,\n    retryable = undefined,\n  } = {},\n) => {\n  const {\n    clientId,\n    tokenURL,\n    restBaseURL,\n    graphqlBaseURL,\n    authScheme = 'token',\n    includeCredentials,\n  } = apiConfig;\n\n  const _user = user.account;\n  const baseURL = isGraphQL ? graphqlBaseURL : restBaseURL;\n\n  token ??= _user?.token;\n  refreshToken ??= _user?.refreshToken;\n  headers.Authorization = `${authScheme} ${token}`;\n\n  // Whether the request is sent with the current user’s tokens, rather than with ones being signed\n  // in with, while the user store may still hold a previous session of another account\n  const isUserToken = !!_user && token === _user.token && refreshToken === _user.refreshToken;\n\n  return sendRequest(\n    `${baseURL}${path}`,\n    {\n      method,\n      headers,\n      body,\n      ...(includeCredentials && { credentials: 'include' }),\n    },\n    {\n      responseType,\n      retryable,\n      refreshAccessToken: refreshToken\n        ? () =>\n            withTokenRefreshLock(async () => {\n              if (isUserToken) {\n                const { account } = user;\n\n                // Another request has refreshed the token since this one was sent, which used up\n                // the refresh token if it’s single-use, so take the new token instead of refreshing\n                // again\n                if (account && isRefreshedElsewhere(account, { token, refreshToken })) {\n                  return { token: account.token, refreshToken: account.refreshToken };\n                }\n\n                // The same goes for another tab, which stores the tokens it has refreshed\n                const stored = await readStoredTokens();\n\n                if (stored && isRefreshedElsewhere(stored, { token, refreshToken })) {\n                  user.account = { .../** @type {User} */ (user.account), ...stored };\n\n                  return stored;\n                }\n              }\n\n              return refreshAccessToken({ clientId, tokenURL, refreshToken });\n            })\n        : undefined,\n    },\n  );\n};\n\n/**\n * Send a request to the GraphQL API of a Git-based service. This function is a wrapper around\n * {@link fetchAPI} and automatically applies the common variables defined in {@link graphqlVars} to\n * the query. Variables can also be passed as an argument to override the defaults.\n * @param {string} query Query string.\n * @param {Record<string, any>} [variables] Any variable to be applied.\n * @param {object} [options] Options.\n * @param {boolean} [options.retryable] Whether the request can be sent again after a transient\n * error. See {@link sendRequest}.\n * @returns {Promise<Record<string, any>>} Response data.\n * @see https://docs.github.com/en/graphql\n * @see https://docs.gitlab.com/api/graphql/\n */\nexport const fetchGraphQL = async (query, variables = {}, { retryable } = {}) => {\n  // Normalize the query by removing line breaks and subsequent space characters. We must be careful\n  // as file paths may contain spaces.\n  query = query.replace(/\\n\\s*/g, ' ');\n\n  // Apply common variables defined in `graphqlVars` to the query\n  Object.entries(graphqlVars).forEach(([key, value]) => {\n    if (query.includes(`$${key}`)) {\n      variables[key] ??= value;\n    }\n  });\n\n  // Extract `data` from the response\n  const { data } = await /** @type {Promise<{ data: Record<string, any> }>} */ (\n    fetchAPI('', { method: 'POST', body: { query, variables }, isGraphQL: true, retryable })\n  );\n\n  return data;\n};\n","import { fetchAPI } from '$lib/services/backends/git/shared/api';\nimport { user } from '$lib/services/user/account.svelte';\n\n/**\n * @import { AuthTokens, User } from '$lib/types/private';\n * @import { BackendName } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} UserFieldMap\n * @property {string} name Response field name for the user’s full name.\n * @property {string} login Response field name for the user’s login name.\n * @property {string} profileURL Response field name for the user’s profile page URL.\n */\n\n/**\n * Retrieve the authenticated user’s profile information from the `/user` REST API endpoint.\n * @param {AuthTokens} tokens Authentication tokens.\n * @param {BackendName | 'local'} backendName Backend name, e.g. `github`.\n * @param {UserFieldMap} fieldMap Mapping of normalized field names to provider-specific response\n * field names.\n * @returns {Promise<User>} User information.\n */\nexport const fetchUserProfile = async ({ token, refreshToken }, backendName, fieldMap) => {\n  // The stored account may belong to someone else, e.g. a previous session the user is signing in\n  // again from, so its tokens are only taken if they change during the request\n  const tokenBefore = user.account?.token;\n\n  const response = /** @type {Record<string, any>} */ (\n    await fetchAPI('/user', { token, refreshToken })\n  );\n\n  const _user = user.account;\n\n  // Update the tokens because these may have been renewed in `refreshAccessToken` while fetching\n  // the user info\n  if (_user?.token && _user.token !== token && _user.token !== tokenBefore) {\n    token = _user.token;\n    refreshToken = _user.refreshToken;\n  }\n\n  return {\n    backendName,\n    id: response.id,\n    name: response[fieldMap.name],\n    login: response[fieldMap.login],\n    email: response.email,\n    avatarURL: response.avatar_url,\n    profileURL: response[fieldMap.profileURL],\n    bot: response.bot ?? false,\n    token,\n    refreshToken,\n  };\n};\n","import { BACKEND_NAME } from '$lib/services/backends/git/github/constants';\nimport { fetchUserProfile } from '$lib/services/backends/git/shared/user';\n\n/**\n * @import { AuthTokens, User } from '$lib/types/private';\n */\n\n/**\n * Retrieve the authenticated user’s profile information from GitHub REST API.\n * @param {AuthTokens} tokens Authentication tokens.\n * @returns {Promise<User>} User information.\n * @see https://docs.github.com/en/rest/users/users#get-the-authenticated-user\n */\nexport const getUserProfile = (tokens) =>\n  fetchUserProfile(tokens, BACKEND_NAME, {\n    name: 'name',\n    login: 'login',\n    profileURL: 'html_url',\n  });\n","export const BACKEND_NAME = 'gitea';\nexport const BACKEND_LABEL = 'Gitea / Forgejo';\n\n/**\n * Name of the backend Decap CMS 3.15 introduced for Forgejo. It’s served by the same\n * implementation, except that the instance URL is derived from the required `api_root` option.\n * @see https://decapcms.org/docs/gitea-backend/#forgejo-backend\n */\nexport const FORGEJO_BACKEND_NAME = 'forgejo';\nexport const FORGEJO_BACKEND_LABEL = 'Forgejo';\n\n/**\n * Names of the backends served by this implementation.\n * @type {string[]}\n */\nexport const BACKEND_NAMES = [BACKEND_NAME, FORGEJO_BACKEND_NAME];\n\n/**\n * Check if the given backend name is served by the Gitea/Forgejo implementation: `gitea`, or\n * `forgejo` as named in Decap CMS.\n * @param {string | undefined} name Backend name.\n * @returns {boolean} Result.\n */\nexport const isGiteaBackendName = (name) => !!name && BACKEND_NAMES.includes(name);\n\nexport const DEFAULT_API_ROOT = 'https://gitea.com/api/v1';\nexport const DEFAULT_AUTH_ROOT = 'https://gitea.com';\nexport const DEFAULT_AUTH_PATH = 'login/oauth/authorize';\n\n/**\n * Minimum supported Gitea version. We require at least 1.24 to use the new `file-contents` API\n * endpoint.\n * @see https://github.com/go-gitea/gitea/pull/34139\n */\nexport const MIN_GITEA_VERSION = 1.24;\n\n/**\n * Minimum supported Forgejo version. We require at least 12.0 to use the new `git/blobs` API\n * endpoint.\n * @see https://codeberg.org/forgejo/forgejo/pulls/8139\n */\nexport const MIN_FORGEJO_VERSION = 12;\n","import { _ } from '@sveltia/i18n';\nimport { generateRandomId, generateUUID, getHash } from '@sveltia/utils/crypto';\nimport { isObject } from '@sveltia/utils/object';\nimport { LocalStorage } from '@sveltia/utils/storage';\n\nimport { isGiteaBackendName } from '$lib/services/backends/git/gitea/constants';\nimport {\n  requestAccessToken,\n  apiConfig as sharedApiConfig,\n} from '$lib/services/backends/git/shared/api';\nimport { cmsConfig } from '$lib/services/config';\nimport { USER_STORAGE_KEY } from '$lib/services/user/constants';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * ApiEndpointConfig,\n * AuthTokens,\n * InternalCmsConfig,\n * SignInOptions,\n * User,\n * } from '$lib/types/private';\n * @import { GitBackend } from '$lib/types/public';\n */\n\n/**\n * Whether the app is running in the authentication popup window.\n */\nexport const inAuthPopup = createRawState(false);\n\n/**\n * Function that cancels the pending authentication, so the user can get out of a sign-in whose\n * popup was closed without the app noticing, or `undefined` if no popup is pending.\n * @type {{ current: (() => void) | undefined }}\n */\nexport const cancelAuthorization = createRawState();\n\n/**\n * Local storage key for the temporary secrets of the client-side Authorization Code Flow.\n */\nconst AUTH_SECRETS_STORAGE_KEY = 'sveltia-cms.auth';\n/**\n * Session storage key under which the auth popup keeps the `state` of its flow, so it can still\n * recognize itself when it comes back without a window opener and window name. See\n * {@link isAuthPopup}.\n */\nconst AUTH_POPUP_STORAGE_KEY = 'sveltia-cms.auth-popup';\n/**\n * Get the name of the `BroadcastChannel` that carries the result of a client-side flow from the\n * auth popup to the window that opened it, when the two have been severed. The name is tied to the\n * flow’s `state`, so another flow, or a window that doesn’t know the `state`, can’t take part.\n * @param {string} state Authorization state, which is the CSRF token of the flow.\n * @returns {string} Channel name.\n */\nconst getAuthChannelName = (state) => `sveltia-cms.auth.${state}`;\n\n/**\n * Get the message the auth popup sends its opener to start the handshake, which the opener sends\n * back to ask for the result. The format is the one Netlify/Decap CMS and its authenticators use.\n * @param {string} provider Backend name, e.g. `github`.\n * @returns {string} Message in the `authorizing:{provider}` format.\n */\nexport const formatHandshakeMessage = (provider) => `authorizing:${provider}`;\n\n/**\n * Get the message the auth popup sends to pass the result of the flow on.\n * @param {string} provider Backend name, e.g. `github`.\n * @param {'success' | 'error'} status Whether the flow has succeeded.\n * @param {Record<string, any>} content Result: the tokens, or the error.\n * @returns {string} Message in the `authorization:{provider}:{status}:{result}` format, the result\n * being serialized as JSON.\n */\nexport const formatResultMessage = (provider, status, content) =>\n  `authorization:${provider}:${status}:${JSON.stringify(content)}`;\n\n/**\n * Extract the result from a message built with {@link formatResultMessage}.\n * @param {string} provider Backend name, e.g. `github`.\n * @param {string} data Message.\n * @returns {string | undefined} Serialized result, or `undefined` if the message isn’t a result\n * for the given backend, or comes without one.\n */\nexport const parseResultMessage = (provider, data) =>\n  data.match(`^authorization:${provider}:(success|error):(?<result>.+)`)?.groups?.result;\n\n/**\n * Get the flow `state` stored in the auth popup’s session storage.\n * @returns {string | null} State, or `null` if it’s not stored or session storage is unavailable.\n */\nconst getAuthPopupState = () => {\n  try {\n    return window.sessionStorage.getItem(AUTH_POPUP_STORAGE_KEY);\n  } catch {\n    return null;\n  }\n};\n\n/**\n * Store the flow `state` in the auth popup’s session storage, or remove it.\n * @param {string} [state] State. Omit to remove it.\n */\nconst setAuthPopupState = (state) => {\n  try {\n    if (state) {\n      window.sessionStorage.setItem(AUTH_POPUP_STORAGE_KEY, state);\n    } else {\n      window.sessionStorage.removeItem(AUTH_POPUP_STORAGE_KEY);\n    }\n  } catch {\n    //\n  }\n};\n\n/**\n * Remove the temporary secrets of the client-side flow, as the flow is over.\n */\nconst clearAuthSecrets = async () => {\n  setAuthPopupState();\n  await LocalStorage.delete(AUTH_SECRETS_STORAGE_KEY);\n};\n\n/**\n * Create the error thrown when the user closes the authentication popup, which callers tell apart\n * from a failure by its name.\n * @returns {Error} Error.\n */\nconst createAbortError = () =>\n  Object.assign(new Error('Authentication aborted'), { name: 'AbortError' });\n\n/**\n * Open a popup window for authentication.\n * @param {object} args Arguments.\n * @param {string} args.authURL Authentication site URL.\n * @returns {Window | null} Popup window object or `null` if the popup could not be opened.\n */\nexport const openPopup = ({ authURL }) => {\n  const width = 600;\n  const height = 800;\n  const { availHeight, availWidth } = window.screen;\n  const top = availHeight / 2 - height / 2;\n  const left = availWidth / 2 - width / 2;\n\n  return window.open(authURL, 'auth', `width=${width},height=${height},top=${top},left=${left}`);\n};\n\n/**\n * Authenticate with a Git service provider through Netlify Identity or other 3rd party OAuth client\n * specified with the configuration file.\n * @param {object} args Arguments.\n * @param {string} args.backendName Backend name, e.g. `github`.\n * @param {string} args.authURL Authentication site URL.\n * @param {Window | null} [args.popup] Optional pre-opened popup window. If not provided, a new\n * popup will be opened.\n * @param {string} [args.state] Authorization state of a client-side flow. If provided, the result\n * is also accepted over the flow’s `BroadcastChannel`, for when the popup comes back without a\n * window opener.\n * @returns {Promise<AuthTokens>} Auth access token and refresh token.\n * @throws {Error} When authentication failed or the popup window is closed before the auth process\n * is complete.\n * @see https://decapcms.org/docs/backends-overview/\n * @see https://sveltiacms.app/en/docs/backends\n */\nexport const authorize = async ({ backendName, authURL, popup, state }) => {\n  const authPopup = popup ?? openPopup({ authURL });\n\n  // Without a popup, there’s no window the result could come from\n  if (!authPopup) {\n    throw createAbortError();\n  }\n\n  return new Promise((resolve, reject) => {\n    // Detaches the `message` listener below. Every exit path aborts it, including the one where the\n    // user closes the popup: otherwise each cancelled sign-in would leave a listener — and the\n    // popup and promise callbacks it captures — attached to the window for the rest of the session.\n    const controller = new AbortController();\n    const provider = backendName;\n    /**\n     * Channel the popup sends the result over when it comes back without a window opener: GitLab’s\n     * sign-in page is served with `Cross-Origin-Opener-Policy: same-origin`, which severs the popup\n     * from this window, so neither window can post a message to the other any more.\n     */\n    const channel = state ? new BroadcastChannel(getAuthChannelName(state)) : undefined;\n    /**\n     * Timer to check if the popup is closed.\n     * @type {ReturnType<typeof setInterval> | undefined}\n     */\n    let timer;\n\n    /**\n     * Stop listening for the result.\n     */\n    const cleanUp = () => {\n      controller.abort();\n      clearInterval(timer);\n      channel?.close();\n      cancelAuthorization.current = undefined;\n    };\n\n    /**\n     * Give up on the authentication, because the popup was closed or the user cancelled it.\n     */\n    const cancel = () => {\n      cleanUp();\n      authPopup.close();\n      reject(createAbortError());\n    };\n\n    // The timer doesn’t work with GitLab: the same header makes `closed` `true` while the popup is\n    // still open. The user can cancel the sign-in instead\n    if (backendName === 'github' || isGiteaBackendName(backendName)) {\n      timer = setInterval(() => {\n        if (authPopup.closed) {\n          cancel();\n        }\n      }, 1000);\n    }\n\n    /**\n     * Settle the promise with the result sent by the popup.\n     * @param {string} data Message in the `authorization:{provider}:{status}:{result}` format.\n     */\n    const handleResult = (data) => {\n      const resultStr = parseResultMessage(provider, data);\n      /**\n       * @type {{ token: string, refreshToken?: string } | { error: string, errorCode?: string }}\n       */\n      let result;\n\n      try {\n        result = resultStr ? JSON.parse(resultStr) : { error: 'No data' };\n\n        if (!isObject(result)) {\n          result = { error: 'Malformed data' };\n        }\n      } catch {\n        result = { error: 'Malformed data' };\n      }\n\n      if ('token' in result) {\n        resolve(result);\n      } else {\n        reject(\n          new Error('Authentication failed', {\n            cause: new Error(\n              result.errorCode\n                ? _(`sign_in_error.${result.errorCode}`, { default: result.error })\n                : result.error,\n            ),\n          }),\n        );\n      }\n\n      cleanUp();\n      authPopup.close();\n    };\n\n    /**\n     * Message event handler. Only messages from the popup itself are handled, so another window,\n     * even on the same origin, can neither take part in the handshake nor inject a token.\n     * @param {object} args Arguments.\n     * @param {string} args.origin Origin URL.\n     * @param {string} args.data Passed data.\n     * @param {MessageEventSource | null} args.source Window that sent the message.\n     */\n    const handler = ({ origin, data, source }) => {\n      if (source !== authPopup || origin !== new URL(authURL).origin || typeof data !== 'string') {\n        return;\n      }\n\n      // First message\n      if (data === formatHandshakeMessage(provider)) {\n        authPopup.postMessage(data, origin);\n\n        return;\n      }\n\n      // Second message\n      handleResult(data);\n    };\n\n    window.addEventListener('message', handler, { signal: controller.signal });\n\n    if (channel) {\n      /**\n       * Channel message handler. There’s no handshake here: only a window that knows the `state`\n       * can post to the channel.\n       * @param {MessageEvent} event Event.\n       */\n      channel.onmessage = ({ data }) => {\n        if (typeof data === 'string') {\n          handleResult(data);\n        }\n      };\n    }\n\n    cancelAuthorization.current = cancel;\n  });\n};\n\n/**\n * Initialize the server-side Authorization Code Flow.\n * @param {object} args Arguments.\n * @param {string} args.backendName Backend name, e.g. `github`.\n * @param {string | undefined} args.siteDomain Domain of the site hosting the CMS. Could be\n * `undefined` if the `site_domain` option is not specified in the backend configuration.\n * @param {string} args.authURL Authorization site URL.\n * @param {string} args.scope Authorization scope.\n * @returns {Promise<AuthTokens>} Auth access token and refresh token.\n */\nexport const initServerSideAuth = async ({ backendName, siteDomain, authURL, scope }) => {\n  const { hostname } = window.location;\n\n  // If the site domain is not specified, use the current hostname. If the hostname is `localhost`,\n  // use `cms.netlify.com` as the default site domain.\n  // @see https://decapcms.org/docs/backends-overview/\n  siteDomain ??= hostname === 'localhost' ? 'cms.netlify.com' : hostname;\n\n  try {\n    // `siteDomain` may contain non-ASCII characters. When authenticating with Netlify, such\n    // internationalized domain names (IDNs) must be written in Punycode. Use `URL` for conversion,\n    // e.g `日本語.jp` -> `xn--wgv71a119e.jp`\n    if (new URL(authURL).origin === 'https://api.netlify.com') {\n      siteDomain = new URL(`https://${siteDomain}`).hostname;\n    }\n  } catch {\n    //\n  }\n\n  const params = new URLSearchParams({\n    provider: backendName,\n    site_id: siteDomain,\n    scope,\n  });\n\n  return authorize({\n    backendName,\n    authURL: `${authURL}?${params}`,\n  });\n};\n\n/**\n * Create a code verifier and challenge for PKCE auth along with a CSRF token.\n * @returns {Promise<{ csrfToken: string, codeVerifier: string, codeChallenge: string}>} Secrets.\n * @see https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs\n */\nexport const createAuthSecrets = async () => {\n  const codeVerifier = `${generateRandomId()}${generateRandomId()}`;\n\n  const codeChallenge = btoa(\n    await getHash(codeVerifier, { algorithm: 'SHA-256', format: 'binary' }),\n  )\n    .replace(/\\+/g, '-')\n    .replace(/\\//g, '_')\n    .replace(/=+$/, '');\n\n  return {\n    csrfToken: generateUUID().replaceAll('-', ''),\n    codeVerifier,\n    codeChallenge,\n  };\n};\n\n/**\n * Initialize the client-side Authorization Code Flow with PKCE.\n * @param {object} args Arguments.\n * @param {string} args.backendName Backend name, e.g. `gitlab`.\n * @param {string} args.clientId OAuth application ID.\n * @param {string | (() => Promise<string>)} args.authURL Authorization site URL, or a function\n * that gets it, e.g. with a request, once the popup has opened: the popup has to open first.\n * @param {string} args.scope Authorization scope.\n * @returns {Promise<AuthTokens>} Auth access token and refresh token.\n * @see https://docs.gitlab.com/ee/api/oauth2.html#authorization-code-with-proof-key-for-code-exchange-pkce\n */\nexport const initClientSideAuth = async ({ backendName, clientId, authURL: _authURL, scope }) => {\n  const { origin, pathname } = window.location;\n  const redirectURL = `${origin}${pathname}`;\n  // Open the popup immediately to prevent Safari from blocking it. Safari blocks popups that aren’t\n  // opened synchronously from a user interaction.\n  const popup = openPopup({ authURL: redirectURL });\n\n  if (!popup) {\n    throw createAbortError();\n  }\n\n  // Perform async operations after opening the popup\n  /** @type {string} */\n  let authURL;\n\n  try {\n    authURL = typeof _authURL === 'function' ? await _authURL() : _authURL;\n  } catch (ex) {\n    popup.close();\n\n    throw ex;\n  }\n\n  const { csrfToken, codeVerifier, codeChallenge } = await createAuthSecrets();\n\n  const params = new URLSearchParams({\n    client_id: clientId,\n    redirect_uri: redirectURL,\n    response_type: 'code',\n    state: csrfToken,\n    scope,\n    code_challenge: codeChallenge,\n    code_challenge_method: 'S256',\n  });\n\n  // Store the temporary secret and real auth URL\n  await LocalStorage.set(AUTH_SECRETS_STORAGE_KEY, {\n    csrfToken,\n    codeVerifier,\n    // The URL may have a query already, e.g. the reference to a Sveltia CMS Additions user\n    realAuthURL: `${authURL}${authURL.includes('?') ? '&' : '?'}${params}`,\n  });\n\n  // Store the user info only with the backend name, so the automatic sign-in flow that triggers\n  // `finishClientSideAuth` below will work\n  await LocalStorage.set(USER_STORAGE_KEY, { backendName });\n\n  // Check if the popup was closed while we were doing async operations\n  if (popup.closed) {\n    throw createAbortError();\n  }\n\n  try {\n    return await authorize({ backendName, authURL: redirectURL, popup, state: csrfToken });\n  } catch (ex) {\n    // The popup may still be open if it was severed from this window, so make sure it can’t finish\n    // the flow the user has given up on\n    await LocalStorage.delete(AUTH_SECRETS_STORAGE_KEY);\n\n    throw ex;\n  }\n};\n\n/**\n * Communicate with the window opener as part of {@link finishClientSideAuth}. If the popup has no\n * opener because it was severed from it, the result is sent over the flow’s `BroadcastChannel`\n * instead, and the popup closes itself, as the opener can no longer close it.\n * @param {object} args Options.\n * @param {string} [args.provider] Backend name, e,g. `github`.\n * @param {string} [args.state] Authorization state of the flow, which names the channel. Tokens\n * must only be sent once the state has been verified.\n * @param {string} [args.token] OAuth access token.\n * @param {string} [args.refreshToken] OAuth refresh token.\n * @param {string} [args.error] Error message when an OAuth token is not available.\n * @param {string} [args.errorCode] Error code to be used to localize the error message in Sveltia\n * CMS.\n */\nexport const sendMessage = ({\n  provider = 'unknown',\n  state,\n  token,\n  refreshToken,\n  error,\n  errorCode,\n}) => {\n  const _state = error ? 'error' : 'success';\n  const content = error ? { provider, error, errorCode } : { provider, token, refreshToken };\n\n  if (!window.opener) {\n    if (state) {\n      const channel = new BroadcastChannel(getAuthChannelName(state));\n\n      channel.postMessage(formatResultMessage(provider, _state, content));\n      channel.close();\n      window.close();\n    }\n\n    return;\n  }\n\n  /**\n   * Listener for messages from the window opener. The tokens are only sent back to the opener, and\n   * only when it’s on the same origin as this popup, so no other window holding a reference to the\n   * popup can obtain them by starting the handshake.\n   * @param {MessageEvent} event Event.\n   */\n  const onMessage = ({ data, origin, source }) => {\n    if (\n      source === window.opener &&\n      origin === window.location.origin &&\n      data === formatHandshakeMessage(provider)\n    ) {\n      window.opener?.postMessage(formatResultMessage(provider, _state, content), origin);\n      // The handshake is complete; remove the listener so repeated auth flows don’t accumulate.\n      window.removeEventListener('message', onMessage);\n    }\n  };\n\n  window.addEventListener('message', onMessage);\n  window.opener?.postMessage(formatHandshakeMessage(provider), window.location.origin);\n};\n\n/**\n * Complete the client-side Authorization Code Flow with PKCE by retrieving an access token and\n * passing it to the window opener. This code is to be called within the auth popup window and\n * basically does the same thing as the callback handler of Sveltia CMS Authenticator.\n * @param {object} args Arguments.\n * @param {string} args.backendName Backend name, e.g. `gitlab`.\n * @param {ApiEndpointConfig} args.apiConfig API endpoint configuration.\n * @param {string} args.code Authorization code.\n * @param {string} args.state Authorization state, which is a CSRF token previously set.\n * @returns {Promise<void>} None.\n * @see https://docs.gitlab.com/ee/api/oauth2.html#authorization-code-with-proof-key-for-code-exchange-pkce\n * @see https://github.com/sveltia/sveltia-cms-auth/blob/main/src/index.js\n */\nexport const finishClientSideAuth = async ({ backendName, apiConfig, code, state }) => {\n  const { clientId, tokenURL, includeCredentials = false } = apiConfig;\n  const { origin, pathname } = new URL(window.location.href);\n  const { csrfToken, codeVerifier } = (await LocalStorage.get(AUTH_SECRETS_STORAGE_KEY)) ?? {};\n  const provider = backendName;\n  const redirectURL = `${origin}${pathname}`;\n\n  // Remove the temporary secret\n  await clearAuthSecrets();\n\n  if (!csrfToken || !codeVerifier || state !== csrfToken) {\n    return sendMessage({\n      provider,\n      state,\n      error: _('sign_in_error.CSRF_DETECTED'),\n      errorCode: 'CSRF_DETECTED',\n    });\n  }\n\n  let token = '';\n  let refreshToken = '';\n  let error = '';\n\n  const response = await requestAccessToken(\n    tokenURL,\n    {\n      grant_type: 'authorization_code',\n      client_id: clientId,\n      code,\n      redirect_uri: redirectURL,\n      code_verifier: codeVerifier,\n    },\n    { includeCredentials },\n  );\n\n  if (!response) {\n    return sendMessage({\n      provider,\n      state,\n      error: _('sign_in_error.TOKEN_REQUEST_FAILED'),\n      errorCode: 'TOKEN_REQUEST_FAILED',\n    });\n  }\n\n  try {\n    ({ access_token: token, refresh_token: refreshToken, error } = await response.json());\n  } catch {\n    return sendMessage({\n      provider,\n      state,\n      error: _('sign_in_error.MALFORMED_RESPONSE'),\n      errorCode: 'MALFORMED_RESPONSE',\n    });\n  }\n\n  return sendMessage({ provider, state, token, refreshToken, error });\n};\n\n/**\n * Handle the client-side Authorization Code Flow with PKCE within the auth popup window. Redirect\n * to the authorization site or finish the flow after being redirected from the auth site.\n * @param {object} args Arguments.\n * @param {string} args.backendName Backend name, e.g. `gitlab`.\n * @param {ApiEndpointConfig} args.apiConfig API endpoint configuration.\n */\nexport const handleClientSideAuthPopup = async ({ backendName, apiConfig }) => {\n  inAuthPopup.current = true;\n\n  const { search } = window.location;\n\n  const {\n    code,\n    state,\n    error,\n    error_description: errorDescription,\n  } = Object.fromEntries(new URLSearchParams(search));\n\n  if (code && state) {\n    await finishClientSideAuth({ backendName, apiConfig, code, state });\n  } else if (error) {\n    // The user denied access, or the authorization failed, e.g. `?error=access_denied&state=…`.\n    // Report it to the opener, which would otherwise wait forever, instead of showing the\n    // authorization page again, and remove the temporary secret as the flow is over\n    await clearAuthSecrets();\n\n    sendMessage({\n      provider: backendName,\n      state,\n      error: errorDescription || error,\n      errorCode: 'AUTH_CODE_REQUEST_FAILED',\n    });\n  } else {\n    const { csrfToken, realAuthURL } = (await LocalStorage.get(AUTH_SECRETS_STORAGE_KEY)) ?? {};\n\n    if (realAuthURL) {\n      // Remember the flow, as the popup may come back from the authorization site without a window\n      // opener and window name\n      setAuthPopupState(csrfToken);\n      window.location.href = realAuthURL;\n    }\n  }\n};\n\n/**\n * Check whether the app is running in the authentication popup window opened by\n * {@link initClientSideAuth}.\n *\n * A page served with `Cross-Origin-Opener-Policy: same-origin`, like GitLab’s sign-in page, severs\n * the popup from its opener, and Chromium also clears the window name, so the popup comes back to\n * the redirect URL without either. It then recognizes itself by the flow `state` it stored in its\n * session storage before leaving for the authorization site: session storage belongs to the tab,\n * so another tab, even one opened with the callback URL, can’t be mistaken for the popup.\n * @returns {boolean} Result.\n */\nexport const isAuthPopup = () => {\n  try {\n    if (window.opener) {\n      return window.opener.origin === window.location.origin && window.name === 'auth';\n    }\n  } catch {\n    // Reading the origin of a cross-origin opener, e.g. a page linking to the CMS that opened it in\n    // a new tab, throws a `SecurityError`, which would otherwise make every sign-in fail\n    return false;\n  }\n\n  const state = new URLSearchParams(window.location.search).get('state');\n\n  return !!state && state === getAuthPopupState();\n};\n\n/**\n * Handle the authentication flow for a Git service provider. This function decides whether to\n * initiate a client-side or server-side authentication flow based on the configured backend name\n * and authentication type.\n * @param {object} args Arguments.\n * @param {boolean} args.auto Whether the sign-in process is automatic.\n * @param {ApiEndpointConfig} args.apiConfig API endpoint configuration.\n * @returns {Promise<AuthTokens | undefined>} Auth access token and refresh token, or `undefined` if\n * the sign-in process is automatic or the flow is being done in a popup window.\n */\nexport const handleAuthFlow = async ({ auto, apiConfig }) => {\n  const { backend } = /** @type {InternalCmsConfig} */ (cmsConfig.current);\n\n  const {\n    name: backendName,\n    site_domain: siteDomain,\n    // @ts-ignore Gitea backend doesn’t have the property\n    auth_type: authType,\n  } = /** @type {GitBackend} */ (backend);\n\n  const { clientId, authScope, authURL } = apiConfig;\n  const authArgs = { backendName, authURL, scope: authScope };\n\n  // Gitea/Forgejo backend only supports PKCE at this time\n  if (isGiteaBackendName(backendName) || authType === 'pkce') {\n    const inPopup = isAuthPopup();\n\n    if (inPopup) {\n      // We are in the auth popup window; let’s get the OAuth flow done\n      await handleClientSideAuthPopup({ backendName, apiConfig });\n    }\n\n    if (inPopup || auto) {\n      return undefined;\n    }\n\n    return initClientSideAuth({ ...authArgs, clientId });\n  }\n\n  if (auto) {\n    return undefined;\n  }\n\n  return initServerSideAuth({ ...authArgs, siteDomain });\n};\n\n/**\n * Get OAuth tokens by handling the authentication flow if necessary.\n * @param {object} args Arguments.\n * @param {SignInOptions} args.options Options.\n * @param {ApiEndpointConfig} args.apiConfig API endpoint configuration.\n * @returns {Promise<AuthTokens | undefined>} Auth access token and refresh token, or `undefined` if\n * the sign-in process is automatic or the flow is being done in a popup window.\n */\nexport const getTokens = async ({ options: { token, refreshToken, auto = false }, apiConfig }) => {\n  if (!token) {\n    const result = await handleAuthFlow({ auto, apiConfig });\n\n    if (!result) {\n      return undefined;\n    }\n\n    ({ token, refreshToken } = result);\n  }\n\n  return { token, refreshToken };\n};\n\n/**\n * Sign in with a backend’s REST API: the tokens are obtained by running the authentication flow if\n * necessary, then the user profile is fetched with the backend-specific function.\n * @param {object} args Arguments.\n * @param {SignInOptions} args.options Options.\n * @param {(tokens: AuthTokens) => Promise<User>} args.getUserProfile Function to retrieve the\n * authenticated user’s profile information from the backend’s REST API.\n * @returns {Promise<User | void>} User info, or nothing when finishing PKCE auth flow in a popup or\n * the sign-in flow cannot be started.\n * @throws {Error} When there was an authentication error.\n */\nexport const signInToBackend = async ({ options, getUserProfile }) => {\n  const { token, refreshToken } = (await getTokens({ options, apiConfig: sharedApiConfig })) ?? {};\n\n  if (!token) {\n    return undefined;\n  }\n\n  return getUserProfile({ token, refreshToken });\n};\n\n/**\n * Sign out from the backend. Nothing to do here.\n * @returns {Promise<void>}\n */\nexport const signOut = async () => undefined;\n","import { loadAdditions } from '$lib/services/app/additions';\nimport { getUserProfile } from '$lib/services/backends/git/github/user';\nimport {\n  signInToBackend,\n  signOut as signOutFromBackend,\n} from '$lib/services/backends/git/shared/auth';\nimport { cmsConfig } from '$lib/services/config';\nimport { isWorkflowConfigured } from '$lib/services/workflow/config';\n\n/**\n * @import { SignInOptions, User } from '$lib/types/private';\n */\n\n/**\n * Get the URL of the page for creating a new Personal Access Token (PAT) on GitHub. The permissions\n * the CMS needs are pre-filled, so a user who follows the link gets a token that works.\n * @param {string} instanceURL Base URL of the GitHub instance, e.g. `https://github.com`. GitHub\n * Enterprise Server doesn’t run under a subpath, so only the origin is used.\n * @returns {string} URL to create a new PAT.\n * @see https://github.blog/changelog/2025-08-26-template-urls-for-fine-grained-pats-and-updated-permissions-ui/\n * @see https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens\n */\nexport const getTokenPageURL = (instanceURL) => {\n  const { origin } = new URL(instanceURL);\n\n  const params = new URLSearchParams({\n    name: 'Sveltia CMS',\n    contents: 'write',\n  });\n\n  // Editorial Workflow opens, labels, merges and closes pull requests. A token with content access\n  // alone gets as far as the commit on the workflow branch, then GitHub refuses to open the pull\n  // request. Pull request access also covers the label writes, which accept either it or issue\n  // access, and the labels are read from the pulls endpoint rather than the issues one.\n  // @see https://github.com/sveltia/sveltia-cms/discussions/1000\n  // @see https://github.com/sveltia/sveltia-cms/issues/1014\n  if (isWorkflowConfigured(cmsConfig.current)) {\n    params.set('pull_requests', 'write');\n  }\n\n  return `${origin}/settings/personal-access-tokens/new?${params}`;\n};\n\n/**\n * Sign in with the GitHub REST API, or with Sveltia CMS Additions when it’s enabled, which hands\n * out the GitHub token instead.\n * @param {SignInOptions} options Options.\n * @returns {Promise<User | void>} User info, or nothing when finishing PKCE auth flow in a popup,\n * the sign-in flow cannot be started, or a Sveltia CMS Additions user must change their password.\n * @throws {Error} When there was an authentication error.\n */\nexport const signIn = async (options) => {\n  const additions = await loadAdditions();\n\n  return additions\n    ? additions.signInWithAdditions(options)\n    : signInToBackend({ options, getUserProfile });\n};\n\n/**\n * Sign out. With Sveltia CMS Additions, this ends the session there, revoking its GitHub token.\n * @returns {Promise<void>}\n */\nexport const signOut = async () => {\n  const additions = await loadAdditions();\n\n  return additions ? additions.signOutFromAdditions() : signOutFromBackend();\n};\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * Progress of a save that takes long enough to be worth reporting: an entry with many new files.\n * @typedef {object} SaveProgress\n * @property {'preparing' | 'committing'} phase What the save is doing. `preparing` is reading and\n * hashing the files to be saved; `committing` is sending them to the repository.\n * @property {number} done Number of files prepared, or commits made.\n * @property {number} total Number of files to prepare, or the estimated number of commits.\n * @property {boolean} approximate Whether `total` is an estimate: the size of each commit follows\n * the upload speed, so the number of commits is only known roughly.\n */\n\n/**\n * A save with fewer files, or commits, than this isn’t worth reporting, as it ends in a moment.\n */\nconst MIN_REPORTED_TOTAL = 2;\n\n/**\n * Progress of the save in flight. It’s `undefined` while nothing is worth reporting.\n * @type {{ current: SaveProgress | undefined }}\n */\nexport const saveProgress = createRawState();\n\n/**\n * Report that the files of a save are being prepared.\n * @param {number} total Number of files to prepare.\n */\nexport const startPreparing = (total) => {\n  saveProgress.current =\n    total >= MIN_REPORTED_TOTAL\n      ? { phase: 'preparing', done: 0, total, approximate: false }\n      : undefined;\n};\n\n/**\n * Report that a file has been prepared. A file saved for several fields is only counted once, so\n * the count never goes past the total.\n */\nexport const advancePreparing = () => {\n  const progress = saveProgress.current;\n\n  if (progress?.phase === 'preparing') {\n    saveProgress.current = { ...progress, done: Math.min(progress.done + 1, progress.total) };\n  }\n};\n\n/**\n * Report the commits made so far, and how many there are likely to be in all.\n * @param {number} done Number of commits made.\n * @param {number} estimatedTotal Estimated number of commits in all. Raised to `done` if lower.\n */\nexport const reportCommits = (done, estimatedTotal) => {\n  const total = Math.max(done, estimatedTotal);\n\n  saveProgress.current =\n    total >= MIN_REPORTED_TOTAL\n      ? { phase: 'committing', done, total, approximate: true }\n      : undefined;\n};\n\n/**\n * Clear the progress, once the save has ended.\n */\nexport const clearSaveProgress = () => {\n  saveProgress.current = undefined;\n};\n","import { locale as appLocale, locales as appLocales, dictionary, waitLocale } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\nimport { LocalStorage } from '@sveltia/utils/storage';\nimport equal from 'fast-deep-equal';\nimport { untrack } from 'svelte';\n\n/**\n * @import { Preferences } from '$lib/types/private';\n */\n\n/**\n * Local storage key for the user preferences. Also used by the i18n service, which reads the\n * language preference synchronously before the preferences below are loaded.\n */\nexport const PREFS_STORAGE_KEY = 'sveltia-cms.prefs';\n\n/**\n * Preference value that makes the UI follow a browser or system setting instead of an explicit\n * choice. It’s the default for both the theme and the language, the latter also being what the\n * legacy `en` locale value is migrated to.\n */\nexport const AUTO_PREF_VALUE = 'auto';\n\n/**\n * @type {{ current: { type: string } | undefined }}\n */\nexport const prefsError = $state({ current: undefined });\n\n/**\n * Current user preferences as reactive state.\n * @type {Preferences}\n */\nexport const prefs = $state({});\n\n/**\n * Whether the stored locale preference has been applied to the app locale.\n */\nlet storedLocaleApplied = false;\n/**\n * Incremented as each locale switch starts. The strings of a locale fetched from the CDN can arrive\n * after the user has picked another one, so only the latest switch is applied once loaded.\n */\nlet localeSwitchCount = 0;\n/**\n * Language preference whose locale was last applied to the app, e.g. {@link AUTO_PREF_VALUE} or\n * `ja`. A locale picked by the user that fails to load is reverted to it, so `auto` stays `auto`\n * rather than becoming the locale it resolved to.\n * @type {string | undefined}\n */\nlet appliedLocalePref;\n\n/**\n * Locale that best matches the browser’s language settings, used while the language preference is\n * {@link AUTO_PREF_VALUE}. It’s populated by `initAppLocale()` and kept up to date there, so that\n * the UI follows a change to those settings without a page reload.\n * @type {{ current: string | undefined }}\n */\nexport const navigatorLocale = $state({ current: undefined });\n\n$effect.root(() => {\n  (async () => {\n    prefsError.current = undefined;\n\n    try {\n      const stored = await LocalStorage.get(PREFS_STORAGE_KEY);\n      // Corrupt or foreign data under the key is as good as none\n      const _prefs = isObject(stored) ? stored : {};\n\n      _prefs.apiKeys ??= {};\n      _prefs.useDraftBackup ??= true;\n      _prefs.closeOnSave ??= true;\n      _prefs.closeWithEscape ??= true;\n      _prefs.underlineLinks ??= true;\n      _prefs.devModeEnabled ??= false;\n      _prefs.localGitCommits ??= false;\n      _prefs.defaultTranslationService ??= 'google';\n      _prefs.locale ??= AUTO_PREF_VALUE;\n\n      // Migrate the legacy `en` value, which predates the regional English variants and used to be\n      // resolved from the browser’s language settings anyway\n      if (_prefs.locale === 'en') {\n        _prefs.locale = AUTO_PREF_VALUE;\n      }\n\n      // Drop the legacy `beta` value, which was used by the removed Beta Features setting\n      delete _prefs.beta;\n\n      Object.assign(prefs, _prefs);\n    } catch {\n      prefsError.current = { type: 'permission_denied' };\n    }\n  })();\n\n  $effect(() => {\n    if (!Object.keys(prefs).length) {\n      return;\n    }\n\n    const snapshot = $state.snapshot(prefs);\n\n    (async () => {\n      try {\n        if (!equal(snapshot, await LocalStorage.get(PREFS_STORAGE_KEY))) {\n          await LocalStorage.set(PREFS_STORAGE_KEY, snapshot);\n        }\n      } catch {\n        //\n      }\n    })();\n\n    const { theme, underlineLinks = true, devModeEnabled: devMode = false } = prefs;\n    const autoTheming = !theme || theme === AUTO_PREF_VALUE;\n    const autoTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n\n    Object.assign(document.documentElement.dataset, {\n      theme: autoTheming ? autoTheme : theme,\n      autoTheming,\n      underlineLinks,\n      devMode,\n    });\n  });\n\n  // Keep this separate from the effect above, so that switching the app locale is not retried\n  // whenever an unrelated preference is updated. A retry can be costly, because the strings for a\n  // locale that failed to load are fetched from the CDN again.\n  $effect(() => {\n    const { locale: localePref } = prefs;\n    const locale = localePref === AUTO_PREF_VALUE ? navigatorLocale.current : localePref;\n\n    if (!locale || !appLocales.includes(locale)) {\n      return;\n    }\n\n    // Don’t track the current locale, which would make this effect re-run on every locale change\n    const previousLocale = untrack(() => appLocale.current);\n    // Whether the user picked the language, as opposed to the stored preference being applied on\n    // startup or the browser’s language settings changing. A failed switch is reverted, while a\n    // stored preference or an automatic switch is kept, the former so that it can be retried on the\n    // next visit, the latter so that the language keeps following the browser\n    const switchedByUser = storedLocaleApplied && localePref !== AUTO_PREF_VALUE;\n\n    storedLocaleApplied = true;\n    localeSwitchCount += 1;\n\n    const switchCount = localeSwitchCount;\n\n    // Load the strings first if the locale is not bundled with the app, so the UI won’t briefly\n    // fall back to the default locale. The loader is registered in `initAppLocale()`.\n    waitLocale(locale).then(() => {\n      // Another locale has been picked in the meantime, which wins\n      if (switchCount !== localeSwitchCount) {\n        return;\n      }\n\n      if (locale in dictionary) {\n        appLocale.set(locale);\n        appliedLocalePref = localePref;\n      } else if (switchedByUser && previousLocale) {\n        // The strings couldn’t be loaded, so keep using the language the user already had instead\n        // of falling back to the default locale. Restore the preference that brought it, or the\n        // locale itself if none has been applied yet, e.g. when the stored one failed to load too\n        prefs.locale = appliedLocalePref ?? previousLocale;\n      }\n    });\n  });\n});\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { getRootDir } from '$lib/services/backends/root-dir';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { encodePathSegments } from '$lib/services/utils/url';\n\n/**\n * @import { RepositoryBaseURLs, RepositoryInfo, RepositoryPath } from '$lib/types/private';\n * @import { BackendName } from '$lib/types/public';\n */\n\n/**\n * @type {RepositoryInfo}\n */\nexport const REPOSITORY_INFO_PLACEHOLDER = {\n  service: '',\n  label: '',\n  owner: '',\n  repo: '',\n  branch: '',\n  repoURL: '',\n  treeBaseURL: '',\n  blobBaseURL: '',\n  isSelfHosted: false,\n  databaseName: '',\n};\n\n/**\n * Regular expression matching the first path segment of a REST API root URL that is exactly `api`,\n * along with everything after it. The origin is matched separately, so a host name starting with\n * `api` is left alone, and so is a path segment that only starts with it, like `apis`.\n */\nconst API_PATH_REGEX = /^(?<origin>(?:[a-z][a-z\\d+.-]*:)?\\/\\/[^/]*)?(?<path>.*?)\\/api(?:\\/.*)?$/i;\n\n/**\n * Get the base URL of the service’s web interface from the REST API root URL. A self-hosted\n * instance can live under a subpath, which is kept.\n * @param {string} restApiRoot REST API root URL. It can be `https://api.github.com`,\n * `https://github.example.com`, `https://gitlab.com/api/v3`, `https://example.com/gitea/api/v1`,\n * etc.\n * @returns {string} Base URL, e.g. `https://github.com` or `https://example.com/gitea`.\n */\nexport const getInstanceURL = (restApiRoot) =>\n  restApiRoot === 'https://api.github.com'\n    ? 'https://github.com'\n    : restApiRoot.replace(API_PATH_REGEX, '$<origin>$<path>');\n\n/**\n * Get the base URL for the repository from the REST API root URL.\n * @param {string} restApiRoot REST API root URL. See {@link getInstanceURL}.\n * @param {string} repoPath Repository path, e.g., `owner/repo`.\n * @returns {string} Base URL for the repository.\n */\nexport const getRepoURL = (restApiRoot, repoPath) => `${getInstanceURL(restApiRoot)}/${repoPath}`;\n\n/**\n * Get the REST API path of the given repository on GitHub or Gitea/Forgejo, whose APIs address a\n * repository the same way. The owner and repository names are encoded, though a valid name never\n * needs it.\n * @param {RepositoryPath} repository Repository.\n * @returns {string} Path, e.g. `/repos/owner/repo`.\n * @see https://docs.github.com/en/rest/repos/repos#get-a-repository\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGet\n */\nexport const getRepositoryPath = ({ owner, repo }) =>\n  `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;\n\n/**\n * Parse a full repository name returned by GitHub or Gitea/Forgejo, like `full_name` or\n * `nameWithOwner`, into the owner and name pair the CMS works with.\n * @param {string} fullName Full name, e.g. `owner/repo`.\n * @returns {RepositoryPath} Repository owner and name.\n */\nexport const toRepositoryPath = (fullName) => {\n  const [owner, repo] = fullName.split('/');\n\n  return { owner, repo };\n};\n\n/**\n * Check whether a full repository name returned by a Git service, like `full_name` on GitHub and\n * Gitea/Forgejo or `path_with_namespace` on GitLab, names the given repository. The services treat\n * owner and repository names as case-insensitive, so they’re compared that way.\n * @param {string | undefined} fullName Full name, e.g. `Owner/Repo`.\n * @param {RepositoryPath} repository Repository to compare with.\n * @returns {boolean} Result. `false` if no name is given.\n */\nexport const isSameRepository = (fullName, { owner, repo }) =>\n  typeof fullName === 'string' && fullName.toLowerCase() === `${owner}/${repo}`.toLowerCase();\n\n/**\n * Get the REST API path of the given pull request on GitHub or Gitea/Forgejo.\n * @param {RepositoryPath} repository Repository holding the pull request.\n * @param {number | undefined} number Pull request number.\n * @returns {string} Path, e.g. `/repos/owner/repo/pulls/1`.\n */\nexport const getPullRequestPath = (repository, number) =>\n  `${getRepositoryPath(repository)}/pulls/${number}`;\n\n/**\n * Get the REST API path of the given branch on GitHub or Gitea/Forgejo.\n * @param {RepositoryPath} repository Repository holding the branch.\n * @param {string} branch Branch name.\n * @returns {string} Path, e.g. `/repos/owner/repo/branches/main`.\n */\nexport const getRestBranchPath = (repository, branch) =>\n  `${getRepositoryPath(repository)}/branches/${encodePathSegments(branch)}`;\n\n/**\n * Create a function to generate base URLs for accessing the repository’s resources on a service’s\n * web interface, which only differs from another service’s by the path segments that come after the\n * repository URL.\n * @param {object} paths Path segments, with a leading slash.\n * @param {string} paths.tree Path to browse a branch, e.g. `/tree`.\n * @param {string} paths.blob Path to read a file on a branch, e.g. `/blob`.\n * @param {string} paths.commit Path to view a commit, e.g. `/commit`.\n * @returns {(repoURL: string, branch?: string) => RepositoryBaseURLs} Function that takes the base\n * URL of the repository and the branch name, which can be `undefined` if the branch is not\n * specified in the CMS configuration, and returns an object containing the tree base URL for\n * browsing files, the blob base URL for accessing file contents, and the commit base URL.\n */\nexport const createBaseURLsGetter =\n  ({ tree, blob, commit }) =>\n  (repoURL, branch) => ({\n    // A branch name may contain a character that ends a URL path, like `#` in `cms/posts/c#`\n    treeBaseURL: branch ? `${repoURL}${tree}/${encodePathSegments(branch)}` : repoURL,\n    blobBaseURL: branch ? `${repoURL}${blob}/${encodePathSegments(branch)}` : '',\n    commitBaseURL: `${repoURL}${commit}`,\n  });\n\n/**\n * Generate the base URLs for accessing the repository’s resources, pointing the tree and blob URLs\n * at the configured root directory, so a file path relative to it can be appended. Without a\n * branch, the tree base URL is the repository itself and there is no blob base URL, so they’re left\n * as they are.\n * @param {(repoURL: string, branch?: string) => RepositoryBaseURLs} getBaseURLs Backend’s function\n * to generate the base URLs.\n * @param {string} repoURL The base URL of the repository.\n * @param {string} [branch] Branch name.\n * @returns {RepositoryBaseURLs} Base URLs.\n */\nconst getScopedBaseURLs = (getBaseURLs, repoURL, branch) => {\n  const urls = getBaseURLs(repoURL, branch);\n  const rootDir = getRootDir();\n\n  if (!rootDir || !branch) {\n    return urls;\n  }\n\n  return {\n    ...urls,\n    treeBaseURL: `${urls.treeBaseURL}/${encodePathSegments(rootDir)}`,\n    blobBaseURL: `${urls.blobBaseURL}/${encodePathSegments(rootDir)}`,\n  };\n};\n\n/**\n * Fill in a backend’s repository info from the CMS configuration during backend initialization.\n * @param {RepositoryInfo} repository Repository info placeholder to be updated in place.\n * @param {object} args Arguments.\n * @param {BackendName} args.service Backend name, e.g. `github`.\n * @param {string} args.label Backend label, e.g. `GitHub`.\n * @param {string} args.owner Repository owner.\n * @param {string} args.repo Repository name.\n * @param {string} [args.branch] Branch name, if specified in the CMS configuration.\n * @param {string} args.restApiRoot REST API root URL of the configured instance.\n * @param {string} args.defaultApiRoot REST API root URL of the service’s hosted instance, used to\n * tell whether the configured instance is self-hosted.\n * @param {(instanceURL: string) => string} args.getTokenPageURL Function to get the URL of the\n * page for creating a new Personal Access Token from the base URL of the service’s web interface.\n * @param {(repoURL: string, branch?: string) => RepositoryBaseURLs} args.getBaseURLs Function to\n * generate the base URLs for accessing the repository’s resources.\n * @returns {RepositoryInfo} The updated repository info.\n */\nexport const initRepositoryInfo = (\n  repository,\n  {\n    service,\n    label,\n    owner,\n    repo,\n    branch,\n    restApiRoot,\n    defaultApiRoot,\n    getTokenPageURL,\n    getBaseURLs,\n  },\n) => {\n  // Drop any trailing slash from the configured URL, e.g. `https://gitlab.com/api/v4/`, so the\n  // hosted service isn’t taken for a self-hosted instance and the repository URL has no `//`\n  restApiRoot = stripSlashes(restApiRoot);\n\n  const repoPath = `${owner}/${repo}`;\n  const repoURL = getRepoURL(restApiRoot, repoPath);\n  const rootDir = getRootDir();\n\n  Object.assign(\n    repository,\n    /** @type {RepositoryInfo} */ ({\n      service,\n      label,\n      owner,\n      repo,\n      branch,\n      repoURL,\n      tokenPageURL: getTokenPageURL(getInstanceURL(restApiRoot)),\n      // The cached files are keyed with paths relative to the root directory, so each directory\n      // of a monorepo gets a database of its own\n      databaseName: rootDir ? `${service}:${repoPath}:${rootDir}` : `${service}:${repoPath}`,\n      isSelfHosted: restApiRoot !== defaultApiRoot,\n    }),\n    getScopedBaseURLs(getBaseURLs, repoURL, branch),\n  );\n\n  if (prefs.devModeEnabled) {\n    // eslint-disable-next-line no-console\n    console.info('repositoryInfo', repository);\n  }\n\n  return repository;\n};\n\n/**\n * Apply the default branch name fetched from the backend to the repository info, once the branch\n * is not specified in the CMS configuration.\n * @param {RepositoryInfo} repository Repository info to be updated in place.\n * @param {object} args Arguments.\n * @param {boolean} args.found Whether the repository was found on the backend.\n * @param {string | undefined} args.branch Default branch name, which is typically `master` or\n * `main`, or `undefined` if the repository is empty.\n * @param {(repoURL: string, branch?: string) => RepositoryBaseURLs} args.getBaseURLs Function to\n * generate the base URLs for accessing the repository’s resources.\n * @returns {string} Branch name.\n * @throws {Error} When the repository could not be found, or when the repository is empty.\n */\nexport const applyDefaultBranch = (repository, { found, branch, getBaseURLs }) => {\n  const { repo, repoURL = '' } = repository;\n\n  if (!found) {\n    throw createLocalizedError(\n      'Failed to retrieve the default branch name.',\n      'repository_not_found',\n      { repo },\n    );\n  }\n\n  if (!branch) {\n    throw createLocalizedError('Failed to retrieve the default branch name.', 'repository_empty', {\n      repo,\n    });\n  }\n\n  Object.assign(repository, { branch }, getScopedBaseURLs(getBaseURLs, repoURL, branch));\n\n  return branch;\n};\n","import { recordBranchAccess } from '$lib/services/backends/branch-access';\nimport { fetchAPI, fetchGraphQL, graphqlVars } from '$lib/services/backends/git/shared/api';\nimport {\n  createPermissionError,\n  toRepositoryAccessError,\n} from '$lib/services/backends/git/shared/errors';\nimport {\n  applyDefaultBranch,\n  createBaseURLsGetter,\n  getRepositoryPath,\n  REPOSITORY_INFO_PLACEHOLDER,\n} from '$lib/services/backends/git/shared/repository';\n\n/**\n * @import { RepositoryBaseURLs, RepositoryInfo } from '$lib/types/private';\n */\n\n/**\n * Placeholder for repository information.\n * @type {RepositoryInfo}\n */\nexport const repository = { ...REPOSITORY_INFO_PLACEHOLDER };\n\n/**\n * Generate base URLs for accessing the repository’s resources.\n * @param {string} repoURL The base URL of the repository.\n * @param {string} [branch] The branch name. Could be `undefined` if the branch is not specified in\n * the CMS configuration.\n * @returns {RepositoryBaseURLs} An object containing the tree base URL for browsing files, and the\n * blob base URL for accessing file contents.\n */\nexport const getBaseURLs = createBaseURLsGetter({\n  tree: '/tree',\n  blob: '/blob',\n  commit: '/commit',\n});\n\n/**\n * Check whether the given response was rejected because the API rate limit is exhausted. GitHub\n * answers a spent primary limit with a 403, the same status it uses to refuse access, so the\n * remaining-request count is what tells the two apart.\n * @param {Response} response Response to check.\n * @returns {boolean} `true` if the request was rate limited.\n * @see https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api\n */\nexport const isRateLimited = ({ status, headers }) =>\n  status === 429 ||\n  headers.get('retry-after') !== null ||\n  headers.get('x-ratelimit-remaining') === '0';\n\n/**\n * Fetch the signed-in user’s access to the configured repository, and whether it can be forked at\n * all. The repository reports the authenticated user’s own permissions, however they’re granted,\n * including through an organization team. Asking the collaborator endpoint instead would let a\n * read-only collaborator in, and would need administrator access to answer, so a maintainer who\n * merely has write access would be turned away as though they had none.\n * @param {(response: Response) => Promise<Error>} [getRefusalError] Function to create the error\n * to throw when the request is refused with a 403 or 404, in place of the plain “no access” one.\n * @returns {Promise<{ canRead: boolean, canWrite: boolean, allowForking: boolean,\n * isPersonalPrivate: boolean }>} Repository access. `canWrite` takes the write, maintain or admin\n * role. `isPersonalPrivate` is whether the repository is private and owned by a personal account.\n * @throws {Error} When the user has no access to the repository, or the answer couldn’t be\n * determined — which is not the same thing.\n * @see https://docs.github.com/en/rest/repos/repos#get-a-repository\n */\nexport const fetchRepositoryAccess = async (getRefusalError) => {\n  const response = /** @type {Response} */ (\n    await fetchAPI(getRepositoryPath(repository), {\n      headers: { Accept: 'application/json' },\n      responseType: 'raw',\n    })\n  );\n\n  if (!response.ok) {\n    // A rate limit shares the 403 status with a refusal, so it’s reported as a failed check rather\n    // than as no access, as reading it as “no write access” would send a maintainer down the fork\n    // path over something passing. A `raw` response skips the token refresh, so an expired token\n    // (401) still counts as no access, sending the user back to the sign-in form\n    const status = isRateLimited(response) ? undefined : response.status;\n\n    if (getRefusalError && (status === 403 || status === 404)) {\n      throw await getRefusalError(response);\n    }\n\n    throw toRepositoryAccessError(repository, status);\n  }\n\n  const {\n    permissions,\n    private: isPrivate,\n    owner,\n    allow_forking: allowForking,\n  } = await response.json();\n\n  return {\n    // A response without the user’s permissions doesn’t say they can read the repository\n    canRead: !!permissions?.pull,\n    canWrite: !!permissions?.push,\n    allowForking: allowForking !== false,\n    isPersonalPrivate: !!isPrivate && owner?.type === 'User',\n  };\n};\n\n/**\n * Check if the user has write access to the current repository, like Netlify/Decap CMS requires.\n * @throws {Error} If the user can’t push to the repository, or the access couldn’t be checked.\n */\nexport const checkRepositoryAccess = async () => {\n  const { canRead, canWrite } = await fetchRepositoryAccess();\n\n  if (!canWrite) {\n    // A read or triage collaborator can read the repository\n    throw createPermissionError(repository.repo, canRead);\n  }\n};\n\nconst FETCH_BRANCH_ACCESS_QUERY = `\n  query($owner: String!, $repo: String!, $qualifiedName: String!) {\n    repository(owner: $owner, name: $repo) {\n      ref(qualifiedName: $qualifiedName) {\n        refUpdateRule {\n          viewerCanPush\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Check if the user can push to the configured branch, and record it in {@link lockedBranch}. Write\n * access is enough to sign in, but a protected branch may require a pull request or only allow some\n * people to push, in which case everything that commits to the branch directly is made read-only up\n * front, rather than failing when the user saves. The rule is `null` for a branch that isn’t\n * protected. A failed request leaves the branch writable, as GitHub still refuses a push the user\n * isn’t allowed to make.\n *\n * Whether the user can merge a pull request into the branch isn’t told: a branch that requires a\n * pull request can’t be pushed to, but its pull requests can still be merged, so the Publish button\n * is left to GitHub to allow or refuse.\n * @see https://docs.github.com/en/graphql/reference/objects#refupdaterule\n */\nexport const checkBranchAccess = async () => {\n  await recordBranchAccess(repository.branch, async (branch) => {\n    const result = /** @type {{ repository?: { ref?: { refUpdateRule?: any } } }} */ (\n      await fetchGraphQL(FETCH_BRANCH_ACCESS_QUERY, { qualifiedName: `refs/heads/${branch}` })\n    );\n\n    return { canPush: result.repository?.ref?.refUpdateRule?.viewerCanPush };\n  });\n};\n\nconst FETCH_DEFAULT_BRANCH_NAME_QUERY = `\n  query($owner: String!, $repo: String!) {\n    repository(owner: $owner, name: $repo) {\n      defaultBranchRef {\n        name\n      }\n    }\n  }\n`;\n\n/**\n * Fetch the repository’s default branch name, which is typically `master` or `main`.\n * @returns {Promise<string>} Branch name.\n * @throws {Error} When the repository could not be found, or when the repository is empty.\n */\nexport const fetchDefaultBranchName = async () => {\n  const result = /** @type {{ repository: { defaultBranchRef?: { name: string } } }} */ (\n    await fetchGraphQL(FETCH_DEFAULT_BRANCH_NAME_QUERY)\n  );\n\n  const branch = applyDefaultBranch(repository, {\n    found: !!result.repository,\n    branch: result.repository?.defaultBranchRef?.name,\n    getBaseURLs,\n  });\n\n  Object.assign(graphqlVars, { branch });\n\n  return branch;\n};\n","import { fetchAPI } from '$lib/services/backends/git/shared/api';\n\n/**\n * Send a request to the REST API of a Git-based service for something that may not exist, such as\n * a branch, a file or a reference. A `404 Not Found` answer means it doesn’t, which is not an error\n * here; any other failure, like an expired token or an outage, is passed on. This lives apart from\n * {@link fetchAPI}, so a test replacing that module still has its requests go through this one.\n * @param {Parameters<typeof fetchAPI>} args Arguments for {@link fetchAPI}: the API endpoint path\n * and, optionally, the fetch options. They’re passed on as given.\n * @returns {Promise<any>} Response data, or `undefined` if the resource is missing.\n * @throws {Error} When the request fails for any other reason.\n */\nexport const fetchAPIOrUndefined = async (...args) => {\n  try {\n    return await fetchAPI(...args);\n  } catch (/** @type {any} */ ex) {\n    if (ex?.cause?.status === 404) {\n      return undefined;\n    }\n\n    throw ex;\n  }\n};\n","import { sleep } from '@sveltia/utils/misc';\n\n/**\n * How many times, and how often, a service is read while it works out something in the background\n * that usually takes a second or two, such as a merge request’s mergeability after a push.\n */\nexport const SETTLE_POLL = { attempts: 10, interval: 1000 };\n\n/**\n * Read a value, again and again while it hasn’t settled, until it has or the attempts run out, in\n * which case the last unsettled value is returned as is. The reads are spaced out by the given\n * interval; there is no wait before the first one, nor after the last one.\n * @template T\n * @param {() => Promise<T>} read Function to read the value.\n * @param {(value: T) => boolean} isSettled Function to check whether the value has settled.\n * @param {object} options Options.\n * @param {number} options.attempts Number of reads at most, including the first one.\n * @param {number} options.interval Time to wait between two reads, in milliseconds.\n * @returns {Promise<T>} Last value read.\n */\nexport const pollUntil = async (read, isSettled, { attempts, interval }) => {\n  const value = await read();\n\n  if (isSettled(value) || attempts <= 1) {\n    return value;\n  }\n\n  await sleep(interval);\n\n  return pollUntil(read, isSettled, { attempts: attempts - 1, interval });\n};\n","/**\n * @import { CommitAuthor, WorkflowFile, WorkflowPullRequest } from '$lib/types/private';\n */\n\n/**\n * Description the CMS opens an Editorial Workflow pull request or merge request with, which tells a\n * maintainer where it came from.\n */\nexport const PULL_REQUEST_DESCRIPTION = 'Automatically generated by Sveltia CMS';\n\n/**\n * Regular expression matching the record of the deletion group a pull request belongs to, along\n * with the blank lines before it. The record is an HTML comment, which the services leave out of\n * the rendered description. It’s global, so {@link setDeletionGroup} removes every record.\n */\nconst DELETION_GROUP_REGEX = /\\s*<!-- sveltia-cms:deletion-group=([\\w-]+) -->/g;\n/**\n * Regular expression matching the first record of the deletion group a pull request belongs to,\n * for {@link getDeletionGroup}. Unlike {@link DELETION_GROUP_REGEX}, it’s not global, so `match()`\n * gives the captured group ID.\n */\nconst DELETION_GROUP_RECORD_REGEX = /<!-- sveltia-cms:deletion-group=([\\w-]+) -->/;\n\n/**\n * Get the record of the given deletion group, to be added to a pull request description.\n * @param {string} deletionGroup Deletion group ID.\n * @returns {string} Record.\n */\nconst formatDeletionGroup = (deletionGroup) =>\n  `<!-- sveltia-cms:deletion-group=${deletionGroup} -->`;\n\n/**\n * Get the description the CMS opens an Editorial Workflow pull request or merge request with,\n * along with the record of the deletion group it belongs to, if any.\n * @param {string} [deletionGroup] Deletion group ID, if any. See {@link getDeletionGroup}.\n * @returns {string} Description.\n */\nexport const getPullRequestDescription = (deletionGroup) =>\n  deletionGroup\n    ? `${PULL_REQUEST_DESCRIPTION}\\n\\n${formatDeletionGroup(deletionGroup)}`\n    : PULL_REQUEST_DESCRIPTION;\n\n/**\n * Get the deletion group recorded in the description of the given pull request: the ID of the\n * selection of entries it was opened with to delete. Each entry of a selection gets its own pull\n * request, and the references to the whole selection are removed in every one of them, so they\n * have to be told apart from the pull requests deleting other entries of the same collection one\n * at a time.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {string | undefined} Deletion group ID, or `undefined` for a pull request deleting an\n * entry on its own, or not deleting one at all.\n */\nexport const getDeletionGroup = ({ description }) =>\n  description?.match(DELETION_GROUP_RECORD_REGEX)?.[1];\n\n/**\n * Record the given deletion group in a pull request description, replacing any group recorded\n * before, or remove the record. The rest of the description, which a maintainer may have edited,\n * is kept as it is.\n * @param {string} description Current description.\n * @param {string | undefined} deletionGroup Deletion group ID, or `undefined` to remove the record.\n * @returns {string} New description.\n */\nexport const setDeletionGroup = (description, deletionGroup) => {\n  const text = description.replace(DELETION_GROUP_REGEX, '');\n\n  return deletionGroup\n    ? [text, formatDeletionGroup(deletionGroup)].filter(Boolean).join('\\n\\n')\n    : text;\n};\n\n/**\n * Create helpers for a title that marks a pull request or merge request as a draft with a prefix,\n * as Gitea/Forgejo and GitLab do in place of a dedicated API field.\n * @param {object} args Arguments.\n * @param {RegExp} args.regex Regular expression matching one draft indicator at the beginning of a\n * title, along with the whitespace around it. It must not have the `g` or `y` flag.\n * @param {string} args.prefix Prefix added to a title to mark it as a draft.\n * @returns {{\n * strip: (title: string) => string,\n * format: (title: string, isDraft: boolean) => string,\n * }} `strip` removes any draft indicator from a raw title; `format` adds the prefix to a title\n * without one if `isDraft` is `true`.\n */\nexport const createDraftTitleCodec = ({ regex, prefix }) => ({\n  /**\n   * Remove any draft indicator from the given title.\n   * @param {string} title Raw title.\n   * @returns {string} Title without a draft prefix.\n   */\n  strip: (title) => {\n    let result = title;\n\n    // Repeat, because a title can carry a combination of indicators, e.g. `Draft: [Draft] Title`\n    while (regex.test(result)) {\n      result = result.replace(regex, '');\n    }\n\n    return result;\n  },\n  /**\n   * Add the draft prefix to the given title if the request is a draft.\n   * @param {string} title Title without a draft prefix.\n   * @param {boolean} isDraft Whether the request is a draft.\n   * @returns {string} Title to send to the API.\n   */\n  format: (title, isDraft) => (isDraft ? `${prefix}${title}` : title),\n});\n\n/**\n * Convert the changed files of a pull request or comparison, as listed by the REST API of GitHub or\n * Gitea/Forgejo, to workflow files.\n * @param {Record<string, any>[]} files Files.\n * @param {object} args Arguments.\n * @param {string} args.removedStatus Status the service gives a removed file: `removed` on GitHub,\n * `deleted` on Gitea/Forgejo.\n * @returns {WorkflowFile[]} Files.\n */\nexport const parseRestFiles = (files, { removedStatus }) =>\n  files.map(({ filename, status, previous_filename: previousPath }) => ({\n    path: filename,\n    sha: '',\n    size: 0,\n    deleted: status === removedStatus,\n    // Gitea/Forgejo gives a file that wasn’t renamed an empty previous path\n    previousPath: previousPath || undefined,\n  }));\n\n/**\n * Convert the user who opened a pull request or merge request to a commit author. An empty display\n * name falls back to the user name, like a missing one.\n * @param {object} user User.\n * @param {string} [user.login] User name.\n * @param {string | null} [user.name] Display name.\n * @param {string | null} [user.email] Email address.\n * @param {number} [user.id] User ID.\n * @returns {CommitAuthor | undefined} Author, or `undefined` if the user is unknown.\n */\nexport const toCommitAuthor = ({ login, name, email, id }) =>\n  login ? { name: name || login, email: email ?? '', id, login } : undefined;\n\n/**\n * Parse a pull request returned by the REST API of GitHub or Gitea/Forgejo, taking the properties\n * the two services give differently from the caller.\n * @param {Record<string, any>} item Pull request.\n * @param {Pick<WorkflowPullRequest, 'title' | 'branch' | 'status' | 'author' | 'description'> &\n * Partial<WorkflowPullRequest>} overrides Properties to add or override.\n * @returns {WorkflowPullRequest} Parsed pull request.\n */\nexport const parseRestPullRequest = (item, overrides) => ({\n  number: item.number,\n  nodeId: String(item.id),\n  url: item.html_url,\n  headSHA: item.head?.sha,\n  createdDate: new Date(item.created_at),\n  updatedDate: new Date(item.updated_at),\n  files: [],\n  ...overrides,\n});\n","import { cmsConfig } from '$lib/services/config';\nimport {\n  DEFAULT_CMS_LABEL_PREFIX,\n  LEGACY_CMS_LABEL_PREFIXES,\n  WORKFLOW_STATUSES,\n} from '$lib/services/workflow/constants';\n\n/**\n * @import { WorkflowStatus } from '$lib/types/private';\n */\n\n/**\n * Get the pull request label prefix configured with the backend’s `cms_label_prefix` option. This\n * is the prefix used when writing labels.\n * @returns {string} Label prefix, e.g. `sveltia-cms/`.\n */\nexport const getLabelPrefix = () => {\n  const { backend } = cmsConfig.current ?? {};\n  const prefix = backend && 'cms_label_prefix' in backend ? backend.cms_label_prefix : undefined;\n\n  return prefix || DEFAULT_CMS_LABEL_PREFIX;\n};\n\n/**\n * Get all the pull request label prefixes recognized when reading labels: the configured prefix,\n * the Sveltia CMS default, and the Netlify/Decap CMS prefixes. This allows the CMS to pick up\n * unpublished entries created with a different prefix or a different CMS.\n * @returns {string[]} Label prefixes, in priority order.\n */\nexport const getKnownLabelPrefixes = () => [\n  ...new Set([getLabelPrefix(), DEFAULT_CMS_LABEL_PREFIX, ...LEGACY_CMS_LABEL_PREFIXES]),\n];\n\n/**\n * Get the pull request label for the given Editorial Workflow status. Labels are always written\n * with the configured prefix, so a pull request created with another CMS is migrated to the\n * configured prefix once its status is updated.\n * @param {WorkflowStatus} status Status.\n * @returns {string} Label, e.g. `sveltia-cms/draft`.\n */\nexport const getStatusLabel = (status) => `${getLabelPrefix()}${status}`;\n\n/**\n * Get all the pull request labels recognized as CMS-managed, including the legacy ones. These are\n * removed from a pull request before a new status label is applied.\n * @returns {string[]} Labels, e.g. `[sveltia-cms/draft, ...]`.\n */\nexport const getAllStatusLabels = () =>\n  getKnownLabelPrefixes().flatMap((prefix) =>\n    WORKFLOW_STATUSES.map((status) => `${prefix}${status}`),\n  );\n\n/**\n * Replace the CMS-managed status label among the given pull request labels with the one for the\n * given status, preserving any other label. Status labels with another known prefix, including the\n * legacy ones, are dropped too.\n * @param {string[]} labels Label names on a pull request.\n * @param {WorkflowStatus} status New status.\n * @returns {string[]} New label names.\n */\nexport const replaceStatusLabel = (labels, status) => {\n  const cmsLabels = getAllStatusLabels();\n\n  return [...labels.filter((name) => !cmsLabels.includes(name)), getStatusLabel(status)];\n};\n\n/**\n * Determine the Editorial Workflow status from the given pull request labels. Labels with a legacy\n * prefix are recognized as well, but the configured prefix takes precedence in the unlikely case\n * that a pull request carries labels with multiple prefixes.\n * @param {string[]} labels Label names on a pull request.\n * @returns {WorkflowStatus | undefined} Status, or `undefined` if the pull request is not managed\n * by the CMS.\n */\nexport const getStatusFromLabels = (labels) => {\n  /** @type {WorkflowStatus | undefined} */\n  let result = undefined;\n\n  getKnownLabelPrefixes().some((prefix) => {\n    result = WORKFLOW_STATUSES.find((status) => labels.includes(`${prefix}${status}`));\n\n    return !!result;\n  });\n\n  return result;\n};\n","import { fetchAPI } from '$lib/services/backends/git/shared/api';\nimport { fetchAPIOrUndefined } from '$lib/services/backends/git/shared/api-optional';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { pollUntil } from '$lib/services/backends/git/shared/poll';\nimport { PULL_REQUEST_DESCRIPTION } from '$lib/services/backends/git/shared/pull-requests';\nimport {\n  getRepositoryPath,\n  isSameRepository,\n  toRepositoryPath,\n} from '$lib/services/backends/git/shared/repository';\nimport { cmsConfig } from '$lib/services/config';\nimport { user } from '$lib/services/user/account.svelte';\nimport { parseBranchName } from '$lib/services/workflow/branch';\nimport {\n  getForkBranchName,\n  getUpstreamBranchName,\n  parseForkBranchName,\n} from '$lib/services/workflow/forks';\nimport { getStatusFromLabels } from '$lib/services/workflow/labels';\nimport {\n  ENTRY_ALREADY_PUBLISHED,\n  forkedRepository,\n  getForkPath,\n  openAuthoring,\n  openAuthoringInitialized,\n  requestForkPermission,\n} from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * CommitOptions,\n * CommitResults,\n * FetchApiOptions,\n * ForkRequestState,\n * RepositoryInfo,\n * RepositoryPath,\n * WorkflowPullRequest,\n * WorkflowStatus,\n * } from '$lib/types/private';\n * @import { GitBackend } from '$lib/types/public';\n */\n\n/**\n * How long to wait for a newly requested fork to become available. A service copies the repository\n * in the background, and a large one can take a while, so the polling is generous before giving up.\n */\nconst FORK_POLL = {\n  interval: 1000,\n  attempts: 30,\n};\n\n/**\n * Check whether Open Authoring is turned on for the given backend in the site configuration. It\n * doesn’t mean the signed-in user is actually contributing through a fork: a user who can write to\n * the configured repository keeps working on it directly. Use the `openAuthoring` store for that.\n * @param {GitBackend['name'] | GitBackend['name'][]} name Backend name, e.g. `github`, or the names\n * of a backend that has more than one, e.g. `gitea` and `forgejo`.\n * @returns {boolean} `true` if the given backend is configured, with the `open_authoring` option\n * enabled.\n */\nexport const isOpenAuthoringConfiguredFor = (name) => {\n  const { backend } = cmsConfig.current ?? {};\n  const names = Array.isArray(name) ? name : [name];\n\n  return (\n    !!backend &&\n    /** @type {string[]} */ (names).includes(backend.name) &&\n    'open_authoring' in backend &&\n    backend.open_authoring === true\n  );\n};\n\n/**\n * Get the repository that receives the CMS’s commits: the signed-in user’s fork when the current\n * session is an Open Authoring one, and the configured repository otherwise. Content is always read\n * from the configured repository, so this is only for writes and for the branches behind them.\n * @param {RepositoryInfo} repository Configured repository.\n * @returns {RepositoryPath} Repository owner and name.\n */\nexport const resolveWorkflowRepository = ({ owner, repo }) =>\n  forkedRepository.current ?? { owner, repo };\n\n/**\n * Get the status of a pull request a contributor opened from their fork, as a maintainer’s session\n * reads it. The contributor marks it ready or takes it back to the drafting stage with its draft\n * state, as they can’t label it, while a maintainer moving it between the review and ready stages\n * labels it. The draft state wins, so a label left over from before the contributor marked it ready\n * doesn’t keep it in the drafting stage, and one a maintainer added doesn’t take it out of there.\n * Only the ready label is taken: a removal is told by what the pull request holds, not by a label\n * anyone with access can put on it.\n * @param {object} args Arguments.\n * @param {boolean} args.draft Whether the pull request is a draft, or a work in progress.\n * @param {string[]} args.labels Names of the labels on the pull request.\n * @returns {WorkflowStatus} Status.\n */\nconst getForkRequestStatus = ({ draft, labels }) => {\n  if (draft) {\n    return 'draft';\n  }\n\n  return getStatusFromLabels(labels) === 'pending_publish' ? 'pending_publish' : 'pending_review';\n};\n\n/**\n * Build the pull request a contributor opened from their fork, for a maintainer to review, once the\n * backend has checked it comes from a fork and targets the configured branch. Only one from a\n * branch named like the CMS names its branches is taken: anything else is a code change the CMS has\n * no business showing. The name proves nothing about the content, which anyone can put on a branch\n * of a public fork, so the pull request is treated as untrusted throughout: it can’t be published\n * from the CMS, which the `fork` property alone is enough for, its description is ignored, and its\n * branch is known by a name qualified with the fork, which can’t be mistaken for a branch of the\n * configured repository. See `getForkBranchName` in `$lib/services/workflow/forks`.\n * @param {object} args Arguments.\n * @param {string} args.owner Owner of the fork, which can be a namespace with subgroups on GitLab.\n * @param {string} args.repo Name of the fork.\n * @param {string} args.headBranch Head branch name in the fork.\n * @param {boolean} args.editable Whether the contributor lets maintainers push to the branch.\n * @param {boolean} args.draft Whether the pull request is a draft, or a work in progress.\n * @param {string[]} args.labels Names of the labels on the pull request.\n * @param {(fields: Pick<WorkflowPullRequest, 'status' | 'branch' | 'description'>) =>\n * WorkflowPullRequest} parse Function to parse the rest of the pull request, given the fields\n * worked out here.\n * @returns {WorkflowPullRequest | undefined} Pull request, or `undefined` if its branch isn’t named\n * like a workflow branch.\n */\nexport const toForkPullRequest = ({ owner, repo, headBranch, editable, draft, labels }, parse) => {\n  const branch = getForkBranchName({ owner, repo, branch: headBranch });\n\n  if (!parseBranchName(getUpstreamBranchName(branch))) {\n    return undefined;\n  }\n\n  const fields = { status: getForkRequestStatus({ draft, labels }), branch, description: '' };\n\n  return { ...parse(fields), ...fields, fork: { owner, repo, editable } };\n};\n\n/**\n * Get the repository a workflow branch lives in, and its name there. That’s the repository given\n * by {@link resolveWorkflowRepository}, except for the branch of a pull request a contributor\n * opened from their fork, which a maintainer reviewing it pushes to in that fork. See\n * `getForkBranchName` in `$lib/services/workflow/forks`.\n * @param {RepositoryInfo} repository Configured repository.\n * @param {string} branch Branch name as the CMS knows it.\n * @returns {RepositoryPath & { branch: string }} Repository owner and name, and the branch name.\n */\nexport const resolveBranchRepository = (repository, branch) =>\n  parseForkBranchName(branch) ?? { ...resolveWorkflowRepository(repository), branch };\n\n/**\n * Make sure a fork can be created, which takes both the service allowing it and the user agreeing\n * to it. Creating a repository on someone’s account is not something to do behind their back.\n * @param {object} args Arguments.\n * @param {string} args.repoPath Repository path to be forked, e.g. `owner/repo`.\n * @param {boolean} args.allowForking Whether the service allows the repository to be forked.\n * @throws {Error} When forking is turned off, or the user declined it.\n */\nexport const ensureForkPermission = async ({ repoPath, allowForking }) => {\n  // Say so rather than letting the fork request fail with nothing to act on\n  if (!allowForking) {\n    throw createLocalizedError(\n      'The repository does not allow forking',\n      'open_authoring.forking_disabled',\n      { repo: repoPath },\n    );\n  }\n\n  if (!(await requestForkPermission(repoPath))) {\n    throw createLocalizedError(\n      'Permission to fork the repository was declined',\n      'open_authoring.fork_declined',\n    );\n  }\n};\n\n/**\n * Log the given failure to create a fork and create an error that tells the user about it.\n * @param {string} repoPath Repository path that was to be forked, e.g. `owner/repo`.\n * @param {Error} ex Failure.\n * @returns {Error} Error to throw.\n */\nexport const createForkError = (repoPath, ex) => {\n  // eslint-disable-next-line no-console\n  console.error('Failed to fork the repository.', ex);\n\n  return createLocalizedError('Failed to fork the repository.', 'open_authoring.fork_failed', {\n    repo: repoPath,\n  });\n};\n\n/**\n * Ask the service to fork the configured repository, falling back to another name when the\n * contributor already has an unrelated repository at the default one. Unlike GitHub, which picks\n * another name itself, Gitea/Forgejo and GitLab refuse the request then.\n * @param {object} args Arguments.\n * @param {string} args.repoPath Repository path to be forked, e.g. `owner/repo`, for the error\n * message.\n * @param {() => Promise<any>} args.requestFork Function to request a fork at the default name.\n * @param {() => Promise<any>} args.requestRenamedFork Function to request a fork at the fallback\n * name.\n * @param {number[]} args.conflictStatuses HTTP status codes the service refuses a name that’s\n * already taken with.\n * @param {() => Promise<boolean>} args.isNameTaken Function to check whether the contributor has a\n * repository at the default name, which tells a name conflict from any other refusal, e.g. a fork\n * of the repository that already exists, or forking being turned off.\n * @returns {Promise<Record<string, any>>} Service’s response describing the new fork.\n * @throws {Error} When the fork could not be created.\n */\nexport const requestForkWithFallbackName = async ({\n  repoPath,\n  requestFork,\n  requestRenamedFork,\n  conflictStatuses,\n  isNameTaken,\n}) => {\n  try {\n    return await requestFork();\n  } catch (/** @type {any} */ ex) {\n    if (!conflictStatuses.includes(ex.cause?.status) || !(await isNameTaken())) {\n      throw createForkError(repoPath, ex);\n    }\n  }\n\n  try {\n    return await requestRenamedFork();\n  } catch (/** @type {any} */ ex) {\n    throw createForkError(repoPath, ex);\n  }\n};\n\n/**\n * Wait until a newly requested fork can be committed to. A service creates a fork asynchronously\n * and the request returns before the copy is complete, so committing to it right away could fail.\n * @param {object} args Arguments.\n * @param {string} args.repoPath Fork path, e.g. `owner/repo`, for the error message.\n * @param {() => Promise<'ready' | 'pending' | 'failed'>} args.checkFork Function to report how far\n * the copy has got. `failed` is for a service that says it has given up, which no amount of waiting\n * will change.\n * @param {number} [args.attemptsLeft] Number of checks at most, including the first one.\n * @throws {Error} When the fork hasn’t become available within the allotted time, or the copy\n * failed outright.\n */\nexport const pollForFork = async ({ repoPath, checkFork, attemptsLeft = FORK_POLL.attempts }) => {\n  const status = await pollUntil(checkFork, (value) => value !== 'pending', {\n    ...FORK_POLL,\n    attempts: attemptsLeft,\n  });\n\n  if (status === 'ready') {\n    return;\n  }\n\n  // Retrying wouldn’t help: the service has given up on the copy, and the contributor has a broken\n  // repository on their account that they have to remove before trying again\n  if (status === 'failed') {\n    throw createLocalizedError('The fork could not be created.', 'open_authoring.fork_failed', {\n      repo: repoPath,\n    });\n  }\n\n  throw createLocalizedError(\n    'Timed out waiting for the fork to be created.',\n    'open_authoring.fork_failed',\n    { repo: repoPath },\n  );\n};\n\n/**\n * Run a backend’s Open Authoring set-up for the signed-in user. Whether they end up on a fork or,\n * as a maintainer, on the configured repository, the outcome is flagged as known once the set-up\n * has completed, for what depends on it.\n * @param {() => Promise<void>} setUp Backend’s set-up, which records a fork if the user needs one.\n * @throws {Error} When the fork could not be set up.\n * @see https://sveltiacms.app/en/docs/workflows/open\n */\nexport const runOpenAuthoringSetUp = async (setUp) => {\n  forkedRepository.current = undefined;\n  openAuthoringInitialized.current = false;\n\n  await setUp();\n\n  openAuthoringInitialized.current = true;\n};\n\n/**\n * Work out how the signed-in user is going to write to the repository, and set up a fork for them\n * if they can’t write to the configured one. This replaces the plain access check performed when\n * Open Authoring is turned off, because a contributor without write access is expected here rather\n * than turned away. The steps are the same on every service, which supplies the requests that\n * differ.\n * @template {{ canWrite: boolean }} A\n * @param {object} args Arguments.\n * @param {RepositoryPath & { branch?: string }} args.repository Configured repository.\n * @param {() => Promise<A>} args.fetchAccess Function to read the signed-in user’s access to the\n * configured repository.\n * @param {() => Promise<unknown>} [args.fetchDefaultBranchName] Function to resolve the branch name\n * once the user turns out to be a contributor, before the fork is looked up, if the fork needs it.\n * It’s otherwise resolved later in the data load.\n * @param {() => Promise<RepositoryPath | undefined>} args.fetchFork Function to look up the user’s\n * existing fork.\n * @param {(fork: RepositoryPath) => Promise<void>} [args.prepareFork] Function to bring an existing\n * fork up to date, or check it’s usable, before it’s taken.\n * @param {(access: A) => boolean | Promise<boolean>} args.fetchForkingAllowed Function to tell\n * whether the configured repository can be forked, given the access read earlier.\n * @param {() => Promise<RepositoryPath>} args.createFork Function to create a fork.\n * @throws {Error} When the fork could not be set up.\n * @see https://sveltiacms.app/en/docs/workflows/open\n */\nexport const setUpForkFor = async (args) => {\n  const { repository, fetchAccess, fetchFork, prepareFork, fetchForkingAllowed } = args;\n  const access = await fetchAccess();\n\n  // A maintainer keeps working on the configured repository, as if Open Authoring was off\n  if (access.canWrite) {\n    return;\n  }\n\n  if (!repository.branch) {\n    await args.fetchDefaultBranchName?.();\n  }\n\n  const existingFork = await fetchFork();\n\n  if (existingFork) {\n    await prepareFork?.(existingFork);\n    forkedRepository.current = existingFork;\n\n    return;\n  }\n\n  // Forking can be turned off on the repository or the instance, and the user has to agree to it\n  await ensureForkPermission({\n    repoPath: `${repository.owner}/${repository.repo}`,\n    allowForking: await fetchForkingAllowed(access),\n  });\n\n  forkedRepository.current = await args.createFork();\n};\n\n/**\n * Make sure the signed-in user can publish an unpublished entry, which an Open Authoring\n * contributor can’t: merging their own pull request is what they lack the access for in the first\n * place.\n * @throws {Error} When the user is a contributor.\n */\nexport const checkPublishAllowed = () => {\n  if (openAuthoring.current) {\n    throw createLocalizedError(\n      'Cannot publish as an Open Authoring contributor',\n      'open_authoring.publish_unsupported',\n    );\n  }\n};\n\n/**\n * Make sure the signed-in user can make the given commit. An Open Authoring contributor can’t write\n * to the configured repository at all, so a change that doesn’t go through Editorial Workflow has\n * nowhere to land. This fails with an explanation rather than letting the API reject the commit\n * with a bare permission error.\n * @param {CommitOptions} options Commit options.\n * @throws {Error} When the user is a contributor and the commit isn’t on a workflow branch.\n */\nexport const checkDirectCommitAllowed = ({ branch }) => {\n  if (openAuthoring.current && !branch) {\n    throw createLocalizedError(\n      'Cannot commit directly to the configured repository',\n      'open_authoring.direct_commit_unsupported',\n    );\n  }\n};\n\n/**\n * Make sure an Open Authoring contributor can move an entry to the given stage. The stage that says\n * an entry is ready to be published is a maintainer’s, so it’s left out of the board and the status\n * menu for a contributor; this catches a request that got through anyway.\n * @param {WorkflowStatus} status New status.\n * @throws {Error} When the entry is being marked ready to publish.\n */\nexport const checkStatusAllowed = (status) => {\n  if (status === 'pending_publish') {\n    throw createLocalizedError(\n      'Cannot mark an entry ready to publish as an Open Authoring contributor',\n      'open_authoring.publish_unsupported',\n    );\n  }\n};\n\n/**\n * Find out whether the request an Open Authoring entry had, which a maintainer has merged since the\n * board was loaded, took everything the entry’s branch holds. It did if the branch still points at\n * the commit the request was merged at: the entry is published, and handing it over for review\n * again would open a request with nothing in it. The leftover branch is then deleted, the way the\n * next load would, and the entry reported as published. A branch that’s gone, which a maintainer\n * can delete with the merge, has nothing left on it either.\n *\n * The branch head is read afresh rather than taken from the entry: a commit made since in another\n * tab, or by a colleague sharing the fork, isn’t on record there, and deleting the branch would\n * lose it.\n * @param {object} args Arguments.\n * @param {string} args.branch Workflow branch name.\n * @param {string} args.mergedSHA Head commit the request was merged at.\n * @param {(branch: string) => Promise<string | undefined>} args.fetchBranchHead Function to read\n * the commit the branch points at, `undefined` if it’s gone.\n * @param {(branch: string) => Promise<void>} args.deleteBranch Function to delete the branch.\n * @throws {Error} An {@link ENTRY_ALREADY_PUBLISHED} error when the branch has nothing left on it.\n * Nothing is thrown when the contributor has committed to the branch since the merge, which makes\n * the entry a fresh draft.\n */\nexport const checkMergedBranch = async ({ branch, mergedSHA, fetchBranchHead, deleteBranch }) => {\n  const head = await fetchBranchHead(branch);\n\n  if (head && head !== mergedSHA) {\n    return;\n  }\n\n  // Deleting a branch is best effort: `deleteBranch` logs a failure rather than raising it, and a\n  // branch that outlives this is picked up on the next load\n  if (head) {\n    await deleteBranch(branch);\n  }\n\n  throw createLocalizedError(ENTRY_ALREADY_PUBLISHED, 'open_authoring.entry_already_published');\n};\n\n/**\n * Report that a request to bring the contributor’s fork up to date with the upstream repository\n * failed. The fork still works when it trails the upstream, it just makes for a noisier pull\n * request, so this only warns.\n * @param {RepositoryPath} fork Fork.\n * @param {any} error Error the request failed with.\n */\nexport const warnForkSyncError = (fork, error) => {\n  // eslint-disable-next-line no-console\n  console.warn(`Failed to sync the ${getForkPath(fork)} fork with the upstream repository.`, error);\n};\n\n/**\n * Report that the contributor’s fork can’t be fast-forwarded to the upstream repository, e.g.\n * because it has commits of its own on the branch, which the CMS can’t resolve on their behalf.\n * Like {@link warnForkSyncError}, this only warns.\n * @param {RepositoryPath} fork Fork.\n */\nexport const warnForkNotFastForwarded = (fork) => {\n  // eslint-disable-next-line no-console\n  console.warn(\n    `The ${getForkPath(fork)} fork could not be fast-forwarded to the upstream repository.`,\n  );\n};\n\n/**\n * Bring the fork’s copy of the given branch up to date with the configured repository, so a new\n * workflow branch starts from what’s currently on the site and the resulting pull request only\n * contains the entry being edited. GitHub and Gitea take the same `merge-upstream` request, which\n * is sent unless another one is given. A failure is logged rather than raised: a fork that has\n * drifted still works, it just makes for a noisier pull request.\n * @param {RepositoryPath} fork Fork to update.\n * @param {string | undefined} branch Branch name.\n * @param {() => Promise<Response | undefined>} [request] Function to send another request instead,\n * resolving to `undefined` when it found nothing to send.\n * @see https://docs.github.com/en/rest/branches/branches#sync-a-fork-branch-with-the-upstream-repository\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoMergeUpstream\n */\nexport const syncForkWith = async (fork, branch, request) => {\n  /** @type {Response | undefined} */\n  let response;\n\n  try {\n    response = /** @type {Response | undefined} */ (\n      await (request\n        ? request()\n        : fetchAPI(`${getRepositoryPath(fork)}/merge-upstream`, {\n            method: 'POST',\n            body: { branch },\n            responseType: 'raw',\n          }))\n    );\n  } catch (/** @type {any} */ ex) {\n    warnForkSyncError(fork, ex);\n\n    return;\n  }\n\n  // The request is refused when the fork has commits of its own on the branch that can’t be\n  // fast-forwarded or merged, which is a state the CMS can’t resolve on the contributor’s behalf.\n  // On GitHub, it’s also refused when the update would change GitHub Actions workflow files and\n  // the OAuth token lacks the `workflow` scope\n  if (response && !response.ok) {\n    warnForkNotFastForwarded(fork);\n  }\n};\n\n/**\n * Look for the fork at the name GitHub or Gitea/Forgejo gives it by default, which is the parent’s.\n * This is where it is unless the contributor renamed it, or already had a repository of that name\n * when the fork was made. A repository that happens to share the name but isn’t a fork of the\n * configured one is ignored.\n * @param {RepositoryPath} repository Configured repository.\n * @param {FetchApiOptions} [options] Request options.\n * @returns {Promise<RepositoryPath | undefined>} The fork, or `undefined` if it isn’t there.\n * @see https://docs.github.com/en/rest/repos/repos#get-a-repository\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGet\n */\nexport const fetchForkByNameFor = async (repository, options) => {\n  const userName = /** @type {string} */ (user.account?.login);\n\n  // Only a missing repository means there’s no fork at the name. Reading a rate limit or an outage\n  // the same way would have the contributor asked to create another one, so that is passed on\n  const result = /** @type {Record<string, any> | undefined} */ (\n    await fetchAPIOrUndefined(\n      getRepositoryPath({ owner: userName, repo: repository.repo }),\n      options,\n    )\n  );\n\n  // The service redirects a request for a repository that was renamed or transferred, so the one\n  // it answered with can sit on an account other than the one asked for. Everything the CMS writes\n  // goes to this repository, so take it only once it’s confirmed to be the signed-in user’s own\n  return result?.fork &&\n    isSameRepository(result.parent?.full_name, repository) &&\n    result.owner?.login?.toLowerCase() === userName.toLowerCase()\n    ? toRepositoryPath(result.full_name)\n    : undefined;\n};\n\n/**\n * Go through the Editorial Workflow branches in the contributor’s fork, deleting the ones left\n * over from a merged request and parsing the rest. A merged request whose head the branch still\n * points at has nothing left on it. Tidying it up keeps the fork from collecting a branch per\n * published entry, and saves comparing each one with the configured branch on every load just to\n * find out it holds nothing. A branch the contributor has committed to since the merge has a\n * different head, so it survives and shows up as a fresh draft.\n * @template T\n * @param {T[]} items Branches as read by the backend.\n * @param {(item: T, index: number) => { leftover: string } | { pending: WorkflowPullRequest }}\n * classify Function to tell a leftover branch, by its name, from one with an entry on it, parsed.\n * @param {(branch: string) => Promise<void>} deleteBranch Function to delete a branch.\n * @returns {Promise<WorkflowPullRequest[]>} Parsed branches that weren’t left over.\n */\nexport const pruneForkBranches = async (items, classify, deleteBranch) => {\n  /** @type {string[]} */\n  const leftover = [];\n  /** @type {WorkflowPullRequest[]} */\n  const pending = [];\n\n  items.forEach((item, index) => {\n    const result = classify(item, index);\n\n    if ('leftover' in result) {\n      leftover.push(result.leftover);\n    } else {\n      pending.push(result.pending);\n    }\n  });\n\n  // Deleting a branch is best effort: `deleteBranch` logs a failure rather than raising it, and a\n  // branch that outlives this is picked up on the next load\n  await runConcurrently(leftover, deleteBranch);\n\n  return pending;\n};\n\n/**\n * Move an Open Authoring entry between the drafting and review stages. A contributor can’t label a\n * request on a repository they don’t have access to, so the stage is recorded in the request\n * itself: a draft is a branch with no request, or one that’s still a draft, while an entry in\n * review has a request waiting for a maintainer. The steps are the same on every service, which\n * supplies the requests that differ.\n * @param {object} args Arguments.\n * @param {WorkflowPullRequest} args.pullRequest Pull request.\n * @param {WorkflowStatus} args.status New status.\n * @param {'number' | 'nodeId'} args.requestKey Property of the pull request that identifies the\n * request on the service, `undefined` until one is opened.\n * @param {(args: { branch: string, title: string, status: WorkflowStatus, description: string })\n * => Promise<WorkflowPullRequest>} args.createRequest Function to open the request.\n * @param {(pullRequest: WorkflowPullRequest) => Promise<ForkRequestState | undefined>}\n * args.fetchRequest Function to read the current state of the request. `undefined` means the\n * request couldn’t be found, in which case the entry carries on with what it knows.\n * @param {(args: { pullRequest: WorkflowPullRequest, status: WorkflowStatus, state?: string,\n * draft?: boolean }) => Promise<void>} args.applyStatus Function to bring the request in line with\n * the new status, given the state it’s in.\n * @param {(branch: string) => Promise<string | undefined>} args.fetchBranchHead Function to read\n * the commit a branch points at: see {@link checkMergedBranch}.\n * @param {(branch: string) => Promise<void>} args.deleteBranch Function to delete a branch.\n * @returns {Promise<WorkflowPullRequest>} Updated pull request, or a new one if the known one is no\n * longer the entry’s.\n * @throws {Error} When the entry is being marked ready to publish, which a contributor can’t do, or\n * has been published since the board was loaded: see {@link checkMergedBranch}.\n * @see https://github.com/sveltia/sveltia-cms/security/advisories/GHSA-8h97-74c4-g246\n */\nexport const updateForkStatusWith = async (args) => {\n  const { pullRequest, status, requestKey, createRequest, fetchRequest, applyStatus } = args;\n  const { fetchBranchHead, deleteBranch } = args;\n\n  checkStatusAllowed(status);\n\n  const { branch, title } = pullRequest;\n\n  // Nothing has been opened yet, so moving out of the drafting stage is what creates the request.\n  // Moving within the drafting stage leaves the branch as it is\n  if (pullRequest[requestKey] === undefined) {\n    return status === 'draft'\n      ? { ...pullRequest, status, updatedDate: new Date() }\n      : createRequest({ branch, title, status, description: PULL_REQUEST_DESCRIPTION });\n  }\n\n  // The request may have been closed, reopened or merged outside the CMS, so read the current state\n  // rather than inferring it from the status the entry was last seen with\n  const request = await fetchRequest(pullRequest);\n\n  if (request) {\n    const { merged, isEntryRequest, getMergedSHA } = request;\n\n    // It may have been merged into the configured branch since the board was loaded. With nothing\n    // committed to the branch since, the entry is published and has nothing left to review\n    if (merged && isEntryRequest) {\n      await checkMergedBranch({\n        branch,\n        mergedSHA: await getMergedSHA(),\n        fetchBranchHead,\n        deleteBranch,\n      });\n    }\n\n    // Otherwise a merged request, or one aimed at another branch since the board was loaded, is no\n    // longer the entry’s review, which is how the next load would see it too: reopening it or\n    // taking it out of draft would put a request for that other branch in front of the maintainers,\n    // or claim a merged one is in review. So the entry carries on without it, as a fresh draft. A\n    // service allows one open request per head and base, so one aimed elsewhere doesn’t stand in\n    // the way of a new one to the configured branch\n    if (merged || !isEntryRequest) {\n      return updateForkStatusWith({\n        ...args,\n        pullRequest: { ...pullRequest, number: undefined, nodeId: undefined, url: undefined },\n      });\n    }\n  }\n\n  await applyStatus({ pullRequest, status, state: request?.state, draft: request?.draft });\n\n  return { ...pullRequest, status, updatedDate: new Date() };\n};\n\n/**\n * Build the pull request object standing in for an Open Authoring draft, which is nothing but a\n * branch in the contributor’s fork. The pull request is opened when they hand the entry over for\n * review, so maintainers aren’t notified about work that isn’t ready for them, and until then the\n * entry is described by the commit that created the branch.\n * @param {object} args Arguments.\n * @param {CommitResults} args.commit Commit just made on the branch.\n * @param {string} args.branch Branch name.\n * @param {string} args.title Title the pull request will be opened with.\n * @returns {WorkflowPullRequest} Pull request.\n */\nexport const createDraftPullRequest = ({ commit, branch, title }) => ({\n  title,\n  branch,\n  status: /** @type {WorkflowStatus} */ ('draft'),\n  createdDate: /** @type {Date} */ (commit.date),\n  updatedDate: /** @type {Date} */ (commit.date),\n  files: [],\n  // Only a maintainer merges, and a contributor is never one\n  canMerge: false,\n});\n","import {\n  fetchDefaultBranchName,\n  fetchRepositoryAccess,\n  repository,\n} from '$lib/services/backends/git/github/repository';\nimport { fetchAPI, fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport {\n  createLocalizedError,\n  NOT_COLLABORATOR_ERROR_MESSAGE,\n} from '$lib/services/backends/git/shared/errors';\nimport {\n  createForkError,\n  fetchForkByNameFor,\n  isOpenAuthoringConfiguredFor,\n  pollForFork,\n  resolveBranchRepository,\n  resolveWorkflowRepository,\n  runOpenAuthoringSetUp,\n  setUpForkFor,\n  syncForkWith,\n} from '$lib/services/backends/git/shared/fork';\nimport {\n  getRepositoryPath,\n  isSameRepository,\n  toRepositoryPath,\n} from '$lib/services/backends/git/shared/repository';\nimport { user } from '$lib/services/user/account.svelte';\n\n/**\n * @import { RepositoryPath } from '$lib/types/private';\n */\n\n/**\n * Check whether Open Authoring is turned on for this backend in the site configuration: see\n * {@link isOpenAuthoringConfiguredFor}.\n * @returns {boolean} `true` if the `open_authoring` backend option is enabled.\n */\nexport const isOpenAuthoringConfigured = () => isOpenAuthoringConfiguredFor('github');\n\n/**\n * Get the repository that receives the CMS’s commits: the signed-in user’s fork when the current\n * session is an Open Authoring one, and the configured repository otherwise. Content is always read\n * from the configured repository, so this is only for writes and for the branches behind them.\n * @returns {RepositoryPath} Repository owner and name.\n */\nexport const getWorkflowRepository = () => resolveWorkflowRepository(repository);\n\n/**\n * Get the repository a workflow branch lives in, and its name there: see\n * {@link resolveBranchRepository}.\n * @param {string} branch Branch name as the CMS knows it.\n * @returns {RepositoryPath & { branch: string }} Repository owner and name, and the branch name.\n */\nexport const getBranchRepository = (branch) => resolveBranchRepository(repository, branch);\n\n/**\n * Get the repository to read the files of the workflow branches from, by commit or blob ID.\n * That’s the repository given by {@link getWorkflowRepository}: the contributor’s fork with Open\n * Authoring, and the configured repository otherwise. The configured repository also serves the\n * commits of the pull requests contributors have opened from their forks, as GitHub keeps them\n * there under `refs/pull/{number}/head`, so a maintainer reads those from it too, rather than from\n * a fork they may not be able to see, e.g. a private one, or one deleted since. Writes and branch\n * lookups go to the fork itself: see {@link getBranchRepository}.\n * @returns {RepositoryPath} Repository owner and name.\n */\nexport const getContentRepository = () => getWorkflowRepository();\n\n/**\n * Check whether the signed-in user has an invitation to the configured repository that they haven’t\n * accepted yet. An invitation grants no access until it’s accepted, and the notification is easy to\n * miss, so it’s a likely reason for being unable to read a repository the user was told they can.\n * @returns {Promise<boolean>} `true` if an invitation is waiting.\n * @see https://docs.github.com/en/rest/collaborators/invitations#list-repository-invitations-for-the-authenticated-user\n */\nexport const hasPendingInvitation = async () => {\n  try {\n    const invitations = /** @type {Record<string, any>[]} */ (\n      await fetchAPI('/user/repository_invitations')\n    );\n\n    return invitations.some(({ repository: invited }) =>\n      isSameRepository(invited?.full_name, repository),\n    );\n  } catch {\n    // The list is a nicety; failing to read it just means there’s nothing extra to say\n    return false;\n  }\n};\n\n/**\n * Work out the most useful thing to tell a user whose request for the configured repository was\n * refused. The bare “no access” is true but rarely actionable, and the two cases below are the ones\n * that come up while setting Open Authoring up.\n * @param {Response} response The refused response.\n * @returns {Promise<Error>} Error to throw, with the message to show.\n */\nconst getNoAccessError = async (response) => {\n  const { owner, repo } = repository;\n  const repoPath = `${owner}/${repo}`;\n\n  /**\n   * Create the error with the given message. It carries the shared message, which the sign-in flow\n   * looks for to drop the cached credentials, so the user gets the sign-in form rather than the\n   * same error on every reload, and can sign in again once the cause has been dealt with.\n   * @param {string} key Localized string key.\n   * @returns {Error} Error.\n   */\n  const createError = (key) =>\n    createLocalizedError(NOT_COLLABORATOR_ERROR_MESSAGE, key, { repo: repoPath });\n\n  if (await hasPendingInvitation()) {\n    return createError('open_authoring.invitation_pending');\n  }\n\n  // A public repository is readable by any authenticated request, so a refusal means the repository\n  // is private. A sign-in that doesn’t cover private repositories is then worth calling out: the\n  // account may well have access, while the token it was given doesn’t. The header is absent for a\n  // fine-grained token, which reports its permissions differently\n  const scopes = response.headers.get('x-oauth-scopes');\n\n  if (scopes !== null && !scopes.split(/,\\s*/).includes('repo')) {\n    return createError('open_authoring.private_repo_scope_required');\n  }\n\n  return createError('repository_no_access');\n};\n\n/**\n * Fetch what the sign-in needs to know about the configured repository: whether the signed-in user\n * can commit to it, and whether it can be forked at all. See {@link fetchRepositoryAccess}. Open\n * Authoring still needs the contributor to be able to read the repository, so being unable to see\n * it is a dead end rather than a reason to fall back to a fork. A refusal is worth a hint.\n * @returns {Promise<{ canRead: boolean, canWrite: boolean, allowForking: boolean,\n * isPersonalPrivate: boolean }>} Repository access.\n * @throws {Error} When the user has no access to the repository, or the answer couldn’t be\n * determined — which is not the same thing.\n */\nexport const fetchOpenAuthoringAccess = async () => {\n  const access = await fetchRepositoryAccess(getNoAccessError);\n\n  // GitHub doesn’t offer read-only collaborators on a repository owned by a personal account, so\n  // a private one has nobody for Open Authoring to serve: everyone invited can write to it and\n  // keeps working on it directly, and everyone else can’t read it at all. The feature then sits\n  // there doing nothing, with nothing on screen to say why, so point it out to whoever set it up\n  if (access.isPersonalPrivate) {\n    // eslint-disable-next-line no-console\n    console.warn(\n      `Open Authoring is enabled, but the ${repository.owner}/${repository.repo} repository is ` +\n        'private and owned by a personal account. GitHub does not allow read-only collaborators ' +\n        'there, so everyone who can sign in can also write to the repository and no one is ' +\n        'treated as a contributor. Transfer the repository to an organization to use Open ' +\n        'Authoring with it.',\n    );\n  }\n\n  return access;\n};\n\n/**\n * Look for the fork at the name GitHub gives it by default: see {@link fetchForkByNameFor}.\n * @returns {Promise<RepositoryPath | undefined>} The fork, or `undefined` if it isn’t there.\n */\nexport const fetchForkByName = () =>\n  fetchForkByNameFor(repository, { headers: { Accept: 'application/json' } });\n\n// `affiliations` is the one that filters by the viewer, so `OWNER` keeps the forks the signed-in\n// user owns. `ownerAffiliations` is about the owner being viewed instead, and its default of\n// `[OWNER, COLLABORATOR]` is widened to every value, so it can’t leave the fork out\nconst FETCH_USER_FORK_QUERY = `\n  query($owner: String!, $repo: String!) {\n    repository(owner: $owner, name: $repo) {\n      forks(\n        affiliations: [OWNER]\n        ownerAffiliations: [OWNER, COLLABORATOR, ORGANIZATION_MEMBER]\n        first: 1\n      ) {\n        nodes {\n          nameWithOwner\n          owner {\n            login\n          }\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Ask the configured repository for the fork the signed-in user owns, wherever it’s named. This\n * only runs when {@link fetchForkByName} came up empty. A failed query is passed on rather than\n * taken for no fork, which would have the contributor asked to create another one.\n * @returns {Promise<RepositoryPath | undefined>} The fork, or `undefined` if there is none.\n * @see https://docs.github.com/en/graphql/reference/objects#repository\n */\nexport const fetchForkFromNetwork = async () => {\n  const userName = user.account?.login;\n\n  const { repository: result } = /** @type {{ repository: Record<string, any> }} */ (\n    await fetchGraphQL(FETCH_USER_FORK_QUERY)\n  );\n\n  const [node] = result?.forks?.nodes ?? [];\n\n  // Check the owner rather than trusting the filter to have applied: committing to someone\n  // else’s fork would fail in a way that’s hard to make sense of\n  if (node?.owner?.login !== userName) {\n    return undefined;\n  }\n\n  return toRepositoryPath(node.nameWithOwner);\n};\n\n/**\n * Look for an existing fork of the configured repository on the signed-in user’s account.\n * @returns {Promise<RepositoryPath | undefined>} The fork, or `undefined` if there is none.\n */\nexport const fetchFork = async () => (await fetchForkByName()) ?? fetchForkFromNetwork();\n\n/**\n * Wait until a newly requested fork can be read back. GitHub creates a fork asynchronously and the\n * request returns before the copy is complete, so committing to it right away could fail.\n * @param {RepositoryPath} fork Fork to wait for.\n * @param {number} [attemptsLeft] Number of checks at most, including the first one.\n * @throws {Error} When the fork hasn’t appeared within the allotted time.\n */\nexport const waitForFork = async ({ owner, repo }, attemptsLeft) => {\n  await pollForFork({\n    repoPath: `${owner}/${repo}`,\n    attemptsLeft,\n    /**\n     * Ask GitHub whether the fork can be read back yet.\n     * @returns {Promise<'ready' | 'pending'>} Whether the copy is complete.\n     */\n    checkFork: async () => {\n      const response = /** @type {Response} */ (\n        await fetchAPI(getRepositoryPath({ owner, repo }), {\n          headers: { Accept: 'application/json' },\n          responseType: 'raw',\n        })\n      );\n\n      // GitHub reports no state of its own while the copy is in progress, so a repository that\n      // can’t be read yet is simply one to come back to\n      return response.ok ? 'ready' : 'pending';\n    },\n  });\n};\n\n/**\n * Fork the configured repository onto the signed-in user’s account.\n * @returns {Promise<RepositoryPath>} The new fork.\n * @throws {Error} When the fork could not be created.\n * @see https://docs.github.com/en/rest/repos/forks#create-a-fork\n */\nexport const createFork = async () => {\n  const { owner, repo } = repository;\n  /** @type {Record<string, any>} */\n  let result;\n\n  try {\n    result = /** @type {Record<string, any>} */ (\n      await fetchAPI(`${getRepositoryPath(repository)}/forks`, { method: 'POST' })\n    );\n  } catch (/** @type {any} */ ex) {\n    throw createForkError(`${owner}/${repo}`, ex);\n  }\n\n  const fork = toRepositoryPath(result.full_name);\n\n  await waitForFork(fork);\n\n  return fork;\n};\n\n/**\n * Bring the fork’s copy of the configured branch up to date: see {@link syncForkWith}.\n * @param {RepositoryPath} fork Fork to update.\n * @returns {Promise<void>} Nothing.\n */\nexport const syncFork = (fork) => syncForkWith(fork, repository.branch);\n\n/**\n * Work out how the signed-in user is going to write to the repository, and set up a fork for them\n * if they can’t write to the configured one. This replaces the plain access check performed when\n * Open Authoring is turned off, because a contributor without write access is expected here rather\n * than turned away.\n * @throws {Error} When the fork could not be set up.\n * @see https://sveltiacms.app/en/docs/workflows/open\n */\nconst setUpOpenAuthoring = async () => {\n  await setUpForkFor({\n    repository,\n    fetchAccess: fetchOpenAuthoringAccess,\n    // Syncing the fork needs the branch name\n    fetchDefaultBranchName,\n    fetchFork,\n    prepareFork: syncFork,\n    /**\n     * Tell whether the repository can be forked, which the access check has read already. Forking\n     * is turned off by default on a private repository, and can be turned off on a public one.\n     * @param {{ allowForking: boolean }} access Repository access.\n     * @returns {boolean} Result.\n     */\n    fetchForkingAllowed: ({ allowForking }) => allowForking,\n    createFork,\n  });\n};\n\n/**\n * Set up Open Authoring for the signed-in user: see {@link setUpOpenAuthoring}.\n * @throws {Error} When the fork could not be set up.\n */\nexport const initOpenAuthoring = async () => {\n  await runOpenAuthoringSetUp(setUpOpenAuthoring);\n};\n","import { sleep } from '@sveltia/utils/misc';\n\nimport { fetchAPI } from '$lib/services/backends/git/shared/api';\nimport { mapConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { getGitHash } from '$lib/services/utils/file';\nimport { encodePathSegments } from '$lib/services/utils/url';\n\n/**\n * @import { AdditionsCommitAuthor } from '$lib/types/private';\n * @import { FileAddition } from '$lib/services/backends/git/shared/commit-split';\n */\n\n/**\n * Number of blobs created at the same time. Creating content counts against GitHub’s secondary rate\n * limit of 80 requests a minute, so a save with many images goes slowly rather than all at once.\n * @see https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits\n */\nconst BLOB_CONCURRENCY = 3;\n\n/**\n * How long to wait before each retry of a request refused by the secondary rate limit. GitHub asks\n * for at least a minute when it doesn’t say how long.\n */\nexport const RATE_LIMIT_DELAYS = [15_000, 30_000, 60_000];\n\n/**\n * Check whether an error comes from GitHub’s secondary rate limit, which it reports with a 403 or\n * 429 status.\n * @param {any} error Error thrown by `fetchAPI`.\n * @returns {boolean} Result.\n */\nconst isRateLimited = (error) => {\n  const { status, message } = error?.cause ?? {};\n\n  return status === 429 || (status === 403 && /rate limit/i.test(String(message)));\n};\n\n/**\n * Send a request, waiting and trying again when the secondary rate limit refuses it.\n * @param {() => Promise<any>} request Request.\n * @returns {Promise<any>} Response.\n * @throws {Error} When the request fails for another reason, or keeps being refused.\n */\nconst sendWithBackoff = async (request) => {\n  for (let attempt = 0; ; attempt += 1) {\n    try {\n      // eslint-disable-next-line no-await-in-loop\n      return await request();\n    } catch (ex) {\n      if (!isRateLimited(ex) || attempt >= RATE_LIMIT_DELAYS.length) {\n        throw ex;\n      }\n\n      // eslint-disable-next-line no-await-in-loop\n      await sleep(RATE_LIMIT_DELAYS[attempt]);\n    }\n  }\n};\n\n/**\n * Check whether a file goes into the tree as text, which saves a request for its blob. Only entry\n * files and other text are passed as strings; assets come as `Blob`s.\n * @param {FileAddition} addition File addition.\n * @returns {boolean} Result.\n */\nconst isText = ({ data }) => typeof data === 'string' || data === undefined;\n\n/**\n * Commit the given additions and deletions on top of the given head through the REST Git Data API,\n * which, unlike GraphQL’s `createCommitOnBranch`, takes an author. That lets someone without a\n * GitHub account be the author of their changes, while an app’s installation token makes the\n * requests. GitHub doesn’t sign such a commit. The branch is moved only if the commit is a\n * fast-forward, so a commit someone else has pushed in the meantime isn’t overwritten, just like\n * with `expectedHeadOid`.\n * @param {object} args Arguments.\n * @param {string} args.owner Repository owner.\n * @param {string} args.repo Repository name.\n * @param {string} args.branch Branch name.\n * @param {string} args.expectedHeadOid Commit the new commit has to go on top of.\n * @param {FileAddition[]} args.additions File additions.\n * @param {{ path: string }[]} args.deletions File deletions.\n * @param {string} args.message Commit message.\n * @param {AdditionsCommitAuthor} args.author Author, who is the committer as well.\n * @returns {Promise<Record<string, any>>} Commit, in the shape the GraphQL path returns: the SHA as\n * `oid`, the date as `committedDate`, and the file SHAs aliased as `file_{index}`.\n * @see https://docs.github.com/en/rest/git\n */\nexport const createGitDataCommit = async ({\n  owner,\n  repo,\n  branch,\n  expectedHeadOid,\n  additions,\n  deletions,\n  message,\n  author,\n}) => {\n  const base = `/repos/${owner}/${repo}/git`;\n  const addedPaths = new Set(additions.map(({ path }) => path));\n  const binaryAdditions = additions.filter((addition) => !isText(addition));\n\n  const [baseCommit, blobShas, fileShas] = await Promise.all([\n    /** @type {Promise<{ tree: { sha: string } }>} */ (\n      fetchAPI(`${base}/commits/${expectedHeadOid}`)\n    ),\n    mapConcurrently(\n      binaryAdditions,\n      async ({ contents }) =>\n        /** @type {{ sha: string }} */ (\n          await sendWithBackoff(() =>\n            fetchAPI(`${base}/blobs`, {\n              method: 'POST',\n              body: { content: contents, encoding: 'base64' },\n            }),\n          )\n        ).sha,\n      { concurrency: BLOB_CONCURRENCY },\n    ),\n    // The tree lists the files at the top level only, so the SHAs are worked out here instead\n    Promise.all(additions.map(({ data }) => getGitHash(data ?? ''))),\n  ]);\n\n  const tree = [\n    ...additions.map((addition) =>\n      isText(addition)\n        ? { path: addition.path, mode: '100644', type: 'blob', content: addition.data ?? '' }\n        : {\n            path: addition.path,\n            mode: '100644',\n            type: 'blob',\n            sha: blobShas[binaryAdditions.indexOf(addition)],\n          },\n    ),\n    // A file deleted and added again at the same path is just updated\n    ...deletions\n      .filter(({ path }) => !addedPaths.has(path))\n      .map(({ path }) => ({ path, mode: '100644', type: 'blob', sha: null })),\n  ];\n\n  /** @type {{ sha: string }} */\n  const { sha: treeSha } = /** @type {any} */ (\n    await fetchAPI(`${base}/trees`, {\n      method: 'POST',\n      body: { base_tree: baseCommit.tree.sha, tree },\n    })\n  );\n\n  const signature = { name: author.name, email: author.email, date: new Date().toISOString() };\n\n  /** @type {{ sha: string, committer: { date: string } }} */\n  const commit = /** @type {any} */ (\n    await fetchAPI(`${base}/commits`, {\n      method: 'POST',\n      body: {\n        message,\n        tree: treeSha,\n        parents: [expectedHeadOid],\n        author: signature,\n        committer: signature,\n      },\n    })\n  );\n\n  // Without `force`, GitHub refuses to move the branch unless it still points to the parent\n  await fetchAPI(`${base}/refs/heads/${encodePathSegments(branch)}`, {\n    method: 'PATCH',\n    body: { sha: commit.sha, force: false },\n  });\n\n  return {\n    oid: commit.sha,\n    committedDate: commit.committer.date,\n    ...Object.fromEntries(additions.map(({ index }, i) => [`file_${index}`, { oid: fileShas[i] }])),\n  };\n};\n","/**\n * Add an item to a list or remove it from the list, without mutating the list. Used to keep a\n * selection in sync with a checkbox: the item is added when it becomes selected, and removed when\n * it’s deselected. Nothing changes when the item is already in the requested state.\n * @template T\n * @param {T[]} list Original list.\n * @param {T} item Item to add or remove.\n * @param {boolean} include Whether the item should be in the list.\n * @param {(a: T, b: T) => boolean} [isEqual] Function to compare the items. Default: identity.\n * @returns {T[]} New list, or the original list if nothing has changed.\n */\nexport const toggleListItem = (list, item, include, isEqual = (a, b) => a === b) => {\n  const included = list.some((i) => isEqual(i, item));\n\n  if (include && !included) {\n    return [...list, item];\n  }\n\n  if (!include && included) {\n    return list.filter((i) => !isEqual(i, item));\n  }\n\n  return list;\n};\n\n/**\n * Split the given list into chunks of the given size.\n * @template T\n * @param {T[]} items Items to split.\n * @param {number} size Maximum number of items per chunk.\n * @returns {T[][]} Chunks, in the original order.\n */\nexport const splitIntoChunks = (items, size) =>\n  Array.from({ length: Math.ceil(items.length / size) }, (_, i) =>\n    items.slice(i * size, (i + 1) * size),\n  );\n\n/**\n * Split the given list into chunks that each stay within the given number of items and the given\n * total size, keeping the original order. A chunk is closed before the item that would push it over\n * either limit, but never left empty, so an item that exceeds the size limit on its own gets a\n * chunk of its own.\n * @template T\n * @param {T[]} items Items to split.\n * @param {object} limits Limits.\n * @param {number} limits.maxItems Maximum number of items per chunk.\n * @param {number} limits.maxSize Maximum total size of the items per chunk.\n * @param {(item: T) => number} limits.getSize Function to get the size of an item.\n * @returns {T[][]} Chunks, in the original order.\n */\nexport const splitIntoSizedChunks = (items, { maxItems, maxSize, getSize }) => {\n  /** @type {T[][]} */\n  const chunks = [];\n  /** @type {T[]} */\n  let chunk = [];\n  let chunkSize = 0;\n\n  items.forEach((item) => {\n    const size = getSize(item);\n\n    if (chunk.length && (chunk.length === maxItems || chunkSize + size > maxSize)) {\n      chunks.push(chunk);\n      chunk = [];\n      chunkSize = 0;\n    }\n\n    chunk.push(item);\n    chunkSize += size;\n  });\n\n  if (chunk.length) {\n    chunks.push(chunk);\n  }\n\n  return chunks;\n};\n","import { fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { splitIntoChunks } from '$lib/services/utils/array';\n\n/**\n * Build a query that asks for one aliased field of the repository per item. GraphQL aliases can’t\n * be variables, so each item gets its own sub-query. The `$branch` variable is only declared when\n * asked for, because the API rejects a query declaring a variable it doesn’t use. It can’t be\n * worked out from the fragments, which embed file paths and branch names that may contain the same\n * text.\n * @param {{ index: number, fragment: string }[]} parts Fragments, along with the index of the\n * item each one belongs to.\n * @param {string} alias Alias prefix. Each fragment is aliased as `${alias}_${index}`.\n * @param {object} [options] Options.\n * @param {boolean} [options.useBranch] Whether the fragments use the `$branch` variable.\n * @returns {string} GraphQL query.\n */\nexport const buildAliasedQuery = (parts, alias, { useBranch = false } = {}) => {\n  const innerQuery = parts\n    .map(({ index, fragment }) => `${alias}_${index}: ${fragment}`)\n    .join('\\n');\n\n  const branchVar = useBranch ? ', $branch: String!' : '';\n\n  return `\n    query($owner: String!, $repo: String!${branchVar}) {\n      repository(owner: $owner, name: $repo) {\n        ${innerQuery}\n      }\n    }\n  `;\n};\n\n/**\n * Ask the GraphQL API for one aliased field of the repository per item, a chunk of items per\n * request, with a limited number of requests in flight at once. A big query takes longer to answer\n * and is more likely to time out or to exceed the API’s query cost limits, so a long list is split.\n * Any failed request rejects the whole batch.\n * @template T\n * @param {object} args Arguments.\n * @param {T[]} args.items Items to look up.\n * @param {string} args.alias Alias prefix, such as `content`. The result for each item is read from\n * `${alias}_${index}`, where `index` is the item’s position in `items`.\n * @param {(item: T) => string | undefined} args.getFragment Function to build the field selection\n * for an item, without the alias, e.g. `object(oid: \"…\") { … }`. It can return an empty string or\n * `undefined` to leave the item out of the query; its result is then `undefined`.\n * @param {number} args.chunkSize Maximum number of items per request.\n * @param {boolean} [args.useBranch] Whether the fragments use the `$branch` variable.\n * @param {Record<string, any>} [args.variables] Query variables. `owner`, `repo` and `branch` are\n * filled in from the configured repository unless given here.\n * @returns {Promise<any[]>} Result for each item, in the same order as `items`.\n */\nexport const fetchAliasedBatch = async ({\n  items,\n  alias,\n  getFragment,\n  chunkSize,\n  useBranch = false,\n  variables = {},\n}) => {\n  /** @type {any[]} */\n  const results = Array(items.length).fill(undefined);\n\n  const parts = items\n    .map((item, index) => ({ index, fragment: getFragment(item) }))\n    .filter(({ fragment }) => !!fragment);\n\n  await runConcurrently(splitIntoChunks(parts, chunkSize), async (chunk) => {\n    const data = /** @type {{ repository?: Record<string, any> | null }} */ (\n      // Copy the variables, as `fetchGraphQL` adds the common ones to the given object\n      await fetchGraphQL(\n        buildAliasedQuery(/** @type {{ index: number, fragment: string }[]} */ (chunk), alias, {\n          useBranch,\n        }),\n        { ...variables },\n      )\n    );\n\n    chunk.forEach(({ index }) => {\n      results[index] = data?.repository?.[`${alias}_${index}`];\n    });\n  });\n\n  return results;\n};\n","/**\n * @import { FileChange } from '$lib/types/private';\n */\n\n/**\n * HTTP statuses the Git hosting service, or a proxy in front of it, answers a request with when it\n * has taken too long or is too large: 408 Request Timeout, 413 Content Too Large, 499 Client Closed\n * Request, 502 Bad Gateway and 504 Gateway Timeout.\n */\nconst UPLOAD_FAILURE_STATUSES = [408, 413, 499, 502, 504];\n\n/**\n * A file addition in a commit, along with the change it comes from.\n * @typedef {object} FileAddition\n * @property {number} index Index of the addition in the changeset. The GitHub backend uses it to\n * alias the file in the query for its new SHA; the GitLab backend to find the change it comes from.\n * @property {string} path File path.\n * @property {string} contents File contents, Base64-encoded unless the backend sends text as is.\n * @property {FileChange['data']} data Original file data.\n */\n\n/**\n * Sort file additions in the order they are committed. Assets come first and text files like\n * entries last, so an entry never lands in the repository before the files it refers to. A file\n * that is deleted and added again at the same path, which is resolved within a single commit, is\n * set aside, as it has to go into the last commit along with the deletions, however large it is;\n * otherwise the deletion would remove it again.\n * @param {FileAddition[]} additions File additions.\n * @param {Set<string>} [deletedPaths] Paths of the files to be deleted.\n * @returns {{ queue: FileAddition[], addedAgain: FileAddition[] }} Additions to be\n * committed in order, and those that go into the last commit.\n */\nexport const sortAdditions = (additions, deletedPaths = new Set()) => ({\n  queue: additions\n    .filter(({ path }) => !deletedPaths.has(path))\n    .toSorted((a, b) => Number(typeof a.data === 'string') - Number(typeof b.data === 'string')),\n  addedAgain: additions.filter(({ path }) => deletedPaths.has(path)),\n});\n\n/**\n * Take the file additions for the next commit from the start of the queue, as many as fit in the\n * given payload size. A single file over the size is taken on its own.\n * @param {FileAddition[]} queue Additions yet to be committed. Modified in place.\n * @param {number} maxSize Maximum size of the encoded file contents.\n * @returns {FileAddition[]} Additions taken.\n */\nexport const takeAdditions = (queue, maxSize) => {\n  /** @type {FileAddition[]} */\n  const group = [];\n  let size = 0;\n\n  while (queue.length && (!group.length || size + queue[0].contents.length <= maxSize)) {\n    const addition = /** @type {FileAddition} */ (queue.shift());\n\n    group.push(addition);\n    size += addition.contents.length;\n  }\n\n  return group;\n};\n\n/**\n * Get the payload size of the given additions.\n * @param {FileAddition[]} additions File additions.\n * @returns {number} Total size of their encoded contents.\n */\nexport const getPayloadSize = (additions) =>\n  additions.reduce((total, { contents }) => total + contents.length, 0);\n\n/**\n * Estimate how many commits are left to make for the given additions at the given commit size. The\n * last commit is always made, even when it only has the entry files or deletions, so there is at\n * least one.\n * @param {FileAddition[]} queue Additions yet to be committed.\n * @param {number} payloadSize Payload size of each commit.\n * @returns {number} Number of commits.\n */\nexport const estimateRemainingCommits = (queue, payloadSize) =>\n  Math.max(1, Math.ceil(getPayloadSize(queue) / payloadSize));\n\n/**\n * Check if a commit request has failed because it took too long or was too large, which the\n * browser typically reports as a network error, as the answer of the service, or the proxy in front\n * of it, comes without CORS headers.\n * @param {any} ex Error thrown.\n * @returns {boolean} Result.\n */\nexport const isUploadFailure = (ex) =>\n  ex?.message === 'Failed to send the request' ||\n  UPLOAD_FAILURE_STATUSES.includes(ex?.cause?.status);\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * Head commit of the configured branch that the loaded site data reflects: the commit the files\n * were fetched at, or the user’s own latest commit. Comparing it with the branch’s current head\n * tells whether someone else has pushed since. Empty until the site data has been loaded, and for a\n * backend that doesn’t track commits.\n */\nexport const repositoryHead = createRawState('');\n\n/**\n * Generation of the loaded site data, incremented when it’s discarded, e.g. on sign-out. A fetch\n * still on its way at that point, like a check for remote changes, belongs to the previous session:\n * it compares the generation it started in with the current one and drops its results instead of\n * putting them back into the stores, where the next user would find them.\n */\nexport const dataGeneration = { current: 0 };\n\n/**\n * Create a check telling whether the site data has been discarded since the call, e.g. by signing\n * out. A fetch started in one session uses it to drop its results once that session is over.\n * @returns {() => boolean} Function returning `true` if the {@link dataGeneration} has changed\n * since the check was created.\n */\nexport const createStaleCheck = () => {\n  const generation = dataGeneration.current;\n\n  return () => generation !== dataGeneration.current;\n};\n","import { encodeBase64 } from '@sveltia/utils/file';\n\nimport { clearSaveProgress, reportCommits } from '$lib/services/backends/commit-progress';\nimport { getBranchRepository } from '$lib/services/backends/git/github/fork';\nimport { createGitDataCommit } from '$lib/services/backends/git/github/git-data';\nimport { fetchAliasedBatch } from '$lib/services/backends/git/github/graphql';\nimport { repository } from '$lib/services/backends/git/github/repository';\nimport { fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport {\n  estimateRemainingCommits,\n  getPayloadSize,\n  isUploadFailure,\n  sortAdditions,\n  takeAdditions,\n} from '$lib/services/backends/git/shared/commit-split';\nimport {\n  addCommitTrailer,\n  assertBranchNotMoved,\n  createCommitMessage,\n  createLastCommitError,\n  dedupeFileCommits,\n  formatPersonTrailer,\n  MAX_FILE_COMMITS,\n  signOffCommitMessage,\n} from '$lib/services/backends/git/shared/commits';\nimport { checkDirectCommitAllowed } from '$lib/services/backends/git/shared/fork';\nimport { repositoryHead } from '$lib/services/backends/git/shared/head';\nimport { user } from '$lib/services/user/account.svelte';\nimport { getBotCoAuthor } from '$lib/services/utils/commit-author';\nimport { getByteSize } from '$lib/services/utils/file';\n\n/**\n * @import { AdditionsCommitAuthor, CommitOptions, CommitResults } from '$lib/types/private';\n * @import { FileChange, FileCommit } from '$lib/types/private';\n * @import { FileAddition } from '$lib/services/backends/git/shared/commit-split';\n */\n\n/**\n * @typedef {object} LastCommitResponse\n * @property {object} repository Repository information.\n * @property {object} repository.ref Reference information.\n * @property {object} repository.ref.target Target commit.\n * @property {object} repository.ref.target.history Commit history.\n * @property {{ oid: string, message: string }[]} repository.ref.target.history.nodes Nodes in the\n * commit history, containing the commit SHA-1 hash and message.\n */\n\nconst FETCH_LAST_COMMIT_QUERY = `\n  query($owner: String!, $repo: String!, $branch: String!) {\n    repository(owner: $owner, name: $repo) {\n      ref(qualifiedName: $branch) {\n        target {\n          ... on Commit {\n            history(first: 1) {\n              nodes {\n                oid\n                message\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Fetch the last commit on the repository.\n * @param {string} [branchName] Branch to look at. Default: the branch configured in the site\n * configuration. An Editorial Workflow branch can be passed here, in which case the commit is\n * looked up in the repository that holds the branch: see {@link getBranchRepository}.\n * @returns {Promise<{ hash: string, message: string }>} Commit’s SHA-1 hash and message.\n * @throws {Error} When the branch could not be found.\n */\nexport const fetchLastCommit = async (branchName) => {\n  const { owner, repo, branch } = branchName\n    ? getBranchRepository(branchName)\n    : { ...repository, branch: repository.branch };\n\n  const result = /** @type {LastCommitResponse} */ (\n    await fetchGraphQL(FETCH_LAST_COMMIT_QUERY, { owner, repo, ...(branchName ? { branch } : {}) })\n  );\n\n  if (!result.repository) {\n    throw createLastCommitError('repository_not_found', { repo });\n  }\n\n  if (!result.repository.ref) {\n    throw createLastCommitError('branch_not_found', { repo, branch });\n  }\n\n  const { oid: hash, message } = result.repository.ref.target.history.nodes[0];\n\n  return { hash, message };\n};\n\n/**\n * GitHub’s GraphQL API cannot resolve blob OIDs for files over this size (10 MB).\n * @see https://github.com/sveltia/sveltia-cms/issues/692\n */\nconst MAX_GRAPHQL_BLOB_SIZE = 10 * 1024 * 1024;\n\n/**\n * Get the head a commit is expected to go on top of. The caller knows it when it has just created\n * the branch. On the configured branch, it’s the commit the loaded site data reflects, which the\n * caller has just brought up to date: GitHub then refuses the commit if someone else has pushed in\n * the meantime, rather than letting it overwrite their change. On a workflow branch, the caller\n * passes the head the entry was loaded or saved at when there is one, for the same reason;\n * otherwise the head is looked up.\n * @param {CommitOptions} options Commit options.\n * @returns {Promise<string>} Commit SHA.\n */\nconst getExpectedHeadOid = async ({ headOid, branch }) => {\n  if (headOid) {\n    return headOid;\n  }\n\n  if (!branch && repositoryHead.current) {\n    return repositoryHead.current;\n  }\n\n  return (await fetchLastCommit(branch)).hash;\n};\n\n/**\n * Maximum size of the Base64-encoded file contents sent in a single commit mutation (16 MB).\n * GitHub’s GraphQL API aborts a much larger request, which the browser only reports as a network\n * error, so the changes are split into several commits beyond this size.\n * @see https://github.com/sveltia/sveltia-cms/issues/1012\n */\nexport const MAX_COMMIT_PAYLOAD_SIZE = 16 * 1024 * 1024;\n\n/**\n * Size of the Base64-encoded file contents sent in the first commit mutation (2 MB). GitHub closes\n * a request whose body hasn’t arrived within about ten seconds, so the size a commit can take\n * depends on the upload speed, which isn’t known until something has been uploaded. The size of the\n * following commits is worked out from the speed of the previous one.\n * @see https://github.com/sveltia/sveltia-cms/issues/1084\n */\nexport const INITIAL_COMMIT_PAYLOAD_SIZE = 2 * 1024 * 1024;\n\n/**\n * Minimum size of the Base64-encoded file contents sent in a commit mutation (256 KB), so a slow\n * connection doesn’t end up with a commit per small file.\n */\nexport const MIN_COMMIT_PAYLOAD_SIZE = 256 * 1024;\n\n/**\n * Time a commit mutation is meant to take (5 seconds), well within the time GitHub waits for a\n * request body.\n */\nconst TARGET_COMMIT_DURATION = 5000;\n\n/**\n * Work out the payload size of the next commit from how long the previous one took, so a commit\n * takes about {@link TARGET_COMMIT_DURATION} on the connection.\n * @param {number} size Size of the Base64-encoded file contents sent in the previous commit.\n * @param {number} duration Time the previous commit took, in milliseconds.\n * @returns {number} Payload size, between {@link MIN_COMMIT_PAYLOAD_SIZE} and\n * {@link MAX_COMMIT_PAYLOAD_SIZE}.\n */\nexport const getNextPayloadSize = (size, duration) =>\n  Math.min(\n    MAX_COMMIT_PAYLOAD_SIZE,\n    Math.max(\n      MIN_COMMIT_PAYLOAD_SIZE,\n      Math.floor((size / Math.max(duration, 1)) * TARGET_COMMIT_DURATION),\n    ),\n  );\n\n/**\n * Split a commit message into the headline and the body, as the GraphQL API takes them separately\n * and joins them with a blank line. The body is left out if there is none.\n * @param {string} message Commit message.\n * @returns {{ headline: string, body?: string }} Message parts.\n */\nconst splitCommitMessage = (message) => {\n  const [headline, ...rest] = message.split(/\\r?\\n/);\n  const body = rest.join('\\n').trim();\n\n  return body ? { headline, body } : { headline };\n};\n\n/**\n * Commit the given additions and deletions on top of the given head.\n * @param {object} args Arguments.\n * @param {string} args.owner Repository owner.\n * @param {string} args.repo Repository name.\n * @param {string} args.branch Branch name.\n * @param {string} args.expectedHeadOid Commit the new commit has to go on top of.\n * @param {FileAddition[]} args.additions File additions.\n * @param {{ path: string }[]} args.deletions File deletions.\n * @param {string} args.message Commit message.\n * @param {AdditionsCommitAuthor} [args.coAuthor] Person to credit in a `Co-authored-by` trailer,\n * since the author is the app whose token makes the commit.\n * @returns {Promise<Record<string, any>>} Commit, including the new file SHAs aliased as\n * `file_{index}`.\n */\nconst createGraphQLCommit = async ({\n  owner,\n  repo,\n  branch,\n  expectedHeadOid,\n  additions,\n  deletions,\n  message,\n  coAuthor,\n}) => {\n  // Part of the query to fetch new file SHAs; skip files over 10 MB to avoid a GitHub GraphQL\n  // limitation where large blob OIDs cannot be resolved\n  // @see https://github.com/sveltia/sveltia-cms/issues/692\n  const fileShaQuery = additions\n    .map(({ index, path, data }) =>\n      getByteSize(data ?? '') <= MAX_GRAPHQL_BLOB_SIZE\n        ? `file_${index}: file(path: ${JSON.stringify(path)}) { oid }`\n        : '',\n    )\n    .filter(Boolean)\n    .join(' ');\n\n  const query = `\n    mutation($input: CreateCommitOnBranchInput!) {\n      createCommitOnBranch(input: $input) {\n        commit {\n          oid\n          committedDate\n          ${fileShaQuery}\n        }\n      }\n    }\n  `;\n\n  const input = {\n    branch: {\n      repositoryNameWithOwner: `${owner}/${repo}`,\n      branchName: branch,\n    },\n    expectedHeadOid,\n    fileChanges: {\n      additions: additions.map(({ path, contents }) => ({ path, contents })),\n      deletions,\n    },\n    message: splitCommitMessage(\n      coAuthor\n        ? addCommitTrailer(message, formatPersonTrailer('Co-authored-by', coAuthor))\n        : message,\n    ),\n  };\n\n  const {\n    createCommitOnBranch: { commit },\n  } = /** @type {{ createCommitOnBranch: { commit: Record<string, any> }}} */ (\n    // The commit can be sent again after a transient error: one that has already landed is\n    // refused, as the branch no longer points at `expectedHeadOid`\n    await fetchGraphQL(query, { input }, { retryable: true })\n  );\n\n  return commit;\n};\n\n/**\n * Create a commit, with the Git Data API when it has to be authored by the given person, or with\n * GraphQL otherwise.\n * @param {object} args Arguments.\n * @param {string} args.owner Repository owner.\n * @param {string} args.repo Repository name.\n * @param {string} args.branch Branch name.\n * @param {string} args.expectedHeadOid Expected head commit SHA.\n * @param {FileAddition[]} args.additions File additions.\n * @param {{ path: string }[]} args.deletions File deletions.\n * @param {string} args.message Commit message.\n * @param {boolean} args.onWorkflowBranch Whether the commit goes to an Editorial Workflow branch.\n * @param {AdditionsCommitAuthor} [args.author] Person to author the commit, with Sveltia CMS\n * Additions.\n * @param {AdditionsCommitAuthor} [args.coAuthor] Person to credit in a `Co-authored-by` trailer,\n * since the author is the app whose token makes the commit.\n * @returns {Promise<Record<string, any>>} Commit, including the new file SHAs aliased as\n * `file_{index}`.\n */\nconst createCommit = async ({ onWorkflowBranch, author, coAuthor, ...args }) => {\n  try {\n    return author\n      ? await createGitDataCommit({ ...args, author })\n      : await createGraphQLCommit({ ...args, coAuthor });\n  } catch (ex) {\n    // GitHub says so in the error message, but the head is looked up rather than the wording\n    // relied upon\n    if (!onWorkflowBranch) {\n      await assertBranchNotMoved(args.expectedHeadOid, fetchLastCommit);\n    }\n\n    throw ex;\n  }\n};\n\n/**\n * Save entries or assets remotely. The changes normally go into a single commit, but a large\n * changeset, typically an entry with many new images, is split into several commits made one after\n * another, with the entry files in the last one. The size of each commit follows the upload speed\n * measured on the previous one, and a commit that times out is retried with fewer files.\n * @param {FileChange[]} changes File changes to be saved.\n * @param {CommitOptions} options Commit options.\n * @returns {Promise<CommitResults>} Commit results, including the commit SHA and updated file SHAs.\n * The commit is the last one made when the changes have been split.\n * @see https://github.blog/changelog/2021-09-13-a-simpler-api-for-authoring-commits/\n * @see https://docs.github.com/en/graphql/reference/mutations#createcommitonbranch\n */\nexport const commitChanges = async (changes, options) => {\n  checkDirectCommitAllowed(options);\n\n  // A workflow branch lives in the contributor’s fork with Open Authoring, or in the fork of the\n  // contributor whose pull request a maintainer is editing, while the configured branch is only\n  // ever committed to by someone who can write to the configured repository\n  const { owner, repo, branch } = options.branch\n    ? getBranchRepository(options.branch)\n    : { ...repository, branch: /** @type {string} */ (repository.branch) };\n\n  /** @type {FileAddition[]} */\n  const additions = await Promise.all(\n    changes\n      .filter(({ action }) => ['create', 'update', 'move'].includes(action))\n      .map(async ({ path, data }, index) => ({\n        index,\n        path,\n        contents: await encodeBase64(data ?? ''),\n        data,\n      })),\n  );\n\n  const deletions = changes\n    .filter(({ action }) => ['move', 'delete'].includes(action))\n    .map(({ previousPath, path }) => ({ path: previousPath ?? path }));\n\n  // With Sveltia CMS Additions, the token belongs to an app, which GraphQL makes the author. The\n  // Git Data API takes an author, and has no size limit on a commit, which goes in one piece\n  const { commitAuthor } = user.account ?? {};\n  const author = commitAuthor?.mode === 'user' ? commitAuthor : undefined;\n\n  const { queue, addedAgain } = sortAdditions(\n    additions,\n    new Set(deletions.map(({ path }) => path)),\n  );\n\n  const message = signOffCommitMessage(createCommitMessage(changes, options));\n  let expectedHeadOid = await getExpectedHeadOid(options);\n  let payloadSize = author ? Infinity : INITIAL_COMMIT_PAYLOAD_SIZE;\n  // Smallest payload that has timed out, which the following commits stay below, as the speed\n  // measured on a slow or uneven connection can suggest a size that has already failed\n  let timedOutSize = Infinity;\n  let commitCount = 0;\n  /** @type {Record<string, any>} */\n  let commit = {};\n  /** @type {Record<string, any>} */\n  const fileShas = {};\n\n  // Commit the additions in groups, each on top of the previous one, sized so that each commit\n  // takes a few seconds to upload. The deletions go into the last commit along with the entries,\n  // so a file isn’t removed before the entry stops referring to it. There is always at least one\n  // commit, which can have no additions, so a changeset with only deletions is still committed\n  try {\n    do {\n      // The files still waiting, at the current commit size, make up the commits yet to be made\n      reportCommits(commitCount, commitCount + estimateRemainingCommits(queue, payloadSize));\n\n      const group = takeAdditions(queue, payloadSize);\n      const isLast = !queue.length;\n      const groupSize = getPayloadSize(group);\n      const startTime = performance.now();\n\n      try {\n        // eslint-disable-next-line no-await-in-loop\n        commit = await createCommit({\n          owner,\n          repo,\n          branch,\n          expectedHeadOid,\n          additions: isLast ? [...group, ...addedAgain] : group,\n          deletions: isLast ? deletions : [],\n          message,\n          onWorkflowBranch: !!options.branch,\n          author,\n          coAuthor: commitAuthor,\n        });\n      } catch (ex) {\n        // The upload has taken too long on the connection. Put the files back and try again with\n        // half of them, provided the branch is still where it was, so the commit hasn’t landed\n        if (\n          group.length > 1 &&\n          isUploadFailure(ex) &&\n          // eslint-disable-next-line no-await-in-loop\n          (await fetchLastCommit(options.branch).catch(() => undefined))?.hash === expectedHeadOid\n        ) {\n          queue.unshift(...group);\n          timedOutSize = Math.min(timedOutSize, groupSize);\n          payloadSize = Math.floor(groupSize / 2);\n          // eslint-disable-next-line no-continue\n          continue;\n        }\n\n        // Some of the assets have landed on the configured branch, but the entry hasn’t. Take the\n        // last commit made as the known head, so the check before the retry doesn’t load those\n        // assets, which would then be saved again under different names. The retry saves them\n        // under the same paths instead, with the same content, along with the entry. A workflow\n        // branch isn’t tracked this way; it’s reset from scratch when no pull request comes out of\n        // it\n        if (commitCount && !options.branch) {\n          repositoryHead.current = expectedHeadOid;\n        }\n\n        throw ex;\n      }\n\n      payloadSize = Math.min(\n        getNextPayloadSize(groupSize, performance.now() - startTime),\n        timedOutSize - 1,\n      );\n      commitCount += 1;\n      Object.assign(fileShas, commit);\n      expectedHeadOid = commit.oid;\n    } while (queue.length);\n  } finally {\n    clearSaveProgress();\n  }\n\n  return {\n    sha: commit.oid,\n    date: new Date(commit.committedDate),\n    files: Object.fromEntries(\n      additions.map(({ index, path, data }) => [\n        path,\n        {\n          sha: fileShas[`file_${index}`]?.oid,\n          // Preserve the original file for large uploads so the UI can create a blob URL\n          ...(data instanceof Blob && data.size > MAX_GRAPHQL_BLOB_SIZE ? { file: data } : {}),\n        },\n      ]),\n    ),\n  };\n};\n\n/**\n * Number of file paths whose history is requested per GraphQL query. Each one asks for up to 100\n * commits, so a long list is split to keep a query within the API’s cost limits.\n */\nconst FILE_COMMITS_CHUNK_SIZE = 50;\n/**\n * Number of a commit’s authors requested, for the co-author of a commit an app made for someone:\n * the app, the person, and anyone else credited.\n */\nconst MAX_COMMIT_AUTHORS = 3;\n\n/**\n * Fetch commit history for the given file paths.\n * @param {string[]} paths File paths to fetch commit history for.\n * @returns {Promise<FileCommit[]>} Deduplicated and sorted list of commits.\n * @see https://docs.github.com/en/graphql/reference/objects#commit\n */\nexport const fetchFileCommits = async (paths) => {\n  const results = await fetchAliasedBatch({\n    items: paths,\n    alias: 'history',\n    useBranch: true,\n    /**\n     * Build the field selection for the history of a file.\n     * @param {string} path File path.\n     * @returns {string} Field selection.\n     */\n    getFragment: (path) => `\n      ref(qualifiedName: $branch) {\n        target {\n          ... on Commit {\n            history(first: ${MAX_FILE_COMMITS}, path: ${JSON.stringify(path)}) {\n              nodes {\n                oid\n                messageHeadline\n                messageBody\n                author {\n                  name\n                  email\n                  avatarUrl\n                  user { login }\n                }\n                authors(first: ${MAX_COMMIT_AUTHORS}) {\n                  nodes {\n                    email\n                    avatarUrl\n                    user { login }\n                  }\n                }\n                committedDate\n              }\n            }\n          }\n        }\n      }\n    `,\n    chunkSize: FILE_COMMITS_CHUNK_SIZE,\n  });\n\n  return dedupeFileCommits(\n    results.flatMap((result) =>\n      (result?.target?.history?.nodes ?? []).map((/** @type {any} */ node) => {\n        // A commit made by an app for someone, e.g. with Sveltia CMS Additions, is theirs. GitHub\n        // lists the co-authors along with the author, with the avatar it shows for each. Only a\n        // GitHub user’s avatar is taken: anyone else gets GitHub’s default one, which tells nothing\n        // about them, so their initials are shown instead\n        const coAuthor = getBotCoAuthor(node.author, node.messageBody);\n\n        const author = coAuthor\n          ? {\n              ...coAuthor,\n              ...node.authors?.nodes?.find(\n                (/** @type {any} */ actor) =>\n                  actor?.email?.toLowerCase() === coAuthor.email.toLowerCase(),\n              ),\n            }\n          : node.author;\n\n        return {\n          sha: node.oid,\n          message: node.messageHeadline ?? '',\n          // The author can be `null` when the commit has no valid author info\n          authorName: coAuthor?.name ?? node.author?.name ?? '',\n          authorEmail: coAuthor ? coAuthor.email : node.author?.email,\n          authorAvatarURL: author?.user ? author.avatarUrl : undefined,\n          authorLogin: author?.user?.login,\n          date: new Date(node.committedDate),\n        };\n      }),\n    ),\n  );\n};\n","import { fetchAPI } from '$lib/services/backends/git/shared/api';\nimport { cmsConfig } from '$lib/services/config';\n\n/**\n * @import { DeployState, DeployStatus, DeployTarget } from '$lib/types/private';\n * @import { GitBackend } from '$lib/types/public';\n */\n\n/**\n * A deployment candidate normalized from a commit status or a deployment reported by a CI/CD\n * provider connected to the Git backend. The two sources have different shapes, so each backend\n * converts them to this before handing the list to {@link pickDeployment}.\n * @typedef {object} DeployCandidate\n * @property {string} name Commit status context, check run name or deployment environment name.\n * @property {string | null} [url] URL reported alongside the candidate, if any. A provider may give\n * `null` or an empty string for none.\n * @property {DeployState} state Normalized state.\n * @property {string | null} [description] Message the provider attached to the candidate, used to\n * spot a build that was canceled without failing.\n * @property {'deployment' | 'status' | 'check'} source Where the candidate came from, which decides\n * how much its URL can be trusted.\n */\n\n/**\n * Names of commit status contexts and deployment environments that typically carry a site URL. It’s\n * used only as a hint when the `preview_context` backend option is not configured; a candidate that\n * doesn’t match is still usable, it just ranks lower. For a check run it does more — see\n * {@link pickDeployment} — so a provider missing from this list is invisible there, which is why\n * `workers` is here for Cloudflare’s “Workers Builds: <name>” runs. A generic `build` is left out\n * deliberately: it’s the name of half the CI jobs in existence, and letting those through would\n * have an unrelated test suite reporting on whether the site is live.\n */\nconst PREVIEW_NAME_REGEX =\n  /netlify|vercel|cloudflare|workers|deploy|preview|pages|render|surge|amplify|firebase/i;\n\n/** Names that suggest a production environment rather than a per-branch preview. */\nconst PRODUCTION_NAME_REGEX = /prod/i;\n/**\n * Descriptions that mean the build never produced a preview. A provider can report such a build as\n * successful — a monorepo site untouched by the commit reports “Deploy preview canceled.” with a\n * success state — and its URL points at the build log rather than a page.\n * @see https://github.com/decaporg/decap-cms/issues/5107\n */\nconst NO_BUILD_DESCRIPTION_REGEX = /canceled|cancelled|skipped|no (?:changes|build)/i;\n/**\n * How far a candidate’s URL can be trusted, highest first. A deployment’s environment URL is a\n * first-class field. A commit status target URL is usually the site, but sometimes a build log. A\n * check run’s details URL is normally a build log, and only some providers — AWS Amplify among them\n * — use it for the preview, so a check run is accepted only when its name says it’s a preview.\n */\nconst SOURCE_RANK = { deployment: 2, status: 1, check: 0 };\n\n/**\n * Get the `preview_context` backend option, which narrows the deploy preview lookup to one commit\n * status context or deployment environment.\n * @returns {string} Configured context, or an empty string if the option is unset.\n */\nexport const getPreviewContext = () => {\n  const { backend } = cmsConfig.current ?? {};\n\n  return /** @type {GitBackend} */ (backend ?? {}).preview_context ?? '';\n};\n\n/**\n * Validate a URL reported by a CI/CD provider and strip any trailing slash, so it can be joined\n * with a `preview_path` value. The path, if any, is kept: GitLab Pages review apps and some\n * Cloudflare setups serve a preview under a path prefix rather than at the origin.\n * @param {string | undefined | null} url Raw URL.\n * @returns {string | undefined} Normalized URL, or `undefined` if it’s unusable.\n */\nexport const normalizeURL = (url) => {\n  if (!url) {\n    return undefined;\n  }\n\n  let parsed;\n\n  try {\n    parsed = new URL(url);\n  } catch {\n    return undefined;\n  }\n\n  // Refuse an insecure URL, which the browser would block anyway when the CMS is served over HTTPS\n  if (parsed.protocol !== 'https:') {\n    return undefined;\n  }\n\n  return parsed.href.replace(/\\/$/, '');\n};\n\n/**\n * Find a site URL in a check run’s output summary. A provider that points its check at a build page\n * can still publish the deploy address there — Cloudflare Pages writes a table of preview URLs into\n * the summary while the check itself links to the Cloudflare dashboard. Any URL sharing a host with\n * the check’s own link is one of those dashboard links, so it’s passed over.\n * @param {string} [summary] Output summary, which is Markdown, HTML, or a mixture of the two.\n * @param {string} [detailsURL] The check run’s own URL.\n * @returns {string | undefined} First URL leading somewhere other than the provider’s dashboard.\n */\nexport const findURLInSummary = (summary, detailsURL) => {\n  if (!summary) {\n    return undefined;\n  }\n\n  let dashboardHost = '';\n\n  try {\n    dashboardHost = new URL(detailsURL ?? '').host;\n  } catch {\n    // The check may have no URL of its own, in which case there’s nothing to pass over\n  }\n\n  return (summary.match(/https:\\/\\/[^\\s\"'<>)\\]]+/g) ?? [])\n    .map((match) => normalizeURL(match))\n    .find((url) => !!url && new URL(url).host !== dashboardHost);\n};\n\n/**\n * Whether a URL names a page on the Git service rather than a deployed site. A CI job that reports\n * through a commit status commonly links to its own log, and on GitLab every job does — `test`,\n * `lint` and the rest all post a status whose target URL is a job page on the GitLab instance.\n * @param {string | null | undefined} url Candidate URL.\n * @param {string} [selfURL] The repository’s own web URL, which shares a host with those pages.\n * @returns {boolean} Result, `false` when either URL can’t be parsed.\n */\nconst isGitServiceURL = (url, selfURL) => {\n  try {\n    return (\n      new URL(/** @type {string} */ (url)).host === new URL(/** @type {string} */ (selfURL)).host\n    );\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Whether a candidate is named like a deployment. A deployment always is one, while a commit status\n * or a check run that doesn’t name itself a preview is likely some other job on the same push — a\n * test suite, a linter — which says nothing about whether the site is live. GitLab posts a commit\n * status for every CI job, and a GitHub Actions or CircleCI job posts one too. Such a candidate\n * isn’t thrown away, because a provider this list has never heard of would otherwise report nothing\n * and let a failed build pass unnoticed; it’s just outranked by anything that does claim to be a\n * deployment, so a finished test suite can’t stand in for a deploy preview that’s still building. A\n * configured `preview_context` has already narrowed the field by name, so whatever survived that is\n * taken at its word.\n * @param {DeployCandidate} candidate Candidate to judge.\n * @param {string} previewContext Configured context, empty when unset.\n * @returns {boolean} Result.\n */\nconst claimsDeployment = ({ name, source }, previewContext) =>\n  !!previewContext || source === 'deployment' || PREVIEW_NAME_REGEX.test(name);\n\n/**\n * Whether a candidate’s URL can lead to the site. A commit status target URL usually does, even\n * for a provider missing from the name list, whereas a check run’s details URL is normally a build\n * log unless the run claims to be a deployment.\n * @param {DeployCandidate} candidate Candidate to judge.\n * @param {string} previewContext Configured context, empty when unset.\n * @returns {boolean} Result.\n */\nconst canSupplyURL = (candidate, previewContext) =>\n  candidate.source !== 'check' || claimsDeployment(candidate, previewContext);\n\n/**\n * Rank a candidate so the best one can be picked with a single sort. A higher number wins.\n * @param {DeployCandidate} candidate Candidate to score.\n * @param {object} args Arguments.\n * @param {'production' | 'preview'} args.kind Kind of deployment expected.\n * @param {string} args.previewContext Configured context, empty when unset.\n * @returns {number} Score.\n */\nconst getScore = (candidate, { kind, previewContext }) => {\n  const { name, url, state, source } = candidate;\n  const isProductionName = PRODUCTION_NAME_REGEX.test(name);\n\n  return (\n    // Enough to sink it below every real candidate, including one that has yet to report a URL:\n    // a green test suite must not stand in for a deployment that’s still building\n    (claimsDeployment(candidate, previewContext) ? 0 : -64) +\n    // A candidate with somewhere to go is worth more than one that only reports a state\n    (url ? 32 : 0) +\n    // A finished build with a page to open is the most useful thing to report, so it outranks a\n    // more trustworthy source that hasn’t produced a URL yet\n    (state === 'ready' ? 16 : 0) +\n    SOURCE_RANK[source] * 4 +\n    // An environment named after what’s being looked up beats the weaker name hint below, so a\n    // `production` environment isn’t passed over for a `preview` one on the production branch\n    ((kind === 'production') === isProductionName ? 2 : 0) +\n    (PREVIEW_NAME_REGEX.test(name) ? 1 : 0)\n  );\n};\n\n/**\n * Pick the deployment that best represents the site build for a commit. A `pending` result may have\n * no URL, because a provider doesn’t always assign one before the build starts; the UI shows that\n * as a disabled control rather than a link.\n * @param {DeployCandidate[]} candidates Candidates, oldest first.\n * @param {object} args Arguments.\n * @param {'production' | 'preview'} args.kind Kind of deployment expected for the commit.\n * @param {string} [args.selfURL] The repository’s own web URL, used to spot a URL that leads back\n * to the Git service instead of to the site.\n * @returns {DeployStatus} Selected deployment.\n */\nexport const pickDeployment = (candidates, { kind, selfURL }) => {\n  const previewContext = getPreviewContext();\n  let remaining = candidates;\n\n  if (previewContext) {\n    const needle = previewContext.toLowerCase();\n    // Decap CMS matches the context exactly, so an exact match wins to stay compatible with an\n    // existing configuration. A partial value falls back to a substring match rather than silently\n    // matching nothing, which is the more useful reading of a half-remembered context name\n    const exact = remaining.filter(({ name }) => name.toLowerCase() === needle);\n\n    remaining = exact.length\n      ? exact\n      : remaining.filter(({ name }) => name.toLowerCase().includes(needle));\n  }\n\n  // A build that was canceled or skipped has no page behind it, whatever state it reports\n  remaining = remaining.filter(\n    ({ description }) => !description || !NO_BUILD_DESCRIPTION_REGEX.test(description),\n  );\n\n  // A URL is worth something only once the provider says the build is done. Before that there’s\n  // nothing behind it, and a provider with no address to give out yet may offer its own dashboard\n  // in the meantime — Cloudflare Pages does, replacing it with the real one on success. A finished\n  // build can still name a page on the Git service instead of a site. Either way the state is kept\n  // and only the URL is dropped, which the caller pairs with the site’s own address\n  remaining = remaining.map((candidate) => ({\n    ...candidate,\n    url:\n      candidate.state === 'ready' &&\n      canSupplyURL(candidate, previewContext) &&\n      !isGitServiceURL(candidate.url, selfURL)\n        ? normalizeURL(candidate.url)\n        : undefined,\n  }));\n\n  if (!remaining.length) {\n    // Configuring `preview_context` is an explicit narrowing, so an unmatched value doesn’t fall\n    // back to the other candidates. That matches Decap CMS, which has no fallback either\n    return { state: 'unknown', checkedTime: Date.now() };\n  }\n\n  // The backends supply candidates oldest first, so a later one wins a tie\n  const [best] = remaining\n    .map((candidate, index) => ({\n      candidate,\n      index,\n      score: getScore(candidate, { kind, previewContext }),\n    }))\n    .sort((a, b) => b.score - a.score || b.index - a.index)\n    .map(({ candidate }) => candidate);\n\n  return {\n    state: best.state,\n    // Every URL left has been through `normalizeURL()` above\n    url: /** @type {string | undefined} */ (best.url),\n    context: best.name,\n    checkedTime: Date.now(),\n  };\n};\n\n/**\n * Add a deploy candidate to the list for each item whose state maps to a normalized one. A null URL\n * or description needs no coercion: {@link pickDeployment} validates the URL and only tests a\n * description that is present.\n * @param {DeployCandidate[]} list Candidate list for the commit.\n * @param {Record<string, any>[] | null | undefined} items Statuses, deployments or check runs.\n * @param {(item: Record<string, any>) => DeployState | undefined} getState Function to get the\n * normalized state of an item, `undefined` to skip it.\n * @param {(item: Record<string, any>) => Omit<DeployCandidate, 'state'>} toCandidate Function to\n * convert an item to a candidate.\n */\nexport const addCandidates = (list, items, getState, toCandidate) => {\n  items?.forEach((item) => {\n    const state = getState(item);\n\n    if (state) {\n      list.push({ ...toCandidate(item), state });\n    }\n  });\n};\n\n/**\n * Run a collector, reporting a failure without failing the batch, so one source or commit whose\n * info can’t be read — a commit whose statuses are gone after a force push, say — doesn’t take the\n * others down with it.\n * @param {() => Promise<void>} task Task to run.\n */\nexport const collectSafely = async (task) => {\n  try {\n    await task();\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.warn('Failed to fetch the deployment info.', ex);\n  }\n};\n\n/**\n * Fetch the deployment status and URL for the given commits with a backend’s own collector, then\n * pick the best candidate for each commit.\n * @param {DeployTarget[]} targets Commits to look up.\n * @param {object} args Arguments.\n * @param {(shas: string[], candidateMap: Record<string, DeployCandidate[]>) => Promise<void>\n * } args.collect Function that adds the candidates found for the given commits to the map, which\n * has an empty list for each commit.\n * @param {string} [args.selfURL] The repository’s own web URL. See {@link pickDeployment}.\n * @returns {Promise<Record<string, DeployStatus>>} Deployments keyed by commit SHA.\n */\nexport const resolveDeployments = async (targets, { collect, selfURL }) => {\n  // A pull request created in an older session may have no head commit recorded yet\n  const validTargets = targets.filter(({ sha }) => !!sha);\n  // Two pull requests can share a head commit, so look each one up only once\n  const shas = [...new Set(validTargets.map(({ sha }) => sha))];\n\n  if (!shas.length) {\n    return {};\n  }\n\n  /** @type {Record<string, DeployCandidate[]>} */\n  const candidateMap = Object.fromEntries(shas.map((sha) => [sha, []]));\n\n  await collect(shas, candidateMap);\n\n  return Object.fromEntries(\n    validTargets.map(({ sha, kind }) => [\n      sha,\n      pickDeployment(candidateMap[sha], { kind, selfURL }),\n    ]),\n  );\n};\n\n/**\n * Fetch the head commit of the configured branch through a REST API that describes a branch with\n * its `commit.id`, as Gitea/Forgejo and GitLab do. That commit is the one the production site is\n * built from.\n * @param {string | undefined} branch Branch name. `undefined` while the default branch hasn’t been\n * detected yet.\n * @param {(branch: string) => string} getPath Function returning the API path of the branch.\n * @returns {Promise<string | undefined>} Commit SHA, or `undefined` if it couldn’t be resolved.\n */\nexport const fetchRestBranchHeadSHA = async (branch, getPath) => {\n  if (!branch) {\n    return undefined;\n  }\n\n  const result = /** @type {Record<string, any>} */ (await fetchAPI(getPath(branch)));\n\n  return result?.commit?.id ?? undefined;\n};\n","import { fetchAliasedBatch } from '$lib/services/backends/git/github/graphql';\nimport { repository } from '$lib/services/backends/git/github/repository';\nimport { fetchAPI, fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport {\n  addCandidates,\n  collectSafely,\n  findURLInSummary,\n  resolveDeployments,\n} from '$lib/services/backends/git/shared/deployment';\nimport { getRepositoryPath } from '$lib/services/backends/git/shared/repository';\nimport { splitIntoChunks } from '$lib/services/utils/array';\n\n/**\n * @import { DeployState, DeployStatus, DeployTarget } from '$lib/types/private';\n * @import { DeployCandidate } from '$lib/services/backends/git/shared/deployment';\n */\n\n/**\n * Manually trigger a deployment with GitHub Actions by dispatching the `repository_dispatch` event.\n * @returns {Promise<Response>} Response.\n * @see https://docs.github.com/en/rest/repos/repos#create-a-repository-dispatch-event\n */\nexport const triggerDeployment = async () =>\n  /** @type {Promise<Response>} */ (\n    fetchAPI(`${getRepositoryPath(repository)}/dispatches`, {\n      method: 'POST',\n      body: { event_type: 'sveltia-cms-publish' },\n      responseType: 'raw',\n    })\n  );\n\n/**\n * Maximum number of commits to look up in one GraphQL request, and deployments to read per commit.\n * A commit rarely has more than a couple of deployments; the cap only guards a repository where\n * several providers are connected at once.\n */\nconst MAX_ITEMS = { commits: 20, deployments: 10, checkSuites: 10, checkRuns: 20 };\n\n/**\n * Map a GraphQL `StatusState` to a normalized state. `EXPECTED` means a required check hasn’t\n * reported yet, so it’s treated the same as a running build.\n * @type {Record<string, DeployState>}\n * @see https://docs.github.com/en/graphql/reference/enums#statusstate\n */\nconst STATUS_STATE_MAP = {\n  SUCCESS: 'ready',\n  PENDING: 'pending',\n  EXPECTED: 'pending',\n  FAILURE: 'error',\n  ERROR: 'error',\n};\n\n/**\n * Map a GraphQL `DeploymentStatusState` to a normalized state. `INACTIVE` and `DESTROYED` are\n * absent, so a superseded or torn-down environment is skipped rather than reported as a preview.\n * @type {Record<string, DeployState>}\n * @see https://docs.github.com/en/graphql/reference/enums#deploymentstatusstate\n */\nconst DEPLOYMENT_STATE_MAP = {\n  SUCCESS: 'ready',\n  PENDING: 'pending',\n  QUEUED: 'pending',\n  IN_PROGRESS: 'pending',\n  WAITING: 'pending',\n  FAILURE: 'error',\n  ERROR: 'error',\n};\n\n/**\n * Map a GraphQL `CheckConclusionState` to a normalized state. `CANCELLED`, `SKIPPED` and `STALE`\n * are absent, so a run that produced nothing is ignored rather than reported as a preview.\n * @type {Record<string, DeployState>}\n * @see https://docs.github.com/en/graphql/reference/enums#checkconclusionstate\n */\nconst CHECK_CONCLUSION_MAP = {\n  SUCCESS: 'ready',\n  NEUTRAL: 'ready',\n  FAILURE: 'error',\n  TIMED_OUT: 'error',\n  STARTUP_FAILURE: 'error',\n  ACTION_REQUIRED: 'error',\n};\n\n/**\n * Names that say a check run offers a deploy preview at its own URL rather than pointing at a build\n * page. It’s only consulted when the run publishes no address in its output summary — AWS Amplify\n * reports “AWS Amplify Console Web Preview” and links straight to the preview, while Cloudflare\n * Pages links to its dashboard and puts the address in the summary instead.\n */\nconst PREVIEW_CHECK_NAME_REGEX = /preview/i;\n\n/**\n * Fetch the head commit of the configured branch, which is the commit the production site is built\n * from.\n * @returns {Promise<string | undefined>} Commit SHA, or `undefined` if it couldn’t be resolved.\n * @see https://docs.github.com/en/graphql/reference/objects#ref\n */\nexport const fetchBranchHeadSHA = async () => {\n  if (!repository.branch) {\n    // The default branch hasn’t been detected yet\n    return undefined;\n  }\n\n  const { repository: result } = /** @type {Record<string, any>} */ (\n    await fetchGraphQL(`\n      query($owner: String!, $repo: String!, $branch: String!) {\n        repository(owner: $owner, name: $repo) {\n          ref(qualifiedName: $branch) {\n            target {\n              ... on Commit {\n                oid\n              }\n            }\n          }\n        }\n      }\n    `)\n  );\n\n  return result?.ref?.target?.oid ?? undefined;\n};\n\n/**\n * Read the given fields from each commit in a single batched request.\n * @param {string[]} shas Commit SHAs. The caller keeps the list to {@link MAX_ITEMS.commits}.\n * @param {string} selection Inner selection on the `Commit` type.\n * @returns {Promise<any[]>} Commit node for each SHA, in the same order.\n */\nconst fetchCommits = (shas, selection) =>\n  fetchAliasedBatch({\n    items: shas,\n    alias: 'commit',\n    /**\n     * Build the field selection for a commit.\n     * @param {string} sha Commit SHA.\n     * @returns {string} Field selection.\n     */\n    getFragment: (sha) => `object(oid: ${JSON.stringify(sha)}) { ... on Commit { ${selection} } }`,\n    chunkSize: MAX_ITEMS.commits,\n  });\n\n/**\n * What to ask for on each commit, and how to read the answer. Keeping the two side by side lets the\n * three be asked for together in one request, or separately when that isn’t possible.\n * @type {Record<string, { selection: string, parse: (commit: any, sha: string,\n * candidateMap: Record<string, DeployCandidate[]>) => void }>}\n */\nconst SOURCES = {\n  /**\n   * Commit statuses, where an external CI service posts a build result when it posts one at all.\n   * @see https://docs.github.com/en/graphql/reference/objects#status\n   */\n  status: {\n    selection: 'status { contexts { context state targetUrl description } }',\n    /**\n     * Read the commit statuses from one commit node.\n     * @param {any} commit Commit node.\n     * @param {string} sha Commit SHA.\n     * @param {Record<string, DeployCandidate[]>} candidateMap Map to populate.\n     */\n    parse: (commit, sha, candidateMap) => {\n      addCandidates(\n        candidateMap[sha],\n        commit?.status?.contexts,\n        ({ state }) => STATUS_STATE_MAP[state],\n        ({ context, targetUrl, description }) => ({\n          name: context ?? '',\n          url: targetUrl,\n          description,\n          source: 'status',\n        }),\n      );\n    },\n  },\n\n  /**\n   * Deployments. Vercel and GitHub Pages report here, and unlike a commit status target URL, the\n   * environment URL is guaranteed to point at the site rather than a build log. Cloudflare, both\n   * Pages and Workers, reports through check runs instead.\n   * @see https://docs.github.com/en/graphql/reference/objects#deployment\n   */\n  deployments: {\n    selection: `deployments(\n      last: ${MAX_ITEMS.deployments}\n      orderBy: { field: CREATED_AT, direction: ASC }\n    ) {\n      nodes {\n        environment\n        latestStatus {\n          state\n          environmentUrl\n          description\n        }\n      }\n    }`,\n    /**\n     * Read the deployments from one commit node.\n     * @param {any} commit Commit node.\n     * @param {string} sha Commit SHA.\n     * @param {Record<string, DeployCandidate[]>} candidateMap Map to populate.\n     */\n    parse: (commit, sha, candidateMap) => {\n      addCandidates(\n        candidateMap[sha],\n        commit?.deployments?.nodes,\n        ({ latestStatus }) => DEPLOYMENT_STATE_MAP[latestStatus?.state],\n        ({ environment, latestStatus }) => ({\n          name: environment ?? '',\n          url: latestStatus?.environmentUrl,\n          description: latestStatus?.description,\n          source: 'deployment',\n        }),\n      );\n    },\n  },\n\n  /**\n   * Check runs. Most are ordinary CI jobs whose details URL is a build log, but a few providers\n   * publish the preview URL here and nowhere else: Cloudflare Pages writes it into the run’s output\n   * summary, and AWS Amplify links its “AWS Amplify Console Web Preview” run straight at the site.\n   * @see https://docs.github.com/en/graphql/reference/objects#checkrun\n   * @see https://github.com/decaporg/decap-cms/issues/5161\n   */\n  checks: {\n    selection: `checkSuites(last: ${MAX_ITEMS.checkSuites}) {\n      nodes {\n        checkRuns(last: ${MAX_ITEMS.checkRuns}) {\n          nodes {\n            name\n            status\n            conclusion\n            detailsUrl\n            summary\n          }\n        }\n      }\n    }`,\n    /**\n     * Read the check runs from one commit node.\n     * @param {any} commit Commit node.\n     * @param {string} sha Commit SHA.\n     * @param {Record<string, DeployCandidate[]>} candidateMap Map to populate.\n     */\n    parse: (commit, sha, candidateMap) => {\n      addCandidates(\n        candidateMap[sha],\n        commit?.checkSuites?.nodes?.flatMap(\n          (/** @type {Record<string, any>} */ suite) => suite?.checkRuns?.nodes ?? [],\n        ),\n        // A run that hasn’t finished has no conclusion yet, so the status carries the state\n        ({ status, conclusion }) =>\n          status === 'COMPLETED' ? CHECK_CONCLUSION_MAP[conclusion] : 'pending',\n        ({ name, detailsUrl, summary }) => ({\n          name: name ?? '',\n          // A URL published in the output is the provider saying where the site went, so it’s taken\n          // at face value. The check’s own link is usually a build page, and is trusted only when\n          // the run names itself a preview, as AWS Amplify’s does\n          url:\n            findURLInSummary(summary, detailsUrl) ??\n            (PREVIEW_CHECK_NAME_REGEX.test(name) ? detailsUrl : undefined),\n          source: 'check',\n        }),\n      );\n    },\n  },\n};\n\n/**\n * Whether the three sources have to be asked for one at a time. GitHub answers a query touching an\n * unavailable field with partial data *and* an `errors` array, which the shared request helper\n * treats as a failure — so one missing field would cost all three. That’s rare, and permanent for a\n * given repository and token, so it’s discovered once and remembered rather than assumed every\n * time. A transient failure latches this too, which only costs extra requests.\n */\nlet askSeparately = false;\n\n/**\n * Ask for all three sources in a single request.\n * @param {string[]} shas Commit SHAs.\n * @param {Record<string, DeployCandidate[]>} candidateMap Map to populate, keyed by commit SHA.\n */\nconst collectTogether = async (shas, candidateMap) => {\n  const selection = Object.values(SOURCES)\n    .map(({ selection: part }) => part)\n    .join('\\n');\n\n  const commits = await fetchCommits(shas, selection);\n\n  shas.forEach((sha, index) => {\n    Object.values(SOURCES).forEach(({ parse }) => parse(commits[index], sha, candidateMap));\n  });\n};\n\n/**\n * Ask for each source in its own request, so an unavailable field only costs its own source.\n * @param {string[]} shas Commit SHAs.\n * @param {Record<string, DeployCandidate[]>} candidateMap Map to populate, keyed by commit SHA.\n */\nconst collectOneByOne = async (shas, candidateMap) => {\n  await Promise.all(\n    // A missing or restricted field shouldn’t take the other sources down with it\n    Object.values(SOURCES).map(({ selection, parse }) =>\n      collectSafely(async () => {\n        const commits = await fetchCommits(shas, selection);\n\n        shas.forEach((sha, index) => parse(commits[index], sha, candidateMap));\n      }),\n    ),\n  );\n};\n\n/**\n * Collect deploy candidates for the given commits from all three sources. They’re asked for in one\n * request per chunk, dropping to one request each only if that fails.\n * @param {string[]} shas Commit SHAs.\n * @param {Record<string, DeployCandidate[]>} candidateMap Candidates keyed by commit SHA.\n */\nconst collectCandidates = async (shas, candidateMap) => {\n  // Chunked here rather than in `fetchAliasedBatch`, so a failure only sends its own chunk down the\n  // one-request-per-source path\n  await runConcurrently(splitIntoChunks(shas, MAX_ITEMS.commits), async (chunk) => {\n    if (!askSeparately) {\n      try {\n        await collectTogether(chunk, candidateMap);\n\n        return;\n      } catch (ex) {\n        // eslint-disable-next-line no-console\n        console.warn('Falling back to a request per deployment source.', ex);\n        askSeparately = true;\n      }\n    }\n\n    await collectOneByOne(chunk, candidateMap);\n  });\n};\n\n/**\n * Fetch the deployment status and URL for the given commits. All three sources are asked for in one\n * request, dropping to one request each only if that fails — which happens when a field is\n * unavailable, on GitHub Enterprise Server or with a token lacking deployment scope, because the\n * API answers with partial data and an error together and the shared request helper rejects the\n * whole response. A repository that needs the split pays for discovering it once.\n * @param {DeployTarget[]} targets Commits to look up.\n * @returns {Promise<Record<string, DeployStatus>>} Deployments keyed by commit SHA.\n */\nexport const fetchDeployments = async (targets) =>\n  resolveDeployments(targets, { collect: collectCandidates, selfURL: repository.repoURL });\n","/**\n * @import { Asset, Entry } from '$lib/types/private';\n */\n\n/**\n * Get the key to match up an entry’s file with the same file of a previous entry. An entry\n * collection can store all the entries in one file, where an entry is told by its position.\n * @param {Entry} entry Entry.\n * @param {string} path Path of one of the entry’s files.\n * @returns {string} Key.\n */\nconst getFileKey = ({ arrayIndex }, path) =>\n  arrayIndex === undefined ? path : `${path}#${arrayIndex}`;\n\n/**\n * Carry the identity of the entries already in the store over to a freshly parsed list. An entry’s\n * `id` is made up when its files are parsed, so a second fetch would give every entry a new one,\n * and anything holding an ID — the editor’s draft, a selection in the list, a saved entry about to\n * replace its predecessor — would lose track of its entry. The ID is matched up through the file\n * paths instead. An entry none of whose files have changed is kept as the very same object, which\n * both spares the UI a re-render of everything and lets the caller tell what a fetch has changed by\n * comparing the objects.\n * @param {object} args Arguments.\n * @param {Entry[]} args.entries Entries parsed from the latest fetch.\n * @param {Entry[]} args.previous Entries in the store at the moment.\n * @param {Set<string>} args.changedPaths Paths of the files whose content differs from what was\n * fetched last time.\n * @returns {Entry[]} The new list, with the previous IDs and objects wherever they apply.\n */\nexport const reconcileEntries = ({ entries, previous, changedPaths }) => {\n  if (!previous.length) {\n    return entries;\n  }\n\n  /** @type {Map<string, Entry>} */\n  const previousByPath = new Map(\n    previous.flatMap((entry) =>\n      Object.values(entry.locales).map(({ path }) => [getFileKey(entry, path), entry]),\n    ),\n  );\n\n  // A previous entry stands in for one new entry only. Its files can end up in two entries, e.g.\n  // when a localized file has been given another canonical slug, and the second one is new\n  const claimed = new Set();\n\n  return entries.map((entry) => {\n    const paths = Object.values(entry.locales).map(({ path }) => path);\n\n    const match = paths\n      .map((path) => previousByPath.get(getFileKey(entry, path)))\n      .find((candidate) => !!candidate && !claimed.has(candidate));\n\n    if (!match) {\n      return entry;\n    }\n\n    claimed.add(match);\n\n    const previousPaths = Object.values(match.locales).map(({ path }) => path);\n\n    // A locale file added or removed makes it a different entry as far as the editor is concerned\n    const unchanged =\n      paths.length === previousPaths.length &&\n      paths.every((path) => previousPaths.includes(path) && !changedPaths.has(path));\n\n    return unchanged ? match : { ...entry, id: match.id };\n  });\n};\n\n/**\n * Keep the asset objects already in the store wherever the file hasn’t changed, so that a blob URL\n * or thumbnail attached to one survives a fetch, and so that the caller can tell what has changed\n * by comparing the objects. An asset committed to an Editorial Workflow branch is not in the file\n * list of the configured branch, so it’s carried over the way `mergeWorkflowAssets` merged it: it\n * keeps shadowing the published file at the same path, which becomes its `replacedAsset`, and one\n * that only exists on the workflow branch stays at the end of the list.\n * @param {object} args Arguments.\n * @param {Asset[]} args.assets Assets from the latest fetch.\n * @param {Asset[]} args.previous Assets in the store at the moment.\n * @param {Set<string>} args.changedPaths Paths of the files whose content differs from what was\n * fetched last time.\n * @returns {Asset[]} The new list, with the previous objects wherever they apply.\n */\nexport const reconcileAssets = ({ assets, previous, changedPaths }) => {\n  if (!previous.length) {\n    return assets;\n  }\n\n  const previousByPath = new Map(previous.map((asset) => [asset.path, asset]));\n  const fetchedPaths = new Set(assets.map(({ path }) => path));\n\n  /**\n   * Put the given published asset under the workflow asset shadowing it.\n   * @param {Asset} workflowAsset Workflow asset in the store.\n   * @param {Asset | undefined} published Published asset at the same path, if any.\n   * @returns {Asset} Workflow asset; the same object if its published version hasn’t changed.\n   */\n  const shadow = (workflowAsset, published) => {\n    const { workflow } = /** @type {{ workflow: NonNullable<Asset['workflow']> }} */ (\n      workflowAsset\n    );\n\n    return workflow.replacedAsset === published\n      ? workflowAsset\n      : { ...workflowAsset, workflow: { ...workflow, replacedAsset: published } };\n  };\n\n  return [\n    ...assets.map((asset) => {\n      const match = previousByPath.get(asset.path);\n      const previousPublished = match?.workflow ? match.workflow.replacedAsset : match;\n\n      const published =\n        previousPublished && !changedPaths.has(asset.path) ? previousPublished : asset;\n\n      return match?.workflow ? shadow(match, published) : published;\n    }),\n    // The published file a workflow asset was shadowing may have been deleted in the meantime\n    ...previous\n      .filter(({ path, workflow }) => !!workflow && !fetchedPaths.has(path))\n      .map((asset) => shadow(asset, undefined)),\n  ];\n};\n","import { getCollection } from '$lib/services/contents/collection';\nimport { getCollectionFile } from '$lib/services/contents/collection/files';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { BaseEntryListItem, Entry, EntryFolderInfo } from '$lib/types/private';\n */\n\n/**\n * Check whether the files of the given collection can be merged into one entry, which is the case\n * with a multi-file i18n structure: the localized files of an entry are grouped by their slug or\n * canonical slug, so a change to one file can move another one to a different entry.\n * @param {EntryFolderInfo} folder Entry folder of a file.\n * @returns {boolean} Result.\n */\nexport const canMergeFiles = ({ collectionName, fileName }) => {\n  const collection = getCollection(collectionName);\n\n  const collectionFile =\n    collection && fileName ? getCollectionFile(collection, fileName) : undefined;\n\n  const { structureMap } = (collectionFile ?? collection)?._i18n ?? {};\n\n  return !!(\n    structureMap?.i18nMultiFile ||\n    structureMap?.i18nMultiFolder ||\n    structureMap?.i18nMultiRootFolder\n  );\n};\n\n/**\n * Work out which of the entries already in the store can stand for the given files as they are, so\n * that a fetch made after the initial load only parses the files that have changed. Parsing every\n * entry again would give the same result for the rest, which `reconcileEntries()` would then throw\n * away in favour of the previous objects anyway.\n *\n * A file is only covered by a previous entry if neither it nor any other file of that entry has\n * changed or gone, and no other previous entry claims it. A file that previously made no entry,\n * e.g. one that failed to parse, is parsed again, so its error is reported again. With a multi-file\n * i18n structure, a new, changed or removed file can regroup the other files of its collection, so\n * the whole collection is parsed again unless every one of its files is covered.\n * @param {object} args Arguments.\n * @param {BaseEntryListItem[]} args.entryFiles Entry files in the latest file list.\n * @param {Entry[]} args.previous Entries in the store at the moment.\n * @param {Set<string>} args.changedPaths Paths of the files whose content differs from what was\n * fetched last time.\n * @returns {{ reusedEntries: Map<string, Entry>, dirtyFiles: BaseEntryListItem[] }} Previous\n * entries to keep, keyed with each of their file paths, and the files to parse.\n */\nexport const planEntryReparse = ({ entryFiles, previous, changedPaths }) => {\n  const currentPaths = new Set(entryFiles.map(({ path }) => path));\n  /** @type {Map<string, Entry>} */\n  const previousByPath = new Map();\n  /** @type {Set<string>} */\n  const sharedPaths = new Set();\n\n  previous.forEach((entry) => {\n    getEntryPaths(entry).forEach((path) => {\n      if (previousByPath.has(path)) {\n        sharedPaths.add(path);\n      }\n\n      previousByPath.set(path, entry);\n    });\n  });\n\n  /**\n   * Find the previous entry that can stand for the given file.\n   * @param {BaseEntryListItem} file File.\n   * @param {boolean} mergeable Whether the file can be merged with other files into one entry.\n   * @returns {Entry | undefined} Entry.\n   */\n  const getReusableEntry = ({ path }, mergeable) => {\n    const entry = previousByPath.get(path);\n\n    if (!entry || changedPaths.has(path) || sharedPaths.has(path)) {\n      return undefined;\n    }\n\n    const paths = getEntryPaths(entry);\n\n    // Without merging, an entry is made of its own file only\n    if (!mergeable && (paths.length !== 1 || paths[0] !== path)) {\n      return undefined;\n    }\n\n    const intact = paths.every(\n      (_path) => currentPaths.has(_path) && !changedPaths.has(_path) && !sharedPaths.has(_path),\n    );\n\n    return intact ? entry : undefined;\n  };\n\n  /** @type {Map<string, Entry>} */\n  const reusedEntries = new Map();\n  /** @type {BaseEntryListItem[]} */\n  const dirtyFiles = [];\n  /** @type {Map<string, boolean>} */\n  const mergeableCache = new Map();\n  /** @type {Map<string, { file: BaseEntryListItem, entry: Entry | undefined }[]>} */\n  const mergeableGroups = new Map();\n\n  entryFiles.forEach((file) => {\n    const { collectionName, fileName } = file.folder;\n    const cacheKey = `${collectionName}\\n${fileName ?? ''}`;\n    let mergeable = mergeableCache.get(cacheKey);\n\n    if (mergeable === undefined) {\n      mergeable = canMergeFiles(file.folder);\n      mergeableCache.set(cacheKey, mergeable);\n    }\n\n    const entry = getReusableEntry(file, mergeable);\n\n    if (mergeable) {\n      // Files are grouped within a collection, so that’s the unit to parse again or keep\n      const group = mergeableGroups.get(collectionName) ?? [];\n\n      group.push({ file, entry });\n      mergeableGroups.set(collectionName, group);\n    } else if (entry) {\n      reusedEntries.set(file.path, entry);\n    } else {\n      dirtyFiles.push(file);\n    }\n  });\n\n  mergeableGroups.forEach((group) => {\n    if (group.every(({ entry }) => !!entry)) {\n      group.forEach(({ file, entry }) => {\n        reusedEntries.set(file.path, /** @type {Entry} */ (entry));\n      });\n    } else {\n      dirtyFiles.push(...group.map(({ file }) => file));\n    }\n  });\n\n  return { reusedEntries, dirtyFiles };\n};\n\n/**\n * Put the previous entries being kept and the freshly parsed ones together, in the order of their\n * first file in the file list, which is the order `prepareEntries()` gives them in.\n * @param {object} args Arguments.\n * @param {BaseEntryListItem[]} args.entryFiles Entry files in the latest file list.\n * @param {Map<string, Entry>} args.reusedEntries Previous entries to keep, keyed with each of their\n * file paths.\n * @param {Entry[]} args.parsedEntries Entries parsed from the other files.\n * @returns {Entry[]} Entries.\n */\nexport const mergeEntries = ({ entryFiles, reusedEntries, parsedEntries }) => {\n  /** @type {Map<string, Entry[]>} */\n  const parsedByPath = new Map();\n\n  // A file storing all the entries of an entry collection makes more than one entry\n  parsedEntries.forEach((entry) => {\n    getEntryPaths(entry).forEach((path) => {\n      // Appended in place: a file holding every entry of a collection has thousands of them, and\n      // copying the list for each one would take quadratic time\n      getOrCreate(parsedByPath, path, () => /** @type {Entry[]} */ ([])).push(entry);\n    });\n  });\n\n  /** @type {Set<Entry>} */\n  const entries = new Set();\n\n  entryFiles.forEach(({ path }) => {\n    const reusedEntry = reusedEntries.get(path);\n\n    (reusedEntry ? [reusedEntry] : (parsedByPath.get(path) ?? [])).forEach((entry) => {\n      entries.add(entry);\n    });\n  });\n\n  return [...entries];\n};\n","import { getAssetKind } from '$lib/services/assets/kinds';\nimport { allAssets } from '$lib/services/assets/state';\nimport { gitConfigFiles } from '$lib/services/backends/git/shared/config';\nimport { reconcileAssets, reconcileEntries } from '$lib/services/backends/git/shared/reconcile';\nimport { mergeEntries, planEntryReparse } from '$lib/services/backends/git/shared/reparse';\nimport { allEntries, dataLoaded, entryParseErrors } from '$lib/services/contents';\nimport { prepareEntries } from '$lib/services/contents/file/process';\n\n/**\n * @import {\n * Asset,\n * BaseAssetListItem,\n * BaseConfigListItem,\n * BaseEntryListItem,\n * BaseFileList,\n * BaseFileListItem,\n * Entry,\n * RepositoryContentsMap,\n * } from '$lib/types/private';\n * @import { RepositoryMetadataMap } from '$lib/services/backends/git/shared/fetch';\n * @import { ParsedFileMap } from '$lib/services/contents/file/process';\n */\n\n/**\n * Complete file info with the size, text content and commit metadata fetched for the file.\n * @param {object} args Arguments.\n * @param {BaseFileListItem} args.fileInfo File info.\n * @param {RepositoryContentsMap} args.fetchedFileMap Map of fetched file metadata and content.\n * @returns {BaseFileListItem} Completed file info.\n */\nexport const parseFileInfo = ({ fileInfo, fetchedFileMap }) => {\n  // The file list only has what the backend lists, plus what was restored from the cache. The\n  // rest comes from `fetchFileContents`: some backends only provide the `size` there, and it’s\n  // where the `text` of an uncached file comes from, as well as its `meta` unless the metadata is\n  // fetched in a separate pass, which fills it in later with `applyFileMetadata`\n  const { meta, size, text } = fetchedFileMap[fileInfo.path] ?? {};\n\n  return {\n    ...fileInfo,\n    size: fileInfo.size ?? size,\n    text: fileInfo.text ?? text,\n    meta: fileInfo.meta ?? meta,\n  };\n};\n\n/**\n * Parse a single asset file to create a complete, serialized asset.\n * @param {BaseAssetListItem} fileInfo Asset file info.\n * @returns {Asset} Parsed asset.\n */\nexport const parseAssetFileInfo = (fileInfo) => {\n  const { name, meta = {}, ...rest } = fileInfo;\n  const kind = getAssetKind(name);\n\n  return { ...rest, ...meta, name, kind };\n};\n\n/**\n * List the paths of the files an entry or asset is made of.\n * @param {Entry | Asset} item Entry or asset.\n * @returns {string[]} Paths.\n */\nconst getFilePaths = (item) =>\n  'locales' in item ? Object.values(item.locales).map(({ path }) => path) : [item.path];\n\n/**\n * Update the stores with the latest entries, assets, config files, and errors. On a fetch made\n * after the initial load, the entries and assets already in the stores are carried over wherever\n * their files haven’t changed, so the rest of the app doesn’t lose track of them.\n * @param {object} args Arguments.\n * @param {Entry[]} args.entries List of entry files.\n * @param {Asset[]} args.assets List of asset files.\n * @param {BaseConfigListItem[]} args.configFiles List of Git config files.\n * @param {Error[]} [args.errors] List of errors encountered while parsing entries.\n * @param {Set<string>} [args.changedPaths] Paths of the files whose content differs from what was\n * fetched last time. Every file counts as changed if omitted.\n */\nexport const updateStores = ({ entries, assets, configFiles, errors = [], changedPaths }) => {\n  const changed = changedPaths ?? new Set([...entries, ...assets].flatMap(getFilePaths));\n\n  allEntries.current = reconcileEntries({\n    entries,\n    previous: allEntries.current,\n    changedPaths: changed,\n  });\n  allAssets.current = reconcileAssets({\n    assets,\n    previous: allAssets.current,\n    changedPaths: changed,\n  });\n  gitConfigFiles.current = configFiles;\n  entryParseErrors.current = errors;\n  dataLoaded.current = true;\n};\n\n/**\n * Fill in the commit metadata that was left out of the first fetch, once it has arrived. The\n * stores are only replaced if something actually changed, and an entry or asset that already has\n * its metadata — one saved while the metadata was on its way — is left alone, as its commit is\n * newer than the one looked up.\n * @param {object} args Arguments.\n * @param {RepositoryContentsMap} args.fetchedFileMap Map of fetched file data, updated in place so\n * the metadata is cached along with the text.\n * @param {RepositoryMetadataMap} args.metadataMap Commit metadata of the fetched files.\n */\nexport const applyFileMetadata = ({ fetchedFileMap, metadataMap }) => {\n  Object.entries(metadataMap).forEach(([path, meta]) => {\n    if (fetchedFileMap[path]) {\n      fetchedFileMap[path].meta = meta;\n    }\n  });\n\n  let entriesChanged = false;\n  let assetsChanged = false;\n\n  const entries = allEntries.current.map((entry) => {\n    if (entry.commitDate) {\n      return entry;\n    }\n\n    // An entry takes its metadata from whichever of its files is known, as when it was parsed\n    const meta = Object.values(entry.locales)\n      .map(({ path }) => metadataMap[path])\n      .find(Boolean);\n\n    if (!meta) {\n      return entry;\n    }\n\n    entriesChanged = true;\n\n    return { ...entry, ...meta };\n  });\n\n  const assets = allAssets.current.map((asset) => {\n    const meta = asset.commitDate ? undefined : metadataMap[asset.path];\n\n    if (!meta) {\n      return asset;\n    }\n\n    assetsChanged = true;\n\n    return { ...asset, ...meta };\n  });\n\n  if (entriesChanged) {\n    allEntries.current = entries;\n  }\n\n  if (assetsChanged) {\n    allAssets.current = assets;\n  }\n};\n\n/**\n * Parse the entry files into entries. On a fetch made after the initial load, only the files that\n * have changed are parsed, and the entries already in the store are kept for the rest.\n * @param {object} args Arguments.\n * @param {BaseEntryListItem[]} args.entryFiles Entry files, completed with their text.\n * @param {Set<string>} [args.changedPaths] Paths of the files whose content differs from what was\n * fetched last time. Every file is parsed if omitted.\n * @param {ParsedFileMap} [args.parsedFileMap] Map to add the content parsed from each file to, so\n * it can be cached.\n * @returns {Promise<{ entries: Entry[], errors: Error[] }>} Parsed entries, and errors encountered\n * while parsing them.\n */\nconst parseEntryFiles = async ({ entryFiles, changedPaths, parsedFileMap }) => {\n  const previous = allEntries.current;\n\n  if (!changedPaths || !previous.length) {\n    return prepareEntries(entryFiles, { parsedFileMap });\n  }\n\n  const { reusedEntries, dirtyFiles } = planEntryReparse({ entryFiles, previous, changedPaths });\n  const { entries: parsedEntries, errors } = await prepareEntries(dirtyFiles, { parsedFileMap });\n\n  return { entries: mergeEntries({ entryFiles, reusedEntries, parsedEntries }), errors };\n};\n\n/**\n * Parse the entry, asset and config files in the file list.\n * @param {object} args Arguments.\n * @param {BaseFileList} args.fileList Repository’s file list.\n * @param {RepositoryContentsMap} args.fetchedFileMap Map of fetched file metadata and content.\n * @param {Set<string>} [args.changedPaths] Paths of the files whose content differs from what was\n * fetched last time, given to parse only those entry files again. Every file is parsed if omitted.\n * @param {ParsedFileMap} [args.parsedFileMap] Map to add the content parsed from each entry file\n * to, so it can be cached. A file whose content comes from the cache isn’t added.\n * @returns {Promise<{ entries: Entry[], errors: Error[], assets: Asset[], configFiles:\n * BaseConfigListItem[] }>} Parsed entries, errors encountered while parsing them, assets and config\n * files.\n */\nexport const parseFiles = async ({\n  fileList: { entryFiles, assetFiles, configFiles },\n  fetchedFileMap,\n  changedPaths,\n  parsedFileMap,\n}) => {\n  const { entries, errors } = await parseEntryFiles({\n    entryFiles: entryFiles.map(\n      (fileInfo) => /** @type {BaseEntryListItem} */ (parseFileInfo({ fileInfo, fetchedFileMap })),\n    ),\n    changedPaths,\n    parsedFileMap,\n  });\n\n  const assets = assetFiles.map((fileInfo) =>\n    parseAssetFileInfo(\n      /** @type {BaseAssetListItem} */ (parseFileInfo({ fileInfo, fetchedFileMap })),\n    ),\n  );\n\n  const configFileItems = configFiles.map(\n    (fileInfo) => /** @type {BaseConfigListItem} */ (parseFileInfo({ fileInfo, fetchedFileMap })),\n  );\n\n  return { entries, errors, assets, configFiles: configFileItems };\n};\n","import { getPathInfo } from '@sveltia/utils/file';\n\n/**\n * @import { BaseFileListItemProps } from '$lib/types/private';\n */\n\n/**\n * Create a file list item for the given path, with the file name derived from it.\n * @param {string} path File path.\n * @param {Partial<Omit<BaseFileListItemProps, 'path' | 'name'>>} [props] Other properties, such as\n * the SHA, size and text. The SHA is an empty string and the size `0` unless given.\n * @returns {BaseFileListItemProps} File list item.\n */\nexport const toFileListItem = (path, { sha = '', size = 0, ...rest } = {}) => ({\n  path,\n  name: getPathInfo(path).basename,\n  sha,\n  size,\n  ...rest,\n});\n\n/**\n * Convert the entries of a Git tree to a file list, leaving out any entry that isn’t a file, like a\n * subtree or a submodule.\n * @param {{ type: string, path: string, sha: string, size?: number }[]} entries Tree entries.\n * @returns {BaseFileListItemProps[]} File list. The size is `0` if the API doesn’t tell.\n */\nexport const toFileListItems = (entries) =>\n  entries\n    .filter(({ type }) => type === 'blob')\n    .map(({ path, sha, size }) => toFileListItem(path, { sha, size }));\n","import { IndexedDB } from '@sveltia/utils/storage';\n\nimport { deferRejection } from '$lib/services/backends/git/shared/defer';\nimport { repositoryHead } from '$lib/services/backends/git/shared/head';\nimport { applyFileMetadata } from '$lib/services/backends/git/shared/parse-files';\nimport { toFileListItem } from '$lib/services/backends/git/shared/tree';\nimport { createFileList, describeFileList } from '$lib/services/backends/process';\nimport { cmsConfigVersion } from '$lib/services/config';\n\n/**\n * @import {\n * BaseFileList,\n * BaseFileListItem,\n * RepositoryContentsMap,\n * RepositoryInfo,\n * } from '$lib/types/private';\n * @import { DebugLogger } from '$lib/services/utils/logging';\n * @import {\n * FetchFileListFunction,\n * FetchFileMetadataFunction,\n * } from '$lib/services/backends/git/shared/fetch';\n * @import { ParsedFileMap } from '$lib/services/contents/file/process';\n */\n\n/**\n * Get the file list from the meta database or fetch it if not cached. The commit the list was\n * fetched at isn’t recorded here but with {@link saveFileListMeta}, once the file contents have\n * been cached: until then, the cache still holds the files of the previous commit, which the file\n * list would be restored from.\n * @param {object} args Arguments.\n * @param {[string, any][]} args.metaEntries Entries read from the meta database.\n * @param {string} args.lastCommitHash The latest commit hash.\n * @param {[string, any][]} args.cachedFileEntries Cached file entries.\n * @param {FetchFileListFunction} args.fetchFileList Function to fetch the repository’s complete\n * file list.\n * @param {DebugLogger} args.log Function to trace the loading in the console.\n * @returns {Promise<BaseFileList>} The file list.\n */\nexport const getFileList = async ({\n  metaEntries,\n  lastCommitHash,\n  cachedFileEntries,\n  fetchFileList,\n  log,\n}) => {\n  const lastConfigHash = cmsConfigVersion.current;\n\n  const {\n    last_config_hash: cachedConfigHash,\n    last_commit_hash: cachedCommitHash,\n    git_config_fetched: gitConfigFetched,\n  } = Object.fromEntries(metaEntries);\n\n  // We need to compare the CMS config hash to support cases where multiple CMS instances with\n  // different configurations are connected to the same repository, or where the config has been\n  // substantially updated. @see https://github.com/sveltia/sveltia-cms/issues/886\n  // Skip fetching the file list if the cached hash matches the latest. But don’t skip if the file\n  // cache is empty; something probably went wrong the last time the files were fetched.\n  if (\n    cachedConfigHash &&\n    cachedConfigHash === lastConfigHash &&\n    cachedCommitHash &&\n    cachedCommitHash === lastCommitHash &&\n    gitConfigFetched &&\n    cachedFileEntries.length\n  ) {\n    const fileList = createFileList(\n      cachedFileEntries.map(([path, data]) => toFileListItem(path, data)),\n    );\n\n    log(`Restored the file list from the cache: ${describeFileList(fileList)}`);\n\n    return fileList;\n  }\n\n  // Get a complete file list first, and filter what’s managed in CMS\n  const fileList = createFileList(await fetchFileList(lastCommitHash));\n\n  log(`Fetched the file list: ${describeFileList(fileList)}`);\n\n  return fileList;\n};\n\n/**\n * Record the commit and CMS configuration the file cache reflects, so that the next fetch for the\n * same ones can restore the file list from the cache. This is only done once the cache has been\n * updated with the files of that commit.\n * @param {object} args Arguments.\n * @param {IndexedDB} args.metaDB The meta database instance.\n * @param {string | undefined} args.lastConfigHash The CMS configuration hash the files were\n * fetched for.\n * @param {string} args.lastCommitHash The commit hash the files were fetched at.\n */\nexport const saveFileListMeta = async ({ metaDB, lastConfigHash, lastCommitHash }) => {\n  await metaDB.saveEntries(\n    Object.entries({\n      last_config_hash: lastConfigHash,\n      last_commit_hash: lastCommitHash,\n      git_config_fetched: true,\n    }),\n  );\n};\n\n/**\n * Move the head the site data reflects on to a commit that has left the configured root directory\n * as it was, so nothing has to be fetched. The file cache is moved on as well, so the next load\n * restores the file list from it rather than listing the directory again, but only if it’s still\n * recorded at the previous head: a cache update in flight records its own commit afterwards.\n * @param {RepositoryInfo} repository Repository info.\n * @param {string} from Head the site data reflects.\n * @param {string} to New head.\n */\nexport const advanceRepositoryHead = async ({ databaseName }, from, to) => {\n  repositoryHead.current = to;\n\n  try {\n    const metaDB = new IndexedDB(/** @type {string} */ (databaseName), 'meta');\n\n    if ((await metaDB.get('last_commit_hash')) === from) {\n      await metaDB.set('last_commit_hash', to);\n    }\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to update the file cache.', ex);\n  }\n};\n\n/**\n * Restore cached text and commit info to `allFiles` array.\n * @param {object} args Arguments.\n * @param {BaseFileListItem[]} args.allFiles The list of all files.\n * @param {RepositoryContentsMap} args.cachedFiles Cached files object.\n */\nexport const restoreCachedFileData = ({ allFiles, cachedFiles }) => {\n  allFiles.forEach(({ sha, path }, index) => {\n    if (cachedFiles[path]?.sha === sha) {\n      Object.assign(allFiles[index], cachedFiles[path]);\n    }\n  });\n};\n\n/**\n * Add the content parsed from the entry files to their file data, so it’s cached along with them\n * and the files don’t have to be parsed again on the next load. A fetched file is about to be\n * cached anyway; a cached one has to be cached again, as its content was parsed for another CMS\n * version or configuration, or not cached at all.\n * @param {object} args Arguments.\n * @param {ParsedFileMap} args.parsedFileMap Content parsed from the entry files.\n * @param {RepositoryContentsMap} args.fetchedFileMap Map of newly fetched file data, updated in\n * place.\n * @param {RepositoryContentsMap} args.cachedFiles Cached files object.\n * @returns {RepositoryContentsMap} Data of the cached files to cache again with their content.\n */\nexport const attachParsedContents = ({ parsedFileMap, fetchedFileMap, cachedFiles }) => {\n  /** @type {RepositoryContentsMap} */\n  const reparsedFileMap = {};\n\n  parsedFileMap.forEach((parsed, path) => {\n    if (fetchedFileMap[path]) {\n      fetchedFileMap[path].parsed = parsed;\n    } else if (cachedFiles[path]) {\n      reparsedFileMap[path] = { ...cachedFiles[path], parsed };\n    }\n  });\n\n  return reparsedFileMap;\n};\n\n/**\n * Update the file cache by saving new entries and deleting unused ones. Both are awaited, as the\n * cache is only recorded as reflecting the commit once it’s up to date: a file left in it would\n * come back with the file list restored from it.\n * @param {object} args Arguments.\n * @param {IndexedDB} args.cacheDB The cache database instance.\n * @param {BaseFileListItem[]} args.allFiles List of all files in the repository.\n * @param {RepositoryContentsMap} args.cachedFiles Cached files object.\n * @param {BaseFileListItem[]} args.fetchingFiles List of files being fetched.\n * @param {RepositoryContentsMap} args.fetchedFileMap Map of newly fetched file data.\n * @param {RepositoryContentsMap} [args.reparsedFileMap] Data of the cached files whose content has\n * been parsed again, from {@link attachParsedContents}.\n */\nexport const updateCache = async ({\n  cacheDB,\n  allFiles,\n  cachedFiles,\n  fetchingFiles,\n  fetchedFileMap,\n  reparsedFileMap = {},\n}) => {\n  const usedPaths = new Set(allFiles.map(({ path }) => path));\n  const unusedPaths = Object.keys(cachedFiles).filter((path) => !usedPaths.has(path));\n\n  const savedEntries = [\n    ...(fetchingFiles.length ? Object.entries(fetchedFileMap) : []),\n    ...Object.entries(reparsedFileMap),\n  ];\n\n  await Promise.all([\n    // Save new entry caches\n    savedEntries.length ? cacheDB.saveEntries(savedEntries) : undefined,\n    // Delete old entry caches\n    unusedPaths.length ? cacheDB.deleteEntries(unusedPaths) : undefined,\n  ]);\n};\n\n/**\n * Start reading the meta and file cache databases. The cache is optional, so if IndexedDB is\n * unavailable or broken, e.g. Chrome failing to open its backing store, the failure is only logged\n * and the files are fetched as if the cache were empty.\n * @param {object} args Arguments.\n * @param {IndexedDB} args.metaDB The meta database instance.\n * @param {IndexedDB} args.cacheDB The cache database instance.\n * @returns {Promise<{ metaEntries: [string, any][], cachedFileEntries: [string, any][] }>} Entries\n * read from the databases.\n */\nexport const readDatabaseEntries = ({ metaDB, cacheDB }) =>\n  // The two stores are opened one after the other: both live in the same database, and on a\n  // brand-new one two instances opening it at the same time race to create their stores, which\n  // leaves one of them with a connection missing its store\n  deferRejection(\n    (async () => {\n      try {\n        const cachedFileEntries = await cacheDB.entries();\n        const metaEntries = await metaDB.entries();\n\n        return { metaEntries, cachedFileEntries };\n      } catch (/** @type {any} */ ex) {\n        // eslint-disable-next-line no-console\n        console.error('Failed to read the file cache.', ex);\n\n        return { metaEntries: [], cachedFileEntries: [] };\n      }\n    })(),\n  );\n\n/**\n * Cache the fetched files, completing them with their commit metadata first if it’s fetched in a\n * separate pass.\n * @param {object} args Arguments.\n * @param {IndexedDB} args.cacheDB The cache database instance.\n * @param {BaseFileListItem[]} args.allFiles List of all files in the repository.\n * @param {RepositoryContentsMap} args.cachedFiles Cached files object.\n * @param {BaseFileListItem[]} args.fetchingFiles List of files being fetched.\n * @param {RepositoryContentsMap} args.fetchedFileMap Map of newly fetched file data.\n * @param {RepositoryContentsMap} [args.reparsedFileMap] Data of the cached files whose content has\n * been parsed again, from {@link attachParsedContents}.\n * @param {FetchFileMetadataFunction} [args.fetchFileMetadata] Function to fetch the commit metadata\n * of entry/asset files separately.\n * @param {DebugLogger} args.log Function to trace the loading in the console.\n */\nexport const completeMetadata = async ({\n  cacheDB,\n  allFiles,\n  cachedFiles,\n  fetchingFiles,\n  fetchedFileMap,\n  reparsedFileMap,\n  fetchFileMetadata,\n  log,\n}) => {\n  const cacheArgs = {\n    cacheDB,\n    allFiles,\n    cachedFiles,\n    fetchingFiles,\n    fetchedFileMap,\n    reparsedFileMap,\n  };\n\n  // Whether the cache written below is complete, or missing the metadata of the fetched files\n  let metadataFetched = true;\n\n  if (fetchFileMetadata && fetchingFiles.length) {\n    // Cache the text right away, so that a reload before the slower metadata pass has finished\n    // only costs that pass next time, not the contents again. A failure here doesn’t stop the\n    // metadata from being filled in; the cache is written again below, which reports it\n    try {\n      await updateCache(cacheArgs);\n      log(`Cached the contents of ${fetchingFiles.length} files`);\n    } catch (/** @type {any} */ ex) {\n      // eslint-disable-next-line no-console\n      console.error('Failed to cache the contents.', ex);\n    }\n\n    try {\n      applyFileMetadata({\n        fetchedFileMap,\n        metadataMap: await fetchFileMetadata(fetchingFiles),\n      });\n      log(`Fetched the commit metadata of ${fetchingFiles.length} files`);\n    } catch (/** @type {any} */ ex) {\n      // The contents are already usable without it, and the metadata is fetched again next time\n      // eslint-disable-next-line no-console\n      console.error('Failed to fetch the commit metadata.', ex);\n      metadataFetched = false;\n    }\n  }\n\n  // Cached with the metadata, which is what marks a file as fetched\n  await updateCache(cacheArgs);\n\n  log(\n    metadataFetched\n      ? `Cached ${fetchingFiles.length} files with their metadata`\n      : `Cached ${fetchingFiles.length} files without their metadata; they are fetched again ` +\n          'next time',\n  );\n};\n\n/**\n * Update the file cache, then record the commit it reflects. If the cache can’t be updated, the\n * commit isn’t recorded, so the next fetch gets the file list again instead of restoring it from a\n * cache that may still hold files of an earlier commit, such as ones deleted since. The site data\n * is already usable without the cache, so the failure is only logged.\n * @param {object} args Arguments.\n * @param {IndexedDB} args.metaDB The meta database instance.\n * @param {string | undefined} args.lastConfigHash The CMS configuration hash the files were\n * fetched for.\n * @param {string} args.lastCommitHash The commit hash the files were fetched at.\n * @param {Promise<void>} args.cacheUpdate Update of the file cache in progress.\n */\nexport const cacheFiles = async ({ metaDB, lastConfigHash, lastCommitHash, cacheUpdate }) => {\n  try {\n    await cacheUpdate;\n    // Only now that the cache holds the files of this commit can the file list be restored from it\n    await saveFileListMeta({ metaDB, lastConfigHash, lastCommitHash });\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to update the file cache.', ex);\n  }\n};\n","import { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport {\n  fromRepoPath,\n  getRootDir,\n  isInRootDir,\n  toRepoChanges,\n  toRepoPath,\n} from '$lib/services/backends/root-dir';\n\n/**\n * @import {\n * BackendService,\n * BaseFileListItem,\n * CommitResults,\n * RepositoryContentsMap,\n * RepositoryInfo,\n * WorkflowBackendService,\n * WorkflowPullRequest,\n * } from '$lib/types/private';\n * @import {\n * FetchFileContentsFunction,\n * FetchFileListFunction,\n * FetchFileMetadataFunction,\n * } from '$lib/services/backends/git/shared/fetch';\n */\n\n/**\n * Wrap a function so it’s replaced with another while a root directory is configured. Without one,\n * the original is called as is, so nothing changes for a site that doesn’t use the option.\n * @template {(...args: any[]) => any} T\n * @param {T} original Original function.\n * @param {(rootDir: string, ...args: Parameters<T>) => ReturnType<T>} scoped Function to call\n * instead, with the root directory as the first argument.\n * @returns {T} Wrapped function.\n */\nconst whenScoped = (original, scoped) =>\n  /** @type {T} */ (\n    /**\n     * Call the replacement while a root directory is configured, or the original otherwise.\n     * @param {Parameters<T>} args Arguments.\n     * @returns {ReturnType<T>} Result.\n     */\n    (...args) => {\n      const rootDir = getRootDir();\n\n      return rootDir ? scoped(rootDir, ...args) : original(...args);\n    }\n  );\n\n/**\n * Re-key a map keyed with file paths.\n * @template T\n * @param {Record<string, T>} map Map.\n * @param {(path: string) => string} convert Function to convert a path.\n * @returns {Record<string, T>} New map.\n */\nconst convertKeys = (map, convert) =>\n  Object.fromEntries(Object.entries(map).map(([path, value]) => [convert(path), value]));\n\n/**\n * Convert the path of a file a pull request changes, along with the path it had before, if any.\n * @template {{ path: string, previousPath?: string }} T\n * @param {T} file File.\n * @param {(path: string) => string} convert Function to convert a path.\n * @returns {T} New file.\n */\nconst convertFile = (file, convert) => ({\n  ...file,\n  path: convert(file.path),\n  ...(file.previousPath !== undefined && { previousPath: convert(file.previousPath) }),\n});\n\n/**\n * Convert the paths of the files a pull request changes.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {(path: string) => string} convert Function to convert a path.\n * @returns {WorkflowPullRequest} New pull request.\n */\nconst convertPullRequest = (pullRequest, convert) => ({\n  ...pullRequest,\n  files: pullRequest.files.map((file) => convertFile(file, convert)),\n});\n\n/**\n * Convert the paths of the committed files to paths relative to the root directory.\n * @param {CommitResults} commit Commit results.\n * @param {string} rootDir Root directory.\n * @returns {CommitResults} New commit results.\n */\nconst scopeCommit = (commit, rootDir) => ({\n  ...commit,\n  files: convertKeys(commit.files, (path) => fromRepoPath(path, rootDir)),\n});\n\n/**\n * Wrap the file fetching functions of a Git backend so the file list only holds the files in the\n * configured root directory, with paths relative to it, while the backend is still given paths\n * relative to the repository root.\n * @param {object} args Arguments.\n * @param {RepositoryInfo} args.repository Repository info.\n * @param {FetchFileListFunction} args.fetchFileList Function to fetch the file list.\n * @param {FetchFileContentsFunction} args.fetchFileContents Function to fetch the contents.\n * @param {FetchFileMetadataFunction} [args.fetchFileMetadata] Function to fetch the metadata.\n * @returns {{\n * fetchFileList: FetchFileListFunction,\n * fetchFileContents: FetchFileContentsFunction,\n * fetchFileMetadata?: FetchFileMetadataFunction,\n * }} Wrapped functions.\n * @throws {Error} When the file list has no file in the root directory, which then doesn’t exist.\n */\nexport const scopeFileFetchers = ({\n  repository,\n  fetchFileList,\n  fetchFileContents,\n  fetchFileMetadata,\n}) => {\n  /**\n   * Give the backend the files with paths relative to the repository root.\n   * @param {BaseFileListItem[]} files Files.\n   * @param {string} rootDir Root directory.\n   * @returns {BaseFileListItem[]} New file list.\n   */\n  const toRepoFiles = (files, rootDir) =>\n    files.map((file) => ({ ...file, path: toRepoPath(file.path, rootDir) }));\n\n  return {\n    fetchFileList: whenScoped(fetchFileList, async (rootDir, lastHash) => {\n      const files = (await fetchFileList(lastHash)).flatMap((file) => {\n        const path = fromRepoPath(file.path, rootDir);\n\n        return isInRootDir(path) ? [{ ...file, path }] : [];\n      });\n\n      // Git has no empty directories, so a root directory without a file doesn’t exist, most likely\n      // because of a typo. Showing an empty CMS would leave the user wondering where their content\n      // has gone\n      if (!files.length) {\n        throw createLocalizedError('Failed to list the files.', 'root_dir_not_found', {\n          repo: `${repository.owner}/${repository.repo}`,\n          dir: rootDir,\n        });\n      }\n\n      return files;\n    }),\n    fetchFileContents: whenScoped(\n      fetchFileContents,\n      async (rootDir, files, lastHash) =>\n        /** @type {RepositoryContentsMap} */ (\n          convertKeys(await fetchFileContents(toRepoFiles(files, rootDir), lastHash), (path) =>\n            fromRepoPath(path, rootDir),\n          )\n        ),\n    ),\n    fetchFileMetadata:\n      fetchFileMetadata &&\n      whenScoped(fetchFileMetadata, async (rootDir, files) =>\n        convertKeys(await fetchFileMetadata(toRepoFiles(files, rootDir)), (path) =>\n          fromRepoPath(path, rootDir),\n        ),\n      ),\n  };\n};\n\n/**\n * Wrap the Editorial Workflow implementation of a Git backend, so the paths of the files a pull\n * request changes are relative to the configured root directory.\n * @param {WorkflowBackendService} workflow Workflow implementation.\n * @returns {WorkflowBackendService} Wrapped implementation.\n */\nconst scopeWorkflow = (workflow) => {\n  /**\n   * Convert a pull request coming from the CMS.\n   * @param {WorkflowPullRequest} pullRequest Pull request.\n   * @param {string} rootDir Root directory.\n   * @returns {WorkflowPullRequest} Pull request with paths relative to the repository root.\n   */\n  const toRepo = (pullRequest, rootDir) =>\n    convertPullRequest(pullRequest, (path) => toRepoPath(path, rootDir));\n\n  /**\n   * Convert a pull request coming from the backend.\n   * @param {WorkflowPullRequest} pullRequest Pull request.\n   * @param {string} rootDir Root directory.\n   * @returns {WorkflowPullRequest} Pull request with paths relative to the root directory.\n   */\n  const fromRepo = (pullRequest, rootDir) =>\n    convertPullRequest(pullRequest, (path) => fromRepoPath(path, rootDir));\n\n  return {\n    ...workflow,\n    fetchPullRequests: whenScoped(workflow.fetchPullRequests, async (rootDir) =>\n      (await workflow.fetchPullRequests()).map((pullRequest) => fromRepo(pullRequest, rootDir)),\n    ),\n    savePullRequest: whenScoped(workflow.savePullRequest, async (rootDir, args) => {\n      const { commit, pullRequest } = await workflow.savePullRequest({\n        ...args,\n        changes: toRepoChanges(args.changes),\n        pullRequest: args.pullRequest && toRepo(args.pullRequest, rootDir),\n      });\n\n      return { commit: scopeCommit(commit, rootDir), pullRequest: fromRepo(pullRequest, rootDir) };\n    }),\n    updateStatus: whenScoped(workflow.updateStatus, async (rootDir, pullRequest, status) =>\n      fromRepo(await workflow.updateStatus(toRepo(pullRequest, rootDir), status), rootDir),\n    ),\n    // A file outside the root directory keeps a path starting with `../`, which matches nothing the\n    // CMS has shown, so a pull request touching one isn’t merged\n    fetchMergeState: whenScoped(workflow.fetchMergeState, async (rootDir, pullRequest) => {\n      const state = await workflow.fetchMergeState(toRepo(pullRequest, rootDir));\n\n      // A path with a `.` or `..` segment, which Git doesn’t allow anyway, wouldn’t convert back to\n      // the same file when its changes are checked, so the pull request isn’t vouched for\n      const unsafe = state.files.some(({ path, previousPath }) =>\n        [path, previousPath].some(\n          (_path) => _path !== undefined && _path.split('/').some((s) => s === '.' || s === '..'),\n        ),\n      );\n\n      return {\n        ...state,\n        files: state.files.map((file) => convertFile(file, (path) => fromRepoPath(path, rootDir))),\n        ...(unsafe && { complete: false }),\n      };\n    }),\n    fetchUnchangedPaths: whenScoped(\n      workflow.fetchUnchangedPaths,\n      async (rootDir, { headSHA, paths }) =>\n        (\n          await workflow.fetchUnchangedPaths({\n            headSHA,\n            paths: paths.map((path) => toRepoPath(path, rootDir)),\n          })\n        ).map((path) => fromRepoPath(path, rootDir)),\n    ),\n    publish: whenScoped(workflow.publish, (rootDir, pullRequest) =>\n      workflow.publish(toRepo(pullRequest, rootDir)),\n    ),\n    discard: whenScoped(workflow.discard, (rootDir, pullRequest) =>\n      workflow.discard(toRepo(pullRequest, rootDir)),\n    ),\n  };\n};\n\n/**\n * Wrap a Git backend service, so the paths the CMS gives and gets are relative to the configured\n * root directory, while the backend keeps dealing with paths relative to the repository root. The\n * file list is scoped separately, by {@link scopeFileFetchers}, as it’s fetched within the\n * backend’s own `fetchFiles`.\n * @param {BackendService} service Backend service.\n * @returns {BackendService} Wrapped service.\n */\nexport const scopeBackendService = (service) => {\n  const { fetchBlob, commitChanges, fetchFileCommits, workflow } = service;\n\n  return {\n    ...service,\n    // GitLab and Gitea/Forgejo read an asset file by its path rather than its blob SHA\n    fetchBlob:\n      fetchBlob &&\n      whenScoped(fetchBlob, (rootDir, asset) =>\n        fetchBlob({ ...asset, path: toRepoPath(asset.path, rootDir) }),\n      ),\n    commitChanges: whenScoped(commitChanges, async (rootDir, changes, options) =>\n      scopeCommit(await commitChanges(toRepoChanges(changes), options), rootDir),\n    ),\n    fetchFileCommits:\n      fetchFileCommits &&\n      whenScoped(fetchFileCommits, (rootDir, paths) =>\n        fetchFileCommits(paths.map((path) => toRepoPath(path, rootDir))),\n      ),\n    workflow: workflow && scopeWorkflow(workflow),\n  };\n};\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { DeployStatus, PublishHint } from '$lib/types/private';\n */\n\n/**\n * Deployments reported by the CI/CD provider connected to the Git backend, keyed by commit SHA.\n * They’re kept here rather than on the pull request objects, because a pull request is rebuilt on\n * every status change while a deployment is refreshed on its own schedule.\n * @type {{ current: Record<string, DeployStatus> }}\n */\nexport const deployments = createRawState({});\n\n/**\n * Head commit of the configured branch, which is what the production site is built from. It’s\n * refreshed after every commit, so the UI can tell whether the user’s own change is live yet.\n */\nexport const productionSHA = createRawState('');\n\n/**\n * What the last commit is expected to have done, worked out without asking the CI/CD provider. See\n * {@link setLastCommitPublishHint}.\n * @type {{ current: PublishHint }}\n */\nexport const lastCommitPublishHint = createRawState({ published: true, time: 0 });\n\n/**\n * Whether the automatic re-checks gave up on a pending build, in which case the UI offers a manual\n * re-check instead.\n */\nexport const deployPollTimedOut = createRawState(false);\n\n/**\n * Drop the deployments recorded for the given commits. Called when a pull request is closed, so the\n * state doesn’t grow for the lifetime of the session.\n * @param {(string | undefined)[]} shas Commit SHAs to forget. A pull request opened in an older\n * session may have no head commit recorded, so a missing one is simply ignored.\n */\nexport const forgetDeployments = (shas) => {\n  const targets = shas.filter((sha) => !!sha);\n\n  if (!targets.length) {\n    return;\n  }\n\n  deployments.current = Object.fromEntries(\n    Object.entries(deployments.current).filter(([sha]) => !targets.includes(sha)),\n  );\n};\n\n/**\n * Reset every deployment state. Called when the user signs out.\n */\nexport const resetDeployments = () => {\n  deployments.current = {};\n  productionSHA.current = '';\n  deployPollTimedOut.current = false;\n  lastCommitPublishHint.current = { published: true, time: 0 };\n};\n\n/**\n * Record what the last commit is expected to have done, worked out without asking the CI/CD\n * provider: `true` when it should have started a deployment, `false` when it shouldn’t have. It’s\n * called when the commit message carries a skip-CI marker, when a commit is made with a known\n * skip-CI option, and when the user triggers a deployment by hand.\n *\n * The time is recorded along with it so that {@link isLastCommitPublished} can tell a deployment\n * read before this point from one read after: the failed build the user has just asked to retry\n * describes an earlier state of the commit, and mustn’t go on saying the site is out of date.\n * @param {boolean} published Whether the last commit is expected to have started a deployment.\n */\nexport const setLastCommitPublishHint = (published) => {\n  lastCommitPublishHint.current = { published, time: Date.now() };\n};\n","import { IndexedDB } from '@sveltia/utils/storage';\n\nimport { hasSkipCIMarker } from '$lib/services/backends/git/shared/commits';\nimport { deferRejection } from '$lib/services/backends/git/shared/defer';\nimport {\n  attachParsedContents,\n  cacheFiles,\n  completeMetadata,\n  getFileList,\n  readDatabaseEntries,\n  restoreCachedFileData,\n  updateCache,\n} from '$lib/services/backends/git/shared/file-cache';\nimport { createStaleCheck, repositoryHead } from '$lib/services/backends/git/shared/head';\nimport { parseFiles, updateStores } from '$lib/services/backends/git/shared/parse-files';\nimport { scopeFileFetchers } from '$lib/services/backends/git/shared/scope';\nimport { cmsConfigVersion } from '$lib/services/config';\nimport { setLastCommitPublishHint } from '$lib/services/deployments';\nimport { createDebugLogger } from '$lib/services/utils/logging';\n\n/**\n * @import {\n * BaseFileList,\n * BaseFileListItem,\n * BaseFileListItemProps,\n * RepositoryContentsMap,\n * RepositoryFileMetadata,\n * RepositoryInfo,\n * } from '$lib/types/private';\n * @import { DebugLogger } from '$lib/services/utils/logging';\n * @import { ParsedFileMap } from '$lib/services/contents/file/process';\n */\n\n/**\n * @typedef {Record<string, RepositoryFileMetadata>} RepositoryMetadataMap Commit metadata of\n * entry/asset files, keyed with a file path.\n */\n\n/**\n * @typedef {(lastHash: string) => Promise<BaseFileListItemProps[]>} FetchFileListFunction\n */\n\n/**\n * A function to fetch the contents of the given files. It’s given the hash of the commit the file\n * list comes from, so a backend that reads a file by path rather than by blob SHA can read it at\n * that commit; reading it at the tip of the branch, which may have moved on since, could cache a\n * text under the blob SHA of another version of the file.\n * @typedef {(fetchingFiles: BaseFileListItem[], lastHash: string) => Promise<RepositoryContentsMap>\n * } FetchFileContentsFunction\n */\n\n/**\n * @typedef {(fetchingFiles: BaseFileListItem[]) => Promise<RepositoryMetadataMap>\n * } FetchFileMetadataFunction\n */\n\n/**\n * What the entries in the store were last parsed for: the repository database name and the CMS\n * configuration hash. A fetch made for the same ones can keep the entries whose files haven’t\n * changed instead of parsing everything again; anything else, such as a configuration change, which\n * can change how every file is parsed, calls for a full parse.\n * @type {string | undefined}\n */\nlet lastParseKey;\n/**\n * Get the key identifying what the entries are parsed for.\n * @param {string | undefined} databaseName Repository database name.\n * @returns {string} Key.\n */\nconst getParseKey = (databaseName) => `${databaseName}\\n${cmsConfigVersion.current}`;\n\n/**\n * Determine the branch if not configured, and fetch its last commit.\n * @param {object} args Arguments.\n * @param {RepositoryInfo} args.repository Repository info. Its `branch` is set to the default\n * branch if not configured.\n * @param {Promise<void> | undefined} args.accessPromise Access check in progress, if any.\n * @param {() => Promise<string>} args.fetchDefaultBranchName Function to fetch the repository’s\n * default branch name.\n * @param {() => Promise<{ hash: string, message: string }>} args.fetchLastCommit Function to fetch\n * the last commit’s SHA-1 hash and message.\n * @param {{ hash: string, message: string }} [args.lastCommit] Last commit, if the caller has\n * just fetched it. It’s only used once the branch is known.\n * @param {DebugLogger} args.log Function to trace the loading in the console.\n * @returns {Promise<{ hash: string, message: string }>} Last commit’s SHA-1 hash and message.\n */\nconst resolveHead = async ({\n  repository,\n  accessPromise,\n  fetchDefaultBranchName,\n  fetchLastCommit,\n  lastCommit,\n  log,\n}) => {\n  let { branch } = repository;\n\n  // A check for remote changes has just fetched the head to compare it, so it isn’t fetched again\n  if (branch && lastCommit) {\n    await accessPromise;\n\n    return lastCommit;\n  }\n\n  if (!branch) {\n    // Only the request is started here; the access check is settled first, so that its error is\n    // the one reported if both fail, as a repository that can’t be read has no branches to list\n    const branchPromise = deferRejection(fetchDefaultBranchName());\n\n    await accessPromise;\n\n    branch = await branchPromise;\n    repository.branch = branch;\n\n    log(`Fetched the default branch name: ${branch}`);\n  }\n\n  // This has to be done after the branch is determined. Again, only the request is started here,\n  // and the access check is settled first\n  const lastCommitPromise = deferRejection(fetchLastCommit());\n\n  await accessPromise;\n\n  const fetchedCommit = await lastCommitPromise;\n\n  log(`Fetched the last commit on ${branch}: ${fetchedCommit.hash}`);\n\n  return fetchedCommit;\n};\n\n/**\n * Restore the cached files, and fetch the contents of the rest.\n * @param {object} args Arguments.\n * @param {BaseFileList} args.fileList Repository’s file list.\n * @param {string} args.lastCommitHash The commit hash the file list comes from, which the\n * contents are read at.\n * @param {[string, any][]} args.cachedFileEntries Cached file entries.\n * @param {FetchFileContentsFunction} args.fetchFileContents Function to fetch the metadata of\n * entry/asset files as well as text file contents.\n * @param {FetchFileMetadataFunction} [args.fetchFileMetadata] Function to fetch the commit metadata\n * of entry/asset files separately.\n * @param {DebugLogger} args.log Function to trace the loading in the console.\n * @returns {Promise<{ cachedFiles: RepositoryContentsMap, changedPaths: Set<string>, fetchingFiles:\n * BaseFileListItem[], fetchedFileMap: RepositoryContentsMap }>} Cached files, paths of the files\n * changed since the last fetch, files being fetched, and what’s known about them.\n */\nconst loadContents = async ({\n  fileList: { allFiles },\n  lastCommitHash,\n  cachedFileEntries,\n  fetchFileContents,\n  fetchFileMetadata,\n  log,\n}) => {\n  /** @type {RepositoryContentsMap} */\n  const cachedFiles = Object.fromEntries(cachedFileEntries);\n\n  restoreCachedFileData({ allFiles, cachedFiles });\n\n  // What differs from the last fetch, which the cache stands for; the user’s own commits keep it up\n  // to date, so their files don’t count. Everything is new on a first load into an empty cache\n  const changedPaths = new Set(\n    allFiles.filter(({ path, sha }) => cachedFiles[path]?.sha !== sha).map(({ path }) => path),\n  );\n\n  // A file is fetched again until its metadata is cached along with its text\n  const fetchingFiles = allFiles.filter(({ meta }) => !meta);\n\n  // With a separate metadata pass, the text may already be in the cache from a run that was\n  // interrupted before its metadata pass finished, in which case only the metadata is missing. An\n  // asset never has any text to read\n  const contentFiles = fetchFileMetadata\n    ? fetchingFiles.filter(({ type, text }) => type !== 'asset' && text === undefined)\n    : fetchingFiles;\n\n  // What’s known about each file being fetched, to be completed below and then cached\n  /** @type {RepositoryContentsMap} */\n  const fetchedFileMap = Object.fromEntries(\n    fetchingFiles.map(({ path, sha, size, text }) => [path, { sha, size, text, meta: undefined }]),\n  );\n\n  log(\n    `Restored ${allFiles.length - fetchingFiles.length} files from the cache; ` +\n      `fetching ${fetchingFiles.length} files`,\n  );\n\n  if (contentFiles.length) {\n    Object.assign(fetchedFileMap, await fetchFileContents(contentFiles, lastCommitHash));\n\n    // Only the text files are downloaded; an asset in the list is just there for its metadata\n    log(\n      `Fetched the contents of ${contentFiles.filter(({ type }) => type !== 'asset').length} files`,\n    );\n  }\n\n  return { cachedFiles, changedPaths, fetchingFiles, fetchedFileMap };\n};\n\n/**\n * Finish loading the site data: update the stores with the parsed files, record the commit they\n * reflect, then update the file cache and record the commit it reflects too.\n * @param {object} args Arguments.\n * @param {Parameters<typeof updateStores>[0]} args.data Parsed entries, assets, config files and\n * errors to update the stores with.\n * @param {string} args.parseKey Key identifying what the entries were parsed for.\n * @param {IndexedDB} args.metaDB The meta database instance.\n * @param {string | undefined} args.lastConfigHash The CMS configuration hash the files were\n * fetched for.\n * @param {string} args.lastCommitHash The commit hash the files were fetched at.\n * @param {() => Promise<void>} args.startCacheUpdate Function to update the file cache, called once\n * the stores have been updated.\n * @param {DebugLogger} args.log Function to trace the loading in the console.\n * @param {string} args.readyMessage Message to log once the site data is ready.\n * @param {() => boolean} args.isStale Function telling whether the site data the files were\n * fetched for has been discarded since, e.g. the user has signed out, in which case nothing is\n * written.\n */\nconst finishLoad = async ({\n  data,\n  isStale,\n  parseKey,\n  metaDB,\n  lastConfigHash,\n  lastCommitHash,\n  startCacheUpdate,\n  log,\n  readyMessage,\n}) => {\n  if (isStale()) {\n    log('Discarded: the site data was reset while loading');\n\n    return;\n  }\n\n  updateStores(data);\n  lastParseKey = parseKey;\n  // Recorded once the stores reflect the commit, so a check made in the meantime still sees the\n  // previous head and knows the data isn’t there yet\n  repositoryHead.current = lastCommitHash;\n  log(readyMessage);\n\n  await cacheFiles({ metaDB, lastConfigHash, lastCommitHash, cacheUpdate: startCacheUpdate() });\n};\n\n/**\n * Fetch file list from a backend service, download/parse all the entry files, then cache them in\n * the `allEntries` and `allAssets` stores.\n * @param {object} args Arguments.\n * @param {RepositoryInfo} args.repository Repository info.\n * @param {() => Promise<void>} [args.checkAccess] Function to check that the user can read the\n * repository, throwing if not. It only needs the signed-in user, so it runs at the same time as the\n * branch and commit requests below rather than before them, saving a round trip on every start.\n * Its error takes precedence over theirs, as a missing branch is usually a symptom of no access.\n * @param {() => Promise<void>} [args.checkBranchAccess] Function to check whether the user can\n * push to the branch, which is known once the head is resolved. It runs alongside the file list\n * request, and the data is only shown once it’s done, so nothing appears editable that isn’t. It\n * isn’t expected to throw.\n * @param {() => Promise<string>} args.fetchDefaultBranchName Function to fetch the repository’s\n * default branch name.\n * @param {() => Promise<{ hash: string, message: string }>} args.fetchLastCommit Function to fetch\n * the last commit’s SHA-1 hash and message.\n * @param {{ hash: string, message: string }} [args.lastCommit] Last commit, if the caller has\n * just fetched it, so it isn’t fetched again.\n * @param {FetchFileListFunction} args.fetchFileList Function to fetch the repository’s complete\n * file list.\n * @param {FetchFileContentsFunction} args.fetchFileContents Function to fetch the metadata of\n * entry/asset files as well as text file contents. If {@link fetchFileMetadata} is given, this is\n * expected to leave the metadata out.\n * @param {FetchFileMetadataFunction} [args.fetchFileMetadata] Function to fetch the commit metadata\n * of entry/asset files separately. Looking up the last commit of every file is by far the slowest\n * part of a cold start on some services, and nothing in the UI needs it right away, so with this\n * the contents are shown as soon as they arrive and the metadata is filled in afterwards.\n */\nexport const fetchAndParseFiles = async ({\n  repository,\n  checkAccess,\n  checkBranchAccess,\n  fetchDefaultBranchName,\n  fetchLastCommit,\n  lastCommit,\n  ...fetchers\n}) => {\n  const { service, owner, repo, databaseName } = repository;\n\n  // Only the files in the configured root directory are listed, with paths relative to it\n  const { fetchFileList, fetchFileContents, fetchFileMetadata } = scopeFileFetchers({\n    repository,\n    ...fetchers,\n  });\n\n  const log = createDebugLogger('Loading site data');\n\n  log(`Started: ${service} ${owner}/${repo}`);\n\n  // A fetch made after the initial load, for the same repository and configuration, only parses the\n  // entry files that have changed. The key is taken now, as the configuration could change while\n  // the files are on their way\n  const parseKey = getParseKey(databaseName);\n  const isStale = createStaleCheck();\n  const incremental = !!repositoryHead.current && lastParseKey === parseKey;\n  const metaDB = new IndexedDB(/** @type {string} */ (databaseName), 'meta');\n  const cacheDB = new IndexedDB(/** @type {string} */ (databaseName), 'file-cache');\n  // The access was verified when the data was first loaded; a later call only brings it up to date\n  const initialLoad = !repositoryHead.current;\n  const accessPromise = checkAccess && initialLoad ? deferRejection(checkAccess()) : undefined;\n  // Start reading the databases right away, but only wait for them once the last commit is known,\n  // so the reads — the file cache holds the text of every entry — overlap the network round trips\n  // below instead of delaying them\n  const databaseEntriesPromise = readDatabaseEntries({ metaDB, cacheDB });\n\n  const { hash: lastCommitHash, message } = await resolveHead({\n    repository,\n    accessPromise,\n    fetchDefaultBranchName,\n    fetchLastCommit,\n    lastCommit,\n    log,\n  });\n\n  const branchAccessPromise = checkBranchAccess && initialLoad ? checkBranchAccess() : undefined;\n  const { metaEntries, cachedFileEntries } = await databaseEntriesPromise;\n\n  log(`Read the file cache: ${cachedFileEntries.length} files`);\n\n  const lastConfigHash = cmsConfigVersion.current;\n\n  const fileList = await getFileList({\n    metaEntries,\n    lastCommitHash,\n    cachedFileEntries,\n    fetchFileList,\n    log,\n  });\n\n  // What the message says is only what the author asked for. It’s the answer until the CI/CD\n  // provider is asked about the commit, which `isLastCommitPublished` prefers once it has one\n  setLastCommitPublishHint(!hasSkipCIMarker(message));\n  await branchAccessPromise;\n\n  const finishArgs = { isStale, parseKey, metaDB, lastConfigHash, lastCommitHash, log };\n\n  // Skip fetching files if no files found\n  if (!fileList.count) {\n    await finishLoad({\n      ...finishArgs,\n      data: { entries: [], assets: [], configFiles: [] },\n      readyMessage: 'The site data is ready: no files to load',\n      /**\n       * Delete what’s left in the cache from the previous commit.\n       * @returns {Promise<void>} Cache update.\n       */\n      startCacheUpdate: () =>\n        updateCache({\n          cacheDB,\n          allFiles: [],\n          cachedFiles: Object.fromEntries(cachedFileEntries),\n          fetchingFiles: [],\n          fetchedFileMap: {},\n        }),\n    });\n\n    return;\n  }\n\n  const { cachedFiles, changedPaths, fetchingFiles, fetchedFileMap } = await loadContents({\n    fileList,\n    lastCommitHash,\n    cachedFileEntries,\n    fetchFileContents,\n    fetchFileMetadata,\n    log,\n  });\n\n  /** @type {ParsedFileMap} */\n  const parsedFileMap = new Map();\n\n  const { entries, errors, assets, configFiles } = await parseFiles({\n    fileList,\n    fetchedFileMap,\n    changedPaths: incremental ? changedPaths : undefined,\n    parsedFileMap,\n  });\n\n  // Cached along with the files, so the next load can skip parsing them\n  const reparsedFileMap = attachParsedContents({ parsedFileMap, fetchedFileMap, cachedFiles });\n\n  log(`Parsed ${entries.length} entries (${errors.length} errors)`);\n\n  await finishLoad({\n    ...finishArgs,\n    data: { entries, assets, configFiles, errors, changedPaths },\n    readyMessage: 'The site data is ready',\n    /**\n     * Cache the fetched files, along with their commit metadata.\n     * @returns {Promise<void>} Cache update.\n     */\n    startCacheUpdate: () =>\n      completeMetadata({\n        cacheDB,\n        allFiles: fileList.allFiles,\n        cachedFiles,\n        fetchingFiles,\n        fetchedFileMap,\n        reparsedFileMap,\n        fetchFileMetadata,\n        log,\n      }),\n  });\n};\n","import { fetchAndParseFiles } from '$lib/services/backends/git/shared/fetch';\nimport { forkedRepository, openAuthoringInitialized } from '$lib/services/workflow/open-authoring';\n\n/**\n * Arguments for {@link fetchRepositoryFiles}.\n * @typedef {Parameters<typeof fetchAndParseFiles>[0] & {\n * isOpenAuthoringConfigured: () => boolean,\n * initOpenAuthoring: () => Promise<void>,\n * }} FetchRepositoryFilesArgs\n */\n\n/**\n * Fetch file list from a backend service, download/parse all the entry files, then cache them in\n * the {@link allEntries} and {@link allAssets} stores, setting the contributor’s fork up first with\n * Open Authoring. A user without write access is then a contributor rather than a stranger, so\n * they’re given a fork to work in instead of being turned away. Setting the fork up may involve the\n * user, so it has to finish before the data is fetched, unlike a plain access check.\n * @param {FetchRepositoryFilesArgs} args Arguments for {@link fetchAndParseFiles}, along with the\n * service’s functions to tell whether Open Authoring is turned on and to set it up. The access\n * checks are only run when they apply.\n */\nexport const fetchRepositoryFiles = async ({\n  isOpenAuthoringConfigured,\n  initOpenAuthoring,\n  checkAccess,\n  checkBranchAccess,\n  ...args\n}) => {\n  const openAuthoring = isOpenAuthoringConfigured();\n\n  // Once only: a later call brings the stores up to date with the repository, and setting the fork\n  // up again would reset the fork state while a workflow commit may be relying on it\n  if (openAuthoring && !openAuthoringInitialized.current) {\n    await initOpenAuthoring();\n  }\n\n  await fetchAndParseFiles({\n    ...args,\n    checkAccess: openAuthoring ? undefined : checkAccess,\n    // A contributor’s changes go to their fork, so the branch they can’t push to doesn’t matter\n    checkBranchAccess: forkedRepository.current ? undefined : checkBranchAccess,\n  });\n};\n","import { dataLoadedProgress } from '$lib/services/contents';\n\n/**\n * How often the simulated progress advances, in milliseconds. Each tick writes to a reactive state\n * that re-renders the progress bar, so this is kept at a rate the eye can follow rather than one\n * derived from the file count, which used to fire every few milliseconds for a small repository.\n */\nexport const PROGRESS_TICK_INTERVAL = 100;\n\n/**\n * Time the simulated progress budgets for each file, in milliseconds. The bar reaches\n * {@link PROGRESS_CEILING} once this much time has passed per file, then holds there until the\n * fetch actually finishes.\n */\nconst PROGRESS_TIME_PER_FILE = 10;\n\n/**\n * Highest value the simulated progress reaches on its own. The bar only shows completion once the\n * files have really arrived.\n */\nexport const PROGRESS_CEILING = 99;\n\n/**\n * Show a simulated progress bar while a batch request that reports no progress of its own is in\n * flight. The bar advances at a steady rate proportional to the number of files, and stops short\n * of the end until {@link stop} is called.\n * @param {number} fileCount Number of files being fetched.\n * @returns {() => void} Function that stops the simulation and hides the progress bar.\n */\nexport const startSimulatedProgress = (fileCount) => {\n  // Advance by however much of the budget passes in one tick, but always by something\n  const step = Math.max(\n    (PROGRESS_TICK_INTERVAL / (Math.max(fileCount, 1) * PROGRESS_TIME_PER_FILE)) * 100,\n    0.1,\n  );\n\n  let progress = 0;\n\n  dataLoadedProgress.current = progress;\n\n  const interval = window.setInterval(() => {\n    progress = Math.min(progress + step, PROGRESS_CEILING);\n    dataLoadedProgress.current = progress;\n  }, PROGRESS_TICK_INTERVAL);\n\n  return () => {\n    window.clearInterval(interval);\n    dataLoadedProgress.current = undefined;\n  };\n};\n","import { isAdditionsEnabled } from '$lib/services/app/additions';\nimport { fetchLastCommit } from '$lib/services/backends/git/github/commits';\nimport {\n  getContentRepository,\n  initOpenAuthoring,\n  isOpenAuthoringConfigured,\n} from '$lib/services/backends/git/github/fork';\nimport { fetchAliasedBatch } from '$lib/services/backends/git/github/graphql';\nimport {\n  checkBranchAccess,\n  checkRepositoryAccess,\n  fetchDefaultBranchName,\n  repository,\n} from '$lib/services/backends/git/github/repository';\nimport { fetchAPI, fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport { mapConcurrently, runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { fetchRepositoryFiles } from '$lib/services/backends/git/shared/files';\nimport { startSimulatedProgress } from '$lib/services/backends/git/shared/progress';\nimport { getRepositoryPath } from '$lib/services/backends/git/shared/repository';\nimport { toFileListItems } from '$lib/services/backends/git/shared/tree';\nimport { getRootDir } from '$lib/services/backends/root-dir';\nimport { getBotCoAuthor } from '$lib/services/utils/commit-author';\nimport { encodePathSegments } from '$lib/services/utils/url';\n\n/**\n * @import {\n * Asset,\n * BaseFileListItem,\n * BaseFileListItemProps,\n * RepositoryContentsMap,\n * } from '$lib/types/private';\n * @import { RepositoryMetadataMap } from '$lib/services/backends/git/shared/fetch';\n */\n\n/**\n * @typedef {{ type: string, path: string, sha: string, size: number }} GitTreeEntry\n */\n\n/**\n * Fetch a Git tree.\n * @param {string} treeRef Commit SHA, branch name or tree SHA.\n * @param {boolean} recursive Whether to list the subtrees as well.\n * @returns {Promise<{ tree: GitTreeEntry[], truncated: boolean }>} Tree, and whether the response\n * was truncated because the tree is too big.\n * @see https://docs.github.com/en/rest/git/trees#get-a-tree\n */\nconst fetchTree = async (treeRef, recursive) => {\n  const query = recursive ? '?recursive=1' : '';\n\n  return /** @type {{ tree: GitTreeEntry[], truncated: boolean }} */ (\n    await fetchAPI(\n      `${getRepositoryPath(repository)}/git/trees/${encodePathSegments(treeRef)}${query}`,\n    )\n  );\n};\n\n/**\n * Fetch the repository’s complete file list, and return it in the canonical format. A tree too big\n * to be listed recursively in one response, as in a huge repository, has its subtrees listed\n * separately instead, as GitHub suggests. With the `root_dir` backend option, only the files in\n * that directory are listed, which saves listing the whole of a big monorepo; the paths are still\n * relative to the repository root.\n * @param {string} [lastHash] The last commit’s SHA-1 hash.\n * @returns {Promise<BaseFileListItemProps[]>} File list.\n * @throws {Error} If a single directory has too many files to list, or if the root directory\n * doesn’t exist.\n */\nexport const fetchFileList = async (lastHash) => {\n  const ref = /** @type {string} */ (lastHash ?? repository.branch);\n  const rootDir = getRootDir();\n  /** @type {GitTreeEntry[]} */\n  const blobs = [];\n\n  /** @type {{ sha: string, prefix: string }[]} */\n  let pending = [\n    // A tree-ish expression addresses the directory’s tree without looking its SHA up first\n    rootDir ? { sha: `${ref}:${rootDir}`, prefix: `${rootDir}/` } : { sha: ref, prefix: '' },\n  ];\n\n  // One level at a time, so the requests in flight stay within the concurrency limit\n  while (pending.length) {\n    // eslint-disable-next-line no-await-in-loop\n    const results = await mapConcurrently(pending, async ({ sha, prefix }) => {\n      const { tree, truncated } = await fetchTree(sha, true).catch((ex) => {\n        if (rootDir && sha === `${ref}:${rootDir}` && ex?.cause?.status === 404) {\n          throw createLocalizedError('Failed to list the files.', 'root_dir_not_found', {\n            repo: `${repository.owner}/${repository.repo}`,\n            dir: rootDir,\n          });\n        }\n\n        throw ex;\n      });\n\n      if (!truncated) {\n        return { prefix, entries: tree, subtrees: [] };\n      }\n\n      // List this directory alone, and its subdirectories separately\n      const { tree: children, truncated: tooBig } = await fetchTree(sha, false);\n\n      if (tooBig) {\n        throw new Error(`The directory '${prefix || '/'}' has too many files to list.`);\n      }\n\n      return {\n        prefix,\n        entries: children,\n        subtrees: children.filter(({ type }) => type === 'tree'),\n      };\n    });\n\n    pending = results.flatMap(({ prefix, subtrees }) =>\n      subtrees.map(({ path, sha }) => ({ sha, prefix: `${prefix}${path}/` })),\n    );\n\n    results.forEach(({ prefix, entries }) => {\n      entries.forEach((entry) => {\n        if (entry.type === 'blob') {\n          blobs.push({ ...entry, path: `${prefix}${entry.path}` });\n        }\n      });\n    });\n  }\n\n  return toFileListItems(blobs);\n};\n\nconst FETCH_DIR_SHA_QUERY = `\n  query($owner: String!, $repo: String!, $expression: String!) {\n    repository(owner: $owner, name: $repo) {\n      object(expression: $expression) {\n        oid\n      }\n    }\n  }\n`;\n\n/**\n * Find the tree SHA of a directory at the given commit.\n * @param {string} ref Commit SHA or branch name.\n * @param {string} dirPath Directory path relative to the repository root.\n * @returns {Promise<string | undefined>} Tree SHA, or `undefined` if the directory doesn’t exist.\n * @see https://docs.github.com/en/graphql/reference/objects#repository\n */\nexport const fetchDirSHA = async (ref, dirPath) => {\n  const { owner, repo } = repository;\n\n  const result = /** @type {{ repository?: { object?: { oid: string } | null } | null }} */ (\n    await fetchGraphQL(FETCH_DIR_SHA_QUERY, { owner, repo, expression: `${ref}:${dirPath}` })\n  );\n\n  return result.repository?.object?.oid;\n};\n\n/**\n * Number of files requested per GraphQL query. The API has no hard limit on aliases, but a bigger\n * query takes longer to answer and is more likely to time out.\n */\nconst CHUNK_SIZE = 250;\n\n/**\n * Get the GraphQL field selection for fetching the text content of the given file.\n * @param {BaseFileListItem} file File.\n * @returns {string} Field selection, or an empty string for an asset, which has no content to read\n * and is just listed for its metadata.\n */\nexport const getFileContentsFragment = ({ type, sha }) =>\n  type === 'asset'\n    ? ''\n    : `object(oid: ${JSON.stringify(sha)}) { ... on Blob { text isTruncated } }`;\n\n/**\n * Get the GraphQL field selection for fetching the last commit of the given file.\n * @param {BaseFileListItem} file File.\n * @returns {string} Field selection.\n */\nexport const getFileMetadataFragment = ({ path }) => `\n  ref(qualifiedName: $branch) {\n    target {\n      ... on Commit {\n        history(first: 1, path: ${JSON.stringify(path)}) {\n          nodes {\n            author {\n              name\n              email\n              user {\n                id: databaseId\n                login\n              }\n            }\n            committedDate\n            messageBody\n          }\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Request a blob from the REST API. The `raw` media type asks for the file content itself, rather\n * than the base64-wrapped JSON the endpoint returns by default.\n * @param {object} args Arguments.\n * @param {string} args.owner Repository owner.\n * @param {string} args.repo Repository name.\n * @param {string} args.sha Blob SHA-1 hash.\n * @param {'text' | 'raw'} args.responseType Whether to read the content as text, or to hand the\n * `Response` back so the caller can decide. Note that `raw` bypasses the shared error handling, so\n * the caller has to check the status itself.\n * @returns {Promise<string | Response>} File content or response, depending on `responseType`.\n * @see https://docs.github.com/en/rest/git/blobs#get-a-blob\n */\nconst requestBlob = async ({ owner, repo, sha, responseType }) =>\n  /** @type {Promise<string | Response>} */ (\n    fetchAPI(`${getRepositoryPath({ owner, repo })}/git/blobs/${sha}`, {\n      headers: { Accept: 'application/vnd.github.raw' },\n      responseType,\n    })\n  );\n\n/**\n * Retrieve the text content of a blob with the REST API, which returns it in full. The GraphQL API\n * cuts `Blob.text` off at 512 KB and reports it with `isTruncated`; keeping that shortened text\n * would silently drop the tail of the file the next time the entry is saved.\n * @param {object} args Arguments.\n * @param {string} args.owner Repository owner.\n * @param {string} args.repo Repository name.\n * @param {string} args.sha Blob SHA-1 hash.\n * @returns {Promise<string>} File content.\n * @see https://github.com/sveltia/sveltia-cms/issues/950\n * @see https://github.com/graphql-hive/graphql-inspector/issues/2079\n */\nexport const fetchBlobText = async ({ owner, repo, sha }) =>\n  /** @type {Promise<string>} */ (requestBlob({ owner, repo, sha, responseType: 'text' }));\n\n/**\n * Parse the file contents from the API response.\n * @param {BaseFileListItem[]} fetchingFiles Base file list.\n * @param {any[]} results Result for each file from the API, in the same order.\n * @returns {Promise<RepositoryContentsMap>} Parsed file contents map. The commit metadata is left\n * out; it’s fetched separately with {@link fetchFileMetadata}.\n */\nexport const parseFileContents = async (fetchingFiles, results) => {\n  /** @type {{ sha: string, data: { text?: string } }[]} */\n  const truncatedFiles = [];\n\n  const entries = fetchingFiles.map(({ path, sha, size }, index) => {\n    const { text, isTruncated } = results[index] ?? {};\n    const data = { sha, size: /** @type {number} */ (size), text, meta: undefined };\n\n    if (isTruncated) {\n      truncatedFiles.push({ sha, data });\n    }\n\n    return [path, data];\n  });\n\n  // Read any oversized blob again with the REST API, which has no such size cap\n  const { owner, repo } = repository;\n\n  await runConcurrently(truncatedFiles, async ({ sha, data }) => {\n    data.text = await fetchBlobText({ owner, repo, sha });\n  });\n\n  return Object.fromEntries(entries);\n};\n\n/**\n * Parse the file metadata from the API response.\n * @param {BaseFileListItem[]} fetchingFiles Base file list.\n * @param {any[]} results Result for each file from the API, in the same order.\n * @returns {RepositoryMetadataMap} Parsed file metadata map.\n */\nexport const parseFileMetadata = (fetchingFiles, results) =>\n  Object.fromEntries(\n    fetchingFiles.flatMap(({ path }, index) => {\n      const commit = results[index]?.target?.history?.nodes?.[0];\n\n      // The file may have been deleted since the tree was fetched, leaving no commit to read. Skip\n      // it rather than losing the metadata of every other file; it’s fetched again next time\n      if (!commit) {\n        return [];\n      }\n\n      const { author, committedDate, messageBody } = commit;\n      const user = author?.user;\n      // A commit made by an app for someone, e.g. with Sveltia CMS Additions, is theirs\n      const coAuthor = getBotCoAuthor(author, messageBody);\n\n      return [\n        [\n          path,\n          {\n            // The author can be `null` when the commit has no valid author info\n            commitAuthor:\n              coAuthor ||\n              (author\n                ? { name: author.name, email: author.email, id: user?.id, login: user?.login }\n                : undefined),\n            commitDate: new Date(committedDate),\n          },\n        ],\n      ];\n    }),\n  );\n\n/**\n * Query the API for the given files, a chunk at a time to avoid an API timeout, with a limited\n * number of requests in flight at once to avoid a Too Many Requests error.\n * @param {BaseFileListItem[]} fetchingFiles Base file list.\n * @param {string} alias Alias prefix.\n * @param {(file: BaseFileListItem) => string} getFragment Function to build the field selection\n * for a file.\n * @param {object} [options] Options.\n * @param {boolean} [options.useBranch] Whether the field selection uses the `$branch` variable.\n * @returns {Promise<any[]>} Result for each file, in the same order as `fetchingFiles`.\n */\nconst fetchInChunks = (fetchingFiles, alias, getFragment, { useBranch = false } = {}) =>\n  fetchAliasedBatch({ items: fetchingFiles, alias, getFragment, chunkSize: CHUNK_SIZE, useBranch });\n\n/**\n * Fetch the text contents of entry/config files. The commit metadata of the files is not included;\n * see {@link fetchFileMetadata}.\n * @param {BaseFileListItem[]} fetchingFiles Base file list.\n * @returns {Promise<RepositoryContentsMap>} Fetched contents map.\n */\nexport const fetchFileContents = async (fetchingFiles) => {\n  // Show a simulated progress bar because the request waiting time is long\n  const stopProgress = startSimulatedProgress(fetchingFiles.length);\n  /** @type {any[]} */\n  let results;\n\n  try {\n    results = await fetchInChunks(fetchingFiles, 'content', getFileContentsFragment);\n  } finally {\n    // Also on failure, so the interval doesn’t keep running behind the error message\n    stopProgress();\n  }\n\n  return parseFileContents(fetchingFiles, results);\n};\n\n/**\n * Fetch the last commit of each entry/asset file. Looking up the history of every path is the slow\n * part of a cold start — far slower than reading the blobs — so it’s done in this second pass,\n * after the contents have been shown.\n * @param {BaseFileListItem[]} fetchingFiles Base file list.\n * @returns {Promise<RepositoryMetadataMap>} Fetched metadata map.\n */\nexport const fetchFileMetadata = async (fetchingFiles) =>\n  parseFileMetadata(\n    fetchingFiles,\n    await fetchInChunks(fetchingFiles, 'commit', getFileMetadataFragment, { useBranch: true }),\n  );\n\n/**\n * Fetch file list from the backend service, download/parse all the entry files, then cache them in\n * the {@link allEntries} and {@link allAssets} stores.\n * @param {object} [options] Options.\n * @param {{ hash: string, message: string }} [options.lastCommit] Last commit on the branch, if the\n * caller has just fetched it, so it isn’t fetched again.\n */\nexport const fetchFiles = async ({ lastCommit } = {}) => {\n  await fetchRepositoryFiles({\n    isOpenAuthoringConfigured,\n    initOpenAuthoring,\n    repository,\n    // With Sveltia CMS Additions, the GitHub token is limited to the repository and the user’s\n    // role, and an installation token has no repository permissions to check\n    checkAccess: isAdditionsEnabled() ? undefined : checkRepositoryAccess,\n    checkBranchAccess,\n    fetchDefaultBranchName,\n    fetchLastCommit,\n    lastCommit,\n    fetchFileList,\n    fetchFileContents,\n    fetchFileMetadata,\n  });\n};\n\n/**\n * Fetch an asset as a Blob via the API.\n * @param {Asset} asset Asset to retrieve the file content.\n * @returns {Promise<Blob>} Blob data.\n */\nexport const fetchBlob = async (asset) => {\n  // An asset attached to an unpublished entry is committed to a workflow branch, whose blobs are\n  // read from the repository that serves the workflow branches’ files\n  const { owner, repo } = asset.workflow ? getContentRepository() : repository;\n  const { sha } = asset;\n\n  const response = /** @type {Response} */ (\n    await requestBlob({ owner, repo, sha, responseType: 'raw' })\n  );\n\n  // A `raw` response skips the shared error handling, so an error body would otherwise be returned\n  // as the file content, and moving or renaming the asset would commit it in place of the file\n  if (!response.ok) {\n    throw new Error('Failed to fetch the blob', { cause: { status: response.status } });\n  }\n\n  // Keep the bytes as they are, even for a text file: decoding it would strip a UTF-8 BOM and\n  // transcode a file GitHub serves in another encoding, e.g. `charset=iso-8859-1`, and moving or\n  // renaming the asset would then commit the altered bytes. The caller sets the MIME type from the\n  // file name, as GitHub serves an SVG or any other text file as `text/plain`\n  return response.blob();\n};\n","import { sendRequest } from '$lib/services/utils/networking';\n\n/**\n * @import { BackendServiceStatus } from '$lib/types/private';\n */\n\n/**\n * Create a function to check a Git service status.\n * @param {string} url URL of the status API.\n * @param {(response: any) => BackendServiceStatus | undefined} getLevel Function to map the API\n * response to a status level. It may throw if the response is malformed.\n * @returns {() => Promise<BackendServiceStatus>} Function to check the status. It resolves to\n * `unknown` when the request fails or the response cannot be mapped.\n */\nexport const createStatusChecker = (url, getLevel) => async () => {\n  try {\n    return getLevel(await sendRequest(url)) ?? 'unknown';\n  } catch {\n    return 'unknown';\n  }\n};\n","import { createStatusChecker } from '$lib/services/backends/git/shared/status';\n\n/**\n * @import { BackendServiceStatus } from '$lib/types/private';\n */\n\n/**\n * The URL of the GitHub status dashboard.\n */\nexport const STATUS_DASHBOARD_URL = 'https://www.githubstatus.com/';\n\n/**\n * Check the GitHub service status.\n * @returns {Promise<BackendServiceStatus>} Current status.\n * @see https://www.githubstatus.com/api\n */\nexport const checkStatus = createStatusChecker(\n  'https://www.githubstatus.com/api/v2/status.json',\n  /**\n   * Map the status API response to a level.\n   * @param {{ status: { indicator: string } }} response Response.\n   * @returns {BackendServiceStatus | undefined} Level.\n   */\n  ({ status: { indicator } }) =>\n    indicator === 'critical'\n      ? 'major'\n      : ['none', 'minor', 'major'].includes(indicator)\n        ? /** @type {BackendServiceStatus} */ (indicator)\n        : undefined,\n);\n","import { sleep } from '@sveltia/utils/misc';\n\nimport { fetchAPI } from '$lib/services/backends/git/shared/api';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { createDraftPullRequest } from '$lib/services/backends/git/shared/fork';\nimport {\n  getDeletionGroup,\n  getPullRequestDescription,\n  setDeletionGroup,\n} from '$lib/services/backends/git/shared/pull-requests';\nimport { getPullRequestPath } from '$lib/services/backends/git/shared/repository';\nimport { cmsConfig } from '$lib/services/config';\nimport { user } from '$lib/services/user/account.svelte';\nimport { parseForkBranchName } from '$lib/services/workflow/forks';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * CommitOptions,\n * CommitResults,\n * FileChange,\n * RepositoryPath,\n * WorkflowChangedFile,\n * WorkflowMergeState,\n * WorkflowPullRequest,\n * WorkflowSaveOptions,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Function to open a pull request with the given description on the service.\n * @typedef {(args: { branch: string, title: string, status: WorkflowStatus, description: string })\n * => Promise<WorkflowPullRequest>} CreatePullRequest\n */\n\n/**\n * Function to update the description of an existing pull request on the service. The current\n * description is read first and passed to `transform`, which returns the new one, so the rest of a\n * description a maintainer may have edited is kept as it is.\n * @typedef {(pullRequest: WorkflowPullRequest, transform: (description: string) => string) =>\n * Promise<string>} UpdateDescription\n */\n\n/**\n * Whether the `squash_merges` backend option is enabled, so a pull request of Editorial Workflow is\n * squash-merged when the entry is published.\n * @returns {boolean} Result.\n */\nexport const isSquashMergeEnabled = () => {\n  const { backend } = cmsConfig.current ?? {};\n\n  return backend && 'squash_merges' in backend ? !!backend.squash_merges : false;\n};\n\n/**\n * Delete a branch with the given REST API request. A branch that’s already gone, for example when\n * its pull request was merged, is fine, and any other failure is only reported in the console.\n * @param {object} args Arguments.\n * @param {string} args.branch Branch name.\n * @param {string} args.path REST API path to send the `DELETE` request to.\n * @param {number[]} args.goneStatuses HTTP status codes meaning the branch is already gone.\n * @throws {Error} When the branch is in a contributor’s fork, which is theirs to delete: a\n * maintainer only closes the pull request from it.\n */\nexport const deleteRemoteBranch = async ({ branch, path, goneStatuses }) => {\n  if (parseForkBranchName(branch)) {\n    throw new Error('A branch in a contributor’s fork cannot be deleted.');\n  }\n\n  try {\n    await fetchAPI(path, { method: 'DELETE', responseType: 'text' });\n  } catch (/** @type {any} */ ex) {\n    // The branch is already gone, which is what was wanted\n    if (goneStatuses.includes(ex.cause?.status)) {\n      return;\n    }\n\n    // Leaving the branch behind is harmless, but it makes the next pull request for the same entry\n    // start from an existing branch, so make the failure visible rather than swallowing it\n    // eslint-disable-next-line no-console\n    console.warn(`Failed to delete the ${branch} branch.`, ex);\n  }\n};\n\n/**\n * Open the pull request for a workflow branch the first save has just created. With Open Authoring\n * a draft is a branch without a pull request, so none is opened for it yet; a removal has no review\n * stages to move through, though, so its pull request is opened right away like it is in the\n * regular flow.\n * @param {object} args Arguments.\n * @param {CommitResults} args.commit Results of the commit that created the branch.\n * @param {string} args.branch Workflow branch name.\n * @param {string} args.title Pull request title.\n * @param {WorkflowStatus} args.status Status to open the pull request with.\n * @param {string} [args.deletionGroup] Deletion group to record in the pull request description.\n * See {@link getDeletionGroup}.\n * @param {CreatePullRequest} args.createPullRequest Function to open a pull request on the service.\n * @returns {Promise<WorkflowPullRequest>} New pull request.\n */\nexport const openWorkflowPullRequest = async ({\n  commit,\n  branch,\n  title,\n  status,\n  deletionGroup,\n  createPullRequest,\n}) => {\n  if (openAuthoring.current && status === 'draft') {\n    return createDraftPullRequest({ commit, branch, title });\n  }\n\n  return createPullRequest({\n    branch,\n    title,\n    status,\n    description: getPullRequestDescription(deletionGroup),\n  });\n};\n\n/**\n * Commit the given changes on the workflow branch, creating the branch and the pull request if they\n * don’t exist yet. This is the flow of a service whose commit itself creates the workflow branch on\n * the first save, so it doesn’t need a request of its own.\n * @param {WorkflowSaveOptions} args Arguments.\n * @param {object} service Service-specific functions.\n * @param {(changes: FileChange[], options: CommitOptions) => Promise<CommitResults>}\n * service.commitToNewBranch Function to commit on a workflow branch no pull request is known for.\n * @param {(changes: FileChange[], options: CommitOptions, pullRequest: WorkflowPullRequest) =>\n * Promise<CommitResults>} service.commitToExistingBranch Function to commit onto the branch of an\n * existing pull request.\n * @param {CreatePullRequest} service.createPullRequest Function to open a pull request on the\n * service.\n * @param {UpdateDescription} service.updateDescription Function to update the description of an\n * existing pull request, which records the deletion group.\n * @returns {Promise<{ commit: CommitResults, pullRequest: WorkflowPullRequest }>} Commit results\n * and the new or updated pull request.\n * @throws {Error} When the pull request comes from a fork whose contributor doesn’t let maintainers\n * push to it.\n */\nexport const saveWorkflowBranch = async (\n  { changes, options, branch, title, status, pullRequest, deletionGroup },\n  { commitToNewBranch, commitToExistingBranch, createPullRequest, updateDescription },\n) => {\n  // The Git service would refuse the commit anyway, but with a message about permissions that says\n  // nothing of the contributor’s choice behind it\n  if (pullRequest?.fork && !pullRequest.fork.editable) {\n    throw createLocalizedError('Failed to save the changes.', 'workflow.fork_not_editable');\n  }\n\n  if (pullRequest) {\n    // A reused pull request may be deleted along with other entries, or carry the record of an\n    // earlier deletion it no longer belongs to. The record is brought in line before the commit, so\n    // a failure leaves the pull request as it was rather than committed with a wrong record\n    const recorded =\n      getDeletionGroup(pullRequest) === deletionGroup\n        ? pullRequest\n        : {\n            ...pullRequest,\n            description: await updateDescription(pullRequest, (description) =>\n              setDeletionGroup(description, deletionGroup),\n            ),\n          };\n\n    return {\n      commit: await commitToExistingBranch(changes, { ...options, branch }, pullRequest),\n      pullRequest: recorded,\n    };\n  }\n\n  const commit = await commitToNewBranch(changes, { ...options, branch });\n\n  return {\n    commit,\n    pullRequest: await openWorkflowPullRequest({\n      commit,\n      branch,\n      title,\n      status,\n      deletionGroup,\n      createPullRequest,\n    }),\n  };\n};\n\n/**\n * Commit the given changes on a workflow branch that no pull request is known for. The branch is\n * usually created along with the commit, but it can already exist: it’s left over from an earlier\n * pull request for the same entry, which the CMS knows nothing about — one merged without deleting\n * the branch, or one that was closed on the service rather than discarded here, which leaves the\n * branch behind. Starting the new pull request from the branch as it stands would carry that\n * earlier work into it — a merged one adds nothing, but a closed one brings back what was thrown\n * away — so the branch is deleted and created afresh from the configured branch. With Open\n * Authoring a draft is a branch without a pull request, so there’s no telling a leftover from a\n * live one; the branch is kept, and it shows up as a draft the next time the fork is listed. The\n * fork is the contributor’s own, so nobody else’s work can be on it.\n * @param {object} args Arguments.\n * @param {string} args.branch Workflow branch name.\n * @param {number} args.branchExistsStatus HTTP status code the service refuses a commit creating\n * the branch with once the branch exists.\n * @param {() => Promise<CommitResults>} args.commitFromStart Function to commit the changes on a\n * branch created from the configured one.\n * @param {() => Promise<CommitResults>} args.commitOnBranch Function to commit the changes onto the\n * existing branch.\n * @param {() => Promise<string | undefined>} args.findOpenPullRequest Function to look up a pull\n * request open from the branch, returning its reference, e.g. `#1`, or `undefined` if there’s none.\n * @param {string} args.inUseMessage English message of the error thrown when one is open.\n * @param {(branch: string) => Promise<void>} args.deleteBranch Function to delete the branch.\n * @returns {Promise<CommitResults>} Commit results.\n * @throws {Error} When the branch exists and a pull request is open from it.\n */\nexport const commitToNewWorkflowBranch = async ({\n  branch,\n  branchExistsStatus,\n  commitFromStart,\n  commitOnBranch,\n  findOpenPullRequest,\n  inUseMessage,\n  deleteBranch,\n}) => {\n  try {\n    return await commitFromStart();\n  } catch (/** @type {any} */ ex) {\n    // The service rejects creating the branch outright once it exists. Anything else is a real\n    // failure\n    if (ex.cause?.status !== branchExistsStatus) {\n      throw ex;\n    }\n  }\n\n  if (openAuthoring.current) {\n    return commitOnBranch();\n  }\n\n  // A pull request open from the branch is one the board doesn’t show: it has lost its status\n  // label, it sits beyond the number of pull requests fetched, it goes to another branch, or it was\n  // never the CMS’s. Committing onto it would take whatever else it holds along with the entry,\n  // unseen, and deleting the branch would close it, so the save is refused instead\n  const number = await findOpenPullRequest();\n\n  if (number) {\n    throw createLocalizedError(inUseMessage, 'workflow.branch_in_use', { number });\n  }\n\n  await deleteBranch(branch);\n\n  return commitFromStart();\n};\n\n/**\n * Create the error for a save onto a workflow branch that is gone, e.g. with a pull request merged\n * or closed on the service, which is worth saying in words rather than with the service’s message\n * about a branch it can’t find.\n * @param {string} branch Workflow branch name.\n * @param {RepositoryPath} repository Repository the branch lived in.\n * @returns {Error} Error.\n */\nexport const createBranchGoneError = (branch, repository) =>\n  createLocalizedError('Failed to save the changes.', 'branch_not_found', {\n    repo: repository.repo,\n    branch,\n  });\n\n/**\n * Make sure the workflow branch of an existing pull request still points at the commit the entry\n * was loaded or saved at, which the conflict check has just compared it with, before committing\n * onto it. Without a head on record there’s nothing to compare, which is refused just the same.\n * @param {object} args Arguments.\n * @param {string} args.branch Workflow branch name.\n * @param {string | undefined} args.headSHA Head commit on record.\n * @param {(branch: string) => Promise<string | undefined>} args.fetchBranchHead Function to fetch\n * the commit the branch points at, or `undefined` if the branch is gone.\n * @param {(branch: string) => RepositoryPath & { branch: string }} args.getBranchRepository\n * Function to get the repository the branch lives in, and its name there, which for a contributor’s\n * branch is the fork and not the name the CMS knows it by.\n * @returns {Promise<string>} Head commit on record.\n * @throws {Error} When the branch is gone, or points at another commit than the one on record.\n */\nexport const assertBranchAtHead = async ({\n  branch,\n  headSHA,\n  fetchBranchHead,\n  getBranchRepository,\n}) => {\n  const head = await fetchBranchHead(branch);\n\n  if (head === undefined) {\n    const { branch: name, ...repository } = getBranchRepository(branch);\n\n    throw createBranchGoneError(name, repository);\n  }\n\n  // Trying again reloads the entry first, which takes the other commit into account\n  if (!headSHA || head !== headSHA) {\n    throw createLocalizedError(\n      'The workflow branch has moved since the entry was loaded.',\n      'save_conflict.branch_moved',\n    );\n  }\n\n  return headSHA;\n};\n\n/**\n * Update the status of a pull request whose status is kept in a label, as on GitHub and\n * Gitea/Forgejo, along with its draft state, so a pull request in the `draft` status can’t be\n * merged accidentally. With Open Authoring the fork flow takes over, as a contributor can’t label a\n * pull request on the upstream repository.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {WorkflowStatus} status New status.\n * @param {object} service Service-specific functions.\n * @param {(pullRequest: WorkflowPullRequest, status: WorkflowStatus) =>\n * Promise<WorkflowPullRequest>} service.updateForkStatus Function to update the status of a pull\n * request with Open Authoring.\n * @param {(pullRequest: WorkflowPullRequest, status: WorkflowStatus) => Promise<void>}\n * service.updateLabels Function to replace the status label of the pull request.\n * @param {(pullRequest: WorkflowPullRequest, isDraft: boolean) => Promise<void>}\n * service.updateDraftState Function to mark the pull request as a draft or ready for review.\n * @returns {Promise<WorkflowPullRequest>} Updated pull request.\n */\nexport const updateLabelledStatus = async (\n  pullRequest,\n  status,\n  { updateForkStatus, updateLabels, updateDraftState },\n) => {\n  if (openAuthoring.current) {\n    return updateForkStatus(pullRequest, status);\n  }\n\n  const isDraft = status === 'draft';\n\n  await updateLabels(pullRequest, status);\n\n  // Only the transitions into and out of the `draft` status change the draft state, so moving\n  // between the review and ready stages needs no further request\n  if (isDraft !== (pullRequest.status === 'draft')) {\n    await updateDraftState(pullRequest, isDraft);\n  }\n\n  return { ...pullRequest, status, updatedDate: new Date() };\n};\n\n/**\n * Get the folders holding the given files, each listed once. A file at the repository root is held\n * by the root, given as an empty string.\n * @param {string[]} paths File paths.\n * @returns {string[]} Folder paths.\n */\nexport const getParentDirs = (paths) => [\n  ...new Set(paths.map((path) => path.slice(0, Math.max(path.lastIndexOf('/'), 0)))),\n];\n\n/**\n * Convert the changed files a pull request’s REST API reports to {@link WorkflowChangedFile} ones,\n * along with their Git file modes, which the list leaves out. A removed file has no mode to read.\n * @param {Record<string, any>[]} files Files returned by the REST API.\n * @param {object} args Arguments.\n * @param {Record<string, WorkflowChangedFile['status']>} args.statusMap Map of the file statuses\n * the REST API reports to {@link WorkflowChangedFile} ones. Any other status modifies the file.\n * @param {string} args.headSHA Git object ID of the commit the files are read at.\n * @param {(args: { headSHA: string, paths: string[] }) => Promise<Map<string, string>>}\n * args.fetchFileModes Function to fetch the modes of the given files at the given commit.\n * @returns {Promise<WorkflowChangedFile[]>} Changed files.\n */\nexport const toChangedFilesWithModes = async (files, { statusMap, headSHA, fetchFileModes }) => {\n  const changedFiles = files.map(({ filename, status, previous_filename: previousPath }) => ({\n    path: /** @type {string} */ (filename),\n    status: statusMap[status] ?? 'modified',\n    previousPath: /** @type {string | undefined} */ (previousPath || undefined),\n  }));\n\n  const modes = await fetchFileModes({\n    headSHA,\n    paths: changedFiles.filter(({ status }) => status !== 'removed').map(({ path }) => path),\n  });\n\n  return changedFiles.map((file) => ({ ...file, mode: modes.get(file.path) }));\n};\n\n/**\n * Get the merge state to report when the pull request’s branch has moved on from the commit on\n * record. Publishing refuses such a pull request outright, as the merge is pinned to that commit,\n * so there’s no point in listing the files of a commit that won’t be merged. The list is reported\n * as complete, or the check would put the refusal down to changes it can’t show instead.\n * @param {WorkflowPullRequest} pullRequest Pull request, with the head commit on record.\n * @param {string} headSHA Commit the branch points at now.\n * @returns {WorkflowMergeState | undefined} State, or `undefined` if the branch hasn’t moved, in\n * which case the files have to be listed.\n */\nexport const getMovedHeadMergeState = (pullRequest, headSHA) =>\n  headSHA === pullRequest.headSHA\n    ? undefined\n    : { headSHA, onConfiguredBranches: true, files: [], complete: true };\n\n/**\n * Work out the merge state of a pull request from its head commit, as read from the service: no\n * files for a pull request that isn’t between the configured branches, no files either when the\n * branch has moved on from the commit on record (see {@link getMovedHeadMergeState}), and the files\n * changed at the head commit otherwise.\n * @param {object} args Arguments.\n * @param {WorkflowPullRequest} args.pullRequest Pull request, with the head commit on record.\n * @param {string | undefined} args.headSHA Commit the pull request’s branch points at now.\n * @param {boolean} args.onConfiguredBranches Whether the pull request goes from a branch of the\n * configured repository into its configured branch.\n * @param {(headSHA: string) => Promise<{ files: WorkflowChangedFile[], complete: boolean }>}\n * args.listChangedFiles Function to list the files changed at the head commit, and tell whether the\n * list is complete.\n * @returns {Promise<WorkflowMergeState>} State.\n */\nexport const resolveMergeState = async ({\n  pullRequest,\n  headSHA,\n  onConfiguredBranches,\n  listChangedFiles,\n}) => {\n  if (!headSHA || !onConfiguredBranches) {\n    return { headSHA, onConfiguredBranches: false, files: [], complete: false };\n  }\n\n  const movedHeadState = getMovedHeadMergeState(pullRequest, headSHA);\n\n  if (movedHeadState) {\n    return movedHeadState;\n  }\n\n  return { headSHA, onConfiguredBranches, ...(await listChangedFiles(headSHA)) };\n};\n\n/**\n * Check whether the given pull request has been merged, on GitHub or Gitea/Forgejo, whose APIs\n * share the endpoint. It answers with a status rather than a body: `204 No Content` when it has,\n * `404 Not Found` when it hasn’t. Both services answer a merge request for any pull request that\n * can’t be merged with a `405 Method Not Allowed`, the pull request having been merged already\n * included, so this tells that case from a real refusal.\n * @param {RepositoryPath} repository Repository holding the pull request.\n * @param {number} number Pull request number.\n * @returns {Promise<boolean>} `true` if the pull request has been merged.\n * @see https://docs.github.com/en/rest/pulls/pulls#check-if-a-pull-request-has-been-merged\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoPullRequestIsMerged\n */\nexport const isPullRequestMerged = async (repository, number) => {\n  const response = /** @type {Response} */ (\n    await fetchAPI(`${getPullRequestPath(repository, number)}/merge`, { responseType: 'raw' })\n  );\n\n  return response.ok;\n};\n\n/**\n * Reopen a pull request that was closed earlier, on GitHub or Gitea/Forgejo, whose REST APIs share\n * the endpoint. The author of a pull request is allowed to do this, so a contributor doesn’t need\n * write access to the configured repository for it.\n * @param {RepositoryPath} repository Repository holding the pull request.\n * @param {number} number Pull request number.\n * @see https://docs.github.com/en/rest/pulls/pulls#update-a-pull-request\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoEditPullRequest\n */\nexport const reopenPullRequest = async (repository, number) => {\n  await fetchAPI(getPullRequestPath(repository, number), {\n    method: 'PATCH',\n    body: { state: 'open' },\n  });\n};\n\n/**\n * Update the description of a pull request on GitHub or Gitea/Forgejo, whose REST APIs share the\n * endpoints. The current description is read first and passed to `transform`, so the rest of it is\n * kept as it is.\n * @param {RepositoryPath} repository Repository holding the pull request.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {(description: string) => string} transform Function to get the new description from the\n * current one, which is an empty string if the pull request has none.\n * @returns {Promise<string>} New description.\n * @see https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request\n * @see https://docs.github.com/en/rest/pulls/pulls#update-a-pull-request\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoEditPullRequest\n */\nexport const updatePullRequestDescription = async (repository, pullRequest, transform) => {\n  const path = getPullRequestPath(repository, pullRequest.number);\n  const { body } = /** @type {Record<string, any>} */ (await fetchAPI(path));\n  const description = transform(body ?? '');\n\n  await fetchAPI(path, { method: 'PATCH', body: { body: description } });\n\n  return description;\n};\n\n/**\n * Approve a pull request on behalf of the signed-in user, on GitHub or Gitea/Forgejo, whose REST\n * APIs share the endpoint, pinned to the head commit the entry was reviewed at.\n * @param {RepositoryPath} repository Repository holding the pull request.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {string} event Review event that approves it, which the services name differently:\n * `APPROVE` on GitHub, `APPROVED` on Gitea/Forgejo.\n * @see https://docs.github.com/en/rest/pulls/reviews#create-a-review-for-a-pull-request\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoCreatePullReview\n */\nexport const approvePullRequest = async (repository, pullRequest, event) => {\n  await fetchAPI(`${getPullRequestPath(repository, pullRequest.number)}/reviews`, {\n    method: 'POST',\n    body: { event, commit_id: pullRequest.headSHA },\n  });\n};\n\n/**\n * Pick the signed-in user’s standing approvals from the reviews of a pull request, as listed by\n * the GitHub or Gitea/Forgejo REST API. GitHub gives a dismissed review a state of its own, while\n * Gitea/Forgejo keeps the state and flags it as dismissed.\n * @param {Record<string, any>[]} reviews Reviews returned by the REST API.\n * @returns {Record<string, any>[]} Approving reviews of the user.\n */\nexport const findOwnApprovals = (reviews) =>\n  reviews.filter(\n    ({ state, dismissed, user: reviewer }) =>\n      state === 'APPROVED' && !dismissed && reviewer?.login === user.account?.login,\n  );\n\n/**\n * Close a pull request without merging it, and delete its branch. An Open Authoring draft has no\n * pull request yet, so deleting the branch is all there is to do for it.\n * @param {RepositoryPath} repository Repository holding the pull request.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {object} service Service-specific values.\n * @param {(branch: string) => Promise<void>} service.deleteBranch Function to delete the branch. A\n * contributor’s branch is left in their fork, where they can still use it, as the maintainer can\n * only close the pull request from it.\n * @param {number[]} [service.closedStatuses] HTTP status codes a refusal to close the pull request\n * comes with when there’s nothing left to close, in which case the branch is still deleted.\n * @param {(number: number) => Promise<unknown>} [service.closeRequest] Function to close the pull\n * request. Default: the request GitHub and Gitea/Forgejo take, whose REST APIs share the endpoint.\n * @see https://docs.github.com/en/rest/pulls/pulls#update-a-pull-request\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoEditPullRequest\n */\nexport const discardPullRequest = async (\n  repository,\n  pullRequest,\n  { deleteBranch, closedStatuses = [], closeRequest },\n) => {\n  if (pullRequest.number !== undefined) {\n    try {\n      await (closeRequest\n        ? closeRequest(pullRequest.number)\n        : fetchAPI(getPullRequestPath(repository, pullRequest.number), {\n            method: 'PATCH',\n            body: { state: 'closed' },\n          }));\n    } catch (/** @type {any} */ ex) {\n      if (!closedStatuses.includes(ex.cause?.status)) {\n        throw ex;\n      }\n    }\n  }\n\n  if (!pullRequest.fork) {\n    await deleteBranch(pullRequest.branch);\n  }\n};\n\n/**\n * Bring an Open Authoring pull request on GitHub or Gitea/Forgejo in line with the given status,\n * for `updateForkStatusWith`. Moving it back to the drafting stage makes it a draft, or a work in\n * progress on Gitea/Forgejo, which keeps it — and the discussion on it — in place while taking it\n * out of the maintainers’ review queue; sending it for review reopens it if it was closed and marks\n * it ready.\n * @param {object} args Arguments.\n * @param {WorkflowPullRequest} args.pullRequest Pull request.\n * @param {WorkflowStatus} args.status New status.\n * @param {string} [args.state] Pull request state, e.g. `open`. GitHub’s GraphQL API reports it in\n * upper case, which makes no difference.\n * @param {boolean} [args.draft] Whether the pull request is a draft.\n * @param {object} service Service-specific values.\n * @param {RepositoryPath} service.repository Repository holding the pull request.\n * @param {(pullRequest: WorkflowPullRequest, isDraft: boolean) => Promise<void>}\n * service.updateDraftState Function to mark the pull request as a draft or ready for review.\n */\nexport const applyForkPullRequestStatus = async (\n  { pullRequest, status, state, draft },\n  { repository, updateDraftState },\n) => {\n  const normalizedState = state?.toLowerCase();\n\n  if (status === 'draft') {\n    if (normalizedState === 'open' && !draft) {\n      await updateDraftState(pullRequest, true);\n    }\n  } else {\n    if (normalizedState === 'closed') {\n      await reopenPullRequest(repository, /** @type {number} */ (pullRequest.number));\n    }\n\n    if (draft) {\n      await updateDraftState(pullRequest, false);\n    }\n  }\n};\n\n/**\n * How often, and for how long at most, a pull request set to auto-merge is read while the service\n * waits for its required checks or pipeline. Those take minutes, so the reads are spaced out. The\n * cap is a safety net for a merge that never lands, e.g. one waiting for a check that never\n * reports, or one the service has queued but not carried out.\n */\nexport const AUTO_MERGE_POLL = { interval: 10000, maxDuration: 60 * 60 * 1000 };\n\n/**\n * Check whether the given error is a client error that won’t go away by itself — the session has\n * ended, or the pull request is gone, say — so there’s no point in sending the request again. The\n * limit on requests having been hit is the exception: that one passes.\n * @param {any} ex Error thrown by `fetchAPI` or `fetchGraphQL`.\n * @returns {boolean} Result.\n */\nexport const isPermanentClientError = (ex) => {\n  const status = ex?.cause?.status;\n\n  return typeof status === 'number' && status >= 400 && status < 500 && status !== 429;\n};\n\n/**\n * Wait for the service to merge a pull request that has been set to auto-merge. The pull request is\n * read every so often and handed to `check`, until it’s merged, in which case this resolves, or\n * until it’s clear that the merge won’t happen on its own, or the wait has run out, in which case\n * an error is thrown. The service keeps the auto-merge armed after a failed check, in case it’s\n * re-run by hand, but a merge made that way would happen behind the CMS’s back once it has reported\n * a failure, so the auto-merge is cancelled along with the report: publishing again is what merges\n * the entry from then on. A failed read says nothing about the merge, which the service carries out\n * on its own, so it’s only logged and the wait goes on, unless it’s a client error that asking\n * again won’t fix: see {@link isPermanentClientError}.\n * @template T\n * @param {object} args Arguments.\n * @param {() => Promise<T>} args.read Function to read the pull request.\n * @param {(item: T) => { merged?: boolean, failure?: string, armed?: boolean }} args.check\n * Function to check the pull request read: whether it has been merged, if not, a summary of why it\n * won’t be merged on its own, `undefined` to keep waiting, and whether its auto-merge is still on.\n * @param {() => Promise<any>} args.cancel Function to cancel the auto-merge. A failure is ignored,\n * as a pull request that has just been merged or closed has no auto-merge left to cancel.\n * @param {string} args.label Name of the pull request for the messages, e.g. `pull request #1`.\n * @param {number} [args.deadline] Time to give up at, as a Unix timestamp in milliseconds.\n * @returns {Promise<void>}\n * @throws {Error} When the pull request won’t be merged, or wasn’t within the time allowed.\n */\nexport const waitForMerge = async (args) => {\n  const { read, check, cancel, label, deadline = Date.now() + AUTO_MERGE_POLL.maxDuration } = args;\n\n  /**\n   * Cancel the auto-merge, reporting a failure rather than throwing it.\n   */\n  const cancelSafely = async () => {\n    try {\n      await cancel();\n    } catch (/** @type {any} */ ex) {\n      // eslint-disable-next-line no-console\n      console.warn(`Failed to cancel the auto-merge on ${label}.`, ex);\n    }\n  };\n\n  if (Date.now() >= deadline) {\n    await cancelSafely();\n\n    throw new Error(`Timed out waiting for ${label} to be merged`);\n  }\n\n  await sleep(AUTO_MERGE_POLL.interval);\n\n  /** @type {{ item: T } | undefined} */\n  let result;\n\n  try {\n    result = { item: await read() };\n  } catch (/** @type {any} */ ex) {\n    if (isPermanentClientError(ex)) {\n      throw ex;\n    }\n\n    // eslint-disable-next-line no-console\n    console.warn(`Failed to read ${label}, still waiting.`, ex);\n  }\n\n  if (result) {\n    const { merged, failure, armed } = check(result.item);\n\n    if (merged) {\n      return;\n    }\n\n    if (failure) {\n      if (armed) {\n        await cancelSafely();\n      }\n\n      throw new Error(`${label[0].toUpperCase()}${label.slice(1)} was not merged: ${failure}`);\n    }\n  }\n\n  await waitForMerge({ ...args, deadline });\n};\n","import { repository } from '$lib/services/backends/git/github/repository';\nimport { fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport { pollUntil, SETTLE_POLL } from '$lib/services/backends/git/shared/poll';\nimport { waitForMerge } from '$lib/services/backends/git/shared/workflow';\n\n/**\n * @import { WorkflowPullRequest } from '$lib/types/private';\n */\n\n/**\n * Rollup states of a commit’s checks under which a pull request set to auto-merge is still expected\n * to merge on its own: a check is running, or hasn’t reported yet.\n * @see https://docs.github.com/en/graphql/reference/enums#statusstate\n */\nconst PENDING_CHECK_STATES = ['PENDING', 'EXPECTED'];\n/**\n * Review decisions that stop a pull request from being merged whatever its checks say, so\n * auto-merge would wait for a review rather than for the checks.\n * @see https://docs.github.com/en/graphql/reference/enums#pullrequestreviewdecision\n */\nconst BLOCKING_REVIEW_DECISIONS = ['REVIEW_REQUIRED', 'CHANGES_REQUESTED'];\n/**\n * Merge states under which GitHub merges a pull request right away. `UNSTABLE` means a check that\n * isn’t required has failed, which doesn’t stop the merge.\n * @see https://docs.github.com/en/graphql/reference/enums#mergestatestatus\n */\nconst MERGEABLE_STATES = ['CLEAN', 'HAS_HOOKS', 'UNSTABLE'];\n/**\n * How many times, and how often, the pull request is read while GitHub works out whether it can be\n * merged. GitHub does that in the background after a push, which usually takes a second or two,\n * and reports `UNKNOWN` meanwhile.\n * @see https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request\n */\nconst MERGE_STATE_POLL = SETTLE_POLL;\n\n/**\n * Query to fetch what tells a pull request GitHub can merge once its required checks pass from one\n * it won’t merge at all.\n * @see https://docs.github.com/en/graphql/reference/objects#pullrequest\n */\nconst FETCH_MERGE_READINESS_QUERY = `\n  query($owner: String!, $repo: String!, $number: Int!) {\n    repository(owner: $owner, name: $repo) {\n      pullRequest(number: $number) {\n        id\n        state\n        merged\n        mergeStateStatus\n        reviewDecision\n        viewerCanEnableAutoMerge\n        autoMergeRequest {\n          enabledAt\n        }\n        commits(last: 1) {\n          nodes {\n            commit {\n              statusCheckRollup {\n                state\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n\nconst ENABLE_AUTO_MERGE_MUTATION = `\n  mutation($input: EnablePullRequestAutoMergeInput!) {\n    enablePullRequestAutoMerge(input: $input) {\n      clientMutationId\n    }\n  }\n`;\n\nconst DISABLE_AUTO_MERGE_MUTATION = `\n  mutation($input: DisablePullRequestAutoMergeInput!) {\n    disablePullRequestAutoMerge(input: $input) {\n      clientMutationId\n    }\n  }\n`;\n\n/**\n * Read the pull request’s merge state over the GraphQL API, which, unlike the REST API, tells a\n * required check still running from any other reason GitHub has to refuse a merge.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<Record<string, any> | undefined>} Pull request node, with the rollup state of\n * its head commit’s checks as `checkState`, or `undefined` if it’s not found.\n */\nconst fetchMergeReadiness = async (pullRequest) => {\n  const { owner, repo } = repository;\n\n  const { repository: result } = /** @type {{ repository: Record<string, any> }} */ (\n    await fetchGraphQL(FETCH_MERGE_READINESS_QUERY, { owner, repo, number: pullRequest.number })\n  );\n\n  const node = result?.pullRequest;\n\n  if (!node) {\n    return undefined;\n  }\n\n  return { ...node, checkState: node.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state };\n};\n\n/**\n * Check whether GitHub is still working out if an open pull request can be merged.\n * @param {Record<string, any> | undefined} node Pull request node from {@link fetchMergeReadiness}.\n * @returns {boolean} Result.\n */\nconst isCheckingMergeability = (node) =>\n  node?.state === 'OPEN' && node.mergeStateStatus === 'UNKNOWN';\n\n/**\n * Read the pull request’s merge state with {@link fetchMergeReadiness}, again and again while\n * GitHub is still working out whether it can be merged, until that settles or the attempts run\n * out, in which case the unsettled state is returned as is.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<Record<string, any> | undefined>} Pull request node, or `undefined` if it’s not\n * found.\n */\nconst fetchSettledMergeReadiness = (pullRequest) =>\n  pollUntil(\n    () => fetchMergeReadiness(pullRequest),\n    (node) => !isCheckingMergeability(node),\n    MERGE_STATE_POLL,\n  );\n\n/**\n * Check whether a pull request GitHub refused to merge is only waiting for its required checks, so\n * it can be set to auto-merge. A pull request also blocked by something else — a failed check, a\n * review still required, a conflict — would sit there unmerged while the CMS waits for it, so it’s\n * left as a refusal. The same goes for a repository that doesn’t allow auto-merge.\n * @param {Record<string, any>} node Pull request node from {@link fetchMergeReadiness}.\n * @returns {boolean} Result.\n */\nconst isWaitingForChecks = (node) =>\n  node.state === 'OPEN' &&\n  node.mergeStateStatus === 'BLOCKED' &&\n  // GitHub doesn’t offer to enable an auto-merge that’s already on, e.g. one set by an earlier\n  // publish whose wait was cut short by closing the page\n  (!!node.viewerCanEnableAutoMerge || !!node.autoMergeRequest) &&\n  PENDING_CHECK_STATES.includes(node.checkState) &&\n  !BLOCKING_REVIEW_DECISIONS.includes(node.reviewDecision);\n\n/**\n * Wait for GitHub to merge a pull request that has been set to auto-merge: see\n * {@link waitForMerge}. The merge won’t happen on its own once a check has failed, a new commit or\n * someone on GitHub has cancelled the auto-merge, or the pull request has been closed. Those are\n * reported as errors, so the entry stays on the Editorial Workflow board rather than being taken\n * for published.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {string} nodeId Pull request node ID.\n * @returns {Promise<void>}\n * @throws {Error} When the pull request won’t be merged, or wasn’t within the time allowed.\n * @see https://docs.github.com/en/graphql/reference/mutations#disablepullrequestautomerge\n */\nconst waitForAutoMerge = (pullRequest, nodeId) =>\n  waitForMerge({\n    /**\n     * Read the pull request.\n     * @returns {Promise<Record<string, any> | undefined>} Pull request node.\n     */\n    read: () => fetchMergeReadiness(pullRequest),\n    /**\n     * Check the pull request read.\n     * @param {Record<string, any> | undefined} node Pull request node, or `undefined` if it’s not\n     * found.\n     * @returns {{ merged?: boolean, failure?: string, armed: boolean }} Result.\n     */\n    check: (node) => {\n      const { merged, state, autoMergeRequest, checkState } = node ?? {};\n      const armed = state === 'OPEN' && !!autoMergeRequest;\n      const failed = !PENDING_CHECK_STATES.includes(checkState) && checkState !== 'SUCCESS';\n\n      return {\n        merged,\n        failure:\n          armed && !failed\n            ? undefined\n            : `${state}, checks ${checkState}, auto-merge ${autoMergeRequest ? 'on' : 'off'}`,\n        armed,\n      };\n    },\n    /**\n     * Cancel the auto-merge.\n     * @returns {Promise<any>} Result.\n     */\n    cancel: () => fetchGraphQL(DISABLE_AUTO_MERGE_MUTATION, { input: { pullRequestId: nodeId } }),\n    label: `pull request #${pullRequest.number}`,\n  });\n\n/**\n * Set a pull request that’s waiting for its required checks to auto-merge, pinned to the commit the\n * entry was loaded or saved at, unless it’s set already.\n * @param {object} args Arguments.\n * @param {WorkflowPullRequest} args.pullRequest Pull request.\n * @param {Record<string, any>} args.node Pull request node from {@link fetchMergeReadiness}.\n * @param {boolean} args.squash Whether to squash the commits.\n * @param {() => Promise<any>} args.merge Function to merge the pull request right away.\n * @returns {Promise<boolean>} Whether GitHub is to merge the pull request once the checks pass,\n * rather than having merged it already.\n */\nconst scheduleAutoMerge = async ({ pullRequest, node, squash, merge }) => {\n  if (node.autoMergeRequest) {\n    return true;\n  }\n\n  const { title, headSHA } = pullRequest;\n\n  try {\n    await fetchGraphQL(ENABLE_AUTO_MERGE_MUTATION, {\n      input: {\n        pullRequestId: node.id,\n        mergeMethod: squash ? 'SQUASH' : 'MERGE',\n        commitHeadline: title,\n        ...(headSHA ? { expectedHeadOid: headSHA } : {}),\n      },\n    });\n\n    return true;\n  } catch {\n    // The response can have been lost after GitHub turned auto-merge on, which a merge now would be\n    // refused for while the checks run, so the pull request is read again first\n    const latest = await fetchMergeReadiness(pullRequest);\n\n    // GitHub may even have merged it by now, which leaves only the branch cleanup to do\n    if (latest?.merged) {\n      return false;\n    }\n\n    if (latest?.autoMergeRequest) {\n      return true;\n    }\n\n    // Otherwise the checks can have passed since the merge was refused, in which case GitHub\n    // refuses auto-merge on a pull request it can merge right away, so it’s merged now instead. A\n    // refusal of that is the error to report\n    await merge();\n\n    return false;\n  }\n};\n\n/**\n * Make what can be made of a merge GitHub has refused with a `405 Method Not Allowed`, which it\n * answers whenever the pull request can’t be merged, whatever the reason, so the pull request is\n * read to tell them apart. GitHub refuses the merge while it’s still working out whether the pull\n * request can be merged, which it does in the background after a push, so the pull request is read\n * again until that settles. Branch protection or a ruleset can also require status checks to pass\n * before a pull request is merged, and GitHub refuses an immediate merge while they’re running, in\n * which case the pull request is set to auto-merge, and this resolves once GitHub has merged it.\n * @param {object} args Arguments.\n * @param {WorkflowPullRequest} args.pullRequest Pull request.\n * @param {boolean} args.squash Whether to squash the commits.\n * @param {() => Promise<any>} args.merge Function to merge the pull request right away, pinned to\n * the commit on record.\n * @param {Error} args.refusal Error the merge was refused with, which is thrown again when there’s\n * nothing to be made of it.\n * @returns {Promise<void>} Resolves once the pull request has been merged, leaving the branch\n * cleanup to the caller.\n * @throws {Error} When the pull request won’t be merged.\n * @see https://docs.github.com/en/graphql/reference/mutations#enablepullrequestautomerge\n * @see https://github.com/sveltia/sveltia-cms/issues/1094\n */\nexport const mergeRefusedPullRequest = async ({ pullRequest, squash, merge, refusal }) => {\n  const node = await fetchSettledMergeReadiness(pullRequest);\n\n  // It has been merged already — by a maintainer on GitHub while this board was open, say. That’s\n  // the outcome the user asked for, so it’s the branch cleanup that’s left to do rather than an\n  // error to report\n  if (node?.merged) {\n    return;\n  }\n\n  if (isCheckingMergeability(node)) {\n    throw new Error(\n      `Timed out waiting for GitHub to check whether pull request #${pullRequest.number} can be ` +\n        'merged',\n      { cause: refusal },\n    );\n  }\n\n  // What held the merge back may have passed by the time the state settles, such as the\n  // mergeability check GitHub runs after a push. The merge is then made once more, pinned to the\n  // same commit, so a push made since can’t slip in\n  if (MERGEABLE_STATES.includes(node?.mergeStateStatus)) {\n    await merge();\n  } else if (node && isWaitingForChecks(node)) {\n    if (await scheduleAutoMerge({ pullRequest, node, squash, merge })) {\n      await waitForAutoMerge(pullRequest, node.id);\n    }\n  } else {\n    throw refusal;\n  }\n};\n","import { fetchBlobText } from '$lib/services/backends/git/github/files';\nimport {\n  getBranchRepository,\n  getContentRepository,\n  getWorkflowRepository,\n} from '$lib/services/backends/git/github/fork';\nimport { fetchAliasedBatch } from '$lib/services/backends/git/github/graphql';\nimport { repository } from '$lib/services/backends/git/github/repository';\nimport { fetchAPI, fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport {\n  parseRestFiles,\n  parseRestPullRequest,\n  toCommitAuthor,\n} from '$lib/services/backends/git/shared/pull-requests';\nimport {\n  getPullRequestPath,\n  getRepositoryPath,\n} from '$lib/services/backends/git/shared/repository';\nimport { deleteRemoteBranch } from '$lib/services/backends/git/shared/workflow';\nimport { encodePathSegments } from '$lib/services/utils/url';\nimport { getStatusLabel, replaceStatusLabel } from '$lib/services/workflow/labels';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * CommitAuthor,\n * WorkflowFile,\n * WorkflowPullRequest,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Maximum numbers of items to retrieve from the GraphQL API: open pull requests, changed files per\n * pull request, and labels per pull request. Editorial Workflow is not meant to hold a huge\n * backlog, so a single page is enough in practice.\n */\nexport const MAX_ITEMS = {\n  pullRequests: 100,\n  files: 100,\n  labels: 100,\n  // Open Authoring branches in the contributor’s fork\n  branches: 100,\n  // Pull requests to look at for a single Open Authoring branch. Only the most recent match is\n  // used, and each candidate carries a file list of its own, so asking for more than a couple\n  // multiplies the size of a query that already has one of these per branch\n  branchPullRequests: 2,\n};\n\n/**\n * Convert the changed files of a pull request, as listed by the GraphQL API, to workflow files.\n * @param {{ path: string, changeType: string }[]} nodes File nodes.\n * @returns {WorkflowFile[]} Files.\n */\nexport const parseFileNodes = (nodes) =>\n  nodes.map(({ path, changeType }) => ({\n    path,\n    sha: '',\n    size: 0,\n    deleted: changeType === 'DELETED',\n    // The previous path of a renamed file isn’t available here; it’s filled in by\n    // {@link fetchPullRequestFileList}\n    renamed: changeType === 'RENAMED',\n  }));\n\n/**\n * Re-fetch the list of files changed in the given pull request with the REST API, which is the only\n * one that reports the path a renamed file had before. The GraphQL API used by\n * `fetchPullRequests()` has a `RENAMED` change type but no matching previous-path field, so\n * this is called only for a pull request that contains a rename. The response is much larger,\n * because it embeds a `patch` for every file and that can’t be turned off.\n * @param {WorkflowPullRequest} pullRequest Pull request to complete.\n * @see https://docs.github.com/en/rest/pulls/pulls#list-pull-requests-files\n */\nexport const fetchPullRequestFileList = async (pullRequest) => {\n  const files = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(\n      `${getPullRequestPath(repository, pullRequest.number)}/files?per_page=${MAX_ITEMS.files}`,\n    )\n  );\n\n  pullRequest.files = parseRestFiles(files, { removedStatus: 'removed' });\n};\n\n/**\n * Number of changed files whose content is requested per GraphQL query. With up to 100 files in\n * each of up to 100 pull requests, asking for all of them at once could exceed the API’s limits.\n */\nconst FILES_CHUNK_SIZE = 100;\n\n/**\n * Fetch the content of the files changed in the given pull requests, and populate the\n * {@link WorkflowFile} objects in place. Binary files, such as images, are skipped; only their blob\n * metadata is stored. The files are read at the pull request’s head commit rather than its branch,\n * so the content shown is that of the commit a publish is pinned to, even if the branch moves on\n * while the board loads.\n * @param {WorkflowPullRequest[]} pullRequests Pull requests to complete.\n */\nexport const fetchPullRequestFiles = async (pullRequests) => {\n  /** @type {{ pullRequest: WorkflowPullRequest, file: WorkflowFile }[]} */\n  const targets = [];\n\n  pullRequests.forEach((pullRequest) => {\n    pullRequest.files.forEach((file) => {\n      if (!file.deleted) {\n        targets.push({ pullRequest, file });\n      }\n    });\n  });\n\n  if (!targets.length) {\n    return;\n  }\n\n  const workflowRepository = getContentRepository();\n\n  const blobs = await fetchAliasedBatch({\n    items: targets,\n    alias: 'file',\n    /**\n     * Build the field selection for a changed file on its pull request branch.\n     * @param {{ pullRequest: WorkflowPullRequest, file: WorkflowFile }} target Target.\n     * @returns {string} Field selection.\n     */\n    getFragment: ({ pullRequest: { headSHA, branch }, file }) => `\n      object(expression: ${JSON.stringify(`${headSHA ?? branch}:${file.path}`)}) {\n        ... on Blob {\n          oid\n          byteSize\n          isBinary\n          isTruncated\n          text\n        }\n      }\n    `,\n    chunkSize: FILES_CHUNK_SIZE,\n    variables: workflowRepository,\n  });\n\n  /** @type {WorkflowFile[]} */\n  const truncatedFiles = [];\n\n  targets.forEach(({ file }, index) => {\n    const blob = blobs[index];\n\n    if (blob) {\n      Object.assign(file, {\n        sha: blob.oid,\n        size: blob.byteSize,\n        text: blob.isBinary ? undefined : (blob.text ?? undefined),\n      });\n\n      if (!blob.isBinary && blob.isTruncated) {\n        truncatedFiles.push(file);\n      }\n    } else {\n      // The file may have been removed from the branch in the meantime\n      file.deleted = true;\n    }\n  });\n\n  // The GraphQL API cuts `Blob.text` off at 512 KB, so read any oversized blob again with the REST\n  // API, which returns it in full. @see https://github.com/sveltia/sveltia-cms/issues/950\n  await runConcurrently(truncatedFiles, async (file) => {\n    file.text = await fetchBlobText({ ...workflowRepository, sha: file.sha });\n  });\n};\n\nconst FETCH_BRANCH_HEAD_QUERY = `\n  query($owner: String!, $repo: String!, $branch: String!) {\n    repository(owner: $owner, name: $repo) {\n      branchHead: ref(qualifiedName: $branch) {\n        target {\n          oid\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Fetch the commit the given workflow branch points at. Two editors working on the same entry\n * share its branch, so this is how a save finds out that someone else has committed to it since\n * the draft was opened. The branch is looked up in the repository it lives in, which is the\n * contributor’s fork with Open Authoring, or when a maintainer edits a contributor’s pull request.\n * @param {string} branch Branch name.\n * @returns {Promise<string | undefined>} Git object ID, or `undefined` if the branch is gone,\n * which is what a merged or closed pull request leaves behind.\n * @see https://docs.github.com/en/graphql/reference/objects#ref\n */\nexport const fetchBranchHead = async (branch) => {\n  const { owner, repo, branch: name } = getBranchRepository(branch);\n\n  const { repository: result } = /** @type {{ repository: Record<string, any> }} */ (\n    await fetchGraphQL(FETCH_BRANCH_HEAD_QUERY, { owner, repo, branch: `refs/heads/${name}` })\n  );\n\n  return result?.branchHead?.target?.oid;\n};\n\n/**\n * Delete the given branch. Failures are ignored, as the branch may already have been deleted by the\n * repository’s automatic head branch deletion setting.\n * @param {string} branch Branch name.\n * @see https://docs.github.com/en/rest/git/refs#delete-a-reference\n */\nexport const deleteBranch = async (branch) => {\n  const repoPath = getRepositoryPath(getWorkflowRepository());\n\n  await deleteRemoteBranch({\n    branch,\n    path: `${repoPath}/git/refs/heads/${encodePathSegments(branch)}`,\n    // GitHub answers a missing reference with a 422 rather than a 404\n    goneStatuses: [404, 422],\n  });\n};\n\n/**\n * Replace the CMS-managed status label on a pull request while preserving any other label.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {WorkflowStatus} status New status.\n * @see https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request\n * @see https://docs.github.com/en/rest/issues/issues#update-an-issue\n */\nexport const updateLabels = async (pullRequest, status) => {\n  // Read the labels from the pulls endpoint: the issues endpoint's `GET` needs issue access, which\n  // a fine-grained token created from the token page doesn't have, while its `PATCH` also accepts\n  // pull request access. @see https://github.com/sveltia/sveltia-cms/issues/1014\n  const { labels = [] } = /** @type {{ labels?: { name: string }[] }} */ (\n    await fetchAPI(getPullRequestPath(repository, pullRequest.number))\n  );\n\n  const newLabels = replaceStatusLabel(\n    labels.map(({ name }) => name),\n    status,\n  );\n\n  await fetchAPI(`${getRepositoryPath(repository)}/issues/${pullRequest.number}`, {\n    method: 'PATCH',\n    body: { labels: newLabels },\n  });\n};\n\n/**\n * Parse the user who opened a pull request, as the REST or GraphQL API returns it. The REST API\n * gives the ID as `id` and leaves out the name and email address, while the GraphQL API gives the\n * ID as `databaseId` and, unless the user keeps them private, the name and email address.\n * @param {Record<string, any> | undefined} user User object.\n * @returns {CommitAuthor | undefined} Author, or `undefined` if the user is unknown.\n */\nexport const parseAuthor = (user) => {\n  const { id = user?.databaseId } = user ?? {};\n\n  return toCommitAuthor({ ...user, id });\n};\n\n/**\n * Convert a pull request to a draft, or mark it ready for review. The REST API cannot toggle the\n * draft state, so the GraphQL API is used here.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {boolean} isDraft Whether the pull request should be a draft.\n * @see https://docs.github.com/en/graphql/reference/mutations#convertpullrequesttodraft\n * @see https://docs.github.com/en/graphql/reference/mutations#markpullrequestreadyforreview\n */\nexport const updateDraftState = async (pullRequest, isDraft) => {\n  const mutation = isDraft ? 'convertPullRequestToDraft' : 'markPullRequestReadyForReview';\n\n  await fetchGraphQL(\n    `\n      mutation($input: ${isDraft ? 'ConvertPullRequestToDraftInput' : 'MarkPullRequestReadyForReviewInput'}!) {\n        ${mutation}(input: $input) {\n          pullRequest {\n            isDraft\n          }\n        }\n      }\n    `,\n    { input: { pullRequestId: pullRequest.nodeId } },\n  );\n};\n\n/**\n * Create a new pull request for the given workflow branch. The pull request is created as a draft,\n * because a newly saved entry always starts with the `draft` status.\n * @param {object} args Arguments.\n * @param {string} args.branch Workflow branch name.\n * @param {string} args.title Pull request title.\n * @param {WorkflowStatus} args.status Status to open the pull request with.\n * @param {string} args.description Pull request description.\n * @returns {Promise<WorkflowPullRequest>} Created pull request.\n * @see https://docs.github.com/en/rest/pulls/pulls#create-a-pull-request\n * @see https://docs.github.com/en/rest/issues/labels#add-labels-to-an-issue\n */\nexport const createPullRequest = async ({ branch, title, status, description }) => {\n  const { branch: baseBranch } = repository;\n  const repoPath = getRepositoryPath(repository);\n  const fork = forkedRepository.current;\n\n  /**\n   * Open the pull request.\n   * @param {boolean} [maintainerCanModify] Whether to let the maintainers push to its branch.\n   * @returns {Promise<Record<string, any>>} Pull request.\n   */\n  const open = async (maintainerCanModify) =>\n    /** @type {Record<string, any>} */ (\n      await fetchAPI(`${repoPath}/pulls`, {\n        method: 'POST',\n        body: {\n          title,\n          // A cross-repository pull request identifies its head branch by the fork’s owner\n          head: fork ? `${fork.owner}:${branch}` : branch,\n          base: baseBranch,\n          draft: status === 'draft',\n          body: description,\n          ...(maintainerCanModify ? { maintainer_can_modify: true } : {}),\n        },\n      })\n    );\n\n  /**\n   * Open a contributor’s pull request, letting the maintainers push to its branch, as GitHub’s own\n   * form does by default, so they can edit the entry in the CMS while reviewing it rather than only\n   * view it. GitHub refuses that for a fork owned by an organization, which gets the pull request\n   * without it instead.\n   * @returns {Promise<Record<string, any>>} Pull request.\n   */\n  const openFromFork = async () => {\n    try {\n      return await open(true);\n    } catch (/** @type {any} */ ex) {\n      if (ex.cause?.status !== 422) {\n        throw ex;\n      }\n\n      return open();\n    }\n  };\n\n  const result = await (fork ? openFromFork() : open());\n\n  const pullRequest = parseRestPullRequest(result, {\n    nodeId: result.node_id,\n    title: result.title,\n    branch,\n    status,\n    // The signed-in user, which is how a later save recognizes the pull request as their own\n    author: parseAuthor(result.user),\n    description,\n  });\n\n  // Labelling an issue requires write access to the repository, which an Open Authoring contributor\n  // doesn’t have. Their status is read from the pull request itself instead\n  if (!fork) {\n    // A brand-new pull request has no label to preserve, so add the status label outright rather\n    // than reading the current list first like {@link updateLabels} has to\n    await fetchAPI(`${repoPath}/issues/${result.number}/labels`, {\n      method: 'POST',\n      body: { labels: [getStatusLabel(status)] },\n    });\n  }\n\n  return pullRequest;\n};\n","import { getWorkflowRepository } from '$lib/services/backends/git/github/fork';\nimport { fetchAliasedBatch } from '$lib/services/backends/git/github/graphql';\nimport {\n  createPullRequest,\n  deleteBranch,\n  fetchBranchHead,\n  fetchPullRequestFileList,\n  fetchPullRequestFiles,\n  MAX_ITEMS,\n  parseFileNodes,\n  updateDraftState,\n} from '$lib/services/backends/git/github/pull-requests';\nimport { repository } from '$lib/services/backends/git/github/repository';\nimport { fetchAPI, fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { pruneForkBranches, updateForkStatusWith } from '$lib/services/backends/git/shared/fork';\nimport { parseRestFiles } from '$lib/services/backends/git/shared/pull-requests';\nimport { getRepositoryPath } from '$lib/services/backends/git/shared/repository';\nimport { applyForkPullRequestStatus } from '$lib/services/backends/git/shared/workflow';\nimport { user } from '$lib/services/user/account.svelte';\nimport { encodePathSegments } from '$lib/services/utils/url';\nimport { getBranchListPrefix } from '$lib/services/workflow/branch';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { ForkRequestState, WorkflowPullRequest, WorkflowStatus } from '$lib/types/private';\n */\n\n/**\n * Build the query to fetch the Editorial Workflow branches in the contributor’s fork, along with\n * the head commit of each one. With Open Authoring the branches are the source of truth: a draft\n * has no pull request yet, so listing pull requests alone would miss it.\n * @returns {string} GraphQL query.\n * @see https://docs.github.com/en/graphql/reference/objects#ref\n */\nconst getFetchForkBranchesQuery = () => `\n  query($owner: String!, $repo: String!, $prefix: String!) {\n    repository(owner: $owner, name: $repo) {\n      refs(refPrefix: $prefix, first: ${MAX_ITEMS.branches}) {\n        nodes {\n          name\n          target {\n            ... on Commit {\n              oid\n              message\n              committedDate\n              author {\n                name\n                email\n                user {\n                  login\n                  databaseId\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Number of fork branches whose pull requests are looked up per GraphQL query. Each one carries\n * the file lists of its candidate pull requests, so a long list is split to keep a query within the\n * API’s limits.\n */\nconst BRANCH_PULL_REQUESTS_CHUNK_SIZE = 50;\n\n/**\n * Build the field selection to fetch the pull request the given fork branch has, if any. A ref in\n * the fork doesn’t report the pull requests opened from it against the configured repository, so\n * they’re looked up from that repository instead, matched by head branch name. The base branch is\n * matched as well: a pull request the contributor opened from the same branch to somewhere other\n * than the configured branch isn’t the one the CMS manages, and acting on it would relabel, rename\n * or close a request that isn’t the entry’s. The author is read too, as anyone can open a pull\n * request from a branch of a public fork.\n * @param {string} branch Branch name to look up.\n * @returns {string} Field selection on the `Repository` type.\n * @see https://docs.github.com/en/graphql/reference/objects#repository\n */\nconst getForkPullRequestsFragment = (branch) => `\n  pullRequests(\n    headRefName: ${JSON.stringify(branch)}\n    baseRefName: ${JSON.stringify(repository.branch)}\n    states: [OPEN, CLOSED, MERGED]\n    first: ${MAX_ITEMS.branchPullRequests}\n    orderBy: { field: CREATED_AT, direction: DESC }\n  ) {\n    nodes {\n      id\n      number\n      title\n      url\n      state\n      isDraft\n      createdAt\n      updatedAt\n      headRefOid\n      headRepositoryOwner {\n        login\n      }\n      author {\n        login\n      }\n      files(first: ${MAX_ITEMS.files}) {\n        nodes {\n          path\n          changeType\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Check whether the given pull request is one the CMS manages for the contributor: opened by them,\n * from the fork the CMS is working in. The configured repository can have a branch of the same\n * name, whose pull request isn’t the contributor’s. Nor is one someone else opened from the\n * contributor’s branch: it would put their title on the entry, and the contributor can’t convert,\n * reopen or close it, nor open their own while it’s open.\n * @param {Record<string, any>} pr Pull request node.\n * @returns {boolean} Result.\n */\nconst isForkPullRequest = (pr) => {\n  const login = user.account?.login?.toLowerCase();\n\n  return (\n    pr.headRepositoryOwner?.login === forkedRepository.current?.owner &&\n    !!login &&\n    pr.author?.login?.toLowerCase() === login\n  );\n};\n\n/**\n * Fetch the pull request each of the given fork branches has on the configured repository.\n * @param {string[]} branches Branch names to look up.\n * @returns {Promise<Map<string, Record<string, any>>>} Map of branch name to the most recent pull\n * request opened from it, where there is one.\n */\nexport const fetchForkBranchPullRequests = async (branches) => {\n  /** @type {Map<string, Record<string, any>>} */\n  const map = new Map();\n\n  if (!branches.length) {\n    return map;\n  }\n\n  const results = await fetchAliasedBatch({\n    items: branches,\n    alias: 'pr',\n    getFragment: getForkPullRequestsFragment,\n    chunkSize: BRANCH_PULL_REQUESTS_CHUNK_SIZE,\n  });\n\n  branches.forEach((branch, index) => {\n    const [node] = (results[index]?.nodes ?? []).filter(isForkPullRequest);\n\n    if (node) {\n      map.set(branch, node);\n    }\n  });\n\n  return map;\n};\n\n/**\n * Parse a branch node returned by {@link getFetchForkBranchesQuery}.\n * @param {Record<string, any>} node Ref node.\n * @param {string} branch Full branch name.\n * @param {Record<string, any>} [pullRequest] Pull request opened from the branch, from\n * {@link fetchForkBranchPullRequests}.\n * @returns {WorkflowPullRequest} Parsed branch. A branch that turns out to hold nothing is dropped\n * later, by {@link fetchForkPullRequests}, once its file list is known.\n */\nexport const parseForkBranch = (node, branch, pullRequest) => {\n  const { message, committedDate, author } = node.target ?? {};\n  // A merged pull request is finished with. Either the branch is simply left over, in which case\n  // comparing it with the configured branch turns up nothing and it drops off the board, or the\n  // contributor has edited the entry again since the merge, which makes it a fresh draft. Carrying\n  // the merged pull request forward would instead try to reopen it when the entry moves to review\n  const current = pullRequest?.state === 'MERGED' ? undefined : pullRequest;\n  const { login, databaseId } = author?.user ?? {};\n  const isOpen = current?.state === 'OPEN';\n  // A closed pull request is treated the same as none at all: the contributor took the entry back\n  // to the drafting stage, and moving it forward again reopens the request\n  const inReview = isOpen && !current.isDraft;\n\n  return {\n    number: current?.number,\n    nodeId: current?.id,\n    // Without a pull request there’s no title to show, so the head commit’s message stands in. It’s\n    // the message the pull request would be opened with anyway\n    title: current?.title ?? message ?? '',\n    url: current?.url,\n    branch,\n    // The branch head, rather than the pull request’s: a save compares it with the branch to find\n    // out whether anything has been committed since, and a closed pull request’s head is stale\n    headSHA: node.target?.oid,\n    status: inReview ? 'pending_review' : 'draft',\n    createdDate: new Date(current?.createdAt ?? committedDate),\n    updatedDate: new Date(current?.updatedAt ?? committedDate),\n    author: author?.name\n      ? { name: author.name, email: author.email ?? '', id: databaseId, login }\n      : undefined,\n    // An open pull request already reports the files it changes, which saves comparing the branch\n    // with the configured branch to work them out. The comparison is the only way to get them for a\n    // branch without one, but it answers with a diff of every file, so it’s worth avoiding where\n    // the paths are already at hand. A closed pull request is left to the comparison as well: its\n    // diff is no longer a reliable account of a branch that has moved on since\n    files: isOpen ? parseFileNodes(current.files?.nodes ?? []) : [],\n  };\n};\n\n/**\n * Fetch the Editorial Workflow branches in the contributor’s fork.\n * @returns {Promise<WorkflowPullRequest[]>} Branches, with their pull requests where they have one.\n */\nexport const fetchForkBranches = async () => {\n  const { owner, repo } = getWorkflowRepository();\n  const prefix = getBranchListPrefix();\n\n  const { repository: result } = /** @type {{ repository: Record<string, any> }} */ (\n    await fetchGraphQL(getFetchForkBranchesQuery(), {\n      owner,\n      repo,\n      prefix: `refs/heads/${prefix}`,\n    })\n  );\n\n  const nodes = /** @type {Record<string, any>[]} */ (result?.refs?.nodes ?? []);\n\n  // The list isn’t paginated, and refs come back in alphabetical order, so going over the cap drops\n  // an arbitrary set of branches from the board. Rare enough to leave unpaged, too confusing to\n  // leave unsaid\n  if (nodes.length === MAX_ITEMS.branches) {\n    // eslint-disable-next-line no-console\n    console.warn(\n      `Only the first ${MAX_ITEMS.branches} Editorial Workflow branches in the fork are listed. ` +\n        'Publish or discard some entries to see the rest.',\n    );\n  }\n\n  const branches = nodes.map(({ name }) => `${prefix}${name}`);\n  const pullRequests = await fetchForkBranchPullRequests(branches);\n\n  return pruneForkBranches(\n    nodes,\n    (node, index) => {\n      const branch = branches[index];\n      const pullRequest = pullRequests.get(branch);\n\n      return pullRequest?.state === 'MERGED' && pullRequest.headRefOid === node.target?.oid\n        ? { leftover: branch }\n        : { pending: parseForkBranch(node, branch, pullRequest) };\n    },\n    deleteBranch,\n  );\n};\n\n/**\n * Fetch the files a fork branch changes, and populate the `WorkflowFile` objects in place.\n * A draft has no pull request to list files from, so the branch is compared with the configured\n * branch instead. The comparison also reports the path a renamed file came from.\n * @param {WorkflowPullRequest} pullRequest Branch to complete.\n * @see https://docs.github.com/en/rest/commits/commits#compare-two-commits\n */\nexport const fetchForkBranchFileList = async (pullRequest) => {\n  const { branch: baseBranch } = repository;\n  // A comparison across repositories identifies the head branch by the fork’s owner\n  const { owner: headOwner } = getWorkflowRepository();\n  const base = encodePathSegments(/** @type {string} */ (baseBranch));\n  const head = `${encodeURIComponent(headOwner)}:${encodePathSegments(pullRequest.branch)}`;\n\n  const { files = [] } = /** @type {{ files?: Record<string, any>[] }} */ (\n    await fetchAPI(\n      `${getRepositoryPath(repository)}/compare/${base}...${head}?per_page=${MAX_ITEMS.files}`,\n    )\n  );\n\n  pullRequest.files = parseRestFiles(files, { removedStatus: 'removed' });\n};\n\n/**\n * Fetch the unpublished entries of an Open Authoring contributor, which live in their fork.\n * @returns {Promise<WorkflowPullRequest[]>} Branches, with their pull requests and changed files.\n */\nexport const fetchForkPullRequests = async () => {\n  const branches = await fetchForkBranches();\n\n  // Only a branch whose files {@link parseForkBranch} couldn’t read off an open pull request has to\n  // be compared with the configured branch\n  await runConcurrently(\n    branches.filter(({ files }) => !files.length),\n    fetchForkBranchFileList,\n  );\n\n  // The comparison reports the path a renamed file came from, but the pull request’s own file list\n  // doesn’t, so those branches need the same follow-up request as the regular flow\n  await runConcurrently(\n    branches.filter(({ files }) => files.some(({ renamed }) => renamed)),\n    fetchPullRequestFileList,\n  );\n\n  // A branch that no longer differs from the configured branch holds nothing to publish. That’s\n  // what a branch left behind by a squash-merged pull request looks like\n  const pending = branches.filter(({ files }) => files.length);\n\n  await fetchPullRequestFiles(pending);\n\n  return pending;\n};\n\nconst FETCH_PULL_REQUEST_STATE_QUERY = `\n  query($id: ID!) {\n    node(id: $id) {\n      ... on PullRequest {\n        state\n        isDraft\n        baseRefName\n        headRefOid\n        headRepositoryOwner {\n          login\n        }\n        author {\n          login\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Read the current state of the pull request an Open Authoring entry has, for\n * {@link updateForkStatusWith}.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<ForkRequestState | undefined>} State, or `undefined` if the pull request can’t\n * be found, in which case the entry carries on with what it knows.\n */\nconst fetchForkRequestState = async ({ nodeId }) => {\n  const { node } = /** @type {{ node?: Record<string, any> }} */ (\n    await fetchGraphQL(FETCH_PULL_REQUEST_STATE_QUERY, { id: nodeId })\n  );\n\n  if (!node) {\n    return undefined;\n  }\n\n  return {\n    merged: node.state === 'MERGED',\n    isEntryRequest: node.baseRefName === repository.branch && isForkPullRequest(node),\n    /**\n     * Read the head commit the pull request was merged at.\n     * @returns {Promise<string>} Commit SHA.\n     */\n    getMergedSHA: async () => node.headRefOid,\n    state: node.state,\n    draft: node.isDraft,\n  };\n};\n\n/**\n * Bring a pull request in line with the given status, for {@link updateForkStatusWith}.\n * @param {Parameters<typeof applyForkPullRequestStatus>[0]} args Arguments.\n * @returns {Promise<void>}\n */\nconst applyForkStatus = (args) =>\n  applyForkPullRequestStatus(args, { repository, updateDraftState });\n\n/**\n * Move an Open Authoring entry between the drafting and review stages. A contributor can’t label a\n * pull request on a repository they don’t have access to, so the stage is recorded in the pull\n * request itself: a draft is a branch with no pull request, or one that’s still a GitHub draft,\n * while an entry in review has a pull request waiting for a maintainer.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {WorkflowStatus} status New status.\n * @returns {Promise<WorkflowPullRequest>} Updated pull request, or a new one if the known one is no\n * longer the entry’s.\n * @throws {Error} When the entry is being marked ready to publish, which a contributor can’t do, or\n * has been published since the board was loaded: see {@link updateForkStatusWith}.\n */\nexport const updateForkStatus = async (pullRequest, status) =>\n  updateForkStatusWith({\n    pullRequest,\n    status,\n    requestKey: 'nodeId',\n    createRequest: createPullRequest,\n    fetchRequest: fetchForkRequestState,\n    applyStatus: applyForkStatus,\n    fetchBranchHead,\n    deleteBranch,\n  });\n","import { sleep } from '@sveltia/utils/misc';\n\n/**\n * Fetch results page by page, following the cursor each page returns, until a page has no next\n * cursor or the given number of pages is reached. Wait for a bit between pages to avoid hitting the\n * API rate limit, unless told otherwise.\n * @template T Result type.\n * @template C Cursor type, such as a continuation token, a URL or a page number.\n * @param {(cursor: C | undefined) => Promise<{ results: T[], next?: C | null }>} fetchPage\n * Function to fetch a page of results, given the cursor returned by the previous page, which is\n * `undefined` for the first page. The returned `next` cursor is empty on the last page.\n * @param {object} [options] Options.\n * @param {number} [options.maxPages] Maximum number of pages to fetch. Default: 10.\n * @param {number} [options.delay] Milliseconds to wait between pages, or `0` not to wait.\n * Default: 50.\n * @returns {Promise<{ results: T[], complete: boolean }>} Results of all the fetched pages, and\n * whether they are all of them: `false` if the reading stopped at the maximum number of pages while\n * another page followed.\n */\nexport const readPages = async (fetchPage, { maxPages = 10, delay = 50 } = {}) => {\n  /** @type {T[]} */\n  const results = [];\n  /** @type {C | undefined} */\n  let cursor;\n\n  for (let page = 1; page <= maxPages; page += 1) {\n    // eslint-disable-next-line no-await-in-loop\n    const { results: pageResults, next } = await fetchPage(cursor);\n\n    results.push(...pageResults);\n\n    if (!next) {\n      return { results, complete: true };\n    }\n\n    cursor = next;\n\n    // Wait for a bit before requesting the next page\n    if (delay && page < maxPages) {\n      // eslint-disable-next-line no-await-in-loop\n      await sleep(delay);\n    }\n  }\n\n  return { results, complete: false };\n};\n\n/**\n * Fetch results page by page: see {@link readPages}.\n * @template T Result type.\n * @template C Cursor type, such as a continuation token, a URL or a page number.\n * @param {(cursor: C | undefined) => Promise<{ results: T[], next?: C | null }>} fetchPage\n * Function to fetch a page of results.\n * @param {object} [options] Options.\n * @param {number} [options.maxPages] Maximum number of pages to fetch. Default: 10.\n * @param {number} [options.delay] Milliseconds to wait between pages. Default: 50.\n * @returns {Promise<T[]>} Results of all the fetched pages.\n */\nexport const fetchPages = async (fetchPage, options) =>\n  (await readPages(fetchPage, options)).results;\n\n/**\n * Fetch results by page number, starting at 1, until a page comes back with fewer results than the\n * page size, which marks it as the last one: see {@link readPages}. This suits a REST API that\n * pages a list without saying how many pages there are.\n * @template T Result type.\n * @param {(page: number) => Promise<T[]>} fetchPage Function to fetch the results of a page.\n * @param {object} options Options.\n * @param {number} options.pageSize Number of results a full page holds.\n * @param {number} [options.maxPages] Maximum number of pages to fetch. Default: 10.\n * @param {number} [options.delay] Milliseconds to wait between pages. Default: 50.\n * @returns {Promise<{ results: T[], complete: boolean }>} Results of all the fetched pages, and\n * whether they are all of them.\n */\nexport const readNumberedPages = (fetchPage, { pageSize, ...options }) =>\n  readPages(async (/** @type {number | undefined} */ page = 1) => {\n    const results = await fetchPage(page);\n\n    return { results, next: results.length < pageSize ? undefined : page + 1 };\n  }, options);\n","import { mergeRefusedPullRequest } from '$lib/services/backends/git/github/auto-merge';\nimport { commitChanges } from '$lib/services/backends/git/github/commits';\nimport {\n  getBranchRepository,\n  getWorkflowRepository,\n  isOpenAuthoringConfigured,\n} from '$lib/services/backends/git/github/fork';\nimport { fetchAliasedBatch } from '$lib/services/backends/git/github/graphql';\nimport {\n  createPullRequest,\n  deleteBranch,\n  fetchBranchHead,\n  fetchPullRequestFileList,\n  fetchPullRequestFiles,\n  MAX_ITEMS,\n  parseAuthor,\n  parseFileNodes,\n  updateDraftState,\n  updateLabels,\n} from '$lib/services/backends/git/github/pull-requests';\nimport { repository } from '$lib/services/backends/git/github/repository';\nimport {\n  fetchForkPullRequests,\n  updateForkStatus,\n} from '$lib/services/backends/git/github/workflow-fork';\nimport { fetchAPI, fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { checkPublishAllowed, toForkPullRequest } from '$lib/services/backends/git/shared/fork';\nimport {\n  getPullRequestPath,\n  getRepositoryPath,\n  isSameRepository,\n} from '$lib/services/backends/git/shared/repository';\nimport {\n  approvePullRequest,\n  createBranchGoneError,\n  discardPullRequest,\n  findOwnApprovals,\n  getParentDirs,\n  isSquashMergeEnabled,\n  resolveMergeState,\n  saveWorkflowBranch,\n  toChangedFilesWithModes,\n  updateLabelledStatus,\n  updatePullRequestDescription,\n} from '$lib/services/backends/git/shared/workflow';\nimport { readNumberedPages } from '$lib/services/utils/paging';\nimport { encodePathSegments } from '$lib/services/utils/url';\nimport { getAllStatusLabels, getStatusFromLabels } from '$lib/services/workflow/labels';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * CommitOptions,\n * CommitResults,\n * FileChange,\n * WorkflowPullRequest,\n * WorkflowSaveOptions,\n * WorkflowChangedFile,\n * WorkflowMergeState,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Get the fields to read from a pull request node, as {@link toPullRequest} expects them.\n * @returns {string} Field selection on the `PullRequest` type.\n */\nconst getPullRequestFields = () => `\n  id\n  number\n  title\n  url\n  body\n  isDraft\n  isCrossRepository\n  baseRefName\n  createdAt\n  updatedAt\n  headRefName\n  headRefOid\n  author {\n    login\n    avatarUrl\n    ... on User {\n      name\n      email\n      databaseId\n    }\n  }\n  labels(first: ${MAX_ITEMS.labels}) {\n    nodes {\n      name\n    }\n  }\n  files(first: ${MAX_ITEMS.files}) {\n    nodes {\n      path\n      changeType\n    }\n  }\n`;\n\n/**\n * Build the selection to fetch the open pull requests to the configured branch that may come from\n * Open Authoring contributors. A contributor can’t label a pull request on the configured\n * repository, so these are matched by base branch rather than by label, and the ones from forks\n * picked out by {@link parseForkPullRequest}. The repository’s own pull requests share the item\n * cap, so a busy repository can crowd the oldest contributions out.\n * @returns {string} Field selection on the `Repository` type.\n */\nconst getForkPullRequestsSelection = () => `\n  forkPullRequests: pullRequests(\n    states: OPEN\n    baseRefName: ${JSON.stringify(repository.branch)}\n    first: ${MAX_ITEMS.pullRequests}\n    orderBy: { field: UPDATED_AT, direction: DESC }\n  ) {\n    nodes {\n      ${getPullRequestFields()}\n      maintainerCanModify\n      headRepository {\n        name\n        owner {\n          login\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Build the query to fetch the open pull requests along with their labels and changed file paths.\n * The status labels are matched by the API rather than by {@link parsePullRequest}, so the item cap\n * applies to the CMS’s own pull requests instead of the repository’s most recently updated ones,\n * which could otherwise push the unpublished entries out of the result. The filter matches a pull\n * request carrying any of the labels, not all of them.\n * @param {object} [options] Options.\n * @param {boolean} [options.withForks] Whether to also fetch the pull requests to the configured\n * branch that may come from Open Authoring contributors.\n * @returns {string} GraphQL query.\n * @see https://docs.github.com/en/graphql/reference/objects#pullrequest\n */\nconst getFetchPullRequestsQuery = ({ withForks = false } = {}) => `\n  query($owner: String!, $repo: String!) {\n    repository(owner: $owner, name: $repo) {\n      pullRequests(\n        states: OPEN\n        labels: ${JSON.stringify(getAllStatusLabels())}\n        first: ${MAX_ITEMS.pullRequests}\n        orderBy: { field: UPDATED_AT, direction: DESC }\n      ) {\n        nodes {\n          ${getPullRequestFields()}\n        }\n      }\n      ${withForks ? getForkPullRequestsSelection() : ''}\n    }\n  }\n`;\n\n/**\n * Convert a pull request node returned by the GraphQL API to a workflow pull request.\n * @param {Record<string, any>} node Pull request node.\n * @param {WorkflowStatus} status Status of the pull request.\n * @returns {WorkflowPullRequest} Pull request.\n */\nconst toPullRequest = (node, status) => ({\n  number: node.number,\n  nodeId: node.id,\n  title: node.title,\n  url: node.url,\n  branch: node.headRefName,\n  headSHA: node.headRefOid,\n  status,\n  createdDate: new Date(node.createdAt),\n  updatedDate: new Date(node.updatedAt),\n  author: parseAuthor(node.author),\n  files: parseFileNodes(node.files?.nodes ?? []),\n  description: node.body ?? '',\n});\n\n/**\n * Get the names of the labels on a pull request node returned by the GraphQL API.\n * @param {Record<string, any>} node Pull request node.\n * @returns {string[]} Label names.\n */\nconst getLabelNames = (node) => node.labels.nodes.map((/** @type {any} */ l) => l.name);\n\n/**\n * Parse a pull request node returned by the GraphQL API.\n * @param {Record<string, any>} node Pull request node.\n * @returns {WorkflowPullRequest | undefined} Parsed pull request, or `undefined` if the pull\n * request is not managed by the CMS.\n */\nexport const parsePullRequest = (node) => {\n  // A pull request from a fork belongs to an Open Authoring contributor. It’s left to\n  // {@link parseForkPullRequest}, which treats it as untrusted: taken here because a maintainer\n  // labelled it, it would pass for one of the CMS’s own, with a branch name that could be mistaken\n  // for one in the configured repository, and could be published from the CMS\n  if (node.isCrossRepository) {\n    return undefined;\n  }\n\n  // A pull request to a branch other than the configured one isn’t the CMS’s either, whatever\n  // label it carries: one whose base branch was changed on GitHub after the CMS opened it, or one\n  // labelled by hand. Listing it would put a card on the board that moves the label on someone\n  // else’s request, and publishes the entry by merging it into that other branch\n  if (node.baseRefName !== repository.branch) {\n    return undefined;\n  }\n\n  const status = getStatusFromLabels(getLabelNames(node));\n\n  if (!status) {\n    return undefined;\n  }\n\n  return toPullRequest(node, status);\n};\n\n/**\n * Parse a pull request node returned by {@link getForkPullRequestsSelection}, for a maintainer to\n * review. See {@link toForkPullRequest}.\n * @param {Record<string, any>} node Pull request node.\n * @returns {WorkflowPullRequest | undefined} Parsed pull request, or `undefined` if it isn’t one a\n * contributor opened from their fork for an entry.\n */\nexport const parseForkPullRequest = (node) => {\n  const { owner, name: repo } = node.headRepository ?? {};\n\n  // A pull request whose fork has been deleted has no branch left to read or push to\n  if (!node.isCrossRepository || node.baseRefName !== repository.branch || !owner?.login || !repo) {\n    return undefined;\n  }\n\n  return toForkPullRequest(\n    {\n      owner: owner.login,\n      repo,\n      headBranch: node.headRefName,\n      editable: !!node.maintainerCanModify,\n      draft: !!node.isDraft,\n      labels: getLabelNames(node),\n    },\n    ({ status }) => toPullRequest(node, status),\n  );\n};\n\n/**\n * Fetch all the open pull requests on the configured repository that carry a CMS status label,\n * along with the changed files. This is the regular flow, used by anyone who can write to the\n * repository; see {@link fetchForkPullRequests} for the Open Authoring one. With Open Authoring\n * turned on, the pull requests contributors have opened from their forks are listed as well, for\n * the maintainers to review.\n * @returns {Promise<WorkflowPullRequest[]>} Pull requests.\n */\nconst fetchLabelledPullRequests = async () => {\n  const { repository: result } = /** @type {{ repository: Record<string, any> }} */ (\n    await fetchGraphQL(getFetchPullRequestsQuery({ withForks: isOpenAuthoringConfigured() }))\n  );\n\n  const pullRequests = /** @type {WorkflowPullRequest[]} */ (\n    [\n      ...(result?.pullRequests?.nodes ?? []).map(parsePullRequest),\n      ...(result?.forkPullRequests?.nodes ?? []).map(parseForkPullRequest),\n    ].filter(Boolean)\n  );\n\n  // Only a pull request with a renamed file needs the heavier REST request, which is the sole\n  // source of the path the file had before\n  await runConcurrently(\n    pullRequests.filter(({ files }) => files.some(({ renamed }) => renamed)),\n    fetchPullRequestFileList,\n  );\n\n  await fetchPullRequestFiles(pullRequests);\n\n  return pullRequests;\n};\n\n/**\n * Fetch all the unpublished entries the signed-in user has in progress.\n * @returns {Promise<WorkflowPullRequest[]>} Pull requests.\n */\nexport const fetchPullRequests = async () =>\n  openAuthoring.current ? fetchForkPullRequests() : fetchLabelledPullRequests();\n\n/**\n * Query to fetch what the `createRef` mutation needs: the node ID of the repository the branch is\n * created in, and the head of the configured branch to start it from. With Open Authoring those are\n * two different repositories — the contributor’s fork and the configured one — because a fork that\n * has drifted would otherwise pass its own commits on to everything branched from it. A fork shares\n * an object store with its parent, so a commit that only exists upstream can still be branched from\n * in the fork. Whether the fork has its own copy of the branch, and the name of its default branch,\n * are fetched as well, for when GitHub refuses that: see {@link createBranch}.\n */\nconst FETCH_BRANCH_BASE_QUERY = `\n  query(\n    $forkOwner: String!\n    $forkRepo: String!\n    $owner: String!\n    $repo: String!\n    $branch: String!\n  ) {\n    fork: repository(owner: $forkOwner, name: $forkRepo) {\n      id\n      ref(qualifiedName: $branch) {\n        name\n      }\n      defaultBranchRef {\n        name\n      }\n    }\n    base: repository(owner: $owner, name: $repo) {\n      ref(qualifiedName: $branch) {\n        target {\n          oid\n        }\n      }\n    }\n  }\n`;\n\nconst CREATE_REF_MUTATION = `\n  mutation($input: CreateRefInput!) {\n    createRef(input: $input) {\n      ref {\n        name\n      }\n    }\n  }\n`;\n\n/**\n * Build the query to fetch the open pull requests from a branch of the given name. Pull requests\n * from forks can use the same branch name, e.g. Open Authoring contributors editing the same entry,\n * so fetch as many as allowed, or theirs could crowd out the one from this repository.\n * @returns {string} GraphQL query.\n */\nconst getFetchOpenPullRequestsQuery = () => `\n  query($owner: String!, $repo: String!, $branch: String!) {\n    repository(owner: $owner, name: $repo) {\n      pullRequests(headRefName: $branch, states: OPEN, first: ${MAX_ITEMS.pullRequests}) {\n        nodes {\n          number\n          isCrossRepository\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Fetch the open pull requests from the given branch of the configured repository, whichever\n * branch they go to. A pull request from a fork can have a head branch of the same name, but it\n * isn’t from this branch, so it’s left out.\n * @param {string} branch Branch name.\n * @returns {Promise<Record<string, any>[]>} Pull request nodes, with their `number`.\n */\nconst fetchOpenPullRequests = async (branch) => {\n  const { owner, repo } = repository;\n\n  const { repository: result } = /** @type {{ repository: Record<string, any> }} */ (\n    await fetchGraphQL(getFetchOpenPullRequestsQuery(), { owner, repo, branch })\n  );\n\n  return /** @type {Record<string, any>[]} */ (result?.pullRequests?.nodes ?? []).filter(\n    ({ isCrossRepository }) => !isCrossRepository,\n  );\n};\n\n/**\n * Point the given branch at the given commit, dropping whatever it held.\n * @param {string} branch Branch name.\n * @param {string} sha Git object ID.\n * @see https://docs.github.com/en/rest/git/refs#update-a-reference\n */\nconst resetBranch = async (branch, sha) => {\n  await fetchAPI(`${getRepositoryPath(repository)}/git/refs/heads/${encodePathSegments(branch)}`, {\n    method: 'PATCH',\n    body: { sha, force: true },\n  });\n};\n\n/**\n * Get the message GitHub gave for a failed GraphQL request, which comes as the error’s cause.\n * @param {any} error Error thrown by `fetchGraphQL`.\n * @returns {string} Message, or an empty string if there is none.\n */\nconst getErrorMessage = (error) => error.cause?.message ?? '';\n\n/**\n * Create a branch pointing at the given commit, without letting a failure propagate.\n * @param {string} repositoryId Node ID of the repository to create the branch in.\n * @param {string} branch Branch name.\n * @param {string} oid Git object ID.\n * @returns {Promise<any>} The error the mutation failed with, or `undefined` if it succeeded.\n */\nconst tryCreateRef = async (repositoryId, branch, oid) => {\n  try {\n    await fetchGraphQL(CREATE_REF_MUTATION, {\n      input: { repositoryId, name: `refs/heads/${branch}`, oid },\n    });\n\n    return undefined;\n  } catch (ex) {\n    return ex;\n  }\n};\n\n/**\n * Find the newest commit a branch of the Open Authoring fork has in common with the configured\n * branch, which is where the two diverged, or the fork branch’s head if it’s only behind.\n * @param {string} forkOwner Owner of the fork.\n * @param {string} forkBranch Branch in the fork.\n * @returns {Promise<string | undefined>} Git object ID, or `undefined` if it couldn’t be found.\n * @see https://docs.github.com/en/rest/commits/commits#compare-two-commits\n */\nconst fetchForkMergeBase = async (forkOwner, forkBranch) => {\n  const { branch } = repository;\n  const base = encodePathSegments(/** @type {string} */ (branch));\n  // A comparison across repositories identifies the head branch by the fork’s owner\n  const head = `${encodeURIComponent(forkOwner)}:${encodePathSegments(forkBranch)}`;\n\n  try {\n    const { merge_base_commit: mergeBase } = /** @type {Record<string, any>} */ (\n      await fetchAPI(`${getRepositoryPath(repository)}/compare/${base}...${head}?per_page=1`)\n    );\n\n    return mergeBase?.sha;\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Create a new branch pointing at the head of the configured branch. If the branch already exists,\n * which happens when an earlier pull request for the same entry left it behind, the error is\n * ignored. The GraphQL API is used rather than the REST one, because a failed mutation still\n * responds with HTTP 200, so the expected “already exists” case doesn’t show up in the browser\n * console as a failed request.\n * @param {string} branch Branch name.\n * @returns {Promise<{ headOid?: string }>} Git object ID the branch points at, which is missing if\n * the branch already existed in an Open Authoring fork and was kept as it was, in which case its\n * head is unknown and has to be looked up.\n * @throws {Error} When the branch exists and a pull request is open from it.\n * @see https://docs.github.com/en/graphql/reference/mutations#createref\n */\nexport const createBranch = async (branch) => {\n  const { repo } = repository;\n  // With Open Authoring the branch is created in the contributor’s fork, but starts from the head\n  // of the configured repository rather than the fork’s own copy of it, so a fork that has fallen\n  // behind or gained commits of its own doesn’t pass them on to the pull request, unless GitHub\n  // refuses that, as explained below\n  const { owner: forkOwner, repo: forkRepo } = getWorkflowRepository();\n\n  const { fork, base } = /** @type {Record<string, any>} */ (\n    await fetchGraphQL(FETCH_BRANCH_BASE_QUERY, { forkOwner, forkRepo })\n  );\n\n  if (!fork) {\n    throw createLocalizedError('Failed to create the branch.', 'repository_not_found', {\n      repo: forkRepo,\n    });\n  }\n\n  if (!base) {\n    throw createLocalizedError('Failed to create the branch.', 'repository_not_found', { repo });\n  }\n\n  if (!base.ref) {\n    throw createLocalizedError('Failed to create the branch.', 'branch_not_found', {\n      repo,\n      branch: repository.branch,\n    });\n  }\n\n  let sha = base.ref.target.oid;\n  let error = await tryCreateRef(fork.id, branch, sha);\n\n  // An OAuth token without the `workflow` scope can’t bring changes to GitHub Actions workflow\n  // files into a repository, which a branch starting upstream does when a fork that has fallen\n  // behind lacks the latest ones. GitHub then refuses the mutation for lack of permission, and the\n  // sync on sign-in has been refused for the same reason. The branch starts instead from where the\n  // fork’s own copy of the configured branch meets it, which the fork already has, so the pull\n  // request holds nothing but the entry. A fork has no copy of a branch created upstream after it\n  // was made, e.g. for a deploy preview, nor of any but the default branch if it was made with that\n  // alone, so its default branch stands in then\n  if (error && openAuthoring.current && /permission/i.test(getErrorMessage(error))) {\n    const forkBranch = fork.ref?.name ?? fork.defaultBranchRef?.name;\n    const mergeBase = forkBranch ? await fetchForkMergeBase(forkOwner, forkBranch) : undefined;\n\n    if (mergeBase && mergeBase !== sha) {\n      sha = mergeBase;\n      error = await tryCreateRef(fork.id, branch, sha);\n    }\n  }\n\n  if (error) {\n    const message = getErrorMessage(error);\n\n    // “A ref named ... already exists in the repository.” Anything else is a real failure\n    if (!message.includes('already exists')) {\n      throw new Error('Failed to create the branch.', {\n        cause: new Error(message || error.message),\n      });\n    }\n\n    // With Open Authoring a draft is a branch without a pull request, so there’s no telling a\n    // leftover from a live one; the branch is kept, and it shows up as a draft the next time the\n    // fork is listed. The fork is the contributor’s own, so nobody else’s work can be on it\n    if (openAuthoring.current) {\n      return {};\n    }\n\n    // A pull request open from the branch is one the board doesn’t show: it has lost its status\n    // label, it sits beyond the number of pull requests fetched, it goes to another branch, or it\n    // was never the CMS’s. Committing onto it would take whatever else it holds along with the\n    // entry, unseen, so the save is refused instead, and the branch is left alone\n    const [openPullRequest] = await fetchOpenPullRequests(branch);\n\n    if (openPullRequest) {\n      throw createLocalizedError(\n        'The workflow branch is in use by another pull request.',\n        'workflow.branch_in_use',\n        { number: `#${openPullRequest.number}` },\n      );\n    }\n\n    // The branch is left over from an earlier pull request for the same entry, which the CMS knows\n    // nothing about: one the maintainer merged without deleting the branch, or one that was closed\n    // on GitHub rather than discarded here, which leaves the branch behind. Starting the new pull\n    // request from the branch as it stands would carry that earlier work into it — a merged one\n    // adds nothing, but a closed one brings back what was thrown away — so the branch is reset to\n    // the head of the configured branch, the same as a freshly created one\n    await resetBranch(branch, sha);\n  }\n\n  return { headOid: sha };\n};\n\n/**\n * Update the pull request’s status label and draft state. A pull request in the `draft` status is\n * kept as a GitHub draft pull request, so it cannot be merged accidentally.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {WorkflowStatus} status New status.\n * @returns {Promise<WorkflowPullRequest>} Updated pull request.\n */\nexport const updateStatus = (pullRequest, status) =>\n  updateLabelledStatus(pullRequest, status, { updateForkStatus, updateLabels, updateDraftState });\n\n/**\n * Approve the pull request on behalf of the signed-in user, pinned to the head commit the entry was\n * reviewed at.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<void>}\n */\nexport const approve = (pullRequest) => approvePullRequest(repository, pullRequest, 'APPROVE');\n\n/**\n * Message a review is dismissed with when the entry is moved back from the ready stage.\n */\nconst WITHDRAWAL_MESSAGE = 'The entry is no longer ready to publish.';\n/**\n * Number of reviews to fetch per page, the most the REST API allows.\n */\nconst REVIEWS_PER_PAGE = 100;\n/**\n * Most pages of reviews to fetch, as a guard against a server that ignores the `page` parameter.\n */\nconst MAX_REVIEW_PAGES = 10;\n\n/**\n * Fetch the reviews of a pull request, up to {@link MAX_REVIEW_PAGES} pages. They’re listed oldest\n * first, so the signed-in user’s latest approval is on the last page of a pull request with many\n * reviews.\n * @param {string} path Path of the pull request’s reviews.\n * @returns {Promise<Record<string, any>[]>} Reviews.\n * @see https://docs.github.com/en/rest/pulls/reviews#list-reviews-for-a-pull-request\n */\nconst fetchReviews = async (path) =>\n  (\n    await readNumberedPages(\n      async (page) =>\n        /** @type {Record<string, any>[]} */ (\n          await fetchAPI(`${path}?per_page=${REVIEWS_PER_PAGE}&page=${page}`)\n        ),\n      { pageSize: REVIEWS_PER_PAGE, maxPages: MAX_REVIEW_PAGES, delay: 0 },\n    )\n  ).results;\n\n/**\n * Withdraw the signed-in user’s approval of the pull request. A submitted review can’t be deleted\n * on GitHub, so it’s dismissed instead, which a branch protection rule may restrict to some users.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @see https://docs.github.com/en/rest/pulls/reviews#dismiss-a-review-for-a-pull-request\n */\nexport const withdrawApproval = async (pullRequest) => {\n  const path = `${getPullRequestPath(repository, pullRequest.number)}/reviews`;\n  const reviews = await fetchReviews(path);\n\n  await Promise.all(\n    findOwnApprovals(reviews).map(({ id }) =>\n      fetchAPI(`${path}/${id}/dismissals`, {\n        method: 'PUT',\n        body: { message: WITHDRAWAL_MESSAGE, event: 'DISMISS' },\n      }),\n    ),\n  );\n};\n\n/**\n * Commit the given changes on a workflow branch that no pull request is known for, creating the\n * branch from the configured one first.\n * @param {FileChange[]} changes Changes to be committed.\n * @param {CommitOptions} options Commit options, with the workflow branch.\n * @returns {Promise<CommitResults>} Commit results.\n * @throws {Error} When the branch exists and a pull request is open from it.\n */\nconst commitToNewBranch = async (changes, options) => {\n  const { headOid } = await createBranch(/** @type {string} */ (options.branch));\n\n  return commitChanges(changes, { ...options, headOid });\n};\n\n/**\n * Commit the given changes onto the branch of an existing pull request, on top of the commit the\n * entry was loaded or saved at, which the conflict check has just compared with the branch, rather\n * than whatever the branch points at by the time the commit is made. A commit pushed in between\n * makes GitHub refuse the save, instead of being taken along unseen and vouched for by the head\n * recorded afterwards.\n * @param {FileChange[]} changes Changes to be committed.\n * @param {CommitOptions} options Commit options, with the workflow branch.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<CommitResults>} Commit results.\n * @throws {Error} When the pull request comes from a fork whose contributor doesn’t let maintainers\n * push to it, or the commit fails.\n */\nconst commitToExistingBranch = async (changes, options, pullRequest) => {\n  const { branch = '' } = options;\n\n  try {\n    return await commitChanges(changes, { ...options, headOid: pullRequest.headSHA });\n  } catch (ex) {\n    // The branch can have gone, which GitHub reports as a ref it can’t resolve. A lookup that\n    // fails says nothing about the branch, so GitHub’s error is passed on then\n    const branchGone = await fetchBranchHead(branch).then(\n      (head) => head === undefined,\n      () => false,\n    );\n\n    if (branchGone) {\n      const { branch: name, ...headRepository } = getBranchRepository(branch);\n\n      throw createBranchGoneError(name, headRepository);\n    }\n\n    throw ex;\n  }\n};\n\n/**\n * Update the description of the given pull request with the given function.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {(description: string) => string} transform Function to get the new description from the\n * current one.\n * @returns {Promise<string>} New description.\n */\nconst updateDescription = (pullRequest, transform) =>\n  updatePullRequestDescription(repository, pullRequest, transform);\n\n/**\n * Commit the given changes on the workflow branch, creating the branch and the pull request if they\n * don’t exist yet.\n * @param {WorkflowSaveOptions} args Arguments.\n * @returns {Promise<{ commit: CommitResults, pullRequest: WorkflowPullRequest }>} Commit results\n * and the new or updated pull request.\n */\nexport const savePullRequest = async (args) =>\n  saveWorkflowBranch(args, {\n    commitToNewBranch,\n    commitToExistingBranch,\n    createPullRequest,\n    updateDescription,\n  });\n\n/**\n * Maximum number of files the comparison API lists. A comparison that reaches it may have left\n * some out, so it can’t vouch for the whole pull request.\n * @see https://docs.github.com/en/rest/commits/commits#compare-two-commits\n */\nconst MAX_COMPARE_FILES = 300;\n\n/**\n * Map of the file statuses the REST API reports to {@link WorkflowChangedFile} ones. A copy adds a\n * file, and `changed` is a change of mode, which modifies it.\n * @type {Record<string, WorkflowChangedFile['status']>}\n */\nconst REST_FILE_STATUSES = {\n  added: 'added',\n  copied: 'added',\n  removed: 'removed',\n  renamed: 'renamed',\n};\n\n/**\n * Fetch the Git file modes of the given files at the given commit, which tell a regular file from\n * a symbolic link or a submodule. The comparison API leaves the mode out, so the trees holding the\n * files are read instead.\n * @param {object} args Arguments.\n * @param {string} args.headSHA Git object ID of the commit.\n * @param {string[]} args.paths File paths.\n * @returns {Promise<Map<string, string>>} Map of file path to its mode as an octal string.\n * @see https://docs.github.com/en/graphql/reference/objects#treeentry\n */\nconst fetchFileModes = async ({ headSHA, paths }) => {\n  const dirs = getParentDirs(paths);\n\n  const trees = await fetchAliasedBatch({\n    items: dirs,\n    alias: 'tree',\n    /**\n     * Build the field selection for a folder at the commit.\n     * @param {string} dir Folder path, or an empty string for the root.\n     * @returns {string} Field selection.\n     */\n    getFragment: (dir) => `\n      object(expression: ${JSON.stringify(`${headSHA}:${dir}`)}) {\n        ... on Tree {\n          entries {\n            name\n            mode\n          }\n        }\n      }\n    `,\n    chunkSize: 50,\n  });\n\n  /** @type {Map<string, string>} */\n  const modes = new Map();\n\n  dirs.forEach((dir, index) => {\n    (trees[index]?.entries ?? []).forEach((/** @type {any} */ { name, mode }) => {\n      modes.set(dir ? `${dir}/${name}` : name, Number(mode).toString(8));\n    });\n  });\n\n  return modes;\n};\n\n/**\n * Read the pull request afresh right before it’s merged. The files are listed by comparing the\n * configured branch with the very commit the pull request points at, rather than read off the pull\n * request, so they describe exactly what a merge pinned to that commit would bring in, even if the\n * branch moves on meanwhile.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<WorkflowMergeState>} State.\n * @see https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request\n * @see https://docs.github.com/en/rest/commits/commits#compare-two-commits\n */\nexport const fetchMergeState = async (pullRequest) => {\n  const { branch } = repository;\n\n  const { head, base } = /** @type {Record<string, any>} */ (\n    await fetchAPI(getPullRequestPath(repository, pullRequest.number))\n  );\n\n  const headSHA = /** @type {string | undefined} */ (head?.sha);\n\n  const onConfiguredBranches =\n    base?.ref === branch &&\n    isSameRepository(base?.repo?.full_name, repository) &&\n    isSameRepository(head?.repo?.full_name, repository);\n\n  return resolveMergeState({\n    pullRequest,\n    headSHA,\n    onConfiguredBranches,\n    /**\n     * List the files the head commit changes from the configured branch.\n     * @param {string} sha Head commit.\n     * @returns {Promise<{ files: WorkflowChangedFile[], complete: boolean }>} Files, and whether\n     * the comparison listed them all.\n     */\n    listChangedFiles: async (sha) => {\n      const encodedBranch = encodePathSegments(/** @type {string} */ (branch));\n\n      const { files = [] } = /** @type {{ files?: Record<string, any>[] }} */ (\n        await fetchAPI(`${getRepositoryPath(repository)}/compare/${encodedBranch}...${sha}`)\n      );\n\n      return {\n        files: await toChangedFilesWithModes(files, {\n          statusMap: REST_FILE_STATUSES,\n          headSHA: sha,\n          fetchFileModes,\n        }),\n        complete: files.length < MAX_COMPARE_FILES,\n      };\n    },\n  });\n};\n\n/**\n * Find which of the given files are the same at the given commit as on the configured branch, by\n * comparing the Git object IDs of their blobs. A file missing from both counts as the same.\n * @param {object} args Arguments.\n * @param {string} args.headSHA Git object ID of the commit.\n * @param {string[]} args.paths File paths.\n * @returns {Promise<string[]>} Paths of the files that are the same.\n * @see https://docs.github.com/en/graphql/reference/objects#repository\n */\nexport const fetchUnchangedPaths = async ({ headSHA, paths }) => {\n  const refs = [/** @type {string} */ (repository.branch), headSHA];\n\n  const blobs = await fetchAliasedBatch({\n    items: paths.flatMap((path) => refs.map((ref) => `${ref}:${path}`)),\n    alias: 'file',\n    /**\n     * Build the field selection for a file at a branch or commit.\n     * @param {string} expression `ref:path` expression.\n     * @returns {string} Field selection.\n     */\n    getFragment: (expression) => `object(expression: ${JSON.stringify(expression)}) { oid }`,\n    chunkSize: 100,\n  });\n\n  return paths.filter(\n    (_path, index) => (blobs[index * 2]?.oid ?? null) === (blobs[index * 2 + 1]?.oid ?? null),\n  );\n};\n\n/**\n * Merge the pull request and delete the workflow branch. The merge is pinned to the commit the\n * entry was loaded or saved at, so a commit pushed to the branch since — after the entry has been\n * reviewed — makes GitHub refuse the merge rather than take it along unseen. Branch protection or a\n * ruleset can require status checks to pass before a pull request is merged, and GitHub refuses an\n * immediate merge while they’re running, which is likely right after the entry is saved. In that\n * case, the pull request is set to auto-merge instead, pinned to the same commit, and GitHub merges\n * it once the checks have passed. Scheduling the merge is not the same as making it: a check can\n * still fail, so this resolves only once the merge has landed. GitHub also refuses the merge while\n * it’s still working out whether the pull request can be merged, which it does in the background\n * after a push, so the pull request is read again until that settles, and merged or set to\n * auto-merge then. See {@link mergeRefusedPullRequest} for that part.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @see https://docs.github.com/en/rest/pulls/pulls#merge-a-pull-request\n * @see https://docs.github.com/en/graphql/reference/mutations#enablepullrequestautomerge\n * @see https://github.com/sveltia/sveltia-cms/issues/1094\n */\nexport const publish = async (pullRequest) => {\n  checkPublishAllowed();\n\n  const { number, title, headSHA } = pullRequest;\n  const squash = isSquashMergeEnabled();\n\n  /**\n   * Merge the pull request right away, pinned to the commit on record.\n   * @returns {Promise<any>} Response.\n   */\n  const merge = () =>\n    fetchAPI(`${getPullRequestPath(repository, number)}/merge`, {\n      method: 'PUT',\n      body: { merge_method: squash ? 'squash' : 'merge', commit_title: title, sha: headSHA },\n    });\n\n  try {\n    await merge();\n  } catch (/** @type {any} */ ex) {\n    // GitHub answers `405 Method Not Allowed` whenever the pull request can’t be merged, whatever\n    // the reason, so the pull request is read to tell them apart\n    if (ex.cause?.status !== 405) {\n      throw ex;\n    }\n\n    await mergeRefusedPullRequest({ pullRequest, squash, merge, refusal: ex });\n  }\n\n  await deleteBranch(pullRequest.branch);\n};\n\n/**\n * Close the pull request without merging it, and delete the workflow branch. A contributor’s\n * branch is left in their fork, where they can still use it, as the maintainer can only close the\n * pull request from it.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<void>}\n */\nexport const discard = (pullRequest) =>\n  discardPullRequest(repository, pullRequest, { deleteBranch });\n\n/**\n * GitHub’s Editorial Workflow implementation.\n * @type {import('$lib/types/private').WorkflowBackendService}\n */\nexport default {\n  fetchPullRequests,\n  savePullRequest,\n  updateStatus,\n  approve,\n  withdrawApproval,\n  fetchBranchHead,\n  fetchMergeState,\n  fetchUnchangedPaths,\n  publish,\n  discard,\n};\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { apiConfig } from '$lib/services/backends/git/shared/api';\nimport { initRepositoryInfo } from '$lib/services/backends/git/shared/repository';\n\n/**\n * @import { ApiEndpointConfig, RepositoryInfo } from '$lib/types/private';\n */\n\n/**\n * Initialize a Git backend with the values read from the CMS configuration: fill in the repository\n * info, build the OAuth authorization and token URLs, and set up the API endpoint configuration.\n * Reading the configuration is left to each backend, since the defaults and the way the repository\n * path is parsed vary between services.\n * @param {RepositoryInfo} repository Repository info placeholder to be updated in place.\n * @param {Parameters<typeof initRepositoryInfo>[1] & {\n * authRoot: string, authPath: string, tokenPath: string,\n * api: Omit<ApiEndpointConfig, 'authURL' | 'tokenURL'>\n * }} args Arguments for {@link initRepositoryInfo}, plus the following. `authRoot` and\n * `authPath` are the `base_url` and `auth_endpoint` backend options, which are joined into the\n * authorization URL. `tokenPath` is the path that replaces `/authorize` in the authorization URL to\n * make the token URL, e.g. `/access_token`. `api` is the rest of the API endpoint configuration.\n * @returns {RepositoryInfo} The updated repository info.\n */\nexport const initGitBackend = (repository, { authRoot, authPath, tokenPath, api, ...args }) => {\n  const authURL = `${stripSlashes(authRoot)}/${stripSlashes(authPath)}`;\n\n  initRepositoryInfo(repository, args);\n\n  Object.assign(\n    apiConfig,\n    /** @type {ApiEndpointConfig} */ ({\n      ...api,\n      authURL,\n      tokenURL: authURL.replace('/authorize', tokenPath),\n    }),\n  );\n\n  return repository;\n};\n","import {\n  normalizeGraphQLBaseURL,\n  normalizeRestBaseURL,\n} from '$lib/services/backends/git/github/api';\nimport { getTokenPageURL, signIn, signOut } from '$lib/services/backends/git/github/auth';\nimport {\n  commitChanges,\n  fetchFileCommits,\n  fetchLastCommit,\n} from '$lib/services/backends/git/github/commits';\nimport {\n  BACKEND_LABEL,\n  BACKEND_NAME,\n  DEFAULT_API_ROOT,\n  DEFAULT_AUTH_PATH,\n  DEFAULT_AUTH_ROOT,\n} from '$lib/services/backends/git/github/constants';\nimport {\n  fetchBranchHeadSHA,\n  fetchDeployments,\n  triggerDeployment,\n} from '$lib/services/backends/git/github/deployment';\nimport { fetchBlob, fetchDirSHA, fetchFiles } from '$lib/services/backends/git/github/files';\nimport { getBaseURLs, repository } from '$lib/services/backends/git/github/repository';\nimport { checkStatus, STATUS_DASHBOARD_URL } from '$lib/services/backends/git/github/status';\nimport workflow from '$lib/services/backends/git/github/workflow';\nimport { graphqlVars } from '$lib/services/backends/git/shared/api';\nimport { initGitBackend } from '$lib/services/backends/git/shared/init';\nimport { toRepositoryPath } from '$lib/services/backends/git/shared/repository';\nimport { cmsConfig } from '$lib/services/config';\n\n/**\n * Path of the Sveltia CMS Additions endpoint whose `/authorize` part is replaced with `/token` to\n * make the token URL.\n */\nconst ADDITIONS_AUTH_PATH = 'v1/auth/authorize';\n\n/**\n * @import { BackendService, RepositoryInfo } from '$lib/types/private';\n */\n\n/**\n * Initialize the GitHub backend.\n * @returns {RepositoryInfo | undefined} Repository info, or nothing when the configured backend is\n * not GitHub.\n */\nexport const init = () => {\n  const { backend } = cmsConfig.current ?? {};\n\n  if (backend?.name !== BACKEND_NAME) {\n    return undefined;\n  }\n\n  const {\n    repo: projectPath,\n    branch,\n    base_url: authRoot = DEFAULT_AUTH_ROOT,\n    auth_endpoint: authPath = DEFAULT_AUTH_PATH,\n    app_id: clientId = '',\n    // GitHub Enterprise Server: https://HOSTNAME/api/v3\n    api_root: restApiRoot = DEFAULT_API_ROOT,\n    // GitHub Enterprise Server: https://HOSTNAME/api/graphql\n    graphql_api_root: graphqlApiRoot = restApiRoot,\n    include_credentials: includeCredentials = false,\n    // Open Authoring on a public repository only needs `public_repo`, which is a narrower grant to\n    // ask a contributor for than full `repo` access. A list can add `workflow`, which keeps a fork\n    // in sync when the repository’s GitHub Actions workflow files change\n    auth_scope: authScope = 'repo',\n    auth_type: authType,\n  } = backend;\n\n  const { owner, repo } = toRepositoryPath(/** @type {string} */ (projectPath));\n\n  initGitBackend(repository, {\n    service: BACKEND_NAME,\n    label: BACKEND_LABEL,\n    owner,\n    repo,\n    branch,\n    restApiRoot,\n    defaultApiRoot: DEFAULT_API_ROOT,\n    getTokenPageURL,\n    getBaseURLs,\n    authRoot,\n    // Sveltia CMS Additions exchanges the session token for a GitHub token at `/v1/auth/token`,\n    // which the usual refresh on a 401 response calls\n    authPath: authType === 'additions' ? ADDITIONS_AUTH_PATH : authPath,\n    tokenPath: authType === 'additions' ? '/token' : '/access_token',\n    api: {\n      clientId,\n      authScope: [authScope, 'user'].flat().join(','),\n      restBaseURL: normalizeRestBaseURL(restApiRoot),\n      graphqlBaseURL: normalizeGraphQLBaseURL(graphqlApiRoot),\n      includeCredentials,\n    },\n  });\n\n  Object.assign(graphqlVars, { owner, repo, branch });\n\n  return repository;\n};\n\n/**\n * @type {BackendService}\n */\nexport default {\n  isGit: true,\n  name: BACKEND_NAME,\n  label: BACKEND_LABEL,\n  repository,\n  statusDashboardURL: STATUS_DASHBOARD_URL,\n  checkStatus,\n  init,\n  signIn,\n  signOut,\n  fetchFiles,\n  fetchLastCommit,\n  fetchBlob,\n  fetchDirSHA,\n  commitChanges,\n  fetchFileCommits,\n  triggerDeployment,\n  fetchBranchHeadSHA,\n  fetchDeployments,\n  workflow,\n};\n","import { createLazyModule } from '$lib/services/api/lazy-module';\nimport { loadChunk } from '$lib/services/app/dependencies';\nimport github from '$lib/services/backends/git/github';\nimport { scopeBackendService } from '$lib/services/backends/git/shared/scope';\n\n/**\n * @import { BackendService } from '$lib/types/private';\n */\n\n/**\n * List of all the Git backend services, keyed by name. This lives apart from the full list of\n * backend services in the parent module so that the local backend, which wraps one of these, can\n * look its remote up without a circular import. Each service is wrapped so the paths the CMS deals\n * with are relative to the `root_dir` backend option, if configured. GitHub, the most common, is\n * bundled with the app, while the others are kept in chunks of their own, see\n * {@link SERVICE_CHUNK_NAMES}: such a service is `undefined` until it’s loaded with\n * {@link loadGitBackendService}.\n * @type {Record<string, BackendService | undefined>}\n */\nexport const gitBackendServices = {\n  github: scopeBackendService(github),\n  gitlab: undefined,\n  gitea: undefined,\n  forgejo: undefined,\n};\n\n/**\n * Chunk holding each Git backend service that isn’t bundled with the app, keyed by service name.\n * @type {Record<string, string>}\n */\nconst SERVICE_CHUNK_NAMES = {\n  gitlab: 'gitlab',\n  gitea: 'gitea',\n  forgejo: 'gitea',\n};\n\n/**\n * Loaders of the chunks holding the Git backend services that aren’t bundled with the app, keyed by\n * chunk name. A chunk exports its services under their names: the `gitea` chunk has both Gitea and\n * Forgejo.\n */\nconst serviceChunks = Object.fromEntries(\n  [...new Set(Object.values(SERVICE_CHUNK_NAMES))].map((chunkName) => [\n    chunkName,\n    createLazyModule({\n      /**\n       * Fetch the chunk.\n       * @returns {Promise<Record<string, BackendService>>} Services.\n       */\n      loader: () => loadChunk(chunkName),\n      notLoadedMessage: `The ${chunkName} chunk is not loaded yet.`,\n    }),\n  ]),\n);\n\n/**\n * Get a Git backend service, loading its chunk first if it’s not bundled with the app. The services\n * of the chunk are added to {@link gitBackendServices}.\n * @param {string} name Service name, e.g. `gitlab`.\n * @returns {Promise<BackendService | undefined>} Service, or `undefined` if there’s no Git backend\n * with the name.\n * @throws {Error} If the chunk can’t be loaded.\n */\nexport const loadGitBackendService = async (name) => {\n  if (!gitBackendServices[name] && name in SERVICE_CHUNK_NAMES) {\n    const services = await serviceChunks[SERVICE_CHUNK_NAMES[name]].load();\n\n    Object.entries(services).forEach(([serviceName, service]) => {\n      // Another call may have added them while the chunk was being loaded\n      gitBackendServices[serviceName] ??= scopeBackendService(service);\n    });\n  }\n\n  return gitBackendServices[name];\n};\n","import {\n  clearLocalGitCache,\n  getLocalGitStatus,\n  saveAndCommitChanges,\n} from '$lib/services/backends/fs/git';\nimport {\n  getScopedRootDirHandle,\n  isTypeMismatchError,\n  readFile,\n} from '$lib/services/backends/fs/shared/handles';\nimport { loadFiles } from '$lib/services/backends/fs/shared/load';\nimport { saveChanges } from '$lib/services/backends/fs/shared/save';\nimport { gitBackendServices } from '$lib/services/backends/git/services';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { getRootDir } from '$lib/services/backends/root-dir';\nimport { cmsConfig } from '$lib/services/config';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { getRepositoryDatabase } from '$lib/services/utils/database';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * Asset,\n * BackendService,\n * CommitOptions,\n * CommitResults,\n * FileChange,\n * InternalCmsConfig,\n * LocalGitStatus,\n * RepositoryInfo,\n * SignInOptions,\n * User,\n * } from '$lib/types/private';\n */\n\nconst backendName = 'local';\nconst label = 'Local Repository';\n/**\n * @type {RepositoryInfo | undefined}\n */\nlet remoteRepository = undefined;\n/**\n * @type {RepositoryInfo}\n */\nconst REPOSITORY_PROPS = { service: '', label: '', owner: '', repo: '', branch: '' };\n\n/**\n * @type {RepositoryInfo}\n */\nconst repository = new Proxy(/** @type {any} */ ({}), {\n  /**\n   * Define the getter.\n   * @param {Record<string, any>} _obj Object itself.\n   * @param {string} key Property name.\n   * @returns {any} Property value.\n   */\n  // @ts-ignore\n  get: (_obj, key) => (remoteRepository ?? REPOSITORY_PROPS)[key],\n});\n\nconst ROOT_DIR_HANDLE_KEY = 'root_dir_handle';\n/**\n * @type {IndexedDB | null | undefined}\n */\nlet rootDirHandleDB = undefined;\n/**\n * Store holding the Git object IDs of the asset files hashed by previous loads, so unchanged files\n * don’t have to be read again. Like the other caches, it only exists when a remote repository is\n * configured, as the database is named after it.\n * @type {IndexedDB | null | undefined}\n */\nlet assetHashDB = undefined;\n/**\n * Handle of the repository’s root directory, which the user has picked.\n * @type {FileSystemDirectoryHandle | undefined}\n */\nlet repoRootDirHandle = undefined;\n/**\n * Handle of the directory the files are read and written in: the configured root directory within\n * the repository, or the repository’s root directory itself.\n * @type {FileSystemDirectoryHandle | undefined}\n */\nlet rootDirHandle = undefined;\n\n/**\n * Get the project’s root directory handle so the app can read all the files under the directory.\n * The handle will be cached in IndexedDB for later use.\n * @param {object} [options] Options.\n * @param {boolean} [options.forceReload] Whether to force getting the handle.\n * @param {boolean} [options.showPicker] Whether to show the directory picker.\n * @returns {Promise<FileSystemDirectoryHandle | null>} Directory handle.\n * @throws {Error | AbortError | NotFoundError} When the File System Access API is not supported by\n * the user’s browser, when the directory picker was dismissed, or when the selected directory is\n * not a project root directory. There might be other reasons to throw.\n * @see https://developer.chrome.com/articles/file-system-access/#stored-file-or-directory-handles-and-permissions\n */\nexport const getRootDirHandle = async ({ forceReload = false, showPicker = true } = {}) => {\n  if (!('showDirectoryPicker' in window)) {\n    throw new Error('unsupported');\n  }\n\n  /** @type {FileSystemDirectoryHandle | null} */\n  let handle = forceReload ? null : ((await rootDirHandleDB?.get(ROOT_DIR_HANDLE_KEY)) ?? null);\n\n  if (handle) {\n    if ((await handle.requestPermission({ mode: 'readwrite' })) !== 'granted') {\n      handle = null;\n    } else {\n      try {\n        await handle.entries().next();\n      } catch (ex) {\n        // The directory may have been (re)moved. Let the user pick the directory again\n        handle = null;\n        // eslint-disable-next-line no-console\n        console.error(ex);\n      }\n    }\n  }\n\n  if (!handle && showPicker) {\n    // This will throw `AbortError` when the user dismissed the picker\n    handle = await window.showDirectoryPicker();\n\n    if (handle) {\n      // Verify this is a project root by checking for `.git`. In a standard repository, `.git` is\n      // a directory. In a git worktree, `.git` is a file containing a `gitdir:` pointer to the\n      // main repository. Both are valid repository roots.\n      try {\n        await handle.getDirectoryHandle('.git');\n      } catch (/** @type {any} */ ex) {\n        if (isTypeMismatchError(ex)) {\n          // `.git` exists but is a file (git worktree), which is still a valid repo root\n          await handle.getFileHandle('.git');\n        } else {\n          throw ex;\n        }\n      }\n\n      // If it looks fine, cache the directory handle\n      await rootDirHandleDB?.set(ROOT_DIR_HANDLE_KEY, handle);\n    }\n  }\n\n  return /** @type {FileSystemDirectoryHandle | null} */ (handle);\n};\n\n/**\n * Initialize the local backend.\n * @returns {RepositoryInfo | undefined} Repository info.\n */\nconst init = () => {\n  const { name: service } = /** @type {InternalCmsConfig} */ (cmsConfig.current).backend;\n\n  remoteRepository = gitBackendServices[service]?.init?.();\n\n  rootDirHandleDB = getRepositoryDatabase(remoteRepository, 'file-system-handles') ?? null;\n  assetHashDB = getRepositoryDatabase(remoteRepository, 'asset-hashes') ?? null;\n\n  return repository;\n};\n\n/**\n * Sign in with the local Git repository. There is no actual sign-in; just show the directory picker\n * to get the handle, so we can read/write files.\n * @param {SignInOptions} options Options.\n * @returns {Promise<User>} User info. Since we don’t have any details for the local user, just\n * return the backend name.\n * @throws {Error} When the directory handle could not be acquired.\n */\nconst signIn = async ({ auto = false }) => {\n  const handle = await getRootDirHandle({ showPicker: !auto });\n\n  if (!handle) {\n    throw new Error('Directory handle could not be acquired');\n  }\n\n  // The user picks the repository root, which is verified by its `.git`, and the files are read and\n  // written in the configured root directory within it\n  try {\n    rootDirHandle = await getScopedRootDirHandle(handle);\n    repoRootDirHandle = handle;\n  } catch {\n    throw createLocalizedError('Failed to open the root directory.', 'root_dir_not_found', {\n      repo: `${repository.owner}/${repository.repo}`,\n      dir: getRootDir(),\n    });\n  }\n\n  return { backendName };\n};\n\n/**\n * Sign out from the local Git repository. There is no actual sign-out; just discard the cached root\n * directory handle.\n */\nconst signOut = async () => {\n  try {\n    await rootDirHandleDB?.delete(ROOT_DIR_HANDLE_KEY);\n  } catch {\n    // The handle is only a convenience for the next sign-in, so an IndexedDB failure is ignored\n  }\n\n  // Free the memory the Git index takes in a large repository\n  clearLocalGitCache();\n};\n\n/**\n * Load file list and all the entry files from the file system, then cache them in the\n * {@link allEntries} and {@link allAssets} stores.\n */\nconst fetchFiles = async () => {\n  await loadFiles(/** @type {FileSystemDirectoryHandle} */ (rootDirHandle), {\n    hashCacheDB: assetHashDB,\n  });\n};\n\n/**\n * Save entries or assets locally. If the user has turned it on, the changes are then committed to\n * the current branch of the local Git repository.\n * @param {FileChange[]} changes File changes to be saved.\n * @param {CommitOptions} options Commit options.\n * @returns {Promise<CommitResults>} Commit results, including the commit SHA, which is a pseudo SHA\n * unless the changes have been committed, saved files, and their blob SHAs.\n */\nconst commitChanges = async (changes, options) => {\n  /**\n   * Save the changes to the files.\n   * @returns {Promise<CommitResults>} Results.\n   */\n  const save = () => saveChanges(rootDirHandle, changes);\n\n  if (prefs.localGitCommits && repoRootDirHandle) {\n    return saveAndCommitChanges({ repoRootDirHandle, changes, options, save });\n  }\n\n  // Free the memory the Git index takes in a large repository, in case commits were turned off\n  clearLocalGitCache();\n\n  return save();\n};\n\n/**\n * Check whether the saved changes can be committed to the local Git repository right now.\n * @returns {Promise<LocalGitStatus | undefined>} Status, or `undefined` if the user hasn’t signed\n * in with the local backend.\n */\nexport const checkLocalGitStatus = async () =>\n  repoRootDirHandle ? getLocalGitStatus(repoRootDirHandle) : undefined;\n\n/**\n * Read an asset file from the file system. An asset uploaded or moved during the session has no\n * file handle of its own, so once the object URL it was given is revoked, the file is read from the\n * disk again.\n * @param {Asset} asset Asset to be fetched.\n * @returns {Promise<Blob>} Blob.\n * @throws {Error} If the root directory handle is not available or the file doesn’t exist.\n */\nconst fetchBlob = async ({ path }) => {\n  if (!rootDirHandle) {\n    throw new Error('Root directory handle is not available');\n  }\n\n  return readFile(rootDirHandle, path);\n};\n\n/**\n * @type {BackendService}\n */\nexport default {\n  isGit: false,\n  name: backendName,\n  label,\n  repository,\n  init,\n  signIn,\n  signOut,\n  fetchFiles,\n  fetchBlob,\n  commitChanges,\n};\n","/* eslint-disable no-console */\n\nimport { getFileHandle } from '$lib/services/backends/fs/shared/handles';\nimport { writeFile } from '$lib/services/backends/fs/shared/save';\nimport { mapConcurrently } from '$lib/services/backends/git/shared/concurrency';\n\n/**\n * Selector of the `<link>` element pointing to the seed manifest, a JSON file listing the files to\n * be copied to an empty test repository, e.g.\n * `<link rel=\"cms-seed-url\" href=\"/seed/manifest.json\">`. The files are fetched from paths relative\n * to the manifest.\n */\nconst SEED_LINK_SELECTOR = 'link[rel=\"cms-seed-url\"]';\n/**\n * Maximum number of seed files to download at the same time.\n */\nconst SEED_FETCH_CONCURRENCY = 6;\n\n/**\n * Get the URL of the seed manifest from the `<link rel=\"cms-seed-url\">` element on the page.\n * @returns {string | undefined} Absolute URL, or `undefined` if there is no such link.\n */\nexport const getSeedManifestURL = () =>\n  /** @type {HTMLLinkElement | null} */ (document.querySelector(SEED_LINK_SELECTOR))?.href ||\n  undefined;\n\n/**\n * Check if the CMS runs as a demo: the test backend is used with a seed manifest, so the user\n * starts with sample content rather than an empty repository.\n * @param {string | undefined} backendName Name of the configured backend.\n * @returns {boolean} Whether the CMS runs as a demo.\n */\nexport const isDemoSite = (backendName) => backendName === 'test-repo' && !!getSeedManifestURL();\n\n/**\n * Check if a path in the seed manifest can be written to the repository: a relative path without\n * empty, `.` or `..` segments, so a file can’t end up outside the repository.\n * @param {unknown} path Path.\n * @returns {path is string} Whether the path is valid.\n */\nexport const isValidSeedPath = (path) =>\n  typeof path === 'string' &&\n  path.split('/').every((segment) => !!segment && segment !== '.' && segment !== '..');\n\n/**\n * Fetch the seed manifest and get the list of files in it.\n * @param {string} manifestURL Manifest URL.\n * @returns {Promise<string[]>} Valid file paths in the manifest.\n * @throws {Error} If the manifest can’t be fetched or its `files` property is not an array.\n */\nexport const fetchSeedManifest = async (manifestURL) => {\n  const response = await fetch(manifestURL);\n\n  if (!response.ok) {\n    throw new Error(`Failed to fetch the seed manifest: ${response.status}`);\n  }\n\n  const { files } = await response.json();\n\n  if (!Array.isArray(files)) {\n    throw new Error('The seed manifest must have a `files` array');\n  }\n\n  // Drop duplicates, so a file isn’t downloaded and written twice\n  return [...new Set(files)].filter((path) => {\n    if (isValidSeedPath(path)) {\n      return true;\n    }\n\n    console.warn(`Skipping an invalid path in the seed manifest: ${JSON.stringify(path)}`);\n\n    return false;\n  });\n};\n\n/**\n * Download a seed file.\n * @param {string} manifestURL Manifest URL, which the file path is relative to.\n * @param {string} path File path.\n * @returns {Promise<Blob | undefined>} File content, or `undefined` if it can’t be downloaded.\n */\nexport const fetchSeedFile = async (manifestURL, path) => {\n  // Encode each segment, so a file name with `#`, `?` or `%` is fetched as is\n  const url = new URL(path.split('/').map(encodeURIComponent).join('/'), manifestURL);\n\n  try {\n    const response = await fetch(url);\n\n    if (!response.ok) {\n      throw new Error(`HTTP ${response.status}`);\n    }\n\n    return await response.blob();\n  } catch (ex) {\n    console.warn(`Failed to seed ${path}:`, ex);\n\n    return undefined;\n  }\n};\n\n/**\n * Write a seed file to the repository.\n * @param {FileSystemDirectoryHandle} repoDirHandle Handle of the repository’s root directory.\n * @param {string} path File path.\n * @param {Blob} blob File content.\n */\nexport const writeSeedFile = async (repoDirHandle, path, blob) => {\n  try {\n    await writeFile(await getFileHandle(repoDirHandle, path), blob);\n  } catch (ex) {\n    console.warn(`Failed to seed ${path}:`, ex);\n  }\n};\n\n/**\n * Copy the files listed in the seed manifest to the test repository if the repository doesn’t exist\n * yet, e.g. on the first visit to a demo site. An existing repository is left untouched, so the\n * user’s changes survive a reload; deleting the repository, e.g. with the Erase All Data option,\n * makes the next sign-in seed it again. Errors are logged rather than thrown, so the user can still\n * sign in, with whatever files could be written.\n * @param {FileSystemDirectoryHandle} storageDirHandle Root directory of the origin private file\n * system (OPFS).\n * @param {string} repoDirName Name of the directory holding the test repository.\n */\nexport const seedTestRepository = async (storageDirHandle, repoDirName) => {\n  const manifestURL = getSeedManifestURL();\n\n  if (!manifestURL) {\n    return;\n  }\n\n  try {\n    await storageDirHandle.getDirectoryHandle(repoDirName);\n\n    // The repository already exists\n    return;\n  } catch {\n    // The repository doesn’t exist yet\n  }\n\n  try {\n    const paths = await fetchSeedManifest(manifestURL);\n\n    // Download everything before creating the repository, so an interrupted download, e.g. when the\n    // tab is closed, doesn’t leave a partial repository that would never be seeded again\n    const blobs = await mapConcurrently(paths, (path) => fetchSeedFile(manifestURL, path), {\n      concurrency: SEED_FETCH_CONCURRENCY,\n    });\n\n    // Don’t create an empty repository if nothing could be downloaded, e.g. when the connection is\n    // lost, so the next sign-in tries again\n    if (!blobs.some(Boolean)) {\n      return;\n    }\n\n    const repoDirHandle = await storageDirHandle.getDirectoryHandle(repoDirName, { create: true });\n\n    await Promise.all(\n      paths.map((path, index) => {\n        const blob = blobs[index];\n\n        return blob ? writeSeedFile(repoDirHandle, path, blob) : undefined;\n      }),\n    );\n  } catch (ex) {\n    console.warn('Failed to seed the test repository:', ex);\n  }\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { seedTestRepository } from '$lib/services/backends/fs/seed';\nimport {\n  getDirectoryHandle,\n  getScopedRootDirHandle,\n  readFile,\n} from '$lib/services/backends/fs/shared/handles';\nimport { loadFiles } from '$lib/services/backends/fs/shared/load';\nimport { saveChanges } from '$lib/services/backends/fs/shared/save';\nimport { dataLoaded } from '$lib/services/contents';\nimport { env } from '$lib/services/user/env.svelte';\n\n/**\n * @import { Asset, BackendService, CommitResults, FileChange, User } from '$lib/types/private';\n */\n\n/**\n * Name of the directory in the origin private file system (OPFS) where the entry and asset files\n * are stored.\n */\nexport const TEST_BACKEND_ROOT_DIR_NAME = 'sveltia-cms-test';\n/**\n * Name of the test backend.\n */\nexport const TEST_BACKEND_NAME = 'test-repo';\n/**\n * Name of the IndexedDB database holding the test backend’s draft backups. The backend has no\n * repository, which would otherwise give the database its name.\n */\nexport const TEST_BACKEND_DATABASE_NAME = `${TEST_BACKEND_NAME}:${TEST_BACKEND_ROOT_DIR_NAME}`;\n\n/**\n * Get the name of the IndexedDB database holding the draft backups of the given backend.\n * @param {BackendService | null | undefined} backend Backend service.\n * @returns {string | undefined} Repository database name, {@link TEST_BACKEND_DATABASE_NAME} for\n * the test backend, which has no repository, or an empty value if the backend has no database.\n */\nexport const getBackupDatabaseName = (backend) =>\n  backend?.name === TEST_BACKEND_NAME\n    ? TEST_BACKEND_DATABASE_NAME\n    : backend?.repository?.databaseName;\n\nconst label = 'Test';\n/**\n * @type {FileSystemDirectoryHandle | undefined}\n */\nlet rootDirHandle = undefined;\n/**\n * Initialize the test backend. There is nothing to do here.\n * @returns {undefined}\n */\nconst init = () => undefined;\n\n/**\n * Sign in with the test backend. There is no actual sign-in; just get the root directory handle in\n * the origin private file system (OPFS), so we can read/write files. On the first sign-in, the\n * repository is seeded with the files listed in the `<link rel=\"cms-seed-url\">` manifest, if any.\n * @returns {Promise<User>} User info. Since we don’t have any details for the local user, just\n * return the backend name.\n * @throws {Error} If the browser can’t write files to the OPFS. The sign-in page disables the\n * option then, but a user cached from an earlier session would still be signed in automatically.\n * @see https://web.dev/articles/origin-private-file-system\n */\nconst signIn = async () => {\n  if (!env.isTestBackendSupported) {\n    throw new Error('Unsupported browser', {\n      cause: { message: _('test_repo_unsupported_browser') },\n    });\n  }\n\n  try {\n    const storageDirHandle = await navigator.storage.getDirectory();\n\n    await seedTestRepository(storageDirHandle, TEST_BACKEND_ROOT_DIR_NAME);\n\n    // The configured root directory is created if needed, like the backend’s own directory\n    rootDirHandle = await getScopedRootDirHandle(\n      await getDirectoryHandle(storageDirHandle, TEST_BACKEND_ROOT_DIR_NAME),\n      { create: true },\n    );\n  } catch {\n    // Directory handle could not be acquired for security reasons, but we can ignore the error\n  }\n\n  return { backendName: TEST_BACKEND_NAME };\n};\n\n/**\n * Sign out from the test backend. There is nothing to do here.\n */\nconst signOut = async () => {};\n\n/**\n * Load file list and all the entry files from the file system, then cache them in the\n * {@link allEntries} and {@link allAssets} stores. If the root directory handle is not available,\n * simply pretend that the data is loaded.\n */\nconst fetchFiles = async () => {\n  if (rootDirHandle) {\n    await loadFiles(rootDirHandle);\n  } else {\n    dataLoaded.current = true;\n  }\n};\n\n/**\n * Save entries or assets in the OPFS using the root directory handle acquired during sign-in. If\n * the handle is not available, do nothing; the data will still be stored in the in-memory cache,\n * allowing the user to continue using the app without an error.\n * @param {FileChange[]} changes File changes to be saved.\n * @returns {Promise<CommitResults>} Commit results, including a pseudo commit SHA, saved files, and\n * their blob SHAs.\n */\nconst commitChanges = async (changes) => saveChanges(rootDirHandle, changes);\n\n/**\n * Read an asset file from the file system. An asset uploaded or moved during the session has no\n * file handle of its own, so once the object URL it was given is revoked, the file is read from the\n * disk again.\n * @param {Asset} asset Asset to be fetched.\n * @returns {Promise<Blob>} Blob.\n * @throws {Error} If the root directory handle is not available or the file doesn’t exist.\n */\nconst fetchBlob = async ({ path }) => {\n  if (!rootDirHandle) {\n    throw new Error('Root directory handle is not available');\n  }\n\n  return readFile(rootDirHandle, path);\n};\n\n/**\n * @type {BackendService}\n */\nexport default {\n  isGit: false,\n  name: TEST_BACKEND_NAME,\n  label,\n  init,\n  signIn,\n  signOut,\n  fetchFiles,\n  fetchBlob,\n  commitChanges,\n};\n","import { loadAdditions } from '$lib/services/app/additions';\nimport local from '$lib/services/backends/fs/local';\nimport test from '$lib/services/backends/fs/test';\nimport { gitBackendServices, loadGitBackendService } from '$lib/services/backends/git/services';\nimport { cmsConfig } from '$lib/services/config';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { BackendService } from '$lib/types/private';\n * @import { BackendName } from '$lib/types/public';\n */\n\n/**\n * List of the supported backend services that aren’t Git hosting services.\n * @type {Record<string, BackendService>}\n */\nconst fileSystemBackendServices = {\n  local,\n  'test-repo': test,\n};\n\n/**\n * Get a backend service that has been loaded. A Git backend service kept in a chunk is only there\n * once it’s been loaded with {@link loadBackendService}.\n * @param {string} name Backend name.\n * @returns {BackendService | undefined} Service.\n * @see https://decapcms.org/docs/backends-overview/\n * @see https://sveltiacms.app/en/docs/backends\n */\nconst getBackendService = (name) => fileSystemBackendServices[name] ?? gitBackendServices[name];\n\n/**\n * List of backend services that are implemented in Netlify/Decap CMS but are not supported in\n * Sveltia CMS for performance and/or deprecation reasons.\n * @type {Record<string, { label: string, deprecated?: boolean }>}\n * @see https://sveltiacms.app/en/docs/migration/netlify-decap-cms#compatibility\n */\nexport const unsupportedBackends = {\n  azure: { label: 'Azure DevOps' },\n  bitbucket: { label: 'Bitbucket' },\n  'git-gateway': { label: 'Git Gateway', deprecated: true },\n};\n\n/**\n * List of valid backend service names. This is used to validate the backend name in the site\n * configuration. Note that the `local` backend is not included here, as it’s a special case that\n * requires a Git backend service to be configured.\n * @type {BackendName[]}\n */\nexport const validBackendNames = /** @type {BackendName[]} */ ([\n  ...Object.keys(gitBackendServices),\n  'test-repo',\n]);\n\n/**\n * Currently selected backend service name. Use {@link selectBackend} to change it, so that the new\n * service is initialized.\n * @type {{ current: string | undefined }}\n */\nexport const backendName = createRawState();\n\n/**\n * Currently selected backend service.\n */\nexport const backend = createDerivedState(() =>\n  backendName.current ? getBackendService(backendName.current) : undefined,\n);\n\n/**\n * Get a backend service, loading it first if it’s kept in a chunk. The local backend wraps the\n * configured Git backend, so that one is loaded along with it, and so is the `additions` chunk\n * when the CMS works with Sveltia CMS Additions.\n * @param {string} name Backend name.\n * @returns {Promise<BackendService | undefined>} Service, or `undefined` if there’s no backend with\n * the name.\n * @throws {Error} If the service can’t be loaded.\n */\nexport const loadBackendService = async (name) => {\n  // Sveltia CMS Additions takes over the sign-in, so it comes with the backend\n  await loadAdditions();\n\n  if (name === 'local') {\n    const remoteName = cmsConfig.current?.backend.name;\n\n    if (remoteName) {\n      await loadGitBackendService(remoteName);\n    }\n  }\n\n  return fileSystemBackendServices[name] ?? loadGitBackendService(name);\n};\n\n/**\n * Select the backend service with the given name, loading it if needed and initializing it if it’s\n * not the current one.\n * @param {string | undefined} name Backend name, or `undefined` to deselect the current backend.\n * @returns {Promise<BackendService | undefined>} Selected backend service, if any.\n * @throws {Error} If the service can’t be loaded.\n */\nexport const selectBackend = async (name) => {\n  const service = name ? await loadBackendService(name) : undefined;\n\n  if (service && service !== backend.current) {\n    service.init();\n  }\n\n  backendName.current = name;\n\n  return service;\n};\n","import { cmsConfig } from '$lib/services/config';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\nimport {\n  getPublishModeOptions,\n  getPublishModeScopes,\n  isWorkflowMode,\n} from '$lib/services/workflow/config';\nimport { OPEN_AUTHORING_STAGES, WORKFLOW_STAGES } from '$lib/services/workflow/constants';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { UnpublishedEntry, WorkflowStatus } from '$lib/types/private';\n * @import { ResolvedPublishMode } from '$lib/services/workflow/config';\n * @import { Collection } from '$lib/types/public';\n */\n\n/**\n * Get the publish mode options of the given collection with the current site configuration. See\n * {@link getPublishModeOptions} for details.\n * @param {Collection | undefined} collection Collection. `undefined` falls back to the site-level\n * publish mode.\n * @returns {ResolvedPublishMode} Resolved options.\n */\nexport const getCollectionPublishModeOptions = (collection) =>\n  getPublishModeOptions({ cmsConfig: cmsConfig.current, collection });\n\n/**\n * Get the review stages an unpublished entry in the given collection moves through, which are the\n * options in the editor’s status menu. They’re configured with the `stages` option of the\n * `publish_mode` option, and Preview Workflow has the drafting stage only. An Open Authoring\n * contributor always gets the stages available to them, whatever the collection says: their last\n * step is to hand the entry over for review.\n * @param {Collection | undefined} collection Collection. `undefined` falls back to the site-level\n * publish mode.\n * @returns {WorkflowStatus[]} Stages, ordered from the earliest to the latest.\n */\nexport const getWorkflowStages = (collection) =>\n  openAuthoring.current\n    ? OPEN_AUTHORING_STAGES\n    : getCollectionPublishModeOptions(collection).stages;\n\n/**\n * Get the stage the given status stands for among the given stages. A pull request labelled with a\n * stage that isn’t configured — by another CMS, before the configuration was changed, or by an Open\n * Authoring contributor handing it over for review in Preview Workflow — is treated as being in the\n * nearest earlier stage, so a review is never skipped. The label itself is left alone until the\n * entry is moved.\n * @param {WorkflowStatus} status Status read from the pull request’s labels.\n * @param {WorkflowStatus[]} stages Configured stages, which always include `draft`.\n * @returns {WorkflowStatus} Stage. A pending deletion has no stages, so it’s returned as is.\n */\nexport const resolveStage = (status, stages) => {\n  if (status === 'pending_deletion') {\n    return status;\n  }\n\n  const index = WORKFLOW_STAGES.indexOf(status);\n\n  return stages.findLast((stage) => WORKFLOW_STAGES.indexOf(stage) <= index) ?? 'draft';\n};\n\n/**\n * Get the stage the given unpublished entry is in. See {@link resolveStage} for details.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {Collection | undefined} collection Collection the entry belongs to.\n * @returns {WorkflowStatus} Stage, or `pending_deletion` for a pending deletion.\n */\nexport const getEntryStage = (entry, collection) =>\n  resolveStage(entry.workflow.status, getWorkflowStages(collection));\n\n/**\n * Get the stages configured for the collection the given unpublished entry belongs to.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {WorkflowStatus[]} Stages. See {@link getWorkflowStages}.\n */\nexport const getStagesOfEntry = (entry) =>\n  getWorkflowStages(getCollection(entry.workflow.collectionName));\n\n/**\n * Get the stage the given unpublished entry is in, which decides the column it’s placed in on the\n * Editorial Workflow board.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {WorkflowStatus} Stage. See {@link getEntryStage}.\n */\nexport const getStageOfEntry = (entry) =>\n  getEntryStage(entry, getCollection(entry.workflow.collectionName));\n\n/**\n * Check whether the given unpublished entry can be moved to the given stage. The collections can be\n * configured with different stages, and an entry can only go to one of its own collection’s.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {WorkflowStatus} status Stage.\n * @returns {boolean} Result.\n */\nexport const isStageAvailable = (entry, status) => getStagesOfEntry(entry).includes(status);\n\n/**\n * Get the stage that comes after the one the given unpublished entry is in.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {Collection | undefined} collection Collection the entry belongs to.\n * @returns {WorkflowStatus | undefined} Next stage, or `undefined` if the entry is in the last\n * stage or is a pending deletion.\n */\nexport const getNextStage = (entry, collection) => {\n  const stages = getWorkflowStages(collection);\n  const stage = resolveStage(entry.workflow.status, stages);\n\n  return stage === 'pending_deletion' ? undefined : stages[stages.indexOf(stage) + 1];\n};\n\n/**\n * Check whether the given unpublished entry is in the last stage, which is where it can be\n * published from. With Preview Workflow, that’s the drafting stage.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {Collection | undefined} collection Collection the entry belongs to.\n * @returns {boolean} Result. Always `false` for a pending deletion.\n */\nexport const isLastStage = (entry, collection) => {\n  const stages = getWorkflowStages(collection);\n\n  return resolveStage(entry.workflow.status, stages) === stages.at(-1);\n};\n\n/**\n * Review stages shown as the columns of the Editorial Workflow board: every stage configured for\n * the site or for any collection that goes through a workflow, in the canonical order. The board\n * has a single column when everything uses Preview Workflow. An Open Authoring contributor gets the\n * stages available to them.\n */\nexport const boardStages = createDerivedState(() => {\n  if (openAuthoring.current) {\n    return OPEN_AUTHORING_STAGES;\n  }\n\n  const config = cmsConfig.current;\n  /** @type {Set<WorkflowStatus>} */\n  const stages = new Set(['draft']);\n\n  getPublishModeScopes(config).forEach((collection) => {\n    const options = getPublishModeOptions({ cmsConfig: config, collection });\n\n    if (isWorkflowMode(options.type)) {\n      options.stages.forEach((stage) => stages.add(stage));\n    }\n  });\n\n  return WORKFLOW_STAGES.filter((stage) => stages.has(stage));\n});\n\n/**\n * I18n string key of the Editorial Workflow page’s name. When everything uses Preview Workflow, the\n * page is a plain list of drafts rather than a board with review stages, so it’s named after them.\n */\nexport const workflowPageLabelKey = createDerivedState(() =>\n  boardStages.current.length === 1 ? 'drafts' : 'editorial_workflow',\n);\n","import { unique } from '@sveltia/utils/array';\n\nimport { backend } from '$lib/services/backends';\nimport { lockedBranch, mergeLockedBranch } from '$lib/services/backends/branch-access';\nimport { getDeletionGroup } from '$lib/services/backends/git/shared/pull-requests';\nimport { cmsConfig } from '$lib/services/config';\nimport { isDraftReadonly } from '$lib/services/config/readonly';\nimport { allEntries, findEntryByPaths } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\nimport { isEntryBranch } from '$lib/services/workflow/branch';\nimport {\n  getPublishMode,\n  isWorkflowConfigured,\n  isWorkflowMode,\n} from '$lib/services/workflow/config';\nimport { isForkEntry } from '$lib/services/workflow/forks';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\nimport { getCollectionPublishModeOptions, isLastStage } from '$lib/services/workflow/stages';\n\n/**\n * @import {\n * CompanionEntry,\n * Entry,\n * EntryDraft,\n * InternalCollection,\n * UnpublishedEntry,\n * UnpublishedEntryProps,\n * WorkflowPullRequest,\n * } from '$lib/types/private';\n * @import { Collection } from '$lib/types/public';\n */\n\n/**\n * Whether Editorial Workflow is enabled for any content. It requires both the `editorial_workflow`\n * publish mode — for the whole site or for at least one collection — and a backend service that\n * implements the feature. This decides whether the feature is set up at all: the pull requests are\n * listed and the Editorial Workflow page is offered. Whether a particular entry goes through the\n * workflow is up to {@link isWorkflowEnabled}, because a collection can opt in or out on its own.\n */\nexport const workflowEnabled = createDerivedState(\n  () => isWorkflowConfigured(cmsConfig.current) && !!backend.current?.workflow,\n);\n\n/**\n * Check whether the entries in the given collection go through Editorial Workflow. The\n * collection-level `publish_mode` option overrides the site-level one. A contributor working on a\n * fork with Open Authoring can’t write to the configured repository, so their changes always go\n * through a pull request, whatever the collection says.\n * @param {Collection | undefined} collection Collection. `undefined` falls back to the site-level\n * publish mode.\n * @returns {boolean} `true` if a change to an entry in the collection is saved to a pull request\n * rather than committed to the configured branch.\n * @see https://github.com/decaporg/decap-cms/issues/1571\n */\nexport const isWorkflowEnabled = (collection) =>\n  !!backend.current?.workflow &&\n  (openAuthoring.current ||\n    isWorkflowMode(getPublishMode({ cmsConfig: cmsConfig.current, collection })));\n\n/**\n * List of all the unpublished entries retrieved from the backend’s open pull requests, including\n * those from the pull requests contributors have opened from their forks. Only the Editorial\n * Workflow board and the code that loads, stores and acts on a pull request read this list; the\n * rest of the CMS reads {@link unpublishedEntries}.\n * @type {{ current: UnpublishedEntry[] }}\n */\nexport const allUnpublishedEntries = createRawState([]);\n\n/**\n * List of the unpublished entries the CMS shows in place of the published ones, in the entry list,\n * the search results and the editor: all of {@link allUnpublishedEntries} but those from the pull\n * requests contributors have opened from their forks, which are only reached from the Editorial\n * Workflow board. Leaving them out here rather than where they’re read means new code doesn’t take\n * untrusted entries in without meaning to. See {@link isForkEntry}.\n * @type {{ readonly current: UnpublishedEntry[] }}\n */\nexport const unpublishedEntries = createDerivedState(() =>\n  // Keep the same array when there’s nothing to leave out, to avoid needless recomputation\n  allUnpublishedEntries.current.some(isForkEntry)\n    ? allUnpublishedEntries.current.filter((entry) => !isForkEntry(entry))\n    : allUnpublishedEntries.current,\n);\n\n/**\n * Whether the unpublished entry list is being loaded or updated.\n */\nexport const unpublishedEntriesLoading = createRawState(false);\n\n/**\n * Whether the unpublished entries have been loaded at least once, successfully or not.\n */\nexport const unpublishedEntriesLoaded = createRawState(false);\n\n/**\n * Workflow branches of the entries being published, which is to say whose pull request is being\n * merged. A merge can take minutes when the Git service waits for a pipeline, and the view that\n * started it is created afresh each time it opens, so the wait is recorded here rather than in that\n * view: any view can then show the entry as busy.\n * @type {{ current: string[] }}\n */\nexport const publishingBranches = createRawState([]);\n\n/**\n * Whether everything needed to resolve an entry is available. The unpublished entries are fetched\n * after the initial data load, so an entry opened with a deep link can’t be resolved until they\n * arrive: a draft for a new entry wouldn’t be found at all, and a draft updating a published entry\n * would fall back to the published version.\n */\nexport const workflowDataReady = createDerivedState(\n  () => !workflowEnabled.current || unpublishedEntriesLoaded.current,\n);\n\n/**\n * Get the unpublished entries in the given collection.\n * @param {string | undefined} collectionName Collection name.\n * @returns {UnpublishedEntry[]} Unpublished entries.\n */\nexport const getUnpublishedEntriesByCollection = (collectionName) =>\n  collectionName\n    ? unpublishedEntries.current.filter(\n        ({ workflow }) => workflow.collectionName === collectionName,\n      )\n    : [];\n\n/**\n * Get the entries in the given collection that ride along in the pull requests of the given\n * unpublished entries, either the new ones or the existing ones changed there.\n * @param {string} collectionName Collection name.\n * @param {UnpublishedEntry[]} entries Unpublished entries to look in.\n * @param {boolean} edited Whether to get the existing entries rather than the new ones.\n * @returns {Entry[]} Entries.\n */\nconst filterCompanionEntries = (collectionName, entries, edited) =>\n  entries.flatMap(({ workflow }) =>\n    (workflow.companions ?? []).flatMap((companion) =>\n      companion.collectionName === collectionName && !!companion.edited === edited\n        ? [companion.entry]\n        : [],\n    ),\n  );\n\n/**\n * Get the new entries in the given collection that ride along in the pull request of an entry of\n * another collection. See {@link UnpublishedEntryProps.companions}. The existing entries changed in\n * such a pull request are left out: see {@link getEditedCompanionEntries}.\n * @param {string} collectionName Collection name.\n * @param {UnpublishedEntry[]} [entries] Unpublished entries to look in. Defaults to all of them.\n * @returns {Entry[]} Entries.\n */\nexport const getCompanionEntries = (collectionName, entries = unpublishedEntries.current) =>\n  filterCompanionEntries(collectionName, entries, false);\n\n/**\n * Get the existing entries in the given collection that have been changed in the pull request of an\n * entry of another collection, as they stand on its branch. See\n * {@link UnpublishedEntryProps.companions}.\n * @param {string} collectionName Collection name.\n * @param {UnpublishedEntry[]} [entries] Unpublished entries to look in. Defaults to all of them.\n * @returns {Entry[]} Entries.\n */\nexport const getEditedCompanionEntries = (collectionName, entries = unpublishedEntries.current) =>\n  filterCompanionEntries(collectionName, entries, true);\n\n/**\n * Get the paths of the existing entries a pull request changes along with its entry: those they\n * have on its branch, and those their published versions have on the configured branch, where the\n * pull request can only change or remove a file. A published version is found by ID, which an\n * edited companion keeps, so one the pull request has renamed is found as well.\n * @param {CompanionEntry[]} companions Entries riding along in the pull request.\n * @returns {{ paths: string[], publishedPaths: Set<string> }} Paths on the branch, and those on the\n * configured branch.\n */\nexport const getEditedCompanionPaths = (companions) => {\n  const editedEntries = companions.flatMap(({ entry, edited }) => (edited ? [entry] : []));\n\n  return {\n    paths: unique(editedEntries.flatMap((entry) => getEntryPaths(entry))),\n    publishedPaths: new Set(\n      editedEntries.flatMap(({ id }) => {\n        const publishedEntry = allEntries.current.find((entry) => entry.id === id);\n\n        return publishedEntry ? getEntryPaths(publishedEntry) : [];\n      }),\n    ),\n  };\n};\n\n/**\n * Find the unpublished entry whose pull request changes the given existing entry along with it,\n * the entry having been edited from a Relation field.\n * @param {Entry} entry Published entry.\n * @returns {UnpublishedEntry | undefined} Unpublished entry.\n */\nexport const findEditingUnpublishedEntry = (entry) =>\n  unpublishedEntries.current.find(({ workflow }) =>\n    (workflow.companions ?? []).some(\n      (companion) => companion.edited && companion.entry.id === entry.id,\n    ),\n  );\n\n/**\n * Get the entries in the given collection that pull requests hold: its unpublished entries, and the\n * new entries riding along in the pull request of an entry of another collection. They take up a\n * slug, a file path or a number as much as the published entries do.\n * @param {string} collectionName Collection name.\n * @returns {Entry[]} Entries.\n */\nexport const getPullRequestEntries = (collectionName) => [\n  ...getUnpublishedEntriesByCollection(collectionName),\n  ...getCompanionEntries(collectionName),\n];\n\n/**\n * Check whether the given unpublished entry is the one an editor route addresses.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} args.subPath Entry sub path, or collection file name.\n * @returns {boolean} Result.\n */\nconst isAddressedEntry = (entry, { collectionName, subPath }) =>\n  entry.workflow.collectionName === collectionName &&\n  // A collection file is addressed by its name, while its `subPath` is the whole file path\n  (entry.workflow.fileName !== undefined\n    ? entry.workflow.fileName === subPath\n    : entry.subPath === subPath);\n\n/**\n * Find the unpublished entry that matches the given collection name and entry sub path. This is\n * used to open the entry editor with the pull request’s version of the entry rather than the\n * published version.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} args.subPath Entry sub path, or collection file name.\n * @returns {UnpublishedEntry | undefined} Unpublished entry.\n */\nexport const getUnpublishedEntry = ({ collectionName, subPath }) =>\n  unpublishedEntries.current.find((entry) => isAddressedEntry(entry, { collectionName, subPath }));\n\n/**\n * Find the unpublished entry that matches the given collection name and entry sub path in the pull\n * request with the given number, which a contributor has opened from their fork. Such an entry is\n * only opened from the Editorial Workflow board, which names the pull request in the editor’s URL,\n * as several pull requests can hold the same entry. See {@link unpublishedEntries}.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} args.subPath Entry sub path, or collection file name.\n * @param {number} args.number Pull request number.\n * @returns {UnpublishedEntry | undefined} Unpublished entry.\n */\nexport const getForkUnpublishedEntry = ({ collectionName, subPath, number }) =>\n  allUnpublishedEntries.current.find(\n    (entry) =>\n      isForkEntry(entry) &&\n      entry.workflow.pullRequest.number === number &&\n      isAddressedEntry(entry, { collectionName, subPath }),\n  );\n\n/**\n * Find the unpublished entry whose workflow branch addresses the given entry. This is the entry the\n * branch was opened for, which stays the same after the slug has been edited, unlike the result of\n * {@link getUnpublishedEntry}. A branch name says nothing about what the pull request holds, so the\n * unpublished entry also has to be the given one: one of its files, or of the files it vacates, is\n * one of the entry’s. Without that, anyone who can push could open a pull request under an entry’s\n * branch name that holds another entry, and the editor of the first would offer to publish it.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} args.slug Entry slug, or collection file name.\n * @param {Entry | undefined} args.entry Entry the branch would hold, as it stands before the\n * changes. `undefined` for a new entry, which has no pull request yet.\n * @returns {UnpublishedEntry | undefined} Unpublished entry.\n */\nexport const getUnpublishedEntryBySlug = ({ collectionName, slug, entry }) => {\n  if (!entry) {\n    return undefined;\n  }\n\n  const paths = new Set(getEntryPaths(entry));\n\n  return unpublishedEntries.current.find(\n    (unpublishedEntry) =>\n      isEntryBranch({\n        branch: unpublishedEntry.workflow.pullRequest.branch,\n        collectionName,\n        slug,\n      }) &&\n      getEntryPaths(unpublishedEntry, { includePrevious: true }).some((path) => paths.has(path)),\n  );\n};\n\n/**\n * Find the unpublished entry with the given ID in the store. The pull requests are read again from\n * time to time, which can replace an entry while a card is being dragged or a confirmation dialog\n * is open, or take it off the board altogether if its pull request has been merged or closed in the\n * meantime; acting on a copy held since then would put stale content back.\n * @param {string | undefined} id Entry ID, e.g. of the entry as it was when an action started.\n * @returns {UnpublishedEntry | undefined} Current entry, or `undefined` if there’s none.\n */\nexport const getUnpublishedEntryById = (id) =>\n  id ? allUnpublishedEntries.current.find((entry) => entry.id === id) : undefined;\n\n/**\n * Find the unpublished entry that corresponds to the given workflow branch.\n * @param {string} branch Branch name.\n * @returns {UnpublishedEntry | undefined} Unpublished entry.\n */\nexport const getUnpublishedEntryByBranch = (branch) =>\n  allUnpublishedEntries.current.find(({ workflow }) => workflow.pullRequest.branch === branch);\n\n/**\n * Find the unpublished entry that the given draft is editing. The draft holds the entry as it was\n * when the editor opened it, and the entry can change while the editor stays open — its status from\n * the status menu or the Editorial Workflow page, its head commit with each save — so the entry is\n * read from the store rather than from that snapshot. The branch the entry is already associated\n * with is preferred over the one derived from the slug: the branch keeps the slug the pull request\n * was opened with, so an entry whose slug has been edited since no longer matches it by slug.\n * @param {object} args Arguments. A draft can be passed as is.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name, if the entry is a collection file.\n * @param {Entry} [args.originalEntry] Entry being edited, before the changes. `undefined` for a new\n * entry, which has no pull request yet.\n * @returns {UnpublishedEntry | undefined} Unpublished entry.\n */\nexport const getUnpublishedEntryByDraft = ({ collectionName, fileName, originalEntry }) => {\n  if (!originalEntry) {\n    return undefined;\n  }\n\n  const branch = /** @type {UnpublishedEntry} */ (originalEntry).workflow?.pullRequest?.branch;\n\n  return (\n    (branch ? getUnpublishedEntryByBranch(branch) : undefined) ??\n    getUnpublishedEntryBySlug({\n      collectionName,\n      slug: fileName ?? originalEntry.slug,\n      entry: originalEntry,\n    })\n  );\n};\n\n/**\n * Check whether the given draft edits an entry from a contributor’s pull request that is no longer\n * open, e.g. merged or closed on the Git service since the editor was opened. There’s nothing left\n * to save it to: the changes must not go to the configured branch, or to a pull request of the\n * maintainers’ own, without anyone meaning to put them there, which is where a save would otherwise\n * take them now that the entry is no longer in the store.\n * @param {Pick<EntryDraft, 'collectionName' | 'fileName' | 'originalEntry'> | null} [draft] Draft,\n * if any.\n * @returns {boolean} Result.\n */\nexport const isOrphanedForkDraft = (draft) =>\n  !!draft && isForkEntry(draft.originalEntry) && !getUnpublishedEntryByDraft(draft);\n\n/**\n * Check whether the changes made in the given draft go to a pull request rather than the configured\n * branch. That’s the case when the draft’s collection uses Editorial Workflow, but also when the\n * entry already has a pull request: a contributor working on a fork always opens one, whatever the\n * collection’s publish mode, and a maintainer editing that entry has to keep working in it — saving\n * the pull request’s unreviewed content straight to the configured branch would bypass the review\n * and leave the pull request open.\n * @param {object} args Arguments. A draft can be passed as is.\n * @param {Collection} [args.collection] Collection.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name, if the entry is a collection file.\n * @param {Entry} [args.originalEntry] Entry being edited, before the changes.\n * @returns {boolean} `true` if the draft is saved through Editorial Workflow.\n */\nexport const isWorkflowDraft = ({ collection, collectionName, fileName, originalEntry }) =>\n  isWorkflowEnabled(collection) ||\n  !!getUnpublishedEntryByDraft({ collectionName, fileName, originalEntry });\n\n/**\n * Check whether the given entry is awaiting removal from the site. Such an entry can’t be edited:\n * the only things left to do with it are carrying the deletion out or calling it off.\n * @param {Entry | undefined} entry Entry to check, published or not.\n * @returns {boolean} `true` if a pull request is pending that deletes the entry.\n */\nexport const isPendingDeletion = (entry) =>\n  /** @type {UnpublishedEntry | undefined} */ (entry)?.workflow?.status === 'pending_deletion';\n\n/**\n * Check whether an entry draft is shown for reference only, which is when it’s read-only (see\n * {@link isDraftReadonly}) or awaiting deletion (see {@link isPendingDeletion}). Its content can’t\n * be changed then, nor can its locales be enabled.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {boolean} Result.\n */\nexport const isDraftLocked = (draft) =>\n  isDraftReadonly(draft) || isPendingDeletion(draft?.originalEntry);\n\n/**\n * Get the entries deleted along with the given unpublished entry. A selection of entries is deleted\n * with the same reference rewrite in each pull request, so the other entries awaiting deletion in\n * the pull requests recording the same selection count as part of it. A selection is recorded per\n * collection, or collection file, so they all belong to the same one as the entry. An entry deleted\n * on its own, or by a pull request opened before the selection was recorded, rewrites only the\n * references to itself. The entry is matched by ID, as the store may have replaced it with a copy\n * since it was read.\n * @param {UnpublishedEntry} entry Unpublished entry awaiting deletion.\n * @returns {UnpublishedEntry[]} The entry, followed by the others deleted with it.\n */\nexport const getDeletionSelection = (entry) => {\n  const deletionGroup = getDeletionGroup(entry.workflow.pullRequest);\n\n  if (!deletionGroup) {\n    return [entry];\n  }\n\n  return [\n    entry,\n    ...unpublishedEntries.current.filter(\n      (e) =>\n        e.id !== entry.id &&\n        isPendingDeletion(e) &&\n        getDeletionGroup(e.workflow.pullRequest) === deletionGroup,\n    ),\n  ];\n};\n\n/**\n * Check whether the signed-in user can merge the given pull request, which is what publishing an\n * unpublished entry does. A protected branch may let a user push to the workflow branches, but not\n * merge into the configured branch. When the backend doesn’t tell, the merge is left to it to allow\n * or refuse. A pull request a contributor opened from their fork is never merged here: the CMS only\n * shows the entry, while anything else on the contributor’s branch would be merged along with it,\n * so it’s reviewed and merged on the Git service instead.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {boolean} Result.\n */\nexport const canMergePullRequest = (pullRequest) =>\n  !pullRequest.fork && pullRequest.canMerge !== false && !mergeLockedBranch.current;\n\n/**\n * Check whether the publish controls are offered at all: an Open Authoring contributor can’t\n * publish anything, and the collection’s `publish` option can hide them.\n * @param {InternalCollection | undefined} collection Collection the entry belongs to.\n * @returns {boolean} Result.\n */\nconst isPublishVisible = (collection) => !openAuthoring.current && collection?.publish !== false;\n\n/**\n * Check whether the review can be skipped for the entries saved or published along with an entry:\n * those created or edited from its Relation fields. An entry of another collection under Editorial\n * Workflow is reviewed along with the entry it rides along with, so it can only skip the review if\n * its own collection lets it with the `direct_publish` option as well. This is the publishing side\n * of the rule `canSaveAlongHost()` in the Relation field’s quick-add service applies to saving.\n * @param {{ collectionName: string }[]} entries Entries saved or published along with the entry.\n * @returns {boolean} Result.\n */\nexport const canSkipReviewAlong = (entries) =>\n  entries.every(({ collectionName }) => {\n    const collection = getCollection(collectionName);\n\n    return (\n      !isWorkflowEnabled(collection) || getCollectionPublishModeOptions(collection).directPublish\n    );\n  });\n\n/**\n * Check whether the given unpublished entry is at a stage it can be published from, and the\n * publish controls are offered at all. See {@link isPublishAllowed}.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {InternalCollection | undefined} collection Collection the entry belongs to.\n * @returns {boolean} Result.\n */\nconst isPublishStage = (entry, collection) =>\n  isPublishVisible(collection) &&\n  (isPendingDeletion(entry) ||\n    isLastStage(entry, collection) ||\n    // Direct publishing bypasses the review, so an entry can be published from any stage, as long\n    // as the entries riding along with it can skip theirs\n    (getCollectionPublishModeOptions(collection).directPublish &&\n      canSkipReviewAlong(entry.workflow.companions ?? [])));\n\n/**\n * Check whether the signed-in user gets the control to publish the given unpublished entry, or to\n * carry out its pending deletion. The entry can only be published from the last stage — the\n * drafting stage with Preview Workflow — unless the `direct_publish` publish mode option lets it\n * skip the review. The collection’s `publish` option can hide the control altogether, so an editor\n * can move an entry through the review stages but leave the actual publishing to someone else. An\n * Open Authoring contributor can’t merge a pull request on the configured repository, and neither\n * can a user who can push to the entry’s branch but not merge into the configured branch.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {InternalCollection | undefined} collection Collection the entry belongs to.\n * @returns {boolean} Result.\n */\nexport const isPublishAllowed = (entry, collection) =>\n  canMergePullRequest(entry.workflow.pullRequest) && isPublishStage(entry, collection);\n\n/**\n * Get the control the signed-in user gets in the place of the Publish button for the given\n * unpublished entry: the Publish button itself when they can publish the entry (see\n * {@link isPublishAllowed}), or a link to review its pull request on the Git service when it’s one\n * a contributor opened from their fork, at a stage it could otherwise be published from. Such a\n * pull request is never merged from the CMS: see {@link canMergePullRequest}.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {InternalCollection | undefined} collection Collection the entry belongs to.\n * @returns {'publish' | 'review' | undefined} Control, or `undefined` if there’s none.\n */\nexport const getPublishAction = (entry, collection) => {\n  if (isPublishAllowed(entry, collection)) {\n    return 'publish';\n  }\n\n  if (isForkEntry(entry) && !!entry.workflow.pullRequest.url && isPublishStage(entry, collection)) {\n    return 'review';\n  }\n\n  return undefined;\n};\n\n/**\n * Check whether the signed-in user gets the option to save the entry being edited and publish it in\n * one go, bypassing the review, as enabled with the `direct_publish` publish mode option. The\n * collection’s `publish` option hides it just like the Publish button, and an Open Authoring\n * contributor can’t publish anything. Without a pull request, the change is committed straight to\n * the configured branch, so the user has to be able to push there; with one, the pull request is\n * merged, so the user has to be able to merge it.\n * @param {InternalCollection | undefined} collection Collection the entry belongs to.\n * @param {UnpublishedEntry | undefined} entry Unpublished entry, if the entry has a pull request.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/980\n * @see https://github.com/decaporg/decap-cms/issues/4054\n */\nexport const isDirectPublishAllowed = (collection, entry) =>\n  !!collection &&\n  isPublishVisible(collection) &&\n  getCollectionPublishModeOptions(collection).directPublish &&\n  (entry ? canMergePullRequest(entry.workflow.pullRequest) : !lockedBranch.current);\n\n/**\n * Replace each published entry that has an open pull request with its unpublished version, so a\n * list shows the pending content rather than what’s currently live. Entries are matched by file\n * path, including the paths a pull request renamed them from, so that editing a slug doesn’t make\n * the entry appear twice.\n * @param {Entry[]} entries Published entries.\n * @param {UnpublishedEntry[]} drafts Unpublished entries to swap in.\n * @returns {Entry[]} Entries with the drafts swapped in. The array is returned as is when there’s\n * nothing to swap, so a consumer can compare it by identity.\n */\nexport const swapUnpublishedEntries = (entries, drafts) => {\n  if (!drafts.length) {\n    return entries;\n  }\n\n  /** @type {Map<string, Entry>} */\n  const draftMap = new Map();\n\n  drafts.forEach((entry) => {\n    getEntryPaths(entry, { includePrevious: true }).forEach((path) => draftMap.set(path, entry));\n  });\n\n  return entries.map(\n    (entry) =>\n      Object.values(entry.locales)\n        .map(({ path }) => draftMap.get(path))\n        .find(Boolean) ?? entry,\n  );\n};\n\n/**\n * Get the full list of entries in a collection: the published ones, with any pending changes\n * swapped in, plus the unpublished entries that have never been published and are therefore missing\n * from {@link allEntries} altogether. Used where the two have to be counted or searched together,\n * unlike the entry list, which shows them as separate groups.\n * @param {Entry[]} entries Published entries.\n * @param {UnpublishedEntry[]} drafts Unpublished entries.\n * @returns {Entry[]} Merged entries. The given array is returned as is when there’s nothing to swap\n * or append.\n */\nexport const mergeUnpublishedEntries = (entries, drafts) => {\n  const swapped = swapUnpublishedEntries(entries, drafts);\n  const swappedIn = new Set(swapped);\n  // Match by identity rather than by path, which a renamed entry would break\n  const unpublished = drafts.filter((entry) => !swappedIn.has(entry));\n\n  // Keep the array identity when there’s nothing to append, so consumers don’t recompute needlessly\n  return unpublished.length ? [...swapped, ...unpublished] : swapped;\n};\n\n/**\n * Get the entry on the production branch that the given unpublished entry updates. Files are\n * matched by path, because an entry keeps its slug when updated.\n * @param {Entry} entry Entry, which is only looked up when it’s an unpublished one.\n * @returns {Entry | undefined} Published version, or `undefined` if the entry isn’t unpublished, or\n * is an entirely new one that has never been published.\n */\nexport const getPublishedVersion = (entry) => {\n  const { workflow } = /** @type {UnpublishedEntry} */ (entry);\n\n  if (!workflow) {\n    return undefined;\n  }\n\n  // The pull request may have renamed the entry, in which case the published version is still at\n  // one of the previous paths\n  const paths = new Set(getEntryPaths(entry, { includePrevious: true }));\n\n  // `allEntries` only holds published entries; an unpublished one lives in `unpublishedEntries`\n  // until it’s merged\n  return findEntryByPaths(paths);\n};\n\n/**\n * Check if the given unpublished entry updates an entry that already exists on the production\n * branch, rather than being an entirely new one. The result decides whether the pull request can be\n * discarded, leaving the published version behind, or the entry has to be deleted outright.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {boolean} `true` if a published version of the entry exists.\n */\nexport const hasPublishedVersion = (entry) => {\n  // A collection file is part of the collection definition, so it stays on the site whether or not\n  // it has been written yet. Discarding the pull request is the only way to undo the changes\n  if (entry.workflow.fileName) {\n    return true;\n  }\n\n  return !!getPublishedVersion(entry);\n};\n\n/**\n * Check if the given unpublished entry has a published version, like {@link hasPublishedVersion},\n * for use in a derived state. The entry can be published from another view, e.g. from the content\n * editor while the Editorial Workflow page is open, so {@link allEntries} is read here to make the\n * derived state depend on it. On its own, `hasPublishedVersion()` doesn’t always read the store: it\n * returns early for a collection file.\n * @param {UnpublishedEntry | undefined} entry Unpublished entry.\n * @returns {boolean} `true` if a published version of the entry exists, `false` if it doesn’t or\n * no entry is given.\n */\nexport const checkPublishedVersion = (entry) => {\n  if (!entry) {\n    return false;\n  }\n\n  // Create a dependency on the store\n  void allEntries.current;\n\n  return hasPublishedVersion(entry);\n};\n\n/**\n * Check if deleting the given entry only discards its draft: an entry with a pull request that has\n * never been published. Any other entry is taken off the site instead, through a pull request with\n * Editorial Workflow, as discarding its pull request would leave the published version on the\n * site. The entry list shows a pull request’s entry in place of the published one it changes, so\n * both the entry editor and the entry list tell the two apart this way. Like\n * {@link checkPublishedVersion}, it can be used in a derived state.\n * @param {Entry | UnpublishedEntry | undefined} entry Entry.\n * @returns {boolean} Result.\n */\nexport const isDiscardableDraft = (entry) =>\n  !!entry && 'workflow' in entry && !checkPublishedVersion(/** @type {UnpublishedEntry} */ (entry));\n","import { getDateTimeParts } from '@sveltia/utils/datetime';\nimport { truncate } from '@sveltia/utils/string';\n\nimport { getSlugTimeZone, trimSlugEnd } from '$lib/services/common/slug';\nimport { replaceTemplatePlaceholder } from '$lib/services/common/template/replacers';\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { cmsConfig } from '$lib/services/config';\nimport { getEntriesInCollectionFolder } from '$lib/services/contents/collection/entries';\nimport { getIdentifierFieldName } from '$lib/services/contents/collection/identifier';\nimport { getNameInFolder } from '$lib/services/contents/collection/nested';\nimport { renameIfNeeded } from '$lib/services/utils/file';\nimport { getPullRequestEntries } from '$lib/services/workflow';\nimport {\n  getMaxSlugBytes,\n  getSlugByteLength,\n  truncateSlugBytes,\n} from '$lib/services/workflow/branch';\n\n/**\n * @import { ReplaceContext } from '$lib/services/common/template/replacers';\n * @import { FillTemplateOptions, InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * Creates existing slugs list for uniqueness validation. With Editorial Workflow, the entries that\n * are still in a pull request count as well: a new entry taking the slug of one of them would take\n * its file path and its workflow branch too. So do the new entries riding along in the pull request\n * of an entry of another collection, whose files would collide when it’s published. Every entry\n * stored in the collection folder counts, including those the collection’s `filter` option leaves\n * out, which can belong to another collection sharing the folder.\n * @param {string} collectionName Collection name.\n * @param {string | undefined} locale Locale string.\n * @param {string} [dirPath] Folder within the collection folder the new entry goes to, as chosen\n * with the path editor of a collection with nested entries. The slug of an entry there is its sub\n * path, e.g. `docs/intro`, so only the entries directly in the folder are taken into account, by\n * their file names.\n * @returns {string[]} List of existing slugs.\n */\nconst getExistingSlugs = (collectionName, locale, dirPath) => {\n  const slugs = /** @type {string[]} */ (\n    [...getEntriesInCollectionFolder(collectionName), ...getPullRequestEntries(collectionName)]\n      .map((e) => (locale ? e.locales[locale]?.slug : e.slug))\n      .filter(Boolean)\n  );\n\n  return dirPath === undefined\n    ? slugs\n    : slugs.flatMap((slug) => getNameInFolder(slug, dirPath) ?? []);\n};\n\n/**\n * Fills a template string with values from the given options.\n * @param {string} template Template string literal containing tags like `{{title}}`.\n * @param {FillTemplateOptions} options Options.\n * @returns {string} Filled template that can be used for an entry slug, path, etc.\n * @see https://decapcms.org/docs/configuration-options/#slug-type\n * @see https://decapcms.org/docs/configuration-options/#slug\n * @see https://decapcms.org/docs/collection-folder/#media-and-public-folder\n * @see https://sveltiacms.app/en/docs/collections/entries/slugs#entry-slugs\n * @see https://sveltiacms.app/en/docs/media/internal#using-placeholders\n */\nexport const fillTemplate = (template, options) => {\n  const {\n    collection,\n    collectionFile,\n    content: valueMap,\n    currentSlug,\n    locale,\n    dateTimeParts,\n    isIndexFile = false,\n    dirPath,\n    numberedSlugs,\n  } = options;\n\n  const { _type, name: collectionName } = collection;\n  const identifierField = getIdentifierFieldName(_type === 'entry' ? collection : undefined);\n\n  const { slug_length: legacySlugLength = undefined, _file: { basePath, fullPathRegEx } = {} } =\n    _type === 'entry' ? collection : {};\n\n  const slugOptions = cmsConfig.current?.slug;\n  // @todo Remove the legacy option prior to the 1.0 release.\n  const maxlength = legacySlugLength ?? slugOptions?.maxlength;\n\n  /** @type {ReplaceContext} */\n  const context = {\n    replaceSubContext: {\n      ...options,\n      dateTimeParts: dateTimeParts ?? getDateTimeParts({ timeZone: getSlugTimeZone() }),\n      identifierField,\n      basePath,\n      fullPathRegEx,\n    },\n    getFieldArgs: {\n      collectionName,\n      fileName: collectionFile?.name,\n      keyPath: '',\n      valueMap,\n      isIndexFile,\n    },\n  };\n\n  // Use a negative lookahead assertion to support nested template tags in transformations like\n  // `{{fields.slug | default('{{fields.title}}')}}` or `{{draft | ternary('{{subtitle}}',\n  // '{{title}}')}}`\n  let slug = replaceTemplateTags(template, (_match, tag) =>\n    replaceTemplatePlaceholder(tag, context),\n  ).trim();\n\n  // We don’t have to rename it when creating a path with a slug given. Skip truncation because the\n  // slug has already been truncated during its own generation, and truncating the entire filled\n  // path template (e.g. `{{slug}}/+page`) would break the non-slug parts of the path.\n  if (currentSlug) {\n    return slug;\n  }\n\n  // A cut may leave the replacement character at the end, which is a hyphen by default but can be\n  // configured with `slug.sanitize_replacement`, and dots, which a branch name can’t end with; they\n  // go with `trimSlugEnd()`\n  let maxBytes = Infinity;\n\n  // Truncate a long slug if the `slug.maxlength` option is set. Leave the end alone if the slug\n  // isn’t cut\n  if (typeof maxlength === 'number') {\n    const truncated = truncate(slug, maxlength, { ellipsis: '' });\n\n    slug = truncated === slug ? slug : trimSlugEnd(truncated);\n  } else {\n    // Otherwise, cap the slug in bytes so the file name and the Editorial Workflow branch name stay\n    // valid. Existing entries are never renamed, since this only applies to a new slug\n    maxBytes = getMaxSlugBytes({ collectionName, dirPath });\n\n    if (getSlugByteLength(slug) > maxBytes) {\n      slug = trimSlugEnd(truncateSlugBytes(slug, maxBytes));\n    }\n  }\n\n  // `slugify` removes the trailing dots of a value, but the template may still end with one, as in\n  // `{{title}}.`, which a branch name can’t end with. A replacement character in front of it goes\n  // as well, like after a cut\n  if (slug.endsWith('.')) {\n    slug = trimSlugEnd(slug);\n  }\n\n  const existingSlugs = getExistingSlugs(collectionName, locale, dirPath);\n  /**\n   * Make the given slug unique. A dot in a slug is part of the name rather than a file extension,\n   * so a number goes at the end.\n   * @param {string} str Slug.\n   * @returns {string} Unique slug.\n   */\n  const rename = (str) => renameIfNeeded(str, existingSlugs, { hasExtension: false });\n  const filledSlug = slug;\n  let uniqueSlug = rename(slug);\n\n  // If the number pushes the slug over the cap, the slug in front of it gives way, so the number\n  // stays distinct, like Decap CMS. Another number may be needed then, so try again\n  while (maxBytes !== Infinity && getSlugByteLength(uniqueSlug) > maxBytes) {\n    const suffixBytes = getSlugByteLength(uniqueSlug) - getSlugByteLength(slug);\n\n    slug = trimSlugEnd(truncateSlugBytes(slug, maxBytes - suffixBytes));\n    uniqueSlug = rename(slug);\n  }\n\n  if (uniqueSlug !== filledSlug) {\n    numberedSlugs?.set(/** @type {InternalLocaleCode} */ (locale), filledSlug);\n  }\n\n  return uniqueSlug;\n};\n","import {\n  getEntryAssetFolderPath,\n  getExistingEntryAssetFolderPath,\n} from '$lib/services/assets/entry-folder';\nimport { getAssetPathMap } from '$lib/services/assets/lookup';\nimport { fillTemplate } from '$lib/services/common/template';\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getAssociatedCollections } from '$lib/services/contents/entry/collections';\nimport { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\nimport { createPath, getDirName, resolvePath } from '$lib/services/utils/file';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * Entry,\n * InternalCollection,\n * InternalLocaleCode,\n * LocalizedEntry,\n * } from '$lib/types/private';\n */\n\n/**\n * Resolve template tags in an entry’s `media_folder` path, such as `/assets/images/{{slug}}`, using\n * the given locale file of the entry.\n * @param {string} template Folder path that may contain template tags.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {Entry} args.entry Entry.\n * @param {LocalizedEntry} args.localeFile Entry’s locale file the path is resolved against.\n * @returns {string} Resolved path.\n */\nexport const fillMediaFolderTemplate = (template, { collection, entry, localeFile }) =>\n  fillTemplate(template, {\n    type: 'media_folder',\n    collection,\n    content: localeFile.content,\n    currentSlug: entry.slug,\n    entryFilePath: localeFile.path,\n    isIndexFile: isCollectionIndexFile(collection, entry),\n  });\n\n/**\n * Get the collection and the locale file of an entry an asset folder’s path is resolved against.\n * @param {object} args Arguments.\n * @param {string} [args.collectionName] Collection name associated with the asset folder. It’s\n * `undefined` for the global asset folder as well as field-level asset folders in custom editor\n * components, which take the entry’s first collection.\n * @param {Entry} [args.entry] Associated entry. Can be `undefined` when editing a new draft.\n * @param {InternalLocaleCode} [args.locale] Locale whose entry file is used. Default: the\n * collection’s default locale.\n * @returns {{ collection: InternalCollection, entry: Entry, localeFile: LocalizedEntry } |\n * undefined} Context, or `undefined` without an entry or a collection.\n */\nconst getEntryLocaleContext = ({ collectionName, entry, locale }) => {\n  const collection = collectionName\n    ? getCollection(collectionName)\n    : entry\n      ? getAssociatedCollections(entry)[0]\n      : undefined;\n\n  if (!entry || !collection) {\n    return undefined;\n  }\n\n  // An entry-relative asset referenced in a locale is stored beside that locale’s file. With the\n  // `multiple_folders` or `multiple_root_folders` i18n structure, each locale’s file is in a folder\n  // of its own\n  const localeFile = /** @type {LocalizedEntry} */ (\n    getEntryLocaleFile(entry, { locale, defaultLocale: collection._i18n.defaultLocale })\n  );\n\n  return { collection, entry, localeFile };\n};\n\n/**\n * Resolve template tags in an asset folder’s `internalPath`, such as `/assets/images/{{slug}}`,\n * using the given entry’s content.\n * @param {object} args Arguments.\n * @param {string} args.internalPath Internal path that may contain template tags.\n * @param {string} [args.collectionName] Collection name associated with the asset folder. It’s\n * `undefined` for the global asset folder as well as field-level asset folders in custom editor\n * components.\n * @param {Entry} [args.entry] Associated entry. Can be `undefined` when editing a new draft.\n * @param {InternalLocaleCode} [args.locale] Locale whose entry file the path is resolved against.\n * Default: the collection’s default locale.\n * @returns {string | undefined} Resolved path, which is the given `internalPath` itself if it has\n * no template tags, or `undefined` if the tags cannot be resolved, typically because the entry has\n * not been saved yet.\n */\nexport const fillInternalPathTemplate = ({ internalPath, collectionName, entry, locale }) => {\n  if (!hasTemplateTags(internalPath)) {\n    return internalPath;\n  }\n\n  const context = getEntryLocaleContext({ collectionName, entry, locale });\n\n  // Cannot resolve the path without an entry\n  return context ? fillMediaFolderTemplate(internalPath, context) : undefined;\n};\n\n/**\n * Find an asset in the folders an entry’s relative assets can be stored in: the one they are saved\n * to, which is the folder the entry occupies if it has one of its own, e.g.\n * `content/posts/2025/06/hello` for `content/posts/2025/06/hello.md` with a\n * `{{year}}/{{month}}/{{slug}}` path option, and otherwise the folder of the entry file, which is\n * an empty string for an entry file at the repository root; then the folder of the entry file.\n * @param {object} context Entry context, as given by {@link getEntryLocaleContext}.\n * @param {InternalCollection} context.collection Collection the entry belongs to.\n * @param {LocalizedEntry} context.localeFile Entry’s locale file.\n * @param {(string | undefined)[]} segments Path segments below the folder, e.g. the subfolder and\n * the file name.\n * @returns {Asset | undefined} Asset, if found.\n */\nexport const findInEntryBaseFolders = (\n  { collection, localeFile: { path: entryFilePath } },\n  segments,\n) => {\n  const entryFileFolder = getDirName(entryFilePath);\n\n  // A set, as the two are the same unless the entry has a folder of its own\n  return new Set([\n    getEntryAssetFolderPath({ collection, entryFilePath, internalPath: entryFileFolder }),\n    // An asset stored beside the entry file before the entry had a folder of its own, or placed\n    // there by hand, is still found\n    entryFileFolder,\n  ])\n    .values()\n    .map((baseFolder) => getAssetPathMap().get(resolvePath(createPath([baseFolder, ...segments]))))\n    .find(Boolean);\n};\n\n/**\n * Get the path of the given asset in an entry-relative folder, relative to the folder holding the\n * entry’s relative assets, which is where the value is resolved against when the asset is found\n * for it; see `getAssetByRelativePathAndCollection()`.\n * @param {Asset} asset Asset.\n * @param {Entry} [entry] Associated entry. Can be `undefined` when editing a new draft.\n * @param {InternalLocaleCode} [locale] Locale whose entry file the path is relative to.\n * @param {string} [collectionName] Name of the collection the asset folder belongs to.\n * @returns {string | undefined} Relative path, e.g. `images/photo.jpg`, or `undefined` if it\n * cannot be determined.\n */\nconst getEntryRelativePath = (asset, entry, locale, collectionName) => {\n  // A file at the repository root has no folder path\n  const assetFolderPath = getDirName(asset.path);\n\n  const entryFolderPath = entry\n    ? getExistingEntryAssetFolderPath({ entry, locale, collectionName })\n    : undefined;\n\n  if (entryFolderPath !== undefined) {\n    // If the asset is in the same folder as the entry, return the file name only\n    if (assetFolderPath === entryFolderPath) {\n      return asset.name;\n    }\n\n    // Return the path relative to the entry’s folder, e.g. `images/photo.jpg`, or `undefined` if\n    // the path cannot be determined\n    const prefix = entryFolderPath ? `${entryFolderPath}/` : '';\n\n    return asset.path.startsWith(prefix) ? asset.path.slice(prefix.length) : undefined;\n  }\n\n  const { internalPath, internalSubPath } = asset.folder;\n\n  // Resolve simple entry-relative paths like `images/photo.jpg` if the asset is in the same folder\n  // as the entry, which can be the repository root\n  if (asset.path === createPath([internalPath, internalSubPath, asset.name])) {\n    return internalPath ? asset.path.slice(internalPath.length + 1) : asset.path;\n  }\n\n  return undefined;\n};\n\n/**\n * Get the absolute path of the given asset in an entry-relative folder with an absolute public\n * path, which stands for the folder’s subfolder in the folder holding the entry’s relative assets;\n * see {@link findInEntryRelativeFolder}.\n * @param {object} args Arguments.\n * @param {string} args.relativePath Path relative to the folder holding the entry’s relative\n * assets, as given by {@link getEntryRelativePath}, e.g. `images/photo.jpg`.\n * @param {AssetFolderInfo} args.folder Asset folder whose public path applies to the asset.\n * @param {Entry} [args.entry] Associated entry, which fills the template tags in the paths.\n * @param {InternalLocaleCode} [args.locale] Locale whose entry file the tags are filled with.\n * @returns {string | undefined} Absolute path, e.g. `/blog/hello/images/photo.jpg`, or `undefined`\n * if the template tags cannot be filled or the asset is not in the folder’s subfolder.\n */\nconst getEntryRelativeAbsolutePath = ({ relativePath, folder, entry, locale }) => {\n  const { collectionName, internalSubPath = '' } = folder;\n\n  const [publicPath, subPath] = [/** @type {string} */ (folder.publicPath), internalSubPath].map(\n    (internalPath) => fillInternalPathTemplate({ internalPath, collectionName, entry, locale }),\n  );\n\n  if (publicPath === undefined || subPath === undefined) {\n    return undefined;\n  }\n\n  // Normalized like the folder the asset is saved to, so a tag that leaves an empty segment, e.g.\n  // `{{dirname}}/images` for an entry at the collection root, still matches\n  const resolvedSubPath = resolvePath(subPath);\n  const prefix = resolvedSubPath ? `${resolvedSubPath}/` : '';\n\n  // The asset is somewhere else in the entry’s folder, which the public path doesn’t stand for\n  if (!relativePath.startsWith(prefix)) {\n    return undefined;\n  }\n\n  // Normalized the same way as the path is when an asset is saved, so an empty segment left by a\n  // tag, e.g. `/blog//images`, or a `.` or `..` segment is resolved; `/` becomes an empty string\n  const basePath = resolvePath(publicPath);\n\n  return `${basePath ? `/${basePath}` : ''}/${relativePath.slice(prefix.length)}`;\n};\n\n/**\n * Get the public path of the given asset in an entry-relative folder, which is saved as a field\n * value. With an absolute public path, e.g. `/blog/{{slug}}/images`, that’s the absolute path, e.g.\n * `/blog/hello/images/photo.jpg`, which is mapped back to the asset by\n * {@link findInEntryRelativeFolder}. Otherwise, or if the absolute path can’t be determined, it’s\n * the path relative to the folder holding the entry’s relative assets, e.g. `images/photo.jpg`.\n * @param {object} args Arguments.\n * @param {Asset} args.asset Asset.\n * @param {AssetFolderInfo} args.folder Asset folder whose public path applies to the asset.\n * @param {Entry} [args.entry] Associated entry. Can be `undefined` when editing a new draft.\n * @param {InternalLocaleCode} [args.locale] Locale whose entry file the path is relative to.\n * Default: the entry’s first locale.\n * @returns {string | undefined} Absolute path starting with `/` or relative path, or `undefined` if\n * neither can be determined.\n */\nexport const getEntryRelativePublicPath = ({ asset, folder, entry, locale }) => {\n  const relativePath = getEntryRelativePath(asset, entry, locale, folder.collectionName);\n\n  // An absolute public path is the folder’s own, e.g. `/blog/{{slug}}/images`\n  const absolutePath =\n    relativePath !== undefined && folder.publicPath?.startsWith('/')\n      ? getEntryRelativeAbsolutePath({ relativePath, folder, entry, locale })\n      : undefined;\n\n  return absolutePath ?? relativePath;\n};\n\n/**\n * Find an asset in an entry-relative folder by an absolute path stored as a field value. The\n * folder’s absolute public path, e.g. `/blog/{{slug}}/images`, stands for its subfolder in the\n * folder holding the entry’s relative assets, e.g. `content/blog/hello/images`, where the asset was\n * saved by `resolveAssetFolderPaths()`.\n * @param {object} args Arguments.\n * @param {string} args.path Saved absolute path, e.g. `/blog/hello/images/photo.jpg`.\n * @param {AssetFolderInfo} args.folder Entry-relative asset folder with an absolute public path.\n * @param {Entry} [args.entry] Associated entry. Without it, the path is resolved against the\n * collection folder, as a relative path is by `getAssetByRelativePath()` in\n * `$lib/services/assets`.\n * @param {InternalLocaleCode} [args.locale] Locale the path is referenced in, which tells which\n * locale’s entry file the asset is stored beside. Default: the default locale.\n * @returns {Asset | undefined} Asset, if found.\n */\nexport const findInEntryRelativeFolder = ({ path, folder, entry, locale }) => {\n  const { collectionName, internalPath, internalSubPath = '' } = folder;\n\n  /**\n   * Look for the asset beside the given locale’s entry file.\n   * @param {InternalLocaleCode | undefined} _locale Locale.\n   * @returns {Asset | undefined} Asset, if found.\n   */\n  const find = (_locale) => {\n    const context = getEntryLocaleContext({ collectionName, entry, locale: _locale });\n\n    const [publicPath, subPath] = [/** @type {string} */ (folder.publicPath), internalSubPath].map(\n      (template) =>\n        !hasTemplateTags(template)\n          ? template\n          : context\n            ? fillMediaFolderTemplate(template, context)\n            : undefined,\n    );\n\n    if (publicPath === undefined || subPath === undefined) {\n      // Cannot resolve the template tags without an entry\n      return undefined;\n    }\n\n    // Normalized the same way as the path is when the asset is saved, so an empty segment left by\n    // a tag, e.g. `/blog//images`, or a `.` or `..` segment matches the saved value\n    const basePath = resolvePath(publicPath);\n    const prefix = basePath ? `/${basePath}/` : '/';\n\n    if (!path.startsWith(prefix)) {\n      return undefined;\n    }\n\n    const localPath = path.slice(prefix.length);\n\n    // Without an entry, the collection folder, which an entry-relative folder always has\n    return context\n      ? findInEntryBaseFolders(context, [subPath, localPath])\n      : getAssetPathMap().get(resolvePath(createPath([internalPath, subPath, localPath])));\n  };\n\n  return (\n    find(locale) ??\n    // A file in a duplicated or synced field is stored once, beside the default locale’s entry\n    // file, which the other locales then share\n    (locale ? find(undefined) : undefined)\n  );\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { cmsConfig } from '$lib/services/config/state';\n\n/**\n * @import { MediaLibraryService } from '$lib/types/private';\n * @import { CmsConfig, MediaField, MediaLibraries } from '$lib/types/public';\n */\n\n/**\n * Find a media library’s options in the given site or field configuration, supporting both the\n * `media_libraries` map and the legacy `media_library` option. A legacy `media_library` option\n * without a `name`, which is only valid at the field level, applies to the library named in the\n * site-level legacy option.\n * @template {keyof MediaLibraries} T\n * @param {T} libraryName Library name.\n * @param {CmsConfig | MediaField | undefined} config Site or field configuration.\n * @param {string} [siteDefaultName] Name of the library the site-level legacy option configures\n * when it has no `name`, e.g. `default`. When given, a legacy option, even a field-level one\n * naming the library, only applies to the library the site-level legacy option configures.\n * Default: none, so a nameless site-level legacy option configures no library.\n * @returns {MediaLibraries[T] | undefined} Options, `false` if the library is explicitly disabled,\n * or `undefined` if the library is not configured.\n */\nexport const findLibraryOptions = (libraryName, config, siteDefaultName) => {\n  const options = config?.media_libraries?.[libraryName];\n\n  if (options !== undefined && options !== null) {\n    return /** @type {MediaLibraries[T]} */ (options);\n  }\n\n  const { media_library: legacyOptions } = config ?? {};\n  const siteName = cmsConfig.current?.media_library?.name ?? siteDefaultName;\n\n  return legacyOptions &&\n    (legacyOptions.name ?? siteName) === libraryName &&\n    (!siteDefaultName || siteName === libraryName)\n    ? /** @type {MediaLibraries[T]} */ (legacyOptions)\n    : undefined;\n};\n\n/**\n * Merge a media library’s field-level options over its site-level ones, so a field only needs to\n * set the options it overrides: the top-level properties are replaced, and those holding an object,\n * such as `config`, are merged one level deep. A field-level `false` disables the library for the\n * field, while field-level options enable a library the site disables.\n * @template {Record<string, any> | false | undefined} T\n * @param {T} siteOptions Site-level options, `false` if the library is explicitly disabled, or\n * `undefined` if the library is not configured.\n * @param {T} fieldOptions Field-level options, in the same form.\n * @returns {T} Merged options.\n */\nexport const mergeLibraryOptions = (siteOptions, fieldOptions) => {\n  if (fieldOptions === undefined) {\n    return siteOptions;\n  }\n\n  if (!fieldOptions || !siteOptions) {\n    return fieldOptions;\n  }\n\n  /** @type {Record<string, any>} */\n  const merged = { ...siteOptions, ...fieldOptions };\n\n  Object.entries(fieldOptions).forEach(([key, value]) => {\n    if (isObject(value) && isObject(siteOptions[key])) {\n      merged[key] = { ...siteOptions[key], ...value };\n    }\n  });\n\n  return /** @type {T} */ (merged);\n};\n\n/**\n * Resolve a media library’s options for the given field, with the field-level options merged over\n * the site-level ones. See {@link mergeLibraryOptions} for details.\n * @template {keyof MediaLibraries} T\n * @param {T} libraryName Library name.\n * @param {MediaField} [fieldConfig] Field configuration.\n * @returns {MediaLibraries[T] | undefined} Options, `false` if the library is explicitly disabled,\n * or `undefined` if the library is not configured.\n */\nexport const resolveLibraryOptions = (libraryName, fieldConfig) =>\n  /** @type {MediaLibraries[T] | undefined} */ (\n    mergeLibraryOptions(\n      /** @type {any} */ (findLibraryOptions(libraryName, cmsConfig.current)),\n      /** @type {any} */ (findLibraryOptions(libraryName, fieldConfig)),\n    )\n  );\n\n/**\n * Get the names of the media libraries marked with the `default` option, which the Select Assets\n * dialog opens on instead of the first repository folder: those marked at the field level first,\n * then those marked at the site level, so the first one offered can be picked. A field can clear\n * the mark of a site-level one with `default: false`. Only the `media_libraries` map is read, as\n * the legacy `media_library` option configures a single library.\n * @param {MediaField} [fieldConfig] Field configuration.\n * @returns {(keyof MediaLibraries)[]} Library names.\n */\nexport const getPreferredLibraryNames = (fieldConfig) => {\n  const fieldLibraries = fieldConfig?.media_libraries ?? {};\n  const siteLibraries = cmsConfig.current?.media_libraries ?? {};\n  /**\n   * Get a library’s options in the given map, treating `null`, e.g. an empty YAML key, as not\n   * configured, like {@link findLibraryOptions} does.\n   * @param {Record<string, any>} libraries Library option map.\n   * @param {string} name Library name.\n   * @returns {any} Options.\n   */\n  const get = (libraries, name) => libraries[name] ?? undefined;\n\n  // A library marked in the field itself comes first, then the site’s libraries in their order. A\n  // library whose mark is inherited from the site is among the latter, even when the field\n  // configures it too.\n  const names = /** @type {(keyof MediaLibraries)[]} */ ([\n    ...new Set([\n      ...Object.keys(fieldLibraries).filter((name) => get(fieldLibraries, name)?.default === true),\n      ...Object.keys(siteLibraries),\n    ]),\n  ]);\n\n  return names.filter((name) => {\n    // `all` holds shared defaults, not the options of a library\n    if (name === 'all') {\n      return false;\n    }\n\n    const options = mergeLibraryOptions(get(siteLibraries, name), get(fieldLibraries, name));\n\n    return isObject(options) && options.default === true;\n  });\n};\n\n/**\n * Get the cloud storage services that can take files from the CMS. A service without an upload\n * function, like Cloudinary, only takes files through its own widget.\n * @param {[string, MediaLibraryService][]} cloudServiceEntries Cloud storage services.\n * @returns {[string, MediaLibraryService][]} Services that can upload files.\n */\nexport const getUploadableServiceEntries = (cloudServiceEntries) =>\n  cloudServiceEntries.filter(([, { upload }]) => !!upload);\n\n/**\n * Find the first media library marked with the `default` option that’s offered.\n * @param {object} args Arguments.\n * @param {string[]} args.preferredLibraryNames Names of the media libraries marked with the\n * `default` option, in order of precedence, as returned by {@link getPreferredLibraryNames}.\n * `default` stands for the repository.\n * @param {boolean} args.repositoryAvailable Whether a repository folder is offered.\n * @param {[string, MediaLibraryService][]} args.cloudServiceEntries Cloud storage services offered.\n * @param {boolean} [args.uploadRequired] Whether the library has to take files to be uploaded,\n * which leaves out a cloud storage service that can’t upload them.\n * @returns {string | undefined} Library name, or `undefined` if none of the marked libraries is\n * offered.\n */\nexport const findPreferredLibraryName = ({\n  preferredLibraryNames,\n  repositoryAvailable,\n  cloudServiceEntries,\n  uploadRequired = false,\n}) => {\n  const serviceEntries = uploadRequired\n    ? getUploadableServiceEntries(cloudServiceEntries)\n    : cloudServiceEntries;\n\n  return preferredLibraryNames.find((name) =>\n    name === 'default'\n      ? repositoryAvailable\n      : serviceEntries.some(([serviceId]) => serviceId === name),\n  );\n};\n","import { cmsConfig } from '$lib/services/config/state';\nimport {\n  findLibraryOptions,\n  mergeLibraryOptions,\n} from '$lib/services/integrations/media-libraries/options';\n\n/**\n * @import { MediaField, MediaLibraryName } from '$lib/types/public';\n */\n\n/**\n * Get any media library options. Support both new and legacy options at the field level and global.\n * The field-level options are merged over the global ones, one level deep.\n * @param {object} [options] Options.\n * @param {MediaLibraryName} [options.libraryName] Library name.\n * @param {MediaField} [options.fieldConfig] Field configuration.\n * @returns {Record<string, any> | false} Options, or `false` if the library is explicitly disabled.\n */\nexport const getMediaLibraryOptions = ({ libraryName = 'default', fieldConfig } = {}) => {\n  const _cmsConfig = cmsConfig.current;\n  // The legacy `media_library` option without a name configures the default library\n  /** @type {Record<string, any> | false | undefined} */\n  const siteOptions = findLibraryOptions(libraryName, _cmsConfig, 'default');\n  /** @type {Record<string, any> | false | undefined} */\n  const fieldOptions = findLibraryOptions(libraryName, fieldConfig, 'default');\n  // The field-level options are merged over the site-level ones\n  const opts = mergeLibraryOptions(siteOptions, fieldOptions);\n\n  if (opts === false) {\n    return false;\n  }\n\n  // `all` provides shared defaults merged into the `default` library’s `config`. Other libraries\n  // (e.g. Cloudinary) pass `config` directly to their SDK, so we must not pollute it. The layers\n  // are applied from the lowest priority: site-level `all`, site-level `config`, field-level `all`\n  // and field-level `config`, so a field-level option always wins over a site-level one.\n  if (libraryName !== 'default') {\n    return { ...opts };\n  }\n\n  const config = {\n    ..._cmsConfig?.media_libraries?.all,\n    ...(siteOptions ? siteOptions.config : undefined),\n    ...fieldConfig?.media_libraries?.all,\n    ...(fieldOptions ? fieldOptions.config : undefined),\n  };\n\n  return opts?.config !== undefined || Object.keys(config).length > 0\n    ? { ...opts, config }\n    : { ...opts };\n};\n","/**\n * @import {\n * RasterImageConversionFormat,\n * RasterImageFormat,\n * VectorImageFormat,\n * } from '$lib/types/public';\n */\n\n/**\n * Raster image formats, including HEIC, which is an input format: only Safari displays it, so it\n * can only be uploaded where it’s converted.\n * @type {RasterImageFormat[]}\n */\nexport const RASTER_IMAGE_FORMATS = ['avif', 'gif', 'heic', 'jpeg', 'png', 'webp'];\n/**\n * MIME types of a HEIC image. A HEIF file with a `.heif` extension has the `image/heif` type rather\n * than `image/heic`.\n */\nexport const HEIC_IMAGE_TYPES = ['image/heic', 'image/heif'];\n/** MIME types of the raster image formats every browser displays, so HEIC is excluded. */\nexport const RASTER_IMAGE_TYPES = RASTER_IMAGE_FORMATS.filter((format) => format !== 'heic').map(\n  (format) => `image/${format}`,\n);\n/**\n * Regex matching a raster image file extension, along with its dot, at the end of a file name. JPEG\n * files can also have a `.jpe` or `.jfif` extension, and HEIC files a `.heif` extension, so those\n * aliases are included.\n */\nexport const RASTER_IMAGE_EXTENSION_REGEX = /\\.(?:avif|gif|heic|heif|jfif|jpe?g|jpe|png|webp)$/i;\n\n/** @type {VectorImageFormat[]} */\nexport const VECTOR_IMAGE_FORMATS = ['svg'];\nexport const VECTOR_IMAGE_TYPES = ['image/svg+xml'];\n/** Regex matching a vector image file extension, along with its dot, at the end of a file name. */\nexport const VECTOR_IMAGE_EXTENSION_REGEX = /\\.(?:svg)$/i;\n\nexport const SUPPORTED_IMAGE_FORMATS = [...RASTER_IMAGE_FORMATS, ...VECTOR_IMAGE_FORMATS];\nexport const SUPPORTED_IMAGE_TYPES = [...RASTER_IMAGE_TYPES, ...VECTOR_IMAGE_TYPES];\n/**\n * MIME types an image field accepts when HEIC images are converted on upload. Listing the HEIC\n * types in `accept` is what makes the file picker offer HEIC photos — and makes iOS Safari hand\n * them over as they are rather than transcoded to JPEG — so they’re only listed in that case.\n */\nexport const SUPPORTED_IMAGE_TYPES_WITH_HEIC = [...SUPPORTED_IMAGE_TYPES, ...HEIC_IMAGE_TYPES];\n\n/**\n * Display labels of the supported image formats.\n * @type {Record<RasterImageFormat | VectorImageFormat, string>}\n */\nconst IMAGE_FORMAT_LABELS = {\n  avif: 'AVIF',\n  gif: 'GIF',\n  heic: 'HEIC',\n  jpeg: 'JPEG',\n  png: 'PNG',\n  webp: 'WebP',\n  svg: 'SVG',\n};\n\n/**\n * Get the labels of the image formats an `accept` list built from {@link SUPPORTED_IMAGE_TYPES} or\n * {@link SUPPORTED_IMAGE_TYPES_WITH_HEIC} covers, to tell the user which images are accepted.\n * @param {string | undefined} accept Accepted file type specifiers, comma-separated.\n * @returns {string[] | undefined} Labels, or `undefined` if the list isn’t one of those.\n */\nexport const getAcceptedImageFormatLabels = (accept) => {\n  const withHeic = accept === SUPPORTED_IMAGE_TYPES_WITH_HEIC.join(',');\n\n  if (!withHeic && accept !== SUPPORTED_IMAGE_TYPES.join(',')) {\n    return undefined;\n  }\n\n  return SUPPORTED_IMAGE_FORMATS.filter((format) => withHeic || format !== 'heic').map(\n    (format) => IMAGE_FORMAT_LABELS[format],\n  );\n};\n\n/** @type {RasterImageConversionFormat[]} */\nexport const RASTER_IMAGE_CONVERSION_FORMATS = ['webp'];\n","// cspell:ignore APNG IDAT\n/* eslint-disable no-bitwise -- reading flags from binary headers */\n\n/**\n * @import { RasterImageFormat } from '$lib/types/public';\n */\n\n/**\n * Check if the bytes have the given ASCII tag at the given offset.\n * @param {Uint8Array} bytes Bytes.\n * @param {number} offset Offset.\n * @param {string} tag Tag, e.g. `acTL`.\n * @returns {boolean} Result.\n */\nconst hasTag = (bytes, offset, tag) =>\n  [...tag].every((char, index) => bytes[offset + index] === char.charCodeAt(0));\n\n/**\n * Get the size of a color table from the packed fields of a GIF screen or image descriptor.\n * @param {number} flags Packed fields.\n * @returns {number} Size in bytes, or `0` if there is no color table.\n */\nconst getGIFColorTableSize = (flags) => (flags & 0x80 ? 3 * 2 ** ((flags & 0x07) + 1) : 0);\n\n/**\n * Skip the data sub-blocks of a GIF extension or image, which end with an empty block.\n * @param {Uint8Array} bytes Bytes.\n * @param {number} offset Offset of the first sub-block.\n * @returns {number} Offset right after the terminating empty block.\n */\nconst skipGIFSubBlocks = (bytes, offset) => {\n  let position = offset;\n\n  while (position < bytes.length && bytes[position] !== 0) {\n    position += bytes[position] + 1;\n  }\n\n  return position + 1;\n};\n\n/**\n * Check if a GIF image has more than one frame, by counting its image descriptors.\n * @param {Uint8Array} bytes File content.\n * @returns {boolean} Result.\n * @see https://www.w3.org/Graphics/GIF/spec-gif89a.txt\n */\nconst isAnimatedGIF = (bytes) => {\n  // Header (6 bytes) and logical screen descriptor (7 bytes), followed by a global color table\n  let position = 13 + getGIFColorTableSize(bytes[10]);\n  let frameCount = 0;\n\n  while (position < bytes.length) {\n    const introducer = bytes[position];\n\n    if (introducer === 0x21) {\n      // Extension: introducer, label, then sub-blocks\n      position = skipGIFSubBlocks(bytes, position + 2);\n    } else if (introducer === 0x2c) {\n      frameCount += 1;\n\n      if (frameCount > 1) {\n        return true;\n      }\n\n      // Image descriptor (10 bytes), local color table, LZW minimum code size, then sub-blocks\n      position = skipGIFSubBlocks(\n        bytes,\n        position + 10 + getGIFColorTableSize(bytes[position + 9]) + 1,\n      );\n    } else {\n      // Trailer or unknown data\n      break;\n    }\n  }\n\n  return false;\n};\n\n/**\n * Check if a WebP image is animated, which is flagged in the extended (`VP8X`) header and comes\n * with an `ANIM` chunk.\n * @param {Uint8Array} bytes File content.\n * @returns {boolean} Result.\n * @see https://developers.google.com/speed/webp/docs/riff_container#extended_file_format\n */\nconst isAnimatedWebP = (bytes) => hasTag(bytes, 12, 'VP8X') && (bytes[20] & 0x02) !== 0;\n\n/**\n * Check if a PNG image is animated (APNG), which comes with an `acTL` chunk before the image data.\n * @param {Uint8Array} bytes File content.\n * @returns {boolean} Result.\n * @see https://wiki.mozilla.org/APNG_Specification\n */\nconst isAnimatedPNG = (bytes) => {\n  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n  // Skip the 8-byte signature\n  let position = 8;\n\n  // Each chunk: length (4 bytes), type (4 bytes), data, CRC (4 bytes)\n  while (position + 8 <= bytes.length) {\n    if (hasTag(bytes, position + 4, 'acTL')) {\n      return true;\n    }\n\n    if (hasTag(bytes, position + 4, 'IDAT')) {\n      return false;\n    }\n\n    position += view.getUint32(position) + 12;\n  }\n\n  return false;\n};\n\n/**\n * Check if the given image is animated: a GIF with more than one frame, an animated WebP or an\n * APNG. Transforming such an image would only keep its first frame, as the browser decodes no more.\n * @param {Blob} blob File or blob.\n * @param {RasterImageFormat | undefined} format Format sniffed from the content.\n * @returns {Promise<boolean>} Result. `false` for any other format, or if the file can’t be read.\n */\nexport const isAnimatedImage = async (blob, format) => {\n  if (format !== 'gif' && format !== 'webp' && format !== 'png') {\n    return false;\n  }\n\n  /** @type {Uint8Array} */\n  let bytes;\n\n  try {\n    bytes = new Uint8Array(await blob.arrayBuffer());\n  } catch {\n    return false;\n  }\n\n  if (format === 'gif') {\n    return isAnimatedGIF(bytes);\n  }\n\n  if (format === 'webp') {\n    return isAnimatedWebP(bytes);\n  }\n\n  return isAnimatedPNG(bytes);\n};\n","/**\n * @import { RasterImageFormat } from '$lib/types/public';\n */\n\n/**\n * Number of leading bytes to read. The ISO BMFF `ftyp` box Apple writes is 24 to 32 bytes; this\n * leaves room for a longer compatible brand list.\n */\nconst HEADER_LENGTH = 64;\n\n/**\n * Brands of a HEIF file: single images, sequences, and the generic `mif1`/`msf1` brands some\n * Android phones use as the major brand, with `heic` only among the compatible brands.\n * @see https://github.com/strukturag/libheif/blob/master/libheif/file.cc\n */\nconst HEIF_BRANDS = new Set([\n  'heic',\n  'heix',\n  'heim',\n  'heis',\n  'hevc',\n  'hevx',\n  'hevm',\n  'hevs',\n  'mif1',\n  'msf1',\n]);\n\n/** Brands of an AVIF file, which shares the container and typically lists `mif1` as well. */\nconst AVIF_BRANDS = new Set(['avif', 'avis']);\n\n/**\n * Check if the bytes start with the given signature.\n * @param {Uint8Array} bytes Bytes.\n * @param {string} signature Signature, as a string of Latin-1 characters.\n * @param {number} [offset] Offset to check at.\n * @returns {boolean} Result.\n */\nconst startsWith = (bytes, signature, offset = 0) =>\n  [...signature].every((char, index) => bytes[offset + index] === char.charCodeAt(0));\n\n/**\n * Read a 4-character ASCII tag at the given offset.\n * @param {Uint8Array} bytes Bytes.\n * @param {number} offset Offset.\n * @returns {string} Tag.\n */\nconst readTag = (bytes, offset) => String.fromCharCode(...bytes.subarray(offset, offset + 4));\n\n/**\n * Get the brands listed in an ISO BMFF `ftyp` box: the major brand followed by the compatible\n * brands, up to the end of the box or of the bytes read.\n * @param {Uint8Array} bytes Leading bytes of the file.\n * @returns {string[]} Brands. Empty if the file doesn’t start with an `ftyp` box.\n */\nconst getBrands = (bytes) => {\n  if (bytes.length < 12 || readTag(bytes, 4) !== 'ftyp') {\n    return [];\n  }\n\n  const boxSize = new DataView(bytes.buffer, bytes.byteOffset).getUint32(0);\n  const end = Math.min(boxSize, bytes.length);\n  // Major brand at 8, minor version at 12, compatible brands from 16\n  const brands = [readTag(bytes, 8)];\n\n  for (let offset = 16; offset + 4 <= end; offset += 4) {\n    brands.push(readTag(bytes, offset));\n  }\n\n  return brands;\n};\n\n/**\n * Detect the format of a raster image from its content rather than its file name or declared MIME\n * type, both of which come from the file extension and are wrong for a photo that was renamed\n * rather than converted — most commonly a HEIC image saved with a `.jpg` extension.\n * @param {Blob} blob File or blob to be sniffed.\n * @returns {Promise<RasterImageFormat | undefined>} Format, or `undefined` if the content doesn’t\n * start with a known signature, or can’t be read. HEIF variants, including `.heif` files, are\n * reported as `heic`.\n * @see https://en.wikipedia.org/wiki/List_of_file_signatures\n */\nexport const sniffRasterImageFormat = async (blob) => {\n  /** @type {Uint8Array} */\n  let bytes;\n\n  try {\n    bytes = new Uint8Array(await blob.slice(0, HEADER_LENGTH).arrayBuffer());\n  } catch {\n    // The file was deleted or moved after being picked; the caller’s decoding check reports it\n    // rather than failing the whole batch\n    return undefined;\n  }\n\n  if (bytes.length < 12) {\n    return undefined;\n  }\n\n  if (startsWith(bytes, '\\xff\\xd8\\xff')) {\n    return 'jpeg';\n  }\n\n  if (startsWith(bytes, '\\x89PNG')) {\n    return 'png';\n  }\n\n  if (startsWith(bytes, 'GIF8')) {\n    return 'gif';\n  }\n\n  if (startsWith(bytes, 'RIFF') && startsWith(bytes, 'WEBP', 8)) {\n    return 'webp';\n  }\n\n  const brands = getBrands(bytes);\n\n  // AVIF first: an AVIF file usually lists the generic HEIF brand `mif1` as a compatible brand\n  if (brands.some((brand) => AVIF_BRANDS.has(brand))) {\n    return 'avif';\n  }\n\n  if (brands.some((brand) => HEIF_BRANDS.has(brand))) {\n    return 'heic';\n  }\n\n  return undefined;\n};\n","import { loadModule } from '$lib/services/app/dependencies';\nimport { RASTER_IMAGE_CONVERSION_FORMATS } from '$lib/services/utils/media/image';\n\n/** @type {Record<string, boolean>} */\nconst encodingSupportMap = {};\n\n/**\n * Check if the browser supports `canvas.convertToBlob()` encoding for the given format. Safari\n * doesn’t support native WebP encoding, so this returns `false` if the `format` is `webp`.\n * @param {string} format Format, like `webp`.\n * @returns {Promise<boolean>} Result.\n * @see https://bugs.webkit.org/show_bug.cgi?id=183257\n */\nexport const checkIfEncodingIsSupported = async (format) => {\n  if (format in encodingSupportMap) {\n    return encodingSupportMap[format];\n  }\n\n  const type = `image/${format}`;\n  const canvas = new OffscreenCanvas(1, 1);\n  // Need this for Chrome for some reason\n  // eslint-disable-next-line no-unused-vars\n  const context = /** @type {OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d'));\n  const blob = await canvas.convertToBlob({ type });\n  const result = blob.type === type;\n\n  encodingSupportMap[format] = result;\n\n  return result;\n};\n\n/**\n * Check whether the image drawn on the given canvas has any pixel that isn’t fully opaque.\n * @param {OffscreenCanvas} canvas Canvas.\n * @returns {boolean} Result.\n */\nconst hasTransparency = (canvas) => {\n  const context = /** @type {OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d'));\n  const { data } = context.getImageData(0, 0, canvas.width, canvas.height);\n\n  // Every fourth byte is the alpha channel of a pixel\n  for (let index = 3; index < data.length; index += 4) {\n    if (data[index] < 255) {\n      return true;\n    }\n  }\n\n  return false;\n};\n\n/**\n * Export Canvas data as an image blob. If the browser doesn’t support native encoding for the given\n * format (e.g. WebP on Safari), use the jSquash library as fallback, or a format the browser does\n * encode if `nativeOnly` is set.\n * @param {OffscreenCanvas} canvas Canvas to be exported.\n * @param {object} [options] Options.\n * @param {string} [options.format] Format, like `webp`.\n * @param {number} [options.quality] Image quality between 0 and 100.\n * @param {boolean} [options.nativeOnly] Whether to use JPEG, or PNG for an image with transparency,\n * rather than load an encoder for a format the browser can’t encode. Encoding with the library\n * takes a while on the main thread, which is fine for a file the user is uploading, but not for\n * every thumbnail in a folder.\n * @returns {Promise<Blob>} Image blob.\n * @see https://github.com/jamsinclair/jSquash\n */\nexport const exportCanvasAsBlob = async (\n  canvas,\n  { format = 'webp', quality = 85, nativeOnly = false } = {},\n) => {\n  const type = `image/${format}`;\n  const supported = await checkIfEncodingIsSupported(format);\n\n  if (!supported && nativeOnly) {\n    return canvas.convertToBlob({\n      // JPEG has no transparency, which would come out black\n      type: hasTransparency(canvas) ? 'image/png' : 'image/jpeg',\n      quality: quality / 100,\n    });\n  }\n\n  if (!supported && /** @type {string[]} */ (RASTER_IMAGE_CONVERSION_FORMATS).includes(format)) {\n    const context = /** @type {OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d'));\n    const imageData = context.getImageData(0, 0, canvas.width, canvas.height);\n\n    try {\n      /** @type {import('@jsquash/webp').encode} */\n      const encode = (await loadModule(`@jsquash/${format}`, 'encode.js?module')).default;\n      const buffer = await encode(imageData, { quality });\n\n      return new Blob([buffer], { type });\n    } catch {\n      //\n    }\n  }\n\n  return canvas.convertToBlob({ type, quality: quality / 100 });\n};\n","import { getUnpkgURL, loadModule } from '$lib/services/app/dependencies';\nimport { createModuleWorker } from '$lib/services/utils/media/image/heic-worker-factory';\nimport { createConcurrencyLimiter } from '$lib/services/utils/scheduling';\n\n/**\n * How long the worker is kept after its last job. Decoding a photo grows the WebAssembly heap to\n * several hundred megabytes, and the heap never shrinks, so the worker is terminated once a batch\n * — an upload, or the thumbnails of an asset list — is done, rather than kept for the session.\n * Long enough for the next asset in a list to reuse it without another fetch and compile.\n */\nconst IDLE_TIMEOUT = 10000;\n/** @type {Promise<Worker> | undefined} */\nlet workerPromise;\n/** @type {boolean} */\nlet workerUnavailable = false;\n/** @type {ReturnType<typeof setTimeout> | undefined} */\nlet idleTimer;\n/**\n * Runs the decode jobs one at a time: a decode blocks the worker anyway, and running them serially\n * means at most one photo’s pixels are held at once.\n */\nconst enqueue = createConcurrencyLimiter(1);\n\n/**\n * Get the source of the module worker. The decoder is imported from UNPKG inside the worker, which\n * has to be created from a same-origin URL, hence a Blob URL. The first message reports whether the\n * import succeeded; each later message is the decoded pixels of a job, or the error.\n * @returns {string} Script.\n */\nconst getWorkerScript = () => {\n  const moduleURL = `${getUnpkgURL('@discourse/heic')}/index.js`;\n\n  return `\n    import(${JSON.stringify(moduleURL)}).then(\n      ({ decode }) => {\n        self.onmessage = async ({ data }) => {\n          try {\n            const { width, height, data: pixels } = await decode(data);\n\n            postMessage({ width, height, data: pixels }, [pixels.buffer]);\n          } catch (error) {\n            postMessage({ error: String(error?.message ?? error) });\n          }\n        };\n\n        postMessage({ ready: true });\n      },\n      (error) => postMessage({ error: String(error?.message ?? error) }),\n    );\n  `;\n};\n\n/**\n * Error thrown when a worker can’t be started at all, as opposed to the decoder failing to load in\n * it: only the former is worth falling back to the main thread for.\n */\nclass WorkerUnavailableError extends Error {}\n\n/**\n * Create the worker and wait for the decoder to load in it.\n * @returns {Promise<Worker>} Worker.\n * @throws {WorkerUnavailableError} If the worker can’t be created or started, e.g. because a\n * Content Security Policy doesn’t allow `blob:` workers.\n * @throws {Error} If the decoder can’t be loaded in the worker.\n */\nconst createWorker = () =>\n  new Promise((resolve, reject) => {\n    const blob = new Blob([getWorkerScript()], { type: 'text/javascript' });\n    const blobURL = URL.createObjectURL(blob);\n    /** @type {Worker} */\n    let worker;\n\n    try {\n      worker = createModuleWorker?.() ?? new Worker(blobURL, { type: 'module' });\n    } catch (error) {\n      // Chrome throws here when a Content Security Policy blocks the worker\n      URL.revokeObjectURL(blobURL);\n      reject(new WorkerUnavailableError('Failed to create a worker', { cause: error }));\n\n      return;\n    }\n\n    /**\n     * Handle the first message, which reports whether the decoder loaded.\n     * @param {MessageEvent} event Event.\n     */\n    const onMessage = ({ data }) => {\n      // eslint-disable-next-line no-use-before-define\n      cleanup();\n\n      if (data.ready) {\n        resolve(worker);\n      } else {\n        worker.terminate();\n        reject(new Error(data.error));\n      }\n    };\n\n    /**\n     * Handle the worker failing to start, e.g. Firefox reporting a Content Security Policy\n     * violation, which it does here rather than by throwing.\n     * @param {ErrorEvent} event Event.\n     */\n    const onError = (event) => {\n      // eslint-disable-next-line no-use-before-define\n      cleanup();\n      worker.terminate();\n      reject(new WorkerUnavailableError(event.message));\n    };\n\n    /**\n     * Remove the listeners, so they don’t act on later messages and errors, and release the URL,\n     * as the script has been fetched by now.\n     */\n    const cleanup = () => {\n      worker.removeEventListener('message', onMessage);\n      worker.removeEventListener('error', onError);\n      URL.revokeObjectURL(blobURL);\n    };\n\n    worker.addEventListener('message', onMessage);\n    worker.addEventListener('error', onError);\n  });\n\n/**\n * Get the worker, creating it if needed. A creation failure isn’t cached, so it can be retried.\n * @returns {Promise<Worker>} Worker.\n * @throws {Error} If the worker can’t be created.\n */\nconst getWorker = () => {\n  clearTimeout(idleTimer);\n\n  workerPromise ??= createWorker().catch((error) => {\n    workerPromise = undefined;\n\n    throw error;\n  });\n\n  return workerPromise;\n};\n\n/**\n * Terminate the worker, releasing the decoder’s memory.\n */\nconst terminateWorker = async () => {\n  const worker = await workerPromise;\n\n  workerPromise = undefined;\n  worker?.terminate();\n};\n\n/**\n * Decode a HEIC image in the worker.\n * @param {Worker} worker Worker.\n * @param {ArrayBuffer} buffer File content. Transferred to the worker.\n * @returns {Promise<ImageData>} Decoded pixels.\n * @throws {Error} If the image can’t be decoded.\n */\nconst decodeInWorker = (worker, buffer) =>\n  new Promise((resolve, reject) => {\n    /**\n     * Handle a message from the worker. Jobs run one at a time, so the next message is the result\n     * of this one.\n     * @param {MessageEvent} event Event.\n     */\n    const onMessage = ({ data }) => {\n      // eslint-disable-next-line no-use-before-define\n      cleanup();\n      idleTimer = setTimeout(terminateWorker, IDLE_TIMEOUT);\n\n      if (data.error) {\n        reject(new Error(data.error));\n\n        return;\n      }\n\n      try {\n        resolve(new ImageData(data.data, data.width, data.height));\n      } catch (error) {\n        // Pixels that don’t match the dimensions; an exception here would otherwise be swallowed\n        // by the event listener and leave the job pending forever\n        reject(error);\n      }\n    };\n\n    /**\n     * Handle an uncaught error in the worker. Its state is unknown, so it’s replaced: a message\n     * posted to a dead worker would never be answered, and the queue would never move on.\n     * @param {ErrorEvent} event Event.\n     */\n    const onError = (event) => {\n      // eslint-disable-next-line no-use-before-define\n      cleanup();\n      workerPromise = undefined;\n      worker.terminate();\n      reject(new Error(event.message));\n    };\n\n    /**\n     * Remove the listeners.\n     */\n    const cleanup = () => {\n      worker.removeEventListener('message', onMessage);\n      worker.removeEventListener('error', onError);\n    };\n\n    worker.addEventListener('message', onMessage);\n    worker.addEventListener('error', onError);\n    worker.postMessage(buffer, [buffer]);\n  });\n\n/**\n * Decode a HEIC image on the main thread. Only used when a worker can’t be created; a decode takes\n * half a second for a 12-megapixel photo, during which the UI is frozen.\n * @param {ArrayBuffer} buffer File content.\n * @returns {Promise<ImageData>} Decoded pixels.\n * @throws {Error} If the decoder can’t be loaded or the image can’t be decoded.\n */\nconst decodeOnMainThread = async (buffer) => {\n  /** @type {{ decode: (buffer: ArrayBuffer) => Promise<ImageData> }} */\n  const { decode } = await loadModule('@discourse/heic', 'index.js');\n\n  return decode(buffer);\n};\n\n/**\n * Decode a HEIC image, in the worker if one can be started, on the main thread otherwise.\n * @param {ArrayBuffer} buffer File content.\n * @returns {Promise<ImageData>} Decoded pixels.\n * @throws {Error} If the image can’t be decoded, or the decoder can’t be loaded.\n */\nconst decodeBuffer = async (buffer) => {\n  if (!workerUnavailable) {\n    /** @type {Worker | undefined} */\n    let worker;\n\n    try {\n      worker = await getWorker();\n    } catch (error) {\n      if (!(error instanceof WorkerUnavailableError)) {\n        // The decoder couldn’t be loaded in the worker, e.g. UNPKG is blocked; it wouldn’t load on\n        // the main thread either, and a transient failure is worth retrying in the worker\n        throw error;\n      }\n\n      // A Content Security Policy that doesn’t allow `blob:` workers, most likely; the decoder can\n      // still be loaded directly if the policy allows UNPKG, as it must for the other libraries\n      workerUnavailable = true;\n    }\n\n    if (worker) {\n      return decodeInWorker(worker, buffer);\n    }\n  }\n\n  return decodeOnMainThread(buffer);\n};\n\n/**\n * Decode a HEIC (HEIF) image, which browsers other than Safari can’t decode natively, using the\n * `@discourse/heic` WebAssembly build of libheif. The decoder runs in a worker, one image at a\n * time, so a batch of photos doesn’t freeze the UI or hold every photo’s pixels in memory at once.\n * @param {Blob} blob File or blob.\n * @returns {Promise<ImageData>} Decoded pixels, which `createImageBitmap()` accepts as a source.\n * @throws {Error} If the image can’t be decoded.\n * @see https://github.com/discourse/jSquash\n * @see https://github.com/jamsinclair/jSquash/pull/101\n */\nexport const decodeHEIC = (blob) =>\n  // Read the file within the queue, so only one photo is held in memory at a time\n  enqueue(async () => decodeBuffer(await blob.arrayBuffer()));\n","/**\n * @import { InternalImageTransformationOptions } from '$lib/types/private';\n */\n\n/**\n * Fill in the defaults of the image transformation options. `width` and `height` have no default,\n * as it depends on the size of the source.\n * @param {InternalImageTransformationOptions} [options] Options.\n * @returns {Required<Omit<InternalImageTransformationOptions, 'width' | 'height'>> &\n * Pick<InternalImageTransformationOptions, 'width' | 'height'>} Options with the defaults.\n */\nexport const resolveTransformOptions = ({\n  format = 'png',\n  quality = 85,\n  width = undefined,\n  height = undefined,\n  fit = 'scale-down',\n  nativeOnly = false,\n} = {}) => ({ format, quality, width, height, fit, nativeOnly });\n","/**\n * @import { ImageFitOption, MediaDimensions } from '$lib/types/private';\n */\n\n/**\n * Calculate the size of resized canvas.\n * @param {MediaDimensions} source Source dimensions.\n * @param {{ width?: number, height?: number, fit?: ImageFitOption }} [target] Target dimensions and\n * fit option.\n * @returns {{ scale: number, width: number, height: number }} Scale and new width/height.\n */\nexport const calculateResize = (\n  { width: originalWidth, height: originalHeight },\n  {\n    width: targetWidth = originalWidth,\n    height: targetHeight = originalHeight,\n    fit = 'scale-down',\n  } = {},\n) => {\n  const original = { scale: 1, width: originalWidth, height: originalHeight };\n\n  if (originalWidth === targetWidth && originalHeight === targetHeight) {\n    return original;\n  }\n\n  const isSmaller = originalWidth <= targetWidth && originalHeight <= targetHeight;\n  let scale = 1;\n  let newWidth = 0;\n  let newHeight = 0;\n\n  if (fit === 'scale-down') {\n    if (isSmaller) {\n      return original;\n    }\n\n    fit = 'contain';\n  }\n\n  if (fit === 'contain') {\n    scale = Math.min(targetWidth / originalWidth, targetHeight / originalHeight);\n    newWidth = originalWidth * scale;\n    newHeight = originalHeight * scale;\n  }\n\n  return { scale, width: newWidth, height: newHeight };\n};\n\n/**\n * Resize a Canvas based on the given dimension.\n * @param {HTMLCanvasElement | OffscreenCanvas} canvas Canvas to be resized.\n * @param {MediaDimensions} source Source dimensions.\n * @param {{ width?: number, height?: number, fit?: ImageFitOption }} [target] Target dimensions and\n * fit option.\n * @returns {{ scale: number, width: number, height: number }} Scale and new width/height.\n */\nexport const resizeCanvas = (canvas, source, target) => {\n  const { scale, width, height } = calculateResize(source, target);\n\n  canvas.width = width;\n  canvas.height = height;\n\n  return { scale, width, height };\n};\n","import { loadModule } from '$lib/services/app/dependencies';\nimport { exportCanvasAsBlob } from '$lib/services/utils/media/image/encode';\nimport { decodeHEIC } from '$lib/services/utils/media/image/heic';\nimport { resolveTransformOptions } from '$lib/services/utils/media/image/options';\nimport { resizeCanvas } from '$lib/services/utils/media/image/resize';\nimport { sniffRasterImageFormat } from '$lib/services/utils/media/image/sniff';\n\n/**\n * @import { InternalImageTransformationOptions } from '$lib/types/private';\n */\n\n/**\n * Options for transforming an image to a thumbnail, which is a WebP image with a maximum width and\n * height of 512 pixels, and a quality of 85, or a JPEG or PNG image where WebP can’t be encoded.\n * @type {InternalImageTransformationOptions}\n */\nexport const THUMBNAIL_TRANSFORM_OPTIONS = {\n  format: 'webp',\n  quality: 85,\n  width: 512,\n  height: 512,\n  fit: 'contain',\n  // A thumbnail is only shown in the CMS, so where WebP can’t be encoded natively, another format\n  // will do, rather than loading an encoder for every thumbnail\n  nativeOnly: true,\n};\n\n/**\n * Create an image source from a Blob URL. This function creates an `<img>` element, waits for it to\n * load, and returns the image element along with its natural dimensions.\n * @param {object} args Arguments.\n * @param {File | Blob} args.blob File or blob to be converted to an image source.\n * @returns {Promise<{ source: CanvasImageSource, naturalWidth: number, naturalHeight: number }>}\n * Image element and its natural dimensions.\n * @throws {Error} If the browser cannot decode the image.\n */\nexport const createImageSource = async ({ blob }) => {\n  const blobURL = URL.createObjectURL(blob);\n  const image = new Image();\n\n  return new Promise((resolve, reject) => {\n    image.addEventListener(\n      'load',\n      () => {\n        resolve({\n          source: image,\n          naturalWidth: image.naturalWidth,\n          naturalHeight: image.naturalHeight,\n        });\n\n        URL.revokeObjectURL(blobURL);\n      },\n      { once: true },\n    );\n\n    // Files the browser can’t decode, such as a HEIC image saved with a `.jpg` extension, fire\n    // `error` instead of `load`\n    image.addEventListener(\n      'error',\n      () => {\n        URL.revokeObjectURL(blobURL);\n        reject(new Error('Failed to decode image'));\n      },\n      { once: true },\n    );\n\n    image.src = blobURL;\n  });\n};\n\n/**\n * Create a video source from a Blob URL. This function creates a `<video>` element, waits for it to\n * be ready, and returns the video element along with its natural dimensions.\n * @param {object} args Arguments.\n * @param {File | Blob} args.blob File or blob to be converted to an video source.\n * @returns {Promise<{ source: CanvasImageSource, naturalWidth: number, naturalHeight: number }>}\n * Video element and its natural dimensions.\n * @throws {Error} If the browser cannot decode the video.\n */\nexport const createVideoSource = async ({ blob }) => {\n  const blobURL = URL.createObjectURL(blob);\n  const video = document.createElement('video');\n\n  return new Promise((resolve, reject) => {\n    video.addEventListener(\n      'canplay',\n      () => {\n        video.pause();\n\n        resolve({\n          source: video,\n          naturalWidth: video.videoWidth,\n          naturalHeight: video.videoHeight,\n        });\n\n        URL.revokeObjectURL(blobURL);\n      },\n      { once: true },\n    );\n\n    // Files the browser can’t decode fire `error` instead of `canplay`. The element is removed here\n    // because the caller only cleans it up on the success path.\n    video.addEventListener(\n      'error',\n      () => {\n        document.body.removeChild(video);\n        URL.revokeObjectURL(blobURL);\n        reject(new Error('Failed to decode video'));\n      },\n      { once: true },\n    );\n\n    video.muted = true;\n    video.autoplay = true;\n    video.playsInline = true;\n\n    // Add `<video>` to DOM or it won’t be rendered on canvas\n    video.style.opacity = '0';\n    video.style.pointerEvents = 'none';\n    document.body.appendChild(video);\n\n    // Assign the source last, so the element is already in the DOM when `error` fires\n    video.src = blobURL;\n  });\n};\n\n/**\n * Get an image source from a Blob or File. If the Blob is a video, create a `<video>` element, and\n * return it. If it’s an image, create an `<img>` element and return it.\n * @param {File | Blob} blob File or blob to be converted to an image source.\n * @returns {Promise<{ source: CanvasImageSource, naturalWidth: number, naturalHeight: number }>}\n * Canvas image source and its natural dimensions.\n */\nexport const createSource = async (blob) => {\n  if (blob.type.startsWith('video/')) {\n    return createVideoSource({ blob });\n  }\n\n  return createImageSource({ blob });\n};\n\n/**\n * Create an image bitmap from a Blob the browser can’t decode natively, by decoding it with a\n * library if it’s a HEIC image, which only Safari decodes natively.\n * @param {File | Blob} blob File or blob.\n * @returns {Promise<ImageBitmap | undefined>} Bitmap, or `undefined` if the blob isn’t a HEIC\n * image.\n * @throws {Error} If the HEIC image can’t be decoded.\n */\nconst createFallbackImageBitmap = async (blob) => {\n  // Sniff the content rather than trust the type: a HEIC photo is often saved with a `.jpg`\n  // extension, and the `.heic` type isn’t set by every platform\n  if ((await sniffRasterImageFormat(blob)) !== 'heic') {\n    return undefined;\n  }\n\n  return createImageBitmap(await decodeHEIC(blob));\n};\n\n/**\n * Convert the given image file to another format.\n * @param {File | Blob} blob Source file.\n * @param {InternalImageTransformationOptions} [options] Options.\n * @returns {Promise<Blob>} New image file.\n * @throws {Error} If the file is not an image.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob\n * @see https://stackoverflow.com/q/62909538\n */\nexport const transformImage = async (blob, options = {}) => {\n  const {\n    format,\n    quality,\n    width: requestedWidth,\n    height: requestedHeight,\n    fit,\n    nativeOnly,\n  } = resolveTransformOptions(options);\n\n  /** @type {CanvasImageSource | undefined} */\n  let source;\n  /** @type {number} */\n  let naturalWidth = 0;\n  /** @type {number} */\n  let naturalHeight = 0;\n\n  try {\n    source = await createImageBitmap(blob);\n  } catch {\n    // Not a format the browser decodes natively, or a video, or SVG\n    source = await createFallbackImageBitmap(blob);\n  }\n\n  if (source) {\n    ({ width: naturalWidth, height: naturalHeight } = source);\n  } else {\n    // Fall back to `<img>` or `<video>`; this includes SVG\n    ({ source, naturalWidth, naturalHeight } = await createSource(blob));\n  }\n\n  const width = requestedWidth ?? naturalWidth;\n  const height = requestedHeight ?? naturalHeight;\n  const canvas = new OffscreenCanvas(512, 512);\n  const context = /** @type {OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d'));\n\n  resizeCanvas(canvas, { width: naturalWidth, height: naturalHeight }, { fit, width, height });\n  context.drawImage(source, 0, 0, canvas.width, canvas.height);\n\n  // Clean up\n  if (source instanceof HTMLVideoElement) {\n    document.body.removeChild(source);\n  } else if ('close' in source) {\n    // An `ImageBitmap` holds the decoded pixels until it’s closed, and a batch of thumbnails would\n    // otherwise keep a full-size copy of every image around until the garbage collector gets to it\n    source.close();\n  }\n\n  return exportCanvasAsBlob(canvas, { format, quality, nativeOnly });\n};\n\n/**\n * Optimize a SVG image using the SVGO library.\n * @param {File | Blob} blob Source file.\n * @returns {Promise<Blob>} Optimized image file.\n * @see https://github.com/svg/svgo/issues/1050\n */\nexport const optimizeSVG = async (blob) => {\n  const string = await blob.text();\n\n  try {\n    /** @type {import('svgo')} */\n    const { optimize } = await loadModule('svgo', 'dist/svgo.browser.js');\n    const { data } = optimize(string);\n\n    return new Blob([data], { type: blob.type });\n  } catch {\n    //\n  }\n\n  return blob;\n};\n","import { isValidFileType } from '@sveltia/utils/file';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { getMediaLibraryOptions } from '$lib/services/integrations/media-libraries';\nimport {\n  RASTER_IMAGE_EXTENSION_REGEX,\n  RASTER_IMAGE_FORMATS,\n  SUPPORTED_IMAGE_TYPES,\n  SUPPORTED_IMAGE_TYPES_WITH_HEIC,\n} from '$lib/services/utils/media/image';\nimport { isAnimatedImage } from '$lib/services/utils/media/image/animation';\nimport { sniffRasterImageFormat } from '$lib/services/utils/media/image/sniff';\nimport { optimizeSVG, transformImage } from '$lib/services/utils/media/image/transform';\nimport mime from '$lib/services/utils/mime';\n\n/**\n * @import {\n * DefaultMediaLibraryConfig,\n * FileTransformations,\n * MediaField,\n * RasterImageFormat,\n * RasterImageTransformationOptions,\n * } from '$lib/types/public';\n */\n\n/**\n * Normalize the `filename_template` media library option.\n * @param {unknown} template Option value.\n * @returns {string | undefined} Template, or `undefined` if it’s not a non-blank string.\n */\nexport const normalizeFileNameTemplate = (template) =>\n  typeof template === 'string' && template.trim() ? template.trim() : undefined;\n\n/**\n * Get normalized default media library options.\n * @param {object} [options] Options.\n * @param {MediaField} [options.fieldConfig] Field configuration.\n * @returns {{ enabled: boolean, config: DefaultMediaLibraryConfig }} Options.\n */\nexport const getDefaultMediaLibraryOptions = ({ fieldConfig } = {}) => {\n  const options = getMediaLibraryOptions({ fieldConfig });\n\n  /** @type {DefaultMediaLibraryConfig} */\n  const {\n    max_file_size: maxSize,\n    multiple,\n    slugify_filename: slugify,\n    filename_template: fileNameTemplate,\n    transformations,\n  } = typeof options === 'boolean' ? {} : (options?.config ?? {});\n\n  return {\n    enabled: options !== false,\n    config: {\n      max_file_size: typeof maxSize === 'number' && Number.isInteger(maxSize) ? maxSize : Infinity,\n      multiple: typeof multiple === 'boolean' ? multiple : false,\n      slugify_filename: typeof slugify === 'boolean' ? slugify : false,\n      filename_template: normalizeFileNameTemplate(fileNameTemplate),\n      transformations: isObject(transformations) ? transformations : undefined,\n    },\n  };\n};\n\n/**\n * Normalize a format name to one of {@link RASTER_IMAGE_FORMATS}.\n * @param {string | undefined} format Format, like `jpeg`.\n * @returns {RasterImageFormat | undefined} Format, or `undefined` if it’s not one of them.\n */\nconst toRasterImageFormat = (format) =>\n  format && /** @type {string[]} */ (RASTER_IMAGE_FORMATS).includes(format)\n    ? /** @type {RasterImageFormat} */ (format)\n    : undefined;\n\n/**\n * Get the formats of a raster image file: the one its content says, and the one its type says. The\n * content is sniffed because a HEIC photo is often saved with a `.jpg` extension, and a `.heic`\n * file doesn’t get the `image/heic` type on every platform.\n * @param {File} file File.\n * @returns {Promise<{ sourceFormat?: RasterImageFormat, declaredFormat?: RasterImageFormat }>}\n * Formats. `sourceFormat` is `undefined` if the file isn’t a supported raster image.\n */\nconst getRasterImageFormats = async (file) => {\n  const [type, subType] = file.type.split('/');\n\n  if (type !== 'image' && !RASTER_IMAGE_EXTENSION_REGEX.test(file.name)) {\n    return {};\n  }\n\n  const declaredFormat = toRasterImageFormat(subType);\n  const sourceFormat = toRasterImageFormat(await sniffRasterImageFormat(file)) ?? declaredFormat;\n\n  return { sourceFormat, declaredFormat };\n};\n\n/**\n * Check whether HEIC images are converted with the given transformations, either by a HEIC-specific\n * or a generic raster image transformation.\n * @param {FileTransformations | undefined} transformations File transformation options.\n * @returns {boolean} Result.\n */\nexport const canConvertHEIC = (transformations) =>\n  !!(transformations?.heic ?? transformations?.raster_image);\n\n/**\n * Get the MIME types an image field or picker accepts: the formats every browser displays, plus\n * HEIC if it’s converted on upload.\n * @param {FileTransformations | undefined} transformations File transformation options.\n * @returns {string[]} MIME types.\n */\nexport const getAcceptedImageTypes = (transformations) =>\n  canConvertHEIC(transformations) ? SUPPORTED_IMAGE_TYPES_WITH_HEIC : SUPPORTED_IMAGE_TYPES;\n\n/**\n * Get the file types a File/Image field or an asset picker accepts, as the value of the `accept`\n * attribute of a file input.\n * @param {object} args Arguments.\n * @param {string} [args.accept] File types configured with the `accept` option, which take\n * precedence.\n * @param {boolean} args.image Whether images are picked, in which case the image types are given,\n * so the asset browser only offers images.\n * @param {FileTransformations | undefined} args.transformations File transformation options. HEIC\n * photos are accepted only if they’re converted on upload.\n * @returns {string | undefined} Comma-separated file types, or `undefined` if any file is accepted.\n */\nexport const getAcceptedFileTypes = ({ accept, image, transformations }) =>\n  accept ?? (image ? getAcceptedImageTypes(transformations).join(',') : undefined);\n\n/**\n * Check whether a file or an asset is one of the given file types, matched by extension or MIME\n * type the same way the browser matches the `accept` attribute of a file input.\n * @param {{ name: string, type?: string }} file File or asset. An asset has no type, and a file may\n * come with an empty one, so the MIME type of the file extension is used then.\n * @param {string | undefined} accept Comma-separated file types, as given by\n * {@link getAcceptedFileTypes}. Any file is accepted if it’s `undefined` or blank.\n * @returns {boolean} Result.\n */\nexport const isAcceptedFile = ({ name, type }, accept) =>\n  isValidFileType(\n    /** @type {File} */ ({ name, type: type || mime.getType(name) || '' }),\n    (accept ?? '')\n      .split(',')\n      .map((specifier) => specifier.trim())\n      .filter(Boolean),\n  );\n\n/**\n * Process the given file by applying a transformation if available.\n * @param {File} file Original file.\n * @param {FileTransformations} transformations File transformation options. The options are\n * validated by the config parser, so they are used as is here.\n * @returns {Promise<File>} Transformed file, or the original file if no transformation is applied\n * or the transformation fails.\n * @throws {Error} If the file is a HEIC image to be converted that can’t be decoded. Browsers\n * other than Safari can’t display a HEIC image, so it’s not uploaded as is in that case.\n */\nexport const transformFile = async (file, transformations) => {\n  const [type, subType] = file.type.split('/');\n\n  // Process SVG image\n  if (type === 'image' && subType === 'svg+xml') {\n    if (transformations.svg?.optimize) {\n      return new File([await optimizeSVG(file)], file.name, { type: file.type });\n    }\n\n    return file;\n  }\n\n  // Process raster image\n  const { sourceFormat, declaredFormat } = await getRasterImageFormats(file);\n\n  if (!sourceFormat) {\n    return file;\n  }\n\n  const formatTransformations =\n    /** @type {Record<string, RasterImageTransformationOptions | undefined>} */ (transformations);\n\n  // A format-specific transformation for the actual format first, then one for the declared\n  // format, so a JPEG image saved with a `.png` extension is still converted with `png` options\n  /** @type {RasterImageTransformationOptions | undefined} */\n  const transformation =\n    formatTransformations[sourceFormat] ??\n    (declaredFormat ? formatTransformations[declaredFormat] : undefined) ??\n    transformations.raster_image;\n\n  // An animated GIF, WebP or PNG would be flattened to its first frame, as the browser decodes no\n  // more, so it’s uploaded as is\n  if (!transformation || (await isAnimatedImage(file, sourceFormat))) {\n    return file;\n  }\n\n  const { format = 'webp', quality = 85, width, height } = transformation;\n  /** @type {Blob} */\n  let blob;\n\n  try {\n    blob = await transformImage(file, { format, quality, width, height });\n  } catch (error) {\n    if (sourceFormat === 'heic') {\n      throw new Error('Failed to decode HEIC image', { cause: error });\n    }\n\n    // The browser can’t decode the file, so upload it as is instead of failing the whole\n    // selection. This mirrors `optimizeSVG`, which also falls back to the original blob.\n    return file;\n  }\n\n  // Name the file after the format actually produced, which can differ from the requested one:\n  // without native WebP encoding and the fallback encoder, a browser exports PNG instead\n  const [, newFormat] = blob.type.split('/');\n\n  const newFileName = RASTER_IMAGE_EXTENSION_REGEX.test(file.name)\n    ? file.name.replace(RASTER_IMAGE_EXTENSION_REGEX, `.${newFormat}`)\n    : `${file.name}.${newFormat}`;\n\n  return new File([blob], newFileName, { type: blob.type });\n};\n","import { compare } from '@sveltia/utils/string';\n\nimport { allAssetFolders, selectedAssetFolder } from '$lib/services/assets/folders';\nimport { isCmsFolderName, isCmsFolderPath } from '$lib/services/assets/reserved';\nimport { allAssets } from '$lib/services/assets/state';\nimport { gitConfigFiles } from '$lib/services/backends/git/shared/config';\nimport { slugify, validateNewFolderName } from '$lib/services/common/slug';\nimport { allEntries } from '$lib/services/contents';\nimport { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\nimport { getOrCreate, memoizeOnSource, memoizeOnSources } from '$lib/services/utils/cache';\nimport {\n  createPath,\n  getBaseName,\n  getDirName,\n  renameReservedFileName,\n  sanitizeFileName,\n} from '$lib/services/utils/file';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * AssetSubfolder,\n * BreadcrumbItem,\n * UploadingAssets,\n * } from '$lib/types/private';\n */\n\n/**\n * Path of the subfolder being browsed below the selected asset folder’s `internalPath`, relative to\n * it. Empty at the folder root, and always empty for a folder that can’t be browsed by subfolder.\n * @type {{ current: string }}\n */\nexport const selectedSubfolderPath = createRawState('');\n\n/**\n * Subfolder currently focused in the Asset Library, whose info is shown in the sidebar, if any.\n * @type {{ current: AssetSubfolder | undefined }}\n */\nexport const focusedSubfolder = createRawState();\n\n/**\n * Subfolder being renamed with the Rename Folder dialog, if any.\n * @type {{ current: AssetSubfolder | undefined }}\n */\nexport const renamingSubfolder = createRawState();\n\n/**\n * Subfolder being deleted with the Delete Folder dialog, if any.\n * @type {{ current: AssetSubfolder | undefined }}\n */\nexport const deletingSubfolder = createRawState();\n\n/**\n * Check if the given asset folder can be browsed by subfolder, which takes a folder whose files all\n * sit below one fixed path: an entry-relative folder is scattered across the entry folders, and a\n * folder with template tags is only resolved per entry, so neither has a single tree to walk. The\n * All Assets folder has no path at all. The assets of such a folder are all listed at once.\n * @param {AssetFolderInfo | undefined} folder Asset folder.\n * @returns {folder is AssetFolderInfo} Result.\n */\nexport const canBrowseSubfolders = (folder) =>\n  !!folder && folder.internalPath !== undefined && !folder.entryRelative && !folder.hasTemplateTags;\n\n/**\n * Get the path of a file or directory relative to a base directory.\n * @param {string} path Path, e.g. `static/images/2024/photo.jpg`.\n * @param {string} basePath Base directory path, e.g. `static/images`. An empty string for the\n * repository root, below which every path sits as is.\n * @returns {string} Relative path, e.g. `2024/photo.jpg`. An empty string if the path is the base\n * directory itself or isn’t below it.\n */\nexport const getRelativePath = (path, basePath) => {\n  if (basePath === '') {\n    return path;\n  }\n\n  return path.startsWith(`${basePath}/`) ? path.slice(basePath.length + 1) : '';\n};\n\n/**\n * Get the path of the subfolder that a URL path points at, relative to the given asset folder.\n * @param {AssetFolderInfo} folder Asset folder.\n * @param {string} folderPath Folder path taken from the URL, e.g. `static/images/2024`.\n * @returns {string} Subfolder path, e.g. `2024`. An empty string for the folder root, or when the\n * folder can’t be browsed by subfolder.\n */\nexport const getSubfolderPath = (folder, folderPath) =>\n  canBrowseSubfolders(folder)\n    ? // `internalPath` is always a string for a folder that can be browsed\n      getRelativePath(folderPath, /** @type {string} */ (folder.internalPath))\n    : '';\n\n/**\n * Find the asset folder that a URL path points at, along with the subfolder browsed below it.\n * @param {string} folderPath Folder path taken from the URL, e.g. `static/images/2024` or `-/all`.\n * @param {AssetFolderInfo} [knownFolder] Folder carried as history state. An internal path can be\n * shared by several folders, and the state settles which one is meant, so it takes precedence over\n * the lookup by path.\n * @returns {{ folder: AssetFolderInfo, subfolderPath: string } | undefined} Folder and subfolder\n * path, or `undefined` if the path doesn’t point at a configured folder or any subfolder of one.\n */\nexport const resolveAssetFolderPath = (folderPath, knownFolder = undefined) => {\n  if (knownFolder) {\n    return { folder: knownFolder, subfolderPath: getSubfolderPath(knownFolder, folderPath) };\n  }\n\n  const folders = allAssetFolders.current;\n\n  const exactMatch = folders.find(({ internalPath, collectionName }) =>\n    folderPath === '-/all'\n      ? internalPath === undefined && collectionName === undefined\n      : internalPath === folderPath,\n  );\n\n  if (exactMatch) {\n    return { folder: exactMatch, subfolderPath: '' };\n  }\n\n  // The path can point below a folder. The deepest folder wins, so that a folder nested in another\n  // gets its own subfolders rather than having them listed as the outer folder’s\n  const parentFolder = folders\n    .filter(\n      (folder) =>\n        canBrowseSubfolders(folder) &&\n        (folder.internalPath === '' || folderPath.startsWith(`${folder.internalPath}/`)),\n    )\n    .sort(\n      (a, b) =>\n        /** @type {string} */ (b.internalPath).length -\n        /** @type {string} */ (a.internalPath).length,\n    )[0];\n\n  return parentFolder\n    ? { folder: parentFolder, subfolderPath: getSubfolderPath(parentFolder, folderPath) }\n    : undefined;\n};\n\n/**\n * Path of the directory being browsed in the Asset Library, e.g. `static/images/2024`, which is\n * the selected asset folder’s `internalPath` joined with {@link selectedSubfolderPath}. It’s\n * `undefined` when the selected folder can’t be browsed by subfolder, in which case every asset\n * below the folder is listed at once.\n */\nexport const browsedDirPath = createDerivedState(() => {\n  const folder = selectedAssetFolder.current;\n\n  return canBrowseSubfolders(folder)\n    ? createPath([folder.internalPath, selectedSubfolderPath.current])\n    : undefined;\n});\n\n/**\n * Whether the directory being browsed in the Asset Library is, or is below, a folder the CMS itself\n * is usually served from, such as `admin`. Nothing can be uploaded or created there.\n */\nexport const browsingCmsFolder = createDerivedState(() =>\n  isCmsFolderPath(browsedDirPath.current ?? ''),\n);\n\n/**\n * List the immediate subfolders of a directory, read off the paths of the files below it. A folder\n * isn’t an object of its own in a Git repository or an object storage bucket, so this is how the\n * folders are found. A folder path ending with a slash stands for an empty folder kept by a\n * placeholder, which has no file to be read off.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Directory path. An empty string for the root.\n * @param {string[]} args.paths Paths of the files below the directory, at any depth. Paths outside\n * the directory are left alone.\n * @returns {AssetSubfolder[]} Subfolders, sorted by name.\n */\nexport const listSubfolders = ({ dirPath, paths }) => {\n  const prefix = dirPath ? `${dirPath}/` : '';\n  /** @type {Set<string>} */\n  const names = new Set();\n\n  paths.forEach((path) => {\n    if (!path.startsWith(prefix)) {\n      return;\n    }\n\n    const index = path.indexOf('/', prefix.length);\n\n    if (index > prefix.length) {\n      names.add(path.slice(prefix.length, index));\n    }\n  });\n\n  return [...names].sort(compare).map((name) => ({ name, path: createPath([dirPath, name]) }));\n};\n\n/**\n * Get the names already taken in a directory, by a subfolder or a file, which a new or renamed\n * subfolder can’t be given.\n * @param {object} args Arguments.\n * @param {AssetSubfolder[]} args.subfolders Subfolders of the directory.\n * @param {string[]} args.fileNames Names of the files right in the directory.\n * @param {string} [args.exclude] Name of the subfolder being renamed, which it can keep.\n * @param {string} [args.dirPath] Path of the directory in the repository. When given, the names of\n * the subfolders leading to another configured asset folder nested in it, e.g. `projects` in\n * `static/uploads` for a collection’s `static/uploads/projects` folder, are taken too: such a\n * folder isn’t listed as a subfolder, as it’s browsed as a folder of its own, but a subfolder\n * renamed or created with its name would be merged into it.\n * @returns {string[]} Names.\n */\nexport const getTakenNames = ({\n  subfolders,\n  fileNames,\n  exclude = undefined,\n  dirPath = undefined,\n}) => [\n  ...subfolders.map(({ name }) => name).filter((name) => name !== exclude),\n  ...fileNames,\n  ...(dirPath === undefined\n    ? []\n    : listSubfolders({\n        dirPath,\n        // A trailing slash makes `listSubfolders` read the folder itself as a subfolder path\n        paths: allAssetFolders.current\n          .filter(({ internalPath, hasTemplateTags }) => internalPath && !hasTemplateTags)\n          .map(({ internalPath }) => `${internalPath}/`),\n      }).map(({ name }) => name)),\n];\n\n/**\n * Index the folders below a directory, read off the paths of the files below it.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Directory path. An empty string for the root.\n * @param {string[]} args.paths Paths of the files below the directory, at any depth. Paths outside\n * the directory are left alone.\n * @returns {Map<string, Set<string>>} Names of the subfolders, keyed by the path of the directory\n * they’re in.\n */\nconst buildFolderTree = ({ dirPath, paths }) => {\n  /** @type {Map<string, Set<string>>} */\n  const tree = new Map();\n  const prefix = dirPath ? `${dirPath}/` : '';\n\n  paths.forEach((path) => {\n    if (!path.startsWith(prefix)) {\n      return;\n    }\n\n    // Add each folder on the way down to the file to the one above it\n    let parentPath = dirPath;\n    let start = prefix.length;\n    let index = path.indexOf('/', start);\n\n    while (index > start) {\n      const name = path.slice(start, index);\n\n      getOrCreate(tree, parentPath, () => new Set()).add(name);\n      parentPath = createPath([parentPath, name]);\n      start = index + 1;\n      index = path.indexOf('/', start);\n    }\n  });\n\n  return tree;\n};\n\n/**\n * List the immediate subfolders of a directory in a tree built with {@link buildFolderTree}.\n * @param {Map<string, Set<string>>} tree Folder tree.\n * @param {string} dirPath Directory path.\n * @returns {AssetSubfolder[]} Subfolders, sorted by name.\n */\nconst listChildFolders = (tree, dirPath) =>\n  [...(tree.get(dirPath) ?? [])]\n    .sort(compare)\n    .map((name) => ({ name, path: createPath([dirPath, name]) }));\n\n/**\n * Group file names by the directory they’re in.\n * @param {string[]} paths File paths.\n * @returns {Map<string, string[]>} Names, keyed by directory path.\n */\nconst groupNamesByDir = (paths) =>\n  new Map(\n    [...Map.groupBy(paths, getDirName)].map(([dirPath, filePaths]) => [\n      dirPath,\n      filePaths.map(getBaseName),\n    ]),\n  );\n\n/**\n * Index of the folders in the repository, read off the paths of the assets and the Git config\n * files, rebuilt when either is replaced. Saving an entry looks up the folder of every file it\n * adds, so the paths are only gone through once rather than for each file.\n * @type {() => Map<string, Set<string>>}\n */\nconst getRepositoryFolderTree = memoizeOnSources(\n  () => [allAssets.current, gitConfigFiles.current],\n  (assets, configFiles) =>\n    buildFolderTree({ dirPath: '', paths: [...assets, ...configFiles].map(({ path }) => path) }),\n);\n\n/**\n * Index of the names of the entry files, keyed by directory path, rebuilt when the entries are\n * replaced.\n * @type {() => Map<string, string[]>}\n */\nconst getEntryFileNamesByDir = memoizeOnSource(\n  () => allEntries.current,\n  (entries) =>\n    groupNamesByDir(\n      entries.flatMap(({ locales }) => Object.values(locales).map(({ path }) => path)),\n    ),\n);\n\n/**\n * Index of the names of the Git config files, keyed by directory path, rebuilt when the files are\n * replaced.\n * @type {() => Map<string, string[]>}\n */\nconst getConfigFileNamesByDir = memoizeOnSource(\n  () => gitConfigFiles.current,\n  (configFiles) => groupNamesByDir(configFiles.map(({ path }) => path)),\n);\n\n/**\n * Get the names of every folder right in a directory of the repository, which a file renamed in it\n * can’t take: the folders holding assets or Git config files, whichever asset folder they belong\n * to, and the ones leading to a configured asset folder nested in the directory.\n * @param {string} dirPath Directory path. An empty string for the repository root.\n * @returns {string[]} Names.\n */\nexport const getFolderNamesInDir = (dirPath) =>\n  getTakenNames({\n    subfolders: listChildFolders(getRepositoryFolderTree(), dirPath),\n    fileNames: [],\n    dirPath,\n  });\n\n/**\n * Get the names of the files right in a directory of the repository that aren’t assets, which a\n * file renamed or uploaded there can’t take without overwriting them: the entry files, as in a Hugo\n * page bundle keeping its images next to its `index.md`, and the Git config files like `.gitkeep`.\n * @param {string} dirPath Directory path. An empty string for the repository root.\n * @returns {string[]} Names.\n */\nexport const getNonAssetFileNamesInDir = (dirPath) => [\n  ...new Set([\n    ...(getEntryFileNamesByDir().get(dirPath) ?? []),\n    ...(getConfigFileNamesByDir().get(dirPath) ?? []),\n  ]),\n];\n\n/**\n * Get the breadcrumb trail of the subfolder being browsed, from the location root down. Each\n * ancestor leads back to itself; the last item is the subfolder being browsed.\n * @param {object} args Arguments.\n * @param {string} args.rootLabel Label of the location root, e.g. the asset folder or the cloud\n * storage service.\n * @param {string[]} args.subfolderNames Names of the subfolders leading to the one being browsed,\n * from the location root down. Empty at the root.\n * @param {(ancestor: { depth: number, path: string }) => void} args.onBrowse Called when an\n * ancestor is selected, with how many subfolder names to keep, `0` being the root, and its path\n * relative to the root, which is an empty string for the root.\n * @returns {BreadcrumbItem[]} Items. Empty at the root, where there is no trail to show.\n */\nexport const getFolderBreadcrumbItems = ({ rootLabel, subfolderNames, onBrowse }) => {\n  if (!subfolderNames.length) {\n    return [];\n  }\n\n  return [\n    ...[rootLabel, ...subfolderNames.slice(0, -1)].map((label, depth) => ({\n      label,\n      // eslint-disable-next-line jsdoc/require-jsdoc\n      onClick: () => {\n        onBrowse({ depth, path: subfolderNames.slice(0, depth).join('/') });\n      },\n    })),\n    { label: /** @type {string} */ (subfolderNames.at(-1)) },\n  ];\n};\n\n/**\n * Cache for {@link getOwnerFolderPath}, keyed by directory path, rebuilt when the asset folders\n * are replaced. Every Git config file is looked up each time subfolders are listed, and each lookup\n * goes through every folder.\n * @type {() => Map<string, string | undefined>}\n */\nconst getOwnerFolderPathCache = memoizeOnSource(\n  () => allAssetFolders.current,\n  () => new Map(),\n);\n\n/**\n * Get the `internalPath` of the asset folder that a directory belongs to: the folder at that path,\n * or else the deepest one it sits below.\n * @param {string} dirPath Directory path.\n * @returns {string | undefined} Folder path, or `undefined` if the directory is outside every\n * folder.\n */\nconst getOwnerFolderPath = (dirPath) =>\n  getOrCreate(\n    getOwnerFolderPathCache(),\n    dirPath,\n    () => resolveAssetFolderPath(dirPath)?.folder.internalPath,\n  );\n\n/**\n * Get the paths that the subfolders of a directory are read off: the assets and the Git config\n * files belonging to the same asset folder as the directory.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Directory path. An empty string for the repository root.\n * @param {Asset[]} args.assets Assets below the directory, at any depth.\n * @returns {string[]} Paths.\n */\nconst getSubfolderSourcePaths = ({ dirPath, assets }) => {\n  // A Git config file counts the same way as an asset: only when it belongs to the same asset\n  // folder as the directory, so a nested asset folder isn’t listed for the `.gitkeep` it holds\n  const ownerFolderPath = getOwnerFolderPath(dirPath);\n\n  const configFiles = gitConfigFiles.current.filter(\n    ({ path }) => getOwnerFolderPath(getDirName(path)) === ownerFolderPath,\n  );\n\n  return [...assets, ...configFiles].map(({ path }) => path);\n};\n\n/**\n * List the immediate subfolders of a directory. A folder isn’t an object of its own in a Git\n * repository, so the subfolders are read off the paths of the files below the directory: the assets\n * and, for a folder that holds no asset yet, the `.gitkeep` and other Git config files that keep\n * it in the repository.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Directory path. An empty string for the repository root.\n * @param {Asset[]} args.assets Assets below the directory, at any depth. These are the assets of\n * the folder the directory belongs to, which leaves out the assets of another asset folder nested\n * in it, as those are that folder’s to list.\n * @returns {AssetSubfolder[]} Subfolders, sorted by name.\n */\nexport const getSubfolders = ({ dirPath, assets }) =>\n  listSubfolders({ dirPath, paths: getSubfolderSourcePaths({ dirPath, assets }) });\n\n/**\n * Get a function listing the immediate subfolders of a directory or of any directory below it, as\n * {@link getSubfolders} does, for walking the whole tree. The paths are read once, rather than once\n * per directory, which adds up to directories × assets for a folder with many subfolders.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Path of the top directory. An empty string for the repository root.\n * @param {Asset[]} args.assets Assets below the directory, at any depth. These are the assets of\n * the folder the directory belongs to, so no directory below it belongs to another asset folder.\n * @returns {(dirPath: string) => AssetSubfolder[]} Function listing the subfolders of the top\n * directory or a directory below it, sorted by name.\n */\nexport const getSubfolderTree = ({ dirPath, assets }) => {\n  const tree = buildFolderTree({ dirPath, paths: getSubfolderSourcePaths({ dirPath, assets }) });\n\n  return (path) => listChildFolders(tree, path);\n};\n\n/**\n * Get the assets right in a directory, leaving out the ones in its subfolders.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Directory path. An empty string for the repository root.\n * @param {Asset[]} args.assets Assets below the directory, at any depth.\n * @returns {Asset[]} Assets in the directory.\n */\nexport const getAssetsInDir = ({ dirPath, assets }) =>\n  assets.filter(({ path }) => getDirName(path) === dirPath);\n\n/**\n * Get the path of the directory that uploaded files are saved to, which is the target folder’s\n * `internalPath` joined with the subfolder path, if any.\n * @param {UploadingAssets} uploadingAssets Files to be uploaded and their target folder.\n * @returns {string | undefined} Directory path, or `undefined` if the target folder has no path,\n * which is the case for the All Assets folder.\n */\nexport const getUploadDirPath = ({ folder, subfolderPath }) =>\n  folder?.internalPath !== undefined ? createPath([folder.internalPath, subfolderPath]) : undefined;\n\n/**\n * Format a new subfolder name the way an uploaded file name is: sanitized, and slugified when the\n * `slugify_filename` option is enabled, so a folder created by hand is named like the files that\n * will be saved in it. A name Windows reserves for a device, like `con`, is numbered as `con-1`.\n * @param {string} name Name as typed.\n * @returns {string} Folder name. An empty string if nothing usable is left.\n */\nexport const formatSubfolderName = (name) => {\n  const { slugify_filename: slugificationEnabled } = getDefaultMediaLibraryOptions().config;\n  const folderName = sanitizeFileName(name.trim());\n\n  // The whole name is slugified: unlike a file name, a folder name has no extension to keep, so a\n  // dot in it is just another character. Slugifying can leave a name Windows reserves for a device,\n  // like `aux` from `Aux!`, which `sanitizeFileName()` has renamed otherwise\n  return slugificationEnabled\n    ? renameReservedFileName(slugify(folderName, { fallback: false }))\n    : folderName;\n};\n\n/**\n * Check whether a subfolder can be given the name typed in the New Folder dialog.\n * @param {object} args Arguments.\n * @param {string} args.name Name to check, as typed.\n * @param {string[]} args.takenNames Names of the files and folders already in the parent\n * directory. A Git tree can’t hold a blob and a subtree under one name, so a file name is taken as\n * well.\n * @returns {'empty' | 'invalid' | 'reserved' | 'duplicate' | undefined} What stops the name from\n * being used, or `undefined` if it can be used.\n */\nexport const validateSubfolderName = ({ name, takenNames }) =>\n  // The files in a folder the CMS itself is usually served from are read-only\n  validateNewFolderName({\n    name,\n    takenNames,\n    format: formatSubfolderName,\n    isReserved: isCmsFolderName,\n  });\n","import { getPathInfo } from '@sveltia/utils/file';\nimport { compare, stripSlashes } from '@sveltia/utils/string';\n\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport { isConfigReadonly } from '$lib/services/config/readonly';\nimport { getValidCollections } from '$lib/services/contents/collection';\nimport { getValidCollectionFiles } from '$lib/services/contents/collection/predicates';\nimport { LOCALE_ROOT_FOLDER_STRUCTURES } from '$lib/services/contents/i18n/config/constants';\nimport { mergeI18nConfigs } from '$lib/services/contents/i18n/config/merge';\nimport { hasLocalePlaceholder } from '$lib/services/contents/i18n/placeholder';\nimport { normalizeFolderPath, stripLeadingDotSlash } from '$lib/services/utils/file';\n\n/**\n * @import {\n * AssetFolderInfo,\n * CollectedMediaField,\n * InternalCmsConfig,\n * InternalSingletonCollection,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import {\n * AssetCollection,\n * Collection,\n * CollectionDivider,\n * CollectionFile,\n * } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} NormalizeAssetFolderArgs\n * @property {string | undefined} collectionName Collection name or `undefined` for the All Assets\n * and Global Assets folders as well as field-level asset folders in custom editor components.\n * @property {string} [fileName] Collection file name. File/singleton collection only.\n * @property {string} [componentName] Custom editor component name for a field-level asset folder.\n * @property {TypedFieldKeyPath} [typedKeyPath] Key path to the field.\n * @property {boolean} [isIndexFile] Whether the field is part of an index file entry.\n * @property {string} mediaFolder Raw `media_folder` option of the collection or collection file.\n * @property {string | undefined} publicFolder Raw `public_folder` option of the collection or\n * collection file.\n * @property {string | undefined} [baseFolder] `folder` option for the collection or base directory\n * of the collection file.\n * @property {GlobalFolders | undefined} globalFolders Global folders information.\n * @property {string} [label] Label for the asset folder. Asset collections only.\n * @property {string} [icon] Icon for the asset folder. Asset collections only.\n * @property {boolean} [isAssetCollection] Whether the asset folder is for an asset collection.\n */\n\n/**\n * @typedef {object} GlobalFolders\n * @property {string} globalMediaFolder Normalized global `media_folder` option.\n * @property {string} globalPublicFolder Normalized global `public_folder` option.\n */\n\n/**\n * Check if a folder string contains template tags.\n * @param {string} folder Folder string.\n * @returns {boolean} `true` if the folder contains template tags.\n */\nexport const hasTags = (folder) =>\n  folder.includes('{{media_folder}}') || folder.includes('{{public_folder}}');\n\n/**\n * Remove the leading slash from a public folder starting with `@`, like `/@assets/images`. Some\n * frameworks expect asset paths starting with `@`, like `@assets/images/...`.\n * @param {string} folder Folder path.\n * @returns {string} Folder path without the extra leading slash.\n */\nconst removeSlashBeforeAtSign = (folder) => folder.replace(/^\\/@/, '@');\n\n/**\n * Replace `{{media_folder}}` and `{{public_folder}}` template tags.\n * @param {string} folder Original folder path.\n * @param {object} context Context for replacement.\n * @param {string} context.globalMediaFolder Normalized global `media_folder` option.\n * @param {string} context.globalPublicFolder Normalized global `public_folder` option.\n * @returns {string} Replaced folder path with a leading slash so it won’t be treated as relative.\n */\nexport const replaceTags = (folder, { globalMediaFolder, globalPublicFolder }) =>\n  folder\n    .trim()\n    .replace('{{media_folder}}', `/${globalMediaFolder}`)\n    .replace('{{public_folder}}', `/${globalPublicFolder}`)\n    .replace('//', '/');\n\n/**\n * Replace the `{{media_folder}}` and `{{public_folder}}` tags in a `media_folder` or\n * `public_folder` option, e.g. `{{media_folder}}/blog`, with the global folders.\n * @param {string} folder Folder option.\n * @param {GlobalFolders | undefined} globalFolders Global folders, as returned by\n * {@link resolveGlobalFolders}.\n * @param {object} [options] Options.\n * @param {boolean} [options.isPublicFolder] Whether the option is `public_folder`.\n * @returns {string | undefined} Folder with the tags replaced, the given folder as is if it has no\n * such tags, or `undefined` if it has some but the global folders are not available.\n */\nexport const replaceFolderTags = (folder, globalFolders, { isPublicFolder = false } = {}) => {\n  if (!hasTags(folder)) {\n    return folder;\n  }\n\n  if (!globalFolders) {\n    return undefined;\n  }\n\n  const replaced = replaceTags(folder, globalFolders);\n\n  // The tag is replaced with a leading slash, which has to be removed again from a global public\n  // folder starting with `@`, like `@assets/images`, the same way as the global folder itself\n  return isPublicFolder ? removeSlashBeforeAtSign(replaced) : replaced;\n};\n\n/**\n * Get the folder that a relative `media_folder` option of an entry collection is relative to: the\n * collection folder, e.g. `content/posts`, or the folder of the file storing all the entries.\n * @param {Collection | InternalSingletonCollection} collection Collection.\n * @returns {string | undefined} Folder path. `undefined` for a file/singleton collection.\n */\nexport const getCollectionBaseFolder = (collection) => {\n  if ('folder' in collection && typeof collection.folder === 'string') {\n    return collection.folder;\n  }\n\n  if ('file' in collection && typeof collection.file === 'string') {\n    return getPathInfo(collection.file).dirname;\n  }\n\n  return undefined;\n};\n\n/**\n * Get a normalized asset folder information given the arguments.\n * @param {NormalizeAssetFolderArgs} args Arguments.\n * @returns {AssetFolderInfo | undefined} Normalized asset folder information or `undefined` if\n * template tags are used but global folder information is not available.\n */\nexport const normalizeAssetFolder = ({\n  collectionName,\n  fileName,\n  componentName,\n  typedKeyPath,\n  isIndexFile = false,\n  mediaFolder,\n  publicFolder,\n  baseFolder,\n  globalFolders,\n  label,\n  icon,\n  isAssetCollection = false,\n}) => {\n  const _mediaFolder = replaceFolderTags(mediaFolder, globalFolders);\n\n  const _publicFolder =\n    publicFolder === undefined\n      ? _mediaFolder\n      : replaceFolderTags(publicFolder, globalFolders, { isPublicFolder: true });\n\n  // Cannot substitute tags without global folder info\n  if (_mediaFolder === undefined || _publicFolder === undefined) {\n    return undefined;\n  }\n\n  mediaFolder = _mediaFolder;\n  publicFolder = _publicFolder;\n\n  // Normalize `./` prefix: `./images` → `images`, `./` → ``, `.` → ``\n  // This must happen after publicFolder defaulting so that `publicPath` preserves the `./` prefix\n  // needed to match stored values like `./images/photo.jpg`.\n  mediaFolder = stripLeadingDotSlash(mediaFolder);\n\n  const entryRelative = !mediaFolder.startsWith('/');\n\n  return {\n    collectionName,\n    fileName,\n    componentName,\n    typedKeyPath,\n    isIndexFile,\n    internalPath: entryRelative\n      ? // A root collection folder can be written as `.`, `./` or `/`, and any other folder can\n        // start with `./`. The configuration passed to the parser still holds the raw value, which\n        // field-level folders are resolved against\n        normalizeFolderPath(baseFolder ?? '')\n      : stripSlashes(mediaFolder),\n    internalSubPath: entryRelative ? stripSlashes(mediaFolder) : undefined,\n    publicPath:\n      // Prefix the public path with `/` unless it’s empty or starting with `.` (entry-relative\n      // setting) or starting with `@` (framework-specific), or it’s the public path of an\n      // entry-relative folder that doesn’t start with `/`, like `images`, which is relative to the\n      // entry as well, so the value stored is `images/photo.jpg`. A trailing slash is removed\n      // either way, like the global public folder’s, so a path can be joined with `/` and a file\n      // name; `./` becomes `.`, which stores the same `./photo.jpg` value\n      /^($|[.@])/.test(publicFolder) || (entryRelative && !publicFolder.startsWith('/'))\n        ? publicFolder.replace(/(?<=.)\\/+$/, '')\n        : `/${stripSlashes(publicFolder)}`,\n    entryRelative,\n    hasTemplateTags: hasTemplateTags(mediaFolder),\n    label,\n    icon,\n    isAssetCollection,\n  };\n};\n\n/**\n * Add an asset folder for a collection or collection file if it’s not the same as the global\n * asset folder.\n * @param {AssetFolderInfo[]} folders List to add the folder to.\n * @param {NormalizeAssetFolderArgs} args Arguments for {@link normalizeAssetFolder}.\n */\nexport const addFolderIfNeeded = (folders, args) => {\n  if (args.mediaFolder === undefined) {\n    return;\n  }\n\n  const folder = normalizeAssetFolder(args);\n\n  if (!folder) {\n    return;\n  }\n\n  const { globalMediaFolder, globalPublicFolder } = args.globalFolders ?? {};\n\n  if (\n    !folder.entryRelative &&\n    folder.internalPath === globalMediaFolder &&\n    folder.publicPath === globalPublicFolder\n  ) {\n    return;\n  }\n\n  folders.push(folder);\n};\n\n/**\n * Iterate through files in a file/singleton collection and add their folders.\n * @param {AssetFolderInfo[]} folders List to add the folders to.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {(CollectionFile | CollectionDivider)[]} args.files Collection files. May include\n * dividers.\n * @param {GlobalFolders | undefined} args.globalFolders Global folders information.\n * @param {string} [args.mediaFolder] Relative `media_folder` option of the file collection, which\n * applies to each file without its own `media_folder`, relative to that file.\n * @param {string} [args.publicFolder] `public_folder` option of the file collection, which goes\n * along with `args.mediaFolder`.\n */\nexport const iterateFiles = (\n  folders,\n  { collectionName, files, globalFolders, mediaFolder, publicFolder },\n) => {\n  getValidCollectionFiles(files).forEach((file) => {\n    const {\n      name: fileName,\n      file: filePath,\n      media_folder: fileMediaFolder,\n      public_folder: filePublicFolder,\n    } = file;\n\n    // A file without its own `media_folder` inherits the collection’s relative one along with its\n    // `public_folder`, while its own `media_folder` defaults its `public_folder` to itself\n    const inherits = fileMediaFolder === undefined;\n\n    addFolderIfNeeded(folders, {\n      collectionName,\n      fileName,\n      // @ts-ignore\n      mediaFolder: inherits ? mediaFolder : fileMediaFolder,\n      publicFolder: inherits ? publicFolder : filePublicFolder,\n      baseFolder: getPathInfo(filePath).dirname,\n      globalFolders,\n    });\n  });\n};\n\n/**\n * Handle field-level media folders and add them if needed.\n * @param {AssetFolderInfo[]} folders List to add the folders to.\n * @param {object} args Arguments.\n * @param {CollectedMediaField[]} args.fieldMediaFolders Collected field-level media folders.\n * @param {Collection[]} args.validCollections Valid collections.\n * @param {GlobalFolders | undefined} args.globalFolders Global folders information.\n */\nexport const handleFieldMediaFolders = (\n  folders,\n  { fieldMediaFolders, validCollections, globalFolders },\n) => {\n  fieldMediaFolders.forEach(({ fieldConfig, context }) => {\n    const { collection, collectionFile, componentName, typedKeyPath, isIndexFile } = context;\n\n    const isValidCollection =\n      !!collection &&\n      (collection.name === '_singletons' ||\n        validCollections.some((c) => c.name === collection.name));\n\n    if (!isValidCollection && !componentName) {\n      return;\n    }\n\n    addFolderIfNeeded(folders, {\n      collectionName: collection?.name,\n      fileName: collectionFile?.name,\n      componentName,\n      typedKeyPath,\n      isIndexFile,\n      mediaFolder: /** @type {string} */ (fieldConfig.media_folder),\n      publicFolder: fieldConfig.public_folder,\n      // A relative folder is relative to the collection file, the same as a file-level folder, or\n      // else to the collection folder, or the folder of the file storing all the entries\n      baseFolder: collectionFile\n        ? getPathInfo(collectionFile.file).dirname\n        : collection\n          ? getCollectionBaseFolder(collection)\n          : undefined,\n      globalFolders,\n    });\n  });\n};\n\n/**\n * Add asset folders for asset collections.\n * @param {AssetFolderInfo[]} folders List to add the folders to.\n * @param {object} args Arguments.\n * @param {AssetCollection[]} args.assetCollections Asset collections from the CMS configuration.\n * @param {GlobalFolders | undefined} args.globalFolders Global folders information.\n */\nconst addAssetCollections = (folders, { assetCollections, globalFolders }) => {\n  assetCollections.forEach((assetCollection) => {\n    const {\n      name,\n      label = name,\n      icon,\n      media_folder: _mediaFolder,\n      public_folder: _publicFolder,\n    } = assetCollection;\n\n    if (_mediaFolder === undefined) {\n      return;\n    }\n\n    addFolderIfNeeded(folders, {\n      collectionName: `assets:${name}`,\n      // The folder is always relative to the repository root, so a leading `./` changes nothing\n      mediaFolder: `/${normalizeFolderPath(_mediaFolder)}`,\n      publicFolder: _publicFolder,\n      globalFolders,\n      label,\n      icon,\n      isAssetCollection: true,\n    });\n  });\n};\n\n/**\n * Check whether an asset folder is read-only, which is when the collection or collection file it\n * belongs to is, or the whole CMS is. A folder that belongs to neither, like the global folder or a\n * custom editor component’s folder, is only read-only along with the whole CMS.\n * @param {object} args Arguments.\n * @param {InternalCmsConfig} args.config CMS configuration.\n * @param {AssetFolderInfo} args.folder Asset folder.\n * @param {Collection[]} args.validCollections Valid collections.\n * @returns {boolean} Result.\n */\nconst isAssetFolderReadonly = ({ config, folder, validCollections }) => {\n  const { collectionName, fileName, isAssetCollection } = folder;\n\n  if (isAssetCollection) {\n    const collection = config.asset_collections?.find(\n      ({ name }) => `assets:${name}` === collectionName,\n    );\n\n    return isConfigReadonly({ config, collection });\n  }\n\n  const collection = validCollections.find(({ name }) => name === collectionName);\n\n  const files =\n    collectionName === '_singletons'\n      ? config.singletons\n      : collection && 'files' in collection\n        ? collection.files\n        : undefined;\n\n  const collectionFile =\n    fileName && files\n      ? getValidCollectionFiles(files).find(({ name }) => name === fileName)\n      : undefined;\n\n  return isConfigReadonly({ config, collection, collectionFile });\n};\n\n/**\n * Resolve the global `media_folder` and `public_folder` options.\n * @param {InternalCmsConfig} config CMS configuration.\n * @returns {GlobalFolders | undefined} Normalized global folders, or `undefined` if the global\n * `media_folder` option is not configured.\n */\nexport const resolveGlobalFolders = (config) => {\n  const { media_folder: _globalMediaFolder, public_folder: _globalPublicFolder } = config;\n\n  if (_globalMediaFolder === undefined) {\n    return undefined;\n  }\n\n  // Normalize the media folder: an empty string, `/`, `.` and `./` are all considered as the root\n  // folder, and a leading `./` is removed from any other folder, e.g. `./static/images`\n  const globalMediaFolder = normalizeFolderPath(_globalMediaFolder);\n\n  // Some frameworks expect asset paths starting with `@`, like `@assets/images/...`. Remove an\n  // extra leading slash in that case. A trailing slash should always be removed internally.\n  const globalPublicFolder = _globalPublicFolder\n    ? removeSlashBeforeAtSign(`/${stripSlashes(_globalPublicFolder)}`)\n    : `/${globalMediaFolder}`;\n\n  return { globalMediaFolder, globalPublicFolder };\n};\n\n/**\n * Add the collection-level and file-level asset folders of the given collections, as well as the\n * file-level asset folders of the singletons.\n * @param {AssetFolderInfo[]} folders List to add the folders to.\n * @param {object} args Arguments.\n * @param {Collection[]} args.validCollections Valid collections.\n * @param {InternalCmsConfig['singletons']} [args.singletons] Singletons.\n * @param {GlobalFolders | undefined} args.globalFolders Global folders information.\n */\nexport const collectCollectionAssetFolders = (\n  folders,\n  { validCollections, singletons, globalFolders },\n) => {\n  const isGlobalFolderConfigured = globalFolders !== undefined;\n\n  validCollections.forEach((collection) => {\n    const {\n      name: collectionName,\n      // @ts-ignore\n      files: collectionFiles,\n      // @ts-ignore\n      // e.g. `{{slug}}/index`\n      path: entryPath,\n      // relative path, e.g. `` (an empty string), `./` (same as an empty string),\n      // `{{media_folder}}/posts`, etc. or absolute path, e.g. `/static/images/posts`, etc.\n      media_folder: _mediaFolder,\n      // `undefined`, `` (an empty string), `{{public_folder}}`, etc. or relative/absolute path\n      public_folder: publicFolder,\n    } = collection;\n\n    // When specifying a `path` on an entry collection, `media_folder` defaults to an empty string\n    const mediaFolder =\n      isGlobalFolderConfigured && _mediaFolder === undefined && entryPath !== undefined\n        ? ''\n        : _mediaFolder;\n\n    // A relative `media_folder` of a file collection is relative to each file, so it’s added for\n    // every file instead of the collection, which has no folder of its own to be relative to\n    const isRelativeFileCollectionFolder =\n      'files' in collection &&\n      typeof mediaFolder === 'string' &&\n      !hasTags(mediaFolder) &&\n      !mediaFolder.startsWith('/');\n\n    if (!isRelativeFileCollectionFolder) {\n      addFolderIfNeeded(folders, {\n        collectionName,\n        // @ts-ignore\n        mediaFolder,\n        publicFolder,\n        baseFolder: getCollectionBaseFolder(collection),\n        entryPath,\n        globalFolders,\n      });\n    }\n\n    if (collectionFiles?.length) {\n      iterateFiles(folders, {\n        collectionName,\n        files: collectionFiles,\n        globalFolders,\n        ...(isRelativeFileCollectionFolder ? { mediaFolder, publicFolder } : {}),\n      });\n    }\n  });\n\n  if (singletons?.length) {\n    // Singleton collection is always at the end\n    iterateFiles(folders, { collectionName: '_singletons', files: singletons, globalFolders });\n  }\n};\n\n/**\n * Get the names of the locale folders an entry-relative asset folder of each collection can sit in.\n * The `multiple_root_folders` i18n structure stores each locale’s copy of the whole site below a\n * folder named after it, so an entry-relative folder’s own files can sit one level deeper than the\n * collection `folder` option says. The same goes for a `folder` with the `{{locale}}` placeholder,\n * which names the locale folder in the middle of the path. Record the locale names so the asset\n * paths can be matched there too; the entry folders already carry the same information in their\n * `folderPathMap`. The locales are read per collection rather than from the site configuration,\n * because a collection can define its own, and only the structures that put the locale in front\n * matter.\n * @param {InternalCmsConfig} config CMS configuration.\n * @param {Collection[]} validCollections Valid collections.\n * @returns {Map<string, string[]>} Map of collection names to locale folder names, which is empty\n * for a collection without locale folders.\n */\nexport const getLocaleFolderNameMap = (config, validCollections) =>\n  new Map(\n    validCollections.map((collection) => {\n      const i18n = mergeI18nConfigs({ cmsConfig: config, collection });\n\n      const hasLocaleFolder =\n        ('folder' in collection &&\n          typeof collection.folder === 'string' &&\n          hasLocalePlaceholder(collection.folder)) ||\n        (!!i18n?.structure && LOCALE_ROOT_FOLDER_STRUCTURES.includes(i18n.structure));\n\n      return [collection.name, hasLocaleFolder ? (i18n?.locales ?? []) : []];\n    }),\n  );\n\n/**\n * Get all asset folders.\n * @param {InternalCmsConfig} config CMS configuration.\n * @param {CollectedMediaField[]} [fieldMediaFolders] Collected field-level media folders.\n * @returns {AssetFolderInfo[]} Asset folders.\n */\nexport const getAllAssetFolders = (config, fieldMediaFolders = []) => {\n  /**\n   * Collection-level and file-level asset folders.\n   * @type {AssetFolderInfo[]}\n   * @see https://decapcms.org/docs/collection-folder/#media-and-public-folder\n   * @see https://sveltiacms.app/en/docs/media/internal\n   */\n  const assetFolders = [];\n  const { collections, singletons, asset_collections: assetCollections } = config;\n  const globalFolders = resolveGlobalFolders(config);\n\n  /** @type {AssetFolderInfo} */\n  const allAssetsFolder = {\n    collectionName: undefined,\n    internalPath: undefined,\n    internalSubPath: undefined,\n    publicPath: undefined,\n    entryRelative: false,\n    hasTemplateTags: false,\n    label: undefined,\n    icon: undefined,\n    isAssetCollection: false,\n  };\n\n  /** @type {AssetFolderInfo | undefined} */\n  const globalAssetFolder = globalFolders\n    ? {\n        ...allAssetsFolder,\n        internalPath: globalFolders.globalMediaFolder,\n        publicPath: globalFolders.globalPublicFolder,\n      }\n    : undefined;\n\n  const validCollections = getValidCollections({ collections });\n\n  collectCollectionAssetFolders(assetFolders, { validCollections, singletons, globalFolders });\n  handleFieldMediaFolders(assetFolders, { fieldMediaFolders, validCollections, globalFolders });\n\n  // `internalPath` is always set to a string via `stripSlashes()` in the folder construction above.\n  assetFolders.sort((a, b) =>\n    compare(/** @type {string} */ (a.internalPath), /** @type {string} */ (b.internalPath)),\n  );\n\n  const allFolders = [];\n\n  if (globalAssetFolder) {\n    allFolders.push(globalAssetFolder);\n  }\n\n  if (assetCollections?.length) {\n    addAssetCollections(assetFolders, { assetCollections, globalFolders });\n  }\n\n  allFolders.push(...assetFolders);\n\n  if (allFolders.length) {\n    allFolders.unshift(allAssetsFolder);\n  }\n\n  const localeFolderNameMap = getLocaleFolderNameMap(config, validCollections);\n\n  return allFolders.map((folder) => {\n    const localeFolderNames = folder.entryRelative\n      ? localeFolderNameMap.get(/** @type {string} */ (folder.collectionName))\n      : undefined;\n\n    // Both properties are only added when they apply, like the other optional ones\n    return {\n      ...folder,\n      ...(localeFolderNames?.length ? { localeFolderNames } : {}),\n      ...(isAssetFolderReadonly({ config, folder, validCollections }) ? { readonly: true } : {}),\n    };\n  });\n};\n","import { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getCollectionFilesByEntry } from '$lib/services/contents/collection/files';\nimport { getAssociatedCollections } from '$lib/services/contents/entry/collections';\n\n/**\n * @import { Entry, InternalCollection, InternalCollectionFile } from '$lib/types/private';\n */\n\n/**\n * Where an entry is configured: a collection it belongs to and, for a file/singleton collection,\n * the collection file it matches.\n * @typedef {object} EntryCollectionContext\n * @property {InternalCollection} collection Collection.\n * @property {InternalCollectionFile} [collectionFile] Collection file, if the collection is a\n * file/singleton collection.\n * @property {boolean} isIndexFile Whether the entry is the collection’s index file.\n */\n\n/**\n * Get every place the given entry is configured in: each collection it belongs to, or, for a\n * file/singleton collection, each collection file it matches. One entry can theoretically appear in\n * multiple collections and collection files depending on the configuration, so its fields are\n * looked up in each of them. The contexts are produced lazily, so a caller looking for the first\n * one that matches doesn’t look up the files of the remaining collections.\n * @param {Entry} entry Entry.\n * @returns {IteratorObject<EntryCollectionContext>} Contexts.\n */\nexport const getEntryCollectionContexts = (entry) =>\n  getAssociatedCollections(entry)\n    .values()\n    .flatMap((collection) => {\n      const isIndexFile = isCollectionIndexFile(collection, entry);\n      const collectionFiles = getCollectionFilesByEntry(collection, entry);\n\n      return collectionFiles.length\n        ? collectionFiles.map((collectionFile) => ({ collection, collectionFile, isIndexFile }))\n        : [{ collection, isIndexFile }];\n    });\n","import { getPathInfo } from '@sveltia/utils/file';\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport {\n  fillInternalPathTemplate,\n  fillMediaFolderTemplate,\n  findInEntryBaseFolders,\n  findInEntryRelativeFolder,\n} from '$lib/services/assets/entry-relative';\nimport {\n  allAssetFolders,\n  getAssetFolder,\n  globalAssetFolder,\n  selectedAssetFolder,\n} from '$lib/services/assets/folders';\nimport { getAssetPathMap } from '$lib/services/assets/lookup';\nimport { allAssets, focusedAsset } from '$lib/services/assets/state';\nimport {\n  focusedSubfolder,\n  getFolderNamesInDir,\n  getNonAssetFileNamesInDir,\n  selectedSubfolderPath,\n} from '$lib/services/assets/subfolders';\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport { getTemplatePattern } from '$lib/services/common/template/utils';\nimport {\n  hasTags,\n  replaceFolderTags,\n  resolveGlobalFolders,\n} from '$lib/services/config/folders/assets';\nimport { cmsConfig } from '$lib/services/config/state';\nimport { getEntryCollectionContexts } from '$lib/services/contents/entry/contexts';\nimport { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\nimport { getOrCreate, memoizeOnSource } from '$lib/services/utils/cache';\nimport {\n  createPath,\n  foldFileName,\n  getDirName,\n  resolvePath,\n  stripPathPrefix,\n} from '$lib/services/utils/file';\nimport { createRootEffect } from '$lib/services/utils/state.svelte';\nimport { decodeURIComponentSafely } from '$lib/services/utils/url';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * Entry,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalLocaleCode,\n * LocalizedEntry,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n */\n\n/**\n * Get an asset by its internal repository path.\n * @param {string} path Asset path.\n * @returns {Asset | undefined} Asset.\n */\nexport const getAssetByInternalPath = (path) => getAssetPathMap().get(path);\n\n/**\n * Get a stable, unique key for the given asset, to be used as its identity in a list. An unsaved\n * asset is keyed by its blob URL, because it can temporarily share a path with the saved asset it’s\n * going to overwrite, and two pending files can share one as well. A saved asset is keyed by its\n * path, which is unique within the repository, and unlike its blob URL — only generated when the\n * file is fetched — never changes while the asset is listed.\n * @param {Asset} asset Asset.\n * @returns {string} Key.\n */\nexport const getAssetKey = ({ unsaved, blobURL, path }) => (unsaved && blobURL ? blobURL : path);\n\n/**\n * Replace the `{{media_folder}}` and `{{public_folder}}` tags in the raw `media_folder` or\n * `public_folder` option of a collection or collection file, e.g. `{{media_folder}}/blog`, with the\n * global folders, the same way as the asset folders are normalized. Otherwise the tags would be\n * taken for entry template tags and filled in with something else.\n * @param {string | undefined} folder Folder option.\n * @param {object} [options] Options.\n * @param {boolean} [options.isPublicFolder] Whether the option is `public_folder`.\n * @returns {string | undefined} Folder with the tags replaced, or the given folder as is if it has\n * no such tags or the global `media_folder` option is not configured.\n */\nconst replaceGlobalFolderTags = (folder, options) => {\n  // Check for the tags first, so the global folders are only resolved when needed\n  if (folder === undefined || !hasTags(folder)) {\n    return folder;\n  }\n\n  const globalFolders = cmsConfig.current ? resolveGlobalFolders(cmsConfig.current) : undefined;\n\n  return replaceFolderTags(folder, globalFolders, options) ?? folder;\n};\n\n/**\n * Find an asset by a relative path, using the associated entry and collection to help locate it.\n * @param {object} context Context.\n * @param {string} context.path Saved relative path.\n * @param {Entry} context.entry Associated entry to be used to help locate an asset from a relative\n * path. Can be `undefined` when editing a new draft.\n * @param {InternalCollection} context.collection Associated collection.\n * @param {InternalCollectionFile} [context.file] Associated collection file.\n * @param {string} [context.componentName] Custom editor component name for a field-level asset\n * folder.\n * @param {TypedFieldKeyPath} [context.typedKeyPath] Field key path for field-level media folders.\n * @param {InternalLocaleCode} [context.locale] Locale the path is referenced in, whose entry file\n * the path is relative to. Default: the default locale.\n * @returns {Asset | undefined} Found asset.\n */\nexport const getAssetByRelativePathAndCollection = ({\n  path,\n  entry,\n  collection,\n  file,\n  componentName,\n  typedKeyPath,\n  locale,\n}) => {\n  const {\n    _i18n: { defaultLocale },\n  } = file ?? collection;\n\n  // When a field-level key path is provided, look up the field-specific asset folder first so we\n  // use the correct `media_folder` (e.g. a field with `media_folder: images1` instead of the\n  // collection-level `/src/assets/images/blog`).\n  const fieldFolder = typedKeyPath\n    ? getAssetFolder({\n        collectionName: collection.name,\n        fileName: file?.name,\n        componentName,\n        typedKeyPath,\n      })\n    : undefined;\n\n  // A collection file without its own `media_folder` inherits the collection’s, along with its\n  // `public_folder`\n  const folderOptions = file?.media_folder !== undefined ? file : collection;\n\n  // A field-level folder that isn’t entry-relative is an absolute one, e.g. `/src/assets/authors`,\n  // which has to be used along with its own `public_folder` rather than the collection’s\n  // `media_folder`\n  let mediaFolder = fieldFolder\n    ? fieldFolder.entryRelative\n      ? (fieldFolder.internalSubPath ?? '')\n      : `/${fieldFolder.internalPath}`\n    : replaceGlobalFolderTags(/** @type {string | undefined} */ (folderOptions.media_folder));\n\n  let publicFolder =\n    fieldFolder?.publicPath !== undefined\n      ? fieldFolder.publicPath\n      : replaceGlobalFolderTags(/** @type {string | undefined} */ (folderOptions.public_folder), {\n          isPublicFolder: true,\n        });\n\n  const localeFile = /** @type {LocalizedEntry} */ (\n    getEntryLocaleFile(entry, { locale, defaultLocale })\n  );\n\n  const { path: entryFilePath, content: entryContent } = localeFile;\n\n  if (!entryFilePath || !entryContent) {\n    return undefined;\n  }\n\n  // Resolve template tags like `{{filename}}` or `{{slug}}` in an entry-relative `media_folder`\n  // (e.g. Hexo’s Post Asset Folder convention) so the asset can be located correctly.\n  // @see https://github.com/sveltia/sveltia-cms/issues/853\n  if (mediaFolder && hasTemplateTags(mediaFolder)) {\n    mediaFolder = fillMediaFolderTemplate(mediaFolder, { collection, entry, localeFile });\n  }\n\n  // Resolve them in `public_folder` too, so its prefix can be stripped from the stored path below\n  // @see https://github.com/sveltia/sveltia-cms/issues/1104\n  if (publicFolder && hasTemplateTags(publicFolder)) {\n    publicFolder = fillMediaFolderTemplate(publicFolder, { collection, entry, localeFile });\n  }\n\n  // Strip the `media_folder` prefix from the stored path before joining with `mediaFolder`, to\n  // avoid duplication when the stored value already includes the media folder (e.g.\n  // `images/photo.jpg`). Also normalize `./` prefix since `./images/photo.jpg` and\n  // `images/photo.jpg` are equivalent relative paths.\n  // `media_folder` is normalized the same way, since `./images` and `images/` are equivalent to\n  // `images`.\n  const normalizedPath = path.replace(/^\\.\\//, '');\n  const normalizedMediaFolder = mediaFolder?.replace(/^\\.\\//, '').replace(/\\/$/, '');\n  let localPath = stripPathPrefix(normalizedPath, normalizedMediaFolder);\n\n  // When `media_folder` is absolute (starts with `/`) and `public_folder` is entry-relative (e.g.\n  // starts with `.` or `..`), we need special handling for the Astro content collections pattern\n  // where images are stored in a shared folder but referenced with relative paths from each entry.\n  // Strip the `public_folder` prefix from the stored value and resolve directly against the\n  // absolute `media_folder`, bypassing `entryFolder` concatenation.\n  // An empty `public_folder` stores bare file names, which are relative to the `media_folder` too\n  if (mediaFolder?.startsWith('/') && publicFolder !== undefined) {\n    // Normalize `public_folder` by removing leading `./`\n    const normalizedPublicFolder = publicFolder.replace(/^\\.\\//, '');\n\n    // Check if the stored path starts with the public folder\n    if (normalizedPath.startsWith(`${normalizedPublicFolder}/`)) {\n      // Strip the public folder prefix to get just the filename/subpath\n      localPath = normalizedPath.slice(normalizedPublicFolder.length + 1);\n    }\n\n    // Resolve against the absolute media_folder (strip leading `/` to make it repo-relative)\n    return getAssetPathMap().get(resolvePath(createPath([mediaFolder.slice(1), localPath])));\n  }\n\n  // Concatenate the folder holding the entry’s relative assets, `media_folder` and the local path\n  return findInEntryBaseFolders({ collection, localeFile }, [mediaFolder, localPath]);\n};\n\n/**\n * Get the asset folders that may hold an asset referenced in a field, from the most specific to the\n * least: the custom editor component’s folder, the field’s, the collection file’s, the\n * collection’s, then the global one.\n * @param {object} args Arguments.\n * @param {string} [args.collectionName] Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} [args.componentName] Custom editor component name for a field-level asset folder.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Field key path for field-level media folders.\n * @param {boolean} [args.requireCollectionName] Whether to leave out the field, collection file\n * and collection folders when no collection name is given.\n * @param {boolean} [args.skipTemplateFolders] Whether to leave out the folders whose path has\n * template tags, which can’t be resolved without an entry.\n * @returns {AssetFolderInfo[]} Asset folders.\n */\nconst getCandidateAssetFolders = ({\n  collectionName,\n  fileName,\n  componentName,\n  typedKeyPath,\n  requireCollectionName = false,\n  skipTemplateFolders = false,\n}) => {\n  const hasCollection = !requireCollectionName || !!collectionName;\n\n  return /** @type {AssetFolderInfo[]} */ (\n    [\n      componentName ? getAssetFolder({ componentName, typedKeyPath }) : undefined,\n      hasCollection && typedKeyPath\n        ? getAssetFolder({ collectionName, fileName, typedKeyPath })\n        : undefined,\n      hasCollection ? getAssetFolder({ collectionName, fileName }) : undefined,\n      hasCollection ? getAssetFolder({ collectionName }) : undefined,\n      globalAssetFolder.current,\n    ].filter((folder) => !!folder && !(skipTemplateFolders && folder.hasTemplateTags))\n  );\n};\n\n/**\n * Get an asset by a relative public path typically stored as an image field value.\n * @param {object} args Arguments.\n * @param {string} args.path Saved relative path.\n * @param {Entry} [args.entry] Associated entry to be used to help locate an asset from a relative\n * path. Can be `undefined` when editing a new draft.\n * @param {string} [args.collectionName] Collection name, used when no entry is available.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} [args.componentName] Custom editor component name for a field-level asset folder.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Field key path for field-level media folders.\n * @param {InternalLocaleCode} [args.locale] Locale the path is referenced in, which tells which\n * locale’s entry file an entry-relative path is relative to. Default: the default locale.\n * @returns {Asset | undefined} Corresponding asset.\n */\nexport const getAssetByRelativePath = ({\n  path,\n  entry,\n  collectionName,\n  fileName,\n  componentName,\n  typedKeyPath,\n  locale,\n}) => {\n  if (!entry) {\n    // Without an entry we use collectionName/fileName to scan configured folders. For\n    // entry-relative folders, internalPath + internalSubPath is used as a best-effort path.\n    const scanningFolders = getCandidateAssetFolders({\n      collectionName,\n      fileName,\n      componentName,\n      typedKeyPath,\n      requireCollectionName: true,\n      skipTemplateFolders: true,\n    });\n\n    const foundAsset = scanningFolders\n      .values()\n      .map((folder) => {\n        // Strip the publicPath prefix from the stored path to get the bare filename/subpath, so\n        // that e.g. `uploads/photo.jpg` with publicPath `/uploads` resolves to `uploads/photo.jpg`\n        // internally rather than `uploads/uploads/photo.jpg`.\n        const localPath = stripPathPrefix(path, folder.publicPath?.replace(/^\\//, ''));\n\n        return getAssetPathMap().get(\n          createPath([folder.internalPath, folder.internalSubPath ?? '', localPath]),\n        );\n      })\n      .find(Boolean);\n\n    return foundAsset ?? getAssetPathMap().get(path);\n  }\n\n  /**\n   * Find the asset relative to the given locale’s entry file, stopping at the first collection or\n   * collection file that has it.\n   * @param {InternalLocaleCode | undefined} _locale Locale.\n   * @returns {Asset | undefined} Asset.\n   */\n  const findAsset = (_locale) =>\n    getEntryCollectionContexts(entry)\n      .map(({ collection, collectionFile: file }) =>\n        getAssetByRelativePathAndCollection({\n          path,\n          entry,\n          collection,\n          file,\n          componentName,\n          typedKeyPath,\n          locale: _locale,\n        }),\n      )\n      .find(Boolean);\n\n  return (\n    findAsset(locale) ??\n    // A file in a duplicated or synced field is stored once, relative to the default locale’s entry\n    // file, which the other locales then share\n    (locale ? findAsset(undefined) : undefined) ??\n    // Fall back to exact match at the root folder\n    getAssetPathMap().get(path)\n  );\n};\n\n/**\n * Cache of {@link getPublicPathRegex} results, keyed by the asset folder.\n * @type {WeakMap<AssetFolderInfo, RegExp>}\n */\nconst publicPathRegexCache = new WeakMap();\n\n/**\n * Get a regular expression matching a directory at or below the given folder’s public path, with\n * any template tag in the path matching a segment.\n * @param {AssetFolderInfo} folder Asset folder.\n * @returns {RegExp} Regular expression.\n */\nconst getPublicPathRegex = (folder) =>\n  getOrCreate(publicPathRegexCache, folder, () => {\n    const publicPath = folder.publicPath ?? '';\n    const normalizedPath = getTemplatePattern(publicPath, '.+?');\n\n    return new RegExp(`^${normalizedPath}${publicPath ? '(?=\\\\/|$)' : '$'}`);\n  });\n\n/**\n * Check if a path is a relative path. A path starting with `@`, like `@assets/images/...` is a\n * special case, considered as an absolute path.\n * @param {string} path Path to check.\n * @returns {boolean} `true` if the path is relative.\n */\nexport const isRelativePath = (path) => !/^[/@]/.test(path);\n\n/**\n * Get an asset by an absolute public path typically stored as an image field value.\n * @param {object} args Arguments.\n * @param {string} args.path Saved absolute path.\n * @param {Entry} [args.entry] Associated entry to be used to help locate an asset from a relative\n * path. Can be `undefined` when editing a new draft.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} [args.componentName] Custom editor component name for a field-level asset folder.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Field key path for field-level media folders.\n * @param {InternalLocaleCode} [args.locale] Locale the path is referenced in, which tells which\n * locale’s entry file an entry-relative path is relative to. Default: the default locale.\n * @returns {Asset | undefined} Corresponding asset.\n */\nexport const getAssetByAbsolutePath = ({\n  path,\n  entry,\n  collectionName,\n  fileName,\n  componentName,\n  typedKeyPath,\n  locale,\n}) => {\n  const exactMatch = getAssetPathMap().get(stripSlashes(path));\n\n  if (exactMatch) {\n    return exactMatch;\n  }\n\n  const { dirname: dirName = '', basename: baseName } = getPathInfo(path);\n\n  /**\n   * Look for the asset in the given folder.\n   * @param {AssetFolderInfo} folder Asset folder.\n   * @returns {Asset | undefined} Asset, if found.\n   */\n  const findInFolder = (folder) => {\n    const { publicPath, collectionName: _collectionName } = folder;\n    let { internalPath } = folder;\n\n    if (folder.entryRelative && publicPath) {\n      // An absolute public path of an entry-relative folder stands for the folder holding the\n      // entry’s relative assets, not the collection folder\n      if (publicPath.startsWith('/')) {\n        return findInEntryRelativeFolder({ path, folder, entry, locale });\n      }\n\n      // A relative one, like `images` or `./images`, gives a value relative to the entry, which an\n      // absolute path can’t stand for\n      if (isRelativePath(publicPath)) {\n        return undefined;\n      }\n    }\n\n    if (internalPath !== undefined) {\n      // Deal with template tags like `/assets/images/{{slug}}`\n      internalPath = fillInternalPathTemplate({\n        internalPath,\n        collectionName: _collectionName,\n        entry,\n        locale,\n      });\n\n      if (internalPath === undefined) {\n        // Cannot resolve the path\n        return undefined;\n      }\n    }\n\n    if (publicPath && dirName) {\n      if (publicPath === '/' || dirName.startsWith(`${publicPath}/`)) {\n        // Handle assets stored in a subfolder of the internal path\n        if (internalPath) {\n          internalPath =\n            publicPath === '/'\n              ? `${internalPath}${dirName}`\n              : dirName.replace(publicPath, internalPath);\n        }\n      } else if (!isRelativePath(publicPath) && !getPublicPathRegex(folder).test(dirName)) {\n        // The directory is neither the public path nor below it, e.g. `/images-old` or `/files`\n        // with the `/images` public path, so the asset cannot be in this folder. A public path with\n        // template tags, like `/images/{{slug}}`, matches any segment in place of the tags\n        return undefined;\n      }\n    }\n\n    return getAssetPathMap().get(createPath([internalPath, baseName]));\n  };\n\n  const scanningFolders = getCandidateAssetFolders({\n    collectionName,\n    fileName,\n    componentName,\n    typedKeyPath,\n  });\n\n  /** @type {Asset | undefined} */\n  let foundAsset = undefined;\n\n  // Use `some` to stop scanning folders as soon as the asset is found\n  scanningFolders.some((folder) => {\n    foundAsset = findInFolder(folder);\n\n    return !!foundAsset;\n  });\n\n  if (foundAsset) {\n    return foundAsset;\n  }\n\n  // Fall back to the last folder whose public path matches the directory. This is only worked out\n  // once the likely folders above have missed, as it tests the path against every asset folder\n  const matchingFolder = allAssetFolders.current.findLast((folder) =>\n    getPublicPathRegex(folder).test(dirName),\n  );\n\n  return matchingFolder ? findInFolder(matchingFolder) : undefined;\n};\n\n/**\n * Get an asset by a public path typically stored as an image field value.\n * @param {object} args Arguments.\n * @param {string} args.value Saved absolute path or relative path.\n * @param {Entry} [args.entry] Associated entry to be used to help locate an asset from a relative\n * path. Can be `undefined` when editing a new draft.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} [args.componentName] Custom editor component name for a field-level asset folder.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Field key path for field-level media folders.\n * @param {InternalLocaleCode} [args.locale] Locale the path is referenced in, which tells which\n * locale’s entry file an entry-relative path is relative to. Default: the default locale.\n * @returns {Asset | undefined} Corresponding asset.\n */\nexport const getAssetByPath = ({ value, ...rest }) => {\n  /**\n   * Look up an asset by the given path.\n   * @param {string} encodedPath Path that may contain URL-encoded characters.\n   * @returns {Asset | undefined} Corresponding asset.\n   */\n  const find = (encodedPath) => {\n    // The path is not encoded unless the `encode_file_path` option is enabled, so a file name can\n    // contain a `%` sign, like `50% off.jpg`, which would make `decodeURIComponent()` throw\n    const path = decodeURIComponentSafely(encodedPath);\n\n    return isRelativePath(path)\n      ? getAssetByRelativePath({ path, ...rest })\n      : getAssetByAbsolutePath({ path, ...rest });\n  };\n\n  // Look up the whole value first, as an unencoded file name can contain a `#` sign, like\n  // `photo #1.jpg`; then remove a potential fragment, like `#section`, and try again\n  const [pathWithoutFragment] = value.split('#');\n\n  return find(value) ?? (pathWithoutFragment !== value ? find(pathWithoutFragment) : undefined);\n};\n\n/**\n * Check if an asset belongs to the given asset folder. An asset is assigned to one folder only, but\n * a folder with a fixed path also holds the assets assigned to another folder with the same path,\n * so that the folders sharing a path, like an asset collection and a collection or field-level\n * folder, all list the same assets. An entry-relative folder has to be the asset’s own, as its path\n * is that of the collection, which the assets are stored somewhere below.\n * @param {Asset} asset Asset.\n * @param {AssetFolderInfo} folder Folder info.\n * @returns {boolean} Result.\n */\nexport const isAssetInFolder = ({ folder: assetFolder }, folder) => {\n  if (assetFolder === folder) {\n    return true;\n  }\n\n  if (!folder.entryRelative) {\n    return !assetFolder.entryRelative && assetFolder.internalPath === folder.internalPath;\n  }\n\n  return (\n    assetFolder.collectionName === folder.collectionName &&\n    assetFolder.fileName === folder.fileName &&\n    assetFolder.typedKeyPath === folder.typedKeyPath &&\n    assetFolder.isIndexFile === folder.isIndexFile &&\n    assetFolder.internalPath === folder.internalPath &&\n    assetFolder.internalSubPath === folder.internalSubPath &&\n    assetFolder.publicPath === folder.publicPath &&\n    assetFolder.entryRelative === folder.entryRelative &&\n    assetFolder.hasTemplateTags === folder.hasTemplateTags\n  );\n};\n\n/**\n * Get a list of assets stored in the given collection defined folder.\n * @param {AssetFolderInfo} folder Folder info.\n * @returns {Asset[]} Assets.\n */\nexport const getAssetsByFolder = (folder) =>\n  allAssets.current.filter((asset) => isAssetInFolder(asset, folder));\n\n/**\n * Get a key that two asset folders share exactly when {@link isAssetInFolder} would put the assets\n * of one in the other: the path alone for a folder with a fixed path, every property it compares\n * for an entry-relative folder.\n * @param {AssetFolderInfo} folder Folder info.\n * @returns {string} Key.\n */\nconst getAssetFolderMatchKey = ({\n  entryRelative,\n  collectionName,\n  fileName,\n  typedKeyPath,\n  isIndexFile,\n  internalPath,\n  internalSubPath,\n  publicPath,\n  hasTemplateTags: _hasTemplateTags,\n}) =>\n  JSON.stringify(\n    entryRelative\n      ? [\n          collectionName,\n          fileName,\n          typedKeyPath,\n          isIndexFile,\n          internalPath,\n          internalSubPath,\n          publicPath,\n          _hasTemplateTags,\n        ]\n      : [internalPath],\n  );\n\n/**\n * Number of assets in each folder, keyed by {@link getAssetFolderMatchKey}, counted in one pass\n * over {@link allAssets} and kept until the assets change.\n */\nconst getAssetCountsByFolder = memoizeOnSource(\n  () => allAssets.current,\n  (assets) => {\n    /** @type {Map<string, number>} */\n    const counts = new Map();\n\n    assets.forEach(({ folder }) => {\n      const key = getAssetFolderMatchKey(folder);\n\n      counts.set(key, (counts.get(key) ?? 0) + 1);\n    });\n\n    return counts;\n  },\n);\n\n/**\n * Count the assets stored in the given collection defined folder. This is the length of\n * {@link getAssetsByFolder}, without going through every asset for each folder, as the folder list\n * does for every folder whenever an asset is added, removed or renamed.\n * @param {AssetFolderInfo} folder Folder info.\n * @returns {number} Number of assets.\n */\nexport const countAssetsInFolder = (folder) =>\n  getAssetCountsByFolder().get(getAssetFolderMatchKey(folder)) ?? 0;\n\n/**\n * Index of the assets, keyed by the path of the directory they’re in, rebuilt when the assets are\n * replaced. Saving an entry looks up the directory of every file it adds.\n * @type {() => Map<string, Asset[]>}\n */\nconst getAssetsByDir = memoizeOnSource(\n  () => allAssets.current,\n  (assets) => Map.groupBy(assets, (asset) => getDirName(asset.path)),\n);\n\n/**\n * Get a list of assets stored in the given internal directory.\n * @param {string} dirname Directory path. An empty string for the repository root.\n * @returns {Asset[]} Assets.\n */\nexport const getAssetsByDirName = (dirname) => [...(getAssetsByDir().get(dirname) ?? [])];\n\n/**\n * Get the names a new file saved in the given internal directory can’t take: those of the assets,\n * the entry and Git config files and the subfolders there. A file would overwrite another, and a\n * Git tree can’t hold a file and a folder under one name.\n * @param {string} dirname Directory path. An empty string for the repository root.\n * @returns {string[]} Names, normalized to NFC.\n */\nexport const getTakenNamesInDir = (dirname) =>\n  [\n    ...getAssetsByDirName(dirname).map((a) => a.name),\n    ...getNonAssetFileNamesInDir(dirname),\n    ...getFolderNamesInDir(dirname),\n  ].map((name) => name.normalize());\n\n// Reset the asset selection when a different folder or subfolder is selected\ncreateRootEffect(() => {\n  // Read the folder and subfolder so that the effect re-runs whenever either changes\n  void selectedAssetFolder.current;\n  void selectedSubfolderPath.current;\n  focusedAsset.current = undefined;\n  focusedSubfolder.current = undefined;\n});\n\n/**\n * Get a list of duplicate files based on their names compared to existing assets.\n * @param {File[]} files The list of files to check for duplicates.\n * @param {Asset[]} assets The list of existing assets to compare against.\n * @returns {File[]} An array of files that have duplicate names in the existing assets.\n */\nexport const getDuplicateFiles = (files, assets) => {\n  if (!assets.length || !files.length) {\n    return [];\n  }\n\n  const existingNames = new Set(assets.map(({ name }) => foldFileName(name)));\n\n  return files.filter((file) => existingNames.has(foldFileName(file.name)));\n};\n","import { getAssetKind } from '$lib/services/assets/kinds';\nimport { matchesFilter } from '$lib/services/common/view';\nimport { getRegex } from '$lib/services/utils/regex';\n\n/**\n * @import { Asset, FilteringConditions } from '$lib/types/private';\n */\n\n/**\n * Filter the given assets.\n * @param {Asset[]} assets Asset list.\n * @param {FilteringConditions} [conditions] Filtering conditions.\n * @returns {Asset[]} Filtered asset list.\n */\nexport const filterAssets = (assets, { field, pattern } = { field: '', pattern: '' }) => {\n  if (!field) {\n    return assets;\n  }\n\n  if (field === 'fileType') {\n    return assets.filter(({ path }) => getAssetKind(path) === pattern);\n  }\n\n  const regex = getRegex(pattern);\n\n  return assets.filter((asset) => {\n    const value = /** @type {Record<string, any>} */ (asset)[field];\n\n    return matchesFilter(value, pattern, regex);\n  });\n};\n","import { groupItems } from '$lib/services/common/view';\n\n/**\n * @import { Asset, GroupingConditions } from '$lib/types/private';\n */\n\n/**\n * Group the given assets.\n * @param {Asset[]} assets Asset list.\n * @param {GroupingConditions | null} [conditions] Grouping conditions.\n * @returns {Record<string, Asset[]>} Grouped assets, where key is a group name, displayed with\n * `getGroupLabel()`, and value is an asset list.\n */\nexport const groupAssets = (assets, conditions) =>\n  groupItems(\n    assets,\n    conditions,\n    (asset, field) => /** @type {Record<string, any>} */ (asset)[field],\n  );\n","const SVG_NS = 'http://www.w3.org/2000/svg';\n\n/**\n * Read the given blob as a `data:` URL.\n * @param {Blob} blob Blob.\n * @returns {Promise<string>} `data:` URL.\n */\nconst readAsDataURL = (blob) =>\n  new Promise((resolve, reject) => {\n    const reader = new FileReader();\n\n    reader.addEventListener('load', () => {\n      resolve(/** @type {string} */ (reader.result));\n    });\n    reader.addEventListener('error', () => {\n      reject(reader.error);\n    });\n    reader.readAsDataURL(blob);\n  });\n\n/**\n * Check if the given `width` or `height` attribute value is a fixed length, rather than missing or\n * a percentage, which doesn’t give the image an intrinsic size.\n * @param {string | null} value Attribute value.\n * @returns {boolean} Result.\n */\nconst isFixedLength = (value) => !!value?.trim() && !value.trim().endsWith('%');\n\n/**\n * Parse the given `viewBox` attribute value.\n * @param {string | null} value Attribute value.\n * @returns {{ x: number, y: number, width: number, height: number } | undefined} Rectangle, or\n * `undefined` if the value is missing or invalid.\n */\nconst parseViewBox = (value) => {\n  const numbers = (value ?? '')\n    .trim()\n    .split(/[\\s,]+/)\n    .map(Number);\n\n  if (numbers.length !== 4 || numbers.some((number) => !Number.isFinite(number))) {\n    return undefined;\n  }\n\n  const [x, y, width, height] = numbers;\n\n  return width > 0 && height > 0 ? { x, y, width, height } : undefined;\n};\n\n/**\n * Create an SVG image that displays the given one without letting it run any script. An object URL\n * has the CMS origin, so an SVG file from the repository opened in a new tab, e.g. with the\n * browser’s “Open Image in New Tab” menu item on a preview, would otherwise run any script in it\n * with access to the user’s token. The wrapper only embeds the original with an `<image>` element,\n * which always renders it in the secure mode where scripts never run, even when the wrapper itself\n * is opened as a document.\n *\n * The wrapper takes the size of the original, so it looks the same in an `<img>` element. When the\n * original has a fixed width and height, those alone define its intrinsic size and aspect ratio;\n * otherwise its `viewBox` does, and the embedded image fills the same box so it isn’t distorted. A\n * file that isn’t valid SVG is still wrapped, to be shown as an empty image.\n * @param {Blob} blob SVG image.\n * @returns {Promise<Blob>} Wrapper SVG image.\n */\nexport const createInertSVG = async (blob) => {\n  const { documentElement: root } = new DOMParser().parseFromString(\n    await blob.text(),\n    'image/svg+xml',\n  );\n\n  const isSVG = root.namespaceURI === SVG_NS && root.localName === 'svg';\n  const svg = document.createElementNS(SVG_NS, 'svg');\n  const image = document.createElementNS(SVG_NS, 'image');\n\n  const hasFixedSize =\n    isSVG && ['width', 'height'].every((n) => isFixedLength(root.getAttribute(n)));\n\n  const attributeNames = hasFixedSize\n    ? ['width', 'height']\n    : ['width', 'height', 'viewBox', 'preserveAspectRatio'];\n\n  if (isSVG) {\n    attributeNames.forEach((name) => {\n      const value = root.getAttribute(name);\n\n      if (value !== null) {\n        svg.setAttribute(name, value);\n      }\n    });\n  }\n\n  const viewBox = parseViewBox(svg.getAttribute('viewBox'));\n\n  Object.entries(viewBox ?? { width: '100%', height: '100%' }).forEach(([name, value]) => {\n    image.setAttribute(name, String(value));\n  });\n\n  image.setAttribute('preserveAspectRatio', 'none');\n  image.setAttribute('href', await readAsDataURL(new Blob([blob], { type: 'image/svg+xml' })));\n  svg.append(image);\n\n  return new Blob([new XMLSerializer().serializeToString(svg)], { type: 'image/svg+xml' });\n};\n","import { getUnpkgURL } from '$lib/services/app/dependencies';\n\n/**\n * PDF.js distribution URL. The CDN builds don’t bundle the library due to the large size and\n * multiple files. However, having it as a dependency in `package.json` allows us to include the\n * latest version in the UNPKG URL, making it faster to load the script without waiting for a\n * redirect. The npm build replaces this module with `pdf-options.npm.js`.\n * @see https://github.com/mozilla/pdf.js\n */\nconst PDFJS_DIST_URL = getUnpkgURL('pdfjs-dist');\nconst PDFJS_WORKER_URL = `${PDFJS_DIST_URL}/build/pdf.worker.min.mjs`;\n\n/**\n * Options for `getDocument()` pointing PDF.js to its data files on UNPKG.\n */\nconst PDFJS_GET_DOC_OPTIONS = {\n  cMapUrl: `${PDFJS_DIST_URL}/cmaps/`,\n  iccUrl: `${PDFJS_DIST_URL}/iccs/`,\n  standardFontDataUrl: `${PDFJS_DIST_URL}/standard_fonts/`,\n  wasmUrl: `${PDFJS_DIST_URL}/wasm/`,\n};\n\n/**\n * @typedef {object} PDFLoadingOptions\n * @property {Record<string, any>} options Options for `getDocument()`.\n * @property {() => void} dispose Function to clean up once the loading task has been destroyed.\n */\n\n/**\n * Get the options for loading a PDF document with PDF.js from UNPKG. The worker is loaded from the\n * same place, and created by PDF.js for each document.\n * @param {import('pdfjs-dist')} pdfjs PDF.js module.\n * @returns {PDFLoadingOptions} Options for `getDocument()`, and a function to clean up once the\n * loading task has been destroyed, which does nothing here.\n */\nexport const createLoadingOptions = (pdfjs) => {\n  pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;\n\n  return {\n    options: PDFJS_GET_DOC_OPTIONS,\n    /**\n     * Nothing to clean up, as PDF.js ends the worker it has created with the loading task.\n     */\n    dispose: () => {},\n  };\n};\n","import { loadModule } from '$lib/services/app/dependencies';\nimport { exportCanvasAsBlob } from '$lib/services/utils/media/image/encode';\nimport { resolveTransformOptions } from '$lib/services/utils/media/image/options';\nimport { resizeCanvas } from '$lib/services/utils/media/image/resize';\nimport { createLoadingOptions } from '$lib/services/utils/media/pdf-options';\n\n/**\n * @import { InternalImageTransformationOptions } from '$lib/types/private';\n * @import { PDFLoadingOptions } from '$lib/services/utils/media/pdf-options';\n */\n\n/**\n * Placeholder for the PDF.js module.\n * @type {import('pdfjs-dist')}\n */\nlet pdfjs;\n\n/**\n * Create a thumbnail image of a PDF document using PDF.js.\n * @param {File | Blob} blob Source file.\n * @param {InternalImageTransformationOptions} [options] Options.\n * @returns {Promise<Blob>} Thumbnail blob.\n * @throws {Error} When the rendering failed.\n * @see https://github.com/mozilla/pdf.js/blob/master/examples/webpack/main.mjs\n * @see https://github.com/mozilla/pdf.js/issues/10478\n */\nexport const renderPDF = async (blob, options = {}) => {\n  const { format, quality, width, height, fit, nativeOnly } = resolveTransformOptions(options);\n\n  // Lazily load the PDF.js library\n  if (!pdfjs) {\n    try {\n      pdfjs = await loadModule('pdfjs-dist', 'build/pdf.min.mjs');\n    } catch {\n      throw new Error('Failed to load PDF.js library');\n    }\n  }\n\n  const url = URL.createObjectURL(blob);\n  const canvas = new OffscreenCanvas(512, 512);\n  const context = /** @type {OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d'));\n  // Without a `worker` option, every document gets a Web Worker of its own, which is only\n  // terminated when the loading task is destroyed. A thumbnail is rendered once, so the task has to\n  // be destroyed right after, or each PDF would leave a worker thread running for the rest of the\n  // session, holding the parsed document in memory. A worker passed in the options is ended by\n  // `dispose()` instead\n  /** @type {import('pdfjs-dist').PDFDocumentLoadingTask | undefined} */\n  let loadingTask;\n  /** @type {PDFLoadingOptions | undefined} */\n  let loadingOptions;\n\n  try {\n    loadingOptions = createLoadingOptions(pdfjs);\n    loadingTask = pdfjs.getDocument({ disableAutoFetch: true, ...loadingOptions.options, url });\n\n    const pdfDocument = await loadingTask.promise;\n    const pdfPage = await pdfDocument.getPage(1);\n    const viewport = pdfPage.getViewport({ scale: 1 });\n\n    const { scale } = resizeCanvas(\n      canvas,\n      { width: viewport.width, height: viewport.height },\n      { width, height, fit },\n    );\n\n    await pdfPage.render({\n      // @ts-ignore `OffscreenCanvas` is supported\n      canvasContext: context,\n      viewport: scale === 1 ? viewport : pdfPage.getViewport({ scale }),\n    }).promise;\n  } catch {\n    throw new Error('Failed to render PDF');\n  } finally {\n    URL.revokeObjectURL(url);\n\n    try {\n      await loadingTask?.destroy();\n    } catch {\n      // The page has been rendered onto the canvas, or the rendering has already failed, so a\n      // failure to clean up changes nothing for the caller\n    }\n\n    loadingOptions?.dispose();\n  }\n\n  return exportCanvasAsBlob(canvas, { format, quality, nativeOnly });\n};\n","import { escapeRegExp } from '@sveltia/utils/string';\n\nimport { getEntryRelativePublicPath } from '$lib/services/assets/entry-relative';\nimport { getAssetFoldersByPath, globalAssetFolder } from '$lib/services/assets/folders';\nimport { canCreateThumbnail, isPDF } from '$lib/services/assets/kinds';\nimport { allAssets } from '$lib/services/assets/state';\nimport { backend } from '$lib/services/backends';\nimport {\n  TEMPLATE_TAG_REGEX,\n  TEMPLATE_TAG_REPLACE_REGEX,\n} from '$lib/services/common/template/constants';\nimport { cmsConfig } from '$lib/services/config';\nimport { createLRUMap, shareInFlight } from '$lib/services/utils/cache';\nimport { getRepositoryDatabase } from '$lib/services/utils/database';\nimport { createPathRegEx, encodeFilePath } from '$lib/services/utils/file';\nimport { createInertSVG } from '$lib/services/utils/media/image/svg';\nimport {\n  THUMBNAIL_TRANSFORM_OPTIONS,\n  transformImage,\n} from '$lib/services/utils/media/image/transform';\nimport { renderPDF } from '$lib/services/utils/media/pdf';\nimport mime from '$lib/services/utils/mime';\nimport { createConcurrencyLimiter } from '$lib/services/utils/scheduling';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import { LRUMap } from '$lib/services/utils/cache';\n * @import {\n * Asset,\n * AssetFolderInfo,\n * Entry,\n * InternalCmsConfig,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n */\n\n/**\n * @typedef {Pick<IndexedDB, 'get' | 'set'> | LRUMap<string, Blob>} ThumbnailStore\n */\n\n/**\n * Blobs behind the object URLs cached on assets, keyed by blob URL. An object URL already keeps its\n * blob alive in memory until it’s revoked, so remembering the blob here costs nothing extra, and it\n * spares every caller after the first from reading the same URL back over the network. It’s also\n * the only way to get an SVG image back, as its URL points to a wrapper made for display rather\n * than the file itself, see {@link getDisplayBlob}.\n *\n * Only blobs the asset doesn’t hold otherwise — downloaded or just saved — belong here, and only\n * under a URL that {@link flushRevocations} is responsible for revoking, because that’s where the\n * entry is discarded. A\n * blob whose URL is revoked elsewhere — an unsaved file’s URL, released by `revokeDraftFileURLs`\n * once the draft is replaced — would otherwise stay in memory for the lifetime of the page.\n * @type {Map<string, Blob>}\n */\nconst cachedBlobs = new Map();\n/**\n * Asset blob downloads currently in flight, keyed by the blob URL or asset path being read. Several\n * components can ask for the same asset at once — the info panel and the toolbar both request an\n * asset’s details as soon as it’s selected — so they share a single download instead of each\n * starting their own.\n * @type {Map<string, Promise<Blob>>}\n */\nconst pendingAssetBlobs = new Map();\n\n/* v8 ignore next */\n/**\n * Reset the asset blob caches. This is used in tests to reset the state between tests.\n */\nexport const _resetAssetBlobCache = () => {\n  cachedBlobs.clear();\n  pendingAssetBlobs.clear();\n};\n\n/**\n * Regular expression matching an XML media type, such as `application/xml`, `text/xml` or\n * `application/xhtml+xml`. A browser renders such a file as a document, which can run script\n * through XHTML elements or an XSLT style sheet.\n */\nconst XML_TYPE_REGEX = /[/+]xml$/;\n\n/**\n * Get a blob that can be displayed in place of the given file without running any script. An\n * object URL has the CMS origin, so a file from the repository opened in a new tab, e.g. with the\n * browser’s “Open Image in New Tab” menu item on a preview, would otherwise run any script in it\n * with access to the user’s token. An SVG image is wrapped in an image that can’t run script, see\n * {@link createInertSVG}, and an HTML or XML document is turned into plain text, as nothing\n * displays one as a document. Any other file is returned as is.\n * @param {Blob} blob Original file.\n * @returns {Promise<Blob>} Blob to be displayed.\n */\nexport const getDisplayBlob = async (blob) => {\n  const type = blob.type.split(';')[0].trim().toLowerCase();\n\n  if (type === 'image/svg+xml') {\n    return createInertSVG(blob);\n  }\n\n  if (type === 'text/html' || XML_TYPE_REGEX.test(type)) {\n    return new Blob([blob], { type: 'text/plain' });\n  }\n\n  return blob;\n};\n\n/**\n * Create an object URL to display the given file with, see {@link getDisplayBlob}. Use this for\n * any URL made from asset or file bytes that is shown in the UI. The URL doesn’t necessarily point\n * to the given bytes, so a caller that needs the file again has to keep the original rather than\n * read the URL back.\n * @param {Blob} blob Original file.\n * @returns {Promise<string>} Object URL.\n */\nexport const createDisplayBlobURL = async (blob) => URL.createObjectURL(await getDisplayBlob(blob));\n\n/**\n * Give the asset an object URL for the given blob if it doesn’t have one yet. The URL points to the\n * blob to be displayed, see {@link getDisplayBlob}; the blob itself is left untouched.\n * @param {Asset} asset Asset.\n * @param {Blob} blob Blob.\n * @returns {Promise<Blob>} The same blob.\n */\nconst cacheAssetBlobURL = async (asset, blob) => {\n  if (!asset.blobURL) {\n    const displayBlob = await getDisplayBlob(blob);\n\n    // Another caller may have created the URL while the wrapper was being made\n    asset.blobURL ??= URL.createObjectURL(displayBlob);\n  }\n\n  return blob;\n};\n\n/**\n * Give the asset an object URL for the given blob, and remember the blob so that later callers can\n * have it without reading the URL back, which may point to a wrapper rather than the file itself.\n * Use this for a blob that the asset doesn’t hold otherwise, e.g. a downloaded or saved file.\n * @param {Asset} asset Asset.\n * @param {Blob} blob Blob.\n * @returns {Promise<Blob>} The same blob.\n */\nexport const cacheAssetBlob = async (asset, blob) => {\n  await cacheAssetBlobURL(asset, blob);\n\n  if (asset.blobURL) {\n    cachedBlobs.set(asset.blobURL, blob);\n  }\n\n  return blob;\n};\n\n/**\n * Download a blob, letting concurrent callers waiting on the same source share one request. A\n * failed download is not remembered, so a later caller can try again.\n * @param {string} key Blob URL or asset path being read.\n * @param {() => Promise<Blob>} download Function that performs the download.\n * @returns {Promise<Blob>} Blob.\n */\nconst downloadOnce = (key, download) => shareInFlight(pendingAssetBlobs, key, download);\n\n/**\n * Download the given asset from the backend, without caching it.\n * @param {Asset} asset Asset.\n * @returns {Promise<Blob>} Blob.\n * @throws {Error} When the blob cannot be retrieved.\n */\nconst downloadAssetBlob = async (asset) => {\n  const { name } = asset;\n  const blob = await backend.current?.fetchBlob?.(asset);\n\n  if (!blob) {\n    throw new Error('Failed to retrieve blob');\n  }\n\n  // Override the MIME type as it can be `application/octet-stream`\n  return new Blob([blob], { type: mime.getType(name) ?? blob.type });\n};\n\n/**\n * Download the given asset from the backend, and cache it on the asset.\n * @param {Asset} asset Asset.\n * @returns {Promise<Blob>} Blob.\n * @throws {Error} When the blob cannot be retrieved.\n */\nconst fetchAssetBlob = async (asset) => cacheAssetBlob(asset, await downloadAssetBlob(asset));\n\n/**\n * Read the file behind the given handle.\n * @param {FileSystemFileHandle} handle File handle.\n * @param {(file: File) => Promise<Blob>} [transform] Function to process the file with, whose\n * failure is reported the same way as a failed read.\n * @returns {Promise<Blob>} File, or the result of `transform`.\n * @throws {Error} When the file cannot be read or processed.\n */\nconst readHandle = async (handle, transform = async (file) => file) => {\n  try {\n    return await transform(await handle.getFile());\n  } catch {\n    throw new Error('Failed to retrieve blob from file handle');\n  }\n};\n\n/**\n * Get the blob for the given asset, from wherever it’s available: the file it was created from, the\n * object URL already cached on it, a file system handle, or the backend.\n * @param {Asset} asset Asset.\n * @returns {Promise<Blob>} Blob.\n * @throws {Error} When the blob cannot be retrieved.\n */\nexport const getAssetBlob = async (asset) => {\n  const { file, handle, blobURL, path } = asset;\n\n  // An unsaved asset holds the original file, which is the same data the object URL points at, so\n  // use it directly rather than reading the URL back. Nothing is cached for it: the file is already\n  // here, and its URL may be revoked by the draft rather than by `flushRevocations`\n  if (file) {\n    return cacheAssetBlobURL(asset, file);\n  }\n\n  if (blobURL) {\n    // The URL can be created elsewhere in the app, in which case the blob has to be read back. The\n    // result isn’t cached, because whoever created the URL also decides when to revoke it\n    return (\n      cachedBlobs.get(blobURL) ?? downloadOnce(blobURL, () => fetch(blobURL).then((r) => r.blob()))\n    );\n  }\n\n  if (handle) {\n    return readHandle(handle, (blob) => cacheAssetBlob(asset, blob));\n  }\n\n  return downloadOnce(path, () => fetchAssetBlob(asset));\n};\n\n/**\n * Get the blob of the given asset to generate a thumbnail from. Unlike {@link getAssetBlob}, this\n * doesn’t cache the full-size file on the asset: the thumbnail is all that’s kept, so an asset grid\n * or an entry list showing hundreds of images doesn’t hold every original in memory as well. A blob\n * that’s already at hand — the unsaved file, the one behind the asset’s object URL, or a download\n * another caller has started — is used as is.\n * @param {Asset} asset Asset.\n * @returns {Promise<Blob>} Blob.\n * @throws {Error} When the blob cannot be retrieved.\n */\nconst getThumbnailSourceBlob = async (asset) => {\n  const { file, handle, blobURL, path } = asset;\n\n  if (file) {\n    return file;\n  }\n\n  if (blobURL) {\n    return getAssetBlob(asset);\n  }\n\n  const pending = pendingAssetBlobs.get(path);\n\n  if (pending) {\n    return pending;\n  }\n\n  if (handle) {\n    return readHandle(handle);\n  }\n\n  return downloadAssetBlob(asset);\n};\n\n/**\n * Get the blob URL for the given asset.\n * @param {Asset} asset Asset.\n * @returns {Promise<string | undefined>} URL or `undefined` if the blob is not available.\n */\nexport const getAssetBlobURL = async (asset) => {\n  if (!asset.blobURL) {\n    await getAssetBlob(asset);\n  }\n\n  return asset.blobURL;\n};\n\n/**\n * Where the thumbnails are cached, keyed by asset SHA: the database if the backend has one, the\n * {@link memoryThumbnailCache} otherwise. It’s picked by {@link initThumbnailStore}.\n * @type {ThumbnailStore | undefined}\n */\nlet thumbnailStore = undefined;\n/**\n * Thumbnail blob resolutions currently in flight, keyed by asset SHA. Generating a thumbnail means\n * a database read and, on a miss, decoding and transforming the full-size image, so concurrent\n * requests for the same asset — several components showing it at once, or one component asking for\n * both a preview and a blurred backdrop — share a single resolution instead of repeating the work.\n * @type {Map<string, Promise<Blob | undefined>>}\n */\nconst pendingThumbnailBlobs = new Map();\n/**\n * Maximum number of thumbnails kept in {@link memoryThumbnailCache}. A thumbnail is a few dozen\n * kilobytes, so this stays within a few dozen megabytes.\n */\nconst MEMORY_THUMBNAIL_CACHE_SIZE = 500;\n/**\n * Thumbnails kept in memory, keyed by asset SHA, for a backend without a database to cache them in,\n * like the test backend. Without it, a thumbnail would be generated again each time a list row\n * showing it is rendered. The least recently used one is dropped first.\n * @type {LRUMap<string, Blob>}\n */\nconst memoryThumbnailCache = createLRUMap(MEMORY_THUMBNAIL_CACHE_SIZE);\n/**\n * Get the cached thumbnail of the given asset, once {@link initThumbnailStore} has been called.\n * @param {string} sha Asset SHA.\n * @returns {Promise<Blob | undefined>} Thumbnail blob, if cached.\n */\nconst getCachedThumbnail = async (sha) => /** @type {ThumbnailStore} */ (thumbnailStore).get(sha);\n\n/* v8 ignore next */\n/**\n * Reset the thumbnail database. This is used in tests to reset the state of the thumbnail database\n * between tests.\n */\nexport const _resetThumbnailStore = () => {\n  thumbnailStore = undefined;\n  pendingThumbnailBlobs.clear();\n  memoryThumbnailCache.clear();\n};\n\n/**\n * Initialize {@link thumbnailStore} if it hasn’t been initialized yet.\n */\nconst initThumbnailStore = () => {\n  thumbnailStore ??=\n    getRepositoryDatabase(backend.current?.repository, 'asset-thumbnails') ?? memoryThumbnailCache;\n};\n\n/**\n * Limit the thumbnails being generated at the same time. Each one decodes the full-size image, so a\n * folder of photos shown for the first time would otherwise hold all of them in memory at once. The\n * latest request goes first: in a list being scrolled, that’s a thumbnail now on screen, which\n * would otherwise wait behind every one requested for the rows scrolled past.\n */\nconst limitThumbnailGeneration = createConcurrencyLimiter(4, { lastInFirstOut: true });\n\n/**\n * Get a thumbnail blob for the given asset, generating it from the original file if it’s not in the\n * cache database yet.\n * @param {Asset} asset Asset.\n * @returns {Promise<Blob | undefined>} Thumbnail blob.\n */\nconst resolveThumbnailBlob = async (asset) => {\n  const { sha } = asset;\n  /** @type {Blob | undefined} */\n  let thumbnailBlob = await getCachedThumbnail(sha);\n\n  if (!thumbnailBlob) {\n    const transform = isPDF(asset.name) ? renderPDF : transformImage;\n\n    thumbnailBlob = await limitThumbnailGeneration(\n      async () => transform(await getThumbnailSourceBlob(asset), THUMBNAIL_TRANSFORM_OPTIONS),\n      { key: sha },\n    );\n\n    await /** @type {ThumbnailStore} */ (thumbnailStore).set(sha, thumbnailBlob);\n  }\n\n  return thumbnailBlob;\n};\n\n/**\n * Check if a thumbnail has been generated for the given file content. A thumbnail is only ever made\n * by decoding the file, so having one proves the file is a usable image, and a caller that would\n * otherwise decode the file just to validate it can skip that.\n * @param {string} sha Git object ID (SHA-1 hash) of the file.\n * @returns {Promise<boolean>} Whether a thumbnail is cached or being generated. A generation in\n * flight is awaited, as the outcome is what matters.\n */\nexport const hasCachedThumbnail = async (sha) => {\n  initThumbnailStore();\n\n  const pending = pendingThumbnailBlobs.get(sha);\n\n  if (pending) {\n    return !!(await pending.catch(() => undefined));\n  }\n\n  return !!(await getCachedThumbnail(sha));\n};\n\n/**\n * Get a thumbnail image for the given asset.\n * @param {Asset} asset Asset.\n * @param {object} [options] Options.\n * @param {boolean} [options.cacheOnly] Whether to search a thumbnail in the cache database only.\n * @returns {Promise<string | undefined>} Thumbnail blob URL. Each caller gets its own object URL,\n * so it can be revoked independently.\n */\nexport const getAssetThumbnailURL = async (asset, { cacheOnly = false } = {}) => {\n  if (!canCreateThumbnail(asset)) {\n    return undefined;\n  }\n\n  initThumbnailStore();\n\n  const { sha } = asset;\n\n  if (cacheOnly && !pendingThumbnailBlobs.has(sha)) {\n    // Nothing is being generated for this asset, so stick to a cache lookup as requested\n    const cachedBlob = await getCachedThumbnail(sha);\n\n    return cachedBlob ? URL.createObjectURL(cachedBlob) : undefined;\n  }\n\n  // The generation of a thumbnail asked for again, e.g. by a row now on screen after one scrolled\n  // past, is moved up the queue. As the latest request goes first, it would otherwise wait behind\n  // every one made since it was first queued\n  if (!cacheOnly && pendingThumbnailBlobs.has(sha)) {\n    limitThumbnailGeneration.prioritize(sha);\n  }\n\n  // A `cacheOnly` caller joins an in-flight resolution rather than reading the database again: the\n  // work is already happening, so waiting for it costs nothing extra\n  const thumbnailBlob = await shareInFlight(pendingThumbnailBlobs, sha, () =>\n    resolveThumbnailBlob(asset),\n  );\n\n  return thumbnailBlob ? URL.createObjectURL(thumbnailBlob) : undefined;\n};\n\n/**\n * Blob URLs awaiting revocation, collected until the next animation frame.\n * @type {Set<string>}\n */\nconst pendingRevocations = new Set();\n/**\n * Blob URLs of the assets preloaded with {@link preloadAssets}, which a revocation leaves alone\n * until they’re no longer preloaded, although no element displays them yet.\n * @type {Set<string>}\n */\nconst preloadedURLs = new Set();\n/**\n * Assets most recently passed to {@link preloadAssets}, including the ones to keep.\n * @type {Asset[]}\n */\nlet preloadedAssets = [];\n/**\n * Assets most recently passed to {@link preloadAssets} to be loaded, excluding the ones to keep.\n * @type {Asset[]}\n */\nlet loadedAssets = [];\n\n/* v8 ignore next */\n/**\n * Discard the queued blob URL revocations. This is used in tests, where the animation frame that\n * would drain the queue is mocked out.\n */\nexport const _resetRevocationQueue = () => {\n  pendingRevocations.clear();\n  preloadedURLs.clear();\n  preloadedAssets = [];\n  loadedAssets = [];\n};\n\n/**\n * Revoke every queued blob URL that no element is displaying any more.\n */\nconst flushRevocations = () => {\n  const urls = new Set(pendingRevocations);\n\n  pendingRevocations.clear();\n\n  // One query for every blob URL on the page, rather than one per asset\n  document.querySelectorAll('[src^=\"blob:\"]').forEach((element) => {\n    urls.delete(/** @type {string} */ (element.getAttribute('src')));\n  });\n\n  preloadedURLs.forEach((url) => {\n    urls.delete(url);\n  });\n\n  if (!urls.size) {\n    return;\n  }\n\n  urls.forEach((url) => {\n    URL.revokeObjectURL(url);\n    cachedBlobs.delete(url);\n  });\n\n  // Update the store directly because the passed `asset` can be a proxy\n  allAssets.current.forEach((asset) => {\n    if (asset.blobURL !== undefined && urls.has(asset.blobURL)) {\n      delete asset.blobURL;\n    }\n  });\n};\n\n/**\n * Revoke the given blob URL if it’s not being used in any elements.\n *\n * The revocations are batched, because every asset preview asks for one as it unmounts: leaving an\n * asset grid would otherwise run a document-wide query and a scan of every asset once per preview,\n * which is O(assets²) in the frame the page navigates away.\n *\n * Deferring to the next frame is also what keeps a still-decoding image working: the flush skips\n * any URL an element is displaying, so a thumbnail is only released once nothing points at it.\n * @param {string | undefined} url Blob URL, or `undefined`/a non-blob URL to ignore.\n */\nexport const revokeBlobURLIfNeeded = (url) => {\n  if (!url?.startsWith('blob:')) {\n    return;\n  }\n\n  const isFirst = !pendingRevocations.size;\n\n  // Queue before scheduling, so the flush can never observe an empty queue\n  pendingRevocations.add(url);\n\n  if (isFirst) {\n    window.requestAnimationFrame(flushRevocations);\n  }\n};\n\n/**\n * Revoke the blob URL for the given asset if it’s not being used in any elements.\n *\n * An unsaved asset is left alone, as its URL belongs to whoever created it: the entry draft, which\n * uses it as the field value until the entry is saved, or the asset picker, for a file dropped\n * into it. Revoking it here would break the field as soon as the picker is closed, if the field\n * hasn’t displayed the URL again by the next frame — which is the case when the same file is\n * picked again on a slow device.\n * @param {Asset} asset Asset.\n * @see https://github.com/sveltia/sveltia-cms/issues/1030\n */\nexport const revokeAssetBlobURLIfNeeded = ({ blobURL, unsaved }) => {\n  if (!unsaved) {\n    revokeBlobURLIfNeeded(blobURL);\n  }\n};\n\n/**\n * Convert the path of an asset stored in a folder with template tags, like\n * `/assets/images/{{slug}}`, to its public path. Each tag in the internal path captures the text it\n * stands for, which then fills the same tag in the public path. A tag can share a path segment with\n * literal text, as in `post-{{slug}}`, and appear more than once.\n * @param {object} args Arguments.\n * @param {string} args.path Asset path, e.g. `static/images/post-hello/photo.jpg`.\n * @param {string} args.internalPath Folder’s internal path, e.g. `static/images/post-{{slug}}`.\n * @param {string} args.publicPath Folder’s public path, e.g. `/images/post-{{slug}}`.\n * @returns {string} Public path, e.g. `/images/post-hello/photo.jpg`.\n */\nconst replaceTemplatePath = ({ path, internalPath, publicPath }) => {\n  /**\n   * Capture group names by tag. A tag, like `{{slug | upper}}`, isn’t always a valid group name.\n   * @type {Map<string, string>}\n   */\n  const groupNames = new Map();\n\n  const regex = createPathRegEx(internalPath, (segment) => {\n    const pattern = segment\n      .split(TEMPLATE_TAG_REGEX)\n      .map((part, index) => {\n        // The odd parts are the tag names captured by the split\n        if (index % 2 === 0) {\n          return escapeRegExp(part);\n        }\n\n        const tag = part.trim();\n        const groupName = groupNames.get(tag);\n\n        if (groupName) {\n          // The same text again\n          return `\\\\k<${groupName}>`;\n        }\n\n        const newGroupName = `tag${groupNames.size}`;\n\n        groupNames.set(tag, newGroupName);\n\n        return `(?<${newGroupName}>[^/]+?)`;\n      })\n      .join('');\n\n    // A tag at the end of the segment takes everything up to the next slash\n    return `${pattern}(?=\\\\/|$)`;\n  });\n\n  return path.replace(regex, (...args) => {\n    /** @type {Record<string, string>} */\n    const groups = args.at(-1);\n\n    return publicPath.replaceAll(TEMPLATE_TAG_REPLACE_REGEX, (tag, name) => {\n      const groupName = groupNames.get(name.trim());\n\n      return groupName ? groups[groupName] : tag;\n    });\n  });\n};\n\n/**\n * Get the asset folder whose public path applies to the given asset.\n * @param {Asset} asset Asset.\n * @returns {AssetFolderInfo} Asset folder.\n */\nconst resolvePublicFolder = (asset) =>\n  asset.folder.collectionName === undefined\n    ? // Use the global asset folder\n      asset.folder\n    : // Search for the asset folder instead of using `asset.folder` directly, as an asset can be\n      // used for multiple collections, and the public path can be different for each\n      (getAssetFoldersByPath(asset.path).find(\n        ({ collectionName }) => collectionName !== undefined,\n      ) ??\n      globalAssetFolder.current ??\n      // There is no global folder without the global `media_folder` option\n      asset.folder);\n\n/**\n * Get the public URL for the given asset.\n * @param {Asset} asset Asset file, such as an image.\n * @param {object} [options] Options.\n * @param {boolean} [options.pathOnly] Whether to use the absolute path starting with `/` instead of\n * the complete URL starting with `https`.\n * @param {boolean} [options.allowSpecial] Whether to allow returning a special, unlinkable path\n * starting with `@`, etc.\n * @param {Entry} [options.entry] Associated entry to be used to help locate an asset from a\n * relative path. Can be `undefined` when editing a new draft.\n * @param {InternalLocaleCode} [options.locale] Locale whose entry file an entry-relative path is\n * relative to. Default: the entry’s first locale.\n * @returns {string | undefined} URL or `undefined` if it cannot be determined.\n */\nexport const getAssetPublicURL = (\n  asset,\n  { pathOnly = false, allowSpecial = false, entry = undefined, locale = undefined } = {},\n) => {\n  const publicFolder = resolvePublicFolder(asset);\n  const { publicPath, entryRelative, hasTemplateTags } = publicFolder;\n\n  const { _baseURL: baseURL = '', output: { encode_file_path: encodingEnabled = false } = {} } =\n    /** @type {InternalCmsConfig} */ (cmsConfig.current);\n\n  // Try to determine an entry-relative path if the asset is in the same folder as the entry, or a\n  // sub-folder of it\n  if (entryRelative) {\n    if (!pathOnly) {\n      return undefined;\n    }\n\n    const path = getEntryRelativePublicPath({ asset, folder: publicFolder, entry, locale });\n\n    // Only an absolute path is encoded; a relative one is stored as is\n    return encodingEnabled && path?.startsWith('/') ? encodeFilePath(path) : path;\n  }\n\n  const internalPath = asset.folder.internalPath ?? '';\n  const publicBasePath = publicPath === '/' ? '' : (publicPath ?? '');\n\n  let path = hasTemplateTags\n    ? replaceTemplatePath({ path: asset.path, internalPath, publicPath: publicBasePath })\n    : internalPath\n      ? asset.path.replace(internalPath, publicBasePath)\n      : // An asset in a root media folder has no folder path to swap for the public path\n        `${publicBasePath}/${asset.path}`;\n\n  // An empty public folder stores a bare path relative to the media folder, e.g. `photo.jpg`, as\n  // Netlify/Decap CMS does, which can’t be linked\n  if (publicPath === '') {\n    path = path.replace(/^\\//, '');\n  }\n\n  if (encodingEnabled) {\n    path = encodeFilePath(path);\n  }\n\n  // Path starting with `@`, etc. cannot be linked\n  if (!path.startsWith('/') && !allowSpecial) {\n    return undefined;\n  }\n\n  if (pathOnly) {\n    return path;\n  }\n\n  return `${baseURL}${path}`;\n};\n\n/**\n * Get the public path of a directory in an asset folder, which is saved as the value of a File\n * field with the `select_folder` option.\n * @param {object} args Arguments.\n * @param {AssetFolderInfo} args.folder Asset folder with a fixed path, which can be browsed by\n * subfolder.\n * @param {string} args.subfolderPath Path of the directory below the folder, relative to it. Empty\n * for the folder root.\n * @returns {string} Public path, e.g. `/images/gallery`.\n */\nexport const getFolderPublicPath = ({ folder, subfolderPath }) => {\n  const { output: { encode_file_path: encodingEnabled = false } = {} } =\n    /** @type {InternalCmsConfig} */ (cmsConfig.current);\n\n  const basePath = (folder.publicPath ?? '').replace(/\\/$/, '');\n  const path = (subfolderPath ? `${basePath}/${subfolderPath}` : basePath) || '/';\n\n  return encodingEnabled ? encodeFilePath(path) : path;\n};\n\n/**\n * Load the given assets ahead of time, so they can be shown at once when the user moves to them,\n * e.g. the assets right before and after the one shown in the details overlay. An image is decoded\n * as well, and an asset already passed to the previous call isn’t loaded again. The assets passed\n * to the previous call that aren’t passed again are released: their\n * blob URLs are revoked unless an element displays them. Pass an empty array to release them all.\n * @param {Asset[]} assets Assets to preload.\n * @param {object} [options] Options.\n * @param {Asset[]} [options.keep] Assets that are being loaded elsewhere, e.g. the one shown in the\n * overlay, whose blob URLs are kept like those of the preloaded assets but which aren’t loaded\n * here. This keeps a preloaded asset the user has just moved to from being released before its\n * preview displays it.\n */\nexport const preloadAssets = (assets, { keep = [] } = {}) => {\n  const retained = [...assets, ...keep];\n  const released = preloadedAssets.filter((asset) => !retained.includes(asset));\n  const added = assets.filter((asset) => !loadedAssets.includes(asset));\n\n  preloadedAssets = retained;\n  loadedAssets = assets;\n\n  keep.forEach((asset) => {\n    if (asset.blobURL) {\n      preloadedURLs.add(asset.blobURL);\n    }\n  });\n\n  released.forEach((asset) => {\n    if (asset.blobURL) {\n      preloadedURLs.delete(asset.blobURL);\n    }\n\n    revokeAssetBlobURLIfNeeded(asset);\n  });\n\n  added.forEach(async (asset) => {\n    try {\n      const url = await getAssetBlobURL(asset);\n\n      if (!url) {\n        return;\n      }\n\n      // The asset may have been released while its blob was being read\n      if (!preloadedAssets.includes(asset)) {\n        revokeAssetBlobURLIfNeeded(asset);\n\n        return;\n      }\n\n      preloadedURLs.add(url);\n\n      if (asset.kind === 'image') {\n        const image = new Image();\n\n        image.src = url;\n        await image.decode();\n      }\n    } catch {\n      // The preview will try again and show the error, if any, once the asset is shown\n    }\n  });\n};\n","/**\n * Helpers for mapping between the paths the CMS uses and the keys an object storage service uses.\n * A service stores every file under a flat key, so a folder is only the common prefix of the keys\n * below it, and the configured `prefix` option is stripped from the paths the CMS sees.\n */\n\n/**\n * @import { S3Config } from '$lib/types/private';\n * @import { AzureMediaLibrary } from '$lib/types/public';\n */\n\n/**\n * Configuration of a cloud storage library. Only the `prefix` option is read here, but the union\n * is named in full rather than structurally: every property of a structural `{ prefix?: string }`\n * would be optional, so the fetch options — which carry no prefix — would satisfy it too, and\n * passing those in place of the configuration would key every object at the container or bucket\n * root instead of under the configured prefix.\n * @typedef {AzureMediaLibrary | S3Config} CloudStorageConfig\n */\n\n/**\n * Get the configured prefix as a directory, with a trailing slash. The option is documented as\n * ending with one, but a prefix without it would otherwise glue itself to the file names and make\n * every path start with a slash, so it’s put right rather than left to break the listing.\n * @param {CloudStorageConfig} config Cloud storage configuration.\n * @returns {string} Prefix, or an empty string for the container or bucket root.\n */\nexport const getPrefix = ({ prefix = '' }) =>\n  prefix && !prefix.endsWith('/') ? `${prefix}/` : prefix;\n\n/**\n * Get the key of the placeholder object that keeps an empty folder, which is the folder path with\n * a trailing slash, the way the AWS console and Azure Storage Explorer create a virtual directory.\n * @param {CloudStorageConfig} config Cloud storage configuration.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @returns {string} Object key.\n */\nexport const getFolderKey = (config, dirPath) => `${getPrefix(config)}${dirPath}/`;\n\n/**\n * Get the key of a file at the given path.\n * @param {CloudStorageConfig} config Cloud storage configuration.\n * @param {string} path File path relative to the configured prefix.\n * @returns {string} Object key.\n */\nexport const getFileKey = (config, path) => `${getPrefix(config)}${path}`;\n\n/**\n * Get the path of an object relative to the configured prefix.\n * @param {CloudStorageConfig} config Cloud storage configuration.\n * @param {string} key Object key.\n * @returns {string} Path.\n */\nexport const getRelativeKey = (config, key) => {\n  const prefix = getPrefix(config);\n\n  return prefix && key.startsWith(prefix) ? key.slice(prefix.length) : key;\n};\n","import { getPathInfo } from '@sveltia/utils/file';\n\nimport { slugify } from '$lib/services/common/slug';\nimport {\n  foldFileName,\n  renameIfNeeded,\n  renameReservedFileName,\n  sanitizeFileName,\n} from '$lib/services/utils/file';\n\n/**\n * Format the file name for uploading, ensuring it is sanitized and optionally slugified. A leading\n * dot is dropped like the characters a file system won’t take, as a dot file is hidden: the CMS\n * doesn’t list one, so the file would be lost from sight once uploaded. A name Windows reserves for\n * a device, like `aux.png`, is numbered as `aux-1.png`.\n * @param {string} originalName The original file name.\n * @param {object} [options] Options.\n * @param {boolean} [options.slugificationEnabled] Whether to slugify the file name.\n * @param {string[]} [options.assetNamesInSameFolder] List of asset names in the same folder to\n * avoid name conflicts.\n * @param {Set<string>} [options.foldedNamesInSameFolder] The same names folded with\n * `foldFileName()`, passed by a caller naming many files in the same folder.\n * @returns {string} The formatted file name, sanitized and possibly slugified.\n */\nexport const formatFileName = (\n  originalName,\n  { slugificationEnabled = false, assetNamesInSameFolder = [], foldedNamesInSameFolder } = {},\n) => {\n  let fileName = sanitizeFileName(originalName).replace(/^\\.+/, '');\n\n  if (slugificationEnabled) {\n    const { filename, extension } = getPathInfo(fileName);\n    const slug = slugify(filename);\n\n    // Lowercase the extension to match the slug’s lowercase behavior, ensuring consistent file\n    // references (e.g., `.JPG` → `.jpg`, `.MOV` → `.mov`)\n    fileName = `${slug}${extension ? `.${extension.toLowerCase()}` : ''}`;\n  }\n\n  // Dropping a leading dot or slugifying can leave a name Windows reserves for a device, like\n  // `aux.png` from `.aux.png` or `Aux!.png`, which `sanitizeFileName()` has renamed otherwise\n  return renameIfNeeded(renameReservedFileName(fileName), assetNamesInSameFolder, {\n    foldedNames: foldedNamesInSameFolder,\n  });\n};\n\n/**\n * Check whether two file names refer to the same file once formatted for uploading. The comparison\n * ignores case, as files whose names only differ in case clash on a case-insensitive file system.\n * @param {string} name1 File name.\n * @param {string} name2 Another file name.\n * @returns {boolean} Result.\n */\nexport const isSameFileName = (name1, name2) =>\n  foldFileName(formatFileName(name1)) === foldFileName(formatFileName(name2));\n\n/**\n * Check whether an asset can be renamed to the given name.\n * @param {object} args Arguments.\n * @param {string} args.name Name as typed, trimmed.\n * @param {string} args.fileName Name the file will be given, which is `name` formatted with\n * {@link formatFileName}.\n * @param {string[]} args.otherNames Names of the other files in the same folder.\n * @param {string[]} [args.folderNames] Names of the subfolders in the same folder. A Git tree can’t\n * hold a file and a folder under one name.\n * @param {string[]} [args.fileNames] Names of the files in the same folder that aren’t assets, like\n * entry files, which a rename would overwrite.\n * @returns {'empty' | 'character' | 'leading_dot' | 'duplicate' | 'file_duplicate' |\n * 'folder_duplicate' | undefined} What stops the name from being used, or `undefined` if it can\n * be used.\n */\nexport const validateAssetName = ({\n  name,\n  fileName,\n  otherNames,\n  folderNames = [],\n  fileNames = [],\n}) => {\n  if (!name) {\n    return 'empty';\n  }\n\n  // Sanitization can leave nothing to name the file with\n  if (name.includes('/') || !fileName) {\n    return 'character';\n  }\n\n  // A dot file is hidden, so the CMS wouldn’t list the asset any more\n  if (name.startsWith('.')) {\n    return 'leading_dot';\n  }\n\n  // Case-insensitive, since `Photo.jpg` and `photo.jpg` clash on a case-insensitive file system\n  // like macOS’s or Windows’s, and Unicode-normalized, as a name can be typed either way\n  const foldedName = foldFileName(fileName);\n  /**\n   * Check if the name is taken.\n   * @param {string[]} names Names to check against.\n   * @returns {boolean} Result.\n   */\n  const isTaken = (names) => names.some((n) => foldFileName(n) === foldedName);\n\n  if (isTaken(otherNames)) {\n    return 'duplicate';\n  }\n\n  if (isTaken(fileNames)) {\n    return 'file_duplicate';\n  }\n\n  if (isTaken(folderNames)) {\n    return 'folder_duplicate';\n  }\n\n  return undefined;\n};\n","/**\n * @import { ExternalAsset } from '$lib/types/private';\n */\n\n/**\n * Filter assets by a search query on the client side, for a storage service that doesn’t offer a\n * search API. An asset matches when its file name or description contains the query,\n * case-insensitively.\n * @param {ExternalAsset[]} assets Assets to filter.\n * @param {string} query Search query.\n * @returns {ExternalAsset[]} Matching assets.\n */\nexport const filterAssetsByQuery = (assets, query) => {\n  const lowerQuery = query.toLowerCase();\n\n  return assets.filter(\n    ({ fileName, description }) =>\n      fileName.toLowerCase().includes(lowerQuery) || description.toLowerCase().includes(lowerQuery),\n  );\n};\n","/* eslint-disable no-await-in-loop */\n\nimport { sleep } from '@sveltia/utils/misc';\n\nimport { formatFileName } from '$lib/services/assets/file-name';\nimport { getAssetKind } from '$lib/services/assets/kinds';\nimport { filterAssetsByQuery } from '$lib/services/integrations/media-libraries/cloud/search';\nimport {\n  getFileKey,\n  getFolderKey,\n  getPrefix,\n  getRelativeKey,\n} from '$lib/services/integrations/media-libraries/cloud/shared/keys';\nimport { getBaseName, getDirName } from '$lib/services/utils/file';\nimport { isSecureURL } from '$lib/services/utils/networking';\nimport { fetchPages } from '$lib/services/utils/paging';\n\n/**\n * @import {\n * ExternalAsset,\n * ExternalFolderListing,\n * MediaLibraryFetchOptions,\n * } from '$lib/types/private';\n * @import {\n * CloudStorageConfig,\n * } from '$lib/services/integrations/media-libraries/cloud/shared/keys';\n * @import {\n * ObjectStorageOperations,\n * } from '$lib/services/integrations/media-libraries/cloud/shared/service';\n */\n\n/**\n * Parameters of the request for a page of objects, made by an {@link ObjectStorageProvider}.\n * @template {CloudStorageConfig} C Service configuration type.\n * @typedef {object} ListPageParams\n * @property {C} config Service configuration.\n * @property {string} credential Credential, such as a SAS token or a secret access key.\n * @property {string} prefix Prefix to list the objects under.\n * @property {string} [cursor] Continuation cursor of the page.\n * @property {string} [delimiter] Delimiter, such as `/`, to leave out the objects whose key\n * contains it after the prefix: those in subfolders.\n */\n\n/**\n * Operations that differ between object storage services, such as Azure Blob Storage and the\n * S3-compatible services, which otherwise list, upload and delete files the same way. Each\n * operation handles the transport, including authorization, of a single request.\n * @template T Object type returned by the service’s list operation.\n * @template {CloudStorageConfig} C Service configuration type.\n * @typedef {object} ObjectStorageProvider\n * @property {(options: MediaLibraryFetchOptions) => string} requireCredential Function to get the\n * credential, such as a SAS token or a secret access key, from the fetch options. It throws when no\n * credential was provided.\n * @property {(params: ListPageParams<C>) => Promise<{ items: T[], cursor?: string }>} listPage\n * Function to fetch a page of objects under the given prefix, starting at the given continuation\n * cursor. The returned cursor is `undefined` on the last page.\n * @property {(item: T) => string} getKey Function to get the key of a listed object.\n * @property {(items: T[], config: C, credential: string) => ExternalAsset[]} parseResults Function\n * to convert objects into the `ExternalAsset` format.\n * @property {(params: { key: string, file: File, config: C, credential: string }) => Promise<T>}\n * putObject Function to upload a file under the given key, overwriting any existing object.\n * @property {(params: { asset: ExternalAsset, key: string, config: C, credential: string }) =>\n * Promise<T>} copyObject Function to copy the object of the given asset, whose `id` is the object\n * key, to the given key on the service, overwriting any existing object. It throws unless the copy\n * is complete, as the source is deleted next.\n * @property {(params: { key: string, config: C, credential: string, allowNotFound?: boolean }) =>\n * Promise<void>} deleteObject Function to delete the object with the given key. With\n * `allowNotFound`, an object that doesn’t exist counts as deleted.\n * @property {(params: { key: string, config: C, credential: string }) => Promise<void>}\n * putFolderObject Function to put a zero-byte placeholder object at the given folder key, which\n * ends with a slash.\n */\n\n/**\n * Get the credential from the fetch options for a request to the service. A custom `endpoint`, such\n * as one for an S3-compatible service or an Azurite emulator, must use HTTPS unless it’s on the\n * local computer, so that the credential, or a SAS token sent in the query string, isn’t exposed\n * over an insecure connection.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {string} Credential.\n * @throws {Error} When the endpoint is insecure, or no credential was provided.\n */\nconst getCredential = (provider, config, options) => {\n  if (config.endpoint && !isSecureURL(config.endpoint)) {\n    throw new Error('Refusing to send credentials over an insecure connection');\n  }\n\n  return provider.requireCredential(options);\n};\n\n/**\n * Get the key prefix to list a folder with.\n * @param {CloudStorageConfig} config Service configuration.\n * @param {string} [dirPath] Folder path relative to the configured prefix. Default: the configured\n * prefix itself.\n * @returns {string} Key prefix.\n */\nconst getListPrefix = (config, dirPath) =>\n  dirPath ? getFolderKey(config, dirPath) : getPrefix(config);\n\n/**\n * Fetch the objects under the configured prefix, or under a folder below it, page by page.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @param {object} [params] Additional parameters.\n * @param {number} [params.maxPages] Maximum number of pages to fetch. Default: 10. `Infinity` to\n * fetch every page.\n * @param {string} [params.dirPath] Path of the folder to list, at any depth, relative to the\n * configured prefix. Default: the configured prefix itself.\n * @param {string} [params.delimiter] Delimiter to list the folder with, such as `/` to leave out\n * the objects in its subfolders. Default: none, listing the folder at any depth.\n * @returns {Promise<{ files: T[], folders: string[], truncated: boolean }>} Objects, split into the\n * files and the folder placeholders, the latter given as folder paths relative to the prefix, and\n * whether the listing was cut short by the page limit, leaving some objects out.\n */\nexport const fetchListing = async (\n  provider,\n  config,\n  options,\n  { maxPages = 10, dirPath, delimiter } = {},\n) => {\n  const credential = getCredential(provider, config, options);\n  const prefix = getListPrefix(config, dirPath);\n  /** @type {T[]} */\n  const files = [];\n  /** @type {string[]} */\n  const folders = [];\n  let truncated = false;\n\n  const items = await fetchPages(\n    async (/** @type {string | undefined} */ cursor) => {\n      const result = await provider.listPage({\n        config,\n        credential,\n        prefix,\n        cursor,\n        ...(delimiter && { delimiter }),\n      });\n\n      // The paging stops at the last page, which has no cursor, or at the page limit, in which\n      // case the cursor of the last page fetched points to the objects left out\n      truncated = !!result.cursor;\n\n      return { results: result.items, next: result.cursor };\n    },\n    { maxPages },\n  );\n\n  items.forEach((item) => {\n    const key = provider.getKey(item);\n\n    // A key ending with a slash is a folder placeholder — one the CMS created for an empty folder,\n    // or one a hierarchical namespace account returns — rather than a file\n    if (key.endsWith('/')) {\n      const folderPath = getRelativeKey(config, key).replace(/\\/$/, '');\n\n      // The placeholder of the prefix itself isn’t a folder below it\n      if (folderPath) {\n        folders.push(folderPath);\n      }\n    } else {\n      files.push(item);\n    }\n  });\n\n  return { files, folders, truncated };\n};\n\n/**\n * Filter the given objects by the asset kind in the fetch options, if any.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {T[]} files Objects.\n * @param {MediaLibraryFetchOptions} options Fetch options.\n * @returns {T[]} Filtered objects.\n */\nconst filterByKind = (provider, files, { kind }) =>\n  kind ? files.filter((item) => getAssetKind(provider.getKey(item)) === kind) : files;\n\n/**\n * List the files under the configured prefix.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @param {object} [params] Additional parameters.\n * @param {number} [params.maxPages] Maximum number of pages to fetch. Default: 10.\n * @returns {Promise<ExternalAsset[]>} Assets.\n */\nexport const listObjects = async (provider, config, options, params = {}) => {\n  const { files } = await fetchListing(provider, config, options, params);\n\n  return provider.parseResults(filterByKind(provider, files, options), config, options.apiKey);\n};\n\n/**\n * List the files and the empty folders under the configured prefix.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<ExternalFolderListing>} Files and folders.\n */\nexport const browseObjects = async (provider, config, options) => {\n  const { files, folders, truncated } = await fetchListing(provider, config, options);\n\n  return {\n    assets: provider.parseResults(filterByKind(provider, files, options), config, options.apiKey),\n    folders,\n    truncated,\n  };\n};\n\n/**\n * List every file and empty folder below the given folder, at any depth, following the listing to\n * the end rather than stopping at the page limit, so that a folder operation like a rename or a\n * deletion leaves nothing behind, however large the bucket. The asset kind filter is ignored.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<ExternalFolderListing>} Files and folders, including the folder itself if it\n * has a placeholder.\n */\nexport const listFolderObjects = async (provider, dirPath, config, options) => {\n  const { files, folders } = await fetchListing(provider, config, options, {\n    maxPages: Infinity,\n    dirPath,\n  });\n\n  return { assets: provider.parseResults(files, config, options.apiKey), folders };\n};\n\n/**\n * Search the files under the configured prefix. Object storage doesn’t have a native search, so\n * the files are listed and filtered client-side.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {string} query Search query.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<ExternalAsset[]>} Assets.\n */\nexport const searchObjects = async (provider, query, config, options) => {\n  const allAssets = await listObjects(provider, config, options, { maxPages: 5 });\n\n  return filterAssetsByQuery(allAssets, query);\n};\n\n/**\n * Get the names of the files directly in the given folder, so that an upload can avoid them. The\n * folder is listed with a delimiter, as the services then sum up each subfolder in a single entry,\n * so even the root of a large bucket only takes a request per 1,000 files right in it. The listing\n * is followed to the end, as a name left out would let an upload overwrite that file.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @param {string} dirPath Folder path relative to the configured prefix, or an empty string for the\n * prefix itself.\n * @returns {Promise<string[]>} File names, normalized to NFC.\n */\nconst getFileNamesInFolder = async (provider, config, options, dirPath) => {\n  const folderKey = getListPrefix(config, dirPath);\n\n  const { files } = await fetchListing(provider, config, options, {\n    maxPages: Infinity,\n    dirPath,\n    delimiter: '/',\n  });\n\n  return (\n    files\n      .map((item) => provider.getKey(item).slice(folderKey.length).normalize())\n      // A service that ignores the delimiter lists the files in the subfolders as well\n      .filter((name) => !name.includes('/'))\n  );\n};\n\n/**\n * Upload files one by one to the folder given in the fetch options. A file whose name is taken in\n * the folder, by an existing file or by one uploaded before it, is renamed with a number suffix,\n * like `photo-1.jpg`, rather than overwriting it, the way an upload to the repository is.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {File[]} files Files to upload.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<ExternalAsset[]>} Uploaded assets.\n * @throws {Error} When a file name has nothing left once sanitized, such as `..`.\n */\nexport const uploadObjects = async (provider, files, config, options) => {\n  if (files.length === 0) {\n    return [];\n  }\n\n  const credential = getCredential(provider, config, options);\n  const { dirPath = '' } = options;\n  const takenNames = await getFileNamesInFolder(provider, config, options, dirPath);\n\n  // Name every file before uploading any, so that an invalid name stops the batch before it starts.\n  // Two files can end up with one name, e.g. `photo.jpg` and `photo.png` both converted to WebP, or\n  // `a/photo.jpg` and `b/photo.jpg` from a dropped folder, so each name is taken in turn\n  const keys = files.map((file) => {\n    // Extract only the filename to prevent path traversal via crafted File objects\n    const baseName = file.name.split(/[/\\\\]/).filter(Boolean).at(-1) ?? '';\n    const fileName = formatFileName(baseName, { assetNamesInSameFolder: takenNames });\n\n    // Sanitizing drops a name like `..`, which would otherwise point the key outside the folder\n    if (!fileName) {\n      throw new Error(`Invalid file name: ${file.name}`);\n    }\n\n    takenNames.push(fileName);\n\n    return getFileKey(config, dirPath ? `${dirPath}/${fileName}` : fileName);\n  });\n\n  /** @type {T[]} */\n  const uploadedObjects = [];\n\n  // eslint-disable-next-line no-restricted-syntax\n  for (const [index, file] of files.entries()) {\n    uploadedObjects.push(await provider.putObject({ key: keys[index], file, config, credential }));\n\n    // Wait a bit between uploads\n    if (files.length > 1) {\n      await sleep(50);\n    }\n  }\n\n  return provider.parseResults(uploadedObjects, config, credential);\n};\n\n/**\n * Delete objects one by one.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {ExternalAsset[]} assets Assets to delete. The `id` of each asset is the object key.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<void>}\n */\nexport const deleteObjects = async (provider, assets, config, options) => {\n  const credential = getCredential(provider, config, options);\n\n  // eslint-disable-next-line no-restricted-syntax\n  for (const { id: key } of assets) {\n    await provider.deleteObject({ key, config, credential });\n\n    // Wait a bit between requests\n    if (assets.length > 1) {\n      await sleep(50);\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Replace an object with a new file, keeping the object key so that the URL stays the same.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {ExternalAsset} asset Asset to replace. Its `id` is the object key.\n * @param {File} file New file.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<ExternalAsset>} Replaced asset.\n */\nexport const replaceObject = async (provider, asset, file, config, options) => {\n  const credential = getCredential(provider, config, options);\n  const object = await provider.putObject({ key: asset.id, file, config, credential });\n\n  return provider.parseResults([object], config, credential)[0];\n};\n\n/**\n * Move an object to another path. Object storage has no move operation, so the object is copied to\n * the new key and then the original is deleted.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {ExternalAsset} asset Asset to move. Its `id` is the object key.\n * @param {string} newPath New path relative to the configured prefix.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<ExternalAsset>} Moved asset.\n */\nexport const moveObject = async (provider, asset, newPath, config, options) => {\n  const credential = getCredential(provider, config, options);\n  const key = getFileKey(config, newPath);\n  const object = await provider.copyObject({ asset, key, config, credential });\n\n  await provider.deleteObject({ key: asset.id, config, credential });\n\n  return provider.parseResults([object], config, credential)[0];\n};\n\n/**\n * Create an empty folder by putting a zero-byte placeholder object at the folder key, the way the\n * services’ own consoles do.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<void>}\n */\nexport const createFolderObject = async (provider, dirPath, config, options) => {\n  const credential = getCredential(provider, config, options);\n\n  await provider.putFolderObject({ key: getFolderKey(config, dirPath), config, credential });\n};\n\n/**\n * Remove the placeholder object of a folder. A folder that has no placeholder, because it only\n * ever held files, is as good as removed.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<void>}\n */\nexport const deleteFolderObject = async (provider, dirPath, config, options) => {\n  const credential = getCredential(provider, config, options);\n\n  await provider.deleteObject({\n    key: getFolderKey(config, dirPath),\n    config,\n    credential,\n    allowNotFound: true,\n  });\n};\n\n/**\n * Get the path an object is moved to when it’s renamed, keeping it in its folder.\n * @param {CloudStorageConfig} config Service configuration.\n * @param {ExternalAsset} asset Asset to rename. Its `id` is the object key.\n * @param {string} newName New file name, without a directory.\n * @returns {string} New path relative to the configured prefix.\n */\nexport const getRenamedPath = (config, asset, newName) => {\n  const dirName = getDirName(getRelativeKey(config, asset.id));\n\n  return dirName ? `${dirName}/${newName}` : newName;\n};\n\n/**\n * Rename an object, keeping it in its folder. The folder is listed to the end first, as the listing\n * the user picked the name against can be cut short in a large bucket, and copying the object onto\n * a file with the new name would overwrite that file.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {ExternalAsset} asset Asset to rename. Its `id` is the object key.\n * @param {string} newName New file name, without a directory.\n * @param {C} config Service configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the credential).\n * @returns {Promise<ExternalAsset>} Renamed asset.\n * @throws {Error} When another file in the folder has the new name.\n */\nexport const renameObject = async (provider, asset, newName, config, options) => {\n  const newPath = getRenamedPath(config, asset, newName);\n  const dirPath = getDirName(newPath);\n  const ownName = getBaseName(getRelativeKey(config, asset.id)).normalize();\n  const takenNames = await getFileNamesInFolder(provider, config, options, dirPath);\n  const normalizedName = newName.normalize();\n\n  if (takenNames.some((name) => name !== ownName && name === normalizedName)) {\n    throw new Error(`A file named “${newName}” already exists in the folder.`);\n  }\n\n  return moveObject(provider, asset, newPath, config, options);\n};\n\n/**\n * Create the operations of an object storage service, binding the given provider to the shared\n * operations, which all take it as their first argument. A file is renamed by moving it within its\n * folder.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @returns {ObjectStorageOperations<C>} Operations.\n */\nexport const createObjectStorageOperations = (provider) =>\n  /** @type {ObjectStorageOperations<C>} */ (\n    Object.fromEntries(\n      Object.entries(\n        /** @type {Record<string, (...args: any[]) => Promise<any>>} */ ({\n          list: listObjects,\n          browse: browseObjects,\n          listFolder: listFolderObjects,\n          search: searchObjects,\n          upload: uploadObjects,\n          delete: deleteObjects,\n          rename: renameObject,\n          replace: replaceObject,\n          move: moveObject,\n          createFolder: createFolderObject,\n          deleteFolder: deleteFolderObject,\n        }),\n      ).map(([name, operation]) => [name, operation.bind(null, provider)]),\n    )\n  );\n","import { cmsConfig } from '$lib/services/config/state';\nimport {\n  findLibraryOptions,\n  resolveLibraryOptions,\n} from '$lib/services/integrations/media-libraries/options';\n\n/**\n * @import {\n * ExternalAsset,\n * ExternalFolderListing,\n * MediaLibraryFetchOptions,\n * MediaLibraryService,\n * } from '$lib/types/private';\n * @import { CmsConfig, MediaField, MediaLibraries } from '$lib/types/public';\n */\n\n/**\n * Operations of an object storage service, which take the resolved service configuration.\n * @template C Service configuration type.\n * @typedef {object} ObjectStorageOperations\n * @property {(config: C, options: MediaLibraryFetchOptions) => Promise<ExternalAsset[]>} list\n * Function to list files.\n * @property {(config: C, options: MediaLibraryFetchOptions) => Promise<ExternalFolderListing>}\n * browse Function to list the files and the empty folders.\n * @property {(dirPath: string, config: C, options: MediaLibraryFetchOptions) =>\n * Promise<ExternalFolderListing>} listFolder Function to list every file and empty folder below a\n * folder, at any depth.\n * @property {(query: string, config: C, options: MediaLibraryFetchOptions) =>\n * Promise<ExternalAsset[]>} search Function to search files.\n * @property {(files: File[], config: C, options: MediaLibraryFetchOptions) =>\n * Promise<ExternalAsset[]>} upload Function to upload files.\n * @property {(assets: ExternalAsset[], config: C, options: MediaLibraryFetchOptions) =>\n * Promise<void>} delete Function to delete files.\n * @property {(asset: ExternalAsset, newName: string, config: C, options: MediaLibraryFetchOptions)\n * => Promise<ExternalAsset>} rename Function to rename a file.\n * @property {(asset: ExternalAsset, file: File, config: C, options: MediaLibraryFetchOptions) =>\n * Promise<ExternalAsset>} replace Function to replace a file.\n * @property {(asset: ExternalAsset, newPath: string, config: C, options: MediaLibraryFetchOptions)\n * => Promise<ExternalAsset>} move Function to move a file.\n * @property {(dirPath: string, config: C, options: MediaLibraryFetchOptions) => Promise<void>}\n * createFolder Function to create an empty folder.\n * @property {(dirPath: string, config: C, options: MediaLibraryFetchOptions) => Promise<void>}\n * deleteFolder Function to remove the placeholder of a folder.\n */\n\n/**\n * Options to define an object storage media library service.\n * @template C Service configuration type.\n * @typedef {object} ObjectStorageServiceOptions\n * @property {keyof MediaLibraries} serviceId Service identifier matching the `media_libraries`\n * key.\n * @property {string} serviceLabel Default service label, overridden by the `label` library option.\n * @property {string} serviceURL Service URL.\n * @property {string} developerURL URL of the page that provides the API/developer service.\n * @property {string} apiKeyURL URL of the page that provides the API key.\n * @property {RegExp} apiKeyPattern API key pattern.\n * @property {(libOptions: any) => C} [resolveConfig] Function to derive the service configuration\n * from the library options. Default: the library options are used as is.\n * @property {(config: C) => boolean} isConfigured Function to check whether the resolved\n * configuration has every option the service needs to be enabled.\n * @property {(config: C, url: string) => boolean} isConfigURL Function to check whether the given\n * URL points to a file on the service with the resolved configuration.\n * @property {ObjectStorageOperations<C>} operations Operations of the service.\n */\n\n/**\n * Create a `MediaLibraryService` member that calls the given operation of an object storage\n * service with the resolved configuration, inserted before the fetch options, which come last.\n * @param {ObjectStorageService<any>} service Service.\n * @param {keyof ObjectStorageOperations<any>} name Operation name.\n * @returns {(...args: any[]) => Promise<any>} Member function.\n */\nconst withConfig =\n  (service, name) =>\n  async (...args) => {\n    const options = args.pop();\n\n    return /** @type {(...args: any[]) => Promise<any>} */ (service.operations[name])(\n      ...args,\n      service.getConfig(options),\n      options,\n    );\n  };\n\n/**\n * Media library service for an object storage service, such as Azure Blob Storage or an\n * S3-compatible service. It resolves the service’s configuration from the CMS or field\n * configuration and delegates the operations to the given functions.\n * @template C Service configuration type.\n * @implements {MediaLibraryService}\n */\nexport class ObjectStorageService {\n  /** @type {'cloud_storage'} */\n  serviceType = 'cloud_storage';\n\n  showServiceLink = true;\n\n  hotlinking = true;\n\n  /** @type {'api_key'} */\n  authType = 'api_key';\n\n  /**\n   * Initialize an `ObjectStorageService` instance with the given service definition.\n   * @param {ObjectStorageServiceOptions<C>} options Service definition.\n   */\n  constructor({\n    serviceId,\n    serviceLabel,\n    serviceURL,\n    developerURL,\n    apiKeyURL,\n    apiKeyPattern,\n    resolveConfig = (libOptions) => libOptions,\n    isConfigured,\n    isConfigURL,\n    operations,\n  }) {\n    this.serviceId = serviceId;\n    this.defaultServiceLabel = serviceLabel;\n    this.serviceURL = serviceURL;\n    this.developerURL = developerURL;\n    this.apiKeyURL = apiKeyURL;\n    this.apiKeyPattern = apiKeyPattern;\n    this.resolveConfig = resolveConfig;\n    this.isConfigured = isConfigured;\n    this.isConfigURL = isConfigURL;\n    this.operations = operations;\n  }\n\n  /**\n   * Get the name to show for the service: the site-level `label` option, if any, which lets a\n   * self-hosted server reached through `endpoint` go by its own name, or the default label. It has\n   * to be read on demand, because the service is instantiated before the config is loaded.\n   * @returns {string} Service label.\n   */\n  get serviceLabel() {\n    return this.getLibraryOptions()?.label || this.defaultServiceLabel;\n  }\n\n  /**\n   * Get the service’s library options from site config.\n   * @param {CmsConfig | MediaField} [config] CMS configuration or field configuration.\n   * @returns {any} Configuration object, `false` if explicitly disabled, or `undefined` if not\n   * configured.\n   */\n  getLibraryOptions(config = cmsConfig.current) {\n    return findLibraryOptions(this.serviceId, config);\n  }\n\n  /**\n   * Get the resolved configuration for the given field or global library options.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {C} Resolved configuration.\n   * @throws {Error} If the service is not configured.\n   */\n  getConfig({ fieldConfig }) {\n    const libOptions = resolveLibraryOptions(this.serviceId, fieldConfig);\n\n    if (!libOptions) {\n      throw new Error(`${this.serviceLabel} configuration is not available`);\n    }\n\n    return this.resolveConfig(libOptions);\n  }\n\n  // The `MediaLibraryService` members below are functions bound to the instance rather than\n  // prototype methods, because consumers destructure them from the service object, which would\n  // lose `this` otherwise.\n\n  /**\n   * Check if the service is enabled.\n   * @param {MediaField} [fieldConfig] Field configuration.\n   * @returns {boolean} True if enabled, false otherwise.\n   */\n  isEnabled = (fieldConfig) => {\n    const options = resolveLibraryOptions(this.serviceId, fieldConfig);\n\n    return !!options && this.isConfigured(this.resolveConfig(options));\n  };\n\n  /**\n   * Whether the given URL points to a file on the service.\n   * @param {string} url URL.\n   * @returns {boolean} Result.\n   */\n  isAssetURL = (url) => {\n    try {\n      return this.isConfigURL(this.getConfig(/** @type {any} */ ({})), url);\n    } catch {\n      // The service is not configured\n      return false;\n    }\n  };\n\n  /**\n   * List files on the service.\n   * @type {NonNullable<MediaLibraryService['list']>}\n   */\n  list = withConfig(this, 'list');\n\n  /**\n   * List the files and the empty folders on the service.\n   * @type {NonNullable<MediaLibraryService['browse']>}\n   */\n  browse = withConfig(this, 'browse');\n\n  /**\n   * List every file and empty folder below a folder on the service, at any depth.\n   * @type {NonNullable<MediaLibraryService['listFolder']>}\n   */\n  listFolder = withConfig(this, 'listFolder');\n\n  /**\n   * Search files on the service.\n   * @type {NonNullable<MediaLibraryService['search']>}\n   */\n  search = withConfig(this, 'search');\n\n  /**\n   * Upload files to the service.\n   * @type {NonNullable<MediaLibraryService['upload']>}\n   */\n  upload = withConfig(this, 'upload');\n\n  /**\n   * Delete files from the service.\n   * @type {NonNullable<MediaLibraryService['delete']>}\n   */\n  delete = withConfig(this, 'delete');\n\n  /**\n   * Rename a file on the service.\n   * @type {NonNullable<MediaLibraryService['rename']>}\n   */\n  rename = withConfig(this, 'rename');\n\n  /**\n   * Replace a file on the service with a new file.\n   * @type {NonNullable<MediaLibraryService['replace']>}\n   */\n  replace = withConfig(this, 'replace');\n\n  /**\n   * Move a file on the service to another path.\n   * @type {NonNullable<MediaLibraryService['move']>}\n   */\n  move = withConfig(this, 'move');\n\n  /**\n   * Create an empty folder on the service.\n   * @type {NonNullable<MediaLibraryService['createFolder']>}\n   */\n  createFolder = withConfig(this, 'createFolder');\n\n  /**\n   * Remove the placeholder of a folder on the service.\n   * @type {NonNullable<MediaLibraryService['deleteFolder']>}\n   */\n  deleteFolder = withConfig(this, 'deleteFolder');\n}\n","/**\n * Parse XML response to JSON.\n * @param {string} xml XML string.\n * @returns {any} Parsed object.\n */\nexport const parseXml = (xml) => {\n  const parser = new DOMParser();\n  const doc = parser.parseFromString(xml, 'text/xml');\n\n  /**\n   * Convert XML node to object.\n   * @param {Element} node XML node.\n   * @returns {any} Object.\n   */\n  const nodeToObject = (node) => {\n    if (node.children.length === 0) {\n      return node.textContent;\n    }\n\n    /** @type {Record<string, any>} */\n    const obj = {};\n\n    Array.from(node.children).forEach((child) => {\n      const key = child.tagName;\n      const value = nodeToObject(child);\n\n      if (Object.hasOwn(obj, key)) {\n        if (Array.isArray(obj[key])) {\n          obj[key].push(value);\n        } else {\n          obj[key] = [obj[key], value];\n        }\n      } else {\n        obj[key] = value;\n      }\n    });\n\n    return obj;\n  };\n\n  return nodeToObject(doc.documentElement);\n};\n\n/**\n * Normalize a value parsed with {@link parseXml} to an array. An element that appears once is\n * parsed as a single value, and one that is missing or empty as `undefined` or an empty string.\n * @param {any} value Parsed value.\n * @returns {any[]} Array.\n */\nexport const toArray = (value) => (value ? (Array.isArray(value) ? value : [value]) : []);\n","import { getAssetKind } from '$lib/services/assets/kinds';\nimport { getRelativeKey } from '$lib/services/integrations/media-libraries/cloud/shared/keys';\nimport { createObjectStorageOperations } from '$lib/services/integrations/media-libraries/cloud/shared/object-storage';\nimport { ObjectStorageService } from '$lib/services/integrations/media-libraries/cloud/shared/service';\nimport { getBaseName } from '$lib/services/utils/file';\nimport { assertResponseOK } from '$lib/services/utils/networking';\nimport { encodePathSegments, trimTrailingSlashes } from '$lib/services/utils/url';\nimport { parseXml, toArray } from '$lib/services/utils/xml';\n\n/**\n * @import {\n * ExternalAsset,\n * MediaLibraryFetchOptions,\n * } from '$lib/types/private';\n * @import { AzureMediaLibrary, CmsConfig, MediaField } from '$lib/types/public';\n * @import {\n * ObjectStorageProvider,\n * } from '$lib/services/integrations/media-libraries/cloud/shared/object-storage';\n */\n\n/**\n * A blob entry in the `List Blobs` response.\n * @typedef {object} AzureBlob\n * @property {string} Name Blob name, including any virtual directory within the container.\n * @property {Record<string, string>} [Properties] Blob properties, such as `Last-Modified`,\n * `Content-Length` and `Content-Type`.\n */\n\n/**\n * Blob service endpoint suffix for the Azure public cloud.\n */\nconst DEFAULT_ENDPOINT_SUFFIX = 'blob.core.windows.net';\n/**\n * Number of blobs to request per `List Blobs` call. The service caps the value at 5000.\n */\nconst MAX_RESULTS = 1000;\n\n/**\n * Build the base URL of the container on the Blob service.\n * @param {AzureMediaLibrary} config Azure Blob Storage configuration.\n * @returns {string} Container URL without a trailing slash.\n */\nexport const buildContainerUrl = ({ account_name: accountName, container, endpoint }) => {\n  const base = endpoint\n    ? trimTrailingSlashes(endpoint)\n    : `https://${accountName}.${DEFAULT_ENDPOINT_SUFFIX}`;\n\n  return `${base}/${container}`;\n};\n\n/**\n * Build a request URL with the SAS token appended. The token is used as given, rather than parsed\n * and re-serialized, because the percent-encoding of its `sig` parameter must be preserved exactly\n * for the signature to remain valid.\n * @param {object} params Parameters.\n * @param {string} params.url Base URL without a query string.\n * @param {string} params.token SAS token, with or without the leading `?`.\n * @param {URLSearchParams} [params.searchParams] Additional query parameters.\n * @returns {string} Authorized URL.\n */\nexport const buildRequestUrl = ({ url, token, searchParams }) => {\n  const query = [searchParams?.toString(), token.trim().replace(/^[?&]/, '')]\n    .filter(Boolean)\n    .join('&');\n\n  return `${url}?${query}`;\n};\n\n/**\n * Build the Blob service URL of a blob, with the SAS token appended.\n * @param {AzureMediaLibrary} config Azure Blob Storage configuration.\n * @param {string} key Blob name.\n * @param {string} token SAS token.\n * @returns {string} Authorized blob URL.\n */\nconst buildBlobRequestUrl = (config, key, token) =>\n  buildRequestUrl({ url: `${buildContainerUrl(config)}/${encodePathSegments(key)}`, token });\n\n/**\n * Get the SAS token from the given fetch options.\n * @param {MediaLibraryFetchOptions} options Fetch options.\n * @returns {string} SAS token.\n * @throws {Error} When no token was provided.\n */\nconst requireToken = ({ apiKey: token }) => {\n  if (!token) {\n    throw new Error('Azure Blob Storage SAS token is required');\n  }\n\n  return token;\n};\n\n/**\n * Parse blobs returned by the Blob service into the `ExternalAsset` format.\n * @param {AzureBlob[]} blobs Blobs.\n * @param {AzureMediaLibrary} config Azure Blob Storage configuration.\n * @param {string} token SAS token.\n * @returns {ExternalAsset[]} Assets.\n */\nexport const parseBlobResults = (blobs, config, token) => {\n  const { public_url: publicUrl } = config;\n  const containerUrl = buildContainerUrl(config);\n\n  return blobs.map(({ Name: key, Properties: properties = {} }) => {\n    const fileName = getBaseName(key) || key;\n    const displayKey = getRelativeKey(config, key);\n    const encodedKey = encodePathSegments(key);\n    const blobUrl = `${containerUrl}/${encodedKey}`;\n    // Assets are hotlinked, so the URL stored in entries must not contain the SAS token, which\n    // expires. A private container therefore requires the `public_url` option; the token is only\n    // added to the preview URL, which is used within the CMS\n    const downloadURL = publicUrl ? `${trimTrailingSlashes(publicUrl)}/${encodedKey}` : blobUrl;\n    const lastModified = properties['Last-Modified'];\n    const size = properties['Content-Length'];\n\n    return {\n      id: key,\n      description: displayKey,\n      previewURL: publicUrl ? downloadURL : buildRequestUrl({ url: blobUrl, token }),\n      downloadURL,\n      fileName,\n      ...(lastModified && { lastModified: new Date(lastModified) }),\n      ...(size && { size: Number(size) }),\n      kind: getAssetKind(key),\n    };\n  });\n};\n\n/**\n * Fetch a page of the blobs under the given prefix from the container. A name ending with a slash\n * is a directory placeholder — one the CMS created for an empty folder, or one a hierarchical\n * namespace account returns — rather than a file.\n * @param {object} params Parameters.\n * @param {AzureMediaLibrary} params.config Azure Blob Storage configuration.\n * @param {string} params.credential SAS token.\n * @param {string} params.prefix Blob name prefix.\n * @param {string} [params.cursor] Continuation marker of the page.\n * @param {string} [params.delimiter] Delimiter to group the names with, leaving out the blobs in\n * virtual directories, which are returned as blob prefixes instead.\n * @returns {Promise<{ items: AzureBlob[], cursor?: string }>} Blobs and the continuation marker of\n * the next page, if any.\n * @see https://learn.microsoft.com/en-us/rest/api/storageservices/list-blobs\n */\nconst listBlobPage = async ({ config, credential: token, prefix, cursor: marker, delimiter }) => {\n  const searchParams = new URLSearchParams({\n    restype: 'container',\n    comp: 'list',\n    maxresults: String(MAX_RESULTS),\n    ...(prefix && { prefix }),\n    ...(delimiter && { delimiter }),\n    ...(marker && { marker }),\n  });\n\n  const url = buildContainerUrl(config);\n  const response = await fetch(buildRequestUrl({ url, token, searchParams }));\n\n  await assertResponseOK(response, 'Failed to list blobs');\n\n  /** @type {any} */\n  const data = parseXml(await response.text());\n\n  return { items: toArray(data.Blobs?.Blob), cursor: data.NextMarker || undefined };\n};\n\n/**\n * Upload a single file to the configured container as a block blob under the given name,\n * overwriting any existing blob with the same name.\n * @param {object} params Parameters.\n * @param {string} params.key Blob name.\n * @param {File} params.file File to upload.\n * @param {AzureMediaLibrary} params.config Azure Blob Storage configuration.\n * @param {string} params.credential SAS token.\n * @returns {Promise<AzureBlob>} Uploaded blob.\n * @see https://learn.microsoft.com/en-us/rest/api/storageservices/put-blob\n */\nconst putBlob = async ({ key, file, config, credential: token }) => {\n  const response = await fetch(buildBlobRequestUrl(config, key, token), {\n    method: 'PUT',\n    headers: {\n      // The `x-ms-version` header is omitted on purpose: with a SAS, the token’s `sv` parameter\n      // determines the service version, and each extra header must be allowed by a CORS rule\n      'x-ms-blob-type': 'BlockBlob',\n      'Content-Type': file.type || 'application/octet-stream',\n    },\n    body: file,\n  });\n\n  await assertResponseOK(response, `Failed to upload file ${file.name}`);\n\n  return {\n    Name: key,\n    Properties: {\n      'Last-Modified': new Date().toUTCString(),\n      'Content-Length': String(file.size),\n      'Content-Type': file.type,\n    },\n  };\n};\n\n/**\n * Delete a single blob from the configured container. The account’s CORS rules must allow the\n * `DELETE` method, in addition to the `GET` and `PUT` methods needed for listing and uploading;\n * otherwise the browser blocks the request at the preflight stage.\n * @param {object} params Parameters.\n * @param {string} params.key Blob name.\n * @param {AzureMediaLibrary} params.config Azure Blob Storage configuration.\n * @param {string} params.credential SAS token.\n * @param {boolean} [params.allowNotFound] Whether a blob that doesn’t exist counts as deleted.\n * @returns {Promise<void>}\n * @see https://learn.microsoft.com/en-us/rest/api/storageservices/delete-blob\n */\nconst deleteBlob = async ({ key, config, credential: token, allowNotFound = false }) => {\n  const response = await fetch(buildBlobRequestUrl(config, key, token), { method: 'DELETE' });\n\n  await assertResponseOK(response, `Failed to delete blob ${key}`, { allowNotFound });\n};\n\n/**\n * Copy a blob in the configured container to another name with the synchronous `Put Blob From\n * URL` operation. The account’s CORS rules must allow the `x-ms-copy-source` header, in addition\n * to `x-ms-blob-type`; otherwise the browser blocks the request at the preflight stage.\n * @param {object} params Parameters.\n * @param {ExternalAsset} params.asset Asset to copy. Its `id` is the blob name.\n * @param {string} params.key New blob name.\n * @param {AzureMediaLibrary} params.config Azure Blob Storage configuration.\n * @param {string} params.credential SAS token.\n * @returns {Promise<AzureBlob>} Copied blob.\n * @see https://learn.microsoft.com/en-us/rest/api/storageservices/put-blob-from-url\n */\nconst copyBlob = async ({ asset, key: newKey, config, credential: token }) => {\n  const { id: key, size } = asset;\n\n  const response = await fetch(buildBlobRequestUrl(config, newKey, token), {\n    method: 'PUT',\n    headers: {\n      'x-ms-blob-type': 'BlockBlob',\n      // The source must be readable by the service, so the SAS token is appended\n      'x-ms-copy-source': buildBlobRequestUrl(config, key, token),\n    },\n  });\n\n  await assertResponseOK(response, `Failed to copy blob ${key}`);\n\n  // With a SAS token issued for a service version older than 2020-04-08, the request is handled as\n  // an asynchronous `Copy Blob` operation instead. Never remove the source while the copy is still\n  // pending, otherwise the copy fails and the file is lost\n  if (response.headers.get('x-ms-copy-status') === 'pending') {\n    throw new Error(`Failed to copy blob ${key}: the copy operation is still pending`);\n  }\n\n  // The copy is a new blob, modified just now rather than when the source was\n  return {\n    Name: newKey,\n    Properties: {\n      'Last-Modified': new Date().toUTCString(),\n      ...(size && { 'Content-Length': String(size) }),\n    },\n  };\n};\n\n/**\n * Put a zero-byte placeholder blob at the given folder name, the way Azure Storage Explorer creates\n * a virtual directory.\n * @param {object} params Parameters.\n * @param {string} params.key Folder blob name, ending with a slash.\n * @param {AzureMediaLibrary} params.config Azure Blob Storage configuration.\n * @param {string} params.credential SAS token.\n * @returns {Promise<void>}\n */\nconst putFolderBlob = async ({ key, config, credential: token }) => {\n  const response = await fetch(buildBlobRequestUrl(config, key, token), {\n    method: 'PUT',\n    headers: { 'x-ms-blob-type': 'BlockBlob', 'Content-Type': 'application/x-directory' },\n  });\n\n  await assertResponseOK(response, `Failed to create folder ${key}`);\n};\n\n/**\n * Blob service calls for the operations shared with the other object storage services.\n * @type {ObjectStorageProvider<AzureBlob, AzureMediaLibrary>}\n */\nconst provider = {\n  requireCredential: requireToken,\n  listPage: listBlobPage,\n  /**\n   * Get the name of a blob.\n   * @param {AzureBlob} blob Blob.\n   * @returns {string} Blob name.\n   */\n  getKey: ({ Name }) => Name,\n  parseResults: parseBlobResults,\n  putObject: putBlob,\n  copyObject: copyBlob,\n  deleteObject: deleteBlob,\n  putFolderObject: putFolderBlob,\n};\n\n/**\n * Whether the given URL points to a blob in the configured container, through either the public\n * URL or the Blob service.\n * @param {AzureMediaLibrary} config Azure Blob Storage configuration.\n * @param {string} url URL.\n * @returns {boolean} Result.\n */\nconst isBlobUrl = (config, url) => {\n  const { public_url: publicUrl } = config;\n\n  return [\n    `${buildContainerUrl(config)}/`,\n    ...(publicUrl ? [`${trimTrailingSlashes(publicUrl)}/`] : []),\n  ].some((base) => url.startsWith(base));\n};\n\n/**\n * Azure Blob Storage media library service integration.\n * @type {ObjectStorageService<AzureMediaLibrary>}\n */\nconst azureBlobStorage = new ObjectStorageService({\n  serviceId: 'azure_blob_storage',\n  serviceLabel: 'Azure Blob Storage',\n  serviceURL: 'https://azure.microsoft.com/products/storage/blobs/',\n  developerURL: 'https://learn.microsoft.com/en-us/rest/api/storageservices/blob-service-rest-api',\n  apiKeyURL: 'https://portal.azure.com/#browse/Microsoft.Storage%2FStorageAccounts',\n  apiKeyPattern: /^\\??(?:[\\w-]+=[^&]*&)*sig=[^&]+(?:&[\\w-]+=[^&]*)*$/,\n  /**\n   * Check if the container and either the account name or a custom endpoint are set.\n   * @param {AzureMediaLibrary} config Azure Blob Storage configuration.\n   * @returns {boolean} Result.\n   */\n  isConfigured: ({ container, account_name: accountName, endpoint }) =>\n    !!(container && (accountName || endpoint)),\n  isConfigURL: isBlobUrl,\n  operations: createObjectStorageOperations(provider),\n});\n\n/**\n * Get Azure Blob Storage library options from site config.\n * @param {CmsConfig | MediaField} [config] CMS configuration or field configuration.\n * @returns {AzureMediaLibrary | false | undefined} Configuration object, or `false` if explicitly\n * disabled.\n */\nexport const getLibraryOptions = (config) => azureBlobStorage.getLibraryOptions(config);\n\nexport const {\n  isEnabled,\n  isAssetURL,\n  list,\n  browse,\n  search,\n  upload,\n  delete: deleteFiles,\n  rename,\n  replace,\n  move,\n  createFolder: createEmptyFolder,\n  deleteFolder: removeFolder,\n} = azureBlobStorage;\n\nexport default azureBlobStorage;\n","import { isObject } from '@sveltia/utils/object';\n\nimport { cmsConfig } from '$lib/services/config/state';\nimport {\n  findLibraryOptions,\n  resolveLibraryOptions,\n} from '$lib/services/integrations/media-libraries/options';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { MediaLibraryService } from '$lib/types/private';\n * @import { CloudinaryMediaLibrary, CmsConfig, MediaField } from '$lib/types/public';\n */\n\n/**\n * Whether the Cloudinary Media Library integration is activated.\n */\nexport const activated = createRawState(false);\n\n/**\n * Whether the Cloudinary Media Library console is loaded.\n */\nexport const consoleLoaded = createRawState(false);\n\n/**\n * Whether the Cloudinary Media Library dialog is open.\n */\nexport const dialogOpen = createRawState(false);\n\n/**\n * Cloudinary Media Library console URL. Used for the popup and iframe src.\n */\nexport const CONSOLE_BASE_URL = 'https://console.cloudinary.com/console/media_library';\n\n/**\n * Cloudinary Media Library iframe origin.\n */\nexport const FRAME_ORIGIN = new URL(CONSOLE_BASE_URL).origin;\n\n/**\n * Cloudinary Media Library iframe’s `src` search parameters.\n */\nexport const FRAME_SRC_PARAMS = [\n  'cloud_name',\n  'api_key',\n  'username',\n  'timestamp',\n  'signature',\n  'integration',\n  'use_saml',\n  'saml_iframe_support',\n];\n\n/**\n * Cloudinary Media Library configuration properties.\n */\nexport const CONFIG_PROPS = [\n  'integration',\n  'inline_container',\n  'z_index',\n  'multiple',\n  'max_files',\n  'default_transformations',\n  'insert_caption',\n  'remove_header',\n  'folder',\n  'search',\n  'collection',\n  'asset',\n  'transformation',\n  'sandboxNotAllowedAttributes',\n  'theme',\n];\n\n/**\n * Get Cloudinary library options from site config.\n * @param {CmsConfig | MediaField} [config] CMS configuration or field configuration.\n * @returns {CloudinaryMediaLibrary | false | undefined} Configuration object, or `false` if\n * explicitly disabled.\n */\nexport const getLibraryOptions = (config = cmsConfig.current) =>\n  findLibraryOptions('cloudinary', config);\n\n/**\n * @type {Map<string, CloudinaryMediaLibrary>}\n */\nexport const optionCacheMap = new Map();\n\n/**\n * Get merged Cloudinary library options from site and field config.\n * Field config options override site config options.\n * @param {MediaField} [fieldConfig] Field configuration.\n * @returns {CloudinaryMediaLibrary} Merged configuration object.\n */\nexport const getMergedLibraryOptions = (fieldConfig) => {\n  const cacheKey = fieldConfig ? JSON.stringify(fieldConfig) : 'global';\n  const cache = optionCacheMap.get(cacheKey);\n\n  if (cache) {\n    return cache;\n  }\n\n  const resolved = /** @type {CloudinaryMediaLibrary} */ (\n    resolveLibraryOptions('cloudinary', fieldConfig) || {}\n  );\n\n  const options = { ...resolved, config: { ...resolved.config } };\n\n  optionCacheMap.set(cacheKey, options);\n\n  return options;\n};\n\n/**\n * Get Cloudinary configuration from the site config, with the given field config merged.\n * @param {MediaField} [fieldConfig] Field configuration.\n * @returns {{ cloudName?: string; apiKey?: string }} Cloudinary configuration.\n */\nexport const getCloudConfig = (fieldConfig) => {\n  const options = resolveLibraryOptions('cloudinary', fieldConfig);\n  const { cloud_name: cloudName, api_key: apiKey } = (options ? options.config : undefined) ?? {};\n\n  return { cloudName, apiKey };\n};\n\n/**\n * Check if Cloudinary integration is enabled.\n * @param {MediaField} [fieldConfig] Field configuration.\n * @returns {boolean} True if enabled, false otherwise.\n */\nexport const isEnabled = (fieldConfig) => {\n  const { cloudName, apiKey } = getCloudConfig(fieldConfig);\n\n  return !!(cloudName && apiKey);\n};\n\n/**\n * Whether the given URL points to a file in the configured Cloudinary product environment.\n * @param {string} url URL.\n * @returns {boolean} Result.\n */\nexport const isAssetURL = (url) => {\n  const { cloudName } = getCloudConfig();\n\n  return !!cloudName && url.startsWith(`https://res.cloudinary.com/${cloudName}/`);\n};\n\n/**\n * Parse a message from the Cloudinary Media Library console, which sends a JSON string.\n * @param {MessageEvent} event The message event.\n * @returns {Record<string, any> | undefined} Message data, or `undefined` if the message comes\n * from elsewhere or is in an unknown format.\n */\nexport const parseMessage = ({ origin, data }) => {\n  if (origin !== FRAME_ORIGIN) {\n    return undefined;\n  }\n\n  if (typeof data === 'string') {\n    try {\n      data = JSON.parse(data);\n    } catch {\n      return undefined;\n    }\n  }\n\n  return isObject(data) ? data : undefined;\n};\n\n/**\n * Cloudinary media library service integration. Cloudinary has a CORS restriction that prevents\n * direct API access from the browser, so the service has no `list`, `search` or `upload` method:\n * the Cloudinary Media Library widget is used for authentication and file selection/uploading\n * instead.\n * @type {MediaLibraryService}\n */\nexport default {\n  serviceType: 'cloud_storage',\n  serviceId: 'cloudinary',\n  serviceLabel: 'Cloudinary',\n  serviceURL: 'https://cloudinary.com/',\n  showServiceLink: true,\n  hotlinking: true,\n  authType: 'widget',\n  developerURL: 'https://cloudinary.com/documentation/',\n  apiKeyURL: 'https://console.cloudinary.com/settings/api-keys',\n  apiKeyPattern: /^[A-Za-z0-9_-]{15,}$/,\n  isEnabled,\n  isAssetURL,\n};\n","import { getHash } from '@sveltia/utils/crypto';\n\nimport { getAssetKind } from '$lib/services/assets/kinds';\nimport { getRelativeKey } from '$lib/services/integrations/media-libraries/cloud/shared/keys';\nimport { createObjectStorageOperations } from '$lib/services/integrations/media-libraries/cloud/shared/object-storage';\nimport { hmacSha256, toHex } from '$lib/services/utils/crypto';\nimport { getBaseName } from '$lib/services/utils/file';\nimport { assertResponseOK } from '$lib/services/utils/networking';\nimport { encodePathSegments, encodeRFC3986, trimTrailingSlashes } from '$lib/services/utils/url';\nimport { parseXml, toArray } from '$lib/services/utils/xml';\n\n/**\n * @import {\n * ExternalAsset,\n * MediaLibraryFetchOptions,\n * S3Config,\n * } from '$lib/types/private';\n * @import {\n * ObjectStorageProvider,\n * } from '$lib/services/integrations/media-libraries/cloud/shared/object-storage';\n * @import {\n * ObjectStorageOperations,\n * } from '$lib/services/integrations/media-libraries/cloud/shared/service';\n */\n\n/**\n * @typedef {object} S3Object\n * @property {string} Key Object key (file path).\n * @property {string} LastModified Last modified timestamp.\n * @property {string} ETag ETag.\n * @property {number} Size File size in bytes.\n * @property {string} [ContentType] Content type.\n */\n\n/**\n * @typedef {object} S3ListResponse\n * @property {S3Object[]} Contents List of objects.\n * @property {boolean} IsTruncated Whether more results are available.\n * @property {string} [NextContinuationToken] Token for next page.\n */\n\n/**\n * Generate AWS Signature Version 4.\n * @param {object} params Parameters.\n * @param {string} params.method HTTP method.\n * @param {string} params.url Request URL.\n * @param {Record<string, string>} params.headers Request headers.\n * @param {string} params.payloadHash SHA-256 hash of the request payload.\n * @param {string} params.accessKeyId AWS access key ID.\n * @param {string} params.secretAccessKey AWS secret access key.\n * @param {string} params.region AWS region.\n * @param {string} params.service AWS service name (e.g., 's3').\n * @param {Date} params.date Request date.\n * @returns {Promise<string>} Authorization header value.\n * @see https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html\n */\nexport const generateAwsSignature = async ({\n  method,\n  url,\n  headers,\n  payloadHash,\n  accessKeyId,\n  secretAccessKey,\n  region,\n  service,\n  date,\n}) => {\n  const urlObj = new URL(url);\n  const amzDate = date.toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n  const dateStamp = amzDate.slice(0, 8);\n  // Create canonical request\n  const canonicalUri = urlObj.pathname;\n\n  const canonicalQueryString = [...urlObj.searchParams.entries()]\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n    .map(([k, v]) => `${encodeRFC3986(k)}=${encodeRFC3986(v)}`)\n    .join('&');\n\n  const canonicalHeaders = Object.entries(headers)\n    .map(([key, value]) => `${key.toLowerCase()}:${value.trim()}`)\n    .sort()\n    .join('\\n');\n\n  const signedHeaders = Object.keys(headers)\n    .map((key) => key.toLowerCase())\n    .sort()\n    .join(';');\n\n  const canonicalRequest = [\n    method,\n    canonicalUri,\n    canonicalQueryString,\n    `${canonicalHeaders}\\n`,\n    signedHeaders,\n    payloadHash,\n  ].join('\\n');\n\n  // Create string to sign\n  const algorithm = 'AWS4-HMAC-SHA256';\n  const credentialScope = `${dateStamp}/${region}/${service}/aws4_request`;\n  const canonicalRequestHash = await getHash(canonicalRequest, { algorithm: 'SHA-256' });\n  const stringToSign = [algorithm, amzDate, credentialScope, canonicalRequestHash].join('\\n');\n  // Calculate signature\n  const kDate = await hmacSha256(`AWS4${secretAccessKey}`, dateStamp);\n  const kRegion = await hmacSha256(kDate, region);\n  const kService = await hmacSha256(kRegion, service);\n  const kSigning = await hmacSha256(kService, 'aws4_request');\n  const signatureHex = toHex(await hmacSha256(kSigning, stringToSign));\n\n  return [\n    `${algorithm} Credential=${accessKeyId}/${credentialScope},`,\n    `SignedHeaders=${signedHeaders}, Signature=${signatureHex}`,\n  ].join(' ');\n};\n\n/**\n * Make a signed S3 API request.\n * @param {object} params Parameters.\n * @param {string} params.method HTTP method.\n * @param {string} params.url Request URL.\n * @param {S3Config} params.config S3 configuration.\n * @param {string} params.secretAccessKey AWS secret access key.\n * @param {string | ArrayBuffer} [params.body] Request body.\n * @param {Record<string, string>} [params.extraHeaders] Additional headers.\n * @returns {Promise<Response>} Response.\n */\nexport const signedRequest = async ({\n  method,\n  url,\n  config,\n  secretAccessKey,\n  body = '',\n  extraHeaders = {},\n}) => {\n  const { access_key_id: accessKeyId, region = 'us-east-1' } = config;\n\n  if (!accessKeyId) {\n    throw new Error('S3 access key ID is required');\n  }\n\n  const date = new Date();\n  const urlObj = new URL(url);\n  const payloadHash = await getHash(body, { algorithm: 'SHA-256' });\n\n  const headers = {\n    Host: urlObj.host,\n    'x-amz-date': date.toISOString().replace(/[:-]|\\.\\d{3}/g, ''),\n    'x-amz-content-sha256': payloadHash,\n    ...extraHeaders,\n  };\n\n  const authorization = await generateAwsSignature({\n    method,\n    url,\n    headers,\n    payloadHash,\n    accessKeyId,\n    secretAccessKey,\n    region,\n    service: 's3',\n    date,\n  });\n\n  return fetch(url, {\n    method,\n    headers: { ...headers, Authorization: authorization },\n    ...(body && { body }),\n  });\n};\n\n/**\n * Build base URL for S3 object.\n * @param {object} params Parameters.\n * @param {string} params.bucket Bucket name.\n * @param {string} params.key Object key.\n * @param {string} [params.endpoint] Custom endpoint.\n * @param {string} [params.region] AWS region.\n * @param {boolean} [params.forcePathStyle] Use path-style URLs.\n * @param {string} [params.publicUrl] Base URL for public access (overrides endpoint for asset\n * URLs). Used for Cloudflare R2 r2.dev or custom domain URLs.\n * @returns {string} Base URL.\n */\nexport const buildObjectUrl = ({ bucket, key, endpoint, region, forcePathStyle, publicUrl }) => {\n  if (publicUrl) {\n    return `${trimTrailingSlashes(publicUrl)}/${key}`;\n  }\n\n  if (endpoint) {\n    return `${trimTrailingSlashes(endpoint)}/${bucket}/${key}`;\n  }\n\n  if (forcePathStyle) {\n    return `https://s3.${region}.amazonaws.com/${bucket}/${key}`;\n  }\n\n  return `https://${bucket}.s3.${region}.amazonaws.com/${key}`;\n};\n\n/**\n * Whether the given URL points to an object in the configured bucket, through either the public\n * URL or the API endpoint.\n * @param {S3Config} config S3 configuration.\n * @param {string} url URL.\n * @returns {boolean} Result.\n */\nexport const isS3ObjectUrl = (config, url) => {\n  const {\n    bucket,\n    region,\n    endpoint,\n    force_path_style: forcePathStyle,\n    public_url: publicUrl,\n  } = config;\n\n  return [\n    buildObjectUrl({ bucket, key: '', endpoint, region, forcePathStyle, publicUrl }),\n    buildObjectUrl({ bucket, key: '', endpoint, region, forcePathStyle }),\n  ].some((base) => url.startsWith(base));\n};\n\n/**\n * Percent-encode an object key for use in a request URL or the `x-amz-copy-source` header, keeping\n * the path separators intact. Unlike `encodeURIComponent()`, the characters `!'()*` are encoded as\n * well, because Signature Version 4 requires every character other than the unreserved ones to be\n * encoded in the canonical URI.\n * @param {string} key Object key.\n * @returns {string} Encoded key.\n * @see https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html\n */\nexport const encodeKey = (key) => encodePathSegments(key, encodeRFC3986);\n\n/**\n * Build the API endpoint URL of an object, which is where the object is read, written and deleted.\n * Unlike {@link buildObjectUrl}, this never uses `public_url`, because a CDN or custom domain in\n * front of the bucket doesn’t accept signed API requests. The key is percent-encoded, so a key\n * containing `#` or `?` is not cut short by the URL parser, and the signed path matches the\n * request.\n * @param {S3Config} config S3 configuration.\n * @param {string} key Object key.\n * @returns {string} Object URL.\n */\nexport const buildObjectApiUrl = (config, key) => {\n  const { bucket, region, endpoint, force_path_style: forcePathStyle } = config;\n\n  return buildObjectUrl({ bucket, key: encodeKey(key), endpoint, region, forcePathStyle });\n};\n\n/**\n * Get the ACL header for a new object, if the service needs one to make it publicly readable.\n * @param {S3Config} config S3 configuration.\n * @returns {Record<string, string>} Header, or an empty object.\n */\nconst getAclHeader = ({ acl }) => (acl ? { 'x-amz-acl': acl } : {});\n\n/**\n * Get the secret access key from the given fetch options.\n * @param {MediaLibraryFetchOptions} options Fetch options.\n * @returns {string} Secret access key.\n * @throws {Error} When no key was provided.\n */\nconst requireSecretAccessKey = ({ apiKey: secretAccessKey }) => {\n  if (!secretAccessKey) {\n    throw new Error('S3 secret access key is required');\n  }\n\n  return secretAccessKey;\n};\n\n/**\n * Parse S3 list response into ExternalAsset format.\n * @param {S3Object[]} objects S3 objects.\n * @param {S3Config} config S3 configuration.\n * @returns {ExternalAsset[]} Assets.\n */\nexport const parseS3Results = (objects, config) => {\n  const {\n    bucket,\n    region,\n    endpoint,\n    force_path_style: forcePathStyle,\n    public_url: publicUrl,\n  } = config;\n\n  return objects.map((obj) => {\n    const key = obj.Key;\n    const fileName = getBaseName(key) || key;\n    const displayKey = getRelativeKey(config, key);\n\n    const baseUrl = buildObjectUrl({\n      bucket,\n      key: encodeKey(key),\n      endpoint,\n      region,\n      forcePathStyle,\n      publicUrl,\n    });\n\n    return {\n      id: key,\n      description: displayKey,\n      previewURL: baseUrl,\n      downloadURL: baseUrl,\n      fileName,\n      lastModified: new Date(obj.LastModified),\n      size: Number(obj.Size),\n      kind: getAssetKind(key),\n    };\n  });\n};\n\n/**\n * Fetch a page of the objects under the given prefix from S3-compatible storage.\n * @param {object} params Parameters.\n * @param {S3Config} params.config S3 configuration.\n * @param {string} params.credential Secret access key.\n * @param {string} params.prefix Key prefix.\n * @param {string} [params.cursor] Continuation token of the page.\n * @param {string} [params.delimiter] Delimiter to group the keys with, leaving out the objects in\n * subfolders, which are returned as common prefixes instead.\n * @returns {Promise<{ items: S3Object[], cursor?: string }>} Objects and the continuation token of\n * the next page, if any.\n * @see https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html\n */\nconst listS3Page = async ({ config, credential: secretAccessKey, prefix, cursor, delimiter }) => {\n  const { bucket, region, endpoint, force_path_style: forcePathStyle } = config;\n\n  const params = new URLSearchParams({\n    'list-type': '2',\n    'max-keys': '1000',\n    ...(prefix && { prefix }),\n    ...(delimiter && { delimiter }),\n    ...(cursor && { 'continuation-token': cursor }),\n  });\n\n  const url = endpoint\n    ? `${trimTrailingSlashes(endpoint)}/${bucket}?${params}`\n    : forcePathStyle\n      ? `https://s3.${region}.amazonaws.com/${bucket}?${params}`\n      : `https://${bucket}.s3.${region}.amazonaws.com/?${params}`;\n\n  const response = await signedRequest({ method: 'GET', url, config, secretAccessKey });\n\n  await assertResponseOK(response, 'Failed to list objects');\n\n  /** @type {any} */\n  const data = parseXml(await response.text());\n\n  return {\n    items: toArray(data.Contents),\n    cursor: (data.IsTruncated === 'true' && data.NextContinuationToken) || undefined,\n  };\n};\n\n/**\n * Upload a single file to S3-compatible storage under the given key, overwriting any existing\n * object with the same key.\n * @param {object} params Parameters.\n * @param {string} params.key Object key.\n * @param {File} params.file File to upload.\n * @param {S3Config} params.config S3 configuration.\n * @param {string} params.credential Secret access key.\n * @returns {Promise<S3Object>} Uploaded object.\n */\nconst putS3Object = async ({ key, file, config, credential: secretAccessKey }) => {\n  const fileContent = await file.arrayBuffer();\n\n  const response = await signedRequest({\n    method: 'PUT',\n    url: buildObjectApiUrl(config, key),\n    config,\n    secretAccessKey,\n    body: fileContent,\n    extraHeaders: {\n      'Content-Type': file.type || 'application/octet-stream',\n      ...getAclHeader(config),\n    },\n  });\n\n  await assertResponseOK(response, `Failed to upload file ${file.name}`);\n\n  return {\n    Key: key,\n    LastModified: new Date().toISOString(),\n    ETag: '',\n    Size: file.size,\n    ContentType: file.type,\n  };\n};\n\n/**\n * Delete a single object from S3-compatible storage. Objects are deleted one by one, as the\n * multi-object delete API requires a `Content-MD5` header, which some S3-compatible services don’t\n * support. The bucket’s CORS policy must allow the `DELETE` method, in addition to the `GET` and\n * `PUT` methods needed for listing and uploading; otherwise the browser blocks the request at the\n * preflight stage.\n * @param {object} params Parameters.\n * @param {string} params.key Object key.\n * @param {S3Config} params.config S3 configuration.\n * @param {string} params.credential Secret access key.\n * @param {boolean} [params.allowNotFound] Whether an object that doesn’t exist counts as deleted.\n * S3 itself reports success for a key that doesn’t exist.\n * @returns {Promise<void>}\n * @see https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html\n */\nconst deleteS3Object = async ({\n  key,\n  config,\n  credential: secretAccessKey,\n  allowNotFound = false,\n}) => {\n  const response = await signedRequest({\n    method: 'DELETE',\n    url: buildObjectApiUrl(config, key),\n    config,\n    secretAccessKey,\n  });\n\n  await assertResponseOK(response, `Failed to delete object ${key}`, { allowNotFound });\n};\n\n/**\n * Copy an object on S3-compatible storage to another key. The bucket’s CORS policy must allow the\n * `x-amz-copy-source` and `x-amz-metadata-directive` headers (an `AllowedHeaders` of `*` is the\n * simplest); otherwise the browser blocks the request at the preflight stage.\n * @param {object} params Parameters.\n * @param {ExternalAsset} params.asset Asset to copy. Its `id` is the object key.\n * @param {string} params.key New object key.\n * @param {S3Config} params.config S3 configuration.\n * @param {string} params.credential Secret access key.\n * @returns {Promise<S3Object>} Copied object.\n * @see https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html\n */\nconst copyS3Object = async ({ asset, key: newKey, config, credential: secretAccessKey }) => {\n  const { bucket } = config;\n  const { id: key, size = 0 } = asset;\n\n  const response = await signedRequest({\n    method: 'PUT',\n    url: buildObjectApiUrl(config, newKey),\n    config,\n    secretAccessKey,\n    extraHeaders: {\n      'x-amz-copy-source': `/${bucket}/${encodeKey(key)}`,\n      'x-amz-metadata-directive': 'COPY',\n      ...getAclHeader(config),\n    },\n  });\n\n  await assertResponseOK(response, `Failed to copy object ${key}`);\n\n  // A copy that fails after S3 has sent the `200 OK` status comes with an `Error` document instead\n  // of `CopyObjectResult`, so check the body before the source is deleted. Some S3-compatible\n  // services send an empty body on success.\n  const body = await response.text();\n\n  if (/^\\s*(?:<\\?xml[^>]*>\\s*)?<Error[\\s>]/.test(body)) {\n    throw new Error(`Failed to copy object ${key}: ${body}`);\n  }\n\n  return { Key: newKey, LastModified: new Date().toISOString(), ETag: '', Size: size };\n};\n\n/**\n * Put a zero-byte placeholder object at the given folder key, the way the AWS console creates a\n * folder.\n * @param {object} params Parameters.\n * @param {string} params.key Folder key, ending with a slash.\n * @param {S3Config} params.config S3 configuration.\n * @param {string} params.credential Secret access key.\n * @returns {Promise<void>}\n */\nconst putS3FolderObject = async ({ key, config, credential: secretAccessKey }) => {\n  const response = await signedRequest({\n    method: 'PUT',\n    url: buildObjectApiUrl(config, key),\n    config,\n    secretAccessKey,\n    extraHeaders: { 'Content-Type': 'application/x-directory', ...getAclHeader(config) },\n  });\n\n  await assertResponseOK(response, `Failed to create folder ${key}`);\n};\n\n/**\n * S3 API calls for the operations shared with the other object storage services.\n * @type {ObjectStorageProvider<S3Object, S3Config>}\n */\nconst provider = {\n  requireCredential: requireSecretAccessKey,\n  listPage: listS3Page,\n  /**\n   * Get the key of an object.\n   * @param {S3Object} object Object.\n   * @returns {string} Key.\n   */\n  getKey: ({ Key }) => Key,\n  // S3 URLs carry no credential, so the parser ignores it\n  parseResults: parseS3Results,\n  putObject: putS3Object,\n  copyObject: copyS3Object,\n  deleteObject: deleteS3Object,\n  putFolderObject: putS3FolderObject,\n};\n\n/**\n * Operations of an S3-compatible object storage service.\n * @type {ObjectStorageOperations<S3Config>}\n */\nexport const s3Operations = createObjectStorageOperations(provider);\n","import { ObjectStorageService } from '$lib/services/integrations/media-libraries/cloud/shared/service';\n\nimport { isS3ObjectUrl, s3Operations } from './core';\n\n/**\n * @import { S3Config } from '$lib/types/private';\n * @import { MediaLibraries, S3MediaLibrary } from '$lib/types/public';\n */\n\n/**\n * Options to define an S3-compatible media library service.\n * @typedef {object} S3CompatibleServiceOptions\n * @property {keyof MediaLibraries} serviceId Service identifier matching the `media_libraries`\n * key.\n * @property {string} serviceLabel Default service label, overridden by the `label` library option.\n * @property {string} serviceURL Service URL.\n * @property {string} developerURL URL of the page that provides the API/developer service.\n * @property {string} apiKeyURL URL of the page that provides the secret access key.\n * @property {RegExp} apiKeyPattern Secret access key pattern.\n * @property {keyof S3MediaLibrary} [requiredOption] Service-specific option that must be set along\n * with `access_key_id` and `bucket` for the service to be enabled, such as `region` or\n * `account_id`. Default: `region`.\n * @property {(libOptions: S3MediaLibrary) => S3Config} [resolveConfig] Function to derive the S3\n * configuration from the library options, typically to add the service’s fixed API endpoint and\n * default public URL, or to fill in a default `access_key_id`. The result is also used to decide\n * whether the service is enabled. Default: the library options are used as is, unless\n * `regionalHost` is given.\n * @property {(region: string | undefined) => string} [regionalHost] Function to get the host name\n * of the service’s API endpoint in the given region, for a service that takes path-style API calls\n * at the region endpoint and serves the public files virtual-hosted-style from a subdomain of it\n * named after the bucket, unless a custom CDN `public_url` is configured.\n * @property {string} [objectAcl] Canned ACL sent in the `x-amz-acl` header when creating an object,\n * for a service where objects are private by default, even in a public bucket, such as DigitalOcean\n * Spaces and Scaleway. It can’t be set in the library options. Default: none, as Amazon S3 rejects\n * ACLs on buckets created since April 2023, and services without per-object ACLs don’t implement\n * the header.\n */\n\n/**\n * Media library service for an S3-compatible object storage service. The S3 API calls are shared\n * in the `core` module; the base class resolves the service’s configuration from the CMS or field\n * configuration and delegates the operations to those functions.\n * @augments {ObjectStorageService<S3Config>}\n */\nexport class S3CompatibleService extends ObjectStorageService {\n  /** @type {'s3'} */\n  compatibleAPI = 's3';\n\n  /**\n   * Initialize an `S3CompatibleService` instance with the given service definition.\n   * @param {S3CompatibleServiceOptions} options Service definition.\n   */\n  constructor({\n    requiredOption = 'region',\n    objectAcl,\n    regionalHost,\n    resolveConfig = regionalHost\n      ? (libOptions) => {\n          const host = regionalHost(libOptions.region);\n\n          return {\n            ...libOptions,\n            endpoint: `https://${host}`,\n            public_url: libOptions.public_url ?? `https://${libOptions.bucket}.${host}`,\n          };\n        }\n      : (libOptions) => libOptions,\n    ...definition\n  }) {\n    super({\n      ...definition,\n      /**\n       * Resolve the configuration, replacing any `acl` in the library options with the service’s\n       * own object ACL.\n       * @param {S3MediaLibrary} libOptions Library options.\n       * @returns {S3Config} Resolved configuration.\n       */\n      resolveConfig: (libOptions) => ({ ...resolveConfig(libOptions), acl: objectAcl }),\n      /**\n       * Check if the access key ID, the bucket and the service-specific option are all set.\n       * @param {S3Config} config Resolved configuration.\n       * @returns {boolean} Result.\n       */\n      isConfigured: (config) => !!(config.access_key_id && config.bucket && config[requiredOption]),\n      isConfigURL: isS3ObjectUrl,\n      operations: s3Operations,\n    });\n\n    this.requiredOption = requiredOption;\n  }\n}\n","import { S3CompatibleService } from './service';\n\n/**\n * Amazon S3 media library service integration.\n */\nconst awsS3 = new S3CompatibleService({\n  serviceId: 'aws_s3',\n  serviceLabel: 'Amazon S3',\n  serviceURL: 'https://aws.amazon.com/s3/',\n  developerURL: 'https://docs.aws.amazon.com/s3/',\n  apiKeyURL: 'https://console.aws.amazon.com/iam/home#/security_credentials',\n  // Amazon S3 keys are 40 characters long, but the integration also works with other S3-compatible\n  // services through the `endpoint` option, whose keys can be longer, e.g. 64 hex digits on Garage\n  apiKeyPattern: /^[A-Za-z0-9/+=]{40,}$/,\n});\n\nexport default awsS3;\n","import { S3CompatibleService } from './service';\n\n/**\n * Backblaze B2 media library service integration. B2 uses the region endpoint for API calls\n * (path-style) and virtual-hosted-style for public asset URLs, unless the user has configured a\n * custom CDN `public_url`.\n */\nexport default new S3CompatibleService({\n  serviceId: 'backblaze_b2',\n  serviceLabel: 'Backblaze B2',\n  serviceURL: 'https://www.backblaze.com/cloud-storage',\n  developerURL: 'https://www.backblaze.com/docs/cloud-storage-s3-compatible-api',\n  apiKeyURL: 'https://secure.backblaze.com/app_keys.htm',\n  apiKeyPattern: /^[A-Za-z0-9/+=]{30,}$/,\n  /**\n   * Get the host name of the B2 API endpoint in the given region.\n   * @param {string | undefined} region Region.\n   * @returns {string} Host name.\n   */\n  regionalHost: (region) => `s3.${region}.backblazeb2.com`,\n});\n","import { S3CompatibleService } from './service';\n\n/**\n * @import { S3Config } from '$lib/types/private';\n * @import { S3MediaLibrary } from '$lib/types/public';\n */\n\n/**\n * Bunny Storage media library service integration. Bunny exposes an S3-compatible endpoint per\n * storage region (path-style), where the access key ID is the storage zone name and the secret\n * access key is the storage zone password. Since the storage zone name is also the bucket name,\n * `access_key_id` defaults to `bucket`. The storage endpoint always requires authentication, so the\n * user must front the zone with a pull zone and set its hostname as `public_url`.\n * @see https://bunny.net/docs/storage/s3\n */\nexport default new S3CompatibleService({\n  serviceId: 'bunny_storage',\n  serviceLabel: 'Bunny Storage',\n  serviceURL: 'https://bunny.net/storage/',\n  developerURL: 'https://bunny.net/docs/storage/s3',\n  apiKeyURL: 'https://dash.bunny.net/storage',\n  // Hyphen-separated hex groups, e.g. `a2350e09-57ec-3f4e-d7a38d0858a6-a5c7-47aa`. Kept loose on\n  // the group count and length, as Bunny doesn’t document the exact format.\n  apiKeyPattern: /^[0-9a-f]{8}(?:-[0-9a-f]{4,12}){3,7}$/i,\n  /**\n   * Add the Bunny region endpoint to the library options, default the access key ID to the storage\n   * zone name.\n   * @param {S3MediaLibrary} libOptions Library options.\n   * @returns {S3Config} Resolved configuration.\n   */\n  resolveConfig: (libOptions) => ({\n    ...libOptions,\n    access_key_id: libOptions.access_key_id ?? libOptions.bucket,\n    endpoint: `https://${libOptions.region}-s3.storage.bunnycdn.com`,\n  }),\n});\n","import { S3CompatibleService } from './service';\n\n/**\n * @import { S3Config } from '$lib/types/private';\n * @import { S3MediaLibrary } from '$lib/types/public';\n */\n\n/**\n * Map of Cloudflare R2 jurisdiction identifiers to their endpoint infixes.\n * @type {Record<string, string>}\n * @see https://github.com/sveltia/sveltia-cms/issues/752\n * @see https://developers.cloudflare.com/r2/reference/data-location/#jurisdictional-restrictions\n */\nconst JURISDICTION_INFIXES = {\n  default: '',\n  eu: 'eu.',\n  fedramp: 'fedramp.',\n};\n\n/**\n * Build the Cloudflare R2 S3 API endpoint for the given account and jurisdiction.\n * @param {S3MediaLibrary} libOptions Library options.\n * @returns {string} Endpoint URL.\n */\nconst getEndpoint = ({ account_id: accountId, jurisdiction = 'default' }) => {\n  const infix = JURISDICTION_INFIXES[jurisdiction] ?? '';\n\n  return `https://${accountId}.${infix}r2.cloudflarestorage.com`;\n};\n\n/**\n * Cloudflare R2 media library service integration. R2 uses the `auto` region.\n */\nexport default new S3CompatibleService({\n  serviceId: 'cloudflare_r2',\n  serviceLabel: 'Cloudflare R2',\n  serviceURL: 'https://www.cloudflare.com/developer-platform/r2/',\n  developerURL: 'https://developers.cloudflare.com/r2/',\n  apiKeyURL: 'https://dash.cloudflare.com/?to=/:account/r2/api-tokens',\n  apiKeyPattern: /^[A-Za-z0-9/+=]{40,}$/,\n  requiredOption: 'account_id',\n  /**\n   * Add the R2 endpoint and the `auto` region to the library options.\n   * @param {S3MediaLibrary} libOptions Library options.\n   * @returns {S3Config} Resolved configuration.\n   */\n  resolveConfig: (libOptions) => ({\n    ...libOptions,\n    region: 'auto',\n    endpoint: getEndpoint(libOptions),\n  }),\n});\n","import { S3CompatibleService } from './service';\n\n/**\n * DigitalOcean Spaces media library service integration. Spaces uses the region endpoint for API\n * calls (path-style) and virtual-hosted-style for public asset URLs, unless the user has configured\n * a custom CDN `public_url`. Files are private by default, and a public file listing doesn’t make\n * them readable, so new objects get the `public-read` ACL.\n */\nexport default new S3CompatibleService({\n  serviceId: 'digitalocean_spaces',\n  serviceLabel: 'DigitalOcean Spaces',\n  serviceURL: 'https://www.digitalocean.com/products/spaces',\n  developerURL: 'https://docs.digitalocean.com/products/spaces/',\n  apiKeyURL: 'https://cloud.digitalocean.com/account/api/spaces',\n  objectAcl: 'public-read',\n  apiKeyPattern: /^[A-Za-z0-9/+=]{43}$/,\n  /**\n   * Get the host name of the Spaces API endpoint in the given region.\n   * @param {string | undefined} region Region.\n   * @returns {string} Host name.\n   */\n  regionalHost: (region) => `${region}.digitaloceanspaces.com`,\n});\n","import { S3CompatibleService } from './service';\n\n/**\n * @import { S3Config } from '$lib/types/private';\n * @import { S3MediaLibrary } from '$lib/types/public';\n */\n\n/**\n * Hostname pattern of a Neon Object Storage endpoint, e.g.\n * `br-cool-darkness-a1b2c3d4.storage.c-1.us-east-2.aws.neon.tech`, where `c-1` is the cell and\n * `us-east-2` the region. The cell is optional, in case a region has none.\n */\nconst ENDPOINT_HOSTNAME_REGEX =\n  /^[a-z0-9-]+\\.storage\\.(?:[a-z0-9-]+\\.)?([a-z]{2}-[a-z]+-\\d+)\\.aws\\.neon\\.tech$/;\n\n/**\n * Parse the Neon Object Storage endpoint given in the library options. Anything other than an HTTPS\n * URL on a Neon storage hostname is rejected, so the signed requests can’t be sent to another host.\n * @param {S3MediaLibrary} libOptions Library options.\n * @returns {{ endpoint: string, region: string } | undefined} Normalized endpoint URL (origin only)\n * and the region in its hostname, or `undefined` if the endpoint is missing or invalid.\n */\nconst parseEndpoint = ({ endpoint }) => {\n  const url = URL.parse(endpoint ?? '');\n\n  if (url?.protocol !== 'https:' || url.port) {\n    return undefined;\n  }\n\n  const [, region] = url.hostname.match(ENDPOINT_HOSTNAME_REGEX) ?? [];\n\n  return region ? { endpoint: url.origin, region } : undefined;\n};\n\n/**\n * Neon Object Storage media library service integration. Each Neon branch has its own endpoint,\n * which includes a cell ID and can’t be derived from other options, so the user must set\n * `endpoint`. Objects are addressed path-style, which is also how a `public_read` bucket serves\n * them anonymously; a private bucket needs a `public_url`. Neon doesn’t implement object ACLs.\n * @see https://neon.com/docs/storage/s3-compatibility\n */\nexport default new S3CompatibleService({\n  serviceId: 'neon_object_storage',\n  serviceLabel: 'Neon Object Storage',\n  serviceURL: 'https://neon.com/docs/storage/overview',\n  developerURL: 'https://neon.com/docs/storage/s3-compatibility',\n  apiKeyURL: 'https://neon.com/docs/storage/authentication',\n  // `nsk_live_` followed by 64 hex digits\n  apiKeyPattern: /^nsk_[a-z]+_[0-9a-f]{64}$/,\n  requiredOption: 'endpoint',\n  /**\n   * Validate the endpoint and take the region from its hostname unless `region` is set.\n   * @param {S3MediaLibrary} libOptions Library options.\n   * @returns {S3Config} Resolved configuration. `endpoint` is `undefined` if invalid, which\n   * disables the service.\n   */\n  resolveConfig: (libOptions) => {\n    const parsed = parseEndpoint(libOptions);\n\n    return {\n      ...libOptions,\n      endpoint: parsed?.endpoint,\n      region: libOptions.region ?? parsed?.region,\n    };\n  },\n});\n","import { S3CompatibleService } from './service';\n\n/**\n * Scaleway Object Storage media library service integration. Scaleway uses the region endpoint for\n * API calls (path-style) and virtual-hosted-style for public asset URLs, unless the user has\n * configured a custom CDN `public_url`. Objects are private by default, even in a public bucket, so\n * new objects get the `public-read` ACL.\n */\nexport default new S3CompatibleService({\n  serviceId: 'scaleway_object_storage',\n  serviceLabel: 'Scaleway Object Storage',\n  serviceURL: 'https://www.scaleway.com/en/object-storage/',\n  developerURL: 'https://www.scaleway.com/en/docs/object-storage/',\n  apiKeyURL: 'https://console.scaleway.com/iam/api-keys',\n  objectAcl: 'public-read',\n  apiKeyPattern: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,\n  /**\n   * Get the host name of the Scaleway API endpoint in the given region.\n   * @param {string | undefined} region Region.\n   * @returns {string} Host name.\n   */\n  regionalHost: (region) => `s3.${region}.scw.cloud`,\n});\n","import { S3CompatibleService } from './service';\n\n/**\n * @import { S3Config } from '$lib/types/private';\n * @import { S3MediaLibrary } from '$lib/types/public';\n */\n\n/**\n * Build the Supabase Storage S3 API endpoint for the given project.\n * @param {S3MediaLibrary} libOptions Library options.\n * @returns {string} Endpoint URL.\n * @see https://supabase.com/docs/guides/storage/s3/authentication\n */\nconst getEndpoint = ({ project_id: projectId }) =>\n  `https://${projectId}.storage.supabase.co/storage/v1/s3`;\n\n/**\n * Build the Supabase Storage public base URL for the given project and bucket.\n * @param {S3MediaLibrary} libOptions Library options.\n * @returns {string} Public base URL (bucket included; key is appended by core).\n */\nconst getPublicUrl = ({ project_id: projectId, bucket }) =>\n  `https://${projectId}.supabase.co/storage/v1/object/public/${bucket}`;\n\n/**\n * Supabase Storage media library service integration.\n */\nexport default new S3CompatibleService({\n  serviceId: 'supabase_storage',\n  serviceLabel: 'Supabase Storage',\n  serviceURL: 'https://supabase.com/storage',\n  developerURL: 'https://supabase.com/docs/guides/storage',\n  apiKeyURL: 'https://supabase.com/dashboard/project/_/storage/settings',\n  apiKeyPattern: /^[A-Za-z0-9/+=]{40,}$/,\n  requiredOption: 'project_id',\n  /**\n   * Add the Supabase S3 endpoint and public URL to the library options.\n   * @param {S3MediaLibrary} libOptions Library options.\n   * @returns {S3Config} Resolved configuration.\n   */\n  resolveConfig: (libOptions) => ({\n    ...libOptions,\n    endpoint: getEndpoint(libOptions),\n    public_url: libOptions.public_url ?? getPublicUrl(libOptions),\n  }),\n});\n","/* eslint-disable no-await-in-loop */\n\nimport { sleep } from '@sveltia/utils/misc';\n\nimport { formatFileName } from '$lib/services/assets/file-name';\nimport { getAssetKind, isMediaKind } from '$lib/services/assets/kinds';\nimport { cmsConfig } from '$lib/services/config/state';\nimport {\n  findLibraryOptions,\n  resolveLibraryOptions,\n} from '$lib/services/integrations/media-libraries/options';\nimport { splitIntoChunks } from '$lib/services/utils/array';\nimport { hmacSha256, toHex } from '$lib/services/utils/crypto';\nimport { assertResponseOK } from '$lib/services/utils/networking';\nimport { fetchPages } from '$lib/services/utils/paging';\nimport { encodeRFC3986 } from '$lib/services/utils/url';\n\n/**\n * @import {\n * AssetKind,\n * ExternalAsset,\n * MediaLibraryFetchOptions,\n * MediaLibraryService,\n * } from '$lib/types/private';\n * @import { CmsConfig, MediaField, UploadcareMediaLibrary } from '$lib/types/public';\n */\n\n/**\n * Origin of the legacy CDN, which projects created before September 4, 2025 can still use.\n * @see https://uploadcare.com/docs/delivery/cdn/\n */\nconst LEGACY_CDN_ORIGIN = 'https://ucarecdn.com';\n/**\n * Regex matching a URL on a project’s own CDN subdomain, like `https://demo.ucarecd.net/`, which\n * newer projects serve their files from.\n * @see https://uploadcare.com/docs/delivery/cdn/\n */\nconst PROJECT_CDN_URL_REGEX = /^https:\\/\\/[\\w-]+\\.ucarecd\\.net\\//i;\n\n/**\n * @typedef {object} UploadcareResource\n * @property {string} uuid File UUID.\n * @property {string} original_filename Original file name.\n * @property {string} original_file_url Original file URL.\n * @property {number} size File size in bytes.\n * @property {string} mime_type MIME type.\n * @property {boolean} is_image Whether the file is an image.\n * @property {boolean} is_ready Whether the file is ready.\n * @property {object | null} content_info Content information with mime, image, video data.\n * @property {string} datetime_uploaded Upload timestamp.\n * @property {string | null} datetime_stored Storage timestamp.\n * @property {string | null} datetime_removed Removal timestamp.\n */\n\n/**\n * @typedef {object} UploadcareListResponse\n * @property {UploadcareResource[]} results List of files.\n * @property {string | null} next Next page URL.\n * @property {number} total Total number of files.\n */\n\n/**\n * Get Uploadcare library options from site config.\n * @param {CmsConfig | MediaField} [config] CMS configuration or field configuration.\n * @returns {UploadcareMediaLibrary | false | undefined} Configuration object, or `false` if\n * explicitly disabled.\n */\nexport const getLibraryOptions = (config = cmsConfig.current) =>\n  findLibraryOptions('uploadcare', config);\n\n/**\n * Get Uploadcare public key from library options.\n * @param {MediaField} [fieldConfig] Field configuration.\n * @returns {string | undefined} Public key.\n */\nexport const getPublicKey = (fieldConfig) => {\n  const options = resolveLibraryOptions('uploadcare', fieldConfig);\n\n  return options ? options.config?.publicKey : undefined;\n};\n/**\n * Check if Uploadcare integration is enabled.\n * @param {MediaField} [fieldConfig] Field configuration.\n * @returns {boolean} True if enabled, false otherwise.\n */\nexport const isEnabled = (fieldConfig) => !!getPublicKey(fieldConfig);\n\n/**\n * Get the kind of an Uploadcare file. The media kinds come from the MIME type, which Uploadcare\n * detects from the content, and the other kinds from the file name, the way the other storage\n * services tell them. An SVG image is therefore an image, though Uploadcare doesn’t process it as\n * one.\n * @param {UploadcareResource} file File.\n * @returns {AssetKind} Kind.\n */\nconst getFileKind = ({ mime_type: mimeType, original_filename: fileName }) => {\n  const [type] = mimeType.split('/');\n\n  return isMediaKind(type) ? /** @type {AssetKind} */ (type) : getAssetKind(fileName);\n};\n\n/**\n * Parse API results into ExternalAsset format.\n * @param {UploadcareResource[]} results API results.\n * @param {object} [options] Additional options.\n * @param {MediaField} [options.fieldConfig] Field configuration for custom handling.\n * @returns {ExternalAsset[]} Assets.\n * @see https://decapcms.org/docs/uploadcare/#integration-settings\n * @see https://sveltiacms.app/en/docs/media/uploadcare\n */\nexport const parseResults = (results, { fieldConfig } = {}) => {\n  const libOptions = resolveLibraryOptions('uploadcare', fieldConfig);\n\n  const {\n    settings: { autoFilename = false, defaultOperations = undefined } = {},\n    config: { cdnBase = undefined } = {},\n  } = libOptions || {};\n\n  return results.map((result) => {\n    const {\n      uuid,\n      original_filename: fileName,\n      original_file_url: url,\n      mime_type: mimeType,\n      datetime_uploaded: timestamp,\n      size,\n    } = result;\n\n    const baseURL = `${new URL(cdnBase ?? url).origin}/${uuid}/`;\n    const isImage = mimeType.startsWith('image/');\n\n    return {\n      id: uuid,\n      description: fileName,\n      previewURL: `${baseURL}${isImage ? '-/preview/400x400/' : ''}`,\n      // The file name is encoded, as it can contain characters like `#` or `%` that would end or\n      // garble the URL path, or a space or parenthesis that would break a Markdown link\n      downloadURL:\n        `${baseURL}${isImage && defaultOperations ? `-${defaultOperations}` : ''}` +\n        `${autoFilename ? encodeRFC3986(fileName) : ''}`,\n      fileName,\n      lastModified: new Date(timestamp),\n      size,\n      kind: getFileKind(result),\n    };\n  });\n};\n\n/**\n * Get the Uploadcare API keys for a request.\n * @param {MediaLibraryFetchOptions} options Options containing the secret key (apiKey).\n * @param {object} [args] Arguments.\n * @param {boolean} [args.secretKeyRequired] Whether to require the secret key.\n * @returns {{ publicKey: string, secretKey: string }} Public key and secret key.\n * @throws {Error} When the public key is not configured, or the required secret key is not\n * provided.\n */\nconst getKeys = ({ fieldConfig, apiKey: secretKey }, { secretKeyRequired = true } = {}) => {\n  const publicKey = getPublicKey(fieldConfig);\n\n  if (!publicKey) {\n    throw new Error('Uploadcare public key is not configured');\n  }\n\n  if (secretKeyRequired && !secretKey) {\n    throw new Error('Uploadcare secret key is not provided');\n  }\n\n  return { publicKey, secretKey };\n};\n\n/**\n * Get the headers for a REST API request.\n * @param {{ publicKey: string, secretKey: string }} keys Public key and secret key.\n * @returns {Record<string, string>} Headers.\n * @see https://uploadcare.com/api-refs/rest-api/v0.7.0/#section/Authentication\n */\nconst getRESTHeaders = ({ publicKey, secretKey }) => ({\n  Accept: 'application/vnd.uploadcare-v0.7+json',\n  Authorization: `Uploadcare.Simple ${publicKey}:${secretKey}`,\n});\n\n/**\n * Get the origin of the CDN the project serves its files from: a subdomain of its own, like\n * `https://demo.ucarecd.net`, or the legacy `https://ucarecdn.com`. The Upload API only returns the\n * file UUIDs, so the origin is read from the URL the REST API gives for one of the uploaded files,\n * which uses the domain the project currently serves files from.\n * @param {string} uuid UUID of an uploaded file.\n * @param {{ publicKey: string, secretKey: string }} keys Public key and secret key.\n * @returns {Promise<string>} Origin. The legacy one if the file info can’t be fetched.\n * @see https://uploadcare.com/docs/api/rest/file/info/\n * @see https://uploadcare.com/docs/delivery/cdn/\n */\nconst getCDNOrigin = async (uuid, keys) => {\n  try {\n    const response = await fetch(`https://api.uploadcare.com/files/${uuid}/`, {\n      headers: getRESTHeaders(keys),\n    });\n\n    if (response.ok) {\n      /** @type {UploadcareResource} */\n      const { original_file_url: url } = await response.json();\n\n      if (url) {\n        return new URL(url).origin;\n      }\n    }\n  } catch {\n    // The files have been uploaded anyway, so fall back to the legacy CDN\n  }\n\n  return LEGACY_CDN_ORIGIN;\n};\n\n/**\n * Fetch files from Uploadcare API with pagination.\n * @param {MediaLibraryFetchOptions} options Options containing the secret key (apiKey) and kind.\n * @param {object} [config] Additional configuration.\n * @param {number} [config.maxPages] Maximum number of pages to fetch. Default: 10.\n * @param {(file: UploadcareResource) => boolean} [config.filter] Optional filter function.\n * @returns {Promise<ExternalAsset[]>} Assets.\n * @see https://uploadcare.com/api-refs/rest-api/v0.7.0/#tag/File/operation/filesList\n */\nexport const fetchFiles = async (options, { maxPages = 10, filter } = {}) => {\n  const { kind, fieldConfig } = options;\n  const headers = getRESTHeaders(getKeys(options, { secretKeyRequired: false }));\n\n  const params = new URLSearchParams({\n    limit: '100',\n    ordering: '-datetime_uploaded',\n    stored: 'true',\n  });\n\n  const allResults = await fetchPages(\n    async (/** @type {string | undefined} */ nextUrl) => {\n      const response = await fetch(nextUrl ?? `https://api.uploadcare.com/files/?${params}`, {\n        headers,\n      });\n\n      await assertResponseOK(response, 'Failed to fetch files');\n\n      /** @type {UploadcareListResponse} */\n      const data = await response.json();\n      // Apply filters: first kind filter if specified, then custom filter if provided\n      let { results } = data;\n\n      if (kind) {\n        results = results.filter((file) => getFileKind(file) === kind);\n      }\n\n      if (filter) {\n        results = results.filter(filter);\n      }\n\n      return { results, next: data.next };\n    },\n    { maxPages },\n  );\n\n  return parseResults(allResults, { fieldConfig });\n};\n\n/**\n * List files from Uploadcare.\n * @param {MediaLibraryFetchOptions} options Options containing the secret key (apiKey).\n * @returns {Promise<ExternalAsset[]>} Assets.\n */\nexport const list = async (options) => fetchFiles(options);\n\n/**\n * Search files in Uploadcare. Since Uploadcare doesn’t have a built-in search API,\n * this implementation fetches files and filters them client-side by filename.\n * @param {string} query Search query.\n * @param {MediaLibraryFetchOptions} options Options containing the secret key (apiKey).\n * @returns {Promise<ExternalAsset[]>} Assets.\n */\nexport const search = async (query, options) => {\n  const lowerQuery = query.toLowerCase();\n  /**\n   * Filter files by filename.\n   * @param {UploadcareResource} file File to check.\n   * @returns {boolean} Whether the file matches the query.\n   */\n  const filter = (file) => file.original_filename.toLowerCase().includes(lowerQuery);\n\n  return fetchFiles(options, { filter });\n};\n\n/**\n * Generate a secure signature for Uploadcare upload.\n * @param {string} secretKey Secret key.\n * @param {number} expire Expiration timestamp.\n * @returns {Promise<string>} Signature.\n * @see https://uploadcare.com/docs/security/secure-uploads/\n */\nexport const generateSignature = async (secretKey, expire) =>\n  toHex(await hmacSha256(secretKey, String(expire)));\n\n/**\n * Upload files to Uploadcare.\n * @param {File[]} files Files to upload.\n * @param {MediaLibraryFetchOptions} options Options containing the secret key (apiKey).\n * @returns {Promise<ExternalAsset[]>} Uploaded assets.\n * @see https://uploadcare.com/api-refs/upload-api/#tag/Upload/operation/baseUpload\n * @see https://uploadcare.com/docs/security/secure-uploads/\n */\nexport const upload = async (files, options) => {\n  if (files.length === 0) {\n    return [];\n  }\n\n  const { fieldConfig } = options;\n  const keys = getKeys(options);\n  const { publicKey, secretKey } = keys;\n  // Generate signature for secure upload (expires in 30 minutes)\n  const expire = Math.floor(Date.now() / 1000) + 1800;\n  const signature = await generateSignature(secretKey, expire);\n  // Create a single FormData with all files\n  const formData = new FormData();\n\n  formData.append('UPLOADCARE_PUB_KEY', publicKey);\n  formData.append('UPLOADCARE_STORE', '1');\n  formData.append('signature', signature);\n  formData.append('expire', String(expire));\n\n  /**\n   * Files keyed by the form field name they are uploaded under, which is also the key of the\n   * response. The name is formatted, so it can differ from the original file name, and a file\n   * whose name is taken by an earlier file is renamed, otherwise the response would have one key\n   * for both.\n   * @type {Map<string, File>}\n   */\n  const fileMap = new Map();\n\n  // Add all files to the same FormData\n  files.forEach((file) => {\n    const fileName = formatFileName(file.name, { assetNamesInSameFolder: [...fileMap.keys()] });\n\n    fileMap.set(fileName, file);\n    formData.append(fileName, file);\n  });\n\n  const response = await fetch('https://upload.uploadcare.com/base/', {\n    method: 'POST',\n    body: formData,\n  });\n\n  await assertResponseOK(response, 'Failed to upload files');\n\n  const data = await response.json();\n  const entries = Object.entries(data).filter(([key]) => !key.startsWith('UPLOADCARE_'));\n\n  // The options and their `config` exist, as the public key has been read from them\n  const { cdnBase } = /** @type {Record<string, any>} */ (\n    /** @type {UploadcareMediaLibrary} */ (resolveLibraryOptions('uploadcare', fieldConfig)).config\n  );\n\n  // A configured CDN base is used in place of the origin, so there’s no need to look it up then\n  const cdnOrigin =\n    cdnBase === undefined && entries.length\n      ? await getCDNOrigin(entries[0][1], keys)\n      : LEGACY_CDN_ORIGIN;\n\n  // Handle both single and multiple file responses\n  const uploadedFiles = entries.map(([fileName, uuid]) => {\n    const file = fileMap.get(fileName);\n    const mimeType = file?.type || 'application/octet-stream';\n    const isImage = mimeType.startsWith('image/');\n\n    return {\n      uuid,\n      original_filename: fileName,\n      original_file_url: `${cdnOrigin}/${uuid}/${fileName}`,\n      size: file?.size || 0,\n      mime_type: mimeType,\n      is_image: isImage,\n      is_ready: true,\n      content_info: null,\n      datetime_uploaded: new Date().toISOString(),\n      datetime_stored: new Date().toISOString(),\n      datetime_removed: null,\n    };\n  });\n\n  return parseResults(uploadedFiles, { fieldConfig });\n};\n\n/**\n * Delete files from Uploadcare. The files are removed from storage in batches, as the REST API\n * accepts up to 100 UUIDs per request.\n * @param {ExternalAsset[]} assets Assets to delete. The `id` of each asset is the file UUID.\n * @param {MediaLibraryFetchOptions} options Options containing the secret key (apiKey).\n * @returns {Promise<void>}\n * @see https://uploadcare.com/api-refs/rest-api/v0.7.0/#tag/File/operation/filesDelete\n */\nexport const deleteFiles = async (assets, options) => {\n  const headers = { ...getRESTHeaders(getKeys(options)), 'Content-Type': 'application/json' };\n\n  const batches = splitIntoChunks(\n    assets.map(({ id }) => id),\n    100,\n  );\n\n  for (let index = 0; index < batches.length; index += 1) {\n    // Wait for a bit before sending the next batch\n    if (index > 0) {\n      await sleep(50);\n    }\n\n    const response = await fetch('https://api.uploadcare.com/files/storage/', {\n      method: 'DELETE',\n      headers,\n      body: JSON.stringify(batches[index]),\n    });\n\n    await assertResponseOK(response, 'Failed to delete files');\n  }\n\n  return undefined;\n};\n\n/**\n * Whether the given URL points to a file on the configured Uploadcare CDN, or else on the legacy\n * CDN or a project’s own CDN subdomain.\n * @param {string} url URL.\n * @returns {boolean} Result.\n */\nexport const isAssetURL = (url) => {\n  const options = getLibraryOptions();\n\n  if (!options) {\n    return false;\n  }\n\n  const cdnBase = options.config?.cdnBase;\n\n  if (cdnBase === undefined) {\n    return url.startsWith(`${LEGACY_CDN_ORIGIN}/`) || PROJECT_CDN_URL_REGEX.test(url);\n  }\n\n  try {\n    return url.startsWith(`${new URL(cdnBase).origin}/`);\n  } catch {\n    // A malformed `cdnBase` can’t be matched\n    return false;\n  }\n};\n\n/**\n * Uploadcare media library service integration. Files can’t be renamed through the REST API, and a\n * re-uploaded file gets a new UUID (and therefore a new URL), so neither `rename` nor `replace` is\n * provided.\n * @type {MediaLibraryService}\n */\nexport default {\n  serviceType: 'cloud_storage',\n  serviceId: 'uploadcare',\n  serviceLabel: 'Uploadcare',\n  serviceURL: 'https://uploadcare.com/',\n  showServiceLink: true,\n  hotlinking: true,\n  authType: 'api_key',\n  developerURL: 'https://uploadcare.com/docs/',\n  apiKeyURL: 'https://app.uploadcare.com/projects/-/api-keys/',\n  apiKeyPattern: /^[a-f0-9]{20}$/,\n  isEnabled,\n  isAssetURL,\n  list,\n  search,\n  upload,\n  delete: deleteFiles,\n};\n","import azureBlobStorage from './azure-blob-storage';\nimport cloudinary from './cloudinary';\nimport awsS3 from './s3/aws-s3';\nimport backblazeB2 from './s3/backblaze-b2';\nimport bunnyStorage from './s3/bunny-storage';\nimport cloudflareR2 from './s3/cloudflare-r2';\nimport digitaloceanSpaces from './s3/digitalocean-spaces';\nimport neonObjectStorage from './s3/neon-object-storage';\nimport scaleway from './s3/scaleway';\nimport supabase from './s3/supabase';\nimport uploadcare from './uploadcare';\n\n/**\n * @import { MediaLibraryService } from '$lib/types/private';\n * @import { CloudMediaLibraryName } from '$lib/types/public';\n */\n\n/**\n * List of all the supported cloud storage services.\n * @type {Record<string, MediaLibraryService>}\n */\nexport const allCloudStorageServices = {\n  aws_s3: awsS3,\n  azure_blob_storage: azureBlobStorage,\n  backblaze_b2: backblazeB2, // S3-compatible\n  bunny_storage: bunnyStorage, // S3-compatible\n  cloudflare_r2: cloudflareR2, // S3-compatible\n  cloudinary,\n  digitalocean_spaces: digitaloceanSpaces, // S3-compatible\n  neon_object_storage: neonObjectStorage, // S3-compatible\n  scaleway_object_storage: scaleway, // S3-compatible\n  supabase_storage: supabase, // S3-compatible\n  uploadcare,\n};\n\n/**\n * List of all supported cloud media library names.\n * @type {CloudMediaLibraryName[]}\n */\nexport const CLOUD_MEDIA_LIBRARY_NAMES = /** @type {any} */ (Object.keys(allCloudStorageServices));\n","import { getAssetByPath, isRelativePath } from '$lib/services/assets';\nimport { allAssetFolders } from '$lib/services/assets/folders';\nimport {\n  getAssetBlobURL,\n  getAssetPublicURL,\n  getAssetThumbnailURL,\n} from '$lib/services/assets/info';\nimport { getCustomComponentName } from '$lib/services/contents/fields/rich-text/components/definitions';\nimport { allCloudStorageServices } from '$lib/services/integrations/media-libraries/cloud';\nimport { getMergedLibraryOptions } from '$lib/services/integrations/media-libraries/cloud/cloudinary';\n\n/**\n * @import {\n * Entry,\n * InternalLocaleCode,\n * MediaFieldSource,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import { MediaField } from '$lib/types/public';\n */\n\nconst URL_REGEX = /^(?:https?|data|blob):/;\n\n/**\n * Get the base URL for assets stored in Cloudinary.\n * @param {MediaField} [fieldConfig] Field configuration.\n * @returns {string | undefined} Base URL or undefined if not applicable.\n */\nexport const getAssetBaseURL = (fieldConfig) => {\n  if (allCloudStorageServices.cloudinary?.isEnabled?.(fieldConfig)) {\n    const options = getMergedLibraryOptions(fieldConfig);\n\n    if (options.output_filename_only && options.config?.cloud_name) {\n      return `https://res.cloudinary.com/${options.config.cloud_name}`;\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Resolve the given image/file entry field value to the file it points to, without loading it.\n * @param {object} args Arguments.\n * @param {string} args.value Saved field value. It can be an absolute path, entry-relative path, or\n * a complete/external URL.\n * @param {Entry} [args.entry] Associated entry to be used to help locate an asset from a relative\n * path. Can be `undefined` when editing a new draft.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} [args.componentName] Custom editor component name for a field-level asset folder.\n * @param {MediaField} [args.fieldConfig] Field configuration.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Field key path for field-level media folders.\n * @param {InternalLocaleCode} [args.locale] Locale the value is referenced in, which tells which\n * locale’s entry file an entry-relative path is relative to. Default: the default locale.\n * @returns {MediaFieldSource | undefined} The URL of a file on an external location, or the asset\n * in the repository. `undefined` if the value is empty or the asset is not found.\n */\nexport const getMediaFieldSource = ({\n  value,\n  entry,\n  collectionName,\n  fileName,\n  componentName,\n  fieldConfig,\n  typedKeyPath,\n  locale,\n}) => {\n  if (!value) {\n    return undefined;\n  }\n\n  if (URL_REGEX.test(value)) {\n    return { url: value };\n  }\n\n  // If the value is a relative path, try to get the asset base URL from the field config. This is a\n  // special case for Cloudinary assets.\n  if (isRelativePath(value)) {\n    const assetBaseURL = getAssetBaseURL(fieldConfig);\n\n    if (assetBaseURL) {\n      return { url: `${assetBaseURL}/${value}` };\n    }\n  }\n\n  const asset = getAssetByPath({\n    value,\n    entry,\n    collectionName,\n    fileName,\n    componentName,\n    typedKeyPath,\n    locale,\n  });\n\n  return asset ? { asset } : undefined;\n};\n\n/**\n * Get the URL of the given media field source.\n * @param {MediaFieldSource | undefined} source Source.\n * @param {boolean} [thumbnail] Whether to use a thumbnail of the image.\n * @returns {Promise<string | undefined>} Blob URL or public URL that can be used in the app UI.\n */\nconst getSourceURL = async (source, thumbnail = false) => {\n  const { url, asset } = source ?? {};\n\n  if (url) {\n    return url;\n  }\n\n  if (!asset) {\n    return undefined;\n  }\n\n  return (\n    (thumbnail ? await getAssetThumbnailURL(asset) : await getAssetBlobURL(asset)) ??\n    getAssetPublicURL(asset)\n  );\n};\n\n/**\n * Get the blob or public URL from the given image/file entry field value.\n * @param {object} args Arguments.\n * @param {string} args.value Saved field value. It can be an absolute path, entry-relative path, or\n * a complete/external URL.\n * @param {Entry} [args.entry] Associated entry to be used to help locate an asset from a relative\n * path. Can be `undefined` when editing a new draft.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} [args.componentName] Custom editor component name for a field-level asset folder.\n * @param {MediaField} [args.fieldConfig] Field configuration.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Field key path for field-level media folders.\n * @param {InternalLocaleCode} [args.locale] Locale the value is referenced in, which tells which\n * locale’s entry file an entry-relative path is relative to. Default: the default locale.\n * @param {boolean} [args.thumbnail] Whether to use a thumbnail of the image.\n * @returns {Promise<string | undefined>} Blob URL or public URL that can be used in the app UI.\n */\nexport const getMediaFieldURL = async ({ thumbnail = false, ...args }) =>\n  getSourceURL(getMediaFieldSource(args), thumbnail);\n\n/**\n * Resolve a file referenced in a RichText field preview to the file it points to, without loading\n * it. The file may come from the preview of a custom editor component, whose fields can have their\n * own media folders. As the preview doesn’t tell which component a file comes from, the media\n * folders of the given components are searched if the file is not found for the RichText field\n * itself.\n * @param {object} args Arguments.\n * @param {string} args.value File path or URL, e.g. an image `src`.\n * @param {Entry} [args.entry] Associated entry. Can be `undefined` when editing a new draft.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Key path of the RichText field.\n * @param {string[]} args.componentNames Names or IDs of the components the field can contain.\n * @param {InternalLocaleCode} [args.locale] Locale the value is referenced in. Default: the default\n * locale.\n * @returns {MediaFieldSource | undefined} The URL of a file on an external location, or the asset\n * in the repository. `undefined` if the value is empty or the asset is not found.\n */\nexport const getRichTextMediaSource = ({ componentNames, ...args }) => {\n  const customComponentNames = componentNames.map(getCustomComponentName).filter(Boolean);\n\n  return (\n    getMediaFieldSource(args) ??\n    allAssetFolders.current\n      .values()\n      .filter(\n        ({ componentName, typedKeyPath }) =>\n          !!typedKeyPath && customComponentNames.includes(componentName),\n      )\n      .map(({ componentName, typedKeyPath }) =>\n        getMediaFieldSource({ ...args, componentName, typedKeyPath }),\n      )\n      .find(Boolean)\n  );\n};\n\n/**\n * Get the blob or public URL of an image, video or other file in a RichText field preview. See\n * {@link getRichTextMediaSource} for how the file is located.\n * @param {object} args Arguments.\n * @param {string} args.value File path or URL, e.g. an image `src`.\n * @param {Entry} [args.entry] Associated entry. Can be `undefined` when editing a new draft.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Key path of the RichText field.\n * @param {string[]} args.componentNames Names or IDs of the components the field can contain.\n * @param {InternalLocaleCode} [args.locale] Locale the value is referenced in. Default: the default\n * locale.\n * @returns {Promise<string | undefined>} Blob URL or public URL that can be used in the app UI.\n */\nexport const getRichTextMediaURL = async (args) => getSourceURL(getRichTextMediaSource(args));\n","import { cmsConfig } from '$lib/services/config';\n\n/**\n * @import { TextEditorMode, TextEditorNodeType } from '@sveltia/ui';\n * @import {\n * MarkdownField,\n * RichTextEditorButtonName,\n * RichTextEditorComponentName,\n * RichTextEditorMode,\n * RichTextField,\n * RichTextValueFormat,\n * } from '$lib/types/public';\n */\n\n/**\n * Regular expression to match the component name prefix in the key path, e.g. `body:c12:`.\n * @type {RegExp}\n */\nexport const COMPONENT_NAME_PREFIX_REGEX = /^.+?:\\w+:/;\n\n/**\n * Remove the component name prefix from a key path, e.g. `body:c12:src` → `src`, to look up\n * a rich text editor component’s field in the component definition. A key path without the prefix\n * is returned as is.\n * @param {string} keyPath Key path.\n * @returns {string} Key path without the prefix.\n */\nexport const stripComponentNamePrefix = (keyPath) =>\n  keyPath.replace(COMPONENT_NAME_PREFIX_REGEX, '');\n\n/**\n * The default `modes` property options.\n * @type {RichTextEditorMode[]}\n */\nexport const DEFAULT_MODES = ['rich_text', 'raw'];\n\n/**\n * Key is a name used in Netlify/Decap CMS, value is a name used in Sveltia UI.\n * @type {Record<RichTextEditorMode, TextEditorMode>}\n */\nexport const NODE_NAME_MAP = {\n  rich_text: 'rich-text',\n  raw: 'plain-text',\n};\n\n/**\n * Buttons that format text within a paragraph, the only ones a field with `multiline: false` can\n * use. The other buttons format a whole block.\n * @type {RichTextEditorButtonName[]}\n */\nexport const INLINE_BUTTONS = ['bold', 'italic', 'underline', 'strikethrough', 'code', 'link'];\n\n/**\n * Buttons that format a whole block, which a field with `multiline: false` can’t use.\n * @type {RichTextEditorButtonName[]}\n */\nexport const BLOCK_BUTTONS = [\n  'heading-one',\n  'heading-two',\n  'heading-three',\n  'heading-four',\n  'heading-five',\n  'heading-six',\n  'bulleted-list',\n  'numbered-list',\n  'task-list',\n  'quote',\n  'align',\n];\n\n/**\n * Buttons only available with the `html` format, as Markdown has no syntax for them. They’re not\n * enabled by default: they have to be listed in the `buttons` option.\n * @type {RichTextEditorButtonName[]}\n */\nexport const HTML_ONLY_BUTTONS = ['underline', 'align'];\n\n/**\n * Buttons not enabled by default: the HTML-only ones, and `task-list`, as task lists are a GitHub\n * Flavored Markdown extension that not every Markdown renderer supports.\n * @type {RichTextEditorButtonName[]}\n */\nexport const OPTIONAL_BUTTONS = [...HTML_ONLY_BUTTONS, 'task-list'];\n\n/**\n * The default `buttons` property options: all the buttons but the optional ones.\n * @type {RichTextEditorButtonName[]}\n */\nexport const DEFAULT_BUTTONS = [...INLINE_BUTTONS, ...BLOCK_BUTTONS].filter(\n  (name) => !OPTIONAL_BUTTONS.includes(name),\n);\n\n/**\n * Key is a name used in Netlify/Decap CMS, value is a name used in Sveltia UI. The built-in\n * `code-block`, `table` and `hr` components are implemented as buttons in Sveltia UI.\n * @type {Record<RichTextEditorButtonName | 'code-block' | 'table' | 'hr', TextEditorNodeType>}\n */\nexport const BUTTON_NAME_MAP = {\n  bold: 'bold',\n  italic: 'italic',\n  underline: 'underline',\n  strikethrough: 'strikethrough',\n  code: 'code',\n  link: 'link',\n  'heading-one': 'heading-1',\n  'heading-two': 'heading-2',\n  'heading-three': 'heading-3',\n  'heading-four': 'heading-4',\n  'heading-five': 'heading-5',\n  'heading-six': 'heading-6',\n  'bulleted-list': 'bulleted-list',\n  'numbered-list': 'numbered-list',\n  'task-list': 'task-list',\n  quote: 'blockquote',\n  align: 'align',\n  'code-block': 'code-block',\n  table: 'table',\n  hr: 'horizontal-rule',\n};\n\n/**\n * Built-in editor components implemented as buttons in Sveltia UI rather than as editor components.\n * They’re all blocks.\n * @type {('code-block' | 'table' | 'hr')[]}\n */\nexport const BUTTON_COMPONENTS = ['code-block', 'table', 'hr'];\n\n/**\n * Built-in editor component names enabled by default. `code-block` is a button in Sveltia CMS, but\n * it’s included here for consistency with the Netlify/Decap CMS API. The `table` and `hr`\n * components, also buttons, are left out: they have to be enabled with the `editor_components`\n * option.\n * @type {RichTextEditorComponentName[]}\n */\nexport const BUILTIN_COMPONENTS = ['code-block', 'image'];\n\n/**\n * Get the format of the given field’s value, falling back to the `field_defaults.richtext` option.\n * Only the RichText field type supports the `format` option, as the Markdown field type, its alias,\n * always holds Markdown.\n * @param {MarkdownField | RichTextField} fieldConfig Field configuration.\n * @returns {RichTextValueFormat} Format.\n */\nexport const getValueFormat = (fieldConfig) => {\n  if (fieldConfig.widget !== 'richtext') {\n    return 'markdown';\n  }\n\n  const { format = cmsConfig.current?.field_defaults?.richtext?.format } = fieldConfig;\n\n  return format === 'html' ? 'html' : 'markdown';\n};\n","import { customComponentRegistry } from '$lib/services/api/registries';\nimport { cmsConfig } from '$lib/services/config';\nimport {\n  BUILTIN_COMPONENTS,\n  BUTTON_COMPONENTS,\n  BUTTON_NAME_MAP,\n  COMPONENT_NAME_PREFIX_REGEX,\n} from '$lib/services/contents/fields/rich-text';\nimport {\n  getComponentDef,\n  getImageComponentId,\n} from '$lib/services/contents/fields/rich-text/components/definitions';\nimport { supportsHTML } from '$lib/services/contents/fields/rich-text/components/utils';\n\n/**\n * @import { TextEditorNodeType } from '@sveltia/ui';\n * @import { ResolvedEditorComponentDefinition } from '$lib/types/private';\n * @import {\n * MarkdownField,\n * RichTextEditorButtonName,\n * RichTextField,\n * RichTextValueFormat,\n * } from '$lib/types/public';\n */\n\n/**\n * Get the names of the editor components enabled for the given RichText/Markdown field. The\n * `editor_components` option defaults to the field defaults, then all the built-in and custom\n * components. The `image` component is replaced with `linked-image` unless the `linked_images`\n * option is disabled, and with an uncaptioned variant if the `captioned_images` option is disabled,\n * e.g. `uncaptioned-linked-image`.\n * @param {MarkdownField | RichTextField} fieldConfig Field configuration.\n * @returns {string[]} Component names.\n */\nexport const getEditorComponentNames = (fieldConfig) => {\n  const defaultConfig = cmsConfig.current?.field_defaults?.richtext ?? {};\n\n  const {\n    editor_components: editorComponents = defaultConfig.editor_components ?? [\n      ...BUILTIN_COMPONENTS,\n      ...customComponentRegistry.keys(),\n    ],\n    linked_images: linked = defaultConfig.linked_images ?? true,\n    captioned_images: captioned = defaultConfig.captioned_images ?? true,\n  } = fieldConfig;\n\n  return editorComponents.map((name) =>\n    name === 'image' ? getImageComponentId({ linked, captioned }) : name,\n  );\n};\n\n/**\n * Get the definitions of the editor components enabled for the given RichText/Markdown field,\n * leaving out any unknown component.\n * @param {MarkdownField | RichTextField} fieldConfig Field configuration.\n * @returns {ResolvedEditorComponentDefinition[]} Component definitions.\n */\nexport const getEditorComponentDefs = (fieldConfig) =>\n  /** @type {ResolvedEditorComponentDefinition[]} */ (\n    getEditorComponentNames(fieldConfig)\n      .map((name) => getComponentDef(name))\n      .filter((def) => !!def)\n  );\n\n/**\n * Get the toolbar buttons of a rich text editor. The `code-block`, `table` and `hr` components are\n * implemented as buttons, which are added when the components are enabled. Unknown button names\n * are left out.\n * @param {RichTextEditorButtonName[]} buttonNames Names of the buttons in the `buttons` option.\n * @param {string[]} componentNames Names of the enabled editor components.\n * @returns {TextEditorNodeType[]} Sveltia UI button names.\n */\nexport const getToolbarButtons = (buttonNames, componentNames) =>\n  [...buttonNames, ...BUTTON_COMPONENTS.filter((name) => componentNames.includes(name))]\n    // @ts-ignore\n    .map((name) => BUTTON_NAME_MAP[name])\n    .filter(Boolean);\n\n/**\n * Get the `allow_nested_components` option of the given RichText/Markdown field, falling back to\n * the field defaults, then `true`. A rich text editor within an editor component takes the option\n * from its root field, so pass that field’s configuration.\n * @param {MarkdownField | RichTextField | undefined} fieldConfig Field configuration.\n * @returns {boolean | 'exclude_self'} Option value.\n */\nexport const resolveAllowNestedComponents = (fieldConfig) =>\n  fieldConfig?.allow_nested_components ??\n  cmsConfig.current?.field_defaults?.richtext?.allow_nested_components ??\n  true;\n\n/**\n * Get the name of the root field from the key path of a field within an editor component.\n * @param {string} keyPath Key path, e.g. `body:c55:content`.\n * @returns {string} Field name, e.g. `body`.\n */\nexport const getRootFieldName = (keyPath) => /** @type {string} */ (keyPath.match(/^[^:]+/)?.[0]);\n\n/**\n * Get the definitions of the editor components available in a rich text editor.\n * @param {object} args Arguments.\n * @param {MarkdownField | RichTextField} args.fieldConfig Field configuration.\n * @param {RichTextValueFormat} args.format Value format. Only the components with HTML syntax can\n * be used in HTML.\n * @param {boolean | 'exclude_self'} args.allowNestedComponents Resolved `allow_nested_components`\n * option. See {@link resolveAllowNestedComponents}.\n * @param {boolean} args.inEditorComponent Whether the editor is within an editor component.\n * @param {string[]} args.parentComponentNames IDs of the editor components the editor is within.\n * @returns {ResolvedEditorComponentDefinition[]} Component definitions.\n */\nexport const getAvailableComponentDefs = ({\n  fieldConfig,\n  format,\n  allowNestedComponents,\n  inEditorComponent,\n  parentComponentNames,\n}) => {\n  if (inEditorComponent && !allowNestedComponents) {\n    return [];\n  }\n\n  return (\n    getEditorComponentDefs(fieldConfig)\n      .filter((def) => format !== 'html' || supportsHTML(def))\n      // Compare the definition IDs, because the parent component names are the IDs, which are\n      // prefixed for custom components, e.g. `x-youtube`\n      .filter(\n        (def) => allowNestedComponents !== 'exclude_self' || !parentComponentNames.includes(def.id),\n      )\n  );\n};\n\n/**\n * Get the keys of the extra values that belong to the editor components of a rich text field but\n * are no longer present in the editor. Left in place, they would trigger validation errors when the\n * entry is saved.\n * @param {Record<string, any>} extraValues Extra values of the locale.\n * @param {string} keyPath Key path of the rich text field.\n * @param {(prefix: string) => boolean} isPresent Function that tells whether the component with\n * the given key path prefix, e.g. `body:c12:`, is present in the editor.\n * @returns {string[]} Keys.\n */\nexport const getStaleExtraValueKeys = (extraValues, keyPath, isPresent) =>\n  Object.keys(extraValues).filter((key) => {\n    const [prefix] = key.match(COMPONENT_NAME_PREFIX_REGEX) ?? [];\n\n    return !!prefix?.startsWith(`${keyPath}:`) && !isPresent(prefix);\n  });\n","/**\n * Parse an HTML fragment into the content of a `<template>` element, which is inert: unlike an\n * element in the document, it doesn’t load the media or run the scripts and event handlers found in\n * the HTML, which comes from untrusted field values.\n * @param {string} value HTML.\n * @returns {HTMLTemplateElement} Template holding the parsed nodes.\n */\nexport const parseHTMLFragment = (value) => {\n  const template = document.createElement('template');\n\n  template.innerHTML = value;\n\n  return template;\n};\n\n/**\n * Parse the start tag of an element, e.g. `<img src=\"a.png\">`.\n * @param {string} tag Start tag.\n * @returns {Element} Element, without content.\n */\nexport const parseStartTag = (tag) =>\n  /** @type {Element} */ (parseHTMLFragment(tag).content.firstElementChild);\n\n/**\n * Serialize the start tag of an element parsed with {@link parseStartTag}. The serialization\n * escapes the attribute values as needed, but may differ from the original tag in formatting, e.g.\n * the quotes around attribute values.\n * @param {Element} element Element, without content.\n * @returns {string} Start tag.\n */\nexport const serializeStartTag = (element) => {\n  const { outerHTML } = element;\n  const endTag = `</${element.localName}>`;\n\n  // A void element like `<img>` has no end tag\n  return outerHTML.endsWith(endTag) ? outerHTML.slice(0, -endTag.length) : outerHTML;\n};\n\n/**\n * Check if a tag found in a Markdown or HTML text sits inside another tag, e.g. in an attribute\n * value as in `<a title='<img src=\"a.png\">'>`, where it’s text rather than an element. Such a tag\n * isn’t a reference, and must not be serialized again either, as that may change its quotes and\n * break out of the attribute value it’s in.\n * @param {string} value Markdown or HTML.\n * @param {number} index Position of the tag.\n * @returns {boolean} Result.\n */\nexport const isInsideTag = (value, index) => {\n  const start = value.lastIndexOf('<', index - 1);\n\n  // A `<` not followed by a letter, as in `a < b`, doesn’t start a tag\n  return (\n    index > 0 && start > value.lastIndexOf('>', index - 1) && /[a-z]/i.test(value[start + 1] ?? '')\n  );\n};\n","import { parseHTMLFragment } from '$lib/services/utils/html';\n\n/**\n * Attributes of a media element that can refer to a file, which may have to be resolved to a blob\n * URL in the preview, keyed by the tag name. `srcset` holds a list of URLs with descriptors.\n * @type {Record<string, string[]>}\n */\nexport const MEDIA_URL_ATTRIBUTES = {\n  img: ['src', 'srcset'],\n  source: ['src', 'srcset'],\n  video: ['src', 'poster'],\n  audio: ['src'],\n};\n\n/**\n * Names of the media elements, regardless of their attributes.\n */\nconst MEDIA_TAG_NAMES = Object.keys(MEDIA_URL_ATTRIBUTES);\n\n/**\n * Selector for the media elements, regardless of their attributes.\n */\nexport const MEDIA_TAG_SELECTOR = MEDIA_TAG_NAMES.join(', ');\n\n/**\n * Regular expression pattern matching the name of a media element, to be used in a pattern\n * matching its tag.\n */\nexport const MEDIA_TAG_NAME_PATTERN = MEDIA_TAG_NAMES.join('|');\n\n/**\n * Regular expression pattern matching the start of a media tag in an HTML string.\n */\nconst MEDIA_TAG_PATTERN = `<(?:${MEDIA_TAG_NAME_PATTERN})[\\\\s/>]`;\n\n/**\n * Regular expression testing if an HTML string may contain a media element.\n */\nexport const MEDIA_TAG_REGEX = new RegExp(MEDIA_TAG_PATTERN, 'i');\n\n/**\n * Global version of {@link MEDIA_TAG_REGEX}, to count the media tags in a value.\n */\nexport const GLOBAL_MEDIA_TAG_REGEX = new RegExp(MEDIA_TAG_PATTERN, 'gi');\n\n/**\n * Prefix of the inert attribute a media URL attribute is moved to by {@link deferMediaURLs}, e.g.\n * `data-deferred-src` for `src`.\n */\nconst DEFERRED_ATTRIBUTE_PREFIX = 'data-deferred-';\n\n/**\n * Selector for the media elements that have a URL attribute, as written or deferred.\n */\nconst MEDIA_ELEMENT_SELECTOR = Object.entries(MEDIA_URL_ATTRIBUTES)\n  .flatMap(([tagName, names]) =>\n    names.flatMap((name) => [\n      `${tagName}[${name}]`,\n      `${tagName}[${DEFERRED_ATTRIBUTE_PREFIX}${name}]`,\n    ]),\n  )\n  .join(', ');\n\n/**\n * Selector for finding unprocessed media elements in the rendered HTML, used by the\n * `MutationObserver` to identify images, videos and audio that need to be processed (e.g. Converted\n * to `blob` URLs for local previews). The `data-processed` attribute is added to elements that have\n * already been processed to avoid reprocessing on subsequent mutations. An element can have its\n * URL attributes deferred with {@link deferMediaURLs}, or as written, e.g. in the DOM element\n * preview of a custom editor component.\n */\nexport const MEDIA_QUERY_SELECTOR = `:is(${MEDIA_ELEMENT_SELECTOR}):not([data-processed])`;\n\n/**\n * Get the media elements in a parsed HTML fragment, in document order.\n * @param {HTMLTemplateElement} template Template holding the parsed nodes, as returned by\n * {@link parseHTMLFragment}.\n * @returns {Element[]} Elements.\n */\nexport const getMediaElements = (template) => [\n  ...template.content.querySelectorAll(MEDIA_TAG_SELECTOR),\n];\n\n/**\n * Move the URL attributes of the media elements in the given HTML, e.g. an image `src`, to inert\n * attributes like `data-deferred-src`, so the browser doesn’t load a file as soon as the HTML is\n * inserted into the document. A path like `/images/photo.jpg` refers to the file in the repository,\n * which may not have been deployed to the site, or even saved yet, so requesting it from the CMS\n * origin would be a wasted request, often failing with 404. The attributes are set again by\n * {@link resolveMediaURLs} once the paths are resolved, leaving any URL the CMS can’t resolve, like\n * an external one, as is. Any deferred attribute already in the HTML is removed, so the content\n * can’t sneak in a URL that has bypassed sanitization.\n * @param {string} html HTML, which should be sanitized beforehand if needed.\n * @returns {string} HTML with the URL attributes deferred.\n */\nexport const deferMediaURLs = (html) => {\n  // Avoid parsing the HTML again if there’s no media element\n  if (!MEDIA_TAG_REGEX.test(html)) {\n    return html;\n  }\n\n  // The content of a template is inert, so nothing is loaded here\n  const template = parseHTMLFragment(html);\n\n  getMediaElements(template).forEach((element) => {\n    MEDIA_URL_ATTRIBUTES[element.localName].forEach((name) => {\n      const value = element.getAttribute(name);\n\n      element.removeAttribute(`${DEFERRED_ATTRIBUTE_PREFIX}${name}`);\n\n      if (value !== null) {\n        element.setAttribute(`${DEFERRED_ATTRIBUTE_PREFIX}${name}`, value);\n        element.removeAttribute(name);\n      }\n    });\n  });\n\n  return template.innerHTML;\n};\n\n/**\n * Parse the value of a `srcset` attribute into image candidates. Like browsers, a URL is a run of\n * non-whitespace characters, so it can contain a comma, as in a `data:` URL, unless the comma ends\n * it; the descriptor, e.g. `2x` or `800w`, follows it up to the next comma.\n * @param {string} srcset Attribute value.\n * @returns {{ url: string, descriptor: string }[]} Candidates.\n * @see https://html.spec.whatwg.org/multipage/images.html#parsing-a-srcset-attribute\n */\nexport const parseSrcset = (srcset) => {\n  /** @type {{ url: string, descriptor: string }[]} */\n  const candidates = [];\n  let position = 0;\n\n  for (;;) {\n    // Skip the whitespace and commas between candidates\n    const urlStart = srcset.slice(position).search(/[^\\s,]/);\n\n    if (urlStart === -1) {\n      break;\n    }\n\n    position += urlStart;\n\n    const url = /** @type {string} */ (srcset.slice(position).match(/^\\S+/)?.[0]);\n\n    position += url.length;\n\n    if (url.endsWith(',')) {\n      // A URL ending with a comma has no descriptor\n      candidates.push({ url: url.replace(/,+$/, ''), descriptor: '' });\n    } else {\n      const descriptorEnd = srcset.indexOf(',', position);\n      const end = descriptorEnd === -1 ? srcset.length : descriptorEnd;\n\n      candidates.push({ url, descriptor: srcset.slice(position, end).trim() });\n      position = end;\n    }\n  }\n\n  return candidates;\n};\n\n/**\n * Serialize image candidates into the value of a `srcset` attribute, the reverse of\n * {@link parseSrcset}. Whitespace in a URL is percent-encoded, as it would otherwise end the URL.\n * @param {{ url: string, descriptor: string }[]} candidates Candidates.\n * @returns {string} Attribute value.\n */\nexport const stringifySrcset = (candidates) =>\n  candidates\n    .map(({ url, descriptor }) =>\n      [url.replace(/\\s/g, encodeURIComponent), descriptor].filter(Boolean).join(' '),\n    )\n    .join(', ');\n\n/**\n * Replace the URLs in the candidates of a `srcset` attribute.\n * @param {{ url: string, descriptor: string }[]} candidates Candidates, as returned by\n * {@link parseSrcset}.\n * @param {(url: string, index: number) => string | null | undefined} getNewURL Function to get the\n * new URL for the URL of the candidate at the given index: a new URL to replace it with, `null` to\n * remove the candidate, or `undefined` to leave it as is.\n * @returns {string | null | undefined} New attribute value; `null` if all the candidates are\n * removed, so is the attribute; `undefined` if nothing is replaced.\n */\nexport const mapSrcset = (candidates, getNewURL) => {\n  let changed = false;\n\n  const newCandidates = candidates.flatMap((candidate, index) => {\n    const url = getNewURL(candidate.url, index);\n\n    if (url === null) {\n      changed = true;\n\n      return [];\n    }\n\n    if (url !== undefined && url !== candidate.url) {\n      changed = true;\n\n      return [{ ...candidate, url }];\n    }\n\n    return [candidate];\n  });\n\n  if (!changed) {\n    return undefined;\n  }\n\n  return newCandidates.length ? stringifySrcset(newCandidates) : null;\n};\n\n/**\n * Resolve the file paths in the URL attributes of the given media element, e.g. an image `src`, a\n * video `poster` or each URL in a `srcset`, so that a file that hasn’t been published or saved yet\n * is displayed in the preview. A path that can’t be resolved is left as is. An attribute deferred\n * with {@link deferMediaURLs} is set again, once all of them have been resolved, so an image with\n * both a `src` and a `srcset` doesn’t start loading the former. Once a `<source>` of a video or\n * audio element is updated, the media is loaded again, as the element doesn’t pick up the change\n * by itself.\n * @param {Element} element Media element, matching {@link MEDIA_QUERY_SELECTOR}.\n * @param {(value: string) => Promise<string | undefined>} resolve Function resolving a path to a\n * URL, if any.\n * @returns {Promise<void>} Promise resolving once all the attributes have been updated.\n */\nexport const resolveMediaURLs = async (element, resolve) => {\n  const names = MEDIA_URL_ATTRIBUTES[element.localName] ?? [];\n\n  /**\n   * Resolve a path, leaving it as is if it can’t be resolved, e.g. because the file can’t be\n   * retrieved, so the other URLs are still resolved.\n   * @param {string} value Path.\n   * @returns {Promise<string>} URL.\n   */\n  const resolveURL = async (value) => {\n    try {\n      return (await resolve(value)) ?? value;\n    } catch {\n      return value;\n    }\n  };\n\n  /**\n   * Resolve the URLs in an attribute value.\n   * @param {string} name Attribute name.\n   * @param {string} value Attribute value.\n   * @returns {Promise<string>} Value with the URLs resolved.\n   */\n  const resolveValue = async (name, value) => {\n    if (!value) {\n      return value;\n    }\n\n    if (name !== 'srcset') {\n      return resolveURL(value);\n    }\n\n    const candidates = parseSrcset(value);\n    const urls = await Promise.all(candidates.map(({ url }) => resolveURL(url)));\n\n    // Leave the attribute as written unless a URL has been resolved\n    return mapSrcset(candidates, (_url, index) => urls[index]) ?? value;\n  };\n\n  const updates = await Promise.all(\n    names.map(async (name) => {\n      const deferredName = `${DEFERRED_ATTRIBUTE_PREFIX}${name}`;\n      const deferred = element.hasAttribute(deferredName);\n      const value = element.getAttribute(deferred ? deferredName : name);\n\n      return value === null\n        ? undefined\n        : { name, deferredName, deferred, value, url: await resolveValue(name, value) };\n    }),\n  );\n\n  let updated = false;\n\n  updates.forEach((update) => {\n    if (!update) {\n      return;\n    }\n\n    const { name, deferredName, deferred, value, url } = update;\n\n    if (deferred) {\n      element.removeAttribute(deferredName);\n    }\n\n    if (deferred || url !== value) {\n      element.setAttribute(name, url);\n      updated = true;\n    }\n  });\n\n  const { localName, parentElement: parent } = element;\n\n  if (updated && localName === 'source' && /^(?:audio|video)$/.test(parent?.localName ?? '')) {\n    /** @type {HTMLMediaElement} */ (parent).load();\n  }\n};\n","import { getImagePattern } from '$lib/services/contents/fields/rich-text/constants';\nimport {\n  getMediaElements,\n  mapSrcset,\n  MEDIA_TAG_NAME_PATTERN,\n  MEDIA_TAG_REGEX,\n  MEDIA_URL_ATTRIBUTES,\n  parseSrcset,\n} from '$lib/services/contents/fields/rich-text/previews/media-urls';\nimport {\n  isInsideTag,\n  parseHTMLFragment,\n  parseStartTag,\n  serializeStartTag,\n} from '$lib/services/utils/html';\n\n/**\n * @import { RichTextValueFormat } from '$lib/types/public';\n */\n\n/**\n * Regular expression to match a Markdown image, capturing its alt text and source as the `alt` and\n * `src` groups. It’s the same pattern the rich text editor’s image component goes by, so the two\n * agree on what an image is: see `IMAGE_REGEX` in `rich-text/constants`, which also tells how it\n * matches in linear time on untrusted Markdown.\n */\nexport const MARKDOWN_IMAGE_REGEX = new RegExp(getImagePattern(), 'g');\n\n/**\n * Pattern matching the start tag of a media element, e.g. `<img src=\"a.png\">` or `<video\n * poster=\"a.jpg\">`, written as raw HTML in a Markdown body. Attribute values can be quoted with\n * either kind of quotes, and contain `>` when quoted.\n *\n * The pattern runs on untrusted Markdown, so it’s written to match in linear time: neither an\n * attribute value nor anything else in the tag can contain `<`, so a failed match at one `<`\n * doesn’t read the text after the next one again. A tag with `<` in an attribute value, as in\n * `alt=\"a<b\"`, is missed, which is rare enough.\n */\nconst MEDIA_START_TAG_PATTERN = [\n  `<(?:${MEDIA_TAG_NAME_PATTERN})(?=[\\\\s/>])`,\n  '(?:[^<>\"\\']|\"[^\"<]*\"|\\'[^\\'<]*\\')*>',\n].join('');\n\n/**\n * Regular expression to match either a Markdown image, capturing its source as the first group, or\n * the start tag of a media element written as raw HTML, which Markdown allows, captured as the\n * second group. Both kinds are displayed in the preview, so both refer to the files.\n */\nexport const MARKDOWN_MEDIA_REGEX = new RegExp(\n  `${MARKDOWN_IMAGE_REGEX.source}|(?<tag>${MEDIA_START_TAG_PATTERN})`,\n  'gi',\n);\n\n/**\n * Where a media URL is written: as the source of a Markdown image, or in an attribute of an HTML\n * media element, including one written as raw HTML in a Markdown body.\n * @typedef {'markdown' | 'html'} MediaSourceSyntax\n */\n\n/**\n * Media URL parsed from a field value, or from a Markdown image source or an HTML attribute in it.\n * The `#` starting a fragment can’t be told from one in a file name written unencoded, e.g. `photo\n * #1.jpg`, so the URL is split at its first `#`, and a reader decides which of the two forms to\n * go by: the whole URL, or the path without the fragment.\n * @typedef {object} MediaSource\n * @property {string} url URL as written, without the angle brackets of a Markdown image source.\n * @property {string} path URL up to its first `#`, or the whole URL if it has none, or starts with\n * one, as a fragment alone points at no file.\n * @property {string} fragment Rest of the URL from its first `#`, or an empty string.\n * @property {MediaSourceSyntax} [syntax] Where the URL is written, unless it’s a field value as a\n * whole, as in an Image or File field.\n * @property {boolean} bracketed Whether the URL is a Markdown image source wrapped in angle\n * brackets, which allow spaces in it, e.g. `<my image.png>`.\n */\n\n/**\n * Parse a media URL.\n * @param {string} source Field value, Markdown image source as written, including any angle\n * brackets, or HTML attribute value with the character references decoded.\n * @param {MediaSourceSyntax} [syntax] Where the URL is written, unless it’s a field value as a\n * whole.\n * @returns {MediaSource} Parsed URL.\n */\nexport const parseMediaSource = (source, syntax) => {\n  const bracketed =\n    syntax === 'markdown' && source.length > 2 && source.startsWith('<') && source.endsWith('>');\n\n  const url = bracketed ? source.slice(1, -1) : source;\n  const fragmentIndex = url.indexOf('#');\n  const path = fragmentIndex > 0 ? url.slice(0, fragmentIndex) : url;\n\n  return { url, path, fragment: url.slice(path.length), syntax, bracketed };\n};\n\n/**\n * Function called for each media URL found in a value, returning a new URL to replace it with,\n * `null` to remove it, or `undefined` to leave it as is. It’s given the URL, and the URL parsed\n * along with where it’s written.\n * @typedef {(url: string, source: MediaSource) => string | null | undefined} MediaURLCallback\n */\n\n/**\n * Pass each URL in the URL attributes of a media element to the given callback, e.g. an image\n * `src`, a video `poster` or each URL in a `srcset`, and update the attributes with the result. An\n * attribute left with no URL is removed. The attributes are read with the character references\n * decoded, e.g. `a&amp;b.jpg` as `a&b.jpg`, the same as the file name they refer to. An empty URL\n * is skipped.\n * @param {Element} element Media element.\n * @param {MediaURLCallback} callback Callback.\n * @returns {boolean} Whether any attribute has been changed.\n */\nexport const updateMediaElementURLs = (element, callback) => {\n  let updated = false;\n\n  MEDIA_URL_ATTRIBUTES[element.localName].forEach((name) => {\n    const value = element.getAttribute(name);\n\n    if (!value) {\n      return;\n    }\n\n    if (name !== 'srcset') {\n      const url = callback(value, parseMediaSource(value, 'html'));\n\n      if (url === null) {\n        element.removeAttribute(name);\n        updated = true;\n      } else if (url !== undefined && url !== value) {\n        element.setAttribute(name, url);\n        updated = true;\n      }\n\n      return;\n    }\n\n    const newValue = mapSrcset(parseSrcset(value), (url) =>\n      callback(url, parseMediaSource(url, 'html')),\n    );\n\n    if (newValue === undefined) {\n      return;\n    }\n\n    if (newValue === null) {\n      element.removeAttribute(name);\n    } else {\n      element.setAttribute(name, newValue);\n    }\n\n    updated = true;\n  });\n\n  return updated;\n};\n\n/**\n * Pass each URL in the start tag of a media element written as raw HTML in a Markdown body, as\n * matched by {@link MARKDOWN_MEDIA_REGEX}, to the given callback, and update the parsed element\n * with the result. A tag sitting inside another tag isn’t a media element.\n * @param {object} args Arguments.\n * @param {string} args.value Markdown body.\n * @param {string} args.tag Start tag found in the body.\n * @param {number} args.index Position of the tag in the body.\n * @param {MediaURLCallback} args.callback Callback.\n * @returns {Element | undefined} Parsed element with the URLs updated, to be serialized with\n * `serializeStartTag()` as needed, or `undefined` if the tag is left as is, because it sits inside\n * another tag or none of its URLs is changed.\n */\nexport const rewriteMediaStartTag = ({ value, tag, index, callback }) => {\n  if (isInsideTag(value, index)) {\n    return undefined;\n  }\n\n  const element = parseStartTag(tag);\n\n  return updateMediaElementURLs(element, callback) ? element : undefined;\n};\n\n/**\n * Pass each media URL in a Markdown body to the given callback, and replace it with the result: the\n * source of a Markdown image, or a URL attribute of a media element written as raw HTML. Only the\n * URL within each image or tag is replaced, so the same file name mentioned anywhere else in the\n * text, or a source whose name contains another’s, e.g. `hero-image.png` for `image.png`, isn’t\n * hit. A tag is serialized again only if one of its URLs is replaced.\n * @param {string} value Markdown body.\n * @param {MediaURLCallback} callback Callback. Removing a URL isn’t supported here, so `null`\n * leaves it as is.\n * @returns {string} New body.\n */\nconst updateMarkdownMediaURLs = (value, callback) =>\n  value.replace(MARKDOWN_MEDIA_REGEX, (markup, ...args) => {\n    /** @type {Record<string, string | undefined>} */\n    const { alt = '', src, tag } = args.at(-1);\n    /** @type {number} */\n    const offset = args.at(-3);\n\n    if (tag !== undefined) {\n      const element = rewriteMediaStartTag({\n        value,\n        tag,\n        index: offset,\n        /**\n         * Leave a URL as is rather than remove it.\n         * @param {string} url URL.\n         * @param {MediaSource} source Parsed URL.\n         * @returns {string | undefined} New URL.\n         */\n        callback: (url, source) => callback(url, source) ?? undefined,\n      });\n\n      return element ? serializeStartTag(element) : markup;\n    }\n\n    const source = /** @type {string} */ (src);\n\n    // An image without a source, e.g. `![a]()`, refers to no file\n    if (!source) {\n      return markup;\n    }\n\n    const parsed = parseMediaSource(source, 'markdown');\n    const url = callback(parsed.url, parsed);\n\n    if (typeof url !== 'string') {\n      return markup;\n    }\n\n    // The source comes right after `![`, the alt text and `](`\n    const start = alt.length + 4;\n    const newSource = parsed.bracketed ? `<${url}>` : url;\n\n    return `${markup.slice(0, start)}${newSource}${markup.slice(start + source.length)}`;\n  });\n\n/**\n * Pass each media URL in an HTML body to the given callback, and replace it with the result. The\n * HTML is parsed rather than matched with a regular expression, so a tag in a comment, an attribute\n * value or a `<script>` element isn’t taken for a media element. The result is serialized again,\n * so a new URL is escaped as needed, and the same file name mentioned anywhere else in the HTML,\n * e.g. in a link, isn’t hit. The serialization may differ from the original in formatting, e.g. the\n * quotes around attribute values, so the original is returned as is if no URL is replaced.\n * @param {string} value HTML body.\n * @param {MediaURLCallback} callback Callback. A URL can also be removed.\n * @returns {string} New body.\n */\nconst updateHTMLMediaURLs = (value, callback) => {\n  // Avoid parsing the HTML if there’s no media element\n  if (!MEDIA_TAG_REGEX.test(value)) {\n    return value;\n  }\n\n  const template = parseHTMLFragment(value);\n  let updated = false;\n\n  getMediaElements(template).forEach((element) => {\n    updated = updateMediaElementURLs(element, callback) || updated;\n  });\n\n  return updated ? template.innerHTML : value;\n};\n\n/**\n * Pass each media URL in a Markdown or RichText field value to the given callback, and replace it\n * with the result. See {@link MARKDOWN_MEDIA_REGEX} and `MEDIA_URL_ATTRIBUTES` for what’s a media\n * URL.\n * @param {string} value Field value.\n * @param {RichTextValueFormat} format Value format, as returned by `getValueFormat()`.\n * @param {MediaURLCallback} callback Callback.\n * @returns {string} New value, or the original one if nothing is replaced.\n */\nexport const updateRichTextMediaURLs = (value, format, callback) =>\n  format === 'html'\n    ? updateHTMLMediaURLs(value, callback)\n    : updateMarkdownMediaURLs(value, callback);\n\n/**\n * Get the media URLs in a Markdown or RichText field value, without duplicates.\n * @param {string} value Field value.\n * @param {RichTextValueFormat} format Value format, as returned by `getValueFormat()`.\n * @returns {string[]} URLs, in the order found.\n */\nexport const getRichTextMediaSources = (value, format) => {\n  /** @type {Set<string>} */\n  const sources = new Set();\n\n  updateRichTextMediaURLs(value, format, (url) => {\n    sources.add(url);\n\n    return undefined;\n  });\n\n  return [...sources];\n};\n\n/**\n * Replace the media URLs in a Markdown or RichText field value.\n * @param {string} value Field value.\n * @param {Map<string, string | undefined>} newSources New URLs keyed by the current ones, as\n * returned by {@link getRichTextMediaSources}. A URL that’s missing or mapped to `undefined` is\n * left as is.\n * @param {RichTextValueFormat} format Value format, as returned by `getValueFormat()`.\n * @returns {string} New value.\n */\nexport const replaceRichTextMediaSources = (value, newSources, format) =>\n  [...newSources.values()].some((newSource) => newSource !== undefined)\n    ? updateRichTextMediaURLs(value, format, (url) => newSources.get(url))\n    : value;\n","/* eslint-disable no-continue */\n/* eslint-disable no-restricted-syntax */\n\nimport { getMediaFieldSource, getRichTextMediaSource } from '$lib/services/assets/media-field';\nimport { cmsConfig } from '$lib/services/config';\nimport { allEntries } from '$lib/services/contents';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getCollectionFilesByEntry } from '$lib/services/contents/collection/files';\nimport { getAssociatedCollections } from '$lib/services/contents/entry/collections';\nimport { getField, getTypedKeyPath } from '$lib/services/contents/entry/fields';\nimport { MEDIA_FIELD_TYPES, RICH_TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getValueFormat } from '$lib/services/contents/fields/rich-text';\nimport { getEditorComponentNames } from '$lib/services/contents/fields/rich-text/options';\nimport {\n  getRichTextMediaSources,\n  MARKDOWN_MEDIA_REGEX,\n  parseMediaSource,\n  updateRichTextMediaURLs,\n} from '$lib/services/contents/fields/rich-text/previews/media-sources';\nimport {\n  GLOBAL_MEDIA_TAG_REGEX,\n  MEDIA_TAG_REGEX,\n} from '$lib/services/contents/fields/rich-text/previews/media-urls';\nimport { decodeURIComponentSafely } from '$lib/services/utils/url';\n\n/**\n * @import {\n * Asset,\n * AssetReference,\n * Entry,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalLocaleCode,\n * MediaFieldSource,\n * } from '$lib/types/private';\n * @import { MediaSource } from '$lib/services/contents/fields/rich-text/previews/media-sources';\n * @import {\n * Field,\n * FieldKeyPath,\n * MarkdownField,\n * MediaField,\n * RichTextField,\n * } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} AssetReferenceTarget\n * @property {string} [url] Asset’s public, external or blob URL. A value holding the URL as is\n * refers to the asset, except for a blob URL, which a value can only refer to through the asset it\n * resolves to. Required unless {@link AssetReferenceTarget.asset} is given.\n * @property {Asset} [asset] Asset without a URL to compare values with, as in an entry-relative\n * folder. A value refers to it when it resolves to the asset, which doesn’t require the asset to\n * have been loaded, unlike a blob URL.\n * @property {string | ((src: string) => string | undefined)} [newURL] New URL to replace the\n * references with, or a function returning it from the reference being replaced, for a reference\n * whose form depends on the entry holding it, like a path relative to the entry.\n */\n\n/**\n * @typedef {object} AssetReferenceMatcher\n * @property {AssetReferenceTarget[]} targets Targets, in the order given.\n * @property {Map<string, number[]>} byURL Indexes of the targets whose URL a value is compared\n * with as is.\n * @property {Map<string, number[]>} byBlobURL Indexes of the targets whose blob URL is compared\n * with that of the asset a value resolves to.\n * @property {Map<string, number[]>} byPath Indexes of the targets whose asset’s path is compared\n * with that of the asset a value resolves to.\n * @property {boolean} resolves Whether a value has to be resolved to an asset for any target,\n * which rules out telling a value that can’t refer to the assets from its text alone.\n */\n\n/**\n * Get the given asset URL in the form it’s stored in a field value, without the site’s base URL.\n * @param {string} url Asset’s public, external or blob URL.\n * @returns {string} URL to compare values with.\n */\nexport const getComparableAssetURL = (url) => {\n  const baseURL = cmsConfig.current?._baseURL;\n\n  return baseURL && !url.startsWith('blob:') ? url.replace(baseURL, '') : url;\n};\n\n/**\n * Index the given targets, so that a value can be compared with all of them at once.\n * @param {AssetReferenceTarget[]} targets Targets, whose URLs are already comparable, as returned\n * by {@link getComparableAssetURL}.\n * @returns {AssetReferenceMatcher} Matcher.\n */\nconst createMatcher = (targets) => {\n  /** @type {AssetReferenceMatcher} */\n  const matcher = {\n    targets,\n    byURL: new Map(),\n    byBlobURL: new Map(),\n    byPath: new Map(),\n    resolves: false,\n  };\n\n  targets.forEach(({ url, asset }, index) => {\n    const [map, key] = asset\n      ? [matcher.byPath, asset.path]\n      : /** @type {string} */ (url).startsWith('blob:')\n        ? [matcher.byBlobURL, /** @type {string} */ (url)]\n        : [matcher.byURL, /** @type {string} */ (url)];\n\n    map.set(key, [...(map.get(key) ?? []), index]);\n  });\n\n  matcher.resolves = !!(matcher.byBlobURL.size || matcher.byPath.size);\n\n  return matcher;\n};\n\n/**\n * Create a function resolving a media field value, or a media URL found in a Markdown or RichText\n * field value, to the file it points to, the way the editor does to display it, without loading\n * the file. A relative path is resolved against the field’s own `media_folder`, if any, and the\n * media URL in a body against those of the editor components the field can contain, too.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry holding the field.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name.\n * @param {InternalLocaleCode} [args.locale] Locale the value is found in, which an entry-relative\n * path is relative to.\n * @param {FieldKeyPath} args.keyPath Key path of the value.\n * @param {FlattenedEntryContent} args.valueMap Content holding the value, which tells the variable\n * types along the key path.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s special index file.\n * @param {Field} args.fieldConfig Field config.\n * @returns {(src: string) => MediaFieldSource | undefined} Function resolving a field value or a\n * media URL in it.\n */\nexport const createMediaSourceResolver = ({\n  entry,\n  collectionName,\n  fileName,\n  locale,\n  keyPath,\n  valueMap,\n  isIndexFile,\n  fieldConfig,\n}) => {\n  /** @type {string | undefined} */\n  let typedKeyPath;\n\n  return (src) => {\n    // Worked out on the first lookup only, as most values don’t need resolving\n    typedKeyPath ??= getTypedKeyPath({ collectionName, fileName, keyPath, valueMap, isIndexFile });\n\n    const args = { entry, collectionName, fileName, typedKeyPath, locale, value: src };\n    const { widget: fieldType = 'string' } = fieldConfig;\n\n    if (MEDIA_FIELD_TYPES.includes(fieldType)) {\n      return getMediaFieldSource({ ...args, fieldConfig: /** @type {MediaField} */ (fieldConfig) });\n    }\n\n    return getRichTextMediaSource({\n      ...args,\n      componentNames: getEditorComponentNames(\n        /** @type {MarkdownField | RichTextField} */ (fieldConfig),\n      ),\n    });\n  };\n};\n\n/**\n * @typedef {object} AssetURLMatch\n * @property {string} url Asset URL matched.\n * @property {string} fragment Fragment of the media URL left out of the match, or an empty string\n * if the whole URL matched.\n * @property {boolean} decoded Whether the media URL holds the asset URL percent-encoded.\n */\n\n/**\n * Find the asset URL the given field value or media URL holds: the URL as is, then decoded, like\n * the `%20` an editor component writes for a space in a body, which is how the CMS itself stores a\n * URL there, and the preview decodes it to find the asset as well. A URL with a fragment, like\n * `/uploads/a.jpg#center`, is then looked up without it, the way the editor finds the asset to\n * display it, see `getAssetByPath()`; the whole URL comes first, as an unencoded file name can\n * contain `#`, like `photo #1.jpg`.\n * @param {string | MediaSource} src Field value, or media URL found in it, as parsed by\n * `parseMediaSource()`.\n * @param {(url: string) => boolean} isAssetURL Function checking whether a URL is one of the asset\n * URLs being looked for.\n * @returns {AssetURLMatch | undefined} Match, if any.\n */\nexport const matchAssetURL = (src, isAssetURL) => {\n  const { url, path, fragment } = typeof src === 'string' ? parseMediaSource(src) : src;\n\n  // The whole URL, then the path without the fragment, if any\n  /** @type {[string, string][]} */\n  const forms = fragment\n    ? [\n        [url, ''],\n        [path, fragment],\n      ]\n    : [[url, '']];\n\n  for (const [value, rest] of forms) {\n    if (isAssetURL(value)) {\n      return { url: value, fragment: rest, decoded: false };\n    }\n\n    // Every string value goes through the pre-filter, and only one with a `%` can be decoded\n    const decoded = value.includes('%') ? decodeURIComponentSafely(value) : value;\n\n    if (decoded !== value && isAssetURL(decoded)) {\n      return { url: decoded, fragment: rest, decoded: true };\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Get the targets whose URL the given field value or media URL holds, in any of the forms\n * {@link matchAssetURL} accepts.\n * @param {AssetReferenceMatcher} matcher Matcher.\n * @param {string | MediaSource} src Field value, or media URL found in it.\n * @returns {number[] | undefined} Indexes of the targets, if any.\n */\nconst getURLTargets = (matcher, src) => {\n  const { byURL } = matcher;\n  const match = matchAssetURL(src, (key) => byURL.has(key));\n\n  return match && byURL.get(match.url);\n};\n\n/**\n * Get the targets the given field value or media URL refers to.\n * @param {AssetReferenceMatcher} matcher Matcher.\n * @param {MediaSource} source Field value, or media URL found in it, as parsed by\n * `parseMediaSource()`.\n * @param {(src: string) => MediaFieldSource | undefined} resolve Function resolving the value to\n * an asset, as returned by {@link createMediaSourceResolver}.\n * @returns {number[]} Indexes of the targets.\n */\nconst getMatchingTargets = (matcher, source, resolve) => {\n  const indexes = getURLTargets(matcher, source) ?? [];\n\n  if (!matcher.resolves) {\n    return indexes;\n  }\n\n  // Resolve the value to its asset without loading it. The asset’s blob URL is created once and\n  // kept on the asset object, so only the asset being looked up can hold the given one — and\n  // there’s no need to download every other asset the entries reference just to compare URLs\n  const { url, asset } = resolve(source.url) ?? {};\n  const blobURL = url ?? asset?.blobURL;\n\n  return [\n    ...indexes,\n    ...((blobURL !== undefined && matcher.byBlobURL.get(blobURL)) || []),\n    ...((asset && matcher.byPath.get(asset.path)) || []),\n  ];\n};\n\n/**\n * Get the new URL to replace a reference to the given targets with, in the form of the reference.\n * A fragment the reference was matched without, like `#center`, is kept. A space in the new URL is\n * encoded as `%20` in a Markdown image source, as the CMS writes it when inserting a file there,\n * see `toFieldValue()`, because the source can’t hold a space unless wrapped in angle brackets —\n * so not in a source wrapped as such. In an HTML attribute, it’s encoded unless the URL replaced\n * already holds a space. In a media field, it’s encoded if the reference holds the URL encoded.\n * @param {AssetReferenceMatcher} matcher Matcher.\n * @param {number[]} indexes Indexes of the targets referred to.\n * @param {MediaSource} source Reference being replaced, as parsed by `parseMediaSource()`.\n * @returns {string | undefined} New URL, if any.\n */\nconst getNewURL = (matcher, indexes, source) => {\n  const { url: src, path, fragment, syntax, bracketed } = source;\n\n  /**\n   * Put the new URL in the form of the reference.\n   * @param {string} newURL New URL.\n   * @param {string} rest Fragment of the reference the new URL doesn’t replace, if any.\n   * @param {boolean} [decoded] Whether the reference holds the URL percent-encoded.\n   * @returns {string} New reference.\n   */\n  const format = (newURL, rest, decoded = false) => {\n    const encode =\n      syntax === 'markdown'\n        ? !bracketed\n        : syntax === 'html'\n          ? !(rest ? path : src).includes(' ')\n          : decoded;\n\n    return `${encode ? newURL.replaceAll(' ', '%20') : newURL}${rest}`;\n  };\n\n  return indexes\n    .map((index) => {\n      const { url, newURL } = matcher.targets[index];\n\n      if (typeof newURL === 'function') {\n        // The whole reference first, as an unencoded file name can contain `#`\n        const whole = newURL(src);\n\n        if (whole) {\n          return format(whole, '');\n        }\n\n        const partial = fragment ? newURL(path) : undefined;\n\n        return partial ? format(partial, fragment) : undefined;\n      }\n\n      if (!newURL) {\n        return undefined;\n      }\n\n      // A target matched by URL may have been matched without the reference’s fragment, while one\n      // matched by resolution replaces the whole reference\n      const match = url === undefined ? undefined : matchAssetURL(source, (key) => key === url);\n\n      return format(newURL, match?.fragment ?? '', match?.decoded);\n    })\n    .find(Boolean);\n};\n\n/**\n * Check if the given value may refer to any of the targets, from its text alone. A value refers to\n * a target either as a whole, in a media field, or as a media URL in a Markdown or HTML body, so a\n * value that’s neither can be skipped before the costly field lookup. The format of a body isn’t\n * known until the field is, so it’s read as Markdown, which finds the media tags of HTML as well,\n * and only parsed as HTML if a tag is missed, e.g. with `<` in an attribute value.\n * @param {AssetReferenceMatcher} matcher Matcher, which must not need to resolve values.\n * @param {string} value Field value.\n * @returns {boolean} Result.\n */\nconst mayReferToTargets = (matcher, value) => {\n  if (getURLTargets(matcher, value)) {\n    return true;\n  }\n\n  if (!value.includes('![') && !MEDIA_TAG_REGEX.test(value)) {\n    return false;\n  }\n\n  /**\n   * Check if any of the given media URLs refers to a target.\n   * @param {string[]} sources URLs.\n   * @returns {boolean} Result.\n   */\n  const hasTarget = (sources) => sources.some((src) => !!getURLTargets(matcher, src));\n\n  if (hasTarget(getRichTextMediaSources(value, 'markdown'))) {\n    return true;\n  }\n\n  const tagCount = [...value.matchAll(MARKDOWN_MEDIA_REGEX)].filter(\n    ({ groups }) => groups?.tag,\n  ).length;\n\n  return (\n    (value.match(GLOBAL_MEDIA_TAG_REGEX)?.length ?? 0) > tagCount &&\n    hasTarget(getRichTextMediaSources(value, 'html'))\n  );\n};\n\n/**\n * Find the targets the given field refers to, and replace the references if the targets have a new\n * URL.\n * @param {object} args Arguments.\n * @param {AssetReferenceMatcher} args.matcher Matcher.\n * @param {string} args.collectionName Collection name.\n * @param {Entry} args.entry Entry.\n * @param {FlattenedEntryContent} args.content Value map for the collection. This will be modified\n * if a reference is replaced.\n * @param {FieldKeyPath} args.keyPath Key path of the value in the collection.\n * @param {string} args.value Value of the field.\n * @param {boolean} args.isIndexFile Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File collection only.\n * @param {InternalLocaleCode} args.locale Locale the value is found in.\n * @returns {{ indexes: Set<number>, field?: Field }} Indexes of the targets found, and the field\n * config, unless the field isn’t configured.\n */\nconst matchField = ({\n  matcher,\n  collectionName,\n  entry,\n  content,\n  keyPath,\n  value,\n  isIndexFile,\n  collectionFile,\n  locale,\n}) => {\n  /** @type {Set<number>} */\n  const indexes = new Set();\n  const fileName = collectionFile?.name;\n  const field = getField({ collectionName, fileName, valueMap: content, keyPath, isIndexFile });\n\n  if (!field) {\n    return { indexes };\n  }\n\n  const { widget: fieldType = 'string' } = field;\n\n  const resolve = createMediaSourceResolver({\n    entry,\n    collectionName,\n    fileName,\n    locale,\n    keyPath,\n    valueMap: content,\n    isIndexFile,\n    fieldConfig: field,\n  });\n\n  if (MEDIA_FIELD_TYPES.includes(fieldType)) {\n    const source = parseMediaSource(value);\n    const matched = getMatchingTargets(matcher, source, resolve);\n    const newURL = getNewURL(matcher, matched, source);\n\n    matched.forEach((index) => indexes.add(index));\n\n    if (newURL) {\n      content[keyPath] = newURL;\n    }\n\n    return { indexes, field };\n  }\n\n  // Search media in a Markdown or HTML body\n  if (RICH_TEXT_FIELD_TYPES.includes(fieldType)) {\n    let replacing = false;\n\n    // Swap the URL within each matched image or tag only, rather than its first occurrence in the\n    // text, which can be a link to the same file, the alt text, or the new URL written by a\n    // previous replacement. The new value is built from the original one, so doing this again,\n    // once for each collection the entry belongs to, gives the same result\n    const replaced = updateRichTextMediaURLs(\n      value,\n      getValueFormat(/** @type {MarkdownField | RichTextField} */ (field)),\n      (_url, source) => {\n        const matched = getMatchingTargets(matcher, source, resolve);\n\n        if (!matched.length) {\n          return undefined;\n        }\n\n        const newURL = getNewURL(matcher, matched, source);\n\n        matched.forEach((index) => indexes.add(index));\n        replacing ||= !!newURL;\n\n        return newURL || undefined;\n      },\n    );\n\n    if (replacing) {\n      content[keyPath] = replaced;\n    }\n  }\n\n  return { indexes, field };\n};\n\n/**\n * Walk the given entries once looking for all the given targets, calling back for each field\n * holding any of them. However many targets are given, each value is looked at once, so looking up\n * the assets of a whole folder costs about the same as looking up one.\n * @param {AssetReferenceTarget[]} targets Targets.\n * @param {object} options Options.\n * @param {Entry[]} options.entries Entries to be searched.\n * @param {boolean} [options.every] Whether to report every field holding a target. Otherwise the\n * search of an entry stops once every target has been found in it, unless the references are\n * being replaced.\n * @param {(reference: AssetReference) => void} [options.onMatch] Called for each field found.\n * @returns {Entry[][]} Entries holding each target, in the order of the targets, each list in the\n * order given.\n */\nconst findAssetReferences = (targets, { entries, every = false, onMatch }) => {\n  const matcher = createMatcher(\n    targets.map((target) =>\n      target.url === undefined ? target : { ...target, url: getComparableAssetURL(target.url) },\n    ),\n  );\n\n  const exhaustive = every || targets.some(({ newURL }) => !!newURL);\n  /** @type {Entry[][]} */\n  const results = targets.map(() => []);\n\n  entries.forEach((entry) => {\n    const { locales } = entry;\n    /**\n     * Collections associated with the entry, along with what each needs for matching a field.\n     * @type {{\n     * collection: InternalCollection,\n     * isIndexFile: boolean,\n     * files: (InternalCollectionFile | undefined)[],\n     * }[] | undefined}\n     */\n    let collections;\n    /** @type {Set<number>} */\n    const found = new Set();\n    /**\n     * Check whether the rest of the entry can be skipped.\n     * @returns {boolean} Result.\n     */\n    const isDone = () => !exhaustive && found.size === targets.length;\n\n    for (const [locale, { content }] of Object.entries(locales)) {\n      for (const [keyPath, value] of Object.entries(content)) {\n        if (typeof value !== 'string' || !value) continue;\n        // Pre-filter: skip values that can’t possibly refer to the targets, avoiding the expensive\n        // getField() call for the vast majority of fields.\n        if (!matcher.resolves && !mayReferToTargets(matcher, value)) continue;\n\n        // Resolved only once a value passes the pre-filter, as most entries have none that does\n        collections ??= getAssociatedCollections(entry).map((collection) => {\n          const collectionFiles = getCollectionFilesByEntry(collection, entry);\n\n          return {\n            collection,\n            isIndexFile: isCollectionIndexFile(collection, entry),\n            files: collectionFiles.length ? collectionFiles : [undefined],\n          };\n        });\n\n        for (const { collection, isIndexFile, files } of collections) {\n          const matchArgs = {\n            matcher,\n            collectionName: collection.name,\n            entry,\n            content,\n            keyPath,\n            locale,\n          };\n\n          const matches = files.map((collectionFile) =>\n            matchField({ ...matchArgs, value, isIndexFile, collectionFile }),\n          );\n\n          matches.forEach(({ indexes, field }, index) => {\n            indexes.forEach((i) => found.add(i));\n\n            if (indexes.size && onMatch) {\n              onMatch({\n                entry,\n                collection,\n                collectionFile: files[index],\n                locale,\n                keyPath,\n                // The field is known to be configured, as nothing matches otherwise\n                fieldConfig: /** @type {Field} */ (field),\n              });\n            }\n          });\n\n          if (isDone()) break;\n        }\n\n        if (isDone()) break;\n      }\n\n      if (isDone()) break;\n    }\n\n    found.forEach((index) => {\n      results[index].push(entry);\n    });\n  });\n\n  return results;\n};\n\n/**\n * Find entries by an asset URL, and replace the URL if needed.\n * @param {string} url Asset’s public or blob URL.\n * @param {object} [options] Options.\n * @param {Entry[]} [options.entries] Entries to be searched.\n * @param {string} [options.newURL] New URL to replace the found URL.\n * @returns {Promise<Entry[]>} Found (and replaced) entries.\n */\nexport const getEntriesByAssetURL = async (\n  url,\n  { entries = allEntries.current, newURL = '' } = {},\n) => findAssetReferences([{ url, newURL }], { entries })[0];\n\n/**\n * Find the entries holding each of the given targets, and replace the references to the targets\n * that have a new URL, in one pass over the entries. Synchronous, for a caller that can’t wait,\n * like a derived state; see {@link getEntriesByAssets} otherwise.\n * @param {AssetReferenceTarget[]} targets Targets.\n * @param {object} [options] Options.\n * @param {Entry[]} [options.entries] Entries to be searched.\n * @returns {Entry[][]} Found (and replaced) entries for each target, in the order of the targets.\n */\nexport const findEntriesByAssets = (targets, { entries = allEntries.current } = {}) =>\n  findAssetReferences(targets, { entries });\n\n/**\n * Find the entries holding each of the given targets, and replace the references to the targets\n * that have a new URL, in one pass over the entries.\n * @param {AssetReferenceTarget[]} targets Targets.\n * @param {object} [options] Options.\n * @param {Entry[]} [options.entries] Entries to be searched.\n * @returns {Promise<Entry[][]>} Found (and replaced) entries for each target, in the order of the\n * targets.\n */\nexport const getEntriesByAssets = async (targets, options) => findEntriesByAssets(targets, options);\n\n/**\n * Get the entries using any of the given targets, each listed once, however many of the targets it\n * uses.\n * @param {AssetReferenceTarget[]} targets Targets.\n * @returns {Promise<Entry[]>} Entries.\n */\nexport const getEntriesUsingTargets = async (targets) =>\n  targets.length ? [...new Set((await getEntriesByAssets(targets)).flat())] : [];\n\n/**\n * Find every field holding any of the given targets in the given entries, in one pass over them.\n * @param {AssetReferenceTarget[]} targets Targets.\n * @param {object} [options] Options.\n * @param {Entry[]} [options.entries] Entries to be searched.\n * @returns {Promise<AssetReference[]>} References, in the order found. An entry that belongs to\n * more than one collection is reported once per collection the field resolves in, and a field\n * holding several of the targets is reported once.\n */\nexport const getAssetReferences = async (targets, { entries = allEntries.current } = {}) => {\n  /** @type {AssetReference[]} */\n  const references = [];\n\n  /**\n   * Record a field found.\n   * @param {AssetReference} reference Reference.\n   */\n  const onMatch = (reference) => {\n    references.push(reference);\n  };\n\n  findAssetReferences(targets, { entries, every: true, onMatch });\n\n  return references;\n};\n","import { loadModule } from '$lib/services/app/dependencies';\nimport { getAssetBlob } from '$lib/services/assets/info';\nimport { toFixed } from '$lib/services/utils/number';\n\n/**\n * @import { Asset, AssetKind, GeoCoordinates } from '$lib/types/private';\n */\n\n/**\n * Extract the timestamp and coordinates (latitude/longitude) from EXIF data of an image asset.\n * @param {Asset} asset Asset object.\n * @param {AssetKind} kind Media type: `image`, `video` or `audio`.\n * @returns {Promise<{ createdDate: Date | undefined, coordinates: GeoCoordinates | undefined }>}\n * Date/Time and GPS Coordinates. If the asset is not an image or does not have EXIF data, returns\n * `undefined`.\n * @see https://github.com/MikeKovarik/exifr\n * @todo Extract more EXIF metadata, such as camera model, exposure time, etc.\n */\nexport const extractExifData = async (asset, kind) => {\n  const isImage = kind === 'image';\n  const blob = isImage ? await getAssetBlob(asset) : null;\n\n  if (!blob) {\n    return { createdDate: undefined, coordinates: undefined };\n  }\n\n  /** @type {Record<string, any>} */\n  let exif = {};\n\n  try {\n    /** @type {import('exifr')} */\n    const { parse } = await loadModule('exifr', 'dist/lite.esm.mjs');\n\n    exif = (await parse(blob)) ?? {};\n  } catch {\n    // EXIF is optional metadata, so a failed CDN load — due to a network issue or an ad blocker —\n    // or an unparsable file shouldn’t block the caller\n  }\n\n  const { latitude, longitude, DateTimeOriginal, CreateDate: timestamp = DateTimeOriginal } = exif;\n\n  return {\n    createdDate: timestamp instanceof Date ? timestamp : undefined,\n    coordinates:\n      Number.isFinite(latitude) && Number.isFinite(longitude)\n        ? { latitude: toFixed(latitude, 7), longitude: toFixed(longitude, 7) }\n        : undefined,\n  };\n};\n","import { extractExifData } from '$lib/services/utils/media/image/exif';\n\n/**\n * @import { Asset, AssetKind, GeoCoordinates, MediaDimensions } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} SourceInfo\n * @property {MediaDimensions} [dimensions] Dimensions (width/height), if available.\n * @property {number} [duration] Duration in seconds, if available.\n */\n\n/**\n * Probe a media element for its dimensions and duration. The source is always a blob URL, so the\n * element is guaranteed to fire either the success event or `error`; the latter resolves with an\n * empty result so that a file the browser cannot decode — a HEIC image saved with a `.jpg`\n * extension, say — never leaves the promise pending forever.\n * @param {object} args Arguments.\n * @param {HTMLImageElement | HTMLMediaElement} args.element Element to be probed.\n * @param {string} args.eventType Event that indicates the media info is available.\n * @param {string} args.src Source URL of the media.\n * @param {() => SourceInfo} args.getInfo Function to collect the info once the event fires.\n * @returns {Promise<SourceInfo>} Dimensions and duration, if available.\n */\nconst probeSource = ({ element, eventType, src, getInfo }) =>\n  /** @type {Promise<SourceInfo>} */ (\n    new Promise((resolve) => {\n      element.addEventListener(eventType, () => resolve(getInfo()), { once: true });\n      element.addEventListener('error', () => resolve({}), { once: true });\n      element.src = src;\n    })\n  );\n\n/**\n * Get the dimensions of an image asset.\n * @param {string} src Source URL of the image.\n * @returns {Promise<SourceInfo>} Dimensions (width/height). `dimensions` is `undefined` if the\n * image cannot be decoded.\n */\nconst getImageSourceInfo = (src) => {\n  const element = new Image();\n\n  return probeSource({\n    element,\n    eventType: 'load',\n    src,\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    getInfo: () => ({\n      dimensions: { width: element.naturalWidth, height: element.naturalHeight },\n    }),\n  });\n};\n\n/**\n * Get the dimensions and duration of a video or audio asset.\n * @param {string} src Source URL of the media.\n * @param {AssetKind} kind Media type: `video` or `audio`.\n * @returns {Promise<SourceInfo>} Dimensions and duration of the media. Both are `undefined` if the\n * media cannot be decoded.\n */\nconst getMediaSourceInfo = async (src, kind) => {\n  const element = /** @type {HTMLMediaElement} */ (document.createElement(kind));\n\n  return probeSource({\n    element,\n    eventType: 'loadedmetadata',\n    src,\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    getInfo: () => {\n      const { duration } = element;\n\n      if (kind === 'audio') {\n        return { duration };\n      }\n\n      const { videoWidth: width, videoHeight: height } = /** @type {HTMLVideoElement} */ (element);\n\n      return { dimensions: { width, height }, duration };\n    },\n  });\n};\n\n/**\n * Get the dimensions and duration of an image, video or audio asset.\n * @param {string} src Source URL.\n * @param {AssetKind} kind Media type: `image`, `video` or `audio`.\n * @returns {Promise<SourceInfo>} Dimensions (width/height) and duration.\n */\nexport const getSourceInfo = async (src, kind) => {\n  if (kind === 'image') {\n    return getImageSourceInfo(src);\n  }\n\n  return getMediaSourceInfo(src, kind);\n};\n\n/**\n * Get the metadata of an image, video or audio asset.\n * @param {Asset} asset Asset object.\n * @param {string} src Source URL.\n * @param {AssetKind} kind Media type: `image`, `video` or `audio`.\n * @returns {Promise<{ dimensions: MediaDimensions | undefined, duration: number | undefined,\n * createdDate: Date | undefined, coordinates: GeoCoordinates | undefined }>} Metadata object\n * containing dimensions, duration, created date and coordinates.\n */\nexport const getMediaMetadata = async (asset, src, kind) => {\n  const [{ dimensions, duration }, { createdDate, coordinates }] = await Promise.all([\n    getSourceInfo(src, kind),\n    extractExifData(asset, kind),\n  ]);\n\n  return { dimensions, duration, createdDate, coordinates };\n};\n","import { isMediaKind } from '$lib/services/assets/kinds';\nimport { getEntriesByAssetURL, getEntriesUsingTargets } from '$lib/services/assets/references';\nimport { getOrCreateAsync } from '$lib/services/utils/cache';\nimport { getSourceInfo } from '$lib/services/utils/media';\n\n/**\n * @import { Entry, ExternalAsset, MediaDimensions } from '$lib/types/private';\n */\n\n/**\n * Media info of an asset on a cloud storage service.\n * @typedef {object} ExternalAssetDetails\n * @property {MediaDimensions} [dimensions] Media dimensions available for an image or video file.\n * @property {number} [duration] Media duration available for a video or audio file, in seconds.\n */\n\n/**\n * Media info for the assets looked at so far, keyed by download URL. Collecting it loads the file\n * in a media element to read its dimensions and duration, and the result depends on nothing but\n * the file, so it’s gathered once per file rather than once per component asking for it.\n * @type {Map<string, Promise<ExternalAssetDetails>>}\n */\nconst cachedDetails = new Map();\n\n/* v8 ignore next */\n/**\n * Reset the media info cache. This is used in tests to reset the state between tests.\n */\nexport const _resetExternalAssetDetailsCache = () => {\n  cachedDetails.clear();\n};\n\n/**\n * Get the media info of the given asset on a cloud storage service. Unlike a repository asset, the\n * file is loaded from its public URL, which doesn’t require the service to allow cross-origin\n * requests, but Exif data can’t be read. A failed attempt isn’t remembered, so a later caller can\n * try again.\n * @param {ExternalAsset} asset Asset.\n * @returns {Promise<ExternalAssetDetails>} Details, or an empty object for a file with no media\n * info.\n */\nexport const getExternalAssetDetails = (asset) => {\n  const { kind, downloadURL } = asset;\n\n  if (!isMediaKind(kind)) {\n    return Promise.resolve({});\n  }\n\n  return getOrCreateAsync(cachedDetails, downloadURL, () => getSourceInfo(downloadURL, kind));\n};\n\n/**\n * Get the list of entries using the given asset on a cloud storage service. Such an asset is\n * hotlinked, so its download URL is what the entries store.\n * @param {ExternalAsset} asset Asset.\n * @returns {Promise<Entry[]>} List of entries using the asset.\n */\nexport const getExternalAssetUsedEntries = async ({ downloadURL }) =>\n  getEntriesByAssetURL(downloadURL);\n\n/**\n * Get the entries using any of the given assets on a cloud storage service, e.g. the files in a\n * folder being renamed. Each entry is listed once, however many of the assets it uses.\n * @param {ExternalAsset[]} assets Assets.\n * @returns {Promise<Entry[]>} List of entries using any of the assets.\n */\nexport const getExternalAssetsUsedEntries = async (assets) =>\n  getEntriesUsingTargets(assets.map(({ downloadURL }) => ({ url: downloadURL })));\n","import { getExternalAssetDetails } from '$lib/services/assets/external/details';\nimport { isMediaKind } from '$lib/services/assets/kinds';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { ExternalAsset } from '$lib/types/private';\n */\n\n/**\n * Maximum number of checks in flight at the same time. The linked files can be on many hosts, but\n * a site typically links to a few, so a burst of requests to one of them is kept small.\n */\nconst CONCURRENCY = 6;\n\n/**\n * Whether the files linked from entries could be loaded, keyed by asset ID, which is the URL. A\n * file is `false` when it couldn’t be loaded, e.g. because it has been deleted (404) or its host is\n * gone, so it can stand out in the Asset Library. A file that hasn’t been checked, or whose host\n * doesn’t answer cross-origin requests so nothing is known about it, has no entry.\n * @type {{ current: Record<string, boolean> }}\n */\nexport const externalAssetAvailability = createRawState({});\n\n/**\n * IDs of the assets checked or queued so far. A file is checked once per session, like the media\n * info gathered for the Info pane, so listing the linked files again doesn’t hit every host again.\n * @type {Set<string>}\n */\nconst checkedIds = new Set();\n\n/* v8 ignore next 5 */\n/**\n * Reset the availability state and the pending checks. This is used in tests to reset the state\n * between tests.\n */\nexport const _resetExternalAssetAvailability = () => {\n  externalAssetAvailability.current = {};\n  checkedIds.clear();\n};\n\n/**\n * Check whether the file at the given URL exists, using a `HEAD` request. Unlike loading the file\n * in a media element, this reports the HTTP status, but only if the host allows cross-origin\n * requests.\n * @param {string} url File URL.\n * @returns {Promise<boolean | undefined>} `true` if the file exists, `false` if it can’t be loaded,\n * or `undefined` if the host doesn’t say either way.\n */\nexport const probeURL = async (url) => {\n  try {\n    const { ok, status } = await fetch(url, { method: 'HEAD' });\n\n    if (ok) {\n      return true;\n    }\n\n    // Any client or server error means the file can’t be loaded, unless the server just doesn’t\n    // answer `HEAD` requests (405 Method Not Allowed, 501 Not Implemented) or is throttling the\n    // requests (429 Too Many Requests), in which case the file may well be fine\n    if (status >= 400 && ![405, 429, 501].includes(status)) {\n      return false;\n    }\n\n    return undefined;\n  } catch {\n    // A cross-origin request is rejected by the browser whatever the status if the host doesn’t\n    // allow it, so the failure tells nothing yet. An opaque request goes through regardless, as\n    // long as the host can be reached at all, so a failure of that means the host is gone\n    try {\n      await fetch(url, { method: 'HEAD', mode: 'no-cors' });\n\n      return undefined;\n    } catch {\n      return false;\n    }\n  }\n};\n\n/**\n * Whether the given URL is blocked as mixed content: an `http:` file can’t be loaded by any means\n * from a CMS served over `https:`, however fine the file is, so nothing can be said about it.\n * @param {string} url File URL.\n * @returns {boolean} Result.\n */\nexport const isMixedContent = (url) =>\n  window.location.protocol === 'https:' && url.startsWith('http:');\n\n/**\n * Check whether the given asset can be loaded. A media file is loaded in a media element, which\n * works on any host, and only falls back to a `HEAD` request when it can’t be decoded, to tell a\n * missing file from one in a format the browser doesn’t support. Any other file can only be\n * checked with a request.\n * @param {ExternalAsset} asset Asset.\n * @returns {Promise<boolean | undefined>} `true` if the file can be loaded, `false` if it can’t,\n * or `undefined` if the host doesn’t say either way.\n */\nexport const checkExternalAssetAvailability = async (asset) => {\n  const { kind, downloadURL } = asset;\n\n  if (isMixedContent(downloadURL)) {\n    return undefined;\n  }\n\n  if (isMediaKind(kind)) {\n    const details = await getExternalAssetDetails(asset);\n\n    if ('dimensions' in details || 'duration' in details) {\n      return true;\n    }\n\n    // The file exists if the host says so; otherwise it couldn’t be loaded either way\n    return (await probeURL(downloadURL)) === true;\n  }\n\n  return probeURL(downloadURL);\n};\n\n/**\n * Check whether the given assets can be loaded, and record the results in\n * {@link externalAssetAvailability} as they come in. An asset that has already been checked, or is\n * being checked, is skipped.\n * @param {ExternalAsset[]} assets Assets.\n * @returns {Promise<void>} Resolves once all the checks are done.\n */\nexport const checkExternalAssetsAvailability = async (assets) => {\n  const unchecked = assets.filter(({ id }) => !checkedIds.has(id));\n\n  // Mark the whole batch before the first check starts, so that a list requested again in the\n  // meantime doesn’t queue the same files twice\n  unchecked.forEach(({ id }) => checkedIds.add(id));\n\n  await runConcurrently(\n    unchecked,\n    async (asset) => {\n      const available = await checkExternalAssetAvailability(asset);\n\n      if (available !== undefined) {\n        externalAssetAvailability.current = {\n          ...externalAssetAvailability.current,\n          [asset.id]: available,\n        };\n      }\n    },\n    { concurrency: CONCURRENCY },\n  );\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { checkExternalAssetsAvailability } from '$lib/services/assets/external/availability';\nimport { getAssetKind } from '$lib/services/assets/kinds';\nimport { cmsConfig } from '$lib/services/config';\nimport { allEntries } from '$lib/services/contents';\nimport { getEntryCollectionContexts } from '$lib/services/contents/entry/contexts';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { MEDIA_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { allCloudStorageServices } from '$lib/services/integrations/media-libraries/cloud';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * Entry,\n * ExternalAsset,\n * FlattenedEntryContent,\n * MediaLibraryService,\n * } from '$lib/types/private';\n */\n\n/**\n * ID of the virtual location listing the files linked from entries. It’s routed like a cloud\n * storage service, at `#/assets/-/linked`.\n */\nexport const LINKED_FILES_SERVICE_ID = 'linked';\n\n/**\n * Whether the given field value is an absolute URL rather than a path to a repository asset.\n */\nconst URL_REGEX = /^https?:\\/\\/\\S+$/;\n\n/**\n * Whether the given File/Image field value links to a file that is neither in the repository nor\n * on a configured cloud storage service, which have their own locations in the Asset Library. A\n * value that starts with the site’s base URL points to a repository asset, as the `public_folder`\n * option can be an absolute URL.\n * @param {string} value Field value.\n * @returns {boolean} Result.\n */\nconst isLinkedURL = (value) => {\n  const baseURL = cmsConfig.current?._baseURL;\n\n  return (\n    URL_REGEX.test(value) &&\n    !(baseURL && value.startsWith(baseURL)) &&\n    !Object.values(allCloudStorageServices).some(\n      ({ isEnabled, isAssetURL }) => (isEnabled?.() ?? true) && isAssetURL?.(value),\n    )\n  );\n};\n\n/**\n * Convert a linked URL to an asset. Since nothing but the URL is known, the file name is the last\n * path segment, and the kind is derived from that name, or is `image` for an Image field.\n * @param {string} url URL.\n * @param {boolean} isImage Whether the URL comes from an Image field.\n * @returns {ExternalAsset} Asset.\n */\nexport const createLinkedAsset = (url, isImage) => {\n  let fileName = url;\n\n  try {\n    fileName = decodeURIComponent(new URL(url).pathname.split('/').filter(Boolean).at(-1) ?? '');\n  } catch {\n    // Keep the URL as the name if it can’t be parsed\n  }\n\n  fileName ||= url;\n\n  const kind = getAssetKind(fileName);\n\n  return {\n    id: url,\n    description: url,\n    previewURL: url,\n    downloadURL: url,\n    fileName,\n    kind: kind === 'other' && isImage ? 'image' : kind,\n  };\n};\n\n/**\n * Get the widget names of the fields the given key path resolves to in the collections the entry\n * belongs to. There can be more than one, as an entry can be shared by several collections and\n * collection files.\n * @param {Entry} entry Entry.\n * @param {FlattenedEntryContent} content Localized entry content.\n * @param {string} keyPath Field key path.\n * @returns {string[]} Widget names.\n */\nconst getFieldWidgets = (entry, content, keyPath) =>\n  getEntryCollectionContexts(entry)\n    .map(({ collection, collectionFile, isIndexFile }) => {\n      const field = getField({\n        collectionName: collection.name,\n        fileName: collectionFile?.name,\n        valueMap: content,\n        keyPath,\n        isIndexFile,\n      });\n\n      return field?.widget ?? 'string';\n    })\n    .toArray();\n\n/**\n * Collect the files linked from the File/Image fields of the given entries. A URL used by more than\n * one entry or field is listed once.\n * @param {Entry[]} entries Entries to scan.\n * @returns {ExternalAsset[]} Linked files.\n */\nexport const collectLinkedAssets = (entries) => {\n  /** @type {Map<string, ExternalAsset>} */\n  const assets = new Map();\n\n  entries.forEach((entry) => {\n    Object.values(entry.locales).forEach(({ content }) => {\n      Object.entries(content).forEach(([keyPath, value]) => {\n        // Pre-filter: most values are not URLs, so skip them before the field lookup\n        if (typeof value !== 'string' || !isLinkedURL(value)) {\n          return;\n        }\n\n        const widgets = getFieldWidgets(entry, content, keyPath);\n\n        if (widgets.some((widget) => MEDIA_FIELD_TYPES.includes(widget)) && !assets.has(value)) {\n          assets.set(value, createLinkedAsset(value, widgets.includes('image')));\n        }\n      });\n    });\n  });\n\n  return [...assets.values()];\n};\n\n/**\n * Files linked from the File/Image fields of all the entries, recomputed whenever the entries\n * change.\n * @type {{ readonly current: ExternalAsset[] }}\n */\nexport const linkedAssets = createDerivedState(() => collectLinkedAssets(allEntries.current));\n\n/**\n * Virtual media library service for the files linked from entries, so that they can be browsed in\n * the Asset Library like the files on a cloud storage service. The files live elsewhere, so they\n * can only be listed, not uploaded, renamed, replaced or deleted.\n * @type {MediaLibraryService}\n */\nexport const linkedFilesService = {\n  serviceType: 'cloud_storage',\n  serviceId: LINKED_FILES_SERVICE_ID,\n  /**\n   * Localized label.\n   * @returns {string} Label.\n   */\n  get serviceLabel() {\n    return _('linked_files');\n  },\n  serviceURL: '',\n  showServiceLink: false,\n  hotlinking: true,\n  authType: 'none',\n  /**\n   * List the linked files. The files live on hosts the CMS knows nothing about, so whether each one\n   * can still be loaded is checked in the background, and the result is reflected in the list.\n   * @returns {Promise<ExternalAsset[]>} Assets.\n   */\n  list: async () => {\n    const assets = linkedAssets.current;\n\n    checkExternalAssetsAvailability(assets);\n\n    return assets;\n  },\n};\n","import { getAdditions } from '$lib/services/app/additions';\nimport { prefs } from '$lib/services/user/prefs.svelte';\n\n/**\n * Get the API keys and the deploy hook an admin of Sveltia CMS Additions has shared with everyone.\n * @returns {{ apiKeys: Record<string, string>, deployHook?: { url: string, authHeader: string } |\n * null }} Credentials, empty without Sveltia CMS Additions.\n */\nconst getSharedCredentials = () => getAdditions()?.sharedCredentials ?? { apiKeys: {} };\n\n/**\n * Store an API key for an external service, such as a translator or a stock photo provider, in the\n * user preferences.\n * @param {string} serviceId Service ID.\n * @param {string} apiKey API key. An empty string removes the key.\n */\nexport const setApiKey = (serviceId, apiKey) => {\n  prefs.apiKeys ??= {};\n  prefs.apiKeys[serviceId] = apiKey;\n};\n\n/**\n * Check whether an API key doesn’t look like one of its service, which would make every request\n * fail. An empty key, or one for a service without a known format, isn’t checked.\n * @param {string} apiKey API key, without surrounding whitespace.\n * @param {RegExp | undefined} pattern Pattern the service’s API keys match.\n * @returns {boolean} Whether the key is wrong.\n */\nexport const isInvalidApiKey = (apiKey, pattern) => !!apiKey && !!pattern && !pattern.test(apiKey);\n\n/**\n * Store an API key for an external service in the user preferences once it matches the pattern\n * expected by the service, e.g. while the user is typing or pasting the key.\n * @param {string} serviceId Service ID.\n * @param {string} value API key as entered by the user. Surrounding whitespace is ignored.\n * @param {RegExp | undefined} pattern Pattern the API key has to match. Without a pattern, the key\n * is never saved.\n * @returns {string | undefined} Saved API key, or `undefined` if it doesn’t match the pattern.\n */\nexport const saveApiKey = (serviceId, value, pattern) => {\n  const apiKey = value.trim();\n\n  if (!pattern?.test(apiKey)) {\n    return undefined;\n  }\n\n  setApiKey(serviceId, apiKey);\n\n  return apiKey;\n};\n\n/**\n * Get the API key to use for an external service: the user’s own, or else the one an admin of\n * Sveltia CMS Additions has shared with everyone.\n * @param {string} serviceId Service ID.\n * @returns {string} API key, or an empty string if there is none.\n */\nexport const getApiKey = (serviceId) =>\n  prefs.apiKeys?.[serviceId] || getSharedCredentials().apiKeys[serviceId] || '';\n\n/**\n * Check whether the API key used for an external service is the one shared by an admin, as the\n * user hasn’t entered their own.\n * @param {string} serviceId Service ID.\n * @returns {boolean} Result.\n */\nexport const isSharedApiKey = (serviceId) =>\n  !prefs.apiKeys?.[serviceId] && !!getSharedCredentials().apiKeys[serviceId];\n\n/**\n * Get the deploy hook to call: the user’s own, or else the one an admin of Sveltia CMS Additions\n * has shared. The two are never mixed, so the user’s URL isn’t sent the admin’s header.\n * @returns {{ url: string, authHeader: string } | undefined} Hook, if any.\n */\nexport const getDeployHook = () => {\n  const { deployHookURL, deployHookAuthHeader } = prefs;\n\n  if (deployHookURL) {\n    return { url: deployHookURL, authHeader: deployHookAuthHeader ?? '' };\n  }\n\n  return getSharedCredentials().deployHook ?? undefined;\n};\n\n/**\n * Check whether the deploy hook used is the one shared by an admin, as the user hasn’t entered\n * their own.\n * @returns {boolean} Result.\n */\nexport const isSharedDeployHook = () => !prefs.deployHookURL && !!getSharedCredentials().deployHook;\n","import { LINKED_FILES_SERVICE_ID, linkedFilesService } from '$lib/services/assets/external/linked';\nimport { canPreviewFile } from '$lib/services/assets/kinds';\nimport { cmsConfig } from '$lib/services/config';\nimport { allCloudStorageServices } from '$lib/services/integrations/media-libraries/cloud';\nimport { getApiKey } from '$lib/services/user/api-keys';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\nimport { encodePathSegments } from '$lib/services/utils/url';\n\n/**\n * @import {\n * AssetSubfolder,\n * ExternalAsset,\n * MediaLibraryService,\n * } from '$lib/types/private';\n */\n\n/**\n * Prefix of the folder path segment in the Asset Library URL that selects a cloud storage service\n * rather than a repository folder, e.g. `#/assets/-/uploadcare`. The same prefix is used for the\n * All Assets folder (`-/all`), which is why a service ID can never be `all`.\n */\nexport const EXTERNAL_LOCATION_PATH_PREFIX = '-/';\n\n/**\n * Cloud storage services enabled in the site configuration, in the order they are defined in\n * {@link allCloudStorageServices}. These are listed as External Locations in the Asset Library.\n * @type {{ readonly current: MediaLibraryService[] }}\n */\nexport const enabledCloudServices = createDerivedState(() => {\n  // Each service reads the config through `isEnabled()`, but a service that doesn’t have the\n  // method is considered enabled, so read the config here to always track it\n  void cmsConfig.current;\n\n  return Object.values(allCloudStorageServices).filter(({ isEnabled }) => isEnabled?.() ?? true);\n});\n\n/**\n * Get an enabled cloud storage service by its ID, or the virtual service listing the files linked\n * from entries.\n * @param {string} serviceId Service ID, e.g. `uploadcare` or `linked`.\n * @returns {MediaLibraryService | undefined} Service, or `undefined` if the service is unknown or\n * not enabled.\n */\nexport const getCloudService = (serviceId) =>\n  serviceId === LINKED_FILES_SERVICE_ID\n    ? linkedFilesService\n    : enabledCloudServices.current.find((service) => service.serviceId === serviceId);\n\n/**\n * Get the Asset Library path for the given cloud storage service.\n * @param {MediaLibraryService} service Service.\n * @returns {string} Path, e.g. `/assets/-/uploadcare`.\n */\nexport const getCloudServicePath = ({ serviceId }) =>\n  `/assets/${EXTERNAL_LOCATION_PATH_PREFIX}${serviceId}`;\n\n/**\n * Get the Asset Library path of the given asset on a cloud storage service, whose details are shown\n * in an overlay. The asset ID, e.g. an object key that may contain slashes and special characters,\n * is percent-encoded per path segment.\n * @param {MediaLibraryService} service Service.\n * @param {ExternalAsset} asset Asset.\n * @returns {string} Path, e.g. `/assets/-/aws_s3/images/photo.jpg`.\n */\nexport const getExternalAssetPath = (service, { id }) =>\n  `${getCloudServicePath(service)}/${encodePathSegments(id)}`;\n\n/**\n * Whether the given asset can be previewed in the details overlay: a media file, a PDF document\n * or a plaintext file.\n * @param {ExternalAsset} asset Asset.\n * @returns {boolean} Result.\n */\nexport const canPreviewExternalAsset = ({ kind, fileName }) => canPreviewFile(kind, fileName);\n\n/**\n * Add newly uploaded assets to the top of a list. An upload is renamed rather than take the name of\n * a file on the service, but the list can be out of date, e.g. still showing a file deleted\n * elsewhere since, so an asset with the same ID is replaced rather than listed twice.\n * @param {ExternalAsset[]} uploaded Uploaded assets.\n * @param {ExternalAsset[]} assets Assets listed so far.\n * @returns {ExternalAsset[]} Merged list.\n */\nexport const mergeUploadedExternalAssets = (uploaded, assets) => {\n  const uploadedIds = new Set(uploaded.map(({ id }) => id));\n\n  return [...uploaded, ...assets.filter(({ id }) => !uploadedIds.has(id))];\n};\n\n/**\n * Cloud storage service currently selected in the Asset Library, or `undefined` when a repository\n * folder is selected instead.\n * @type {{ current: MediaLibraryService | undefined }}\n */\nexport const selectedCloudService = createRawState();\n\n/**\n * Assets on the selected cloud storage service. It’s `undefined` while the assets are being\n * fetched, and reset when a different service is selected.\n * @type {{ current: ExternalAsset[] | undefined }}\n */\nexport const externalAssets = createRawState();\n\n/**\n * Whether the given cloud storage service stores files at paths that the Asset Library and the\n * asset picker browse folder by folder, like a repository folder. That takes a service that lists\n * its folders — an S3-compatible service or Azure Blob Storage — rather than one with a flat file\n * list, like Uploadcare, or one with a widget of its own, like Cloudinary.\n * @param {MediaLibraryService | undefined} service Service.\n * @returns {service is MediaLibraryService} Result.\n */\nexport const hasFolderSupport = (service) => !!service?.browse;\n\n/**\n * Paths of the empty folders on the selected cloud storage service, each kept by a placeholder\n * object, relative to the configured prefix. The folders that hold files are read off the file\n * paths instead. Empty for a service without folder support.\n * @type {{ current: string[] }}\n */\nexport const externalFolders = createRawState([]);\n\n/**\n * Path of the folder being browsed on the selected cloud storage service, relative to the\n * configured prefix. Empty at the root, and always empty for a service without folder support.\n * @type {{ current: string }}\n */\nexport const selectedExternalDirPath = createRawState('');\n\n/**\n * Subfolder currently focused in the list, whose info is shown in the Info pane, if any.\n * @type {{ current: AssetSubfolder | undefined }}\n */\nexport const focusedExternalSubfolder = createRawState();\n\n/**\n * Whether to show the New Folder dialog for the selected cloud storage service.\n * @type {{ current: boolean }}\n */\nexport const showNewExternalFolderDialog = createRawState(false);\n\n/**\n * Subfolder being renamed with the Rename Folder dialog, if any.\n * @type {{ current: AssetSubfolder | undefined }}\n */\nexport const renamingExternalSubfolder = createRawState();\n\n/**\n * Subfolder being deleted with the Delete Folder dialog, if any.\n * @type {{ current: AssetSubfolder | undefined }}\n */\nexport const deletingExternalSubfolder = createRawState();\n\n/**\n * Number of assets on each cloud storage service whose list has been fetched so far, keyed by\n * service ID. Shown in the Asset Library sidebar; a service that hasn’t been visited yet has no\n * count, as listing it would require the user’s credentials and an extra API call.\n * @type {{ current: Record<string, number> }}\n */\nexport const externalAssetCounts = createRawState({});\n\n/**\n * Key of the error message to be shown when the assets could not be fetched.\n * @type {{ current: string | undefined }}\n */\nexport const externalAssetsError = createRawState();\n\n/**\n * Whether the list of assets stopped short of the end, as the service holds more files than are\n * listed at once, so the user can be told that some files are left out.\n * @type {{ current: boolean }}\n */\nexport const externalAssetsTruncated = createRawState(false);\n\n/**\n * Assets selected in the list.\n * @type {{ current: ExternalAsset[] }}\n */\nexport const selectedExternalAssets = createRawState([]);\n\n/**\n * Set of selected asset IDs, for O(1) membership checks in list items.\n */\nexport const selectedExternalAssetIdSet = createDerivedState(\n  () => new Set(selectedExternalAssets.current.map(({ id }) => id)),\n);\n\n/**\n * Asset that has focus in the list, whose details are shown in the Info pane.\n * @type {{ current: ExternalAsset | undefined }}\n */\nexport const focusedExternalAsset = createRawState();\n\n/**\n * Drop the selected and focused assets that fail the given test, e.g. once they have been deleted\n * or are no longer listed. The selection is only replaced when an asset is actually dropped, so a\n * caller running in an effect doesn’t invalidate it needlessly.\n * @param {(id: string) => boolean} keep Function telling whether to keep the asset with the given\n * ID.\n */\nexport const pruneExternalAssetSelection = (keep) => {\n  const selected = selectedExternalAssets.current;\n  const kept = selected.filter(({ id }) => keep(id));\n\n  if (kept.length !== selected.length) {\n    selectedExternalAssets.current = kept;\n  }\n\n  if (focusedExternalAsset.current && !keep(focusedExternalAsset.current.id)) {\n    focusedExternalAsset.current = undefined;\n  }\n};\n\n/**\n * Assets the toolbar actions operate on: the selected assets, or else the focused asset, if any.\n * @type {{ readonly current: ExternalAsset[] }}\n */\nexport const selectedOrFocusedExternalAssets = createDerivedState(() => {\n  if (selectedExternalAssets.current.length) {\n    return [...selectedExternalAssets.current];\n  }\n\n  return focusedExternalAsset.current ? [focusedExternalAsset.current] : [];\n});\n\n/**\n * ID of the asset whose details are shown in the overlay, taken from the URL. The asset itself is\n * looked up in {@link externalAssets} once the list is loaded.\n * @type {{ current: string | undefined }}\n */\nexport const overlaidExternalAssetId = createRawState();\n\n/**\n * Asset being renamed, shown in the Rename Asset dialog.\n * @type {{ current: ExternalAsset | undefined }}\n */\nexport const renamingExternalAsset = createRawState();\n\n/**\n * Search terms entered in the list’s search bar, used to narrow down the assets by file name.\n * @type {{ current: string }}\n */\nexport const externalAssetSearchTerms = createRawState('');\n\n/**\n * Get the credentials needed to call the given service’s API, which the user has entered in the\n * Asset Library, the asset picker or the Settings dialog. Without the user’s own API key, the one\n * an admin of Sveltia CMS Additions has shared is used.\n * @param {MediaLibraryService} service Service.\n * @returns {{ apiKey: string, userName: string, password: string }} Credentials, each of which is\n * an empty string if not entered.\n */\nexport const getFetchOptions = ({ serviceId }) => {\n  const apiKey = getApiKey(serviceId);\n  const [userName = '', password = ''] = (prefs.logins?.[serviceId] ?? '').split(' ');\n\n  return { apiKey, userName, password };\n};\n\n/**\n * Whether the user has provided the credentials needed to call the given service’s API.\n * @param {MediaLibraryService} service Service.\n * @returns {boolean} Result.\n */\nexport const hasAuthInfo = (service) => {\n  const { apiKey, password } = getFetchOptions(service);\n\n  return service.authType === 'none' || !!apiKey || !!password;\n};\n\n/**\n * Reset the list state. Called when a different service is selected.\n */\nexport const resetExternalAssets = () => {\n  externalAssets.current = undefined;\n  externalFolders.current = [];\n  externalAssetsError.current = undefined;\n  externalAssetsTruncated.current = false;\n  selectedExternalAssets.current = [];\n  selectedExternalDirPath.current = '';\n  focusedExternalAsset.current = undefined;\n  focusedExternalSubfolder.current = undefined;\n  overlaidExternalAssetId.current = undefined;\n  renamingExternalAsset.current = undefined;\n  renamingExternalSubfolder.current = undefined;\n  deletingExternalSubfolder.current = undefined;\n  externalAssetSearchTerms.current = '';\n};\n\n/**\n * Browse a folder on the selected cloud storage service. The focus moves off whatever was focused\n * in the folder being left, and the selection is emptied, so the toolbar never acts on an asset\n * the user can’t see.\n * @param {string} dirPath Folder path relative to the configured prefix. An empty string for the\n * root.\n */\nexport const browseExternalFolder = (dirPath) => {\n  selectedExternalDirPath.current = dirPath;\n  selectedExternalAssets.current = [];\n  focusedExternalAsset.current = undefined;\n  focusedExternalSubfolder.current = undefined;\n};\n","import equal from 'fast-deep-equal';\nimport { untrack } from 'svelte';\n\nimport { selectedCloudService } from '$lib/services/assets/external';\nimport { selectedAssetFolder } from '$lib/services/assets/folders';\nimport { initViewSettingsStorage } from '$lib/services/common/view';\nimport { createRawState, createRootEffect } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { AssetListView, BackendService } from '$lib/types/private';\n */\n\n/**\n * View settings for all the asset collection.\n * @type {{ current: Record<string, AssetListView> | undefined }}\n */\nexport const assetListSettings = createRawState();\n\n/**\n * Default view settings for the selected asset collection.\n * @type {AssetListView}\n */\nexport const defaultView = {\n  type: 'grid',\n  showInfo: true,\n  sort: {\n    key: 'name',\n    order: 'ascending',\n  },\n};\n\n/**\n * View settings for the selected asset collection.\n * @type {{ current: AssetListView }}\n */\nexport const currentView = createRawState({ type: 'grid', showInfo: true });\n\n/**\n * Get the key under which the view settings for the selected location are saved: the internal\n * path of a repository folder, `-/{serviceId}` for a cloud storage service, or `*` for All Assets.\n * @returns {string} Key.\n */\nexport const getSettingsKey = () => {\n  const service = selectedCloudService.current;\n\n  if (service) {\n    return `-/${service.serviceId}`;\n  }\n\n  return selectedAssetFolder.current?.internalPath ?? '*';\n};\n\n/**\n * Initialize {@link assetListSettings} and relevant effects.\n * @param {BackendService} _backend Backend service.\n */\nexport const initSettings = async ({ repository }) => {\n  await initViewSettingsStorage(repository, 'assets-view', assetListSettings);\n\n  // Restore the view settings when a different folder or service is selected\n  createRootEffect(() => {\n    void [selectedAssetFolder.current, selectedCloudService.current];\n\n    untrack(() => {\n      const view = assetListSettings.current?.[getSettingsKey()] ?? structuredClone(defaultView);\n\n      if (!equal(view, currentView.current)) {\n        currentView.current = view;\n      }\n    });\n  });\n\n  // Save the view settings when the view is changed\n  createRootEffect(() => {\n    const view = currentView.current;\n\n    untrack(() => {\n      const key = getSettingsKey();\n      const savedView = assetListSettings.current?.[key] ?? {};\n\n      if (!equal(view, savedView)) {\n        assetListSettings.current = { ...assetListSettings.current, [key]: view };\n      }\n    });\n  });\n};\n","import { getPathInfo } from '@sveltia/utils/file';\n\nimport { sortItemsByKey } from '$lib/services/common/view';\nimport { getCommitAuthorName } from '$lib/services/utils/commit-author';\n\n/**\n * @import { Asset, SortingConditions } from '$lib/types/private';\n */\n\n/**\n * Get the value to sort a file by its name. The file extension is excluded to sort numbered files\n * properly, e.g. `hero.png`, `hero-1.png`, `hero-2.png` instead of `hero-1.png`, `hero-2.png`,\n * `hero.png`. Only the extension is removed, so dots in the rest of the name, e.g. `v1.10.png`,\n * still count.\n * @param {string} name File name.\n * @returns {string} Name without the extension.\n */\nexport const getNameSortValue = (name) => getPathInfo(name).filename;\n\n/**\n * Get an asset’s property value.\n * @param {Asset} asset Asset.\n * @param {string} key Sorting key. A field name of the asset or a special key like `commit_author`,\n * `commit_date`, or `name`.\n * @returns {any} Value.\n */\nexport const getValue = (asset, key) => {\n  const { commitAuthor, commitDate } = asset;\n\n  if (key === 'commit_author') {\n    return getCommitAuthorName(commitAuthor);\n  }\n\n  if (key === 'commit_date') {\n    return commitDate;\n  }\n\n  if (key === 'name') {\n    return getNameSortValue(asset.name);\n  }\n\n  return /** @type {Record<string, any>} */ (asset)[key] ?? '';\n};\n\n/**\n * Sort the given assets.\n * @param {Asset[]} assets Asset list.\n * @param {SortingConditions} [conditions] Sorting conditions.\n * @returns {Asset[]} Sorted asset list.\n */\nexport const sortAssets = (assets, { key, order } = {}) => {\n  if (!key || !order) {\n    return assets;\n  }\n\n  const _assets = [...assets];\n\n  const type =\n    { commit_author: String, commit_date: Date }[key] ||\n    /** @type {Record<string, any>} */ (_assets[0])?.[key]?.constructor ||\n    String;\n\n  sortItemsByKey(\n    _assets,\n    (a) => {\n      const v = getValue(a, key);\n\n      return type !== String ? Number(v ?? 0) : (v ?? '');\n    },\n    type === String,\n    order,\n  );\n\n  return _assets;\n};\n","import { _, locale as appLocale } from '@sveltia/i18n';\nimport equal from 'fast-deep-equal';\nimport { untrack } from 'svelte';\n\nimport { isAssetInFolder } from '$lib/services/assets';\nimport { selectedAssetFolder } from '$lib/services/assets/folders';\nimport {\n  focusedAsset,\n  publishedAssets,\n  selectedAssets,\n  uploadingAssets,\n} from '$lib/services/assets/state';\nimport {\n  browsedDirPath,\n  focusedSubfolder,\n  getAssetsInDir,\n  getSubfolders,\n  selectedSubfolderPath,\n} from '$lib/services/assets/subfolders';\nimport { filterAssets } from '$lib/services/assets/view/filter';\nimport { groupAssets } from '$lib/services/assets/view/group';\nimport { assetListSettings, currentView, initSettings } from '$lib/services/assets/view/settings';\nimport { sortAssets } from '$lib/services/assets/view/sort';\nimport { backend } from '$lib/services/backends';\nimport { getCollection, getCollectionLabel } from '$lib/services/contents/collection';\nimport { getCollectionFile, getCollectionFileLabel } from '$lib/services/contents/collection/files';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { getBaseName } from '$lib/services/utils/file';\nimport {\n  createDerivedState,\n  createRawState,\n  createRootEffect,\n  createStableDerivedState,\n} from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Asset, AssetFolderInfo, AssetFolderSummary } from '$lib/types/private';\n */\n\n/**\n * Whether the asset details overlay is shown.\n */\nexport const showAssetOverlay = createRawState(false);\n\n/**\n * Whether to show the Upload Assets dialog.\n */\nexport const showUploadAssetsDialog = createRawState(false);\n\n/**\n * Whether to show the New Folder dialog.\n */\nexport const showNewSubfolderDialog = createRawState(false);\n\n/**\n * Whether to show the Upload Assets confirmation dialog.\n */\nexport const showUploadAssetsConfirmDialog = createDerivedState(\n  () => !!uploadingAssets.current.files.length,\n);\n\n/**\n * Get the label for the given collection. It can be a category name if the folder is a\n * collection-specific asset folder.\n * @param {AssetFolderInfo} folder Folder info.\n * @returns {string} Human-readable label.\n * @see https://decapcms.org/docs/collection-folder/#media-and-public-folder\n * @see https://sveltiacms.app/en/docs/media/internal\n */\nexport const getFolderLabelByCollection = ({ label, collectionName, fileName, internalPath }) => {\n  if (label) {\n    return label;\n  }\n\n  if (collectionName === undefined) {\n    return _(internalPath === undefined ? 'all_assets' : 'global_assets');\n  }\n\n  const collection = getCollection(collectionName);\n  const collectionLabel = collection ? getCollectionLabel(collection) : collectionName;\n\n  if (!fileName) {\n    return collectionLabel;\n  }\n\n  const file = collection ? getCollectionFile(collection, fileName) : undefined;\n  const fileLabel = file ? getCollectionFileLabel(file) : fileName;\n\n  return `${collectionLabel} › ${fileLabel}`;\n};\n\n/**\n * List of all the assets in the selected asset folder, including those in its subfolders.\n */\nexport const selectedFolderAssets = createDerivedState(() => {\n  const { current: _allAssets } = publishedAssets;\n  const { current: _selectedAssetFolder } = selectedAssetFolder;\n\n  if (_allAssets && _selectedAssetFolder && _selectedAssetFolder.internalPath !== undefined) {\n    // A folder restored from `window.history.state` is an equal but separate object, and the\n    // assets of another folder with the same path are listed as well\n    return _allAssets.filter((asset) => isAssetInFolder(asset, _selectedAssetFolder));\n  }\n\n  return _allAssets ? [..._allAssets] : [];\n});\n\n/**\n * List of the assets shown for the selected asset folder: the assets right in the directory being\n * browsed, the ones in its subfolders being reached through {@link listedSubfolders}. Every asset\n * below the folder is listed at once when the folder can’t be browsed by subfolder.\n */\nexport const listedAssets = createDerivedState(() => {\n  const assets = selectedFolderAssets.current;\n  const dirPath = browsedDirPath.current;\n\n  if (dirPath === undefined) {\n    return assets;\n  }\n\n  return getAssetsInDir({ dirPath, assets });\n});\n\n/**\n * Subfolders of the directory being browsed, listed ahead of the assets. Empty unless the selected\n * asset folder is browsed by subfolder.\n */\nexport const listedSubfolders = createDerivedState(() => {\n  const dirPath = browsedDirPath.current;\n\n  return dirPath === undefined\n    ? []\n    : getSubfolders({ dirPath, assets: selectedFolderAssets.current });\n});\n\n/**\n * What the folder info panel describes: the focused subfolder, or the folder being browsed — the\n * subfolder being browsed if any, otherwise the selected folder itself.\n * @type {{ readonly current: AssetFolderSummary | undefined }}\n */\nexport const folderSummary = createDerivedState(() => {\n  const subfolder = focusedSubfolder.current;\n\n  if (subfolder) {\n    const { name, path } = subfolder;\n    const assets = selectedFolderAssets.current;\n\n    return {\n      name,\n      path,\n      folderCount: getSubfolders({ dirPath: path, assets }).length,\n      assetCount: getAssetsInDir({ dirPath: path, assets }).length,\n    };\n  }\n\n  const folder = selectedAssetFolder.current;\n\n  // The panel is only shown with a folder selected\n  if (!folder) {\n    return undefined;\n  }\n\n  const dirPath = browsedDirPath.current;\n\n  return {\n    name:\n      getBaseName(selectedSubfolderPath.current) ||\n      // `appLocale.current` is a key, because the label can be localized\n      (appLocale.current && getFolderLabelByCollection(folder)),\n    // The All Assets folder has no path\n    path: dirPath ?? folder.internalPath,\n    // A folder that isn’t browsed by subfolder lists every asset below it at once\n    folderCount: dirPath === undefined ? undefined : listedSubfolders.current.length,\n    assetCount: listedAssets.current.length,\n  };\n});\n\n/**\n * Find the assets listed right before and after the given one, for the previous/next navigation in\n * the details overlay. The list is the one the user sees, so the neighbors follow the current\n * sorting, filtering and grouping. An asset that can’t be previewed isn’t opened in the overlay\n * from the list, so it’s skipped.\n * @template T\n * @param {Record<string, T[]>} groups Listed assets, grouped as the list shows them.\n * @param {(asset: T) => boolean} isCurrent Whether an asset is the one shown in the overlay.\n * @param {(asset: T) => boolean} canPreview Whether an asset can be shown in the overlay.\n * @returns {{ previous?: T, next?: T }} Neighbors, each omitted when the current asset is the first\n * or last one, or when it isn’t listed at all.\n */\nexport const getAdjacentAssets = (groups, isCurrent, canPreview) => {\n  const assets = Object.values(groups)\n    .flat(1)\n    .filter((asset) => isCurrent(asset) || canPreview(asset));\n\n  const index = assets.findIndex(isCurrent);\n\n  if (index === -1) {\n    return {};\n  }\n\n  return { previous: assets[index - 1], next: assets[index + 1] };\n};\n\n/**\n * Last computed value of {@link assetGroups}, reused when the new value is deeply equal, so that\n * the list is not re-rendered needlessly.\n * @type {Record<string, Asset[]>}\n */\nlet previousAssetGroups = {};\n/**\n * Sorting conditions of the current view. This and the other view conditions below are picked out\n * of {@link currentView} one by one, so replacing the view to switch between list and grid, or to\n * collapse a group, doesn’t sort, filter and group the assets all over again: each step only\n * reruns when the conditions it uses have actually changed.\n */\nconst sortConditions = createStableDerivedState(() => currentView.current.sort);\n/**\n * Filtering conditions of the current view. See {@link sortConditions}.\n */\nconst filterConditions = createStableDerivedState(() => currentView.current.filter);\n/**\n * Grouping conditions of the current view. See {@link sortConditions}.\n */\nconst groupConditions = createStableDerivedState(() => currentView.current.group);\n\n/**\n * {@link listedAssets} sorted with the current view’s conditions. Sorting is the costliest step, so\n * it comes first: changing a filter then only reruns the cheaper steps below.\n * @type {{ readonly current: Asset[] }}\n */\nconst sortedAssets = createDerivedState(() =>\n  sortAssets(listedAssets.current, sortConditions.current),\n);\n\n/**\n * {@link sortedAssets} filtered with the current view’s conditions.\n * @type {{ readonly current: Asset[] }}\n */\nconst filteredAssets = createDerivedState(() =>\n  filterAssets(sortedAssets.current, filterConditions.current),\n);\n\n/**\n * Sorted, filtered and grouped assets for the selected asset collection.\n * @type {{ readonly current: Record<string, Asset[]> }}\n */\nexport const assetGroups = createDerivedState(() => {\n  const groups = groupAssets(filteredAssets.current, groupConditions.current);\n\n  if (!equal(previousAssetGroups, groups)) {\n    previousAssetGroups = groups;\n  }\n\n  return previousAssetGroups;\n});\n\n/**\n * Map from asset path to the asset’s row index in the list, used by list rows to resolve their\n * `aria-rowindex` in O(1). The index is counted across the groups rather than within each one, as\n * the rows of every group make up one grid, and follows the current sorting and filtering. The\n * subfolders come first, so they offset the index. Rows are appended by an infinite scroller and\n * never unmounted, so once a large folder has been scrolled through, an `indexOf()` per row would\n * make every subsequent list update O(n²).\n */\nexport const listedAssetIndexMap = createDerivedState(() => {\n  const offset = listedSubfolders.current.length;\n\n  return new Map(\n    Object.values(assetGroups.current)\n      .flat(1)\n      .map((asset, index) => [asset.path, index + offset]),\n  );\n});\n\ncreateRootEffect(() => {\n  const { current: _backend } = backend;\n\n  if (_backend && !untrack(() => assetListSettings.current)) {\n    initSettings(_backend);\n  }\n});\n\n// Clear the selection when the listed assets or the filter change, so it never includes an asset\n// the current view hides, which a bulk action like Delete would otherwise apply to. Likewise, drop\n// the focus from an asset the view no longer lists, e.g. an image once the list is filtered to\n// documents, as the toolbar actions and the info panel fall back to the focused asset. An updated\n// copy of the focused asset, e.g. after it’s replaced, has the same path, so the focus stays.\ncreateRootEffect(() => {\n  const assets = listedAssets.current;\n  const filter = filterConditions.current;\n  const asset = untrack(() => focusedAsset.current);\n\n  selectedAssets.current = [];\n\n  if (\n    asset &&\n    !filterAssets(\n      assets.filter(({ path }) => path === asset.path),\n      filter,\n    ).length\n  ) {\n    focusedAsset.current = undefined;\n  }\n\n  if (untrack(() => prefs.devModeEnabled)) {\n    // eslint-disable-next-line no-console\n    console.info('listedAssets', assets);\n  }\n});\n","import { createDeepState, createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { EntryEditorPane, InternalLocaleCode, SelectAssetsView } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} CopyToastState\n * @property {number | undefined} id Unique identifier for the toast.\n * @property {boolean} show Whether the toast is currently visible.\n * @property {'info' | 'success' | 'error'} status Status of the toast.\n * @property {string | undefined} message Message to display in the toast.\n * @property {number} count Number of copies made.\n * @property {InternalLocaleCode | undefined} sourceLanguage Source locale for the copy.\n */\n\n/**\n * Minimum width for entry editor panes in percentage. This ensures that panes remain usable and\n * prevents them from being resized to an unusable width.\n * @constant {number}\n */\nexport const MIN_PANE_SIZE = 30;\n\n/**\n * Whether the content details overlay is shown.\n */\nexport const showContentOverlay = createRawState(false);\n\n/**\n * Whether to show the toast notification for a duplicated entry.\n */\nexport const showDuplicateToast = createRawState(false);\n\n/**\n * Number of inline editors that are currently active in the entry editor, such as the file name\n * editor in a File/Image field. While any of them is active, the Escape key shortcut to close the\n * entry editor is disabled, so the key can be used to cancel the inline editing instead.\n */\nexport const activeInlineEditors = createRawState(0);\n\n/**\n * @type {{ current: { show: boolean, multiple: boolean, resolve?: (value?: string) => void } }}\n */\nexport const translatorApiKeyDialogState = createDeepState({ show: false, multiple: false });\n\n/**\n * Copy/translation toast state.\n * @type {{ current: CopyToastState }}\n */\nexport const copyFromLocaleToast = createDeepState({\n  id: undefined,\n  show: false,\n  status: 'success',\n  message: undefined,\n  count: 1,\n  sourceLanguage: undefined,\n});\n\n/**\n * State of the toast shown once a list item is copied or pasted. It’s shared by every List field,\n * so the editor only has one toast for them. The ID changes each time the toast is shown, so the\n * same message shown again stays for the full duration.\n * @type {{ current: {\n * id: number,\n * show: boolean,\n * status: 'success' | 'info' | 'warning' | 'error',\n * message: string,\n * } }}\n */\nexport const listItemClipboardToast = createDeepState({\n  id: 0,\n  show: false,\n  status: 'success',\n  message: '',\n});\n\n/**\n * @type {{ current: ?EntryEditorPane }}\n */\nexport const editorFirstPane = createRawState(null);\n\n/**\n * @type {{ current: ?EntryEditorPane }}\n */\nexport const editorSecondPane = createRawState(null);\n\n/**\n * View settings for the Select Assets dialog.\n * @type {{ current: SelectAssetsView | undefined }}\n */\nexport const selectAssetsView = createRawState();\n","import { encodePathSegments } from '$lib/services/utils/url';\n\n/**\n * @import { UnpublishedEntry } from '$lib/types/private';\n */\n\n/**\n * Get the path of the Content Editor for an entry, encoded for the URL hash. A collection file is\n * addressed by its name, while an entry in a folder collection is addressed by its `subPath`, which\n * for a collection file would be the whole file path.\n * @param {string} collectionName Collection name, e.g. `posts`, or `_singletons`.\n * @param {string} name File name, or the entry’s `subPath`, e.g. `2024/hello-world`.\n * @param {object} [options] Options.\n * @param {number} [options.pullRequestNumber] Number of the pull request a contributor has opened\n * from their fork to open the entry from, rather than the published version or the maintainers’\n * own pull request.\n * @returns {string} Path, e.g. `/collections/posts/entries/2024/hello-world`, followed by\n * `?_pr={number}` with a pull request number.\n */\nexport const getEntryEditorPath = (collectionName, name, { pullRequestNumber } = {}) => {\n  const path = encodePathSegments(`/collections/${collectionName}/entries/${name}`);\n\n  return pullRequestNumber === undefined ? path : `${path}?_pr=${pullRequestNumber}`;\n};\n\n/**\n * Get the path of the Content Editor for an unpublished entry, as the Editorial Workflow board\n * opens it. An entry from a pull request a contributor has opened from their fork is opened with\n * the pull request named, as several pull requests can hold the same entry and the editor\n * otherwise opens the published version or the maintainers’ own pull request.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {string} Path, e.g. `/collections/posts/entries/hello?_pr=7`.\n */\nexport const getUnpublishedEntryEditorPath = (entry) => {\n  const { collectionName, fileName, pullRequest } = entry.workflow;\n\n  // A collection file is addressed by its name, while its `subPath` is the whole file path\n  return getEntryEditorPath(collectionName, fileName ?? entry.subPath, {\n    pullRequestNumber: pullRequest.fork ? pullRequest.number : undefined,\n  });\n};\n","/**\n * Open a URL in a new tab/window.\n * @param {string | undefined | null} url URL to open.\n * @param {object} [options] Options.\n * @param {boolean} [options.noopener] Whether to prevent the destination from accessing\n * `window.opener`. Defaults to `true`. Set to `false` for OAuth flows that require `postMessage`\n * communication.\n * @returns {Window | null} Opened window, if available.\n */\nexport const openNewTab = (url, { noopener = true } = {}) => {\n  if (!url) {\n    return null;\n  }\n\n  const features = noopener ? 'noopener,noreferrer' : '';\n\n  return window.open(url, '_blank', features);\n};\n","import { sleep } from '@sveltia/utils/misc';\nimport { flushSync } from 'svelte';\n\nimport { showAssetOverlay } from '$lib/services/assets/view';\nimport { cmsConfig } from '$lib/services/config';\nimport { showContentOverlay } from '$lib/services/contents/editor';\nimport { getEntryEditorPath } from '$lib/services/contents/editor/route';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\nimport { decodeURIComponentSafely, encodePathSegments } from '$lib/services/utils/url';\nimport { openNewTab } from '$lib/services/utils/window';\n\n/**\n * @import { InternalCmsConfig } from '$lib/types/private';\n */\n\n/**\n * View transition type: `forwards` and `backwards` move between pages, `previous` and `next` move\n * between the items listed on a page, e.g. the assets in the details overlay, and `unknown` is a\n * plain fade.\n * @typedef {'forwards' | 'backwards' | 'previous' | 'next' | 'unknown'} ViewTransitionType\n */\n\n/**\n * @typedef {object} GoToMethodOptions\n * @property {object} [state] History state to be included.\n * @property {boolean} [replaceState] Whether to replace the history state.\n * @property {boolean} [notifyChange] Whether to dispatch a `hashchange` event.\n * @property {ViewTransitionType} [transitionType] View transition type.\n */\n\n/**\n * Whether the app has an overlay. Some elements have to be `inert` while an overlay is displayed.\n * We cannot use the `<Modal>` component for these overlays because it will make everything inert,\n * including the toast notifications and announced page title.\n */\nexport const hasOverlay = createDerivedState(\n  () => showContentOverlay.current || showAssetOverlay.current,\n);\n\n/**\n * Name of the currently selected page.\n */\nexport const selectedPageName = createRawState('');\n\n/**\n * Page status to be announced by screen readers.\n */\nexport const announcedPageStatus = createRawState('');\n\n/**\n * Name of the main area on the current page, e.g. the collection or asset folder being viewed,\n * shown in the document title. Empty when the page has no specific name, e.g. Settings.\n */\nexport const mainAreaTitle = createRawState('');\n\n/**\n * Title of the overlay covering the page, e.g. the entry being edited, shown in the document title\n * in preference to {@link mainAreaTitle}. Empty while no overlay is open.\n */\nexport const overlayTitle = createRawState('');\n\n/**\n * Parse the URL and return the decoded result.\n * @param {string} [href] URL. Omit this to use the current URL.\n * @returns {{ path: string, params: Record<string, string> }} Path and search params.\n */\nexport const parseLocation = (href = window.location.href) => {\n  const hashPath = new URL(href).hash.substring(1);\n  // Split the hash into a path and a query string by hand rather than parsing it as a URL of its\n  // own, which would resolve any `.` or `..` segment, even a percent-encoded one, so that searching\n  // for `..` would lead to the root path. A second `#` ends both\n  const [pathname, ...query] = hashPath.split('#')[0].split('?');\n  const searchParams = new URLSearchParams(query.join('?'));\n\n  return {\n    // Give the path a leading slash if it lacks one, e.g. a link with the slashes percent-encoded.\n    // Drop any trailing slash before decoding, so a hand-typed `#/collections/` resolves the same\n    // way as `#/collections` rather than matching no route at all. The root path is left as is\n    path: decodeURIComponentSafely(\n      `${pathname.startsWith('/') ? '' : '/'}${pathname}`.replace(/(?!^)\\/+$/, ''),\n    ),\n    params: Object.fromEntries(\n      // Merge multiple values of the same key with a comma, e.g. `?a=1&a=2` becomes `{ a: '1,2' }`.\n      // This is to support both `?tags=tag1,tag2` and `?tags=tag1&tags=tag2` formats for dynamic\n      // default values.\n      [...new Set(searchParams.keys())].map((key) => [key, searchParams.getAll(key).join(',')]),\n    ),\n  };\n};\n\n/**\n * Currently active view transition, if any. Used to prevent nested transitions from aborting the\n * active one, which would cause “Transition was skipped” errors in the browser console.\n * @type {ViewTransition | null}\n */\nlet activeTransition = null;\n\n/**\n * Longest time, in milliseconds, the running view transition waits for the holds added with\n * {@link holdViewTransition} before it takes the snapshot of the new state anyway.\n */\nexport const VIEW_TRANSITION_HOLD_LIMIT = 300;\n\n/**\n * Promises the running view transition waits for before the new state is captured.\n * @type {Set<Promise<any>>}\n */\nconst transitionHolds = new Set();\n/**\n * Whether the running view transition has been skipped, in which case it doesn’t wait for holds.\n */\nlet transitionSkipped = false;\n/**\n * Function to stop waiting for the holds, once the running transition has been skipped, if any.\n * @type {(() => void) | undefined}\n */\nlet stopWaitingForHolds = undefined;\n\n/**\n * Make the running view transition wait for the given promise before it captures the new state,\n * for up to {@link VIEW_TRANSITION_HOLD_LIMIT} milliseconds, so that content loaded asynchronously,\n * such as an image in the asset details overlay, is part of the animation rather than popping in\n * once it’s over. Call this while the content is being updated; the call does nothing if no\n * transition is running.\n * @param {Promise<any>} promise Promise to wait for. A rejection counts as settled.\n */\nexport const holdViewTransition = (promise) => {\n  if (activeTransition) {\n    transitionHolds.add(promise);\n  }\n};\n\n/**\n * Wait for the holds added with {@link holdViewTransition}, up to the time limit, and clear them.\n */\nconst waitForTransitionHolds = async () => {\n  if (!transitionHolds.size || transitionSkipped) {\n    transitionHolds.clear();\n\n    return;\n  }\n\n  const skipped = /** @type {PromiseWithResolvers<void>} */ (Promise.withResolvers());\n\n  stopWaitingForHolds = skipped.resolve;\n\n  await Promise.race([\n    Promise.allSettled(transitionHolds),\n    sleep(VIEW_TRANSITION_HOLD_LIMIT),\n    skipped.promise,\n  ]);\n\n  stopWaitingForHolds = undefined;\n  transitionHolds.clear();\n};\n\n// Finish the running view transition as soon as a key is pressed. Until the animation is over, the\n// transition overlay catches every hit test, and Sveltia UI only activates a button with its\n// keyboard shortcut if a hit test finds the button, so a shortcut pressed right after the page\n// changed would be ignored, e.g. Accel+S or Escape right after the entry editor opened, and the\n// browser would handle Accel+S itself. The listener is added as the module is loaded, so it runs\n// before the one Sveltia UI adds once a component with a shortcut is mounted. Rendering stays\n// suppressed until the new state has been captured, even for a skipped transition, so it also stops\n// waiting for the content it holds for, e.g. while the user flips through assets with a key\nglobalThis.addEventListener?.(\n  'keydown',\n  () => {\n    if (activeTransition) {\n      activeTransition.skipTransition();\n      transitionSkipped = true;\n      stopWaitingForHolds?.();\n    }\n  },\n  { capture: true },\n);\n\n/**\n * Start page transition, if possible, after updating the content.\n * @param {ViewTransitionType} transitionType View transition type.\n * @param {() => void} updateContent Function to trigger a content update.\n * @see https://developer.chrome.com/docs/web-platform/view-transitions/same-document\n */\nexport const startViewTransition = (transitionType, updateContent) => {\n  // Fall back to a direct update if the View Transitions API is unavailable, or if a transition is\n  // already running (e.g. a redirect `goto()` inside `navigate()`), to avoid aborting it.\n  if (!document.startViewTransition || activeTransition) {\n    updateContent();\n    return;\n  }\n\n  const options = {\n    types: [transitionType],\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    update: async () => {\n      updateContent();\n      await sleep(50);\n      await new Promise((resolve) => {\n        flushSync(() => {\n          resolve(undefined);\n        });\n      });\n      await waitForTransitionHolds();\n    },\n  };\n\n  // Firefox for Android currently doesn’t support the options parameter of `startViewTransition`\n  // and will throw a `TypeError` if provided.\n  // @see https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition\n  try {\n    const transition = document.startViewTransition(options);\n\n    activeTransition = transition;\n    transitionSkipped = false;\n\n    // The browser skips a transition it can’t animate — most often because the document is hidden,\n    // e.g. the user switched to another tab while a save was in flight — and says so by rejecting\n    // `ready` with an `InvalidStateError`. The `update` callback still runs, so the content is up\n    // to date and there’s nothing to recover from, but the rejection has to be observed or it\n    // reaches the console as `Uncaught (in promise) InvalidStateError`\n    transition.ready.catch(() => undefined);\n\n    // `finished` only rejects when `update` itself failed, which is a real error worth reporting.\n    // It also has to be observed here, because `finally()` re-throws whatever it received\n    transition.finished\n      .catch((/** @type {any} */ ex) => {\n        // eslint-disable-next-line no-console\n        console.error(ex);\n      })\n      .finally(() => {\n        activeTransition = null;\n        // A hold added once the new state had been captured has nothing left to delay\n        transitionHolds.clear();\n      });\n  } catch {\n    // A browser that throws while the transition is being set up leaves nothing to wait for, so\n    // don’t let a stale handle block every later transition\n    activeTransition = null;\n    updateContent();\n  }\n};\n\n/**\n * Determine the transition type with the Navigation API, which knows where the URL we came from\n * sits in the session history relative to the current one. Unlike a comparison of the two paths,\n * this reflects the direction the user actually moved in, including navigation between two\n * different sections of the app or between two URLs with the same number of path segments.\n * @param {string} oldURL URL before the navigation.\n * @returns {ViewTransitionType | undefined} Transition type, or `undefined` if the API is\n * unavailable or the previous entry is no longer in the history, e.g. because it has been replaced.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API\n */\nconst getTransitionTypeFromHistory = (oldURL) => {\n  const currentIndex = window.navigation?.currentEntry?.index ?? -1;\n\n  if (currentIndex === -1) {\n    return undefined;\n  }\n\n  // The same URL can appear more than once in the history, so pick the entry closest to the current\n  // one, which is the one the user has most likely just left.\n  const [oldIndex] = window.navigation\n    .entries()\n    .filter(({ url, index }) => url === oldURL && index !== currentIndex)\n    .map(({ index }) => index)\n    .sort((a, b) => Math.abs(a - currentIndex) - Math.abs(b - currentIndex));\n\n  if (oldIndex === undefined) {\n    return undefined;\n  }\n\n  return oldIndex < currentIndex ? 'forwards' : 'backwards';\n};\n\n/**\n * Determine the transition type by comparing the two paths. This is a fallback for browsers without\n * the Navigation API, and for navigation the API cannot place in the history.\n * @param {string} oldURL URL before the navigation.\n * @param {string} newURL URL after the navigation.\n * @param {RegExp} routeRegex Regex to match a specific route.\n * @returns {ViewTransitionType} Transition type.\n */\nconst getTransitionTypeFromPaths = (oldURL, newURL, routeRegex) => {\n  const oldPath = parseLocation(oldURL).path;\n  const newPath = parseLocation(newURL).path;\n  // Compare paths to see if it’s a navigation within the same section, e.g. `/collections` to\n  // `/collections/posts`.\n  const inSameSection = routeRegex.test(oldPath) && routeRegex.test(newPath);\n  // Count the number of path segments; navigating from `/collections` to `/collections/posts` and\n  // `/collections/posts` to `/collections/posts/new` is forwards, while `/assets/-/all` to\n  // `/assets` is backwards\n  const oldPathSegmentCount = oldPath.split('/').length;\n  const newPathSegmentCount = newPath.split('/').length;\n\n  if (!inSameSection || oldPathSegmentCount === newPathSegmentCount) {\n    return 'unknown';\n  }\n\n  return oldPathSegmentCount < newPathSegmentCount ? 'forwards' : 'backwards';\n};\n\n/**\n * Update the content when the `hashchange` event is triggered. This function aims to support page\n * transition via the browser’s back/forward navigation.\n * @param {HashChangeEvent} event `hashchange` event.\n * @param {() => void} updateContent Function to trigger a content update.\n * @param {RegExp} routeRegex Regex to match a specific route.\n */\nexport const updateContentFromHashChange = (event, updateContent, routeRegex) => {\n  const { isTrusted, oldURL, newURL } = event;\n\n  // If `isTrusted` is `true`, it’s the browser’s back/forward navigation, so we need to start\n  // transitioning. If `false`, the event is triggered by the `goto` method below and transition has\n  // already started; in that case, just finish updating the content.\n  if (!isTrusted) {\n    updateContent();\n    return;\n  }\n\n  const transitionType =\n    getTransitionTypeFromHistory(oldURL) ?? getTransitionTypeFromPaths(oldURL, newURL, routeRegex);\n\n  startViewTransition(transitionType, () => updateContent());\n};\n\n/**\n * Navigate to a different URL or replace the current URL. This is similar to SvelteKit’s `goto`\n * method but assumes hash-based SPA routing.\n * @param {string} path URL path. It will appear in th URL hash but omit the leading `#` sign here.\n * Encode any entry or asset path in it with {@link encodePathSegments}, so a file or folder name\n * containing a `%`, `#` or `?` sign makes it through the URL hash intact and is decoded back to the\n * same name by {@link parseLocation}.\n * @param {GoToMethodOptions} [options] Options.\n */\nexport const goto = async (\n  path,\n  { state = {}, replaceState = false, notifyChange = true, transitionType = 'unknown' } = {},\n) => {\n  const { path: currentPath } = parseLocation();\n\n  // If we’re already on this page AND not updating state, don’t navigate or trigger a transition.\n  // The given path is encoded, while the current one is decoded\n  if (\n    currentPath === decodeURIComponentSafely(path) &&\n    !Object.keys(state).length &&\n    !replaceState\n  ) {\n    return;\n  }\n\n  // Keep the query string, which the page may have been opened with, as a hash change would\n  const { origin, pathname, search, hash } = window.location;\n  const oldURL = `${origin}${pathname}${search}${hash}`;\n  const newURL = `${origin}${pathname}${search}#${path}`;\n  // `from` is the URL of the previous history entry, which {@link goBack} relies on. Replacing the\n  // current entry doesn’t change what the previous entry is, so carry the value over; the entry\n  // being replaced is gone and must not become `from`, or a direct link followed by an in-place\n  // URL update would send the user out of the app on Back\n  const from = replaceState ? window.history.state?.from : oldURL;\n  /** @type {[any, string, string]} */\n  const args = [{ ...state, from }, '', newURL];\n\n  if (replaceState) {\n    window.history.replaceState(...args);\n  } else {\n    window.history.pushState(...args);\n  }\n\n  if (notifyChange) {\n    startViewTransition(transitionType, () => {\n      window.dispatchEvent(new HashChangeEvent('hashchange', { oldURL, newURL }));\n    });\n  }\n};\n\n/**\n * Route pattern for the shorthand link to an entry that Netlify/Decap CMS accepts, which is\n * documented alongside their Open Authoring feature as a way to hand contributors a direct link.\n * They redirect it to their own entry route, which is the same one Sveltia CMS uses, so a site\n * migrating over keeps any such link it has already published working.\n * @see https://decapcms.org/docs/open-authoring/\n */\nconst LEGACY_ENTRY_ROUTE_REGEX = /^\\/edit\\/(?<collectionName>[^/]+)\\/(?<subPath>.+)$/;\n\n/**\n * Redirect a Netlify/Decap CMS entry shorthand link, e.g. `#/edit/posts/hello`, to the equivalent\n * Sveltia CMS route, e.g. `#/collections/posts/entries/hello`. The current URL is replaced rather\n * than pushed, so the shorthand doesn’t sit in the history and send the user back to it.\n * @returns {boolean} `true` if the current URL was a shorthand link and a redirect has been\n * started, in which case the caller has nothing left to do for this navigation.\n */\nexport const redirectLegacyEntryLink = () => {\n  const { path, params } = parseLocation();\n  const { collectionName, subPath } = path.match(LEGACY_ENTRY_ROUTE_REGEX)?.groups ?? {};\n\n  if (!collectionName || !subPath) {\n    return false;\n  }\n\n  // Carry any query string over, so the editor locale and dynamic default values survive\n  const query = new URLSearchParams(params).toString();\n\n  goto(`${getEntryEditorPath(collectionName, subPath)}${query ? `?${query}` : ''}`, {\n    replaceState: true,\n  });\n\n  return true;\n};\n\n/**\n * Page names that make up the whole route. Unlike the content library and the other pages that\n * take a path of their own, anything following these in the URL is a dead link.\n */\nconst STANDALONE_PAGE_NAMES = ['workflow', 'menu'];\n/**\n * Search modes set by the pages that search their own items.\n * @type {Record<string, 'contents' | 'assets'>}\n */\nconst PAGE_SEARCH_MODES = { collections: 'contents', assets: 'assets' };\n\n/**\n * Result of {@link resolveRoute}: a URL to redirect to, a dead link, or the page to show along with\n * the search mode to set. `searchMode` is `undefined` when the current search mode is to be kept.\n * @typedef {{ redirect: string } | { notFound: true } | {\n * pageName: string, searchMode: 'contents' | 'assets' | null | undefined }} ResolvedRoute\n */\n\n/**\n * Determine which page to show for the given URL path.\n * @param {string} path URL path, as returned by {@link parseLocation}.\n * @param {string[]} pageNames Names of the available pages.\n * @returns {ResolvedRoute} Result.\n */\nexport const resolveRoute = (path, pageNames) => {\n  // The page name has to fill the whole first path segment, so `/collections-foo` doesn’t pass for\n  // the content library and land on a page that can’t make sense of the rest of the path\n  const { pageName } = path.match(`^\\\\/(?<pageName>${pageNames.join('|')})(?=\\\\/|$)`)?.groups ?? {};\n\n  // The CMS configuration has moved to the Administration page\n  if (path === '/config') {\n    return { redirect: '#/admin/config' };\n  }\n\n  if (!pageName) {\n    // The bare `#/` path is where the app starts, so open the content library. Any other unknown\n    // path is a dead link. Show a Not Found page instead of redirecting, which would hide the fact\n    // that the URL the user followed no longer goes anywhere\n    return path === '/' ? { redirect: '#/collections' } : { notFound: true };\n  }\n\n  if (STANDALONE_PAGE_NAMES.includes(pageName) && path !== `/${pageName}`) {\n    return { notFound: true };\n  }\n\n  // The content library and the asset library search their own items. The search page keeps the\n  // current mode, and any other page has nothing to search\n  return {\n    pageName,\n    searchMode: pageName === 'search' ? undefined : (PAGE_SEARCH_MODES[pageName] ?? null),\n  };\n};\n\n/**\n * Go back to the previous page if possible, or navigate to the given fallback URL.\n * @param {string} path Fallback URL path. With the Navigation API, the previous page is only\n * returned to when it’s at this path, or when `returnTo` accepts its path.\n * @param {GoToMethodOptions & { returnTo?: (path: string) => boolean }} [options] Options to be\n * passed to {@link goto}, and `returnTo` to tell which other previous pages to return to, e.g. the\n * search results an entry was opened from.\n */\nexport const goBack = (path, { returnTo, ...options } = {}) => {\n  const transitionType = 'backwards';\n\n  // Use the Navigation API if available, which is more reliable than `window.history`\n  if (window.navigation?.currentEntry) {\n    const { index } = window.navigation.currentEntry;\n    const { sameDocument, url } = window.navigation.entries()[index - 1] ?? {};\n    const previousPath = url ? parseLocation(url).path : undefined;\n\n    if (\n      sameDocument &&\n      previousPath !== undefined &&\n      (previousPath === decodeURIComponentSafely(path) || returnTo?.(previousPath))\n    ) {\n      startViewTransition(transitionType, () => {\n        window.navigation.back();\n      });\n    } else {\n      goto(path, { ...options, transitionType });\n    }\n\n    return;\n  }\n\n  if (window.history.state?.from) {\n    startViewTransition(transitionType, () => {\n      window.history.back();\n    });\n  } else {\n    goto(path, { ...options, transitionType });\n  }\n};\n\n/**\n * Get the path the entry editor goes back to: the collections list for a singleton file, or the\n * collection entries list otherwise — the folder being browsed for a collection with nested\n * entries, so the user lands where they opened the entry from.\n * @param {object} args Arguments.\n * @param {string | undefined} args.collectionName Name of the entry’s collection.\n * @param {string} [args.dirPath] Folder being browsed in a collection with nested entries, if any.\n * @returns {string} Route path.\n */\nexport const getEntryEditorBackPath = ({ collectionName, dirPath = '' }) => {\n  if (collectionName === '_singletons') {\n    return '/collections';\n  }\n\n  return dirPath\n    ? encodePathSegments(`/collections/${collectionName}/filter/${dirPath}`)\n    : `/collections/${collectionName}`;\n};\n\n/**\n * Open the production site in a new browser tab.\n */\nexport const openProductionSite = () => {\n  const { display_url: displayURL, _siteURL: siteURL } = /** @type {InternalCmsConfig} */ (\n    cmsConfig.current\n  );\n\n  openNewTab(displayURL || siteURL || '/');\n};\n","<script module>\n  /**\n   * The instance that last set {@link mainAreaTitle}. A page transition can mount the next area\n   * before the previous one is destroyed, and the outgoing cleanup must not wipe the incoming\n   * title.\n   * @type {object | undefined}\n   */\n  let titleOwner;\n</script>\n\n<script>\n  import { mainAreaTitle } from '$lib/services/app/navigation';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Snippet} [primaryToolbar] Primary toolbar content.\n   * @property {Snippet} [secondaryToolbar] Secondary toolbar content.\n   * @property {Snippet} [mainContent] Main content.\n   * @property {Snippet} [secondarySidebar] Secondary sidebar content.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let {\n    primaryToolbar = undefined,\n    secondaryToolbar = undefined,\n    mainContent = undefined,\n    secondarySidebar = undefined,\n    ...rest\n  } = $props();\n\n  const instance = {};\n\n  // The accessible name of the area also names the document, so the browser tab and history\n  // entries say which collection or folder is open rather than just the app name\n  $effect(() => {\n    titleOwner = instance;\n    mainAreaTitle.current = rest['aria-label'] ?? '';\n\n    return () => {\n      if (titleOwner === instance) {\n        mainAreaTitle.current = '';\n      }\n    };\n  });\n</script>\n\n<!-- One `main` per page: the area holding the page’s content, as opposed to the sidebar -->\n<main class=\"wrapper\" {...rest}>\n  {@render primaryToolbar?.()}\n  <div role=\"none\" class=\"main-inner\">\n    <div role=\"none\" class=\"main-inner-main\">\n      {@render secondaryToolbar?.()}\n      {@render mainContent?.()}\n    </div>\n    {@render secondarySidebar?.()}\n  </div>\n</main>\n\n<style>\n  .wrapper {\n    flex: auto;\n    display: flex;\n    flex-direction: column;\n    overflow: hidden;\n    height: 100%;\n    background-color: var(--sui-primary-background-color);\n\n    @media (768px <= width) {\n      view-transition-name: page-main;\n    }\n\n    :global {\n      .sui.toolbar.primary {\n        justify-content: center;\n\n        @media (width < 768px) {\n          border-block-end: var(--area-border);\n          background-color: var(--sui-secondary-background-color);\n        }\n      }\n    }\n  }\n\n  /* The area sits next to the primary sidebar and below the global toolbar */\n  :global(.resizable-pane) > .wrapper {\n    border-block-start: var(--area-border);\n    border-inline-start: var(--area-border);\n    border-start-start-radius: 16px;\n  }\n\n  .main-inner {\n    flex: auto;\n    display: flex;\n    overflow: hidden;\n\n    .main-inner-main {\n      flex: auto;\n      display: flex;\n      flex-direction: column;\n      overflow: hidden;\n    }\n\n    :global {\n      .secondary-sidebar {\n        flex: none;\n        overflow: auto;\n        box-sizing: content-box;\n        width: 320px;\n        background-color: var(--sui-secondary-background-color);\n\n        @media (768px <= width) {\n          border-block-start: var(--area-border);\n          border-inline-start: var(--area-border);\n          border-start-start-radius: 16px;\n        }\n\n        [role='listbox'] {\n          padding: 12px;\n        }\n      }\n    }\n  }\n</style>\n","<script>\n  import { _, isRTL } from '@sveltia/i18n';\n  import { Button, Icon } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [aria-label] `aria-label` property on the button.\n   * @property {boolean} [useShortcut] Whether to enable Escape keyboard shortcut. Default: `false`.\n   * @property {(event: MouseEvent) => void} [onclick] `click` event handler.\n   */\n\n  /** @type {Props} */\n  let { 'aria-label': ariaLabel, useShortcut = false, onclick = undefined } = $props();\n</script>\n\n<Button\n  variant=\"ghost\"\n  iconic\n  aria-label={ariaLabel ?? _('back')}\n  keyShortcuts={useShortcut ? 'Escape' : undefined}\n  class=\"back\"\n  {onclick}\n>\n  {#snippet startIcon()}\n    <Icon name={isRTL() ? 'arrow_forward' : 'arrow_back'} />\n  {/snippet}\n</Button>\n","<!--\n  @component\n  The main area of a Administration section: a toolbar with the section’s title and actions, above\n  its content. On a small screen, the toolbar leads back to the Menu page, which lists the sections.\n-->\n<script>\n  import { Spacer, Toolbar } from '@sveltia/ui';\n\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import BackButton from '$lib/components/common/page-toolbar/back-button.svelte';\n  import { getAdditions } from '$lib/services/app/additions';\n  import { goBack } from '$lib/services/app/navigation';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} title Title of the section.\n   * @property {Snippet} [actions] Buttons for the toolbar.\n   * @property {Snippet} children Content.\n   */\n\n  /** @type {Props} */\n  let { title, actions = undefined, children } = $props();\n\n  // Sveltia CMS Additions, whose chunk is loaded along with the backend if it’s enabled\n  const additions = $derived(getAdditions());\n</script>\n\n<PageContainerMainArea id=\"admin-container\" aria-label={title}>\n  {#snippet primaryToolbar()}\n    <Toolbar variant=\"primary\" ariaLabel={title}>\n      {#if env.isSmallScreen}\n        <BackButton\n          onclick={() => {\n            goBack('/menu');\n          }}\n        />\n      {/if}\n      <h2 role=\"none\">{title}</h2>\n      <Spacer flex />\n      {@render actions?.()}\n    </Toolbar>\n  {/snippet}\n  {#snippet mainContent()}\n    <div role=\"none\" class=\"content\">\n      {#if additions}\n        <additions.UpdateInfobar />\n      {/if}\n      {@render children()}\n    </div>\n  {/snippet}\n</PageContainerMainArea>\n\n<style>\n  h2 {\n    font-size: var(--sui-font-size-x-large);\n  }\n\n  .content {\n    display: flex;\n    flex-direction: column;\n    gap: 16px;\n    overflow: auto;\n    padding: 16px;\n    height: 100%;\n  }\n</style>\n","/**\n * Splits text into the characters a reader sees, keeping an emoji or a letter with its combining\n * marks whole.\n */\nconst graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });\n/**\n * A letter or a digit, which an initial has to be.\n */\nconst LETTER_REGEX = /[\\p{L}\\p{N}]/u;\n/**\n * Chinese, Japanese and Korean, whose names aren’t abbreviated to initials: the first character of\n * the family name stands for the person instead, as an avatar commonly shows.\n */\nconst CJK_REGEX = /[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}]/u;\n\n/**\n * Get the first letter or digit of a word, whole.\n * @param {string} word Word, which has one.\n * @returns {string} Letter.\n */\nconst getFirstLetter = (word) =>\n  /** @type {Intl.SegmentData} */ (\n    [...graphemeSegmenter.segment(word)].find(({ segment }) => LETTER_REGEX.test(segment))\n  ).segment;\n\n/**\n * Get the initials of a name to show in place of an avatar, e.g. `AL` for Ada Lovelace, or `山` for\n * 山田太郎.\n * @param {string} name Name.\n * @param {string} [fallback] Another name to take them from if the name has no letters, e.g. one\n * made of emoji, such as the username.\n * @returns {string} Initials, at most two, or an empty string.\n */\nexport const getInitials = (name, fallback = '') => {\n  // Only words with a letter, so each one has an initial\n  const words = name\n    .trim()\n    .split(/\\s+/)\n    .filter((word) => LETTER_REGEX.test(word));\n\n  if (!words.length) {\n    return fallback ? getInitials(fallback) : '';\n  }\n\n  if (CJK_REGEX.test(getFirstLetter(words[0]))) {\n    return getFirstLetter(words[0]);\n  }\n\n  return words.slice(0, 2).map(getFirstLetter).join('').toLocaleUpperCase();\n};\n","<!--\n  @component\n  A person’s avatar: their picture, if there’s one, or else their initials. It’s decorative, as the\n  name is always given next to it, or in a label around it.\n-->\n<script>\n  import { getInitials } from '$lib/services/utils/name';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [name] Name of the person, whose initials are shown.\n   * @property {string} [username] Username of the person, whose initials are shown if the name has\n   * no letters, e.g. one made of emoji.\n   * @property {string} [text] Text to show instead of initials, e.g. `+2` for people left out of a\n   * list, which is shown in a neutral color.\n   * @property {string} [src] URL of their picture. The initials are shown if it can’t be loaded.\n   * @property {number} [size] Width and height in pixels.\n   * @property {string} [class] Class name to add, e.g. to place the avatar.\n   */\n\n  /** @type {Props} */\n  let {\n    name = '',\n    username = '',\n    text = undefined,\n    src = undefined,\n    size = 24,\n    class: className = undefined,\n  } = $props();\n\n  /** URL of a picture that couldn’t be loaded. */\n  let brokenSrc = $state();\n</script>\n\n{#if src && src !== brokenSrc}\n  <img\n    class={['avatar', className]}\n    {src}\n    alt=\"\"\n    width={size}\n    height={size}\n    loading=\"lazy\"\n    onerror={() => {\n      brokenSrc = src;\n    }}\n  />\n{:else}\n  <span\n    class={['avatar', 'initials', text !== undefined && 'neutral', className]}\n    style:--size=\"{size}px\"\n    aria-hidden=\"true\"\n  >\n    {text ?? getInitials(name, username)}\n  </span>\n{/if}\n\n<style>\n  .avatar {\n    flex: none;\n    border-radius: 50%;\n  }\n\n  .initials {\n    display: inline-flex;\n    justify-content: center;\n    align-items: center;\n    width: var(--size);\n    height: var(--size);\n    background-color: var(--sui-info-background-color);\n    color: var(--sui-info-foreground-color);\n    font-size: calc(var(--size) * 0.42);\n    font-weight: var(--sui-font-weight-bold);\n    line-height: 1;\n\n    &.neutral {\n      background-color: var(--sui-secondary-background-color);\n      color: var(--sui-secondary-foreground-color);\n    }\n  }\n</style>\n","<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} title The panel title.\n   * @property {Snippet} [actions] Controls shown at the end of the panel header.\n   * @property {Snippet} [children] Slot content.\n   */\n\n  /** @type {Props} */\n  let { title, actions = undefined, children = undefined } = $props();\n\n  const id = $props.id();\n</script>\n\n<section role=\"group\" class=\"panel\" aria-labelledby=\"panel-{id}-label\">\n  <header>\n    <h3 id=\"panel-{id}-label\">{title}</h3>\n    {@render actions?.()}\n  </header>\n  <div>\n    {@render children?.()}\n  </div>\n</section>\n\n<style>\n  section {\n    overflow: hidden;\n    height: 100%;\n    display: flex;\n    flex-direction: column;\n  }\n\n  header {\n    flex: none;\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    border-bottom: 1px solid var(--sui-secondary-border-color);\n    padding: 0 16px;\n    height: var(--sui-primary-toolbar-size);\n  }\n\n  h3 {\n    flex: auto;\n    font-size: var(--sui-font-size-x-large);\n  }\n\n  div {\n    flex: auto;\n    overflow: auto;\n\n    :global {\n      h4 {\n        display: flex;\n        align-items: center;\n        padding: 12px 12px 8px;\n        font-size: var(--sui-font-size-large);\n      }\n\n      & > .empty {\n        padding: 16px;\n      }\n\n      .empty {\n        color: var(--sui-secondary-foreground-color);\n        font-size: var(--sui-font-size-small);\n      }\n\n      .sui.button.ref {\n        display: flex;\n        justify-content: flex-start;\n        gap: 8px;\n        padding: 8px;\n        width: -moz-available;\n        width: -webkit-fill-available;\n        width: stretch;\n        height: auto;\n      }\n    }\n  }\n</style>\n","import { _ } from '@sveltia/i18n';\n\nimport { getAdditions } from '$lib/services/app/additions';\nimport { user } from '$lib/services/user/account.svelte';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Component } from 'svelte';\n */\n\n/**\n * A section of the Administration page, listed in its sidebar.\n * @typedef {object} AdminSection\n * @property {string} key Key, which is also the last segment of its path, e.g. `users` for\n * `/admin/users`.\n * @property {string} labelKey Message key of its label.\n * @property {string} icon Material Symbols icon name.\n * @property {Component<{ title: string }>} [component] Panel it shows, for a section that comes\n * with the Sveltia CMS Additions chunk.\n */\n\n/**\n * Path of the Administration page.\n */\nexport const ADMIN_PATH = '/admin';\n\n/**\n * Section showing the CMS configuration, for developers.\n * @type {AdminSection}\n */\nconst CONFIG_SECTION = { key: 'config', labelKey: 'cms_config', icon: 'data_object' };\n\n/**\n * Get the sections of the Administration page the signed-in user can see: user management and the\n * service’s settings for an admin of Sveltia CMS Additions, which come with its chunk, and the CMS\n * configuration while developer mode is on. With none, the page isn’t offered at all.\n * @returns {AdminSection[]} Sections, in the order they’re listed.\n */\nexport const getAdminSections = () => [\n  ...(user.account?.role === 'admin' ? (getAdditions()?.adminSections ?? []) : []),\n  ...(prefs.devModeEnabled ? [CONFIG_SECTION] : []),\n];\n\n/**\n * Get the path of an Administration section.\n * @param {string} key Section key, e.g. `users`.\n * @returns {string} Path, e.g. `/admin/users`.\n */\nexport const getAdminSectionPath = (key) => `${ADMIN_PATH}/${key}`;\n\n/**\n * Key of the section shown last, which the Administration button opens again, like the Assets\n * button opens the folder shown last.\n */\nexport const lastAdminSectionKey = createRawState('');\n\n/**\n * Get the path the Administration button opens: the section shown last, if the user can still see\n * it, or else the page itself, which opens on its first section.\n * @returns {string | undefined} Path, or `undefined` if the user can see none of the page.\n */\nexport const getAdminLink = () => {\n  const sections = getAdminSections();\n  const key = lastAdminSectionKey.current;\n\n  if (!sections.length) {\n    return undefined;\n  }\n\n  return sections.some((section) => section.key === key) ? getAdminSectionPath(key) : ADMIN_PATH;\n};\n\n/**\n * Get the section the given URL path points to.\n * @param {string} path URL path, e.g. `/admin/users`.\n * @returns {string | undefined} Section key, an empty string for the page itself, which lists the\n * sections on a small screen, or `undefined` if the path isn’t on the page or goes deeper than a\n * section.\n */\nexport const getAdminSectionKey = (path) =>\n  path.match(/^\\/admin(?:\\/(?<key>[^/]+))?$/)?.groups?.key ??\n  (path === ADMIN_PATH ? '' : undefined);\n\n/**\n * Get what to announce to screen reader users when the Administration page shows another section,\n * like the other pages announce what they show.\n * @param {object} args Arguments.\n * @param {string | undefined} args.sectionKey Key of the section in the URL, from\n * {@link getAdminSectionKey}.\n * @param {AdminSection[]} args.sections Sections the user can see.\n * @param {boolean} args.isSmallScreen Whether the screen is small, where the page itself lists the\n * sections. On a large screen, it opens the first section instead, which is announced then.\n * @returns {string} Announcement, or an empty string if there’s nothing to announce yet.\n */\nexport const getAdminPageAnnouncement = ({ sectionKey, sections, isSmallScreen }) => {\n  if (sectionKey === '') {\n    return isSmallScreen ? _('viewing_admin_section_list') : '';\n  }\n\n  const section = sections.find(({ key }) => key === sectionKey);\n\n  return section\n    ? _('viewing_x_admin_section', { values: { section: _(section.labelKey) } })\n    : _('page_not_found');\n};\n","import { encodeBase64 } from '@sveltia/utils/file';\n\nimport SveltiaLogo from '$lib/assets/sveltia-logo.svg?raw&inline';\nimport { cmsConfig } from '$lib/services/config';\nimport {\n  THUMBNAIL_TRANSFORM_OPTIONS,\n  transformImage,\n} from '$lib/services/utils/media/image/transform';\nimport mime from '$lib/services/utils/mime';\nimport { fetchOK } from '$lib/services/utils/networking';\nimport {\n  createDerivedState,\n  createRawState,\n  createRootEffect,\n} from '$lib/services/utils/state.svelte';\n\n/**\n * @import { InternalImageTransformationOptions } from '$lib/types/private';\n */\n\nconst IMAGE_DATA_URL_REGEX = /^data:(image\\/[a-zA-Z0-9.+-]+);base64,/;\n\n/**\n * Default title for the CMS, used when `app_title` is not specified in the configuration.\n */\nexport const DEFAULT_APP_TITLE = 'Sveltia CMS';\n\n/**\n * Default logo for the CMS, used when `logo` is not specified in the configuration. This is a\n * base64-encoded SVG of the Sveltia logo, inlined to avoid an extra network request.\n */\nexport const DEFAULT_APP_LOGO_URL = `data:image/svg+xml;base64,${btoa(SveltiaLogo)}`;\n\n/**\n * The app title, derived from the CMS configuration’s `app_title` field.\n */\nexport const appTitle = createDerivedState(() => cmsConfig.current?.app_title || DEFAULT_APP_TITLE);\n\n/**\n * The app logo URL, derived from the CMS configuration. It checks both `logo.src` and the\n * deprecated `logo_url` for backward compatibility.\n */\nexport const appLogoURL = createDerivedState(\n  () => cmsConfig.current?.logo?.src || cmsConfig.current?.logo_url || DEFAULT_APP_LOGO_URL,\n);\n\n/**\n * The app logo MIME type, derived from the app logo URL. It extracts the MIME type from data URLs\n * or uses the file extension for regular URLs.\n */\nexport const appLogoType = createDerivedState(() => {\n  const url = appLogoURL.current;\n  const match = url.match(IMAGE_DATA_URL_REGEX);\n\n  if (match) {\n    return match[1];\n  }\n\n  return mime.getType(url) ?? undefined;\n});\n\n/**\n * Get a data URL for the given image blob, transformed to the specified options. This is used to\n * generate the app icon for the CMS manifest and Apple touch icon.\n * @param {Blob} blob Original image blob.\n * @param {InternalImageTransformationOptions} options Transformation options.\n * @returns {Promise<string>} Data URL of the transformed image. Its type is the transformed blob’s,\n * as the thumbnail options let another format stand in where WebP can’t be encoded natively.\n */\nconst getDataURL = async (blob, options) => {\n  const transformedBlob = await transformImage(blob, options);\n  const data = await encodeBase64(transformedBlob);\n\n  return `data:${transformedBlob.type};base64,${data}`;\n};\n\n/**\n * The app icon URL, derived from the app logo URL. It generates a WebP thumbnail of the logo, or a\n * PNG or JPEG one where WebP can’t be encoded natively, for use in the app manifest and as the\n * Apple touch icon. If the transformation fails, it falls back to no icon. The available sizes are\n * 192x192 and 512x512, which are recommended for PWA support.\n * @type {{ current: { small: string, large: string } | undefined }}\n * @see https://developer.chrome.com/docs/lighthouse/pwa/installable-manifest\n */\nexport const appIconURLs = createRawState();\n\ncreateRootEffect(() => {\n  // Set when a newer logo supersedes this run. Fetching and transforming the logo is asynchronous,\n  // so a run that started earlier may settle after a later one has, and it must not overwrite the\n  // newer icons with its own stale ones\n  let superseded = false;\n  const logoURL = appLogoURL.current;\n\n  (async () => {\n    /** @type {{ small: string, large: string } | undefined} */\n    let iconURLs;\n\n    try {\n      const blob = await (await fetchOK(logoURL)).blob();\n\n      const [small, large] = await Promise.all([\n        getDataURL(blob, { ...THUMBNAIL_TRANSFORM_OPTIONS, width: 192, height: 192 }),\n        getDataURL(blob, THUMBNAIL_TRANSFORM_OPTIONS),\n      ]);\n\n      iconURLs = { small, large };\n    } catch {\n      iconURLs = undefined;\n    }\n\n    if (!superseded) {\n      appIconURLs.current = iconURLs;\n    }\n  })();\n\n  // Called before the next run starts\n  return () => {\n    superseded = true;\n  };\n});\n\n/**\n * The app manifest URL, derived from the app title and logo. It generates a blob URL containing a\n * JSON manifest for the CMS, which can be used for PWA support.\n * @see https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Manifest\n */\nexport const appManifestURL = createDerivedState(() => {\n  const title = appTitle.current;\n  const iconURLs = appIconURLs.current;\n\n  if (!iconURLs) {\n    return undefined;\n  }\n\n  const { origin, pathname } = window.location;\n  // Both icons are transformed the same way, so they have the same type\n  const type = /** @type {RegExpMatchArray} */ (iconURLs.small.match(IMAGE_DATA_URL_REGEX))[1];\n\n  const manifest = {\n    name: title,\n    short_name: title,\n    start_url: `${origin}${pathname}`,\n    display: 'standalone',\n    icons: [\n      { src: iconURLs.small, sizes: '192x192', type },\n      { src: iconURLs.large, sizes: '512x512', type },\n    ],\n  };\n\n  const blob = new Blob([JSON.stringify(manifest)], { type: 'application/manifest+json' });\n\n  // Use a blob URL instead of a data URL to prevent a long string from being inlined in the HTML.\n  // The blob URL will be revoked when the page is unloaded.\n  return URL.createObjectURL(blob);\n});\n","import { PACKAGE_NAME, UNPKG_ORIGIN, version as userVersion } from '$lib/services/app';\nimport { getScriptVersionSpec } from '$lib/services/app/dependencies';\n\n/**\n * How often to check for a new version.\n */\nexport const UPDATE_CHECK_INTERVAL = 60 * 60 * 1000; // 1 hour\n\n/**\n * How long to wait before offering a reload once a new version has been found. Redirects are\n * cached by the UNPKG CDN, so an older script may still be served right after a release, and the\n * notification would persist when the user reloads the page.\n * @see https://unpkg.com/#cache-behavior\n */\nexport const UPDATE_CACHE_TIMEOUT = 10 * 60 * 1000; // 10 min\n\n/**\n * Get the latest published version of a package, by default the application. It’s read from UNPKG\n * rather than the npm registry, as the CMS already loads files from there, so a site’s Content\n * Security Policy doesn’t need to allow another origin.\n * @param {object} [args] Arguments.\n * @param {string} [args.versionSpec] Version range or tag to resolve, e.g. `^1`, as it appears in\n * the script URL. The latest release if omitted or empty.\n * @param {string} [args.packageName] Package name, e.g. `@sveltia/cms-additions`.\n * @returns {Promise<string | undefined>} Version, or `undefined` if it couldn’t be fetched.\n */\nexport const getLatestVersion = async ({ versionSpec = '', packageName = PACKAGE_NAME } = {}) => {\n  try {\n    const response = await fetch(\n      `${UNPKG_ORIGIN}/${packageName}${versionSpec ? `@${versionSpec}` : ''}/package.json`,\n    );\n\n    if (!response.ok) {\n      return undefined;\n    }\n\n    const { version } = await response.json();\n\n    return typeof version === 'string' && version ? version : undefined;\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Compare two versions like `1.2.3`, part by part as numbers, so `0.10.0` is newer than `0.9.0`. A\n * missing part counts as `0`, so `1.0` is the same as `1.0.0`, and a pre-release suffix is ignored.\n * @param {string} a Version.\n * @param {string} b Version.\n * @returns {number} Negative if `a` is older, positive if newer, zero if the same.\n */\nexport const compareVersions = (a, b) => {\n  const [x, y] = [a, b].map((version) =>\n    version\n      .split('-')[0]\n      .split('.')\n      .map((part) => Number(part) || 0),\n  );\n\n  return Array.from({ length: Math.max(x.length, y.length) }).reduce(\n    (/** @type {number} */ result, _, index) => result || (x[index] ?? 0) - (y[index] ?? 0),\n    0,\n  );\n};\n\n/**\n * Check whether the given version is newer than the running one. An older version can be reported\n * right after a release, while the CDN still serves a cached `package.json`, and that’s not an\n * update.\n * @param {string} latestVersion Latest published version, e.g. `1.2.3`.\n * @returns {boolean} Result.\n */\nconst isNewerVersion = (latestVersion) => compareVersions(latestVersion, userVersion) > 0;\n\n/**\n * Check whether a new version of the application is available, and whether a reload would pick it\n * up. It would if the script, classic or module, is loaded from the CDN without the exact version,\n * as long as the new version is within the range in the URL, e.g. `^1`: the URL is resolved the way\n * the CDN would. If it’s pinned in the script tag, a newer release is outside its range or it’s\n * installed via npm, a reload won’t update the instance, so a console warning is shown instead.\n * @returns {Promise<boolean>} `true` if a reload would update the application.\n */\nexport const isUpdateAvailable = async () => {\n  const versionSpec = getScriptVersionSpec();\n\n  if (versionSpec !== undefined) {\n    const resolvedVersion = await getLatestVersion({ versionSpec });\n\n    if (resolvedVersion && isNewerVersion(resolvedVersion)) {\n      return true;\n    }\n\n    // Without a version, the URL already serves the latest release\n    if (!versionSpec) {\n      return false;\n    }\n  }\n\n  const latestVersion = await getLatestVersion();\n\n  if (!latestVersion || !isNewerVersion(latestVersion)) {\n    return false;\n  }\n\n  // eslint-disable-next-line no-console\n  console.warn(\n    `[Sveltia CMS] A new version (${latestVersion}) is available. ` +\n      `You are using version ${userVersion}. ` +\n      'Update the pinned version in your script tag or package.json to upgrade.',\n  );\n\n  return false;\n};\n","import {\n  DEFAULT_AUTH_ROOT,\n  FORGEJO_BACKEND_NAME,\n} from '$lib/services/backends/git/gitea/constants';\nimport { getInstanceURL } from '$lib/services/backends/git/shared/repository';\n\n/**\n * @import { ForgejoBackend, GiteaBackend } from '$lib/types/public';\n */\n\n/**\n * Get the OAuth base URL, which is the URL of the Gitea/Forgejo instance, from the backend\n * configuration. The `base_url` option takes precedence. Without it, the Forgejo backend derives\n * the URL from the required `api_root` option, as Decap CMS does, while the Gitea backend falls\n * back to Gitea.com.\n * @param {GiteaBackend | ForgejoBackend} backend Backend configuration.\n * @returns {string} OAuth base URL, e.g. `https://codeberg.org`.\n */\nexport const getAuthRoot = ({ name, base_url: baseURL, api_root: apiRoot }) =>\n  baseURL ??\n  (name === FORGEJO_BACKEND_NAME && apiRoot ? getInstanceURL(apiRoot) : DEFAULT_AUTH_ROOT);\n","import { createLRUMap } from '$lib/services/utils/cache';\n\n/**\n * @import { RepositoryInfo } from '$lib/types/private';\n * @import { LRUMap } from '$lib/services/utils/cache';\n */\n\n/**\n * Function to find the tree SHA of a directory at the given commit or branch.\n * @typedef {(ref: string, dirPath: string) => Promise<string | undefined>} DirSHALookup\n */\n\n/**\n * Maximum number of directory lookups kept by each backend. The check for remote changes looks up\n * the old and new heads at the same time, so more than one is kept.\n */\nconst MAX_DIR_LOOKUPS = 4;\n/**\n * Pattern of a full commit SHA, either SHA-1 or SHA-256.\n */\nconst COMMIT_SHA_REGEX = /^[\\da-f]{40,64}$/;\n\n/**\n * Wrap a function that looks the tree SHA of a directory up, so that a lookup at a commit is made\n * only once. A backend that can’t resolve a `ref:path` expression in a single request has to list\n * the directory holding the one looked up, and the check for remote changes and the file list that\n * follows it look the same directory up at the same commit. The tree of a directory at a commit\n * never changes, so the result can be reused, but a branch name moves, so it’s always looked up.\n * @param {RepositoryInfo} repository Repository info, whose owner and name are part of the cache\n * key, so a switch to another repository doesn’t reuse the lookups.\n * @param {DirSHALookup} lookUp Function to look a directory up without the cache.\n * @returns {{ fetchDirSHA: DirSHALookup, resetDirLookups: () => void }} The cached lookup, and a\n * function to forget the lookups, used in tests.\n */\nexport const createCachedDirSHALookup = (repository, lookUp) => {\n  /** @type {LRUMap<string, string | undefined>} */\n  const lookups = createLRUMap(MAX_DIR_LOOKUPS);\n\n  return {\n    /**\n     * Find the tree SHA of a directory, reusing a lookup made at the same commit.\n     * @param {string} ref Commit SHA or branch name.\n     * @param {string} dirPath Directory path relative to the repository root.\n     * @returns {Promise<string | undefined>} Tree SHA, or `undefined` if the directory doesn’t\n     * exist.\n     */\n    fetchDirSHA: async (ref, dirPath) => {\n      const key = `${repository.owner}/${repository.repo}:${ref}:${dirPath}`;\n\n      if (lookups.has(key)) {\n        return lookups.get(key);\n      }\n\n      const sha = await lookUp(ref, dirPath);\n\n      if (COMMIT_SHA_REGEX.test(ref)) {\n        lookups.set(key, sha);\n      }\n\n      return sha;\n    },\n    /**\n     * Forget the lookups.\n     */\n    resetDirLookups: () => {\n      lookups.clear();\n    },\n  };\n};\n","import { backend } from '$lib/services/backends';\nimport { isDeployingCommit } from '$lib/services/backends/git/shared/commits';\nimport { cmsConfig } from '$lib/services/config';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { CommitOptions } from '$lib/types/private';\n * @import { GitBackend } from '$lib/types/public';\n */\n\n/**\n * Get the two options that decide whether a commit skips CI, as the configured Git backend sets\n * them.\n * @returns {{ skipCI?: boolean, autoDeploy?: boolean }} Options, both `undefined` when no Git\n * backend is configured, in which case there is no CI to skip.\n */\nconst getSkipCIOptions = () => {\n  const { current: _cmsConfig } = cmsConfig;\n  const { current: _backend } = backend;\n\n  if (!_cmsConfig || !_backend?.isGit) {\n    return {};\n  }\n\n  const { skip_ci: skipCI, automatic_deployments: autoDeploy } = /** @type {GitBackend} */ (\n    _cmsConfig.backend\n  );\n\n  return { skipCI, autoDeploy };\n};\n\n/**\n * Whether the skip CI configuration is explicitly set in the CMS configuration. This is used to\n * determine if the skip CI option should be shown in the UI.\n */\nexport const skipCIConfigured = createDerivedState(() => {\n  const { skipCI, autoDeploy } = getSkipCIOptions();\n\n  return typeof skipCI === 'boolean' || typeof autoDeploy === 'boolean';\n});\n\n/**\n * Whether the skip CI option is enabled in the CMS configuration.\n */\nexport const skipCIEnabled = createDerivedState(() => {\n  const { skipCI, autoDeploy } = getSkipCIOptions();\n\n  return skipCI === true || autoDeploy === false;\n});\n\n/**\n * Check whether a commit is to be reported as publishing its changes, in a toast after saving. That\n * only applies when the skip CI option is configured; without it, every commit is published, and\n * saying so each time would be noise. See {@link isDeployingCommit}.\n * @param {Partial<CommitOptions>} options Commit options.\n * @returns {boolean} Result.\n */\nexport const isPublishingCommit = (options) =>\n  skipCIConfigured.current && isDeployingCommit(options);\n","/* eslint-disable no-await-in-loop */\n\nimport { mapConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport {\n  getRepositoryDatabase,\n  readCacheEntries,\n  updateCacheEntries,\n} from '$lib/services/utils/database';\n\n/**\n * The direct children of a Git tree, each as a `[name, sha]` pair. Names rather than paths are\n * kept, as a tree with the same content has the same ID wherever it is.\n * @typedef {object} TreeListing\n * @property {[string, string][]} trees Subtrees.\n * @property {[string, string][]} blobs Files.\n */\n\n/**\n * A directory to list along with its subdirectories.\n * @typedef {object} TreeRoot\n * @property {string} path Directory path relative to the repository root, or an empty string for\n * the root itself.\n * @property {string} [sha] The directory’s tree ID. Without it, the directory is always listed,\n * though its subdirectories can still come from the cache.\n */\n\n/**\n * Name of the IndexedDB store holding the tree listings, keyed with tree IDs.\n */\nexport const TREE_CACHE_STORE_NAME = 'tree-cache';\n\n/**\n * List the files in the given directories and all their subdirectories, a level at a time. A\n * backend that can only list a directory a page at a time would otherwise have to list every file\n * again whenever the branch moves on, however small the change. Instead, the listing of each\n * directory is cached under its tree ID, which stands for the whole content of the directory: a\n * directory whose ID is cached is taken from the cache along with everything inside it that hasn’t\n * changed, so a commit only costs the directories on the paths to the files it touched. Being\n * content-addressed, a cached listing can’t go stale. The directories of a level that have to be\n * listed are requested at the same time.\n * @param {object} args Arguments.\n * @param {{ databaseName?: string }} args.repository Repository info, which names the database.\n * @param {TreeRoot[]} args.roots Directories to list. None of them should be inside another.\n * @param {(path: string) => Promise<TreeListing>} args.fetchTreeListing Function to list the\n * direct children of a directory, given its path relative to the repository root.\n * @param {boolean} args.cacheable Whether the listings fetched can be cached, which is only the\n * case when `fetchTreeListing` reads a commit rather than a branch: a branch may move on between\n * requests, which could file a listing under the ID of another version of the directory.\n * @param {number} [args.concurrency] Maximum number of directories listed at the same time.\n * @returns {Promise<{ type: 'blob', path: string, sha: string }[]>} Files, with paths relative to\n * the repository root.\n */\nexport const listTrees = async ({\n  repository,\n  roots,\n  fetchTreeListing,\n  cacheable,\n  concurrency,\n}) => {\n  const db = getRepositoryDatabase(repository, TREE_CACHE_STORE_NAME);\n  /** @type {Map<string, TreeListing>} */\n  const cache = await readCacheEntries(db);\n  /** @type {Map<string, TreeListing>} */\n  const fetched = new Map();\n  /** @type {Map<string, Promise<TreeListing>>} */\n  const pending = new Map();\n  /** @type {Set<string>} */\n  const visited = new Set();\n  /** @type {{ type: 'blob', path: string, sha: string }[]} */\n  const blobs = [];\n  let completed = false;\n\n  /**\n   * Get the listing of a directory, from the cache if possible. A tree that appears more than once,\n   * like two directories with the same content, is only listed once.\n   * @param {TreeRoot} root Directory.\n   * @returns {Promise<TreeListing>} Listing.\n   */\n  const getListing = async ({ path, sha }) => {\n    if (!sha) {\n      return fetchTreeListing(path);\n    }\n\n    visited.add(sha);\n\n    const cached = cache.get(sha);\n\n    if (cached) {\n      return cached;\n    }\n\n    if (!pending.has(sha)) {\n      pending.set(\n        sha,\n        fetchTreeListing(path).then((listing) => {\n          // Git has no empty trees, so an empty listing means the directory couldn’t be found,\n          // which mustn’t stick to its ID\n          if (cacheable && (listing.trees.length || listing.blobs.length)) {\n            fetched.set(sha, listing);\n          }\n\n          return listing;\n        }),\n      );\n    }\n\n    return /** @type {Promise<TreeListing>} */ (pending.get(sha));\n  };\n\n  try {\n    let level = roots;\n\n    while (level.length) {\n      const listings = await mapConcurrently(level, getListing, { concurrency });\n      const currentLevel = level;\n\n      level = listings.flatMap(({ trees, blobs: files }, index) => {\n        const { path } = currentLevel[index];\n        const prefix = path ? `${path}/` : '';\n\n        files.forEach(([name, sha]) => {\n          blobs.push({ type: 'blob', path: `${prefix}${name}`, sha });\n        });\n\n        return trees.map(([name, sha]) => ({ path: `${prefix}${name}`, sha }));\n      });\n    }\n\n    completed = true;\n  } finally {\n    // Keep what has been listed even if the walk failed, so a retry doesn’t start over, but only\n    // prune the trees no longer in the repository once everything has been seen\n    await updateCacheEntries(\n      db,\n      fetched,\n      completed ? [...cache.keys()].filter((sha) => !visited.has(sha)) : [],\n    );\n  }\n\n  return blobs;\n};\n","import { getField } from '$lib/services/contents/entry/fields';\nimport { getSnapshot } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * PendingEntry,\n * } from '$lib/types/private';\n * @import { Field, RelationField } from '$lib/types/public';\n */\n\n/**\n * Check whether the given field is a Relation field referring to the given collection’s entries.\n * @param {Field | undefined} field Field configuration.\n * @param {string} collectionName Collection name.\n * @returns {field is RelationField} Result.\n */\nexport const isRelationFieldOf = (field, collectionName) =>\n  field?.widget === 'relation' &&\n  /** @type {RelationField} */ (field).collection === collectionName;\n\n/**\n * A set of values a pending entry can be referenced from.\n * @typedef {object} ValueSource\n * @property {FlattenedEntryContent} valueMap Flattened values.\n * @property {Omit<GetFieldArgs, 'keyPath' | 'valueMap'>} [fieldArgs] Arguments to look up the field\n * holding a value, so only a Relation field pointing at the entry’s collection counts. Omitted for\n * the values of rich text editor components, whose fields can’t be looked up by key path; any\n * matching value counts there.\n */\n\n/**\n * Get the pending entries of the given draft that belong to the given collection.\n * @param {EntryDraft} draft Draft being edited.\n * @param {string} collectionName Collection name.\n * @returns {PendingEntry[]} Pending entries.\n */\nexport const getPendingEntriesByCollection = (draft, collectionName) =>\n  draft.pendingEntries.filter((pendingEntry) => pendingEntry.collectionName === collectionName);\n\n/**\n * Get the pending entries of the given draft that are new to the given collection, leaving out the\n * existing entries edited from a Relation field, which already take up a slot, a slug and a number.\n * @param {EntryDraft} draft Draft being edited.\n * @param {string} collectionName Collection name.\n * @returns {PendingEntry[]} Pending entries.\n */\nexport const getNewPendingEntriesByCollection = (draft, collectionName) =>\n  getPendingEntriesByCollection(draft, collectionName).filter(({ baseEntry }) => !baseEntry);\n\n/**\n * Get the values the entry being edited holds: the field values in every locale, and the values of\n * the rich text editor components, which are stored apart.\n * @param {EntryDraft} draft Draft.\n * @returns {ValueSource[]} Value sources.\n */\nconst getDraftValueSources = ({\n  collectionName,\n  fileName,\n  isIndexFile,\n  currentValues,\n  extraValues,\n}) => [\n  ...Object.values(currentValues).map((valueMap) => ({\n    valueMap,\n    fieldArgs: { collectionName, fileName, isIndexFile },\n  })),\n  ...Object.values(extraValues).map((valueMap) => ({ valueMap })),\n];\n\n/**\n * Get the values a pending entry holds in every locale, which is what a pending entry created from\n * a field of that entry is referenced by.\n * @param {PendingEntry} pendingEntry Pending entry.\n * @returns {ValueSource[]} Value sources.\n */\nconst getPendingEntryValueSources = ({ collectionName, entry }) =>\n  Object.values(entry.locales).flatMap(({ content }) =>\n    content ? [{ valueMap: content, fieldArgs: { collectionName } }] : [],\n  );\n\n/**\n * Check whether any of the given sources holds one of the values the pending entry goes by, in a\n * field that can refer to it. Two collections can have an entry going by the same value, e.g. a tag\n * and a category both stored by the slug `news`, so a value alone doesn’t tell which entry a field\n * refers to.\n * @param {ValueSource[]} sources Value sources to look in.\n * @param {PendingEntry} pendingEntry Pending entry.\n * @returns {boolean} Whether the entry is referenced.\n */\nconst isReferencedIn = (sources, { collectionName, values }) =>\n  sources.some(({ valueMap, fieldArgs }) =>\n    Object.entries(valueMap).some(([keyPath, value]) => {\n      if (!values.includes(value)) {\n        return false;\n      }\n\n      if (!fieldArgs) {\n        return true;\n      }\n\n      const field = getField({ ...fieldArgs, valueMap, keyPath });\n\n      // A value in a field that can’t be looked up is given the benefit of the doubt\n      return !field || isRelationFieldOf(field, collectionName);\n    }),\n  );\n\n/**\n * Get the pending entries of the given draft that are still referenced, as they are on the draft.\n * See {@link getReferencedPendingEntries}, which detaches them for saving.\n * @param {EntryDraft} draft Draft.\n * @returns {Set<PendingEntry>} Referenced pending entries.\n */\nexport const getReferencedPendingEntrySet = (draft) => {\n  const sources = getDraftValueSources(draft);\n  /** @type {Set<PendingEntry>} */\n  const referenced = new Set();\n\n  /**\n   * Add the pending entries referenced by the sources collected so far.\n   * @returns {boolean} Whether any entry has been added.\n   */\n  const grow = () => {\n    const newlyReferenced = draft.pendingEntries.filter(\n      (pendingEntry) => !referenced.has(pendingEntry) && isReferencedIn(sources, pendingEntry),\n    );\n\n    newlyReferenced.forEach((pendingEntry) => {\n      referenced.add(pendingEntry);\n      sources.push(...getPendingEntryValueSources(pendingEntry));\n    });\n\n    return newlyReferenced.length > 0;\n  };\n\n  while (grow()) {\n    // Keep going until no more entries are reached\n  }\n\n  return referenced;\n};\n\n/**\n * Get the existing entries edited from a Relation field that the given draft still refers to, as\n * they are on the draft. The cheap check comes first, as this runs on every change: nothing is\n * looked up unless the draft has such an entry at all.\n * @param {EntryDraft} draft Draft.\n * @returns {PendingEntry[]} Edited pending entries.\n */\nexport const getReferencedEditedEntries = (draft) =>\n  draft.pendingEntries?.some(({ baseEntry }) => !!baseEntry)\n    ? [...getReferencedPendingEntrySet(draft)].filter(({ baseEntry }) => !!baseEntry)\n    : [];\n\n/**\n * Get the pending entries of the given draft that are still referenced, so they can be saved along\n * with the entry. An entry was created from a Relation field and selected there right away, so it’s\n * only wanted as long as one of the values it goes by is still held by a field in one of the\n * locales, including a field of a rich text editor component. A deselected entry is left out of\n * the save rather than created for nothing. A pending entry can also be referenced by another\n * pending entry rather than by the entry being edited, when it was created from a Relation field of\n * that entry’s quick-add dialog, so the referenced set is grown until no more entries are reached,\n * and one referenced only by a deselected entry is left out along with it.\n * @param {EntryDraft} draft Draft to save.\n * @returns {PendingEntry[]} Pending entries, in the order they were added, detached from the\n * reactive draft: they go into the entry and asset stores, whose consumers may clone them, which a\n * `$state` proxy can’t be.\n */\nexport const getReferencedPendingEntries = (draft) => {\n  const referenced = getReferencedPendingEntrySet(draft);\n\n  return draft.pendingEntries\n    .filter((pendingEntry) => referenced.has(pendingEntry))\n    .map((pendingEntry) => getSnapshot(pendingEntry));\n};\n","/**\n * @import { CodeField } from '$lib/types/public';\n */\n\n/**\n * Get the property names a Code field stores the code and the language under: the `keys` option,\n * with its default.\n * @param {CodeField} fieldConfig Field configuration.\n * @returns {{ code: string, lang: string } | undefined} Property names, or `undefined` if the field\n * has the `output_code_only` option, so its value is the code itself rather than an object.\n */\nexport const getCodeKeys = (fieldConfig) => {\n  const { output_code_only: outputCodeOnly = false, keys = { code: 'code', lang: 'lang' } } =\n    fieldConfig;\n\n  return outputCodeOnly ? undefined : keys;\n};\n\n/**\n * Check if the given key is one of the property names a Code field stores the code and the language\n * under. See {@link getCodeKeys}.\n * @param {CodeField} fieldConfig Field configuration.\n * @param {string} key Key.\n * @returns {boolean} Result.\n */\nexport const isCodeValueKey = (fieldConfig, key) => {\n  const keys = getCodeKeys(fieldConfig);\n\n  return !!keys && [keys.code, keys.lang].includes(key);\n};\n","import { processNestedTemplates } from '$lib/services/common/template/nested';\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { parseTransformations } from '$lib/services/common/transformations';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport {\n  getFieldDisplayValue,\n  getVisibleFieldDisplayValue,\n} from '$lib/services/contents/entry/values';\n\n/**\n * @import {\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalLocaleCode,\n * StringTransformation,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath, ListField, VariableFieldType } from '$lib/types/public';\n */\n\n/**\n * Format the summary template of an Object field, or of a List field item when `itemKeyPath` is\n * given.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {FieldKeyPath} [args.itemKeyPath] Key path of the value to summarize, e.g. `images.0` for\n * the first item of a List field. Defaults to `keyPath`.\n * @param {FlattenedEntryContent} args.valueMap Entry content.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {string} [args.summaryTemplate] Summary template, e.g. `{{fields.slug}}`.\n * @param {boolean} [args.hasSingleSubField] Whether the field is a List field with a single `field`\n * instead of multiple `fields`, so the item is the value itself.\n * @returns {string} Formatted summary.\n */\nexport const formatSummary = ({\n  collectionName,\n  fileName,\n  keyPath,\n  itemKeyPath = keyPath,\n  valueMap,\n  isIndexFile = false,\n  locale,\n  summaryTemplate,\n  hasSingleSubField = false,\n}) => {\n  /** @type {GetFieldArgs} */\n  const getFieldArgs = { collectionName, fileName, keyPath: '', valueMap, isIndexFile };\n\n  if (!summaryTemplate) {\n    if (hasSingleSubField) {\n      return getFieldDisplayValue({\n        ...getFieldArgs,\n        keyPath: itemKeyPath,\n        locale,\n        plainText: true,\n      });\n    }\n\n    return getVisibleFieldDisplayValue({\n      valueMap,\n      locale,\n      keyPath: itemKeyPath,\n      keyPathPrefix: `${itemKeyPath}.`,\n      getFieldArgs,\n      plainText: true,\n    });\n  }\n\n  /**\n   * Get the display value of the subfield a template tag refers to.\n   * @param {string} tag Template tag without transformations, e.g. `fields.slug`.\n   * @param {StringTransformation[]} [parsedTransformations] Transformations to apply, which may\n   * contain nested template tags. Omitted for a nested tag, which can’t have transformations.\n   * @returns {string} Display value.\n   */\n  const getDisplayValue = (tag, parsedTransformations) => {\n    const fieldName = stripFieldTagPrefix(tag);\n\n    if (hasSingleSubField) {\n      // For single-field lists, check if the requested field name matches the actual field name\n      const listFieldConfig = /** @type {ListField} */ (getField({ ...getFieldArgs, keyPath }));\n\n      if (!('field' in listFieldConfig) || listFieldConfig.field.name !== fieldName) {\n        return '';\n      }\n    }\n\n    return getFieldDisplayValue({\n      ...getFieldArgs,\n      keyPath: hasSingleSubField ? itemKeyPath : `${itemKeyPath}.${fieldName}`,\n      locale,\n      plainText: true,\n      transformations: parsedTransformations\n        ? processNestedTemplates(parsedTransformations, (innerTag) =>\n            getDisplayValue(parseTransformations(innerTag).value),\n          )\n        : undefined,\n    });\n  };\n\n  /**\n   * Replacer function for template tags in the summary template. It extracts the field value based\n   * on the placeholder, applies any transformations, and returns the display value to replace the\n   * tag.\n   * @param {string} _match The entire matched template tag, e.g. `{{fields.slug | upper}}`. Unused\n   * in the function but required by the `replace` method.\n   * @param {string} placeholder The content inside the template tag, e.g. `fields.slug | upper`.\n   * @returns {string} The display value to replace the template tag.\n   */\n  const replacer = (_match, placeholder) => {\n    const { value: tag, transformations } = parseTransformations(placeholder);\n\n    return getDisplayValue(tag, transformations);\n  };\n\n  return replaceTemplateTags(summaryTemplate, replacer);\n};\n\n/**\n * Get the message logged when an Object field value or a List field item doesn’t have a type that\n * the field defines, so the developer can fix the content or the configuration.\n * @param {object} args Arguments.\n * @param {'object' | 'list'} args.fieldType Type of the field holding the value.\n * @param {string | undefined} args.type Type the value has, if any.\n * @param {string} args.typeKey Property holding the type.\n * @param {{ name: string }[]} args.types Types the field defines.\n * @returns {string} Message.\n */\nexport const getUnknownTypeMessage = ({ fieldType, type, typeKey, types }) => {\n  const target = fieldType === 'list' ? 'list item' : 'object';\n\n  return type\n    ? `The “${type}” type is not defined for the ${fieldType} field.`\n    : `The type key is not found in the ${target}. The item must include the “${typeKey}” ` +\n        `property with one of the defined types: ${types.map((t) => t.name).join(', ')}`;\n};\n\n/**\n * Log a warning about an Object field value or a List field item that doesn’t have a type the field\n * defines, so the developer can fix the content or the configuration.\n * @param {object} args Arguments.\n * @param {'object' | 'list'} args.fieldType Type of the field holding the value.\n * @param {FieldKeyPath} args.keyPath Key path of the Object field or the List field item.\n * @param {string | undefined} args.type Type the value has, if any.\n * @param {string} args.typeKey Property holding the type.\n * @param {{ name: string }[]} args.types Types the field defines.\n */\nexport const warnUnknownType = ({ fieldType, keyPath, ...args }) => {\n  const target = fieldType === 'list' ? 'List item' : 'Object field';\n\n  // eslint-disable-next-line no-console\n  console.warn(`${target} ${keyPath}: ${getUnknownTypeMessage({ fieldType, ...args })}`);\n};\n\n/**\n * Resolve the type of an Object field value or a List field item, along with the subfields and the\n * summary template that apply to it.\n * @param {object} args Arguments.\n * @param {VariableFieldType[]} [args.types] Types the field defines. `undefined` if the field\n * doesn’t have variable types.\n * @param {Field[]} [args.fields] Subfields of a field without variable types.\n * @param {string} [args.summary] Summary template of the field.\n * @param {string} [args.type] Type the value has, if any.\n * @returns {{\n * typeConfig: VariableFieldType | undefined,\n * unknownType: boolean,\n * subFields: Field[],\n * summaryTemplate: string | undefined,\n * }} Configuration of the type, if found; whether the field has variable types but the value\n * doesn’t have one of them; the subfields to show; and the summary template, which a type can\n * override.\n */\nexport const resolveVariableType = ({ types, fields, summary, type }) => {\n  if (!types) {\n    return {\n      typeConfig: undefined,\n      unknownType: false,\n      subFields: fields ?? [],\n      summaryTemplate: summary,\n    };\n  }\n\n  const typeConfig = type ? types.find(({ name }) => name === type) : undefined;\n\n  return {\n    typeConfig,\n    unknownType: !typeConfig,\n    subFields: typeConfig?.fields ?? [],\n    summaryTemplate: typeConfig?.summary || summary,\n  };\n};\n\n/**\n * Get the typed key path of a value that can have a variable type, such as an Object field or a\n * List field item, with the type it has.\n * @param {TypedFieldKeyPath} typedKeyPath Typed key path of the value, e.g. `hero` or\n * `sections.*`.\n * @param {string} [type] Type of the value, if the field has variable types.\n * @returns {TypedFieldKeyPath} Typed key path, e.g. `sections.*<banner>`.\n */\nexport const getTypedKeyPath = (typedKeyPath, type) =>\n  type ? `${typedKeyPath}<${type}>` : typedKeyPath;\n\n/**\n * Get the typed key path of a subfield of a value that can have a variable type.\n * @param {object} args Arguments.\n * @param {TypedFieldKeyPath} args.typedKeyPath Typed key path of the value, e.g. `sections.*`.\n * @param {string} [args.type] Type of the value, if the field has variable types.\n * @param {string} args.subFieldName Name of the subfield.\n * @returns {TypedFieldKeyPath} Typed key path, e.g. `sections.*<banner>.title`.\n */\nexport const getTypedSubKeyPath = ({ typedKeyPath, type, subFieldName }) =>\n  `${getTypedKeyPath(typedKeyPath, type)}.${subFieldName}`;\n","/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { Field, RelationField } from '$lib/types/public';\n */\n\n/**\n * Localize a field value copied from another locale. This supports a special case for the Relation\n * field: if the `value_field` option is something like `{{locale}}/{{slug}}`, the stored value is\n * prefixed with a locale code, which has to be replaced with the target locale. Any other value is\n * returned as is.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {any} args.value Value copied from the source locale.\n * @param {InternalLocaleCode} args.sourceLocale Source locale.\n * @param {InternalLocaleCode} args.targetLocale Target locale.\n * @returns {any} Localized value.\n */\nexport const getLocalizedRelationValue = ({ fieldConfig, value, sourceLocale, targetLocale }) => {\n  // Check the option rather than the widget: the Relation editor renders its options with the\n  // Select editor, passing on its own configuration with the `widget` changed to `select`\n  const { value_field: valueField } = /** @type {RelationField} */ (fieldConfig);\n\n  if (\n    typeof value !== 'string' ||\n    typeof valueField !== 'string' ||\n    !valueField.startsWith('{{locale}}/') ||\n    !value.startsWith(`${sourceLocale}/`)\n  ) {\n    return value;\n  }\n\n  return `${targetLocale}/${value.slice(sourceLocale.length + 1)}`;\n};\n","import { getLocalizedDateTimeValue } from '$lib/services/contents/fields/date-time/value';\nimport { getLocalizedRelationValue } from '$lib/services/contents/fields/relation/helpers/locale';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { Field } from '$lib/types/public';\n */\n\n/**\n * Localize a field value copied from another locale: a Relation field value prefixed with the\n * source locale gets the target locale instead, and a DateTime field value written in the source\n * locale with `localize_format: true` is written in the target locale. Any other value is returned\n * as is.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {any} args.value Value copied from the source locale.\n * @param {InternalLocaleCode} args.sourceLocale Source locale.\n * @param {InternalLocaleCode} args.targetLocale Target locale.\n * @returns {any} Localized value.\n */\nexport const getLocalizedFieldValue = (args) =>\n  getLocalizedDateTimeValue({ ...args, value: getLocalizedRelationValue(args) });\n","import { isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { getCodeKeys } from '$lib/services/contents/fields/code/helpers';\nimport { getLocalizedFieldValue } from '$lib/services/contents/fields/locale';\nimport { isValueEmpty } from '$lib/services/utils/object';\n\n/**\n * @import { CodeField, Field, FieldKeyPath } from '$lib/types/public';\n * @import { FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * Field types supporting the `duplicate_if_empty` i18n strategy: those holding a single, simple\n * value. A File, Image, Relation or Select field only supports it when it doesn’t accept multiple\n * values.\n */\nexport const DUPLICATE_IF_EMPTY_FIELD_TYPES = [\n  'code',\n  'datetime',\n  'file',\n  'image',\n  'markdown',\n  'number',\n  'relation',\n  'richtext',\n  'select',\n  'string',\n  'text',\n];\n\n/**\n * Check if the given field uses the `duplicate_if_empty` i18n strategy, which copies the default\n * locale’s value to the other locales where the value is empty, while leaving it editable there.\n * The strategy only applies to the field types listed in {@link DUPLICATE_IF_EMPTY_FIELD_TYPES};\n * any other field with the option works like a translatable field.\n * @param {Field} fieldConfig Field configuration.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/120\n */\nexport const isDuplicateIfEmptyField = (fieldConfig) =>\n  fieldConfig.i18n === 'duplicate_if_empty' &&\n  DUPLICATE_IF_EMPTY_FIELD_TYPES.includes(fieldConfig.widget ?? 'string') &&\n  !isFieldMultiple(fieldConfig);\n\n/**\n * Get the key path holding the main value of the given field, which tells whether the field is\n * empty. That’s the field’s own key path, except for a Code field that outputs the language along\n * with the code, whose value is an object holding the code under a key of its own.\n * @param {Field} fieldConfig Field configuration.\n * @param {FieldKeyPath} keyPath Key path of the field.\n * @returns {FieldKeyPath} Key path.\n */\nexport const getMainValueKeyPath = (fieldConfig, keyPath) => {\n  if (fieldConfig.widget !== 'code') {\n    return keyPath;\n  }\n\n  const keys = getCodeKeys(/** @type {CodeField} */ (fieldConfig));\n\n  return keys ? `${keyPath}.${keys.code}` : keyPath;\n};\n\n/**\n * Check if the given field is empty in the given locale’s content, so that the default locale’s\n * value takes its place.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.content Content of a locale.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Key path of the field.\n * @returns {boolean} Result.\n */\nexport const isFieldEmpty = ({ content, fieldConfig, keyPath }) =>\n  isValueEmpty(content[getMainValueKeyPath(fieldConfig, keyPath)]);\n\n/**\n * Find the field using the `duplicate_if_empty` i18n strategy that the given key path belongs to.\n * That’s the field at the key path, or, for a Code field that outputs the language along with the\n * code, the field above the `code` or `lang` key.\n * @param {FieldKeyPath} keyPath Key path of the value.\n * @param {(keyPath: FieldKeyPath) => Field | undefined} getFieldConfig Function to look up the\n * field configuration for a key path.\n * @returns {{ fieldConfig: Field, fieldKeyPath: FieldKeyPath } | undefined} Field and its key path,\n * or `undefined` if the key path doesn’t belong to such a field.\n */\nexport const findDuplicateIfEmptyField = (keyPath, getFieldConfig) => {\n  const fieldConfig = getFieldConfig(keyPath);\n\n  if (fieldConfig) {\n    return isDuplicateIfEmptyField(fieldConfig)\n      ? { fieldConfig, fieldKeyPath: keyPath }\n      : undefined;\n  }\n\n  const index = keyPath.lastIndexOf('.');\n\n  if (index < 0) {\n    return undefined;\n  }\n\n  const fieldKeyPath = keyPath.slice(0, index);\n  const parentFieldConfig = getFieldConfig(fieldKeyPath);\n\n  return parentFieldConfig?.widget === 'code' &&\n    isDuplicateIfEmptyField(parentFieldConfig) &&\n    getMainValueKeyPath(parentFieldConfig, fieldKeyPath) !== fieldKeyPath\n    ? { fieldConfig: parentFieldConfig, fieldKeyPath }\n    : undefined;\n};\n\n/**\n * Check if a locale follows the default locale for a `duplicate_if_empty` field, i.e. Its value is\n * empty or still the one copied from the default locale before the value was changed there. Such a\n * locale gets the new value of the default locale, while a value of its own is left alone.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {any} args.targetValue Current main value in the target locale.\n * @param {any} args.previousValue Main value in the default locale before the change.\n * @param {InternalLocaleCode} args.sourceLocale Default locale.\n * @param {InternalLocaleCode} args.targetLocale Target locale.\n * @returns {boolean} Result.\n */\nexport const followsDefaultLocale = ({\n  fieldConfig,\n  targetValue,\n  previousValue,\n  sourceLocale,\n  targetLocale,\n}) =>\n  isValueEmpty(targetValue) ||\n  targetValue ===\n    getLocalizedFieldValue({ fieldConfig, value: previousValue, sourceLocale, targetLocale });\n","import { isObject } from '@sveltia/utils/object';\n\nimport { getAllSubFields, someSubField } from '$lib/services/contents/fields/list/subfields';\nimport { formatSummary as formatObjectSummary } from '$lib/services/contents/fields/object/helpers';\nimport { isDuplicateIfEmptyField } from '$lib/services/contents/i18n/duplicate-if-empty';\nimport { isFieldMirrored, isFieldTranslatable } from '$lib/services/contents/i18n/fields';\n\n/**\n * @import { FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n * @import { Field, FieldKeyPath, ListField } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} ListFieldInfo\n * @property {boolean} hasSingleSubField Whether the List field has the `field` (singular) option.\n * @property {boolean} hasMultiSubFields Whether the List field has the `fields` (plural) option.\n * @property {boolean} hasVariableTypes Whether the List field has the variable `types` option.\n * @property {boolean} hasSubFields Whether the List field has sub-fields.\n */\n\n/**\n * Get information about the List field type.\n * @param {ListField} field Field.\n * @returns {ListFieldInfo} Field type information.\n */\nexport const getListFieldInfo = (field) => {\n  const hasSingleSubField = 'field' in field;\n  const hasMultiSubFields = 'fields' in field;\n  const hasVariableTypes = 'types' in field;\n\n  return {\n    hasSingleSubField,\n    hasMultiSubFields,\n    hasVariableTypes,\n    hasSubFields: hasSingleSubField || hasMultiSubFields || hasVariableTypes,\n  };\n};\n\n/**\n * Check whether any subfield of the given List or Object field, at any depth, has the `duplicate`,\n * `sync` or `duplicate_if_empty` i18n strategy. The items of a translatable List field with such a\n * subfield are paired across the locales by their position, as the subfield value is copied to the\n * item at the same position in every other locale.\n * @param {Field} fieldConfig Field configuration.\n * @returns {boolean} Result.\n */\nexport const hasDuplicatedSubField = (fieldConfig) =>\n  getAllSubFields(fieldConfig).some((subField) =>\n    someSubField(\n      subField,\n      (field) => isFieldMirrored(field.i18n) || isDuplicateIfEmptyField(field),\n    ),\n  );\n\n/**\n * Check whether the given field is a translatable List field whose items are paired across the\n * locales by their position, because it has a subfield with the `duplicate`, `sync` or\n * `duplicate_if_empty` i18n strategy. Such items are added, removed and moved in every locale at\n * once.\n * @param {Field} fieldConfig Field configuration.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/1065\n */\nexport const isPairedList = (fieldConfig) =>\n  fieldConfig.widget === 'list' &&\n  isFieldTranslatable(fieldConfig.i18n) &&\n  hasDuplicatedSubField(fieldConfig);\n\n/**\n * Get the key paths of the paired List fields among the given fields, including those nested in an\n * Object field, but not those in a List field’s items, which are numbered. See\n * {@link isPairedList}.\n * @param {Field[]} fields Fields.\n * @param {FieldKeyPath} [prefix] Key path of the parent field, if any.\n * @returns {FieldKeyPath[]} Key paths.\n */\nexport const getPairedListKeyPaths = (fields, prefix = '') =>\n  fields.flatMap((fieldConfig) => {\n    const keyPath = prefix ? `${prefix}.${fieldConfig.name}` : fieldConfig.name;\n\n    if (isPairedList(fieldConfig)) {\n      return [keyPath];\n    }\n\n    const { fields: subFields } = /** @type {{ fields?: Field[] }} */ (fieldConfig);\n\n    return fieldConfig.widget === 'object' && subFields\n      ? getPairedListKeyPaths(subFields, keyPath)\n      : [];\n  });\n\n/**\n * Check whether the editor should show a List field as a single item rather than as a list. That’s\n * the case for a field limited to one item with `max: 1`, as a developer may store a single object\n * in an array, so the user doesn’t need to see an item count, a list toggle or reorder controls. A\n * field holding more items than that, e.g. edited outside the CMS, is shown as a list, so the extra\n * items can be removed.\n * @param {object} args Arguments.\n * @param {ListField} args.fieldConfig Field configuration.\n * @param {number} args.itemCount Number of items the field holds.\n * @returns {boolean} Result.\n */\nexport const isSingleItemList = ({ fieldConfig, itemCount }) =>\n  fieldConfig.max === 1 && itemCount <= 1;\n\n/**\n * Format the summary template of a List field.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {FlattenedEntryContent} args.valueMap Entry content.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {string} [args.summaryTemplate] Summary template, e.g. `{{fields.slug}}`.\n * @param {boolean} args.hasSingleSubField Whether the field has a single `field` instead of\n * multiple `fields`.\n * @param {number} args.index List index.\n * @returns {string} Formatted summary.\n */\nexport const formatSummary = ({ index, ...args }) =>\n  formatObjectSummary({ ...args, itemKeyPath: `${args.keyPath}.${index}` });\n\n/**\n * Get the `each` block key that identifies a List field item. Object items carry a generated ID\n * that follows the item as the list is reordered; primitives can only be keyed by their position.\n * @param {any[]} items List items.\n * @param {number} index Target index.\n * @returns {string | number} Key.\n */\nexport const getListItemKey = (items, index) => {\n  const item = items[index];\n\n  return isObject(item) ? (item.__sc_item_id ?? index) : index;\n};\n\n/**\n * Tag the object items of a List field before they are added, removed or reordered, so that each\n * item remembers its original key path, which is used to revert changes correctly once the items\n * have shifted. Tags that are already set are kept, and primitive items are left alone.\n * @param {any[]} valueList List items, which are mutated in place.\n * @param {FieldKeyPath} keyPath Key path of the List field.\n * @param {object} [options] Options.\n * @param {boolean} [options.assignIds] Whether to also give each item a unique ID, so that a keyed\n * `each` block keeps following each item rather than its position.\n */\nexport const tagListItems = (valueList, keyPath, { assignIds = false } = {}) => {\n  valueList.forEach((item, index) => {\n    if (isObject(item)) {\n      if (assignIds) {\n        item.__sc_item_id ??= crypto.randomUUID();\n      }\n\n      item.__sc_item_original_key_path ??= `${keyPath}.${index}`;\n    }\n  });\n};\n","import { getField } from '$lib/services/contents/entry/fields';\nimport { getCodeKeys } from '$lib/services/contents/fields/code/helpers';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import { GetFieldArgs, OwnerField } from '$lib/types/private';\n * @import { CodeField, ListField } from '$lib/types/public';\n */\n\n/**\n * Get the field that owns a value stored under a key path without a field configuration of its\n * own: an item of a List field without subfields, e.g. `tags.0`, a KeyValue pair, e.g. `meta.foo`,\n * or the code or language of a Code field that outputs both, e.g. `snippet.code`. Such a value is\n * one part of its field’s value, so it’s copied and reverted along with the field.\n * @param {GetFieldArgs} getFieldArgs Arguments for the `getField` function, with the key path of a\n * value that `getField()` doesn’t resolve.\n * @returns {OwnerField | undefined} Key path and configuration of the owner field, or `undefined`\n * if the value doesn’t belong to such a field.\n */\nexport const getValueOwnerField = (getFieldArgs) => {\n  const { keyPath } = getFieldArgs;\n  const index = keyPath.lastIndexOf('.');\n\n  if (index < 0) {\n    return undefined;\n  }\n\n  // A KeyValue pair key is stored escaped, so the last dot always separates it from the field\n  const ownerKeyPath = keyPath.slice(0, index);\n  const fieldConfig = getField({ ...getFieldArgs, keyPath: ownerKeyPath });\n\n  if (!fieldConfig) {\n    return undefined;\n  }\n\n  const { widget: fieldType } = fieldConfig;\n\n  const owned =\n    fieldType === 'keyvalue' ||\n    (fieldType === 'list' &&\n      !getListFieldInfo(/** @type {ListField} */ (fieldConfig)).hasSubFields &&\n      isNumeric(keyPath.slice(index + 1))) ||\n    (fieldType === 'code' && !!getCodeKeys(/** @type {CodeField} */ (fieldConfig)));\n\n  return owned ? { keyPath: ownerKeyPath, fieldConfig } : undefined;\n};\n","import { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\nimport { getValueOwnerField } from '$lib/services/contents/entry/owner-field';\nimport { escapeKeySegment, unescapeKeySegment } from '$lib/services/utils/object';\n\n/**\n * @import { FlattenedEntryContent, GetFieldArgs } from '$lib/types/private';\n * @import { FieldKeyPath, KeyValueField } from '$lib/types/public';\n */\n\n/**\n * Regular expression to strip the key from a pair’s key path, e.g. `metadata.foo` → `metadata`.\n * The key can be empty, so use `*` instead of `+`.\n */\nexport const PAIR_KEY_PATH_REGEX = /\\.[^.]*$/;\n\n/**\n * Get the configuration of the KeyValue field that the given pair belongs to. A pair is stored\n * under an arbitrary key, e.g. `metadata.foo`, that `getField()` can’t resolve on its own, so the\n * field is looked up by the parent key path instead. See {@link getValueOwnerField}.\n * @param {GetFieldArgs} args Arguments for the `getField()` function, with a pair’s key path.\n * @returns {KeyValueField | undefined} Field configuration, or `undefined` if the key path doesn’t\n * belong to a KeyValue field.\n */\nexport const getKeyValueField = (args) => {\n  const fieldConfig = getValueOwnerField(args)?.fieldConfig;\n\n  return fieldConfig?.widget === 'keyvalue'\n    ? /** @type {KeyValueField} */ (fieldConfig)\n    : undefined;\n};\n\n/**\n * Get key-value pairs from the given flattened content. A key is stored escaped, so a dot in it\n * isn’t taken as a key path delimiter, and is unescaped here.\n * @param {FlattenedEntryContent} content Flattened content for a locale.\n * @param {FieldKeyPath} keyPath Field key path.\n * @param {object} [options] Options.\n * @param {boolean} [options.live] Whether the content may be mutated after this call, like the\n * draft’s live map, which {@link setPairs} mutates in place. Its key paths are then read as they\n * are right now, rather than from the index kept for a snapshot.\n * @returns {[string, string][]} Key-value pairs.\n */\nexport const getPairsFromContent = (content, keyPath, { live = true } = {}) => {\n  const prefix = `${keyPath}.`;\n\n  return /** @type {[string, string][]} */ (\n    getKeysByPrefix(content, prefix, { live }).map((key) => [\n      unescapeKeySegment(key.slice(prefix.length)),\n      content[key],\n    ])\n  );\n};\n\n/**\n * Replace the key-value pairs stored in the given flattened content. A key is escaped, so a dot in\n * it isn’t taken as a key path delimiter.\n * @param {FlattenedEntryContent} content Flattened content for a locale, modified in place.\n * @param {FieldKeyPath} keyPath Field key path.\n * @param {[string, string][]} pairs Key-value pairs.\n */\nexport const setPairs = (content, keyPath, pairs) => {\n  // Clear the existing pairs first. Unlike other non-primitive fields, a KeyValue field stores no\n  // placeholder at its own key path: its keys are arbitrary strings, and `unflatten()` would turn\n  // numeric ones into an array. `finalizeContent()` rebuilds the object from the children instead.\n  // The content is the draft’s live map, which is mutated right below, so its key paths have to be\n  // read as they are right now\n  getKeysByPrefix(content, `${keyPath}.`, { live: true }).forEach((_keyPath) => {\n    delete content[_keyPath];\n  });\n\n  // The editor stores `null` at the field’s own key path while it holds no pairs, so that the\n  // field still gets validated. That has to go once there are pairs, or `unflatten()` would let it\n  // win over them\n  if (pairs.length && content[keyPath] === null) {\n    delete content[keyPath];\n  }\n\n  pairs.forEach(([key, value]) => {\n    content[`${keyPath}.${escapeKeySegment(key)}`] = value;\n  });\n};\n\n/**\n * Put the key-value pairs stored in the given flattened content in the same order as those in the\n * reference content, e.g. the default locale’s. The pairs whose key the reference doesn’t hold go\n * last, in their current order. Only the order changes: no pair is added, removed or given another\n * value.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.content Flattened content for a locale, modified in place.\n * @param {FlattenedEntryContent} args.referenceContent Flattened content to take the order from.\n * @param {FieldKeyPath} args.keyPath Field key path.\n */\nexport const alignPairOrder = ({ content, referenceContent, keyPath }) => {\n  const pairs = getPairsFromContent(content, keyPath);\n  const keys = pairs.map(([key]) => key);\n\n  const referenceKeys = getPairsFromContent(referenceContent, keyPath)\n    .map(([key]) => key)\n    .filter((key) => keys.includes(key));\n\n  const orderedKeys = [...referenceKeys, ...keys.filter((key) => !referenceKeys.includes(key))];\n\n  // Leave the content alone if the order is already right\n  if (orderedKeys.some((key, index) => key !== keys[index])) {\n    setPairs(\n      content,\n      keyPath,\n      orderedKeys.map((key) => /** @type {[string, string]} */ (pairs[keys.indexOf(key)])),\n    );\n  }\n};\n","import {\n  getKeyValueField,\n  PAIR_KEY_PATH_REGEX,\n} from '$lib/services/contents/fields/key-value/pairs';\n\n/**\n * @import { EntryDraft, FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Group the key paths in the given value map by their parent key path, keeping the order they are\n * stored in. Top-level key paths have no parent, so they are left out.\n * @param {FlattenedEntryContent} valueMap Value map.\n * @param {(valueMap: FlattenedEntryContent, key: string) => boolean} isRealKey Function to check\n * whether a key holds content.\n * @returns {Map<FieldKeyPath, FieldKeyPath[]>} Key paths grouped by their parent key path.\n */\nconst groupKeyPathsByParent = (valueMap, isRealKey) => {\n  /** @type {Map<FieldKeyPath, FieldKeyPath[]>} */\n  const groups = new Map();\n\n  Object.keys(valueMap).forEach((keyPath) => {\n    if (!keyPath.includes('.') || !isRealKey(valueMap, keyPath)) {\n      return;\n    }\n\n    const parentKeyPath = keyPath.replace(PAIR_KEY_PATH_REGEX, '');\n    const group = groups.get(parentKeyPath);\n\n    if (group) {\n      group.push(keyPath);\n    } else {\n      groups.set(parentKeyPath, [keyPath]);\n    }\n  });\n\n  return groups;\n};\n\n/**\n * Check whether the key-value pairs of any KeyValue field in the draft have been reordered. The\n * pairs are stored as the children of the field’s key path, so the order they are stored in is the\n * order they are saved in, but a value comparison can’t tell. This is only meaningful once the\n * values themselves are known to be the same, in which case every parent key path has the very same\n * children in both value maps and only their order can differ. The field lookup is skipped for the\n * groups whose order is unchanged, which is all of them unless something has been reordered.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {(valueMap: FlattenedEntryContent, key: string) => boolean} args.isRealKey Function to\n * check whether a key holds content that has to be compared.\n * @param {InternalLocaleCode[]} [args.locales] Locales to check, whose values are known to be the\n * same. Defaults to every locale in the draft’s current values.\n * @returns {boolean} Whether any pairs have been reordered.\n */\nexport const isPairOrderModified = ({ draft, isRealKey, locales }) => {\n  const { collectionName, fileName, isIndexFile, originalValues, currentValues } = draft;\n\n  return (locales ?? Object.keys(currentValues)).some((locale) => {\n    const currentValueMap = currentValues[locale];\n    // The locales are known to be the same in both value stores by now\n    const originalGroups = groupKeyPathsByParent(originalValues[locale], isRealKey);\n    const currentGroups = groupKeyPathsByParent(currentValueMap, isRealKey);\n\n    return [...currentGroups].some(([parentKeyPath, keyPaths]) => {\n      const originalKeyPaths = /** @type {FieldKeyPath[]} */ (originalGroups.get(parentKeyPath));\n\n      return (\n        keyPaths.some((keyPath, index) => keyPath !== originalKeyPaths[index]) &&\n        !!getKeyValueField({\n          collectionName,\n          fileName,\n          isIndexFile,\n          keyPath: keyPaths[0],\n          valueMap: currentValueMap,\n        })\n      );\n    });\n  });\n};\n","import { isObject, toRaw } from '@sveltia/utils/object';\nimport { stripSlashes } from '@sveltia/utils/string';\nimport equal from 'fast-deep-equal';\n\nimport { getReferencedEditedEntries } from '$lib/services/contents/draft/pending-entries';\nimport { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\nimport { INTERNAL_PROP_PREFIX } from '$lib/services/contents/fields/internal-props';\nimport { isPairOrderModified } from '$lib/services/contents/fields/key-value/order';\n\n/**\n * Regex to match internal properties added to list items, which should be excluded from output.\n */\nexport const INTERNAL_PROP_REGEX = new RegExp(`\\\\.${INTERNAL_PROP_PREFIX}\\\\w+$`);\n\n/**\n * Draft properties holding the collection configuration and the entry being edited, which are fixed\n * for the lifetime of a draft. Every function building a draft hands these to `createState()` as\n * static keys, so that all the drafts opened for one collection hand out the very same objects\n * rather than a reactive proxy each.\n * @see https://github.com/sveltia/sveltia-cms/issues/1006\n */\nexport const STATIC_DRAFT_KEYS = ['collection', 'collectionFile', 'fields', 'originalEntry'];\n\n/**\n * @import {\n * AssetFolderInfo,\n * EntryDraft,\n * EntryDraftValues,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * LocaleContentMap,\n * LocaleSlugMap,\n * LocaleStateMap,\n * } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Nesting depth of the {@link suspendAutoDuplication} calls currently in flight.\n */\nlet autoDupSuspendDepth = 0;\n\n/**\n * Whether the automatic i18n duplication in the draft value proxies is currently enabled. It’s\n * temporarily disabled for performance reasons when making large changes to the values. Use\n * {@link suspendAutoDuplication} to disable it.\n * @returns {boolean} Result.\n */\nexport const isAutoDuplicationEnabled = () => !autoDupSuspendDepth;\n\n/**\n * Run the given function with the automatic i18n duplication in the draft value proxies suspended.\n *\n * A caller that writes a `duplicate` field to every locale itself has to stop the proxy from\n * duplicating the same value again. Suspensions nest — the proxy is re-enabled only once the\n * outermost one finishes — so a caller doesn’t have to know whether anything it calls suspends\n * too. The suspension is released even if the function throws.\n * @param {() => any} fn Function to run. If it returns a promise, the suspension is held until that\n * promise settles.\n * @returns {any} Whatever `fn` returns.\n * @throws {Error} Whatever `fn` throws, after releasing the suspension.\n */\nexport const suspendAutoDuplication = (fn) => {\n  autoDupSuspendDepth += 1;\n\n  /**\n   * Release this suspension, re-enabling the duplication if it was the outermost one.\n   */\n  const release = () => {\n    autoDupSuspendDepth -= 1;\n  };\n\n  /** @type {any} */\n  let result;\n\n  try {\n    result = fn();\n  } catch (ex) {\n    release();\n    throw ex;\n  }\n\n  if (result instanceof Promise) {\n    return result.finally(release);\n  }\n\n  release();\n\n  return result;\n};\n\n/**\n * Revoke the blob URLs of the given outgoing draft’s unsaved files.\n *\n * Each of these URLs keeps its entire file in memory until it’s revoked, and nothing else releases\n * them: the URL is the field value for the duration of the editing session, and is swapped for the\n * real file path when the entry is saved. Once the draft is replaced, the URLs are unreachable but\n * still registered with the browser, so every image attached in the editor would stay in memory\n * until the page is reloaded. A restored backup regenerates its URLs from the stored files, so\n * discarding them here doesn’t break that.\n * @param {EntryDraft | null | undefined} draft The outgoing draft, if any.\n */\nexport const revokeDraftFileURLs = (draft) => {\n  Object.keys(draft?.files ?? {}).forEach((blobURL) => {\n    URL.revokeObjectURL(blobURL);\n  });\n};\n\n/**\n * Filter out internal properties from a value map.\n * @param {FlattenedEntryContent} valueMap The value map to filter.\n * @returns {FlattenedEntryContent} The filtered value map.\n */\nexport const filterRealValues = (valueMap) =>\n  Object.fromEntries(Object.entries(valueMap).filter(([key]) => !INTERNAL_PROP_REGEX.test(key)));\n\n/**\n * Check whether a value map key holds content that the comparison below has to look at. Internal\n * properties are bookkeeping rather than content. An `undefined` value is left out as well: it’s\n * empty when the entry is written, so it makes no difference to the saved file whether the key is\n * there, and a key holding one can’t always be reproduced — reverting a field assigns the original\n * `undefined` back to a property that was just deleted, which leaves a state proxy without the key.\n * @param {FlattenedEntryContent} valueMap Value map to look in.\n * @param {string} key Key to check.\n * @returns {boolean} Whether the key counts.\n */\nexport const isRealKey = (valueMap, key) =>\n  !INTERNAL_PROP_REGEX.test(key) && valueMap[key] !== undefined;\n\n/**\n * Collect the values stored at the given field key path and under it, leaving out the keys that\n * {@link isRealKey} doesn’t count.\n * @param {FlattenedEntryContent} valueMap Flattened content for a locale.\n * @param {FieldKeyPath} keyPath Field key path.\n * @param {object} [options] Options.\n * @param {boolean} [options.relative] Whether to key the values by their path relative to the\n * field, in which case the field’s own value, if any, is keyed by an empty string. Otherwise they\n * are keyed by their full key path.\n * @param {boolean} [options.dropEmptyPlaceholders] Whether to leave out empty object/array\n * placeholders as well. An Object or List field may or may not have one at its own key path,\n * depending on how the value map was built, while the actual values are always flattened to their\n * own key paths.\n * @returns {FlattenedEntryContent} Collected values.\n */\nexport const collectFieldValues = (\n  valueMap,\n  keyPath,\n  { relative = false, dropEmptyPlaceholders = false } = {},\n) => {\n  const prefix = `${keyPath}.`;\n\n  // This runs for every field editor on every change, so the key paths under the field are looked\n  // up in the value map’s index rather than by walking all of them\n  return Object.fromEntries(\n    [...(Object.hasOwn(valueMap, keyPath) ? [keyPath] : []), ...getKeysByPrefix(valueMap, prefix)]\n      .filter((key) => {\n        if (!isRealKey(valueMap, key)) {\n          return false;\n        }\n\n        const value = valueMap[key];\n\n        return !(\n          dropEmptyPlaceholders &&\n          (isObject(value) || Array.isArray(value)) &&\n          !Object.keys(value).length\n        );\n      })\n      .map((key) => [relative ? key.slice(prefix.length) : key, valueMap[key]]),\n  );\n};\n\n/**\n * Compare a locale’s original and current value maps, ignoring internal properties in the current\n * one. Equivalent to deep-comparing {@link filterRealValues} of the current map against the\n * original, but without building the filtered copy first.\n * @param {FlattenedEntryContent} originalValueMap Original values for the locale.\n * @param {FlattenedEntryContent} currentValueMap Current values for the locale.\n * @returns {boolean} Whether the values differ.\n */\nexport const isValueMapModified = (originalValueMap, currentValueMap) => {\n  let realKeyCount = 0;\n\n  const anyValueChanged = Object.keys(currentValueMap).some((key) => {\n    if (!isRealKey(currentValueMap, key)) {\n      return false;\n    }\n\n    realKeyCount += 1;\n\n    return (\n      !Object.hasOwn(originalValueMap, key) || !equal(originalValueMap[key], currentValueMap[key])\n    );\n  });\n\n  // Also catch keys that only exist in the original map, which the loop above cannot see\n  return (\n    anyValueChanged ||\n    Object.keys(originalValueMap).filter((key) => isRealKey(originalValueMap, key)).length !==\n      realKeyCount\n  );\n};\n\n/**\n * Get the locales of the draft’s values that have to be compared to tell whether the draft has been\n * modified. A locale disabled before and after the edit is not saved, so its values make no\n * difference, e.g. the ones copied from the default locale when the locale was enabled and then\n * disabled again.\n * @param {EntryDraft} draft Entry draft.\n * @param {LocaleContentMap} values Original or current values of the draft.\n * @returns {InternalLocaleCode[]} Locales.\n */\nconst getComparedLocales = ({ originalLocales, currentLocales }, values) =>\n  Object.keys(values).filter(\n    (locale) => originalLocales[locale] !== false || currentLocales[locale] !== false,\n  );\n\n/**\n * Compare the original and current values of the given locales in the draft.\n * @param {EntryDraft} draft Entry draft.\n * @param {InternalLocaleCode[]} locales Locales to compare, from {@link getComparedLocales}.\n * @returns {boolean} Whether the values differ.\n */\nconst areValuesModified = (draft, locales) => {\n  const { originalValues, currentValues } = draft;\n\n  if (locales.length !== getComparedLocales(draft, originalValues).length) {\n    return true;\n  }\n\n  return locales.some((locale) => {\n    const originalValueMap = originalValues[locale];\n\n    return !originalValueMap || isValueMapModified(originalValueMap, currentValues[locale]);\n  });\n};\n\n/**\n * Check whether the given entry draft has been modified.\n *\n * Called from a `$derived`, this is recomputed whenever any of the compared values changes — so on\n * every keystroke in the editor — hence the hand-rolled value comparison instead of deep-comparing\n * a filtered copy of the whole content.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {boolean} Whether the draft has been modified. `false` if there is no draft.\n */\nexport const isDraftModified = (draft) => {\n  if (!draft) {\n    return false;\n  }\n\n  const {\n    originalLocales,\n    currentLocales,\n    originalSlugs,\n    currentSlugs,\n    originalPath,\n    currentPath,\n  } = draft;\n\n  const locales = getComparedLocales(draft, draft.currentValues);\n\n  return (\n    !equal(originalLocales, currentLocales) ||\n    !equal(originalSlugs, currentSlugs) ||\n    // Moving an entry with the path editor is a change of its own, with no field to go with it\n    stripSlashes(originalPath ?? '') !== stripSlashes(currentPath ?? '') ||\n    // Internal properties are excluded from the value comparison\n    areValuesModified(draft, locales) ||\n    // Reordering the pairs of a KeyValue field changes no value, only the order they are saved in\n    isPairOrderModified({ draft, isRealKey, locales }) ||\n    // An existing entry edited from a Relation field is saved along with the entry, which may\n    // otherwise be left as it was, as long as the entry still refers to it\n    getReferencedEditedEntries(draft).length > 0\n  );\n};\n\n/**\n * Copy the values of the given draft that a backup restores to a plain object. The draft is a\n * `$state` proxy, which IndexedDB can’t clone, so every part has to be copied. `File` objects are\n * cloneable as they are.\n * @param {EntryDraft} draft Draft.\n * @returns {EntryDraftValues} Values.\n */\nexport const getDraftValues = ({\n  currentLocales = {},\n  currentPath,\n  currentSlugs = {},\n  currentValues = {},\n  files,\n}) => ({\n  currentLocales: /** @type {LocaleStateMap} */ (toRaw(currentLocales)),\n  currentSlugs: /** @type {LocaleSlugMap} */ (toRaw(currentSlugs)),\n  // The folder chosen with the path editor, which only a collection with `meta.path` has\n  ...(currentPath !== undefined ? { currentPath } : {}),\n  currentValues: /** @type {LocaleContentMap} */ (toRaw(currentValues)),\n  files: Object.fromEntries(\n    Object.entries(files).map(\n      ([blobURL, { file, folder, replace, subfolderPath, nameTemplate }]) => [\n        blobURL,\n        {\n          file,\n          folder: folder ? /** @type {AssetFolderInfo} */ (toRaw(folder)) : folder,\n          replace,\n          subfolderPath,\n          // The random values are kept in a `Map`, which a JSON round trip would lose\n          ...(nameTemplate\n            ? {\n                nameTemplate: {\n                  ...nameTemplate,\n                  randomValues: new Map(nameTemplate.randomValues),\n                  dateTimeParts: { ...nameTemplate.dateTimeParts },\n                },\n              }\n            : {}),\n        },\n      ],\n    ),\n  ),\n});\n","/**\n * @import { FlattenedEntryContent } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Property key on a value map proxy that yields the map’s version. See {@link getValueMapVersion}.\n */\nconst VERSION_KEY = Symbol('valueMapVersion');\n\n/**\n * Get the version of the given value map, a counter that goes up whenever a value is written to or\n * deleted from the map through the proxy created with {@link createValueMap}. Reading it in a\n * reactive context makes that context depend on the whole map at the cost of a single dependency,\n * which is how the shared value map snapshot is kept fresh without every reader walking all the\n * values.\n * @param {FlattenedEntryContent | undefined} valueMap Value map.\n * @returns {number | undefined} Version, or `undefined` if the map is not a proxy.\n */\nexport const getValueMapVersion = (valueMap) => /** @type {any} */ (valueMap)?.[VERSION_KEY];\n\n/**\n * Property key on a value map proxy that yields the versions of its subtrees. See\n * {@link getSubtreeVersion}.\n */\nconst SUBTREE_VERSIONS_KEY = Symbol('subtreeVersions');\n\n/**\n * A counter of the writes to a subtree of a value map.\n */\nclass SubtreeVersion {\n  count = $state(0);\n}\n\n/**\n * Get the version of a subtree of the given value map: a counter that goes up whenever a value is\n * written to or deleted from the key path or any key path below it. Reading it in a reactive\n * context makes that context depend on the subtree only, so a field editor isn’t updated when\n * another field changes, as it is when it depends on the whole map with {@link getValueMapVersion}.\n *\n * The counters are created along with the key paths, never here: Svelte doesn’t track a state read\n * in the reaction that has created it, so a counter created on its first read, from a `$derived`,\n * would never be depended on. A key path that has no value yet, e.g. an optional field left empty,\n * has no counter, so the version of the whole map stands in for it.\n * @param {FlattenedEntryContent | undefined} valueMap Value map.\n * @param {FieldKeyPath} keyPath Key path of the subtree.\n * @returns {number | undefined} Version, or `undefined` if the map is not a proxy.\n */\nexport const getSubtreeVersion = (valueMap, keyPath) => {\n  /** @type {Map<FieldKeyPath, SubtreeVersion> | undefined} */\n  const versions = /** @type {any} */ (valueMap)?.[SUBTREE_VERSIONS_KEY];\n\n  if (!versions) {\n    return undefined;\n  }\n\n  const version = versions.get(keyPath);\n\n  return version ? version.count : getValueMapVersion(valueMap);\n};\n\n/**\n * Create a Proxy holding a flattened value map. The values live in a deeply reactive `$state`\n * object behind the proxy, so a component reading a single value only depends on that value. The\n * proxy also counts its writes; see {@link getValueMapVersion}.\n * @param {FlattenedEntryContent} [target] Plain object holding the initial values.\n * @param {object} [hooks] Functions called after a value is written or deleted through the proxy,\n * whether or not it has actually changed.\n * @param {(\n * obj: FlattenedEntryContent, keyPath: FieldKeyPath, value: any, previousValue: any,\n * added: boolean\n * ) => void} [hooks.onSet] Function called after a value is written, also taking the value the key\n * path held before and whether the key path has just been added to the map.\n * @param {(obj: FlattenedEntryContent, keyPath: FieldKeyPath, previousValue: any) => void}\n * [hooks.onDelete] Function called after a value is deleted, also taking the value the key path\n * held before.\n * @returns {any} Created proxy.\n */\nexport const createValueMap = (target = {}, { onSet, onDelete } = {}) => {\n  /** @type {FlattenedEntryContent} */\n  const values = $state(target);\n  let version = $state(0);\n  /**\n   * Key paths in insertion order. Svelte’s `$state` proxy keeps a deleted key in its target, so a\n   * key deleted and written again would otherwise be listed in its old position. That reorders the\n   * pairs of a KeyValue field as soon as one of them is renamed, because the editor rewrites all of\n   * them, and the order is what the entry file ends up with.\n   * This is intentionally a plain `Set`, not a `SvelteSet`: a caller enumerating the keys already\n   * depends on the `$state` proxy, which is read in the `ownKeys` trap below.\n   * @type {Set<string | symbol>}\n   */\n  // eslint-disable-next-line svelte/prefer-svelte-reactivity\n  const keys = new Set(Object.keys(target));\n  /**\n   * Versions of the subtrees, keyed by key path: one for each key path in the map and each key\n   * path above one. See {@link getSubtreeVersion}. A plain `Map`, as each version is reactive of\n   * its own.\n   * @type {Map<FieldKeyPath, SubtreeVersion>}\n   */\n  // eslint-disable-next-line svelte/prefer-svelte-reactivity\n  const subtreeVersions = new Map();\n\n  /**\n   * Get the given key path and the ones above it, e.g. `a`, `a.b` and `a.b.c` for `a.b.c`.\n   * @param {FieldKeyPath} keyPath Key path.\n   * @returns {FieldKeyPath[]} Key paths.\n   */\n  const getSubtreeKeyPaths = (keyPath) => {\n    const segments = keyPath.split('.');\n\n    return segments.map((_segment, index) => segments.slice(0, index + 1).join('.'));\n  };\n\n  /**\n   * Create the versions of the subtrees the given key path belongs to, if they don’t exist yet.\n   * @param {FieldKeyPath} keyPath Key path.\n   */\n  const addSubtreeVersions = (keyPath) => {\n    getSubtreeKeyPaths(keyPath).forEach((subtreeKeyPath) => {\n      if (!subtreeVersions.has(subtreeKeyPath)) {\n        subtreeVersions.set(subtreeKeyPath, new SubtreeVersion());\n      }\n    });\n  };\n\n  /**\n   * Count a write to the given key path in the version of the map and of the subtrees it belongs\n   * to.\n   * @param {FieldKeyPath} keyPath Key path.\n   */\n  const countWrite = (keyPath) => {\n    version += 1;\n\n    // Every key path written to has its versions, created along with it\n    getSubtreeKeyPaths(keyPath).forEach((subtreeKeyPath) => {\n      /** @type {SubtreeVersion} */ (subtreeVersions.get(subtreeKeyPath)).count += 1;\n    });\n  };\n\n  keys.forEach((keyPath) => {\n    addSubtreeVersions(/** @type {FieldKeyPath} */ (keyPath));\n  });\n\n  return new Proxy(/** @type {any} */ (values), {\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    get: (obj, key) =>\n      key === VERSION_KEY ? version : key === SUBTREE_VERSIONS_KEY ? subtreeVersions : obj[key],\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    ownKeys: (obj) => {\n      // Read the keys through the `$state` proxy, so that a caller enumerating them depends on\n      // them; only the order comes from our own list\n      // eslint-disable-next-line svelte/prefer-svelte-reactivity\n      const ownKeys = new Set(Reflect.ownKeys(obj));\n\n      return [\n        ...[...keys].filter((key) => ownKeys.has(key)),\n        ...[...ownKeys].filter((key) => !keys.has(key)),\n      ];\n    },\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    set: (obj, /** @type {FieldKeyPath} */ keyPath, value) => {\n      const previousValue = obj[keyPath];\n      const added = !(keyPath in obj);\n\n      if (previousValue !== value) {\n        obj[keyPath] = value;\n        keys.add(keyPath);\n        addSubtreeVersions(keyPath);\n        countWrite(keyPath);\n      }\n\n      onSet?.(obj, keyPath, value, previousValue, added);\n\n      return true;\n    },\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    deleteProperty: (obj, /** @type {FieldKeyPath} */ keyPath) => {\n      const previousValue = obj[keyPath];\n\n      if (keyPath in obj) {\n        delete obj[keyPath];\n        keys.delete(keyPath);\n        countWrite(keyPath);\n      }\n\n      onDelete?.(obj, keyPath, previousValue);\n\n      return true;\n    },\n  });\n};\n","import { untrack } from 'svelte';\n\nimport {\n  getSubtreeVersion,\n  getValueMapVersion,\n} from '$lib/services/contents/draft/create/versioned-map.svelte';\n\n/**\n * @import {\n * DraftValueStoreKey,\n * EntryDraft,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Cache of value map snapshots, keyed by the value map proxy each was taken from, along with the\n * proxy’s version at the time. This is intentionally a plain `WeakMap`, not a `SvelteMap`: it’s a\n * memo, and making it reactive would add a spurious dependency to every field editor that reads it.\n * The entries are garbage-collected along with the drafts.\n * @type {WeakMap<FlattenedEntryContent, { version: number, snapshot: FlattenedEntryContent }>}\n */\nconst snapshotCache = new WeakMap();\n\n/**\n * Get a snapshot of the flattened entry content for the given locale, detached from the Proxy in\n * {@link EntryDraft}. The result is cached and shared between callers until the values are updated\n * next. The editor renders one component per field, and each of them needs the whole content to\n * resolve variable types and list items, so snapshotting it separately in every component is\n * prohibitively expensive for large entries.\n *\n * Called from a `$derived`, this only depends on the value map’s version rather than on every value\n * in it, so the derived is recomputed once per update and hands back the shared snapshot.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @param {InternalLocaleCode} locale Locale code.\n * @param {DraftValueStoreKey} [valueStoreKey] Key to read the values from.\n * @returns {FlattenedEntryContent} Flattened entry content. An empty object if unavailable.\n */\nexport const getValueMapSnapshot = (draft, locale, valueStoreKey = 'currentValues') => {\n  const valueMap = draft?.[valueStoreKey]?.[locale];\n\n  if (!valueMap) {\n    return {};\n  }\n\n  const version = getValueMapVersion(valueMap);\n\n  // A plain object, e.g. in a draft built for a one-off validation, has no version to memoize on\n  if (version === undefined) {\n    return $state.snapshot(valueMap);\n  }\n\n  const cached = snapshotCache.get(valueMap);\n\n  if (cached?.version === version) {\n    return cached.snapshot;\n  }\n\n  // The version is the only dependency a reactive caller needs\n  const snapshot = untrack(() => $state.snapshot(valueMap));\n\n  snapshotCache.set(valueMap, { version, snapshot });\n\n  return snapshot;\n};\n\n/**\n * Get a snapshot of the flattened entry content for every locale of the given draft, with\n * {@link getValueMapSnapshot}. Called from a `$derived`, this only depends on the versions of the\n * value maps, and a locale that hasn’t changed keeps the same snapshot.\n * @param {EntryDraft} draft Entry draft.\n * @returns {Record<InternalLocaleCode, FlattenedEntryContent>} Flattened entry content, keyed by\n * locale.\n */\nexport const getValueMapSnapshots = (draft) =>\n  Object.fromEntries(\n    Object.keys(draft.currentValues ?? {}).map((locale) => [\n      locale,\n      getValueMapSnapshot(draft, locale),\n    ]),\n  );\n\n/**\n * Get the same snapshot as {@link getValueMapSnapshot}, but, called from a `$derived`, only depend\n * on the given field’s values: the value at its key path and every value below it. A field editor\n * reads the whole map, e.g. to resolve a variable type, but only has to be updated when its own\n * values change, rather than whenever any field in the entry does — which with every field of a\n * long entry rendered makes each keystroke update hundreds of editors.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @param {InternalLocaleCode} locale Locale code.\n * @param {FieldKeyPath} keyPath Key path of the field.\n * @param {DraftValueStoreKey} [valueStoreKey] Key to read the values from.\n * @returns {FlattenedEntryContent} Flattened entry content. An empty object if unavailable.\n */\nexport const getFieldValueMapSnapshot = (\n  draft,\n  locale,\n  keyPath,\n  valueStoreKey = 'currentValues',\n) => {\n  // A plain object, e.g. in a draft built for a one-off validation, has no versions\n  if (getSubtreeVersion(draft?.[valueStoreKey]?.[locale], keyPath) === undefined) {\n    return getValueMapSnapshot(draft, locale, valueStoreKey);\n  }\n\n  return untrack(() => getValueMapSnapshot(draft, locale, valueStoreKey));\n};\n","import { getContext, setContext, untrack } from 'svelte';\n\nimport { isDraftModified } from '$lib/services/contents/draft';\nimport { getValueMapSnapshots } from '$lib/services/contents/draft/value-map.svelte';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { EntryDraft, FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * Key of the Svelte context holding an {@link EntryDraftState}.\n */\nconst CONTEXT_KEY = 'entry-draft';\n/**\n * Attribute marking an editor root element registered with {@link setEntryDraftRoot}.\n */\nconst ROOT_ATTRIBUTE = 'data-entry-draft-root';\n/**\n * Entry draft states keyed by editor root element. See {@link setEntryDraftRoot}.\n * @type {WeakMap<Element, EntryDraftState>}\n */\nconst rootElementMap = new WeakMap();\n/**\n * Snapshots of the original value maps, keyed by the reactive value map they were taken from. A\n * locale’s original values are only ever replaced as a whole — when the draft is saved, a locale\n * is enabled or a backup is restored — never changed in place, so a snapshot stays valid as long as\n * the map it was taken from is the one in the draft.\n * @type {WeakMap<FlattenedEntryContent, FlattenedEntryContent>}\n */\nconst originalValueSnapshots = new WeakMap();\n\n/**\n * Get a snapshot of the original values of every locale of the given draft. Called from a\n * `$derived`, this only depends on which map each locale holds, not on every value in it.\n * @param {EntryDraft} draft Entry draft.\n * @returns {Record<InternalLocaleCode, FlattenedEntryContent>} Original values, keyed by locale.\n */\nconst getOriginalValueSnapshots = (draft) =>\n  Object.fromEntries(\n    Object.entries(draft.originalValues).map(([locale, valueMap]) => [\n      locale,\n      // A locale enabled without any content yet has no original values\n      valueMap\n        ? getOrCreate(originalValueSnapshots, valueMap, () =>\n            untrack(() => $state.snapshot(valueMap)),\n          )\n        : valueMap,\n    ]),\n  );\n\n/**\n * Get a copy of the given draft for {@link isDraftModified} to compare, holding the shared value\n * map snapshots rather than the value map proxies. The check is recomputed on every keystroke, and\n * reading the values through the proxies would make it depend on every value of every locale, and\n * pay for each read.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {EntryDraft | null | undefined} Copy of the draft, or the draft itself if there is none.\n */\nconst getComparedDraft = (draft) =>\n  draft && {\n    ...draft,\n    originalValues: getOriginalValueSnapshots(draft),\n    currentValues: getValueMapSnapshots(draft),\n  };\n\n/**\n * Reactive container for the entry draft open in an editor. The draft itself is a deeply reactive\n * `$state` object, so a field editor mutating its values notifies exactly the components that read\n * them; this container is what lets the draft be replaced as a whole, e.g. when another entry is\n * opened or the current one is saved.\n *\n * Each editor instance has its own container, provided to its descendants with\n * {@link setEntryDraftContext}, so more than one entry can be edited at the same time.\n */\nexport class EntryDraftState {\n  /**\n   * Current draft. `undefined` if there is no draft, e.g. the entry could not be found, or `null`\n   * once the draft has been saved and the editor is about to close.\n   * @type {EntryDraft | null | undefined}\n   */\n  current = $state.raw();\n\n  /**\n   * Whether the current draft has been modified.\n   */\n  modified = $derived(isDraftModified(getComparedDraft(this.current)));\n}\n\n/**\n * Provide the given entry draft state to the descendant components. Called by the editor root.\n * @param {EntryDraftState} entryDraft Entry draft state.\n * @returns {EntryDraftState} The same state.\n */\nexport const setEntryDraftContext = (entryDraft) => setContext(CONTEXT_KEY, entryDraft);\n\n/**\n * Get the entry draft state provided by the nearest editor root.\n * @returns {EntryDraftState} Entry draft state.\n */\nexport const getEntryDraftContext = () => getContext(CONTEXT_KEY);\n\n/**\n * Create the `context` option for Svelte’s `mount()`, so that a component mounted outside the\n * Svelte component tree — the entry preview rendered in an iframe, or a field preview rendered by a\n * React preview template — can still find the given entry draft state with\n * {@link getEntryDraftContext}, which would otherwise be `undefined` there.\n * @param {EntryDraftState} entryDraft Entry draft state.\n * @returns {Map<string, EntryDraftState>} Context map.\n */\nexport const createEntryDraftMountContext = (entryDraft) =>\n  // eslint-disable-next-line svelte/prefer-svelte-reactivity\n  new Map([[CONTEXT_KEY, entryDraft]]);\n\n/**\n * Register the given element as the root of an editor holding the given entry draft state, so that\n * a component rendered somewhere below it but mounted outside the Svelte component tree — a rich\n * text editor component, which Lexical mounts on its own — can still find the state through the\n * DOM with {@link getEntryDraftByElement}, as the Svelte context doesn’t reach it.\n * @param {Element} element Editor root element.\n * @param {EntryDraftState} entryDraft Entry draft state.\n */\nexport const setEntryDraftRoot = (element, entryDraft) => {\n  element.setAttribute(ROOT_ATTRIBUTE, '');\n  rootElementMap.set(element, entryDraft);\n};\n\n/**\n * Get the entry draft state of the editor the given element is rendered in.\n * @param {Element | null | undefined} element Element within an editor.\n * @returns {EntryDraftState | undefined} Entry draft state, or `undefined` if the element is not\n * within a registered editor root.\n */\nexport const getEntryDraftByElement = (element) => {\n  const root = element?.closest(`[${ROOT_ATTRIBUTE}]`);\n\n  return root ? rootElementMap.get(root) : undefined;\n};\n","/**\n * @import { InternalCollection } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Get the name of a front matter property the CMS manages for entries in the given collection, from\n * a collection option that takes a property name or a boolean.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {Field[]} [args.fields] Field list of the collection or the collection’s index file.\n * @param {FieldKeyPath | boolean} [args.option] Option value.\n * @param {FieldKeyPath} args.defaultKey Property name to use when the option is `true`.\n * @returns {FieldKeyPath | undefined} Property name, or `undefined` if the property is not managed\n * by the CMS. That’s the case when the option is `false` or an empty string, when a field with the\n * same name is configured, or when the collection is not an entry collection.\n */\nexport const getManagedKey = ({ collection, fields = [], option, defaultKey }) => {\n  if (collection?._type !== 'entry') {\n    return undefined;\n  }\n\n  const key = option === true ? defaultKey : option || undefined;\n\n  // A field with the same name is the user’s to manage in the entry editor, so leave the property\n  // alone rather than writing to it behind their back\n  if (!key || fields.some(({ name }) => name === key)) {\n    return undefined;\n  }\n\n  return key;\n};\n","import { getManagedKey } from '$lib/services/contents/entry/managed-key';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import {\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalEntryCollection,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Default property name used to store URL aliases, which are redirects from an entry’s previous\n * paths to its current path. Both Hugo and Zola support it out of the box.\n * @see https://gohugo.io/content-management/urls/#aliases\n * @see https://www.getzola.org/documentation/content/page/#front-matter\n */\nexport const DEFAULT_ALIASES_KEY = 'aliases';\n\n/**\n * Get the property name used to store URL aliases for entries in the given collection.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {Field[]} [args.fields] Field list of the collection or the collection’s index file.\n * @returns {FieldKeyPath | undefined} Property name, which is the `aliases_field` option value if\n * defined, or `undefined` if aliases are not managed by the CMS. That’s the case when the option is\n * `false`, when a field with the same name is configured, or when the collection is not an entry\n * collection. Entries in a file or singleton collection are identified by a file name that can\n * never be changed, so they can’t be renamed or duplicated in the first place.\n */\nexport const getAliasesKey = ({ collection, fields }) => {\n  const { aliases_field: option = DEFAULT_ALIASES_KEY } = /** @type {InternalEntryCollection} */ (\n    collection ?? {}\n  );\n\n  return getManagedKey({ collection, fields, option, defaultKey: DEFAULT_ALIASES_KEY });\n};\n\n/**\n * Get the existing alias list item key paths in the given flattened content, sorted by index.\n * @param {FlattenedEntryContent} content Flattened entry content.\n * @param {FieldKeyPath} aliasesKey Property name used to store URL aliases.\n * @returns {string[]} Sorted key paths, such as `['aliases.0', 'aliases.1']`.\n */\nexport const getAliasKeyPaths = (content, aliasesKey) => {\n  const prefix = `${aliasesKey}.`;\n\n  return Object.keys(content)\n    .filter((keyPath) => keyPath.startsWith(prefix) && isNumeric(keyPath.slice(prefix.length)))\n    .sort((a, b) => Number(a.slice(prefix.length)) - Number(b.slice(prefix.length)));\n};\n\n/**\n * Remove the alias property from the given flattened content. An alias must be unique across the\n * entire site, so it can never be carried over to another entry, such as a duplicate.\n * @param {FlattenedEntryContent} content Flattened entry content to be modified in place.\n * @param {FieldKeyPath | undefined} aliasesKey Property name used to store URL aliases. If it’s\n * `undefined`, nothing is removed, because the property is not managed by the CMS.\n */\nexport const removeAliases = (content, aliasesKey) => {\n  if (!aliasesKey) {\n    return;\n  }\n\n  getAliasKeyPaths(content, aliasesKey).forEach((keyPath) => {\n    delete content[keyPath];\n  });\n\n  delete content[aliasesKey];\n};\n","import { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { getAliasesKey, getAliasKeyPaths } from '$lib/services/contents/entry/aliases';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { Entry, InternalCollection, InternalEntryCollection } from '$lib/types/private';\n * @import { Field } from '$lib/types/public';\n */\n\n/**\n * An earlier location of an entry, from before it was renamed.\n * @typedef {object} EarlierEntryPath\n * @property {string} subPath Sub path the entry had, as in its key.\n * @property {string[]} paths File paths it had, one for each locale that redirects from it.\n */\n\n/**\n * Normalize a path on the site for a comparison: with a leading slash, and without a trailing one,\n * which an alias may or may not have.\n * @param {string} path Path.\n * @returns {string} Normalized path.\n */\nconst normalizeSitePath = (path) => `/${path.replace(/^\\/+|\\/+$/g, '')}`;\n\n/**\n * Create a regular expression that reads the slug from an entry’s URL, from the `preview_path`\n * option: `{{slug}}` captures it, and any other tag, e.g. a date or a locale, matches a segment.\n * @param {string} template `preview_path` option.\n * @returns {RegExp | undefined} Regular expression, or `undefined` if the URL has no slug in it.\n */\nconst getSlugRegex = (template) => {\n  const parts = normalizeSitePath(template).split(/(\\{\\{[^}]*\\}\\})/);\n\n  if (!parts.some((part) => /^\\{\\{\\s*slug\\s*\\}\\}$/.test(part))) {\n    return undefined;\n  }\n\n  const source = parts\n    .map((part) => {\n      if (/^\\{\\{\\s*slug\\s*\\}\\}$/.test(part)) {\n        return '(?<slug>.+?)';\n      }\n\n      return part.startsWith('{{') ? '[^/]*?' : RegExp.escape(part);\n    })\n    .join('');\n\n  return new RegExp(`^${source}$`);\n};\n\n/**\n * Get the locations an entry had before it was renamed outside the CMS, e.g. with `git mv`, which\n * the Git host doesn’t carry its history or comments over from. The URL aliases (redirects) the\n * entry keeps, e.g. Hugo’s `aliases`, which the CMS adds when it renames an entry, tell its earlier\n * URLs, which the `preview_path` option tells the slug in. An entry that is there again, e.g. a new\n * one with the earlier slug, is left alone, as the location is now its own.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {Field[]} [args.fields] Field list of the collection.\n * @param {Entry} args.entry Entry.\n * @returns {EarlierEntryPath[]} Earlier locations.\n */\nexport const getEarlierEntryPaths = ({ collection, fields, entry }) => {\n  const aliasesKey = getAliasesKey({ collection, fields });\n  const template = /** @type {InternalEntryCollection} */ (collection).preview_path;\n  const slugRegex = aliasesKey && template ? getSlugRegex(template) : undefined;\n\n  if (!aliasesKey || !slugRegex) {\n    return [];\n  }\n\n  const { subPath, locales } = entry;\n  const folder = subPath.includes('/') ? subPath.slice(0, subPath.lastIndexOf('/') + 1) : '';\n  /** @type {Set<string> | undefined} */\n  let existingSubPaths;\n\n  /**\n   * Check whether an entry is at the given location, listing the collection’s entries only once an\n   * alias has given one, as most entries have none.\n   * @param {string} earlierSubPath Sub path.\n   * @returns {boolean} Result.\n   */\n  const isTaken = (earlierSubPath) => {\n    existingSubPaths ??= new Set(getEntriesByCollection(collection.name).map((e) => e.subPath));\n\n    return existingSubPaths.has(earlierSubPath);\n  };\n\n  /** @type {Map<string, Set<string>>} */\n  const earlier = new Map();\n\n  Object.values(locales).forEach(({ slug, path, content }) => {\n    // The slug is the path without an extension, or its last segment, e.g. with folders. A slug\n    // made up otherwise, e.g. translated, doesn’t tell an earlier path\n    const slugIsPath = slug === subPath;\n\n    if ((!slugIsPath && `${folder}${slug}` !== subPath) || !path.includes(subPath)) {\n      return;\n    }\n\n    // A list, or a single redirect, which `jekyll-redirect-from` takes as a string too\n    [\n      content[aliasesKey],\n      ...getAliasKeyPaths(content, aliasesKey).map((keyPath) => content[keyPath]),\n    ]\n      .filter(isNonEmptyString)\n      .forEach((alias) => {\n        const captured = slugRegex.exec(normalizeSitePath(alias))?.groups?.slug;\n\n        // A slug with a `.` or `..` segment, or an empty one, would point outside the entry’s\n        // folder, e.g. at another entry, which a stray or crafted alias mustn’t mix in\n        const earlierSlug = captured?.split('/').every((segment) => !/^\\.{0,2}$/.test(segment))\n          ? captured\n          : undefined;\n\n        const earlierSubPath =\n          earlierSlug && (slugIsPath ? earlierSlug : `${folder}${earlierSlug}`);\n\n        if (!earlierSubPath || earlierSubPath === subPath || isTaken(earlierSubPath)) {\n          return;\n        }\n\n        const paths = earlier.get(earlierSubPath) ?? new Set();\n        // The sub path ends the file path, but for the extension, while a folder may share its name\n        const index = path.lastIndexOf(subPath);\n\n        paths.add(`${path.slice(0, index)}${earlierSubPath}${path.slice(index + subPath.length)}`);\n        earlier.set(earlierSubPath, paths);\n      });\n  });\n\n  return [...earlier].map(([earlierSubPath, paths]) => ({\n    subPath: earlierSubPath,\n    paths: [...paths],\n  }));\n};\n","/**\n * @import { EntryDraft } from '$lib/types/private';\n */\n\n/**\n * Get the key that names an entry for Sveltia CMS Additions, e.g. for its comments: its\n * collection and its file name or path, so the files of an entry with several locales share one\n * key. It leaves out the branch, which the lock key adds.\n * @param {string} collectionName Collection name.\n * @param {string} subPath Entry path without an extension, or the file name of a collection file.\n * @returns {string} Key.\n */\nexport const getEntryKey = (collectionName, subPath) => `${collectionName}/${subPath}`;\n\n/**\n * Get the key of an entry draft, if it has one: a new entry, which isn’t saved yet, and an item of\n * an entry stored as an array, which shares a file with other entries, don’t.\n * @param {EntryDraft | null | undefined} draft Draft.\n * @returns {string | undefined} Key.\n */\nexport const getDraftEntryKey = (draft) => {\n  if (!draft || draft.isNew || draft.originalEntry?.arrayIndex !== undefined) {\n    return undefined;\n  }\n\n  const subPath = draft.fileName ?? draft.originalEntry?.subPath;\n\n  return subPath ? getEntryKey(draft.collectionName, subPath) : undefined;\n};\n","/**\n * Abstracted AI API client utilities for Chat Completions, Messages, and Responses APIs.\n * Supports OpenAI, Mistral, DeepSeek, Anthropic, and custom compatible endpoints.\n */\n\nimport { isObject } from '@sveltia/utils/object';\n\n/**\n * @import { AiCompletionOptions } from '$lib/types/private';\n */\n\n/**\n * Options for the request to the API.\n * @typedef {object} RequestOptions\n * @property {string} endpoint API endpoint URL.\n * @property {Record<string, string>} [headers] Additional headers.\n * @property {Record<string, any>} [extraBody] Additional body parameters to include in the request.\n */\n\n/**\n * Default maximum number of output tokens. A translation of a long entry needs a large budget, and\n * a model that thinks spends part of it on reasoning, so this is well above the length of a typical\n * answer while staying within the output limit of every default model used by the integrations.\n */\nexport const DEFAULT_MAX_TOKENS = 16_000;\n\n/**\n * Create the error thrown when a response was cut off at the output token limit, so that the\n * truncated, likely unparsable, text isn’t returned as if it were complete.\n * @param {string} apiLabel API name, e.g. `Messages`, which is followed by `API`.\n * @returns {Error} Error.\n */\nexport const createTruncationError = (apiLabel) =>\n  new Error(`The response from the ${apiLabel} API was cut off at the token limit.`);\n\n/**\n * Join the text parts of a response, which can be split into several parts and include other\n * kinds of parts, such as thinking blocks.\n * @param {unknown} parts Parts of the response, expected to be an array.\n * @param {(part: Record<string, any>) => boolean} isAnswer Function to check whether a part holds\n * the answer rather than, e.g., a thought.\n * @param {string} apiLabel API name, e.g. `Messages`, which is followed by `API`.\n * @returns {string} Joined text, trimmed.\n * @throws {Error} When the response has no text part.\n */\nexport const joinTextParts = (parts, isAnswer, apiLabel) => {\n  /** @type {string[]} */\n  const texts = Array.isArray(parts)\n    ? parts\n        .filter((part) => isObject(part) && isAnswer(part) && typeof part.text === 'string')\n        .map(({ text }) => text)\n    : [];\n\n  if (!texts.length) {\n    throw new Error(`Invalid response format from ${apiLabel} API.`);\n  }\n\n  return texts.join('').trim();\n};\n\n/**\n * Get the request headers for an API that authenticates with a bearer token.\n * @param {string} apiKey API key.\n * @param {Record<string, string>} headers Additional headers, which take precedence.\n * @returns {Record<string, string>} Headers.\n */\nconst getBearerHeaders = (apiKey, headers) => ({\n  'Content-Type': 'application/json',\n  Authorization: `Bearer ${apiKey}`,\n  ...headers,\n});\n\n/**\n * Send a JSON request to an API endpoint and return the parsed response.\n * @param {object} args Arguments.\n * @param {string} args.endpoint API endpoint URL.\n * @param {Record<string, string>} args.headers Request headers.\n * @param {Record<string, any>} args.body Request body, serialized as JSON.\n * @param {string} args.apiLabel API name to be used in an error message, e.g. `Messages`, which\n * is followed by `API error`.\n * @returns {Promise<Record<string, any>>} Parsed response body.\n * @throws {Error} When the API returns a non-OK response.\n */\nexport const postJSON = async ({ endpoint, headers, body, apiLabel }) => {\n  const response = await fetch(endpoint, {\n    method: 'POST',\n    headers,\n    body: JSON.stringify(body),\n  });\n\n  if (!response.ok) {\n    const errorData = await response.json().catch(() => ({}));\n    // The services disagree on where they put the message, so both places are looked at\n    const errorMessage = errorData.error?.message || errorData.message || '';\n\n    throw new Error(\n      `${apiLabel} API error: ${response.status} ${response.statusText}` +\n        `${errorMessage ? ` - ${errorMessage}` : ''}`,\n    );\n  }\n\n  return response.json();\n};\n\n/**\n * Sends a message using the Chat Completions API format.\n * Used by: Mistral, DeepSeek, and compatible custom endpoints.\n * @param {AiCompletionOptions & RequestOptions} options Options.\n * @returns {Promise<string>} Response text.\n * @throws {Error} When the API call fails or returns an invalid response.\n */\nexport const chatCompletions = async ({\n  endpoint,\n  headers = {},\n  apiKey,\n  model,\n  systemPrompt,\n  userMessage,\n  temperature = 0.3,\n  maxTokens = DEFAULT_MAX_TOKENS,\n  reasoning = 'high',\n  extraBody = {},\n}) => {\n  const data = await postJSON({\n    endpoint,\n    headers: getBearerHeaders(apiKey, headers),\n    apiLabel: 'Chat Completions',\n    body: {\n      model,\n      messages: [\n        { role: 'system', content: systemPrompt },\n        { role: 'user', content: userMessage },\n      ],\n      temperature,\n      max_tokens: maxTokens,\n      stream: false,\n      reasoning_effort: reasoning,\n      ...extraBody,\n    },\n  });\n\n  // The content can be empty or cut off mid-way when the budget runs out, e.g. on reasoning\n  if (data.choices?.[0]?.finish_reason === 'length') {\n    throw createTruncationError('Chat Completions');\n  }\n\n  if (!data.choices || !Array.isArray(data.choices) || !data.choices[0]?.message?.content) {\n    throw new Error('Invalid response format from Chat Completions API.');\n  }\n\n  return data.choices[0].message.content.trim();\n};\n\n/**\n * Sends a message using the Responses API format.\n * Used by: OpenAI, and compatible custom endpoints.\n * @param {AiCompletionOptions & RequestOptions} options Options.\n * @returns {Promise<string>} Response text.\n * @throws {Error} When the API call fails or returns an invalid response.\n */\nexport const responses = async ({\n  endpoint,\n  headers = {},\n  apiKey,\n  model,\n  systemPrompt,\n  userMessage,\n  maxTokens = DEFAULT_MAX_TOKENS,\n  reasoning,\n  extraBody = {},\n}) => {\n  const data = await postJSON({\n    endpoint,\n    headers: getBearerHeaders(apiKey, headers),\n    apiLabel: 'Responses',\n    body: {\n      model,\n      instructions: systemPrompt,\n      input: userMessage,\n      store: false,\n      max_output_tokens: maxTokens,\n      // Reasoning tokens count toward `max_output_tokens`; without this, the model’s default effort\n      // applies\n      ...(reasoning ? { reasoning: { effort: reasoning } } : {}),\n      ...extraBody,\n    },\n  });\n\n  // An incomplete response can also be cut off by a content filter, which is reported as invalid\n  if (data.status === 'incomplete' && data.incomplete_details?.reason === 'max_output_tokens') {\n    throw createTruncationError('Responses');\n  }\n\n  // Try to get output_text directly first (simpler response format)\n  if (typeof data.output_text === 'string') {\n    return data.output_text.trim();\n  }\n\n  // Otherwise parse the output array for message items\n  /** @type {unknown[]} */\n  const output = Array.isArray(data.output) ? data.output : [];\n\n  /** @type {unknown} */\n  const message = output.find(\n    (item) =>\n      isObject(item) &&\n      'type' in item &&\n      item.type === 'message' &&\n      'content' in item &&\n      Array.isArray(item.content),\n  );\n\n  if (!isObject(message) || !('content' in message) || !Array.isArray(message.content)) {\n    throw new Error('Invalid response format from Responses API.');\n  }\n\n  const { content } = message;\n\n  /** @type {unknown} */\n  const textItem = content.find(\n    (item) =>\n      isObject(item) &&\n      'type' in item &&\n      item.type === 'output_text' &&\n      'text' in item &&\n      typeof item.text === 'string',\n  );\n\n  if (isObject(textItem) && 'text' in textItem && typeof textItem.text === 'string') {\n    return textItem.text.trim();\n  }\n\n  throw new Error('Invalid response format from Responses API.');\n};\n\n/**\n * Sends a message using the Messages API format.\n * Used by: Anthropic Claude, and compatible custom endpoints.\n * @param {AiCompletionOptions & RequestOptions} options Options.\n * @returns {Promise<string>} Response text.\n * @throws {Error} When the API call fails or returns an invalid response.\n */\nexport const messages = async ({\n  endpoint,\n  headers = {},\n  apiKey,\n  model,\n  systemPrompt,\n  userMessage,\n  maxTokens = DEFAULT_MAX_TOKENS,\n  reasoning,\n  extraBody = {},\n}) => {\n  /** @type {Record<string, string>} */\n  const defaultHeaders = { 'Content-Type': 'application/json', ...headers };\n\n  // Use x-api-key for Anthropic, Authorization for custom endpoints by default\n  if (!headers.Authorization && !headers['x-api-key']) {\n    defaultHeaders['x-api-key'] = apiKey;\n  }\n\n  const data = await postJSON({\n    endpoint,\n    headers: defaultHeaders,\n    apiLabel: 'Messages',\n    body: {\n      model,\n      max_tokens: maxTokens,\n      system: systemPrompt,\n      messages: [{ role: 'user', content: userMessage }],\n      // Other reasoning levels are left to the model’s default effort\n      ...(reasoning === 'none' ? { thinking: { type: 'disabled' } } : {}),\n      ...extraBody,\n    },\n  });\n\n  if (data.stop_reason === 'refusal') {\n    throw new Error('The request was declined by the Messages API.');\n  }\n\n  if (data.stop_reason === 'max_tokens') {\n    throw createTruncationError('Messages');\n  }\n\n  // The response can begin with `thinking` blocks and split the answer into several text blocks\n  return joinTextParts(data.content, (block) => block.type === 'text', 'Messages');\n};\n","/**\n * Generic Anthropic Claude API client.\n * @see https://docs.claude.com/en/api/messages\n */\n\nimport { messages } from './api.js';\n\n/**\n * @import { AiCompletionOptions } from '$lib/types/private';\n */\n\nconst endpoint = 'https://api.anthropic.com/v1/messages';\n\nconst headers = {\n  'anthropic-version': '2023-06-01',\n  // Work around for CORS issues in browsers\n  // @see https://simonwillison.net/2024/Aug/23/anthropic-dangerous-direct-browser-access/\n  'anthropic-dangerous-direct-browser-access': 'true',\n};\n\nexport const serviceId = 'anthropic';\nexport const serviceLabel = 'Anthropic Claude';\nexport const apiLabel = 'Anthropic API';\nexport const developerURL = 'https://docs.claude.com/en/api/overview';\nexport const apiKeyURL = 'https://platform.claude.com/settings/keys';\n// Anchored, so a key for another service entered while this one is selected isn’t accepted and sent\n// to the wrong API. The key type after `sk-ant-` varies, e.g. `api03` or `usr`\nexport const apiKeyPattern = /^sk-ant-[a-z]+\\d*-[a-zA-Z0-9-_]{40,}$/;\n\n/**\n * Send a message to the Anthropic Messages API and return the response text.\n * @param {AiCompletionOptions} options Options.\n * @returns {Promise<string>} Response text.\n * @throws {Error} When the API call fails or returns an invalid response.\n */\nexport const complete = async (options) => messages({ ...options, endpoint, headers });\n","/**\n * Generic DeepSeek API client.\n * @see https://api-docs.deepseek.com/api/create-chat-completion\n */\n\nimport { chatCompletions } from './api.js';\n\n/**\n * @import { AiCompletionOptions } from '$lib/types/private';\n */\n\nconst endpoint = 'https://api.deepseek.com/chat/completions';\n\nexport const serviceId = 'deepseek';\nexport const serviceLabel = 'DeepSeek';\nexport const apiLabel = 'DeepSeek API';\nexport const developerURL = 'https://api-docs.deepseek.com/';\nexport const apiKeyURL = 'https://platform.deepseek.com/api_keys';\n// Anchored, so a key for another service entered while this one is selected isn’t accepted and sent\n// to the wrong API\nexport const apiKeyPattern = /^sk-[a-zA-Z0-9]{32,}$/;\n\n/**\n * Send a message to the DeepSeek Chat Completions API and return the response text.\n * @param {AiCompletionOptions} options Options.\n * @returns {Promise<string>} Response text.\n * @throws {Error} When the API call fails or returns an invalid response.\n */\nexport const complete = async (options) =>\n  chatCompletions({\n    ...options,\n    endpoint,\n    extraBody: /** @type {Record<string, any>} */ ({\n      thinking: { type: options.reasoning === 'none' ? 'disabled' : 'enabled' },\n    }),\n  });\n","/**\n * Generic Google Gemini API client.\n * @see https://ai.google.dev/api/generate-content\n */\n\nimport {\n  createTruncationError,\n  DEFAULT_MAX_TOKENS,\n  joinTextParts,\n  postJSON,\n} from '$lib/services/integrations/ai/api';\n\n/**\n * @import { AiCompletionOptions } from '$lib/types/private';\n */\n\nexport const serviceId = 'google-ai';\nexport const serviceLabel = 'Google Gemini';\nexport const apiLabel = 'Gemini API';\nexport const developerURL = 'https://ai.google.dev/gemini-api/docs';\nexport const apiKeyURL = 'https://aistudio.google.com/api-keys';\n// Anchored, so a key for another service entered while this one is selected isn’t accepted and sent\n// to the wrong API. Google AI Studio now issues `AQ.` authentication keys alongside the legacy\n// `AIza` ones.\n// @see https://discuss.ai.google.dev/t/gemini-api-key-start-from-aq/171575\nexport const apiKeyPattern = /^(?:AIza[a-zA-Z0-9_-]{35}|AQ\\.[a-zA-Z0-9._-]{20,})$/;\n\n/**\n * Send a message to the Google Gemini API and return the response text.\n * @param {AiCompletionOptions & { responseFormat?: string }} options Options. Pass\n * `responseFormat: 'application/json'` to request a JSON response directly without markdown fences.\n * @returns {Promise<string>} Response text.\n * @throws {Error} When the API call fails or returns an invalid response.\n * @see https://ai.google.dev/api#authentication\n */\nexport const complete = async ({\n  apiKey,\n  model,\n  systemPrompt,\n  userMessage,\n  temperature = 0.3,\n  maxTokens = DEFAULT_MAX_TOKENS,\n  responseFormat,\n}) => {\n  const data = await postJSON({\n    endpoint: `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`,\n    // The key goes in a header rather than the URL, which can end up in logs\n    headers: { 'Content-Type': 'application/json', 'x-goog-api-key': apiKey },\n    apiLabel: 'Gemini',\n    body: {\n      system_instruction: { parts: [{ text: systemPrompt }] },\n      contents: [{ parts: [{ text: userMessage }] }],\n      generationConfig: {\n        temperature,\n        maxOutputTokens: maxTokens,\n        ...(responseFormat ? { responseMimeType: responseFormat } : {}),\n      },\n    },\n  });\n\n  const candidate = Array.isArray(data.candidates) ? data.candidates[0] : undefined;\n\n  if (candidate?.finishReason === 'MAX_TOKENS') {\n    throw createTruncationError('Gemini');\n  }\n\n  // The answer can be split into several parts, and a thinking model can add a thought summary\n  return joinTextParts(candidate?.content?.parts, (part) => !part.thought, 'Gemini');\n};\n","/**\n * Generic Mistral AI API client.\n * @see https://docs.mistral.ai/api\n */\n\nimport { chatCompletions } from './api.js';\n\n/**\n * @import { AiCompletionOptions } from '$lib/types/private';\n */\n\nconst endpoint = 'https://api.mistral.ai/v1/chat/completions';\n\nexport const serviceId = 'mistral';\nexport const serviceLabel = 'Mistral';\nexport const apiLabel = 'Mistral AI API';\nexport const developerURL = 'https://docs.mistral.ai/';\nexport const apiKeyURL = 'https://console.mistral.ai/home?profile_dialog=api-keys';\n// Either a legacy 32-character key or a newer `mstrl_`-prefixed one. Anchored, and a Google key\n// (`AIza…`) excluded, so a key for another service entered while this one is selected isn’t\n// accepted and sent to the wrong API\nexport const apiKeyPattern = /^(?:(?!AIza)[a-zA-Z0-9]{32,}|mstrl_[a-zA-Z0-9_-]{32,})$/;\n\n/**\n * Send a message to the Mistral AI Chat Completions API and return the response text.\n * @param {AiCompletionOptions} options Options.\n * @returns {Promise<string>} Response text.\n * @throws {Error} When the API call fails or returns an invalid response.\n */\nexport const complete = async (options) => chatCompletions({ ...options, endpoint });\n","/**\n * Generic OpenAI API client.\n * @see https://developers.openai.com/api/reference/resources/responses/methods/create\n */\n\nimport { responses } from './api.js';\n\n/**\n * @import { AiCompletionOptions } from '$lib/types/private';\n */\n\nconst endpoint = 'https://api.openai.com/v1/responses';\n\nexport const serviceId = 'openai';\nexport const serviceLabel = 'OpenAI GPT';\nexport const apiLabel = 'OpenAI API';\nexport const developerURL = 'https://platform.openai.com/docs/overview';\nexport const apiKeyURL = 'https://platform.openai.com/api-keys';\n// Anchored, and an Anthropic key (`sk-ant-…`) excluded, so a key for another service entered while\n// this one is selected isn’t accepted and sent to the wrong API\nexport const apiKeyPattern = /^sk-(?!ant-)[a-zA-Z0-9-_]{40,}$/;\n\n/**\n * Send a message to the OpenAI Responses API and return the response text.\n * @param {AiCompletionOptions} options Options.\n * @returns {Promise<string>} Response text.\n * @throws {Error} When the API call fails or returns an invalid response.\n */\nexport const complete = async (options) => responses({ ...options, endpoint });\n","import * as anthropic from './anthropic';\nimport * as deepseek from './deepseek';\nimport * as google from './google';\nimport * as mistral from './mistral';\nimport * as openai from './openai';\n\n/**\n * @import { AiService } from '$lib/types/private';\n */\n\n/**\n * List of all the supported AI services, keyed by service ID. Alphabetical order by service name.\n * @type {Record<string, AiService>}\n */\nexport const allAiServices = Object.fromEntries(\n  [anthropic, deepseek, google, mistral, openai].map((service) => [service.serviceId, service]),\n);\n","import { escapeAttr, escapeHTML } from '$lib/services/utils/string';\n\n/**\n * Create a photo credit for a stock photo, linking the whole text to the photo page, e.g. `<a\n * href=\"…\">Photo by Jane on Pexels</a>`.\n * @param {object} args Arguments.\n * @param {string} args.name Photographer name.\n * @param {string} args.serviceLabel Service name, e.g. `Pexels`.\n * @param {string} args.url Photo page URL.\n * @returns {string} Credit HTML.\n */\nexport const createLinkedCredit = ({ name, serviceLabel, url }) =>\n  `<a href=\"${escapeAttr(url)}\">Photo by ${escapeHTML(name)} on ${serviceLabel}</a>`;\n\n/**\n * Create a photo credit for a stock photo, linking the photographer and the service separately,\n * e.g. `Photo by <a href=\"…\">Jane</a> on <a href=\"…\">Unsplash</a>`.\n * @param {object} args Arguments.\n * @param {string} args.name Photographer name.\n * @param {string} args.profileURL Photographer profile URL.\n * @param {string} args.serviceLabel Service name, e.g. `Unsplash`.\n * @param {string} args.serviceURL Service URL.\n * @returns {string} Credit HTML.\n */\nexport const createAttributedCredit = ({ name, profileURL, serviceLabel, serviceURL }) =>\n  `Photo by <a href=\"${escapeAttr(profileURL)}\">${escapeHTML(name)}</a> on ` +\n  `<a href=\"${escapeAttr(serviceURL)}\">${serviceLabel}</a>`;\n\n/**\n * Regular expression matching a photo credit created with {@link createLinkedCredit} or\n * {@link createAttributedCredit}, also once sanitized, which may add or reorder attributes. The\n * name is escaped there, so it can’t contain `<`. The whitespace around the credit is matched as\n * well, so the text on both sides can be joined with a single space when it’s removed.\n */\nconst STOCK_CREDIT_REGEX = new RegExp(\n  [\n    String.raw`\\s*(?:`,\n    String.raw`Photo by <a\\s[^>]*>[^<]*<\\/a> on <a\\s[^>]*>[^<]*<\\/a>`,\n    String.raw`|<a\\s[^>]*>Photo by [^<]* on [^<]*<\\/a>`,\n    String.raw`)\\s*`,\n  ].join(''),\n  'g',\n);\n\n/**\n * Remove the photo credits created with {@link createLinkedCredit} or\n * {@link createAttributedCredit} from the given HTML, e.g. a caption, joining the text around each\n * with a single space.\n * @param {string} html HTML.\n * @returns {string} HTML without the credits, trimmed.\n */\nexport const removeStockCredits = (html) => html.replace(STOCK_CREDIT_REGEX, ' ').trim();\n","import { locale as appLocale } from '@sveltia/i18n';\n\nimport { getLanguageScript } from '$lib/services/utils/locale';\nimport { fetchPages } from '$lib/services/utils/paging';\n\n/**\n * @import { ExternalAsset, MediaLibraryFetchOptions } from '$lib/types/private';\n */\n\n/**\n * Get the best matching locale supported by a stock asset API: the app locale if the API supports\n * it, otherwise the first supported locale of the same language written in the same script, so\n * Traditional Chinese doesn’t get Simplified Chinese results, otherwise the first supported locale\n * of the same language, otherwise the fallback.\n * @param {string[]} supportedLocales Locale codes supported by the API, either language codes like\n * `en` or language-region codes like `en-US`.\n * @param {string} fallback Locale code to fall back to.\n * @returns {string} Locale code.\n */\nexport const getSupportedLocale = (supportedLocales, fallback) => {\n  const locale = appLocale.current.toLowerCase();\n  const [lang] = locale.split('-');\n  const languageScript = getLanguageScript(locale);\n\n  return (\n    supportedLocales.find((code) => code.toLowerCase() === locale) ??\n    (languageScript\n      ? supportedLocales.find((code) => getLanguageScript(code) === languageScript)\n      : undefined) ??\n    supportedLocales.find((code) => code.split('-')[0] === lang) ??\n    fallback\n  );\n};\n\n/**\n * Send a request to a stock asset API and parse the JSON response.\n * @param {string} url Request URL.\n * @param {RequestInit} [init] Request options.\n * @returns {Promise<any>} Parsed response.\n * @throws {Error} When the request failed.\n */\nexport const fetchJSON = async (url, init) => {\n  const response = init ? await fetch(url, init) : await fetch(url);\n\n  if (!response.ok) {\n    throw new Error(`Failed to fetch ${url}: ${response.status}`);\n  }\n\n  return response.json();\n};\n\n/**\n * Fetch search results page by page, until the API reports no more pages or the given number of\n * pages is reached.\n * @template T\n * @param {object} args Arguments.\n * @param {number} args.maxPages Maximum number of pages to fetch.\n * @param {(page: number) => Promise<any>} args.fetchPage Function to fetch a page of results.\n * @param {(response: any, page: number) => { results: T[], hasMore: boolean }} args.parsePage\n * Function to extract the results from a page, along with whether another page follows.\n * @returns {Promise<T[]>} Results of all the fetched pages.\n */\nexport const fetchPagedResults = async ({ maxPages, fetchPage, parsePage }) =>\n  fetchPages(\n    async (/** @type {number | undefined} */ cursor) => {\n      const page = cursor ?? 1;\n      const { results, hasMore } = parsePage(await fetchPage(page), page);\n\n      return { results, next: hasMore ? page + 1 : undefined };\n    },\n    { maxPages },\n  );\n\n/**\n * Create the `list` and `search` functions of a stock asset provider whose API lists curated\n * pictures at one endpoint and searches pictures at another.\n * @template T\n * @param {object} args Arguments.\n * @param {string} args.listURL Endpoint to list curated pictures.\n * @param {string} args.searchURL Endpoint to search pictures.\n * @param {(apiKey: string) => Record<string, string>} [args.getHeaders] Function to get the\n * request headers for the given API key. Default: no headers.\n * @param {(apiKey: string) => Record<string, any>} args.getListParams Function to get the query\n * parameters to list pictures.\n * @param {(query: string, apiKey: string) => Record<string, any>} args.getSearchParams Function\n * to get the query parameters to search pictures.\n * @param {string} [args.listKey] Property of the list response holding the results. Default: the\n * response itself.\n * @param {string} args.searchKey Property of the search response holding the results.\n * @param {(response: any, page: number) => boolean} [args.hasMore] Function to check whether\n * another search result page follows, for an API that pages the search results with the `page`\n * query parameter. Default: the results are fetched in a single request without the parameter.\n * @param {number} [args.maxPages] Maximum number of search result pages to fetch. Required with\n * `hasMore`.\n * @param {(results: T[]) => ExternalAsset[]} args.parseResults Function to convert the results\n * into the `ExternalAsset` format.\n * @returns {{\n * list: (options: MediaLibraryFetchOptions) => Promise<ExternalAsset[]>,\n * search: (query: string, options: MediaLibraryFetchOptions) => Promise<ExternalAsset[]>,\n * }} Functions.\n */\nexport const createStockFetchers = ({\n  listURL,\n  searchURL,\n  getHeaders,\n  getListParams,\n  getSearchParams,\n  listKey,\n  searchKey,\n  maxPages,\n  hasMore,\n  parseResults,\n}) => {\n  /**\n   * Send a request to the API.\n   * @param {string} url Endpoint.\n   * @param {URLSearchParams} params Query parameters.\n   * @param {string} apiKey API key.\n   * @returns {Promise<any>} Parsed response.\n   */\n  const request = (url, params, apiKey) =>\n    fetchJSON(`${url}?${params}`, getHeaders && { headers: getHeaders(apiKey) });\n\n  return {\n    /**\n     * Fetch curated pictures.\n     * @param {MediaLibraryFetchOptions} options Options.\n     * @returns {Promise<ExternalAsset[]>} Assets.\n     */\n    list: async ({ apiKey }) => {\n      const response = await request(listURL, new URLSearchParams(getListParams(apiKey)), apiKey);\n\n      return parseResults(listKey ? response[listKey] : response);\n    },\n    /**\n     * Search images.\n     * @param {string} query Search query.\n     * @param {MediaLibraryFetchOptions} options Options.\n     * @returns {Promise<ExternalAsset[]>} Assets.\n     */\n    search: async (query, { apiKey }) => {\n      const params = new URLSearchParams(getSearchParams(query, apiKey));\n\n      if (!hasMore) {\n        return parseResults((await request(searchURL, params, apiKey))[searchKey]);\n      }\n\n      const results = await fetchPagedResults({\n        maxPages: /** @type {number} */ (maxPages),\n        /**\n         * Fetch a page of search results.\n         * @param {number} page Page number.\n         * @returns {Promise<any>} Response.\n         */\n        fetchPage: (page) => {\n          params.set('page', String(page));\n\n          return request(searchURL, params, apiKey);\n        },\n        /**\n         * Extract the results from a page.\n         * @param {any} response Response.\n         * @param {number} page Page number.\n         * @returns {{ results: T[], hasMore: boolean }} Results and whether another page follows.\n         */\n        parsePage: (response, page) => ({\n          results: response[searchKey],\n          hasMore: hasMore(response, page),\n        }),\n      });\n\n      return parseResults(results);\n    },\n  };\n};\n","import { createLinkedCredit } from '$lib/services/integrations/media-libraries/stock/credit';\nimport {\n  createStockFetchers,\n  getSupportedLocale,\n} from '$lib/services/integrations/media-libraries/stock/utils';\n\n/**\n * @import { ExternalAsset, MediaLibraryService } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} FetchResult\n * @property {number} id Asset ID.\n * @property {string} url Page URL.\n * @property {string} alt Description.\n * @property {{ large2x: string, medium: string }} src Image URLs.\n * @property {string} photographer Photographer name.\n */\n\n/**\n * @see https://www.pexels.com/api/documentation/#photos-search__parameters__locale\n */\nconst SUPPORTED_LOCALES = [\n  'en-US,pt-BR,es-ES,ca-ES,de-DE,it-IT,fr-FR,sv-SE,id-ID,pl-PL,ja-JP,zh-TW,zh-CN,ko-KR,th-TH,nl-NL',\n  'hu-HU,vi-VN,cs-CZ,da-DK,fi-FI,uk-UA,el-GR,ro-RO,nb-NO,sk-SK,tr-TR,ru-RU',\n]\n  .join(',')\n  .split(',');\n\nconst ENDPOINT = 'https://api.pexels.com/v1';\n\n/** @type {Record<string, any>} */\nconst SEARCH_PARAMS = {\n  per_page: 80,\n};\n\nconst DESCRIPTION_REGEX = /\\/photo\\/(?<alt>.+?)-\\d+\\/$/;\n\n/**\n * Get the best matching locale supported by Pexels API.\n * @returns {string} Locale code.\n */\nexport const getLocale = () => getSupportedLocale(SUPPORTED_LOCALES, 'en-US');\n\n/**\n * Parse API results into ExternalAsset format.\n * @param {FetchResult[]} results API results.\n * @returns {ExternalAsset[]} Assets.\n */\nexport const parseResults = (results) =>\n  results.map(({ id, url, alt, src: { large2x, medium }, photographer }) => ({\n    id: String(id),\n    description: url.match(DESCRIPTION_REGEX)?.groups?.alt.replace(/-/g, ' ') ?? alt,\n    previewURL: medium,\n    downloadURL: large2x,\n    fileName: `pexels-${photographer.split(/\\s+/).join('-').toLowerCase()}-${id}.jpg`,\n    kind: 'image',\n    credit: createLinkedCredit({ name: photographer, serviceLabel: 'Pexels', url }),\n  }));\n\n/**\n * Fetch curated pictures, or search images.\n * @see https://www.pexels.com/api/documentation/\n * @todo Support video files.\n */\nexport const { list, search } = createStockFetchers({\n  listURL: `${ENDPOINT}/curated`,\n  searchURL: `${ENDPOINT}/search`,\n  /**\n   * Get the request headers.\n   * @param {string} apiKey API key.\n   * @returns {Record<string, string>} Headers.\n   */\n  getHeaders: (apiKey) => ({ Authorization: apiKey }),\n  /**\n   * Get the query parameters to list curated pictures.\n   * @returns {Record<string, any>} Parameters.\n   */\n  getListParams: () => SEARCH_PARAMS,\n  /**\n   * Get the query parameters to search images.\n   * @param {string} query Search query.\n   * @returns {Record<string, any>} Parameters.\n   */\n  getSearchParams: (query) => ({ ...SEARCH_PARAMS, query, locale: getLocale() }),\n  listKey: 'photos',\n  searchKey: 'photos',\n  maxPages: 2,\n  /**\n   * Check whether another page of search results follows.\n   * @param {{ next_page?: string }} response Response.\n   * @returns {boolean} Result.\n   */\n  hasMore: ({ next_page: nextPage }) => !!nextPage,\n  parseResults,\n});\n\n/**\n * @type {MediaLibraryService}\n */\nexport default {\n  serviceType: 'stock_assets',\n  serviceId: 'pexels',\n  serviceLabel: 'Pexels',\n  serviceURL: 'https://www.pexels.com/',\n  showServiceLink: true,\n  hotlinking: false,\n  authType: 'api_key',\n  developerURL: 'https://www.pexels.com/api/',\n  apiKeyURL: 'https://www.pexels.com/api/new/',\n  apiKeyPattern: /^[a-zA-Z\\d]{56}$/,\n  list,\n  search,\n};\n","import { fetchJSON } from '$lib/services/integrations/media-libraries/stock/utils';\n\n/**\n * @import {\n * ExternalAsset,\n * MediaLibraryService,\n * } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} FetchResult\n * @property {string} id Asset ID.\n * @property {number} width Image width.\n * @property {number} height Image height.\n */\n\nconst ENDPOINT = 'https://picsum.photos/v2/list';\nconst LIMIT = 100;\nconst TOTAL_PAGES = 10;\nconst FETCH_PAGES = 3;\n\n/**\n * Parse API results into ExternalAsset format.\n * @param {FetchResult[]} results API results.\n * @returns {ExternalAsset[]} Assets.\n */\nexport const parseResults = (results) =>\n  results.map(({ id, width, height }) => {\n    // Limit the maximum dimension to 1920px to avoid excessively large files, while maintaining the\n    // aspect ratio. 1920x1280 is a common resolution that provides good quality without being too\n    // large for most use cases.\n    const landscape = width >= height;\n    const [w, h] = landscape ? [1920, 1280] : [1280, 1920];\n    const [pw, ph] = landscape ? [480, 320] : [320, 480];\n\n    return {\n      id,\n      // The service doesn’t provide descriptions\n      description: '',\n      previewURL: `https://picsum.photos/id/${id}/${pw}/${ph}.webp`,\n      downloadURL: `https://picsum.photos/id/${id}/${w}/${h}.webp`,\n      fileName: `picsum-${id}.webp`,\n      kind: 'image',\n      // No credit is required as the photos are licensed under CC0\n      // https://github.com/DMarby/picsum-photos/issues/81#issuecomment-1340068800\n    };\n  });\n\n/**\n * Fetch all available pictures across all pages.\n * @returns {Promise<ExternalAsset[]>} Assets.\n * @see https://picsum.photos/#list-images\n */\nexport const list = async () => {\n  // Pick random pages from the 10 available (100 images each).\n  const pages = Array.from({ length: TOTAL_PAGES }, (_, i) => i + 1)\n    .sort(() => Math.random() - 0.5)\n    .slice(0, FETCH_PAGES);\n\n  /** @type {FetchResult[][]} */\n  const pageResults = await Promise.all(\n    pages.map((page) => fetchJSON(`${ENDPOINT}?page=${page}&limit=${LIMIT}`)),\n  );\n\n  // Randomize the results for variety, as the API returns them in the same order for the same page.\n  return parseResults(pageResults.flat().sort(() => Math.random() - 0.5));\n};\n\n/**\n * @type {MediaLibraryService}\n */\nexport default {\n  serviceType: 'stock_assets',\n  serviceId: 'picsum',\n  serviceLabel: 'Lorem Picsum',\n  serviceURL: 'https://picsum.photos/',\n  showServiceLink: true,\n  hotlinking: true,\n  authType: 'none',\n  list,\n};\n","import { createLinkedCredit } from '$lib/services/integrations/media-libraries/stock/credit';\nimport {\n  createStockFetchers,\n  getSupportedLocale,\n} from '$lib/services/integrations/media-libraries/stock/utils';\nimport { getBaseName } from '$lib/services/utils/file';\n\n/**\n * @import { ExternalAsset, MediaLibraryService } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} FetchResult\n * @property {number} id Asset ID.\n * @property {string} webformatURL Image URL.\n * @property {string} previewURL Preview URL.\n * @property {string} largeImageURL Large image URL.\n * @property {number} imageWidth Image width.\n * @property {number} imageHeight Image height.\n * @property {string} pageURL Page URL.\n * @property {string} tags Tags.\n * @property {string} user User name.\n */\n\n/**\n * @see https://pixabay.com/api/docs/#api_search_images\n */\nconst SUPPORTED_LOCALES =\n  'cs,da,de,en,es,fr,id,it,hu,nl,no,pl,pt,ro,sk,fi,sv,tr,vi,th,bg,ru,el,ja,ko,zh'.split(',');\n\nconst ENDPOINT = 'https://pixabay.com/api';\n\n/** @type {Record<string, any>} */\nconst SEARCH_PARAMS = {\n  image_type: 'photo',\n  min_width: 1280,\n  safesearch: true,\n  per_page: 150,\n};\n\n/**\n * Parse API results into ExternalAsset format.\n * @param {FetchResult[]} results API results.\n * @returns {ExternalAsset[]} Assets.\n */\nexport const parseResults = (results) =>\n  results.map(\n    ({\n      id,\n      webformatURL,\n      previewURL,\n      largeImageURL,\n      imageWidth,\n      imageHeight,\n      pageURL,\n      tags,\n      user,\n    }) => ({\n      id: String(id),\n      description: tags,\n      previewURL: webformatURL.replace('_640.', imageWidth > imageHeight ? '_180.' : '_340.'),\n      downloadURL: largeImageURL,\n      fileName: getBaseName(previewURL).replace('_150.', '_1280.'),\n      kind: 'image',\n      credit: createLinkedCredit({ name: user, serviceLabel: 'Pixabay', url: pageURL }),\n    }),\n  );\n\n/**\n * Get the best matching locale supported by Pixabay API.\n * @returns {string} Locale code.\n */\nexport const getLocale = () => getSupportedLocale(SUPPORTED_LOCALES, 'en');\n\n/**\n * Fetch curated pictures, or search images.\n * @see https://pixabay.com/api/docs/\n * @todo Support video files.\n */\nexport const { list, search } = createStockFetchers({\n  listURL: `${ENDPOINT}/`,\n  searchURL: `${ENDPOINT}/`,\n  /**\n   * Get the query parameters to list editors’ choice pictures.\n   * @param {string} apiKey API key.\n   * @returns {Record<string, any>} Parameters.\n   */\n  getListParams: (apiKey) => ({\n    ...SEARCH_PARAMS,\n    key: apiKey,\n    lang: getLocale(),\n    editors_choice: String(true),\n  }),\n  /**\n   * Get the query parameters to search images.\n   * @param {string} query Search query.\n   * @param {string} apiKey API key.\n   * @returns {Record<string, any>} Parameters.\n   */\n  getSearchParams: (query, apiKey) => ({\n    ...SEARCH_PARAMS,\n    key: apiKey,\n    lang: getLocale(),\n    q: query,\n  }),\n  listKey: 'hits',\n  searchKey: 'hits',\n  parseResults,\n});\n\n/**\n * @type {MediaLibraryService}\n */\nexport default {\n  serviceType: 'stock_assets',\n  serviceId: 'pixabay',\n  serviceLabel: 'Pixabay',\n  serviceURL: 'https://pixabay.com/',\n  showServiceLink: true,\n  hotlinking: false,\n  authType: 'api_key',\n  developerURL: 'https://pixabay.com/service/about/api/',\n  apiKeyURL: 'https://pixabay.com/api/docs/#api_key',\n  apiKeyPattern: /^\\d+-[a-f\\d]{25}$/,\n  list,\n  search,\n};\n","import { createAttributedCredit } from '$lib/services/integrations/media-libraries/stock/credit';\nimport {\n  createStockFetchers,\n  fetchJSON,\n  getSupportedLocale,\n} from '$lib/services/integrations/media-libraries/stock/utils';\n\n/**\n * @import {\n * ExternalAsset,\n * MediaLibraryFetchOptions,\n * MediaLibraryService,\n * } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} FetchResult\n * @property {string} id Asset ID.\n * @property {string} description Description.\n * @property {string} alt_description Alt description.\n * @property {{ regular: string, thumb: string }} urls Image URLs.\n * @property {{ username: string, name: string }} user User info.\n * @property {{ download_location?: string }} [links] Links, including the endpoint to request once\n * the photo is used.\n */\n\n/**\n * @see https://unsplash.com/documentation#supported-languages\n */\nconst SUPPORTED_LOCALES = [\n  'af,sq,am,ar,hy,as,az,bn,ba,eu,bs,bg,yue,ca,lzh,zh-Hans,zh-Hant,hr,cs,da,prs,dv,nl,en,et,fo,fj',\n  'fil,fi,fr,fr-ca,gl,ka,de,el,gu,ht,he,hi,mww,hu,is,id,ikt,iu,iu-Latn,ga,it,ja,kn,kk,km,ko,ku,kmr',\n  'ky,lo,lv,lt,mk,mg,ms,ml,mt,mi,mr,mn-Cyrl,mn-Mong,my,ne,nb,or,ps,fa,pl,pt,pt-pt,pa,otq,ro,ru,sm',\n  'sr-Cyrl,sr-Latn,sk,sl,so,es,sw,sv,ty,ta,tt,te,th,bo,ti,to,tr,tk,uk,hsb,ur,ug,uz,vi,cy,yua,zu',\n]\n  .join(',')\n  .split(',');\n\nconst ENDPOINT = 'https://api.unsplash.com';\nconst CREDIT_LINK_PARAMS = 'utm_source=sveltia-cms&utm_medium=referral';\n\n/** @type {Record<string, any>} */\nconst SEARCH_PARAMS = {\n  per_page: 30,\n};\n\n/**\n * Get the best matching locale supported by Unsplash API.\n * @returns {string} Locale code.\n */\nexport const getLocale = () => getSupportedLocale(SUPPORTED_LOCALES, 'en');\n\n/**\n * Parse API results into ExternalAsset format.\n * @param {FetchResult[]} results API results.\n * @returns {ExternalAsset[]} Assets.\n */\nexport const parseResults = (results) =>\n  results.map(\n    ({\n      id,\n      description,\n      alt_description: alt,\n      urls: { regular, thumb },\n      user: { username, name },\n      links,\n    }) => ({\n      id: String(id),\n      description: [description, alt].filter(Boolean).join(' — '),\n      previewURL: thumb,\n      downloadURL: regular,\n      fileName: `${name.split(/\\s+/).join('-').toLowerCase()}-${id}-unsplash.jpg`,\n      kind: 'image',\n      credit: createAttributedCredit({\n        name,\n        profileURL: `https://unsplash.com/@${username}?${CREDIT_LINK_PARAMS}`,\n        serviceLabel: 'Unsplash',\n        serviceURL: `https://unsplash.com/?${CREDIT_LINK_PARAMS}`,\n      }),\n      downloadTrackingURL: links?.download_location,\n    }),\n  );\n\n/**\n * Get the request headers for the given API key.\n * @param {string} apiKey API key.\n * @returns {Record<string, string>} Headers.\n */\nconst getHeaders = (apiKey) => ({ Authorization: `Client-ID ${apiKey}` });\n\n/**\n * Fetch curated pictures, or search images.\n * @see https://unsplash.com/documentation\n * @todo Support video files.\n */\nexport const { list, search } = createStockFetchers({\n  listURL: `${ENDPOINT}/photos`,\n  searchURL: `${ENDPOINT}/search/photos`,\n  getHeaders,\n  /**\n   * Get the query parameters to list curated pictures.\n   * @returns {Record<string, any>} Parameters.\n   */\n  getListParams: () => SEARCH_PARAMS,\n  /**\n   * Get the query parameters to search images.\n   * @param {string} query Search query.\n   * @returns {Record<string, any>} Parameters.\n   */\n  getSearchParams: (query) => ({ ...SEARCH_PARAMS, query, lang: getLocale() }),\n  searchKey: 'results',\n  maxPages: 5,\n  /**\n   * Check whether another page of search results follows.\n   * @param {{ total_pages: number }} response Response.\n   * @param {number} page Page number.\n   * @returns {boolean} Result.\n   */\n  hasMore: ({ total_pages: totalPages }, page) => page < totalPages,\n  parseResults,\n});\n\n/**\n * Let Unsplash know a photo has been used, as its API guidelines require. A failure is only logged,\n * so it never gets in the way of the insertion.\n * @param {ExternalAsset} asset Inserted photo.\n * @param {MediaLibraryFetchOptions} options Options.\n * @returns {Promise<void>}\n * @see https://help.unsplash.com/en/articles/2511258-guideline-triggering-a-download\n */\nexport const trackDownload = async ({ downloadTrackingURL }, { apiKey }) => {\n  if (!downloadTrackingURL) {\n    return;\n  }\n\n  try {\n    await fetchJSON(downloadTrackingURL, { headers: getHeaders(apiKey) });\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  }\n};\n\n/**\n * @type {MediaLibraryService}\n */\nexport default {\n  serviceType: 'stock_assets',\n  serviceId: 'unsplash',\n  serviceLabel: 'Unsplash',\n  serviceURL: 'https://unsplash.com/',\n  showServiceLink: true,\n  hotlinking: true,\n  authType: 'api_key',\n  developerURL: 'https://unsplash.com/developers',\n  apiKeyURL: 'https://unsplash.com/oauth/applications',\n  apiKeyPattern: /^[a-zA-Z\\d_-]{40,}$/,\n  list,\n  search,\n  trackDownload,\n};\n","import { getMediaLibraryOptions } from '$lib/services/integrations/media-libraries';\n\nimport pexels from './pexels';\nimport picsum from './picsum';\nimport pixabay from './pixabay';\nimport unsplash from './unsplash';\n\n/**\n * @import { MediaLibraryService } from '$lib/types/private';\n * @import { MediaField, StockMediaLibrary, StockAssetProviderName } from '$lib/types/public';\n */\n\n/**\n * List of all the supported stock asset providers.\n * @type {Record<StockAssetProviderName, MediaLibraryService>}\n */\nexport const allStockAssetProviders = {\n  pexels,\n  picsum,\n  pixabay,\n  unsplash,\n};\n\n/**\n * Get normalized stock photo/video media library options.\n * @param {object} [options] Options.\n * @param {MediaField} [options.fieldConfig] Field configuration.\n * @returns {StockMediaLibrary} Options.\n */\nexport const getStockAssetMediaLibraryOptions = ({ fieldConfig } = {}) => {\n  const options = getMediaLibraryOptions({ libraryName: 'stock_assets', fieldConfig });\n\n  // Explicitly disabled\n  if (options === false) {\n    return { providers: [] };\n  }\n\n  const allProviderNames = /** @type {StockAssetProviderName[]} */ (\n    Object.keys(allStockAssetProviders)\n  );\n\n  const { providers } = options;\n\n  return {\n    providers: Array.isArray(providers) ? providers : allProviderNames,\n  };\n};\n","/**\n * Shared utilities for translation services.\n */\n\nimport { getLocaleLabel } from '$lib/services/contents/i18n';\n\n/**\n * @import {\n * AiCompletionOptions,\n * AiService,\n * LanguagePair,\n * TranslationOptions,\n * TranslationService,\n * } from '$lib/types/private';\n */\n\n/**\n * Normalize a locale code to a language label in English that AI services can understand.\n * @param {string} locale Locale code, e.g., 'en', 'fr-FR', 'zh-CN'.\n * @returns {string | undefined} Normalized language label, e.g., 'English', 'French', 'Chinese'.\n */\nexport const normalizeLanguage = (locale) => getLocaleLabel(locale, { displayLocale: 'en' });\n\n/**\n * Generate a standardized system prompt for AI translation services.\n * @param {string} sourceLanguageName Source language name, e.g., 'English', 'Canadian French'.\n * @param {string} targetLanguageName Target language name, e.g., 'French', 'Brazilian Portuguese'.\n * @returns {string} System prompt for translation.\n */\nexport const createTranslationSystemPrompt = (sourceLanguageName, targetLanguageName) => {\n  const baseInstructions = [\n    '- CRITICAL: Leave content EXACTLY unchanged within HTML elements that have translate=\"no\"',\n    '- CRITICAL: Leave content EXACTLY unchanged within HTML elements that have class=\"notranslate\"',\n    '- CRITICAL: Leave content EXACTLY unchanged between \"notranslate\" and \"/notranslate\" comments',\n    '- Preserve all markdown formatting (headers, links, bold, italic, code blocks, lists, etc.)',\n    '- Preserve all HTML tags and attributes exactly as they are',\n    '- Maintain the original structure and formatting',\n    '- Do not translate code content within code blocks or inline code',\n    '- Do not translate URLs, email addresses, or technical identifiers',\n    '- If you see translate=\"no\", class=\"notranslate\", or notranslate comments, copy that content verbatim without any changes',\n  ];\n\n  const lineBreakInstructions = [\n    '- Do not split translations into separate paragraphs or add extra line breaks',\n    '- Keep each translation as a single continuous text string in the array',\n  ];\n\n  const responseInstructions = [\n    '- Return your response as a valid JSON array containing the translated texts',\n    '- The array should contain the translated texts in the same order as provided',\n    '- VALIDATION: Before responding, double-check that any translate=\"no\", class=\"notranslate\", or notranslate comment content remains EXACTLY the same',\n  ];\n\n  const allInstructions = [...baseInstructions, ...lineBreakInstructions, ...responseInstructions];\n\n  return (\n    'You are a professional translator. Translate the given texts from ' +\n    `${sourceLanguageName} to ${targetLanguageName}. ` +\n    'Your response must be valid JSON that can be parsed directly.\\n\\n' +\n    `IMPORTANT INSTRUCTIONS:\\n${allInstructions.join('\\n')}\\n\\n` +\n    'OUTPUT FORMAT:\\n' +\n    '- Output ONLY valid JSON, nothing else\\n' +\n    '- Do NOT use markdown code blocks or formatting\\n' +\n    '- Do NOT add any explanation or commentary\\n' +\n    '- Your entire response should be parseable by JSON.parse()\\n' +\n    '- Start your response with [ and end with ]\\n\\n' +\n    'Required JSON structure:\\n' +\n    '[\"translation 1\", \"translation 2\", ...]'\n  );\n};\n\n/**\n * Create a standardized user prompt for translation requests.\n * @param {string[]} texts Array of texts to translate.\n * @returns {string} User prompt for translation.\n */\nexport const createTranslationUserPrompt = (texts) =>\n  'Translate these texts and return ONLY valid JSON (no markdown, no code blocks):\\n' +\n  `${JSON.stringify(texts)}\\n\\n` +\n  'Respond with JSON only:';\n\n/**\n * Parse and validate a JSON array of translations from an AI API response.\n * @param {string} content Raw text content from the AI response.\n * @param {number} expectedCount Expected number of translated strings.\n * @param {string} serviceLabel Label for the AI service used in error messages, e.g. `'Anthropic\n * API'`.\n * @returns {string[]} Array of translated strings.\n * @throws {Error} When the content cannot be parsed or the count doesn’t match.\n */\nconst parseAiTranslationResponse = (content, expectedCount, serviceLabel) => {\n  let translations;\n\n  try {\n    translations = JSON.parse(content);\n  } catch {\n    throw new Error(`Failed to parse JSON response from ${serviceLabel}.`);\n  }\n\n  if (!Array.isArray(translations)) {\n    throw new Error(`Invalid JSON structure in ${serviceLabel} response.`);\n  }\n\n  if (translations.length !== expectedCount) {\n    throw new Error(\n      `Translation count mismatch: expected ${expectedCount}, got ${translations.length}`,\n    );\n  }\n\n  return translations;\n};\n\n/**\n * Create the functions to check and resolve the language pair of a translation service.\n * @param {(locale: string) => string | undefined} normalize Function to normalize a locale code to\n * what the service understands, which returns `undefined` for an unsupported locale.\n * @returns {{\n * availability: (languages: LanguagePair) => Promise<boolean>,\n * resolveLanguages: (sourceLanguage: string, targetLanguage: string) => [string, string],\n * }} `availability` checks if both the source and target languages are supported, and\n * `resolveLanguages` normalizes them, throwing when either is not supported.\n */\nexport const createLanguageResolver = (normalize) => ({\n  /**\n   * Check if the given source and target languages are supported.\n   * @param {LanguagePair} languages Language pair.\n   * @returns {Promise<boolean>} Result.\n   */\n  availability: async ({ sourceLanguage, targetLanguage }) =>\n    !!normalize(sourceLanguage) && !!normalize(targetLanguage),\n  /**\n   * Normalize the given source and target languages.\n   * @param {string} sourceLanguage Source locale code.\n   * @param {string} targetLanguage Target locale code.\n   * @returns {[string, string]} Normalized source and target languages.\n   * @throws {Error} When the source or target locale is not supported.\n   */\n  resolveLanguages: (sourceLanguage, targetLanguage) => {\n    const source = normalize(sourceLanguage);\n    const target = normalize(targetLanguage);\n\n    if (!source) {\n      throw new Error('Source locale is not supported.');\n    }\n\n    if (!target) {\n      throw new Error('Target locale is not supported.');\n    }\n\n    return [source, target];\n  },\n});\n\n/**\n * Check if the given source and target languages are supported, or resolve their names, throwing\n * when either is not supported.\n */\nexport const { availability, resolveLanguages: resolveLanguageNames } =\n  createLanguageResolver(normalizeLanguage);\n\n/**\n * Create a `translate` function for an AI-based translation service.\n * @param {(options: AiCompletionOptions) => Promise<string>} complete AI completion function from\n * the service’s AI module.\n * @param {string} model Model identifier to use for translation.\n * @param {string} apiLabel Label for the service used in error messages, e.g. `'Anthropic API'`.\n * @param {object} [extraOptions] Extra options to pass to `complete`, e.g. `{ reasoning: 'none' }`.\n * @returns {(texts: string[], options: TranslationOptions) => Promise<string[]>} Translate\n * function.\n */\nconst createAiTranslate =\n  (complete, model, apiLabel, extraOptions = {}) =>\n  /**\n   * Translate the given texts using the AI service.\n   * @param {string[]} texts Array of original texts.\n   * @param {TranslationOptions} options Options.\n   * @returns {Promise<string[]>} Translated strings in the original order.\n   */\n  async (texts, { sourceLanguage, targetLanguage, apiKey }) => {\n    const [sourceLangName, targetLangName] = resolveLanguageNames(sourceLanguage, targetLanguage);\n\n    const content = await complete({\n      apiKey,\n      model,\n      systemPrompt: createTranslationSystemPrompt(sourceLangName, targetLangName),\n      userMessage: createTranslationUserPrompt(texts),\n      ...extraOptions,\n    });\n\n    return parseAiTranslationResponse(content, texts.length, apiLabel);\n  };\n\n/**\n * Create a translation service backed by an AI service. Every AI service supports Markdown content\n * and preserves formatting.\n * @param {object} args Arguments.\n * @param {AiService} args.ai The service’s AI module.\n * @param {string} args.model Model identifier to use for translation.\n * @param {object} [args.extraOptions] Extra options to pass to `complete`.\n * @returns {TranslationService} Translation service.\n */\nexport const createAiTranslationService = ({\n  ai: { serviceId, serviceLabel, apiLabel, developerURL, apiKeyURL, apiKeyPattern, complete },\n  model,\n  extraOptions,\n}) => ({\n  serviceId,\n  serviceLabel,\n  apiLabel,\n  developerURL,\n  apiKeyURL,\n  apiKeyPattern,\n  markdownSupported: true,\n  availability,\n  translate: createAiTranslate(complete, model, apiLabel, extraOptions),\n});\n","import * as ai from '$lib/services/integrations/ai/anthropic';\n\nimport { createAiTranslationService } from './ai-translation.js';\n\n/**\n * @import { TranslationService } from '$lib/types/private';\n */\n\n/**\n * Translation service using Anthropic Claude Haiku. Supports markdown content and preserves\n * formatting.\n * @type {TranslationService}\n * @see https://docs.claude.com/en/docs/about-claude/models/overview\n * @see https://docs.claude.com/en/api/messages\n */\nexport default createAiTranslationService({\n  ai,\n  model: 'claude-haiku-5-5',\n  extraOptions: { reasoning: 'none' },\n});\n","import * as ai from '$lib/services/integrations/ai/deepseek';\n\nimport { createAiTranslationService } from './ai-translation.js';\n\n/**\n * @import { TranslationService } from '$lib/types/private';\n */\n\n/**\n * Translation service using DeepSeek. Supports markdown content and preserves formatting.\n * @type {TranslationService}\n * @see https://api-docs.deepseek.com/api/create-chat-completion\n */\nexport default createAiTranslationService({\n  ai,\n  model: 'deepseek-flash',\n  extraOptions: { reasoning: 'none' },\n});\n","import { postJSON } from '$lib/services/integrations/ai/api';\nimport { createLanguageResolver } from '$lib/services/integrations/translators/ai-translation';\nimport { splitIntoSizedChunks } from '$lib/services/utils/array';\nimport { getByteSize } from '$lib/services/utils/file';\nimport { getLikelyLocale } from '$lib/services/utils/locale';\n\n/**\n * @import { TranslationOptions, TranslationService } from '$lib/types/private';\n */\n\nconst serviceId = 'google';\nconst serviceLabel = 'Google Cloud Translation';\nconst apiLabel = 'Cloud Translation API';\nconst developerURL = 'https://console.cloud.google.com/apis/library/translate.googleapis.com';\nconst apiKeyURL = 'https://console.cloud.google.com/apis/api/translate.googleapis.com/credentials';\n// Anchored, so a key for another service entered while this one is selected isn’t accepted and sent\n// to the wrong API\nconst apiKeyPattern = /^AIza[0-9A-Za-z-_]{35}$/;\n\n/**\n * Supported source/target languages for Google Cloud Translation API.\n * @see https://cloud.google.com/translate/docs/languages\n */\nconst SUPPORTED_LANGUAGES = [\n  'ab,ace,ach,af,ak,alz,am,ar,as,awa,ay,az',\n  'ba,ban,bbc,be,bem,bew,bg,bho,bik,bm,bn,br,bs,bts,btx,bua',\n  'ca,ceb,cgg,chm,ckb,cnh,co,crh,crs,cs,cv,cy',\n  'da,de,din,doi,dov,dv,dz',\n  'ee,el,en,eo,es,et,eu',\n  'fa,ff,fi,fil,fj,fr,fr-CA,fr-FR,fy',\n  'ga,gaa,gd,gl,gn,gom,gu',\n  'ha,haw,he,hi,hil,hmn,hr,hrx,ht,hu,hy',\n  'id,ig,ilo,is,it,iw',\n  'ja,jv,jw',\n  'ka,kk,km,kn,ko,kri,ktu,ku,ky',\n  'la,lb,lg,li,lij,lmo,ln,lo,lt,ltg,luo,lus,lv',\n  'mai,mak,mg,mi,min,mk,ml,mn,mni-Mtei,mr,ms,ms-Arab,mt,my',\n  'ne,new,nl,no,nr,nso,nus,ny',\n  'oc,om,or',\n  'pa,pa-Arab,pag,pam,pap,pl,ps,pt,pt-BR,pt-PT',\n  'qu',\n  'rn,ro,rom,ru,rw',\n  'sa,scn,sd,sg,shn,si,sk,sl,sm,sn,so,sq,sr,ss,st,su,sv,sw,szl',\n  'ta,te,tet,tg,th,ti,tk,tl,tn,tr,ts,tt',\n  'ug,uk,ur,uz',\n  'vi',\n  'xh',\n  'yi,yo,yua,yue',\n  'zh,zh-CN,zh-TW,zu',\n]\n  .join(',')\n  .split(',');\n\n/**\n * Language codes that Google Cloud Translation API knows under a different code.\n * @type {Record<string, string>}\n */\nconst LANGUAGE_ALIASES = {\n  // Norwegian written standard, which Google calls Norwegian\n  nb: 'no',\n};\n\n/**\n * Normalize a locale code to a supported language code. A locale can have a script code, like\n * `zh-Hant` or `pa-Arab`, and a region code, like `fr-FR`, in either case and separated with a\n * hyphen or an underscore. Without a script code, the script is the one the region implies, e.g.\n * the Arabic script for `pa-PK`.\n * @param {string} locale Locale code, e.g., 'en', 'fr-FR', 'zh-CN', 'zh-Hant'.\n * @returns {string | undefined} Normalized language code, e.g., 'en', 'fr-FR', 'zh-CN', 'zh-TW'.\n */\nexport const normalizeLanguage = (locale) => {\n  const [language, ...parts] = locale.split(/[-_]/);\n  const lang = language.toLowerCase();\n  const scriptTag = parts.find((tag) => /^[a-z]{4}$/i.test(tag));\n  const regionTag = parts.find((tag) => /^(?:[a-z]{2}|\\d{3})$/i.test(tag));\n  const region = regionTag?.toUpperCase();\n\n  const script = scriptTag\n    ? `${scriptTag[0].toUpperCase()}${scriptTag.slice(1).toLowerCase()}`\n    : region && getLikelyLocale(`${lang}-${region}`)?.script;\n\n  // Chinese: We should not fall back to `zh` for Traditional Chinese, because it’s Simplified\n  if (lang === 'zh') {\n    if (script === 'Hant') {\n      return 'zh-TW';\n    }\n\n    if (script === 'Hans') {\n      return 'zh-CN';\n    }\n  }\n\n  // The bare language code gives the text in the language’s usual script, so don’t fall back to it\n  // for another script, e.g. `sr` for `sr-Latn` or `sr-ME`, which Google writes in Cyrillic\n  if (\n    script &&\n    !SUPPORTED_LANGUAGES.includes(`${lang}-${script}`) &&\n    script !== getLikelyLocale(lang)?.script\n  ) {\n    return undefined;\n  }\n\n  const candidates = [\n    script ? `${lang}-${script}` : undefined,\n    region ? `${lang}-${region}` : undefined,\n    LANGUAGE_ALIASES[lang] ?? lang,\n  ];\n\n  return candidates.find((code) => !!code && SUPPORTED_LANGUAGES.includes(code));\n};\n\n/**\n * Check if the given source and target languages are supported, or normalize them, throwing when\n * either is not supported.\n */\nexport const { availability, resolveLanguages } = createLanguageResolver(normalizeLanguage);\n\n/**\n * Maximum number of text segments the Cloud Translation API v2 accepts in a request.\n */\nconst MAX_SEGMENTS_PER_REQUEST = 128;\n/**\n * Maximum total size of the texts in a request, in UTF-8 bytes. The API rejects a request larger\n * than 100K bytes, so this leaves room for the rest of the JSON body.\n * @see https://cloud.google.com/translate/quotas\n */\nconst MAX_BYTES_PER_REQUEST = 90_000;\n\n/**\n * Split the given texts into chunks that each fit in a single API request: at most\n * {@link MAX_SEGMENTS_PER_REQUEST} texts and {@link MAX_BYTES_PER_REQUEST} bytes. A text larger\n * than the byte budget is given a chunk of its own, as a single text can’t be split.\n * @param {string[]} texts Texts.\n * @returns {string[][]} Chunks of texts in the original order.\n */\nexport const chunkTexts = (texts) =>\n  splitIntoSizedChunks(texts, {\n    maxItems: MAX_SEGMENTS_PER_REQUEST,\n    maxSize: MAX_BYTES_PER_REQUEST,\n    getSize: getByteSize,\n  });\n\n/**\n * Translate the given text with Google Cloud Translation API using the basic model and HTML format.\n * The texts are sent in as many requests as the API limits require, one after another.\n * @param {string[]} texts Array of original texts.\n * @param {TranslationOptions} options Options.\n * @returns {Promise<string[]>} Translated strings in the original order.\n * @throws {Error} When the source or target locale is not supported or API call fails.\n * @see https://cloud.google.com/translate/docs/basic/translating-text\n * @see https://cloud.google.com/translate/docs/reference/rest/v2/translate\n * @see https://cloud.google.com/docs/authentication/api-keys-use\n */\nconst translate = async (texts, { sourceLanguage, targetLanguage, apiKey }) => {\n  [sourceLanguage, targetLanguage] = resolveLanguages(sourceLanguage, targetLanguage);\n\n  // Cloud Translation API v2 endpoint\n  const url = 'https://translation.googleapis.com/language/translate/v2';\n  /** @type {string[]} */\n  const results = [];\n\n  // Send the requests one after another rather than at once, not to burst the per-minute quota\n  // eslint-disable-next-line no-restricted-syntax\n  for (const chunk of chunkTexts(texts)) {\n    const requestBody = {\n      q: chunk,\n      source: sourceLanguage,\n      target: targetLanguage,\n      format: 'html',\n    };\n\n    const { data } = /** @type {{ data: { translations: { translatedText: string }[] } }} */ (\n      // eslint-disable-next-line no-await-in-loop\n      await postJSON({\n        endpoint: url,\n        headers: { 'Content-Type': 'application/json', 'X-goog-api-key': apiKey },\n        apiLabel: 'Google Translate',\n        body: requestBody,\n      })\n    );\n\n    // cspell:disable-next-line\n    // Decode apostrophes in translated text (e.g., \"Aujourd&#39;hui\" → \"Aujourd'hui\")\n    results.push(...data.translations.map((t) => t.translatedText.replace(/&#39;/g, \"'\")));\n  }\n\n  return results;\n};\n\n/**\n * @type {TranslationService}\n */\nexport default {\n  serviceId,\n  serviceLabel,\n  apiLabel,\n  developerURL,\n  apiKeyURL,\n  apiKeyPattern,\n  markdownSupported: false,\n  availability,\n  translate,\n};\n","import { allAiServices } from '$lib/services/integrations/ai';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\nimport anthropic from './anthropic';\nimport deepseek from './deepseek';\nimport google from './google';\nimport googleAi from './google-ai';\nimport mistral from './mistral';\nimport openai from './openai';\n\n/**\n * @import { TranslationService } from '$lib/types/private';\n */\n\n/**\n * List of all the supported translation services. Alphabetical order by service name.\n * @type {Record<string, TranslationService>}\n */\nexport const allTranslationServices = {\n  anthropic,\n  deepseek,\n  google,\n  'google-ai': googleAi,\n  mistral,\n  openai,\n};\n\n/**\n * Dedicated machine translation services, whose API keys are managed on the Internationalization\n * settings panel. The others are backed by a generic AI service, whose API key is managed on the AI\n * settings panel.\n * @type {Record<string, TranslationService>}\n */\nexport const machineTranslationServices = Object.fromEntries(\n  Object.entries(allTranslationServices).filter(([serviceId]) => !(serviceId in allAiServices)),\n);\n\n/**\n * Translation service selected in the user preferences.\n * @type {{ readonly current: TranslationService }}\n */\nexport const translator = createDerivedState(() => {\n  const { defaultTranslationService = 'google' } = prefs;\n\n  return allTranslationServices[defaultTranslationService] ?? google;\n});\n","import * as ai from '$lib/services/integrations/ai/google';\n\nimport { createAiTranslationService } from './ai-translation.js';\n\n/**\n * @import { TranslationService } from '$lib/types/private';\n */\n\n/**\n * Translation service using Google Gemini Flash-Lite. Supports markdown content and preserves\n * formatting.\n * @type {TranslationService}\n * @see https://ai.google.dev/gemini-api/docs/models/gemini\n * @see https://ai.google.dev/api/generate-content\n */\nexport default createAiTranslationService({\n  ai,\n  model: 'gemini-3.5-flash-lite',\n  extraOptions: { responseFormat: 'application/json' },\n});\n","import * as ai from '$lib/services/integrations/ai/mistral';\n\nimport { createAiTranslationService } from './ai-translation.js';\n\n/**\n * @import { TranslationService } from '$lib/types/private';\n */\n\n/**\n * Translation service using Mistral Small. Supports markdown content and preserves formatting.\n * @type {TranslationService}\n * @see https://docs.mistral.ai/api\n */\nexport default createAiTranslationService({\n  ai,\n  model: 'mistral-small-latest',\n  extraOptions: { reasoning: 'none' },\n});\n","import * as ai from '$lib/services/integrations/ai/openai';\n\nimport { createAiTranslationService } from './ai-translation.js';\n\n/**\n * @import { TranslationService } from '$lib/types/private';\n */\n\n/**\n * Translation service using GPT-6 Luna. Supports markdown content and preserves formatting.\n * @type {TranslationService}\n * @see https://developers.openai.com/api/reference/resources/responses/methods/create\n */\nexport default createAiTranslationService({\n  ai,\n  model: 'gpt-6-luna',\n  // Keep the reasoning short, as its tokens are taken from the output budget the translation needs\n  extraOptions: { reasoning: 'low' },\n});\n","import { allAiServices } from '$lib/services/integrations/ai';\nimport { allCloudStorageServices } from '$lib/services/integrations/media-libraries/cloud';\nimport {\n  allStockAssetProviders,\n  getStockAssetMediaLibraryOptions,\n} from '$lib/services/integrations/media-libraries/stock';\nimport { machineTranslationServices } from '$lib/services/integrations/translators';\nimport { isInvalidApiKey } from '$lib/services/user/api-keys';\n\n/**\n * @import { AiService, MediaLibraryService, TranslationService } from '$lib/types/private';\n */\n\n/**\n * Services that take an API key, listed together, e.g. the translation services.\n * @typedef {object} ApiKeyServiceGroup\n * @property {string} key Key, e.g. `translators`.\n * @property {string} titleKey Message key of the group’s title.\n * @property {string} fieldLabelKey Message key of a service’s field label, which takes the service\n * name as `service`.\n * @property {[string, AiService | MediaLibraryService | TranslationService][]} entries Services,\n * with their IDs.\n */\n\n/**\n * Get the cloud storage services the CMS configuration turns on, which take an API key. Cloudinary\n * signs in with its own widget instead.\n * @returns {[string, MediaLibraryService][]} Services, with their IDs.\n */\nexport const getCloudStorageServiceEntries = () =>\n  Object.entries(allCloudStorageServices).filter(\n    ([, { isEnabled, authType }]) => (isEnabled?.() ?? true) && authType !== 'widget',\n  );\n\n/**\n * Get the stock photo services the CMS configuration turns on, which take an API key. Lorem Picsum\n * needs none.\n * @returns {[string, MediaLibraryService][]} Services, with their IDs.\n */\nexport const getStockPhotoServiceEntries = () => {\n  const { providers = [] } = getStockAssetMediaLibraryOptions();\n\n  return Object.entries(allStockAssetProviders).filter(\n    ([serviceId, { authType }]) =>\n      providers.includes(/** @type {any} */ (serviceId)) && authType !== 'none',\n  );\n};\n\n/**\n * Get the services that take an API key, in groups, leaving out the groups with none turned on.\n * @returns {ApiKeyServiceGroup[]} Groups.\n */\nexport const getApiKeyServiceGroups = () =>\n  /** @type {ApiKeyServiceGroup[]} */ ([\n    {\n      key: 'translators',\n      titleKey: 'prefs.i18n.translators.api_keys.title',\n      fieldLabelKey: 'prefs.i18n.translators.field_label',\n      entries: Object.entries(machineTranslationServices),\n    },\n    {\n      key: 'ai',\n      titleKey: 'prefs.ai.api_keys.title',\n      fieldLabelKey: 'prefs.ai.field_label',\n      entries: Object.entries(allAiServices),\n    },\n    {\n      key: 'cloud_storage',\n      titleKey: 'prefs.media.cloud_storage.api_keys.title',\n      fieldLabelKey: 'prefs.media.cloud_storage.field_label',\n      entries: getCloudStorageServiceEntries(),\n    },\n    {\n      key: 'stock_photos',\n      titleKey: 'prefs.media.stock_photos.api_keys.title',\n      fieldLabelKey: 'prefs.media.stock_photos.field_label',\n      entries: getStockPhotoServiceEntries(),\n    },\n  ]).filter(({ entries }) => entries.length);\n\n/**\n * Find an API key that doesn’t match the pattern its service expects.\n * @param {Record<string, string>} apiKeys API keys by service ID. Empty ones are ignored.\n * @param {ApiKeyServiceGroup[]} groups Services the keys are for.\n * @returns {string | undefined} Label of the first service whose key is wrong, if any.\n */\nexport const findInvalidApiKey = (apiKeys, groups) =>\n  groups\n    .flatMap(({ entries }) => entries)\n    .find(([serviceId, { apiKeyPattern }]) =>\n      isInvalidApiKey(apiKeys[serviceId]?.trim() ?? '', apiKeyPattern),\n    )?.[1].serviceLabel;\n","import { allAssets } from '$lib/services/assets/state';\nimport { backend } from '$lib/services/backends';\nimport { advanceRepositoryHead } from '$lib/services/backends/git/shared/file-cache';\nimport { createStaleCheck, repositoryHead } from '$lib/services/backends/git/shared/head';\nimport { getRootDir } from '$lib/services/backends/root-dir';\nimport { allEntries } from '$lib/services/contents';\nimport { productionSHA } from '$lib/services/deployments';\n\n/**\n * @import {\n * Asset,\n * BackendService,\n * Entry,\n * RemoteChanges,\n * RepositoryInfo,\n * } from '$lib/types/private';\n */\n\n/**\n * Shortest gap between two checks made in passing, in milliseconds: the tab being focused, or an\n * entry being opened, prompts a check, and doing either a few times in a row shouldn’t send a burst\n * of requests. A save always checks.\n */\nexport const MIN_CHECK_GAP = 10 * 1000;\n\n/**\n * The check in flight, if any. A second caller gets the same promise rather than a second round of\n * requests.\n * @type {Promise<RemoteChanges | undefined> | undefined}\n */\nlet pending;\n/** When the last check was started, as a Unix timestamp in milliseconds. `0` before the first. */\nlet lastCheckTime = 0;\n/**\n * Number of commits being made. A check isn’t started while one is: the commit is about to put its\n * results into the stores, and a fetch landing after that would replace them with the state of the\n * repository from before the commit.\n */\nlet commitCount = 0;\n/**\n * The last commit queued, settled once it’s done, whether it succeeded or not. Commits are made one\n * at a time, so each is made on top of the head the previous one left: GitHub refuses a commit made\n * against a head other than the branch’s current one.\n * @type {Promise<void>}\n */\nlet commitQueue = Promise.resolve();\n\n/**\n * Work out what a fetch has changed. The fetch keeps every unchanged entry and asset as the same\n * object and carries an entry’s ID over to its changed version, so the two lists can be compared\n * directly.\n * @param {object} args Arguments.\n * @param {Entry[]} args.entriesBefore Entries before the fetch.\n * @param {Asset[]} args.assetsBefore Assets before the fetch.\n * @returns {RemoteChanges} What has changed.\n */\nexport const diffStores = ({ entriesBefore, assetsBefore }) => {\n  const entryIds = new Map(entriesBefore.map((entry) => [entry.id, entry]));\n  const assetPaths = new Map(assetsBefore.map((asset) => [asset.path, asset]));\n  const entriesAfter = allEntries.current;\n  const assetsAfter = allAssets.current;\n  const entryIdsAfter = new Set(entriesAfter.map(({ id }) => id));\n  const assetPathsAfter = new Set(assetsAfter.map(({ path }) => path));\n\n  return {\n    addedEntries: entriesAfter.filter(({ id }) => !entryIds.has(id)),\n    modifiedEntries: entriesAfter.filter((entry) => {\n      const before = entryIds.get(entry.id);\n\n      return !!before && before !== entry;\n    }),\n    deletedEntries: entriesBefore.filter(({ id }) => !entryIdsAfter.has(id)),\n    addedAssets: assetsAfter.filter(({ path }) => !assetPaths.has(path)),\n    modifiedAssets: assetsAfter.filter((asset) => {\n      const before = assetPaths.get(asset.path);\n\n      return !!before && before !== asset;\n    }),\n    deletedAssets: assetsBefore.filter(({ path }) => !assetPathsAfter.has(path)),\n  };\n};\n\n/**\n * Whether the given changes contain anything.\n * @param {RemoteChanges} changes Changes.\n * @returns {boolean} Result.\n */\nconst hasChanges = (changes) => Object.values(changes).some((list) => list.length > 0);\n/**\n * Tree SHA of the configured root directory at the commit it was last looked up for, so a check\n * made after the branch has moved only has to look up the new head.\n * @type {{ rootDir: string, commit: string, sha: string | undefined } | undefined}\n */\nlet rootDirTree;\n\n/**\n * Forget the root directory tree looked up last. Used in tests.\n */\nexport const _resetRootDirTree = () => {\n  rootDirTree = undefined;\n};\n\n/**\n * Check whether the configured root directory is the same at both commits, which means a commit\n * made in between only changed the rest of the repository, such as another site in a monorepo.\n * @param {BackendService} service Backend service.\n * @param {string} from Commit the site data reflects.\n * @param {string} to New head of the branch.\n * @returns {Promise<boolean>} Result. It’s `false` without a root directory, for a backend that\n * can’t tell, and when the lookup fails, so the files are fetched as usual.\n */\nconst isRootDirUnchanged = async ({ fetchDirSHA }, from, to) => {\n  const rootDir = getRootDir();\n\n  if (!rootDir || !fetchDirSHA) {\n    return false;\n  }\n\n  try {\n    // The tree at the commit the data reflects is usually known from the previous check\n    const [before, after] = await Promise.all([\n      rootDirTree?.rootDir === rootDir && rootDirTree.commit === from\n        ? rootDirTree.sha\n        : fetchDirSHA(from, rootDir),\n      fetchDirSHA(to, rootDir),\n    ]);\n\n    rootDirTree = { rootDir, commit: to, sha: after };\n\n    return !!before && before === after;\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to look up the root directory.', ex);\n\n    return false;\n  }\n};\n\n/**\n * Ask the backend for the branch head and, if it has moved since the site data was loaded, fetch\n * what has changed into the stores.\n * @param {BackendService} service Backend service.\n * @returns {Promise<RemoteChanges | undefined>} What has changed, or `undefined` if nothing has.\n */\nconst check = async (service) => {\n  const { fetchLastCommit, fetchFiles } = service;\n  // The site data may be discarded while the requests are on their way, e.g. by signing out; the\n  // results then belong to the previous session and must not be written back\n  const isStale = createStaleCheck();\n  const lastCommit = await /** @type {NonNullable<typeof fetchLastCommit>} */ (fetchLastCommit)();\n\n  if (isStale() || lastCommit.hash === repositoryHead.current) {\n    return undefined;\n  }\n\n  // In a monorepo, most commits are likely made to the other sites. One that leaves the root\n  // directory as it is changes nothing the CMS shows, so nothing is fetched. The site isn’t taken\n  // to be rebuilt from the commit either, as a build for a commit that doesn’t touch it is\n  // typically skipped\n  if (await isRootDirUnchanged(service, repositoryHead.current, lastCommit.hash)) {\n    if (isStale()) {\n      return undefined;\n    }\n\n    await advanceRepositoryHead(\n      /** @type {RepositoryInfo} */ (service.repository),\n      repositoryHead.current,\n      lastCommit.hash,\n    );\n\n    return undefined;\n  }\n\n  const entriesBefore = allEntries.current;\n  const assetsBefore = allAssets.current;\n\n  await fetchFiles({ lastCommit });\n\n  if (isStale()) {\n    return undefined;\n  }\n\n  // The site is now being built from the new head, so that’s the deployment to watch\n  productionSHA.current = repositoryHead.current;\n\n  const changes = diffStores({ entriesBefore, assetsBefore });\n\n  return hasChanges(changes) ? changes : undefined;\n};\n\n/**\n * Check whether someone else has pushed to the configured branch since the site data was loaded,\n * and if so bring the stores up to date. The check costs one small request when nothing has\n * changed; otherwise the files that have changed are fetched, and the entries and assets already in\n * the stores are kept wherever they still apply, so the app doesn’t lose track of them.\n *\n * Nothing is checked while a commit is being made, or for a backend that can’t tell — the local\n * backend has no commits to compare.\n * @param {object} [options] Options.\n * @param {number} [options.maxAge] Skip the check if one was started within this many milliseconds,\n * whoever asked for it. A check made in passing uses {@link MIN_CHECK_GAP}.\n * @returns {Promise<RemoteChanges | undefined>} The entries and assets that have changed, or\n * `undefined` if nothing has, or if no check could be made.\n * @throws {Error} When the backend couldn’t be reached.\n */\nexport const checkForRemoteChanges = async ({ maxAge = 0 } = {}) => {\n  const service = backend.current;\n\n  if (!service?.fetchLastCommit || !repositoryHead.current || commitCount) {\n    return undefined;\n  }\n\n  if (maxAge && !pending && Date.now() - lastCheckTime < maxAge) {\n    return undefined;\n  }\n\n  if (!pending) {\n    lastCheckTime = Date.now();\n    pending = check(service).finally(() => {\n      pending = undefined;\n    });\n  }\n\n  return pending;\n};\n\n/**\n * Run a commit, holding off any check for remote changes until its results are in the stores. A\n * check already in flight is waited for first, so it can’t land in the middle either. A commit\n * queued while another is being made waits for that one to finish, so the user’s own commits don’t\n * race each other; a failed commit doesn’t hold up the next one.\n * @template T\n * @param {() => Promise<T>} commit Function that makes the commit and updates the stores.\n * @returns {Promise<T>} Whatever the function returns.\n */\nexport const suspendChecksWhile = async (commit) => {\n  const previousCommit = commitQueue;\n  const { promise, resolve } = Promise.withResolvers();\n\n  commitQueue = promise;\n  // Counted from the start, so no check is started while the commit is waiting for its turn\n  commitCount += 1;\n\n  try {\n    await previousCommit;\n    // Waiting for the promise is what matters; the result, or a failure, is the other caller’s\n    await pending?.catch(() => undefined);\n\n    return await commit();\n  } finally {\n    commitCount -= 1;\n    resolve(undefined);\n  }\n};\n","import { findEntriesByAssets } from '$lib/services/assets/references';\nimport { allAssets } from '$lib/services/assets/state';\n\n/**\n * @import { Asset, CompanionEntry, Entry, UnpublishedEntry } from '$lib/types/private';\n */\n\n/**\n * Get the version of the given asset that belongs with the given entry. An asset committed to a\n * workflow branch only exists on that branch, so it’s only the entry of that branch that can use\n * it: any other entry gets the published version it shadows, if there’s one. Otherwise a file that\n * someone pushed to one pull request would be copied into another entry’s commit — when the entry\n * is moved or duplicated — without having been reviewed.\n * @param {Asset | undefined} asset Asset from the asset list.\n * @param {Entry | undefined} entry Entry using the asset, published or not.\n * @returns {Asset | undefined} Asset, or `undefined` if the entry has no version of it.\n */\nexport const getEntryAssetVersion = (asset, entry) => {\n  const branch = asset?.workflow?.branch;\n\n  if (\n    !branch ||\n    branch === /** @type {UnpublishedEntry | undefined} */ (entry)?.workflow?.pullRequest.branch\n  ) {\n    return asset;\n  }\n\n  return /** @type {Asset} */ (asset).workflow?.replacedAsset;\n};\n\n/**\n * Get those of the given asset paths that the given entry uses, in a media field or as a media URL\n * in a Markdown or RichText field, the way the editor resolves them to display the files. So do the\n * new entries created or edited from a Relation field of the entry, which are committed along with\n * it.\n * @param {Entry} entry Entry, published or not.\n * @param {CompanionEntry[]} companions Entries of other collections committed along with it.\n * @param {string[]} paths Asset paths.\n * @returns {Set<string>} Paths used.\n */\nexport const getUsedAssetPaths = (entry, companions, paths) => {\n  if (!paths.length) {\n    return new Set();\n  }\n\n  const results = findEntriesByAssets(\n    paths.map((path) => ({ asset: /** @type {Asset} */ ({ path }) })),\n    { entries: [entry, ...companions.map(({ entry: companion }) => companion)] },\n  );\n\n  return new Set(paths.filter((_path, index) => results[index].length));\n};\n\n/**\n * Merge assets committed to a workflow branch into the regular asset list, so an image attached to\n * an unpublished entry can be previewed before the entry is published. When an asset shadows a\n * published file at the same path, the published version is kept aside so it can be restored if the\n * draft is discarded.\n * @param {Asset[]} assets Assets to merge. Each one must carry its `workflow.branch`.\n */\nexport const mergeWorkflowAssets = (assets) => {\n  if (!assets.length) {\n    return;\n  }\n\n  // A map keeps the existing order, so a merged asset doesn’t jump to the end of the media library\n  const assetMap = new Map(allAssets.current.map((asset) => [asset.path, asset]));\n\n  assets.forEach((asset) => {\n    const existing = assetMap.get(asset.path);\n\n    assetMap.set(asset.path, {\n      ...asset,\n      workflow: {\n        branch: /** @type {string} */ (asset.workflow?.branch),\n        // Don’t let a re-save of the same draft overwrite the original published version\n        replacedAsset: existing?.workflow ? existing.workflow.replacedAsset : existing,\n      },\n    });\n  });\n\n  allAssets.current = [...assetMap.values()];\n};\n\n/**\n * Remove the assets committed to the given workflow branch, restoring any published version they\n * were shadowing.\n * @param {string} branch Workflow branch name.\n * @param {(asset: Asset) => boolean} filter Function to pick the assets to remove.\n */\nconst removeBranchAssets = (branch, filter) => {\n  allAssets.current = allAssets.current.flatMap((asset) =>\n    asset.workflow?.branch === branch && filter(asset)\n      ? (asset.workflow.replacedAsset ?? [])\n      : asset,\n  );\n};\n\n/**\n * Remove the assets committed to the given workflow branch, restoring any published version they\n * were shadowing. Used when a draft is discarded, as the branch and its files are then gone.\n * @param {string} branch Workflow branch name.\n */\nexport const removeWorkflowAssets = (branch) => {\n  removeBranchAssets(branch, () => true);\n};\n\n/**\n * Remove the assets committed to the given workflow branch at the given paths, restoring any\n * published version they were shadowing. Used when a save takes the files off the branch again.\n * @param {string} branch Workflow branch name.\n * @param {Set<string>} paths File paths.\n */\nexport const removeWorkflowAssetsAt = (branch, paths) => {\n  removeBranchAssets(branch, ({ path }) => paths.has(path));\n};\n\n/**\n * Clear the Editorial Workflow information from the assets committed to the given branch, as they\n * now exist on the configured branch. Used when a draft is published.\n * @param {string} branch Workflow branch name.\n */\nexport const publishWorkflowAssets = (branch) => {\n  allAssets.current = allAssets.current.map((asset) => {\n    if (asset.workflow?.branch !== branch) {\n      return asset;\n    }\n\n    const { workflow: _workflow, ...publishedAsset } = asset;\n\n    return publishedAsset;\n  });\n};\n","import { isConfigReadonly } from '$lib/services/config/readonly';\nimport { getCollectionLabel } from '$lib/services/contents/collection';\nimport { getCollectionFilesByEntry } from '$lib/services/contents/collection/files';\nimport { getAssociatedCollections } from '$lib/services/contents/entry/collections';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\n\n/**\n * @import { Entry, InternalCollection } from '$lib/types/private';\n */\n\n/**\n * Check whether an entry is read-only with the `readonly` option, which is when the whole CMS is,\n * or any collection or collection file the entry belongs to is. An entry can appear in more than\n * one collection, and it can’t be rewritten through one while another locks it. This is for an\n * entry rewritten along with another change, e.g. a reference to a renamed entry, so a branch the\n * user can’t push to doesn’t count: a simple-mode change is read-only as a whole then, and one\n * going through Editorial Workflow commits the rewrite to its own branch.\n * @param {Entry} entry Entry.\n * @returns {boolean} Result.\n */\nexport const isEntryReadonly = (entry) =>\n  isConfigReadonly() ||\n  getAssociatedCollections(entry).some(\n    (collection) =>\n      isConfigReadonly({ collection }) ||\n      getCollectionFilesByEntry(collection, entry).some((collectionFile) =>\n        isConfigReadonly({ collection, collectionFile }),\n      ),\n  );\n\n/**\n * Get the label naming an entry in a message about the read-only entries that block a change, e.g.\n * `Posts › Hello World`.\n * @param {Entry} entry Entry.\n * @param {InternalCollection} [collection] Collection the entry is shown under. Default: the first\n * collection the entry belongs to.\n * @returns {string} Label, or the entry slug if the entry belongs to no collection.\n */\nexport const getReadonlyEntryLabel = (entry, collection = getAssociatedCollections(entry)[0]) =>\n  collection\n    ? `${getCollectionLabel(collection)} › ${getEntrySummary(collection, entry)}`\n    : entry.slug;\n","import { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { isEntryReadonly } from '$lib/services/contents/entry/readonly';\n\n/**\n * @import { Entry, InternalEntryCollection } from '$lib/types/private';\n */\n\n/**\n * Check whether an existing entry of an entry collection can be changed from a Relation field of\n * another entry and saved along with it. An entry stored in a file with the other entries of the\n * collection can’t, as two entries edited in the same file couldn’t be saved at once, nor can the\n * collection’s index file, which has fields of its own, or a read-only entry.\n * @param {InternalEntryCollection} collection Collection the entry belongs to.\n * @param {Entry} entry Entry.\n * @returns {boolean} Result.\n */\nexport const isEntryEditableAlong = (collection, entry) =>\n  !isArrayFileCollection(collection) &&\n  !isCollectionIndexFile(collection, entry) &&\n  !isEntryReadonly(entry);\n","import { generateUUID } from '@sveltia/utils/crypto';\n\nimport { parseAssetFileInfo } from '$lib/services/backends/git/shared/parse-files';\nimport { toFileListItem } from '$lib/services/backends/git/shared/tree';\nimport { createFileList } from '$lib/services/backends/process';\nimport { isInRootDir } from '$lib/services/backends/root-dir';\nimport { isReadonly } from '$lib/services/config/readonly';\nimport { allEntries, findEntryByPaths } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport {\n  getEntriesByCollection,\n  matchesCollectionFilter,\n} from '$lib/services/contents/collection/entries';\nimport { getCollectionFileEntry } from '$lib/services/contents/collection/files';\nimport { isEntryEditableAlong } from '$lib/services/contents/entry/editable';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport { prepareEntries } from '$lib/services/contents/file/process';\nimport { getEntryFoldersByPath } from '$lib/services/contents/folders';\nimport { usesMultiFileStructure } from '$lib/services/contents/i18n/config';\nimport { parseBranchName } from '$lib/services/workflow/branch';\nimport { getUpstreamBranchName } from '$lib/services/workflow/forks';\n\n/**\n * @import {\n * Asset,\n * BaseEntryListItem,\n * BaseFileListItemProps,\n * CompanionEntry,\n * Entry,\n * InternalEntryCollection,\n * EntryFolderInfo,\n * WorkflowStatus,\n * UnpublishedEntry,\n * UnpublishedEntryProps,\n * WorkflowPullRequest,\n * } from '$lib/types/private';\n */\n\n/**\n * Get the given entry collection, which is known to exist.\n * @param {string} name Collection name.\n * @returns {InternalEntryCollection} Collection.\n */\nconst getEntryCollection = (name) => /** @type {InternalEntryCollection} */ (getCollection(name));\n\n/**\n * Assign the given entry file to the given collection if its path is in one of the collection’s\n * folders. Collections can share a folder and tell their entries apart with the `filter` option,\n * but the file list assigns a file to the first of them only, so a file of the collection a pull\n * request was opened for may come with the folder of another one.\n * @param {BaseEntryListItem} file Entry file.\n * @param {string} collectionName Collection name.\n * @returns {BaseEntryListItem} Entry file, with the collection’s folder if the path is in it.\n * @see https://github.com/sveltia/sveltia-cms/issues/1149\n */\nconst assignToCollection = (file, collectionName) => {\n  if (file.folder.collectionName === collectionName) {\n    return file;\n  }\n\n  const folder = getEntryFoldersByPath(file.path).find(\n    (candidate) => candidate.collectionName === collectionName,\n  );\n\n  return folder ? { ...file, folder } : file;\n};\n\n/**\n * Find the folder of another collection an entry parsed for the given collection belongs to: an\n * entry the collection’s `filter` option excludes, in a folder it shares with a collection whose\n * filter the entry passes. That’s an entry of the other collection committed along with the entry\n * the pull request was opened for, such as one created from a Relation field.\n * @param {Entry} entry Entry.\n * @param {string} collectionName Name of the collection the entry was parsed for.\n * @returns {EntryFolderInfo | undefined} Folder of the other collection, if any.\n */\nconst findOtherCollectionFolder = (entry, collectionName) => {\n  const otherFolders = getEntryFoldersByPath(getEntryPaths(entry)[0]).filter(\n    (folder) => folder.collectionName !== collectionName,\n  );\n\n  if (!otherFolders.length) {\n    return undefined;\n  }\n\n  // Both collections exist, as the entry was parsed from a file in their folders\n  if (matchesCollectionFilter(getEntryCollection(collectionName), entry)) {\n    return undefined;\n  }\n\n  return otherFolders.find((folder) =>\n    matchesCollectionFilter(getEntryCollection(folder.collectionName), entry),\n  );\n};\n\n/**\n * Get the key that links the localized files of an entry with the multi-file i18n structure, as\n * {@link prepareEntries} does: the canonical slug if one of the files has it, or the sub path.\n * @param {Entry} entry Entry.\n * @param {string} canonicalSlugKey Property name of the canonical slug.\n * @returns {string} Key.\n */\nconst getLinkingKey = (entry, canonicalSlugKey) =>\n  Object.values(entry.locales)\n    .map(({ content }) => content[canonicalSlugKey])\n    .find((value) => typeof value === 'string') ?? entry.subPath;\n\n/**\n * Find the published version of an entry parsed from a pull request.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry parsed from the pull request.\n * @param {string[]} args.previousPaths File paths the pull request renamed the entry from.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name.\n * @returns {Entry | undefined} Published entry.\n */\nconst findPublishedEntry = ({ entry, previousPaths, collectionName, fileName }) => {\n  // `allEntries` holds the version currently on the configured branch\n  const publishedEntry = findEntryByPaths(new Set([...getEntryPaths(entry), ...previousPaths]));\n\n  if (publishedEntry) {\n    return publishedEntry;\n  }\n\n  // A locale turned on for the entry adds a file the published version doesn’t have, so a pull\n  // request carrying only that file shares no path with it. Link the files the way the entry list\n  // does instead: a collection file by its name, and an entry by its canonical slug or sub path\n  if (fileName) {\n    return getCollectionFileEntry(collectionName, fileName);\n  }\n\n  const collection = getCollection(collectionName);\n\n  // Other structures keep every locale in the same file, which a path always finds\n  if (!collection || !usesMultiFileStructure(collection._i18n.structureMap)) {\n    return undefined;\n  }\n\n  const canonicalSlugKey = collection._i18n.canonicalSlug.key;\n  const linkingKey = getLinkingKey(entry, canonicalSlugKey);\n\n  return getEntriesByCollection(collectionName).find(\n    (published) => getLinkingKey(published, canonicalSlugKey) === linkingKey,\n  );\n};\n\n/**\n * Fill in the parts of an unpublished entry that the pull request doesn’t carry. With the\n * multi-file i18n structure, an entry is spread over one file per locale and only the changed ones\n * are committed, so the rest have to come from the published version. Without them the editor shows\n * the untouched locales as disabled, and an entry whose default locale file isn’t in the pull\n * request has no slug at all, because the slug is read from that file alone.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry parsed from the pull request.\n * @param {string[]} args.previousPaths File paths the pull request renamed the entry from.\n * @param {Set<string>} args.deletedPaths File paths the pull request deletes. A locale turned off\n * for the entry has its file deleted, so it’s left out rather than brought back from the published\n * version.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name.\n * @param {Entry} [args.publishedEntry] Published version of the entry, if already known. Looked up\n * otherwise.\n * @returns {Entry} Entry with the unchanged locales merged in.\n */\nconst completeEntry = ({\n  entry,\n  previousPaths,\n  deletedPaths,\n  collectionName,\n  fileName,\n  publishedEntry = findPublishedEntry({ entry, previousPaths, collectionName, fileName }),\n}) => {\n  if (!publishedEntry) {\n    return entry;\n  }\n\n  // A rename commits every locale file, so the pull request’s own slug is authoritative. Otherwise\n  // the published entry is: the slug may have come from a non-default locale file, which differs\n  // from the entry’s own slug when localized slugs are in use\n  const renamed = !!previousPaths.length && !!entry.slug;\n\n  return {\n    ...publishedEntry,\n    ...entry,\n    // The pull request wins for the locales it carries; the others stay as published, unless it\n    // deletes their files\n    locales: {\n      ...Object.fromEntries(\n        Object.entries(publishedEntry.locales).filter(([, { path }]) => !deletedPaths.has(path)),\n      ),\n      ...entry.locales,\n    },\n    slug: renamed ? entry.slug : publishedEntry.slug,\n    subPath: renamed ? entry.subPath : publishedEntry.subPath,\n  };\n};\n\n/**\n * Parse the entries of other collections that ride along in a pull request: those created or\n * edited from a Relation field of the entry the pull request was opened for, and committed with it.\n * A new entry is one the configured branch doesn’t have yet, in a collection the CMS can create\n * entries in. An existing one is changed in the pull request; its unchanged locales come from the\n * published version, whose ID it keeps. That’s also how the CMS rewrites another entry along with\n * the entry, e.g. to update a reference to it on a rename, so such an entry is listed as edited\n * too.\n * A file of a file collection, which a Relation field can’t add to or edit, or of a collection the\n * CMS can’t write to that way, isn’t one of them: such a file is left for the publish check to\n * refuse.\n * @param {BaseEntryListItem[]} entryFiles Entry files in the pull request, with their text.\n * @param {string} collectionName Name of the collection the pull request was opened for.\n * @param {Set<string>} deletedPaths File paths the pull request deletes, such as the file of a\n * locale turned off for an edited entry.\n * @returns {Promise<CompanionEntry[]>} Entries.\n */\nconst parseCompanions = async (entryFiles, collectionName, deletedPaths) => {\n  /**\n   * Check whether the CMS can create an entry in the given collection.\n   * @param {string} name Collection name.\n   * @returns {boolean} Result.\n   */\n  const isCreatable = (name) => getEntryCollection(name).create !== false;\n\n  // Neither kind can be in a collection the CMS can’t write to, so its files aren’t parsed at all\n  const files = entryFiles.filter(({ folder, text }) => {\n    const collection = getCollection(folder.collectionName);\n\n    return (\n      folder.collectionName !== collectionName &&\n      folder.fileName === undefined &&\n      text !== undefined &&\n      collection?._type === 'entry' &&\n      !isReadonly({ collection })\n    );\n  });\n\n  const results = await Promise.all(\n    [...Map.groupBy(files, ({ folder }) => folder.collectionName)].map(\n      async ([companionCollectionName, companionFiles]) =>\n        (await prepareEntries(companionFiles)).entries.flatMap((entry) => {\n          const publishedEntry = findPublishedEntry({\n            entry,\n            previousPaths: [],\n            collectionName: companionCollectionName,\n          });\n\n          if (!publishedEntry) {\n            return isCreatable(companionCollectionName)\n              ? [{ collectionName: companionCollectionName, entry }]\n              : [];\n          }\n\n          if (!isEntryEditableAlong(getEntryCollection(companionCollectionName), publishedEntry)) {\n            return [];\n          }\n\n          return [\n            {\n              collectionName: companionCollectionName,\n              entry: {\n                ...completeEntry({\n                  entry,\n                  previousPaths: [],\n                  deletedPaths,\n                  collectionName: companionCollectionName,\n                  publishedEntry,\n                }),\n                id: publishedEntry.id,\n              },\n              edited: true,\n            },\n          ];\n        }),\n    ),\n  );\n\n  return results.flat();\n};\n\n/**\n * Pick the entries a pull request was opened for out of those parsed from the files of its\n * collection. Renaming or deleting an entry rewrites the other entries of the collection that\n * reference it, in a collection with a Relation field pointing at itself, and moving an entry of a\n * nested collection moves the entries below it along. Those files are committed to the same branch,\n * but they belong to the entries the CMS rewrote, which are published as they were written and\n * aren’t listed: the publish check accounts for them. The branch name tells the entry apart, as it\n * carries the slug the entry had when the pull request was opened, either its published one or the\n * one it’s saved with; a new entry, which no other entry can reference yet, is the branch’s as\n * well. An entry renamed again after the pull request was opened matches neither, so if nothing\n * else does, the entry the pull request renamed is taken, the one highest up the tree if the\n * entries below it moved along. Otherwise a pull request that vacates a path of the collection\n * deletes the entry, which has no file left to parse, while one that doesn’t keeps every entry, so\n * it doesn’t vanish from the board.\n * @param {object} args Arguments.\n * @param {Entry[]} args.entries Entries parsed from the pull request.\n * @param {string} args.slug Entry slug, or collection file name, the branch name carries.\n * @param {WorkflowPullRequest} args.pullRequest Pull request.\n * @param {string[]} args.previousPaths Paths of the collection’s entry files the pull request\n * renames or deletes.\n * @returns {Entry[]} Entries of the pull request.\n */\nconst findOwnEntries = ({ entries, slug, pullRequest, previousPaths: vacatedPaths }) => {\n  const renames = new Map(\n    pullRequest.files.flatMap(({ path, previousPath }) =>\n      previousPath ? [[path, previousPath]] : [],\n    ),\n  );\n\n  const candidates = entries.map((entry) => {\n    const paths = getEntryPaths(entry);\n    const previousPaths = paths.flatMap((path) => renames.get(path) ?? []);\n\n    const publishedEntry =\n      findEntryByPaths(paths) ??\n      (previousPaths.length ? findEntryByPaths(previousPaths) : undefined);\n\n    return { entry, publishedEntry, renamed: !!previousPaths.length };\n  });\n\n  const ownEntries = candidates\n    .filter(\n      ({ entry, publishedEntry }) =>\n        !publishedEntry || entry.slug === slug || publishedEntry.slug === slug,\n    )\n    .map(({ entry }) => entry);\n\n  if (ownEntries.length) {\n    return ownEntries;\n  }\n\n  if (!vacatedPaths.length) {\n    return entries;\n  }\n\n  /**\n   * Get the depth of the given entry in its collection.\n   * @param {Entry} entry Entry.\n   * @returns {number} Number of path segments in its sub path.\n   */\n  const getDepth = (entry) => entry.subPath.split('/').length;\n\n  const [movedEntry] = candidates\n    .filter(({ renamed }) => renamed)\n    .map(({ entry }) => entry)\n    .sort((a, b) => getDepth(a) - getDepth(b));\n\n  return movedEntry ? [movedEntry] : [];\n};\n\n/**\n * Contents of one or more pull requests.\n * @typedef {object} PullRequestContents\n * @property {UnpublishedEntry[]} entries Unpublished entries.\n * @property {Asset[]} assets Assets committed along with the entries. These only exist on the\n * workflow branch until the entries are published.\n */\n\n/**\n * Create the workflow properties of an unpublished entry, which tie it to its pull request.\n * @param {object} args Arguments.\n * @param {WorkflowPullRequest} args.pullRequest Pull request holding the entry.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string[]} [args.previousPaths] Paths the entry occupied before the pull request.\n * @param {CompanionEntry[]} [args.companions] New entries of other collections in the pull request.\n * @returns {UnpublishedEntryProps} Properties.\n */\nexport const createUnpublishedEntryProps = ({\n  pullRequest,\n  collectionName,\n  fileName,\n  previousPaths,\n  companions = [],\n}) => ({\n  pullRequest,\n  status: pullRequest.status,\n  collectionName,\n  fileName,\n  previousPaths,\n  ...(companions.length ? { companions } : {}),\n});\n\n/**\n * Parse the files in the given pull request. See {@link convertPullRequest}.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<PullRequestContents>} Entries and assets.\n */\nconst parsePullRequestContents = async (pullRequest) => {\n  // A contributor’s branch is named like the CMS’s own, once the fork is taken off its name\n  const parsed = parseBranchName(getUpstreamBranchName(pullRequest.branch));\n\n  // A branch named without the root directory belongs to the site only if all its files are in the\n  // directory; otherwise it’s another site’s in the monorepo, or a change the CMS can’t show\n  if (\n    !parsed ||\n    (parsed.legacy &&\n      pullRequest.files.some(\n        ({ path, previousPath }) =>\n          !isInRootDir(path) || (previousPath !== undefined && !isInRootDir(previousPath)),\n      ))\n  ) {\n    return { entries: [], assets: [] };\n  }\n\n  const { collectionName } = parsed;\n\n  const files = /** @type {BaseFileListItemProps[]} */ (\n    pullRequest.files\n      .filter(({ deleted }) => !deleted)\n      .map(({ path, sha, size, text }) => toFileListItem(path, { sha, size, text }))\n  );\n\n  const { entryFiles: listedEntryFiles, assetFiles } = createFileList(files);\n  let entryFiles = listedEntryFiles.map((file) => assignToCollection(file, collectionName));\n\n  // Editing the slug renames the entry file. Keep the path it came from, so the entry list can\n  // still match the draft with its published counterpart. Both backends report a rename with the\n  // old path, and a file the pull request simply deleted counts too.\n  const vacatedPaths = pullRequest.files.flatMap(({ path, deleted, previousPath }) => {\n    if (previousPath) {\n      return [previousPath];\n    }\n\n    return deleted ? [path] : [];\n  });\n\n  const vacatedEntryFiles = vacatedPaths.length\n    ? createFileList(vacatedPaths.map((path) => toFileListItem(path)))\n        .entryFiles.map((file) => assignToCollection(file, collectionName))\n        .filter(({ folder }) => folder.collectionName === collectionName)\n    : [];\n\n  const previousPaths = vacatedEntryFiles.map(({ path }) => path);\n\n  // Files deleted outright, as opposed to renamed. With the multi-file i18n structure, turning off\n  // a locale deletes that locale’s file only.\n  const deletedPaths = new Set(\n    pullRequest.files.filter(({ deleted }) => deleted).map(({ path }) => path),\n  );\n\n  // An image attached to an unpublished entry is committed to the workflow branch only, so it’s\n  // missing from the asset list built from the configured branch. Parse it here so the entry\n  // editor and the entry list can show it. The blob itself is fetched by its SHA, which works\n  // regardless of the branch it lives on.\n  const assets = assetFiles.map((file) => ({\n    ...parseAssetFileInfo(file),\n    workflow: { branch: pullRequest.branch },\n  }));\n\n  // Only keep the files that belong to the collection indicated by the branch name, so that a file\n  // committed along with the entry doesn’t create a bogus entry. A binary file has no text, so it\n  // can’t be parsed as an entry either.\n  let targetFiles = entryFiles.filter(\n    ({ folder, text }) => folder.collectionName === collectionName && text !== undefined,\n  );\n\n  const parsedEntries = targetFiles.length ? (await prepareEntries(targetFiles)).entries : [];\n\n  // An entry of another collection sharing the folder, which the collection’s filter excludes, is\n  // handed over to that collection, so it’s parsed as an entry committed along with the entry. The\n  // entry the branch is named after stays, even if an edit took it out of the filter, and so do the\n  // entries if none would be left, so the pull request doesn’t vanish from the board\n  const handOverCandidates = parsedEntries.flatMap((entry) => {\n    const folder = entry.slug !== parsed.slug && findOtherCollectionFolder(entry, collectionName);\n\n    return folder ? [{ entry, folder }] : [];\n  });\n\n  const handedOver = handOverCandidates.length < parsedEntries.length ? handOverCandidates : [];\n  const handedOverEntries = new Set(handedOver.map(({ entry }) => entry));\n\n  if (handedOver.length) {\n    /** @type {Map<string, EntryFolderInfo>} */\n    const handedOverFolders = new Map(\n      handedOver.flatMap(({ entry, folder }) => getEntryPaths(entry).map((path) => [path, folder])),\n    );\n\n    entryFiles = entryFiles.map((file) => {\n      const folder = handedOverFolders.get(file.path);\n\n      return folder ? { ...file, folder } : file;\n    });\n\n    targetFiles = targetFiles.filter(({ path }) => !handedOverFolders.has(path));\n  }\n\n  // Other entries of the collection the CMS rewrote along with the entry are left out\n  const ownEntries = targetFiles.length\n    ? findOwnEntries({\n        entries: parsedEntries.filter((entry) => !handedOverEntries.has(entry)),\n        slug: parsed.slug,\n        pullRequest,\n        previousPaths,\n      })\n    : [];\n\n  // A pull request that only removes entry files has nothing to parse, so reuse the published entry\n  // it touches. When it deletes all the entry’s files, it’s an Unpublish, and the published content\n  // is what the list and the editor display while the removal awaits publication. Otherwise it only\n  // deletes the files of locales turned off for the entry: it’s an edit without those locales. The\n  // other files of the collection it may carry are those of the entries a removal rewrites.\n  if (!ownEntries.length) {\n    const removedPaths = new Set(previousPaths);\n\n    const removedEntries = previousPaths.length\n      ? allEntries.current.filter((entry) =>\n          Object.values(entry.locales).some(({ path }) => removedPaths.has(path)),\n        )\n      : [];\n\n    return {\n      entries: removedEntries.map((entry) => {\n        const remainingLocales = Object.entries(entry.locales).filter(\n          ([, { path }]) => !deletedPaths.has(path),\n        );\n\n        if (remainingLocales.length) {\n          return {\n            ...entry,\n            locales: Object.fromEntries(remainingLocales),\n            workflow: createUnpublishedEntryProps({\n              pullRequest,\n              collectionName,\n              fileName: vacatedEntryFiles[0].folder.fileName,\n              previousPaths,\n            }),\n          };\n        }\n\n        return {\n          ...entry,\n          workflow: {\n            pullRequest,\n            // A removal opened before the dedicated status existed carries `pending_publish`, so\n            // the status is taken from the contents rather than the label\n            status: /** @type {WorkflowStatus} */ ('pending_deletion'),\n            collectionName,\n            fileName: undefined,\n            previousPaths,\n          },\n        };\n      }),\n      assets,\n    };\n  }\n\n  const ownPaths = new Set(ownEntries.flatMap((entry) => getEntryPaths(entry)));\n  const ownFile = targetFiles.find(({ path }) => ownPaths.has(path)) ?? targetFiles[0];\n  const { fileName } = ownFile.folder;\n  const companions = await parseCompanions(entryFiles, collectionName, deletedPaths);\n\n  return {\n    entries: ownEntries.map((entry) => ({\n      ...completeEntry({ entry, previousPaths, deletedPaths, collectionName, fileName }),\n      workflow: createUnpublishedEntryProps({\n        pullRequest,\n        collectionName,\n        fileName,\n        previousPaths,\n        companions,\n      }),\n    })),\n    assets,\n  };\n};\n\n/**\n * Convert the files in the given pull request to entries and assets in the canonical format, so\n * they can be displayed and edited with the regular entry list and editor components.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<PullRequestContents>} Entries and assets. There’s usually a single entry, but a\n * pull request can technically contain multiple entries.\n */\nexport const convertPullRequest = async (pullRequest) => {\n  const contents = await parsePullRequestContents(pullRequest);\n\n  if (!pullRequest.fork) {\n    return contents;\n  }\n\n  // A removal reuses the published entry, ID included, which is fine as long as one pull request\n  // at most stands for an entry. A contributor’s pull request can stand for the same entry as the\n  // maintainers’ own, or as another contributor’s, so its entries get IDs of their own\n  return {\n    ...contents,\n    entries: contents.entries.map((entry) => ({ ...entry, id: generateUUID() })),\n  };\n};\n\n/**\n * Convert all the given pull requests to entries and assets.\n * @param {WorkflowPullRequest[]} pullRequests Pull requests.\n * @returns {Promise<PullRequestContents>} Entries and assets.\n */\nexport const convertPullRequests = async (pullRequests) => {\n  const results = await Promise.all(pullRequests.map(convertPullRequest));\n\n  return {\n    entries: results.flatMap(({ entries }) => entries),\n    assets: results.flatMap(({ assets }) => assets),\n  };\n};\n","import equal from 'fast-deep-equal';\n\nimport { backend } from '$lib/services/backends';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { createStaleCheck, repositoryHead } from '$lib/services/backends/git/shared/head';\nimport { checkForRemoteChanges } from '$lib/services/backends/refresh';\nimport { cmsConfig } from '$lib/services/config';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport {\n  allUnpublishedEntries,\n  publishingBranches,\n  unpublishedEntriesLoaded,\n  unpublishedEntriesLoading,\n  workflowEnabled,\n} from '$lib/services/workflow';\nimport { mergeWorkflowAssets, removeWorkflowAssets } from '$lib/services/workflow/assets';\nimport { convertPullRequests } from '$lib/services/workflow/entries';\nimport { openAuthoringInitialized } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * BackendService,\n * CompanionEntry,\n * UnpublishedEntry,\n * WorkflowPullRequest,\n * } from '$lib/types/private';\n */\n\n/**\n * How long the unpublished entries are taken to be fresh, in milliseconds, unless the configured\n * branch has moved in the meantime. Listing the pull requests costs a couple of requests rather\n * than the one small request a branch check does, so they’re not listed on every check: a merge\n * made on the Git service moves the branch, which prompts a reload on the next check anyway, and\n * this interval catches the rest — a pull request opened, closed or relabelled by someone else.\n */\nexport const WORKFLOW_CHECK_INTERVAL = 5 * 60 * 1000;\n\n/**\n * Shortest gap between two reloads prompted by the user coming back to the tab, in milliseconds.\n * The user may well have been on the Git service, reviewing or merging, so the board is brought up\n * to date then rather than on the next scheduled check, but switching tabs back and forth shouldn’t\n * send a burst of requests.\n */\nexport const WORKFLOW_RETURN_GAP = 30 * 1000;\n\n/**\n * When the unpublished entries were last loaded, as a Unix timestamp in milliseconds, and the head\n * of the configured branch at the time.\n */\nlet lastLoad = { time: 0, head: '' };\n/**\n * The reload in flight, if any. A second caller gets the same promise rather than a second round of\n * requests.\n * @type {Promise<boolean> | undefined}\n */\nlet pendingReload;\n\n/**\n * Remember that the unpublished entries have just been loaded.\n * @param {string} head Head of the configured branch the load started at.\n */\nconst recordLoad = (head) => {\n  lastLoad = { time: Date.now(), head };\n};\n\n/**\n * Forget when the unpublished entries were loaded, and any reload in flight. Used in tests.\n */\nexport const _resetWorkflowLoadState = () => {\n  lastLoad = { time: 0, head: '' };\n  pendingReload = undefined;\n};\n\n/**\n * Check whether the pull requests can be listed yet. With Open Authoring, whether they live in the\n * signed-in user’s fork or, for a maintainer, in the configured repository is only found out while\n * the files are being fetched; listing them before that would look in the wrong repository.\n * @returns {boolean} Result.\n */\nconst isWorkflowReady = () => {\n  const { backend: backendConfig } = cmsConfig.current ?? {};\n\n  const openAuthoringConfigured =\n    !!backendConfig && 'open_authoring' in backendConfig && !!backendConfig.open_authoring;\n\n  return !openAuthoringConfigured || openAuthoringInitialized.current;\n};\n\n/**\n * Get the backend’s workflow service, if Editorial Workflow is enabled and the pull requests can be\n * listed yet.\n * @returns {NonNullable<BackendService['workflow']> | undefined} Workflow service, or `undefined`\n * if it’s not in use or not ready.\n */\nconst getReadyWorkflow = () => {\n  const workflow = backend.current?.workflow;\n\n  return workflowEnabled.current && workflow && isWorkflowReady() ? workflow : undefined;\n};\n\n/**\n * Start retrieving the backend’s open pull requests, if Editorial Workflow is enabled. Listing them\n * doesn’t depend on the published entries, so this is called before the files are fetched and the\n * request overlaps that work; {@link loadUnpublishedEntries} then picks the result up once the\n * entries are there to match the pull requests against.\n * @returns {Promise<WorkflowPullRequest[]> | undefined} Pull requests, or `undefined` if the\n * feature is not in use or the listing can’t start yet, in which case\n * {@link loadUnpublishedEntries} requests them itself once the files are fetched. A rejection is\n * left for {@link loadUnpublishedEntries} to handle.\n */\nexport const startLoadingPullRequests = () => {\n  const workflow = getReadyWorkflow();\n\n  if (!workflow) {\n    return undefined;\n  }\n\n  unpublishedEntriesLoading.current = true;\n\n  const promise = workflow.fetchPullRequests();\n\n  promise.catch(() => {\n    // Handled in `loadUnpublishedEntries()`\n  });\n\n  return promise;\n};\n\n/**\n * Retrieve the unpublished entries from the backend’s open pull requests and update the\n * {@link allUnpublishedEntries} store. Any error is logged and swallowed, because a failure here\n * should not prevent the user from working with published content.\n * @param {Promise<WorkflowPullRequest[]> | undefined} [pullRequests] Pull requests being\n * retrieved, from {@link startLoadingPullRequests}. Requested here if omitted.\n * @returns {Promise<void>}\n */\nexport const loadUnpublishedEntries = async (pullRequests = startLoadingPullRequests()) => {\n  if (!pullRequests) {\n    return;\n  }\n\n  const head = repositoryHead.current;\n  // The site data may be discarded while the requests are on their way, e.g. by signing out; the\n  // results then belong to the previous session and must not be written back, nor mark the next\n  // session’s entries as loaded\n  const isStale = createStaleCheck();\n\n  try {\n    const { entries, assets } = await convertPullRequests(await pullRequests);\n\n    if (!isStale()) {\n      allUnpublishedEntries.current = entries;\n      mergeWorkflowAssets(assets);\n      recordLoad(head);\n    }\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  } finally {\n    if (!isStale()) {\n      unpublishedEntriesLoading.current = false;\n      // Mark as loaded even on failure, so a deep link isn’t stuck on the loading state forever\n      unpublishedEntriesLoaded.current = true;\n    }\n  }\n};\n\n/**\n * Group the given unpublished entries by workflow branch. A branch usually holds a single entry,\n * but a pull request can technically contain more.\n * @param {UnpublishedEntry[]} entries Unpublished entries.\n * @returns {Map<string, UnpublishedEntry[]>} Entries keyed by branch, in the order given.\n */\nconst groupByBranch = (entries) =>\n  Map.groupBy(entries, ({ workflow }) => workflow.pullRequest.branch);\n\n/**\n * Check whether two lists hold the same entry objects in the same order.\n * @param {UnpublishedEntry[] | undefined} a List.\n * @param {UnpublishedEntry[] | undefined} b Another list.\n * @returns {boolean} Result. Two missing lists are the same.\n */\nconst isSameList = (a = [], b = []) =>\n  a.length === b.length && a.every((entry, index) => entry === b[index]);\n\n/**\n * Give the new entries read afresh from a pull request the IDs of the ones already in the store,\n * matched by any of their files, as they’re parsed with new IDs each time. Without that, the entry\n * they ride along with would never be the same as before. The first file isn’t enough: the locales\n * of an entry saved in this session are in the configured order, while those of an entry read from\n * the pull request are in the order its files are listed in.\n * @param {CompanionEntry[] | undefined} fetched Entries read from the pull request.\n * @param {CompanionEntry[] | undefined} existing Entries in the store.\n * @returns {CompanionEntry[] | undefined} Entries.\n */\nconst carryOverCompanions = (fetched, existing = []) => {\n  const ids = new Map(\n    existing.flatMap(({ entry }) => getEntryPaths(entry).map((path) => [path, entry.id])),\n  );\n\n  return fetched?.map((companion) => {\n    const id = getEntryPaths(companion.entry)\n      .map((path) => ids.get(path))\n      .find(Boolean);\n\n    return id ? { ...companion, entry: { ...companion.entry, id } } : companion;\n  });\n};\n\n/**\n * Bring the entries read afresh from a pull request in line with the ones already in the store, so\n * the board and the editor don’t lose track of them: each keeps the ID of the entry it replaces,\n * along with those of the new entries riding along with it, and an entry that hasn’t changed at all\n * stays the same object.\n * @param {UnpublishedEntry[]} fetched Entries read from the pull request.\n * @param {UnpublishedEntry[]} existing Entries of the same branch in the store.\n * @returns {UnpublishedEntry[]} Entries to store.\n */\nconst carryOverEntries = (fetched, existing) => {\n  const entries = fetched.map((entry, index) => {\n    const previous = existing[index];\n\n    if (!previous) {\n      return entry;\n    }\n\n    const { workflow } = entry;\n\n    const carried = {\n      ...entry,\n      id: previous.id,\n      ...(workflow.companions\n        ? {\n            workflow: {\n              ...workflow,\n              companions: carryOverCompanions(workflow.companions, previous.workflow.companions),\n            },\n          }\n        : {}),\n    };\n\n    return equal(carried, previous) ? previous : carried;\n  });\n\n  return isSameList(entries, existing) ? existing : entries;\n};\n\n/**\n * Get the head commit the given entries of a branch were read at.\n * @param {UnpublishedEntry[]} [entries] Entries of the branch.\n * @returns {string | undefined} Git object ID, if any.\n */\nconst getHeadSHA = (entries) => entries?.[0]?.workflow.pullRequest.headSHA;\n\n/**\n * Find the branches whose entries in the store are more recent than what the listing reports. A Git\n * service can report a pull request as of an earlier commit for a moment after a push: Gitea and\n * Forgejo work out the changed files from a reference they move to the branch head in the\n * background, and the head GitHub reports for a pull request may trail its branch as well. Taking\n * that snapshot would roll back the entry just saved in this tab, and the next save, made on top of\n * the older head, would be refused as a conflict. So where the heads differ, the branch is read,\n * which is a small request: if it still points at the head in the store, nothing has been committed\n * since, and the listing is the one behind. Anything else it reports for the pull request, such as\n * a label changed on the Git service, comes in with the next reload. A snapshot that yields no\n * entry at all, with none of the files listed yet, is behind just the same. A branch that can’t be\n * read leaves the listing to be taken as it is.\n * @param {NonNullable<BackendService['workflow']>} workflow Workflow service.\n * @param {Map<string, UnpublishedEntry[]>} stored Entries in the store, keyed by branch.\n * @param {Map<string, UnpublishedEntry[]>} fetched Entries read from the pull requests, keyed by\n * branch.\n * @param {Set<string>} openBranches Branches of the pull requests listed.\n * @returns {Promise<Set<string>>} Branches whose entries in the store are to be kept.\n */\nconst findUpToDateBranches = async (workflow, stored, fetched, openBranches) => {\n  /** @type {Set<string>} */\n  const branches = new Set();\n\n  const candidates = [...stored.keys()].filter((branch) => {\n    const head = getHeadSHA(stored.get(branch));\n\n    return openBranches.has(branch) && !!head && head !== getHeadSHA(fetched.get(branch));\n  });\n\n  await runConcurrently(candidates, async (branch) => {\n    try {\n      if ((await workflow.fetchBranchHead(branch)) === getHeadSHA(stored.get(branch))) {\n        branches.add(branch);\n      }\n    } catch (ex) {\n      // eslint-disable-next-line no-console\n      console.error('Failed to check the workflow branch for changes.', ex);\n    }\n  });\n\n  return branches;\n};\n\n/**\n * Read the open pull requests again and bring the {@link allUnpublishedEntries} store up to date\n * with them. See {@link reloadUnpublishedEntries}.\n * @param {NonNullable<BackendService['workflow']>} workflow Workflow service.\n * @returns {Promise<boolean>} Whether anything has changed.\n */\nconst reload = async (workflow) => {\n  // The site data may be discarded while the requests are on their way, e.g. by signing out; the\n  // results then belong to the previous session and must not be written back\n  const isStale = createStaleCheck();\n  const head = repositoryHead.current;\n  // The store as it stands before the request, to tell the changes made in this tab in the meantime\n  // — a save, a status change, a publish — from the ones the request reports\n  const before = groupByBranch(allUnpublishedEntries.current);\n  const pullRequests = await workflow.fetchPullRequests();\n\n  if (isStale()) {\n    return false;\n  }\n\n  const openBranches = new Set(pullRequests.map(({ branch }) => branch));\n\n  // A pull request that has gone has most likely been merged on the Git service. The published\n  // entry is brought in first, so the entry doesn’t drop out of the entry list until the next\n  // check for remote changes. A pull request closed without merging moves nothing, so it costs one\n  // small request\n  if ([...before.keys()].some((branch) => !openBranches.has(branch))) {\n    try {\n      await checkForRemoteChanges();\n    } catch (ex) {\n      // eslint-disable-next-line no-console\n      console.error('Failed to check the repository for changes.', ex);\n    }\n\n    if (isStale()) {\n      return false;\n    }\n  }\n\n  const { entries, assets } = await convertPullRequests(pullRequests);\n\n  if (isStale()) {\n    return false;\n  }\n\n  const fetched = groupByBranch(entries);\n  const upToDate = await findUpToDateBranches(workflow, before, fetched, openBranches);\n\n  if (isStale()) {\n    return false;\n  }\n\n  const current = groupByBranch(allUnpublishedEntries.current);\n  const publishing = new Set(publishingBranches.current);\n  /** @type {Set<string>} */\n  const changedBranches = new Set();\n\n  /**\n   * Get the entries to store for the given branch.\n   * @param {string} branch Workflow branch.\n   * @returns {UnpublishedEntry[]} Entries; empty if the pull request has gone.\n   */\n  const resolve = (branch) => {\n    const existing = current.get(branch) ?? [];\n\n    // A change made in this tab while the request was on its way is more recent than what the\n    // request reports, and so is an entry being published, which leaves the store once merged, and\n    // one whose branch hasn’t moved since it was stored\n    if (\n      publishing.has(branch) ||\n      upToDate.has(branch) ||\n      !isSameList(existing, before.get(branch))\n    ) {\n      return existing;\n    }\n\n    const resolved = carryOverEntries(fetched.get(branch) ?? [], existing);\n\n    if (resolved !== existing) {\n      changedBranches.add(branch);\n    }\n\n    return resolved;\n  };\n\n  // The entries already listed keep their places, so a card doesn’t jump around on the board, and\n  // the new ones come after them in the order the backend lists them\n  const branches = new Set([...current.keys(), ...fetched.keys()]);\n  const resolved = [...branches].flatMap(resolve);\n\n  recordLoad(head);\n\n  if (!changedBranches.size) {\n    return false;\n  }\n\n  allUnpublishedEntries.current = resolved;\n\n  // The assets committed to a branch that has changed or gone are replaced with the ones it holds\n  // now, if any, restoring the published versions they were shadowing\n  changedBranches.forEach(removeWorkflowAssets);\n  mergeWorkflowAssets(\n    assets.filter(({ workflow: assetWorkflow }) =>\n      changedBranches.has(/** @type {string} */ (assetWorkflow?.branch)),\n    ),\n  );\n\n  return true;\n};\n\n/**\n * Read the backend’s open pull requests again and bring the {@link allUnpublishedEntries} store up\n * to date with them, so the Editorial Workflow board and the entry lists notice the pull requests\n * opened, updated, merged or closed by anyone else — a colleague, a bot, the Git service itself —\n * since they were loaded. Unlike {@link loadUnpublishedEntries}, the result is merged into the\n * store rather than replacing it: an unchanged entry stays the same object, a changed one keeps its\n * ID, and anything changed in this tab while the request was on its way is left as it is.\n *\n * Nothing is reloaded before the entries have been loaded once, or when Editorial Workflow isn’t\n * in use.\n * @param {object} [options] Options.\n * @param {boolean} [options.fresh] Make sure the pull requests are listed after the call, rather\n * than joining a reload already in flight, which may have listed them before a change the caller\n * knows about.\n * @returns {Promise<boolean>} Whether anything has changed.\n * @throws {Error} When the backend couldn’t be reached.\n */\nexport const reloadUnpublishedEntries = async ({ fresh = false } = {}) => {\n  const workflow = getReadyWorkflow();\n\n  if (!workflow || !unpublishedEntriesLoaded.current) {\n    return false;\n  }\n\n  if (fresh && pendingReload) {\n    // Waiting is what matters; the result, or a failure, is the other caller’s\n    await pendingReload.catch(() => undefined);\n  }\n\n  if (!pendingReload) {\n    pendingReload = reload(workflow).finally(() => {\n      pendingReload = undefined;\n    });\n  }\n\n  return pendingReload;\n};\n\n/**\n * Reload the unpublished entries if they may be out of date: the configured branch has moved since\n * they were loaded, which is what a pull request merged on the Git service does, or they were\n * loaded longer ago than the given time.\n * @param {object} [options] Options.\n * @param {number} [options.maxAge] Reload if the entries were loaded more than this many\n * milliseconds ago.\n * @returns {Promise<boolean>} Whether anything has changed.\n * @throws {Error} When the backend couldn’t be reached.\n */\nexport const checkForWorkflowChanges = async ({ maxAge = WORKFLOW_CHECK_INTERVAL } = {}) => {\n  if (\n    !pendingReload &&\n    repositoryHead.current === lastLoad.head &&\n    Date.now() - lastLoad.time < maxAge\n  ) {\n    return false;\n  }\n\n  return reloadUnpublishedEntries();\n};\n","import { checkForRemoteChanges, MIN_CHECK_GAP } from '$lib/services/backends/refresh';\nimport {\n  checkForWorkflowChanges,\n  WORKFLOW_CHECK_INTERVAL,\n  WORKFLOW_RETURN_GAP,\n} from '$lib/services/workflow/load';\n\n/**\n * How often to ask the backend whether the configured branch has moved, in milliseconds. One small\n * request per check keeps the cost negligible against any service’s rate limit, while a minute is\n * soon enough to notice a colleague’s change before much is built on stale data.\n */\nexport const REMOTE_CHECK_INTERVAL = 60 * 1000;\n\n/** Handle of the scheduled check, or `0` while nothing is scheduled. */\nlet timer = 0;\n/** When the polling was started, as a Unix timestamp in milliseconds. */\nlet startTime = 0;\n/**\n * Whether the tab is showing. Nobody is looking at a hidden tab, so a change found there would only\n * be a wasted request, and the tab is checked as soon as it’s shown again.\n * @returns {boolean} Result.\n */\nconst isVisible = () => document.visibilityState === 'visible';\n\n/**\n * Check the repository, then the unpublished entries, reporting a failure rather than letting it\n * escape the timer. The branch goes first: a pull request merged on the Git service moves it, which\n * prompts the unpublished entries to be reloaded straight away, with the published version in.\n * @param {object} [options] Options.\n * @param {number} [options.maxAge] Skip the branch check if one was started within this many\n * milliseconds.\n * @param {number} [options.workflowMaxAge] Skip reloading the unpublished entries if they were\n * loaded within this many milliseconds and the branch hasn’t moved since.\n */\nconst check = async ({ maxAge = 0, workflowMaxAge = WORKFLOW_CHECK_INTERVAL } = {}) => {\n  try {\n    await checkForRemoteChanges({ maxAge });\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to check the repository for changes.', ex);\n  }\n\n  try {\n    await checkForWorkflowChanges({ maxAge: workflowMaxAge });\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to check the unpublished entries for changes.', ex);\n  }\n};\n\n/**\n * Check the repository on schedule, unless the tab is hidden.\n */\nconst checkOnSchedule = () => {\n  if (isVisible()) {\n    check();\n  }\n};\n\n/**\n * Check the repository as the user comes back to the tab, unless a check was made only moments ago,\n * or the polling has only just started — the data was fresh then. The last check may have been\n * made by a save or an entry being opened rather than by this loop, which counts just as well.\n */\nconst checkOnReturn = () => {\n  if (isVisible() && Date.now() - startTime >= MIN_CHECK_GAP) {\n    check({ maxAge: MIN_CHECK_GAP, workflowMaxAge: WORKFLOW_RETURN_GAP });\n  }\n};\n\n/**\n * Start checking the repository for someone else’s commits, and the pull requests behind the\n * unpublished entries for anyone else’s changes, on schedule and whenever the user comes back to\n * the tab. Called once the site data has been loaded, which is when the data is\n * fresh, so the first check is a full interval away. Starting again is a no-op.\n */\nexport const startRemoteChangePolling = () => {\n  if (timer) {\n    return;\n  }\n\n  startTime = Date.now();\n  timer = window.setInterval(checkOnSchedule, REMOTE_CHECK_INTERVAL);\n  document.addEventListener('visibilitychange', checkOnReturn);\n  window.addEventListener('focus', checkOnReturn);\n};\n\n/**\n * Stop the checks. Called when the user signs out.\n */\nexport const stopRemoteChangePolling = () => {\n  if (!timer) {\n    return;\n  }\n\n  window.clearInterval(timer);\n  document.removeEventListener('visibilitychange', checkOnReturn);\n  window.removeEventListener('focus', checkOnReturn);\n  timer = 0;\n};\n","/**\n * @import { DeployState } from '$lib/types/private';\n */\n\n/**\n * How long to wait between re-checks while a build is pending, in milliseconds. The interval is\n * fixed rather than widening: a build finishing is what the editor is waiting on, so noticing it\n * late is worse than the cost of asking, and one request per check keeps that cost small.\n */\nexport const POLL_INTERVAL = 5000;\n\n/**\n * How long to keep re-checking a pending build before giving up, in milliseconds. Once it elapses,\n * the UI offers a manual re-check instead, so a stuck or very long build doesn’t poll forever.\n */\nexport const POLL_MAX_DURATION = 10 * 60 * 1000;\n\n/**\n * How long to keep waiting for a commit that has nothing reported against it, in milliseconds. A\n * provider can take a moment to post its first status after a push — a CI job often sits in a queue\n * for a while before it starts — so the loop doesn’t conclude from the first empty answers that\n * there’s no build to wait for. It’s a duration rather than a number of checks, because a queue\n * wait is measured in time, not in requests.\n */\nexport const UNKNOWN_GRACE_DURATION = 60 * 1000;\n\n/**\n * How long a resolved deployment stays fresh, in milliseconds. Reopening a view within this window\n * reuses the cached result instead of querying the backend again.\n */\nexport const DEPLOY_TTL = 30000;\n\n/** How long a page liveness result is cached per URL, in milliseconds. */\nexport const PING_TTL = 30000;\n\n/**\n * Map of deploy states to the i18n string keys of the sentences describing them, for the states an\n * editor needs explained. A finished build needs no words, and an unknown state has nothing to say.\n * @type {Partial<Record<DeployState, string>>}\n */\nexport const DEPLOY_STATE_MESSAGES = {\n  checking: 'deploy_preview.checking',\n  pending: 'deploy_preview.building',\n  error: 'deploy_preview.build_failed',\n};\n","import { PING_TTL } from '$lib/services/deployments/constants';\nimport { sendRequest } from '$lib/services/utils/networking';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { PageLiveness } from '$lib/types/private';\n */\n\n/**\n * Liveness of preview pages, keyed by the full URL.\n * @type {{ current: Record<string, PageLiveness> }}\n */\nexport const pageLiveness = createRawState({});\n\n/**\n * How many pages to remember. A result is only useful for {@link PING_TTL}, so the cap is about\n * keeping a long editing session from accumulating an entry for every page ever opened, not about\n * holding a useful working set.\n */\nconst MAX_CACHED_PAGES = 100;\n/**\n * Recent and in-flight checks, keyed by URL, so a re-render or a second view asking about the same\n * page doesn’t send another request.\n * @type {Map<string, { time: number, promise: Promise<PageLiveness> }>}\n */\nconst cache = new Map();\n\n/**\n * Drop the pages least worth remembering once the cache outgrows its cap: the results that have\n * expired first, then the oldest of what’s left. The state is trimmed in step, so the two can’t\n * drift apart.\n */\nconst prune = () => {\n  if (cache.size <= MAX_CACHED_PAGES) {\n    return;\n  }\n\n  const cutoff = Date.now() - PING_TTL;\n\n  const dropped = new Set(\n    [...cache.entries()].filter(([, { time }]) => time < cutoff).map(([url]) => url),\n  );\n\n  // A Map iterates in insertion order, so this takes the longest-standing entries first\n  [...cache.keys()].forEach((url) => {\n    if (cache.size - dropped.size > MAX_CACHED_PAGES) {\n      dropped.add(url);\n    }\n  });\n\n  dropped.forEach((url) => cache.delete(url));\n\n  pageLiveness.current = Object.fromEntries(\n    Object.entries(pageLiveness.current).filter(([url]) => !dropped.has(url)),\n  );\n};\n\n/**\n * Check whether the given page is live.\n * @param {string} url URL to check.\n * @returns {Promise<PageLiveness>} Result.\n */\nconst request = async (url) => {\n  /** @type {Response} */\n  let response;\n\n  try {\n    response = /** @type {Response} */ (\n      await sendRequest(url, { method: 'GET' }, { responseType: 'raw' })\n    );\n  } catch {\n    return 'unknown';\n  }\n\n  if (response.ok) {\n    return 'ready';\n  }\n\n  // A page that hasn’t been built yet is a 404. Any other status, including the 401 that a\n  // password-protected preview returns, says nothing about the build, and the link still works for\n  // a signed-in user, so don’t report it as missing\n  return response.status === 404 ? 'pending' : 'unknown';\n};\n\n/**\n * Check whether the page at the given URL is live yet, and record the result in\n * {@link pageLiveness}.\n *\n * Only a same-origin URL is requested. A cross-origin response can’t be read without an\n * `Access-Control-Allow-Origin` header, which no major static host sets on HTML documents, and an\n * opaque `no-cors` response reports the same thing for a 200 and a 404 alike. Sending the request\n * anyway would cost a round trip and a console error to learn nothing, so it’s skipped. In practice\n * this covers the common setup where the CMS is served from the site it edits.\n * @param {string} url URL to check.\n * @param {object} [options] Options.\n * @param {boolean} [options.recheckPending] Whether to check again a page found missing, however\n * recently. Used once the build is reported finished: a page checked while it was building would\n * otherwise be reported missing until the cached result expires, with nothing to check it again.\n * @returns {Promise<PageLiveness>} Result.\n */\nexport const pingURL = async (url, { recheckPending = false } = {}) => {\n  const cached = cache.get(url);\n  const recheck = recheckPending && pageLiveness.current[url] === 'pending';\n\n  if (cached && !recheck && Date.now() - cached.time < PING_TTL) {\n    return cached.promise;\n  }\n\n  let sameOrigin = false;\n\n  try {\n    sameOrigin = new URL(url).origin === window.location.origin;\n  } catch {\n    sameOrigin = false;\n  }\n\n  const promise = sameOrigin\n    ? request(url)\n    : Promise.resolve(/** @type {PageLiveness} */ ('unknown'));\n\n  // Delete the entry first, as setting an existing key keeps its place in the insertion order,\n  // which {@link prune} goes by, and the page just checked could otherwise be the first to go\n  cache.delete(url);\n  cache.set(url, { time: Date.now(), promise });\n  prune();\n\n  const result = await promise;\n\n  // Skip an update that changes nothing, so a component checking the URL from an effect that reads\n  // the state doesn’t loop\n  pageLiveness.current =\n    pageLiveness.current[url] === result\n      ? pageLiveness.current\n      : { ...pageLiveness.current, [url]: result };\n\n  return result;\n};\n\n/**\n * Clear the cached liveness results. Called when the user signs out, so a different site’s pages\n * aren’t reported from the previous session.\n */\nexport const resetPageLiveness = () => {\n  cache.clear();\n  pageLiveness.current = {};\n};\n","import { backend } from '$lib/services/backends';\nimport { skipCIConfigured } from '$lib/services/backends/git/shared/integration';\nimport { cmsConfig } from '$lib/services/config';\nimport { deployments, productionSHA } from '$lib/services/deployments';\nimport { DEPLOY_TTL } from '$lib/services/deployments/constants';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\nimport { allUnpublishedEntries } from '$lib/services/workflow';\n\n/**\n * @import { BackendService, DeployStatus, DeployTarget } from '$lib/types/private';\n */\n\n/**\n * Report what the lookup is doing while dev mode is on. The requests it makes are ordinary API\n * calls, indistinguishable from the rest in the network panel, so a preview that never appears is\n * otherwise hard to trace.\n * @param {string} message What happened.\n * @param {any | (() => any)} [detail] Supporting detail, or a function returning it when working\n * that out costs more than reading a variable. Nothing is evaluated while dev mode is off.\n */\nconst report = (message, detail) => {\n  if (!prefs.devModeEnabled) {\n    return;\n  }\n\n  // eslint-disable-next-line no-console\n  console.info(\n    `deployPreview: ${message}`,\n    (typeof detail === 'function' ? detail() : detail) ?? '',\n  );\n};\n\n/**\n * Incremented whenever an in-flight resolution should be discarded, which happens when polling\n * stops. The shared request helper takes no abort signal, so the response is dropped on arrival\n * instead of the request being cancelled.\n */\nlet currentToken = 0;\n/**\n * Incremented as each resolution starts. Two can be in flight at once — a scheduled check and the\n * manual re-check, say — and the one that started later is the more authoritative, so an older\n * response is dropped rather than allowed to land on top of it.\n */\nlet runCount = 0;\n\n/**\n * Discard whatever resolution is in flight, so its result doesn’t land in the store after the view\n * that asked for it is gone.\n */\nexport const cancelDeployResolution = () => {\n  currentToken += 1;\n};\n\n/**\n * Collect the commits worth looking up: the head of the configured branch, which the production\n * site is built from, and the head of every open Editorial Workflow pull request.\n * @returns {DeployTarget[]} Targets, without duplicates.\n */\nexport const getDeployTargets = () => {\n  const branch = backend.current?.repository?.branch ?? '';\n  /** @type {DeployTarget[]} */\n  const targets = [];\n  const seen = new Set();\n  const prodSHA = productionSHA.current;\n\n  if (prodSHA) {\n    targets.push({ sha: prodSHA, branch, kind: 'production' });\n    seen.add(prodSHA);\n  }\n\n  allUnpublishedEntries.current.forEach(({ workflow: { pullRequest } }) => {\n    const { number, headSHA, branch: prBranch } = pullRequest;\n\n    // An Open Authoring draft with no number is a branch in the contributor’s fork that nothing\n    // has been opened for, so there’s no pull request for the service to have built a preview of.\n    // Its head is on record all the same, so a save can tell whether the branch has moved. A draft\n    // whose pull request was closed keeps its number and is still asked about, which costs one\n    // lookup that finds nothing: the state isn’t on record to tell the two apart.\n    // A contributor’s pull request, once opened, is asked about like any other: a service set up to\n    // build pull requests from forks does build it, and the commit is reachable from the configured\n    // repository because a fork shares its parent’s object store\n    if (number === undefined || !headSHA || seen.has(headSHA)) {\n      return;\n    }\n\n    targets.push({ sha: headSHA, branch: prBranch, kind: 'preview' });\n    seen.add(headSHA);\n  });\n\n  return targets;\n};\n\n/**\n * The commits worth looking up, recomputed whenever the branch head moves or the open pull requests\n * change — which is what a save does. Anything watching the deploy state uses this rather than\n * calling {@link getDeployTargets} once, so a commit made during the session is picked up.\n * @type {{ readonly current: DeployTarget[] }}\n */\nexport const deployTargets = createDerivedState(() => getDeployTargets());\n\n/**\n * Whether it’s worth asking the backend about deployments at all. There’s nothing to look up when\n * the service can’t report one. Preview links being turned off isn’t enough on its own: with\n * `skip_ci` configured, the answer also tells the Publish Changes button whether the last commit\n * ever went out, which is worth a request even when no link is shown for it.\n * @returns {boolean} Result.\n */\nexport const canResolveDeployments = () => {\n  const { show_preview_links: showLinks = true } = cmsConfig.current ?? {};\n\n  return (showLinks || skipCIConfigured.current) && !!backend.current?.fetchDeployments;\n};\n\n/**\n * Whether the recorded deployment is recent enough to reuse.\n * @param {DeployStatus} [status] Recorded deployment.\n * @returns {boolean} Result.\n */\nconst isFresh = (status) =>\n  !!status && status.state !== 'checking' && Date.now() - status.checkedTime < DEPLOY_TTL;\n\n/**\n * Record that the given commits are about to be looked up. Only a commit with no result yet is\n * marked; re-checking a known one in the background shouldn’t flip the UI back to a loading state\n * on every poll.\n * @param {DeployTarget[]} targets Commits about to be looked up.\n */\nconst markChecking = (targets) => {\n  const map = deployments.current;\n\n  /** @type {Record<string, DeployStatus>} */\n  const additions = Object.fromEntries(\n    targets\n      .filter(({ sha }) => !map[sha])\n      .map(({ sha }) => [sha, /** @type {DeployStatus} */ ({ state: 'checking', checkedTime: 0 })]),\n  );\n\n  // Leave the state alone when there’s nothing to add, so readers aren’t woken for nothing — an\n  // effect that took its reading while polling started would otherwise re-run on every lookup\n  if (Object.keys(additions).length) {\n    deployments.current = { ...map, ...additions };\n  }\n};\n\n/**\n * Record that a lookup is about to happen for any commit nothing is known about yet. This runs\n * synchronously, so the control reports the wait from the moment a save moves the tracked commit\n * rather than showing a live site link until the first result lands.\n */\nexport const markLookupPending = () => {\n  markChecking(getDeployTargets());\n};\n\n/**\n * Ask the backend for the deployment status of every tracked commit and record the results. A\n * failure is reported as an unknown state rather than thrown, because a missing deploy preview\n * shouldn’t stop the user from editing.\n * @param {object} [options] Options.\n * @param {boolean} [options.force] Whether to re-query a commit whose deployment is still fresh.\n * @param {boolean} [options.pendingOnly] Whether to look only at commits whose build hasn’t\n * finished. Used by the re-check loop, which would otherwise keep asking about every commit on the\n * board just because one of them is still building, and which ignores the freshness window because\n * re-reading is the point.\n * @returns {Promise<void>}\n */\nexport const resolveDeployments = async ({ force = false, pendingOnly = false } = {}) => {\n  if (!canResolveDeployments()) {\n    report(\n      'not looking anything up: the backend can’t report deployments, or preview links are off',\n    );\n\n    return;\n  }\n\n  // Guaranteed by the check above\n  const fetchDeployments = /** @type {NonNullable<BackendService['fetchDeployments']>} */ (\n    backend.current?.fetchDeployments\n  );\n\n  const cached = deployments.current;\n\n  const targets = getDeployTargets().filter(({ sha }) => {\n    if (force) {\n      return true;\n    }\n\n    const state = cached[sha]?.state;\n\n    if (pendingOnly) {\n      // A finished build won’t change on its own; only a forced re-check looks at one again.\n      // Everything else is re-read however recently it was seen — noticing a change is the whole\n      // reason the loop is running, so treating a recent answer as good enough would throttle the\n      // checks to the freshness window and leave the interval doing nothing\n      return state !== 'ready' && state !== 'error';\n    }\n\n    return !isFresh(cached[sha]);\n  });\n\n  if (!targets.length) {\n    report('nothing to look up', () => ({ tracked: getDeployTargets(), known: cached }));\n\n    return;\n  }\n\n  report('looking up', targets);\n\n  const token = currentToken;\n\n  runCount += 1;\n\n  const run = runCount;\n\n  markChecking(targets);\n\n  /** @type {Record<string, DeployStatus>} */\n  let results;\n\n  try {\n    results = await fetchDeployments(targets);\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to fetch the deployment info.', ex);\n\n    results = Object.fromEntries(\n      targets.map(({ sha }) => [sha, { state: 'unknown', checkedTime: Date.now() }]),\n    );\n  }\n\n  if (token !== currentToken) {\n    report('discarding a result that arrived after the lookup was cancelled', results);\n\n    return;\n  }\n\n  if (run !== runCount) {\n    report('discarding a result that a later lookup has superseded', results);\n\n    return;\n  }\n\n  report('resolved', results);\n  deployments.current = { ...deployments.current, ...results };\n};\n\n/**\n * Resolve the head commit of the configured branch, which the production site is built from.\n * @returns {Promise<void>}\n */\nexport const refreshProductionSHA = async () => {\n  const fetchBranchHeadSHA = backend.current?.fetchBranchHeadSHA;\n\n  if (!fetchBranchHeadSHA) {\n    return;\n  }\n\n  try {\n    const sha = (await fetchBranchHeadSHA()) ?? '';\n\n    report('tracking the branch head', sha);\n    productionSHA.current = sha;\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to fetch the branch head commit.', ex);\n  }\n};\n\n/**\n * Look the production deployment target up and resolve whatever is known so far. Called once the\n * user is signed in and the content has been loaded.\n *\n * The caller doesn’t await this, so nothing may escape: an unexpected failure would otherwise\n * surface as an unhandled rejection rather than something anyone can act on. The deploy state is a\n * convenience, and losing it shouldn’t be louder than that.\n * @param {object} [options] Options.\n * @param {string} [options.head] Head commit of the configured branch, if it has just been\n * resolved along with the content, so it isn’t fetched again.\n * @returns {Promise<void>}\n */\nexport const initDeployments = async ({ head } = {}) => {\n  try {\n    if (head && backend.current?.fetchBranchHeadSHA) {\n      report('tracking the branch head', head);\n      productionSHA.current = head;\n    } else {\n      await refreshProductionSHA();\n    }\n\n    await resolveDeployments();\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to look up the deployment info.', ex);\n  }\n};\n","/**\n * Encode the data carried by a magic link, used to sign in with a mobile device, to a string that\n * can be put in the URL hash. The data is serialized to JSON, encoded as UTF-8, so that it can hold\n * any character, e.g. in a password or a deploy hook URL stored in the preferences, and then\n * encoded with the URL-safe Base64 alphabet. Unlike the standard alphabet, it has no `/`, which\n * the router would take for a path separator, and trim if it came last.\n * @param {any} data Data to encode.\n * @returns {string} Encoded data.\n */\nexport const encodeMagicLinkData = (data) =>\n  new TextEncoder()\n    .encode(JSON.stringify(data))\n    .toBase64({ alphabet: 'base64url', omitPadding: true });\n\n/**\n * Decode the data carried by a magic link, encoded with {@link encodeMagicLinkData}. Links made by\n * earlier versions of the app, which used `btoa()` and the standard Base64 alphabet, are also\n * accepted: their text was Latin-1, so a byte sequence that is not valid UTF-8 is read as Latin-1\n * like `atob()` does. ASCII text, which is all such a link usually holds, is the same either way;\n * only Latin-1 text that happens to be valid UTF-8 as well, such as `Ã©`, would read differently.\n * @param {string} encodedData Encoded data.\n * @returns {any} Decoded data.\n * @throws {Error} If the data is not valid Base64 or JSON.\n */\nexport const decodeMagicLinkData = (encodedData) => {\n  const bytes = Uint8Array.fromBase64(encodedData.replaceAll('+', '-').replaceAll('/', '_'), {\n    alphabet: 'base64url',\n  });\n\n  let text;\n\n  try {\n    text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n  } catch {\n    // Not `TextDecoder('latin1')`, which is actually windows-1252 and maps `0x80`–`0x9F` otherwise\n    text = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('');\n  }\n\n  return JSON.parse(text);\n};\n","import { deployments, deployPollTimedOut, productionSHA } from '$lib/services/deployments';\nimport { canResolveDeployments } from '$lib/services/deployments/resolve';\nimport {\n  createDerivedState,\n  createRawState,\n  createRootEffect,\n} from '$lib/services/utils/state.svelte';\n\n/**\n * @import { DeployingEntry, UnpublishedEntry } from '$lib/types/private';\n */\n\n/**\n * Entries whose pull request has been merged during this session, in merge order, as recorded by\n * {@link trackDeployingEntry} — whatever the site has done since.\n * @type {{ current: DeployingEntry[] }}\n */\nconst mergedEntries = createRawState([]);\n\n/**\n * Whether the site has caught up with the given commit on the configured branch. A finished build\n * counts, and so does a commit nothing reports on once the re-checks have given the provider time:\n * there’s nothing more to wait for either way. A failed build doesn’t count, because the change\n * isn’t on the site, and the board is where that shows until a later commit — the next save or\n * merge — is built.\n * @param {string} sha Commit SHA.\n * @returns {boolean} Result.\n */\nconst isBuildDone = (sha) => {\n  const state = sha ? deployments.current[sha]?.state : undefined;\n\n  return state === 'ready' || state === 'unknown';\n};\n\n/**\n * Whether the site has caught up with the head of the configured branch, which is the commit every\n * merge made so far has landed on.\n */\nexport const productionBuildDone = createDerivedState(() => isBuildDone(productionSHA.current));\n\n/**\n * Entries whose change is on its way to the site: their pull request has been merged, but the site\n * hasn’t been rebuilt and deployed from the merge yet, so a published entry isn’t live and a\n * deleted one is still up. They stay on the Editorial Workflow board with the build state until\n * the site has caught up, because a merged deletion has left the entry list, and the board is the\n * only place left to say so.\n *\n * Every merge lands on the same branch, so a build of any later commit carries the earlier changes\n * as well: an entry is on its way until the build of its own commit, of one recorded after it, or\n * of the current branch head is done. The re-check loop only follows the current head, so the\n * build of a commit that was superseded while still running is never seen to finish, and the\n * later ones are what conclude it.\n * @type {{ readonly current: DeployingEntry[] }}\n * @see https://github.com/sveltia/sveltia-cms/issues/992\n */\nexport const deployingEntries = createDerivedState(() => {\n  if (productionBuildDone.current) {\n    return [];\n  }\n\n  const entries = mergedEntries.current;\n  const lastDone = entries.findLastIndex(({ sha }) => isBuildDone(sha));\n\n  return lastDone === -1 ? entries : entries.slice(lastDone + 1);\n});\n\n/**\n * Record that the given entry’s pull request has been merged, so the board can show it until the\n * site has caught up. Nothing is recorded when the backend can’t report deployments, because the\n * wait would never be seen to end. The head of the configured branch has to be refreshed first, or\n * the entry would be judged against the build of the commit before the merge.\n * @param {UnpublishedEntry} entry Entry as it was published, with the workflow properties.\n */\nexport const trackDeployingEntry = (entry) => {\n  const sha = productionSHA.current;\n\n  if (!canResolveDeployments() || !sha) {\n    return;\n  }\n\n  const { workflow } = entry;\n  const { branch } = workflow.pullRequest;\n\n  mergedEntries.current = [\n    // Only the entries still on their way are kept, so the list doesn’t grow for the lifetime of\n    // the session. One published again replaces its earlier record\n    ...deployingEntries.current.filter((e) => e.entry.workflow.pullRequest.branch !== branch),\n    {\n      entry: {\n        ...entry,\n        workflow: {\n          ...workflow,\n          // The merge time is what the card shows\n          pullRequest: { ...workflow.pullRequest, updatedDate: new Date() },\n        },\n      },\n      sha,\n    },\n  ];\n};\n\n/**\n * Forget the merged entries. Called when the user signs out.\n */\nexport const resetDeployingEntries = () => {\n  mergedEntries.current = [];\n};\n\n// Once the re-checks have given up on a build, nothing more will be learned about it on its own,\n// so the entries waiting for it are let go rather than left saying the site is on its way. This\n// has to stick: the flag is cleared again as soon as the re-checks restart, which any save or\n// merge does by moving a tracked commit, and a list that merely hid its entries while the flag was\n// set would bring them all back then\ncreateRootEffect(() => {\n  if (deployPollTimedOut.current) {\n    resetDeployingEntries();\n  }\n});\n","import { _ } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\nimport { LocalStorage } from '@sveltia/utils/storage';\n\nimport { isAdditionsEnabled, loadAdditions, requireAdditions } from '$lib/services/app/additions';\nimport { goto, parseLocation } from '$lib/services/app/navigation';\nimport { backend, backendName, selectBackend } from '$lib/services/backends';\nimport { lockedBranch, mergeLockedBranch } from '$lib/services/backends/branch-access';\nimport { NOT_COLLABORATOR_ERROR_MESSAGE } from '$lib/services/backends/git/shared/errors';\nimport {\n  createStaleCheck,\n  dataGeneration,\n  repositoryHead,\n} from '$lib/services/backends/git/shared/head';\nimport { startRemoteChangePolling, stopRemoteChangePolling } from '$lib/services/backends/poll';\nimport { cmsConfig } from '$lib/services/config';\nimport { dataLoaded } from '$lib/services/contents';\nimport { arrayFileItems } from '$lib/services/contents/file/process';\nimport { resetDeployments } from '$lib/services/deployments';\nimport { resetPageLiveness } from '$lib/services/deployments/ping';\nimport { initDeployments } from '$lib/services/deployments/resolve';\nimport { user } from '$lib/services/user/account.svelte';\nimport { LEGACY_USER_STORAGE_KEYS, USER_STORAGE_KEY } from '$lib/services/user/constants';\nimport { decodeMagicLinkData } from '$lib/services/user/magic-link';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { createRawState, requestAnswer } from '$lib/services/utils/state.svelte';\nimport {\n  allUnpublishedEntries,\n  publishingBranches,\n  unpublishedEntriesLoaded,\n} from '$lib/services/workflow';\nimport { resetDeployingEntries } from '$lib/services/workflow/deploy';\nimport { loadUnpublishedEntries, startLoadingPullRequests } from '$lib/services/workflow/load';\nimport {\n  forkedRepository,\n  forkPermissionRequest,\n  openAuthoringInitialized,\n} from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * BackendService,\n * InternalCmsConfig,\n * MagicLinkConfirmationRequest,\n * User,\n * } from '$lib/types/private';\n */\n\n/**\n * Context of the sign-in error.\n * @typedef {'authentication' | 'dataFetch'} SignInErrorContext\n */\n\nconst MAGIC_LINK_REGEX = /^\\/signin\\/(?<encodedData>.+)/;\n\nexport const auth = $state({\n  /** @type {{ message: string, context: SignInErrorContext }} */\n  signInError: { message: '', context: 'authentication' },\n  /** Whether the user is not authenticated. */\n  unauthenticated: true,\n  /** Whether a sign-in is in progress. */\n  signingIn: false,\n  /**\n   * A username and a temporary password from a magic link emailed to a Sveltia CMS Additions user,\n   * to fill in the sign-in form with. The user still signs in, and then chooses their own password.\n   * @type {{ username: string, password: string } | undefined}\n   */\n  emailedSignIn: undefined,\n});\n\n/**\n * The pending request asking the user whether to sign in to the account a magic link belongs to,\n * which the UI turns into a confirmation dialog. The link can be crafted by anyone, so it’s only\n * used once the user has recognized the account. It’s `undefined` while no request is outstanding.\n * @type {{ current: MagicLinkConfirmationRequest | undefined }}\n */\nexport const magicLinkConfirmation = createRawState();\n\n/**\n * Remove the API keys and log-in credentials for integrations, such as translation services and\n * cloud storage, from the user preferences, so they don’t remain on the device once the user has\n * signed out. The deploy hook URL and its `Authorization` header go too, as either can carry a\n * secret that triggers a deployment. Other preferences, like the theme and language, are kept. This\n * is done on an explicit sign-out, but not when an expired or revoked token sends the user back to\n * the sign-in form, unless the credentials came with a magic link: see\n * {@link clearMagicLinkCredentials}.\n */\nconst clearIntegrationCredentials = () => {\n  prefs.apiKeys = {};\n  delete prefs.logins;\n  delete prefs.deployHookURL;\n  delete prefs.deployHookAuthHeader;\n  delete prefs.magicLinkAccount;\n};\n\n/**\n * Remove the integration credentials copied with a magic link once the session it started has\n * ended, however it ended. Since anyone can craft a link, they may be someone else’s: left on the\n * device, they would carry over to the user’s own account, sending its uploads to someone else’s\n * cloud storage, its translations through someone else’s API keys and its deployments to someone\n * else’s hook. They’re kept as long as the link’s account is signed in, also on the next visit.\n * Checking the account, rather than only clearing them where a session ends, also covers another\n * tab, which doesn’t see the preferences this one has changed: signing in to another account there\n * leaves the credentials in storage until they’re loaded with that account’s session.\n * @param {User} [account] Account starting a session. Omit it when the session has ended.\n */\nconst clearMagicLinkCredentials = (account) => {\n  const { magicLinkAccount } = prefs;\n\n  if (\n    magicLinkAccount &&\n    (magicLinkAccount.backendName !== account?.backendName ||\n      magicLinkAccount.id !== account?.id ||\n      magicLinkAccount.login !== account?.login)\n  ) {\n    clearIntegrationCredentials();\n  }\n};\n\n/**\n * Clear the cached user token so the sign-in form is shown on next load. The user caches left by\n * Netlify/Decap CMS, which may also hold a token, are removed as well, and so are the credentials\n * copied with a magic link.\n */\nconst clearUserCache = async () => {\n  clearMagicLinkCredentials();\n  await Promise.all([\n    LocalStorage.set(USER_STORAGE_KEY, {}),\n    ...LEGACY_USER_STORAGE_KEYS.map((key) => LocalStorage.delete(key)),\n  ]);\n  user.account = undefined;\n  auth.unauthenticated = true;\n};\n\n/**\n * Clear the cached token for authentication/access errors so the sign-in form is shown instead of a\n * dead-end error. Don’t clear for configuration errors like missing branches or repositories where\n * the credentials are still valid.\n * @param {Error} error Exception to check if it’s an authentication error.\n */\nconst clearUserCacheIfNeeded = async (error) => {\n  const isAuthError =\n    typeof (/** @type {any} */ (error?.cause)?.status) === 'number' ||\n    error?.message === NOT_COLLABORATOR_ERROR_MESSAGE;\n\n  if (isAuthError) {\n    await clearUserCache();\n  }\n};\n\n/**\n * Reset the sign-in error.\n */\nexport const resetError = () => {\n  auth.signInError = { message: '', context: 'authentication' };\n};\n\n/**\n * Log an authentication error on the UI and in the browser console.\n * @param {Error} ex Exception.\n * @param {SignInErrorContext} [context] Context of the error.\n */\nexport const logError = (ex, context = 'authentication') => {\n  let message = /** @type {{ message: string }} */ (ex.cause)?.message || _('unexpected_error');\n\n  if (ex.name === 'NotFoundError') {\n    message = _('sign_in_error.not_project_root');\n  }\n\n  if (ex.name === 'AbortError') {\n    message = _(\n      backendName.current === 'local'\n        ? 'sign_in_error.picker_dismissed'\n        : 'sign_in_error.authentication_aborted',\n    );\n  }\n\n  auth.signInError = { message, context };\n  // eslint-disable-next-line no-console\n  console.error(ex.name, ex.message, ex.cause);\n};\n\n/**\n * Parse a magic link URL to extract what it carries: the token and preferences of a QR code\n * sign-in, or the username and temporary password emailed to a Sveltia CMS Additions user, which\n * are kept in {@link auth} to fill in the sign-in form.\n * @returns {{ _user: { token: string } | undefined, copiedPrefs: Record<string, any> | undefined\n * }} Object containing the user token and copied preferences.\n */\nexport const parseMagicLink = () => {\n  const { path } = parseLocation();\n  const { encodedData } = path.match(MAGIC_LINK_REGEX)?.groups ?? {};\n\n  if (!encodedData) {\n    return { _user: undefined, copiedPrefs: undefined };\n  }\n\n  // Remove token from the URL\n  goto('', { replaceState: true });\n\n  /** @type {{ token: string } | undefined} */\n  let _user = undefined;\n  /** @type {Record<string, any> | undefined} */\n  let copiedPrefs = undefined;\n\n  try {\n    const data = decodeMagicLinkData(encodedData);\n\n    if (isObject(data) && typeof data.token === 'string') {\n      _user = { token: data.token };\n\n      if (isObject(data.prefs)) {\n        copiedPrefs = data.prefs;\n      }\n    } else if (\n      isObject(data) &&\n      typeof data.username === 'string' &&\n      typeof data.password === 'string'\n    ) {\n      auth.emailedSignIn = { username: data.username, password: data.password };\n    }\n  } catch {\n    //\n  }\n\n  return { _user, copiedPrefs };\n};\n\n/**\n * Find cached user info, including a compatible Netlify/Decap CMS user object.\n * @returns {Promise<Record<string, any> | undefined>} Cached user info, or undefined if not found.\n */\nexport const getUserCache = async () => {\n  /**\n   * Check whether the given value is a cached user.\n   * @param {any} value Stored value.\n   * @returns {boolean} Result.\n   */\n  const isUserCache = (value) => isObject(value) && typeof value.backendName === 'string';\n\n  // Read the keys one at a time, stopping at the first hit. The empty object left by signing out of\n  // Sveltia CMS isn’t one, so a later sign-in with Netlify/Decap CMS is still picked up\n  return [USER_STORAGE_KEY, ...LEGACY_USER_STORAGE_KEYS].reduce(async (previous, key) => {\n    const found = await previous;\n\n    if (found) {\n      return found;\n    }\n\n    const value = await LocalStorage.get(key);\n\n    return isUserCache(value) ? value : undefined;\n  }, /** @type {Promise<Record<string, any> | undefined>} */ (Promise.resolve(undefined)));\n};\n\n/**\n * Get the name of the backend the given cached user signed in with. Netlify/Decap CMS calls the\n * local backend `proxy`, as it’s served by its local proxy server, while Sveltia CMS calls it\n * `local`; the other names are those of the `backend.name` option, which both use as is.\n * @param {Record<string, any> | undefined} _user Cached user info.\n * @returns {string | undefined} Backend name.\n */\nconst getCachedBackendName = (_user) =>\n  _user?.backendName === 'proxy' ? 'local' : _user?.backendName;\n\n/**\n * Select the backend with the given name, loading it if needed. A failure to load it, e.g. when the\n * chunk holding a Git backend can’t be fetched, is reported as a sign-in error.\n * @param {string} _backendName Backend name.\n * @returns {Promise<BackendService | undefined>} Selected backend service, or `undefined` if it\n * couldn’t be loaded or there’s no backend with the name.\n */\nconst trySelectBackend = async (_backendName) => {\n  try {\n    return await selectBackend(_backendName);\n  } catch (/** @type {any} */ ex) {\n    logError(ex);\n\n    return undefined;\n  }\n};\n\n/**\n * Get the backend instance based on the cached user info or site config.\n * @param {Record<string, any> | undefined} _user Cached user info.\n * @returns {Promise<BackendService | undefined>} Backend instance to be used, or `undefined` if it\n * couldn’t be loaded.\n */\nexport const getBackend = async (_user) => {\n  // Determine the backend name based on the user cache or site config. Use the local backend if the\n  // user cache is found and the backend name is `local`, which is used by Sveltia CMS, or `proxy`,\n  // which is used by Netlify/Decap CMS when running the local proxy server. Otherwise, simply use\n  // the backend name from the site config. This is to ensure that the user is signed in with the\n  // correct backend, especially when the user cache is from a different backend than the current\n  // site config.\n  const _backendName =\n    getCachedBackendName(_user) === 'local'\n      ? 'local'\n      : /** @type {InternalCmsConfig} */ (cmsConfig.current).backend.name;\n\n  return trySelectBackend(_backendName);\n};\n\n/**\n * Verify the token passed with a magic link, and ask the user to confirm the account it belongs\n * to. Since anyone can craft a link, it could otherwise sign the user in to someone else’s account\n * without their knowledge, overwriting their session, and copy the settings in the link, such as a\n * deploy hook URL, to their device.\n * @param {string} token Token passed with the link.\n * @returns {Promise<User | undefined>} User info if the token is valid and the user has confirmed\n * the account, or `undefined` otherwise.\n */\nexport const confirmMagicLink = async (token) => {\n  const _backend = await getBackend(undefined);\n\n  if (!_backend) {\n    return undefined;\n  }\n\n  /** @type {User | undefined} */\n  let account = undefined;\n\n  auth.signingIn = true;\n\n  try {\n    // The user store is left untouched, so an existing session stays cached until the user agrees\n    // to replace it\n    account = /** @type {User | undefined} */ (await _backend.signIn({ token, auto: true }));\n  } catch {\n    //\n  }\n\n  auth.signingIn = false;\n\n  if (!account) {\n    return undefined;\n  }\n\n  // An earlier link still waiting for an answer is declined\n  const confirmed = await requestAnswer(\n    magicLinkConfirmation,\n    { account: /** @type {User} */ (account) },\n    false,\n  );\n\n  return confirmed ? account : undefined;\n};\n\n/**\n * Copy the user preferences passed with a magic link. The deploy hook URL and its `Authorization`\n * header are only copied together, so a link that has a URL but no header can’t leave the header\n * already on this device to be sent to the new URL. The integration credentials are then marked as\n * belonging to the account the link signs in to, which the link itself can’t override.\n * @param {Record<string, any>} copiedPrefs Preferences passed with the link.\n * @param {User} account Account the link signs in to.\n */\nexport const copyMagicLinkPrefs = (copiedPrefs, account) => {\n  // Credentials copied with an earlier link mustn’t stay for those this one lacks\n  clearMagicLinkCredentials();\n\n  if ('deployHookURL' in copiedPrefs) {\n    delete prefs.deployHookAuthHeader;\n  }\n\n  Object.assign(prefs, copiedPrefs, {\n    magicLinkAccount: { backendName: account.backendName, id: account.id, login: account.login },\n  });\n};\n\n/**\n * Load the files and unpublished entries from the backend the user has just signed in to, then\n * start keeping them up to date.\n * @param {BackendService} _backend Backend.\n */\nconst loadRepositoryData = async (_backend) => {\n  // Signing out while the data is being loaded discards it, and stops the polling started below\n  const isStale = createStaleCheck();\n  // The pull requests don’t depend on the files, so they’re requested at the same time. That needs\n  // the branch they target, though: without one configured, the default branch is only known once\n  // the files are being fetched, and every pull request would be dropped as targeting another\n  // branch. They’re then requested once the files are there\n  const branchKnown = !_backend.repository || !!_backend.repository.branch;\n  const pullRequests = branchKnown ? startLoadingPullRequests() : undefined;\n\n  await _backend.fetchFiles();\n\n  // The pull requests requested early belong to the previous session as well, and are dropped\n  if (isStale()) {\n    return;\n  }\n\n  await loadUnpublishedEntries(pullRequests);\n\n  if (isStale()) {\n    return;\n  }\n\n  // The deploy state is a nicety, so it’s resolved in the background rather than delaying the UI.\n  // The files were loaded from the branch head, which is the commit the production site is built\n  // from, so it isn’t fetched again\n  initDeployments({ head: repositoryHead.current });\n  // From here on, someone else’s commits are picked up as they land\n  startRemoteChangePolling();\n};\n\n/**\n * Check if the user info is cached, set the backend, and automatically start loading files if the\n * backend is Git-based and user’s auth token is found.\n */\nexport const signInAutomatically = async () => {\n  resetError();\n\n  const { _user: magicLinkUser, copiedPrefs } = parseMagicLink();\n  /** @type {Record<string, any> | undefined} */\n  let _user = magicLinkUser ? await confirmMagicLink(magicLinkUser.token) : undefined;\n  // The account has been verified already if the user has accepted a magic link\n  const verified = !!_user;\n\n  // Fall back to the cached user, which also covers a declined or invalid magic link\n  _user ??= await getUserCache();\n\n  // Initialize the backend, which is needed on the login page\n  const _backend = await getBackend(_user);\n\n  // If no cached user info is found, simply return as we cannot sign in automatically\n  if (!_user) {\n    return;\n  }\n\n  // A user cached with another backend, e.g. before the site moved from GitLab to GitHub, holds a\n  // token for that service, which mustn’t be sent to the configured one. Netlify/Decap CMS doesn’t\n  // use such a cache either. Clear it, so the sign-in page is shown\n  // The same goes for a user cached before the site started or stopped using Sveltia CMS\n  // Additions, whose session token, or GitHub refresh token, belongs to the other service. Only\n  // Additions gives a user a role. The stub cached while a sign-in popup is open has no token yet\n  if (\n    !verified &&\n    _backend &&\n    (getCachedBackendName(_user) !== backendName.current ||\n      (backendName.current !== 'local' && !!_user.token && !!_user.role !== isAdditionsEnabled()))\n  ) {\n    await clearUserCache();\n\n    return;\n  }\n\n  if (!verified && _backend) {\n    // Temporarily populate the `user` store with the cache, otherwise it’s not updated in\n    // `refreshAccessToken`\n    user.account = /** @type {User} */ (_user);\n\n    const { token, refreshToken } = _user;\n\n    auth.signingIn = true;\n\n    try {\n      _user = /** @type {User} */ (await _backend.signIn({ token, refreshToken, auto: true }));\n    } catch {\n      // The local backend may throw if the file handle permission is not given\n      _user = undefined;\n      user.account = undefined;\n    }\n  }\n\n  auth.signingIn = false;\n  auth.unauthenticated = !_user;\n\n  if (!_user || !_backend) {\n    return;\n  }\n\n  // Use the cached user to start fetching files\n  user.account = /** @type {User} */ (_user);\n  // Someone already signed in has no use for the details of an emailed magic link, which would\n  // otherwise fill in the sign-in form after they sign out\n  auth.emailedSignIn = undefined;\n\n  // Copy user preferences passed with QR code, or drop the credentials copied with a link to\n  // another account\n  if (verified && copiedPrefs) {\n    copyMagicLinkPrefs(copiedPrefs, user.account);\n  } else {\n    clearMagicLinkCredentials(user.account);\n  }\n\n  try {\n    await loadRepositoryData(_backend);\n  } catch (/** @type {any} */ ex) {\n    // The API request may fail if the cached token has been expired or revoked. Then let the user\n    // sign in again. 404 Not Found is also considered an authentication error.\n    // https://docs.github.com/en/rest/overview/troubleshooting-the-rest-api#404-not-found-for-an-existing-resource\n    if ([401, 403, 404].includes(ex.cause?.status)) {\n      auth.unauthenticated = true;\n    } else {\n      logError(ex, 'dataFetch');\n    }\n\n    await clearUserCacheIfNeeded(ex);\n  }\n};\n\n/**\n * Sign in with the given backend.\n * @param {string} _backendName Backend name to be used.\n * @param {string} [token] Personal Access Token (PAT) to be used for authentication.\n * @param {object} [credentials] Credentials for Sveltia CMS Additions.\n * @param {string} [credentials.username] Username.\n * @param {string} [credentials.password] Password.\n * @param {string} [credentials.refreshToken] Session token, after the user has changed a temporary\n * password.\n * @param {string} [credentials.provider] Provider to sign in through instead, e.g. `github`.\n */\nexport const signInManually = async (_backendName, token, credentials = {}) => {\n  resetError();\n\n  const _backend = await trySelectBackend(_backendName);\n\n  if (!_backend) {\n    return;\n  }\n\n  let _user;\n\n  // An account may be left in the store from a previous session whose data failed to load. It may\n  // be someone else’s, so its tokens mustn’t be picked up while signing in, e.g. as renewed ones\n  user.account = undefined;\n  auth.signingIn = true;\n\n  try {\n    _user = await _backend.signIn({ token, auto: false, ...credentials });\n  } catch (/** @type {any} */ ex) {\n    auth.signingIn = false;\n    auth.unauthenticated = true;\n\n    if (!!token && ex.cause?.status === 401) {\n      // If the user is signing in using a personal access token (PAT) and the token is invalid,\n      // display a specific error message.\n      logError(\n        new Error('Invalid token', { cause: { message: _('sign_in_error.invalid_token') } }),\n      );\n    } else {\n      logError(ex);\n    }\n\n    return;\n  }\n\n  auth.signingIn = false;\n  auth.unauthenticated = !_user;\n\n  if (!_user) {\n    return;\n  }\n\n  clearMagicLinkCredentials(_user);\n  // Signed in, so the details of an emailed magic link, if any, aren’t needed any more\n  auth.emailedSignIn = undefined;\n  user.account = _user;\n\n  try {\n    await loadRepositoryData(_backend);\n  } catch (/** @type {any} */ ex) {\n    logError(ex, 'dataFetch');\n    await clearUserCacheIfNeeded(ex);\n  }\n};\n\n/**\n * Replace the temporary password of a Sveltia CMS Additions user, then finish signing in with the\n * new session the change returns.\n * @param {string} _backendName Backend name to be used.\n * @param {string} newPassword New password.\n * @returns {Promise<boolean>} Whether the password was changed. Signing in afterwards reports its\n * own errors.\n */\nexport const signInWithNewPassword = async (_backendName, newPassword) => {\n  resetError();\n\n  /** @type {string} */\n  let refreshToken;\n\n  try {\n    // Only offered with Sveltia CMS Additions\n    await loadAdditions();\n    refreshToken = await requireAdditions().changeTemporaryPassword(newPassword);\n  } catch (/** @type {any} */ ex) {\n    logError(ex);\n\n    return false;\n  }\n\n  await signInManually(_backendName, undefined, { refreshToken });\n\n  return true;\n};\n\n/**\n * Sign out from the current backend.\n */\nexport const signOut = async () => {\n  stopRemoteChangePolling();\n  // A check for remote changes, or a load, still on its way belongs to this session, so it mustn’t\n  // put its results back into the stores once they have been reset below\n  dataGeneration.current += 1;\n\n  // A failure, e.g. an IndexedDB error, mustn’t keep the user signed in\n  try {\n    await backend.current?.signOut();\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  }\n\n  await clearUserCache();\n  clearIntegrationCredentials();\n\n  await selectBackend(undefined);\n  dataLoaded.current = false;\n  // The items of the files storing all the entries of a collection belong to this repository\n  arrayFileItems.clear();\n  repositoryHead.current = '';\n  lockedBranch.current = undefined;\n  mergeLockedBranch.current = undefined;\n  allUnpublishedEntries.current = [];\n  unpublishedEntriesLoaded.current = false;\n  publishingBranches.current = [];\n  // A magic link still waiting for an answer would sign the user back in\n  magicLinkConfirmation.current?.respond(false);\n  // The fork belongs to the signed-out user, so the next user needs Open Authoring set up again\n  forkPermissionRequest.current?.respond(false);\n  forkedRepository.current = undefined;\n  openAuthoringInitialized.current = false;\n  resetDeployingEntries();\n  resetDeployments();\n  resetPageLiveness();\n\n  const redirectURL = cmsConfig.current?.logout_redirect_url;\n\n  if (redirectURL) {\n    window.location.href = redirectURL;\n  }\n};\n","/**\n * Create a generation counter, which tells whether something has been reset since a request\n * started, e.g. a user who has signed out while it was on its way, so its response is dropped\n * rather than brought back for whoever comes next.\n * @returns {{ capture: () => () => boolean, bump: () => void }} Counter.\n */\nexport const createGeneration = () => {\n  let generation = 0;\n\n  return {\n    /**\n     * Take the current generation.\n     * @returns {() => boolean} Function that tells whether it’s still current.\n     */\n    capture: () => {\n      const captured = generation;\n\n      return () => captured === generation;\n    },\n    /**\n     * Start a new generation, so those taken before are no longer current.\n     */\n    bump: () => {\n      generation += 1;\n    },\n  };\n};\n","import { DOCS_BASE_URL } from '$lib/services/app';\n\n/**\n * URL for documentation on unsupported features and compatibility between Netlify/Decap CMS and\n * Sveltia CMS. When users call an unsupported API function, they will see a warning in the console\n * with a link to this documentation.\n */\nexport const COMPATIBILITY_URL = `${DOCS_BASE_URL}/migration/netlify-decap-cms#compatibility`;\n\n/**\n * List of API functions in Netlify/Decap CMS that we don’t plan to support in Sveltia CMS, either\n * because they are undocumented or because they are incompatible with Sveltia CMS’s architecture\n * and design principles.\n */\nexport const UNSUPPORTED_FUNC_NAMES = [\n  // Undocumented\n  'getBackend',\n  'getCustomFormats',\n  'getCustomFormatsExtensions',\n  'getCustomFormatsFormatters',\n  'getEditorComponents',\n  'getEventListeners',\n  'getLocale',\n  'getMediaLibrary',\n  'getPreviewStyles',\n  'getPreviewTemplate',\n  'getRemarkPlugins',\n  'getWidgetValueSerializer',\n  'getWidgets',\n  'invokeEvent',\n  'moment', // Removed in Decap CMS 3.1.1 as it switched from Moment.js to Day.js\n  'registerBackend',\n  'registerMediaLibrary',\n  'registerWidgetValueSerializer',\n  'removeEventListener',\n  'resolveWidget',\n  // Documented but not planned for implementation\n  'registerLocale', // https://decapcms.org/docs/configuration-options/#locale\n  'registerRemarkPlugin', // https://decapcms.org/docs/widgets/#Markdown\n  // Note: `getWidget` is also undocumented, but we’ve added support for it as requested\n  // https://github.com/sveltia/sveltia-cms/issues/915\n];\n","<!--\n  @component\n  Implement the editor for a Boolean field.\n  @see https://decapcms.org/docs/widgets/#Boolean\n  @see https://sveltiacms.app/en/docs/fields/boolean\n-->\n<script>\n  import { Switch } from '@sveltia/ui';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { BooleanField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {BooleanField} fieldConfig Field configuration.\n   * @property {boolean | 'mixed' | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    fieldId,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n</script>\n\n<!--\n  A field that has never been set has no value yet, but a Sveltia UI `<Switch>` falls back to\n  `false` and refuses an `undefined` binding, so the value goes through a getter and setter instead\n-->\n<Switch\n  bind:checked={\n    () => currentValue ?? false,\n    (checked) => {\n      currentValue = checked;\n    }\n  }\n  {readonly}\n  {required}\n  {invalid}\n  aria-labelledby=\"{fieldId}-label\"\n  aria-errormessage=\"{fieldId}-error\"\n/>\n","<!--\n  @component\n  Implement the preview for a Boolean field.\n  @see https://decapcms.org/docs/widgets/#Boolean\n  @see https://sveltiacms.app/en/docs/fields/boolean\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { BooleanField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {BooleanField} fieldConfig Field configuration.\n   * @property {boolean | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { currentValue = false } = $props();\n</script>\n\n{#if typeof currentValue === 'boolean'}\n  <p>\n    {_(`boolean.${currentValue}`)}\n  </p>\n{/if}\n","/**\n * Run a write to the entry draft in a microtask, outside Svelte’s update cycle.\n *\n * Field editors sync their local state to the draft from an `$effect`, and Svelte can only\n * memoize its dirty-marking traversal for writes made outside a running reaction. A write made\n * while an effect is running makes Svelte re-walk the derived graph below the value map once per\n * path that reaches it, even within `untrack()`, which is exponential in the depth of the editor\n * tree — tens of seconds per keystroke on a deeply nested entry. Deferring the write avoids that.\n *\n * As the write runs later, the callback should capture the values it needs beforehand, and check\n * that the draft is still there or that the editor is still mounted where that matters.\n * @param {() => void} write Function making the write.\n */\nexport const deferDraftWrite = (write) => {\n  queueMicrotask(write);\n};\n","import { getContext, setContext } from 'svelte';\n\n/**\n * @import { DraftValueStoreKey, FieldEditorContext } from '$lib/types/private';\n */\n\n/**\n * Key of the context a field editor provides to the editors of its subfields, and a rich text\n * editor component to the fields in it.\n */\nconst CONTEXT_KEY = 'field-editor';\n\n/**\n * Check if a field is rendered within a rich text editor component. Its values are then stored in\n * the draft’s `extraValues` rather than `currentValues`, which is passed down to every descendant\n * field. The `fieldContext` doesn’t tell it reliably, as a List with a single subfield overrides it\n * for the subfield.\n * @param {DraftValueStoreKey | undefined} valueStoreKey Key to store the field values in the entry\n * draft, as passed to the field editor or shared through the `field-editor` context.\n * @returns {boolean} Result.\n */\nexport const isInEditorComponent = (valueStoreKey) => valueStoreKey === 'extraValues';\n\n/**\n * Get the context provided by the nearest field editor or rich text editor component. A field’s\n * editor rendered on its own, outside of both, gets an empty object.\n * @returns {FieldEditorContext} Context.\n */\nexport const getFieldEditorContext = () =>\n  getContext(CONTEXT_KEY) ?? /** @type {FieldEditorContext} */ ({});\n\n/**\n * Provide the context to the field editors below the current component.\n * @param {FieldEditorContext} context Context.\n */\nexport const setFieldEditorContext = (context) => {\n  setContext(CONTEXT_KEY, context);\n};\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * Field editor updates still in flight, e.g. a rich text editor converting what was just typed to\n * Markdown, which happens with a short delay. Until such an update lands, the entry draft holds a\n * stale value for the field, so the draft has to wait for them before it’s validated and saved.\n * @type {Set<Promise<void>>}\n */\nconst pendingFieldUpdates = new Set();\n\n/**\n * Whether a field editor update is in flight. The entry counts as changed meanwhile, so the Save\n * button is enabled as soon as the user has made a change: a change made in a rich text editor only\n * reaches the draft a moment later, and Accel+S pressed in between would find the button disabled\n * and be ignored.\n * @type {{ current: boolean }}\n */\nexport const fieldUpdatePending = createRawState(false);\n\n/**\n * Register a field editor update carrying a change made by the user that hasn’t reached the entry\n * draft yet.\n * @param {Promise<void>} promise Promise that settles once the draft holds the latest value.\n */\nexport const trackPendingFieldUpdate = (promise) => {\n  /** Remove the settled promise. A rejected update is treated like a settled one. */\n  const remove = () => {\n    pendingFieldUpdates.delete(promise);\n    fieldUpdatePending.current = !!pendingFieldUpdates.size;\n  };\n\n  pendingFieldUpdates.add(promise);\n  fieldUpdatePending.current = true;\n  promise.then(remove, remove);\n};\n\n/**\n * Wait for all in-flight field editor updates to reach the entry draft. Call this before validating\n * an entry for saving, so that the values being validated are the ones the user sees.\n * @returns {Promise<void>} Promise that resolves once no update is pending.\n */\nexport const awaitPendingFieldUpdates = async () => {\n  // An update landing may trigger another one, so drain until no promises remain\n  while (pendingFieldUpdates.size) {\n    // eslint-disable-next-line no-await-in-loop\n    await Promise.allSettled(pendingFieldUpdates);\n  }\n};\n\n/**\n * Run the given function once all in-flight field editor updates have reached the entry draft. Use\n * it to change the locale or the mode of an editor pane: the field editors in the pane are reused\n * for the new locale, so an update still in flight, e.g. a rich text editor converting what was\n * just typed, would be written to the new locale, and lost for the one it was made in.\n * @param {() => void} fn Function to run.\n */\nexport const afterPendingFieldUpdates = async (fn) => {\n  await awaitPendingFieldUpdates();\n  fn();\n};\n","import { tick } from 'svelte';\n\nimport { trackPendingFieldUpdate } from '$lib/services/contents/editor/pending';\n\n/**\n * Register a pending field editor update for as long as the editor holds a change made by the user\n * that it passes on to the entry draft with a short delay, e.g. a rich text editor converting the\n * content to Markdown, so a save right after a change doesn’t validate and write the previous\n * value. The update settles a tick after the editor is no longer pending, once the value has\n * reached the draft through the bindings and effects, or when the editor goes away. Call it while\n * initializing the editor component, as it creates an effect.\n * @param {() => boolean} getPending Function returning whether the editor holds such a change.\n */\nexport const trackPendingWhile = (getPending) => {\n  $effect(() => {\n    if (!getPending()) {\n      return undefined;\n    }\n\n    /** @type {PromiseWithResolvers<void>} */\n    const { promise, resolve } = Promise.withResolvers();\n\n    trackPendingFieldUpdate(promise);\n\n    return async () => {\n      await tick();\n      resolve();\n    };\n  });\n};\n","<!--\n  @component\n  Implement the editor for a Code field.\n  @see https://decapcms.org/docs/widgets/#Code\n  @see https://sveltiacms.app/en/docs/fields/code\n-->\n<script>\n  import { CodeEditor } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import { isObject } from '@sveltia/utils/object';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { deferDraftWrite } from '$lib/services/contents/draft/update/deferred';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getFieldEditorContext } from '$lib/services/contents/editor/field-context';\n  import { trackPendingWhile } from '$lib/services/contents/editor/pending.svelte';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { CodeField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {CodeField} fieldConfig Field configuration.\n   * @property {string | Record<string, string> | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const { valueStoreKey = 'currentValues' } = getFieldEditorContext();\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  let code = $state('');\n  let lang = $state('');\n  let pending = $state(false);\n\n  const {\n    default_language: defaultLanguage = 'plain',\n    allow_language_selection: showLanguageSwitcher = true,\n    output_code_only: outputCodeOnly = false,\n    keys: outputKeys = { code: 'code', lang: 'lang' },\n  } = $derived(fieldConfig);\n  const valueMap = $derived(\n    getFieldValueMapSnapshot(entryDraft.current, locale, keyPath, valueStoreKey),\n  );\n  const codeKeyPath = $derived(`${keyPath}.${outputKeys.code}`);\n  const langKeyPath = $derived(`${keyPath}.${outputKeys.lang}`);\n\n  /**\n   * Values of {@link code} and {@link lang} right after they were last synced with the draft. The\n   * value is only written back once the user has changed either of them, so opening an entry\n   * doesn’t add the object placeholder or the default language to the stored value, which would\n   * mark the draft as modified. A new value comes with an empty language, though, which is\n   * replaced with the default one right away.\n   */\n  let syncedInputValues = { code: '', lang: '' };\n\n  /**\n   * Update {@link code} and {@link lang} based on {@link currentValue}.\n   */\n  const setInputValue = () => {\n    if (outputCodeOnly) {\n      if (typeof currentValue !== 'string') {\n        code = '';\n      } else if (code !== currentValue) {\n        code = currentValue;\n      }\n\n      lang = defaultLanguage;\n    } else {\n      const _code = valueMap[codeKeyPath];\n      const _lang = valueMap[langKeyPath] || defaultLanguage;\n\n      if (typeof _code !== 'string') {\n        code = '';\n      } else if (code !== _code) {\n        code = _code;\n      }\n\n      if (typeof _lang !== 'string') {\n        // Fall back to the default language rather than an empty one, which the editor replaces\n        // with `plain` on its own, as if the user had picked it\n        lang = defaultLanguage;\n      } else if (lang !== _lang) {\n        lang = _lang;\n      }\n\n      syncedInputValues = { code, lang: valueMap[langKeyPath] === '' ? '' : lang };\n    }\n  };\n\n  /**\n   * Update {@link currentValue} based on {@link code} and {@link lang}.\n   */\n  const setCurrentValue = () => {\n    if (outputCodeOnly) {\n      if (currentValue !== code) {\n        currentValue = code;\n      }\n\n      return;\n    }\n\n    if (code === syncedInputValues.code && lang === syncedInputValues.lang) {\n      return;\n    }\n\n    const draft = entryDraft.current;\n\n    /* v8 ignore next 3 -- the editor is only rendered while the draft is there */\n    if (!draft) {\n      return;\n    }\n\n    syncedInputValues = { code, lang };\n\n    /** @type {Record<string, any>} */\n    const updates = {};\n\n    if (!isObject(valueMap[keyPath]) || Object.keys(valueMap[keyPath]).length) {\n      updates[keyPath] = {};\n    }\n\n    if (valueMap[codeKeyPath] !== code) {\n      updates[codeKeyPath] = code;\n    }\n\n    if (valueMap[langKeyPath] !== lang) {\n      updates[langKeyPath] = lang;\n    }\n\n    /* v8 ignore next 3 -- only when a change is undone before the previous one reaches the draft */\n    if (!Object.keys(updates).length) {\n      return;\n    }\n\n    const valueStore = draft[valueStoreKey][locale];\n\n    // This runs from an effect, so the write to the draft is deferred\n    deferDraftWrite(() => {\n      Object.assign(valueStore, updates);\n    });\n  };\n\n  watch(\n    () => valueMap,\n    () => {\n      setInputValue();\n    },\n  );\n\n  watch(\n    () => [code, lang],\n    () => {\n      setCurrentValue();\n    },\n  );\n\n  // While the editor holds a change made by the user, register it as a pending update: the editor\n  // passes the code on with a short delay, so a save right after a change would otherwise validate\n  // and write the previous value\n  trackPendingWhile(() => pending);\n</script>\n\n{#await sleep() then}\n  <!--\n    Reset the editor when the configuration changes. It happens when fields are reordered or removed\n    in a variable type list field. @see https://github.com/sveltia/sveltia-cms/issues/480\n  -->\n  {#key JSON.stringify(fieldConfig)}\n    <CodeEditor\n      bind:code\n      bind:lang\n      bind:pending\n      {showLanguageSwitcher}\n      flex\n      {readonly}\n      {required}\n      {invalid}\n      aria-labelledby=\"{fieldId}-label\"\n      aria-errormessage=\"{fieldId}-error\"\n    />\n  {/key}\n{/await}\n","<!--\n  @component\n  Implement the preview for a Code field.\n  @see https://decapcms.org/docs/widgets/#Code\n  @see https://sveltiacms.app/en/docs/fields/code\n-->\n<script>\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { CodeField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {CodeField} fieldConfig Field configuration.\n   * @property {string | Record<string, string> | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldEditorProps & Props} */\n  let { locale, keyPath, fieldConfig, currentValue } = $props();\n\n  const {\n    default_language: defaultLanguage = '',\n    output_code_only: outputCodeOnly = false,\n    keys: outputKeys = { code: 'code', lang: 'lang' },\n  } = $derived(fieldConfig);\n  const valueMap = $derived(getFieldValueMapSnapshot(entryDraft.current, locale, keyPath));\n  const codeKeyPath = $derived(`${keyPath}.${outputKeys.code}`);\n  const langKeyPath = $derived(`${keyPath}.${outputKeys.lang}`);\n  const code = $derived(outputCodeOnly ? currentValue : valueMap[codeKeyPath]);\n  const lang = $derived(outputCodeOnly ? defaultLanguage : valueMap[langKeyPath]);\n</script>\n\n{#if code}\n  <pre class={lang ? `language-${lang}` : undefined}>{code}</pre>\n{/if}\n","/**\n * Regular expression matching a hex color, with an optional alpha channel.\n */\nconst HEX_COLOR_REGEX = /^#(?<r>[0-9a-f]{2})(?<g>[0-9a-f]{2})(?<b>[0-9a-f]{2})(?<a>[0-9a-f]{2})?$/i;\n/**\n * Parse a two-digit hex value as an integer.\n * @param {string} hex Hex value.\n * @returns {number} Integer.\n */\nconst hexToInt = (hex) => Number.parseInt(hex, 16);\n\n/**\n * Format a hex color as a CSS `rgb()` string, e.g. `#ff8000` as `rgb(255 128 0)`, so the channel\n * values can be shown next to the hex value.\n * @param {string | undefined} hex Hex color.\n * @param {object} [options] Options.\n * @param {boolean} [options.enableAlpha] Whether to include the alpha channel, as a percentage, if\n * the color has one.\n * @returns {string} Formatted color, or an empty string if the value is not a hex color.\n */\nexport const formatHexAsRGB = (hex, { enableAlpha = false } = {}) => {\n  const { r, g, b, a } = hex?.match(HEX_COLOR_REGEX)?.groups ?? {};\n\n  if (!r) {\n    return '';\n  }\n\n  const alpha = enableAlpha && a ? ` / ${Math.round((hexToInt(a) / 255) * 100)}%` : '';\n\n  return `rgb(${hexToInt(r)} ${hexToInt(g)} ${hexToInt(b)}${alpha})`;\n};\n\n/**\n * Regular expression matching a 6-digit hex color, which is what a color input accepts.\n */\nconst RGB_HEX_REGEX = /^#[0-9a-f]{6}$/i;\n\n/**\n * Split a stored color into the parts the editor’s controls take: the 6-digit hex color for the\n * color input, and the alpha channel as an integer for the opacity slider.\n * @param {any} currentValue Value in the entry draft.\n * @returns {{ rgb: string, alpha: number } | undefined} Parts, or `undefined` if the value is not a\n * hex color, in which case the controls keep what they have.\n */\nexport const parseColorFieldValue = (currentValue) => {\n  if (typeof currentValue !== 'string') {\n    return undefined;\n  }\n\n  const { r, g, b, a = 'ff' } = currentValue.match(HEX_COLOR_REGEX)?.groups ?? {};\n\n  if (!r) {\n    return undefined;\n  }\n\n  return { rgb: `#${r}${g}${b}`, alpha: hexToInt(a) };\n};\n\n/**\n * Get the value to be stored in the entry draft for the editor’s controls.\n * @param {object} args Arguments.\n * @param {string} args.rgb Value of the color input.\n * @param {number} args.alpha Value of the opacity slider, from 0 to 255.\n * @param {boolean} [args.enableAlpha] Whether the field stores the alpha channel.\n * @returns {string} Hex color, with the alpha channel if enabled, or an empty string if the color\n * input holds nothing usable.\n */\nexport const getColorFieldValue = ({ rgb, alpha, enableAlpha = false }) => {\n  if (!RGB_HEX_REGEX.test(rgb)) {\n    return '';\n  }\n\n  return enableAlpha ? `${rgb}${alpha.toString(16).padStart(2, '0')}` : rgb;\n};\n\n/**\n * Get the values the editor’s controls should take for the stored color. An empty value resets the\n * controls, unless they already produce it, like a half-typed hex color in the text input does.\n * @param {object} args Arguments.\n * @param {any} args.currentValue Value in the entry draft.\n * @param {string} args.rgb Current value of the color input.\n * @param {number} args.alpha Current value of the opacity slider, from 0 to 255.\n * @param {boolean} [args.enableAlpha] Whether the field stores the alpha channel.\n * @returns {{ rgb: string, alpha: number } | undefined} New values, or `undefined` if the controls\n * should keep what they have.\n */\nexport const getColorFieldInputValues = ({ currentValue, rgb, alpha, enableAlpha = false }) => {\n  const parts = parseColorFieldValue(currentValue);\n\n  if (parts) {\n    return parts;\n  }\n\n  if (\n    (currentValue === undefined || currentValue === null || currentValue === '') &&\n    getColorFieldValue({ rgb, alpha, enableAlpha }) !== ''\n  ) {\n    return { rgb: '', alpha: 255 };\n  }\n\n  return undefined;\n};\n","<!--\n  @component\n  Implement the editor for a Color field.\n  @see https://decapcms.org/docs/widgets/#color\n  @see https://sveltiacms.app/en/docs/fields/color\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, ColorInput, Slider, TextInput } from '@sveltia/ui';\n\n  import {\n    getColorFieldInputValues,\n    getColorFieldValue,\n  } from '$lib/services/contents/fields/color/helpers';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { ColorField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ColorField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  let inputValue = $state('');\n  let inputAlphaValue = $state(255);\n\n  const { allowInput = false, enableAlpha = false } = $derived(fieldConfig);\n\n  const id = $props.id();\n\n  /**\n   * Values of the controls right after they were last synced with {@link currentValue}. The value\n   * is only written back once the user has changed a control from these, so a stored color the\n   * controls can’t represent, like `#fff` or `red`, isn’t replaced as soon as the editor is opened.\n   */\n  let syncedInputValues = { rgb: '', alpha: 255 };\n\n  /**\n   * Update {@link inputValue} and {@link inputAlphaValue} based on {@link currentValue}.\n   */\n  const setInputValue = () => {\n    const parts = getColorFieldInputValues({\n      currentValue,\n      rgb: inputValue,\n      alpha: inputAlphaValue,\n      enableAlpha,\n    });\n\n    if (parts) {\n      // Avoid a cycle dependency & infinite loop\n      if (inputValue !== parts.rgb) {\n        inputValue = parts.rgb;\n      }\n\n      if (enableAlpha && inputAlphaValue !== parts.alpha) {\n        inputAlphaValue = parts.alpha;\n      }\n    }\n\n    syncedInputValues = { rgb: inputValue, alpha: inputAlphaValue };\n  };\n\n  /**\n   * Update {@link currentValue} based on {@link inputValue} and {@link inputAlphaValue}, if the\n   * user has changed either of them.\n   */\n  const setCurrentValue = () => {\n    if (inputValue === syncedInputValues.rgb && inputAlphaValue === syncedInputValues.alpha) {\n      return;\n    }\n\n    const newValue = getColorFieldValue({ rgb: inputValue, alpha: inputAlphaValue, enableAlpha });\n\n    // Avoid a cycle dependency & infinite loop\n    if (currentValue !== newValue) {\n      currentValue = newValue;\n    }\n  };\n\n  watch(\n    () => currentValue,\n    () => {\n      setInputValue();\n    },\n  );\n\n  watch(\n    () => [inputValue, inputAlphaValue],\n    () => {\n      setCurrentValue();\n    },\n  );\n</script>\n\n<div role=\"none\">\n  <ColorInput\n    id=\"{id}-picker\"\n    bind:value={inputValue}\n    {readonly}\n    {required}\n    {invalid}\n    aria-labelledby=\"{fieldId}-label\"\n    aria-errormessage=\"{fieldId}-error\"\n  />\n  {#if allowInput || enableAlpha}\n    <span role=\"none\" class=\"value\">\n      {#if allowInput}\n        <TextInput\n          dir=\"ltr\"\n          id=\"{id}-input\"\n          bind:value={inputValue}\n          {invalid}\n          {readonly}\n          {required}\n          aria-labelledby=\"{fieldId}-label\"\n          aria-errormessage=\"{fieldId}-error\"\n        />\n      {/if}\n      {#if enableAlpha}\n        {_('opacity')}\n        <Slider\n          min={0}\n          max={255}\n          disabled={!inputValue}\n          {readonly}\n          bind:value={inputAlphaValue}\n          sliderLabel={_('opacity')}\n        />\n      {/if}\n    </span>\n  {/if}\n  {#if !readonly && !required}\n    <Button\n      variant=\"tertiary\"\n      label={_('clear')}\n      disabled={!inputValue}\n      aria-controls={`${id}-picker ${allowInput ? `${id}-input` : ''}`}\n      onclick={() => {\n        inputValue = '';\n        inputAlphaValue = 255;\n      }}\n    />\n  {/if}\n</div>\n\n<style>\n  div {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n\n    .value {\n      display: flex;\n      align-items: center;\n      gap: 8px;\n\n      :global {\n        .sui.text-input {\n          width: 88px;\n          min-width: 0;\n        }\n\n        .sui.slider {\n          padding: 8px;\n          --sui-slider-base-width: 80px;\n        }\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the preview for a Color field.\n  @see https://decapcms.org/docs/widgets/#color\n  @see https://sveltiacms.app/en/docs/fields/color\n-->\n<script>\n  import { formatHexAsRGB } from '$lib/services/contents/fields/color/helpers';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { ColorField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ColorField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { fieldConfig, currentValue } = $props();\n\n  const { enableAlpha = false } = $derived(fieldConfig);\n  const rgb = $derived(formatHexAsRGB(currentValue, { enableAlpha }));\n</script>\n\n{#if typeof currentValue === 'string' && currentValue.trim()}\n  <p>\n    <span role=\"none\" class=\"preview\">\n      <span role=\"none\" class=\"color\" style:background-color={currentValue}></span>\n      <span role=\"none\" class=\"value\">{currentValue}</span>\n      <span role=\"none\" class=\"value\">{rgb}</span>\n    </span>\n  </p>\n{/if}\n\n<style>\n  .preview {\n    display: inline-flex;\n    align-items: center;\n    gap: 8px;\n\n    .color {\n      display: block;\n      width: 24px;\n      height: 24px;\n      border-radius: 24px;\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the editor for a Compute field. The field is hidden in `FieldEditor`; the value itself\n  is resolved by `updateComputedValues`, which walks the whole draft rather than relying on this\n  editor being rendered.\n-->\n<script>\n  import { TextInput } from '@sveltia/ui';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { ComputeField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ComputeField} fieldConfig Field configuration.\n   * @property {string | number | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    fieldId,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n</script>\n\n<TextInput\n  dir=\"auto\"\n  value={String(currentValue)}\n  flex\n  {readonly}\n  {required}\n  {invalid}\n  aria-labelledby=\"{fieldId}-label\"\n  aria-errormessage=\"{fieldId}-error\"\n/>\n","import { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import { ContentIndex, FlattenedEntryContent, ListItemIndex } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Our internal representation of an entry is a flat map from key path to value, so a caller\n * walking the field configuration has to ask the content what shape it holds: whether a key path\n * holds anything at all, and which list items exist under it. A plain scan would be O(keys) per\n * field, and such a walk visits every configured field, so the content is indexed once up front.\n *\n * Two shapes are offered because the full index isn’t cheap: it records every parent/child pair,\n * and building it for a large entry takes a couple of milliseconds. A caller that only needs the\n * list question — the common case on a hot path — gets {@link indexListItems}, which skips the\n * rest.\n */\n\n/**\n * Index the given content so that both {@link hasChildKeys} and {@link getItemIndexes} answer in\n * constant time.\n * @param {FlattenedEntryContent} content Flattened entry content.\n * @returns {ContentIndex} Index of the content.\n */\nexport const indexContent = (content) => {\n  /** @type {Map<FieldKeyPath, Set<string>>} */\n  const childSegmentMap = new Map();\n\n  Object.keys(content).forEach((key) => {\n    const segments = key.split('.');\n    let path = '';\n\n    segments.forEach((segment, index) => {\n      if (index > 0) {\n        const siblings = childSegmentMap.get(path);\n\n        if (siblings) {\n          siblings.add(segment);\n        } else {\n          childSegmentMap.set(path, new Set([segment]));\n        }\n      }\n\n      path = index === 0 ? segment : `${path}.${segment}`;\n    });\n  });\n\n  return { childSegmentMap };\n};\n\n/**\n * Check whether the given key path has any child key paths in the indexed content.\n * @param {ContentIndex} index Index of the content.\n * @param {FieldKeyPath} keyPath Key path.\n * @returns {boolean} Result.\n */\nexport const hasChildKeys = (index, keyPath) => index.childSegmentMap.has(keyPath);\n\n/**\n * Get the indexes of the list items stored under the given key path, in ascending order.\n * @param {ContentIndex} index Index of the content.\n * @param {FieldKeyPath} keyPath Key path of the list field.\n * @returns {number[]} Item indexes.\n */\nexport const getItemIndexes = (index, keyPath) =>\n  [...(index.childSegmentMap.get(keyPath) ?? [])]\n    .filter(isNumeric)\n    .map(Number)\n    .sort((a, b) => a - b);\n\n/**\n * Index only the list items in the given content, which is around twice as fast as\n * {@link indexContent}: the key paths are scanned in place rather than split, and only the numeric\n * segments are recorded.\n * @param {FlattenedEntryContent} content Flattened entry content.\n * @returns {ListItemIndex} Index of the list items, keyed by the key path holding them.\n */\nexport const indexListItems = (content) => {\n  /** @type {ListItemIndex} */\n  const itemMap = new Map();\n\n  Object.keys(content).forEach((key) => {\n    let start = 0;\n\n    for (;;) {\n      const dotIndex = key.indexOf('.', start);\n\n      if (dotIndex === -1) {\n        return;\n      }\n\n      const nextDotIndex = key.indexOf('.', dotIndex + 1);\n      const end = nextDotIndex === -1 ? key.length : nextDotIndex;\n      const segment = key.slice(dotIndex + 1, end);\n\n      if (isNumeric(segment)) {\n        const keyPath = key.slice(0, dotIndex);\n        const indexes = itemMap.get(keyPath);\n\n        if (indexes) {\n          indexes.add(Number(segment));\n        } else {\n          itemMap.set(keyPath, new Set([Number(segment)]));\n        }\n      }\n\n      start = dotIndex + 1;\n    }\n  });\n\n  return itemMap;\n};\n\n/**\n * Get the indexes of the list items stored under the given key path, in ascending order.\n * @param {ListItemIndex} index Index of the list items.\n * @param {FieldKeyPath} keyPath Key path of the list field.\n * @returns {number[]} Item indexes.\n */\nexport const getListItemIndexes = (index, keyPath) =>\n  [...(index.get(keyPath) ?? [])].sort((a, b) => a - b);\n","import { TAG_PLACEHOLDER } from '$lib/services/common/template/constants';\nimport { splitTemplateTags } from '$lib/services/common/template/tags';\nimport { getOrCreateBounded } from '$lib/services/utils/cache';\nimport { toFixed } from '$lib/services/utils/number';\n\n/**\n * A node of a parsed arithmetic expression.\n * @typedef {{ type: 'number', value: number }\n * | { type: 'tag', index: number }\n * | { type: 'unary', operator: string, operand: ExpressionNode }\n * | { type: 'binary', operator: string, left: ExpressionNode, right: ExpressionNode }\n * | { type: 'call', name: string, args: ExpressionNode[] }} ExpressionNode\n */\n\n/**\n * A template tag in an arithmetic expression.\n * @typedef {object} ExpressionTag\n * @property {string} content Content of the tag, e.g. `fields.price` for `{{fields.price}}`.\n * @property {boolean} allItems Whether the tag is an argument of an aggregate function, like\n * `{{fields.lines.*.amount}}` in `sum({{fields.lines.*.amount}})`. It then resolves to a list of\n * values, one for each item the last `*` in the tag stands for.\n */\n\n/**\n * A parsed arithmetic expression.\n * @typedef {object} ParsedExpression\n * @property {ExpressionNode} [tree] Syntax tree. `undefined` if the expression is invalid.\n * @property {ExpressionTag[]} tags Template tags in the expression, in the order they appear. A\n * `tag` node refers to one by its index.\n */\n\n/**\n * Value of a template tag in an arithmetic expression: a number, `undefined` for an empty value or\n * something other than a number, or the resolved values of a tag that covers every item.\n * @typedef {number | undefined | unknown[]} ExpressionOperand\n */\n\n/**\n * Function resolving a template tag of an arithmetic expression.\n * @callback ExpressionTagResolver\n * @param {string} content Content of the tag, e.g. `fields.price | default('0')` for\n * `{{fields.price | default('0')}}`.\n * @param {{ allItems: boolean }} options Options. With `allItems`, the tag is an argument of an\n * aggregate function, and the function returns a list of values, one for each item the last `*` in\n * the tag stands for, or a list with the single value of a tag without a `*`.\n * @returns {any} Resolved value, or values with `allItems`.\n */\n\n/**\n * A token of an arithmetic expression.\n * @typedef {{ type: 'number', value: number }\n * | { type: 'tag', index: number }\n * | { type: 'name', name: string }\n * | { type: 'punctuator', value: string }} ExpressionToken\n */\n\n/**\n * A function available in an expression.\n * @typedef {object} ExpressionFunction\n * @property {number} minArgs Minimum number of arguments.\n * @property {number} maxArgs Maximum number of arguments.\n * @property {(...args: number[]) => number} [fn] Function computing the result from the arguments.\n * Only for a function that isn’t an aggregate one.\n * @property {(values: number[]) => number | undefined} [aggregate] Function computing the result\n * from the values of the arguments, which makes it an aggregate function. `undefined` if there is\n * no result.\n * @property {boolean} [anyValue] Whether an aggregate function takes any value of a template tag\n * covering every item, rather than only numbers. The values it gets are then all `0`.\n */\n\n/**\n * Regular expression matching a token at the current position, preceded by any whitespace.\n */\nconst TOKEN_REGEX =\n  /\\s*(?:(?<number>\\d+(?:\\.\\d+)?|\\.\\d+)|(?<tag>\\0)|(?<name>[A-Za-z_]\\w*)|(?<punctuator>[-+*/%(),]))/y;\n\n/**\n * Regular expression matching a value a template tag can resolve to as an operand: a decimal\n * number, without the hexadecimal and other notations `Number()` would accept.\n */\nconst OPERAND_REGEX = /^[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[-+]?\\d+)?$/i;\n/**\n * Sum up the given values.\n * @param {number[]} values Values.\n * @returns {number} Sum.\n */\nconst sum = (values) => values.reduce((total, value) => total + value, 0);\n/**\n * Compute the average of the given values.\n * @param {number[]} values Values.\n * @returns {number | undefined} Average, or `undefined` if there is no value.\n */\nconst average = (values) => (values.length ? sum(values) / values.length : undefined);\n/**\n * Get the largest of the given values.\n * @param {number[]} values Values.\n * @returns {number | undefined} Largest value, or `undefined` if there is no value.\n */\nconst maximum = (values) => (values.length ? Math.max(...values) : undefined);\n/**\n * Get the smallest of the given values.\n * @param {number[]} values Values.\n * @returns {number | undefined} Smallest value, or `undefined` if there is no value.\n */\nconst minimum = (values) => (values.length ? Math.min(...values) : undefined);\n/**\n * Count the given values.\n * @param {number[]} values Values.\n * @returns {number} Number of values.\n */\nconst count = (values) => values.length;\n\n/**\n * Functions available in an expression, keyed by name. An aggregate function, `avg`, `count`,\n * `max`, `min` or `sum`, takes any number of arguments. A template tag passed directly to one\n * covers every item of a list, like `{{fields.lines.*.amount}}`, and its empty values are left out,\n * so an item that has yet to be filled in doesn’t empty the result. `count` counts the values,\n * whatever they are; the others compute from numbers.\n * @type {Record<string, ExpressionFunction>}\n */\nconst FUNCTIONS = {\n  abs: { minArgs: 1, maxArgs: 1, fn: Math.abs },\n  ceil: { minArgs: 1, maxArgs: 1, fn: Math.ceil },\n  floor: { minArgs: 1, maxArgs: 1, fn: Math.floor },\n  round: {\n    minArgs: 1,\n    maxArgs: 2,\n    /**\n     * Round the value to the given number of decimal places.\n     * @param {number} value Value.\n     * @param {number} [digits] Number of decimal places, which is truncated to an integer. A\n     * negative number rounds to tens, hundreds and so on.\n     * @returns {number} Rounded value.\n     */\n    fn: (value, digits = 0) => toFixed(value, Math.trunc(digits)),\n  },\n  avg: { minArgs: 1, maxArgs: Infinity, aggregate: average },\n  count: { minArgs: 1, maxArgs: Infinity, aggregate: count, anyValue: true },\n  max: { minArgs: 1, maxArgs: Infinity, aggregate: maximum },\n  min: { minArgs: 1, maxArgs: Infinity, aggregate: minimum },\n  sum: { minArgs: 1, maxArgs: Infinity, aggregate: sum },\n};\n\n/**\n * Maximum number of parsed expressions to cache.\n */\nconst PARSED_EXPRESSION_CACHE_SIZE = 100;\n/**\n * Cache of parsed expressions, keyed by the expression. A Compute field is resolved whenever\n * anything in the draft changes, while its expression only changes with the configuration.\n * @type {Map<string, ParsedExpression>}\n */\nconst parsedExpressionCache = new Map();\n\n/**\n * Split the given expression into tokens.\n * @param {string} expression Expression with its template tags replaced by `TAG_PLACEHOLDER`, so\n * the value a tag resolves to is always a single operand: a field holding `2) * (3` can’t change\n * the structure of the expression.\n * @returns {ExpressionToken[] | undefined} Tokens, or `undefined` if the expression has a character\n * that can’t start a token.\n */\nconst tokenize = (expression) => {\n  /** @type {ExpressionToken[]} */\n  const tokens = [];\n  const regex = new RegExp(TOKEN_REGEX);\n  let tagIndex = 0;\n  // Only whitespace follows the last token\n  const end = expression.trimEnd().length;\n\n  while (regex.lastIndex < end) {\n    const groups = regex.exec(expression)?.groups;\n\n    if (!groups) {\n      return undefined;\n    }\n\n    if (groups.number !== undefined) {\n      tokens.push({ type: 'number', value: Number(groups.number) });\n    } else if (groups.tag !== undefined) {\n      tokens.push({ type: 'tag', index: tagIndex });\n      tagIndex += 1;\n    } else if (groups.name !== undefined) {\n      tokens.push({ type: 'name', name: groups.name });\n    } else {\n      tokens.push({ type: 'punctuator', value: groups.punctuator });\n    }\n  }\n\n  return tokens;\n};\n\n/**\n * Build a syntax tree from the given tokens with a recursive descent parser. Multiplication,\n * division and remainder bind tighter than addition and subtraction, and operators of the same\n * precedence are evaluated from left to right.\n * @param {ExpressionToken[]} tokens Tokens.\n * @returns {{ tree: ExpressionNode | undefined, allItemsTagIndexes: Set<number> }} Syntax tree,\n * `undefined` if the tokens don’t form a valid expression, and the indexes of the template tags\n * passed directly to an aggregate function.\n */\nconst buildTree = (tokens) => {\n  let position = 0;\n  /** @type {Set<number>} */\n  const allItemsTagIndexes = new Set();\n\n  /**\n   * Consume the next token if it’s the given punctuator.\n   * @param {string} value Punctuator.\n   * @returns {boolean} Whether the token was consumed.\n   */\n  const accept = (value) => {\n    const token = tokens[position];\n\n    if (token?.type === 'punctuator' && token.value === value) {\n      position += 1;\n\n      return true;\n    }\n\n    return false;\n  };\n\n  /**\n   * Parse an addition or subtraction, which has the lowest precedence, so it’s a whole expression.\n   * It’s assigned once the functions it calls are defined, as an expression in parentheses or a\n   * function argument calls it in turn.\n   * @type {() => ExpressionNode | undefined}\n   */\n  let parseAdditive;\n\n  /**\n   * Parse a binary operation of the given operators, or a single operand of a higher precedence.\n   * @param {string[]} operators Operators.\n   * @param {() => ExpressionNode | undefined} parseOperand Function parsing an operand.\n   * @returns {ExpressionNode | undefined} Node, or `undefined` if it’s invalid.\n   */\n  const parseBinary = (operators, parseOperand) => {\n    let left = parseOperand();\n\n    while (left) {\n      const operator = operators.find(accept);\n\n      if (!operator) {\n        break;\n      }\n\n      const right = parseOperand();\n\n      left = right ? { type: 'binary', operator, left, right } : undefined;\n    }\n\n    return left;\n  };\n\n  /**\n   * Parse the arguments of a function call, after the opening parenthesis.\n   * @returns {ExpressionNode[] | undefined} Arguments, or `undefined` if they’re invalid.\n   */\n  const parseArgs = () => {\n    /** @type {ExpressionNode[]} */\n    const args = [];\n\n    if (accept(')')) {\n      return args;\n    }\n\n    do {\n      const arg = parseAdditive();\n\n      if (!arg) {\n        return undefined;\n      }\n\n      args.push(arg);\n    } while (accept(','));\n\n    return accept(')') ? args : undefined;\n  };\n\n  /**\n   * Parse a number, a template tag, a function call or an expression in parentheses.\n   * @returns {ExpressionNode | undefined} Node, or `undefined` if it’s invalid.\n   */\n  const parsePrimary = () => {\n    const token = tokens[position];\n\n    if (token?.type === 'number' || token?.type === 'tag') {\n      position += 1;\n\n      return token;\n    }\n\n    if (token?.type === 'name') {\n      position += 1;\n\n      const { name } = token;\n      const func = Object.hasOwn(FUNCTIONS, name) ? FUNCTIONS[name] : undefined;\n      const args = func && accept('(') ? parseArgs() : undefined;\n\n      if (!func || !args || args.length < func.minArgs || args.length > func.maxArgs) {\n        return undefined;\n      }\n\n      if (func.aggregate) {\n        args.forEach((arg) => {\n          if (arg.type === 'tag') {\n            allItemsTagIndexes.add(arg.index);\n          }\n        });\n      }\n\n      return { type: 'call', name, args };\n    }\n\n    if (accept('(')) {\n      const node = parseAdditive();\n\n      return node && accept(')') ? node : undefined;\n    }\n\n    return undefined;\n  };\n\n  /**\n   * Parse a unary plus or minus, or a primary expression.\n   * @returns {ExpressionNode | undefined} Node, or `undefined` if it’s invalid.\n   */\n  const parseUnary = () => {\n    const operator = ['-', '+'].find(accept);\n\n    if (!operator) {\n      return parsePrimary();\n    }\n\n    const operand = parseUnary();\n\n    return operand ? { type: 'unary', operator, operand } : undefined;\n  };\n\n  /**\n   * Parse a multiplication, division or remainder.\n   * @returns {ExpressionNode | undefined} Node, or `undefined` if it’s invalid.\n   */\n  const parseMultiplicative = () => parseBinary(['*', '/', '%'], parseUnary);\n\n  /**\n   * Parse an addition or subtraction.\n   * @returns {ExpressionNode | undefined} Node, or `undefined` if it’s invalid.\n   */\n  parseAdditive = () => parseBinary(['+', '-'], parseMultiplicative);\n\n  const tree = parseAdditive();\n\n  // Any token left over, like the second number in `1 2`, makes the expression invalid\n  return { tree: position === tokens.length ? tree : undefined, allItemsTagIndexes };\n};\n\n/**\n * Parse the given arithmetic expression, such as `{{fields.price}} * {{fields.quantity}}`. It can\n * have numbers, template tags, the `+`, `-`, `*`, `/` and `%` operators, parentheses, the `abs`,\n * `ceil`, `floor` and `round` functions and the `avg`, `count`, `max`, `min` and `sum` aggregate\n * functions. The result is cached and shared between callers.\n * @param {string} expression Expression.\n * @returns {ParsedExpression} Parsed expression.\n */\nexport const parseExpression = (expression) =>\n  getOrCreateBounded(\n    parsedExpressionCache,\n    expression,\n    () => {\n      const { tags: contents, literals } = splitTemplateTags(expression);\n      const tokens = tokenize(literals.join(TAG_PLACEHOLDER));\n\n      const { tree, allItemsTagIndexes } = tokens\n        ? buildTree(tokens)\n        : { tree: undefined, allItemsTagIndexes: new Set() };\n\n      return {\n        tree,\n        tags: contents.map((content, index) => ({\n          content,\n          allItems: allItemsTagIndexes.has(index),\n        })),\n      };\n    },\n    PARSED_EXPRESSION_CACHE_SIZE,\n  );\n\n/**\n * Normalize the value a template tag has resolved to into a string without surrounding whitespace.\n * @param {unknown} value Resolved value.\n * @returns {string} String. Empty for `null` and `undefined`.\n */\nconst normalizeValue = (value) => String(value ?? '').trim();\n\n/**\n * Convert the value a template tag has resolved to into an operand.\n * @param {any} value Resolved value.\n * @returns {number | undefined} Number, or `undefined` if the value is empty or isn’t a number.\n */\nconst toOperand = (value) => {\n  const string = normalizeValue(value);\n\n  return OPERAND_REGEX.test(string) ? Number(string) : undefined;\n};\n\n/**\n * Check whether the given resolved value is empty.\n * @param {unknown} value Value.\n * @returns {boolean} Result.\n */\nconst isEmptyValue = (value) => !normalizeValue(value);\n\n/**\n * Evaluate a call of an aggregate function.\n * @param {ExpressionFunction} func Function, which has the `aggregate` property.\n * @param {ExpressionNode[]} args Arguments.\n * @param {ExpressionOperand[]} operands Values of the template tags, by index.\n * @param {(node: ExpressionNode) => number | undefined} evaluate Function evaluating an argument\n * other than a template tag covering every item.\n * @returns {number | undefined} Result, or `undefined` if a value isn’t a number, or there is no\n * value to compute the average, the maximum or the minimum of.\n */\nconst evaluateAggregate = (func, args, operands, evaluate) => {\n  /** @type {number[]} */\n  const values = [];\n\n  // eslint-disable-next-line no-restricted-syntax\n  for (const arg of args) {\n    const operand = arg.type === 'tag' ? operands[arg.index] : undefined;\n\n    if (Array.isArray(operand)) {\n      // eslint-disable-next-line no-restricted-syntax\n      for (const value of operand.filter((_value) => !isEmptyValue(_value))) {\n        // Anything counts, while the others need a number\n        const number = func.anyValue ? 0 : toOperand(value);\n\n        if (number === undefined) {\n          return undefined;\n        }\n\n        values.push(number);\n      }\n    } else {\n      const value = evaluate(arg);\n\n      if (value === undefined) {\n        return undefined;\n      }\n\n      values.push(value);\n    }\n  }\n\n  return /** @type {NonNullable<ExpressionFunction['aggregate']>} */ (func.aggregate)(values);\n};\n\n/**\n * Evaluate the given syntax tree.\n * @param {ExpressionNode} node Node.\n * @param {ExpressionOperand[]} operands Values of the template tags, by index.\n * @returns {number | undefined} Result, or `undefined` if an operand is missing.\n */\nconst evaluateNode = (node, operands) => {\n  if (node.type === 'number') {\n    return node.value;\n  }\n\n  if (node.type === 'tag') {\n    // A tag covering every item is only passed to an aggregate function, which reads it itself\n    return /** @type {number | undefined} */ (operands[node.index]);\n  }\n\n  if (node.type === 'unary') {\n    const operand = evaluateNode(node.operand, operands);\n\n    if (operand === undefined) {\n      return undefined;\n    }\n\n    return node.operator === '-' ? -operand : operand;\n  }\n\n  if (node.type === 'call') {\n    const func = FUNCTIONS[node.name];\n\n    if (func.aggregate) {\n      return evaluateAggregate(func, node.args, operands, (arg) => evaluateNode(arg, operands));\n    }\n\n    const args = node.args.map((arg) => evaluateNode(arg, operands));\n\n    return args.includes(undefined)\n      ? undefined\n      : /** @type {NonNullable<ExpressionFunction['fn']>} */ (func.fn)(\n          .../** @type {number[]} */ (args),\n        );\n  }\n\n  const left = evaluateNode(node.left, operands);\n  const right = evaluateNode(node.right, operands);\n\n  if (left === undefined || right === undefined) {\n    return undefined;\n  }\n\n  switch (node.operator) {\n    case '+':\n      return left + right;\n    case '-':\n      return left - right;\n    case '*':\n      return left * right;\n    case '/':\n      return left / right;\n    default:\n      return left % right;\n  }\n};\n\n/**\n * Evaluate the given arithmetic expression. Each template tag in it is resolved with the given\n * function, and the value it resolves to is used as a number.\n * @param {string} expression Expression. See {@link parseExpression} for the syntax.\n * @param {ExpressionTagResolver} resolveTag Function resolving a template tag.\n * @returns {number | undefined} Result. `undefined` if the expression is invalid, a tag resolves to\n * an empty value or something other than a number, or the result isn’t a finite number, as with a\n * division by zero.\n */\nexport const evaluateExpression = (expression, resolveTag) => {\n  const { tree, tags } = parseExpression(expression);\n\n  if (!tree) {\n    return undefined;\n  }\n\n  const result = evaluateNode(\n    tree,\n    tags.map(({ content, allItems }) =>\n      allItems\n        ? [resolveTag(content, { allItems })].flat()\n        : toOperand(resolveTag(content, { allItems })),\n    ),\n  );\n\n  return result !== undefined && Number.isFinite(result) ? result : undefined;\n};\n","import { generateUUID } from '@sveltia/utils/crypto';\nimport { escapeRegExp } from '@sveltia/utils/string';\n\nimport { FIELD_TAG_PREFIX_REGEX, UUID_TYPES } from '$lib/services/common/template/constants';\nimport { processNestedTemplates } from '$lib/services/common/template/nested';\nimport { replaceTemplateTags, splitTemplateTags } from '$lib/services/common/template/tags';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { applyTransformations, parseTransformations } from '$lib/services/common/transformations';\nimport { getListItemIndexes, indexListItems } from '$lib/services/contents/entry/content-index';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getFieldDisplayValue } from '$lib/services/contents/entry/values';\nimport { evaluateExpression } from '$lib/services/contents/fields/compute/expression';\nimport {\n  getNumberFormatter,\n  isFloatType,\n  isStringOutput,\n  yieldsNumber,\n} from '$lib/services/contents/fields/number/helpers';\nimport { getListFormatter } from '$lib/services/contents/i18n';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { isNumeric, roundFloatError, toFixed } from '$lib/services/utils/number';\n\n/**\n * @import {\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * ListItemIndex,\n * StringTransformation,\n * } from '$lib/types/private';\n * @import { ComputeField, Field, FieldKeyPath, LocaleCode } from '$lib/types/public';\n * @import { ListFormatter } from '$lib/services/contents/i18n';\n */\n\n/**\n * UUIDs generated for the Compute fields of a locale’s content, keyed by the content and then by\n * the field’s key path, in the order of the UUID tags in the template. The content maps live as\n * long as the draft does, so a value is generated once per draft; see {@link getUuids}.\n * @type {WeakMap<FlattenedEntryContent, Map<FieldKeyPath, string[]>>}\n */\nconst generatedUuidMap = new WeakMap();\n\n/**\n * Get the index of the list item the field is in, which is the last numeric segment of the given\n * key path: `2` for `authors.2.slug`, for `lines.2.meta.n` in an Object field of a list item, and\n * for `lines.2`, the item itself of a list with a single subfield. In a nested list, it’s the index\n * of the innermost item, e.g. `3` for `sections.1.authors.3.slug`.\n * @param {FieldKeyPath} keyPath Key path of the field.\n * @returns {number | undefined} Index, or `undefined` if the field is not in a list item.\n * @see https://github.com/sveltia/sveltia-cms/issues/172\n */\nexport const getListIndex = (keyPath) => {\n  const index = keyPath.split('.').findLast(isNumeric);\n\n  return index === undefined ? undefined : Number(index);\n};\n\n/**\n * Check whether the given template tag is a UUID tag.\n * @param {string} tagName Tag name.\n * @returns {boolean} Result.\n */\nconst isUuidTag = (tagName) => Object.hasOwn(UUID_TYPES, tagName);\n\n/**\n * A UUID tag found in a value template.\n * @typedef {object} UuidTagInfo\n * @property {string} tagName Tag name: `uuid`, `uuid_short` or `uuid_shorter`.\n * @property {boolean} extractable Whether the UUID can be read back from a value the template has\n * resolved to. Only a tag at either edge of the template can, meaning one before the first or after\n * the last tag of another kind; see {@link parseUuidTags}.\n */\n\n/**\n * Find the UUID tags in the given value template.\n *\n * The returned regular expression matches a value the template has resolved to, capturing the UUIDs\n * that can be told apart from the rest. Any tag of another kind can resolve to anything, so a UUID\n * tag placed between such tags with nothing but their values around it is ambiguous — the UUID\n * could start anywhere in a run of hexadecimal characters — and every such tag along with\n * everything from the first tag of another kind to the last is matched by a single wildcard\n * instead. The single wildcard also keeps the matching linear: one wildcard per tag would make a\n * value that doesn’t match, such as a long one saved before a UUID tag was added to the template,\n * take polynomial time to reject.\n * @param {string} valueTemplate Value template.\n * @returns {{ uuidTags: UuidTagInfo[], regex: RegExp }} UUID tags in the order they appear, and the\n * regular expression, which captures the UUID of each extractable tag in that order.\n */\nconst parseUuidTags = (valueTemplate) => {\n  const { tags, literals: rawLiterals } = splitTemplateTags(valueTemplate);\n  const tagNames = tags.map((placeholder) => parseTransformations(placeholder).value);\n  const literals = rawLiterals.map(escapeRegExp);\n  const firstOtherIndex = tagNames.findIndex((tagName) => !isUuidTag(tagName));\n  const lastOtherIndex = tagNames.findLastIndex((tagName) => !isUuidTag(tagName));\n\n  /**\n   * Build the part of the regular expression covering the given tags and the literal text around\n   * them. The literal at index `i` is the text before tag `i`, and the last one is the trailing\n   * text.\n   * @param {number} start Index of the first tag.\n   * @param {number} end Index after the last tag.\n   * @returns {string} Regular expression source.\n   */\n  const build = (start, end) =>\n    tagNames\n      .slice(start, end)\n      .map((tagName, i) => `${literals[start + i]}(${UUID_TYPES[tagName].pattern})`)\n      .join('') + literals[end];\n\n  const source =\n    firstOtherIndex === -1\n      ? build(0, tagNames.length)\n      : `${build(0, firstOtherIndex)}[\\\\s\\\\S]*${build(lastOtherIndex + 1, tagNames.length)}`;\n\n  const uuidTags = tagNames\n    .map((tagName, index) => ({\n      tagName,\n      extractable: firstOtherIndex === -1 || index < firstOtherIndex || index > lastOtherIndex,\n    }))\n    .filter(({ tagName }) => isUuidTag(tagName));\n\n  // An `upper` transformation is the one way a UUID can change while staying recognizable\n  return { uuidTags, regex: new RegExp(`^${source}$`, 'i') };\n};\n\n/**\n * Check whether the given value template holds a UUID tag: `{{uuid}}`, `{{uuid_short}}` or\n * `{{uuid_shorter}}`.\n * @param {string} [valueTemplate] Value template.\n * @returns {boolean} Result.\n */\nexport const hasUuidTag = (valueTemplate = '') => parseUuidTags(valueTemplate).uuidTags.length > 0;\n\n/**\n * Get the UUIDs for the UUID tags in the given value template.\n *\n * A UUID has to survive the field being resolved again, which happens whenever anything in the\n * draft changes, or an existing entry would lose the UUID it was saved with and a new entry would\n * get a different one on every keystroke — and, since a changed value triggers another resolution,\n * never settle. So the UUIDs are first taken from the field’s current value, which keeps them\n * across a reload of the entry, a backup restore or a list item being moved. A UUID that can’t be\n * read from the value — because the value is empty, a transformation has altered the UUID’s shape,\n * or the tag sits between tags of another kind — is the one generated for the field earlier in the\n * draft’s life, or a new one if there is none yet.\n * @param {object} args Arguments.\n * @param {string} args.valueTemplate Value template.\n * @param {FieldKeyPath} args.keyPath Key path of the field.\n * @param {FlattenedEntryContent} args.valueMap Flattened entry content the template is resolved\n * against.\n * @returns {string[]} UUIDs in the order of the tags. Empty if the template has no UUID tag.\n */\nconst getUuids = ({ valueTemplate, keyPath, valueMap }) => {\n  const { uuidTags, regex } = parseUuidTags(valueTemplate);\n\n  if (!uuidTags.length) {\n    return [];\n  }\n\n  const currentValue = valueMap[keyPath];\n\n  const extractedUuids =\n    typeof currentValue === 'string' ? currentValue.match(regex)?.slice(1) : undefined;\n\n  if (extractedUuids?.length === uuidTags.length) {\n    return extractedUuids;\n  }\n\n  const cache = getOrCreate(generatedUuidMap, valueMap, () => new Map());\n  let generatedUuids = cache.get(keyPath);\n\n  if (generatedUuids?.length !== uuidTags.length) {\n    generatedUuids = uuidTags.map(({ tagName }) => generateUUID(UUID_TYPES[tagName].length));\n    cache.set(keyPath, generatedUuids);\n  }\n\n  if (!extractedUuids) {\n    return generatedUuids;\n  }\n\n  let extractedIndex = 0;\n\n  return uuidTags.map(({ extractable }, index) => {\n    if (!extractable) {\n      return /** @type {string[]} */ (generatedUuids)[index];\n    }\n\n    const uuid = extractedUuids[extractedIndex];\n\n    extractedIndex += 1;\n\n    return uuid;\n  });\n};\n\n/**\n * Convert the result of a Compute field’s arithmetic expression into the value to be stored,\n * according to the field’s `value_type`. A result with a fraction is rounded to 15 significant\n * digits, so the error of binary floating-point arithmetic doesn’t end up in the file, e.g. `0.3`\n * rather than `0.30000000000000004` for `0.1 * 3`, while an integer is kept as is, as rounding\n * would change a large one. With an integer type, the result is then rounded to the nearest\n * integer like the `round()` function of an expression does, with halves away from zero, e.g. `101`\n * for `1.005 * 100`, which is `100.49999999999999`, and `-2` for `-1.5`.\n * @param {number | undefined} result Result of the expression. `undefined` if it can’t be computed.\n * @param {ComputeField} fieldConfig Field configuration.\n * @returns {string | number | null} Value to be stored. A result that can’t be computed, or an\n * integer beyond the range JavaScript can represent exactly, is stored like an empty Number field:\n * `null` for the number types, or an empty string for the string types.\n */\nexport const getNumericValue = (result, fieldConfig) => {\n  // The value type means the same as a Number field’s, including a custom one, which is treated\n  // like `int/string`\n  const stringOutput = isStringOutput(fieldConfig);\n  const integer = !isFloatType(fieldConfig);\n\n  // Adding zero turns `-0` into `0`\n  const number =\n    result === undefined ? undefined : (integer ? toFixed(result, 0) : roundFloatError(result)) + 0;\n\n  if (number === undefined || (integer && !Number.isSafeInteger(number))) {\n    return stringOutput ? '' : null;\n  }\n\n  return stringOutput ? String(number) : number;\n};\n\n/**\n * Format the given value of a Compute field for display. A number the field yields is formatted\n * like a Number field value, e.g. `1,234.5` for `1234.5` in English.\n * @param {object} args Arguments.\n * @param {string | number | null | undefined} args.value Field value.\n * @param {ComputeField} args.fieldConfig Field configuration.\n * @param {LocaleCode | undefined} args.canonicalLocale Canonical locale code.\n * @returns {string} Formatted value. Empty if the value is empty. A value that isn’t a number, like\n * one saved before the `value_type` option was changed, is returned as is.\n */\nexport const formatComputedValue = ({ value, fieldConfig, canonicalLocale }) => {\n  const string = String(value ?? '');\n  const number = Number(value);\n\n  return yieldsNumber(fieldConfig) && string.trim() && Number.isFinite(number)\n    ? getNumberFormatter(canonicalLocale).format(number)\n    : string;\n};\n\n/**\n * Where a `{{fields.*}}` tag of a Compute field is resolved: the content and the rich text editor\n * component, if any, the key path refers to.\n * @typedef {object} FieldTagSource\n * @property {FlattenedEntryContent} valueMap Content holding the field value.\n * @property {string} [componentName] Name of the component whose field the key path refers to.\n * @property {FieldKeyPath} ownKeyPath Key path of the Compute field within the content, or of the\n * rich text field holding the field’s component, which tells the list items the field is in.\n */\n\n/**\n * Indexes of the list items in the content a `{{fields.*}}` tag is resolved against, keyed by the\n * content. A snapshot of the draft is resolved against by every Compute field of the draft, so the\n * index is built once for all of them.\n * @type {WeakMap<FlattenedEntryContent, ListItemIndex>}\n */\nconst listItemIndexMap = new WeakMap();\n\n/**\n * Resolve the `*` wildcards in the key path of a `{{fields.*}}` tag, like `lines.*.price`. A `*`\n * stands for the current item: the item of that list the Compute field is in, so a field at\n * `lines.2.amount` gets `lines.2.price`. In an aggregate function, the last `*` stands for every\n * item instead, and so does any other `*` that has no current item, so `orders.*.lines.*.amount`\n * gives the amount of every line of the current order, or of every order outside one.\n * @param {object} args Arguments.\n * @param {FieldKeyPath} args.fieldKeyPath Key path of the tag.\n * @param {FieldKeyPath} args.ownKeyPath Key path of the Compute field within the same content.\n * @param {boolean} args.allItems Whether the tag is an argument of an aggregate function.\n * @param {FlattenedEntryContent} args.valueMap Content the tag is resolved against.\n * @returns {FieldKeyPath[]} Key paths without wildcards, in the order of the items. The key path\n * itself if it has no wildcard. Empty if a `*` has no current item outside an aggregate function.\n */\nexport const expandWildcards = ({ fieldKeyPath, ownKeyPath, allItems, valueMap }) => {\n  const segments = fieldKeyPath.split('.');\n  const lastWildcardIndex = segments.lastIndexOf('*');\n\n  if (lastWildcardIndex === -1) {\n    return [fieldKeyPath];\n  }\n\n  const ownSegments = ownKeyPath.split('.');\n  /** @type {string[][]} */\n  let paths = [[]];\n\n  segments.forEach((segment, index) => {\n    if (segment !== '*') {\n      paths.forEach((path) => path.push(segment));\n\n      return;\n    }\n\n    paths = paths.flatMap((path) => {\n      const expand = allItems && index === lastWildcardIndex;\n      const ownIndex = ownSegments[index];\n\n      // The field is in an item of this list when its key path starts with the list’s\n      const isCurrentItem =\n        !expand &&\n        isNumeric(ownIndex ?? '') &&\n        path.every((pathSegment, segmentIndex) => pathSegment === ownSegments[segmentIndex]);\n\n      if (isCurrentItem) {\n        return [[...path, ownIndex]];\n      }\n\n      if (!allItems) {\n        return [];\n      }\n\n      const listIndex = getOrCreate(listItemIndexMap, valueMap, () => indexListItems(valueMap));\n\n      return getListItemIndexes(listIndex, path.join('.')).map((itemIndex) => [\n        ...path,\n        String(itemIndex),\n      ]);\n    });\n  });\n\n  return paths.map((path) => path.join('.'));\n};\n\n/**\n * Get the values of a rich text editor component instance, without its key path prefix.\n * @param {FlattenedEntryContent} valueMap Content of the `extraValues` store.\n * @param {string} keyPathPrefix Key path prefix of the component instance, e.g. `body:c12:`.\n * @returns {FlattenedEntryContent} Component values, e.g. `heading` for `body:c12:heading`.\n */\nconst getComponentValues = (valueMap, keyPathPrefix) =>\n  Object.fromEntries(\n    Object.entries(valueMap)\n      .filter(([key]) => key.startsWith(keyPathPrefix))\n      .map(([key, value]) => [key.slice(keyPathPrefix.length), value]),\n  );\n\n/**\n * What a Compute field’s `value` template is resolved against, shared by the functions resolving\n * its template tags; see {@link getComputedValue} for the properties taken from its arguments.\n * @typedef {object} ComputeContext\n * @property {FieldKeyPath} keyPath Key path of the field.\n * @property {InternalLocaleCode} locale Locale code.\n * @property {FlattenedEntryContent} valueMap Flattened entry content, or the content of the\n * `extraValues` store for a field of a rich text editor component.\n * @property {string} collectionName Collection name.\n * @property {string} [fileName] Collection file name.\n * @property {boolean} isIndexFile Whether the entry is the collection’s special index file.\n * @property {string} keyPathPrefix Key path prefix of the rich text editor component instance the\n * field belongs to, or an empty string.\n * @property {FlattenedEntryContent} entryValueMap Flattened entry content, for a field of a rich\n * text editor component.\n * @property {string | undefined} componentName Name of the component the field belongs to.\n * @property {boolean} numeric Whether the template is an arithmetic expression.\n * @property {ListFormatter} listFormatter Formatter for a list of values.\n * @property {FlattenedEntryContent} [componentValues] Values of the component instance, without\n * the key path prefix, once {@link getFieldTagSource} has needed them.\n */\n\n/**\n * Get the content and the component the given key path refers to.\n * @param {ComputeContext} context Context.\n * @param {FieldKeyPath} fieldKeyPath Key path from a `{{fields.*}}` tag.\n * @returns {FieldTagSource} Source.\n */\nconst getFieldTagSource = (context, fieldKeyPath) => {\n  const { keyPath, valueMap, keyPathPrefix, componentName, collectionName, fileName, isIndexFile } =\n    context;\n\n  if (!keyPathPrefix) {\n    return { valueMap, ownKeyPath: keyPath };\n  }\n\n  const getFieldArgs = { collectionName, fileName, isIndexFile, keyPath: fieldKeyPath };\n\n  if (componentName && getField({ ...getFieldArgs, componentName })) {\n    context.componentValues ??= getComponentValues(valueMap, keyPathPrefix);\n\n    return {\n      valueMap: context.componentValues,\n      componentName,\n      ownKeyPath: keyPath.slice(keyPathPrefix.length),\n    };\n  }\n\n  // The component sits in the rich text field whose key path starts the prefix, e.g.\n  // `lines.2.body` for `lines.2.body:c12:`, which is in the same list items as the component\n  return { valueMap: context.entryValueMap, ownKeyPath: keyPathPrefix.split(':')[0] };\n};\n\n/**\n * Check whether the stored value of the given field is inserted as is rather than its display\n * value. That’s a number, including the value of a Compute field that yields one, and, in an\n * arithmetic expression, the stored value of a Select or Relation field, e.g. `5` rather than its\n * label `Express (5)`, including that of an item of a multiple one, which has no display value.\n * @param {Field | undefined} fieldConfig Configuration of the field the tag refers to.\n * @param {boolean} numeric Whether the template is an arithmetic expression.\n * @returns {boolean} Result.\n */\nconst usesRawValue = (fieldConfig, numeric) =>\n  !!fieldConfig &&\n  (yieldsNumber(fieldConfig) ||\n    (numeric && (fieldConfig.widget === 'select' || fieldConfig.widget === 'relation')));\n\n/**\n * Resolve a `{{fields.*}}` tag for a single field.\n * @param {ComputeContext} context Context.\n * @param {FieldKeyPath} fieldKeyPath Key path of the field, without any `*`, unless it couldn’t be\n * resolved.\n * @param {FieldTagSource} source Where the tag is resolved.\n * @param {StringTransformation[]} transformations Transformations of the tag.\n * @returns {string} Resolved value.\n */\nconst resolveFieldTag = (context, fieldKeyPath, source, transformations) => {\n  const { locale, collectionName, fileName, isIndexFile, numeric, listFormatter } = context;\n  const { valueMap: sourceValueMap, componentName: sourceComponentName } = source;\n\n  const getFieldArgs = {\n    collectionName,\n    fileName,\n    componentName: sourceComponentName,\n    valueMap: sourceValueMap,\n    keyPath: fieldKeyPath,\n    isIndexFile,\n  };\n\n  // Let `getFieldDisplayValue()` apply the transformations, so they get the raw value and the field\n  // configuration: a boolean for `ternary` rather than `'false'`, which is truthy, and the stored\n  // date for `date` rather than the localized display value. A value missing from the content, like\n  // that of a List field, which is stored under its item key paths, or an unset field, would come\n  // back empty whatever the transformations, breaking `default`, so the transformations are applied\n  // to its display value instead.\n  const rawValue = sourceValueMap[fieldKeyPath];\n  const hasRawValue = rawValue !== undefined;\n\n  // A number is inserted as stored rather than formatted for display, so a template like\n  // `/p/{{fields.sku}}` doesn’t give `/p/123,456`, and an arithmetic expression can use it\n  if (hasRawValue) {\n    const sourceFieldConfig = getField(getFieldArgs);\n\n    if (usesRawValue(sourceFieldConfig, numeric)) {\n      // The transformations get a string as they would get the display value, so `0` isn’t taken\n      // as empty by `default`\n      const value = String(rawValue ?? '');\n\n      return transformations.length\n        ? applyTransformations({ fieldConfig: sourceFieldConfig, value, transformations, locale })\n        : value;\n    }\n  }\n\n  const fieldValue = getFieldDisplayValue({\n    ...getFieldArgs,\n    locale,\n    transformations: hasRawValue ? transformations : undefined,\n  });\n\n  const value = Array.isArray(fieldValue) ? listFormatter.format(fieldValue) : String(fieldValue);\n\n  return !hasRawValue && transformations.length\n    ? applyTransformations({ value, transformations, locale })\n    : value;\n};\n\n/**\n * Resolve the `value` template of a Compute field.\n * @param {object} args Arguments.\n * @param {ComputeField} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Key path of the field.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FlattenedEntryContent} args.valueMap Flattened entry content the template is resolved\n * against. The field’s own current value is read from it to keep any UUID it holds.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @param {string} [args.keyPathPrefix] Key path prefix of the rich text editor component instance\n * the field belongs to, e.g. `body:c12:`, in which case {@link args.valueMap} is the content of the\n * `extraValues` store. A `{{fields.*}}` tag then refers to a field of the component, or, if the\n * component has no such field, to a field of the entry.\n * @param {FlattenedEntryContent} [args.entryValueMap] Flattened entry content, for a field of a\n * rich text editor component to refer to a field of the entry.\n * @returns {string | number | null} Computed value. With a numeric `value_type`, see\n * {@link getNumericValue}.\n */\nexport const getComputedValue = ({\n  fieldConfig,\n  keyPath,\n  locale,\n  valueMap,\n  collectionName,\n  fileName,\n  isIndexFile = false,\n  keyPathPrefix = '',\n  entryValueMap = {},\n}) => {\n  const { value: valueTemplate = '' } = fieldConfig;\n  const numeric = yieldsNumber(fieldConfig);\n\n  // A lone `{{index}}` yields the number itself rather than its string representation, so that the\n  // value is written to the file as a number. A numeric `value_type` decides the type itself\n  if (!numeric && valueTemplate === '{{index}}') {\n    return getListIndex(keyPath) ?? '';\n  }\n\n  // A UUID can’t be an operand of an arithmetic expression, and the configuration parser reports\n  // one used there, so none is generated\n  const uuids = numeric ? [] : getUuids({ valueTemplate, keyPath, valueMap });\n  let uuidIndex = 0;\n\n  /** @type {ComputeContext} */\n  const context = {\n    keyPath,\n    locale,\n    valueMap,\n    collectionName,\n    fileName,\n    isIndexFile,\n    keyPathPrefix,\n    entryValueMap,\n    componentName: keyPathPrefix ? valueMap[`${keyPathPrefix}__sc_component_name`] : undefined,\n    numeric,\n    listFormatter: getListFormatter(locale),\n  };\n\n  /**\n   * Resolve a template tag of the value template.\n   * @param {string} placeholder Tag content, e.g. `fields.title | upper`.\n   * @param {{ allItems?: boolean }} [options] Options. With `allItems`, the tag is an argument of\n   * an aggregate function in an arithmetic expression, and the last `*` in a `{{fields.*}}` tag\n   * stands for every item of the list rather than the current one.\n   * @returns {string | string[]} Resolved value, or a list of values with `allItems`.\n   */\n  const resolvePlaceholder = (placeholder, { allItems = false } = {}) => {\n    const { value: tagName, transformations: parsedTransformations } =\n      parseTransformations(placeholder);\n\n    if (tagName === 'index') {\n      const value = String(getListIndex(keyPath) ?? '');\n\n      return allItems ? [value] : value;\n    }\n\n    // Resolve the tags in the transformation arguments like the tag itself, e.g. `{{fields.title}}`\n    // in `default('{{fields.title}}')`. A UUID tag there resolves to nothing, as the UUIDs are\n    // counted only in the template itself and one there would shift the others\n    const transformations = processNestedTemplates(parsedTransformations, (innerTag) =>\n      isUuidTag(parseTransformations(innerTag).value)\n        ? ''\n        : /** @type {string} */ (resolvePlaceholder(innerTag)),\n    );\n\n    if (FIELD_TAG_PREFIX_REGEX.test(tagName)) {\n      const fieldKeyPath = stripFieldTagPrefix(tagName);\n      const source = getFieldTagSource(context, fieldKeyPath);\n\n      const fieldKeyPaths = expandWildcards({\n        fieldKeyPath,\n        ownKeyPath: source.ownKeyPath,\n        allItems,\n        valueMap: source.valueMap,\n      });\n\n      if (allItems) {\n        return fieldKeyPaths.map((_keyPath) =>\n          resolveFieldTag(context, _keyPath, source, transformations),\n        );\n      }\n\n      // A `*` that doesn’t stand for the current item resolves to nothing, as it did before\n      // wildcards were supported\n      return resolveFieldTag(context, fieldKeyPaths[0] ?? fieldKeyPath, source, transformations);\n    }\n\n    if (!isUuidTag(tagName)) {\n      return allItems ? [] : '';\n    }\n\n    let value = uuids[uuidIndex];\n\n    uuidIndex += 1;\n\n    if (transformations.length) {\n      value = applyTransformations({ value, transformations, locale });\n    }\n\n    return allItems ? [value] : value;\n  };\n\n  if (numeric) {\n    return getNumericValue(evaluateExpression(valueTemplate, resolvePlaceholder), fieldConfig);\n  }\n\n  return replaceTemplateTags(\n    valueTemplate,\n    (_match, placeholder) => /** @type {string} */ (resolvePlaceholder(placeholder)),\n  );\n};\n","<!--\n  @component\n  Implement the preview for a Compute field.\n-->\n<script>\n  import { formatComputedValue } from '$lib/services/contents/fields/compute/helpers';\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { ComputeField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ComputeField} fieldConfig Field configuration.\n   * @property {string | number | null | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, fieldConfig, currentValue } = $props();\n\n  const canonicalLocale = $derived(getCanonicalLocale(locale));\n</script>\n\n<p lang={canonicalLocale} dir={getDirection(locale)}>\n  {formatComputedValue({ value: currentValue, fieldConfig, canonicalLocale })}\n</p>\n","<!--\n  @component Cloudinary media library panel component. This is a minimal implementation of the\n  Cloudinary Media Library widget embedded in an iframe. It sets up the iframe source URL with\n  necessary query parameters and handles communication with the iframe via `postMessage`. This way,\n  we don’t need to load the third-party script directly in our application.\n  @see https://cloudinary.com/documentation/media_library_widget\n  @see https://media-library.cloudinary.com/global/all.js\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, EmptyState } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import {\n    activated,\n    CONFIG_PROPS,\n    CONSOLE_BASE_URL,\n    consoleLoaded,\n    dialogOpen,\n    FRAME_ORIGIN,\n    getMergedLibraryOptions,\n    parseMessage,\n  } from '$lib/services/integrations/media-libraries/cloud/cloudinary';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @import { MediaLibraryAssetKind, SelectedResource } from '$lib/types/private';\n   * @import { CloudinaryMediaLibrary, MediaField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {MediaField} [fieldConfig] File/Image field configuration.\n   * @property {MediaLibraryAssetKind} [kind] Asset kind.\n   * @property {boolean} [multiple] Whether to allow selecting multiple assets.\n   * @property {boolean} [hidden] Whether the panel is hidden.\n   * @property {(resources: SelectedResource[]) => void} onSelect Custom `Select` event handler.\n   */\n\n  /** @type {Props} */\n  let { fieldConfig, kind, multiple = false, hidden = false, onSelect } = $props();\n\n  // The merged options always have the `config` object\n  const libOptions = $derived(\n    /** @type {CloudinaryMediaLibrary & { config: Record<string, any> }} */ (\n      getMergedLibraryOptions(fieldConfig)\n    ),\n  );\n\n  /** @type {HTMLIFrameElement | null} */\n  let iframe = null;\n\n  /**\n   * Send configuration message to the Cloudinary Media Library iframe.\n   */\n  const sendMessage = () => {\n    const { folder } = libOptions.config;\n\n    const config = {\n      ...Object.fromEntries(\n        Object.entries(libOptions.config).filter(([k]) => CONFIG_PROPS.includes(k)),\n      ),\n      multiple,\n      max_files: fieldConfig?.max ?? libOptions.config.max_files ?? 20,\n      folder: {\n        path: folder?.path ?? '',\n        // The resource type filters the view. The configured one wins; otherwise an Image field\n        // shows images only, while a File field shows every type, as a PDF file is an image and a\n        // video file a video on Cloudinary. An `undefined` type is left out of the message\n        resource_type: folder?.resource_type ?? kind,\n      },\n    };\n\n    const data = {\n      type: 'ML_WIDGET_SHOW',\n      data: { mlId: iframe?.dataset?.mlId, config },\n    };\n\n    // eslint-disable-next-line no-console\n    console.debug('Cloudinary Panel sending message:', data);\n\n    iframe?.contentWindow?.postMessage(JSON.stringify(data), FRAME_ORIGIN);\n  };\n\n  /**\n   * Handle asset insertion from the Cloudinary Media Library.\n   * @param {{ assets: { public_id: string; format?: string; secure_url: string; derived?: {\n   * secure_url: string }[] }[] }} assets The inserted assets data.\n   */\n  const onInsert = ({ assets }) => {\n    const {\n      output_filename_only: outputFilenameOnly = false,\n      use_transformations: useTransformations = true,\n    } = libOptions;\n\n    /** @type {SelectedResource[]} */\n    const resources = assets.map((asset) => {\n      const url = asset.secure_url;\n\n      if (outputFilenameOnly) {\n        // Like Decap CMS, output the public ID, which includes the folder, with the format as the\n        // extension. A raw file has no format, as its public ID ends with the extension already\n        const { public_id: publicId, format } = asset;\n\n        return { url: format ? `${publicId}.${format}` : publicId };\n      }\n\n      if (useTransformations) {\n        return { url: asset.derived?.[0]?.secure_url ?? url };\n      }\n\n      return { url };\n    });\n\n    onSelect(resources);\n  };\n\n  /**\n   * Handle messages received from the Cloudinary Media Library iframe. The `consoleLoaded` message\n   * is handled by the iframe component instead, as it can arrive before this panel is mounted.\n   * @param {MessageEvent} event The message event.\n   */\n  const onMessage = (event) => {\n    const data = parseMessage(event);\n\n    if (!data) {\n      return;\n    }\n\n    // eslint-disable-next-line no-console\n    console.debug('Cloudinary Panel received message:', data);\n\n    if (data.type === 'login' && data.consoleDomain) {\n      activated.current = true;\n      dialogOpen.current = true;\n    }\n\n    if (data.type === 'ML_WIDGET_INSERT_DATA') {\n      dialogOpen.current = false;\n      onInsert(data.data);\n    }\n\n    if (data.type === 'ML_WIDGET_HIDE') {\n      dialogOpen.current = false;\n    }\n  };\n\n  onMount(() => {\n    iframe = document.querySelector('iframe#cloudinary-iframe');\n    window.addEventListener('message', onMessage);\n\n    return () => {\n      window.removeEventListener('message', onMessage);\n    };\n  });\n\n  $effect(() => {\n    if (libOptions && consoleLoaded.current) {\n      sendMessage();\n    }\n  });\n</script>\n\n{#if !hidden}\n  <EmptyState>\n    {#if activated.current}\n      <Button\n        variant=\"primary\"\n        label={_('cloud_storage.cloudinary.open_library')}\n        onclick={() => {\n          dialogOpen.current = true;\n        }}\n      />\n    {:else}\n      <Button\n        variant=\"primary\"\n        label={_('cloud_storage.cloudinary.activate.button_label')}\n        onclick={() => {\n          // Let the user sign in to Cloudinary first in a separate tab, otherwise third-party\n          // cookies in the iframe won’t work, and authentication will fail. Allow `window.opener`\n          // so Cloudinary can send the login message back via `postMessage`.\n          openNewTab(`${CONSOLE_BASE_URL}/cms_login?cms=true`, { noopener: false });\n        }}\n      />\n      <div role=\"none\">{_('cloud_storage.cloudinary.activate.description')}</div>\n    {/if}\n  </EmptyState>\n{/if}\n","<script>\n  import { TruncatedText } from '@sveltia/ui';\n  import { stripSlashes } from '@sveltia/utils/string';\n  import { sanitize } from 'isomorphic-dompurify';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [path] The asset path to display.\n   * @property {string} [caption] The caption for the asset. Either `path` or `caption` should be\n   * provided. The `path` will be split into segments and displayed with line breaks, while the\n   * `caption` will be displayed as is without splitting.\n   * @property {Snippet} [children] Slot content.\n   */\n\n  /**\n   * Options for {@link sanitize}. Attributes are dropped, so a file name like\n   * `<wbr style=\"position: fixed; inset: 0\">.png` cannot restyle the app.\n   */\n  const SANITIZE_OPTIONS = { ALLOWED_TAGS: ['wbr'], ALLOWED_ATTR: [] };\n\n  /** @type {Props} */\n  let { path, caption, children = undefined } = $props();\n\n  const segments = $derived(path ? stripSlashes(path).split('/') : caption ? [caption] : []);\n\n  /**\n   * Get a label with `<wbr>` tags for line breaking after hyphens, underscores, and dots.\n   * @param {string} str The string to process.\n   * @returns {string} The processed string with `<wbr>` tags for line breaking.\n   */\n  const getLabel = (str) => sanitize(str.replace(/([-_.])/g, '$1<wbr>'), SANITIZE_OPTIONS);\n</script>\n\n{#if segments.length}\n  <!-- Hide the asset path from screen readers because the image comes with alt text -->\n  <span class=\"name\" dir=\"ltr\" aria-hidden=\"true\">\n    <TruncatedText lines={2}>\n      {#each segments as segment, index (`${segment}-${index}`)}\n        {#if index === segments.length - 1}\n          <!-- File name -->\n          <strong>{@html getLabel(segment)}</strong>\n        {:else}\n          <!-- Folder name -->\n          {@html getLabel(segment)}/\n        {/if}\n      {/each}\n    </TruncatedText>\n    {@render children?.()}\n  </span>\n{/if}\n\n<style>\n  .name {\n    color: var(--sui-tertiary-foreground-color);\n\n    :global(strong) {\n      color: var(--sui-primary-foreground-color);\n      font-weight: var(--sui-font-weight-normal);\n    }\n  }\n</style>\n","<!--\n  @component\n  Breadcrumb trail of folders, the last of which is the current one. The ancestors are buttons\n  leading back to themselves. When the trail doesn’t fit, the names are cut short first; once they\n  can’t be cut any further, the ancestors between the first and the current folder are folded into\n  a menu, the way Google Drive does.\n-->\n<script>\n  import { _, isRTL } from '@sveltia/i18n';\n  import { Button, Icon, Menu, MenuButton, MenuItem } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  /**\n   * @import { BreadcrumbItem } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {BreadcrumbItem[]} items Folders, from the root down to the current one.\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   */\n\n  /** @type {Props} */\n  let { items, class: className = '' } = $props();\n\n  /**\n   * Width between the items.\n   */\n  const GAP = 4;\n\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n  /**\n   * Hidden copy of the whole trail, laid out with nothing cut short or folded, so the room the\n   * trail needs can be measured whatever is shown. Measuring the shown trail instead would depend\n   * on its own state: once folded, it takes less room, and would look like it fits.\n   * @type {HTMLElement | undefined}\n   */\n  let copy = $state();\n  /**\n   * Whether the middle ancestors are folded into a menu. Measured whenever the trail or the room\n   * for it changes.\n   */\n  let folded = $state(false);\n\n  const ancestors = $derived(items.slice(0, -1));\n  /** The current folder, which every trail ends with. */\n  const current = $derived(/** @type {BreadcrumbItem} */ (items.at(-1)));\n  /** Ancestors between the first and the current folder, which can be folded into a menu. */\n  const middle = $derived(ancestors.slice(1));\n  const canFold = $derived(middle.length > 0);\n\n  /**\n   * Get the name shown by a trail item.\n   * @param {Element} element Item.\n   * @returns {string} Name.\n   */\n  const getName = (element) => element.querySelector('bdi')?.textContent ?? '';\n\n  /**\n   * Give each name the least room it gets, then fold or unfold the trail depending on the room for\n   * it. A long name can be cut down to a few characters, while a short one keeps its own width, so\n   * it isn’t padded when the trail has room to spare.\n   */\n  const measure = () => {\n    /* v8 ignore next 3 -- the elements are bound by the time anything measures them */\n    if (!wrapper || !copy) {\n      return;\n    }\n\n    const em = parseFloat(getComputedStyle(wrapper).fontSize);\n    /**\n     * The least width of each name, by name. A plain object rather than a `Map`, as nothing\n     * reactive depends on it.\n     * @type {Record<string, number>}\n     */\n    const leastWidths = {};\n    let width = (copy.children.length - 1) * GAP;\n\n    [...copy.children].forEach((child) => {\n      const { classList } = child;\n      const { width: natural } = child.getBoundingClientRect();\n\n      if (classList.contains('crumb') || classList.contains('current')) {\n        const least = Math.min(natural, em * (classList.contains('current') ? 6 : 4.5));\n\n        leastWidths[getName(child)] = least;\n        width += least;\n      } else {\n        width += natural;\n      }\n    });\n\n    // Let the shown trail be cut down to the least widths\n    [...wrapper.children].forEach((child) => {\n      const { classList } = child;\n\n      if (classList.contains('crumb') || classList.contains('current')) {\n        /** @type {HTMLElement} */ (child).style.minWidth = `${leastWidths[getName(child)]}px`;\n      }\n    });\n\n    // The wrapper reports whole pixels, so allow for the rounding\n    folded = canFold && width > wrapper.clientWidth + 1;\n  };\n\n  $effect(() => {\n    // Measure again whenever the trail changes\n    void items;\n\n    const element = wrapper;\n\n    /* v8 ignore next 3 -- the element is bound by the time the effect runs */\n    if (!element) {\n      return undefined;\n    }\n\n    const observer = new ResizeObserver(() => {\n      // Sizing the names changes the layout, which mustn’t happen within the observation itself,\n      // or the browser drops the notification along with a “loop completed” error\n      requestAnimationFrame(() => {\n        measure();\n      });\n    });\n\n    observer.observe(element);\n    // The measurement writes `folded`, which must not re-run the effect\n    untrack(() => {\n      measure();\n    });\n    // The names are wider once the font has loaded\n    document.fonts.ready.then(() => {\n      measure();\n    });\n\n    return () => {\n      observer.disconnect();\n    };\n  });\n\n  // The least widths above are given to the elements shown at the time, so a change of the shown\n  // elements — a fold or an unfold — needs another pass\n  $effect(() => {\n    void folded;\n    untrack(() => {\n      measure();\n    });\n  });\n</script>\n\n{#snippet separator()}\n  <Icon name={isRTL() ? 'chevron_left' : 'chevron_right'} class=\"separator\" />\n{/snippet}\n\n{#snippet ancestor(/** @type {BreadcrumbItem} */ { label, onClick })}\n  <Button variant=\"link\" class=\"crumb\" onclick={onClick}>\n    <bdi>{label}</bdi>\n  </Button>\n  {@render separator()}\n{/snippet}\n\n<nav class={['breadcrumb', className, { folded }]} aria-label={_('folder')} bind:this={wrapper}>\n  {#if folded}\n    {@render ancestor(ancestors[0])}\n    <MenuButton variant=\"ghost\" iconic size=\"small\" class=\"more\" aria-label={_('more_folders')}>\n      {#snippet endIcon()}\n        <Icon name=\"more_horiz\" />\n      {/snippet}\n      {#snippet popup()}\n        <Menu ariaLabel={_('more_folders')}>\n          {#each middle as { label, onClick }, index (index)}\n            <MenuItem variant=\"ghost\" {label} onclick={onClick}>\n              {#snippet startIcon()}\n                <Icon name=\"folder\" />\n              {/snippet}\n            </MenuItem>\n          {/each}\n        </Menu>\n      {/snippet}\n    </MenuButton>\n    {@render separator()}\n  {:else}\n    {#each ancestors as item, index (index)}\n      {@render ancestor(item)}\n    {/each}\n  {/if}\n  <span class=\"current\"><bdi>{current.label}</bdi></span>\n  <div class=\"copy\" aria-hidden=\"true\" inert bind:this={copy}>\n    {#each ancestors as { label }, index (index)}\n      <span class=\"crumb\"><bdi>{label}</bdi></span>\n      {@render separator()}\n    {/each}\n    <span class=\"current\"><bdi>{current.label}</bdi></span>\n  </div>\n</nav>\n\n<style>\n  .breadcrumb {\n    position: relative;\n    display: flex;\n    align-items: center;\n    gap: 4px;\n    min-width: 0;\n    white-space: nowrap;\n\n    /* A name is cut short with an ellipsis rather than wrapped, down to the least width the script\n    above gives it, so the trail stays one line tall */\n\n    & > :global(.crumb),\n    & > .current {\n      flex: 0 1 auto;\n      overflow: hidden;\n      min-width: 0;\n      text-overflow: ellipsis;\n    }\n\n    .current {\n      display: block;\n    }\n\n    .copy {\n      position: absolute;\n      inset-block-start: 0;\n      inset-inline-start: 0;\n      display: flex;\n      align-items: center;\n      gap: 4px;\n      visibility: hidden;\n      pointer-events: none;\n\n      & > * {\n        flex: none;\n      }\n    }\n\n    :global {\n      .sui.button.crumb {\n        display: block;\n        color: var(--sui-secondary-foreground-color);\n        font-size: inherit;\n\n        .label {\n          display: block;\n          overflow: hidden;\n          text-overflow: ellipsis;\n          white-space: nowrap;\n        }\n\n        &:hover .label {\n          color: var(--sui-primary-foreground-color);\n        }\n      }\n\n      .separator,\n      .more {\n        flex: none;\n        color: var(--sui-secondary-foreground-color);\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Breadcrumb trail of the subfolder being browsed in the asset picker. Each ancestor leads back to\n  itself, like the breadcrumb of the Asset Library. Nothing is shown at the root.\n-->\n<script>\n  import Breadcrumb from '$lib/components/common/breadcrumb.svelte';\n  import { getFolderBreadcrumbItems } from '$lib/services/assets/subfolders';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} rootLabel Label of the location root: the asset folder or the cloud storage\n   * service.\n   * @property {string} path Path of the subfolder being browsed, relative to the location root.\n   * Empty at the root.\n   * @property {(path: string) => void} [onNavigate] Called with the relative path of an ancestor\n   * folder to go back to, or an empty string for the root.\n   */\n\n  /** @type {Props} */\n  let { rootLabel, path, onNavigate = undefined } = $props();\n\n  const items = $derived(\n    getFolderBreadcrumbItems({\n      rootLabel,\n      subfolderNames: path ? path.split('/') : [],\n      /**\n       * Go back to the ancestor selected in the breadcrumb.\n       * @param {{ path: string }} ancestor Ancestor.\n       */\n      onBrowse: ({ path: ancestorPath }) => {\n        onNavigate?.(ancestorPath);\n      },\n    }),\n  );\n</script>\n\n{#if items.length}\n  <Breadcrumb class=\"picker-breadcrumb\" {items} />\n{/if}\n\n<style>\n  :global(.picker-breadcrumb) {\n    flex: none;\n    padding: 0 8px 8px;\n\n    :global(.current) {\n      font-weight: var(--sui-font-weight-bold);\n    }\n  }\n</style>\n","<script>\n  import { Icon, Option } from '@sveltia/ui';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} value The `value` attribute of the option.\n   * @property {string} ariaLabel Accessible name of the option, typically the file name or the\n   * image description. The tile only shows a preview and a caption that isn’t part of the button’s\n   * text, so without this the option would be nameless.\n   * @property {boolean} selected Whether the option is selected.\n   * @property {ViewType} [viewType] View type.\n   * @property {boolean} multiple Whether to allow selecting multiple assets.\n   * @property {(event: CustomEvent) => void} onChange Custom `Change` event handler.\n   * @property {Snippet} children Slot content.\n   */\n\n  /** @type {Props} */\n  let { value, ariaLabel, selected, viewType = 'grid', multiple, onChange, children } = $props();\n</script>\n\n<div role=\"none\" class=\"wrapper {viewType}\">\n  <Option label=\"\" aria-label={ariaLabel} {value} {selected} {onChange}>\n    {#snippet startIcon()}\n      {#if multiple}\n        <span role=\"none\" class=\"icon check-background\">\n          <Icon name=\"check\" class=\"icon check\" />\n        </span>\n      {/if}\n    {/snippet}\n    {@render children?.()}\n  </Option>\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n\n    :global {\n      [role='option'] {\n        position: relative;\n\n        & > .icon.check {\n          display: none;\n        }\n\n        &[aria-selected='false'] {\n          .check-background {\n            border-color: var(--sui-checkbox-border-color);\n            background-color: var(--sui-checkbox-background-color);\n\n            .icon {\n              display: none;\n            }\n          }\n        }\n\n        &[aria-selected='true'] {\n          .check-background {\n            border-color: var(--sui-primary-accent-color);\n            color: var(--sui-primary-accent-color-inverted);\n            background-color: var(--sui-primary-accent-color);\n          }\n        }\n\n        .check-background {\n          display: flex;\n          justify-content: center;\n          align-items: center;\n          border-width: 1px;\n          border-radius: var(--sui-checkbox-border-radius);\n          width: 20px;\n          height: 20px;\n          pointer-events: none;\n\n          .icon {\n            color: inherit !important;\n            font-size: 20px;\n          }\n        }\n      }\n    }\n\n    &.grid {\n      :global {\n        .check-background {\n          position: absolute;\n          inset-block-start: 8px;\n          inset-inline-start: 8px;\n          z-index: 1;\n        }\n      }\n    }\n\n    &.list {\n      :global {\n        .check-background {\n          margin-inline-start: 16px;\n        }\n      }\n    }\n  }\n</style>\n","import { tick } from 'svelte';\n\n/**\n * Move the focus to the page container, which is made focusable first.\n */\nconst focusPageContainer = () => {\n  const container = document.querySelector('#page-container');\n\n  if (container instanceof HTMLElement) {\n    container.tabIndex = -1;\n    container.focus();\n  }\n};\n\n/**\n * Remember the element that has the focus as an overlay opens, and return a function that gives it\n * the focus back once the overlay has closed. Without this, closing the entry editor or the asset\n * details drops the focus on `<body>`, and a keyboard or screen reader user has to work their way\n * back from the top of the document to the row they opened.\n * @returns {() => void} Function to call once the overlay is gone. It focuses the element that\n * opened the overlay if it’s still in the document — the row of an entry that has been deleted is\n * gone by then — and the page container otherwise, so the focus at least stays near the list.\n */\nexport const rememberFocus = () => {\n  // `<body>` when nothing has the focus; never `null` in a rendered document\n  const opener = /** @type {HTMLElement} */ (document.activeElement);\n\n  return () => {\n    if (opener.isConnected && opener !== document.body && !opener.closest('[inert]')) {\n      opener.focus();\n\n      return;\n    }\n\n    focusPageContainer();\n  };\n};\n\n/**\n * Watch where the focus is on every frame for a moment, while content is being replaced, so a focus\n * dropped on `<body>` along with the old content can be moved back.\n * @param {(activeElement: Element | null) => boolean} check Function that looks at the element\n * having the focus, moves the focus if needed, and returns whether to keep watching.\n * @param {number} timeout How long to watch, in milliseconds.\n */\nconst watchFocus = (check, timeout) => {\n  const startTime = performance.now();\n\n  /**\n   * Check the focus, and do it again on the next frame unless it’s done.\n   */\n  const step = () => {\n    if (check(document.activeElement) && performance.now() - startTime < timeout) {\n      window.requestAnimationFrame(step);\n    }\n  };\n\n  window.requestAnimationFrame(step);\n};\n\n/**\n * Move the focus to the entry or asset list on the page. A control acting on the selected items,\n * like the Delete button, is disabled once they are gone, which drops its focus on `<body>`, so a\n * keyboard or screen reader user would have to work their way back from the top of the document.\n * The row of the list that is in the tab order takes the focus, or the page container if the list\n * is empty. The list may still be updated after that, e.g. the row of a deleted entry removed, so\n * the page is watched for a moment to move the focus on to a row again if it has been dropped on\n * `<body>`, or if a row shows up while the page container has it.\n * @param {object} [options] Options.\n * @param {number} [options.timeout] How long to watch the page, in milliseconds.\n */\nexport const focusList = ({ timeout = 2000 } = {}) => {\n  const container = document.querySelector('#page-container');\n\n  if (!(container instanceof HTMLElement)) {\n    return;\n  }\n\n  /**\n   * Focus the row in the tab order, or the page container if there is none.\n   */\n  const focus = () => {\n    const row = container.querySelector('[role=\"grid\"] [tabindex=\"0\"]');\n\n    if (row instanceof HTMLElement) {\n      row.focus();\n    } else {\n      container.tabIndex = -1;\n      container.focus();\n    }\n  };\n\n  focus();\n\n  watchFocus((activeElement) => {\n    if (activeElement === document.body || activeElement === container) {\n      focus();\n\n      return true;\n    }\n\n    // Stop once the user has moved the focus elsewhere\n    return container.contains(activeElement);\n  }, timeout);\n};\n\n/**\n * Move the focus to an overlay once it has been opened, so a keyboard or screen reader user can\n * start working with its content right away. The overlay wrapper is made focusable first.\n * @param {() => HTMLElement | null | undefined} getWrapper Function returning the overlay wrapper.\n * It’s called after the next tick, because the element may be unmounted in the meantime, e.g. if\n * the overlay has been closed.\n */\nexport const focusOverlay = async (getWrapper) => {\n  // Wait until `inert` is updated\n  await tick();\n\n  const wrapper = getWrapper();\n\n  if (wrapper) {\n    wrapper.tabIndex = 0;\n    wrapper.focus();\n  }\n};\n\n/**\n * Keep the focus within a container whose content is about to be replaced, such as the pane of the\n * asset picker when a folder is opened. If the element that has the focus is removed along with\n * the old content, the focus would drop on `<body>`, and a keyboard or screen reader user would\n * have to work their way back from the top of the document. It goes to the first list box in the\n * container instead, which is the list of folders or files, or the container itself if there is\n * none yet, while the new content is still loading. The container is watched for a moment after\n * that, so the focus can move on to a list box that shows up in the meantime.\n * @param {HTMLElement} container Container that stays in the document.\n * @param {object} [options] Options.\n * @param {number} [options.timeout] How long to watch the container, in milliseconds.\n */\nexport const keepFocusIn = (container, { timeout = 2000 } = {}) => {\n  watchFocus((activeElement) => {\n    // The focus has stayed within the new content, or the user has moved it elsewhere\n    if (activeElement !== document.body && activeElement !== container) {\n      return false;\n    }\n\n    const listbox = container.querySelector('[role=\"listbox\"]');\n\n    if (listbox instanceof HTMLElement) {\n      listbox.focus();\n\n      return false;\n    }\n\n    if (activeElement === document.body && container.isConnected) {\n      container.tabIndex = -1;\n      container.focus();\n    }\n\n    return true;\n  }, timeout);\n};\n","<!--\n  @component\n  Subfolders of the folder being browsed in the asset picker, listed ahead of the assets. Like the\n  assets below, they’re options in a list box, which the arrow keys move through. A folder is opened\n  with a click or the Enter key. When a folder is to be picked instead of files, a click or the\n  Space key selects a folder instead, and a double click or the Enter key opens it, like in a file\n  manager.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, Listbox, Option } from '@sveltia/ui';\n\n  import { keepFocusIn } from '$lib/services/app/focus';\n\n  /**\n   * @import { AssetSubfolder, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {AssetSubfolder[]} subfolders Subfolders.\n   * @property {ViewType} [viewType] View type, which lays the folders out in a grid or a column.\n   * @property {(subfolder: AssetSubfolder) => void} [onOpen] Called when a subfolder is opened.\n   * @property {boolean} [multiple] Whether more than one subfolder can be selected.\n   * @property {string[]} [selectedPaths] Paths of the selected subfolders.\n   * @property {(subfolder: AssetSubfolder, selected: boolean) => void} [onSelect] Called with a\n   * subfolder and whether it’s now selected. Given only when a folder is to be picked, which makes\n   * a click select a folder rather than open it.\n   */\n\n  /** @type {Props} */\n  let {\n    subfolders,\n    viewType = 'grid',\n    onOpen = undefined,\n    multiple = false,\n    selectedPaths = [],\n    onSelect = undefined,\n  } = $props();\n\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n  /**\n   * Whether the subfolder being clicked was selected before the click. It’s read in the capture\n   * phase, before the list box handles the click.\n   */\n  let wasSelected = false;\n\n  /**\n   * Open a subfolder. The folders are replaced with those of the subfolder, or removed if it has\n   * none, taking the focus with them, so it’s kept within the closest `data-focus-scope`\n   * container, like the content pane of the Select Assets dialog, if the folders had it.\n   * @param {AssetSubfolder} subfolder Subfolder.\n   */\n  const open = (subfolder) => {\n    const focusScope = wrapper?.closest('[data-focus-scope]');\n    const hadFocus = !!wrapper?.contains(document.activeElement);\n\n    onOpen?.(subfolder);\n\n    if (hadFocus && focusScope instanceof HTMLElement) {\n      keepFocusIn(focusScope);\n    }\n  };\n\n  /**\n   * Handle a click on a subfolder: open it, or, when folders can be selected, clear the selection\n   * of a selected folder in a single selection. The list box selects the folder clicked, and\n   * toggles it in a multiple selection, but it has no way to clear a single selection. This runs\n   * once the list box has handled the click: the handler is delegated to the document root.\n   * @param {MouseEvent} event Click event.\n   * @param {AssetSubfolder} subfolder Subfolder.\n   */\n  const onClick = (event, subfolder) => {\n    if (!onSelect) {\n      open(subfolder);\n\n      return;\n    }\n\n    // The second click of a double click, which opens the folder, leaves the selection as is\n    if (!multiple && event.detail === 1 && wasSelected) {\n      onSelect(subfolder, false);\n    }\n  };\n\n  /**\n   * Open the subfolder under the list box cursor with the Enter key when folders can be selected.\n   * The list box would otherwise click it, selecting it or toggling its selection, which the Space\n   * key already does.\n   * @param {KeyboardEvent} event Keyboard event.\n   */\n  const onKeyDown = (event) => {\n    if (!onSelect || event.key !== 'Enter') {\n      return;\n    }\n\n    const path = wrapper?.querySelector('[role=\"option\"].focused')?.getAttribute('data-value');\n    const subfolder = subfolders.find((s) => s.path === path);\n\n    if (subfolder) {\n      event.preventDefault();\n      event.stopPropagation();\n      open(subfolder);\n    }\n  };\n</script>\n\n<!-- A folder that is only opened isn’t marked as selected, so the check mark is left out -->\n{#snippet noCheckIcon()}{/snippet}\n\n<div role=\"none\" class=\"wrapper\" bind:this={wrapper} onkeydowncapture={onKeyDown}>\n  <Listbox class=\"subfolders {viewType}\" multiple={!!onSelect && multiple} ariaLabel={_('folders')}>\n    {#each subfolders as subfolder (subfolder.path)}\n      <Option\n        label={subfolder.name}\n        value={subfolder.path}\n        selected={!!onSelect && selectedPaths.includes(subfolder.path)}\n        aria-description={_('folder')}\n        checkIcon={onSelect ? undefined : noCheckIcon}\n        onChange={(/** @type {CustomEvent} */ event) => {\n          onSelect?.(subfolder, event.detail.selected);\n        }}\n        onclickcapture={() => {\n          wasSelected = selectedPaths.includes(subfolder.path);\n        }}\n        onclick={(/** @type {MouseEvent} */ event) => {\n          onClick(event, subfolder);\n        }}\n        ondblclick={() => {\n          if (onSelect) {\n            open(subfolder);\n          }\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"folder\" />\n        {/snippet}\n      </Option>\n    {/each}\n  </Listbox>\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n\n    :global {\n      .listbox.subfolders {\n        gap: 4px;\n        margin-bottom: 8px;\n        border-width: 0;\n        padding: 0;\n        min-width: 0;\n        background-color: transparent;\n\n        &.grid {\n          display: grid;\n          grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));\n        }\n\n        .option button {\n          border-radius: var(--sui-control-medium-border-radius);\n          min-width: 0;\n          height: 40px;\n\n          .label {\n            overflow: hidden;\n            text-overflow: ellipsis;\n            white-space: nowrap;\n          }\n        }\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Assets listed in the asset picker, in a grid or a list, along with the subfolders of the folder\n  being browsed, if any. The assets are rendered lazily as they’re scrolled into view.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { InfiniteScroll, Listbox } from '@sveltia/ui';\n\n  import SubfolderStrip from '$lib/components/assets/browser/subfolder-strip.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { AssetSubfolder, MediaLibraryAssetKind, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ViewType} [viewType] View type.\n   * @property {string} [gridId] The `id` attribute of the inner listbox.\n   * @property {boolean} [multiple] Whether to allow selecting multiple assets.\n   * @property {MediaLibraryAssetKind} [kind] Kind of the listed assets, which names the list:\n   * images, or files of any kind if `undefined`.\n   * @property {AssetSubfolder[]} [subfolders] Subfolders of the folder being browsed, listed ahead\n   * of the assets.\n   * @property {(subfolder: AssetSubfolder) => void} [onOpenSubfolder] Called when a subfolder is\n   * opened.\n   * @property {string[]} [selectedSubfolderPaths] Paths of the selected subfolders.\n   * @property {(subfolder: AssetSubfolder, selected: boolean) => void} [onSelectSubfolder] Called\n   * with a subfolder and whether it’s now selected, when a folder is to be picked.\n   * @property {any[]} items Listed items.\n   * @property {string} itemKey Name of the item property that identifies each item.\n   * @property {Snippet<[any]>} renderItem Snippet rendering an item, as a `SimpleImageGridItem`.\n   */\n\n  /** @type {Props} */\n  let {\n    viewType = 'grid',\n    gridId = undefined,\n    multiple = false,\n    kind = undefined,\n    subfolders = [],\n    onOpenSubfolder = undefined,\n    selectedSubfolderPaths = [],\n    onSelectSubfolder = undefined,\n    items,\n    itemKey,\n    renderItem,\n  } = $props();\n</script>\n\n{#if subfolders.length}\n  <SubfolderStrip\n    {subfolders}\n    {viewType}\n    {multiple}\n    onOpen={onOpenSubfolder}\n    selectedPaths={selectedSubfolderPaths}\n    onSelect={onSelectSubfolder}\n  />\n{/if}\n<!-- An empty list box would only be a stop for the Tab key, with nothing to move through -->\n{#if items.length}\n  <div role=\"none\" class=\"wrapper\">\n    <Listbox\n      id={gridId}\n      class={viewType}\n      {multiple}\n      ariaLabel={_(`assets_dialog.available_${kind === 'image' ? 'images' : 'files'}`)}\n    >\n      <InfiniteScroll {items} {itemKey} {renderItem} />\n    </Listbox>\n  </div>\n{/if}\n\n<style>\n  .wrapper {\n    display: contents;\n\n    :global {\n      .listbox {\n        gap: 4px;\n        border-width: 0;\n\n        .option {\n          button {\n            border-radius: var(--sui-control-medium-border-radius);\n            padding: 4px;\n            width: 100%;\n            height: auto;\n            transition: none;\n\n            &:focus-visible {\n              outline-color: transparent;\n            }\n\n            .preview {\n              flex: none;\n              border-radius: var(--sui-control-medium-border-radius);\n              aspect-ratio: 1 / 1;\n              object-fit: contain;\n            }\n          }\n        }\n\n        .name {\n          min-height: calc(var(--sui-font-size-default) * 2);\n          white-space: normal;\n          line-height: var(--sui-line-height-compact);\n        }\n      }\n\n      .listbox.grid {\n        display: grid;\n        grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));\n\n        .option {\n          button {\n            flex-direction: column;\n            justify-content: flex-start;\n\n            .preview {\n              width: 100%;\n              height: auto;\n            }\n\n            .name {\n              flex: none;\n              margin: 4px 0 12px;\n              padding: 0 8px;\n              width: 100%;\n              min-height: calc(var(--sui-font-size-default) * 3);\n\n              &:empty {\n                display: none;\n              }\n            }\n          }\n        }\n\n        button[aria-selected='true'] {\n          outline-offset: -2px;\n          outline-width: 2px !important;\n          outline-style: solid;\n          outline-color: var(--sui-primary-accent-color-light);\n        }\n      }\n\n      .listbox.list {\n        .option {\n          button {\n            gap: 16px;\n\n            .preview {\n              width: 64px;\n            }\n\n            .name {\n              flex: auto;\n              padding-inline: 0 8px;\n            }\n          }\n\n          button[aria-selected='true'] {\n            outline-offset: -2px;\n            outline-width: 2px !important;\n            outline-style: solid;\n            outline-color: var(--sui-primary-accent-color-light);\n          }\n        }\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Dialog asking for the name of a file or folder, shared by the Rename Asset dialog and the dialogs\n  naming a subfolder. It shows a description, the input field, an optional note and the validation\n  error, while the caller validates the name and acts on it.\n-->\n<script>\n  import { Dialog, TextInput } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} open Whether the dialog is open.\n   * @property {string} title Dialog title.\n   * @property {string} okLabel Label of the OK button.\n   * @property {boolean} okDisabled Whether the OK button is disabled.\n   * @property {() => void} onOk Called when the OK button is clicked or the name is submitted with\n   * the Enter key.\n   * @property {() => void} [onOpen] Called once the dialog is open.\n   * @property {() => void} [onClose] Called once the dialog is closed.\n   * @property {string} description Text shown above the input field.\n   * @property {string} [blockedMessage] Why the name can’t be submitted, shown in place of the\n   * description. The input field is then disabled.\n   * @property {string} value Entered name.\n   * @property {HTMLInputElement} [element] Input element.\n   * @property {string} ariaLabel The `aria-label` attribute on the input field.\n   * @property {() => void} [oninput] Called when the user types in the input field.\n   * @property {string} [note] Note shown below the input field, e.g. the name the file will be\n   * saved as.\n   * @property {string} [error] Validation error, shown below the input field, which is then marked\n   * as invalid.\n   */\n\n  /** @type {Props} */\n  let {\n    open = $bindable(false),\n    title,\n    okLabel,\n    okDisabled,\n    onOk,\n    onOpen = undefined,\n    onClose = undefined,\n    description,\n    blockedMessage = undefined,\n    value = $bindable(''),\n    element = $bindable(),\n    ariaLabel,\n    oninput = undefined,\n    note = undefined,\n    error = undefined,\n  } = $props();\n\n  const componentId = $props.id();\n  /**\n   * Whether the user has submitted the name with the Enter key. The dialog has no way to be closed\n   * as if its OK button were clicked, so `onOk` is called once it has closed, just before\n   * `onClose`, as the button would do.\n   */\n  let submitted = false;\n</script>\n\n<Dialog\n  {title}\n  bind:open\n  {okLabel}\n  {okDisabled}\n  {onOk}\n  onOpen={() => {\n    // A submission is only pending while the dialog is closing, so drop one left behind by a close\n    // that reopening the dialog has interrupted\n    submitted = false;\n    onOpen?.();\n  }}\n  onClose={() => {\n    if (submitted) {\n      submitted = false;\n      onOk();\n    }\n\n    onClose?.();\n  }}\n>\n  {#if blockedMessage}\n    <p role=\"alert\">{blockedMessage}</p>\n  {:else}\n    <p>{description}</p>\n  {/if}\n  <div role=\"none\">\n    <TextInput\n      dir=\"auto\"\n      bind:value\n      bind:element\n      flex\n      disabled={!!blockedMessage}\n      {ariaLabel}\n      invalid={!!error}\n      aria-errormessage=\"{componentId}-error\"\n      {oninput}\n      onkeydown={(/** @type {KeyboardEvent} */ event) => {\n        // Submit with the Enter key like the OK button, unless it’s confirming an IME conversion\n        if (event.key === 'Enter' && !event.isComposing && !okDisabled) {\n          event.preventDefault();\n          submitted = true;\n          open = false;\n        }\n      }}\n    />\n  </div>\n  {#if note}\n    <div role=\"status\" class=\"note\">{note}</div>\n  {/if}\n  <div role=\"none\" class=\"error\" id=\"{componentId}-error\">\n    {#if error}\n      {error}\n    {/if}\n  </div>\n</Dialog>\n\n<style>\n  p {\n    margin: 0 0 8px;\n  }\n\n  div {\n    display: flex;\n    align-items: center;\n    gap: 4px;\n  }\n\n  .note {\n    margin: 4px 0 0;\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n  }\n\n  .error {\n    margin: 0;\n    color: var(--sui-error-foreground-color);\n    font-size: var(--sui-font-size-small);\n  }\n</style>\n","<!--\n  @component\n  Dialog asking for the name of a subfolder, shared by the New Folder and Rename Folder dialogs of\n  the Asset Library and the asset picker. It validates the name against the names already taken in\n  the parent folder, and hands the formatted name over to the caller.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import NameInputDialog from '$lib/components/assets/list/name-input-dialog.svelte';\n  import { formatSubfolderName, validateSubfolderName } from '$lib/services/assets/subfolders';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} open Whether the dialog is open.\n   * @property {string} title Dialog title.\n   * @property {string} okLabel Label of the OK button.\n   * @property {string} description Text shown above the input field.\n   * @property {string} [blockedMessage] Why the folder can’t be renamed, e.g. because a read-only\n   * entry uses a file in it, shown in place of the description; the name can’t be submitted then.\n   * @property {string} [name] Current folder name, shown in the input field when renaming. Empty\n   * for a new folder.\n   * @property {string[]} takenNames Names of the files and folders already in the parent folder,\n   * which the new name must not duplicate. The current name is not among these when renaming.\n   * @property {(name: string) => void} onSubmit Called with the formatted name once confirmed.\n   * @property {() => void} [onClose] Called once the dialog has closed, after `onSubmit` if it was\n   * confirmed.\n   */\n\n  /** @type {Props} */\n  let {\n    open = $bindable(false),\n    title,\n    okLabel,\n    description,\n    blockedMessage = undefined,\n    name = '',\n    takenNames,\n    onSubmit,\n    onClose = undefined,\n  } = $props();\n\n  let newName = $state('');\n  /**\n   * Whether the folder name has been typed in yet. An empty name is only reported once the field\n   * has been used, so the dialog doesn’t open with an error against a field nobody has touched.\n   */\n  let nameEdited = $state(false);\n\n  const error = $derived(validateSubfolderName({ name: newName, takenNames }));\n  const invalid = $derived(nameEdited && !!error);\n  /** Whether the name is what it was, so there is nothing to rename. */\n  const unchanged = $derived(!!name && formatSubfolderName(newName) === name);\n\n  // Reset the input whenever the dialog is opened\n  $effect(() => {\n    if (open) {\n      newName = name;\n      nameEdited = false;\n    }\n  });\n</script>\n\n<NameInputDialog\n  {title}\n  bind:open\n  {okLabel}\n  okDisabled={!!blockedMessage || !!error || unchanged}\n  onOk={() => {\n    onSubmit(formatSubfolderName(newName));\n  }}\n  {onClose}\n  {description}\n  {blockedMessage}\n  bind:value={newName}\n  ariaLabel={_('new_folder_name')}\n  oninput={() => {\n    nameEdited = true;\n  }}\n  error={invalid ? _(`new_folder_error.${error}`) : undefined}\n/>\n","import { observeVisibility, whenSteadilyVisible } from '@sveltia/utils/element';\n\n/**\n * Margin around the viewport within which a thumbnail that scrolls into view starts loading, so\n * it’s there by the time it’s seen.\n */\nconst THUMBNAIL_ROOT_MARGIN = '200px 0px';\n/**\n * How long, in milliseconds, a thumbnail that scrolls into view has to stay there before it starts\n * loading. A row passes through the viewport and the margin in less than that while a list is\n * flung, so only the rows the scrolling slows down or stops at load their thumbnails.\n */\nconst THUMBNAIL_DWELL_TIME = 200;\n/**\n * Time of the last scroll anywhere in the document, from `performance.now()`. `-Infinity` until\n * something has been scrolled.\n */\nlet lastScrollTime = -Infinity;\n/**\n * Whether {@link lastScrollTime} is being kept up to date.\n */\nlet trackingScroll = false;\n\n/**\n * Start keeping {@link lastScrollTime} up to date, if not done yet. A scroll event doesn’t bubble,\n * so it’s caught on its way down instead, from whichever element is scrolled.\n */\nconst trackScroll = () => {\n  if (!trackingScroll) {\n    trackingScroll = true;\n    globalThis.addEventListener(\n      'scroll',\n      () => {\n        lastScrollTime = performance.now();\n      },\n      { capture: true, passive: true },\n    );\n  }\n};\n\n/**\n * Call a function once the given thumbnail container is to be shown. One that’s in the viewport\n * when it’s first observed while nothing is being scrolled, as the first rows of a list or the\n * tiles of a grid that has just been opened, is shown right away. Otherwise it has to stay in or\n * near the viewport for a moment, so the rows a list is scrolled past, including those rendered\n * while it’s being scrolled, don’t queue up thumbnails ahead of the ones the user stops at.\n * @param {Element} element Element holding the thumbnail.\n * @param {() => void} callback Function to call.\n * @returns {() => void} Function to cancel the call if it hasn’t been made yet.\n */\nexport const whenThumbnailShown = (element, callback) => {\n  // Without a way to tell, the thumbnail is shown right away, as `whenSteadilyVisible()` does\n  if (!('IntersectionObserver' in globalThis)) {\n    return whenSteadilyVisible(element, callback);\n  }\n\n  trackScroll();\n\n  /** @type {(() => void) | undefined} */\n  let cancelWait;\n\n  // The first report tells whether the element is in the viewport now, without the margin\n  const stopObserving = observeVisibility(element, (visible) => {\n    stopObserving();\n\n    if (visible && performance.now() - lastScrollTime > THUMBNAIL_DWELL_TIME) {\n      callback();\n    } else {\n      cancelWait = whenSteadilyVisible(element, callback, {\n        delay: THUMBNAIL_DWELL_TIME,\n        rootMargin: THUMBNAIL_ROOT_MARGIN,\n      });\n    }\n  });\n\n  return () => {\n    stopObserving();\n    cancelWait?.();\n  };\n};\n","import { removeVisibilityResolver } from '@sveltia/utils/element';\n\nimport { holdViewTransition } from '$lib/services/app/navigation';\nimport { revokeAssetBlobURLIfNeeded, revokeBlobURLIfNeeded } from '$lib/services/assets/info';\nimport { whenThumbnailShown } from '$lib/services/utils/visibility';\n\n/**\n * @import { Asset } from '$lib/types/private';\n */\n\n/**\n * Functions managing the lifecycle of an asset preview.\n * @typedef {object} PreviewLifecycle\n * @property {boolean} destroyed Whether the preview has been removed.\n * @property {(asset: Asset | undefined) => void} trackAsset Remember the asset being rendered.\n * @property {(url: string | undefined) => void} ownURL Remember an object URL the preview created.\n * @property {(result: { url?: string, failed: boolean, thumbnail: boolean }) => string | undefined\n * } settleLookup Take in the result of the latest URL lookup.\n * @property {(element: HTMLElement) => Promise<void>} waitForThumbnail Wait until the given\n * thumbnail is to be shown.\n * @property {() => void} holdTransition Make the running view transition wait.\n * @property {() => void} releaseTransition Release the view transition being held, if any.\n * @property {(element?: HTMLElement) => void} destroy Release everything.\n */\n\n/**\n * Create what keeps track of what one asset preview holds on to while it’s on screen, and lets go\n * of once it’s removed.\n *\n * This is deliberately a plain module, kept outside the reactive graph, as the `destroy` function\n * runs while the component is being destroyed. Reading the `asset` prop there would read whatever\n * the parent passes it from — a `$derived` holding the thumbnail of a collapsed Object field or\n * List item. Svelte answers a read made while an effect is being torn down by walking that\n * derived’s dependency graph to see whether it has to be recomputed, and that walk doesn’t memoize:\n * in a deeply nested entry editor, where every level multiplies the number of paths to the same\n * derived, expanding one field froze the browser for tens of seconds.\n * @returns {PreviewLifecycle} Functions to manage the lifecycle.\n * @see https://github.com/sveltia/sveltia-cms/issues/1006\n */\nexport const createPreviewLifecycle = () => {\n  /**\n   * Object URLs created by this preview. Every `getAssetThumbnailURL()` call returns a URL of its\n   * own, so these have to be released here — `revokeAssetBlobURLIfNeeded()` only knows about the\n   * one URL shared on the asset itself.\n   * @type {string[]}\n   */\n  const ownedURLs = [];\n  /**\n   * The URL the last lookup has found, to be released once it’s been replaced. The component’s own\n   * source URL can’t tell, as it’s reset as soon as the asset changes.\n   * @type {string | undefined}\n   */\n  let lookedUpSrc = undefined;\n  /** @type {Asset | undefined} */\n  let currentAsset = undefined;\n  let destroyed = false;\n  /** @type {(() => void) | undefined} */\n  let resolveTransition = undefined;\n  /** @type {(() => void) | undefined} */\n  let cancelThumbnailWait = undefined;\n\n  /**\n   * Remember an object URL this preview created.\n   * @param {string | undefined} url Object URL.\n   */\n  const ownURL = (url) => {\n    if (url && !ownedURLs.includes(url)) {\n      ownedURLs.push(url);\n    }\n  };\n\n  /**\n   * Release an object URL this preview created, once no element is displaying it any more.\n   * @param {string | undefined} url Object URL.\n   */\n  const releaseOwnedURL = (url) => {\n    const index = url ? ownedURLs.indexOf(url) : -1;\n\n    if (index > -1) {\n      ownedURLs.splice(index, 1);\n      revokeBlobURLIfNeeded(url);\n    }\n  };\n\n  /**\n   * Release the view transition being held, if any.\n   */\n  const releaseTransition = () => {\n    resolveTransition?.();\n    resolveTransition = undefined;\n  };\n\n  /**\n   * Remember the asset being rendered, for {@link destroy} to release.\n   * @param {Asset | undefined} asset Asset.\n   */\n  const trackAsset = (asset) => {\n    currentAsset = asset;\n  };\n\n  /**\n   * Take in the result of the latest URL lookup, and release the URL it replaces.\n   * @param {object} result Result of the lookup.\n   * @param {string} [result.url] URL found.\n   * @param {boolean} result.failed Whether the lookup has failed.\n   * @param {boolean} result.thumbnail Whether the URL is a thumbnail, which the preview owns, as\n   * opposed to the full-size URL shared on the asset.\n   * @returns {string | undefined} The URL the preview ends up with, which is the previous one if\n   * the lookup has failed.\n   */\n  const settleLookup = ({ url, failed, thumbnail }) => {\n    const previousSrc = lookedUpSrc;\n    const nextSrc = failed ? previousSrc : url;\n\n    lookedUpSrc = nextSrc;\n\n    if (thumbnail) {\n      ownURL(nextSrc);\n    }\n\n    if (previousSrc !== nextSrc) {\n      releaseOwnedURL(previousSrc);\n    }\n\n    return nextSrc;\n  };\n\n  /**\n   * Wait until the given thumbnail is to be shown: right away if it’s in view, or once it has\n   * scrolled into view and stayed there for a moment. A thumbnail in a grid being scrolled quickly\n   * then doesn’t queue its generation ahead of the ones the user stops at, and no layout is forced\n   * to find out, which matters with a thumbnail per tile. The promise is left pending if another\n   * wait starts or the preview is removed first: only the latest lookup is acted on, and an earlier\n   * wait isn’t left to observe the same element alongside this one.\n   * @param {HTMLElement} element Element.\n   * @returns {Promise<void>} Promise resolved once the thumbnail is to be shown.\n   */\n  const waitForThumbnail = (element) =>\n    new Promise((resolve) => {\n      cancelThumbnailWait?.();\n      cancelThumbnailWait = whenThumbnailShown(element, () => {\n        cancelThumbnailWait = undefined;\n        resolve();\n      });\n    });\n\n  /**\n   * Make the running view transition wait until {@link releaseTransition} is called, replacing an\n   * earlier hold.\n   */\n  const holdTransition = () => {\n    releaseTransition();\n\n    const { promise, resolve } = /** @type {PromiseWithResolvers<void>} */ (\n      Promise.withResolvers()\n    );\n\n    resolveTransition = resolve;\n    holdViewTransition(promise);\n  };\n\n  /**\n   * Release everything once the preview is removed.\n   * @param {HTMLElement} [element] Media element.\n   */\n  const destroy = (element) => {\n    destroyed = true;\n    releaseTransition();\n\n    if (currentAsset) {\n      revokeAssetBlobURLIfNeeded(currentAsset);\n    }\n\n    // The revocation is batched into the next frame and skips any URL an element is still\n    // displaying, which is what keeps an image that hasn’t finished decoding — or one that outlives\n    // this component — from losing its source. @see\n    // https://github.com/sveltia/sveltia-cms/issues/944\n    ownedURLs.splice(0).forEach((url) => {\n      revokeBlobURLIfNeeded(url);\n    });\n\n    if (element) {\n      removeVisibilityResolver(element);\n    }\n\n    cancelThumbnailWait?.();\n  };\n\n  return {\n    /**\n     * Whether the preview has been removed. A URL lookup that finishes afterwards releases what it\n     * created, as {@link destroy} has already run.\n     * @returns {boolean} Result.\n     */\n    get destroyed() {\n      return destroyed;\n    },\n    trackAsset,\n    ownURL,\n    settleLookup,\n    waitForThumbnail,\n    holdTransition,\n    releaseTransition,\n    destroy,\n  };\n};\n","import { flushSync } from 'svelte';\n\n/**\n * Whether a {@link flushSync} call is already queued for the current microtask checkpoint.\n */\nlet flushQueued = false;\n\n/**\n * Run the queued {@link flushSync}, allowing a new one to be queued afterwards.\n */\nconst runQueuedFlush = () => {\n  flushQueued = false;\n  flushSync();\n};\n\n/**\n * Request a synchronous flush of pending Svelte effects, coalescing repeated requests made within\n * the same microtask checkpoint into a single {@link flushSync} call.\n *\n * `flushSync()` re-renders the whole component tree, so calling it from a component that appears\n * many times on a page — an asset thumbnail in a grid, say — costs O(n) full renders when the\n * instances settle together. Queuing the call collapses that into one, while still flushing before\n * the browser paints.\n */\nexport const requestFlushSync = () => {\n  if (flushQueued) {\n    return;\n  }\n\n  flushQueued = true;\n  queueMicrotask(runQueuedFlush);\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon } from '@sveltia/ui';\n  import { waitForVisibility } from '@sveltia/utils/element';\n  import { onMount, untrack } from 'svelte';\n\n  import {\n    getAssetBlobURL,\n    getAssetThumbnailURL,\n    revokeBlobURLIfNeeded,\n  } from '$lib/services/assets/info';\n  import { isPDF, THUMBNAIL_KINDS } from '$lib/services/assets/kinds';\n  import { createPreviewLifecycle } from '$lib/services/assets/preview-lifecycle';\n  import { requestFlushSync } from '$lib/services/utils/render';\n  import { createLatestGuard } from '$lib/services/utils/scheduling';\n  import { watchAsync } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { Asset, AssetKind } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {AssetKind} kind Asset type.\n   * @property {'lazy' | 'eager'} [loading] Loading method.\n   * @property {Asset} [asset] Asset.\n   * @property {string} [src] Source URL.\n   * @property {'tile' | 'icon'} [variant] Style variant.\n   * @property {boolean} [blurBackground] Whether to show a blurred background (like Slack’s media\n   * overlay).\n   * @property {boolean} [cover] Whether to use `object-fit: cover`.\n   * @property {boolean} [checkerboard] Whether to show a checkerboard background below a\n   * transparent image.\n   * @property {boolean} [dissolve] Whether to add a short dissolve transition (fade-in effect) to\n   * the image/video when it’s first loaded to avoid a sudden appearance.\n   * @property {string} [alt] Alt text for the image.\n   * @property {boolean} [controls] Whether to show controls for audio/video. If this is `false` and\n   * {@link kind} is `audio`, an icon will be displayed instead.\n   * @property {boolean} [holdTransition] Whether to make the running view transition wait for the\n   * media to be loaded, so that it’s part of the animation rather than popping in once it’s over.\n   * Only for a single, prominent preview, such as the one in the asset details overlay.\n   * @property {() => void} [onError] Function called once the preview falls back to an icon because\n   * the media can’t be loaded, either as its URL lookup has failed or as the element has failed to\n   * load it.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let {\n    kind,\n    loading = 'lazy',\n    asset = undefined,\n    src = undefined,\n    variant = undefined,\n    blurBackground = false,\n    cover = false,\n    checkerboard = false,\n    dissolve = true,\n    alt = '',\n    controls = false,\n    holdTransition = false,\n    onError = () => undefined,\n    ...rest\n  } = $props();\n\n  /** @type {HTMLImageElement | HTMLMediaElement | undefined} */\n  let mediaElement = $state();\n  /**\n   * What the preview shows: the asset, or the source URL if there is no asset. The info panels keep\n   * one preview while the focus moves between assets, so the states below are tied to the source\n   * they were reached for, and a new source starts afresh.\n   */\n  const source = $derived(asset ?? src);\n  /**\n   * The source whose media has failed to load.\n   * @type {Asset | string | undefined}\n   */\n  let failedSource = $state.raw();\n  /**\n   * The source whose media has been loaded.\n   * @type {Asset | string | undefined}\n   */\n  let loadedSource = $state.raw();\n  const hasError = $derived(!!source && failedSource === source);\n  const loaded = $derived(!!source && loadedSource === source);\n  /** @type {string | undefined} */\n  let blurImageURL = $state();\n  /**\n   * The source URL: the `src` property, or for the `asset`-based flow, the URL looked up in\n   * {@link updateSrc}. A change of the property replaces the looked-up URL.\n   */\n  let resolvedSrc = $derived.by(() => {\n    // Drop the URL looked up for the previous asset once another one comes, so that its media isn’t\n    // displayed with the details of the new one until the new URL has been looked up\n    void asset;\n\n    return src;\n  });\n  /**\n   * The actual `src` applied to the media element. For the `asset`-based flow this mirrors\n   * {@link resolvedSrc} (which is set after a visibility check inside {@link updateSrc}). For an\n   * externally-provided `src` with `loading === 'lazy'`, it is deferred via\n   * {@link waitForVisibility} so that the browser does not eagerly fetch off-screen images in grid\n   * layouts.\n   * @type {string | undefined}\n   */\n  let mediaSrc = $state();\n\n  const isThumbnail = $derived(!!asset && !!variant && !controls);\n  const isImage = $derived(\n    kind === 'image' ||\n      (!!asset && isPDF(asset.name)) ||\n      (isThumbnail && THUMBNAIL_KINDS.includes(kind)),\n  );\n\n  /**\n   * Guard for {@link updateSrc}. A call that finds a later one has started on the way leaves the\n   * result to that one, so that the latest asset wins when the focus moves quickly.\n   */\n  const srcRequestGuard = createLatestGuard();\n  /** The object URLs, view transition and waits of this preview, outside the reactive graph. */\n  const lifecycle = createPreviewLifecycle();\n\n  /**\n   * Update the {@link resolvedSrc} value.\n   */\n  const updateSrc = async () => {\n    /* v8 ignore next 3 -- the effect below only calls this for a mounted asset */\n    if (!asset || !mediaElement) {\n      return;\n    }\n\n    const isLatest = srcRequestGuard.next();\n    // Read up front, as a derived can’t be read once the component has been destroyed\n    const requestedAsset = asset;\n    const thumbnail = isThumbnail;\n\n    if (loading === 'lazy') {\n      if (thumbnail) {\n        await lifecycle.waitForThumbnail(mediaElement);\n      } else {\n        await waitForVisibility(mediaElement);\n      }\n    }\n\n    /** @type {string | undefined} */\n    let url = undefined;\n    let failed = false;\n\n    try {\n      url = thumbnail\n        ? await getAssetThumbnailURL(requestedAsset)\n        : await getAssetBlobURL(requestedAsset);\n    } catch {\n      failed = true;\n    }\n\n    // The preview was removed while the URL was being looked up. Release it as the cleanup does,\n    // which skips a URL another element is displaying\n    if (lifecycle.destroyed) {\n      revokeBlobURLIfNeeded(url);\n\n      return;\n    }\n\n    // Another asset has come in the meantime. Release a thumbnail made for this one, which nothing\n    // displays; the full-size URL is shared on the asset itself, so leave that alone\n    if (!isLatest()) {\n      if (thumbnail) {\n        revokeBlobURLIfNeeded(url);\n      }\n\n      return;\n    }\n\n    if (failed) {\n      failedSource = requestedAsset;\n    } else {\n      resolvedSrc = url;\n    }\n\n    const nextSrc = lifecycle.settleLookup({ url, failed, thumbnail });\n\n    if (blurBackground && !blurImageURL && nextSrc) {\n      blurImageURL = nextSrc;\n    }\n\n    // For some reason this is required to update the `$effect` calling `checkLoaded()`, otherwise\n    // navigating from `/assets` to `/assets/<collection>` on small screen leaves the preview empty.\n    // Queued rather than immediate, so a grid full of previews settling at once costs one flush\n    // instead of one per preview.\n    requestFlushSync();\n  };\n\n  /**\n   * Update the {@link loaded} state when the media is loaded.\n   */\n  const checkLoaded = async () => {\n    /* v8 ignore next 3 -- the effect below only calls this once the media has a source */\n    if (!mediaElement || !mediaSrc) {\n      return;\n    }\n\n    // The element’s own readiness only means anything once the DOM actually reflects `mediaSrc`.\n    // An `<img>` whose `src` attribute hasn’t been written yet reports `complete === true`, which\n    // would otherwise mark the preview loaded — and, back when that signal also revoked the blob\n    // URL, kill the image just as the real `src` was applied. @see\n    // https://github.com/sveltia/sveltia-cms/issues/944\n    const isSrcApplied = mediaElement.getAttribute('src') === mediaSrc;\n\n    const isReady =\n      isSrcApplied &&\n      (isImage\n        ? /** @type {HTMLImageElement} */ (mediaElement).complete\n        : !!(/** @type {HTMLMediaElement} */ (mediaElement).readyState));\n\n    // Read up front: the outcome only counts if the preview still shows the same media afterwards\n    const currentSource = source;\n    const currentSrc = mediaSrc;\n\n    if (!isReady) {\n      // Not loaded yet; wait until it’s ready\n      const failed = await new Promise((resolve) => {\n        mediaElement?.addEventListener(isImage ? 'load' : 'loadedmetadata', () => resolve(false), {\n          once: true,\n        });\n        mediaElement?.addEventListener('error', () => resolve(true), { once: true });\n      });\n\n      // Another source has come while the media was loading\n      if (mediaSrc !== currentSrc) {\n        return;\n      }\n\n      if (failed) {\n        // Show the fallback icon rather than an empty tile that never finishes its transition\n        failedSource = currentSource;\n\n        return;\n      }\n    }\n\n    // The media is ready to be shown, so the view transition can capture it\n    lifecycle.releaseTransition();\n\n    // The preview may have been removed while the media was loading\n    /* v8 ignore next 3 */\n    if (!mediaElement) {\n      return;\n    }\n\n    // Enable a dissolve transition\n    if (dissolve) {\n      await waitForVisibility(mediaElement);\n    }\n\n    loadedSource = currentSource;\n  };\n\n  $effect(() => {\n    // `blurImageURL` is only rendered when `blurBackground` is enabled, so don’t look up — and\n    // create an object URL for — a thumbnail that nothing will display. Every thumbnail in an asset\n    // grid would otherwise pay for a blurred backdrop it never shows.\n    if (blurBackground && asset && !blurImageURL) {\n      (async () => {\n        const url = await getAssetThumbnailURL(asset, { cacheOnly: true });\n\n        // The preview was removed while the thumbnail was being looked up\n        if (lifecycle.destroyed) {\n          revokeBlobURLIfNeeded(url);\n\n          return;\n        }\n\n        // Without a cached thumbnail, the media itself doubles as the backdrop once its URL has\n        // been looked up in `updateSrc`, which may well have finished first, so don’t clear it\n        if (url) {\n          blurImageURL = url;\n          lifecycle.ownURL(url);\n        }\n      })();\n    }\n  });\n\n  $effect(() => {\n    // An asset on an external location comes as a plain URL rather than an `Asset`, and has no\n    // cached thumbnail, so the image itself doubles as the blurred backdrop\n    if (blurBackground && !asset && kind === 'image' && resolvedSrc) {\n      blurImageURL = resolvedSrc;\n    }\n  });\n\n  // The cleanup can’t read the `asset` prop, which may lead to a derived of the parent: reading one\n  // during teardown froze deeply nested editors, so it gets a plain copy instead\n  $effect(() => {\n    lifecycle.trackAsset(asset);\n  });\n\n  $effect(() => {\n    if (holdTransition && source) {\n      lifecycle.holdTransition();\n    }\n  });\n\n  // Notify the parent of a failure, whether the URL lookup or the media element has failed\n  $effect(() => {\n    if (hasError) {\n      lifecycle.releaseTransition();\n      untrack(() => onError());\n    }\n  });\n\n  $effect(() => {\n    if (mediaElement && asset) {\n      updateSrc();\n    }\n  });\n\n  // The source can change or go away before the element becomes visible, which `watchAsync` takes\n  // care of\n  watchAsync(\n    () => {\n      // For the asset-based flow, `resolvedSrc` is set by `updateSrc` after a visibility check\n      if (asset || !resolvedSrc || !mediaElement || loading !== 'lazy') {\n        mediaSrc = resolvedSrc;\n\n        return undefined;\n      }\n\n      // For externally-provided `src`, use Intersection Observer instead of relying on the native\n      // `loading=\"lazy\"` attribute, which browsers may ignore in grid/flex layouts\n      mediaSrc = undefined;\n\n      const currentSrc = resolvedSrc;\n      const element = mediaElement;\n\n      return (async () => {\n        await waitForVisibility(element);\n\n        return currentSrc;\n      })();\n    },\n    (currentSrc) => {\n      mediaSrc = currentSrc;\n    },\n  );\n\n  $effect(() => {\n    if (mediaElement && mediaSrc) {\n      checkLoaded();\n    }\n  });\n\n  onMount(() => () => {\n    lifecycle.destroy(mediaElement);\n  });\n</script>\n\n<div\n  role=\"none\"\n  class=\"preview {variant}\"\n  class:cover\n  class:checkerboard\n  class:dissolve\n  class:loaded\n>\n  {#if hasError}\n    <Icon name=\"draft\" />\n  {:else if isImage}\n    <img {loading} src={mediaSrc} {alt} {...rest} bind:this={mediaElement} />\n  {:else if kind === 'video'}\n    <!-- svelte-ignore a11y_media_has_caption -->\n    <video\n      src={mediaSrc}\n      controls={controls || undefined}\n      playsinline\n      {...rest}\n      bind:this={mediaElement}\n    ></video>\n  {:else if kind === 'audio'}\n    {#if controls}\n      <audio src={mediaSrc} controls playsinline {...rest} bind:this={mediaElement}></audio>\n    {:else}\n      <Icon name=\"audio_file\" />\n    {/if}\n  {:else}\n    <Icon name=\"draft\" />\n  {/if}\n  {#if blurBackground}\n    <div role=\"none\" class=\"blur\">\n      <div role=\"status\" class=\"overlay\">\n        {#if !isThumbnail && !loaded}\n          {_('loading')}\n        {/if}\n      </div>\n      <img role=\"none\" loading=\"lazy\" src={blurImageURL} alt=\"\" class:loaded={!!blurImageURL} />\n    </div>\n  {/if}\n</div>\n\n<style>\n  .preview {\n    display: inline-flex;\n    align-items: center;\n    justify-content: center;\n    position: relative;\n    width: 100%;\n    height: 100%;\n\n    &.tile {\n      border-width: 1px;\n      border-style: solid;\n      border-color: transparent;\n      padding: var(--tile-padding, 12px);\n\n      :global(.sui.icon) {\n        font-size: 48px;\n      }\n    }\n\n    &.icon {\n      border-radius: var(--sui-control-medium-border-radius);\n      width: var(--icon-size, 32px);\n      height: var(--icon-size, 32px);\n    }\n\n    &:is(.tile, .icon) {\n      overflow: hidden;\n      aspect-ratio: 1 / 1;\n\n      img {\n        /* Prevent the image from being dragged */\n        pointer-events: none;\n      }\n    }\n\n    .blur {\n      display: contents;\n\n      & > * {\n        position: absolute;\n        inset: 0;\n        pointer-events: none;\n      }\n\n      .overlay {\n        display: flex;\n        justify-content: center;\n        align-items: center;\n        z-index: -1;\n        backdrop-filter: blur(32px) brightness(0.8);\n      }\n\n      img {\n        width: 100%;\n        height: 100%;\n        z-index: -2;\n        object-fit: cover;\n        transform: scale(1.2);\n\n        &.loaded {\n          opacity: 1;\n        }\n      }\n    }\n\n    &.cover {\n      padding: 0;\n\n      & > :is(:global(img, video)) {\n        flex: auto;\n      }\n    }\n\n    & > :is(:global(img, video)) {\n      flex: 0;\n      max-width: 100%;\n      max-height: 100%;\n    }\n\n    &.dissolve {\n      :is(:global(img, video)) {\n        opacity: 0;\n        transition: opacity 250ms;\n      }\n\n      &.loaded {\n        :is(:global(img, video)) {\n          opacity: 1;\n        }\n      }\n    }\n  }\n\n  /* prettier-ignore */\n  .checkerboard img {\n    /* hardcoded, the same color as the checkerboard in Photoshop */\n    background-image:\n      linear-gradient(45deg, #ccc 25%, transparent 25%, transparent 75%, #ccc 75%),\n      linear-gradient(45deg, #ccc 25%, #fff 25%, #fff 75%, #ccc 75%);\n    background-size: 8px 8px;\n    background-position: 0 0, 4px 4px;\n  }\n\n  :not(.checkerboard) img {\n    /* hardcoded, the same color as the transparent image preview in Chrome and Firefox */\n    background-color: #e5e5e5;\n  }\n\n  :is(:global(img, video)) {\n    object-fit: contain;\n\n    &:not([src]) {\n      visibility: hidden;\n    }\n  }\n\n  .cover :is(:global(img, video)) {\n    object-fit: cover;\n    aspect-ratio: 1 / 1;\n  }\n</style>\n","import { _ } from '@sveltia/i18n';\nimport { sanitize } from 'isomorphic-dompurify';\n\nimport { LINK_SANITIZE_OPTIONS } from '$lib/services/utils/string';\n\n/**\n * @import { MediaLibraryService } from '$lib/types/private';\n */\n\n/**\n * Get the localized label of the credential a cloud storage service asks for, e.g. Secret Access\n * Key. The service’s own label is used if defined, then the one shared by the services with the\n * same API, then the default label for the authentication type.\n * @param {Pick<MediaLibraryService, 'serviceId' | 'compatibleAPI' | 'authType'>} service Service.\n * @returns {string} Localized label.\n */\nexport const getAuthKeyLabel = ({ serviceId, compatibleAPI, authType }) => {\n  const defaultLabel = _(`cloud_storage.auth.${authType}.key_label`);\n\n  const sharedLabel = compatibleAPI\n    ? _(`cloud_storage.${compatibleAPI}.auth_key_label`, { default: defaultLabel })\n    : defaultLabel;\n\n  return _(`cloud_storage.${serviceId}.auth_key_label`, { default: sharedLabel });\n};\n\n/**\n * Get the localized description of an external service that requires an API key, with links to\n * the service’s website and the page where the key can be obtained, and sanitize the result.\n * @param {string} key Localization string key, e.g. `prefs.i18n.translators.description`.\n * @param {object} args Arguments.\n * @param {string} args.service Service label.\n * @param {string} args.developerURL URL of the service’s website.\n * @param {string} args.apiKeyURL URL of the page where the API key can be obtained.\n * @returns {string} Linked and sanitized HTML string.\n */\nexport const getServiceDescription = (key, { service, developerURL, apiKeyURL }) =>\n  sanitize(\n    _(key, {\n      values: { service, homeHref: `href=\"${developerURL}\"`, apiKeyHref: `href=\"${apiKeyURL}\"` },\n    })\n      // Remove invisible characters used for link detection in the locale string\n      .replace(/[\\u2068\\u2069]/g, ''),\n    LINK_SANITIZE_OPTIONS,\n  );\n","<!--\n  @component\n  Prompt the user for the credentials needed to use an external media library service: an API key\n  for a stock photo provider or most cloud storage services, or a username and password for a\n  service that requires signing in. The credentials are saved to the user preferences once\n  validated, so they can be reused across the asset picker, the Asset Library and the Settings\n  dialog.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, EmptyState, SecretInput, TextInput } from '@sveltia/ui';\n  import { sanitize } from 'isomorphic-dompurify';\n\n  import {\n    getAuthKeyLabel,\n    getServiceDescription,\n  } from '$lib/services/integrations/service-description';\n  import { saveApiKey } from '$lib/services/user/api-keys';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import { LINK_SANITIZE_OPTIONS } from '$lib/services/utils/string';\n\n  /**\n   * @import { MediaLibraryService } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {MediaLibraryService} serviceProps Media library service details.\n   * @property {string} [error] Error message shown above the prompt, e.g. when the credentials\n   * saved earlier have been rejected by the service, so the user can enter new ones.\n   * @property {() => void} [onAuth] Called once the credentials have been saved.\n   */\n\n  /** @type {Props} */\n  let { serviceProps, error = undefined, onAuth = undefined } = $props();\n\n  const {\n    serviceType = 'stock_assets',\n    serviceId = '',\n    serviceLabel = '',\n    authType = 'api_key',\n    compatibleAPI,\n    developerURL = '',\n    apiKeyURL = '',\n    apiKeyPattern,\n    signIn,\n  } = $derived(serviceProps);\n\n  const isStockAssets = $derived(serviceType === 'stock_assets');\n\n  const input = $state({ userName: '', password: '' });\n  /** @type {'initial' | 'requested' | 'success' | 'error'} */\n  let authState = $state('initial');\n</script>\n\n<EmptyState>\n  {#if error}\n    <p role=\"alert\" class=\"error\">{error}</p>\n  {/if}\n  <p role=\"alert\">\n    {#if isStockAssets}\n      {@html getServiceDescription('prefs.media.stock_photos.description', {\n        service: serviceLabel,\n        developerURL,\n        apiKeyURL,\n      })}\n    {/if}\n    {#if serviceType === 'cloud_storage'}\n      {@html sanitize(\n        _(`cloud_storage.${serviceId}.auth.${authState}`, {\n          default: _(`cloud_storage.auth.${authType}.${authState}`, {\n            values: {\n              service: serviceLabel,\n              key: getAuthKeyLabel({ serviceId, compatibleAPI, authType }),\n            },\n          }),\n        }),\n        LINK_SANITIZE_OPTIONS,\n      )}\n    {/if}\n  </p>\n  {#if authType === 'api_key'}\n    <div role=\"none\" class=\"input-outer\">\n      <TextInput\n        dir=\"ltr\"\n        flex\n        monospace\n        spellcheck=\"false\"\n        ariaLabel={_('prefs.media.stock_photos.field_label', {\n          values: { service: serviceLabel },\n        })}\n        oninput={(event) => {\n          const { value } = /** @type {HTMLInputElement} */ (event.target);\n\n          if (saveApiKey(serviceId, value, apiKeyPattern) !== undefined) {\n            onAuth?.();\n          }\n        }}\n      />\n    </div>\n  {/if}\n  {#if authType === 'password'}\n    <div role=\"none\" class=\"input-outer\">\n      <TextInput\n        dir=\"ltr\"\n        flex\n        spellcheck=\"false\"\n        ariaLabel={_('username')}\n        disabled={authState === 'requested'}\n        bind:value={input.userName}\n      />\n    </div>\n    <div role=\"none\" class=\"input-outer\">\n      <SecretInput\n        ariaLabel={_('password')}\n        disabled={authState === 'requested'}\n        bind:value={input.password}\n      />\n    </div>\n    <div role=\"none\" class=\"input-outer\">\n      <Button\n        variant=\"secondary\"\n        label={_('sign_in')}\n        disabled={!input.userName || !input.password || authState === 'requested'}\n        onclick={async () => {\n          authState = 'requested';\n          input.userName = input.userName.trim();\n          input.password = input.password.trim();\n\n          if (await signIn?.(input.userName, input.password)) {\n            authState = 'success';\n            prefs.logins ??= {};\n            prefs.logins[serviceId] = [input.userName, input.password].join(' ');\n            onAuth?.();\n          } else {\n            authState = 'error';\n          }\n        }}\n      />\n    </div>\n  {/if}\n</EmptyState>\n\n<style>\n  p {\n    margin: 0 0 8px;\n\n    &.error {\n      color: var(--sui-error-foreground-color);\n    }\n  }\n\n  .input-outer {\n    width: 400px;\n    max-width: 100%;\n    text-align: center;\n  }\n</style>\n","<!--\n  @component\n  Thin wrapper around `<AssetPreview>` that pins the asset kind to `image`. Every property is\n  forwarded as is; see `asset-preview.svelte` for the supported properties and their defaults.\n-->\n<script>\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n\n  /** @type {Record<string, any>} */\n  const { ...rest } = $props();\n</script>\n\n<AssetPreview kind=\"image\" {...rest} />\n","<!--\n  @component\n  An iconic button to remove an item, such as a list item, a key-value pair or a file.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} Props\n   * @property {'ghost'} [variant] Style variant.\n   * @property {'small' | 'medium'} [size] Button size.\n   * @property {boolean} [disabled] Whether the button is disabled.\n   * @property {boolean} [hidden] Whether the button is hidden.\n   * @property {(event: MouseEvent) => void} [onclick] Click event handler.\n   */\n\n  /** @type {Props} */\n  const {\n    variant = undefined,\n    size = 'small',\n    disabled = false,\n    hidden = false,\n    onclick = undefined,\n  } = $props();\n</script>\n\n<Button {variant} {size} iconic {disabled} {hidden} aria-label={_('remove')} {onclick}>\n  {#snippet startIcon()}\n    <Icon name=\"close\" />\n  {/snippet}\n</Button>\n","import { _, locale as appLocale } from '@sveltia/i18n';\n\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @type {Map<string, Intl.NumberFormat>}\n */\nconst fileSizeFormatterCache = new Map();\n\n/**\n * Format the given file size in bytes, KB, MB, GB or TB.\n * @param {number} size File size.\n * @returns {string} Formatted size.\n */\nexport const formatSize = (size) => {\n  const locale = appLocale.current;\n\n  const formatter = getOrCreate(\n    fileSizeFormatterCache,\n    locale,\n    () => new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }),\n  );\n\n  const kb = 1000;\n  const mb = kb * 1000;\n  const gb = mb * 1000;\n  const tb = gb * 1000;\n\n  if (size < kb) {\n    return _('file_size_units.b', { values: { size: formatter.format(size) } });\n  }\n\n  if (size < mb) {\n    return _('file_size_units.kb', { values: { size: formatter.format(size / kb) } });\n  }\n\n  if (size < gb) {\n    return _('file_size_units.mb', { values: { size: formatter.format(size / mb) } });\n  }\n\n  if (size < tb) {\n    return _('file_size_units.gb', { values: { size: formatter.format(size / gb) } });\n  }\n\n  return _('file_size_units.tb', { values: { size: formatter.format(size / tb) } });\n};\n","import { _ } from '@sveltia/i18n';\nimport { getPathInfo } from '@sveltia/utils/file';\n\n/**\n * Get the localized label of the type of the given file, e.g. `PNG image`, from its extension. The\n * extension is matched case-insensitively, so `PHOTO.JPG` is labelled like `photo.jpg`. The MIME\n * subtype of a file can’t be used instead, as it doesn’t always match a label, e.g. `svg+xml`.\n * @param {string} fileName File name or path.\n * @param {object} [options] Options.\n * @param {string} [options.fallback] Label to use for an unknown type. Default: the extension in\n * upper case, or nothing if the file has no extension.\n * @returns {string} Label.\n */\nexport const getFileTypeLabel = (fileName, { fallback } = {}) => {\n  const extension = getPathInfo(fileName).extension?.toLowerCase() ?? '';\n\n  return _(`file_type_labels.${extension}`, { default: fallback ?? extension.toUpperCase() });\n};\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Icon, TruncatedText } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import { onDestroy } from 'svelte';\n\n  import Image from '$lib/components/assets/shared/image.svelte';\n  import RemoveButton from '$lib/components/common/remove-button.svelte';\n  import { formatSize } from '$lib/services/assets/file-size';\n  import { getFileTypeLabel } from '$lib/services/assets/file-type';\n  import { SUPPORTED_IMAGE_TYPES } from '$lib/services/utils/media/image';\n\n  /**\n   * @typedef {object} Props\n   * @property {File[]} files File list.\n   * @property {WeakMap<File, File>} [transformedFileMap] Mapping of transformed files and the\n   * originals.\n   * @property {boolean} [removable] Whether to show the Remove button on each row.\n   * @property {boolean} [showThumbnail] Whether to show a thumbnail of each image file. Disable\n   * this for files the browser cannot decode, which would only ever render as a broken image.\n   */\n\n  /** @type {Props} */\n  let {\n    files = $bindable([]),\n    transformedFileMap = undefined,\n    removable = true,\n    showThumbnail = true,\n  } = $props();\n\n  /**\n   * Thumbnail blob URLs, keyed by the file they were created from. A blob URL keeps the whole file\n   * alive until it’s revoked, so each file gets exactly one URL, reused across renders and released\n   * as soon as the file leaves the list or the component is destroyed. Creating the URL inline in\n   * the markup instead would strand a copy of every previewed upload for the rest of the session.\n   * @type {Map<File, string>}\n   */\n  // eslint-disable-next-line svelte/prefer-svelte-reactivity\n  const thumbnailURLs = new Map();\n\n  /**\n   * Get the thumbnail blob URL for the given file, creating it on first use.\n   * @param {File} file File.\n   * @returns {string} Blob URL.\n   */\n  const getThumbnailURL = (file) => {\n    let url = thumbnailURLs.get(file);\n\n    if (url === undefined) {\n      url = URL.createObjectURL(file);\n      thumbnailURLs.set(file, url);\n    }\n\n    return url;\n  };\n\n  // Release the URLs of files the user has removed from the list. This runs after the render that\n  // added any new files, so a file that is merely reordered keeps its URL — and its `<img>` doesn’t\n  // reload.\n  $effect(() => {\n    const listedFiles = new Set(files);\n\n    thumbnailURLs.forEach((url, file) => {\n      if (!listedFiles.has(file)) {\n        URL.revokeObjectURL(url);\n        thumbnailURLs.delete(file);\n      }\n    });\n  });\n\n  onDestroy(() => {\n    thumbnailURLs.forEach((url) => URL.revokeObjectURL(url));\n    thumbnailURLs.clear();\n  });\n</script>\n\n<div role=\"list\" class=\"files\">\n  {#each files as file, index (`${file.name}-${index}`)}\n    {#await sleep() then}\n      {@const { name, type, size } = file}\n      {@const originalFile = transformedFileMap?.get(file)}\n      <div role=\"listitem\" class=\"file\">\n        {#if showThumbnail && SUPPORTED_IMAGE_TYPES.includes(type)}\n          <Image src={getThumbnailURL(file)} variant=\"icon\" checkerboard={true} />\n        {:else}\n          <span role=\"none\" class=\"image\">\n            <Icon name=\"draft\" />\n          </span>\n        {/if}\n        <div role=\"none\" class=\"info\">\n          <div role=\"none\" class=\"name\">\n            <TruncatedText>\n              {name.normalize()}\n            </TruncatedText>\n          </div>\n          <div role=\"none\" class=\"meta\">\n            {#key appLocale.current}\n              <bdi>\n                {getFileTypeLabel(name)}\n              </bdi>\n              ·\n              <bdi>{formatSize(size)}</bdi>\n            {/key}\n            {#if originalFile && originalFile.type !== file.type}\n              {_('file_meta_converted_from_x', {\n                values: {\n                  type: getFileTypeLabel(originalFile.name),\n                },\n              })}\n            {/if}\n          </div>\n        </div>\n        <RemoveButton\n          variant=\"ghost\"\n          size=\"medium\"\n          hidden={!removable || files.length === 1}\n          onclick={(event) => {\n            event.stopPropagation();\n            // Reassigned rather than spliced, so a parent binding a derived list gets the change\n            files = files.toSpliced(index, 1);\n          }}\n        />\n      </div>\n    {/await}\n  {/each}\n</div>\n\n<style>\n  .files {\n    display: flex;\n    flex-direction: column;\n    gap: 16px;\n    margin: 0 8px;\n  }\n\n  .file {\n    display: flex;\n    align-items: center;\n    gap: 16px;\n    overflow: hidden;\n\n    :global(.preview) {\n      flex: none;\n    }\n\n    .image {\n      flex: none;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      width: 40px;\n      height: 40px;\n      aspect-ratio: 1 / 1;\n      object-fit: cover;\n      border-radius: var(--sui-control-medium-border-radius);\n      background-color: var(--sui-tertiary-background-color);\n    }\n\n    .info {\n      flex: auto;\n      display: flex;\n      flex-direction: column;\n      gap: 4px;\n      overflow: hidden;\n      text-align: start;\n\n      .meta {\n        font-size: var(--sui-font-size-small);\n        color: var(--sui-secondary-foreground-color);\n      }\n    }\n  }\n</style>\n","import { hasAuthInfo, selectedExternalAssets } from '$lib/services/assets/external';\nimport { assetsLocked, canCreateAsset, hasReadonlyAsset } from '$lib/services/assets/folders';\nimport { isCmsFolderPath } from '$lib/services/assets/reserved';\nimport { selectedAssets } from '$lib/services/assets/state';\nimport { getDirName } from '$lib/services/utils/file';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * AssetMoveRequest,\n * ExternalAsset,\n * MediaLibraryService,\n * } from '$lib/types/private';\n */\n\n/**\n * Get the assets that moving to the given directory would actually move, leaving out those that\n * are already there.\n * @param {object} args Arguments.\n * @param {Asset[]} args.assets Assets to be moved.\n * @param {string} args.dirPath Destination directory path.\n * @returns {Asset[]} Assets.\n */\nexport const getMovableAssets = ({ assets, dirPath }) =>\n  assets.filter(({ path }) => getDirName(path) !== dirPath);\n\n/**\n * Whether the given assets can be moved at all: the media library can be changed, and none of the\n * assets is read-only or in a folder the CMS is served from.\n * @param {Asset[]} assets Assets.\n * @returns {boolean} Result.\n */\nexport const canMoveAssets = (assets) =>\n  !!assets.length && !assetsLocked.current && !hasReadonlyAsset(assets);\n\n/**\n * Whether files can be moved to the given cloud storage service: it takes uploads, and the user has\n * entered the credentials for it. The Cloudinary widget handles uploads on its own, so Cloudinary\n * can’t take the files.\n * @param {MediaLibraryService} service Service.\n * @returns {boolean} Result.\n */\nexport const canMoveToService = (service) => !!service.upload && hasAuthInfo(service);\n\n/**\n * Whether files can be moved to a repository directory: one files can be added to, outside the\n * folders the CMS is served from.\n * @param {AssetFolderInfo | undefined} folder Asset folder the directory belongs to.\n * @param {string} dirPath Directory path.\n * @returns {boolean} Result.\n */\nconst canMoveToFolder = (folder, dirPath) =>\n  !!folder && canCreateAsset(folder) && !isCmsFolderPath(dirPath);\n\n/**\n * Whether the given assets can be moved to a directory, as when they’re dropped on it: they can be\n * moved at all, and the directory can take them. A repository directory has to be one files can be\n * added to, and at least one of the assets mustn’t be there already; a name conflict doesn’t count\n * here, as the Move dialog reports it. A cloud storage service has to take uploads, and the user\n * has to have entered the credentials for it.\n * @param {object} args Arguments.\n * @param {Asset[]} args.assets Assets.\n * @param {AssetFolderInfo} [args.folder] Asset folder the directory belongs to, for a repository\n * directory.\n * @param {MediaLibraryService} [args.service] Cloud storage service, for a folder on it.\n * @param {string} args.dirPath Directory path.\n * @returns {boolean} Result.\n */\nexport const canMoveAssetsTo = ({ assets, folder, service, dirPath }) => {\n  if (!canMoveAssets(assets)) {\n    return false;\n  }\n\n  if (service) {\n    return canMoveToService(service);\n  }\n\n  return canMoveToFolder(folder, dirPath) && !!getMovableAssets({ assets, dirPath }).length;\n};\n\n/**\n * Whether the given files on a cloud storage service can be moved elsewhere: the service can delete\n * them once they have been copied, and the media library can be changed, as the entries using them\n * are updated.\n * @param {MediaLibraryService} service Service the files are on.\n * @param {ExternalAsset[]} assets Files.\n * @returns {boolean} Result.\n */\nexport const canMoveExternalAssets = (service, assets) =>\n  !!assets.length && !assetsLocked.current && !!service.delete;\n\n/**\n * Get the files on a cloud storage service that moving to the given destination would actually\n * move. On the same service, the files already in the folder stay where they are, and nothing is\n * moved if the service can’t move a file, as one without folders can’t, or list a folder in full,\n * which tells the names taken there.\n * @param {object} args Arguments.\n * @param {ExternalAsset[]} args.assets Files.\n * @param {MediaLibraryService} args.service Service the files are on.\n * @param {{ service?: MediaLibraryService, dirPath: string }} args.destination Destination: a\n * folder on a service, or a repository directory, which has no service.\n * @returns {ExternalAsset[]} Files.\n */\nexport const getMovableExternalAssets = ({ assets, service, destination }) => {\n  if (destination.service?.serviceId !== service.serviceId) {\n    return assets;\n  }\n\n  return service.move && service.listFolder\n    ? assets.filter(({ description }) => getDirName(description) !== destination.dirPath)\n    : [];\n};\n\n/**\n * Get the files dragged along with the given one from the asset list: every selected file if the\n * file is part of the selection, or the file alone otherwise.\n * @template {{ path?: string, id?: string }} T\n * @param {T} file File whose row the drag starts from.\n * @param {T[]} selectedFiles Selected files.\n * @param {(file: T) => string | undefined} getKey Function telling the files apart.\n * @returns {T[]} Files.\n */\nconst getDraggedFiles = (file, selectedFiles, getKey) =>\n  selectedFiles.some((selected) => getKey(selected) === getKey(file)) ? [...selectedFiles] : [file];\n\n/**\n * Get the request to move the repository assets dragged along with the given one from the asset\n * list: every selected asset if the asset is part of the selection, or the asset alone otherwise.\n * @param {Asset} asset Asset whose row the drag starts from.\n * @returns {AssetMoveRequest | undefined} Request, or `undefined` if the assets can’t be moved.\n */\nexport const getDraggedAssets = (asset) => {\n  const assets = getDraggedFiles(asset, selectedAssets.current, ({ path }) => path);\n\n  return canMoveAssets(assets) ? { assets } : undefined;\n};\n\n/**\n * Get the request to move the files on a cloud storage service dragged along with the given one\n * from the asset list: every selected file if the file is part of the selection, or the file alone\n * otherwise.\n * @param {ExternalAsset} asset File whose row the drag starts from.\n * @param {MediaLibraryService} service Service the file is on.\n * @returns {AssetMoveRequest | undefined} Request, or `undefined` if the files can’t be moved.\n */\nexport const getDraggedExternalAssets = (asset, service) => {\n  const externalAssets = getDraggedFiles(asset, selectedExternalAssets.current, ({ id }) => id);\n\n  return canMoveExternalAssets(service, externalAssets) ? { externalAssets, service } : undefined;\n};\n\n/**\n * Whether the dragged files can be moved to a directory, as when they’re dropped on it. Repository\n * assets are checked as {@link canMoveAssetsTo} does. Files on a cloud storage service can go to a\n * repository directory files can be added to, or to a service that takes uploads and that the user\n * has entered the credentials for; on their own service, at least one of them mustn’t be in the\n * folder already.\n * @param {object} args Arguments.\n * @param {AssetMoveRequest | undefined} args.request Dragged files, if any.\n * @param {AssetFolderInfo} [args.folder] Asset folder the directory belongs to, for a repository\n * directory.\n * @param {MediaLibraryService} [args.service] Cloud storage service, for a folder on it.\n * @param {string} args.dirPath Directory path.\n * @returns {boolean} Result.\n */\nexport const canMoveRequestTo = ({ request, folder, service, dirPath }) => {\n  if (!request) {\n    return false;\n  }\n\n  const { assets = [], externalAssets = [], service: sourceService } = request;\n\n  if (!sourceService) {\n    return canMoveAssetsTo({ assets, folder, service, dirPath });\n  }\n\n  if (!canMoveExternalAssets(sourceService, externalAssets)) {\n    return false;\n  }\n\n  if (service) {\n    return (\n      canMoveToService(service) &&\n      !!getMovableExternalAssets({\n        assets: externalAssets,\n        service: sourceService,\n        destination: { service, dirPath },\n      }).length\n    );\n  }\n\n  return canMoveToFolder(folder, dirPath);\n};\n","import { canMoveRequestTo } from '$lib/services/assets/movable';\nimport { assetMoveRequest, draggedFiles } from '$lib/services/assets/state';\n\n/**\n * @import { Attachment } from 'svelte/attachments';\n * @import { AssetFolderInfo, AssetMoveRequest, MediaLibraryService } from '$lib/types/private';\n */\n\n/**\n * Type of the drag data set when files are dragged from the asset list: the JSON-encoded paths of\n * repository assets or IDs of files on a cloud storage service. It tells such a drag apart from a\n * drag of files from the user’s computer, which the upload drop zone takes.\n */\nexport const ASSET_DRAG_TYPE = 'application/x-sveltia-cms-assets';\n\n/**\n * Class added to a drop target while assets that can be dropped on it are dragged over it.\n */\nconst DRAGOVER_CLASS = 'dragover';\n\n/**\n * Whether the given drag event carries assets dragged from the asset list.\n * @param {DragEvent} event Drag event.\n * @returns {boolean} Result.\n */\nexport const isAssetDrag = (event) => !!event.dataTransfer?.types.includes(ASSET_DRAG_TYPE);\n\n/**\n * Create an attachment that makes a row in the asset list draggable, so the files can be dropped\n * on a folder to be moved there.\n * @param {() => AssetMoveRequest | undefined} getRequest Function returning the files to drag: the\n * selected ones if the row is part of the selection, or the row’s own file otherwise, as a move\n * request. `undefined` if the files can’t be moved.\n * @returns {Attachment<HTMLElement>} Attachment.\n */\nexport const createAssetDragSource = (getRequest) => (element) => {\n  /**\n   * Start dragging the files.\n   * @param {DragEvent} event `dragstart` event.\n   */\n  const onDragStart = (event) => {\n    const request = getRequest();\n\n    if (!request || !event.dataTransfer) {\n      event.preventDefault();\n\n      return;\n    }\n\n    const { assets = [], externalAssets = [] } = request;\n\n    draggedFiles.current = request;\n    event.dataTransfer.effectAllowed = 'move';\n    event.dataTransfer.setData(\n      ASSET_DRAG_TYPE,\n      JSON.stringify([...assets.map(({ path }) => path), ...externalAssets.map(({ id }) => id)]),\n    );\n  };\n\n  /**\n   * Let go of the files once the drag is over, whether or not they have been dropped.\n   */\n  const onDragEnd = () => {\n    draggedFiles.current = undefined;\n  };\n\n  element.draggable = true;\n  element.addEventListener('dragstart', onDragStart);\n  element.addEventListener('dragend', onDragEnd);\n\n  return () => {\n    element.draggable = false;\n    element.removeEventListener('dragstart', onDragStart);\n    element.removeEventListener('dragend', onDragEnd);\n  };\n};\n\n/**\n * Create an attachment that makes a folder or a cloud storage service in the sidebar, or a\n * subfolder in the asset list, a drop target for the files dragged from the list. Dropping them\n * opens the Move dialog with the folder selected, where the move is confirmed. A drag of anything\n * else, like files from the user’s computer, is left alone.\n * @param {object} args Arguments.\n * @param {AssetFolderInfo} [args.folder] Asset folder the directory belongs to, for a repository\n * directory.\n * @param {MediaLibraryService} [args.service] Cloud storage service, for a folder on it.\n * @param {string} args.dirPath Directory path.\n * @returns {Attachment<HTMLElement>} Attachment.\n */\nexport const createAssetDropTarget =\n  ({ folder, service, dirPath }) =>\n  (element) => {\n    /**\n     * Whether the dragged assets can be moved to the directory.\n     * @returns {boolean} Result.\n     */\n    const canDrop = () =>\n      canMoveRequestTo({ request: draggedFiles.current, folder, service, dirPath });\n\n    /**\n     * Tell whether the assets can be dropped here, and highlight the target if they can.\n     * @param {DragEvent} event `dragover` event.\n     */\n    const onDragOver = (event) => {\n      if (!isAssetDrag(event)) {\n        return;\n      }\n\n      // Keep a target inside the asset list from passing the drag on to the upload drop zone\n      event.preventDefault();\n      event.stopPropagation();\n\n      const droppable = canDrop();\n\n      /** @type {DataTransfer} */ (event.dataTransfer).dropEffect = droppable ? 'move' : 'none';\n      element.classList.toggle(DRAGOVER_CLASS, droppable);\n    };\n\n    /**\n     * Remove the highlight once the pointer leaves the target, not one of its descendants.\n     * @param {DragEvent} event `dragleave` event.\n     */\n    const onDragLeave = (event) => {\n      if (!element.contains(/** @type {Node | null} */ (event.relatedTarget))) {\n        element.classList.remove(DRAGOVER_CLASS);\n      }\n    };\n\n    /**\n     * Open the Move dialog for the dropped assets, with the directory selected.\n     * @param {DragEvent} event `drop` event.\n     */\n    const onDrop = (event) => {\n      if (!isAssetDrag(event)) {\n        return;\n      }\n\n      event.preventDefault();\n      event.stopPropagation();\n      element.classList.remove(DRAGOVER_CLASS);\n\n      if (canDrop()) {\n        assetMoveRequest.current = {\n          .../** @type {AssetMoveRequest} */ (draggedFiles.current),\n          dirPath,\n          serviceId: service?.serviceId,\n        };\n      }\n\n      draggedFiles.current = undefined;\n    };\n\n    element.addEventListener('dragover', onDragOver);\n    element.addEventListener('dragleave', onDragLeave);\n    element.addEventListener('drop', onDrop);\n\n    return () => {\n      element.classList.remove(DRAGOVER_CLASS);\n      element.removeEventListener('dragover', onDragOver);\n      element.removeEventListener('dragleave', onDragLeave);\n      element.removeEventListener('drop', onDrop);\n    };\n  };\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { AlertDialog, Button, FilePicker, Icon } from '@sveltia/ui';\n  import { scanFiles } from '@sveltia/utils/file';\n  import { onMount } from 'svelte';\n\n  import UploadAssetsPreview from '$lib/components/assets/shared/upload-assets-preview.svelte';\n  import { isAssetDrag } from '$lib/services/assets/drag';\n  import { getListFormatter } from '$lib/services/contents/i18n';\n  import { env } from '$lib/services/user/env.svelte';\n  import { getAcceptedImageFormatLabels } from '$lib/services/utils/media/image';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [accept] The `accept` attribute for the `<input type=\"file\">`.\n   * @property {boolean} [disabled] Whether to disable new file selection.\n   * @property {boolean} [multiple] Whether to accept multiple files.\n   * @property {boolean} [showUploadButton] Whether to show the upload button.\n   * @property {boolean} [showFilePreview] Whether to show file preview after files are selected.\n   * @property {boolean} [filterDroppedFiles] Whether to drop files that don’t match {@link accept}\n   * and report the mismatch. Disable this when the consumer checks the selection itself, so the\n   * user is told once, in one place. The `accept` attribute still narrows the file picker.\n   * @property {(detail: { files: File[] }) => void} [onDrop] Custom `Drop` event handler.\n   * @property {Snippet} [children] Slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    accept = undefined,\n    disabled = false,\n    multiple = false,\n    showUploadButton = false,\n    showFilePreview = false,\n    filterDroppedFiles = true,\n    onDrop = undefined,\n    children = undefined,\n  } = $props();\n\n  /** @type {HTMLElement | undefined} */\n  let dropTarget = $state();\n  let dragging = $state(false);\n  let typeMismatch = $state(false);\n  let showTypeMismatchAlertDialog = $state(false);\n  /** @type {FilePicker | undefined} */\n  let filePicker = $state();\n  /** @type {File[]}  */\n  let files = $state([]);\n\n  const showDefaultContent = $derived(showUploadButton || (showFilePreview && files.length));\n  // Named formats for the mismatch message, if `accept` is one of the image type lists\n  const acceptedImageFormats = $derived(getAcceptedImageFormatLabels(accept));\n\n  /**\n   * Open the file picker to let the user choose file(s).\n   */\n  export const openFilePicker = () => {\n    filePicker?.open();\n  };\n\n  /**\n   * Reset the file list.\n   */\n  export const reset = () => {\n    // Prevent an infinite loop\n    if (!files.length) {\n      return;\n    }\n\n    files = [];\n    onDrop?.({ files });\n  };\n\n  /**\n   * Format a list of strings for display in the current locale.\n   * @param {string[]} list List of strings.\n   * @returns {string} Formatted list.\n   */\n  const formatList = (list) =>\n    getListFormatter(appLocale.current, { type: 'disjunction' }).format(list);\n\n  /**\n   * Cache the selected files, and notify the list.\n   * @param {File[]} allFiles Files.\n   */\n  const updateFileList = (allFiles) => {\n    files = multiple ? allFiles : allFiles.slice(0, 1);\n    onDrop?.({ files });\n  };\n\n  /**\n   * Handler for custom `Select` events dispatched by the drop target.\n   * @param {Event} event Event.\n   */\n  const onSelect = (event) => {\n    onDrop?.({ files: /** @type {CustomEvent} */ (event).detail.files });\n  };\n\n  onMount(() => {\n    dropTarget?.addEventListener('Select', onSelect);\n\n    return () => {\n      dropTarget?.removeEventListener('Select', onSelect);\n    };\n  });\n\n  $effect(() => {\n    if (!showDefaultContent && typeMismatch) {\n      showTypeMismatchAlertDialog = true;\n    }\n  });\n</script>\n\n{#snippet typeMismatchAlert()}\n  {#if acceptedImageFormats}\n    {_('dropped_image_type_mismatch', { values: { types: formatList(acceptedImageFormats) } })}\n  {:else}\n    {_('dropped_file_type_mismatch', {\n      values: { types: formatList(/** @type {string} */ (accept).split(/,\\s*/)) },\n    })}\n  {/if}\n{/snippet}\n\n<div\n  bind:this={dropTarget}\n  role=\"none\"\n  class=\"drop-target\"\n  ondragover={(event) => {\n    // Assets dragged from the list are moved by dropping them on a folder, not uploaded\n    if (isAssetDrag(event)) {\n      return;\n    }\n\n    event.preventDefault();\n\n    if (disabled || !event.dataTransfer) {\n      return;\n    }\n\n    event.dataTransfer.dropEffect = 'copy';\n    dragging = true;\n    typeMismatch = false;\n  }}\n  ondragleave={(event) => {\n    event.preventDefault();\n\n    if (disabled) {\n      return;\n    }\n\n    dragging = false;\n  }}\n  ondragend={(event) => {\n    event.preventDefault();\n\n    if (disabled) {\n      return;\n    }\n\n    dragging = false;\n  }}\n  ondrop={async (event) => {\n    if (isAssetDrag(event)) {\n      return;\n    }\n\n    event.preventDefault();\n\n    if (disabled || !event.dataTransfer) {\n      return;\n    }\n\n    dragging = false;\n\n    // A drop without any file, like text or a link, is ignored. Check this before the scan, as the\n    // items are no longer available once the event has been handled\n    const hasFiles = Array.from(event.dataTransfer.items).some(({ kind }) => kind === 'file');\n\n    const filteredFileList = await scanFiles(event.dataTransfer, {\n      accept: filterDroppedFiles ? accept : undefined,\n    });\n\n    if (filteredFileList.length) {\n      updateFileList(filteredFileList);\n    } else if (filterDroppedFiles && accept && hasFiles) {\n      typeMismatch = true;\n    }\n  }}\n>\n  <!--\n    File(s) can be selected when `openFilePicker()` is called from outside the component, typically\n    with an external upload button. In that case, the file preview, if enabled, should replace the\n    default slot content.\n  -->\n  {#if showDefaultContent}\n    <div role=\"none\" class=\"content\">\n      {#if showUploadButton}\n        <div role=\"none\">\n          {#if env.hasMouse}\n            {_('drop_files_or_click_to_browse', { values: { count: multiple ? 2 : 1 } })}\n          {:else}\n            {_('tap_to_browse')}\n          {/if}\n        </div>\n        <div role=\"none\">\n          <Button\n            variant=\"primary\"\n            label={_('choose_files', { values: { count: multiple ? 2 : 1 } })}\n            {disabled}\n            onclick={() => {\n              openFilePicker();\n            }}\n          >\n            {#snippet startIcon()}\n              <Icon name=\"cloud_upload\" />\n            {/snippet}\n          </Button>\n        </div>\n        {#if typeMismatch}\n          <div role=\"alert\">\n            {@render typeMismatchAlert()}\n          </div>\n        {/if}\n      {/if}\n      {#if showFilePreview && files.length}\n        <UploadAssetsPreview bind:files />\n      {/if}\n    </div>\n  {:else}\n    {@render children?.()}\n  {/if}\n  {#if dragging}\n    <div role=\"none\" class=\"drop-indicator\">\n      <div role=\"none\">\n        <Icon name=\"download\" />\n        <span role=\"none\">{_('drop_files_here', { values: { count: multiple ? 2 : 1 } })}</span>\n      </div>\n    </div>\n  {/if}\n</div>\n\n<FilePicker\n  {accept}\n  {multiple}\n  bind:this={filePicker}\n  onSelect={({ files: _files }) => {\n    updateFileList(_files);\n  }}\n/>\n\n{#if !showDefaultContent}\n  <AlertDialog bind:open={showTypeMismatchAlertDialog} title={_('unsupported_file_type')}>\n    {@render typeMismatchAlert()}\n  </AlertDialog>\n{/if}\n\n<style>\n  .drop-target {\n    display: flex;\n    flex-direction: column;\n    position: relative;\n    overflow: hidden;\n    height: 100%;\n    pointer-events: auto;\n\n    :global {\n      & > .group {\n        overflow-y: auto;\n        padding: 16px;\n        width: 100%;\n        height: 100%;\n      }\n\n      button:not(:disabled) {\n        pointer-events: auto;\n      }\n    }\n  }\n\n  .drop-indicator {\n    position: absolute;\n    inset: 0;\n    z-index: 10;\n    border-radius: var(--sui-control-large-border-radius);\n    background-color: hsl(var(--sui-background-color-4-hsl) / 80%);\n    -webkit-backdrop-filter: blur(8px);\n    backdrop-filter: blur(8px);\n    text-align: center;\n    pointer-events: none;\n\n    div {\n      position: absolute;\n      inset: 0;\n      display: flex;\n      flex-direction: column;\n      justify-content: center;\n      align-items: center;\n      gap: 4px;\n      border: 4px dashed var(--sui-primary-accent-color);\n      border-radius: var(--sui-control-large-border-radius);\n      font-size: var(--sui-font-size-x-large);\n\n      :global(.icon) {\n        color: var(--sui-secondary-foreground-color);\n        font-size: 48px;\n      }\n    }\n  }\n\n  .content {\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-content: center;\n    gap: 16px;\n    overflow: auto;\n    height: 100%;\n    min-height: 320px;\n    text-align: center;\n  }\n</style>\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { AlertDialog } from '@sveltia/ui';\n\n  import { formatSize } from '$lib/services/assets/file-size';\n  import { getListFormatter } from '$lib/services/contents/i18n';\n  import { getAcceptedImageFormatLabels } from '$lib/services/utils/media/image';\n\n  /**\n   * @import { RejectedFileNames } from '$lib/services/contents/fields/file/resources';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {number} maxSize The maximum allowed file size in bytes.\n   * @property {string} [accept] File types the files are checked against, which are named when a\n   * file is not one of them.\n   */\n\n  /** @type {Props} */\n  let { maxSize, accept = undefined } = $props();\n\n  let open = $state(false);\n  /** @type {string[]} */\n  let oversizedFileNames = $state.raw([]);\n  /** @type {string[]} */\n  let invalidFileNames = $state.raw([]);\n  /** @type {string[]} */\n  let mismatchedFileNames = $state.raw([]);\n\n  /**\n   * Show the dialog if any files were rejected. Nothing happens if every list is empty.\n   * @param {RejectedFileNames} args Names of the rejected files.\n   */\n  export const report = (args) => {\n    const { mismatchedFileNames: mismatched = [] } = args;\n\n    if (!args.oversizedFileNames.length && !args.invalidFileNames.length && !mismatched.length) {\n      return;\n    }\n\n    ({ oversizedFileNames, invalidFileNames } = args);\n    mismatchedFileNames = mismatched;\n    open = true;\n  };\n\n  /**\n   * The dialog covers every rejection reason, so a file batch that hits only one of them keeps the\n   * more specific title. A single dialog is used because two would open into the top layer at once\n   * and stack, hiding one behind the other.\n   */\n  const title = $derived.by(() => {\n    const lists = [oversizedFileNames, invalidFileNames, mismatchedFileNames];\n\n    if (lists.filter((list) => list.length).length > 1) {\n      return _('assets_dialog.rejected_files.title');\n    }\n\n    if (mismatchedFileNames.length) {\n      return _('unsupported_file_type');\n    }\n\n    return invalidFileNames.length\n      ? _('assets_dialog.invalid_file.title')\n      : _('assets_dialog.large_file.title');\n  });\n  // Named formats for the mismatch message, if `accept` is one of the image type lists\n  const acceptedImageFormats = $derived(getAcceptedImageFormatLabels(accept));\n\n  /**\n   * Format a list of strings for display in the current locale.\n   * @param {string[]} list List of strings.\n   * @returns {string} Formatted list.\n   */\n  const formatList = (list) =>\n    getListFormatter(appLocale.current, { type: 'disjunction' }).format(list);\n</script>\n\n{#snippet fileList(/** @type {string[]} */ names)}\n  <ul class=\"filenames\">\n    {#each names as name, index (`${name}-${index}`)}\n      <li>{name}</li>\n    {/each}\n  </ul>\n{/snippet}\n\n<AlertDialog bind:open {title}>\n  {#if oversizedFileNames.length}\n    <div>\n      {_('warning_oversized_files', {\n        values: { count: oversizedFileNames.length, size: formatSize(maxSize) },\n      })}\n    </div>\n    {@render fileList(oversizedFileNames)}\n  {/if}\n  {#if invalidFileNames.length}\n    <div>\n      {_('warning_invalid_files', { values: { count: invalidFileNames.length } })}\n    </div>\n    {@render fileList(invalidFileNames)}\n  {/if}\n  {#if mismatchedFileNames.length}\n    <div>\n      {#if acceptedImageFormats}\n        {_('warning_unsupported_image_files', {\n          values: { count: mismatchedFileNames.length, types: formatList(acceptedImageFormats) },\n        })}\n      {:else}\n        {_('warning_unsupported_files', {\n          values: {\n            count: mismatchedFileNames.length,\n            types: formatList(/** @type {string} */ (accept).split(/,\\s*/)),\n          },\n        })}\n      {/if}\n    </div>\n    {@render fileList(mismatchedFileNames)}\n  {/if}\n</AlertDialog>\n\n<style>\n  div:not(:first-child) {\n    margin-top: 8px;\n  }\n\n  .filenames {\n    border-radius: var(--sui-control-medium-border-radius);\n    padding: 12px;\n    background-color: var(--sui-tertiary-background-color);\n    font-size: var(--sui-font-size-default);\n  }\n\n  ul {\n    margin: 8px 0 0;\n    padding: 0;\n    list-style: none;\n  }\n\n  li {\n    margin: 0;\n    padding: 0;\n  }\n</style>\n","import { getFolderPublicPath } from '$lib/services/assets/info';\nimport { canBrowseSubfolders, getRelativePath } from '$lib/services/assets/subfolders';\nimport { findPreferredLibraryName } from '$lib/services/integrations/media-libraries/options';\nimport {\n  allStockAssetProviders,\n  getStockAssetMediaLibraryOptions,\n} from '$lib/services/integrations/media-libraries/stock';\nimport { getDirName } from '$lib/services/utils/file';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * AssetLibraryFolderMap,\n * ExternalAsset,\n * MediaLibraryFetchOptions,\n * MediaLibraryService,\n * SelectedResource,\n * } from '$lib/types/private';\n * @import { MediaField, StockAssetProviderName } from '$lib/types/public';\n */\n\n/**\n * Sort services by their label in alphabetical order.\n * @param {[string, { serviceLabel: string }]} a First service entry.\n * @param {[string, { serviceLabel: string }]} b Second service entry.\n * @returns {number} Sorting order value.\n */\nexport const sortServicesByName = (a, b) => {\n  const nameA = a[1].serviceLabel.toLowerCase();\n  const nameB = b[1].serviceLabel.toLowerCase();\n\n  return nameA.localeCompare(nameB);\n};\n\n/**\n * Check if a repository folder is offered in the Select Assets dialog. Folder selection takes a\n * folder that can be browsed by subfolder.\n * @param {{ folder: AssetFolderInfo | undefined, enabled: boolean }} entry Folder map entry.\n * @param {boolean} selectFolder Whether a folder is to be selected instead of files.\n * @returns {boolean} Result.\n */\nexport const isFolderOffered = ({ folder, enabled }, selectFolder) =>\n  enabled && (!selectFolder || canBrowseSubfolders(folder));\n\n/**\n * Get the name of the first repository folder offered in the dialog, which is selected when the\n * dialog opens.\n * @param {object} args Arguments.\n * @param {AssetLibraryFolderMap} args.assetLibraryFolderMap Asset library folder map.\n * @param {boolean} args.isDefaultLibraryEnabled Whether the default media library is enabled.\n * @param {boolean} args.selectFolder Whether a folder is to be selected instead of files.\n * @returns {string | undefined} Library name, e.g. `default-collection`, or `undefined` if no\n * folder is offered.\n */\nexport const getFirstDefaultLibraryName = ({\n  assetLibraryFolderMap,\n  isDefaultLibraryEnabled,\n  selectFolder,\n}) => {\n  if (!isDefaultLibraryEnabled) {\n    return undefined;\n  }\n\n  const id = Object.entries(assetLibraryFolderMap).find(([, entry]) =>\n    isFolderOffered(entry, selectFolder),\n  )?.[0];\n\n  return id ? `default-${id}` : undefined;\n};\n\n/**\n * Get the name of the location selected when the dialog opens: the first location marked with the\n * `default` option that’s offered, or else the first repository folder offered, or else\n * the first cloud storage service if there are files to be uploaded to it, or else the first\n * external service.\n * @param {object} args Arguments.\n * @param {AssetLibraryFolderMap} args.assetLibraryFolderMap Asset library folder map.\n * @param {boolean} args.isDefaultLibraryEnabled Whether the default media library is enabled.\n * @param {boolean} args.selectFolder Whether a folder is to be selected instead of files.\n * @param {boolean} args.hasPendingFiles Whether files dropped on the field are waiting to be\n * uploaded to a cloud storage service.\n * @param {[string, MediaLibraryService][]} args.cloudServiceEntries Cloud storage services offered.\n * @param {[string, MediaLibraryService][]} args.externalServiceEntries Cloud storage services and\n * stock asset providers offered, sorted by name.\n * @param {string[]} [args.preferredLibraryNames] Names of the media libraries marked with the\n * `default` option, in order of precedence. The default library, `default`, stands for the first\n * repository folder offered.\n * @returns {string} Library name. Empty if no location is offered, which is the case when a folder\n * is to be selected but the field has no folder that can be browsed.\n */\nexport const getInitialLibraryName = ({\n  assetLibraryFolderMap,\n  isDefaultLibraryEnabled,\n  selectFolder,\n  hasPendingFiles,\n  cloudServiceEntries,\n  externalServiceEntries,\n  preferredLibraryNames = [],\n}) => {\n  const firstDefaultLibraryName = getFirstDefaultLibraryName({\n    assetLibraryFolderMap,\n    isDefaultLibraryEnabled,\n    selectFolder,\n  });\n\n  // A cloud storage service isn’t offered when a folder is to be selected, or when it’s disabled\n  // for the field. Files waiting to be uploaded need a service that can take them.\n  const preferredName = findPreferredLibraryName({\n    preferredLibraryNames,\n    repositoryAvailable: !!firstDefaultLibraryName,\n    cloudServiceEntries,\n    uploadRequired: hasPendingFiles,\n  });\n\n  if (preferredName && preferredName !== 'default') {\n    return preferredName;\n  }\n\n  if (firstDefaultLibraryName) {\n    return firstDefaultLibraryName;\n  }\n\n  // A cloud storage service can take the files to be uploaded\n  const [serviceId] = (hasPendingFiles ? cloudServiceEntries[0] : undefined) ??\n    externalServiceEntries[0] ?? [''];\n\n  return serviceId;\n};\n\n/**\n * Get the stock asset providers offered in the dialog, sorted by name.\n * @param {object} args Arguments.\n * @param {MediaField} [args.fieldConfig] Field configuration.\n * @param {boolean} args.selectFolder Whether a folder is to be selected instead of files. A folder\n * can only be picked from the repository, so no provider is offered then.\n * @param {boolean} args.isDefaultLibraryEnabled Whether the default media library is enabled.\n * @returns {[string, MediaLibraryService][]} Provider entries.\n */\nexport const getStockAssetProviderEntries = ({\n  fieldConfig,\n  selectFolder,\n  isDefaultLibraryEnabled,\n}) => {\n  if (selectFolder) {\n    return [];\n  }\n\n  const { providers = [] } = getStockAssetMediaLibraryOptions({ fieldConfig });\n\n  return Object.entries(allStockAssetProviders)\n    .filter(\n      ([serviceId, { hotlinking }]) =>\n        providers.includes(/** @type {StockAssetProviderName} */ (serviceId)) &&\n        // When hotlinking is not required, files are downloaded and then uploaded to the\n        // repository, so the default library has to be configured.\n        (hotlinking || isDefaultLibraryEnabled),\n    )\n    .sort(sortServicesByName);\n};\n\n/**\n * Get the public paths of the folders to be picked: the selected subfolders, or the directory being\n * browsed.\n * @param {object} args Arguments.\n * @param {boolean} args.selectFolder Whether a folder is to be selected instead of files.\n * @param {boolean} args.browsingSubfolders Whether the selected folder is browsed by subfolder.\n * @param {AssetFolderInfo | undefined} args.folder Selected folder, which is always set while it’s\n * browsed by subfolder.\n * @param {string | undefined} args.basePath Path of the selected folder, which is always set while\n * it’s browsed by subfolder.\n * @param {string} args.subfolderPath Path of the directory being browsed, relative to the folder.\n * @param {string[]} args.selectedSubfolderPaths Paths of the selected subfolders.\n * @returns {string[]} Public paths. Empty unless a folder is to be picked from a folder that can be\n * browsed.\n */\nexport const getPickedFolderPublicPaths = ({\n  selectFolder,\n  browsingSubfolders,\n  folder,\n  basePath,\n  subfolderPath,\n  selectedSubfolderPaths,\n}) => {\n  if (!selectFolder || !browsingSubfolders) {\n    return [];\n  }\n\n  const subfolderPaths = selectedSubfolderPaths.length\n    ? selectedSubfolderPaths.map((path) => getRelativePath(path, /** @type {string} */ (basePath)))\n    : [subfolderPath];\n\n  return subfolderPaths.map((path) =>\n    getFolderPublicPath({ folder: /** @type {AssetFolderInfo} */ (folder), subfolderPath: path }),\n  );\n};\n\n/**\n * Get the subfolder an unsaved asset is going to be saved to, which its provisional path holds.\n * @param {Asset} asset Unsaved asset.\n * @param {string | undefined} targetFolderPath Path of the target folder.\n * @returns {string} Subfolder path relative to the target folder. Empty for the folder root.\n */\nexport const getUnsavedAssetSubfolderPath = ({ path }, targetFolderPath) =>\n  targetFolderPath !== undefined ? getDirName(getRelativePath(path, targetFolderPath)) : '';\n\n/**\n * Get the resources to hand over to the field once the Insert button is clicked. An unsaved asset\n * becomes the file to be saved, along with its target folder and subfolder.\n * @param {object} args Arguments.\n * @param {SelectedResource[]} args.resources Selected resources.\n * @param {string | undefined} args.targetFolderPath Path of the target folder.\n * @returns {SelectedResource[]} Resources.\n */\nexport const getInsertedResources = ({ resources, targetFolderPath }) =>\n  resources.map((resource) => {\n    const { asset, replace } = resource;\n\n    if (!asset?.unsaved) {\n      return $state.snapshot(resource);\n    }\n\n    // The `File` is taken as is: `$state.snapshot()` would clone it with `structuredClone()`, and\n    // the copy would then have to be read and hashed all over again\n    return {\n      file: asset.file,\n      folder: $state.snapshot(asset.folder),\n      subfolderPath: getUnsavedAssetSubfolderPath(asset, targetFolderPath),\n      replace,\n    };\n  });\n\n/**\n * Get the selection with a newly selected resource. A single selection is replaced as a whole: the\n * list box only deselects the options it shows, so an earlier pick hidden by a search or left in\n * another folder would otherwise stay selected.\n * @param {object} args Arguments.\n * @param {SelectedResource[]} args.resources Currently selected resources.\n * @param {SelectedResource} args.resource Newly selected resource.\n * @param {(resource: SelectedResource) => boolean} args.isSame Function telling whether a selected\n * resource is the same as the new one, so that it is not listed twice.\n * @param {boolean} [args.multiple] Whether multiple resources can be selected.\n * @returns {SelectedResource[]} New selection.\n */\nexport const getSelectionWithResource = ({ resources, resource, isSame, multiple = false }) =>\n  multiple ? [...resources.filter((r) => !isSame(r)), resource] : [resource];\n\n/**\n * Get the resources selected on a location the user has just switched to. The URL entered under\n * Enter URL is kept while another location is browsed, so it’s selected again on coming back, while\n * the selection made on any other location starts afresh.\n * @param {object} args Arguments.\n * @param {string} args.libraryName Name of the location switched to.\n * @param {string} args.enteredURL URL entered under Enter URL, if any.\n * @returns {SelectedResource[]} Resources.\n */\nexport const getLocationResources = ({ libraryName, enteredURL }) => {\n  const url = libraryName === 'enter-url' ? enteredURL.trim() : '';\n\n  return url ? [{ url }] : [];\n};\n\n/**\n * Let a stock asset service know its assets have been inserted, if its API guidelines require it,\n * like Unsplash’s. The requests are not awaited, so they never hold up the insertion.\n * @param {object} args Arguments.\n * @param {MediaLibraryService['trackDownload']} args.trackDownload Service’s function to report a\n * used asset, if any.\n * @param {SelectedResource[]} args.resources Inserted resources.\n * @param {Map<string, ExternalAsset>} args.assets Selected assets, keyed by download URL.\n * @param {MediaLibraryFetchOptions} args.options Options, including the API key.\n */\nexport const trackInsertedExternalAssets = ({ trackDownload, resources, assets, options }) => {\n  if (!trackDownload) {\n    return;\n  }\n\n  resources.forEach(({ url }) => {\n    const asset = url ? assets.get(url) : undefined;\n\n    if (asset) {\n      // The service never rejects, but an unexpected error mustn’t surface either\n      trackDownload(asset, options).catch(() => {});\n    }\n  });\n};\n","import { createDeepState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { UpdateToastState } from '$lib/types/private';\n */\n\n/**\n * @type {UpdateToastState}\n */\nexport const UPDATE_TOAST_DEFAULT_STATE = {\n  saved: false,\n  moved: false,\n  renamed: false,\n  deleted: false,\n  folderCreated: false,\n  folderRenamed: false,\n  folderDeleted: false,\n  deletionPending: false,\n  discarded: false,\n  deletionCancelled: false,\n  alreadyPublished: false,\n  published: false,\n  count: 1,\n};\n\n/**\n * State of the content updates toast notification.\n * @type {{ current: UpdateToastState }}\n */\nexport const contentUpdatesToast = createDeepState({ ...UPDATE_TOAST_DEFAULT_STATE });\n","import { getAssetByInternalPath } from '$lib/services/assets';\nimport { focusedAsset, overlaidAsset } from '$lib/services/assets/state';\nimport { UPDATE_TOAST_DEFAULT_STATE } from '$lib/services/contents/collection/data';\nimport { createDeepState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Asset, UpdateToastState } from '$lib/types/private';\n */\n\n/**\n * State of the asset updates toast notification.\n * @type {{ current: UpdateToastState }}\n */\nexport const assetUpdatesToast = createDeepState({ ...UPDATE_TOAST_DEFAULT_STATE });\n\n/**\n * State of the toasts reporting an asset commit under way and one that has failed, set by\n * `runAssetCommit()`. `pending` counts the commits under way; while any are, the `progress`\n * message of the latest one still running is shown. `failed` shows the `failure` message. The\n * messages are kept once the toasts are hidden, so they don’t go blank while fading out.\n * @type {{ current: { pending: number, progress: string, failed: boolean, failure: string } }}\n */\nexport const assetCommitToast = createDeepState({\n  pending: 0,\n  progress: '',\n  failed: false,\n  failure: '',\n});\n\n/**\n * Replace the focused and overlaid assets with the ones now in the asset list, after the assets\n * have been saved, moved or renamed.\n * @param {(asset: Asset) => string | undefined} getPath Function to get the path the given asset is\n * now found at, or `undefined` to leave it as is.\n */\nexport const refreshFocusedAssets = (getPath) => {\n  [focusedAsset, overlaidAsset].forEach((state) => {\n    const path = state.current ? getPath(state.current) : undefined;\n\n    if (path !== undefined) {\n      state.current = getAssetByInternalPath(path);\n    }\n  });\n};\n","import { backend } from '$lib/services/backends';\nimport { createBaseCommitMessage } from '$lib/services/backends/git/shared/commits';\nimport { toRepoChanges } from '$lib/services/backends/root-dir';\nimport { cmsConfig } from '$lib/services/config';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { createRawState, requestAnswer } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * CommitMessagePromptMode,\n * CommitMessageRequest,\n * CommitOptions,\n * FileChange,\n * } from '$lib/types/private';\n * @import { GitBackend } from '$lib/types/public';\n */\n\n/**\n * Message of the error thrown when the user cancels a commit by dismissing the prompt.\n */\nconst COMMIT_CANCELLED = 'commit_cancelled';\n\n/**\n * The pending request for a commit message, which the UI turns into a prompt dialog. It’s\n * `undefined` while no request is outstanding.\n * @type {{ current: CommitMessageRequest | undefined }}\n */\nexport const commitMessageRequest = createRawState();\n\n/**\n * Text last entered in the prompt with the `prefix` or `suffix` mode. It’s typically an issue\n * number that the next few commits share, so the prompt starts with it. Kept for the session only.\n */\nlet lastAddition = '';\n\n/**\n * Check if the given error has been thrown because the user cancelled a commit.\n * @param {any} ex Error.\n * @returns {boolean} Result.\n */\nexport const isCommitCancelled = (ex) => ex?.message === COMMIT_CANCELLED;\n\n/**\n * Run an action that commits changes, and sort out how it ended. A cancellation at the commit\n * message prompt isn’t a failure, so it’s not logged. Any other error is logged to the console.\n * @template T\n * @param {() => Promise<T>} action Action to run.\n * @returns {Promise<{ ok: true, cancelled: false, result: T, error: undefined }\n * | { ok: false, cancelled: boolean, result: undefined, error: any }>} Outcome. `error` is what\n * the action threw, whether it was a cancellation or a failure.\n */\nexport const runCommit = async (action) => {\n  try {\n    return { ok: true, cancelled: false, result: await action(), error: undefined };\n  } catch (/** @type {any} */ ex) {\n    const cancelled = isCommitCancelled(ex);\n\n    if (!cancelled) {\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    }\n\n    return { ok: false, cancelled, result: undefined, error: ex };\n  }\n};\n\n/**\n * Get how the user is asked for a commit message. The user is only asked when the changes are\n * actually committed: by a Git backend, or by the local backend with local Git commits turned on.\n * @returns {CommitMessagePromptMode | undefined} Mode, or `undefined` if the user isn’t asked.\n */\nexport const getCommitMessagePromptMode = () => {\n  const { current: _cmsConfig } = cmsConfig;\n  const { current: _backend } = backend;\n\n  if (\n    !_cmsConfig ||\n    !_backend ||\n    !(_backend.isGit || (_backend.name === 'local' && prefs.localGitCommits))\n  ) {\n    return undefined;\n  }\n\n  const { prompt_commit_messages: mode } = /** @type {GitBackend} */ (_cmsConfig.backend);\n\n  return mode === true || mode === 'prefix' || mode === 'suffix' ? mode : undefined;\n};\n\n/**\n * Ask the user for a commit message, and wait for the answer.\n * @param {object} args Arguments.\n * @param {CommitMessagePromptMode} args.mode How the text the user enters is used.\n * @param {string} args.defaultMessage Message made from the template.\n * @returns {Promise<string | null>} Text entered, or `null` if the user has cancelled.\n */\nconst requestCommitMessage = async ({ mode, defaultMessage }) =>\n  // Saves are made one at a time, so a second request can’t normally be outstanding, but an earlier\n  // one is answered just in case\n  requestAnswer(\n    commitMessageRequest,\n    { mode, defaultMessage, initialValue: mode === true ? defaultMessage : lastAddition },\n    null,\n  );\n\n/**\n * Ask the user for a commit message if the `prompt_commit_messages` backend option is set, and add\n * the answer to the commit options. Nothing is asked if the options already have one, e.g. when the\n * same answer is used for several commits.\n * @param {FileChange[]} changes Changes to be committed, with paths relative to the root directory.\n * @param {CommitOptions} options Commit options.\n * @returns {Promise<CommitOptions>} Commit options, with the user’s message if asked.\n * @throws {Error} When the user has cancelled the commit. Use {@link isCommitCancelled} to tell it\n * from a failure.\n */\nexport const promptCommitMessage = async (changes, options) => {\n  const mode = getCommitMessagePromptMode();\n\n  if (!mode || options.userMessage !== undefined) {\n    return options;\n  }\n\n  // The commit message names the paths relative to the repository root\n  const defaultMessage = createBaseCommitMessage(toRepoChanges(changes), options);\n  const message = await requestCommitMessage({ mode, defaultMessage });\n\n  if (message === null) {\n    throw new Error(COMMIT_CANCELLED);\n  }\n\n  let userMessage = message.trim();\n\n  if (mode === true) {\n    // An unchanged message is made from the template again when committing, which can then tell\n    // the files apart more accurately, e.g. when several entries are stored in the same file\n    if (userMessage === defaultMessage) {\n      userMessage = '';\n    }\n  } else {\n    lastAddition = userMessage;\n  }\n\n  return { ...options, userMessage };\n};\n","import { tick } from 'svelte';\n\nimport { assetCommitToast } from '$lib/services/assets/data';\nimport { runCommit } from '$lib/services/backends/commit-prompt';\n\n/**\n * Progress messages of the commits under way, in the order they started. The toast shows the\n * latest one still running, so a commit finishing doesn’t leave its message up for another.\n * @type {string[]}\n */\nconst runningMessages = [];\n\n/**\n * Run an action that commits changes to assets, or otherwise saves them, and report how it goes\n * through {@link assetCommitToast}: a progress toast while it’s under way, if a message is given,\n * as committing to a remote repository takes a few seconds and the dialog that started it is\n * usually gone by then, and a failure toast if it fails. A cancellation at the commit message\n * prompt isn’t a failure. A success is reported by the action itself, through `assetUpdatesToast`.\n * @template T\n * @param {() => Promise<T>} action Action to run.\n * @param {object} messages Message keys.\n * @param {string} [messages.progress] Progress message, if any.\n * @param {string} messages.failure Failure message.\n * @returns {ReturnType<typeof runCommit<T>>} Outcome, as returned by `runCommit()`.\n */\nexport const runAssetCommit = async (action, { progress, failure }) => {\n  if (progress) {\n    runningMessages.push(progress);\n    Object.assign(assetCommitToast.current, { progress, pending: runningMessages.length });\n  }\n\n  const outcome = await runCommit(action);\n\n  if (progress) {\n    runningMessages.splice(runningMessages.indexOf(progress), 1);\n    assetCommitToast.current.pending = runningMessages.length;\n\n    if (runningMessages.length) {\n      assetCommitToast.current.progress = /** @type {string} */ (runningMessages.at(-1));\n    }\n  }\n\n  if (!outcome.ok && !outcome.cancelled) {\n    // Hide a failure toast that’s still up first, so the new one gets its full display time\n    if (assetCommitToast.current.failed) {\n      assetCommitToast.current.failed = false;\n      await tick();\n    }\n\n    Object.assign(assetCommitToast.current, { failure, failed: true });\n  }\n\n  return outcome;\n};\n","import { getAssetBlob } from '$lib/services/assets/info';\nimport { readBlobAsFile } from '$lib/services/utils/file';\n\n/**\n * @import { Asset, FileChange } from '$lib/types/private';\n */\n\n/**\n * Create the file change that moves the given asset to another path.\n * @param {Asset} asset Asset to move.\n * @param {string} path New path.\n * @param {string} [name] File name at the new path. Default: the asset’s current name.\n * @returns {Promise<FileChange>} Change.\n */\nexport const createAssetMoveChange = async (asset, path, name = asset.name) => {\n  const blob = asset.file ?? (await getAssetBlob(asset));\n\n  return {\n    action: 'move',\n    path,\n    previousPath: asset.path,\n    previousSha: asset.sha,\n    // The file about to be moved away can’t be read afterwards, to write the copy or to hash it\n    data: await readBlobAsFile(blob, name),\n  };\n};\n","import { getAssetPublicURL } from '$lib/services/assets/info';\n\n/**\n * @import { Asset } from '$lib/types/private';\n * @import { AssetReferenceTarget } from '$lib/services/assets/references';\n */\n\n/**\n * Get what the references to the given asset are matched by: the public path of an asset that has\n * one, in the form it’s stored in a field value, or else the asset itself, as in an entry-relative\n * folder, where a value like `images/photo.jpg` refers to a different file in each entry’s folder,\n * so only a value resolving to the asset refers to it. The same goes for a relative public path, as\n * with an empty `public_folder`, which stores a bare path relative to the media folder, e.g.\n * `photo.jpg`, or one starting with `.`: another collection’s media folder can hold a different\n * file stored as the same value. A path starting with `/` or `@`, or a URL, refers to one file\n * only. The asset is matched without being loaded, unlike by its blob URL.\n * @param {Asset} asset Asset.\n * @returns {AssetReferenceTarget} Target. The URL is not stripped of the site’s base URL, see\n * `getComparableAssetURL()`.\n */\nexport const getAssetReferenceTarget = (asset) => {\n  const url = asset.folder.entryRelative\n    ? undefined\n    : getAssetPublicURL(asset, { allowSpecial: true, pathOnly: true });\n\n  return url === undefined || !/^(?:[/@]|[a-z][\\d+.a-z-]*:\\/\\/)/i.test(url) ? { asset } : { url };\n};\n","import { isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { MULTI_VALUE_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { forEachSubFieldConfig } from '$lib/services/contents/fields/list/subfields';\n\n/**\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Parse a field to generate a sorted key path list.\n * @param {object} args Arguments.\n * @param {Field} args.field Single field.\n * @param {FieldKeyPath} args.keyPath Key path of the field.\n * @param {FieldKeyPath[]} args.keyPathList Key path list.\n */\nconst parseField = ({ field, keyPath, keyPathList }) => {\n  const { widget: fieldType } = field;\n\n  keyPathList.push(keyPath);\n\n  if (fieldType === 'list' || fieldType === 'object') {\n    const { field: subField, fields, types, typeKey = 'type' } = /** @type {any} */ (field);\n    const prefix = fieldType === 'list' ? `${keyPath}.*` : keyPath;\n\n    if (types && !fields) {\n      keyPathList.push(`${prefix}.${typeKey}`);\n    } else if (fieldType === 'list' && !fields && !subField) {\n      keyPathList.push(prefix);\n    }\n\n    forEachSubFieldConfig(field, keyPath, (_field, _keyPath) => {\n      parseField({ field: _field, keyPath: _keyPath, keyPathList });\n    });\n  } else if (fieldType && MULTI_VALUE_FIELD_TYPES.includes(fieldType) && isFieldMultiple(field)) {\n    // Only add wildcard path for multi-value field types that aren’t list/object\n    keyPathList.push(`${keyPath}.*`);\n  }\n};\n\n/**\n * Create a list of field names (flattened key path list) from the configured collection fields.\n * @param {Field[]} fields Field list of a collection or a file.\n * @returns {FieldKeyPath[]} Sorted key path list. List items are with `*`.\n * @example [`author.name`, `books.*.title`, `books.*.summary`, `publishDate`, `body`]\n */\nexport const createKeyPathList = (fields) => {\n  /** @type {FieldKeyPath[]} */\n  const keyPathList = [];\n\n  // Iterate over the top-level fields first\n  fields.forEach((field) => {\n    parseField({\n      field,\n      keyPath: field.name,\n      keyPathList,\n    });\n  });\n\n  return keyPathList;\n};\n","/**\n * @import { Entry, FlattenedEntryContent, LocalizedEntry } from '$lib/types/private';\n */\n\n/**\n * Function returning the new content of a locale. The content of the entry it’s given is shared\n * with the store, so it has to return a copy rather than change it.\n * @callback EntryContentGetter\n * @param {{ locale: string, localizedEntry: LocalizedEntry }} args Arguments.\n * @returns {FlattenedEntryContent} New content.\n */\n\n/**\n * Replace the content of every locale of an entry that has content. A locale that was disabled only\n * carries the path of its file, and is left as is.\n * @param {Entry} entry Entry.\n * @param {EntryContentGetter} getContent Function returning the new content.\n * @returns {Entry} Copy of the entry with the new content.\n */\nexport const mapEntryContent = (entry, getContent) => ({\n  ...entry,\n  locales: Object.fromEntries(\n    Object.entries(entry.locales).map(([locale, localizedEntry]) => [\n      locale,\n      localizedEntry.content\n        ? { ...localizedEntry, content: getContent({ locale, localizedEntry }) }\n        : localizedEntry,\n    ]),\n  ),\n});\n","import { getDateTimeParts } from '@sveltia/utils/datetime';\nimport dayjs from 'dayjs';\nimport dayjsCustomParseFormat from 'dayjs/plugin/customParseFormat';\nimport dayjsLocalizedFormat from 'dayjs/plugin/localizedFormat';\nimport dayjsUTC from 'dayjs/plugin/utc';\n\nimport { backend } from '$lib/services/backends';\nimport { getSlugTimeZone } from '$lib/services/common/slug';\nimport { fillTemplate } from '$lib/services/common/template';\nimport { DATE_TIME_TEMPLATE_REGEX } from '$lib/services/common/template/constants';\nimport { cmsConfig } from '$lib/services/config';\nimport {\n  getIndexFile,\n  isCollectionIndexFile,\n} from '$lib/services/contents/collection/entries/index-file';\nimport { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\nimport { getDate, isValidDate } from '$lib/services/contents/fields/date-time/parse';\nimport { omitLocalePlaceholder } from '$lib/services/contents/i18n/placeholder';\nimport { addSharedValues } from '$lib/services/contents/i18n/shared-values';\nimport { encodePathSegments } from '$lib/services/utils/url';\n\n/**\n * @import {\n * Entry,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { DateTimeField, Field } from '$lib/types/public';\n */\n\ndayjs.extend(dayjsCustomParseFormat);\ndayjs.extend(dayjsLocalizedFormat);\ndayjs.extend(dayjsUTC);\n\n/**\n * Determine date and time parts from the given entry content.\n * @param {object} args Arguments.\n * @param {string} [args.dateFieldName] Date field name.\n * @param {Field[]} args.fields Fields.\n * @param {FlattenedEntryContent} args.content Entry content.\n * @param {InternalLocaleCode} [args.locale] Locale of the content.\n * @param {boolean} [args.inSlugTimeZone] Whether to read a date/time value in the time zone of the\n * slug template tags instead of the field’s own. See `getSlugTimeZone()`. A date-only value is\n * always read as written.\n * @returns {Record<string, string> | undefined} Date and time parts.\n */\nexport const extractDateTime = ({ dateFieldName, fields, content, locale, inSlugTimeZone }) => {\n  const fieldConfig = dateFieldName\n    ? fields.find(({ widget, name }) => widget === 'datetime' && name === dateFieldName)\n    : fields.find(({ widget }) => widget === 'datetime');\n\n  const fieldValue = fieldConfig ? content[fieldConfig.name] : undefined;\n\n  if (!fieldConfig || !fieldValue) {\n    return undefined;\n  }\n\n  const config = /** @type {DateTimeField} */ (fieldConfig);\n  const date = getDate(fieldValue, config, locale);\n\n  if (!isValidDate(date)) {\n    return undefined;\n  }\n\n  const { format, dateOnly, utc, outputUTC, singleCustomTimeZone } = parseDateTimeConfig(config);\n\n  // Read the parts in the time zone `getDate()` parsed the value in: a date without a custom format\n  // is UTC midnight, while one in a custom format is the browser’s midnight, and a date/time is\n  // shown in the field’s custom time zone if any, like in the input\n  const fieldTimeZone =\n    utc || outputUTC || (dateOnly && !format) ? 'UTC' : dateOnly ? undefined : singleCustomTimeZone;\n\n  if (inSlugTimeZone && !dateOnly) {\n    return getDateTimeParts({ date, timeZone: getSlugTimeZone() });\n  }\n\n  return getDateTimeParts({ date, timeZone: fieldTimeZone });\n};\n\n/**\n * Fill the given path template with an entry’s values, the way the `preview_path` option is filled:\n * besides field values, it supports the `{{slug}}`, `{{locale}}`, `{{dirname}}`, `{{filename}}`\n * and date/time tags. It’s also used for a path given as the `thumbnail` option.\n * @param {object} args Arguments.\n * @param {string} args.pathTemplate Path template.\n * @param {string} [args.dateFieldName] Name of the DateTime field to fill the date/time tags from.\n * If omitted, the first DateTime field is used.\n * @param {Field[]} args.fields Fields of the collection or collection file.\n * @param {InternalCollection} args.collection Collection.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only. Its fields and i18n configuration are used instead of the collection’s.\n * @param {InternalLocaleCode} args.locale Locale.\n * @param {string} [args.slug] Entry slug for the locale.\n * @param {string} args.entryFilePath Entry file path for the locale.\n * @param {FlattenedEntryContent} args.content Entry content for the locale.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @returns {string | undefined} Filled path, or `undefined` if it cannot be determined because the\n * date/time parts are not available or a tag cannot be resolved.\n */\nexport const fillEntryPathTemplate = ({\n  pathTemplate,\n  dateFieldName,\n  fields,\n  collection,\n  collectionFile,\n  locale,\n  slug,\n  entryFilePath,\n  content,\n  isIndexFile = false,\n}) => {\n  /** @type {Record<string, string> | undefined} */\n  let dateTimeParts;\n\n  if (DATE_TIME_TEMPLATE_REGEX.test(pathTemplate)) {\n    dateTimeParts = extractDateTime({ dateFieldName, fields, content, locale });\n\n    // Cannot generate a path if the date and time parts are not available\n    if (!dateTimeParts) {\n      return undefined;\n    }\n  }\n\n  try {\n    return fillTemplate(pathTemplate, {\n      type: 'preview_path',\n      collection,\n      collectionFile,\n      content,\n      locale,\n      currentSlug: slug,\n      entryFilePath,\n      dateTimeParts,\n      isIndexFile,\n    });\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Get the given entry’s path on the live site, based on the `preview_path` option defined on the\n * collection or collection file. The result is not normalized, so it may or may not have a leading\n * slash, depending on the template.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only.\n * @param {InternalLocaleCode} args.locale Locale.\n * @param {string} [args.slug] Entry slug for the locale.\n * @param {string} [args.path] Entry file path for the locale.\n * @param {FlattenedEntryContent} [args.content] Entry content for the locale.\n * @param {FlattenedEntryContent} [args.defaultContent] Entry content for the default locale. A\n * field that isn’t translated, like a date, is only stored in the default locale, so its value is\n * taken from there unless the locale’s content has one.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @returns {string | undefined} Path on the live site, or `undefined` if it cannot be determined,\n * typically because the `preview_path` option is not defined.\n */\nexport const getPreviewPath = ({\n  collection,\n  collectionFile,\n  locale,\n  slug,\n  path: entryFilePath,\n  content,\n  defaultContent,\n  isIndexFile = false,\n}) => {\n  const {\n    preview_path: pathTemplate,\n    preview_path_date_field: dateFieldName,\n    fields: regularFields = [],\n    _i18n: { defaultLocale, omitDefaultLocaleFromPreviewPath },\n  } = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  if (!entryFilePath || !content || !pathTemplate) {\n    return undefined;\n  }\n\n  const indexFile = isIndexFile ? getIndexFile(collection) : undefined;\n  let template = pathTemplate;\n\n  // Handle the case where the default locale is omitted from the preview path, ensuring that the\n  // URL is correctly generated without the locale segment for the default locale.\n  if (locale === defaultLocale && omitDefaultLocaleFromPreviewPath) {\n    template = omitLocalePlaceholder(template) ?? template;\n  }\n\n  return fillEntryPathTemplate({\n    pathTemplate: template,\n    dateFieldName,\n    fields: indexFile?.fields ?? regularFields,\n    collection,\n    collectionFile,\n    locale,\n    slug,\n    entryFilePath,\n    // A field that isn’t translated has no value in another locale’s content\n    content: addSharedValues({\n      getFieldArgs: {\n        collectionName: collection.name,\n        fileName: collectionFile?.name,\n        isIndexFile,\n      },\n      locale,\n      defaultLocale,\n      content,\n      defaultContent,\n    }),\n    isIndexFile,\n  });\n};\n\n/**\n * Get the given entry file’s web-accessible URL on the live site or a deploy preview.\n * @param {Entry} entry Entry.\n * @param {InternalLocaleCode} locale Locale.\n * @param {InternalCollection} collection Collection.\n * @param {InternalCollectionFile} [collectionFile] Collection file. File/singleton collection only.\n * @param {object} [options] Options.\n * @param {string} [options.baseURL] Base URL to use instead of the site’s own, typically the deploy\n * preview URL reported by a CI/CD provider for an Editorial Workflow pull request. It takes\n * precedence over the `site_url` option, which may be unset.\n * @param {boolean} [options.fallbackToRoot] Whether to link to the root of the site when the\n * collection or collection file has no `preview_path` option, as Decap CMS does. It’s meant for a\n * deploy preview, whose address changes with each pull request, so the CMS is the easiest place to\n * find it; a link to the home page of the live site isn’t worth offering on every entry.\n * @returns {string | undefined} URL on the live site or the deploy preview.\n * @see https://decapcms.org/docs/deploy-preview-links/\n */\nexport const getEntryPreviewURL = (entry, locale, collection, collectionFile, options = {}) => {\n  const { show_preview_links: showLinks = true, _baseURL } = cmsConfig.current ?? {};\n  const baseURL = options.baseURL || _baseURL;\n  const { slug, path, content } = entry.locales[locale] ?? {};\n\n  if (!showLinks || !baseURL) {\n    return undefined;\n  }\n\n  const { preview_path: pathTemplate } =\n    collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  // Only a missing option falls back to the root: a `preview_path` that can’t be filled in for this\n  // entry still gives no link, as the page it names is somewhere else on the site\n  if (options.fallbackToRoot && !pathTemplate) {\n    return `${baseURL.replace(/\\/$/, '')}/`;\n  }\n\n  const previewPath = getPreviewPath({\n    collection,\n    collectionFile,\n    locale,\n    slug,\n    path,\n    content,\n    defaultContent: entry.locales[(collectionFile ?? collection)._i18n.defaultLocale]?.content,\n    isIndexFile: isCollectionIndexFile(collection, entry),\n  });\n\n  if (previewPath === undefined) {\n    return undefined;\n  }\n\n  return `${baseURL.replace(/\\/$/, '')}/${previewPath.replace(/^\\//, '')}`;\n};\n\n/**\n * Get the given entry file’s web-accessible URL on the repository.\n * @param {Entry} entry Entry.\n * @param {InternalLocaleCode} locale Locale.\n * @returns {string} URL on the repository.\n */\nexport const getEntryRepoBlobURL = (entry, locale) => {\n  const path = entry.locales[locale]?.path;\n\n  // A name can contain characters like `#` or `%` that have a meaning in a URL\n  return `${backend.current?.repository?.blobBaseURL}/${path ? encodePathSegments(path) : ''}?plain=1`;\n};\n","import { getPreviewPath } from '$lib/services/contents/entry';\n\n/**\n * Get the given entry’s site-relative path on the live site, based on the `preview_path` option.\n * Unlike {@link getPreviewPath}, the result always has a leading slash, as Hugo and Zola resolve an\n * alias relative to the current page without one.\n * @param {Parameters<typeof getPreviewPath>[0]} args Arguments.\n * @returns {string | undefined} Path, or `undefined` if it cannot be determined.\n */\nexport const getSitePath = (args) => {\n  const path = getPreviewPath(args);\n\n  return path === undefined ? undefined : `/${path.replace(/^\\//, '')}`;\n};\n","import { mapEntryContent } from '$lib/services/contents/entry/locales';\nimport { getManagedKey } from '$lib/services/contents/entry/managed-key';\nimport { getSitePath } from '$lib/services/contents/entry/site-path';\n\n/**\n * @import {\n * Entry,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Property name used to store an entry’s permalink when the `permalink_field` option is `true`.\n * It’s what Eleventy reads to decide where to build a page.\n * @see https://www.11ty.dev/docs/permalinks/\n */\nexport const DEFAULT_PERMALINK_KEY = 'permalink';\n\n/**\n * Get the property name used to store the permalink of entries in the given collection.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {Field[]} [args.fields] Field list of the collection or the collection’s index file.\n * @returns {FieldKeyPath | undefined} Property name, or `undefined` if permalinks are not managed\n * by the CMS, which is the default as the property means something else to other generators.\n */\nexport const getPermalinkKey = ({ collection, fields }) =>\n  getManagedKey({\n    collection,\n    fields,\n    option: /** @type {InternalEntryCollection} */ (collection)?.permalink_field,\n    defaultKey: DEFAULT_PERMALINK_KEY,\n  });\n\n/**\n * Store the entry’s path on the live site, filled from the `preview_path` option, in the property\n * named with the `permalink_field` option, so the site is built with the path the CMS links to. If\n * the path can’t be worked out, e.g. because the date it contains is empty, the property is\n * removed, as an outdated path could build the page over another one.\n *\n * Only a string is replaced: anything else in the property is the user’s, like Eleventy’s\n * `permalink: false`, which keeps a page from being built at all, or its object form.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {Field[]} [args.fields] Field list of the collection or the collection’s index file.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s index file.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FlattenedEntryContent} args.content Flattened entry content to be modified in place.\n * @param {FlattenedEntryContent} [args.defaultContent] Entry content for the default locale.\n * @param {string} [args.slug] Entry slug for the locale.\n * @param {string} [args.path] Entry file path for the locale.\n * @see https://github.com/sveltia/sveltia-cms/discussions/1133\n */\nexport const fillPermalink = ({\n  collection,\n  fields,\n  isIndexFile = false,\n  locale,\n  content,\n  defaultContent,\n  slug,\n  path,\n}) => {\n  // This is `undefined` unless the option is enabled for an entry collection\n  const permalinkKey = getPermalinkKey({ collection, fields });\n\n  // The index file is Hugo’s, which doesn’t have a use for the property\n  if (\n    !permalinkKey ||\n    isIndexFile ||\n    !(/** @type {InternalEntryCollection} */ (collection).preview_path)\n  ) {\n    return;\n  }\n\n  const isUserValue =\n    typeof (content[permalinkKey] ?? '') !== 'string' ||\n    Object.keys(content).some((keyPath) => keyPath.startsWith(`${permalinkKey}.`));\n\n  if (isUserValue) {\n    return;\n  }\n\n  const sitePath = getSitePath({ collection, locale, slug, path, content, defaultContent });\n\n  if (sitePath === undefined) {\n    delete content[permalinkKey];\n  } else {\n    content[permalinkKey] = sitePath;\n  }\n};\n\n/**\n * Refresh the permalink of an entry changed without the entry editor, such as one moved along with\n * its folder or changed by a bulk edit, as the path can depend on the slug and on any field.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s index file.\n * @param {Entry} args.entry Entry with the changes applied.\n * @returns {Entry} Entry with the permalink updated in every locale that has content. The given\n * entry is returned as is when the collection doesn’t store permalinks.\n */\nexport const refreshPermalinks = ({ collection, isIndexFile = false, entry }) => {\n  const { fields } = /** @type {InternalEntryCollection} */ (collection);\n\n  if (isIndexFile || !getPermalinkKey({ collection, fields })) {\n    return entry;\n  }\n\n  const defaultContent = entry.locales[collection._i18n.defaultLocale]?.content;\n\n  return mapEntryContent(entry, ({ locale, localizedEntry: { slug, path, content } }) => {\n    const copiedContent = { .../** @type {FlattenedEntryContent} */ (content) };\n\n    fillPermalink({\n      collection,\n      fields,\n      locale,\n      content: copiedContent,\n      defaultContent,\n      slug,\n      path,\n    });\n\n    return copiedContent;\n  });\n};\n","import { toRaw } from '@sveltia/utils/object';\nimport { compare } from '@sveltia/utils/string';\nimport { TomlDate } from 'smol-toml';\n\nimport { cmsConfig } from '$lib/services/config';\nimport { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { INTERNAL_PROP_REGEX } from '$lib/services/contents/draft';\nimport { createKeyPathList } from '$lib/services/contents/draft/save/key-path';\nimport { getAliasesKey, getAliasKeyPaths } from '$lib/services/contents/entry/aliases';\nimport {\n  getField,\n  getFieldKind,\n  hasRootField,\n  isFieldRequired,\n} from '$lib/services/contents/entry/fields';\nimport { getWildcardKeyPathPattern } from '$lib/services/contents/entry/key-paths';\nimport { getPermalinkKey } from '$lib/services/contents/entry/permalink';\nimport { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\nimport { convertMapLists, getMapKeyField } from '$lib/services/contents/fields/list/map';\nimport { resolveFileConfig } from '$lib/services/contents/file/config';\nimport { TOML_FORMATS } from '$lib/services/contents/file/constants';\nimport { isFieldInLocale } from '$lib/services/contents/i18n/shared-values';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport {\n  hasIndexLikeChildKey,\n  isPlainObject,\n  isValueEmpty,\n  unflattenKeys,\n} from '$lib/services/utils/object';\n\n/**\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { DateTimeField, Field, FileFormat, RawEntryContent } from '$lib/types/public';\n */\n\n/**\n * Cache of wildcard key-path regexes used in {@link finalizeContent}, keyed by `keyPath`.\n * @type {Map<string, RegExp>}\n */\nconst wildcardKeyPathRegexCache = new Map();\n\n/**\n * Get a regular expression that matches a concrete key path of a wildcard key path, or any key path\n * below it, capturing the concrete key path, e.g. `list.0.title` in `list.0.title` and\n * `list.0.pairs` in `list.0.pairs.foo` for `list.*.title` and `list.*.pairs` respectively.\n * @param {string} keyPath Key path that may contain wildcards.\n * @returns {RegExp} Regular expression.\n */\nconst getWildcardKeyPathRegex = (keyPath) =>\n  getOrCreate(\n    wildcardKeyPathRegexCache,\n    keyPath,\n    () => new RegExp(`^(${getWildcardKeyPathPattern(keyPath)})(?:\\\\.|$)`),\n  );\n\n/**\n * Regular expression matching a key path ending with a numeric segment, capturing the parent key\n * path.\n */\nconst INDEXED_KEY_PATH_REGEX = /^(.+)\\.\\d+$/;\n\n/**\n * Check if the given key path is an array item, e.g. the item of a List field, in the output. A\n * numeric segment is unflattened into an array index, unless the parent is already an object in\n * the sorted property map, like a KeyValue field or an Object field with a subfield named like an\n * index.\n * @param {string} key Key path.\n * @param {FlattenedEntryContent} sortedMap Sorted property map.\n * @returns {boolean} Result.\n */\nconst isArrayItemKeyPath = (key, sortedMap) => {\n  const [, parentKey] = key.match(INDEXED_KEY_PATH_REGEX) ?? [];\n\n  return parentKey !== undefined && !isPlainObject(sortedMap[parentKey]);\n};\n\n/**\n * Keep the closest array item the given omitted key path belongs to, e.g. `links.0` for\n * `links.0.label`, by adding an empty object for it unless it already has a value or another\n * property. Otherwise an item whose subfields are all omitted would leave a hole in the array,\n * which is written as `null` in JSON and YAML, and dropped in TOML, shifting the other items.\n * @param {string} key Omitted key path.\n * @param {FlattenedEntryContent} sortedMap Sorted property map.\n */\nconst keepArrayItem = (key, sortedMap) => {\n  const segments = key.split('.');\n\n  for (let index = segments.length - 1; index > 0; index -= 1) {\n    const itemKey = segments.slice(0, index).join('.');\n\n    if (isArrayItemKeyPath(itemKey, sortedMap)) {\n      if (\n        !Object.hasOwn(sortedMap, itemKey) &&\n        !Object.keys(sortedMap).some((_key) => _key.startsWith(`${itemKey}.`))\n      ) {\n        sortedMap[itemKey] = {};\n      }\n\n      return;\n    }\n  }\n};\n\n/**\n * Move a property name/value from a unsorted property map to a sorted property map.\n * @param {object} args Arguments.\n * @param {string} args.key Property name.\n * @param {Field} [args.field] Associated field.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FlattenedEntryContent} args.unsortedMap Unsorted property map.\n * @param {FlattenedEntryContent} args.sortedMap Sorted property map.\n * @param {boolean} args.isTomlOutput Whether the output it TOML format.\n * @param {boolean} args.omitEmptyOptionalFields Whether to prevent fields with `required: false`\n * and an empty value from being included in the data output.\n */\nexport const copyProperty = ({\n  key,\n  field,\n  locale,\n  unsortedMap,\n  sortedMap,\n  isTomlOutput,\n  omitEmptyOptionalFields,\n}) => {\n  // Skip internal properties added to list items\n  if (INTERNAL_PROP_REGEX.test(key)) {\n    delete unsortedMap[key];\n    return;\n  }\n\n  let value = unsortedMap[key];\n\n  // Use native date for TOML if a custom format is not defined\n  // @see https://github.com/squirrelchat/smol-toml?tab=readme-ov-file#dates\n  // @see https://toml.io/en/v1.0.0#offset-date-time\n  if (\n    isTomlOutput &&\n    field?.widget === 'datetime' &&\n    !parseDateTimeConfig(/** @type {DateTimeField} */ (field)).format\n  ) {\n    if (isValueEmpty(value)) {\n      // An optional field without a value saves nothing. We cannot save `null` because TOML\n      // doesn’t support it, and an empty string may not be the expected value for a date field\n      value = undefined;\n    } else {\n      const tomlDate = new TomlDate(value);\n\n      // A date, a time or a date-time, with or without an offset, becomes a native TOML value. Any\n      // other value, e.g. `TBD`, `2024-01` or `3:04 PM`, which a field without a date or a time can\n      // hold, is kept as a string\n      if (tomlDate.isValid()) {\n        value = tomlDate;\n      }\n    }\n  }\n\n  // The option omits the empty properties of an object, never the items of an array, which would\n  // leave holes in it\n  if (\n    omitEmptyOptionalFields &&\n    field &&\n    !isFieldRequired({ fieldConfig: field, locale }) &&\n    isValueEmpty(value) &&\n    !isArrayItemKeyPath(key, sortedMap)\n  ) {\n    const childKeys = Object.keys(unsortedMap).filter((_key) => _key.startsWith(`${key}.`));\n\n    if (\n      childKeys.some((_key) => !INTERNAL_PROP_REGEX.test(_key) && !isValueEmpty(unsortedMap[_key]))\n    ) {\n      // Preserve the parent because it has non-empty children\n      sortedMap[key] = value;\n    } else {\n      // Omit the empty value and remove any empty children so they are not processed later\n      childKeys.forEach((_key) => {\n        delete unsortedMap[_key];\n      });\n\n      keepArrayItem(key, sortedMap);\n    }\n  } else {\n    sortedMap[key] = value;\n  }\n\n  delete unsortedMap[key];\n};\n\n/**\n * Field types whose object or array value is flattened into key paths that no field configuration\n * describes: a Hidden field takes anything its `default` or the file gives it, and a Code field\n * saves the code and the language under the property names of its `keys` option.\n */\nconst OPAQUE_FIELD_TYPES = ['code', 'hidden'];\n\n/**\n * Check whether the given field holds a value whose properties no field configuration describes: a\n * custom field, or one of {@link OPAQUE_FIELD_TYPES}.\n * @param {Field} field Field configuration.\n * @returns {boolean} Result.\n */\nconst isOpaqueField = (field) =>\n  OPAQUE_FIELD_TYPES.includes(String(field.widget)) || getFieldKind(field) === 'custom';\n\n/**\n * Shared state of a {@link finalizeContent} run, passed to the helpers that copy the fields.\n * @typedef {object} FinalizeContext\n * @property {InternalLocaleCode} locale Locale code.\n * @property {InternalLocaleCode} defaultLocale Default locale code, or `_default` if i18n is not\n * enabled.\n * @property {{ collectionName: string, fileName?: string, valueMap: FlattenedEntryContent,\n * isIndexFile: boolean }} getFieldArgs Arguments for `getField()`, without the key path.\n * @property {FlattenedEntryContent} unsortedMap Unsorted property map.\n * @property {FlattenedEntryContent} sortedMap Sorted property map.\n * @property {{ locale: InternalLocaleCode, unsortedMap: FlattenedEntryContent, sortedMap:\n * FlattenedEntryContent, isTomlOutput: boolean, omitEmptyOptionalFields: boolean }} copyArgs\n * Arguments for {@link copyProperty}, without the key and the field.\n */\n\n/**\n * Copy a KeyValue field’s key-value pairs to the sorted property map.\n * @param {FinalizeContext} ctx Context.\n * @param {string} keyPath Concrete key path of the field.\n * @param {Field} field Field configuration.\n */\nconst copyKeyValueField = (ctx, keyPath, field) => {\n  const { unsortedMap, sortedMap, copyArgs } = ctx;\n  const prefix = `${keyPath}.`;\n\n  const pairKeyPaths = Object.keys(unsortedMap).filter((_keyPath) => {\n    if (!_keyPath.startsWith(prefix)) {\n      return false;\n    }\n\n    // A blank pair, like the one a required field gets as its default value, isn’t saved.\n    // Validation doesn’t count it either, so it can only be left in an optional field. A pair with\n    // an empty key but a value, which a file can hold, is kept as is\n    if (!_keyPath.slice(prefix.length).trim() && !unsortedMap[_keyPath]) {\n      delete unsortedMap[_keyPath];\n\n      return false;\n    }\n\n    return true;\n  });\n\n  // A field without pairs is saved as an empty object, just like a List field without items is\n  // saved as an empty array, whether or not it holds the `null` placeholder the editor stores to\n  // have the field validated. Whether it does depends on whether its editor has been shown, so it\n  // can’t make a difference to the output. `copyProperty()` still omits the empty object if the\n  // field is optional and the `omit_empty_optional_fields` output option is enabled\n  if (!pairKeyPaths.length) {\n    // A field that isn’t in the locale’s content, e.g. one that isn’t translatable in a locale\n    // other than the default, doesn’t get the empty object either\n    if (Object.hasOwn(unsortedMap, keyPath) || isFieldInLocale({ ...ctx, keyPath })) {\n      // Any other value, such as a string where the file doesn’t hold an object, is left as is\n      unsortedMap[keyPath] ??= {};\n      copyProperty({ ...copyArgs, key: keyPath, field });\n    }\n\n    return;\n  }\n\n  // Work around a bug in the flat library where numeric property keys used for KeyValue fields\n  // trigger a wrong conversion to an array instead of an object\n  // @see https://github.com/hughsk/flat/issues/103\n  sortedMap[keyPath] = {};\n  delete unsortedMap[keyPath];\n\n  pairKeyPaths.forEach((_keyPath) => {\n    copyProperty({ ...copyArgs, key: _keyPath, field });\n  });\n};\n\n/**\n * Copy the value of a custom or Hidden field to the sorted property map. An object or array value\n * is flattened into the key paths below the field’s own, which aren’t listed in the configured\n * fields. Copy them right away, in the order the control or the file gave the properties, rather\n * than leaving them to be sorted with the remainder at the end of the output.\n * @param {FinalizeContext} ctx Context.\n * @param {string} keyPath Concrete key path of the field.\n * @param {Field} field Field configuration.\n */\nconst copyOpaqueField = ({ unsortedMap, copyArgs }, keyPath, field) => {\n  if (Object.hasOwn(unsortedMap, keyPath)) {\n    copyProperty({ ...copyArgs, key: keyPath, field });\n  }\n\n  const prefix = `${keyPath}.`;\n\n  Object.keys(unsortedMap)\n    .filter((_keyPath) => _keyPath.startsWith(prefix))\n    .forEach((_keyPath) => {\n      copyProperty({ ...copyArgs, key: _keyPath });\n    });\n};\n\n/**\n * Add an empty object as a placeholder for an Object field whose subfields include one named like a\n * list index, e.g. `2024`, so it’s not unflattened into an array. A value read from a file already\n * has one, but a new entry or a newly added object doesn’t.\n * @param {FinalizeContext} ctx Context.\n * @param {string} keyPath Concrete key path of the field.\n * @param {Field} [field] Field configuration.\n */\nconst addObjectPlaceholder = ({ unsortedMap, sortedMap }, keyPath, field) => {\n  if (field?.widget === 'object' && hasIndexLikeChildKey(unsortedMap, keyPath)) {\n    sortedMap[keyPath] = {};\n  }\n};\n\n/**\n * Copy the value of a field to the sorted property map, dispatching a KeyValue field and an opaque\n * field to their own handlers. A KeyValue field is handled on its own, even if it holds a value at\n * its own key path, which is the placeholder of an empty field. A key path with wildcards is never\n * dispatched, as it has to be resolved to the concrete key paths of the list items first.\n * @param {FinalizeContext} ctx Context.\n * @param {string} keyPath Key path of the field.\n * @param {Field | undefined} field Field configuration.\n * @returns {boolean} Whether the field has been handled. `false` if the key path holds no value,\n * leaving it to the caller to resolve its wildcards or add a placeholder.\n */\nconst copyField = (ctx, keyPath, field) => {\n  const isConcrete = !keyPath.includes('*');\n\n  if (field?.widget === 'keyvalue' && isConcrete) {\n    copyKeyValueField(ctx, keyPath, field);\n  } else if (field && isConcrete && isOpaqueField(field)) {\n    copyOpaqueField(ctx, keyPath, field);\n  } else if (Object.hasOwn(ctx.unsortedMap, keyPath)) {\n    copyProperty({ ...ctx.copyArgs, key: keyPath, field });\n  } else {\n    return false;\n  }\n\n  return true;\n};\n\n/**\n * Copy the values of a wildcard key path’s concrete key paths to the sorted property map, resolving\n * the wildcards to the list items, e.g. `list.*.title` → `list.0.title`, `list.1.title`. A KeyValue\n * field has no value at its own key path when it holds pairs, so look for the key paths below it as\n * well.\n * @param {FinalizeContext} ctx Context.\n * @param {string} keyPath Key path that may contain wildcards.\n * @param {Field | undefined} field Field configuration.\n */\nconst copyWildcardField = (ctx, keyPath, field) => {\n  const regex = getWildcardKeyPathRegex(keyPath);\n\n  const concreteKeyPaths = new Set(\n    Object.keys(ctx.unsortedMap)\n      .map((_keyPath) => _keyPath.match(regex)?.[1])\n      .filter((_keyPath) => _keyPath !== undefined),\n  );\n\n  [...concreteKeyPaths]\n    .sort((a, b) => compare(a, b))\n    .forEach((concreteKeyPath) => {\n      // When the wildcard path couldn’t resolve a typed list field, resolve with the concrete key\n      // path so that field metadata (e.g. `required`) is available to `copyProperty`\n      const resolvedField = field ?? getField({ ...ctx.getFieldArgs, keyPath: concreteKeyPath });\n\n      if (!copyField(ctx, concreteKeyPath, resolvedField)) {\n        addObjectPlaceholder(ctx, concreteKeyPath, resolvedField);\n      }\n    });\n};\n\n/**\n * Finalize the content by sorting the entry draft content’s object properties by the order of the\n * configured collection fields. The result can be formatted as expected with `JSON.stringify()`, as\n * the built-in method uses insertion order for string key ordering.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {Field[]} args.fields Field list of a collection or a file.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {InternalLocaleCode} args.defaultLocale Default locale code, or `_default` if i18n is not\n * enabled.\n * @param {FlattenedEntryContent} args.valueMap Flattened entry content.\n * @param {string} [args.canonicalSlugKey] Property name of a canonical slug.\n * @param {string} [args.permalinkKey] Property name of the entry’s permalink. Placed right after\n * the canonical slug, ahead of all configured fields, when present in the value map.\n * @param {string} [args.aliasesKey] Property name of the entry’s URL aliases. Placed right after\n * the permalink, ahead of all configured fields, when present in the value map.\n * @param {string} [args.orderKey] Property name of the entry order field. Placed right after the\n * aliases, ahead of all configured fields, when present in the value map and not a configured field\n * itself.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @param {boolean} [args.isTomlOutput] Whether the output it TOML format.\n * @returns {RawEntryContent} Unflattened entry content sorted by fields. Output order is: canonical\n * slug → permalink → aliases → order → configured fields → remainder.\n */\nconst finalizeContent = ({\n  collectionName,\n  fileName,\n  fields,\n  locale,\n  defaultLocale,\n  valueMap,\n  canonicalSlugKey,\n  permalinkKey,\n  aliasesKey,\n  orderKey,\n  isIndexFile = false,\n  isTomlOutput = false,\n}) => {\n  /** @type {FlattenedEntryContent} */\n  const unsortedMap = toRaw(valueMap);\n  /** @type {FlattenedEntryContent} */\n  const sortedMap = {};\n\n  const { omit_empty_optional_fields: omitEmptyOptionalFields = false } =\n    cmsConfig.current?.output ?? {};\n\n  const getFieldArgs = { collectionName, fileName, valueMap, isIndexFile };\n  const copyArgs = { locale, unsortedMap, sortedMap, isTomlOutput, omitEmptyOptionalFields };\n  /** @type {FinalizeContext} */\n  const ctx = { locale, defaultLocale, getFieldArgs, unsortedMap, sortedMap, copyArgs };\n  const keyPathList = createKeyPathList(fields);\n\n  // Add the properties managed by the CMS first, so they appear at the top of the output: the slug,\n  // the permalink and the URL aliases, which relate to it, then the order field. The aliases\n  // normally hold a list, which is flattened into indexed key paths, but the property itself is\n  // copied too in case the user stores something else in it\n  [\n    canonicalSlugKey,\n    permalinkKey,\n    aliasesKey,\n    ...(aliasesKey ? getAliasKeyPaths(unsortedMap, aliasesKey) : []),\n    // A configured order field, e.g. `weight`, stays where it’s defined in the field list\n    // @see https://github.com/sveltia/sveltia-cms/issues/1169\n    orderKey && !keyPathList.includes(orderKey) ? orderKey : undefined,\n  ].forEach((key) => {\n    if (key && Object.hasOwn(unsortedMap, key)) {\n      copyProperty({ ...copyArgs, key });\n    }\n  });\n\n  // Move the listed properties to a new object\n  keyPathList.forEach((keyPath) => {\n    const field = getField({ ...getFieldArgs, keyPath });\n\n    if (!copyField(ctx, keyPath, field)) {\n      copyWildcardField(ctx, keyPath, field);\n    }\n  });\n\n  // Move the remainder, if any, to a new object. Sorting also guarantees that a parent key path\n  // precedes its own children, which `unflatten()` below depends on to keep the children\n  Object.keys(unsortedMap)\n    .sort((a, b) => compare(a, b))\n    .forEach((key) => {\n      copyProperty({ ...copyArgs, key });\n    });\n\n  return unflattenKeys(sortedMap);\n};\n\n/**\n * Remove `null` and `undefined` from the given value for TOML output, as TOML has no null. An item\n * of a list, e.g. an empty optional Number field in a simple list, is dropped, as smol-toml throws\n * on it. An object property is dropped too: smol-toml skips it in a table but writes an invalid\n * inline table, e.g. for an object in a nested list.\n * @param {any} value Value.\n * @returns {any} Value without `null` and `undefined`. Arrays and plain objects are copied.\n */\nconst removeTomlNulls = (value) => {\n  if (Array.isArray(value)) {\n    return value.filter((item) => item !== null && item !== undefined).map(removeTomlNulls);\n  }\n\n  // Leave class instances, such as a `TomlDate`, as they are\n  if (isPlainObject(value)) {\n    return Object.fromEntries(\n      Object.entries(value)\n        .filter(([, val]) => val !== null && val !== undefined)\n        .map(([key, val]) => [key, removeTomlNulls(val)]),\n    );\n  }\n\n  return value;\n};\n\n/**\n * Serialize the content for the output.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FlattenedEntryContent} args.valueMap Original content.\n * @param {FileFormat} [args.format] Format of the file being saved. In a collection in the\n * `frontmatter` format, it’s the front matter format detected in the existing file, which decides\n * whether dates are written as native TOML dates. Defaults to the configured format.\n * @returns {RawEntryContent} Modified and unflattened content.\n */\nexport const serializeContent = ({ draft, locale, valueMap, format }) => {\n  const { collection, collectionName, collectionFile, fields, isIndexFile } = draft;\n\n  const {\n    _i18n: {\n      defaultLocale,\n      canonicalSlug: { key: canonicalSlugKey },\n    },\n  } = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  const isTomlOutput = TOML_FORMATS.includes(\n    format ?? resolveFileConfig({ collection, collectionFile, isIndexFile }).format,\n  );\n\n  const finalizedContent = finalizeContent({\n    collectionName,\n    fileName: collectionFile?.name,\n    fields,\n    locale,\n    defaultLocale,\n    valueMap,\n    canonicalSlugKey,\n    permalinkKey: getPermalinkKey({ collection, fields }),\n    aliasesKey: getAliasesKey({ collection, fields }),\n    orderKey: getOrderFieldKey(collection),\n    isIndexFile,\n    isTomlOutput,\n  });\n\n  // Store the List fields with the `map_key_field` option as maps\n  const mappedContent = convertMapLists(finalizedContent, fields, false);\n  const content = isTomlOutput ? removeTomlNulls(mappedContent) : mappedContent;\n\n  // Handle a special case: top-level List field. TOML doesn’t support top-level arrays, so we\n  // ignore the `root` option for such cases, unless the list is stored as a map\n  if (hasRootField(fields, 'list')) {\n    const isMap = !!getMapKeyField(fields[0]);\n\n    if (isMap || !isTomlOutput) {\n      return content[fields[0].name] ?? (isMap ? {} : []);\n    }\n  }\n\n  // Handle a special case: top-level KeyValue field\n  if (hasRootField(fields, 'keyvalue')) {\n    return content[fields[0].name] ?? {};\n  }\n\n  return content;\n};\n","import { serializeContent } from '$lib/services/contents/draft/save/serialize';\nimport { hasRootField } from '$lib/services/contents/entry/fields';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { Entry, InternalCollection, InternalCollectionFile } from '$lib/types/private';\n * @import { Field, FieldKeyPath, FileFormat } from '$lib/types/public';\n */\n\n/**\n * Collect the `comment` option of the given fields, and of the subfields of Object fields.\n * @param {Field[]} fields Fields.\n * @param {string} prefix Key path prefix.\n * @returns {Record<FieldKeyPath, string>} Comments keyed by field key path.\n */\nconst collectFieldComments = (fields, prefix) =>\n  Object.fromEntries(\n    fields.flatMap((field) => {\n      const { name, widget = 'string', comment } = field;\n      const keyPath = `${prefix}${name}`;\n      /** @type {[FieldKeyPath, string][]} */\n      const entries = isNonEmptyString(comment) ? [[keyPath, comment]] : [];\n\n      if (widget === 'object' && 'fields' in field && Array.isArray(field.fields)) {\n        entries.push(...Object.entries(collectFieldComments(field.fields, `${keyPath}.`)));\n      }\n\n      return entries;\n    }),\n  );\n\n/**\n * Collect the `comment` option of the given fields, and of the subfields of Object fields, to be\n * written before the keys in a YAML file, like Netlify/Decap CMS does. The subfields of a List\n * field are left out, as the comment would have to be repeated on every item. A top-level List or\n * KeyValue field is saved without its own key, so its comment has nowhere to go, and could\n * otherwise land on a list item or pair of the same name.\n * @param {Field[]} [fields] Fields.\n * @param {string} [prefix] Key path prefix, e.g. a locale key followed by a period.\n * @returns {Record<FieldKeyPath, string>} Comments keyed by field key path.\n * @see https://decapcms.org/docs/configuration-options/#fields\n */\nexport const getFieldComments = (fields = [], prefix = '') =>\n  hasRootField(fields, 'list') || hasRootField(fields, 'keyvalue')\n    ? {}\n    : collectFieldComments(fields, prefix);\n\n/**\n * Collect the field comments for a single-file entry, taking i18n single-file structures into\n * account the same way as {@link buildSingleFileContent}: the fields of each locale are nested\n * under its locale key, except for the default locale with `single_file_default_root`.\n * @param {object} args Arguments.\n * @param {InternalCollection | InternalCollectionFile} args.config Collection or collection file\n * holding the i18n configuration.\n * @param {Field[]} [args.fields] Fields of the entry.\n * @returns {Record<FieldKeyPath, string>} Comments keyed by field key path.\n */\nexport const getSingleFileComments = ({ config, fields }) => {\n  const {\n    _i18n: {\n      i18nEnabled,\n      allLocales,\n      defaultLocale,\n      structureMap: { i18nSingleFileDefaultRoot } = {},\n    },\n  } = config;\n\n  if (!i18nEnabled) {\n    return getFieldComments(fields);\n  }\n\n  return Object.assign(\n    {},\n    ...allLocales.map((locale) =>\n      getFieldComments(\n        fields,\n        i18nSingleFileDefaultRoot && locale === defaultLocale ? '' : `${locale}.`,\n      ),\n    ),\n  );\n};\n\n/**\n * Build the file content for a single-file entry, taking i18n single-file structures into account.\n * For `single_file_default_root`, the default locale’s fields are written at the root level and\n * non-default locales are nested under their locale key.\n * @param {object} args Arguments.\n * @param {InternalCollection | InternalCollectionFile} args.config Collection or collection file\n * holding the i18n configuration.\n * @param {Entry} args.entry Entry whose locales have already been updated.\n * @param {any} args.draft Entry draft, or a synthetic draft holding the properties read by\n * {@link serializeContent}.\n * @param {FileFormat} [args.format] Format of the file being saved. See {@link serializeContent}.\n * @returns {Record<string, any>} Serializable content object passed to `formatEntryFile()`.\n */\nexport const buildSingleFileContent = ({ config, entry, draft, format }) => {\n  const {\n    _i18n: { i18nEnabled, defaultLocale, structureMap: { i18nSingleFileDefaultRoot } = {} },\n  } = config;\n\n  if (!i18nEnabled) {\n    return serializeContent({\n      draft,\n      locale: '_default',\n      valueMap: entry.locales[defaultLocale].content,\n      format,\n    });\n  }\n\n  const localeContents = Object.fromEntries(\n    Object.entries(entry.locales)\n      .filter(([, le]) => !!le.content)\n      .map(([locale, le]) => [\n        locale,\n        serializeContent({ draft, locale, valueMap: le.content, format }),\n      ]),\n  );\n\n  if (i18nSingleFileDefaultRoot) {\n    // Remove `lang` from default content to avoid stale/duplicate values; it’s always\n    // auto-generated from the configured locales.\n    const { lang: _lang, ...defaultContent } = localeContents[defaultLocale] ?? {};\n\n    const nonDefaultContent = Object.fromEntries(\n      Object.entries(localeContents).filter(([locale]) => locale !== defaultLocale),\n    );\n\n    return {\n      // Add `lang` field at the root level as per Lume’s convention for single-file i18n\n      // @see https://lume.land/plugins/multilanguage/#multilanguage-pages-from-a-single-file\n      lang: [defaultLocale, ...Object.keys(nonDefaultContent)],\n      ...defaultContent,\n      ...nonDefaultContent,\n    };\n  }\n\n  // `i18nSingleFile`: nested locale keys\n  return localeContents;\n};\n","import { stringify as stringifyTOML } from 'smol-toml';\nimport { Document, isMap, visit } from 'yaml';\n\nimport { customFileFormatRegistry } from '$lib/services/api/registries';\nimport { cmsConfig } from '$lib/services/config';\nimport {\n  BUILTIN_FILE_FORMATS,\n  FRONTMATTER_DELIMITER_MAP,\n  FRONTMATTER_FORMATS,\n  getFormatSyntax,\n  TOML_FORMATS,\n} from '$lib/services/contents/file/constants';\nimport {\n  getUnsafeIntegerSource,\n  hasUnsafeIntegerSources,\n  restoreBigInts,\n} from '$lib/services/contents/file/integers';\nimport { prependLeadingComment } from '$lib/services/contents/file/leading-comments';\nimport { restoreTomlValueSources } from '$lib/services/contents/file/toml-sources';\nimport {\n  getJSONSourceText,\n  restoreValueSources,\n  SourcedValue,\n  sourcedValueYAMLTag,\n} from '$lib/services/contents/file/value-sources';\n\n/**\n * @import { Scalar, ToStringOptions } from 'yaml';\n * @import { FormatSyntax } from '$lib/services/contents/file/constants';\n * @import { FileConfig, FileState, InternalLocaleCode } from '$lib/types/private';\n * @import {\n * FieldKeyPath,\n * FileFormatterContext,\n * JsonFormatOptions,\n * RawEntryContent,\n * YamlFormatOptions,\n * } from '$lib/types/public';\n */\n\n/**\n * Get `JSON.rawJSON()`, which TypeScript doesn’t know yet.\n * @returns {((text: string) => any) | undefined} Function, or `undefined` in a browser without it.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/rawJSON\n */\nconst getRawJSON = () => /** @type {{ rawJSON?: (text: string) => any }} */ (JSON).rawJSON;\n\n/**\n * Create a `JSON.stringify()` replacer that writes a {@link SourcedValue} as its source text, and\n * an integer read from a file, which a `number` can’t represent exactly, as it was read. The\n * replacer is given what `toJSON()` returns, so a {@link SourcedValue} is looked up in the holder.\n * @param {(text: string) => any} rawJSON `JSON.rawJSON()`.\n * @returns {(this: any, key: string, value: any) => any} Replacer.\n */\nconst createReplacer = (rawJSON) =>\n  // eslint-disable-next-line func-names\n  function (key, value) {\n    const original = this[key];\n\n    const source =\n      original instanceof SourcedValue\n        ? getJSONSourceText(original)\n        : getUnsafeIntegerSource(value);\n\n    return source === undefined ? value : rawJSON(source);\n  };\n\n/**\n * Format the given object as a JSON document using the built-in method.\n * @param {Record<string, any>} obj Object to be formatted.\n * @param {JsonFormatOptions} [options] Options.\n * @returns {string} Formatted document.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify\n */\nexport const formatJSON = (obj, options = cmsConfig.current?.output?.json ?? {}) => {\n  const {\n    indent_style: indentStyle = 'space',\n    indent_size: indentSize = indentStyle === 'tab' ? 1 : 2,\n  } = options;\n\n  const rawJSON = getRawJSON();\n\n  return JSON.stringify(\n    obj,\n    // Write a value that hasn’t changed since it was read, e.g. a float that is a whole number, as\n    // it was read, and so an integer that a `number` can’t represent exactly. A browser without\n    // `JSON.rawJSON()` writes the number\n    rawJSON ? createReplacer(rawJSON) : undefined,\n    indentStyle === 'tab' ? '\\t'.repeat(indentSize) : indentSize,\n  ).trim();\n};\n\n/**\n * Format the given object as a TOML document using a library.\n * @param {Record<string, any>} obj Object to be formatted.\n * @returns {string} Formatted document.\n * @see https://github.com/squirrelchat/smol-toml\n */\nexport const formatTOML = (obj) =>\n  // Write an integer that a `number` can’t represent exactly as it was read\n  stringifyTOML(hasUnsafeIntegerSources() ? restoreBigInts(obj) : obj).trim();\n\n/**\n * Add the given comments to the keys of a YAML map and the maps nested in it, like Netlify/Decap\n * CMS does with the `comment` field option. Items of a sequence are left alone, as the comment\n * belongs to the field rather than to each item.\n * @param {any} node YAML node.\n * @param {Record<FieldKeyPath, string>} comments Comments keyed by field key path.\n * @param {string} [prefix] Key path of the node.\n * @see https://decapcms.org/docs/configuration-options/#fields\n */\nconst addYAMLComments = (node, comments, prefix = '') => {\n  if (!isMap(node)) {\n    return;\n  }\n\n  node.items.forEach(({ key: _key, value }) => {\n    // A key created from an object is always a scalar\n    const key = /** @type {Scalar} */ (_key);\n    const keyPath = `${prefix}${key.value}`;\n    // A key named after an `Object.prototype` member, e.g. `toString`, mustn’t pick up that member\n    const comment = Object.hasOwn(comments, keyPath) ? comments[keyPath] : undefined;\n\n    if (comment) {\n      // A line break can be given as a real one or, like Netlify/Decap CMS, as an escaped `\\n`\n      key.commentBefore = comment\n        .split(/\\\\n|\\n/)\n        .map((line) => ` ${line}`)\n        .join('\\n');\n    }\n\n    addYAMLComments(value, comments, `${keyPath}.`);\n  });\n};\n\n/**\n * Regular expression matching a string that a YAML 1.1 parser, like Psych used by Jekyll or go-yaml\n * v2 used by older Hugo releases, reads as a boolean, e.g. `yes`, `No` or `off`, the “Norway\n * problem”.\n * @see https://yaml.org/type/bool.html\n */\nconst YAML_1_1_BOOL_REGEX =\n  /^(?:y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)$/;\n\n/**\n * Regular expression matching a string that a YAML 1.1 parser reads as a number: an integer or a\n * float with underscores, a binary or octal integer, or a sexagesimal number like `1:20` (80),\n * as well as an integer or a float with commas, which Psych also accepts. A date isn’t included, as\n * it’s meant to be read as one.\n * @see https://yaml.org/type/int.html\n * @see https://yaml.org/type/float.html\n * @see https://github.com/ruby/psych/blob/master/lib/psych/scalar_scanner.rb\n */\nconst YAML_1_1_NUMBER_REGEX = new RegExp(\n  [\n    '^[-+]?(?:',\n    [\n      // Binary, octal and hexadecimal integers\n      '0b[01_,]+',\n      '0[0-7_,]+',\n      '0x[\\\\da-fA-F_,]+',\n      // Decimal integers and floats\n      '(?:\\\\d[\\\\d_,]*)?\\\\.[\\\\d_,]*(?:[eE][-+]?\\\\d+)?',\n      '\\\\d[\\\\d_,]*',\n      // Sexagesimal integers and floats\n      '\\\\d[\\\\d_]*(?::[0-5]?\\\\d)+(?:\\\\.[\\\\d_]*)?',\n    ].join('|'),\n    ')$',\n  ].join(''),\n);\n\n/**\n * Check whether the given string would be read as something else than a string by a YAML 1.1\n * parser if written as a plain scalar. The `yaml` library follows YAML 1.2, which only quotes a\n * string that a YAML 1.2 parser would misread, like `true` or `1.5`.\n * @param {string} value String.\n * @returns {boolean} Result.\n */\nexport const isAmbiguousYAMLString = (value) =>\n  YAML_1_1_BOOL_REGEX.test(value) || YAML_1_1_NUMBER_REGEX.test(value);\n\n/**\n * Format the given object as a YAML document using a library.\n * @param {Record<string, any>} obj Object to be formatted.\n * @param {YamlFormatOptions} [options] Options.\n * @param {object} [legacyOptions] Deprecated collection-level options.\n * @param {boolean} [legacyOptions.quote] Quote option.\n * @param {Record<FieldKeyPath, string>} [comments] Comments to add before the keys, keyed by field\n * key path.\n * @returns {string} Formatted document.\n * @see https://eemeli.org/yaml/#tostring-options\n * @todo Remove `legacyOptions` prior to the 1.0 release.\n */\nexport const formatYAML = (\n  obj,\n  options = cmsConfig.current?.output?.yaml ?? {},\n  legacyOptions = {},\n  comments = {},\n) => {\n  const {\n    indent_size: indent = 2,\n    indent_sequences: indentSeq = true,\n    quote = 'none',\n    block_quote: blockQuote = true,\n  } = options;\n\n  const { quote: legacyQuote = false } = legacyOptions;\n\n  /** @type {ToStringOptions} */\n  const toStringOptions = {\n    indent,\n    indentSeq,\n    blockQuote,\n    lineWidth: 0,\n    defaultKeyType: 'PLAIN',\n    defaultStringType:\n      legacyQuote || quote === 'double'\n        ? 'QUOTE_DOUBLE'\n        : quote === 'single'\n          ? 'QUOTE_SINGLE'\n          : 'PLAIN',\n    singleQuote: !(legacyQuote || quote === 'double'),\n  };\n\n  // Write a value that hasn’t changed since it was read, e.g. a float that is a whole number, as it\n  // was read\n  const doc = new Document(obj, { customTags: [sourcedValueYAMLTag] });\n\n  // Quote the strings, including keys, that a YAML 1.1 parser would read as a boolean or a number,\n  // which a YAML 1.2 parser doesn’t, so the `yaml` library writes them plain. Don’t use the\n  // `version: '1.1'` option instead, as it would also quote dates\n  visit(doc, {\n    /**\n     * Quote a string scalar if needed, and restore an integer that a `number` can’t represent.\n     * @param {unknown} _key Key of the node in its parent.\n     * @param {Scalar} node Scalar node.\n     */\n    Scalar: (_key, node) => {\n      if (typeof node.value === 'string' && isAmbiguousYAMLString(node.value)) {\n        node.type = toStringOptions.singleQuote ? 'QUOTE_SINGLE' : 'QUOTE_DOUBLE';\n      }\n\n      // Write an integer that a `number` can’t represent exactly as it was read\n      const source = getUnsafeIntegerSource(node.value);\n\n      if (source !== undefined) {\n        node.value = BigInt(source);\n      }\n    },\n  });\n\n  addYAMLComments(doc.contents, comments);\n\n  return doc.toString(toStringOptions).trim();\n};\n\n/**\n * Formatter for each syntax, taking the content, the file configuration and the comments to add.\n * @type {Record<FormatSyntax, (content: RawEntryContent, _file: FileConfig,\n * comments?: Record<FieldKeyPath, string>) => string>}\n */\nconst FORMATTERS = {\n  /**\n   * Format the given content as YAML, with the comments.\n   * @param {RawEntryContent} content Content.\n   * @param {FileConfig} _file File configuration.\n   * @param {Record<FieldKeyPath, string>} [comments] Comments.\n   * @returns {string} Formatted document.\n   */\n  yaml: (content, { yamlQuote = false }, comments) =>\n    formatYAML(content, undefined, { quote: yamlQuote }, comments),\n  /**\n   * Format the given content as TOML.\n   * @param {RawEntryContent} content Content.\n   * @returns {string} Formatted document.\n   */\n  toml: (content) => formatTOML(content),\n  /**\n   * Format the given content as JSON.\n   * @param {RawEntryContent} content Content.\n   * @returns {string} Formatted document.\n   */\n  json: (content) => formatJSON(content),\n};\n\n/**\n * Format the given content in the given syntax, with the comments. The comments at the top of the\n * file being overwritten are kept in YAML and TOML; JSON has no comments.\n * @param {object} args Arguments.\n * @param {FormatSyntax} args.syntax Syntax.\n * @param {RawEntryContent} args.content Content.\n * @param {FileConfig} args._file File configuration.\n * @param {Record<FieldKeyPath, string>} [args.comments] Comments to add before the keys, keyed by\n * field key path. YAML only.\n * @param {string} [args.leadingComment] Comments at the top of the file being overwritten, or of\n * its front matter.\n * @returns {string} Formatted document.\n */\nconst formatSyntax = ({ syntax, content, _file, comments, leadingComment }) => {\n  const str = FORMATTERS[syntax](content, _file, comments);\n\n  return syntax === 'json' ? str : prependLeadingComment(str, leadingComment);\n};\n\n/**\n * Check whether the given format is written as front matter followed by a body, including the\n * `frontmatter` format, in which a new file gets YAML front matter.\n * @param {string} format File format.\n * @returns {boolean} Result.\n */\nconst isFrontMatterFormat = (format) =>\n  format === 'frontmatter' || FRONTMATTER_FORMATS.includes(/** @type {any} */ (format));\n\n/**\n * Format front matter for the given entry content.\n * @param {object} args Arguments.\n * @param {RawEntryContent} args.content Entry content.\n * @param {FileConfig} args._file File configuration.\n * @param {Record<FieldKeyPath, string>} [args.comments] Comments to add before the keys, keyed by\n * field key path. YAML only.\n * @param {string} [args.leadingComment] Comments at the top of the front matter being overwritten.\n * YAML and TOML only.\n * @returns {string} Formatted front matter.\n * @throws {Error} When the format is not a front matter format, or the content could not be\n * formatted.\n */\nexport const formatFrontMatter = ({ content, _file, comments, leadingComment }) => {\n  const {\n    format,\n    fmDelimiters,\n    bodyField: { key: bodyKey = 'body', inline: bodyInline = false } = {},\n  } = _file;\n\n  const [sd, ed] = fmDelimiters ?? FRONTMATTER_DELIMITER_MAP['yaml-frontmatter'];\n  let body = '';\n\n  if (!bodyInline && Object.hasOwn(content, bodyKey)) {\n    const value = content[bodyKey];\n\n    // Only text can go below the front matter. Any other value, e.g. an object in a file not\n    // written by the CMS, stays in the front matter rather than being thrown away; a missing value\n    // is just an empty body\n    if (typeof value === 'string' || value === null || value === undefined) {\n      body = value ?? '';\n      delete content[bodyKey];\n    }\n  }\n\n  // Support Markdown without a front matter block, particularly for VitePress. A body starting with\n  // a delimiter line would be read back as front matter, though, so it gets an empty block above\n  // it. Any default delimiter counts, as the `frontmatter` format is detected from the first line.\n  // The parser skips any whitespace before the block, so the first line is the first one after\n  // that, e.g. a thematic break below a blank line, but the body is written as is. The blank line\n  // inside the block keeps the parser from taking the body’s delimiter as the end\n  if (!Object.keys(content).length) {\n    // A block holding nothing but comments is kept as is\n    if (leadingComment) {\n      return `${sd}\\n${leadingComment}\\n${ed}\\n${body ? `\\n${body}\\n` : ''}`;\n    }\n\n    const firstLine = body.trimStart().split('\\n', 1)[0].trimEnd();\n    const delimiters = [sd, ...Object.values(FRONTMATTER_DELIMITER_MAP).map(([d]) => d)];\n\n    return delimiters.includes(firstLine) ? `${sd}\\n\\n${ed}\\n\\n${body}\\n` : `${body}\\n`;\n  }\n\n  const syntax = isFrontMatterFormat(format) ? getFormatSyntax(format) : undefined;\n\n  if (!syntax) {\n    throw new Error(`Unsupported front matter format: ${format}`);\n  }\n\n  let head = formatSyntax({ syntax, content, _file, comments, leadingComment });\n\n  // Like Netlify/Decap CMS, strip the outer braces of the object when they double as the\n  // delimiters, so the front matter block is the object itself rather than one wrapped in another\n  // pair of braces\n  if (syntax === 'json' && sd === '{' && ed === '}') {\n    head = head.slice(1, -1).replace(/^\\n/, '').replace(/\\n$/, '');\n  }\n\n  return `${sd}\\n${head}\\n${ed}\\n${!bodyInline && body ? `\\n${body}\\n` : ''}`;\n};\n\n/**\n * Format raw entry content with the built-in formatter for its format.\n * @param {object} entry File entry.\n * @param {RawEntryContent | Record<InternalLocaleCode, RawEntryContent>} entry.content Content\n * object. Note that this method may modify the `content` (the `body` property will be removed if\n * exists) so it shouldn’t be a reference to an existing object.\n * @param {FileConfig} entry._file Entry file configuration.\n * @param {Record<FieldKeyPath, string>} [entry.comments] Comments to add before the keys, keyed by\n * field key path, from the `comment` field option. YAML only, like Netlify/Decap CMS.\n * @param {FileState} [entry.state] What is remembered about the file being overwritten: the source\n * text of the values, to write the ones that haven’t changed as they were, and the comments at the\n * top, to keep in YAML and TOML.\n * @returns {string} Formatted string.\n * @throws {Error} When the content could not be formatted.\n */\nconst formatWithBuiltInFormatter = ({ content, _file, comments, state = {} }) => {\n  const { valueSources, leadingComment } = state;\n  const { format } = _file;\n\n  if (format === 'raw') {\n    return typeof content.body === 'string' ? `${content.body}\\n` : '';\n  }\n\n  // Write the values that haven’t changed as they were, e.g. a float that is a whole number rather\n  // than as an integer, or a TOML date rather than as a string\n  if (valueSources) {\n    content = TOML_FORMATS.includes(format)\n      ? restoreTomlValueSources(content, valueSources)\n      : restoreValueSources(content, valueSources);\n  }\n\n  try {\n    if (isFrontMatterFormat(format)) {\n      return formatFrontMatter({ content, _file, comments, leadingComment });\n    }\n\n    // A built-in format other than `raw` has a syntax\n    const syntax = /** @type {FormatSyntax} */ (getFormatSyntax(format));\n\n    return `${formatSyntax({ syntax, content, _file, comments, leadingComment })}\\n`;\n  } catch (/** @type {any} */ ex) {\n    throw new Error(`The entry could not be formatted due to ${ex.name}: ${ex.message}`, {\n      cause: ex,\n    });\n  }\n};\n\n/**\n * Format raw entry content, with the custom formatter registered for its format if any, or with the\n * built-in one. A custom formatter can call the built-in one with the `serialize` function it’s\n * given, e.g. to run the output through a code formatter.\n * @param {object} entry File entry.\n * @param {RawEntryContent | Record<InternalLocaleCode, RawEntryContent>} entry.content Content\n * object. Note that this method may modify the `content` (the `body` property will be removed if\n * exists) so it shouldn’t be a reference to an existing object.\n * @param {FileConfig} entry._file Entry file configuration.\n * @param {Record<FieldKeyPath, string>} [entry.comments] Comments to add before the keys, keyed by\n * field key path, from the `comment` field option. YAML only, like Netlify/Decap CMS.\n * @param {FileState} [entry.state] What is remembered about the file being overwritten: the source\n * text of the values, to write the ones that haven’t changed as they were, and the comments at the\n * top, to keep in YAML and TOML.\n * @returns {Promise<string>} Formatted string.\n * @throws {Error} When the format has no formatter, neither a custom one nor a built-in one, or the\n * content could not be formatted. Writing an empty file instead would wipe the entry’s content.\n */\nexport const formatEntryFile = async ({ content, _file, comments, state }) => {\n  // An existing file of a collection in the `frontmatter` format is saved in the front matter\n  // format it was read in, but the custom formatter is registered under the configured format. Fall\n  // back to one registered for the detected format, which is what was used before\n  const { format, configuredFormat = format } = _file;\n  const configuredFormatter = customFileFormatRegistry.get(configuredFormat)?.formatter;\n  const customFormat = configuredFormatter ? configuredFormat : format;\n\n  const customFormatter =\n    configuredFormatter ?? customFileFormatRegistry.get(customFormat)?.formatter;\n\n  const hasBuiltInFormatter = BUILTIN_FILE_FORMATS.includes(format);\n\n  if (!customFormatter) {\n    if (!hasBuiltInFormatter) {\n      throw new Error(\n        customFileFormatRegistry.has(format)\n          ? `Entries in the custom “${format}” format can’t be saved, as no \\`toFile\\` method ` +\n              'was registered for it with `CMS.registerCustomFormat()`'\n          : `Entries in the unknown “${format}” format can’t be saved`,\n      );\n    }\n\n    return formatWithBuiltInFormatter({ content, _file, comments, state });\n  }\n\n  /** @type {FileFormatterContext} */\n  const context = {\n    /**\n     * Format the given content with the built-in formatter.\n     * @param {any} data Entry content.\n     * @returns {Promise<string>} Formatted string.\n     * @throws {Error} When the format has no built-in formatter, or the content could not be\n     * formatted.\n     */\n    serialize: async (data) => {\n      // Formatting an empty object instead would wipe the entry’s content\n      if (typeof data !== 'object' || data === null) {\n        throw new TypeError('The `serialize` function must be given the entry content');\n      }\n\n      if (!hasBuiltInFormatter) {\n        throw new Error(\n          `Entries in the custom “${format}” format can’t be serialized, as there’s no built-in ` +\n            'formatter for it',\n        );\n      }\n\n      return formatWithBuiltInFormatter({\n        // Copy the content, as the built-in formatter takes the body out of it\n        content: Array.isArray(data) ? [...data] : { ...data },\n        _file,\n        comments,\n        state,\n      });\n    },\n  };\n\n  const output = await customFormatter(content, context);\n\n  if (typeof output !== 'string') {\n    throw new TypeError(\n      `The \\`toFile\\` method registered for the custom “${customFormat}” format must return ` +\n        'a string',\n    );\n  }\n\n  return `${output.trim()}\\n`;\n};\n","import {\n  buildSingleFileContent,\n  getFieldComments,\n  getSingleFileComments,\n} from '$lib/services/contents/draft/save/content';\nimport { serializeContent } from '$lib/services/contents/draft/save/serialize';\nimport { formatEntryFile } from '$lib/services/contents/file/format';\n\n/**\n * @import {\n * Entry,\n * FileConfig,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalLocaleCode,\n * FileState,\n * } from '$lib/types/private';\n */\n\n/**\n * Serialize an entry’s content and format it as the data of one of the files the entry is stored\n * in, along with the `comment` field options to be written in a YAML file.\n * @param {object} args Arguments.\n * @param {any} args.draft Entry draft, or a synthetic draft holding the properties read by\n * {@link serializeContent}.\n * @param {InternalCollection | InternalCollectionFile} args.config Collection or collection file\n * holding the i18n configuration.\n * @param {FileConfig} args._file Entry file configuration.\n * @param {Entry} args.entry Entry to be saved.\n * @param {InternalLocaleCode} [args.locale] Locale of the file, when the collection uses a\n * file-per-locale i18n structure. Omit it for an entry stored in a single file, which then holds\n * every locale.\n * @param {FileState} [args.state] What is remembered about the file being overwritten. See\n * {@link formatEntryFile}.\n * @returns {Promise<string>} Formatted file data.\n */\nexport const formatEntryData = ({ draft, config, _file, entry, locale, state }) =>\n  formatEntryFile(\n    // The format of `_file` is the one the file is actually saved in, e.g. the front matter format\n    // detected in an existing file of a collection in the `frontmatter` format\n    locale === undefined\n      ? {\n          content: buildSingleFileContent({ config, entry, draft, format: _file.format }),\n          _file,\n          comments: getSingleFileComments({ config, fields: draft.fields }),\n          state,\n        }\n      : {\n          content: serializeContent({\n            draft,\n            locale,\n            valueMap: entry.locales[locale].content,\n            format: _file.format,\n          }),\n          _file,\n          comments: getFieldComments(draft.fields),\n          state,\n        },\n  );\n","import { FRONTMATTER_DELIMITER_MAP } from '$lib/services/contents/file/constants';\n\n/**\n * @import { FileConfig } from '$lib/types/private';\n * @import { FrontMatterFormat } from '$lib/types/public';\n */\n\n/**\n * Get the configuration to save a file with. In a collection in the `frontmatter` format, an\n * existing file keeps the front matter format it was read in, with the default delimiters of that\n * format unless the collection sets its own; only a new file gets YAML front matter.\n * @param {object} args Arguments.\n * @param {FileConfig} args._file Configuration of the collection’s files.\n * @param {FrontMatterFormat} [args.format] Front matter format detected in the file before the\n * save, if it exists.\n * @returns {FileConfig} Configuration.\n */\nexport const getSavedFileConfig = ({ _file, format }) => {\n  if (_file.format !== 'frontmatter' || !format) {\n    return _file;\n  }\n\n  return {\n    ..._file,\n    format,\n    configuredFormat: _file.format,\n    fmDelimiters: _file.fmDelimiters ?? FRONTMATTER_DELIMITER_MAP[format],\n  };\n};\n","import { backend } from '$lib/services/backends';\nimport { formatEntryData } from '$lib/services/contents/draft/save/entry-file';\nimport { getSavedFileConfig } from '$lib/services/contents/file/detected-formats';\nimport { takeOverFileState } from '$lib/services/contents/file/state';\nimport { usesSingleFileStructure } from '$lib/services/contents/i18n/config';\nimport { getRepositoryDatabase } from '$lib/services/utils/database';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * Entry,\n * FileChange,\n * FileConfig,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalI18nOptions,\n * InternalLocaleCode,\n * RepositoryFileInfo,\n * } from '$lib/types/private';\n */\n\n/**\n * A change to one of the files an entry occupies, as planned by the caller of\n * {@link buildEntryFileChanges}, which then fills in the previous SHA and the file data.\n * @typedef {Omit<FileChange, 'previousSha' | 'data'> & { currentPath?: string }} EntryFilePlan\n * The `currentPath` is the path the file is stored at now, to look up its SHA with. It’s\n * `undefined` for a new file.\n */\n\n/**\n * Resolve a usable file-cache `IndexedDB` handle: prefer the caller-provided one (so the same\n * handle is shared across composite operations like delete + renumber), otherwise open one.\n * @param {IndexedDB} [provided] Caller-provided handle.\n * @returns {IndexedDB | undefined} Cache handle, or `undefined` if no backend is configured.\n */\nexport const resolveCacheDB = (provided) => {\n  if (provided) {\n    return provided;\n  }\n\n  return getRepositoryDatabase(backend.current?.repository, 'file-cache');\n};\n\n/**\n * Get the previous SHA of the file from the cache database.\n * @param {object} args Arguments.\n * @param {string | undefined} args.previousPath Previous file path.\n * @param {IndexedDB | undefined} args.cacheDB Cache database for file info.\n * @returns {Promise<string | undefined>} Previous SHA or `undefined` if not found.\n */\nexport const getPreviousSha = async ({ previousPath, cacheDB }) => {\n  if (!previousPath) {\n    return undefined;\n  }\n\n  const cache = /** @type {RepositoryFileInfo | undefined} */ (await cacheDB?.get(previousPath));\n\n  return cache?.sha;\n};\n\n/**\n * Check if the entries of a collection are stored in a single file each, rather than in a file per\n * locale.\n * @param {InternalI18nOptions} i18n Normalized i18n configuration of the collection or collection\n * file.\n * @returns {boolean} Result.\n */\nexport const isSingleFileEntry = ({ i18nEnabled, structureMap = /** @type {any} */ ({}) }) =>\n  !i18nEnabled || usesSingleFileStructure(structureMap);\n\n/**\n * Build the file changes for an entry, one for each file it occupies: a single one, or one per\n * locale if the collection uses a file-per-locale i18n structure. The caller plans each change,\n * and the previous SHA and the data of the file are filled in. A deleted file has no data.\n * @param {object} args Arguments.\n * @param {any} args.draft Entry draft, or a synthetic draft holding the properties read by\n * {@link formatEntryData}.\n * @param {InternalCollection | InternalCollectionFile} args.config Collection or collection file\n * the entry belongs to.\n * @param {FileConfig} args._file Entry file configuration.\n * @param {Entry} args.entry Entry to be saved.\n * @param {IndexedDB | undefined} args.cacheDB Cache database for file info.\n * @param {(locale?: InternalLocaleCode) => EntryFilePlan | undefined} args.planChange Function\n * planning the change to the file of the given locale, or to the single file if no locale is\n * given. It returns `undefined` if the file doesn’t change.\n * @returns {Promise<FileChange[]>} File changes.\n */\nexport const buildEntryFileChanges = async ({\n  draft,\n  config,\n  _file,\n  entry,\n  cacheDB,\n  planChange,\n}) => {\n  const locales = isSingleFileEntry(config._i18n) ? [undefined] : config._i18n.allLocales;\n\n  const changes = await Promise.all(\n    locales.map(async (locale) => {\n      const plan = planChange(locale);\n\n      if (!plan) {\n        return undefined;\n      }\n\n      const { currentPath, ...change } = plan;\n\n      if (change.action === 'delete') {\n        return {\n          ...change,\n          previousSha: await getPreviousSha({ cacheDB, previousPath: currentPath }),\n        };\n      }\n\n      // What is remembered about a file storing all the entries of an entry collection, e.g. the\n      // source map keyed by the position of each item, only applies when the whole file is\n      // formatted, see `combineArrayFileChanges()`. A new item has no path of its own to take it\n      // over from either, which would make the file forget it before it’s written\n      const state = _file.arrayFile\n        ? {}\n        : takeOverFileState({ previousPath: currentPath, path: change.path });\n\n      const [previousSha, data] = await Promise.all([\n        getPreviousSha({ cacheDB, previousPath: currentPath }),\n        formatEntryData({\n          draft,\n          config,\n          _file: getSavedFileConfig({ _file, format: state.format }),\n          entry,\n          locale,\n          state,\n        }),\n      ]);\n\n      return { ...change, previousSha, data };\n    }),\n  );\n\n  return /** @type {FileChange[]} */ (changes.filter(Boolean));\n};\n","import { generateUUID } from '@sveltia/utils/crypto';\nimport equal from 'fast-deep-equal';\n\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { allEntries } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { resolveCacheDB } from '$lib/services/contents/draft/save/file-changes';\nimport { getEntrySummaryFromContent } from '$lib/services/contents/entry/summary';\nimport { formatEntryFile } from '$lib/services/contents/file/format';\nimport { arrayFileItems, createArrayItemEntry } from '$lib/services/contents/file/process';\nimport { fileStates, updateFileState } from '$lib/services/contents/file/state';\nimport { moveArrayItemSources } from '$lib/services/contents/file/value-sources';\nimport { getEntryFoldersByPath } from '$lib/services/contents/folders';\n\n/**\n * @import {\n * ArrayItemTarget,\n * Entry,\n * FileChange,\n * InternalEntryCollection,\n * RepositoryFileInfo,\n * RepositoryFileMetadata,\n * ValueSourceMap,\n * } from '$lib/types/private';\n */\n\n/**\n * Item of a file storing all the entries of an entry collection, as it will be saved.\n * @typedef {object} ArrayFileSlot\n * @property {any} item Raw item.\n * @property {number} [from] Position of the item in the array before the changes. `undefined` for\n * a new item.\n */\n\n/**\n * Changes made to a file storing all the entries of an entry collection, combined into one.\n * @typedef {object} ArrayFileUpdate\n * @property {InternalEntryCollection} collection Collection.\n * @property {string} path File path.\n * @property {ArrayFileSlot[]} slots Items of the file, as they will be saved.\n * @property {FileChange} change Change rewriting the whole file.\n * @property {ValueSourceMap} [sourceMap] Source map of the file as it will be saved.\n */\n\n/**\n * Get the entry collection storing all the entries in the file at the given path.\n * @param {string} path File path.\n * @returns {InternalEntryCollection | undefined} Collection, or `undefined` if the file is not one.\n */\nexport const getArrayFileCollection = (path) => {\n  // Such a file is listed with its path like a collection file, but without a collection file name\n  const folder = getEntryFoldersByPath(path).find(\n    ({ fileName, filePathMap }) => !fileName && !!filePathMap,\n  );\n\n  const collection = folder ? getCollection(folder.collectionName) : undefined;\n\n  return isArrayFileCollection(collection)\n    ? /** @type {InternalEntryCollection} */ (collection)\n    : undefined;\n};\n\n/**\n * Get the changes to be made to a file storing all the entries of an entry collection.\n * @param {FileChange[]} changes Changes.\n * @returns {Map<string, { collection: InternalEntryCollection, changes: FileChange[] }>} Changes\n * grouped by file path. Changes to other files are not included.\n */\nconst groupArrayFileChanges = (changes) => {\n  /** @type {Map<string, { collection: InternalEntryCollection, changes: FileChange[] }>} */\n  const groups = new Map();\n\n  changes.forEach((change) => {\n    const { path } = change;\n    const group = groups.get(path);\n\n    if (group) {\n      group.changes.push(change);\n\n      return;\n    }\n\n    const collection = getArrayFileCollection(path);\n\n    if (collection) {\n      groups.set(path, { collection, changes: [change] });\n    }\n  });\n\n  return groups;\n};\n\n/**\n * Apply the changes to the items of a file storing all the entries of an entry collection.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Collection.\n * @param {string} args.path File path.\n * @param {any[]} args.items Items currently in the file.\n * @param {FileChange[]} args.changes Changes to the items.\n * @returns {ArrayFileSlot[]} Items to be saved.\n * @throws {Error} When an item has been changed since the user has seen it, which means it has\n * probably moved, and the change would then apply to another item.\n */\nexport const applyArrayFileChanges = ({ collection, path, items, changes }) => {\n  /** @type {ArrayFileSlot[]} */\n  const slots = items.map((item, index) => ({ item, from: index }));\n  // A reorder moves the slots around, but each keeps the position it came from, so an item can be\n  // found by that position without going through the slots for each change\n  const slotsByOrigin = new Map(slots.map((slot) => [slot.from, slot]));\n  /** @type {Set<number>} */\n  const removed = new Set();\n\n  /**\n   * Make sure the item the user has seen is still at the same position.\n   * @param {ArrayItemTarget} target Item.\n   * @throws {Error} When it isn’t.\n   */\n  const check = ({ index, locales }) => {\n    const current =\n      index < items.length\n        ? createArrayItemEntry({ collection, item: items[index], index, path })\n        : undefined;\n\n    if (index >= items.length || (locales && !equal(current?.locales, locales))) {\n      throw createLocalizedError(\n        `The item at ${index} in ${path} has been changed since it was loaded.`,\n        'save_conflict.array_item_changed',\n      );\n    }\n  };\n\n  changes.forEach((change) => {\n    const { action, data, arrayItem, arrayOrder } = change;\n\n    if (arrayOrder) {\n      arrayOrder.forEach(check);\n\n      // The items take the positions the listed items occupy now, so an item that’s not listed,\n      // e.g. one that doesn’t make an entry, stays where it is\n      const positions = arrayOrder.map(({ index }) => index).sort((a, b) => a - b);\n      const reordered = arrayOrder.map(({ index }) => slots[index]);\n\n      positions.forEach((position, order) => {\n        slots[position] = reordered[order];\n      });\n\n      return;\n    }\n\n    if (arrayItem) {\n      check(arrayItem);\n    }\n\n    if (action === 'delete') {\n      if (arrayItem) {\n        removed.add(arrayItem.index);\n      }\n\n      return;\n    }\n\n    const item = JSON.parse(/** @type {string} */ (data));\n\n    if (arrayItem) {\n      // The position can have changed with a reorder made in the same commit. A removed item is\n      // only left out at the end, so the item is always found\n      const slot = /** @type {ArrayFileSlot} */ (slotsByOrigin.get(arrayItem.index));\n\n      slot.item = item;\n    } else {\n      slots.push({ item });\n    }\n  });\n\n  return slots.filter(({ from }) => from === undefined || !removed.has(from));\n};\n\n/**\n * Get a label for the first item changed in a file storing all the entries of an entry collection,\n * which stands in for the entry slug in the commit message, as the slug is just the position.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Collection.\n * @param {string} args.path File path.\n * @param {any[]} args.items Items currently in the file.\n * @param {FileChange} args.change First change to the file.\n * @returns {string | undefined} Label, e.g. the title of the entry.\n */\nconst getItemLabel = ({ collection, path, items, change }) => {\n  const { data, arrayItem, arrayOrder } = change;\n  const target = arrayOrder?.[0] ?? arrayItem;\n  const index = target?.index ?? items.length;\n  const item = data ? JSON.parse(/** @type {string} */ (data)) : items[index];\n  const entry = createArrayItemEntry({ collection, item, index, path });\n  const content = entry?.locales[collection._i18n.defaultLocale]?.content;\n\n  return content\n    ? getEntrySummaryFromContent(content, {\n        identifierField: collection.identifier_field,\n        useBody: false,\n      }) || undefined\n    : undefined;\n};\n\n/**\n * Combine the changes made to each file storing all the entries of an entry collection into one\n * change rewriting the file. The file is rewritten from the items as they are in the repository\n * now, rather than from the entries in the store, so an item someone else has changed in the\n * meantime is kept, as long as it’s not the one being changed, and so are the items that don’t\n * make an entry and the properties that aren’t defined as fields.\n * @param {FileChange[]} changes Changes, including the ones to other files.\n * @returns {Promise<{ changes: FileChange[], arrayFileUpdates: ArrayFileUpdate[] }>} Changes to be\n * committed, and the combined changes to the files storing all the entries.\n * @throws {Error} When a file can’t be updated, or an item has been changed by someone else.\n */\nexport const combineArrayFileChanges = async (changes) => {\n  const groups = groupArrayFileChanges(changes);\n\n  if (!groups.size) {\n    return { changes, arrayFileUpdates: [] };\n  }\n\n  const cacheDB = resolveCacheDB();\n\n  /** @type {ArrayFileUpdate[]} */\n  const arrayFileUpdates = await Promise.all(\n    [...groups].map(async ([path, { collection, changes: fileChanges }]) => {\n      const items = arrayFileItems.get(path);\n\n      // A file that exists but doesn’t contain an array can’t be updated without losing its content\n      if (items === null) {\n        throw createLocalizedError(\n          `${path} can’t be updated, as it doesn’t contain a valid array.`,\n          'save_conflict.array_file_invalid',\n          { path },\n        );\n      }\n\n      const slots = applyArrayFileChanges({\n        collection,\n        path,\n        items: items ?? [],\n        changes: fileChanges,\n      });\n\n      const cache = /** @type {RepositoryFileInfo | undefined} */ (await cacheDB?.get(path));\n      const state = fileStates.get(path) ?? {};\n\n      // The source text of the values read from the file moves along with the items\n      const sourceMap = state.valueSources\n        ? moveArrayItemSources(\n            state.valueSources,\n            slots.map(({ from }) => from),\n          )\n        : undefined;\n\n      /** @type {FileChange} */\n      const change = {\n        action: items ? 'update' : 'create',\n        slug:\n          getItemLabel({ collection, path, items: items ?? [], change: fileChanges[0] }) ??\n          fileChanges[0].slug,\n        path,\n        previousSha: cache?.sha,\n        data: await formatEntryFile({\n          content: /** @type {any} */ (slots.map(({ item }) => item)),\n          _file: collection._file,\n          // The comments at the top of the file are kept as well\n          state: { ...state, valueSources: sourceMap },\n        }),\n      };\n\n      return { collection, path, slots, change, sourceMap };\n    }),\n  );\n\n  return {\n    changes: [\n      ...changes.filter(({ path }) => !groups.has(path)),\n      ...arrayFileUpdates.map(({ change }) => change),\n    ],\n    arrayFileUpdates,\n  };\n};\n\n/**\n * Create the entries for the files storing all the entries of an entry collection, once the\n * combined changes have been committed. An entry keeps the ID of the entry it was made from, so the\n * rest of the app doesn’t lose track of it even when it has moved in the array.\n * @param {object} args Arguments.\n * @param {ArrayFileUpdate[]} args.arrayFileUpdates Combined changes.\n * @param {Entry[]} args.savingEntries Entries being saved, whose IDs go to the new entries.\n * @param {RepositoryFileMetadata} args.meta Commit metadata.\n * @returns {{ entries: Entry[], savedEntries: Map<Entry, Entry> }} All the entries in the files,\n * and the new entries made from the entries being saved.\n */\nexport const createArrayFileEntries = ({ arrayFileUpdates, savingEntries, meta }) => {\n  /** @type {Entry[]} */\n  const entries = [];\n  /** @type {Map<Entry, Entry>} */\n  const savedEntries = new Map();\n\n  arrayFileUpdates.forEach(({ collection, path, slots, sourceMap }) => {\n    const { defaultLocale } = collection._i18n;\n\n    /**\n     * Check if the given entry is stored in the file.\n     * @param {Entry} entry Entry.\n     * @returns {boolean} Result.\n     */\n    const isInFile = (entry) =>\n      entry.arrayIndex !== undefined && entry.locales[defaultLocale]?.path === path;\n\n    // Look up the entries by their position before the changes\n    const previousEntries = new Map(\n      allEntries.current.filter(isInFile).map((entry) => [entry.arrayIndex, entry]),\n    );\n\n    // The items are now what’s in the file, which the next change to it is applied to\n    arrayFileItems.set(\n      path,\n      slots.map(({ item }) => item),\n    );\n\n    if (sourceMap) {\n      updateFileState(path, { valueSources: sourceMap });\n    }\n\n    const fileSavingEntries = new Map(\n      savingEntries.filter(isInFile).map((entry) => [entry.arrayIndex, entry]),\n    );\n\n    // A new entry has no position yet, so it’s matched up with the item added for it in order\n    const newSavingEntries = savingEntries.filter(\n      (entry) => entry.arrayIndex === undefined && entry.locales[defaultLocale]?.path === path,\n    );\n\n    let newItemCount = 0;\n\n    slots.forEach(({ item, from }, index) => {\n      const savingEntry =\n        from === undefined ? newSavingEntries[newItemCount] : fileSavingEntries.get(from);\n\n      const previousEntry = from === undefined ? undefined : previousEntries.get(from);\n\n      if (from === undefined) {\n        newItemCount += 1;\n      }\n\n      const entry = createArrayItemEntry({ collection, item, index, path, meta });\n\n      if (!entry) {\n        return;\n      }\n\n      entry.id = savingEntry?.id ?? previousEntry?.id ?? generateUUID();\n      entries.push(entry);\n\n      if (savingEntry) {\n        savedEntries.set(savingEntry, entry);\n      }\n    });\n  });\n\n  return { entries, savedEntries };\n};\n","import { cacheAssetBlob } from '$lib/services/assets/info';\nimport { allAssets } from '$lib/services/assets/state';\nimport { backend } from '$lib/services/backends';\nimport { promptCommitMessage } from '$lib/services/backends/commit-prompt';\nimport { isDeployingCommit } from '$lib/services/backends/git/shared/commits';\nimport { repositoryHead } from '$lib/services/backends/git/shared/head';\nimport { checkForRemoteChanges, suspendChecksWhile } from '$lib/services/backends/refresh';\nimport { allEntries } from '$lib/services/contents';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport { combineArrayFileChanges, createArrayFileEntries } from '$lib/services/contents/file/array';\nimport { productionSHA, setLastCommitPublishHint } from '$lib/services/deployments';\nimport { user } from '$lib/services/user/account.svelte';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { getRepositoryDatabase } from '$lib/services/utils/database';\nimport { getByteSize } from '$lib/services/utils/file';\n\n/**\n * @import {\n * Asset,\n * BackendService,\n * ChangeResults,\n * CommitAuthor,\n * CommitOptions,\n * CommitResults,\n * Entry,\n * FileChange,\n * RepositoryFileInfo,\n * User,\n * } from '$lib/types/private';\n */\n\n/**\n * Get the commit author information from the user store.\n * @returns {CommitAuthor | undefined} Commit author information including `name`, `email`, `id`,\n * and `login`. `undefined` for the local and test-repo backends.\n */\nexport const getCommitAuthor = () => {\n  const userData = /** @type {User} */ (user.account);\n\n  if (!userData) {\n    return undefined;\n  }\n\n  const { name, email, id, login } = userData;\n\n  if (!name || !email) {\n    return undefined;\n  }\n\n  return { name, email, id, login };\n};\n\n/**\n * Update the file cache with the given changes. This will update the file cache with the latest\n * file content and metadata, such as SHA and size, for Git-based backends. The cache stands for the\n * state of the repository as the user knows it, so a later fetch can tell the user’s own changes\n * from someone else’s by the SHA; that’s why an asset, which has no text to cache, is recorded too.\n * @param {object} args Arguments.\n * @param {FileChange[]} args.changes Committed changes.\n * @param {CommitResults} args.commit Commit results.\n */\nexport const updateCache = async ({ changes, commit }) => {\n  const cacheDB = getRepositoryDatabase(backend.current?.repository, 'file-cache');\n\n  if (!cacheDB) {\n    return;\n  }\n\n  const { files, author: commitAuthor, date: commitDate } = commit;\n  const meta = { commitAuthor, commitDate };\n\n  await Promise.all(\n    changes.map(async (change) => {\n      const { action, path, previousPath, data } = change;\n\n      // Delete the file from the cache if the action is `delete`\n      if (action === 'delete') {\n        await cacheDB.delete(path);\n        return;\n      }\n\n      // Delete the previous file from the cache if the action is `move`\n      if (action === 'move') {\n        await cacheDB.delete(previousPath);\n      }\n\n      /** @type {RepositoryFileInfo} */\n      const fileInfo = {\n        sha: files[path]?.sha,\n        // Only a deletion, handled above, comes without data\n        size: getByteSize(/** @type {string | File} */ (data)),\n        text: typeof data === 'string' ? data : undefined,\n        meta,\n      };\n\n      // Update the file cache with the new file content and metadata\n      await cacheDB.set(path, fileInfo);\n    }),\n  );\n};\n\n/**\n * Update the entry and asset stores with the results of the commit changes.\n * @param {object} args Arguments.\n * @param {FileChange[]} args.changes Committed changes.\n * @param {Entry[]} args.savedEntries Entries that have been saved.\n * @param {Asset[]} args.savedAssets Assets that have been saved.\n * @param {Entry[]} [args.arrayFileEntries] All the entries in the files storing all the entries of\n * an entry collection that have been rewritten, which replace the entries previously in the files.\n */\nexport const updateStores = ({ changes, savedEntries, savedAssets, arrayFileEntries = [] }) => {\n  const savedEntryIds = new Set([...savedEntries, ...arrayFileEntries].map((e) => e.id));\n  const arrayFilePaths = new Set(arrayFileEntries.flatMap((e) => getEntryPaths(e)));\n  const arrayFileEntrySet = new Set(arrayFileEntries);\n\n  allEntries.current = [\n    ...allEntries.current.filter(\n      (e) =>\n        !savedEntryIds.has(e.id) &&\n        !(\n          e.arrayIndex !== undefined &&\n          Object.values(e.locales).some(({ path }) => arrayFilePaths.has(path))\n        ),\n    ),\n    ...savedEntries.filter((e) => !arrayFileEntrySet.has(e)),\n    ...arrayFileEntries,\n  ];\n\n  const excludingPaths = new Set(savedAssets.map((a) => a.path));\n\n  changes.forEach((c) => {\n    if (c.action === 'move' && c.previousPath) {\n      excludingPaths.add(c.previousPath);\n    } else if (c.action === 'delete') {\n      excludingPaths.add(c.path);\n    }\n  });\n\n  allAssets.current = [\n    ...allAssets.current.filter((a) => !excludingPaths.has(a.path)),\n    ...savedAssets,\n  ];\n};\n\n/**\n * Save changes to the backend and update the file cache and stores with the results.\n *\n * The repository is checked for someone else’s commits first, so that the commit is made on top of\n * the branch as it is rather than as it was when the site data was loaded — GitHub rejects a commit\n * made against a head that has moved. The check is a nicety here: if it fails, the commit is\n * attempted anyway, and the backend has the last word. It also brings the files storing all the\n * entries of an entry collection up to date, so the changes to them are applied to the items as\n * they are now, and combined into one change for each file.\n * @param {object} args Arguments.\n * @param {FileChange[]} args.changes Changes to be committed.\n * @param {Entry[]} [args.savingEntries] Entries to be saved.\n * @param {Asset[]} [args.savingAssets] Assets to be saved.\n * @param {CommitOptions} args.options Options for committing changes, such as commit type.\n * @returns {Promise<ChangeResults>} Change results containing the commit information, saved\n * entries, and saved assets.\n */\nexport const saveChanges = async ({ changes, savingEntries = [], savingAssets = [], options }) => {\n  const { commitChanges, fetchLastCommit } = /** @type {BackendService} */ (backend.current);\n  // Ask for a commit message first if configured, so the repository is checked for changes once\n  // the user is done, however long that takes. Cancelling it throws, leaving everything as it was\n  const commitOptions = await promptCommitMessage(changes, options);\n\n  try {\n    await checkForRemoteChanges();\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to check the repository for changes.', ex);\n  }\n\n  /** Whether the commit has landed on top of someone else’s commit the stores don’t reflect. */\n  let missedRemoteChanges = false;\n\n  const results = await suspendChecksWhile(async () => {\n    // The head the stores reflect, which the commit is expected to be made on top of\n    const headBefore = repositoryHead.current;\n    // A check for remote changes made from here on would replace the items the changes are applied\n    // to, and the entries the saved ones are matched up with\n    const { changes: combinedChanges, arrayFileUpdates } = await combineArrayFileChanges(changes);\n\n    /** @type {CommitResults} */\n    const commit = {\n      ...(await commitChanges(combinedChanges, commitOptions)),\n      author: getCommitAuthor(),\n    };\n\n    if (prefs.devModeEnabled) {\n      // eslint-disable-next-line no-console\n      console.debug('Commit changes:', combinedChanges);\n      // eslint-disable-next-line no-console\n      console.debug('Commit results:', commit);\n    }\n\n    const { files, author: commitAuthor, date: commitDate } = commit;\n\n    const { entries: arrayFileEntries, savedEntries: savedArrayFileEntries } =\n      createArrayFileEntries({\n        arrayFileUpdates,\n        savingEntries,\n        meta: { commitAuthor, commitDate },\n      });\n\n    // An entry stored in a file with the other entries of the collection is replaced with the one\n    // made from the file as it has been saved, which knows its position in the array\n    const savedEntries = savingEntries.map(\n      (entry) =>\n        savedArrayFileEntries.get(entry) ??\n        /** @type {Entry} */ ({ ...entry, commitAuthor, commitDate }),\n    );\n\n    const savedAssets = await Promise.all(\n      savingAssets.map(async (asset) => {\n        const { sha, file } = files[asset.path] ?? {};\n\n        const savedAsset = /** @type {Asset} */ ({\n          ...asset,\n          sha,\n          blobURL: undefined,\n          commitAuthor,\n          commitDate,\n        });\n\n        // The URL has the CMS origin and can be opened in a new tab from a preview, so an SVG image\n        // gets the URL of a wrapper that can’t run any script, like an asset loaded from the\n        // repository does. The file is remembered with it, so reading the asset gives the file\n        if (file) {\n          try {\n            await cacheAssetBlob(savedAsset, file);\n          } catch (ex) {\n            // The commit has landed, so the save has succeeded; the asset is loaded from the\n            // repository instead\n            // eslint-disable-next-line no-console\n            console.error('Failed to cache the saved asset.', ex);\n          }\n        }\n\n        return savedAsset;\n      }),\n    );\n\n    try {\n      await updateCache({ changes: combinedChanges, commit });\n    } catch (ex) {\n      // The commit has landed, so the save has succeeded even if the cache couldn’t be written,\n      // e.g. when the storage quota is exceeded. The stores still have to be updated and the head\n      // advanced, or the next commit would be refused. A file missing from the cache is fetched\n      // again on the next load\n      // eslint-disable-next-line no-console\n      console.error('Failed to update the file cache.', ex);\n    }\n\n    updateStores({ changes: combinedChanges, savedEntries, savedAssets, arrayFileEntries });\n    // The site is rebuilt from this commit, so the deploy state the UI reports is now about the\n    // user’s own change. Editorial Workflow commits don’t come through here; they land on a\n    // workflow branch and are tracked by the pull request instead\n    productionSHA.current = commit.sha;\n    // Whatever the commit is, e.g. an entry deletion or an asset upload, it replaces what the\n    // previous one was expected to do, until the CI/CD provider is asked about it\n    setLastCommitPublishHint(isDeployingCommit(commitOptions));\n\n    if (fetchLastCommit) {\n      // GitLab and Gitea/Forgejo only refuse a commit when one of the files being changed has been\n      // changed by someone else, so the commit can be made on top of a colleague’s commit to\n      // another file. The stores then reflect the commit only as far as the user’s own files go,\n      // and taking it as the head would mean the colleague’s commit is never fetched: the file\n      // would be saved over later, or the save refused for good. The head is left where it was\n      // instead, so the colleague’s commit is fetched by the next check\n      if (commit.parentSha === undefined || commit.parentSha === headBefore) {\n        // The stores now reflect this commit, so it’s the head to compare the branch with from here\n        // on\n        repositoryHead.current = commit.sha;\n      } else {\n        missedRemoteChanges = true;\n      }\n    }\n\n    return { commit, savedEntries, savedAssets };\n  });\n\n  if (missedRemoteChanges) {\n    // Fetch the commits made in the meantime now rather than on the next scheduled check. It’s not\n    // waited for: the save is done, and a failure leaves it to the next check\n    checkForRemoteChanges().catch((ex) => {\n      // eslint-disable-next-line no-console\n      console.error('Failed to check the repository for changes.', ex);\n    });\n  }\n\n  return results;\n};\n","import { createLazyModule } from '$lib/services/api/lazy-module';\nimport { loadModule } from '$lib/services/app/dependencies';\n\n/**\n * @import { LazyModule } from '$lib/services/api/lazy-module';\n */\n\n/**\n * @typedef {typeof import('immutable')} ImmutableModule\n */\n\n/**\n * Loader for Immutable.js. The library is only used for the Netlify/Decap CMS-compatible API —\n * custom field types, preview templates and event hooks receive Immutable Maps — so it’s fetched\n * from the CDN when one of those is registered rather than shipped with every install.\n * @type {LazyModule<ImmutableModule>}\n */\nconst immutable = createLazyModule({\n  /**\n   * Fetch the library from the CDN.\n   * @returns {Promise<ImmutableModule>} The module.\n   */\n  loader: () => loadModule('immutable', 'dist/immutable.es.js'),\n  notLoadedMessage: 'Immutable.js is not loaded yet. Call `loadImmutable()` first.',\n});\n\n/**\n * Whether Immutable.js has been loaded. Components that build props synchronously can depend on\n * this to know when they can render.\n */\nexport const immutableLoaded = immutable.loaded;\n/**\n * Load Immutable.js. Calling this again returns the same promise.\n */\nexport const loadImmutable = immutable.load;\n/**\n * Start loading Immutable.js in the background, so that it’s ready by the time a component needs\n * it. A failure is left for the eventual {@link loadImmutable} call to report.\n */\nexport const preloadImmutable = immutable.preload;\n/**\n * Get the loaded Immutable.js module. The caller is responsible for awaiting {@link loadImmutable}\n * first; anything reachable from a custom field, preview template or event hook has done so.\n */\nexport const getImmutable = immutable.get;\n/**\n * Forget the loaded module. Used in tests.\n */\nexport const _resetImmutable = immutable.reset;\n","import { encodeBase64 } from '@sveltia/utils/file';\n\nimport { getAssetBlob, getAssetBlobURL, getAssetPublicURL } from '$lib/services/assets/info';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Asset } from '$lib/types/private';\n */\n\n/**\n * Number of times an {@link AssetProxy} has had its URL replaced with a blob URL. A React\n * component reads the `url` property when it renders, and isn’t told when it changes, so the\n * components that pass `getAsset` to one depend on this to render it again with the blob URL.\n * Otherwise a preview would keep the public path, which doesn’t point to the file on the CMS site,\n * nor at all for a file that hasn’t been published yet.\n */\nexport const assetURLUpdates = createRawState(0);\n\n/**\n * Promises resolving once each {@link AssetProxy} has tried to replace its URL with the blob URL,\n * kept outside the object so that it doesn’t become part of the public `ApiAsset` interface.\n * @type {WeakMap<object, Promise<boolean>>}\n */\nconst urlUpdates = new WeakMap();\n\n/**\n * Wait until the given asset has its final URL. An editor component preview is computed once from\n * the asset’s `url`, so the preview has to be computed again if the URL has changed meanwhile.\n * @param {object} asset Asset returned by a `getAsset` function.\n * @returns {Promise<boolean>} Whether the `url` property has changed. Always `false` for an asset\n * that isn’t an {@link AssetProxy}, e.g. an unsaved file, whose URL is final from the start.\n */\nexport const waitForAssetURL = async (asset) => urlUpdates.get(asset) ?? false;\n\n/**\n * Implement the `ApiAsset` interface for assets returned by the API.\n */\nexport class AssetProxy {\n  #asset;\n\n  /**\n   * Initialize an `AssetProxy` instance with the provided asset data.\n   * @param {Asset} asset Cached asset object.\n   */\n  constructor(asset) {\n    this.#asset = asset;\n    this.path = getAssetPublicURL(asset, { pathOnly: true }) ?? '';\n    this.url = asset.blobURL ?? this.path;\n    this.field = undefined;\n    this.fileObj = asset.file;\n\n    urlUpdates.set(\n      this,\n      (async () => {\n        try {\n          // Replace the URL with the blob URL if available, otherwise keep the existing URL\n          const blobURL = await getAssetBlobURL(asset);\n\n          if (blobURL && blobURL !== this.url) {\n            this.url = blobURL;\n            assetURLUpdates.current += 1;\n\n            return true;\n          }\n        } catch {\n          // The blob can’t be retrieved, e.g. offline or the file is gone; keep the existing URL\n        }\n\n        return false;\n      })(),\n    );\n  }\n\n  /**\n   * Return the URL of the asset as a string.\n   * @returns {string} The URL of the asset.\n   */\n  toString() {\n    return this.url;\n  }\n\n  /**\n   * Return a Promise that resolves to a base64-encoded string of the asset’s content.\n   * @returns {Promise<string>} A Promise that resolves to a base64-encoded string of the asset’s\n   * content.\n   * @throws {Error} If the asset blob cannot be retrieved or encoded.\n   */\n  async toBase64() {\n    try {\n      const blob = await getAssetBlob(this.#asset);\n\n      return encodeBase64(blob);\n    } catch (/** @type {any} */ error) {\n      throw new Error(`Failed to encode asset as base64: ${error.message}`);\n    }\n  }\n}\n","import { encodeBase64 } from '@sveltia/utils/file';\n\nimport { fetchOK } from '$lib/services/utils/networking';\n\n/**\n * Implement the `ApiAsset` interface for a file on an external location, referred to with a\n * complete URL, e.g. `https://example.com/photo.jpg`, or a URL derived from a cloud storage\n * service’s base URL. The URL serves as both the `url` and the `path`, like Netlify/Decap CMS.\n */\nexport class ExternalAssetProxy {\n  /**\n   * Initialize an `ExternalAssetProxy` instance.\n   * @param {string} url URL of the file.\n   */\n  constructor(url) {\n    this.path = url;\n    this.url = url;\n    this.field = undefined;\n    this.fileObj = undefined;\n  }\n\n  /**\n   * Return the URL of the asset as a string.\n   * @returns {string} The URL of the asset.\n   */\n  toString() {\n    return this.url;\n  }\n\n  /**\n   * Return a Promise that resolves to a base64-encoded string of the file’s content.\n   * @returns {Promise<string>} A Promise that resolves to a base64-encoded string of the file’s\n   * content.\n   * @throws {Error} If the file cannot be retrieved, e.g. because the server doesn’t allow\n   * cross-origin requests, or encoded.\n   */\n  async toBase64() {\n    try {\n      return encodeBase64(await (await fetchOK(this.url)).blob());\n    } catch (/** @type {any} */ error) {\n      throw new Error(`Failed to encode asset as base64: ${error.message}`);\n    }\n  }\n}\n","import { encodeBase64 } from '@sveltia/utils/file';\n\n/**\n * Implement the `ApiAsset` interface for a file added to the entry draft but not saved yet. A field\n * value refers to such a file with its temporary blob URL until the entry is saved, so the URL\n * serves as both the `url` and the `path`.\n */\nexport class UnsavedAssetProxy {\n  #file;\n\n  /**\n   * Initialize an `UnsavedAssetProxy` instance.\n   * @param {string} blobURL Blob URL the field value refers to the file with.\n   * @param {File} file File to be uploaded.\n   */\n  constructor(blobURL, file) {\n    this.#file = file;\n    this.path = blobURL;\n    this.url = blobURL;\n    this.field = undefined;\n    this.fileObj = file;\n  }\n\n  /**\n   * Return the URL of the asset as a string.\n   * @returns {string} The URL of the asset.\n   */\n  toString() {\n    return this.url;\n  }\n\n  /**\n   * Return a Promise that resolves to a base64-encoded string of the file’s content.\n   * @returns {Promise<string>} A Promise that resolves to a base64-encoded string of the file’s\n   * content.\n   */\n  async toBase64() {\n    return encodeBase64(this.#file);\n  }\n}\n","import { DOCS_BASE_URL } from '$lib/services/app';\n\n/**\n * Mapping of deprecation warnings that have been issued once. This prevents flooding the console\n * with repeated warnings.\n * @type {Record<string, boolean>}\n */\nexport const warnedOnceMap = {\n  slug_length: false,\n  slug_editor_tag: false,\n  yaml_quote: false,\n  save_all_locales: false,\n  automatic_deployments: false,\n  multiple_folders_i18n_root: false,\n  omit_default_locale_from_filename: false,\n  logo_url: false,\n  flat_metadata_keys: false,\n};\n\n/**\n * Deprecation warning messages.\n * @type {Record<string, string>}\n */\nexport const warningMessages = {\n  slug_length:\n    'The `slug_length` collection option is deprecated and will be removed in Sveltia CMS 1.0. ' +\n    'Use the global `slug.maxlength` option instead. ' +\n    `${DOCS_BASE_URL}/collections/entries/slugs#global-slug-options`,\n  slug_editor_tag:\n    'The `{{fields._slug}}` and `{{fields._slug | localize}}` slug template tags are deprecated ' +\n    'and will be removed in Sveltia CMS 1.0. Use the `slug` collection option’s object form ' +\n    'instead: `{{fields._slug}}` is equivalent to `slug: { editable: true }`, and ' +\n    '`{{fields._slug | localize}}` is equivalent to `slug: { editable: true, i18n: true }`. ' +\n    `${DOCS_BASE_URL}/collections/entries/slugs#making-slugs-editable`,\n  yaml_quote:\n    'The `yaml_quote` collection option is deprecated and will be removed in Sveltia CMS 1.0. ' +\n    'Use the global `output.yaml.quote` option instead. `yaml_quote: true` is equivalent to ' +\n    '`quote: double`. ' +\n    `${DOCS_BASE_URL}/data-output#controlling-data-output`,\n  save_all_locales:\n    'The `save_all_locales` i18n option is deprecated and will be removed in Sveltia CMS 1.0. ' +\n    'Use the `initial_locales` option instead. `save_all_locales: false` is equivalent to ' +\n    '`initial_locales: all`. ' +\n    `${DOCS_BASE_URL}/i18n/options#disabling-non-default-locale-content`,\n  automatic_deployments:\n    'The `automatic_deployments` backend option is deprecated and will be removed in Sveltia CMS ' +\n    '1.0. Use the `skip_ci` option instead. `automatic_deployments: false` is equivalent to ' +\n    '`skip_ci: true`, and `automatic_deployments: true` is equivalent to `skip_ci: false`. ' +\n    `${DOCS_BASE_URL}/deployments#disabling-automatic-deployments`,\n  multiple_folders_i18n_root:\n    'The `multiple_folders_i18n_root` i18n structure is deprecated and will be removed in ' +\n    'Sveltia CMS 1.0. Use the `multiple_root_folders` structure instead. ' +\n    `${DOCS_BASE_URL}/i18n/structures#multiple-root-folders`,\n  omit_default_locale_from_filename:\n    'The `omit_default_locale_from_filename` i18n option is deprecated and will be removed in ' +\n    'Sveltia CMS 1.0. Use the `omit_default_locale_from_file_path` option instead. ' +\n    `${DOCS_BASE_URL}/i18n/options`,\n  logo_url:\n    'The `logo_url` option is deprecated and will be removed in a future version of Sveltia CMS. ' +\n    'Use the `logo.src` option instead. ' +\n    `${DOCS_BASE_URL}/customization#custom-logo`,\n  flat_metadata_keys:\n    'Reading the `fieldsMetaData` of a nested field with its flat key path, like `details.author` ' +\n    'or `books.0.author`, or the metadata of a List field’s single `field` under the List field’s ' +\n    'name is deprecated and will be removed in a future version of Sveltia CMS. Use the nested ' +\n    \"path instead, like `fieldsMetaData.getIn(['books', 'author'])` or \" +\n    \"`fieldsMetaData.getIn(['tags', 'tag'])`. \" +\n    `${DOCS_BASE_URL}/api/preview-templates`,\n};\n\n/**\n * Issue a deprecation warning if it hasn’t been issued yet.\n * @param {string} key Key of the warning to issue.\n * @param {string} [message] Custom message to display instead of the default one.\n */\nexport const warnDeprecation = (key, message) => {\n  // Skip during tests\n  if (import.meta.env.VITEST) {\n    return;\n  }\n\n  if (!warnedOnceMap[key]) {\n    // eslint-disable-next-line no-console\n    console.warn(message ?? warningMessages[key]);\n    warnedOnceMap[key] = true;\n  }\n};\n","import { AssetProxy } from '$lib/services/api/asset-proxy';\nimport { ExternalAssetProxy } from '$lib/services/api/external-asset-proxy';\nimport { getImmutable } from '$lib/services/api/immutable';\nimport { UnsavedAssetProxy } from '$lib/services/api/unsaved-asset-proxy';\nimport { isAssetInFolder } from '$lib/services/assets';\nimport { getAssetFolder } from '$lib/services/assets/folders';\nimport { getMediaFieldSource, getRichTextMediaSource } from '$lib/services/assets/media-field';\nimport { allAssets } from '$lib/services/assets/state';\nimport { warnDeprecation } from '$lib/services/config/deprecations';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { getCollectionFileEntry } from '$lib/services/contents/collection/files';\nimport { filterRealValues } from '$lib/services/contents/draft';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { ITEM_INDEX_SUFFIX_REGEX } from '$lib/services/contents/entry/key-paths';\nimport { getEntryOptions } from '$lib/services/contents/fields/relation/helpers';\nimport { getOrCreate, memoizeOnSource } from '$lib/services/utils/cache';\nimport { isNumeric } from '$lib/services/utils/number';\nimport { unflattenMap } from '$lib/services/utils/object';\n\n/**\n * @import { MapOf } from 'immutable';\n * @import {\n * Asset,\n * AssetFolderInfo,\n * Entry,\n * EntryDraft,\n * EntryFileMap,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalLocaleCode,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import {\n * ApiAsset,\n * ApiEntry,\n * FieldKeyPath,\n * GetAsset,\n * ListFieldWithSubField,\n * RelationField,\n * } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} PreviewData\n * @property {MapOf<ApiEntry>} entryMap Immutable Map of entry data for the current locale.\n * @property {FlattenedEntryContent} valueMap Flattened content values for the current locale.\n * @property {Omit<GetFieldArgs, 'keyPath'>} getFieldArgs Arguments for getField function.\n * @property {MapOf<any>} fieldsMetaData Metadata for fields in the current locale.\n * @property {GetAsset} getAsset Function to get asset URLs.\n */\n\n/**\n * Create an Immutable.js Map representing the entry data, compatible with Netlify/Decap CMS event\n * hook handlers.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.content Entry content for the default locale.\n * @param {string[]} args.otherLocales Other locale keys.\n * @param {Entry['locales']} args.locales All locale data keyed by locale.\n * @param {string} args.slug Entry slug.\n * @param {string} args.path Entry file path.\n * @param {boolean} args.isNew Whether the entry is new.\n * @param {string} args.collectionName Collection name.\n * @param {Asset[]} args.associatedAssets Assets associated with the entry.\n * @returns {MapOf<ApiEntry>} Immutable Map of the entry data.\n * @see https://immutable-js.com/docs/v5/Map/\n */\nexport const createEntryMap = ({\n  content,\n  otherLocales,\n  locales,\n  slug,\n  path,\n  isNew,\n  collectionName,\n  associatedAssets,\n}) =>\n  // @ts-ignore\n  getImmutable().fromJS({\n    // Entry data for the default locale\n    data: unflattenMap(content),\n    // Entry data for other locales\n    // @see https://github.com/decaporg/decap-cms/issues/4729\n    i18n: Object.fromEntries(\n      otherLocales.map((locale) => [locale, { data: unflattenMap(locales[locale].content) }]),\n    ),\n    // Other entry properties\n    slug,\n    path,\n    newRecord: isNew,\n    collection: collectionName,\n    mediaFiles: associatedAssets.map(({ sha, file, size, blobURL, ...asset }) => ({\n      id: sha,\n      name: asset.name,\n      path: asset.path,\n      file,\n      size,\n      url: blobURL,\n      displayURL: blobURL,\n    })),\n    // Additional properties included for compatibility with Netlify/Decap CMS\n    meta: { path },\n    isModification: null,\n    label: null,\n    partial: false,\n    author: '',\n    raw: '',\n    status: '',\n    updatedOn: '',\n  });\n\n/**\n * Convert an entry to an Immutable Map for preview templates.\n * @param {object} args Arguments.\n * @param {Entry | undefined} args.entry Entry object to convert.\n * @param {InternalLocaleCode} args.locale Locale to use for content and path extraction.\n * @param {string} args.collectionName Collection name.\n * @param {Asset[]} args.associatedAssets Associated assets to include.\n * @param {FlattenedEntryContent} [args.content] Optional content override (if not provided,\n * extracted from entry).\n * @returns {MapOf<ApiEntry>} Immutable Map of entry data.\n */\nexport const convertEntryToMap = ({ entry, locale, collectionName, associatedAssets, content }) => {\n  const entryContent = content ?? entry?.locales?.[locale]?.content ?? {};\n\n  return /** @type {MapOf<ApiEntry>} */ (\n    createEntryMap({\n      content: entryContent,\n      otherLocales: Object.keys(entry?.locales ?? {}).filter((l) => l !== locale),\n      locales: entry?.locales ?? {},\n      slug: entry?.slug ?? '',\n      path: entry?.locales?.[locale]?.path ?? '',\n      isNew: false,\n      collectionName,\n      associatedAssets,\n    })\n  );\n};\n\n/**\n * Create an asset getter function for React components (preview templates and custom field types)\n * and editor component previews, compatible with the `getAsset` function of Netlify/Decap CMS.\n * @param {object} args Arguments.\n * @param {Entry} [args.entry] Entry object. Can be `undefined` when editing a new draft.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] File name.\n * @param {EntryFileMap} [args.files] Files added to the entry draft but not saved yet, keyed by the\n * blob URLs the field values refer to them with.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Key path of the RichText field, when the getter is\n * used by editor component previews.\n * @param {string[]} [args.componentNames] Names or IDs of the editor components the RichText field\n * can contain, whose field-level media folders are also searched.\n * @param {InternalLocaleCode} [args.locale] Locale being previewed, which an entry-relative path is\n * relative to. Default: the default locale.\n * @returns {GetAsset} Function that gets asset URLs.\n */\nexport const createGetAsset =\n  ({ entry, collectionName, fileName, files, typedKeyPath, componentNames, locale }) =>\n  /**\n   * Get the asset for a given asset path.\n   * @param {string} path Path to the asset, the blob URL of a file that hasn’t been saved yet, or\n   * the URL of a file on an external location.\n   * @returns {ApiAsset | undefined} Asset item.\n   */\n  (path) => {\n    const unsavedFile = files?.[path]?.file;\n\n    if (unsavedFile) {\n      return new UnsavedAssetProxy(path, unsavedFile);\n    }\n\n    const args = { value: path, entry, collectionName, fileName, typedKeyPath, locale };\n\n    const { asset, url } =\n      (componentNames\n        ? getRichTextMediaSource({ ...args, componentNames })\n        : getMediaFieldSource(args)) ?? {};\n\n    if (asset) {\n      return new AssetProxy(asset);\n    }\n\n    if (url) {\n      return new ExternalAssetProxy(url);\n    }\n\n    return undefined;\n  };\n\n/**\n * Cache of {@link getReferencedEntryLookup} results, keyed by the entry list they index, then by\n * the Relation field config, then by locale.\n * @type {WeakMap<Entry[], WeakMap<RelationField, Map<InternalLocaleCode, Map<any, Entry>>>>}\n */\nconst referencedEntryLookupCache = new WeakMap();\n\n/**\n * Get a lookup table of the given referenced entries by the value a Relation field stores. The\n * values are resolved with the field’s `value_field` template the same way as the field’s options,\n * so a template like `{{locale}}/{{slug}}` or `{{fields.name.first}}` matches the stored values.\n * The table is built once per entry list, field and locale, instead of the list being scanned for\n * every value — the metadata is rebuilt whenever the entry draft is updated.\n * @param {Entry[]} entries Referenced entries.\n * @param {InternalLocaleCode} locale Locale code.\n * @param {RelationField} fieldConfig Relation field config.\n * @returns {Map<any, Entry>} Entries by value. When several entries share a value, the first one\n * is kept.\n */\nconst getReferencedEntryLookup = (entries, locale, fieldConfig) =>\n  getOrCreate(\n    getOrCreate(\n      getOrCreate(referencedEntryLookupCache, entries, () => new WeakMap()),\n      fieldConfig,\n      () => new Map(),\n    ),\n    locale,\n    () => {\n      /** @type {Map<any, Entry>} */\n      const lookup = new Map();\n\n      entries.forEach((refEntry) => {\n        // A `value_field` referencing a list field gives one value per list item\n        getEntryOptions({ locale, fieldConfig, refEntry }).forEach(({ value }) => {\n          if (!lookup.has(value)) {\n            lookup.set(value, refEntry);\n          }\n        });\n      });\n\n      return lookup;\n    },\n  );\n\n/**\n * Get the path of a field’s metadata in `fieldsMetaData`, the way Netlify/Decap CMS nests it: each\n * Object or List field passes the metadata of its subfields up under its own name, merging the\n * metadata of all the List items. A List item index is therefore dropped, along with the index of a\n * multi-value field like a Relation field with the `multiple` option, except that a List field with\n * a single `field` passes the subfield’s metadata up under the subfield’s name. A numeric segment\n * is only an index if it doesn’t name a subfield of an Object field, e.g. `years.2024`.\n * @param {object} args Arguments.\n * @param {Omit<GetFieldArgs, 'keyPath'>} args.getFieldArgs Arguments for getField function.\n * @param {FieldKeyPath} args.keyPath Field key path, e.g. `books.0.author` or `tags.0`.\n * @returns {string[]} Metadata path, e.g. `['books', 'author']` or `['tags', 'tag']`.\n */\nexport const getMetaDataPath = ({ getFieldArgs, keyPath }) => {\n  const segments = keyPath.split('.');\n\n  return segments.flatMap((segment, index) => {\n    // A top-level segment is always a field name\n    if (!index || !isNumeric(segment)) {\n      return [segment];\n    }\n\n    const parentField = getField({\n      ...getFieldArgs,\n      keyPath: /** @type {FieldKeyPath} */ (segments.slice(0, index).join('.')),\n    });\n\n    if (parentField?.widget === 'object') {\n      return [segment];\n    }\n\n    const { field: subField } = /** @type {ListFieldWithSubField} */ (parentField ?? {});\n\n    return parentField?.widget === 'list' && subField ? [subField.name] : [];\n  });\n};\n\n/**\n * Warn when one of the given keys of an Immutable Map is read. `getIn()` goes through `get()`, so\n * replacing that method on the instance covers both. A copy made with `set()` and the like loses\n * the warning, which is fine for a Map that’s only meant to be read. Comparing the Map with\n * `Immutable.is()` reads every key, so that can warn as well.\n * @param {MapOf<any>} map Immutable Map.\n * @param {Set<string>} keys Deprecated keys.\n */\nconst warnOnRead = (map, keys) => {\n  const { get } = map;\n\n  /**\n   * Read a key of the Map, warning if it’s a deprecated one.\n   * @param {string} key Key.\n   * @param {any} [notSetValue] Value to return if the key is not found.\n   * @returns {any} Value.\n   */\n  const getWithWarning = (key, notSetValue) => {\n    if (keys.has(key)) {\n      warnDeprecation('flat_metadata_keys');\n    }\n\n    return get.call(map, key, notSetValue);\n  };\n\n  /** @type {any} */ (map).get = getWithWarning;\n};\n\n/**\n * Get metadata for fields. For relation fields, looks up and stores the referenced entry content\n * keyed by collection name and value, matching the `fieldsMetaData` structure of Netlify/Decap CMS\n * preview templates and custom field types: the metadata of a field nested in an Object or List\n * field is found under the parent field’s name, as {@link getMetaDataPath} describes, e.g.\n * `fieldsMetaData.getIn(['books', 'author', 'authors', 'jane'])`. For backward compatibility, it’s\n * also stored under the flattened key path of a nested field, e.g. `books.0.author`, with any\n * trailing List item index removed.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @param {Omit<GetFieldArgs, 'keyPath'>} args.getFieldArgs Arguments for getField function.\n * @returns {import('immutable').MapOf<any>} Immutable Map of entry metadata.\n * @see https://decapcms.org/docs/customization/#accessing-metadata\n */\nexport const getMetaData = ({ locale, getFieldArgs }) => {\n  const { valueMap = {} } = getFieldArgs;\n  // Use null-prototype objects, so a name or value like `constructor` or `__proto__` is an own key\n  /** @type {Record<string, any>} */\n  const metaData = Object.create(null);\n  /** @type {Map<string, Entry[]>} */\n  const refEntriesCache = new Map();\n  /**\n   * Flat key paths at the top level.\n   * @type {Set<string>}\n   */\n  const legacyKeys = new Set();\n  /**\n   * Collection names right under a List field’s name, for a List field with a single `field`.\n   * @type {Map<string, Set<string>>}\n   */\n  const legacyListKeys = new Map();\n\n  Object.entries(valueMap).forEach(([key, value]) => {\n    const keyPath = /** @type {FieldKeyPath} */ (key);\n    const field = getField({ ...getFieldArgs, keyPath });\n\n    // Populate metadata for relation fields by looking up referenced entries\n    if (field?.widget === 'relation') {\n      const { collection: refCollection, file: refFile } = field;\n\n      const refEntries = (() => {\n        const cacheKey = `${refCollection}:${refFile ?? ''}`;\n        const cache = refEntriesCache.get(cacheKey);\n\n        if (cache) {\n          return cache;\n        }\n\n        // The collection’s entry list is used as is, rather than copied, so that it keeps the same\n        // identity across calls and its lookup table in `getReferencedEntryLookup()` can be reused\n        const entries = refFile\n          ? [getCollectionFileEntry(refCollection, refFile)].filter((entry) => !!entry)\n          : getEntriesByCollection(refCollection);\n\n        refEntriesCache.set(cacheKey, entries);\n\n        return entries;\n      })();\n\n      // The option values are strings, while a value written by hand may be a number, e.g. `1`\n      const refEntry = getReferencedEntryLookup(\n        refEntries,\n        locale,\n        /** @type {RelationField} */ (field),\n      ).get(String(value));\n\n      const defaultLocale = getCollection(refCollection)?._i18n.defaultLocale;\n\n      // Fall back to the referenced collection’s default locale, then `_default` (no i18n), the\n      // same way the field’s options are looked up\n      const flatContent = (\n        refEntry?.locales[locale] ??\n        (defaultLocale ? refEntry?.locales[defaultLocale] : undefined) ??\n        refEntry?.locales._default\n      )?.content;\n\n      // The referenced entry’s data is nested like that of the entry itself, as in Netlify/Decap\n      // CMS, so a subfield is read with `getIn(['author', 'authors', 'jane', 'name', 'first'])`\n      const content = flatContent ? unflattenMap(flatContent) : undefined;\n      const metaDataPath = getMetaDataPath({ getFieldArgs, keyPath });\n\n      // The legacy key drops a trailing index, but not a numeric subfield name, which the metadata\n      // path keeps\n      const legacyKey =\n        metaDataPath.at(-1) === key.split('.').at(-1)\n          ? key\n          : key.replace(ITEM_INDEX_SUFFIX_REGEX, '');\n\n      // Keep the legacy key unless it’s the same as the metadata path, as for a top-level field. It\n      // differs for a nested field, e.g. `books.0.author`, and for the single subfield of a List\n      // field, e.g. `tags`, whose metadata path is `['tags', 'tag']`\n      const paths =\n        metaDataPath.length === 1 && metaDataPath[0] === legacyKey\n          ? [metaDataPath]\n          : [metaDataPath, [legacyKey]];\n\n      if (paths.length > 1) {\n        // A field name can’t contain a dot, so a key with one is always a flat key path. Otherwise\n        // it’s the List field’s own name, under which the single subfield’s name is the current\n        // path, even if the subfield is named after the collection\n        if (legacyKey.includes('.')) {\n          legacyKeys.add(legacyKey);\n        } else if (metaDataPath[1] !== refCollection) {\n          getOrCreate(legacyListKeys, legacyKey, () => new Set()).add(refCollection);\n        }\n      }\n\n      paths.forEach((path) => {\n        const fieldMetaData = [...path, refCollection].reduce((parent, name) => {\n          parent[name] ??= Object.create(null);\n\n          return parent[name];\n        }, metaData);\n\n        fieldMetaData[value] = content;\n      });\n    }\n  });\n\n  const metaDataMap = /** @type {MapOf<any>} */ (getImmutable().fromJS(metaData));\n\n  // Without any key to watch, leave the Map alone: an empty one is Immutable.js’s shared instance\n  if (legacyKeys.size) {\n    warnOnRead(metaDataMap, legacyKeys);\n  }\n\n  legacyListKeys.forEach((keys, name) => {\n    warnOnRead(/** @type {any} */ (metaDataMap).get(name), keys);\n  });\n\n  return metaDataMap;\n};\n\n/**\n * Build a synthetic entry object with current values for live preview updates. The internal\n * properties the editor adds to list items, like `__sc_item_id`, are left out, as they’re not part\n * of the content.\n * @param {object} args Arguments.\n * @param {Entry | undefined} args.originalEntry The original entry object.\n * @param {Record<InternalLocaleCode, FlattenedEntryContent>} args.currentValues Object with locale\n * keys mapping to current content values.\n * @returns {Entry} A new entry object with updated locale content while preserving original slugs\n * and paths.\n */\nexport const buildEntry = ({ originalEntry, currentValues }) =>\n  /** @type {Entry} */ ({\n    ...originalEntry,\n    locales: Object.fromEntries(\n      Object.entries(currentValues).map(([locale, content]) => [\n        locale,\n        {\n          slug: originalEntry?.locales[locale]?.slug ?? originalEntry?.slug,\n          path: originalEntry?.locales[locale]?.path ?? originalEntry?.subPath,\n          content: filterRealValues(content),\n        },\n      ]),\n    ),\n  });\n\n/**\n * Cache of {@link getAssociatedPreviewAssets} results, keyed by the asset folder and dropped when\n * `allAssets` is replaced. The preview data is rebuilt whenever the entry draft is updated, so\n * without it every keystroke would walk the whole asset library.\n */\nconst getPreviewAssetCache = memoizeOnSource(\n  () => allAssets.current,\n  () => /** @type {WeakMap<AssetFolderInfo, Asset[]>} */ (new WeakMap()),\n);\n\n/**\n * Get assets associated with a collection or entry folder.\n * @param {object} args Arguments.\n * @param {string} [args.collectionName] Collection name.\n * @param {string} [args.fileName] File name.\n * @returns {Asset[]} Assets filtered to the relevant folder.\n */\nexport const getAssociatedPreviewAssets = ({ collectionName, fileName }) => {\n  const assetFolder = getAssetFolder({ collectionName, fileName });\n\n  if (!assetFolder) {\n    return [];\n  }\n\n  return getOrCreate(getPreviewAssetCache(), assetFolder, () =>\n    allAssets.current.filter((asset) => isAssetInFolder(asset, assetFolder)),\n  );\n};\n\n/**\n * Build shared preview data used by both preview templates and custom field types.\n *\n * {@link PreviewData.fieldsMetaData} is computed only when it’s read, and the result is kept for\n * subsequent reads. Building it walks every value in the entry and scans the referenced collection\n * for each Relation field value, while a custom field control only needs\n * {@link PreviewData.entryMap}. Given that the data is rebuilt whenever the draft is updated, doing\n * that work upfront would cost a collection scan on every keystroke.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft being previewed.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @returns {PreviewData} Object containing computed preview data.\n */\nexport const buildPreviewData = ({ draft, locale }) => {\n  const { collectionName, fileName, isIndexFile, originalEntry, currentValues, files } = draft;\n  const entry = buildEntry({ originalEntry, currentValues });\n  /* v8 ignore next */\n  const valueMap = entry.locales[locale].content ?? {};\n  /** @type {Omit<GetFieldArgs, 'keyPath'>} */\n  const getFieldArgs = { collectionName, fileName, valueMap, isIndexFile };\n  /** @type {MapOf<any> | undefined} */\n  let fieldsMetaData;\n\n  return {\n    entryMap: convertEntryToMap({\n      entry,\n      locale,\n      collectionName,\n      associatedAssets: getAssociatedPreviewAssets({ collectionName, fileName }),\n      content: valueMap,\n    }),\n    valueMap,\n    getFieldArgs,\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    get fieldsMetaData() {\n      fieldsMetaData ??= getMetaData({ locale, getFieldArgs });\n\n      return fieldsMetaData;\n    },\n    getAsset: createGetAsset({ entry, collectionName, fileName, files, locale }),\n  };\n};\n","import { unique } from '@sveltia/utils/array';\nimport { getPathInfo } from '@sveltia/utils/file';\nimport { escapeRegExp } from '@sveltia/utils/string';\n\nimport { getAssetByPath, isRelativePath } from '$lib/services/assets';\nimport { getOwnedEntryFolderPath } from '$lib/services/assets/entry-folder';\nimport { getAssetFolder, getAssetFoldersByPath } from '$lib/services/assets/folders';\nimport { revokeBlobURLIfNeeded } from '$lib/services/assets/info';\nimport { canCreateThumbnail } from '$lib/services/assets/kinds';\nimport { getMediaFieldSource, getMediaFieldURL } from '$lib/services/assets/media-field';\nimport { findEntriesByAssets } from '$lib/services/assets/references';\nimport { allAssets } from '$lib/services/assets/state';\nimport { allEntries } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { fillEntryPathTemplate } from '$lib/services/contents/entry';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getEntryDisplayLocale } from '$lib/services/contents/entry/paths';\nimport { MEDIA_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getOrCreate, memoizeOnSource } from '$lib/services/utils/cache';\nimport { getEntryAssetVersion } from '$lib/services/workflow/assets';\n\n/**\n * @import { Asset, Entry, InternalCollection, InternalEntryCollection } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Cache of the regular expressions matching a wildcard thumbnail field name, keyed by the name.\n * The entry list asks for a thumbnail once per row, so the pattern is compiled once per collection\n * rather than once per entry.\n * @type {Map<string, RegExp>}\n */\nconst thumbnailFieldRegexCache = new Map();\n\n/**\n * A field value or filled file path to look for an entry thumbnail.\n * @typedef {object} ThumbnailCandidate\n * @property {any} value Field value or file path.\n * @property {FieldKeyPath} [keyPath] Field key path. Not available for a file path.\n */\n\n/**\n * Check if the given `thumbnail` option item is a path template rather than a field key path.\n * @param {string} name Field key path or path template.\n * @returns {boolean} Result.\n */\nexport const isThumbnailPath = (name) => name.startsWith('/');\n\n/**\n * An entry’s thumbnail.\n * @typedef {object} EntryThumbnail\n * @property {string} src Image URL.\n * @property {boolean} owned Whether `src` is an object URL created for this thumbnail alone, which\n * the caller has to release once it’s no longer displayed. A URL found in a field value or the\n * asset’s public URL is not.\n */\n\n/**\n * Get the given entry’s thumbnail.\n * @param {InternalEntryCollection} collection Entry’s collection.\n * @param {Entry} entry Entry.\n * @returns {Promise<EntryThumbnail | undefined>} Thumbnail. Use {@link loadEntryThumbnail} to\n * display it, which releases the object URL for you.\n */\nexport const getEntryThumbnail = async (collection, entry) => {\n  const {\n    name: collectionName,\n    fields = [],\n    preview_path_date_field: dateFieldName,\n    _i18n: { defaultLocale },\n    _thumbnailFieldNames,\n  } = collection;\n\n  const { locales } = entry;\n  const locale = /** @type {string} */ (getEntryDisplayLocale(locales, defaultLocale));\n  const { content, slug, path: entryFilePath } = locales[locale] ?? {};\n\n  if (!content) {\n    return undefined;\n  }\n\n  const contentKeys = _thumbnailFieldNames.some((name) => name.includes('*'))\n    ? Object.keys(content)\n    : undefined;\n\n  /** @type {ThumbnailCandidate[]} */\n  const candidates = _thumbnailFieldNames.flatMap((name) => {\n    // Fill in a path template like `/images/{{slug}}.webp`, which works like a field value\n    if (isThumbnailPath(name)) {\n      const value = fillEntryPathTemplate({\n        pathTemplate: name,\n        dateFieldName,\n        fields,\n        collection,\n        locale,\n        slug,\n        entryFilePath,\n        content,\n        isIndexFile: isCollectionIndexFile(collection, entry),\n      });\n\n      return /** @type {ThumbnailCandidate[]} */ ([{ value }]);\n    }\n\n    // Support wildcards in the key path, e.g. `images.*.src` or `sections.*.images.*`\n    if (name.includes('*')) {\n      const regex = getOrCreate(\n        thumbnailFieldRegexCache,\n        name,\n        () => new RegExp(`^${escapeRegExp(name).replaceAll('\\\\*', '.+')}$`),\n      );\n\n      return /** @type {string[]} */ (contentKeys)\n        .filter((keyPath) => regex.test(keyPath))\n        .map((keyPath) => ({ value: content[keyPath], keyPath }));\n    }\n\n    return [{ value: content[name], keyPath: name }];\n  });\n\n  // Cannot use `Promise.all` or `Promise.any` here because we need the first available URL\n  // eslint-disable-next-line no-restricted-syntax\n  for (const { value, keyPath } of candidates) {\n    const args = { value, entry, collectionName, typedKeyPath: keyPath, locale };\n    const { asset } = (value && getMediaFieldSource(args)) || {};\n\n    // Skip a file without a thumbnail, like a document, rather than show it as a broken image, and\n    // try the next candidate instead\n    const src =\n      value && (!asset || canCreateThumbnail(asset))\n        ? // eslint-disable-next-line no-await-in-loop\n          await getMediaFieldURL({ ...args, thumbnail: true })\n        : undefined;\n\n    if (src) {\n      // For an asset, `getMediaFieldURL()` returns either a thumbnail object URL of its own, or the\n      // asset’s public URL. For anything else, it returns the field value as is\n      return { src, owned: !!asset && src.startsWith('blob:') };\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Load the given entry’s thumbnail for display, and release it once it’s no longer needed. Every\n * thumbnail comes with an object URL of its own, so an entry list that renders its rows again, or\n * is left, would otherwise keep a thumbnail in memory for each time it was shown. Call it from an\n * effect and return the result, so the thumbnail is released when the effect reruns or is\n * destroyed. Releasing doesn’t call back, so the caller stops showing the thumbnail by other means,\n * e.g. by keeping the entry it was loaded for alongside it; the revocation waits until no element\n * displays the URL.\n * @param {InternalEntryCollection} collection Entry’s collection.\n * @param {Entry} entry Entry.\n * @param {(src: string) => void} onLoad Function called with the thumbnail URL once it’s loaded.\n * It’s not called for an entry without a thumbnail, or when the thumbnail can’t be loaded.\n * @returns {() => void} Function to release the thumbnail.\n */\nexport const loadEntryThumbnail = (collection, entry, onLoad) => {\n  let released = false;\n  /** @type {EntryThumbnail | undefined} */\n  let thumbnail;\n\n  getEntryThumbnail(collection, entry).then(\n    (result) => {\n      if (released) {\n        // Nothing displays a thumbnail that arrives too late, so let it go right away\n        if (result?.owned) {\n          revokeBlobURLIfNeeded(result.src);\n        }\n\n        return;\n      }\n\n      thumbnail = result;\n\n      if (result) {\n        onLoad(result.src);\n      }\n    },\n    () => {\n      // A missing or undecodable image just leaves the entry without a thumbnail\n    },\n  );\n\n  return () => {\n    released = true;\n\n    // The revocation waits for the next frame and skips a URL an element still displays, so an\n    // image being removed along with the row doesn’t lose its source midway\n    if (thumbnail?.owned) {\n      revokeBlobURLIfNeeded(thumbnail.src);\n    }\n  };\n};\n\n/**\n * Cache of {@link getEntryIdsByFolder} results, keyed by a collection’s entry list, which keeps its\n * identity until the entries change.\n * @type {WeakMap<Entry[], Map<string, Set<string>>>}\n */\nconst entryIdsByFolderCache = new WeakMap();\n\n/**\n * Index the entries of the given collection by the folders their files are stored in.\n * @param {string} collectionName Collection name.\n * @returns {Map<string, Set<string>>} IDs of the entries with a file in each folder.\n */\nconst getEntryIdsByFolder = (collectionName) => {\n  const entries = getEntriesByCollection(collectionName);\n\n  return getOrCreate(entryIdsByFolderCache, entries, () => {\n    /** @type {Map<string, Set<string>>} */\n    const map = new Map();\n\n    entries.forEach(({ id, locales }) => {\n      Object.values(locales).forEach(({ path }) => {\n        const dirPath = getPathInfo(path).dirname;\n\n        if (dirPath !== undefined) {\n          getOrCreate(map, dirPath, () => new Set()).add(id);\n        }\n      });\n    });\n\n    return map;\n  });\n};\n\n/**\n * An asset along with the folder it’s stored in.\n * @typedef {object} IndexedAsset\n * @property {Asset} asset Asset.\n * @property {string} dirPath Folder the asset is stored in.\n */\n\n/**\n * Index of `allAssets` by folder, rebuilt when the store is replaced. See\n * {@link getAssetsBelowFolder}.\n */\nconst getAssetsByFolder = memoizeOnSource(\n  () => allAssets.current,\n  (_allAssets) => {\n    /** @type {Map<string, IndexedAsset[]>} */\n    const map = new Map();\n\n    _allAssets.forEach((asset) => {\n      const dirPath = getPathInfo(asset.path).dirname;\n\n      if (dirPath === undefined) {\n        return;\n      }\n\n      const item = { asset, dirPath };\n\n      // Walk up to the top-level folder\n      for (let path = dirPath; ; path = path.slice(0, path.lastIndexOf('/'))) {\n        getOrCreate(map, path, () => []).push(item);\n\n        if (!path.includes('/')) {\n          break;\n        }\n      }\n    });\n\n    return map;\n  },\n);\n\n/**\n * Get the assets stored in the given folder or any of its subfolders. Every asset is indexed under\n * its own folder and each folder above it, so this is a lookup rather than a scan of the whole\n * asset library — which would otherwise be repeated for every entry being deleted at once.\n * @param {string} folderPath Folder path.\n * @returns {IndexedAsset[]} Assets, in the order of `allAssets`.\n */\nconst getAssetsBelowFolder = (folderPath) => getAssetsByFolder().get(folderPath) ?? [];\n\n/**\n * Get a folder path for each of the given entry’s locale files, leaving out a file without one.\n * @param {Entry} entry Entry.\n * @param {(path: string) => string | undefined} getFolderPath Function returning the folder path\n * for a file path.\n * @returns {string[]} Folder paths.\n */\nconst mapEntryFolderPaths = ({ locales }, getFolderPath) =>\n  Object.values(locales).flatMap(({ path }) => getFolderPath(path) ?? []);\n\n/**\n * Get the folders the given entry occupies by itself. With the `multiple_folders` and\n * `multiple_root_folders` i18n structures, each locale has a folder of its own. When entries are\n * files sharing a folder, there is none.\n * @param {InternalCollection} collection Collection the entry belongs to.\n * @param {Entry} entry Entry.\n * @returns {string[]} Folder paths.\n */\nconst getOwnedEntryFolderPaths = (collection, entry) =>\n  mapEntryFolderPaths(entry, (path) => getOwnedEntryFolderPath(collection, path));\n\n/**\n * Get the folders the given entry’s files are stored in.\n * @param {Entry} entry Entry.\n * @returns {string[]} Folder paths.\n */\nconst getEntryFolderPaths = (entry) =>\n  mapEntryFolderPaths(entry, (path) => getPathInfo(path).dirname);\n\n/**\n * Get a list of assets associated with the given entry.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry.\n * @param {string} args.collectionName Name of a collection that the entry belongs to.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {boolean} [args.relative] Whether to only collect assets stored at a relative path.\n * @returns {Asset[]} Assets.\n */\nexport const getAssociatedAssets = ({ entry, collectionName, fileName, relative = false }) => {\n  const { locales } = entry;\n  const collection = getCollection(collectionName);\n\n  if (!collection) {\n    return [];\n  }\n\n  const isIndexFile = isCollectionIndexFile(collection, entry);\n\n  const assets = /** @type {Asset[]} */ (\n    unique(\n      Object.entries(locales)\n        .flatMap(([locale, { content }]) =>\n          Object.entries(content ?? {}).map(([keyPath, value]) => {\n            if (typeof value === 'string' && (relative ? isRelativePath(value) : true)) {\n              const widget =\n                getField({ collectionName, fileName, keyPath, isIndexFile })?.widget ?? 'string';\n\n              if (!MEDIA_FIELD_TYPES.includes(widget)) {\n                return undefined;\n              }\n\n              const asset = getAssetByPath({ value, entry, collectionName, fileName, locale });\n\n              if (\n                asset &&\n                getAssetFoldersByPath(asset.path).some(\n                  (f) =>\n                    f.collectionName === collectionName &&\n                    f.fileName === fileName &&\n                    (relative ? f.entryRelative : true),\n                )\n              ) {\n                return asset;\n              }\n            }\n\n            return undefined;\n          }),\n        )\n        .filter(Boolean),\n    )\n  );\n\n  // Add orphaned/unused entry-relative assets\n  if (relative && getAssetFolder({ collectionName, fileName })?.entryRelative) {\n    // With the `multiple_folders` and `multiple_root_folders` i18n structures, each locale has a\n    // folder of its own, so the entry’s assets are spread across all of them. Only a folder the\n    // entry occupies by itself counts: when entries are files sharing a folder, the other files in\n    // it can belong to any of them, so none of those is this entry’s to move or delete\n    const entryFolderPaths = new Set(getOwnedEntryFolderPaths(collection, entry));\n    const existingPaths = new Set(assets.map(({ path }) => path));\n    const entryIdsByFolder = getEntryIdsByFolder(collectionName);\n\n    entryFolderPaths.forEach((entryFolderPath) => {\n      /**\n       * Check whether the given folder belongs to an entry stored below this one, which owns the\n       * files in it. In a collection with nested entries, an entry can have others stored beneath\n       * it, and each of those keeps its media in its own folder.\n       * @param {string} assetFolderPath Folder holding an asset, at or below the entry folder.\n       * @returns {boolean} Result.\n       */\n      const isDescendantEntryFolder = (assetFolderPath) => {\n        // The entry folder is always an ancestor here, so there’s a slash to walk back to\n        let dirPath = assetFolderPath;\n\n        while (dirPath.length > entryFolderPath.length) {\n          const entryIds = entryIdsByFolder.get(dirPath);\n\n          // A set in the index is never empty, so it holds another entry unless it holds just this\n          if (entryIds && (entryIds.size > 1 || !entryIds.has(entry.id))) {\n            return true;\n          }\n\n          dirPath = dirPath.slice(0, dirPath.lastIndexOf('/'));\n        }\n\n        return false;\n      };\n\n      // Include assets in the entry folder and its subfolders\n      getAssetsBelowFolder(entryFolderPath).forEach(({ asset, dirPath }) => {\n        if (!isDescendantEntryFolder(dirPath) && !existingPaths.has(asset.path)) {\n          assets.push(asset);\n          existingPaths.add(asset.path);\n        }\n      });\n    });\n  }\n\n  return assets;\n};\n\n/**\n * Get the versions of the relative assets associated with the given entry that the entry has.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry.\n * @param {string} args.collectionName Name of a collection that the entry belongs to.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @returns {Asset[]} Assets.\n */\nconst getEntryRelativeAssetVersions = ({ entry, collectionName, fileName }) =>\n  /** @type {Asset[]} */ ([\n    // Two versions of a file can map to the same asset, so the list is deduplicated again\n    ...new Set(\n      getAssociatedAssets({ entry, collectionName, fileName, relative: true })\n        .map((asset) => getEntryAssetVersion(asset, entry))\n        .filter(Boolean),\n    ),\n  ]);\n\n/**\n * Collect the assets stored outside the folders their entry occupies by itself, which another\n * entry may refer to.\n * @param {InternalCollection} collection Collection the entries belong to.\n * @param {Entry[]} entries Entries.\n * @param {Asset[][]} assetLists Assets of each entry, in the order of the entries.\n * @returns {Asset[]} Assets, deduplicated by path.\n */\nconst collectSharedAssets = (collection, entries, assetLists) => {\n  /** @type {Map<string, Asset>} */\n  const sharedAssets = new Map();\n\n  entries.forEach((entry, index) => {\n    const folderPaths = getOwnedEntryFolderPaths(collection, entry);\n\n    assetLists[index].forEach((asset) => {\n      if (!folderPaths.some((folderPath) => asset.path.startsWith(`${folderPath}/`))) {\n        sharedAssets.set(asset.path, asset);\n      }\n    });\n  });\n\n  return [...sharedAssets.values()];\n};\n\n/**\n * Find the entries referring to each of the given assets. One pass for all the assets, however many\n * entries are being deleted, over the collection and any other entry stored in the same folders as\n * the given entries, e.g. that of another collection filtering them.\n * @param {Asset[]} assets Assets.\n * @param {Entry[]} entries Entries the assets belong to.\n * @param {string} collectionName Name of a collection that the entries belong to.\n * @returns {Map<string, string[]>} IDs of the referring entries, keyed with the asset path.\n */\nconst getReferringEntryIds = (assets, entries, collectionName) => {\n  const folderPaths = new Set(entries.flatMap(getEntryFolderPaths));\n\n  const referringEntries = findEntriesByAssets(\n    assets.map((asset) => ({ asset })),\n    {\n      entries: [\n        ...new Set([\n          ...getEntriesByCollection(collectionName),\n          ...allEntries.current.filter((entry) =>\n            getEntryFolderPaths(entry).some((dirPath) => folderPaths.has(dirPath)),\n          ),\n        ]),\n      ],\n    },\n  );\n\n  return new Map(\n    assets.map((asset, index) => [asset.path, referringEntries[index].map(({ id }) => id)]),\n  );\n};\n\n/**\n * Get the assets stored alongside each of the given entries, which are removed with it. Only a\n * collection whose asset folder is entry-relative stores assets with its entries.\n *\n * An asset outside the folders an entry occupies by itself, as when the entries are files sharing a\n * folder, is left out if another entry of the collection refers to it too: a duplicated entry keeps\n * referring to the original’s files there, and would be left with broken links. That includes\n * another of the given entries, so a file shared by two entries deleted together stays behind\n * rather than being deleted with either, which the other may still need, e.g. while its deletion\n * awaits review.\n * @param {object} args Arguments.\n * @param {Entry[]} args.entries Entries.\n * @param {string} args.collectionName Name of a collection that the entries belong to.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @returns {Asset[][]} Assets of each entry, in the order of the entries, or empty lists unless the\n * collection stores them with the entries. The entries of a collection storing all of them in one\n * file share the folder of the file, and an asset there can be used by any of them, so none of the\n * assets belongs to one entry alone. Only the versions an entry has are returned: a file another\n * pull request put at the same path isn’t the entry’s to remove.\n */\nexport const getEntriesRelativeAssets = ({ entries, collectionName, fileName }) => {\n  const collection = getAssetFolder({ collectionName, fileName })?.entryRelative\n    ? getCollection(collectionName)\n    : undefined;\n\n  if (!collection || isArrayFileCollection(collection)) {\n    return entries.map(() => []);\n  }\n\n  const assetLists = entries.map((entry) =>\n    getEntryRelativeAssetVersions({ entry, collectionName, fileName }),\n  );\n\n  const sharedAssets = collectSharedAssets(collection, entries, assetLists);\n\n  if (!sharedAssets.length) {\n    return assetLists;\n  }\n\n  const referringIds = getReferringEntryIds(sharedAssets, entries, collectionName);\n\n  return assetLists.map((list, index) =>\n    list.filter((asset) =>\n      (referringIds.get(asset.path) ?? []).every((id) => id === entries[index].id),\n    ),\n  );\n};\n\n/**\n * Get the assets stored alongside the given entry, which are removed with it. See\n * {@link getEntriesRelativeAssets} for which ones.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry.\n * @param {string} args.collectionName Name of a collection that the entry belongs to.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @returns {Asset[]} Assets, or an empty list unless the collection stores them with the entry.\n */\nexport const getEntryRelativeAssets = ({ entry, collectionName, fileName }) =>\n  getEntriesRelativeAssets({ entries: [entry], collectionName, fileName })[0];\n","import { isObject } from '@sveltia/utils/object';\n\nimport { loadImmutable } from '$lib/services/api/immutable';\nimport { createEntryMap } from '$lib/services/api/preview-data';\nimport { eventHookRegistry } from '$lib/services/api/registries';\nimport { getAssociatedAssets } from '$lib/services/contents/entry/assets';\nimport { getEntryDisplayLocale, getEntryLocaleFile } from '$lib/services/contents/entry/paths';\nimport { user } from '$lib/services/user/account.svelte';\nimport { flattenKeys } from '$lib/services/utils/object';\n\n/**\n * @import {\n * Entry,\n * InternalCollection,\n * InternalCollectionFile,\n * LocalizedEntry,\n * User,\n * } from '$lib/types/private';\n * @import { AppEventType } from '$lib/types/public';\n */\n\n/**\n * Supported event hooks.\n * @type {AppEventType[]}\n */\nexport const SUPPORTED_EVENT_TYPES = [\n  'preSave',\n  'postSave',\n  'prePublish',\n  'postPublish',\n  'preUnpublish',\n  'postUnpublish',\n];\n\n/**\n * Event types whose handler can return updated entry data, which is then written to the file.\n *\n * `prePublish` is deliberately absent: by the time an Editorial Workflow entry is published, its\n * content has already been committed to the pull request branch, and publishing only merges that\n * branch. Applying an update here would change the in-memory entry without changing the file,\n * leaving the two out of sync. Supporting it means re-serializing the entry and committing it to\n * the branch before the merge.\n * @type {AppEventType[]}\n */\nexport const UPDATABLE_EVENT_TYPES = ['preSave'];\n\n/**\n * Call the registered event hooks.\n * @param {object} args Arguments.\n * @param {AppEventType} args.type Type of event.\n * @param {Entry} args.entry Entry the event is about. This object may be mutated by the hook when\n * the event type is in {@link UPDATABLE_EVENT_TYPES}.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only.\n * @param {boolean} [args.isNew] Whether the entry is being created rather than updated.\n * @throws {Error} When a `pre*` hook throws, which stops the operation. An error thrown by a\n * `post*` hook is only logged, as the operation has already been carried out by then.\n */\nexport const callEventHooks = async ({\n  type,\n  entry,\n  collection,\n  collectionFile,\n  isNew = false,\n}) => {\n  const { login: _login, name: _name } = /** @type {User} */ (user.account);\n  // Not destructuring defaults, which only replace `undefined`: a GitHub user without a display\n  // name has a `null` name\n  const login = _login ?? '';\n  const name = _name ?? '';\n  const collectionName = collection.name;\n  const fileName = collectionFile?.name;\n\n  const {\n    _i18n: { defaultLocale },\n  } = collectionFile ?? collection;\n\n  const hooks = [...eventHookRegistry].filter((hook) => hook.name === type);\n\n  if (!hooks.length) {\n    return;\n  }\n\n  /** @type {import('immutable')['isMap']} */\n  let isMap;\n\n  // The hooks receive the entry as an Immutable Map. Saving must not depend on the library being\n  // reachable, so if it can’t be loaded, the hooks are skipped rather than the operation failing —\n  // possibly after the commit has already been made, in the case of a `post*` event\n  try {\n    ({ isMap } = await loadImmutable());\n  } catch (error) {\n    // eslint-disable-next-line no-console\n    console.error(`Skipping the ${type} event hooks: Immutable.js could not be loaded`, error);\n\n    return;\n  }\n\n  const { slug, locales } = entry;\n  // A multi-file i18n entry can be missing its default locale file, in which case another locale\n  // stands in for it: the hooks get its data as the main data, which is written back to it, so it’s\n  // not one of the other locales\n  const mainLocale = /** @type {string} */ (getEntryDisplayLocale(locales, defaultLocale));\n  const otherLocales = Object.keys(locales).filter((locale) => locale !== mainLocale);\n  const associatedAssets = getAssociatedAssets({ entry, collectionName, fileName });\n\n  // We need to use a for loop here to call handlers sequentially\n  // eslint-disable-next-line no-restricted-syntax\n  for (const hook of hooks) {\n    // Read the content on every iteration, so a hook sees the changes made by the previous ones. An\n    // entry without any locale file gets empty data rather than the destructuring throwing\n    const { content, path } = /** @type {LocalizedEntry} */ (\n      getEntryLocaleFile(entry, { locale: mainLocale }) ?? {}\n    );\n\n    let updatedMap;\n\n    try {\n      // eslint-disable-next-line no-await-in-loop\n      updatedMap = await hook.handler({\n        author: { login, name },\n        // Create an Immutable.js Map representing the entry data with deep conversion\n        entry: createEntryMap({\n          content,\n          otherLocales,\n          locales,\n          slug,\n          path,\n          isNew,\n          collectionName,\n          associatedAssets,\n        }),\n      });\n    } catch (error) {\n      // A `pre*` hook can stop the operation by throwing, but a `post*` hook runs once the change\n      // has been made, so its failure can’t undo it. Report the error and carry on with the next\n      // hook, rather than making a successful save or publish look like it failed. No `post*` hook\n      // can update the entry, so there’s nothing more to do with this one\n      if (!type.startsWith('post')) {\n        throw error;\n      }\n\n      // eslint-disable-next-line no-console\n      console.error(`The ${type} event hook failed`, error);\n    }\n\n    // If the hook returned an updated entry, merge its data back into the savingEntry\n    if (UPDATABLE_EVENT_TYPES.includes(type) && isMap(updatedMap)) {\n      const map = updatedMap.toJS();\n\n      if (isObject(map.data) && isObject(map.i18n)) {\n        locales[mainLocale].content = flattenKeys(map.data);\n\n        otherLocales.forEach((locale) => {\n          if (isObject(map.i18n[locale]?.data)) {\n            locales[locale].content = flattenKeys(map.i18n[locale].data);\n          }\n        });\n      } else {\n        // `map` is always a plain object here (guaranteed by `isMap(updatedMap)` above)\n        locales[mainLocale].content = flattenKeys(map);\n      }\n    }\n  }\n};\n","import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\nimport {\n  getAliasesKey,\n  getAliasKeyPaths,\n  removeAliases,\n} from '$lib/services/contents/entry/aliases';\nimport { getSitePath } from '$lib/services/contents/entry/site-path';\nimport { isValueEmpty } from '$lib/services/utils/object';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n */\n\n/**\n * Add the entry’s previous path to the `aliases` list so links to the old path keep working after\n * the slug has been edited. This only applies when the `preview_path` option is defined on the\n * collection, because that option is what allows the CMS to know the entry’s path on the live site.\n * If the property doesn’t exist yet, it’s created as a list with a single item; if it already\n * exists as a list, the previous path is appended to it. A property with any other shape, such as a\n * plain string, is left untouched so a user-defined value is never lost. The property name can be\n * customized with the `aliases_field` option, which can also be set to `false` to skip the\n * processing entirely.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FlattenedEntryContent} args.content Flattened entry content to be modified in place.\n * @param {string} args.slug New entry slug for the locale.\n * @param {string} args.path New entry file path for the locale.\n * @see https://github.com/sveltia/sveltia-cms/discussions/731\n */\nexport const addAlias = ({ draft, locale, content, slug, path }) => {\n  const { isNew, isIndexFile, collection, fields, originalEntry } = draft;\n\n  // The index file’s slug is fixed, so it can never be renamed\n  if (isNew || isIndexFile || !originalEntry) {\n    return;\n  }\n\n  const { preview_path: pathTemplate } = /** @type {InternalEntryCollection} */ (collection);\n  // This is `undefined` for anything but an entry collection, whose slugs are the only editable\n  // ones, so no further collection type check is needed below\n  const aliasesKey = getAliasesKey({ collection, fields });\n\n  if (!pathTemplate || !aliasesKey) {\n    return;\n  }\n\n  const {\n    slug: originalSlug,\n    path: originalPath,\n    content: originalContent,\n  } = originalEntry.locales[locale] ?? {};\n\n  // Nothing to do if the locale has just been enabled or the slug is unchanged\n  if (originalSlug === undefined || originalSlug === slug) {\n    return;\n  }\n\n  // Use the original content, as fields referenced by the `preview_path` template, such as a date,\n  // may have been edited along with the slug\n  const { defaultLocale } = collection._i18n;\n\n  const previousPath = getSitePath({\n    collection,\n    locale,\n    slug: originalSlug,\n    path: originalPath,\n    content: originalContent,\n    defaultContent: originalEntry.locales[defaultLocale]?.content,\n  });\n\n  const currentPath = getSitePath({\n    collection,\n    locale,\n    slug,\n    path,\n    content,\n    // A snapshot, which is replaced rather than changed as the draft is edited\n    defaultContent: getValueMapSnapshot(draft, defaultLocale),\n  });\n\n  // The `preview_path` template may not contain the slug at all, in which case the path is\n  // unchanged and an alias would just point the page at itself\n  if (previousPath === undefined || previousPath === currentPath) {\n    return;\n  }\n\n  const keyPaths = getAliasKeyPaths(content, aliasesKey);\n\n  // Leave an unsupported shape, such as a plain string, untouched\n  if (!keyPaths.length && !isValueEmpty(content[aliasesKey])) {\n    return;\n  }\n\n  const aliases = keyPaths\n    .map((keyPath) => content[keyPath])\n    .filter(isNonEmptyString)\n    // Avoid a duplicate as well as an alias pointing at the entry’s own current path, which both\n    // Hugo and Zola report as a conflict\n    .filter((alias) => alias !== previousPath && alias !== currentPath);\n\n  removeAliases(content, aliasesKey);\n\n  [...aliases, previousPath].forEach((alias, index) => {\n    content[`${aliasesKey}.${index}`] = alias;\n  });\n};\n","import { createAssetMoveChange } from '$lib/services/assets/data/move-change';\nimport { getOwnedEntryFolderPath } from '$lib/services/assets/entry-folder';\nimport { getAssetFolder } from '$lib/services/assets/folders';\nimport { allAssets } from '$lib/services/assets/state';\nimport { getEntryAssetVersion } from '$lib/services/workflow/assets';\n\n/**\n * @import { Asset, Entry, FileChange, InternalCollection } from '$lib/types/private';\n */\n\n/**\n * Work out which folders the entry has vacated, keyed by the folder it left behind. With a\n * multi-folder i18n structure each locale has a folder of its own, so there can be more than one.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {Entry} args.originalEntry Entry as it is stored now.\n * @param {Entry} args.savingEntry Same entry with its new paths.\n * @returns {Map<string, string>} Key is the old folder path, value is the new one.\n */\nexport const getMovedFolders = ({ collection, originalEntry, savingEntry }) => {\n  /** @type {Map<string, string>} */\n  const movedFolders = new Map();\n\n  Object.entries(savingEntry.locales).forEach(([locale, { path }]) => {\n    const previousPath = originalEntry.locales[locale]?.path;\n\n    if (!previousPath) {\n      return;\n    }\n\n    const oldFolderPath = getOwnedEntryFolderPath(collection, previousPath);\n    const newFolderPath = getOwnedEntryFolderPath(collection, path);\n\n    if (oldFolderPath && newFolderPath && oldFolderPath !== newFolderPath) {\n      movedFolders.set(oldFolderPath, newFolderPath);\n    }\n  });\n\n  return movedFolders;\n};\n\n/**\n * Get the path a file goes to when the folder holding it moves, along with the entry that owns the\n * folder.\n * @param {string} path File path.\n * @param {string} oldFolderPath Path of the folder being moved.\n * @param {string} newFolderPath Path the folder is moved to.\n * @returns {string | undefined} New path, or `undefined` if the file isn’t in the folder.\n */\nexport const getPathInMovedFolder = (path, oldFolderPath, newFolderPath) =>\n  path.startsWith(`${oldFolderPath}/`)\n    ? `${newFolderPath}${path.slice(oldFolderPath.length)}`\n    : undefined;\n\n/**\n * Build the file changes that take an entry’s relative assets along when the entry itself is filed\n * elsewhere. With a Hugo-style page bundle — a `path` option like `{{slug}}/_index` combined with a\n * relative `media_folder` — the assets are stored in the entry’s own folder, so moving the entry\n * with the path editor or renaming its slug has to move them too, or the entry would be left\n * pointing at files that stayed behind.\n *\n * Everything below the old folder is taken, including the assets of any descendant entry the\n * `subfolders` mode moves along with this one, as well as files in a subfolder of its own.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {Entry} [args.originalEntry] Entry as it was before the save. `undefined` for a new entry,\n * which has nothing to move.\n * @param {Entry} args.savingEntry Entry being saved.\n * @param {FileChange[]} args.changes Changes collected so far, which are left untouched. An asset\n * the save already writes to the entry’s new folder wins over the one being moved there.\n * @returns {Promise<{ changes: FileChange[], savingAssets: Asset[] }>} Collected changes and the\n * assets to be saved.\n */\nexport const buildEntryAssetMoveChanges = async ({\n  collection,\n  fileName,\n  originalEntry,\n  savingEntry,\n  changes,\n}) => {\n  /** @type {{ changes: FileChange[], savingAssets: Asset[] }} */\n  const noChanges = { changes: [], savingAssets: [] };\n\n  // Assets are only bound to an entry when the collection stores them at a relative path\n  if (\n    !originalEntry ||\n    !getAssetFolder({ collectionName: collection.name, fileName })?.entryRelative\n  ) {\n    return noChanges;\n  }\n\n  const movedFolders = getMovedFolders({ collection, originalEntry, savingEntry });\n\n  if (!movedFolders.size) {\n    return noChanges;\n  }\n\n  const takenPaths = new Set(changes.map(({ path }) => path));\n\n  // Only the versions of the assets this entry has: another pull request’s file isn’t moved along\n  const assets = /** @type {Asset[]} */ (\n    allAssets.current.map((asset) => getEntryAssetVersion(asset, originalEntry)).filter(Boolean)\n  );\n\n  /** @type {FileChange[]} */\n  const moveChanges = [];\n  /** @type {Asset[]} */\n  const savingAssets = [];\n\n  await Promise.all(\n    [...movedFolders].map(async ([oldFolderPath, newFolderPath]) =>\n      Promise.all(\n        assets.map(async (asset) => {\n          const path = getPathInMovedFolder(asset.path, oldFolderPath, newFolderPath);\n\n          if (path === undefined) {\n            return;\n          }\n\n          // The destination is already being written in this save, typically because the user\n          // replaced the file while moving the entry. Drop the stale copy rather than overwriting\n          // the new one with it\n          if (takenPaths.has(path)) {\n            moveChanges.push({ action: 'delete', path: asset.path, previousSha: asset.sha });\n\n            return;\n          }\n\n          moveChanges.push(await createAssetMoveChange(asset, path));\n          savingAssets.push({ ...asset, path });\n        }),\n      ),\n    ),\n  );\n\n  return { changes: moveChanges, savingAssets };\n};\n","import { getExistingEntryAssetFolderPath } from '$lib/services/assets/entry-folder';\nimport { getAssetFolder } from '$lib/services/assets/folders';\nimport { getAssetPublicURL } from '$lib/services/assets/info';\nimport { getEntriesByAssets } from '$lib/services/assets/references';\nimport { allAssets } from '$lib/services/assets/state';\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport {\n  getMovedFolders,\n  getPathInMovedFolder,\n} from '$lib/services/contents/draft/save/asset-move';\nimport { getBaseName } from '$lib/services/utils/file';\nimport { getEntryAssetVersion } from '$lib/services/workflow/assets';\n\n/**\n * @import {\n * Asset,\n * Entry,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalLocaleCode,\n * LocalizedEntry,\n * } from '$lib/types/private';\n * @import { AssetReferenceTarget } from '$lib/services/assets/references';\n */\n\n/**\n * Get the path an asset goes to when the folder holding it moves along with the entry, as\n * `buildEntryAssetMoveChanges()` moves it.\n * @param {string} path Asset path.\n * @param {Map<string, string>} movedFolders Moved folders, from `getMovedFolders()`.\n * @returns {string} New path, or the same path if the asset stays where it is.\n */\nconst getMovedAssetPath = (path, movedFolders) =>\n  [...movedFolders]\n    .map(([oldFolderPath, newFolderPath]) =>\n      getPathInMovedFolder(path, oldFolderPath, newFolderPath),\n    )\n    .find((movedPath) => movedPath !== undefined) ?? path;\n\n/**\n * Get the targets rewriting the absolute references to an entry’s relative assets in a locale,\n * whose public path is about to change, e.g. from `/blog/hello/images/photo.jpg` to\n * `/blog/hello-world/images/photo.jpg` once the slug filling the `public_folder` template has been\n * renamed. The references are matched by their old URL as is, so a relative reference, or one to\n * another entry’s asset, is left alone.\n * @param {object} args Arguments.\n * @param {Map<string, string>} args.movedFolders Folders the entry is leaving, see\n * `getMovedFolders()`.\n * @param {string} args.collectionName Collection name.\n * @param {Entry} args.originalEntry Entry as it is stored now.\n * @param {Entry} args.savingEntry Same entry as it’s being saved.\n * @param {InternalLocaleCode} args.locale Locale whose entry file the assets are stored beside.\n * @returns {AssetReferenceTarget[]} Targets, each with the old URL and the new one.\n */\nconst getLocaleTargets = ({ movedFolders, collectionName, originalEntry, savingEntry, locale }) => {\n  const folderPath = getExistingEntryAssetFolderPath({\n    entry: originalEntry,\n    locale,\n    collectionName,\n  });\n\n  const prefix = folderPath ? `${folderPath}/` : '';\n\n  // Only the versions of the assets this entry has, as in `buildEntryAssetMoveChanges()`. Those\n  // outside the entry’s folder are left out first, so the asset list isn’t mapped on every save\n  const assets = /** @type {Asset[]} */ (\n    allAssets.current\n      .filter(({ path }) => path.startsWith(prefix))\n      .map((asset) => getEntryAssetVersion(asset, originalEntry))\n      .filter(Boolean)\n  );\n\n  return assets.flatMap((asset) => {\n    const url = getAssetPublicURL(asset, { pathOnly: true, entry: originalEntry, locale });\n\n    // A relative reference stays the same wherever the entry goes\n    if (!url?.startsWith('/')) {\n      return [];\n    }\n\n    const path = getMovedAssetPath(asset.path, movedFolders);\n\n    const newURL = getAssetPublicURL(\n      { ...asset, path, name: getBaseName(path) },\n      { pathOnly: true, entry: savingEntry, locale },\n    );\n\n    return newURL && newURL !== url ? [{ url, newURL }] : [];\n  });\n};\n\n/**\n * Rewrite the references in an entry being saved to its own relative assets, when they are referred\n * to with an absolute public path filled with the entry’s values, e.g. `/blog/{{slug}}/images`,\n * which changes when the slug is renamed or the entry is moved, e.g. with `{{dirname}}`. The\n * references would otherwise keep the old path, which no longer leads to the assets, whether or not\n * they have moved to the entry’s new folder along with it. The references are rewritten in each\n * locale with the paths of that locale, as well as the default locale’s, which a field holding the\n * same value in every locale refers to, the same way they are written when a file is uploaded; see\n * `replaceBlobURLs()` in `changes.js`. Every field that can hold an asset reference is covered, the\n * same as when an asset is renamed or moved; see `getEntriesByAssets()`.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s special index file.\n * @param {Entry} [args.originalEntry] Entry as it was before the save. `undefined` for a new entry,\n * which has no references to rewrite yet.\n * @param {Entry} args.savingEntry Entry being saved. It’s left untouched.\n * @returns {Promise<Entry>} The entry with its references rewritten in a copy of the content of\n * each locale holding any of them, or the given entry if there’s nothing to rewrite.\n */\nexport const rewriteEntryAssetReferences = async ({\n  collection,\n  collectionFile,\n  isIndexFile,\n  originalEntry,\n  savingEntry,\n}) => {\n  const { name: collectionName } = collection;\n  const folder = getAssetFolder({ collectionName, fileName: collectionFile?.name, isIndexFile });\n  const publicPath = folder?.publicPath;\n\n  // Only an absolute public path with template tags changes along with the entry; a relative one\n  // is resolved against wherever the entry is\n  if (\n    !originalEntry ||\n    !folder?.entryRelative ||\n    !publicPath?.startsWith('/') ||\n    !hasTemplateTags(publicPath)\n  ) {\n    return savingEntry;\n  }\n\n  const movedFolders = getMovedFolders({ collection, originalEntry, savingEntry });\n  const { defaultLocale } = (collectionFile ?? collection)._i18n;\n  /** @type {Map<InternalLocaleCode, AssetReferenceTarget[]>} */\n  const targetCache = new Map();\n\n  /**\n   * Get the targets of a locale, worked out once.\n   * @param {InternalLocaleCode} locale Locale.\n   * @returns {AssetReferenceTarget[]} Targets.\n   */\n  const getTargets = (locale) => {\n    let targets = targetCache.get(locale);\n\n    if (!targets) {\n      targets = originalEntry.locales[locale]\n        ? getLocaleTargets({\n            movedFolders,\n            collectionName,\n            originalEntry,\n            savingEntry,\n            locale,\n          })\n        : [];\n      targetCache.set(locale, targets);\n    }\n\n    return targets;\n  };\n\n  /** @type {[InternalLocaleCode, LocalizedEntry][]} */\n  const locales = await Promise.all(\n    Object.entries(savingEntry.locales).map(async ([locale, localizedEntry]) => {\n      const targets = localizedEntry.content\n        ? [\n            ...getTargets(locale),\n            // A file in a field holding the same value in every locale is stored beside the\n            // default locale’s entry file\n            ...(locale === defaultLocale ? [] : getTargets(defaultLocale)),\n          ]\n        : [];\n\n      if (!targets.length) {\n        return [locale, localizedEntry];\n      }\n\n      // The content is copied, as it can be shared with the entry in the store\n      const content = { ...localizedEntry.content };\n\n      // Searched as an entry with this locale only, so the references are rewritten with the paths\n      // of this locale. The references are replaced in place, in the copy\n      await getEntriesByAssets(targets, {\n        entries: [{ ...savingEntry, locales: { [locale]: { ...localizedEntry, content } } }],\n      });\n\n      return [locale, { ...localizedEntry, content }];\n    }),\n  );\n\n  return locales.every(([locale, localizedEntry]) => localizedEntry === savingEntry.locales[locale])\n    ? savingEntry\n    : { ...savingEntry, locales: Object.fromEntries(locales) };\n};\n","import { getDateTimeParts } from '@sveltia/utils/datetime';\nimport { getPathInfo } from '@sveltia/utils/file';\n\nimport { formatFileName } from '$lib/services/assets/file-name';\nimport { getSlugTimeZone } from '$lib/services/common/slug';\nimport { replaceTemplatePlaceholder } from '$lib/services/common/template/replacers';\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { getIdentifierFieldName } from '$lib/services/contents/collection/identifier';\n\n/**\n * @import { ReplaceContext } from '$lib/services/common/template/replacers';\n * @import {\n * AssetNameTemplate,\n * EntryDraft,\n * EntryFileItem,\n * FlattenedEntryContent,\n * InternalCollection,\n * } from '$lib/types/private';\n */\n\n/**\n * Entry values a `filename_template` is filled with.\n * @typedef {object} AssetNameContext\n * @property {InternalCollection} [collection] Collection of the entry the file is added to.\n * @property {string} [collectionFileName] Collection file name. File/singleton collection only.\n * @property {FlattenedEntryContent} [content] Content of the entry in the default locale.\n * @property {string} [slug] Slug of the entry in the default locale.\n * @property {boolean} [isIndexFile] Whether the entry is the collection’s special index file.\n */\n\n/**\n * Create a template to name an uploaded file with, capturing the current date and time so the name\n * doesn’t change between the one shown while editing and the one saved.\n * @param {string} template The `filename_template` media library option.\n * @param {object} [options] Options.\n * @param {boolean} [options.slugificationEnabled] Whether the filled name is slugified, according\n * to the `slugify_filename` media library option.\n * @returns {AssetNameTemplate} Template.\n */\nexport const createAssetNameTemplate = (template, { slugificationEnabled = false } = {}) => ({\n  template,\n  slugificationEnabled,\n  randomValues: new Map(),\n  dateTimeParts: getDateTimeParts({ timeZone: getSlugTimeZone() }),\n});\n\n/**\n * Get the entry values a `filename_template` is filled with. They come from the default locale, so\n * a file used in several locales gets one name.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.defaultLocaleSlug Default locale’s entry slug.\n * @returns {AssetNameContext} Context.\n */\nexport const getAssetNameContext = ({ draft, defaultLocaleSlug }) => {\n  const { collection, fileName, defaultLocale, currentValues, isIndexFile } = draft;\n\n  return {\n    collection,\n    collectionFileName: fileName,\n    content: currentValues[defaultLocale],\n    slug: defaultLocaleSlug,\n    isIndexFile,\n  };\n};\n\n/**\n * Fill the `filename_template` media library option to get the name of an uploaded file. The tag\n * values are slugified like in an entry slug template, and the original extension is appended.\n * @param {AssetNameContext & { nameTemplate: AssetNameTemplate, originalName: string }} args\n * Arguments: the template, the original file name, which `{{filename}}` and `{{extension}}` stand\n * for, and the entry values.\n * @returns {string} File name.\n */\nexport const fillAssetNameTemplate = ({\n  nameTemplate: { template, randomValues, dateTimeParts },\n  originalName,\n  collection,\n  collectionFileName,\n  content = {},\n  slug,\n  isIndexFile = false,\n}) => {\n  const { extension } = getPathInfo(originalName);\n\n  const identifierField = getIdentifierFieldName(\n    collection?._type === 'entry' ? collection : undefined,\n  );\n\n  /** @type {ReplaceContext} */\n  const context = {\n    replaceSubContext: {\n      collection: /** @type {InternalCollection} */ (collection),\n      content,\n      currentSlug: slug,\n      dateTimeParts,\n      randomValues,\n      assetFileName: originalName,\n      identifierField,\n      basePath: undefined,\n    },\n    getFieldArgs: {\n      collectionName: collection?.name ?? '',\n      fileName: collectionFileName,\n      keyPath: '',\n      valueMap: content,\n      isIndexFile,\n    },\n  };\n\n  const name = replaceTemplateTags(template, (_match, tag) =>\n    replaceTemplatePlaceholder(tag, context),\n  ).trim();\n\n  return extension ? `${name}.${extension}` : name;\n};\n\n/**\n * Get the name a file pending upload in an entry draft is saved with, before it’s made unique in\n * the target folder. It’s the file’s own name unless the `filename_template` media library option\n * applies to the file. The filled name is then sanitized, and slugified if the `slugify_filename`\n * option is enabled, like an upload in the asset library.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {EntryFileItem} args.item File pending upload.\n * @param {string} args.defaultLocaleSlug Default locale’s entry slug.\n * @returns {string} File name.\n */\nexport const getPendingFileName = ({ draft, item: { file, nameTemplate }, defaultLocaleSlug }) => {\n  if (!nameTemplate) {\n    return file.name;\n  }\n\n  const name = fillAssetNameTemplate({\n    nameTemplate,\n    originalName: file.name,\n    ...getAssetNameContext({ draft, defaultLocaleSlug }),\n  });\n\n  return formatFileName(name, { slugificationEnabled: nameTemplate.slugificationEnabled });\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { DATE_TIME_FIELDS, UUID_TYPES } from '$lib/services/common/template/constants';\nimport { getTemplateTags } from '$lib/services/common/template/tags';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { parseTransformations } from '$lib/services/common/transformations';\nimport { getIdentifierFieldName } from '$lib/services/contents/collection/identifier';\nimport { usesSingleFileStructure } from '$lib/services/contents/i18n/config';\n\n/**\n * @import {\n * InternalCollection,\n * InternalEntryCollection,\n * InternalSlugOptions,\n * } from '$lib/types/private';\n * @import {\n * Collection,\n * CollectionSlugOptions,\n * EntryCollection,\n * SlugEditableStage,\n * } from '$lib/types/public';\n */\n\n/**\n * Legacy template tag that shows the slug editor for the default locale.\n * @todo Remove the support prior to the 1.0 release.\n */\nexport const LEGACY_SLUG_EDITOR_TAG = '{{fields._slug}}';\n\n/**\n * Legacy template tag that shows the slug editor for all locales.\n * @todo Remove the support prior to the 1.0 release.\n */\nexport const LEGACY_LOCALIZED_SLUG_EDITOR_TAG = '{{fields._slug | localize}}';\n\n/**\n * Get the slug template configured for an entry collection, either as the `slug` option itself or\n * as its `template` property.\n * @param {EntryCollection} collection Entry collection.\n * @returns {string | undefined} Template, or `undefined` if not configured.\n */\nexport const getConfiguredSlugTemplate = ({ slug }) => {\n  if (typeof slug === 'string') {\n    return slug;\n  }\n\n  if (isObject(slug) && typeof slug.template === 'string') {\n    return slug.template;\n  }\n\n  return undefined;\n};\n\n/**\n * Check whether the given slug template contains one of the legacy slug editor tags.\n * @param {string | undefined} template Slug template.\n * @returns {boolean} Result.\n */\nexport const hasLegacySlugEditorTag = (template) =>\n  !!template?.includes(LEGACY_SLUG_EDITOR_TAG) ||\n  !!template?.includes(LEGACY_LOCALIZED_SLUG_EDITOR_TAG);\n\n/**\n * Get the stages at which the slug can be edited.\n * @param {CollectionSlugOptions['editable']} editable The `editable` option. Default: `true`.\n * @returns {SlugEditableStage[]} Stages.\n */\nconst getEditableStages = (editable = true) => {\n  if (typeof editable === 'boolean') {\n    return editable ? ['create', 'update'] : [];\n  }\n\n  // A value of another type is reported against the JSON schema\n  return Array.isArray(editable) ? editable : [];\n};\n\n/**\n * Get the normalized slug options of an entry collection. The `slug` option can be a template\n * string, which may contain the legacy slug editor tags, or an object with the template and the\n * slug editor options.\n * @param {Collection | InternalCollection} collection Collection. Only an entry collection has\n * slug options; for another collection, the defaults are returned.\n * @returns {InternalSlugOptions} Normalized options.\n * @see https://github.com/sveltia/sveltia-cms/issues/999\n * @see https://github.com/sveltia/sveltia-cms/issues/1072\n */\nexport const getSlugOptions = (collection) => {\n  const { slug, file } = /** @type {EntryCollection} */ (collection);\n  const identifierField = getIdentifierFieldName(/** @type {EntryCollection} */ (collection));\n  /** @type {CollectionSlugOptions} */\n  const options = isObject(slug) ? /** @type {CollectionSlugOptions} */ (slug) : {};\n  const configuredTemplate = getConfiguredSlugTemplate(/** @type {EntryCollection} */ (collection));\n  // An entry stored in a file with the other entries of the collection is told by its position, so\n  // there’s no slug to edit\n  const stages = typeof file === 'string' ? [] : getEditableStages(options.editable);\n  const update = stages.includes('update');\n\n  // A numbered slug isn’t made from a template, so a configured one is ignored, and the slug editor\n  // is prefilled with the number rather than having to be filled in. An entry stored in a file with\n  // the other entries has no slug to number\n  if (options.auto_increment === true && typeof file !== 'string') {\n    return {\n      template: '',\n      editorRequired: false,\n      editorValueIsSlug: true,\n      editable: { create: stages.includes('create'), update },\n      localized: options.i18n === true,\n      autoIncrement: true,\n      hint: options.hint,\n      pattern: options.pattern,\n    };\n  }\n\n  const legacyLocalized = !!configuredTemplate?.includes(LEGACY_LOCALIZED_SLUG_EDITOR_TAG);\n  const legacy = hasLegacySlugEditorTag(configuredTemplate);\n  const create = legacy || stages.includes('create');\n  const localized = legacyLocalized || options.i18n === true;\n\n  // The slug comes from the slug editor alone when it’s explicitly made editable on creation\n  // without a template. Otherwise, the slug editor, which is shown by default, is prefilled with\n  // the slug the template fills, which defaults to the identifier field\n  const editorOnly =\n    configuredTemplate === undefined && options.editable !== undefined && stages.includes('create');\n\n  const template =\n    configuredTemplate ??\n    (editorOnly\n      ? localized\n        ? LEGACY_LOCALIZED_SLUG_EDITOR_TAG\n        : LEGACY_SLUG_EDITOR_TAG\n      : `{{${identifierField}}}`);\n\n  const editorRequired = hasLegacySlugEditorTag(template);\n\n  return {\n    template,\n    editorRequired,\n    // A legacy template can put the slug editor’s value among other tags, e.g.\n    // `{{year}}-{{fields._slug}}`\n    editorValueIsSlug:\n      !editorRequired ||\n      [LEGACY_SLUG_EDITOR_TAG, LEGACY_LOCALIZED_SLUG_EDITOR_TAG].includes(template),\n    editable: { create, update },\n    localized,\n    autoIncrement: false,\n    hint: options.hint,\n    pattern: options.pattern,\n  };\n};\n\n/**\n * Template tags a slug template can use that don’t refer to a field, and therefore can’t be\n * localized.\n * @type {string[]}\n */\nconst NON_FIELD_TAGS = [...DATE_TIME_FIELDS, ...Object.keys(UUID_TYPES), 'slug'];\n\n/**\n * Get the key paths of the fields whose values are localized in the slug, which are the tags in the\n * slug template carrying the `localize` flag, e.g. `{{title | localize}}`. With the slug’s `i18n`\n * option enabled, every field tag in the template is localized.\n * @param {InternalEntryCollection} collection Collection.\n * @returns {string[]} Key paths. An empty array if the slug isn’t localized.\n */\nexport const getLocalizingKeyPaths = (collection) => {\n  const { template, localized } = getSlugOptions(collection);\n  /** @type {Set<string>} */\n  const keyPaths = new Set();\n\n  getTemplateTags(template).forEach(({ content: placeholder }) => {\n    // Leave out the transformations, e.g. `upper` in `{{title | upper | localize}}`. The `localize`\n    // flag can come anywhere among them; it’s a no-op when the template is filled\n    const { value, transformations } = parseTransformations(placeholder);\n    const keyPath = stripFieldTagPrefix(value);\n\n    if (transformations.some(({ method }) => method === 'localize')) {\n      keyPaths.add(keyPath);\n    } else if (localized && !NON_FIELD_TAGS.includes(keyPath)) {\n      keyPaths.add(keyPath);\n    }\n  });\n\n  return [...keyPaths];\n};\n\n/**\n * Check whether the entries in the given collection get a slug of their own for each locale, which\n * is the case when i18n is enabled with the multiple files or folders structure, and either the\n * slug’s `i18n` option is enabled or the slug template contains the `localize` flag, e.g.\n * `{{title | localize}}`.\n * @param {InternalCollection} collection Collection.\n * @returns {boolean} Result.\n * @see https://sveltiacms.app/en/docs/i18n/slugs#localizing-entry-slugs\n */\nexport const hasLocalizedSlugs = (collection) => {\n  const {\n    _i18n: { i18nEnabled, structureMap },\n  } = collection;\n\n  return (\n    // A monolingual collection has only one locale, so there’s nothing to localize\n    i18nEnabled &&\n    !usesSingleFileStructure(structureMap) &&\n    collection._type === 'entry' &&\n    (getSlugOptions(collection).localized || !!getLocalizingKeyPaths(collection).length)\n  );\n};\n","import { getPathInfo } from '@sveltia/utils/file';\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport {\n  DEFAULT_INDEX_FILE_NAMES,\n  getEntryDirPath,\n  getNestedIndexFileName,\n  hasNestedEntries,\n} from '$lib/services/contents/collection/nested';\nimport { hasLocalizedSlugs } from '$lib/services/contents/collection/slug';\nimport { getBaseName } from '$lib/services/utils/file';\nimport { mergeUnpublishedEntries, unpublishedEntries } from '$lib/services/workflow';\n\n/**\n * @import { Entry, InternalCollection, InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * Get the name of the folder an entry occupies in the given locale, in a collection where every\n * entry is an index file within a folder of its own. The folder is named after the entry’s slug,\n * so it goes by a different name in each locale when the slug is localized.\n * @param {string} subPath Entry’s sub path in the locale, e.g. `docs/guides/_index`.\n * @returns {string} Folder name, e.g. `guides`. An empty string if the entry is directly in the\n * collection folder, which is the case for the collection’s own index file.\n */\nexport const getOwnFolderName = (subPath) => getBaseName(getEntryDirPath(subPath));\n\n/**\n * Check whether the folders of a collection with nested entries go by a different name in each\n * locale. That’s the case when the entry slugs are localized: a folder is named after the entry it\n * belongs to, which is stored either in it or beside it, so the folder chain above an entry is\n * localized along with the entry itself.\n * @param {InternalCollection} collection Collection.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/962\n */\nexport const hasLocalizedFolders = (collection) =>\n  hasNestedEntries(collection) && hasLocalizedSlugs(collection);\n\n/**\n * Find the entry a folder is named after, along with the folder name it has in the given locale.\n * In the `subfolders` mode that’s the folder’s own index file; otherwise it’s the folder’s index\n * file if it has one, as named with the `meta.path.index_file` option or by convention, or else a\n * file of the same name as the folder stored beside it, which is how Eleventy, Jekyll and other\n * frameworks give a folder its page.\n * @param {object} args Arguments.\n * @param {Entry[]} args.entries Entries in the collection.\n * @param {string} args.dirPath Folder path in the default locale, relative to the collection\n * folder.\n * @param {string[]} args.indexFileNames File names, without an extension, an index file can have.\n * @param {InternalLocaleCode} args.locale Locale.\n * @returns {string | undefined} Localized folder name, or `undefined` if the folder has no entry or\n * its entry lacks the locale.\n */\nconst getLocalizedFolderName = ({ entries, dirPath, indexFileNames, locale }) => {\n  const indexEntry = entries.find(({ subPath }) =>\n    indexFileNames.some((name) => subPath === `${dirPath}/${name}`),\n  );\n\n  if (indexEntry) {\n    const localizedSubPath = indexEntry.locales[locale]?.slug;\n\n    return localizedSubPath ? getOwnFolderName(localizedSubPath) || undefined : undefined;\n  }\n\n  const siblingEntry = entries.find(({ subPath }) => subPath === dirPath);\n  const localizedSubPath = siblingEntry?.locales[locale]?.slug;\n\n  return localizedSubPath ? getPathInfo(localizedSubPath).basename : undefined;\n};\n\n/**\n * Get every entry in the collection, including the unpublished ones. With Editorial Workflow, a\n * section can be started and filled in one sitting, so a folder that only exists as a draft has to\n * be recognized too, or the sub-pages filed under it would land in a folder with the default\n * locale’s name.\n * @param {Pick<InternalCollection, 'name'>} collection Collection.\n * @returns {Entry[]} Entries.\n */\nexport const getAllEntries = (collection) => {\n  const { name } = collection;\n\n  return mergeUnpublishedEntries(\n    getEntriesByCollection(name),\n    unpublishedEntries.current.filter(({ workflow }) => workflow.collectionName === name),\n  );\n};\n\n/**\n * Get the given locale’s counterpart of a folder path within a collection with nested entries. The\n * path editor chooses a folder once, in the default locale, and the folders go by localized names\n * in the other locales, so each locale’s file has to be stored below the localized chain instead.\n * Each folder takes its name from the entry it belongs to, as described in {@link\n * getLocalizedFolderName}. A folder without such an entry, or whose entry lacks the locale, keeps\n * its name.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {string} args.dirPath Folder path in the default locale, relative to the collection\n * folder.\n * @param {InternalLocaleCode} args.locale Locale.\n * @param {Entry[]} [args.entries] Entries to look the folders up in. Defaults to every entry in the\n * collection, including the unpublished ones.\n * @returns {string} Localized folder path without leading and trailing slashes. The given path,\n * normalized the same way, if the collection’s folders aren’t localized or the locale is the\n * default one.\n * @see https://github.com/sveltia/sveltia-cms/issues/962\n */\nexport const localizeDirPath = ({ collection, dirPath, locale, entries }) => {\n  const path = stripSlashes(dirPath);\n\n  if (!path || locale === collection._i18n.defaultLocale || !hasLocalizedFolders(collection)) {\n    return path;\n  }\n\n  const configuredIndexFileName = getNestedIndexFileName(collection);\n\n  const indexFileNames = configuredIndexFileName\n    ? [configuredIndexFileName]\n    : DEFAULT_INDEX_FILE_NAMES;\n\n  const allEntries = entries ?? getAllEntries(collection);\n  let prefix = '';\n\n  return path\n    .split('/')\n    .map((segment) => {\n      prefix = prefix ? `${prefix}/${segment}` : segment;\n\n      return (\n        getLocalizedFolderName({ entries: allEntries, dirPath: prefix, indexFileNames, locale }) ??\n        segment\n      );\n    })\n    .join('/');\n};\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { fillTemplate } from '$lib/services/common/template';\nimport { getEntriesInCollectionFolder } from '$lib/services/contents/collection/entries';\nimport { getIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport {\n  getSharedEntryFileName,\n  stripIndexFileName,\n  usesCustomEntryPath,\n} from '$lib/services/contents/collection/nested';\nimport { localizeDirPath } from '$lib/services/contents/collection/nested/i18n';\nimport {\n  getLocalizingKeyPaths,\n  getSlugOptions,\n  hasLocalizedSlugs,\n  LEGACY_SLUG_EDITOR_TAG,\n} from '$lib/services/contents/collection/slug';\nimport { extractDateTime } from '$lib/services/contents/entry';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { isNumeric } from '$lib/services/utils/number';\nimport { getPullRequestEntries } from '$lib/services/workflow';\n\n/**\n * @import {\n * EntryDraft,\n * EntryFileMap,\n * EntrySlugVariants,\n * FillTemplateOptions,\n * FlattenedEntryContent,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * LocaleSlugMap,\n * PendingEntry,\n * } from '$lib/types/private';\n */\n\n/**\n * Replace blob URLs in the value map with the actual file names (without extension) so that asset\n * fields (image, file) can be used in slug templates.\n * @param {FlattenedEntryContent} valueMap Flattened entry content.\n * @param {EntryFileMap} files Draft file map keyed by blob URL.\n * @returns {FlattenedEntryContent} Value map with blob URLs replaced.\n * @see https://github.com/sveltia/sveltia-cms/issues/710\n */\nexport const resolveBlobURLs = (valueMap, files) => {\n  const resolved = { ...valueMap };\n\n  Object.entries(resolved).forEach(([key, value]) => {\n    if (typeof value === 'string' && value.startsWith('blob:') && files[value]) {\n      resolved[key] = files[value].file.name.replace(/\\.[^.]+$/, '');\n    }\n  });\n\n  return resolved;\n};\n\n/**\n * Random values generated for each entry draft’s slug. See {@link getRandomValues}.\n * @type {WeakMap<EntryDraft, Map<string, string>>}\n */\nconst randomValueMaps = new WeakMap();\n\n/**\n * Get the random values generated so far for the given draft’s slug, such as the one for a\n * `{{uuid}}` tag. A new entry’s slug is shown while it’s being edited, so reusing them keeps the\n * slug from changing on every keystroke, and the saved slug the same as the one shown.\n * @param {EntryDraft} draft Entry draft.\n * @returns {Map<string, string>} Random values keyed by what they stand for.\n */\nexport const getRandomValues = (draft) => getOrCreate(randomValueMaps, draft, () => new Map());\n\n/**\n * Get the folder chosen with the path editor of a collection with nested entries, in the given\n * locale. The folder is chosen in the default locale; when the slugs are localized, so are the\n * folders, and the entry’s file in another locale goes to the localized counterpart instead. The\n * entry’s slug is checked against that folder, and the entry is saved there, so both take it from\n * here.\n * @param {EntryDraft} draft Entry draft.\n * @param {InternalLocaleCode} [locale] Locale. Default: the default locale.\n * @returns {string} Folder path without leading and trailing slashes. An empty string for the\n * collection folder.\n * @see https://github.com/sveltia/sveltia-cms/issues/962\n */\nexport const getChosenDirPath = ({ collection, currentPath }, locale) =>\n  localizeDirPath({\n    collection,\n    dirPath: stripSlashes(currentPath ?? ''),\n    locale: locale ?? collection._i18n.defaultLocale,\n  });\n\n/**\n * Get the folder where an entry’s slug is filed as a bare name, as chosen with the path editor of a\n * collection with nested entries, when the entry’s file is named after its slug. That’s the case\n * for a new entry, and for a locale just enabled for an existing entry. The slug of an entry in\n * such a collection is otherwise its sub path, e.g. `docs/intro`, so a new slug has to be unique\n * among the entries in that folder rather than compared with the sub paths of every entry. Where\n * every entry shares one file name, the entry gets a folder of its own, which is checked with the\n * path instead. In another locale, that’s the localized counterpart of the folder; see\n * {@link getChosenDirPath}.\n * @param {EntryDraft} draft Entry draft.\n * @param {InternalLocaleCode} [locale] Locale to get the folder in. Default: the default locale.\n * @returns {string | undefined} Folder path without leading and trailing slashes, or `undefined`\n * if the slug in the locale is an existing sub path or the path editor doesn’t decide where it\n * goes.\n * @see https://github.com/sveltia/sveltia-cms/issues/962\n */\nexport const getSlugDirPath = (draft, locale) => {\n  const { collection, isNew, originalLocales } = draft;\n  const isNewInLocale = isNew || (!!locale && !originalLocales?.[locale]);\n\n  if (!isNewInLocale || !usesCustomEntryPath(draft) || getSharedEntryFileName(collection)) {\n    return undefined;\n  }\n\n  return getChosenDirPath(draft, locale);\n};\n\n/**\n * Names of the DateTime field that holds an entry’s date, as inferred by Decap CMS.\n * @type {string[]}\n */\nconst ENTRY_DATE_FIELD_NAMES = ['date', 'publishDate', 'publish_date'];\n\n/**\n * Get the date/time parts that fill the date/time tags, e.g. `{{year}}`, in a new entry’s slug and\n * path templates. Like Decap CMS, they come from the entry’s date, which is the value of the first\n * DateTime field named `date`, `publishDate` or `publish_date` in the default locale, so that a\n * backdated post is named after its own date. A date/time is read in UTC, or in the browser’s time\n * zone with the `timezone` slug option set to `local`, while a date-only value is read as written.\n * As the slug is only filled for a new entry, changing the date later doesn’t rename the file.\n * @param {EntryDraft} draft Entry draft.\n * @returns {Record<string, string> | undefined} Date/time parts, or `undefined` if the collection\n * has no such field or it’s empty, in which case the time of the save is used.\n * @see https://github.com/decaporg/decap-website/pull/183\n */\nexport const getEntryDateTimeParts = (draft) => {\n  const { collection, collectionFile, currentValues } = draft;\n\n  const {\n    fields = [],\n    _i18n: { defaultLocale },\n  } = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  const dateFieldName = fields.find(\n    ({ widget, name }) => widget === 'datetime' && ENTRY_DATE_FIELD_NAMES.includes(name),\n  )?.name;\n\n  if (!dateFieldName) {\n    return undefined;\n  }\n\n  return extractDateTime({\n    dateFieldName,\n    fields,\n    content: currentValues[defaultLocale] ?? {},\n    locale: defaultLocale,\n    inSlugTimeZone: true,\n  });\n};\n\n/**\n * Get the slug typed in the slug editor of the given locale, or the one shared by every locale.\n * @param {EntryDraft} draft Entry draft.\n * @param {string} locale Locale.\n * @returns {string | undefined} Slug.\n */\nconst getCurrentSlug = ({ currentSlugs }, locale) => currentSlugs?.[locale] ?? currentSlugs?._;\n\n/**\n * Get base options for {@link fillTemplate}.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @returns {FillTemplateOptions} Options.\n */\nexport const getFillSlugOptions = ({ draft }) => {\n  const { collection, collectionFile, currentValues, files, isIndexFile } = draft;\n\n  const {\n    _i18n: { defaultLocale },\n  } = collectionFile ?? collection;\n\n  return {\n    collection: /** @type {InternalEntryCollection} */ (collection),\n    content: {\n      ...resolveBlobURLs(currentValues[defaultLocale], files),\n      // Slug candidate for the default locale\n      _slug: getCurrentSlug(draft, defaultLocale),\n    },\n    locale: defaultLocale,\n    dateTimeParts: getEntryDateTimeParts(draft),\n    isIndexFile,\n    randomValues: getRandomValues(draft),\n  };\n};\n\n/**\n * Check whether a slug is typed in the slug editor of the given locale.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.locale Locale.\n * @returns {boolean} Result.\n */\nconst hasTypedSlug = ({ draft, locale }) => {\n  const editorValue = getCurrentSlug(draft, locale);\n\n  return !!draft.slugEditor[locale] && !!editorValue?.trim();\n};\n\n/**\n * Get the slug template to fill for a new entry in the given locale. A slug editor filled in by the\n * user takes over from the configured template, unless the template itself takes the slug from the\n * slug editor.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.locale Locale.\n * @param {boolean} [args.templateOnly] Whether to ignore a filled-in slug editor, to get the slug\n * the template fills.\n * @returns {string} Slug template, e.g. `{{title}}`. An empty string for a non-entry collection,\n * whose entry slug is the file name.\n */\nexport const getSlugTemplate = ({ draft, locale, templateOnly = false }) => {\n  const { collection } = draft;\n\n  if (collection._type !== 'entry') {\n    return '';\n  }\n\n  const { template, editorRequired } = getSlugOptions(collection);\n\n  if (!templateOnly && !editorRequired && hasTypedSlug({ draft, locale })) {\n    return LEGACY_SLUG_EDITOR_TAG;\n  }\n\n  return template;\n};\n\n/**\n * Check whether a new entry’s slug in the given locale is numbered automatically, which is when\n * the collection’s slug has the `auto_increment` option and no slug is typed in the slug editor.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.locale Locale.\n * @param {boolean} [args.templateOnly] Whether to ignore a filled-in slug editor, to get the slug\n * the entry is given without it.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/1072\n */\nexport const isSlugAutoNumbered = ({ draft, locale, templateOnly = false }) => {\n  const { collection } = draft;\n\n  if (collection._type !== 'entry' || !getSlugOptions(collection).autoIncrement) {\n    return false;\n  }\n\n  return templateOnly || !hasTypedSlug({ draft, locale });\n};\n\n/**\n * Get the slug a new entry is given in a collection whose slug is numbered automatically: the\n * integer after the highest one among the slugs of the entries stored in the collection folder, in\n * any locale, as the other locales share the number, starting from `1`. In a collection with nested\n * entries, the last segment of an entry’s sub path counts, leaving out the file name every entry\n * shares in the `subfolders` mode, e.g. `index`. The entries still in a pull request count too,\n * including the new ones riding along in the pull request of an entry of another collection, as do\n * the entries created from a Relation field that are saved along with the entry being edited. Like\n * the `auto_increment` option of a Number field, it’s worked out again at save time, so two entries\n * created at the same time can’t take the same number.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {PendingEntry[]} [args.pendingEntries] Entries that aren’t in the collection yet. Default:\n * the draft’s own pending entries.\n * @returns {string} Slug.\n * @see https://github.com/sveltia/sveltia-cms/issues/1072\n */\nexport const getNextSlugNumber = ({ draft, pendingEntries = draft.pendingEntries }) => {\n  const { collection, collectionName } = draft;\n\n  const max = [\n    ...getEntriesInCollectionFolder(collectionName),\n    ...getPullRequestEntries(collectionName),\n    ...pendingEntries\n      .filter((pendingEntry) => pendingEntry.collectionName === collectionName)\n      .map(({ entry }) => entry),\n  ]\n    .flatMap(({ slug, locales }) => [\n      slug,\n      ...Object.values(locales).map((content) => content.slug),\n    ])\n    .reduce((result, slug) => {\n      const name = /** @type {string} */ (stripIndexFileName(collection, slug).split('/').pop());\n\n      return isNumeric(name) ? Math.max(result, Number(name)) : result;\n    }, 0);\n\n  return String(max + 1);\n};\n\n/**\n * Get the localized slug for the given locale.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.locale Locale.\n * @param {string[]} args.localizingKeyPaths List of key paths that the value will be localized.\n * @param {string} args.defaultLocaleSlug Default locale’s entry slug, which a numbered slug shares.\n * @param {boolean} [args.templateOnly] See {@link getSlugTemplate}.\n * @param {Map<InternalLocaleCode, string>} [args.numberedSlugs] See {@link getSlugs}.\n * @returns {string} Localized slug.\n */\nexport const getLocalizedSlug = ({\n  draft,\n  locale,\n  localizingKeyPaths,\n  defaultLocaleSlug,\n  templateOnly = false,\n  numberedSlugs = undefined,\n}) => {\n  const { isNew, originalLocales, currentValues, files } = draft;\n  const _slug = getCurrentSlug(draft, locale);\n\n  // When creating a new entry or enabling a locale for an existing entry, we need to fill the slug\n  // template to generate the initial slug for the new locale. For other cases, we keep the existing\n  // slug to avoid changing URLs unexpectedly.\n  if (isNew || !originalLocales[locale]) {\n    // Every locale shares the number given to the default locale, unless a slug is typed in. The\n    // slug of an existing entry in a collection with nested entries is its sub path, of which the\n    // number is the last segment, as a filled template would be\n    if (isSlugAutoNumbered({ draft, locale, templateOnly })) {\n      return /** @type {string} */ (defaultLocaleSlug.split('/').pop());\n    }\n\n    // The entry’s date and random values are shared by every locale\n    const options = getFillSlugOptions({ draft });\n\n    return fillTemplate(getSlugTemplate({ draft, locale, templateOnly }), {\n      ...options,\n      locale,\n      dirPath: getSlugDirPath(draft, locale),\n      numberedSlugs,\n      content: {\n        // Merge the default locale content and localized content. A field that isn’t localized\n        // only exists in the default locale, so its value is kept from there\n        ...options.content,\n        ...resolveBlobURLs(\n          Object.fromEntries(\n            localizingKeyPaths\n              .map((keyPath) => [keyPath, currentValues[locale]?.[keyPath]])\n              .filter(([, value]) => value !== undefined),\n          ),\n          files,\n        ),\n        // Slug candidate for the current locale\n        _slug,\n      },\n    });\n  }\n\n  return /** @type {string} */ (_slug);\n};\n\n/**\n * Get the localized slug map. This only applies when the i18n structure is multiple files or\n * folders, and the slug template contains the `localize` flag, e.g. `{{title | localize}}`.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.defaultLocaleSlug Default locale’s entry slug.\n * @param {boolean} [args.templateOnly] See {@link getSlugTemplate}.\n * @param {Map<InternalLocaleCode, string>} [args.numberedSlugs] See {@link getSlugs}.\n * @returns {LocaleSlugMap | undefined} Localized slug map.\n */\nexport const getLocalizedSlugs = ({\n  draft,\n  defaultLocaleSlug,\n  templateOnly = false,\n  numberedSlugs = undefined,\n}) => {\n  const { collection, collectionFile, currentLocales } = draft;\n\n  const {\n    _i18n: { defaultLocale },\n  } = collectionFile ?? collection;\n\n  // A file/singleton collection has no slug template, so there is nothing to localize\n  if (collectionFile || !hasLocalizedSlugs(collection)) {\n    return undefined;\n  }\n\n  /**\n   * List of key paths that the value will be localized.\n   */\n  const localizingKeyPaths = getLocalizingKeyPaths(\n    /** @type {InternalEntryCollection} */ (collection),\n  );\n\n  return Object.fromEntries(\n    Object.entries(currentLocales).map(([locale]) => {\n      const slug =\n        locale === defaultLocale\n          ? defaultLocaleSlug\n          : getLocalizedSlug({\n              draft,\n              locale,\n              localizingKeyPaths,\n              defaultLocaleSlug,\n              templateOnly,\n              numberedSlugs,\n            });\n\n      return [locale, slug];\n    }),\n  );\n};\n\n/**\n * Get the canonical slug to be added to the content of each file when the slug is localized. It\n * helps Sveltia CMS and some frameworks to link localized files. The default property name is\n * `translationKey` used in Hugo’s multilingual support, and the default value is the default\n * locale’s slug.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.defaultLocaleSlug Default locale’s entry slug.\n * @param {LocaleSlugMap | undefined} args.localizedSlugs Localized slug map.\n * @param {FillTemplateOptions} args.fillSlugOptions Arguments for {@link fillTemplate}.\n * @returns {string | undefined} Canonical slug.\n * @see https://sveltiacms.app/en/docs/i18n/slugs#localizing-entry-slugs\n * @see https://gohugo.io/content-management/multilingual/#bypassing-default-linking\n */\nexport const getCanonicalSlug = ({ draft, defaultLocaleSlug, localizedSlugs, fillSlugOptions }) => {\n  if (!localizedSlugs) {\n    return undefined;\n  }\n\n  const { collection, collectionFile } = draft;\n\n  const {\n    _i18n: {\n      canonicalSlug: { value: canonicalSlugTemplate },\n    },\n  } = collectionFile ?? collection;\n\n  if (canonicalSlugTemplate === '{{slug}}') {\n    return defaultLocaleSlug;\n  }\n\n  return fillTemplate(canonicalSlugTemplate, {\n    ...fillSlugOptions,\n    currentSlug: defaultLocaleSlug,\n  });\n};\n\n/**\n * Determine entry slugs.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {boolean} [args.templateOnly] Whether to ignore a filled-in slug editor, to get the slugs\n * the template fills for a new entry.\n * @param {PendingEntry[]} [args.pendingEntries] Entries that aren’t in the collection yet, which a\n * numbered slug comes after. Default: the draft’s own pending entries.\n * @param {Map<InternalLocaleCode, string>} [args.numberedSlugs] Map to record the slug the\n * template fills for a new entry in, for each locale where another entry uses it, so a number is\n * added to make it unique.\n * @returns {EntrySlugVariants} Slugs.\n */\nexport const getSlugs = ({\n  draft,\n  templateOnly = false,\n  pendingEntries = undefined,\n  numberedSlugs = undefined,\n}) => {\n  const { isNew, collection, collectionFile, fileName, isIndexFile } = draft;\n\n  if (isIndexFile) {\n    return {\n      defaultLocaleSlug: /** @type {string} */ (getIndexFile(collection)?.name),\n      localizedSlugs: undefined,\n      canonicalSlug: undefined,\n    };\n  }\n\n  const {\n    _i18n: { defaultLocale },\n  } = collectionFile ?? collection;\n\n  const fillSlugOptions = getFillSlugOptions({ draft });\n\n  /**\n   * Get the slug of a new entry in the default locale.\n   * @returns {string} Slug.\n   */\n  const getNewEntrySlug = () => {\n    if (isSlugAutoNumbered({ draft, locale: defaultLocale, templateOnly })) {\n      return getNextSlugNumber({ draft, pendingEntries });\n    }\n\n    return fillTemplate(getSlugTemplate({ draft, locale: defaultLocale, templateOnly }), {\n      ...fillSlugOptions,\n      dirPath: getSlugDirPath(draft),\n      numberedSlugs,\n    });\n  };\n\n  const defaultLocaleSlug =\n    fileName ??\n    (isNew ? getNewEntrySlug() : /** @type {string} */ (getCurrentSlug(draft, defaultLocale)));\n\n  const localizedSlugs = getLocalizedSlugs({\n    draft,\n    defaultLocaleSlug,\n    templateOnly,\n    numberedSlugs,\n  });\n\n  const canonicalSlug = getCanonicalSlug({\n    draft,\n    defaultLocaleSlug,\n    localizedSlugs,\n    fillSlugOptions,\n  });\n\n  return { defaultLocaleSlug, localizedSlugs, canonicalSlug };\n};\n","import { getPathInfo } from '@sveltia/utils/file';\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport { fillTemplate } from '$lib/services/common/template';\nimport { getIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport {\n  getEntryDirPath,\n  getSharedEntryFileName,\n  usesCustomEntryPath,\n} from '$lib/services/contents/collection/nested';\nimport { getOwnFolderName, localizeDirPath } from '$lib/services/contents/collection/nested/i18n';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { hasLocalizedSlugs } from '$lib/services/contents/collection/slug';\nimport {\n  getChosenDirPath,\n  getEntryDateTimeParts,\n  getRandomValues,\n} from '$lib/services/contents/draft/slugs';\nimport { resolveFileConfig } from '$lib/services/contents/file/config';\nimport { getLocalePath } from '$lib/services/contents/i18n';\nimport {\n  fillLocalePlaceholder,\n  hasLocalePlaceholder,\n} from '$lib/services/contents/i18n/placeholder';\nimport { createPath, getBaseName } from '$lib/services/utils/file';\n\n/**\n * @import {\n * Entry,\n * EntryDraft,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { I18nFileStructure } from '$lib/types/public';\n */\n\n/**\n * Build the file path based on i18n structure and locale settings.\n * @param {object} args Arguments.\n * @param {string} args.basePath Base directory path.\n * @param {string} args.path File path (slug or subpath).\n * @param {string} args.extension File extension.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {boolean} args.omitLocale Whether to omit locale from the file path.\n * @param {I18nFileStructure} args.structure I18n structure type.\n * @returns {string} Complete file path string.\n */\nexport const buildPathByStructure = ({\n  basePath,\n  path,\n  extension,\n  locale,\n  omitLocale,\n  structure,\n}) => {\n  // The `{{locale}}` placeholder in the `folder` option says where the locale folder goes, so the\n  // structure has nothing to add\n  if (hasLocalePlaceholder(basePath)) {\n    return `${fillLocalePlaceholder({ path: basePath, locale, omitLocale })}/${path}.${extension}`;\n  }\n\n  switch (structure) {\n    case 'multiple_folders':\n      return omitLocale\n        ? `${basePath}/${path}.${extension}`\n        : `${basePath}/${locale}/${path}.${extension}`;\n    case 'multiple_folders_i18n_root': // deprecated\n    case 'multiple_root_folders': // new name\n      return omitLocale\n        ? `${basePath}/${path}.${extension}`\n        : `${locale}/${basePath}/${path}.${extension}`;\n    case 'multiple_files':\n      return omitLocale\n        ? `${basePath}/${path}.${extension}`\n        : `${basePath}/${path}.${locale}.${extension}`;\n    default:\n      return `${basePath}/${path}.${extension}`;\n  }\n};\n\n/**\n * Build the entry’s sub path from the folder chosen with the path editor. The file name within the\n * folder is either the one shared by every entry in the collection, as configured with the\n * `meta.path.index_file` option, or the entry’s own file name: the slug for a new entry, or the\n * existing file name for an entry that’s only being moved. With a shared file name, the chosen\n * folder is where a new entry is created rather than the entry’s own folder, which is named after\n * the slug.\n *\n * The folder is chosen once, in the default locale. When the slugs are localized, so are the\n * folders named after them, and each locale’s file goes below the localized folder chain, in a\n * folder named after the localized slug.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.slug Entry slug in the locale. For an existing entry in a collection with\n * nested entries, that’s the entry’s sub path in the locale.\n * @param {string | undefined} args.indexFileName File name shared by every entry in the collection,\n * if any.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @returns {string} Sub path without a file extension.\n * @see https://github.com/sveltia/sveltia-cms/issues/962\n */\nexport const buildCustomEntryPath = ({ draft, slug, indexFileName, locale }) => {\n  const { collection, isNew, originalEntry, currentPath } = draft;\n  const dirPath = stripSlashes(currentPath ?? '');\n  const localized = locale !== collection._i18n.defaultLocale && hasLocalizedSlugs(collection);\n\n  if (indexFileName) {\n    // Every entry shares one file name, so a folder is what makes an entry. A new entry therefore\n    // gets a folder of its own, named after the slug, within the folder the editor points at\n    if (isNew) {\n      return createPath([getChosenDirPath(draft, locale), slug, indexFileName]);\n    }\n\n    // An existing entry already has such a folder, and the editor points at it. In another locale,\n    // the folder goes by the name in the localized slug; a locale that has just been enabled has a\n    // bare slug, which becomes the folder name as it would for a new entry\n    const parentPath = localizeDirPath({ collection, dirPath: getEntryDirPath(dirPath), locale });\n    const ownFolderName = localized ? getOwnFolderName(slug) || slug : getBaseName(dirPath);\n\n    return createPath([parentPath, ownFolderName, indexFileName]);\n  }\n\n  // The sub path already has the locale and the file extension stripped off. A locale that has just\n  // been enabled keeps its localized slug, or it would be saved under the default locale’s name\n  const originalSubPath =\n    originalEntry?.locales[locale]?.slug ?? (localized ? undefined : originalEntry?.subPath);\n\n  const fileName = originalSubPath ? getPathInfo(originalSubPath).basename : slug;\n\n  // A slug filed as a bare name has been made unique within the same folder\n  return createPath([getChosenDirPath(draft, locale), fileName]);\n};\n\n/**\n * Check whether an existing entry’s file in the given locale stays where it is. The path editor\n * decides where the entry goes, so the slug alone can’t tell whether the file has moved; but as\n * long as the folder is left as it was and the slug is unchanged, the file stays put, even if not\n * where a rebuild would put it, e.g. a locale stored under folders that weren’t localized at the\n * time. Without the path editor, an unchanged slug is enough.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {string} args.slug Entry slug in the locale.\n * @returns {boolean} Result. Always `false` for a new entry, which has no file yet.\n */\nexport const keepsOriginalPath = ({ draft, locale, slug }) => {\n  const { originalEntry, originalPath, currentPath } = draft;\n\n  // A partial entry, without the locales, can stand in for the original when a draft is only built\n  // to be checked\n  if (originalEntry?.locales?.[locale]?.slug !== slug) {\n    return false;\n  }\n\n  if (!usesCustomEntryPath(draft)) {\n    return true;\n  }\n\n  // The path editor is in use, so the folder is set\n  return stripSlashes(originalPath ?? '') === stripSlashes(/** @type {string} */ (currentPath));\n};\n\n/**\n * Get the sub path of an existing entry’s file going by the given slug, for a locale of the entry\n * whose own file can’t be kept, typically one enabled after the entry was created. Unless the entry\n * is renamed, its files keep their slug, so the new file goes alongside them rather than where the\n * collection’s `path` option would put a new entry: the template can have tags that aren’t filled\n * the same way twice, like `{{year}}` without a date field, which takes the time of the save, or\n * `{{uuid_short}}`, while the localized files of an entry are linked by their shared sub path when\n * they’re read back. A renamed entry has no file going by the new slug, so the template is filled\n * again for every locale.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.slug Entry slug in the locale.\n * @param {RegExp} args.fullPathRegEx Regular expression matching the collection’s entry paths.\n * @returns {string | undefined} Sub path without the locale and file extension, or `undefined` if\n * no file of the entry has the slug.\n */\nexport const getKeptSubPath = ({ draft, slug, fullPathRegEx }) =>\n  Object.values(draft.originalEntry?.locales ?? {})\n    .filter((localizedEntry) => localizedEntry.slug === slug)\n    .map(({ path }) => path.match(fullPathRegEx)?.groups?.subPath)\n    .find((subPath) => !!subPath);\n\n/**\n * Determine the file path for the given entry draft depending on the collection type, i18n config\n * and entry collection’s subpath.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {string} args.slug Entry slug.\n * @returns {string} Complete path, including the folder, slug, extension and possibly locale.\n * @see https://decapcms.org/docs/i18n/\n * @see https://sveltiacms.app/en/docs/i18n\n */\nexport const createEntryPath = ({ draft, locale, slug }) => {\n  const { collection, collectionFile, originalEntry, currentValues, isIndexFile } = draft;\n\n  const {\n    _i18n: { defaultLocale, structure, omitDefaultLocaleFromFilePath },\n  } = collectionFile ?? collection;\n\n  if (collectionFile) {\n    const { _i18n, file } = collectionFile;\n\n    return getLocalePath({ _i18n, locale, path: stripSlashes(file) });\n  }\n\n  // All the entries are stored in one file, which holds all the translations\n  if (isArrayFileCollection(collection)) {\n    return /** @type {string} */ (\n      /** @type {InternalEntryCollection} */ (collection)._file.fullPath\n    );\n  }\n\n  const entryCollection = /** @type {InternalEntryCollection} */ (collection);\n  const indexFileName = getSharedEntryFileName(entryCollection);\n  // A blank folder in the path editor means the entry goes where it would without the editor, so\n  // the collection’s own `path` option and slug take over rather than the entry landing on a bare\n  // index file in the collection folder\n  // @see https://github.com/decaporg/decap-cms/issues/7094\n  const useCustomPath = usesCustomEntryPath(draft);\n\n  if (keepsOriginalPath({ draft, locale, slug })) {\n    return /** @type {Entry} */ (originalEntry).locales[locale].path;\n  }\n\n  // The index file can have an extension of its own\n  const { basePath, subPath, extension, fullPathRegEx } = resolveFileConfig({\n    collection: entryCollection,\n    isIndexFile,\n  });\n\n  /**\n   * Support entry collection’s subpath.\n   * @see https://decapcms.org/docs/collection-folder/#folder-collections-path\n   * @see https://decapcms.org/docs/collection-nested/\n   * @see https://sveltiacms.app/en/docs/collections/entries/slugs#file-paths\n   */\n  let path = isIndexFile\n    ? /** @type {string} */ (getIndexFile(entryCollection)?.name)\n    : useCustomPath\n      ? buildCustomEntryPath({ draft, slug, indexFileName, locale })\n      : subPath\n        ? // A locale enabled for an existing entry goes alongside the entry’s other files.\n          // Otherwise the template is filled with the default locale’s values, as the default\n          // locale, so that every locale, and every call for the same draft, e.g. for the entry\n          // file and for its entry-relative assets, gets the same random values for tags like\n          // `{{uuid_short}}`\n          (getKeptSubPath({ draft, slug, fullPathRegEx: /** @type {RegExp} */ (fullPathRegEx) }) ??\n          fillTemplate(subPath, {\n            collection: entryCollection,\n            locale: defaultLocale,\n            content: currentValues[defaultLocale],\n            currentSlug: slug,\n            dateTimeParts: getEntryDateTimeParts(draft),\n            randomValues: getRandomValues(draft),\n          }))\n        : slug;\n\n  // Remove extension from index file name if it already has one\n  if (isIndexFile && path?.endsWith(`.${extension}`)) {\n    path = path.slice(0, -extension.length - 1);\n  }\n\n  const pathString = buildPathByStructure({\n    basePath: /** @type {string} */ (basePath),\n    path,\n    extension,\n    locale,\n    omitLocale: omitDefaultLocaleFromFilePath && locale === defaultLocale,\n    structure,\n  });\n\n  // Remove unnecessary slashes in case `basePath` is empty\n  return createPath(pathString.split('/'));\n};\n","import equal from 'fast-deep-equal';\n\nimport { getAssetsByDirName, getTakenNamesInDir } from '$lib/services/assets';\nimport {\n  getEntryAssetFolderPath,\n  getOwnedEntryFolderPath,\n} from '$lib/services/assets/entry-folder';\nimport { formatFileName, isSameFileName } from '$lib/services/assets/file-name';\nimport { getAssetKind } from '$lib/services/assets/kinds';\nimport { getPendingFileName } from '$lib/services/assets/name';\nimport { assertOutsideCmsFolders } from '$lib/services/assets/reserved';\nimport { advancePreparing } from '$lib/services/backends/commit-progress';\nimport { fillTemplate } from '$lib/services/common/template';\nimport { createEntryPath } from '$lib/services/contents/draft/save/entry-path';\nimport { getFillSlugOptions } from '$lib/services/contents/draft/slugs';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport {\n  createPath,\n  encodeFilePath,\n  foldFileName,\n  getDirName,\n  getGitHash,\n  resolvePath,\n} from '$lib/services/utils/file';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * AssetNameTemplate,\n * EntryDraft,\n * FileChange,\n * FillTemplateOptions,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Resolved paths for entry assets.\n * @typedef {object} ResolvedAssetFolderPaths\n * @property {string} resolvedInternalPath Resolved `internalPath` with any template tags replaced.\n * May contain a sub path when assets are entry-relative.\n * @property {string} resolvedPublicPath Resolved `publicPath` with any template tags replaced.\n */\n\n/**\n * Properties for a saving asset.\n * @typedef {object} SavingAsset\n * @property {string} collectionName Collection name.\n * @property {string} [text] Raw text for a plaintext file, like HTML or Markdown.\n * @property {AssetFolderInfo} folder Folder info.\n */\n\n/**\n * Fill a template string if it contains template tags, otherwise return as-is.\n * @param {string} pathString Path string that may contain template tags.\n * @param {FillTemplateOptions} fillSlugOptions Arguments for {@link fillTemplate}.\n * @returns {string} Resolved path.\n */\nconst fillTemplateIfNeeded = (pathString, fillSlugOptions) =>\n  pathString.includes('{{') ? fillTemplate(pathString, fillSlugOptions) : pathString;\n\n/**\n * Resolve the internal asset path for entry-relative assets.\n * @param {object} args Arguments.\n * @param {string | undefined} args.internalSubPath Internal sub-path from folder config.\n * @param {string} args.assetFolderPath Folder holding the entry’s relative assets.\n * @param {FillTemplateOptions} args.fillSlugOptions Arguments for template filling.\n * @returns {string} Resolved internal path.\n */\nconst resolveInternalPath = ({ internalSubPath, assetFolderPath, fillSlugOptions }) => {\n  // We already know the entry file path, so we can resolve the internal path to the asset folder\n  // even when it’s entry-relative. We should use the folder path extracted from entryFilePath\n  // rather than reconstructing the path from templates, because when date-related template tags are\n  // used in subPath (e.g., `{{year}}-{{month}}-{{day}}-{{slug}}/index`), the resolved path would be\n  // different from the original entry path if we filled the template again. This would cause assets\n  // saved at a later date to be stored in a different folder than the entry itself.\n  const internalPathString = createPath([\n    assetFolderPath,\n    internalSubPath, // subfolder, e.g. `images` or an empty string\n  ]);\n\n  return resolvePath(fillTemplateIfNeeded(internalPathString, fillSlugOptions));\n};\n\n/**\n * Resolve the public asset path for entry-relative assets, which is the path the field value is\n * built from. The assets sit in the folder holding the entry, so the value is relative to the entry\n * itself and needs nothing but the configured `public_folder`, unless that starts with `/`, which\n * makes the value an absolute path, e.g. `/blog/hello/images/photo.jpg`.\n * @param {object} args Arguments.\n * @param {string} args.publicPath Public path from folder config.\n * @param {FillTemplateOptions} args.fillSlugOptions Arguments for template filling.\n * @returns {string} Resolved public path.\n */\nconst resolvePublicPath = ({ publicPath, fillSlugOptions }) => {\n  // Dot-only public path is a special case; the final path stored as the field value will be\n  // `./image.png` rather than `image.png`\n  if (/^\\.?$/.test(publicPath)) {\n    return publicPath;\n  }\n\n  const resolvedPath = resolvePath(fillTemplateIfNeeded(publicPath, fillSlugOptions));\n\n  // `resolvePath()` removes the leading slash, which an absolute public path has to keep\n  return publicPath.startsWith('/') ? `/${resolvedPath}` : resolvedPath;\n};\n\n/**\n * Get the internal/public asset path configuration for the entry assets.\n * @param {object} args Arguments.\n * @param {AssetFolderInfo} args.folder Asset folder associated with a new file.\n * @param {FillTemplateOptions} args.fillSlugOptions Arguments for {@link fillTemplate}.\n * @returns {ResolvedAssetFolderPaths} Determined paths.\n */\nexport const resolveAssetFolderPaths = ({ folder, fillSlugOptions }) => {\n  const { entryRelative, internalPath, internalSubPath, publicPath } = folder;\n\n  if (internalPath === undefined || publicPath === undefined) {\n    // This shouldn’t happen, but avoids type errors in the following code\n    return { resolvedInternalPath: '', resolvedPublicPath: '' };\n  }\n\n  if (!entryRelative) {\n    return {\n      resolvedInternalPath: fillTemplate(internalPath, fillSlugOptions),\n      resolvedPublicPath: fillTemplate(publicPath, fillSlugOptions),\n    };\n  }\n\n  const { collection, entryFilePath } = fillSlugOptions;\n\n  const resolvedInternalPath = resolveInternalPath({\n    internalSubPath,\n    assetFolderPath: getEntryAssetFolderPath({\n      collection,\n      entryFilePath: entryFilePath ?? '',\n      internalPath,\n    }),\n    fillSlugOptions,\n  });\n\n  const resolvedPublicPath = resolvePublicPath({ publicPath, fillSlugOptions });\n\n  return { resolvedInternalPath, resolvedPublicPath };\n};\n\n/**\n * Resolve the internal and public asset folder paths for a file being added to the given draft.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} [args.locale] Locale the file is being added to. Defaults to the\n * default locale, which is enough to resolve the public path, the same for every locale.\n * @param {string} [args.slug] Entry slug for that locale. Defaults to the default locale’s slug.\n * @param {string} args.defaultLocaleSlug Default locale’s entry slug.\n * @param {AssetFolderInfo} args.folder Asset folder associated with a new file.\n * @returns {ResolvedAssetFolderPaths} Determined paths.\n */\nexport const getAssetFolderPaths = ({ draft, locale, slug, defaultLocaleSlug, folder }) => {\n  const { collection, collectionFile, isIndexFile } = draft;\n\n  const {\n    _i18n: { defaultLocale },\n  } = collectionFile ?? collection;\n\n  return resolveAssetFolderPaths({\n    folder,\n    fillSlugOptions: {\n      ...getFillSlugOptions({ draft }),\n      type: 'media_folder',\n      // The date/time tags in a media folder stand for the time of the save, not the entry’s date\n      dateTimeParts: undefined,\n      currentSlug: defaultLocaleSlug,\n      // Resolve against the locale being edited: with a `multiple_folders` or\n      // `multiple_root_folders` i18n structure each locale has a folder of its own, and an asset\n      // referenced from one locale’s entry has to sit beside that entry\n      entryFilePath: createEntryPath({\n        draft,\n        locale: locale ?? defaultLocale,\n        slug: slug ?? defaultLocaleSlug,\n      }),\n      isIndexFile,\n    },\n  });\n};\n\n/**\n * Join the resolved public path and file name to create the public URL to be stored as the field\n * value.\n * @param {string} publicPath Resolved public path.\n * @param {string} fileName File name.\n * @returns {string} Public URL.\n */\nexport const createPublicURL = (publicPath, fileName) =>\n  publicPath ? `${publicPath === '/' ? '' : publicPath}/${fileName}` : fileName;\n\n/**\n * Get the folder that the assets in the given folder are moved from, when the save takes the entry\n * to another folder of its own. The assets stored with an entry follow it to its new folder, which\n * is empty until then, so a file added in the same save has to be named against the assets that\n * are on their way there as well. Otherwise one of them would take the new file’s name, and the\n * move would then drop it as replaced, along with what the entry used it for. The move itself is\n * planned by `buildEntryAssetMoveChanges()` in `asset-move.js`.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale the file is being added to.\n * @param {string} args.entryFilePath Path the entry file is saved to in that locale.\n * @param {string} args.folderPath Folder the file is saved to.\n * @returns {string | undefined} Folder path, or `undefined` if no asset is moved to the folder.\n */\nconst getVacatedAssetFolderPath = ({ draft, locale, entryFilePath, folderPath }) => {\n  const { collection, isNew, originalEntry } = draft;\n  const previousPath = isNew ? undefined : originalEntry?.locales[locale]?.path;\n\n  if (!previousPath) {\n    return undefined;\n  }\n\n  const oldFolderPath = getOwnedEntryFolderPath(collection, previousPath);\n  const newFolderPath = getOwnedEntryFolderPath(collection, entryFilePath);\n\n  if (\n    !oldFolderPath ||\n    !newFolderPath ||\n    oldFolderPath === newFolderPath ||\n    !(folderPath === newFolderPath || folderPath.startsWith(`${newFolderPath}/`))\n  ) {\n    return undefined;\n  }\n\n  return `${oldFolderPath}${folderPath.slice(newFolderPath.length)}`;\n};\n\n/**\n * Get the information required to save an asset.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} [args.locale] Locale the file is being added to. See\n * {@link getAssetFolderPaths}.\n * @param {string} [args.slug] Entry slug for that locale.\n * @param {string} args.defaultLocaleSlug Default locale’s entry slug.\n * @param {AssetFolderInfo} args.folder Asset folder associated with a new file.\n * @param {string} [args.subfolderPath] Subfolder below the folder the file is saved to, picked\n * while browsing the folder in the asset picker.\n * @returns {{ assetFolderPaths: ResolvedAssetFolderPaths, assetNamesInSameFolder: string[],\n * takenNamesInSameFolder: string[], assetNamesMovingIn: string[], savingAssetProps: SavingAsset }}\n * Arguments. `takenNamesInSameFolder` adds the names of the other files and the subfolders there,\n * which a new file can’t take or replace. `assetNamesMovingIn` lists the assets moved to the folder\n * in the same save, which take their names with them. See {@link getVacatedAssetFolderPath}.\n */\nexport const getAssetSavingInfo = ({\n  draft,\n  locale,\n  slug,\n  defaultLocaleSlug,\n  folder,\n  subfolderPath = '',\n}) => {\n  const { collectionName } = draft;\n  let assetFolderPaths = getAssetFolderPaths({ draft, locale, slug, defaultLocaleSlug, folder });\n\n  if (subfolderPath) {\n    const { resolvedInternalPath, resolvedPublicPath } = assetFolderPaths;\n\n    assetFolderPaths = {\n      ...assetFolderPaths,\n      resolvedInternalPath: createPath([resolvedInternalPath, subfolderPath]),\n      resolvedPublicPath: createPublicURL(resolvedPublicPath, subfolderPath),\n    };\n  }\n\n  const { resolvedInternalPath } = assetFolderPaths;\n  const _locale = locale ?? getDraftI18nConfig(draft).defaultLocale;\n\n  const vacatedFolderPath = folder.entryRelative\n    ? getVacatedAssetFolderPath({\n        draft,\n        locale: _locale,\n        entryFilePath: createEntryPath({ draft, locale: _locale, slug: slug ?? defaultLocaleSlug }),\n        folderPath: resolvedInternalPath,\n      })\n    : undefined;\n\n  /**\n   * Get the names of the assets stored in the given folder. A name is kept as it’s spelled in the\n   * repository, which may be in another Unicode normalization form than a name typed in the\n   * browser, e.g. a decomposed `café.jpg` saved on macOS, so a file replacing the asset is written\n   * to the same path rather than next to it. Names are compared with `foldFileName()`.\n   * @param {string} folderPath Folder path.\n   * @returns {string[]} Asset names.\n   */\n  const getNames = (folderPath) => getAssetsByDirName(folderPath).map((a) => a.name);\n\n  return {\n    assetFolderPaths,\n    assetNamesInSameFolder: getNames(resolvedInternalPath),\n    takenNamesInSameFolder: getTakenNamesInDir(resolvedInternalPath),\n    assetNamesMovingIn: vacatedFolderPath ? getNames(vacatedFolderPath) : [],\n    savingAssetProps: { collectionName, folder },\n  };\n};\n\n/**\n * Replace a blob URL with the final path, and add the file to the changeset.\n * @param {object} args Arguments.\n * @param {File} args.file Raw file.\n * @param {AssetFolderInfo} args.folder Asset folder associated with the new file.\n * @param {string} [args.subfolderPath] Subfolder below the folder the file is saved to.\n * @param {boolean} args.replace Whether to replace an existing file.\n * @param {AssetNameTemplate} [args.nameTemplate] Template to name the file with.\n * @param {string} args.blobURL Blob URL of the file.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} [args.locale] Locale the file is being added to. See\n * {@link getAssetFolderPaths}.\n * @param {string} [args.slug] Entry slug for that locale.\n * @param {string} args.defaultLocaleSlug Default locale’s entry slug.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {FlattenedEntryContent} args.content Localized content.\n * @param {FileChange[]} args.changes Changeset.\n * @param {Asset[]} args.savingAssets List of assets to be saved.\n * @param {boolean} args.encodingEnabled Whether the file path encoding is enabled.\n */\nexport const replaceBlobURL = async ({\n  file,\n  folder,\n  subfolderPath,\n  replace,\n  nameTemplate,\n  blobURL,\n  draft,\n  locale,\n  slug,\n  defaultLocaleSlug,\n  keyPath,\n  content,\n  changes,\n  savingAssets,\n  encodingEnabled,\n}) => {\n  const sha = await getGitHash(file);\n\n  advancePreparing();\n\n  const {\n    savingAssetProps,\n    assetNamesInSameFolder,\n    takenNamesInSameFolder,\n    assetNamesMovingIn,\n    assetFolderPaths: { resolvedInternalPath, resolvedPublicPath },\n  } = getAssetSavingInfo({ draft, locale, slug, defaultLocaleSlug, folder, subfolderPath });\n\n  // Files already being saved to the same folder in this save\n  const savingAssetsInSameFolder = savingAssets.filter(\n    (f) => getDirName(f.path) === resolvedInternalPath,\n  );\n\n  // The same file picked for another field or locale is saved once, as long as it goes to the same\n  // place: the same folder, and the same subfolder in it. A file replacing an existing one must\n  // keep its name, so an identical file saved under another name doesn’t count\n  const dupFile = savingAssetsInSameFolder.find(\n    (f) =>\n      f.sha === sha &&\n      (!folder.entryRelative || equal(f.folder, folder)) &&\n      (!replace || isSameFileName(f.name, file.name)),\n  );\n\n  let fileName = '';\n\n  // Check if the file has already been added for other field or locale\n  if (dupFile) {\n    fileName = dupFile.name;\n  } else {\n    // A different file with the same name, e.g. two images pasted from the clipboard as\n    // `image.png`, may already be headed for this folder in the same save. It’s not in the asset\n    // store yet, so take its name into account too, or one file would overwrite the other. The\n    // code below runs without awaiting anything, so concurrent calls can’t pick the same name\n    const item = { file, folder, replace, nameTemplate };\n    const pendingFileName = getPendingFileName({ draft, item, defaultLocaleSlug });\n    const namesInSave = savingAssetsInSameFolder.map((f) => f.name);\n    const ownName = replace ? formatFileName(pendingFileName) : undefined;\n    /**\n     * Check if the given name is in the given list, ignoring case and the Unicode normalization\n     * form.\n     * @param {string[]} names Names.\n     * @param {string} name Name.\n     * @returns {boolean} Result.\n     */\n    const hasName = (names, name) => names.some((n) => foldFileName(n) === foldFileName(name));\n\n    // Only the first of the files with the same name in this save replaces the existing file;\n    // another one gets a name of its own, or it would overwrite the first one. Nor can a file\n    // replace anything but an asset, e.g. an entry file next to it\n    const replacing =\n      ownName !== undefined &&\n      !hasName(namesInSave, ownName) &&\n      (hasName(assetNamesInSameFolder, ownName) || !hasName(takenNamesInSameFolder, ownName));\n\n    fileName = replacing\n      ? ownName\n      : formatFileName(pendingFileName, {\n          assetNamesInSameFolder: [\n            ...takenNamesInSameFolder,\n            ...assetNamesMovingIn,\n            ...namesInSave,\n          ],\n        });\n\n    // A replacing file overwrites the existing asset whose name only differs in case or in the\n    // Unicode normalization form, e.g. `Photo.jpg` and `photo.jpg`, rather than being added next to\n    // it, as the two would clash on a case-insensitive file system\n    const replacedName = replacing\n      ? assetNamesInSameFolder.find((name) => foldFileName(name) === foldFileName(fileName))\n      : undefined;\n\n    const update = !!replacedName;\n\n    if (replacedName) {\n      fileName = replacedName;\n    }\n\n    const assetPath = resolvedInternalPath ? `${resolvedInternalPath}/${fileName}` : fileName;\n\n    // A file picked in the editor can go to any subfolder the picker browsed to, but the files in a\n    // folder the CMS itself is served from are read-only, like they are in the Asset Library\n    assertOutsideCmsFolders([assetPath]);\n\n    changes.push({\n      action: update ? 'update' : 'create',\n      path: assetPath,\n      data: file,\n    });\n\n    savingAssets.push({\n      ...savingAssetProps,\n      blobURL,\n      name: fileName,\n      path: assetPath,\n      sha,\n      size: file.size,\n      kind: getAssetKind(fileName),\n    });\n  }\n\n  let publicURL = createPublicURL(resolvedPublicPath, fileName);\n\n  if (encodingEnabled) {\n    publicURL = encodeFilePath(publicURL);\n  }\n\n  content[keyPath] = /** @type {string} */ (content[keyPath]).replaceAll(blobURL, () => publicURL);\n};\n","import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\nimport { fillPermalink, getPermalinkKey } from '$lib/services/contents/entry/permalink';\n\n/**\n * @import { EntryDraft, FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * Store the path of the entry being saved in the property named with the `permalink_field` option.\n * The path can depend on the slug and on any field, so it’s worked out on every save, for a new\n * entry as well as an existing one. See {@link fillPermalink}.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FlattenedEntryContent} args.content Flattened entry content to be modified in place.\n * @param {string} args.slug New entry slug for the locale.\n * @param {string} args.path New entry file path for the locale.\n */\nexport const setPermalink = ({ draft, locale, content, slug, path }) => {\n  const { collection, fields, isIndexFile } = draft;\n\n  // Don’t take a snapshot of the values for nothing\n  if (!getPermalinkKey({ collection, fields })) {\n    return;\n  }\n\n  fillPermalink({\n    collection,\n    fields,\n    isIndexFile,\n    locale,\n    content,\n    // A snapshot, which is replaced rather than changed as the draft is edited\n    defaultContent: getValueMapSnapshot(draft, collection._i18n.defaultLocale),\n    slug,\n    path,\n  });\n};\n","import { getBlobRegex } from '@sveltia/utils/file';\nimport { toRaw } from '@sveltia/utils/object';\n\nimport { callEventHooks } from '$lib/services/api/events';\nimport { globalAssetFolder } from '$lib/services/assets/folders';\nimport { cmsConfig } from '$lib/services/config';\nimport { allEntries } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { hasNestedEntries } from '$lib/services/contents/collection/nested';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { filterRealValues } from '$lib/services/contents/draft';\nimport { addAlias } from '$lib/services/contents/draft/save/aliases';\nimport { rewriteEntryAssetReferences } from '$lib/services/contents/draft/save/asset-references';\nimport { replaceBlobURL } from '$lib/services/contents/draft/save/assets';\nimport { createEntryPath } from '$lib/services/contents/draft/save/entry-path';\nimport {\n  buildEntryFileChanges,\n  resolveCacheDB,\n} from '$lib/services/contents/draft/save/file-changes';\nimport { setPermalink } from '$lib/services/contents/draft/save/permalink';\nimport { getCanonicalSlug, getFillSlugOptions } from '$lib/services/contents/draft/slugs';\nimport { getDraftFieldArgs, getField } from '$lib/services/contents/entry/fields';\nimport { RICH_TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { resolveFileConfig } from '$lib/services/contents/file/config';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isDuplicatedField } from '$lib/services/contents/i18n/shared-values';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * Entry,\n * EntryDraft,\n * EntrySlugVariants,\n * FileChange,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalCollectionFile,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * LocalizedEntryMap,\n * PendingEntry,\n * } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n * @import { EntryFilePlan } from '$lib/services/contents/draft/save/file-changes';\n */\n\n/**\n * Get the sub path of a file within the collection folder.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection | InternalCollectionFile} args.collection Entry collection, or\n * the collection file for a file/singleton collection, which is what holds the file configuration\n * in that case.\n * @param {string} args.path File path.\n * @param {string} args.fallback Sub path to fall back to if the path can’t be parsed.\n * @returns {string} Sub path.\n */\nconst getSubPath = ({ collection: { _file }, path, fallback }) =>\n  _file.fullPathRegEx ? (path.match(_file.fullPathRegEx)?.groups?.subPath ?? fallback) : fallback;\n\n/**\n * Get the canonical slug for an entry in a collection with nested entries, where an entry is\n * identified by its path within the collection folder rather than by a bare slug. Linking the\n * localized files by the slug alone would take two entries with the same slug in different folders\n * for one entry once they’re read back from the repository, so it’s the default locale’s sub path\n * that links them.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {EntrySlugVariants} args.slugs Entry slugs.\n * @returns {string | undefined} Canonical slug, or `undefined` if the collection is not nested or\n * the slugs aren’t localized, in which case the regular canonical slug applies.\n * @see https://github.com/sveltia/sveltia-cms/issues/962\n */\nconst getNestedCanonicalSlug = ({ draft, slugs: { defaultLocaleSlug, localizedSlugs } }) => {\n  const { collection, defaultLocale } = draft;\n\n  if (!localizedSlugs || !hasNestedEntries(collection)) {\n    return undefined;\n  }\n\n  const path = createEntryPath({ draft, locale: defaultLocale, slug: defaultLocaleSlug });\n\n  const subPath = getSubPath({\n    collection: /** @type {InternalEntryCollection} */ (collection),\n    path,\n    fallback: defaultLocaleSlug,\n  });\n\n  return getCanonicalSlug({\n    draft,\n    defaultLocaleSlug: subPath,\n    localizedSlugs,\n    fillSlugOptions: getFillSlugOptions({ draft }),\n  });\n};\n\n/**\n * Arguments shared by the normalization of an entry’s content in every locale.\n * @typedef {object} NormalizeContentArgs\n * @property {EntryDraft} draft Entry draft.\n * @property {EntryDraft['files']} files Files attached to the draft, keyed by blob URL.\n * @property {string} defaultLocaleSlug Default locale’s entry slug.\n * @property {FileChange[]} changes File changeset, which saved assets are added to.\n * @property {Asset[]} savingAssets List of assets to be saved.\n * @property {GetFieldArgs} getFieldArgs Arguments to get a field configuration.\n * @property {boolean} encodingEnabled Whether the file path encoding is enabled.\n * @property {AssetFolderInfo | undefined} globalAssetFolder Global asset folder, which a file is\n * saved to unless it’s associated with another folder. `undefined` without the global\n * `media_folder` option.\n */\n\n/**\n * Replace the blob URLs found in a field value with the paths of the assets they point to.\n * @param {NormalizeContentArgs & {\n * locale: InternalLocaleCode, slug: string, content: FlattenedEntryContent, keyPath: FieldKeyPath,\n * matches: RegExpExecArray[] }} args Arguments. `content` is modified in place, and `matches` are\n * the blob URLs found in the value.\n */\nconst replaceBlobURLs = async ({\n  draft,\n  files,\n  defaultLocaleSlug,\n  changes,\n  savingAssets,\n  getFieldArgs,\n  encodingEnabled,\n  globalAssetFolder: _globalAssetFolder,\n  locale,\n  slug,\n  content,\n  keyPath,\n  matches,\n}) => {\n  const fieldArgs = { ...getFieldArgs, valueMap: content, keyPath };\n  const field = getField(fieldArgs);\n  const { defaultLocale } = getDraftI18nConfig(draft);\n\n  // A file in a field holding the same value in every locale, i.e. a `duplicate` or `sync` field,\n  // is stored once, in the default locale’s folder, rather than in each locale’s folder with the\n  // `multiple_folders` or `multiple_root_folders` i18n structure. Every locale refers to it by the\n  // same path. A file in a translatable field still goes to the folder of its own locale\n  // @see https://sveltiacms.app/en/docs/media/internal#multilingual-entries\n  const isMirrored =\n    locale !== defaultLocale &&\n    !!field &&\n    isDuplicatedField({ fieldConfig: field, getFieldArgs: fieldArgs });\n\n  const replaceBlobArgs = {\n    draft,\n    defaultLocaleSlug,\n    changes,\n    savingAssets,\n    // The default locale’s slug is used when the slug is omitted\n    locale: isMirrored ? defaultLocale : locale,\n    slug: isMirrored ? undefined : slug,\n    keyPath,\n    content,\n    // Enable encoding for markdown fields to support embedded images\n    encodingEnabled: RICH_TEXT_FIELD_TYPES.includes(field?.widget ?? '') || encodingEnabled,\n  };\n\n  // Replace blob URLs in File/Image fields with asset paths\n  await Promise.all(\n    matches.map(async ([blobURL]) => {\n      const {\n        file,\n        folder = _globalAssetFolder,\n        replace,\n        subfolderPath,\n        nameTemplate,\n      } = files[blobURL] ?? {};\n\n      // A blob URL only lives as long as the page, so one without the file it was made for, e.g.\n      // left by a backup whose file couldn’t be stored, would be saved as a broken link\n      if (!file) {\n        throw new Error(\n          `The file referenced in the \"${field?.label ?? keyPath}\" field is no longer available. ` +\n            'Select the file again.',\n        );\n      }\n\n      // A file can only be cached without a folder, and there is no global folder either, when\n      // only a cloud media library is configured. The file has nowhere to go in the repository\n      if (!folder) {\n        throw new Error(`There is no asset folder to save the file \"${file.name}\" to`);\n      }\n\n      await replaceBlobURL({\n        ...replaceBlobArgs,\n        file,\n        folder,\n        replace,\n        subfolderPath,\n        nameTemplate,\n        blobURL,\n      });\n    }),\n  );\n};\n\n/**\n * Field types whose leading whitespace is part of the value: indentation in a Text field, or an\n * indented code block at the start of Markdown. Their values only lose trailing whitespace.\n */\nconst MULTILINE_FIELD_TYPES = ['text', ...RICH_TEXT_FIELD_TYPES];\n\n/**\n * Remove the whitespace from a string value that the field it belongs to doesn’t need. A Code\n * field value is kept as is, as any whitespace can be significant in code, e.g. the indentation of\n * the first line in YAML or Python and the final newline. A Text, Markdown or rich text field value\n * keeps its leading whitespace. Any other value, including one that no field configuration\n * describes, is trimmed on both ends.\n * @param {object} args Arguments.\n * @param {GetFieldArgs} args.getFieldArgs Arguments to get a field configuration.\n * @param {FlattenedEntryContent} args.content Entry content.\n * @param {FieldKeyPath} args.keyPath Key path of the value.\n * @param {string} args.value Value.\n * @returns {string} Trimmed value.\n */\nconst trimValue = ({ getFieldArgs, content, keyPath, value }) => {\n  const fieldArgs = { ...getFieldArgs, valueMap: content };\n  const field = getField({ ...fieldArgs, keyPath });\n  // A Code field that saves the language too stores the code below its own key path, e.g.\n  // `code.code`, which no field configuration describes\n  const parentKeyPath = keyPath.split('.').slice(0, -1).join('.');\n\n  const fieldType = field\n    ? (field.widget ?? 'string')\n    : parentKeyPath && getField({ ...fieldArgs, keyPath: parentKeyPath })?.widget;\n\n  if (fieldType === 'code') {\n    return value;\n  }\n\n  if (MULTILINE_FIELD_TYPES.includes(String(fieldType))) {\n    return value.trimEnd();\n  }\n\n  return value.trim();\n};\n\n/**\n * Normalize a field value for saving: remove an undefined value, trim a string as the field needs\n * with {@link trimValue}, and replace the blob URLs in it with asset paths.\n * @param {NormalizeContentArgs & {\n * locale: InternalLocaleCode, slug: string, content: FlattenedEntryContent, keyPath: FieldKeyPath,\n * value: any }} args Arguments. `content` is modified in place.\n */\nconst normalizeFieldValue = async ({ keyPath, value, ...args }) => {\n  const { content } = args;\n\n  if (value === undefined) {\n    delete content[keyPath];\n\n    return;\n  }\n\n  if (typeof value !== 'string') {\n    return;\n  }\n\n  content[keyPath] = trimValue({ getFieldArgs: args.getFieldArgs, content, keyPath, value });\n\n  const matches = [...value.matchAll(getBlobRegex('g'))];\n\n  if (!matches.length) {\n    return;\n  }\n\n  await replaceBlobURLs({ ...args, keyPath, matches });\n};\n\n/**\n * Normalize an entry’s content in a locale for saving: add the canonical slug and an alias,\n * normalize each field value, then add the permalink.\n * @param {NormalizeContentArgs & {\n * locale: InternalLocaleCode, slug: string, path: string, content: FlattenedEntryContent,\n * canonicalSlug: string | undefined, canonicalSlugKey: string }} args Arguments. `content` is\n * modified in place.\n */\nconst normalizeLocaleContent = async ({ path, canonicalSlug, canonicalSlugKey, ...args }) => {\n  const { draft, locale, slug, content } = args;\n\n  // Add the canonical slug only when it’s defined; if it’s undefined (e.g. the slug template\n  // has no `| localize` filter), skip the assignment to avoid wiping a user-defined field\n  // that happens to share the same key (e.g. `translationKey`).\n  if (canonicalSlug !== undefined) {\n    content[canonicalSlugKey] = canonicalSlug;\n  }\n\n  // Keep links to the entry’s previous path working after the slug has been edited\n  addAlias({ draft, locale, content, slug, path });\n\n  // Normalize data\n  await Promise.all(\n    Object.entries(content).map(([keyPath, value]) =>\n      normalizeFieldValue({ ...args, keyPath, value }),\n    ),\n  );\n\n  // Store the entry’s path on the live site, if the collection asks for it. It comes last, as the\n  // path can contain a field value, which must no longer be a blob URL\n  setPermalink({ draft, locale, content, slug, path });\n};\n\n/**\n * Create base saving entry data.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {EntrySlugVariants} args.slugs Entry slugs.\n * @returns {Promise<{ localizedEntryMap: LocalizedEntryMap, changes: FileChange[], savingAssets:\n * Asset[] }>} Localized entry map, file changeset and asset list.\n */\nexport const createBaseSavingEntryData = async ({ draft, slugs }) => {\n  const { defaultLocaleSlug, localizedSlugs } = slugs;\n  const _globalAssetFolder = globalAssetFolder.current;\n  const { collection, collectionFile, currentLocales, currentValues, files } = draft;\n\n  const {\n    _i18n: {\n      canonicalSlug: { key: canonicalSlugKey },\n    },\n  } = collectionFile ?? collection;\n\n  /** @type {FileChange[]} */\n  const changes = [];\n  /** @type {Asset[]} */\n  const savingAssets = [];\n  const { encode_file_path: encodingEnabled = false } = cmsConfig.current?.output ?? {};\n  const getFieldArgs = getDraftFieldArgs(draft, { keyPath: '', valueMap: {} });\n  const canonicalSlug = getNestedCanonicalSlug({ draft, slugs }) ?? slugs.canonicalSlug;\n\n  /** @type {NormalizeContentArgs} */\n  const normalizeArgs = {\n    draft,\n    files,\n    defaultLocaleSlug,\n    changes,\n    savingAssets,\n    getFieldArgs,\n    encodingEnabled,\n    globalAssetFolder: _globalAssetFolder,\n  };\n\n  const localizedEntryMap = Object.fromEntries(\n    await Promise.all(\n      Object.entries(currentValues).map(async ([locale, valueMap]) => {\n        // Normalize a copy, so the draft keeps its blob URLs until the save has gone through. If\n        // the commit fails, a retry then saves the files again, rather than committing the entry\n        // with paths to files that never reached the repository\n        // @see https://github.com/sveltia/sveltia-cms/issues/1012\n        // The internal properties the editor adds to list items, like `__sc_item_id`, are left out:\n        // they’re not part of the content, and would otherwise reach the event hooks and the stores\n        const content = filterRealValues(valueMap);\n        const localizedSlug = localizedSlugs?.[locale];\n        const slug = localizedSlug ?? defaultLocaleSlug;\n        const path = createEntryPath({ draft, locale, slug });\n\n        if (!currentLocales[locale]) {\n          return [locale, { path }];\n        }\n\n        await normalizeLocaleContent({\n          ...normalizeArgs,\n          locale,\n          slug,\n          path,\n          content,\n          canonicalSlug,\n          canonicalSlugKey,\n        });\n\n        return [locale, { slug, path, content: toRaw(content) }];\n      }),\n    ),\n  );\n\n  return { localizedEntryMap, changes, savingAssets };\n};\n\n/**\n * Remove the locales turned off in the draft from the saving entry, once the file changes have been\n * worked out. Such a locale only carries the path of its file, so the change plan can delete the\n * file, but the entry saved to the stores has no file in that locale anymore — or never had one, if\n * the locale was turned on and off again before the first save. Left in, the path would count as\n * one of the entry’s files: deleting the entry later in the same session would delete a file that\n * no longer exists, which the Git services refuse, and the entry would look changed when compared\n * with the same entry read back from the repository.\n * @param {Entry} entry Saving entry.\n * @returns {Entry} Entry with the locales that have content only.\n */\nexport const removeDisabledLocales = (entry) => ({\n  ...entry,\n  locales: Object.fromEntries(\n    Object.entries(entry.locales).filter(([, { content }]) => content !== undefined),\n  ),\n});\n\n/**\n * Get the item that a change to an entry applies to, if the entry is stored in a file with the\n * other entries of an entry collection. The item is identified by its position, and by the content\n * the user has seen, so that the change doesn’t apply to another item if the array has changed.\n * The content is taken from the entry in the store, as the given entry can be a copy with the\n * change already made to it, e.g. a reference to a renamed asset or entry. Without one, the given\n * entry stands in, which the item then has to match.\n * @param {Entry | undefined} entry Existing entry. `undefined` for a new entry, which is added to\n * the end of the array.\n * @returns {Pick<FileChange, 'arrayItem'>} Properties to add to the change.\n */\nexport const getArrayItemTarget = (entry) => {\n  if (entry?.arrayIndex === undefined) {\n    return {};\n  }\n\n  const { locales } = allEntries.current.find(({ id }) => id === entry.id) ?? entry;\n\n  return { arrayItem: { index: entry.arrayIndex, locales } };\n};\n\n/**\n * Plan the file change for the entry draft, specifically for a single-file entry.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Entry} args.savingEntry Entry to be saved.\n * @param {boolean} [args.recreate] Whether to write the entry anew, because someone else has\n * deleted it since the draft was opened. See {@link createSavingEntryData}.\n * @returns {EntryFilePlan} Planned change.\n */\nexport const planSingleFileChange = ({ draft, savingEntry, recreate = false }) => {\n  const { collection, originalEntry, collectionFile } = draft;\n  const isNew = draft.isNew || recreate;\n\n  const {\n    _i18n: { defaultLocale },\n  } = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  const { slug, path } = savingEntry.locales[defaultLocale];\n  const previousPath = isNew ? undefined : originalEntry?.locales[defaultLocale]?.path;\n  // Comparing the paths rather than the slugs also catches an entry moved with the path editor,\n  // which leaves the slug alone\n  const renamed = !isNew && !!previousPath && previousPath !== path;\n\n  return {\n    action: isNew ? 'create' : renamed ? 'move' : 'update',\n    slug,\n    path,\n    previousPath: renamed ? previousPath : undefined,\n    currentPath: previousPath,\n    ...(isArrayFileCollection(collection) && !isNew ? getArrayItemTarget(originalEntry) : {}),\n  };\n};\n\n/**\n * Plan the file change for the entry draft, specifically for a multi-file entry.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Entry} args.savingEntry Entry to be saved.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {boolean} [args.recreate] Whether to write the entry anew, because someone else has\n * deleted it since the draft was opened. See {@link createSavingEntryData}.\n * @returns {EntryFilePlan | undefined} Planned change, or `undefined` if there’s no file to save\n * or delete for the locale.\n */\nexport const planMultiFileChange = ({ draft, savingEntry, locale, recreate = false }) => {\n  const { originalLocales, currentLocales, originalEntry } = draft;\n  const isNew = draft.isNew || recreate;\n  const { slug, path } = savingEntry.locales[locale] ?? {};\n  const previousPath = isNew ? undefined : originalEntry?.locales[locale]?.path;\n\n  if (currentLocales[locale]) {\n    const renamed = !isNew && !!originalLocales[locale] && !!previousPath && previousPath !== path;\n\n    return {\n      action: isNew || !originalLocales[locale] ? 'create' : renamed ? 'move' : 'update',\n      slug,\n      path,\n      previousPath: renamed ? previousPath : undefined,\n      currentPath: previousPath,\n    };\n  }\n\n  if (!isNew && originalLocales[locale]) {\n    // Delete the file where it is now. The path built for the disabled locale follows the new slug\n    // and folder, so it points elsewhere once the entry is renamed or moved in the same save\n    return {\n      action: 'delete',\n      slug: originalEntry?.locales[locale]?.slug ?? slug,\n      path: /** @type {string} */ (previousPath),\n      currentPath: previousPath,\n    };\n  }\n\n  return undefined;\n};\n\n/**\n * Create saving entry data.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {EntrySlugVariants} args.slugs Entry slugs.\n * @param {boolean} [args.recreate] Whether to write the entry anew, as if it were new, because\n * someone else has deleted it since the draft was opened and the user has chosen to save anyway.\n * Its files are then created rather than updated, moved or deleted, as none of them exists anymore.\n * @param {boolean} [args.runPreSave] Whether to call the `preSave` event hooks. It’s `false` for an\n * entry created from a Relation field, which is only saved along with the entry referring to it;\n * the hooks are then called by {@link preparePendingEntryCommit} at that point.\n * @returns {Promise<{ savingEntry: Entry, savingAssets: Asset[], changes: FileChange[] }>} Saving\n * entry, assets and file changes.\n */\nexport const createSavingEntryData = async ({\n  draft,\n  slugs,\n  recreate = false,\n  runPreSave = true,\n}) => {\n  const { id, collection, collectionFile } = draft;\n  const { defaultLocaleSlug } = slugs;\n  // A file/singleton collection keeps its file configuration on the collection file\n  const entryCollection = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n  const { defaultLocale } = entryCollection._i18n;\n\n  const { localizedEntryMap, changes, savingAssets } = await createBaseSavingEntryData({\n    draft,\n    slugs,\n  });\n\n  // An entry may have no file in the default locale, e.g. when only `hello.fr.md` exists. Another\n  // locale then stands in for it, just like when the entry is read from the repository\n  const { path } =\n    localizedEntryMap[defaultLocale] ??\n    Object.values(localizedEntryMap).find(({ content }) => content) ??\n    Object.values(localizedEntryMap)[0];\n\n  const subPath = getSubPath({ collection: entryCollection, path, fallback: defaultLocaleSlug });\n  // In a collection with nested entries, an entry is identified by its path within the collection\n  // folder rather than by a file name, so that’s also the slug the entry gets when it’s read back\n  // from the repository. Use it here as well, or the entry saved in this session would differ from\n  // the same entry after a reload.\n  const nested = hasNestedEntries(collection);\n\n  /** @type {Entry} */\n  let savingEntry = {\n    id,\n    slug: nested ? subPath : defaultLocaleSlug,\n    subPath,\n    // An entry stored in a file with the other entries keeps its position, while a new one gets\n    // one once the file is saved\n    ...(draft.isNew || draft.originalEntry?.arrayIndex === undefined\n      ? {}\n      : { arrayIndex: draft.originalEntry.arrayIndex }),\n    locales: Object.fromEntries(\n      Object.entries(localizedEntryMap).map(([locale, localizedEntry]) => [\n        locale,\n        nested\n          ? {\n              ...localizedEntry,\n              slug: getSubPath({\n                collection: entryCollection,\n                path: localizedEntry.path,\n                fallback: defaultLocaleSlug,\n              }),\n            }\n          : localizedEntry,\n      ]),\n    ),\n  };\n\n  // The references to the entry’s own assets by an absolute path filled with its values, e.g.\n  // `/blog/{{slug}}/images/photo.jpg`, follow a renamed slug or a move of the entry. An entry\n  // someone else has deleted is written anew, from references the user has seen\n  savingEntry = await rewriteEntryAssetReferences({\n    collection,\n    collectionFile,\n    isIndexFile: draft.isIndexFile,\n    originalEntry: draft.isNew || recreate ? undefined : draft.originalEntry,\n    savingEntry,\n  });\n\n  if (runPreSave) {\n    await callEventHooks({\n      type: 'preSave',\n      entry: savingEntry,\n      collection,\n      collectionFile,\n      isNew: draft.isNew,\n    });\n  }\n\n  changes.push(\n    ...(await buildEntryFileChanges({\n      draft,\n      config: entryCollection,\n      _file: resolveFileConfig({ collection, collectionFile, isIndexFile: draft.isIndexFile }),\n      entry: savingEntry,\n      cacheDB: resolveCacheDB(),\n      /**\n       * Plan the change to a file of the entry.\n       * @param {InternalLocaleCode} [locale] Locale of the file, or `undefined` for the single\n       * file.\n       * @returns {EntryFilePlan | undefined} Planned change.\n       */\n      planChange: (locale) =>\n        locale === undefined\n          ? planSingleFileChange({ draft, savingEntry, recreate })\n          : planMultiFileChange({ draft, savingEntry, locale, recreate }),\n    })),\n  );\n\n  return { savingEntry, savingAssets, changes };\n};\n\n/**\n * Prepare an entry created or edited from a Relation field for the commit of the entry referring to\n * it: call the `preSave` event hooks, which are held back until then, so they don’t run for an\n * entry that is discarded along with the draft. If a hook updates the entry, its file changes are\n * built again from the updated content, each the same way as before: created for a new entry, and\n * updated for an existing one; the other changes, like the assets uploaded with the entry, are\n * kept.\n * The pending entry itself is left as is, so a retry after a failed commit starts over from it.\n * @param {PendingEntry} pendingEntry Pending entry.\n * @returns {Promise<PendingEntry>} Pending entry to commit.\n */\nexport const preparePendingEntryCommit = async (pendingEntry) => {\n  const { collectionName, entry, changes, baseEntry } = pendingEntry;\n  const isNew = !baseEntry;\n  // Quick-add only creates and edits entries in an entry collection, see `getCreatableCollection()`\n  // and `canEditEntry()`\n  const collection = /** @type {InternalEntryCollection} */ (getCollection(collectionName));\n\n  /** @type {Entry} */\n  const savingEntry = {\n    ...entry,\n    locales: Object.fromEntries(\n      Object.entries(entry.locales).map(([locale, localizedEntry]) => [\n        locale,\n        { ...localizedEntry },\n      ]),\n    ),\n  };\n\n  await callEventHooks({ type: 'preSave', entry: savingEntry, collection, isNew });\n\n  // A hook updating the entry replaces the content of the locales\n  const updated = Object.entries(savingEntry.locales).some(\n    ([locale, { content }]) => content !== entry.locales[locale].content,\n  );\n\n  if (!updated) {\n    return pendingEntry;\n  }\n\n  const { defaultLocale } = collection._i18n;\n  const entryPaths = new Set(Object.values(entry.locales).map(({ path }) => path));\n\n  const fileChanges = await buildEntryFileChanges({\n    // A synthetic draft holding the properties read by `formatEntryData()`\n    draft: { collection, collectionName, fields: collection.fields, isIndexFile: false },\n    config: collection,\n    _file: resolveFileConfig({ collection }),\n    entry: savingEntry,\n    cacheDB: resolveCacheDB(),\n    /**\n     * Plan the change to a file of the entry, the same as the one planned when the entry was added.\n     * @param {InternalLocaleCode} [locale] Locale of the file, or `undefined` for the single\n     * file.\n     * @returns {EntryFilePlan | undefined} Planned change, or `undefined` if the entry has no file\n     * in the locale.\n     */\n    planChange: (locale) => {\n      const localizedEntry = savingEntry.locales[locale ?? defaultLocale];\n\n      if (!localizedEntry) {\n        return undefined;\n      }\n\n      const { slug, path } = localizedEntry;\n\n      // An existing entry has a change planned for each of its files when it’s added: an update,\n      // or a creation for a locale turned on. It’s never a move, see `isPendingEntryMoved()`\n      const { action } = isNew\n        ? { action: /** @type {const} */ ('create') }\n        : /** @type {FileChange} */ (changes.find((change) => change.path === path));\n\n      // The file is looked up to update it, unless it’s to be created\n      return { action, slug, path, currentPath: action === 'create' ? undefined : path };\n    },\n  });\n\n  return {\n    ...pendingEntry,\n    entry: savingEntry,\n    changes: [...changes.filter(({ path }) => !entryPaths.has(path)), ...fileChanges],\n  };\n};\n","import { _ } from '@sveltia/i18n';\nimport { getPathInfo } from '@sveltia/utils/file';\n\nimport { assetUpdatesToast, refreshFocusedAssets } from '$lib/services/assets/data';\nimport { createAssetMoveChange } from '$lib/services/assets/data/move-change';\nimport { getAssetFoldersByPath, globalAssetFolder } from '$lib/services/assets/folders';\nimport { getAssetPublicURL } from '$lib/services/assets/info';\nimport { getAssetReferenceTarget } from '$lib/services/assets/reference-target';\nimport { getEntriesByAssets } from '$lib/services/assets/references';\nimport { assertOutsideCmsFolders } from '$lib/services/assets/reserved';\nimport { saveChanges } from '$lib/services/backends/save';\nimport { UPDATE_TOAST_DEFAULT_STATE } from '$lib/services/contents/collection/data';\nimport { getIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { createSavingEntryData } from '$lib/services/contents/draft/save/changes';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { getEntryCollectionContexts } from '$lib/services/contents/entry/contexts';\nimport { getReadonlyEntryLabel, isEntryReadonly } from '$lib/services/contents/entry/readonly';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { encodeFilePath, getBaseName } from '$lib/services/utils/file';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * Entry,\n * EntryDraft,\n * FileChange,\n * InternalEntryCollection,\n * MovingAsset,\n * } from '$lib/types/private';\n * @import { CollectionIndexFile } from '$lib/types/public';\n * @import { AssetReferenceTarget } from '$lib/services/assets/references';\n */\n\n/**\n * Get base properties for the entry draft.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry to get base properties for.\n * @returns {Partial<EntryDraft>} Base properties for the entry draft.\n */\nexport const getDraftBaseProps = ({ entry }) => {\n  const { locales } = entry;\n  const localeEntries = Object.entries(locales);\n  const originalLocales = Object.fromEntries(localeEntries.map(([locale]) => [locale, true]));\n\n  const originalSlugs = Object.fromEntries(\n    localeEntries.map(([locale, { slug }]) => [locale, slug]),\n  );\n\n  const originalValues = Object.fromEntries(\n    localeEntries.map(([locale, { content }]) => [locale, content]),\n  );\n\n  return {\n    createdAt: Date.now(),\n    isNew: false,\n    canPreview: true,\n    originalEntry: entry,\n    originalLocales,\n    currentLocales: structuredClone(originalLocales),\n    originalSlugs,\n    currentSlugs: structuredClone(originalSlugs),\n    originalValues,\n    currentValues: structuredClone(originalValues),\n    files: {},\n    validities: {},\n    validationMessages: {},\n    expanderStates: {},\n  };\n};\n\n/**\n * Add saving entry data to the stack.\n * @param {object} args Arguments.\n * @param {Partial<EntryDraft>} args.draftProps Entry draft properties.\n * @param {CollectionIndexFile} [args.indexFile] Index file of the collection.\n * @param {Entry[]} args.savingEntries Entries to be saved. This will be modified.\n * @param {FileChange[]} args.changes File changes to be saved. This will be modified.\n */\nexport const addSavingEntryData = async ({ draftProps, indexFile, savingEntries, changes }) => {\n  const { collection, collectionFile } = draftProps;\n\n  const { fields: regularFields = [] } =\n    collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  const draft = /** @type {EntryDraft} */ ({\n    ...draftProps,\n    fields: indexFile?.fields ?? regularFields,\n  });\n\n  const { savingEntry, changes: _changes } = await createSavingEntryData({\n    draft,\n    slugs: getSlugs({ draft }),\n  });\n\n  savingEntries.push(savingEntry);\n  changes.push(..._changes);\n};\n\n/**\n * Collect changes for the given entry.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry to collect changes for.\n * @param {Entry[]} args.savingEntries Entries to be saved. This will be modified.\n * @param {FileChange[]} args.changes File changes to be saved. This will be modified.\n */\nexport const collectEntryChanges = async ({ entry, savingEntries, changes }) => {\n  const draftBaseProps = getDraftBaseProps({ entry });\n\n  await Promise.all(\n    getEntryCollectionContexts(entry).map(({ collection, collectionFile, isIndexFile }) => {\n      /** @type {Partial<EntryDraft>} */\n      const draftProps = {\n        ...draftBaseProps,\n        collection,\n        collectionName: collection.name,\n        isIndexFile,\n        ...(collectionFile ? { collectionFile, fileName: collectionFile.name } : {}),\n      };\n\n      return addSavingEntryData({\n        draftProps,\n        indexFile: isIndexFile ? getIndexFile(collection) : undefined,\n        savingEntries,\n        changes,\n      });\n    }),\n  );\n};\n\n/**\n * Get the new URL of a moved asset that has no public path, as in an entry-relative folder, by\n * swapping the folder’s internal path for its public path.\n * @param {object} args Arguments.\n * @param {AssetFolderInfo | undefined} args._globalAssetFolder Global asset folder, if any.\n * @param {string} args.newPath New path for the asset.\n * @param {Asset} args.asset Asset being moved.\n * @returns {string} URL.\n */\nconst getFallbackURL = ({ _globalAssetFolder, newPath, asset }) => {\n  const { publicPath } =\n    getAssetFoldersByPath(asset.path).find(({ collectionName }) => collectionName !== undefined) ??\n    _globalAssetFolder ??\n    // There is no global folder without the global `media_folder` option\n    asset.folder;\n\n  return newPath.replace(asset.folder.internalPath ?? '', publicPath ?? '');\n};\n\n/**\n * Get a function that rewrites a reference to a renamed asset that has no public path, as in an\n * entry-relative folder. Such a reference is relative to the entry holding it, so only its file\n * name is swapped, leaving the rest — `./`, `../` or a subfolder — as the entry has it. A file name\n * encoded in the reference, as with the `encode_file_path` option, is replaced in the same form.\n * @param {string} oldName Current file name.\n * @param {string} newName New file name.\n * @returns {(src: string) => string | undefined} Function returning the new reference, or\n * `undefined` if the reference doesn’t end with the file name.\n */\nconst getRenamedReference = (oldName, newName) => (src) => {\n  const [from, to] =\n    [\n      [oldName, newName],\n      // The form the `encode_file_path` option saves a reference in\n      [encodeFilePath(oldName), encodeFilePath(newName)],\n      // A reference encoded by hand, which leaves characters like `(` and `)` as they are\n      [encodeURI(oldName), encodeURI(newName)],\n    ].find(([name]) => src === name || src.endsWith(`/${name}`)) ?? [];\n\n  return from === undefined ? undefined : `${src.slice(0, -from.length)}${to}`;\n};\n\n/**\n * Get the message explaining why assets can’t be moved or renamed: some of the entries using them\n * are read-only, so the references in them can’t be updated, and leaving them pointing at a file\n * that’s no longer there would break them.\n * @param {Entry[]} entries Entries using the assets.\n * @returns {string | undefined} Message naming the read-only entries, or `undefined` if there is\n * none.\n */\nexport const getMoveBlockedMessage = (entries) => {\n  const readonlyEntries = entries.filter((entry) => isEntryReadonly(entry));\n\n  return readonlyEntries.length\n    ? _('cannot_move_referenced_asset', {\n        values: {\n          entries: readonlyEntries.map((entry) => getReadonlyEntryLabel(entry)).join(', '),\n        },\n      })\n    : undefined;\n};\n\n/**\n * Entries found to use some files, ahead of rewriting the references to the files once their new\n * locations are known.\n * @typedef {object} ReferenceRewritePlan\n * @property {AssetReferenceTarget[]} targets What the references to each file are matched by.\n * @property {Entry[][]} usedEntries Entries using each file, in the same order.\n */\n\n/**\n * Find the entries using some files, before the files are moved, and refuse the move if any of\n * them is read-only: its references can’t be rewritten, and leaving it pointing at a file that’s no\n * longer there would break it. The entries are searched once for all the files, however many there\n * are. Nothing is replaced yet, so the originals are left alone until the change is saved.\n * @param {AssetReferenceTarget[]} targets What the references to each file are matched by.\n * @returns {Promise<ReferenceRewritePlan>} Plan to pass to {@link rewriteEntryReferences}.\n * @throws {Error} When an entry using the files is read-only, with a message naming the entries.\n */\nexport const planReferenceRewrite = async (targets) => {\n  const usedEntries = targets.length ? await getEntriesByAssets(targets) : [];\n  const blockedMessage = getMoveBlockedMessage([...new Set(usedEntries.flat())]);\n\n  if (blockedMessage) {\n    throw new Error(blockedMessage);\n  }\n\n  return { targets, usedEntries };\n};\n\n/**\n * Rewrite the references to some files in the entries found to use them, so these point at the\n * files’ new locations, which may be anywhere: another repository folder, or a cloud storage\n * service.\n * @param {object} args Arguments.\n * @param {ReferenceRewritePlan} args.plan Entries using the files, from\n * {@link planReferenceRewrite}.\n * @param {(index: number) => AssetReferenceTarget['newURL']} args.getNewURL Function returning the\n * new reference to the file at the given index, only called for a file some entry uses.\n * @param {Map<string, Entry>} args.updatingEntryMap Copies of the entries being rewritten, keyed by\n * entry ID. An entry using several of the files is copied once and has every reference replaced in\n * that copy, so it’s saved once with all of them; a copy per file would each hold a single\n * replacement and overwrite the others. The caller collects the changes from the copies.\n */\nexport const rewriteEntryReferences = async ({\n  plan: { targets, usedEntries },\n  getNewURL,\n  updatingEntryMap,\n}) => {\n  /** @type {AssetReferenceTarget[]} */\n  const replacingTargets = [];\n  /** @type {Set<Entry>} */\n  const updatingEntries = new Set();\n\n  targets.forEach((target, index) => {\n    if (usedEntries[index].length) {\n      replacingTargets.push({ ...target, newURL: getNewURL(index) });\n      usedEntries[index].forEach((entry) => updatingEntries.add(entry));\n    }\n  });\n\n  if (!replacingTargets.length) {\n    return;\n  }\n\n  const entries = [...updatingEntries].map((entry) =>\n    getOrCreate(updatingEntryMap, entry.id, () => structuredClone(entry)),\n  );\n\n  // The references are replaced in place, in one pass over the copies\n  await getEntriesByAssets(replacingTargets, { entries });\n};\n\n/**\n * Get the reference to an asset once it has been moved to another path in the repository. It’s\n * worked out the same way as the current one, so that the public folder, the `encode_file_path`\n * option and template tags are all dealt with alike. A move to another folder takes that folder’s\n * public path; otherwise the asset’s own folder still applies.\n * @param {MovingAsset & { _globalAssetFolder: AssetFolderInfo | undefined }} args Asset being\n * moved, its new path and folder, and the global asset folder, if any.\n * @returns {AssetReferenceTarget['newURL']} New reference, or a function rewriting a reference\n * relative to the entry holding it.\n */\nconst getNewAssetReference = ({\n  _globalAssetFolder,\n  asset,\n  path: newPath,\n  folder = asset.folder,\n}) => {\n  const newName = getBaseName(newPath);\n\n  // A rename of an entry-relative asset is applied to each reference as the entry holding it has\n  // it, which is the form it was saved in, e.g. `./photo.jpg` with `public_folder: ./`, or an\n  // encoded name with the `encode_file_path` option. The path `getAssetPublicURL()` gives such an\n  // asset is relative to its folder, regardless of the public folder, and isn’t encoded\n  if (\n    asset.folder.entryRelative &&\n    newPath.slice(0, -newName.length) === asset.path.slice(0, -asset.name.length)\n  ) {\n    return getRenamedReference(asset.name, newName);\n  }\n\n  return (\n    getAssetPublicURL(\n      { ...asset, path: newPath, name: newName, folder },\n      { pathOnly: true, allowSpecial: true },\n    ) ?? getFallbackURL({ _globalAssetFolder, newPath, asset })\n  );\n};\n\n/**\n * Rewrite the references to the given assets in the entries that use them, so these point at the\n * assets’ new paths in the repository.\n * @param {object} args Arguments.\n * @param {AssetFolderInfo | undefined} args._globalAssetFolder Global asset folder, if any.\n * @param {MovingAsset[]} args.movingAssets Assets being moved, with their new paths.\n * @param {Map<string, Entry>} args.updatingEntryMap Copies of the entries being rewritten, see\n * {@link rewriteEntryReferences}.\n * @throws {Error} When an entry using the assets is read-only, with a message naming the entries.\n */\nexport const collectEntryChangesFromAssets = async ({\n  _globalAssetFolder,\n  movingAssets,\n  updatingEntryMap,\n}) => {\n  await rewriteEntryReferences({\n    // Matched the same way as everywhere else, e.g. the count of the entries using an asset: by its\n    // public path, or else by the asset itself, as in an entry-relative folder, which works whether\n    // or not the asset has been loaded\n    plan: await planReferenceRewrite(\n      movingAssets.map(({ asset }) => getAssetReferenceTarget(asset)),\n    ),\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    getNewURL: (index) => getNewAssetReference({ _globalAssetFolder, ...movingAssets[index] }),\n    updatingEntryMap,\n  });\n};\n\n/**\n * Rewrite the references to some files in the entries found to use them, as\n * {@link rewriteEntryReferences} does, and collect the changes to save the entries with.\n * @param {object} args Arguments.\n * @param {ReferenceRewritePlan} args.plan Entries using the files, from\n * {@link planReferenceRewrite}.\n * @param {(index: number) => AssetReferenceTarget['newURL']} args.getNewURL Function returning the\n * new reference to the file at the given index.\n * @returns {Promise<{ savingEntries: Entry[], changes: FileChange[] }>} Entries to be saved, and\n * the changes to their files. Both are empty when no entry uses the files.\n */\nexport const collectReferenceChanges = async ({ plan, getNewURL }) => {\n  /** @type {Map<string, Entry>} */\n  const updatingEntryMap = new Map();\n  /** @type {Entry[]} */\n  const savingEntries = [];\n  /** @type {FileChange[]} */\n  const changes = [];\n\n  await rewriteEntryReferences({ plan, getNewURL, updatingEntryMap });\n  await Promise.all(\n    [...updatingEntryMap.values()].map((entry) =>\n      collectEntryChanges({ entry, savingEntries, changes }),\n    ),\n  );\n\n  return { savingEntries, changes };\n};\n\n/**\n * Save the changes to the entries using some moved files, if any, along with changes to other\n * files, e.g. the repository files being created or deleted, in one commit. Nothing is committed\n * when there’s nothing to change, as when a file on a cloud storage service that no entry uses is\n * moved.\n * @param {object} args Arguments.\n * @param {ReferenceRewritePlan} args.plan Entries using the files, from\n * {@link planReferenceRewrite}.\n * @param {string[]} args.newURLs New references to the files, in the same order.\n * @param {FileChange[]} [args.changes] Changes to other files.\n * @param {Asset[]} [args.savingAssets] Repository assets being saved.\n * @param {'uploadMedia' | 'deleteMedia'} args.commitType Commit type.\n */\nexport const saveReferenceChanges = async ({\n  plan,\n  newURLs,\n  changes = [],\n  savingAssets = [],\n  commitType,\n}) => {\n  const { savingEntries, changes: entryChanges } = await collectReferenceChanges({\n    plan,\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    getNewURL: (index) => newURLs[index],\n  });\n\n  if (changes.length || entryChanges.length) {\n    await saveChanges({\n      changes: [...changes, ...entryChanges],\n      savingEntries,\n      savingAssets,\n      options: { commitType },\n    });\n  }\n};\n\n/**\n * Update the asset and entry stores after moving or renaming assets.\n * @param {object} args Arguments.\n * @param {'move' | 'rename'} args.action The action performed, either 'move' or 'rename'.\n * @param {MovingAsset[]} args.movedAssets The assets that have been moved or renamed.\n * @param {boolean} [args.notify] Whether to show a toast reporting the move. Default: `true`.\n */\nexport const updateStores = ({ action, movedAssets, notify = true }) => {\n  refreshFocusedAssets(({ path }) => movedAssets.find((a) => a.asset.path === path)?.path);\n\n  if (notify) {\n    assetUpdatesToast.current = {\n      ...UPDATE_TOAST_DEFAULT_STATE,\n      moved: action === 'move',\n      renamed: action === 'rename',\n      count: movedAssets.length,\n    };\n  }\n};\n\n/**\n * Move or rename assets while updating links in the entries.\n * @param {'move' | 'rename'} action Action type.\n * @param {MovingAsset[]} movingAssets Assets to be moved/renamed.\n * @param {object} [options] Options.\n * @param {FileChange[]} [options.extraChanges] Changes to files other than the assets, committed\n * along with the move, e.g. the `.gitkeep` of a folder being renamed.\n * @param {boolean} [options.notify] Whether to show a toast reporting the move. Default: `true`.\n * A caller that reports the result in its own words, like a folder rename, turns it off.\n */\nexport const moveAssets = async (\n  action,\n  movingAssets,\n  { extraChanges = [], notify = true } = {},\n) => {\n  assertOutsideCmsFolders([\n    ...movingAssets.flatMap(({ asset, path }) => [asset.path, path]),\n    ...extraChanges.flatMap(({ path, previousPath }) => [\n      path,\n      ...(previousPath ? [previousPath] : []),\n    ]),\n  ]);\n\n  const _globalAssetFolder = globalAssetFolder.current;\n  /** @type {FileChange[]} */\n  const changes = [];\n  /** @type {Entry[]} */\n  const savingEntries = [];\n  /** @type {Asset[]} */\n  const savingAssets = [];\n  /** @type {Map<string, Entry>} */\n  const updatingEntryMap = new Map();\n\n  await Promise.all(\n    movingAssets.map(async ({ asset, path, folder = asset.folder }) => {\n      const name = getPathInfo(path).basename;\n\n      savingAssets.push({ ...asset, path, name, folder });\n      changes.push(await createAssetMoveChange(asset, path, name));\n    }),\n  );\n\n  await collectEntryChangesFromAssets({ _globalAssetFolder, movingAssets, updatingEntryMap });\n\n  await Promise.all(\n    [...updatingEntryMap.values()].map((entry) =>\n      collectEntryChanges({ entry, savingEntries, changes }),\n    ),\n  );\n\n  await saveChanges({\n    changes: [...changes, ...extraChanges],\n    savingEntries,\n    savingAssets,\n    options: { commitType: 'uploadMedia' },\n  });\n\n  updateStores({ action, movedAssets: movingAssets, notify });\n};\n","/**\n * A step that changes something outside the CMS, such as a file on a cloud storage service, along\n * with the way to undo it.\n * @template T\n * @typedef {object} ReversibleStep\n * @property {() => Promise<T>} run Function making the change and returning its result.\n * @property {(result: T) => Promise<unknown>} undo Function undoing the change, given its result.\n */\n\n/**\n * Run the given steps one at a time, then finish with the results, e.g. by saving the entries that\n * point at the files the steps have uploaded or moved. If a step or the finish fails, the steps\n * run so far are undone, in the order they were run, and the error is thrown again. A step that\n * can’t be undone is left as it is, and the error is logged, so the other steps are still undone.\n * @template T\n * @param {ReversibleStep<T>[]} steps Steps.\n * @param {(results: T[]) => Promise<unknown>} finish Function called with the results of every\n * step, in the same order.\n * @returns {Promise<T[]>} Results.\n * @throws {Error} When a step or the finish fails.\n */\nexport const runWithUndo = async (steps, finish) => {\n  /** @type {T[]} */\n  const results = [];\n\n  try {\n    // eslint-disable-next-line no-restricted-syntax\n    for (const { run } of steps) {\n      // eslint-disable-next-line no-await-in-loop\n      results.push(await run());\n    }\n\n    await finish(results);\n  } catch (ex) {\n    // eslint-disable-next-line no-restricted-syntax\n    for (const [index, result] of results.entries()) {\n      try {\n        // eslint-disable-next-line no-await-in-loop\n        await steps[index].undo(result);\n      } catch (error) {\n        // eslint-disable-next-line no-console\n        console.error(error);\n      }\n    }\n\n    throw ex;\n  }\n\n  return results;\n};\n","import { _ } from '@sveltia/i18n';\n\nimport {\n  getMoveBlockedMessage,\n  planReferenceRewrite,\n  saveReferenceChanges,\n} from '$lib/services/assets/data/move';\nimport { getFetchOptions } from '$lib/services/assets/external';\nimport { assetsLocked } from '$lib/services/assets/folders';\nimport { runWithUndo } from '$lib/services/utils/undo';\n\n/**\n * @import { Entry, ExternalAsset, MediaLibraryService } from '$lib/types/private';\n * @import { ReferenceRewritePlan } from '$lib/services/assets/data/move';\n */\n\n/**\n * Get the message explaining why files on a cloud storage service can’t be renamed or moved: the\n * references to them in the entries can’t be updated, as one of the entries is read-only, or the\n * media library is locked, as for an Open Authoring contributor, so no commit can be made.\n * @param {Entry[]} entries Entries using the files.\n * @param {number} count Number of files.\n * @returns {string | undefined} Message, or `undefined` if the references can be updated.\n */\nexport const getExternalChangeBlockedMessage = (entries, count) =>\n  getMoveBlockedMessage(entries) ??\n  (assetsLocked.current && entries.length\n    ? _('cannot_change_used_external_files', { values: { count } })\n    : undefined);\n\n/**\n * Find the entries using some files on a cloud storage service before the files are moved or\n * renamed, and refuse if the references in them can’t be updated: an entry is read-only, or the\n * media library is locked, as for an Open Authoring contributor, so no commit can be made. A file\n * on a service is hotlinked, so its download URL is what the entries store.\n * @param {ExternalAsset[]} assets Files.\n * @returns {Promise<ReferenceRewritePlan>} Plan to pass to `saveReferenceChanges()`.\n * @throws {Error} When the references can’t be updated, with a message saying why.\n */\nexport const planExternalReferenceRewrite = async (assets) => {\n  // A read-only entry is refused here\n  const plan = await planReferenceRewrite(assets.map(({ downloadURL }) => ({ url: downloadURL })));\n\n  const message = getExternalChangeBlockedMessage(\n    [...new Set(plan.usedEntries.flat())],\n    assets.length,\n  );\n\n  if (message) {\n    throw new Error(message);\n  }\n\n  return plan;\n};\n\n/**\n * Move a file to another path on a cloud storage service.\n * @param {MediaLibraryService} service Service, which can move files.\n * @param {ExternalAsset} asset File.\n * @param {string} path New path relative to the configured prefix.\n * @returns {Promise<ExternalAsset>} Moved file.\n */\nconst moveFile = (service, asset, path) =>\n  /** @type {NonNullable<MediaLibraryService['move']>} */ (service.move)(\n    asset,\n    path,\n    getFetchOptions(service),\n  );\n\n/**\n * Move files to other paths on a cloud storage service, one at a time as the services do, then\n * save the entries using them, pointing at the new URLs. If a move or the save fails, the files\n * moved so far are moved back, so the entries still find them; a file that can’t be moved back is\n * left where it is.\n * @param {object} args Arguments.\n * @param {MediaLibraryService} args.service Service, which can move files.\n * @param {{ asset: ExternalAsset, path: string }[]} args.moves Files and their new paths, relative\n * to the configured prefix.\n * @param {ReferenceRewritePlan} args.plan Entries using the files, in the same order, from\n * {@link planExternalReferenceRewrite}.\n * @returns {Promise<ExternalAsset[]>} Moved files, in the same order.\n * @throws {Error} When a move or the save fails.\n */\nexport const moveFilesWithReferences = ({ service, moves, plan }) =>\n  runWithUndo(\n    moves.map(({ asset, path }) => ({\n      // eslint-disable-next-line jsdoc/require-jsdoc\n      run: () => moveFile(service, asset, path),\n      // eslint-disable-next-line jsdoc/require-jsdoc\n      undo: (movedAsset) => moveFile(service, movedAsset, asset.description),\n    })),\n    (movedAssets) =>\n      saveReferenceChanges({\n        plan,\n        newURLs: movedAssets.map(({ downloadURL }) => downloadURL),\n        commitType: 'uploadMedia',\n      }),\n  );\n","import { RASTER_IMAGE_TYPES } from '$lib/services/utils/media/image';\nimport { sniffRasterImageFormat } from '$lib/services/utils/media/image/sniff';\n\n/**\n * Check whether the given file is a usable raster image. Only the formats every target browser is\n * expected to decode are checked, so a file the browser simply lacks a decoder for — a TIFF image,\n * a real HEIC image or a video with an unsupported codec — is never reported as corrupt.\n *\n * A file that declares one of the checked formats but fails to decode is either corrupt or\n * mislabeled, the most common case being a HEIC photo saved with a `.jpg` extension. Uploading it\n * would put a broken asset in the repository, so it’s rejected up front — unless HEIC conversion is\n * configured, in which case the photo is decoded by a library while it’s converted, which is where\n * a failure is reported.\n * @param {File} file File to be checked.\n * @param {object} [options] Options.\n * @param {boolean} [options.convertHEIC] Whether HEIC images are converted on upload.\n * @returns {Promise<boolean>} Whether the file is usable. `true` for any file that isn’t checked.\n */\nexport const isValidImage = async (file, { convertHEIC = false } = {}) => {\n  if (!(/** @type {string[]} */ (RASTER_IMAGE_TYPES).includes(file.type))) {\n    return true;\n  }\n\n  // Sniff the content: only Safari decodes HEIC natively, so `createImageBitmap()` below would\n  // reject a perfectly good photo that’s going to be converted\n  if ((await sniffRasterImageFormat(file)) === 'heic') {\n    return convertHEIC;\n  }\n\n  try {\n    // `createImageBitmap()` decodes the actual bytes rather than trusting the file’s type, and it\n    // does so off the main thread. It’s already used for image transformation.\n    (await createImageBitmap(file)).close();\n\n    return true;\n  } catch {\n    return false;\n  }\n};\n","import { formatFileName } from '$lib/services/assets/file-name';\nimport { hasCachedThumbnail } from '$lib/services/assets/info';\nimport { createAssetNameTemplate, fillAssetNameTemplate } from '$lib/services/assets/name';\nimport { uploadingAssets } from '$lib/services/assets/state';\nimport {\n  canConvertHEIC,\n  getDefaultMediaLibraryOptions,\n  transformFile,\n} from '$lib/services/integrations/media-libraries/default';\nimport { getGitHash } from '$lib/services/utils/file';\nimport { RASTER_IMAGE_TYPES } from '$lib/services/utils/media/image';\nimport { sniffRasterImageFormat } from '$lib/services/utils/media/image/sniff';\nimport { isValidImage } from '$lib/services/utils/media/image/validate';\nimport { createConcurrencyLimiter } from '$lib/services/utils/scheduling';\nimport { createRawState, createRootEffect } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { AssetNameContext } from '$lib/services/assets/name';\n * @import { ProcessedAssets } from '$lib/types/private';\n * @import { SharedMediaLibraryOptions } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} ProcessFileResult\n * @property {File} file Processed file.\n * @property {File | undefined} originalFile Pre-transformation file if a transformation was\n * applied.\n * @property {boolean} oversized Whether the file exceeds the maximum allowed size.\n * @property {boolean} invalid Whether the file is corrupt or mislabeled and therefore cannot be\n * uploaded.\n */\n\n/**\n * Check whether the given file is a usable image, without decoding it again if it has been decoded\n * already: a thumbnail cached for the same content, e.g. because the file was shown in the asset\n * selection dialog, is proof enough. Decoding a large photo takes a good fraction of a second, and\n * it’s done on every file in a batch at once.\n * @param {File} file File to be checked.\n * @param {boolean} convertHEIC Whether HEIC images are converted on upload.\n * @returns {Promise<boolean>} Whether the file is usable. `true` for any file that isn’t checked.\n * @see isValidImage\n */\nconst isUsableImage = async (file, convertHEIC) => {\n  // Only the formats `isValidImage()` decodes are worth looking up: hashing the file means reading\n  // it in full, which a video or an archive on its way to a cloud service would never be otherwise\n  if (!(/** @type {string[]} */ (RASTER_IMAGE_TYPES).includes(file.type))) {\n    return true;\n  }\n\n  // A thumbnail proves a HEIC photo could be decoded by the library, not that it can be uploaded,\n  // which depends on the configuration\n  if ((await sniffRasterImageFormat(file)) !== 'heic') {\n    try {\n      if (await hasCachedThumbnail(await getGitHash(file))) {\n        return true;\n      }\n    } catch {\n      // The file couldn’t be read or the cache couldn’t be queried; either way the decoding check\n      // below gives the answer, and a file that can’t be read is reported as invalid rather than\n      // failing the whole batch\n    }\n  }\n\n  return isValidImage(file, { convertHEIC });\n};\n\n/**\n * Process a file by applying renaming, slugification, transformation, and validation.\n * @param {File} file File to process.\n * @param {SharedMediaLibraryOptions} [options] Processing options.\n * @param {object} [extraOptions] Extra options.\n * @param {string} [extraOptions.nameTemplate] The `filename_template` media library option to\n * rename the file with right away. A file added to an entry is named when the entry is saved\n * instead, as the template can refer to the entry content.\n * @param {AssetNameContext} [extraOptions.nameContext] Entry values to fill the template with, for\n * a file that goes to a cloud storage service from an entry: unlike a file saved with the entry,\n * it’s uploaded, and has to be named, right away.\n * @returns {Promise<ProcessFileResult>} Result of processing the file. An invalid file is returned\n * as is, because there’s nothing to transform and it won’t be uploaded anyway.\n */\nexport const processFile = async (\n  file,\n  {\n    slugify_filename: slugifyFilename = false,\n    transformations,\n    max_file_size: maxFileSize = Infinity,\n  } = {},\n  { nameTemplate, nameContext } = {},\n) => {\n  // Check the original file object, whose hash is likely memoized already; a renamed copy would\n  // have to be read again to be hashed\n  const usable = await isUsableImage(file, canConvertHEIC(transformations));\n\n  if (nameTemplate || slugifyFilename) {\n    const { name, type, lastModified } = file;\n\n    let newName = nameTemplate\n      ? fillAssetNameTemplate({\n          nameTemplate: createAssetNameTemplate(nameTemplate),\n          originalName: name,\n          ...nameContext,\n        })\n      : name;\n\n    newName = formatFileName(newName, { slugificationEnabled: slugifyFilename });\n\n    file = new File([file], newName, { type, lastModified });\n  }\n\n  if (!usable) {\n    return { file, originalFile: undefined, oversized: false, invalid: true };\n  }\n\n  const preTransformFile = file;\n\n  if (transformations) {\n    try {\n      file = await transformFile(file, transformations);\n    } catch {\n      // A HEIC image that can’t be decoded; it can’t be uploaded as is, as nothing could display it\n      return { file, originalFile: undefined, oversized: false, invalid: true };\n    }\n  }\n\n  return {\n    file,\n    originalFile: file !== preTransformFile ? preTransformFile : undefined,\n    oversized: file.size > maxFileSize,\n    invalid: false,\n  };\n};\n\n/**\n * Sort processed files by whether they can be uploaded. A file that is both invalid and oversized\n * is reported as invalid only, as its size doesn’t matter once it can’t be uploaded anyway.\n * @param {ProcessFileResult[]} results Results of {@link processFile}.\n * @returns {{ validFiles: File[], oversizedFiles: File[], invalidFiles: File[] }} Processed files,\n * grouped.\n */\nexport const partitionProcessedFiles = (results) => ({\n  validFiles: results\n    .filter(({ oversized, invalid }) => !oversized && !invalid)\n    .map(({ file }) => file),\n  oversizedFiles: results\n    .filter(({ oversized, invalid }) => oversized && !invalid)\n    .map(({ file }) => file),\n  invalidFiles: results.filter(({ invalid }) => invalid).map(({ file }) => file),\n});\n\n/**\n * Limit the files being processed at the same time. Validating or transforming an image decodes it\n * at full size, so a large batch of photos processed all at once could run the tab out of memory.\n */\nconst limitFileProcessing = createConcurrencyLimiter(4);\n\n/**\n * Get the initial state of {@link processedAssets}, before any file is processed.\n * @returns {ProcessedAssets} State.\n */\nconst getInitialProcessedAssets = () => ({\n  processing: false,\n  validFiles: [],\n  oversizedFiles: [],\n  invalidFiles: [],\n  transformedFileMap: new WeakMap(),\n});\n\n/**\n * Assets currently being processed. Updated whenever {@link uploadingAssets} changes.\n * @type {{ current: ProcessedAssets }}\n */\nexport const processedAssets = createRawState(getInitialProcessedAssets());\n\ncreateRootEffect(() => {\n  // Set when a newer selection supersedes this run. Processing a file is asynchronous and can take\n  // a while — transcoding a large image, for one — so a run that started earlier may well settle\n  // after a later one has, and it must not overwrite the newer results with its own stale ones.\n  let superseded = false;\n  const originalFiles = uploadingAssets.current.files;\n  const { config } = getDefaultMediaLibraryOptions();\n\n  processedAssets.current = getInitialProcessedAssets();\n\n  (async () => {\n    if (originalFiles.length && config.transformations) {\n      processedAssets.current = { ...getInitialProcessedAssets(), processing: true };\n    }\n\n    // A file replacing an existing asset takes over its name, so it’s not renamed\n    const nameTemplate = uploadingAssets.current.originalAssets?.length\n      ? undefined\n      : config.filename_template;\n\n    // A file still waiting for its turn when a newer selection comes in is skipped, so it doesn’t\n    // hold up the files of that selection\n    const results = await Promise.all(\n      originalFiles.map((file) =>\n        limitFileProcessing(async () =>\n          superseded ? undefined : processFile(file, config, { nameTemplate }),\n        ),\n      ),\n    );\n\n    if (superseded) {\n      return;\n    }\n\n    const processedResults = /** @type {ProcessFileResult[]} */ (results);\n\n    processedAssets.current = {\n      processing: false,\n      ...partitionProcessedFiles(processedResults),\n      transformedFileMap: new WeakMap(\n        processedResults\n          .filter(({ originalFile }) => originalFile !== undefined)\n          .map(({ file, originalFile }) => [file, /** @type {File} */ (originalFile)]),\n      ),\n    };\n  })();\n\n  // Called before the next run starts\n  return () => {\n    superseded = true;\n  };\n});\n","import { assetUpdatesToast } from '$lib/services/assets/data';\nimport { saveReferenceChanges } from '$lib/services/assets/data/move';\nimport {\n  externalAssetCounts,\n  externalAssets,\n  externalAssetsError,\n  externalAssetsTruncated,\n  externalFolders,\n  focusedExternalAsset,\n  focusedExternalSubfolder,\n  getFetchOptions,\n  mergeUploadedExternalAssets,\n  pruneExternalAssetSelection,\n  selectedCloudService,\n  selectedExternalAssets,\n  selectedExternalDirPath,\n} from '$lib/services/assets/external';\nimport {\n  moveFilesWithReferences,\n  planExternalReferenceRewrite,\n} from '$lib/services/assets/external/move';\nimport { getAssetNameContext } from '$lib/services/assets/name';\nimport { partitionProcessedFiles, processFile } from '$lib/services/assets/process';\nimport { cmsConfig } from '$lib/services/config';\nimport { UPDATE_TOAST_DEFAULT_STATE } from '$lib/services/contents/collection/data';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { normalizeFileNameTemplate } from '$lib/services/integrations/media-libraries/default';\nimport { createPath, getDirName } from '$lib/services/utils/file';\nimport { createDeepState, createRawState } from '$lib/services/utils/state.svelte';\nimport { runWithUndo } from '$lib/services/utils/undo';\n\n/**\n * @import {\n * AssetSubfolder,\n * EntryDraft,\n * ExternalAsset,\n * ExternalFolderListing,\n * MediaLibraryFetchOptions,\n * MediaLibraryService,\n * } from '$lib/types/private';\n * @import { MediaField, SharedMediaLibraryOptions } from '$lib/types/public';\n */\n\n/**\n * State of the toast reporting the progress or failure of an operation on a cloud storage service,\n * or a warning about one that has only partly succeeded, like a move that has left the originals\n * behind. Successful operations are reported through {@link assetUpdatesToast}, like repository\n * assets.\n * @type {{ current: { show: boolean, status: 'info' | 'warning' | 'error', message: string } }}\n */\nexport const externalAssetsToast = createDeepState({ show: false, status: 'info', message: '' });\n\n/**\n * Files to be uploaded to the selected cloud storage service. The Asset Library processes these\n * once set, so that files dropped on the list, picked with the Upload button or chosen to replace\n * an existing asset are all handled the same way.\n * @type {{ current: { files: File[], originalAsset?: ExternalAsset } }}\n */\nexport const uploadingExternalAssets = createRawState({ files: [] });\n\n/**\n * Get the options shared by all the media libraries, which include the file size limit and\n * transformations applied before uploading. The field-level options, if any, are merged into the\n * global ones, as with `getMediaLibraryOptions()` in the media library integrations.\n * @param {MediaField} [fieldConfig] Configuration of the field the files are selected for.\n * @returns {SharedMediaLibraryOptions} Options.\n */\nexport const getSharedMediaLibraryOptions = (fieldConfig) => ({\n  ...cmsConfig.current?.media_libraries?.all,\n  ...fieldConfig?.media_libraries?.all,\n});\n\n/**\n * Show the toast reporting an error.\n * @param {string} message Message key.\n * @param {unknown} ex Exception, logged to the console.\n */\nconst reportError = (message, ex) => {\n  externalAssetsToast.current = { show: true, status: 'error', message };\n  // eslint-disable-next-line no-console\n  console.error(ex);\n};\n\n/**\n * Show the toast reporting a successful operation.\n * @param {'saved' | 'renamed' | 'deleted' | 'folderCreated' | 'folderRenamed' | 'folderDeleted'}\n * action Action.\n * @param {number} [count] Number of assets.\n */\nconst reportSuccess = (action, count = 1) => {\n  externalAssetsToast.current.show = false;\n  assetUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, [action]: true, count };\n};\n\n/**\n * Replace the asset list and record the number of assets for the sidebar.\n * @param {ExternalAsset[] | undefined} assets Assets, or `undefined` while being fetched.\n */\nconst setAssets = (assets) => {\n  const service = selectedCloudService.current;\n\n  externalAssets.current = assets;\n\n  if (assets && service) {\n    externalAssetCounts.current = {\n      ...externalAssetCounts.current,\n      [service.serviceId]: assets.length,\n    };\n  }\n};\n\n/**\n * Drop the given assets from the list, the selection and the focus, once a deletion has removed\n * them from the service.\n * @param {ExternalAsset[]} assets Assets that no longer exist.\n */\nconst forgetDeletedAssets = (assets) => {\n  const deletedIds = new Set(assets.map(({ id }) => id));\n\n  setAssets(externalAssets.current?.filter(({ id }) => !deletedIds.has(id)));\n  pruneExternalAssetSelection((id) => !deletedIds.has(id));\n};\n\n/**\n * Replace an asset in the list with an updated one, e.g. after renaming or replacing the file. The\n * focus and selection are updated as well.\n * @param {ExternalAsset} oldAsset Asset to be replaced.\n * @param {ExternalAsset} newAsset Updated asset.\n */\nconst updateAsset = (oldAsset, newAsset) => {\n  /**\n   * Swap the asset.\n   * @param {ExternalAsset} asset Asset in the list.\n   * @returns {ExternalAsset} Updated or unchanged asset.\n   */\n  const swap = (asset) => (asset.id === oldAsset.id ? newAsset : asset);\n\n  setAssets(externalAssets.current?.map(swap));\n  selectedExternalAssets.current = selectedExternalAssets.current.map(swap);\n\n  if (focusedExternalAsset.current?.id === oldAsset.id) {\n    focusedExternalAsset.current = newAsset;\n  }\n};\n\n/**\n * Drop the selected and focused assets, and the focused subfolder, that are no longer in the list,\n * e.g. after the list has been reloaded from the service.\n * @param {ExternalAsset[]} assets Assets in the list.\n * @param {string[]} [folders] Paths of the empty folders in the list.\n */\nconst pruneSelection = (assets, folders = []) => {\n  const ids = new Set(assets.map(({ id }) => id));\n\n  pruneExternalAssetSelection((id) => ids.has(id));\n\n  const focusedPath = focusedExternalSubfolder.current?.path;\n\n  // A folder exists as long as a file or a placeholder sits below it\n  if (\n    focusedPath !== undefined &&\n    !assets.some(({ description }) => description.startsWith(`${focusedPath}/`)) &&\n    !folders.some((path) => path === focusedPath || path.startsWith(`${focusedPath}/`))\n  ) {\n    focusedExternalSubfolder.current = undefined;\n  }\n};\n\n/**\n * Sequence number of the latest {@link loadExternalAssets} call, used to ignore the result of an\n * earlier call that is still in flight. A load can be started again while one is pending, e.g. when\n * the API key is saved on every keystroke that matches the service’s key pattern.\n */\nlet latestLoadId = 0;\n\n/**\n * Fetch the content of an asset on a cloud storage service. Unlike a repository asset, the file is\n * only available at its public URL, so this works only if the service allows cross-origin requests.\n * @param {ExternalAsset} asset Asset.\n * @returns {Promise<Blob>} File content.\n * @throws {Error} If the file could not be fetched.\n */\nexport const fetchExternalAssetBlob = async ({ downloadURL }) => {\n  const response = await fetch(downloadURL);\n\n  if (!response.ok) {\n    throw new Error(`The response returned with HTTP status ${response.status}.`);\n  }\n\n  return response.blob();\n};\n\n/**\n * Fetch the assets on the given cloud storage service and populate the list.\n * @param {MediaLibraryService} service Service.\n */\nexport const loadExternalAssets = async (service) => {\n  latestLoadId += 1;\n\n  const loadId = latestLoadId;\n\n  setAssets(undefined);\n  externalAssetsError.current = undefined;\n  externalAssetsTruncated.current = false;\n\n  try {\n    const fetchOptions = getFetchOptions(service);\n\n    // A service with folder support lists its empty folders along with the files\n    const {\n      assets,\n      folders,\n      truncated = false,\n    } = service.browse\n      ? await service.browse(fetchOptions)\n      : { assets: (await service.list?.(fetchOptions)) ?? [], folders: [] };\n\n    // Ignore the result if a different service has been selected or a newer load has been started\n    // in the meantime\n    if (selectedCloudService.current === service && loadId === latestLoadId) {\n      setAssets(assets);\n      externalFolders.current = folders;\n      externalAssetsTruncated.current = truncated;\n      pruneSelection(assets, folders);\n    }\n  } catch (ex) {\n    if (selectedCloudService.current === service && loadId === latestLoadId) {\n      setAssets([]);\n      externalFolders.current = [];\n      externalAssetsError.current = 'search_fetch_failed';\n      pruneSelection([]);\n    }\n\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  }\n};\n\n/**\n * Validate and transform files before they are uploaded to a cloud storage service, and sort out\n * the ones that can’t be uploaded, so the caller can tell the user.\n * @param {File[]} files Files to be uploaded.\n * @param {SharedMediaLibraryOptions} options Media library options, which include the file size\n * limit, the transformations to apply and the template to rename the files with.\n * @param {object} [extraOptions] Extra options.\n * @param {boolean} [extraOptions.replacing] Whether the file replaces an existing asset, taking\n * over its name, so the file isn’t renamed with the template.\n * @param {EntryDraft | null} [extraOptions.draft] Draft of the entry the files are added to, whose\n * current values fill the template. Without one, the entry tags get random values.\n * @returns {Promise<{ validFiles: File[], oversizedFileNames: string[], invalidFileNames: string[]\n * }>} Files that can be uploaded, and the names of the files that were rejected.\n */\nexport const prepareExternalUploads = async (files, options, { replacing = false, draft } = {}) => {\n  const nameTemplate = replacing ? undefined : normalizeFileNameTemplate(options.filename_template);\n\n  const nameContext =\n    nameTemplate && draft\n      ? getAssetNameContext({ draft, defaultLocaleSlug: getSlugs({ draft }).defaultLocaleSlug })\n      : undefined;\n\n  const processed = await Promise.all(\n    files.map((file) => processFile(file, options, { nameTemplate, nameContext })),\n  );\n\n  const { validFiles, oversizedFiles, invalidFiles } = partitionProcessedFiles(processed);\n\n  return {\n    validFiles,\n    oversizedFileNames: oversizedFiles.map(({ name }) => name),\n    invalidFileNames: invalidFiles.map(({ name }) => name),\n  };\n};\n\n/**\n * Upload files to the selected cloud storage service, or replace an existing asset with a file.\n * Files are validated and transformed according to the shared media library options first, and\n * any rejected file is reported back so the caller can tell the user.\n * @param {File[]} files Files to be uploaded.\n * @param {object} [options] Options.\n * @param {ExternalAsset} [options.originalAsset] Asset to be replaced by the first file.\n * @returns {Promise<{ oversizedFileNames: string[], invalidFileNames: string[] }>} Names of the\n * files that were rejected.\n */\nexport const uploadExternalAssets = async (files, { originalAsset } = {}) => {\n  const service = selectedCloudService.current;\n\n  const { validFiles, oversizedFileNames, invalidFileNames } = await prepareExternalUploads(\n    files,\n    getSharedMediaLibraryOptions(),\n    { replacing: !!originalAsset },\n  );\n\n  if (service && validFiles.length) {\n    externalAssetsToast.current = {\n      show: true,\n      status: 'info',\n      message: 'uploading_files_progress',\n    };\n\n    try {\n      // A new file goes to the folder being browsed; a replacement keeps the asset’s own path\n      const fetchOptions = {\n        ...getFetchOptions(service),\n        dirPath: selectedExternalDirPath.current,\n      };\n\n      if (originalAsset) {\n        if (service.replace) {\n          updateAsset(\n            originalAsset,\n            await service.replace(originalAsset, validFiles[0], fetchOptions),\n          );\n          reportSuccess('saved', 1);\n        }\n      } else if (service.upload) {\n        const uploaded = await service.upload(validFiles, fetchOptions);\n\n        setAssets(mergeUploadedExternalAssets(uploaded, externalAssets.current ?? []));\n        reportSuccess('saved', uploaded.length);\n      }\n    } catch (ex) {\n      reportError('uploading_files_failed', ex);\n      // The files are uploaded one by one, so those uploaded before the failure are on the service\n      // already. Reload the list to show them rather than leave them out until the next reload\n      await loadExternalAssets(service);\n    }\n  }\n\n  return { oversizedFileNames, invalidFileNames };\n};\n\n/**\n * Delete the given assets from the selected cloud storage service and remove them from the list.\n * @param {ExternalAsset[]} assets Assets to be deleted.\n * @returns {Promise<boolean>} Whether the assets have been deleted.\n */\nexport const deleteExternalAssets = async (assets) => {\n  const service = selectedCloudService.current;\n\n  if (!service?.delete || !assets.length) {\n    return false;\n  }\n\n  try {\n    await service.delete(assets, getFetchOptions(service));\n  } catch (ex) {\n    reportError('deleting_assets_failed', ex);\n    // Some of the assets may have been deleted before the failure, so reload the list rather than\n    // keep showing files that no longer exist\n    await loadExternalAssets(service);\n\n    return false;\n  }\n\n  forgetDeletedAssets(assets);\n  reportSuccess('deleted', assets.length);\n\n  return true;\n};\n\n/**\n * Rename the given asset on the selected cloud storage service and update the list. The entries\n * using the asset are pointed at its new URL in one commit; if that fails, the file is renamed back\n * so they still find it. The rename is refused up front if the entries can’t be updated, as one of\n * them is read-only or the media library is locked.\n * @param {ExternalAsset} asset Asset to be renamed.\n * @param {string} newName New file name.\n * @returns {Promise<ExternalAsset | undefined>} Renamed asset, or `undefined` if the asset could\n * not be renamed.\n */\nexport const renameExternalAsset = async (asset, newName) => {\n  const service = selectedCloudService.current;\n\n  if (!service?.rename) {\n    return undefined;\n  }\n\n  const fetchOptions = getFetchOptions(service);\n\n  try {\n    const plan = await planExternalReferenceRewrite([asset]);\n    const { rename } = service;\n\n    const [renamedAsset] = await runWithUndo(\n      [\n        {\n          // eslint-disable-next-line jsdoc/require-jsdoc\n          run: () => rename(asset, newName, fetchOptions),\n          // eslint-disable-next-line jsdoc/require-jsdoc\n          undo: (renamed) => rename(renamed, asset.fileName, fetchOptions),\n        },\n      ],\n      ([renamed]) =>\n        saveReferenceChanges({ plan, newURLs: [renamed.downloadURL], commitType: 'uploadMedia' }),\n    );\n\n    updateAsset(asset, renamedAsset);\n    reportSuccess('renamed', 1);\n\n    return renamedAsset;\n  } catch (ex) {\n    reportError('renaming_asset_failed', ex);\n\n    return undefined;\n  }\n};\n\n/**\n * Get the assets below a folder on the selected cloud storage service, at any depth, which are\n * what a rename moves along and a deletion removes.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @returns {ExternalAsset[]} Assets.\n */\nexport const getExternalSubfolderAssets = (dirPath) =>\n  (externalAssets.current ?? []).filter(({ description }) => description.startsWith(`${dirPath}/`));\n\n/**\n * Get a folder on the selected cloud storage service and every folder below it, which are what a\n * rename rebases and a deletion removes.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @returns {string[]} Folder paths.\n */\nconst getExternalFolderTree = (dirPath) =>\n  externalFolders.current.filter((path) => path === dirPath || path.startsWith(`${dirPath}/`));\n\n/**\n * Get the assets and the empty folders below a folder on the given cloud storage service, at any\n * depth, which are what a rename moves along and a deletion removes. They are listed from the\n * service in full when it can list a folder, as the asset list stops short of the end on a service\n * holding many files, and a folder operation working off it would leave files behind; otherwise\n * they are read off the list.\n * @param {MediaLibraryService} service Service.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @param {MediaLibraryFetchOptions} fetchOptions Fetch options.\n * @returns {Promise<ExternalFolderListing>} Assets and folder paths, including the folder itself\n * if it’s kept by a placeholder.\n */\nconst getExternalFolderContents = async (service, dirPath, fetchOptions) =>\n  service.listFolder\n    ? service.listFolder(dirPath, fetchOptions)\n    : { assets: getExternalSubfolderAssets(dirPath), folders: getExternalFolderTree(dirPath) };\n\n/**\n * Create an empty folder in the folder being browsed on the selected cloud storage service. The\n * service keeps a placeholder object for it, which is what the folder is listed from.\n * @param {string} name Folder name.\n * @returns {Promise<boolean>} Whether the folder has been created.\n */\nexport const createExternalFolder = async (name) => {\n  const service = selectedCloudService.current;\n\n  if (!service?.createFolder) {\n    return false;\n  }\n\n  const dirPath = createPath([selectedExternalDirPath.current, name]);\n\n  try {\n    await service.createFolder(dirPath, getFetchOptions(service));\n  } catch (ex) {\n    reportError('creating_folder_failed', ex);\n\n    return false;\n  }\n\n  externalFolders.current = [...externalFolders.current, dirPath];\n  reportSuccess('folderCreated');\n\n  return true;\n};\n\n/**\n * Rename a folder on the selected cloud storage service, which moves every asset below it, one by\n * one, along with the placeholder of any empty folder below it. The entries using the assets are\n * updated, and the rename is refused up front if they can’t be. The rename is refused if a folder\n * with the new name already exists, as its files would be overwritten. The list is reloaded from\n * the service afterwards, whether or not every move went through, so it never shows a file at a\n * path it no longer has.\n * @param {AssetSubfolder} subfolder Folder to be renamed.\n * @param {string} newName New folder name.\n * @returns {Promise<boolean>} Whether the folder has been renamed.\n */\nexport const renameExternalFolder = async ({ path: dirPath }, newName) => {\n  const service = selectedCloudService.current;\n\n  if (!service?.move || !service.createFolder || !service.deleteFolder) {\n    return false;\n  }\n\n  const newDirPath = createPath([getDirName(dirPath), newName]);\n  /**\n   * Get the path of a file or folder once the folder has been renamed.\n   * @param {string} path Current path.\n   * @returns {string} New path.\n   */\n  const rebase = (path) => `${newDirPath}${path.slice(dirPath.length)}`;\n  const fetchOptions = getFetchOptions(service);\n  // Checked up front, as reloading the list lets go of a focused folder that is no longer there\n  const focused = focusedExternalSubfolder.current?.path === dirPath;\n\n  externalAssetsToast.current = { show: true, status: 'info', message: 'renaming_folder' };\n\n  try {\n    const { assets, folders } = await getExternalFolderContents(service, dirPath, fetchOptions);\n    // The destination is listed in full too, as the list the user picked the name against can be\n    // cut short on a service holding many files, and moving the files onto an existing folder\n    // would overwrite its files with the same names\n    const destination = await getExternalFolderContents(service, newDirPath, fetchOptions);\n\n    if (destination.assets.length || destination.folders.length) {\n      throw new Error(`A folder named “${newName}” already exists in the folder.`);\n    }\n\n    // The entries using the files are pointed at their new URLs once they have moved, or the files\n    // are moved back\n    await moveFilesWithReferences({\n      service,\n      moves: assets.map((asset) => ({ asset, path: rebase(asset.description) })),\n      plan: await planExternalReferenceRewrite(assets),\n    });\n\n    // A placeholder can’t be moved, so a new one is made and the old one removed. The renamed\n    // folder itself gets one only if it had one, i.e. it held no file\n    // eslint-disable-next-line no-restricted-syntax\n    for (const path of folders) {\n      // eslint-disable-next-line no-await-in-loop\n      await service.createFolder(rebase(path), fetchOptions);\n      // eslint-disable-next-line no-await-in-loop\n      await service.deleteFolder(path, fetchOptions);\n    }\n  } catch (ex) {\n    reportError('renaming_folder_failed', ex);\n    await loadExternalAssets(service);\n\n    return false;\n  }\n\n  await loadExternalAssets(service);\n\n  // Keep the Info pane on the folder under its new name\n  if (focused) {\n    focusedExternalSubfolder.current = { name: newName, path: newDirPath };\n  }\n\n  reportSuccess('folderRenamed');\n\n  return true;\n};\n\n/**\n * Delete a folder on the selected cloud storage service along with every asset below it, and the\n * placeholder of any empty folder below it, including its own.\n * @param {AssetSubfolder} subfolder Folder to be deleted.\n * @returns {Promise<boolean>} Whether the folder has been deleted.\n */\nexport const deleteExternalFolder = async ({ path: dirPath }) => {\n  const service = selectedCloudService.current;\n\n  if (!service?.delete || !service.deleteFolder) {\n    return false;\n  }\n\n  const fetchOptions = getFetchOptions(service);\n  /** @type {ExternalAsset[]} */\n  let assets = [];\n  /** @type {string[]} */\n  let folders = [];\n\n  externalAssetsToast.current = { show: true, status: 'info', message: 'deleting_folder' };\n\n  try {\n    ({ assets, folders } = await getExternalFolderContents(service, dirPath, fetchOptions));\n\n    await service.delete(assets, fetchOptions);\n\n    // eslint-disable-next-line no-restricted-syntax\n    for (const path of folders) {\n      // eslint-disable-next-line no-await-in-loop\n      await service.deleteFolder(path, fetchOptions);\n    }\n  } catch (ex) {\n    reportError('deleting_folder_failed', ex);\n    // Some of the files may have been deleted before the failure, so reload the list rather than\n    // keep showing files that no longer exist\n    await loadExternalAssets(service);\n\n    return false;\n  }\n\n  forgetDeletedAssets(assets);\n  externalFolders.current = externalFolders.current.filter((path) => !folders.includes(path));\n\n  // The Info pane has nothing to describe once the folder is gone\n  if (focusedExternalSubfolder.current?.path === dirPath) {\n    focusedExternalSubfolder.current = undefined;\n  }\n\n  reportSuccess('folderDeleted');\n\n  return true;\n};\n","import { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @typedef {Map<string, string>} NormalizedValueCache\n */\n\n/**\n * Normalized value caches that outlive a single search, keyed by the object the values belong to,\n * typically an entry. Normalizing every field of every entry is what a search mostly spends its\n * time on, and the values rarely change between two searches, so the work is kept for as long as\n * the object is around; a saved or reloaded entry is a new object, so its cache starts over.\n * @type {WeakMap<object, NormalizedValueCache>}\n */\nconst persistentCaches = new WeakMap();\n\n/**\n * Get the normalized value cache for the given object, creating it on first use.\n * @param {object} owner Object the values belong to.\n * @returns {NormalizedValueCache} Cache.\n */\nexport const getNormalizedValueCache = (owner) =>\n  getOrCreate(persistentCaches, owner, () => new Map());\n\n/**\n * Match a letter of a script where the combining marks following it are accents or optional vowel\n * points a query can leave out — Latin, Greek, Hebrew and Arabic, or Cyrillic in its own group —\n * along with the run of marks. Elsewhere a mark is part of the spelling — Japanese kana voicing\n * marks (`ビ` vs `ヒ`), Devanagari vowel signs, Thai tone marks — so stripping it would make\n * unrelated words match. The run is matched with the letter rather than with a lookbehind, which\n * would scan the run back from every mark in it and take quadratic time over a long one.\n */\nconst ACCENT_REGEX = new RegExp(\n  `([${['Latin', 'Greek', 'Hebrew', 'Arabic']\n    .map((script) => `\\\\p{Script=${script}}`)\n    .join('')}])\\\\p{M}+|(\\\\p{Script=Cyrillic})(\\\\p{M}+)`,\n  'gv',\n);\n\n/**\n * Match the combining marks of a run following a Cyrillic letter that are stripped: all but the\n * breve of `й` and `ў`, which are letters of their own, unlike `ё`, commonly written `е`.\n */\nconst CYRILLIC_ACCENT_REGEX = /[\\p{M}--[\\u0306]]/gv;\n\n/**\n * Strip the accents from the given match of {@link ACCENT_REGEX}.\n * @param {string} _match Whole match.\n * @param {string | undefined} base Letter of a script whose marks are all stripped.\n * @param {string | undefined} cyrillic Cyrillic letter.\n * @param {string | undefined} marks Marks following the Cyrillic letter.\n * @returns {string} Letter with the marks it keeps.\n */\nconst stripAccents = (_match, base, cyrillic, marks) =>\n  base ?? `${cyrillic}${/** @type {string} */ (marks).replace(CYRILLIC_ACCENT_REGEX, '')}`;\n\n/**\n * Match a string made of ASCII characters only.\n */\n// eslint-disable-next-line no-control-regex\nconst ASCII_REGEX = /^[\\x00-\\x7F]*$/;\n\n/**\n * Normalize the given string for search value comparison: fold accents like `é` to `e` and\n * lowercase it. Since `transliterate` is slow, we only apply basic normalization. The accents are\n * stripped from the decomposed (NFD) string, then the result is composed (NFC) again, so that a\n * Hangul syllable like `학` isn’t left split into its letters, where `하` would match it.\n * @param {string} value Original value.\n * @returns {string} Normalized value.\n * @see https://stackoverflow.com/q/990904\n */\nexport const normalize = (value) => {\n  value = value.trim();\n\n  if (!value) {\n    return '';\n  }\n\n  // ASCII text has nothing to decompose or strip, so it only has to be lowercased, which saves most\n  // of the work for the bulk of the content of many sites. Not with `toLocaleLowerCase()`, which\n  // can follow the browser’s locale, e.g. turning `I` into `ı` without a dot in Turkish\n  if (ASCII_REGEX.test(value)) {\n    return value.toLowerCase();\n  }\n\n  return value.normalize('NFD').replace(ACCENT_REGEX, stripAccents).toLowerCase().normalize('NFC');\n};\n\n/**\n * Get a normalized value, using the provided per-search cache when available.\n * @param {string} value Original value.\n * @param {NormalizedValueCache} [normalizedValueCache] Normalized value cache.\n * @returns {string} Normalized value.\n */\nconst getNormalizedValue = (value, normalizedValueCache = undefined) => {\n  if (!normalizedValueCache) {\n    return normalize(value);\n  }\n\n  const cachedValue = normalizedValueCache.get(value);\n\n  if (cachedValue !== undefined) {\n    return cachedValue;\n  }\n\n  const normalizedValue = normalize(value);\n\n  normalizedValueCache.set(value, normalizedValue);\n\n  return normalizedValue;\n};\n\n/**\n * Check if the given label matches the search terms.\n * @param {object} args Arguments.\n * @param {string} args.value Value to check against.\n * @param {string} args.terms Search terms.\n * @param {NormalizedValueCache} [args.normalizedValueCache] Normalized value cache.\n * @returns {boolean} Result of the match check.\n */\nexport const hasMatch = ({ value, terms, normalizedValueCache = undefined }) =>\n  getNormalizedValue(value, normalizedValueCache).includes(terms);\n\n/**\n * Split the search terms into normalized, unique, whitespace-separated tokens, so that a query like\n * “annual report cover” can match a file named `annual-report-cover-photo.png`, where the words are\n * present but not separated by spaces.\n * @param {string} terms Search terms.\n * @returns {string[]} Tokens. Empty if the terms are blank.\n */\nexport const tokenize = (terms) => [...new Set(normalize(terms).split(/\\s+/).filter(Boolean))];\n\n/**\n * Check if the value contains every one of the given tokens, in any order.\n * @param {object} args Arguments.\n * @param {string} args.value Value to check against.\n * @param {string[]} args.tokens Search tokens from {@link tokenize}. An empty list matches any\n * value, so callers should bail out early when the search terms are blank.\n * @param {NormalizedValueCache} [args.normalizedValueCache] Normalized value cache.\n * @returns {boolean} Result of the match check.\n */\nexport const hasAllMatches = ({ value, tokens, normalizedValueCache = undefined }) => {\n  const normalizedValue = getNormalizedValue(value, normalizedValueCache);\n\n  return tokens.every((token) => normalizedValue.includes(token));\n};\n","import { _ } from '@sveltia/i18n';\nimport { untrack } from 'svelte';\n\nimport {\n  externalAssets,\n  externalAssetSearchTerms,\n  externalFolders,\n  focusedExternalSubfolder,\n  hasFolderSupport,\n  pruneExternalAssetSelection,\n  selectedCloudService,\n  selectedExternalDirPath,\n} from '$lib/services/assets/external';\nimport { LINKED_FILES_SERVICE_ID } from '$lib/services/assets/external/linked';\nimport { listSubfolders } from '$lib/services/assets/subfolders';\nimport { currentView } from '$lib/services/assets/view/settings';\nimport { getNameSortValue } from '$lib/services/assets/view/sort';\nimport { groupItems, sortItemsByKey } from '$lib/services/common/view';\nimport { getNormalizedValueCache, hasMatch, normalize } from '$lib/services/search/util';\nimport { getBaseName, getDirName } from '$lib/services/utils/file';\nimport {\n  createDerivedState,\n  createRootEffect,\n  createStableDerivedState,\n} from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * AssetFolderSummary,\n * AssetSubfolder,\n * ExternalAsset,\n * FilteringConditions,\n * GroupingConditions,\n * SortingConditions,\n * SortKey,\n * } from '$lib/types/private';\n * @import { ViewGroup } from '$lib/types/public';\n */\n\n/**\n * Keys the assets on a cloud storage service can be sorted by, and the value types that determine\n * the wording of the sort order labels. Unlike repository assets, these don’t have commit info, but\n * the services report when a file was last modified and its size.\n * @type {Record<string, 'date' | 'number' | undefined>}\n */\nconst EXTERNAL_ASSET_SORT_KEY_TYPES = {\n  name: undefined,\n  last_modified: 'date',\n  size: 'number',\n};\n\n/**\n * Keys the assets on a cloud storage service can be sorted by.\n */\nexport const EXTERNAL_ASSET_SORT_KEYS = Object.keys(EXTERNAL_ASSET_SORT_KEY_TYPES);\n\n/**\n * List of available sort keys with localized labels. `_()` reads the current app locale, so the\n * list is recomputed when the locale changes.\n * @type {{ readonly current: SortKey[] }}\n */\nexport const externalAssetSortKeys = createDerivedState(() =>\n  Object.entries(EXTERNAL_ASSET_SORT_KEY_TYPES).map(([key, type]) => ({\n    key,\n    label: _(`sort_keys.${key}`),\n    type,\n  })),\n);\n\n/**\n * Get an asset’s property value for sorting.\n * @param {ExternalAsset} asset Asset.\n * @param {string} key Sort key.\n * @returns {string | number} Value.\n */\nexport const getSortValue = (asset, key) => {\n  if (key === 'last_modified') {\n    return asset.lastModified?.getTime() ?? 0;\n  }\n\n  if (key === 'size') {\n    return asset.size ?? 0;\n  }\n\n  return getNameSortValue(asset.fileName);\n};\n\n/**\n * Sort the given assets.\n * @param {ExternalAsset[]} assets Asset list.\n * @param {SortingConditions} [conditions] Sorting conditions.\n * @returns {ExternalAsset[]} Sorted asset list.\n */\nexport const sortExternalAssets = (assets, { key, order } = {}) => {\n  if (!key || !order || !EXTERNAL_ASSET_SORT_KEYS.includes(key)) {\n    return assets;\n  }\n\n  return sortItemsByKey([...assets], (asset) => getSortValue(asset, key), key === 'name', order);\n};\n\n/**\n * Filter the given assets. Only the `fileType` filter shown in the Asset Library is supported.\n * @param {ExternalAsset[]} assets Asset list.\n * @param {FilteringConditions} [conditions] Filtering conditions.\n * @returns {ExternalAsset[]} Filtered asset list.\n */\nexport const filterExternalAssets = (assets, { field, pattern } = { field: '', pattern: '' }) => {\n  if (field !== 'fileType') {\n    return assets;\n  }\n\n  return assets.filter(({ kind }) => kind === pattern);\n};\n\n/**\n * Get an asset’s property value for grouping. Only the `domain` of the file’s URL is supported: the\n * files linked from entries can be hosted anywhere, and a long list is easier to go through host by\n * host.\n * @param {ExternalAsset} asset Asset.\n * @param {string} field Group field.\n * @returns {string | undefined} Value, or `undefined` if the field is unknown or the URL can’t be\n * parsed, so that the asset goes to the Other group.\n */\nexport const getGroupValue = (asset, field) => {\n  if (field !== 'domain') {\n    return undefined;\n  }\n\n  try {\n    return new URL(asset.downloadURL).hostname;\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Group the given assets.\n * @param {ExternalAsset[]} assets Asset list.\n * @param {GroupingConditions | null} [conditions] Grouping conditions.\n * @returns {Record<string, ExternalAsset[]>} Grouped assets, where key is a group name, displayed\n * with `getGroupLabel()`, and value is an asset list. Without conditions, all the assets are in a\n * single group named `*`.\n */\nexport const groupExternalAssets = (assets, conditions) =>\n  groupItems(assets, conditions, getGroupValue);\n\n/**\n * Grouping options offered for the selected location. The files linked from entries can be grouped\n * by domain; the files on a cloud storage service are all on the same host, so they have none.\n * `_()` reads the current app locale, so the list is recomputed when the locale changes.\n * @type {{ readonly current: ViewGroup[] }}\n */\nexport const externalAssetViewGroups = createDerivedState(() =>\n  selectedCloudService.current?.serviceId === LINKED_FILES_SERVICE_ID\n    ? [{ label: _('domain'), field: 'domain' }]\n    : [],\n);\n\n/**\n * Narrow down the given assets by the search terms. The file name and description, which is the\n * path of the file on the service, are matched.\n * @param {ExternalAsset[]} assets Asset list.\n * @param {string} terms Search terms.\n * @returns {ExternalAsset[]} Matching asset list.\n */\nexport const searchExternalAssets = (assets, terms) => {\n  const normalizedTerms = normalize(terms);\n\n  if (!normalizedTerms) {\n    return assets;\n  }\n\n  // The normalized names are kept with each asset, as the search runs on every keystroke\n  return assets.filter((asset) => {\n    const normalizedValueCache = getNormalizedValueCache(asset);\n\n    return (\n      hasMatch({ value: asset.fileName, terms: normalizedTerms, normalizedValueCache }) ||\n      hasMatch({ value: asset.description, terms: normalizedTerms, normalizedValueCache })\n    );\n  });\n};\n\n/**\n * List the immediate subfolders of a folder on a cloud storage service with folder support, read\n * off the paths of the files below it and the empty folders kept by a placeholder.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Folder path relative to the configured prefix. An empty string for\n * the root.\n * @param {ExternalAsset[]} args.assets Assets on the service, whose `description` is the file path.\n * @param {string[]} args.folders Paths of the empty folders on the service.\n * @returns {AssetSubfolder[]} Subfolders, sorted by name.\n */\nexport const getExternalSubfolders = ({ dirPath, assets, folders }) =>\n  listSubfolders({\n    dirPath,\n    paths: [\n      ...assets.map(({ description }) => description),\n      // An empty folder is given with a trailing slash, as it has no file to be read off\n      ...folders.map((path) => `${path}/`),\n    ],\n  });\n\n/**\n * Get the assets right in a folder on a cloud storage service with folder support, leaving out the\n * ones in its subfolders.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Folder path relative to the configured prefix. An empty string for\n * the root.\n * @param {ExternalAsset[]} args.assets Assets on the service, whose `description` is the file path.\n * @returns {ExternalAsset[]} Assets in the folder.\n */\nexport const getExternalAssetsInDir = ({ dirPath, assets }) =>\n  assets.filter(({ description }) => getDirName(description) === dirPath);\n\n/**\n * Get the label of a folder on a cloud storage service, which is the folder path, or the service\n * name at the root.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Folder path relative to the configured prefix. An empty string for\n * the root.\n * @param {string} args.serviceLabel Service name.\n * @returns {string} Label, e.g. `/images/2024` or `Amazon S3`.\n */\nexport const getExternalFolderLabel = ({ dirPath, serviceLabel }) =>\n  dirPath ? `/${dirPath}` : serviceLabel;\n\n/**\n * Whether the selected cloud storage service is being browsed folder by folder: it has folder\n * support, and nothing is being searched for. A search looks through the whole service instead,\n * listing the matches with their paths.\n * @type {{ readonly current: boolean }}\n */\nexport const browsingExternalFolders = createDerivedState(\n  () => hasFolderSupport(selectedCloudService.current) && !externalAssetSearchTerms.current,\n);\n\n/**\n * Subfolders of the folder being browsed on the selected cloud storage service, listed ahead of\n * the assets. Empty unless the service is browsed folder by folder.\n * @type {{ readonly current: AssetSubfolder[] }}\n */\nexport const listedExternalSubfolders = createDerivedState(() => {\n  if (!browsingExternalFolders.current) {\n    return [];\n  }\n\n  return getExternalSubfolders({\n    dirPath: selectedExternalDirPath.current,\n    assets: externalAssets.current ?? [],\n    folders: externalFolders.current,\n  });\n});\n\n/**\n * Sorting conditions of the current view. This and the filtering conditions below are picked out\n * of {@link currentView} one by one, so replacing the view to switch between list and grid, or to\n * group the assets, doesn’t sort and filter them all over again.\n */\nconst sortConditions = createStableDerivedState(() => currentView.current.sort);\n/**\n * Filtering conditions of the current view. See {@link sortConditions}.\n */\nconst filterConditions = createStableDerivedState(() => currentView.current.filter);\n\n/**\n * Sorted and filtered assets on the selected cloud storage service. While the service is browsed\n * folder by folder, only the assets right in the folder being browsed are listed. Sorting is the\n * costliest step, so it’s done here rather than after the search, which runs on every keystroke.\n * @type {{ readonly current: ExternalAsset[] }}\n */\nconst sortedExternalAssets = createDerivedState(() => {\n  let assets = externalAssets.current ?? [];\n\n  if (browsingExternalFolders.current) {\n    assets = getExternalAssetsInDir({ dirPath: selectedExternalDirPath.current, assets });\n  }\n\n  return filterExternalAssets(\n    sortExternalAssets(assets, sortConditions.current),\n    filterConditions.current,\n  );\n});\n\n/**\n * Sorted, filtered and searched assets on the selected cloud storage service. The Asset Library’s\n * {@link currentView} is shared with repository folders, so the view type, sort order and file\n * type filter are remembered per service just like per folder.\n * @type {{ readonly current: ExternalAsset[] }}\n */\nexport const listedExternalAssets = createDerivedState(() =>\n  searchExternalAssets(sortedExternalAssets.current, externalAssetSearchTerms.current),\n);\n\n/**\n * What the folder info panel describes: the focused subfolder, or the folder being browsed on the\n * selected cloud storage service — the service itself at the root.\n * @type {{ readonly current: AssetFolderSummary | undefined }}\n */\nexport const externalFolderSummary = createDerivedState(() => {\n  const subfolder = focusedExternalSubfolder.current;\n\n  if (subfolder) {\n    const { name, path } = subfolder;\n    const assets = externalAssets.current ?? [];\n\n    return {\n      name,\n      path,\n      folderCount: getExternalSubfolders({\n        dirPath: path,\n        assets,\n        folders: externalFolders.current,\n      }).length,\n      assetCount: getExternalAssetsInDir({ dirPath: path, assets }).length,\n    };\n  }\n\n  const service = selectedCloudService.current;\n\n  // The panel is only shown with a service selected\n  if (!service) {\n    return undefined;\n  }\n\n  // A search looks through the whole service rather than the folder being browsed\n  const browsing = browsingExternalFolders.current;\n  const dirPath = browsing ? selectedExternalDirPath.current : '';\n\n  return {\n    name: getBaseName(dirPath) || service.serviceLabel,\n    // The service root has no path of its own\n    path: dirPath || undefined,\n    folderCount: browsing ? listedExternalSubfolders.current.length : undefined,\n    assetCount: listedExternalAssets.current.length,\n  };\n});\n\n/**\n * {@link listedExternalAssets} grouped as the list shows them.\n * @type {{ readonly current: Record<string, ExternalAsset[]> }}\n */\nexport const externalAssetGroups = createDerivedState(() =>\n  groupExternalAssets(listedExternalAssets.current, currentView.current.group),\n);\n\n/**\n * Map from asset ID to the asset’s row index in the list, used by list rows to resolve their\n * `aria-rowindex` in O(1). The index is counted across the groups rather than within each one, as\n * the rows of every group make up one grid. The subfolders come first, so they offset the index.\n * Like `listedAssetIndexMap` for repository assets.\n * @type {{ readonly current: Map<string, number> }}\n */\nexport const listedExternalAssetIndexMap = createDerivedState(() => {\n  const offset = listedExternalSubfolders.current.length;\n\n  return new Map(\n    Object.values(externalAssetGroups.current)\n      .flat(1)\n      .map(({ id }, index) => [id, index + offset]),\n  );\n});\n\n/**\n * Drop the selected and focused assets that are no longer listed, so that the toolbar actions\n * never operate on an asset the user can’t see, e.g. one hidden by the search terms or the file\n * type filter. The selection survives a change of the sort order, as the assets stay listed.\n */\nexport const pruneHiddenAssets = () => {\n  const listedIds = new Set(listedExternalAssets.current.map(({ id }) => id));\n\n  untrack(() => pruneExternalAssetSelection((id) => listedIds.has(id)));\n};\n\ncreateRootEffect(pruneHiddenAssets);\n","<!--\n  @component\n  Implement a panel that allows searching media files from an external media library and selecting\n  one for an image/file entry field.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState, Infobar } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import AssetPath from '$lib/components/assets/browser/asset-path.svelte';\n  import PickerBreadcrumb from '$lib/components/assets/browser/picker-breadcrumb.svelte';\n  import SimpleImageGridItem from '$lib/components/assets/browser/simple-image-grid-item.svelte';\n  import SimpleImageGrid from '$lib/components/assets/browser/simple-image-grid.svelte';\n  import SubfolderNameDialog from '$lib/components/assets/list/subfolder-name-dialog.svelte';\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import CloudServiceAuth from '$lib/components/assets/shared/cloud-service-auth.svelte';\n  import DropZone from '$lib/components/assets/shared/drop-zone.svelte';\n  import RejectedFilesAlertDialog from '$lib/components/assets/shared/rejected-files-alert-dialog.svelte';\n  import {\n    getSelectionWithResource,\n    trackInsertedExternalAssets,\n  } from '$lib/services/assets/browser/select-assets-dialog.svelte';\n  import { runAssetCommit } from '$lib/services/assets/data/commit';\n  import { getFetchOptions, mergeUploadedExternalAssets } from '$lib/services/assets/external';\n  import {\n    fetchExternalAssetBlob,\n    getSharedMediaLibraryOptions,\n    prepareExternalUploads,\n  } from '$lib/services/assets/external/data';\n  import {\n    getExternalAssetsInDir,\n    getExternalFolderLabel,\n    getExternalSubfolders,\n  } from '$lib/services/assets/external/view';\n  import { getRelativePath, getTakenNames } from '$lib/services/assets/subfolders';\n  import { selectAssetsView } from '$lib/services/contents/editor';\n  import { env } from '$lib/services/user/env.svelte';\n  import { createLatestGuard } from '$lib/services/utils/scheduling';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import {\n   * EntryDraft,\n   * ExternalAsset,\n   * MediaLibraryAssetKind,\n   * MediaLibraryFetchOptions,\n   * MediaLibraryService,\n   * SelectedResource,\n   * } from '$lib/types/private';\n   * @import { MediaField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {MediaField} [fieldConfig] File/Image field configuration.\n   * @property {EntryDraft | null} [draft] Draft of the entry the files are selected for, whose\n   * values fill the `filename_template` option of an uploaded file.\n   * @property {MediaLibraryAssetKind} [kind] Asset kind.\n   * @property {boolean} [multiple] Whether to allow selecting multiple assets.\n   * @property {string} [searchTerms] Search terms for filtering assets.\n   * @property {MediaLibraryService} serviceProps Media library service details.\n   * @property {string} [gridId] The `id` attribute of the inner listbox.\n   * @property {SelectedResource[]} selectedResources Selected resources.\n   */\n\n  /** @type {Props} */\n  let {\n    kind,\n    fieldConfig = undefined,\n    draft = undefined,\n    multiple = false,\n    searchTerms = '',\n    serviceProps,\n    gridId = undefined,\n    selectedResources = $bindable([]),\n  } = $props();\n\n  const {\n    serviceType = 'stock_assets',\n    serviceId = '',\n    serviceLabel = '',\n    hotlinking = false,\n    authType = 'api_key',\n    init,\n    list,\n    browse,\n    search,\n    upload,\n    createFolder,\n    trackDownload,\n  } = $derived(serviceProps);\n\n  // Use the grid view for Picsum as it doesn’t provide description for the assets, and the list\n  // view relies on the description to show asset information.\n  const viewType = $derived(serviceId === 'picsum' ? 'grid' : selectAssetsView.current?.type);\n  const isStockAssets = $derived(serviceType === 'stock_assets');\n  const allMediaLibraryOptions = $derived(getSharedMediaLibraryOptions(fieldConfig));\n  /* v8 ignore start -- only read to report a file exceeding the configured size */\n  const maxSize = $derived(\n    /** @type {number} */ (allMediaLibraryOptions.max_file_size ?? Infinity),\n  );\n  /* v8 ignore stop */\n\n  let hasConfig = $state(true);\n  let hasAuthInfo = $state(false);\n  let apiKey = $state('');\n  let userName = $state('');\n  let password = $state('');\n  /**\n   * Assets listed by the service. Only ever replaced as a whole, so the list, which can run to\n   * thousands of files on a cloud storage service, isn’t wrapped in a deep proxy.\n   * @type {ExternalAsset[] | null}\n   */\n  let listedAssets = $state.raw(null);\n  /**\n   * Paths of the empty folders on a service with folder support, each kept by a placeholder.\n   * @type {string[]}\n   */\n  let folders = $state([]);\n  /**\n   * Path of the folder being browsed on a service with folder support, relative to the configured\n   * prefix. Empty at the root.\n   */\n  let dirPath = $state('');\n  /**\n   * Whether the listing stopped short of the end, as the service holds more files than are listed\n   * at once, so some files are left out.\n   */\n  let truncated = $state(false);\n  let newFolderDialogOpen = $state(false);\n  /** @type {string | undefined} */\n  let error = $state();\n  /** @type {RejectedFilesAlertDialog | undefined} */\n  let rejectedFilesAlert = $state();\n\n  /** @type {MediaLibraryFetchOptions} */\n  const listFetchOptions = $derived({ kind, fieldConfig, apiKey, userName, password });\n  /**\n   * Search query. The search terms are shared by all the services in the dialog, so a service that\n   * can’t search, like Lorem Picsum, ignores the terms entered for another service.\n   */\n  const searchQuery = $derived(search ? searchTerms.trim() : '');\n  /**\n   * Whether the service is browsed folder by folder, like a repository folder in the picker. A\n   * search looks through the whole service instead, listing the matches with their paths.\n   */\n  const browsing = $derived(!!browse && !searchQuery);\n  /**\n   * Assets shown in the panel: those right in the folder being browsed, or every asset listed.\n   * @type {ExternalAsset[]}\n   */\n  const panelAssets = $derived.by(() => {\n    const assets = listedAssets ?? [];\n\n    return browsing ? getExternalAssetsInDir({ dirPath, assets }) : assets;\n  });\n  const subfolders = $derived(\n    browsing ? getExternalSubfolders({ dirPath, assets: listedAssets ?? [], folders }) : [],\n  );\n  /** Names already taken in the folder being browsed, which a new folder can’t be given. */\n  const takenNames = $derived(\n    getTakenNames({ subfolders, fileNames: panelAssets.map(({ fileName }) => fileName) }),\n  );\n  /** The folder being browsed, named after the service at the root. */\n  const folderLabel = $derived(getExternalFolderLabel({ dirPath, serviceLabel }));\n\n  /**\n   * Guard for {@link getAssets}. A request made earlier, e.g. a search for the terms typed before,\n   * can come back after a later one, and its result must not replace the latest one.\n   */\n  const requestGuard = createLatestGuard();\n\n  /**\n   * Search or list assets from the external media library.\n   * @param {string} query Search query, which is only given to a service that can search.\n   */\n  const getAssets = async (query) => {\n    const isLatest = requestGuard.next();\n\n    listedAssets = null;\n    error = undefined;\n    truncated = false;\n\n    try {\n      /** @type {ExternalAsset[]} */\n      let assets;\n      /** @type {string[] | undefined} */\n      let emptyFolders;\n      let incomplete = false;\n\n      if (query) {\n        assets = await /** @type {NonNullable<typeof search>} */ (search)(query, listFetchOptions);\n      } else if (browse) {\n        // A service with folder support lists its empty folders along with the files\n        ({\n          assets,\n          folders: emptyFolders,\n          truncated: incomplete = false,\n        } = await browse(listFetchOptions));\n      } else {\n        assets = (await list?.(listFetchOptions)) ?? [];\n      }\n\n      if (!isLatest()) {\n        return;\n      }\n\n      listedAssets = assets;\n      truncated = incomplete;\n\n      if (emptyFolders) {\n        folders = emptyFolders;\n      }\n    } catch (ex) {\n      if (!isLatest()) {\n        return;\n      }\n\n      error = 'search_fetch_failed';\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    }\n  };\n\n  /**\n   * Download the selected asset, if needed, and return the file and credit. If hotlinking is\n   * required by the service, just return the URL instead of downloading the file.\n   * @param {ExternalAsset} asset Selected asset.\n   * @returns {Promise<SelectedResource | undefined>} The selected resource with the file or URL.\n   * @todo Support video files.\n   */\n  const getResource = async (asset) => {\n    const { downloadURL: url, fileName, credit } = asset;\n\n    if (hotlinking) {\n      return { url, credit };\n    }\n\n    try {\n      const blob = await fetchExternalAssetBlob(asset);\n\n      return { url, credit, file: new File([blob], fileName, { type: blob.type }) };\n    } catch (ex) {\n      error = 'image_fetch_failed';\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    }\n\n    return undefined;\n  };\n\n  /**\n   * Whether files can be uploaded, which takes a service that supports it and the credentials,\n   * which the user may not have provided yet.\n   * @returns {boolean} Result.\n   */\n  export const canUpload = () => hasAuthInfo && !!upload;\n\n  /**\n   * Handle `Drop` event to upload files.\n   * @param {File[]} files Dropped files.\n   */\n  export const uploadFiles = async (files) => {\n    // A request without the credentials would only fail\n    if (!canUpload()) {\n      return;\n    }\n\n    const prepared = await prepareExternalUploads(files, allMediaLibraryOptions, { draft });\n\n    files = prepared.validFiles;\n    rejectedFilesAlert?.report(prepared);\n\n    if (!files.length) {\n      return;\n    }\n\n    const { ok } = await runAssetCommit(\n      async () => {\n        // The files go to the folder being browsed, or the one the search started from\n        const uploaded = await /** @type {NonNullable<typeof upload>} */ (upload)(files, {\n          ...listFetchOptions,\n          dirPath,\n        });\n\n        const resources = await Promise.all(uploaded.map((asset) => getResource(asset)));\n\n        // The uploaded files, listed first and selected, confirm the upload\n        selectedResources = resources.filter((r) => !!r).slice(0, multiple ? undefined : 1);\n        listedAssets = mergeUploadedExternalAssets(uploaded, listedAssets ?? []);\n      },\n      { progress: 'uploading_files_progress', failure: 'uploading_files_failed' },\n    );\n\n    if (!ok) {\n      // The files are uploaded one by one, so those uploaded before the failure are on the service\n      // already. Reload the list to show them rather than leave them out until the next reload\n      getAssets(searchQuery);\n    }\n  };\n\n  /**\n   * Whether a folder can be created in the folder being browsed, which takes a service with folder\n   * support that can create one, while it’s browsed rather than searched.\n   * @returns {boolean} Result.\n   */\n  export const canCreateFolder = () => browsing && !!createFolder;\n\n  /**\n   * Open the New Folder dialog.\n   */\n  export const showNewFolderDialog = () => {\n    newFolderDialogOpen = true;\n  };\n\n  /**\n   * Create a folder in the folder being browsed, which is then listed along with the others.\n   * @param {string} name Folder name.\n   */\n  const createNewFolder = (name) => {\n    const path = dirPath ? `${dirPath}/${name}` : name;\n\n    runAssetCommit(\n      async () => {\n        await /** @type {NonNullable<typeof createFolder>} */ (createFolder)(\n          path,\n          listFetchOptions,\n        );\n        folders = [...folders, path];\n      },\n      { failure: 'creating_folder_failed' },\n    );\n  };\n\n  /**\n   * URLs of the selected resources, built once per selection change so that each listed item can\n   * check its own selection without going through the whole selection.\n   */\n  const selectedURLs = $derived(new Set(selectedResources.map(({ url }) => url)));\n\n  /**\n   * Check if the given asset is already selected.\n   * @param {ExternalAsset} asset The asset to check.\n   * @returns {boolean} `true` if the asset is selected, `false` otherwise.\n   */\n  const isSelected = (asset) => selectedURLs.has(asset.downloadURL);\n\n  /**\n   * The latest selection state the list box reported for each asset, keyed by download URL. The\n   * resource of a selected asset is only ready after an `await`, by which time the asset may have\n   * been deselected: the list box reports the asset that loses a single selection after the one\n   * that gets it, if it comes later in the list, and the user can move on while a file downloads.\n   * @type {Map<string, boolean>}\n   */\n  // eslint-disable-next-line svelte/prefer-svelte-reactivity\n  const requestedSelection = new Map();\n\n  /**\n   * The assets picked from the list, keyed by download URL, so the service can be told which ones\n   * have been inserted. An asset stays here once deselected: only the selected resources count.\n   * @type {Map<string, ExternalAsset>}\n   */\n  // eslint-disable-next-line svelte/prefer-svelte-reactivity\n  const pickedAssets = new Map();\n\n  /**\n   * Let the service know the selected assets have been inserted, if its API guidelines require it,\n   * like Unsplash’s. The requests are not awaited, so they never hold up the insertion.\n   */\n  export const trackDownloads = () => {\n    trackInsertedExternalAssets({\n      trackDownload,\n      resources: selectedResources,\n      assets: pickedAssets,\n      options: listFetchOptions,\n    });\n  };\n\n  /**\n   * Handle selection change of an asset.\n   * @param {ExternalAsset} asset The asset whose selection changed.\n   * @param {boolean} selected `true` if the asset is now selected, `false` otherwise.\n   */\n  const onSelectionChange = async (asset, selected) => {\n    const { downloadURL } = asset;\n\n    if (selected && !multiple) {\n      // A new single selection replaces the earlier one, including a pick hidden by a search or\n      // left in another folder, which the list box doesn’t deselect, and a pick still downloading\n      [...requestedSelection.keys()].forEach((url) => {\n        requestedSelection.set(url, false);\n      });\n    }\n\n    requestedSelection.set(downloadURL, selected);\n\n    if (selected) {\n      const resource = await getResource(asset);\n\n      // Read the selection again, as it may have changed during the `await`\n      if (resource && requestedSelection.get(downloadURL)) {\n        pickedAssets.set(downloadURL, asset);\n        selectedResources = getSelectionWithResource({\n          resources: selectedResources,\n          resource,\n          /**\n           * Check if a selected resource comes from the same asset.\n           * @param {SelectedResource} r Selected resource.\n           * @returns {boolean} Result.\n           */\n          isSame: (r) => r.url === downloadURL,\n          multiple,\n        });\n      }\n    } else {\n      selectedResources = selectedResources.filter((r) => r.url !== downloadURL);\n    }\n  };\n\n  /**\n   * Load the stored credentials. Fetching the assets is left to the effect below, which reacts to\n   * `hasAuthInfo` being set.\n   */\n  const loadAuthInfo = () => {\n    const options = getFetchOptions(serviceProps);\n\n    apiKey = options.apiKey;\n    userName = options.userName;\n    password = options.password;\n    hasAuthInfo = authType === 'none' || !!apiKey || !!password;\n  };\n\n  onMount(() => {\n    (async () => {\n      if (typeof init === 'function') {\n        hasConfig = false;\n        hasConfig = await init();\n      }\n\n      if (!hasConfig) {\n        return;\n      }\n\n      loadAuthInfo();\n      listedAssets = null;\n    })();\n  });\n\n  watch(\n    () => [searchQuery, hasAuthInfo],\n    () => {\n      if (hasAuthInfo) {\n        getAssets(searchQuery);\n      }\n    },\n  );\n</script>\n\n{#snippet breadcrumb()}\n  {#if browsing}\n    <PickerBreadcrumb\n      rootLabel={serviceLabel}\n      path={dirPath}\n      onNavigate={(path) => {\n        dirPath = path;\n      }}\n    />\n  {/if}\n{/snippet}\n\n{#snippet content()}\n  {#if !listedAssets}\n    <EmptyState>\n      <span role=\"alert\">{_(searchQuery ? 'searching' : 'loading')}</span>\n    </EmptyState>\n  {:else if !panelAssets.length && !subfolders.length}\n    {@render breadcrumb()}\n    <EmptyState>\n      <span role=\"alert\">{_('no_files_found')}</span>\n    </EmptyState>\n  {:else}\n    {@render breadcrumb()}\n    {#if truncated}\n      <Infobar\n        status=\"warning\"\n        dismissible={false}\n        --sui-infobar-border-width=\"0 0 1px\"\n        --sui-infobar-message-justify-content=\"center\"\n      >\n        {_('external_assets_truncated')}\n      </Infobar>\n    {/if}\n    <div role=\"none\" class=\"grid-wrapper\">\n      <SimpleImageGrid\n        {viewType}\n        {gridId}\n        {multiple}\n        {kind}\n        {subfolders}\n        onOpenSubfolder={({ path }) => {\n          dirPath = path;\n        }}\n        items={panelAssets}\n        itemKey=\"id\"\n      >\n        {#snippet renderItem(/** @type {ExternalAsset} */ asset)}\n          {@const { id, previewURL, description, kind: _kind } = asset}\n          <SimpleImageGridItem\n            value={id}\n            ariaLabel={description}\n            {viewType}\n            {multiple}\n            selected={isSelected(asset)}\n            onChange={({ detail: { selected } }) => {\n              onSelectionChange(asset, selected);\n            }}\n          >\n            <AssetPreview\n              kind={_kind}\n              src={previewURL}\n              alt={description}\n              variant=\"tile\"\n              crossorigin=\"anonymous\"\n            />\n            {#if viewType === 'list' || (!env.isSmallScreen && !isStockAssets)}\n              <!-- The path is relative to the folder being browsed -->\n              <AssetPath\n                {...isStockAssets\n                  ? { caption: description }\n                  : { path: browsing ? getRelativePath(description, dirPath) : description }}\n              />\n            {/if}\n          </SimpleImageGridItem>\n        {/snippet}\n      </SimpleImageGrid>\n    </div>\n  {/if}\n{/snippet}\n\n{#if hasAuthInfo}\n  {#if error}\n    <EmptyState>\n      <span role=\"alert\">{_(`assets_dialog.error.${error}`)}</span>\n    </EmptyState>\n  {:else if upload}\n    <DropZone accept={fieldConfig?.accept} multiple onDrop={({ files }) => uploadFiles(files)}>\n      {@render content()}\n    </DropZone>\n  {:else}\n    {@render content()}\n  {/if}\n{:else if hasConfig}\n  <CloudServiceAuth {serviceProps} onAuth={loadAuthInfo} />\n{:else}\n  <EmptyState>\n    <span role=\"alert\">{_('cloud_storage.invalid')}</span>\n  </EmptyState>\n{/if}\n\n<RejectedFilesAlertDialog bind:this={rejectedFilesAlert} {maxSize} />\n\n{#if createFolder}\n  <SubfolderNameDialog\n    bind:open={newFolderDialogOpen}\n    title={_('new_folder')}\n    okLabel={_('new_folder_create')}\n    description={_('new_folder_description', { values: { folder: folderLabel } })}\n    {takenNames}\n    onSubmit={(name) => {\n      createNewFolder(name);\n    }}\n  />\n{/if}\n\n<style>\n  .grid-wrapper {\n    overflow-y: auto;\n    height: 100%;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState } from '@sveltia/ui';\n  import { stripSlashes } from '@sveltia/utils/string';\n\n  import AssetPath from '$lib/components/assets/browser/asset-path.svelte';\n  import SimpleImageGridItem from '$lib/components/assets/browser/simple-image-grid-item.svelte';\n  import SimpleImageGrid from '$lib/components/assets/browser/simple-image-grid.svelte';\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import { getAssetKey } from '$lib/services/assets';\n  import { getSelectionWithResource } from '$lib/services/assets/browser/select-assets-dialog.svelte';\n  import { getNormalizedValueCache, hasAllMatches, tokenize } from '$lib/services/search/util';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import {\n   * Asset,\n   * AssetSubfolder,\n   * MediaLibraryAssetKind,\n   * SelectedResource,\n   * ViewType,\n   * } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [multiple] Whether to allow selecting multiple assets.\n   * @property {MediaLibraryAssetKind} [kind] Kind of the assets being picked, which names the\n   * list: images, or files of any kind if `undefined`.\n   * @property {Asset[]} [assets] Asset list.\n   * @property {ViewType} [viewType] View type.\n   * @property {string} [searchTerms] Search terms for filtering assets.\n   * @property {string} [basePath] Path to an asset folder, if any folder is selected.\n   * @property {string} [gridId] The `id` attribute of the inner listbox.\n   * @property {boolean} [checkerboard] Whether to show a checkerboard background below a\n   * transparent image.\n   * @property {string} [emptyMessage] Message shown when there is nothing to list, in place of the\n   * default “No files found” message.\n   * @property {SelectedResource[]} [selectedResources] Selected resources.\n   * @property {AssetSubfolder[]} [subfolders] Subfolders of the folder being browsed, listed ahead\n   * of the assets.\n   * @property {(detail: { asset: Asset }) => void} [onSelect] Custom `select` event handler.\n   * @property {(subfolder: AssetSubfolder) => void} [onOpenSubfolder] Called when a subfolder is\n   * opened.\n   * @property {string[]} [selectedSubfolderPaths] Paths of the selected subfolders.\n   * @property {(subfolder: AssetSubfolder, selected: boolean) => void} [onSelectSubfolder] Called\n   * with a subfolder and whether it’s now selected, when a folder is to be picked.\n   */\n\n  /** @type {Props} */\n  let {\n    multiple = false,\n    kind = undefined,\n    assets = [],\n    viewType = 'grid',\n    searchTerms = '',\n    basePath = undefined,\n    gridId = undefined,\n    checkerboard = false,\n    emptyMessage = undefined,\n    selectedResources = $bindable([]),\n    subfolders = [],\n    onSelect = undefined,\n    onOpenSubfolder = undefined,\n    selectedSubfolderPaths = [],\n    onSelectSubfolder = undefined,\n  } = $props();\n\n  // Split the search terms into individual words for filtering purposes\n  const tokens = $derived(tokenize(searchTerms));\n\n  // The items are built separately from the filtering, so typing a search term reuses them instead\n  // of creating a new object for every asset. Each item wraps the asset rather than copying it, so\n  // the preview and the selection get the original asset object\n  /** @type {{ asset: Asset, relPath: string, key: string }[]} */\n  const listedItems = $derived(\n    assets.map((asset) => {\n      const { folder, name, path } = asset;\n\n      // Compute the relative path for display and filtering purposes. If the asset is in a folder,\n      // we want to show the path relative to that folder. If the asset is not in a folder, we just\n      // show the file name.\n      const relPath =\n        basePath && !folder.entryRelative ? stripSlashes(path.replace(basePath, '')) : name;\n\n      // An unsaved asset can share a path with the saved asset it’s going to overwrite, so each\n      // item is identified by a unique key instead, avoiding Svelte `each` key conflicts\n      return { asset, relPath, key: getAssetKey(asset) };\n    }),\n  );\n\n  const filteredItems = $derived(\n    tokens.length\n      ? // Filter assets by search terms in the relative path, keeping each normalized path for the\n        // next keystroke\n        listedItems.filter((item) =>\n          hasAllMatches({\n            value: item.relPath,\n            tokens,\n            normalizedValueCache: getNormalizedValueCache(item),\n          }),\n        )\n      : listedItems,\n  );\n\n  /**\n   * Keys of the selected assets, built once per selection change so that each listed item can check\n   * its own selection without going through the whole selection.\n   */\n  const selectedAssetKeys = $derived(\n    new Set(selectedResources.flatMap(({ asset }) => (asset ? [getAssetKey(asset)] : []))),\n  );\n\n  /**\n   * Check if the given asset is already selected.\n   * @param {Asset} asset The asset to check.\n   * @returns {boolean} `true` if the asset is selected, `false` otherwise.\n   */\n  const isSelected = (asset) => selectedAssetKeys.has(getAssetKey(asset));\n\n  /**\n   * Handle selection change of an asset.\n   * @param {Asset} asset The asset whose selection changed.\n   * @param {boolean} selected `true` if the asset is now selected, `false` otherwise.\n   */\n  const onSelectionChange = (asset, selected) => {\n    const key = getAssetKey(asset);\n    /**\n     * Check if a selected resource holds the given asset.\n     * @param {SelectedResource} resource Selected resource.\n     * @returns {boolean} Result.\n     */\n    const isSame = (resource) => !!resource.asset && getAssetKey(resource.asset) === key;\n\n    if (selected) {\n      selectedResources = getSelectionWithResource({\n        resources: selectedResources,\n        resource: { asset },\n        isSame,\n        multiple,\n      });\n      onSelect?.({ asset });\n    } else {\n      selectedResources = selectedResources.filter((r) => !isSame(r));\n    }\n  };\n</script>\n\n{#if filteredItems.length || subfolders.length}\n  <div role=\"none\" class=\"grid-wrapper\">\n    <SimpleImageGrid\n      {multiple}\n      {gridId}\n      {viewType}\n      {kind}\n      {subfolders}\n      {onOpenSubfolder}\n      {selectedSubfolderPaths}\n      {onSelectSubfolder}\n      items={filteredItems}\n      itemKey=\"key\"\n    >\n      {#snippet renderItem(/** @type {{ asset: Asset, relPath: string, key: string }} */ item)}\n        {@const { asset, key, relPath } = item}\n        {@const { kind: assetKind, unsaved } = asset}\n        <SimpleImageGridItem\n          value={key}\n          ariaLabel={relPath}\n          {viewType}\n          {multiple}\n          selected={isSelected(asset)}\n          onChange={({ detail: { selected } }) => {\n            onSelectionChange(asset, selected);\n          }}\n        >\n          {#if viewType === 'grid' && unsaved}\n            <div role=\"none\" class=\"unsaved\">{_('assets_dialog.unsaved')}</div>\n          {/if}\n          <AssetPreview kind={assetKind} {asset} alt={relPath} variant=\"tile\" {checkerboard} />\n          {#if !env.isSmallScreen || viewType === 'list'}\n            <AssetPath path={relPath}>\n              {#if viewType === 'list' && unsaved}\n                <div role=\"none\" class=\"unsaved\">{_('assets_dialog.unsaved')}</div>\n              {/if}\n            </AssetPath>\n          {/if}\n        </SimpleImageGridItem>\n      {/snippet}\n    </SimpleImageGrid>\n  </div>\n{:else}\n  <EmptyState>\n    <span role=\"none\">{emptyMessage ?? _('no_files_found')}</span>\n  </EmptyState>\n{/if}\n\n<style>\n  .grid-wrapper {\n    overflow-y: auto;\n    height: 100%;\n\n    :global {\n      [role='listbox'] {\n        background-color: transparent;\n\n        &.grid {\n          .unsaved {\n            position: absolute;\n            inset-block-start: 8px;\n            inset-inline-end: 8px;\n            z-index: 1;\n          }\n        }\n\n        &.list {\n          .name {\n            display: flex;\n            gap: 8px;\n            align-items: center;\n            justify-content: space-between;\n\n            /* `Option` pins button descendants to `flex: none`, so a long name can’t shrink */\n            .truncated-text {\n              flex: auto;\n              min-width: 0;\n            }\n          }\n        }\n      }\n    }\n  }\n\n  .unsaved {\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    border-color: var(--sui-info-border-color);\n    border-radius: 4px;\n    padding: 2px 6px;\n    color: var(--sui-info-foreground-color);\n    background-color: var(--sui-info-background-color);\n    font-size: var(--sui-font-size-small);\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { untrack } from 'svelte';\n\n  import AssetsPanel from '$lib/components/assets/browser/assets-panel.svelte';\n  import PickerBreadcrumb from '$lib/components/assets/browser/picker-breadcrumb.svelte';\n  import DropZone from '$lib/components/assets/shared/drop-zone.svelte';\n  import { selectAssetsView } from '$lib/services/contents/editor';\n\n  /**\n   * @import {\n   * Asset,\n   * AssetSubfolder,\n   * MediaLibraryAssetKind,\n   * SelectedResource,\n   * } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [multiple] Whether to allow selecting multiple assets.\n   * @property {MediaLibraryAssetKind} [kind] Kind of the assets being picked: images, or files of\n   * any kind if `undefined`.\n   * @property {boolean} [selectFolder] Whether a folder is being selected instead of files, which\n   * takes no dropped files and lists subfolders only.\n   * @property {boolean} [uploadDisabled] Whether nothing can be uploaded to the directory being\n   * browsed, such as a read-only folder or one the CMS itself is served from, which then takes no\n   * dropped files.\n   * @property {string | undefined} [accept] Accepted file type specifiers.\n   * @property {Asset[]} [assets] Asset list.\n   * @property {string} [searchTerms] Search terms for filtering assets.\n   * @property {string} [basePath] Path to an asset folder, if any folder is selected.\n   * @property {string} [folderLabel] Label of the selected folder, shown at the start of the\n   * breadcrumb while a subfolder is browsed.\n   * @property {string} [subfolderPath] Path of the subfolder being browsed, relative to the\n   * folder. Empty at the folder root.\n   * @property {AssetSubfolder[]} [subfolders] Subfolders of the directory being browsed.\n   * @property {SelectedResource[]} selectedResources Selected resources.\n   * @property {(detail: { files: File[] }) => void} [onDrop] Custom `Drop` event handler.\n   * @property {(subfolderPath: string) => void} [onNavigate] Called with the relative path of an\n   * ancestor folder to go back to from the breadcrumb, or an empty string for the folder root.\n   * @property {(subfolder: AssetSubfolder) => void} [onOpenSubfolder] Called when a listed\n   * subfolder is opened.\n   * @property {string[]} [selectedSubfolderPaths] Paths of the selected subfolders.\n   * @property {(subfolder: AssetSubfolder, selected: boolean) => void} [onSelectSubfolder] Called\n   * with a subfolder and whether it’s now selected, when a folder is to be picked.\n   */\n\n  /** @type {Props} */\n  let {\n    multiple = false,\n    kind = undefined,\n    selectFolder = false,\n    uploadDisabled = false,\n    accept = undefined,\n    assets = [],\n    searchTerms = '',\n    basePath = undefined,\n    folderLabel = '',\n    subfolderPath = '',\n    subfolders = [],\n    selectedResources = $bindable([]),\n    onDrop,\n    onNavigate = undefined,\n    onOpenSubfolder = undefined,\n    selectedSubfolderPaths = [],\n    onSelectSubfolder = undefined,\n  } = $props();\n\n  /** @type {DropZone | undefined} */\n  let dropZone = $state();\n\n  $effect(() => {\n    if (!selectedResources.length) {\n      untrack(() => {\n        dropZone?.reset();\n      });\n    }\n  });\n</script>\n\n<!--\n  Dropped files are not filtered by `accept` here, just like the files chosen with the Upload\n  button: the field checks the format once the inserted files have been processed, which is the\n  only point a transformation could have changed it.\n-->\n<DropZone\n  bind:this={dropZone}\n  disabled={selectFolder || uploadDisabled}\n  {multiple}\n  {accept}\n  filterDroppedFiles={false}\n  {onDrop}\n>\n  <div role=\"none\" class=\"wrapper\">\n    <PickerBreadcrumb rootLabel={folderLabel} path={subfolderPath} {onNavigate} />\n    <div role=\"none\" class=\"panel\">\n      <AssetsPanel\n        {multiple}\n        {kind}\n        {assets}\n        viewType={selectAssetsView.current?.type}\n        {searchTerms}\n        {basePath}\n        {subfolders}\n        gridId=\"select-assets-grid\"\n        checkerboard={true}\n        emptyMessage={selectFolder ? _('assets_dialog.no_subfolders') : undefined}\n        bind:selectedResources\n        {onOpenSubfolder}\n        {selectedSubfolderPaths}\n        {onSelectSubfolder}\n      />\n    </div>\n  </div>\n</DropZone>\n\n<style>\n  .wrapper {\n    display: flex;\n    flex-direction: column;\n    height: 100%;\n  }\n\n  .panel {\n    flex: auto;\n    overflow: hidden;\n  }\n</style>\n","<!--\n  @component\n  List of the locations the Select Assets dialog can pick assets from: the repository folders, the\n  cloud storage services and Enter URL, and the stock asset providers. It’s a list box on a large\n  screen, and a drop-down list on a small one.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, Listbox, Option, OptionGroup, Select } from '@sveltia/ui';\n\n  import { isFolderOffered } from '$lib/services/assets/browser/select-assets-dialog.svelte';\n  import {\n    activated as cloudinaryActivated,\n    dialogOpen as cloudinaryDialogOpen,\n  } from '$lib/services/integrations/media-libraries/cloud/cloudinary';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { AssetLibraryFolderMap, MediaLibraryService } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} libraryName Name of the selected location.\n   * @property {AssetLibraryFolderMap} assetLibraryFolderMap Default asset library folder map.\n   * @property {boolean} showRepository Whether to offer the repository folders.\n   * @property {boolean} selectFolder Whether a folder is to be selected instead of files, which\n   * limits the repository folders to those that can be browsed by subfolder.\n   * @property {[string, MediaLibraryService][]} cloudServiceEntries Cloud storage services offered.\n   * @property {boolean} showURLInput Whether to offer Enter URL.\n   * @property {[string, MediaLibraryService][]} stockAssetProviderEntries Stock asset providers\n   * offered.\n   * @property {string} controlsId ID of the content pane the selected location is shown in.\n   * @property {(name: string) => void} onChange Function called with the name of the location\n   * selected by the user.\n   */\n\n  /** @type {Props} */\n  let {\n    libraryName,\n    assetLibraryFolderMap,\n    showRepository,\n    selectFolder,\n    cloudServiceEntries,\n    showURLInput,\n    stockAssetProviderEntries,\n    controlsId,\n    onChange,\n  } = $props();\n\n  const Selector = $derived(env.isSmallScreen ? Select : Listbox);\n</script>\n\n{#snippet locationOption(\n  /**\n   * @type {{\n   * name: string,\n   * label: string,\n   * icon: string,\n   * onclick?: () => void,\n   * }}\n   */ { name, label, icon, onclick },\n)}\n  <Option {name} {label} selected={libraryName === name} {onclick}>\n    {#snippet startIcon()}\n      <Icon name={icon} />\n    {/snippet}\n  </Option>\n{/snippet}\n\n<Selector\n  class=\"tabs\"\n  ariaLabel={_('assets_dialog.locations')}\n  aria-controls={controlsId}\n  filterThreshold={-1}\n  onChange={(event) => {\n    onChange(event.detail.name);\n  }}\n>\n  {#if showRepository}\n    <OptionGroup label={_('asset_location.repository')}>\n      {#each Object.entries(assetLibraryFolderMap) as [id, entry] (id)}\n        {#if isFolderOffered(entry, selectFolder)}\n          {@render locationOption({\n            name: `default-${id}`,\n            label: entry.folder?.label || _(`assets_dialog.folder.${id}`),\n            icon: 'folder',\n          })}\n        {/if}\n      {/each}\n    </OptionGroup>\n  {/if}\n  {#if showURLInput || !!cloudServiceEntries.length}\n    <OptionGroup label={_('asset_location.external')}>\n      {#each cloudServiceEntries as [, { serviceId, serviceLabel }] (serviceId)}\n        {@render locationOption({\n          name: serviceId,\n          label: serviceLabel,\n          icon: 'cloud',\n          /**\n           * Open the Cloudinary widget, once activated, when its location is clicked.\n           */\n          onclick: () => {\n            if (serviceId === 'cloudinary' && cloudinaryActivated.current) {\n              cloudinaryDialogOpen.current = true;\n            }\n          },\n        })}\n      {/each}\n      {#if showURLInput}\n        {@render locationOption({\n          name: 'enter-url',\n          label: _('assets_dialog.enter_url'),\n          icon: 'link_2',\n        })}\n      {/if}\n    </OptionGroup>\n  {/if}\n  {#if stockAssetProviderEntries.length}\n    <OptionGroup label={_('asset_location.stock_photos')}>\n      {#each stockAssetProviderEntries as [serviceId, { serviceLabel }] (serviceId)}\n        {@render locationOption({\n          name: serviceId,\n          label: serviceLabel,\n          icon: 'photo_camera_back',\n        })}\n      {/each}\n    </OptionGroup>\n  {/if}\n</Selector>\n","import { getImmutable } from '$lib/services/api/immutable';\nimport { buildPreviewData } from '$lib/services/api/preview-data';\nimport { getValueMapSnapshots } from '$lib/services/contents/draft/value-map.svelte';\n\n/**\n * @import { MapOf } from 'immutable';\n * @import { EntryDraft } from '$lib/types/private';\n * @import { CustomField } from '$lib/types/public';\n */\n\n/**\n * Cache of Immutable Maps converted from field configurations. Field configurations are immutable\n * objects created once during config normalization, so they can be safely used as `WeakMap` keys,\n * and entries are garbage collected along with the configuration.\n * @type {WeakMap<CustomField, MapOf<CustomField>>}\n */\nconst fieldConfigMapCache = new WeakMap();\n\n/**\n * Convert a field configuration to an Immutable Map for a React component, reusing the previous\n * result for the same configuration object. Returning a stable reference avoids deep-converting the\n * configuration on every render and lets `React.memo()` and `shouldComponentUpdate()` in custom\n * widgets skip unnecessary re-renders.\n * @param {CustomField} fieldConfig Field configuration.\n * @returns {MapOf<CustomField>} Immutable Map of the field configuration.\n */\nexport const getFieldConfigMap = (fieldConfig) => {\n  const cached = fieldConfigMapCache.get(fieldConfig);\n\n  if (cached) {\n    return cached;\n  }\n\n  const map = /** @type {MapOf<CustomField>} */ (getImmutable().fromJS(fieldConfig));\n\n  fieldConfigMapCache.set(fieldConfig, map);\n\n  return map;\n};\n\n/**\n * Short-lived cache of {@link buildPreviewData} results, keyed by draft and locale. Building the\n * data walks the whole entry and deep-converts it to Immutable Maps, so when several custom field\n * controls and previews render in response to one change, they should share a computation instead\n * of repeating it.\n *\n * The cache is only valid for the current microtask: the entry draft is mutated in place rather\n * than replaced, so the draft object cannot be used to detect changes, and holding the data any\n * longer would risk serving stale content.\n * @type {Map<EntryDraft, Map<string, ReturnType<typeof buildPreviewData>>>}\n */\nconst previewDataCache = new Map();\n/** Whether a microtask to flush {@link previewDataCache} has already been scheduled. */\nlet previewDataCacheFlushScheduled = false;\n\n/**\n * Get the preview data for the given draft, reusing the result computed earlier in the same\n * microtask when available.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft entry state.\n * @param {string} args.locale Current locale.\n * @returns {ReturnType<typeof buildPreviewData>} Preview data.\n */\nexport const getPreviewData = ({ draft, locale }) => {\n  const draftCache = previewDataCache.get(draft) ?? new Map();\n  const cached = draftCache.get(locale);\n\n  if (cached) {\n    return cached;\n  }\n\n  // The shared snapshots are read rather than the value maps themselves, so a control only depends\n  // on their versions rather than on every value, and a locale that hasn’t changed isn’t copied\n  const data = buildPreviewData({\n    draft: { ...draft, currentValues: getValueMapSnapshots(draft) },\n    locale: /** @type {any} */ (locale),\n  });\n\n  draftCache.set(locale, data);\n  previewDataCache.set(draft, draftCache);\n\n  if (!previewDataCacheFlushScheduled) {\n    previewDataCacheFlushScheduled = true;\n\n    queueMicrotask(() => {\n      previewDataCache.clear();\n      previewDataCacheFlushScheduled = false;\n    });\n  }\n\n  return data;\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { loadImmutable } from '$lib/services/api/immutable';\nimport { getFieldConfigMap } from '$lib/services/contents/fields/custom/helpers';\n\n/**\n * @import { EntryValidityState, InternalLocaleCode } from '$lib/types/private';\n * @import { CustomField, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Registry of custom field component instances keyed by locale and field key path. These instances\n * may have an `isValid()` method for custom validation.\n * @type {Map<string, any>}\n */\nconst customFieldInstances = new Map();\n/**\n * Cache of validation results keyed by locale and field key path. `pending` is `true` while an\n * async `isValid()` call is in flight, so that a save attempt can wait for the final verdict.\n * @type {Map<string, { valid: boolean, message?: string, pending: boolean }>}\n */\nconst validationCache = new Map();\n/**\n * In-flight validation promises keyed by locale and field key path, used to await pending results\n * before saving.\n * @type {Map<string, Promise<void>>}\n */\nconst pendingValidations = new Map();\n/**\n * Monotonically increasing sequence number per locale and field key path, used to discard results\n * from stale `isValid()` calls that resolve out of order.\n * @type {Map<string, number>}\n */\nconst validationSequences = new Map();\n/**\n * Get the internal cache key for a custom field instance.\n * @param {InternalLocaleCode} locale Locale code.\n * @param {FieldKeyPath} keyPath Field key path.\n * @returns {string} Cache key.\n */\nconst getCacheKey = (locale, keyPath) => `${locale}:${keyPath}`;\n\n/**\n * Register a custom field component instance for validation.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {any} args.instance Custom field component instance (may have an `isValid()` method).\n */\nexport const registerCustomFieldInstance = ({ locale, keyPath, instance }) => {\n  if (instance && typeof instance === 'object') {\n    customFieldInstances.set(getCacheKey(locale, keyPath), instance);\n  }\n};\n\n/**\n * Unregister a custom field instance and discard any cached or in-flight validation state. Nothing\n * happens if another instance has been registered under the same key path since: the field editors\n * in a list are kept when the items are reordered or one is removed, so the key path an editor\n * unregisters may already belong to the editor of another item.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {any} args.instance Instance registered by the caller, if any.\n */\nexport const unregisterCustomFieldInstance = ({ locale, keyPath, instance }) => {\n  const cacheKey = getCacheKey(locale, keyPath);\n\n  if (customFieldInstances.has(cacheKey) && customFieldInstances.get(cacheKey) !== instance) {\n    return;\n  }\n\n  customFieldInstances.delete(cacheKey);\n  validationCache.delete(cacheKey);\n  pendingValidations.delete(cacheKey);\n  // Bump the sequence so any in-flight validation resolving after teardown is discarded instead of\n  // repopulating the cache for a field that no longer exists\n  validationSequences.set(cacheKey, (validationSequences.get(cacheKey) ?? 0) + 1);\n};\n\n/**\n * Discard all custom field validation state. Called when an entry draft is created so that results\n * never leak between drafts.\n */\nexport const resetCustomFieldValidation = () => {\n  customFieldInstances.clear();\n  validationCache.clear();\n  pendingValidations.clear();\n  validationSequences.clear();\n};\n\n/**\n * Parse the result returned by a widget’s `isValid()` method.\n * @param {any} result Return value of `isValid()`.\n * @returns {{ valid: boolean, message?: string }} Normalized result.\n */\nconst parseValidationResult = (result) => {\n  // Handle Netlify/Decap CMS validation result formats:\n  // - Boolean: `true` (valid) or `false` (invalid)\n  // - Object: `{ error: { message: 'text' } }` (invalid with nested message, per docs)\n  if (result === false) {\n    return { valid: false };\n  }\n\n  if (typeof result === 'object' && result !== null) {\n    const { error } = result;\n\n    // Documentation format: `{ error: { message: 'text' } }`\n    if (typeof error === 'object' && error !== null && typeof error.message === 'string') {\n      return { valid: false, message: error.message };\n    }\n  }\n\n  // Any other shape, including `true`, is treated as valid\n  return { valid: true };\n};\n\n/**\n * Trigger async validation for a custom field. The result is cached so that the synchronous\n * validation pass can pick it up, and the returned promise is tracked so that a save attempt can\n * await the final verdict.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {any} args.value Field value.\n * @param {CustomField} args.fieldConfig Field configuration.\n * @returns {Promise<void>} Promise that resolves when validation is complete.\n */\nexport const triggerCustomFieldValidation = async ({ locale, keyPath, value, fieldConfig }) => {\n  const cacheKey = getCacheKey(locale, keyPath);\n  const instance = customFieldInstances.get(cacheKey);\n\n  if (typeof instance?.isValid !== 'function') {\n    validationCache.set(cacheKey, { valid: true, pending: false });\n\n    return;\n  }\n\n  const sequence = (validationSequences.get(cacheKey) ?? 0) + 1;\n\n  validationSequences.set(cacheKey, sequence);\n\n  // Preserve the previous verdict while revalidating, but mark it as pending so that a save attempt\n  // waits for the fresh result instead of trusting a stale one\n  const previous = validationCache.get(cacheKey);\n\n  validationCache.set(cacheKey, {\n    valid: previous?.valid ?? true,\n    message: previous?.message,\n    pending: true,\n  });\n\n  const promise = (async () => {\n    // The validator receives the field configuration as an Immutable Map\n    await loadImmutable();\n\n    const field = getFieldConfigMap(fieldConfig);\n    /** @type {{ valid: boolean, message?: string }} */\n    let outcome;\n\n    try {\n      outcome = parseValidationResult(await instance.isValid(value, field));\n    } catch (error) {\n      // If `isValid()` throws, treat the field as invalid. Widgets are trusted first-party code, so\n      // the message is surfaced as-is, but it’s always rendered as plain text, never as HTML.\n      outcome = {\n        valid: false,\n        message: error instanceof Error ? error.message : _('validation.unexpected_error'),\n      };\n    }\n\n    // Discard the result if a newer validation started, or the field was unregistered, while this\n    // one was in flight\n    if (validationSequences.get(cacheKey) !== sequence) {\n      return;\n    }\n\n    validationCache.set(cacheKey, { ...outcome, pending: false });\n  })();\n\n  pendingValidations.set(cacheKey, promise);\n\n  try {\n    await promise;\n  } finally {\n    if (pendingValidations.get(cacheKey) === promise) {\n      pendingValidations.delete(cacheKey);\n    }\n  }\n};\n\n/**\n * Wait for all in-flight custom field validations to settle. Call this before validating an entry\n * for saving, so that the verdicts read by {@link validateCustomField} reflect the current values.\n * @returns {Promise<void>} Promise that resolves once no validation is pending.\n */\nexport const awaitCustomFieldValidations = async () => {\n  // A validator may trigger further validation, so drain until no promises remain\n  while (pendingValidations.size) {\n    // eslint-disable-next-line no-await-in-loop\n    await Promise.all(pendingValidations.values());\n  }\n};\n\n/**\n * Validate a custom field using the cached validation result. This is called synchronously during\n * the validation pass.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {EntryValidityState} args.validity Validity state to update.\n */\nexport const validateCustomField = ({ locale, keyPath, validity }) => {\n  const cacheKey = getCacheKey(locale, keyPath);\n  const instance = customFieldInstances.get(cacheKey);\n\n  // Only validate if there’s a validator registered\n  if (typeof instance?.isValid !== 'function') {\n    return;\n  }\n\n  const cached = validationCache.get(cacheKey);\n\n  if (!cached) {\n    return;\n  }\n\n  validity.customError = !cached.valid;\n\n  if (!cached.valid && cached.message) {\n    validity.customErrorMessage = cached.message;\n  } else {\n    // `customErrorMessage` is a non-boolean property, so a leftover value would make the field look\n    // invalid via the validity proxy. Always clear it unless there’s a current message.\n    delete validity.customErrorMessage;\n  }\n};\n","import { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\nimport { getInputValue } from '$lib/services/contents/fields/date-time/value';\n\n/**\n * @import { EntryValidityState, ValidateFieldFuncArgs } from '$lib/types/private';\n * @import { DateTimeField, DateTimeInputType } from '$lib/types/public';\n */\n\n/**\n * @typedef DateTimeFieldValidationDetail\n * @property {boolean} hasMin Whether the field has a minimum value.\n * @property {boolean} hasMax Whether the field has a maximum value.\n * @property {boolean} invalid Whether the value is invalid.\n */\n\n/**\n * Validate a DateTime field value against the field configuration.\n * @param {ValidateFieldFuncArgs} args Arguments.\n * @returns {{ validity: EntryValidityState, detail: DateTimeFieldValidationDetail }} Result.\n */\nexport const validateDateTimeField = ({ fieldConfig, value, locale }) => {\n  const config = /** @type {DateTimeField} */ (fieldConfig);\n  const { type, min, max, singleCustomTimeZone: timeZone } = parseDateTimeConfig(config);\n  const hasMin = typeof min === 'string' && !!min;\n  const hasMax = typeof max === 'string' && !!max;\n  let rangeUnderflow = false;\n  let rangeOverflow = false;\n\n  if (value && (hasMin || hasMax)) {\n    // Convert stored value to native input format for comparison\n    const inputValue = getInputValue({\n      currentValue: value,\n      fieldConfig: config,\n      timeZone,\n      locale,\n    });\n\n    if (inputValue) {\n      const inputElement = document.createElement('input');\n\n      inputElement.type = type;\n      if (hasMin) inputElement.min = min;\n      if (hasMax) inputElement.max = max;\n      inputElement.value = inputValue;\n\n      ({ rangeUnderflow, rangeOverflow } = inputElement.validity);\n    }\n  }\n\n  const invalid = rangeUnderflow || rangeOverflow;\n\n  return {\n    validity: { rangeUnderflow, rangeOverflow },\n    detail: { hasMin, hasMax, invalid },\n  };\n};\n\n/**\n * Intl.DateTimeFormat instance for formatting time strings in a more human-friendly way.\n */\nconst timeFormatter = new Intl.DateTimeFormat('en-GB', {\n  hour12: true,\n  timeZone: 'UTC',\n  hour: '2-digit',\n  minute: '2-digit',\n});\n\n/**\n * Format a time string (e.g. \"14:30\") to a more human-friendly format (e.g. \"2:30 PM\").\n * @param {string} value Time string in \"HH:mm\" format.\n * @returns {string} Formatted time string.\n */\nexport const formatTime = (value) =>\n  timeFormatter.format(new Date(`1970-01-01T${value}Z`)).toUpperCase();\n\n/**\n * Format a date/time string based on the field type and configuration. For date-only fields, it\n * returns the date part. For time-only fields, it returns the time part formatted in a more\n * human-friendly way. For date-time fields, it returns both parts formatted in a more\n * human-friendly way.\n * @param {DateTimeInputType} type The type of the date/time field.\n * @param {string} value Date/time string in ISO format.\n * @returns {string} Formatted date/time string.\n */\nexport const getFormattedDateTime = (type, value) => {\n  if (type === 'date') {\n    return value;\n  }\n\n  if (type === 'time') {\n    return formatTime(value);\n  }\n\n  const [datePart, timePart] = value.split('T');\n\n  return `${datePart}, ${formatTime(timePart)}`;\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { getDraftFieldArgs, getField, isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { MEDIA_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\nimport { getFormattedDateTime } from '$lib/services/contents/fields/date-time/validate';\nimport {\n  COMPONENT_NAME_PREFIX_REGEX,\n  stripComponentNamePrefix,\n} from '$lib/services/contents/fields/rich-text';\nimport { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n/**\n * @import { EntryDraft, EntryValidityState, InternalLocaleCode } from '$lib/types/private';\n * @import {\n * DateTimeField,\n * DateTimeInputType,\n * Field,\n * FieldKeyPath,\n * MinMaxValueField,\n * StringField,\n * TextField,\n * } from '$lib/types/public';\n */\n\n/**\n * Get the error message for a range validity error (underflow or overflow).\n * @param {object} args Arguments.\n * @param {string} args.direction `'underflow'` or `'overflow'`.\n * @param {string} args.limitKey `'min'` or `'max'`.\n * @param {string | number | undefined} args.limitValue The limit value from the field config.\n * @param {string} args.fieldType Field widget type.\n * @param {string | undefined} args.type Native input type derived from the field config.\n * @param {boolean} args.canAddMultiValue Whether the field supports adding multiple values.\n * @returns {string} Translated error message.\n */\nconst getRangeErrorMessage = ({\n  direction,\n  limitKey,\n  limitValue,\n  fieldType,\n  type,\n  canAddMultiValue,\n}) => {\n  if (fieldType === 'datetime' && typeof limitValue === 'string') {\n    return _(`validation.range_${direction}.${type}`, {\n      values: {\n        [limitKey]: getFormattedDateTime(/** @type {DateTimeInputType} */ (type), limitValue),\n      },\n    });\n  }\n\n  if (fieldType === 'number') {\n    return _(`validation.range_${direction}.number`, { values: { [limitKey]: limitValue } });\n  }\n\n  if (canAddMultiValue) {\n    return _(`validation.range_${direction}.add`, {\n      values: { [limitKey]: limitValue },\n    });\n  }\n\n  return _(`validation.range_${direction}.select`, { values: { [limitKey]: limitValue } });\n};\n\n/**\n * Get the human-readable validation error messages for a field given its current validity state.\n * @param {object} args Arguments.\n * @param {EntryValidityState} args.validity Field validity state.\n * @param {Field} args.fieldConfig Full field configuration.\n * @returns {string[]} List of translated error message strings, one per violated constraint.\n */\nexport const getFieldValidationMessages = ({ validity, fieldConfig }) => {\n  /** @type {string[]} */\n  const messages = [];\n  const { widget: fieldType = 'string' } = fieldConfig;\n  // @ts-ignore Some field types don’t have `pattern` property\n  const { pattern = /** @type {string[]} */ ([]) } = fieldConfig;\n  const isDatetime = fieldType === 'datetime';\n\n  const parsedDateTimeConf = isDatetime\n    ? parseDateTimeConfig(/** @type {DateTimeField} */ (fieldConfig))\n    : /** @type {ReturnType<typeof parseDateTimeConfig>} */ ({});\n\n  // prettier-ignore\n  const type =\n    fieldType === 'string'\n      ? /** @type {StringField} */ (fieldConfig).type ?? 'text'\n      : isDatetime\n        ? parsedDateTimeConf.type\n        : fieldType === 'number'\n          ? /** @type {'number'} */ ('number')\n          : undefined;\n\n  const { min, max } = isDatetime\n    ? parsedDateTimeConf\n    : /** @type {MinMaxValueField} */ (fieldConfig);\n\n  // A multiple-value Select or Relation field has its options selected rather than items added, so\n  // it gets the `select` message\n  const canAddMultiValue =\n    fieldType === 'list' ||\n    fieldType === 'keyvalue' ||\n    (MEDIA_FIELD_TYPES.includes(fieldType) && isFieldMultiple(fieldConfig));\n\n  if (validity.valueMissing) {\n    messages.push(_('validation.value_missing'));\n  }\n\n  if (validity.tooShort) {\n    const { minlength } = /** @type {StringField | TextField} */ (fieldConfig);\n\n    messages.push(_('validation.too_short', { values: { min: minlength } }));\n  }\n\n  if (validity.tooLong) {\n    const { maxlength } = /** @type {StringField | TextField} */ (fieldConfig);\n\n    messages.push(_('validation.too_long', { values: { max: maxlength } }));\n  }\n\n  if (validity.rangeUnderflow) {\n    messages.push(\n      getRangeErrorMessage({\n        direction: 'underflow',\n        limitKey: 'min',\n        limitValue: min,\n        fieldType,\n        type,\n        canAddMultiValue,\n      }),\n    );\n  }\n\n  if (validity.rangeOverflow) {\n    messages.push(\n      getRangeErrorMessage({\n        direction: 'overflow',\n        limitKey: 'max',\n        limitValue: max,\n        fieldType,\n        type,\n        canAddMultiValue,\n      }),\n    );\n  }\n\n  if (validity.patternMismatch) {\n    messages.push(pattern[1]);\n  }\n\n  if (validity.typeMismatch) {\n    messages.push(_(`validation.type_mismatch.${type}`));\n  }\n\n  if (validity.duplicateError) {\n    messages.push(_('validation.value_not_unique'));\n  }\n\n  if (validity.mapKeyDuplicate) {\n    messages.push(_('validation.key_not_unique'));\n  }\n\n  if (validity.mapKeyNumeric) {\n    messages.push(_('validation.key_numeric'));\n  }\n\n  if (validity.customError) {\n    messages.push(validity.customErrorMessage ?? _('validation.invalid_value'));\n  }\n\n  return messages;\n};\n\n/**\n * Get the human-readable validation error messages for the folder chosen with the entry path\n * editor, which is validated as `_path` rather than as a field, so it has no stored messages.\n * @param {EntryValidityState | undefined} validity Validity state of the path.\n * @returns {string[]} List of translated error message strings, one per violated constraint.\n * @see validatePath\n */\nexport const getPathValidationMessages = (validity) => {\n  /** @type {string[]} */\n  const messages = [];\n\n  if (validity?.patternMismatch) {\n    messages.push(_('edit_path_error.invalid'));\n  }\n\n  if (validity?.customError) {\n    messages.push(_('edit_path_error.recursive'));\n  }\n\n  if (validity?.duplicateError) {\n    messages.push(_('edit_path_error.duplicate'));\n  }\n\n  return messages;\n};\n\n/**\n * Get the fields that have validation error messages in the given locale, in the order the fields\n * were validated. That includes the fields of rich text editor components, stored in\n * `extraValues`, and a multi-value field whose list itself is invalid, whose key path, e.g.\n * `tags`, only holds messages while the values are stored under `tags.0`, `tags.1`, etc.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @returns {{ keyPath: FieldKeyPath, label: string, messages: string[] }[]} Invalid fields, with\n * the label of each field or its name if the label is not defined, or an empty string if the field\n * cannot be found.\n */\nexport const getInvalidFields = ({ draft, locale }) => {\n  const { currentValues, extraValues } = draft;\n  const currentValueMap = currentValues[locale] ?? {};\n  const extraValueMap = extraValues[locale] ?? {};\n\n  return (\n    Object.entries(draft.validationMessages[locale] ?? {})\n      .filter(([, messages]) => !!messages.length)\n      .map(([keyPath, messages]) => {\n        const [prefix] = keyPath.match(COMPONENT_NAME_PREFIX_REGEX) ?? [];\n        const valueMap = prefix ? extraValueMap : currentValueMap;\n\n        return { keyPath, messages, prefix, valueMap };\n      })\n      // The messages are kept until the next validation, so skip a field removed since then, e.g. a\n      // list item or a rich text editor component. A list is kept as long as it has an item, which\n      // is stored under `tags.0`, etc. while the list itself is validated as `tags`\n      .filter(\n        ({ keyPath, valueMap }) =>\n          keyPath in valueMap || Object.keys(valueMap).some((key) => key.startsWith(`${keyPath}.`)),\n      )\n      .map(({ keyPath, messages, prefix, valueMap }) => {\n        const field = getField(\n          getDraftFieldArgs(draft, {\n            keyPath: stripComponentNamePrefix(keyPath),\n            valueMap,\n            // A rich text editor component field is looked up in the component definition\n            componentName: prefix ? extraValueMap[`${prefix}__sc_component_name`] : undefined,\n          }),\n        );\n\n        return {\n          keyPath,\n          label: field ? getFieldLabel({ config: field, locale }) : '',\n          messages,\n        };\n      })\n  );\n};\n","import { isFieldRequired } from '$lib/services/contents/entry/fields';\nimport { isInvalidNumberValue } from '$lib/services/contents/fields/number/helpers';\n\n/**\n * @import { EntryValidityState, ValidateFieldFuncArgs } from '$lib/types/private';\n * @import { NumberField } from '$lib/types/public';\n */\n\n/**\n * Validate a Number field value against the field configuration.\n * @param {ValidateFieldFuncArgs} args Arguments.\n * @returns {{ validity: EntryValidityState }} Result.\n */\nexport const validateNumberField = ({ fieldConfig, locale, value }) => {\n  const config = /** @type {NumberField} */ (fieldConfig);\n  const { value_type: valueType = 'int', min, max } = config;\n\n  // A blank string, which an empty `int/string` or `float/string` field holds, is no value at all,\n  // like `null`, rather than zero, which `Number('')` would make it\n  const number =\n    value === null || (typeof value === 'string' && !value.trim()) ? NaN : Number(value);\n\n  // Text the number input couldn’t parse, like `1,5` or `abc`, as well as a number the field can’t\n  // store, like `Infinity`, is kept in the draft so it can be reported here, rather than saved as\n  // an empty value without a word\n  const invalidNumber = isInvalidNumberValue(value, config);\n  const hasNumber = !invalidNumber && Number.isFinite(number);\n  const rangeUnderflow = hasNumber && typeof min === 'number' && number < min;\n  const rangeOverflow = !rangeUnderflow && hasNumber && typeof max === 'number' && number > max;\n\n  const typeMismatch =\n    invalidNumber ||\n    ((valueType === 'int' || valueType === 'float') &&\n      isFieldRequired({ fieldConfig, locale }) &&\n      value === null);\n\n  return {\n    validity: { rangeUnderflow, rangeOverflow, typeMismatch },\n  };\n};\n","/**\n * @import { EntryValidityState, ValidateFieldFuncArgs } from '$lib/types/private';\n * @import { StringField, TextField } from '$lib/types/public';\n */\n\n/**\n * @typedef StringFieldValidationDetail\n * @property {number} count Character count.\n * @property {boolean} hasMin Whether the field has a minimum length.\n * @property {boolean} hasMax Whether the field has a maximum length.\n * @property {boolean} invalid Whether the value is invalid.\n */\n\n/**\n * Validate a String/Text field value against the field configuration.\n * @param {ValidateFieldFuncArgs} args Arguments.\n * @returns {{ validity: EntryValidityState, detail: StringFieldValidationDetail }} Result.\n */\nexport const validateStringField = ({ fieldConfig, value }) => {\n  const config = /** @type {StringField | TextField} */ (fieldConfig);\n  const { widget: fieldType = 'string', minlength, maxlength } = config;\n\n  const hasMin =\n    Number.isInteger(minlength) && /** @type {number} */ (minlength) <= (maxlength ?? Infinity);\n\n  const hasMax =\n    Number.isInteger(maxlength) && (minlength ?? 0) <= /** @type {number} */ (maxlength);\n\n  const { type = 'text', prefix, suffix } = /** @type {StringField} */ (config);\n  // A number or boolean that hasn’t been converted to a string is counted as the text it’s written\n  // as rather than throwing\n  let trimValue = typeof value === 'string' ? value : String(value ?? '');\n\n  // Remove the prefix and suffix, which the user doesn’t type, before counting and validating\n  if (fieldType === 'string') {\n    if (prefix && trimValue.startsWith(prefix)) {\n      trimValue = trimValue.slice(prefix.length);\n    }\n\n    if (suffix && trimValue.endsWith(suffix)) {\n      trimValue = trimValue.slice(0, -suffix.length);\n    }\n  }\n\n  const count = [...trimValue.trim()].length;\n  const tooShort = hasMin && count < /** @type {number} */ (minlength);\n  const tooLong = hasMax && count > /** @type {number} */ (maxlength);\n  let typeMismatch = false;\n\n  // Check the URL or email with native form validation\n  if (fieldType === 'string' && trimValue) {\n    if (type !== 'text') {\n      const inputElement = document.createElement('input');\n\n      inputElement.type = type;\n      inputElement.value = trimValue;\n\n      ({ typeMismatch } = inputElement.validity);\n    }\n\n    // Check if the email’s domain part contains a dot, because native validation marks\n    // `me@example` valid but it’s not valid in the real world\n    if (type === 'email' && !typeMismatch && !trimValue.split('@')[1]?.includes('.')) {\n      typeMismatch = true;\n    }\n  }\n\n  const invalid = tooShort || tooLong || typeMismatch;\n\n  return {\n    validity: { tooShort, tooLong, typeMismatch },\n    detail: { count, hasMin, hasMax, invalid },\n  };\n};\n","import { validateDateTimeField } from '$lib/services/contents/fields/date-time/validate';\nimport { validateNumberField } from '$lib/services/contents/fields/number/validate';\nimport { validateStringField } from '$lib/services/contents/fields/string/validate';\nimport { getRegex } from '$lib/services/utils/regex';\n\n/**\n * @import {\n * EntryValidityState,\n * ValidateFieldFuncArgs,\n * } from '$lib/types/private';\n */\n\n/**\n * Map of functions to validate different field types. Each function receives the field config and\n * the current value, and returns an object with the same properties as `EntryValidityState` except\n * `valid`.\n * @type {Record<string, (args: ValidateFieldFuncArgs) => { validity: EntryValidityState }>}\n */\nexport const VALIDATE_FIELD_FUNCTIONS = {\n  datetime: validateDateTimeField,\n  number: validateNumberField,\n  string: validateStringField,\n  text: validateStringField,\n};\n\n/**\n * Test a value against the `pattern` option of a field, updating `validity` in place.\n * @param {object} args Arguments.\n * @param {any} args.value Value to test, converted to a string.\n * @param {any} args.validation Pattern validation array or undefined.\n * @param {EntryValidityState} args.validity Validity state to update.\n */\nexport const validatePattern = ({ value, validation, validity }) => {\n  if (Array.isArray(validation)) {\n    const regex = getRegex(validation[0]);\n\n    if (regex && !regex.test(String(value))) {\n      validity.patternMismatch = true;\n    }\n  }\n};\n\n/**\n * Validate a scalar field (all non-aggregate types), updating `validity` in place.\n * @param {object} args Arguments.\n * @param {any} args.value Current field value.\n * @param {boolean} args.required Whether the field is required.\n * @param {any} args.validation Pattern validation array or undefined.\n * @param {EntryValidityState} args.validity Validity state to update.\n * @param {boolean} [args.selected] Whether the value is a selected option, which is never empty,\n * even if the option’s value is `null` or an empty string.\n * @returns {{ empty: boolean }} Whether the field holds no value at all.\n */\nexport const validateScalarField = ({\n  value,\n  required,\n  validation,\n  validity,\n  selected = false,\n}) => {\n  const trimmed = typeof value === 'string' ? value.trim() : value;\n  const empty = !selected && (trimmed === undefined || trimmed === null || trimmed === '');\n\n  if (required && empty) {\n    validity.valueMissing = true;\n  }\n\n  validatePattern({ value: trimmed, validation, validity });\n\n  return { empty };\n};\n","import { getField } from '$lib/services/contents/entry/fields';\nimport { getCodeKeys, isCodeValueKey } from '$lib/services/contents/fields/code/helpers';\n\n/**\n * @import { FlattenedEntryContent, GetFieldArgs, LocaleValidityMap } from '$lib/types/private';\n * @import { CodeField } from '$lib/types/public';\n */\n\n/**\n * Get the configuration of the Code field that the given key path is the code or language of.\n * Unless the `output_code_only` option is enabled, a Code field stores its value as an object,\n * flattened into e.g. `snippet.code` and `snippet.lang`, which `getField()` can’t resolve on its\n * own, so the field is looked up by the parent key path instead.\n * @param {GetFieldArgs} args Arguments for the {@link getField} function, with the key path of the\n * code or language.\n * @returns {CodeField | undefined} Field configuration, or `undefined` if the key path isn’t the\n * code or language of a Code field.\n */\nexport const getCodeField = (args) => {\n  const { keyPath } = args;\n  const index = keyPath.lastIndexOf('.');\n\n  if (index === -1) {\n    return undefined;\n  }\n\n  const fieldConfig = getField({ ...args, keyPath: keyPath.slice(0, index) });\n\n  if (fieldConfig?.widget !== 'code') {\n    return undefined;\n  }\n\n  return isCodeValueKey(/** @type {CodeField} */ (fieldConfig), keyPath.slice(index + 1))\n    ? /** @type {CodeField} */ (fieldConfig)\n    : undefined;\n};\n\n/**\n * Resolve the current value for a code field.\n * @param {object} args Arguments.\n * @param {string} args.keyPath Field key path. It’s the field’s own, not the `.code` or `.lang`\n * sub-key, which is resolved with {@link getCodeField} beforehand.\n * @param {any} args.value Current field value.\n * @param {FlattenedEntryContent} args.valueMap Entry values.\n * @param {CodeField} args.fieldConfig Code field configuration.\n * @param {LocaleValidityMap} args.validities Full validity map.\n * @param {string} args.locale Current locale.\n * @returns {{ skip: boolean, keyPath: string, value: any }} Whether to skip, and the resolved key\n * path and value.\n */\nexport const resolveCodeField = ({ keyPath, value, valueMap, fieldConfig, validities, locale }) => {\n  const keys = getCodeKeys(fieldConfig);\n\n  // The field is validated only once, whether through its own key path or its sub-keys\n  if (keyPath in validities[locale]) {\n    return { skip: true, keyPath, value };\n  }\n\n  const resolvedValue = keys ? valueMap[`${keyPath}.${keys.code}`] : value;\n\n  return { skip: false, keyPath, value: resolvedValue };\n};\n","/**\n * @import { EntryValidityState } from '$lib/types/private';\n */\n\n/**\n * Default validity state for a field.\n * @type {EntryValidityState}\n */\nexport const DEFAULT_VALIDITY = {\n  valueMissing: false,\n  tooShort: false,\n  tooLong: false,\n  rangeUnderflow: false,\n  rangeOverflow: false,\n  patternMismatch: false,\n  typeMismatch: false,\n  customError: false,\n  duplicateError: false,\n  mapKeyDuplicate: false,\n  mapKeyNumeric: false,\n};\n\n/**\n * Finalize a validity state by adding the `valid` property, which is `true` when none of the\n * constraint flags is set. Mimics the native `ValidityState.valid` property.\n *\n * This is a plain property rather than a getter or a Proxy trap: the validity state is stored in\n * the reactive entry draft, whose `$state` proxy reads own properties only, so a computed property\n * would be invisible there.\n * @param {EntryValidityState} validity Validity state without the `valid` property.\n * @returns {EntryValidityState} Validity state with the `valid` property.\n */\nexport const finalizeValidity = (validity) => {\n  const finalized = { ...validity };\n\n  finalized.valid = !Object.values(validity).some(Boolean);\n\n  return finalized;\n};\n\n/**\n * Flag the given validity state when a field holding a number of items, like a List or KeyValue\n * field, has too few or too many of them, or none at all while it’s required.\n * @param {EntryValidityState} validity Validity state to update in place.\n * @param {object} args Arguments.\n * @param {number} args.count Number of items.\n * @param {boolean} args.required Whether the field is required.\n * @param {any} args.min The field’s `min` option. Ignored unless it’s a number.\n * @param {any} args.max The field’s `max` option. Ignored unless it’s a number.\n */\nexport const validateItemCount = (validity, { count, required, min, max }) => {\n  if (required && !count) {\n    validity.valueMissing = true;\n  } else if (typeof min === 'number' && count < min) {\n    validity.rangeUnderflow = true;\n  } else if (typeof max === 'number' && count > max) {\n    validity.rangeOverflow = true;\n  }\n};\n","import { validateItemCount } from '$lib/services/contents/draft/validate/validity';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getPairsFromContent } from '$lib/services/contents/fields/key-value/pairs';\nimport { stripComponentNamePrefix } from '$lib/services/contents/fields/rich-text';\n\n/**\n * @import {\n * EntryValidityState,\n * GetFieldArgs,\n * LocaleValidityMap,\n * } from '$lib/types/private';\n */\n\nconst KEY_PATH_REGEX = /(.+?)(?:\\.[^.]*)?$/;\n\n/**\n * Validate a keyvalue field, updating `validity` in place and resolving the canonical key path.\n * @param {object} args Arguments.\n * @param {string} args.keyPath Field key path (may be a sub-key of the keyvalue parent).\n * @param {GetFieldArgs} args.getFieldArgs Base args for {@link getField}.\n * @param {EntryValidityState} args.validity Validity state to update.\n * @param {LocaleValidityMap} args.validities Full validity map.\n * @param {string} args.locale Current locale.\n * @param {boolean} args.required Whether the field is required.\n * @param {string | number} args.min Minimum allowed pairs.\n * @param {string | number} args.max Maximum allowed pairs.\n * @returns {{ skip: boolean, keyPath: string, empty?: boolean }} Whether to skip, the resolved key\n * path, and whether the field holds no pairs at all.\n */\nexport const validateKeyValueField = ({\n  keyPath,\n  getFieldArgs,\n  validity,\n  validities,\n  locale,\n  required,\n  min,\n  max,\n}) => {\n  /**\n   * Check whether the given key path points to a KeyValue field.\n   * @param {string} _keyPath Key path, which may have a component name prefix.\n   * @returns {boolean} Result.\n   */\n  const isKeyValueField = (_keyPath) =>\n    getField({\n      ...getFieldArgs,\n      keyPath: stripComponentNamePrefix(_keyPath),\n    })?.widget === 'keyvalue';\n\n  // Given that values for a KeyValue field are flatten into `field.key1`, `field.key2` ...\n  // `field.keyN`, we should validate only once against all these values. The key can be\n  // empty, so use `.*` in the regex instead of `.+`\n  let _keyPath = /** @type {string} */ (keyPath.match(KEY_PATH_REGEX)?.[1]);\n  let isKeyValue = isKeyValueField(_keyPath);\n\n  // The key path can also be the field’s own, e.g. `obj.meta` holding `null` once all the pairs of\n  // a KeyValue field nested in an Object field have been removed\n  if (!isKeyValue && isKeyValueField(keyPath)) {\n    _keyPath = keyPath;\n    isKeyValue = true;\n  }\n\n  if (_keyPath in validities[locale] || !isKeyValue) {\n    return { skip: true, keyPath };\n  }\n\n  // A blank pair, like the one a required field gets as its default value, isn’t saved, so it\n  // doesn’t count. A pair with an empty key but a value, which a file can hold, still does\n  const pairs = getPairsFromContent(getFieldArgs.valueMap ?? {}, _keyPath).filter(\n    ([key, value]) => key.trim() || value,\n  );\n\n  validateItemCount(validity, { count: pairs.length, required, min, max });\n\n  return { skip: false, keyPath: _keyPath, empty: !pairs.length };\n};\n","import { validateItemCount } from '$lib/services/contents/draft/validate/validity';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import {\n * EntryValidityState,\n * FlattenedEntryContent,\n * LocaleValidityMap,\n * } from '$lib/types/private';\n */\n\n/**\n * Regular expression to match the item index at the start of a key path relative to its list, e.g.\n * `0` in `0` or `0.name`.\n */\nconst LEADING_INDEX_REGEX = /^\\d+/;\n\n/**\n * Validate a list/multiple-value field, updating `validity` in place.\n * @param {object} args Arguments.\n * @param {string} args.keyPath Field key path.\n * @param {any} args.value Current field value.\n * @param {FlattenedEntryContent} args.valueMap Entry values. Only the keys are read, and only when\n * the item count cannot be taken from {@link value} directly.\n * @param {EntryValidityState} args.validity Validity state to update.\n * @param {LocaleValidityMap} args.validities Full validity map.\n * @param {string} args.locale Current locale.\n * @param {boolean} args.required Whether the field is required.\n * @param {string | number} args.min Minimum allowed items.\n * @param {string | number} args.max Maximum allowed items.\n * @returns {{ skip: boolean, empty?: boolean }} Whether the caller should skip further validation,\n * and whether the field holds no items at all.\n */\nexport const validateListField = ({\n  keyPath,\n  value,\n  valueMap,\n  validity,\n  validities,\n  locale,\n  required,\n  min,\n  max,\n}) => {\n  // Given that values for an array field are flatten into `field.0`, `field.1` ... `field.N`, we\n  // should validate only once against all these values\n  if (keyPath in validities[locale]) {\n    return { skip: true };\n  }\n\n  /**\n   * Count the list items by scanning the flattened key paths.\n   *\n   * We need to check both the list itself and the items in the list because the list can be empty\n   * but still have items in the list, depending on the flattening condition. It means the data\n   * usually looks like `{ field.0: 'foo', field.1: 'bar' }`, but it can contain an empty list like\n   * `{ field: [], field.0: 'foo', field.1: 'bar' }` in some cases. Or it can be a simple list field\n   * like `{ field: ['foo', 'bar'] }` without the subfields.\n   * @returns {number} Item count.\n   */\n  const countItems = () => {\n    const prefix = `${keyPath}.`;\n    /** @type {Set<string>} */\n    const indexes = new Set();\n\n    // This runs on every keystroke once the entry has been validated, against the draft’s live\n    // values, so the cheap prefix test is done first and only the matching keys are parsed\n    Object.keys(valueMap).forEach((key) => {\n      if (key.startsWith(prefix)) {\n        const index = key.slice(prefix.length).match(LEADING_INDEX_REGEX)?.[0];\n\n        if (index !== undefined) {\n          indexes.add(index);\n        }\n      }\n    });\n\n    return indexes.size;\n  };\n\n  const size = Array.isArray(value) && !!value.length ? value.length : countItems();\n\n  validateItemCount(validity, { count: size, required, min, max });\n\n  return { skip: false, empty: !size };\n};\n\n/**\n * Get the items of a List field without subfields, which are stored as `field.0`, `field.1` …\n * `field.N`, unless the list itself holds them in an array.\n * @param {object} args Arguments.\n * @param {string} args.keyPath Field key path.\n * @param {any} args.value Current field value.\n * @param {FlattenedEntryContent} args.valueMap Entry values.\n * @returns {any[]} Items in list order.\n */\nexport const getListItems = ({ keyPath, value, valueMap }) => {\n  if (Array.isArray(value) && !!value.length) {\n    return value;\n  }\n\n  const prefix = `${keyPath}.`;\n\n  return Object.keys(valueMap)\n    .flatMap((key) => {\n      const index = key.startsWith(prefix) ? key.slice(prefix.length) : undefined;\n\n      return index !== undefined && isNumeric(index) ? [[Number(index), valueMap[key]]] : [];\n    })\n    .sort(([a], [b]) => a - b)\n    .map(([, item]) => item);\n};\n","import { validatePattern } from '$lib/services/contents/draft/validate/scalar';\nimport { MEDIA_FIELD_TYPES, MULTI_VALUE_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { resolveCodeField } from '$lib/services/contents/fields/code/validate';\nimport { validateKeyValueField } from '$lib/services/contents/fields/key-value/validate';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport { getListItems, validateListField } from '$lib/services/contents/fields/list/validate';\n\n/**\n * @import {\n * EntryDraft,\n * EntryValidityState,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * LocaleValidityMap,\n * } from '$lib/types/private';\n * @import {\n * CodeField,\n * Field,\n * FieldKeyPath,\n * ListField,\n * LocaleCode,\n * } from '$lib/types/public';\n */\n\n/**\n * Arguments for the functions that prepare an aggregate or special field for validation.\n * @typedef {object} PrepareFieldArgs\n * @property {FieldKeyPath} keyPath Field key path.\n * @property {any} value Field value.\n * @property {FlattenedEntryContent} valueMap Entry values.\n * @property {Field} fieldConfig Field configuration.\n * @property {GetFieldArgs} getFieldArgs Arguments to get the field configuration.\n * @property {EntryDraft['files']} files Files attached to the draft.\n * @property {EntryValidityState} validity Validity state to update.\n * @property {LocaleValidityMap} validities Validity state of all the fields.\n * @property {LocaleCode} locale Current locale.\n * @property {boolean} required Whether the field is required.\n * @property {string | number} min Minimum value or item count.\n * @property {string | number} max Maximum value or item count.\n */\n\n/**\n * Result of the preparation of a field for validation.\n * @typedef {object} PreparedField\n * @property {boolean} skip Whether the field is not validated any further, because it has been\n * validated already.\n * @property {FieldKeyPath} keyPath Key path to validate the field at.\n * @property {any} value Value to validate.\n * @property {boolean} empty Whether the field holds no value at all.\n */\n\n/**\n * Get the value of a media field to validate. The stored value can be a blob URL, whose original\n * file name is validated instead.\n * @param {object} args Arguments.\n * @param {string} args.fieldType Field type.\n * @param {any} args.value Field value.\n * @param {EntryDraft['files']} args.files Files attached to the draft.\n * @returns {any} Value to validate.\n */\nexport const resolveMediaValue = ({ fieldType, value, files }) => {\n  if (\n    MEDIA_FIELD_TYPES.includes(fieldType) &&\n    typeof value === 'string' &&\n    value.startsWith('blob:')\n  ) {\n    // The stored `value` is a blob URL; get the original file name\n    return files[value]?.file?.name;\n  }\n\n  return value;\n};\n\n/**\n * Prepare a List field, or a field that takes multiple values, for validation.\n * @param {PrepareFieldArgs} args Arguments.\n * @returns {PreparedField} Result.\n */\nexport const prepareListField = ({\n  keyPath,\n  value,\n  valueMap,\n  fieldConfig,\n  files,\n  validity,\n  validities,\n  locale,\n  required,\n  min,\n  max,\n}) => {\n  const { skip, empty } = validateListField({\n    keyPath,\n    value,\n    valueMap,\n    validity,\n    validities,\n    locale,\n    required,\n    min,\n    max,\n  });\n\n  // Like Decap CMS, test the pattern of a List field without subfields, or a multiple File, Image,\n  // Relation or Select field, against its items joined with commas, e.g. `a,b,c`, rather than\n  // against each item. A custom field taking an array, also prepared here, is left alone\n  // @ts-ignore A List field with subfields doesn’t have the `pattern` option\n  const { widget: fieldType = 'string', pattern: validation } = fieldConfig;\n\n  if (\n    !skip &&\n    !empty &&\n    Array.isArray(validation) &&\n    (fieldType === 'list'\n      ? !getListFieldInfo(/** @type {ListField} */ (fieldConfig)).hasSubFields\n      : MULTI_VALUE_FIELD_TYPES.includes(fieldType))\n  ) {\n    validatePattern({\n      // Like Decap’s Immutable `List.join()`, this converts a number to a string and `null` to an\n      // empty string. A file just uploaded is tested by its name, as in a single File/Image field\n      value: getListItems({ keyPath, value, valueMap })\n        .map((item) => resolveMediaValue({ fieldType, value: item, files }))\n        .join(','),\n      validation,\n      validity,\n    });\n  }\n\n  return { skip, keyPath, value, empty: !!empty };\n};\n\n/**\n * Prepare an Object field for validation.\n * @param {PrepareFieldArgs} args Arguments.\n * @returns {PreparedField} Result.\n */\nconst prepareObjectField = ({ keyPath, value, valueMap, validity, required }) => {\n  // An Object field holding subfields may have no value at its own key path, e.g. right after the\n  // editor adds the subfields and deletes the `null` it stored while the object was removed, so\n  // the subfields tell whether it’s there\n  const empty =\n    value === undefined\n      ? !Object.keys(valueMap).some((key) => key.startsWith(`${keyPath}.`))\n      : !value;\n\n  if (required && empty) {\n    validity.valueMissing = true;\n  }\n\n  return { skip: false, keyPath, value, empty };\n};\n\n/**\n * Prepare a KeyValue field for validation.\n * @param {PrepareFieldArgs} args Arguments.\n * @returns {PreparedField} Result.\n */\nconst prepareKeyValueField = ({\n  keyPath,\n  value,\n  getFieldArgs,\n  validity,\n  validities,\n  locale,\n  required,\n  min,\n  max,\n}) => {\n  const result = validateKeyValueField({\n    keyPath,\n    getFieldArgs,\n    validity,\n    validities,\n    locale,\n    required,\n    min,\n    max,\n  });\n\n  return { skip: result.skip, keyPath: result.keyPath, value, empty: !!result.empty };\n};\n\n/**\n * Prepare a Code field for validation.\n * @param {PrepareFieldArgs} args Arguments.\n * @returns {PreparedField} Result.\n */\nconst prepareCodeField = ({ keyPath, value, valueMap, fieldConfig, validities, locale }) => {\n  const result = resolveCodeField({\n    keyPath,\n    value,\n    valueMap,\n    fieldConfig: /** @type {CodeField} */ (fieldConfig),\n    validities,\n    locale,\n  });\n\n  return { skip: result.skip, keyPath: result.keyPath, value: result.value, empty: false };\n};\n\n/**\n * Map of functions to prepare different field types for validation, which run before the\n * functions in `VALIDATE_FIELD_FUNCTIONS` in the `scalar` module. List fields and fields that take\n * multiple values are prepared with {@link prepareListField} instead.\n * @type {Record<string, (args: PrepareFieldArgs) => PreparedField>}\n */\nexport const PREPARE_FIELD_FUNCTIONS = {\n  object: prepareObjectField,\n  keyvalue: prepareKeyValueField,\n  code: prepareCodeField,\n};\n\n/**\n * Clear the constraint flags of an empty field, updating `validity` in place.\n * @param {EntryValidityState} validity Validity state to update.\n * @param {boolean} enforceRequired Whether an empty required field is marked as missing.\n */\nexport const relaxEmptyFieldValidity = (validity, enforceRequired) => {\n  Object.assign(validity, {\n    patternMismatch: false,\n    tooShort: false,\n    rangeUnderflow: false,\n    typeMismatch: false,\n  });\n\n  // An Editorial Workflow draft that hasn’t been filled in yet can still be saved, so even a\n  // required field left empty goes unmarked while the entry is in the drafting stage\n  if (!enforceRequired) {\n    validity.valueMissing = false;\n  }\n};\n","import { getUnpublishedEntryByDraft, isWorkflowDraft } from '$lib/services/workflow';\nimport { getCollectionPublishModeOptions, getEntryStage } from '$lib/services/workflow/stages';\n\n/**\n * @import { EntryDraft, UnpublishedEntry, WorkflowStatus } from '$lib/types/private';\n */\n\n/**\n * Get the Editorial Workflow stage of the entry the given draft is editing. The status can change\n * while the editor stays open — from the status menu, or on the Editorial Workflow page — so it’s\n * read from the store rather than from the draft’s snapshot of the entry.\n * @param {EntryDraft} draft Draft being edited.\n * @returns {WorkflowStatus} Stage. An entry that has no pull request yet starts as a draft.\n */\nconst getWorkflowStage = (draft) => {\n  const entry =\n    getUnpublishedEntryByDraft(draft) ??\n    /** @type {UnpublishedEntry | undefined} */ (draft.originalEntry);\n\n  return entry?.workflow ? getEntryStage(entry, draft.collection) : 'draft';\n};\n\n/**\n * Check whether the required fields of the given draft have to be filled in for it to be saved.\n * With a workflow an entry lives in a pull request until it’s published, so one that’s still in the\n * drafting stage can be saved incomplete, and the fields left empty aren’t marked as errors, unless\n * the `allow_incomplete_drafts` publish mode option is turned off. Anywhere else a save puts the\n * entry straight on the site, and a workflow entry that has moved on from the drafting stage is on\n * its way there too.\n * @param {EntryDraft} draft Draft to check.\n * @returns {boolean} `true` if an empty required field is an error.\n * @see https://github.com/decaporg/decap-cms/issues/464\n * @see https://github.com/decaporg/decap-cms/issues/5013\n */\nexport const isRequiredEnforced = (draft) =>\n  !isWorkflowDraft(draft) ||\n  !getCollectionPublishModeOptions(draft.collection).allowIncompleteDrafts ||\n  getWorkflowStage(draft) !== 'draft';\n","import { _ } from '@sveltia/i18n';\n\nimport { slugify } from '$lib/services/common/slug';\nimport { cmsConfig } from '$lib/services/config';\nimport {\n  getEntriesByCollection,\n  getEntriesInCollectionFolder,\n} from '$lib/services/contents/collection/entries';\nimport { getNameInFolder, getSharedEntryFileName } from '$lib/services/contents/collection/nested';\nimport { getSlugOptions } from '$lib/services/contents/collection/slug';\nimport { getSlugDirPath } from '$lib/services/contents/draft/slugs';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport { getRegex } from '$lib/services/utils/regex';\nimport { getPullRequestEntries } from '$lib/services/workflow';\n\n/**\n * @import {\n * Entry,\n * EntryDraft,\n * EntryValidityState,\n * InternalLocaleCode,\n * LocaleValidityMap,\n * UnpublishedEntry,\n * } from '$lib/types/private';\n */\n\n/**\n * What stops a slug from being used: it’s empty, contains a slash or whitespace (other than a plain\n * space, if the slug is meant to have them) or starts with a dot, doesn’t match the collection’s\n * `pattern` slug option, or is taken by another entry.\n * @typedef {'empty' | 'invalid' | 'pattern' | 'duplicate'} SlugValidationError\n */\n\n/**\n * Get the other entries of the collection the draft belongs to: the published ones and the\n * unpublished ones, leaving out any version of the entry being edited, told apart by the draft’s\n * ID as well as the original entry’s paths. A new entry has no original, yet it’s saved under the\n * draft’s ID with Editorial Workflow, and once it is, the draft is validated again — to see whether\n * the entry can be sent for review — while the saved entry already holds its slug and values. The\n * published ones include every entry stored in the collection folder, even those the collection’s\n * `filter` option leaves out: they can belong to another collection sharing the folder, and their\n * files can’t be overwritten either. With Editorial Workflow, a draft that has already renamed the\n * entry leaves the published version behind under the old slug, so that version has to be\n * recognized as the same entry — otherwise reverting the slug looks like a conflict. The\n * unpublished entries are concatenated rather than swapped over their published versions, because\n * a draft that renamed an entry leaves the published file behind, so both slugs are still in use.\n * The new entries riding along in the pull request of an entry of another collection count too.\n * @param {EntryDraft} draft Entry draft.\n * @param {object} [options] Options.\n * @param {boolean} [options.inFolder] Whether to include every published entry stored in the\n * collection folder. When `false`, only the published entries the collection lists, which pass its\n * `filter` option, are included.\n * @returns {(Entry | UnpublishedEntry)[]} Entries.\n */\nexport const getOtherEntries = (draft, { inFolder = true } = {}) => {\n  // An entry in the Editorial Workflow has previous paths\n  const { id, collectionName, originalEntry } =\n    /** @type {EntryDraft & { originalEntry?: UnpublishedEntry }} */ (draft);\n\n  // Every file path this entry occupies\n  const ownPaths = new Set(\n    originalEntry ? getEntryPaths(originalEntry, { includePrevious: true }) : [],\n  );\n\n  return [\n    ...(inFolder ? getEntriesInCollectionFolder : getEntriesByCollection)(collectionName),\n    ...getPullRequestEntries(collectionName),\n  ].filter(\n    (entry) =>\n      entry.id !== id && !Object.values(entry.locales).some(({ path }) => ownPaths.has(path)),\n  );\n};\n\n/**\n * Get the slugs taken by the other entries of the collection, for each locale of the draft’s slugs.\n * A locale-agnostic slug, under the `_` key, can collide with another entry’s slug in any locale.\n * The entry’s own original slug in a locale never counts as taken in that locale; in another\n * locale, it can be another entry’s slug, which would be overwritten. For a new entry placed with\n * the path editor of a collection with nested entries, or a locale just enabled for an existing\n * one, only the entries in the chosen folder count, by their file names, because the slug of an\n * entry there is otherwise its sub path. With localized slugs, that’s the folder’s localized\n * counterpart in each locale but the default one. See {@link getSlugDirPath}.\n * @param {EntryDraft} draft Entry draft.\n * @param {InternalLocaleCode[]} [locales] Locales to get the taken slugs for. Default: the locales\n * of the draft’s slugs.\n * @returns {Record<InternalLocaleCode, string[]>} Taken slugs for each locale.\n */\nexport const getTakenSlugs = (draft, locales = Object.keys(draft.currentSlugs)) => {\n  const { originalSlugs } = draft;\n  const otherEntries = getOtherEntries(draft);\n\n  return Object.fromEntries(\n    locales.map((locale) => {\n      const ownSlug = originalSlugs[locale] ?? originalSlugs._;\n      // A locale-agnostic slug is stored in the folder chosen in the default locale\n      const dirPath = getSlugDirPath(draft, locale === '_' ? undefined : locale);\n\n      return [\n        locale,\n        otherEntries\n          .flatMap((entry) =>\n            locale === '_'\n              ? Object.values(entry.locales).map(({ slug }) => slug)\n              : [entry.locales[locale]?.slug],\n          )\n          .flatMap((slug) => {\n            if (typeof slug !== 'string' || slug === ownSlug) {\n              return [];\n            }\n\n            const name = dirPath === undefined ? slug : getNameInFolder(slug, dirPath);\n\n            return name === undefined ? [] : [name];\n          }),\n      ];\n    }),\n  );\n};\n\n/**\n * Check whether a slug is meant to contain spaces, because the global `sanitize_replacement` slug\n * option contains one.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/1093\n */\nconst slugCanHaveSpaces = () =>\n  cmsConfig.current?.slug?.sanitize_replacement?.includes(' ') ?? false;\n\n/**\n * Check whether the given slug can be used.\n * @param {object} args Arguments.\n * @param {string | undefined} args.slug Slug to check, as typed.\n * @param {boolean} [args.required] Whether the slug must be given. An empty slug that isn’t\n * required is valid, as the slug template fills it instead.\n * @param {[string | RegExp, string]} [args.pattern] The collection’s `pattern` slug option.\n * @param {boolean} [args.allowSpaces] Whether the slug can contain plain spaces. Defaults to\n * whether the global `sanitize_replacement` slug option contains one.\n * @param {string[]} [args.takenSlugs] Slugs taken by the other entries.\n * @param {InternalLocaleCode} [args.locale] Locale of the slug, used to slugify it the same way it\n * will be saved.\n * @returns {SlugValidationError | undefined} What stops the slug from being used, or `undefined` if\n * it can be used.\n */\nexport const validateSlug = ({\n  slug,\n  required = true,\n  pattern,\n  allowSpaces = slugCanHaveSpaces(),\n  takenSlugs = [],\n  locale,\n}) => {\n  const trimmedSlug = slug?.trim() ?? '';\n\n  if (!trimmedSlug) {\n    return required ? 'empty' : undefined;\n  }\n\n  // A slash or whitespace would break the file path and URL structure. A plain space is fine if the\n  // slug is meant to have them; `slugify` turns any run of them into the replacement on save\n  if ((allowSpaces ? /[/]|[^\\S ]/ : /[/\\s]/).test(/** @type {string} */ (slug))) {\n    return 'invalid';\n  }\n\n  // A file name starting with a dot makes a dot file, which is hidden and skipped when the\n  // repository files are listed, so the entry would be lost once saved. `slugify` removes the dot,\n  // but a slug meant to be hidden is rejected rather than silently saved under another one\n  if (trimmedSlug.startsWith('.')) {\n    return 'invalid';\n  }\n\n  if (Array.isArray(pattern)) {\n    const regex = getRegex(pattern[0]);\n\n    if (regex && !regex.test(trimmedSlug)) {\n      return 'pattern';\n    }\n  }\n\n  // Compare the slug the way it will be saved\n  if (takenSlugs.includes(slugify(trimmedSlug, { locale }))) {\n    return 'duplicate';\n  }\n\n  return undefined;\n};\n\n/**\n * Get the message for the given slug validation error.\n * @param {object} args Arguments.\n * @param {SlugValidationError} args.error Error.\n * @param {[string | RegExp, string]} [args.pattern] The collection’s `pattern` slug option, whose\n * second item is the message for a slug that doesn’t match.\n * @returns {string} Message.\n */\nexport const getSlugValidationMessage = ({ error, pattern }) =>\n  error === 'pattern' && pattern?.[1] ? pattern[1] : _(`edit_slug_error.${error}`);\n\n/**\n * Check whether the slug of the given locale has to be validated. For a new entry, that’s when the\n * slug editor is shown. For an existing entry, that’s when the slug has been edited, except in a\n * collection where every entry is an index file within a folder of its own: there the slug editor\n * renames the folder, which goes by different rules than a slug, and a localized slug is a sub\n * path.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale, or `_` for a locale-agnostic slug.\n * @returns {boolean} Result.\n */\nconst isSlugEditable = ({ draft, locale }) => {\n  const { collection, isNew, currentLocales, currentSlugs, originalSlugs, slugEditor } = draft;\n\n  // The slug can only be edited in an entry collection; the slug of a file/singleton collection’s\n  // entry is the file name\n  if (collection._type !== 'entry') {\n    return false;\n  }\n\n  // Only validate slugs for locales that are currently enabled. A disabled locale’s slug is not\n  // written to disk, so an empty value should not block saving.\n  // @see https://github.com/sveltia/sveltia-cms/issues/740\n  if (locale !== '_' && !currentLocales?.[locale]) {\n    return false;\n  }\n\n  if (isNew) {\n    return !!slugEditor[locale];\n  }\n\n  return currentSlugs[locale] !== originalSlugs[locale] && !getSharedEntryFileName(collection);\n};\n\n/**\n * Validate the slugs and return the results. A slug is validated when the user can edit it: in a\n * new entry with the slug editor shown, or in an existing entry whose slug has been edited.\n * @param {EntryDraft} draft Draft to validate.\n * @returns {{ valid: boolean, validities: LocaleValidityMap }} Validation results.\n */\nexport const validateSlugs = (draft) => {\n  const { collection, isNew, currentSlugs, slugEditor } = draft;\n  /** @type {LocaleValidityMap} */\n  const validities = {};\n  let valid = true;\n  /** @type {Record<InternalLocaleCode, string[]> | undefined} */\n  let takenSlugs;\n  // The options are only used for an entry collection, where the slug can be edited\n  const { editorRequired, editorValueIsSlug, pattern } = getSlugOptions(collection);\n  // An existing entry’s slug is edited as a whole. A new entry’s value can be only a part of the\n  // slug, in which case it can’t be told whether the slug is taken\n  const isWholeSlug = !isNew || editorValueIsSlug;\n  const allowSpaces = slugCanHaveSpaces();\n  // A slug editor that has never been shown, e.g. in a closed sidebar panel, hasn’t set its slug\n  // yet, and the slug must still be given\n  const locales = new Set([...Object.keys(currentSlugs), ...Object.keys(slugEditor)]);\n\n  locales.forEach((locale) => {\n    const slug = currentSlugs[locale];\n\n    const error = isSlugEditable({ draft, locale })\n      ? validateSlug({\n          slug,\n          // An existing entry always needs a slug, while a new entry’s slug can come from the\n          // template\n          required: !isNew || editorRequired,\n          pattern,\n          allowSpaces,\n          // Only look for other entries when the slug could collide with one\n          takenSlugs:\n            isWholeSlug && slug?.trim() ? (takenSlugs ??= getTakenSlugs(draft))[locale] : [],\n          locale,\n        })\n      : undefined;\n\n    /** @type {EntryValidityState} */\n    const validity = {\n      valueMissing: error === 'empty',\n      patternMismatch: error === 'invalid',\n      customError: error === 'pattern',\n      duplicateError: error === 'duplicate',\n      valid: !error,\n    };\n\n    if (error) {\n      valid = false;\n      validity.customErrorMessage = getSlugValidationMessage({ error, pattern });\n    }\n\n    validities[locale] = { _slug: validity };\n  });\n\n  return { valid, validities };\n};\n","/**\n * @import { InternalCollection } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Regular expression matching the item index of a List field within a key path, e.g. `.0` in\n * `speakers.0.name` and `.3` in `tags.3`.\n */\nconst LIST_ITEM_INDEX_REGEX = /\\.\\d+(?=\\.|$)/;\n\n/**\n * Check whether a field holds exactly one value per entry of an entry collection, so its value can\n * be compared with the same field’s in the other entries, as the `unique` and `auto_increment`\n * options do. Every entry of an entry collection has the same fields, except the special index\n * file, which has fields of its own. A field in a List field or a rich text editor component can\n * appear any number of times in an entry, so it doesn’t count.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s special index file.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {boolean} [args.inEditorComponent] Whether the field is in a rich text editor component.\n * @returns {boolean} Result.\n */\nexport const isPerEntryField = ({\n  collection,\n  isIndexFile = false,\n  keyPath,\n  inEditorComponent = false,\n}) =>\n  collection._type === 'entry' &&\n  !isIndexFile &&\n  !inEditorComponent &&\n  !LIST_ITEM_INDEX_REGEX.test(keyPath);\n","import { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getOtherEntries } from '$lib/services/contents/draft/validate/slugs';\nimport { isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { isPerEntryField } from '$lib/services/contents/entry/per-entry';\nimport { MEDIA_FIELD_TYPES } from '$lib/services/contents/fields';\n\n/**\n * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n * @import { Field, FieldKeyPath, UniqueValueProps } from '$lib/types/public';\n */\n\n/**\n * Field types that support the `unique` option. Each of them holds a single string or number,\n * unless it takes multiple values, which the option doesn’t support.\n */\nconst UNIQUE_FIELD_TYPES = [\n  'color',\n  'datetime',\n  'file',\n  'image',\n  'markdown',\n  'number',\n  'relation',\n  'richtext',\n  'select',\n  'string',\n  'text',\n];\n\n/**\n * Normalize a field value so that values meaning the same thing compare equal: a number is compared\n * by its numeric value, so `1`, `'1'` and `'01'` are the same in a Number field, a color regardless\n * of case, so `#FF0000` and `#ff0000` are the same, and any other value as a string with its\n * surrounding whitespace trimmed. A file just uploaded to a File or Image field, stored as a blob\n * URL until the entry is saved, is a new file, so it can’t be the same as another entry’s.\n * @param {any} value Value.\n * @param {string} fieldType Field type.\n * @returns {string | number | undefined} Normalized value, or `undefined` if the value is empty or\n * can’t be compared.\n */\nexport const normalizeUniqueValue = (value, fieldType) => {\n  if (value === undefined || value === null || typeof value === 'object') {\n    return undefined;\n  }\n\n  const trimmed = String(value).trim();\n\n  if (!trimmed) {\n    return undefined;\n  }\n\n  if (fieldType === 'number') {\n    const number = Number(trimmed);\n\n    return Number.isFinite(number) ? number : undefined;\n  }\n\n  if (fieldType === 'color') {\n    return trimmed.toLowerCase();\n  }\n\n  if (MEDIA_FIELD_TYPES.includes(fieldType) && trimmed.startsWith('blob:')) {\n    return undefined;\n  }\n\n  return trimmed;\n};\n\n/**\n * Check whether the `unique` option applies to the given field. It’s only meaningful for a field\n * that holds one value per entry of an entry collection. A field that takes multiple values doesn’t\n * qualify either, as it holds a list.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {string} [args.componentName] Rich text editor component name.\n * @returns {boolean} Result.\n */\nexport const isUniqueField = ({ draft, fieldConfig, keyPath, componentName }) => {\n  const { widget: fieldType = 'string' } = fieldConfig;\n\n  return (\n    UNIQUE_FIELD_TYPES.includes(fieldType) &&\n    /** @type {UniqueValueProps} */ (fieldConfig).unique === true &&\n    !isFieldMultiple(fieldConfig) &&\n    isPerEntryField({\n      collection: draft.collection,\n      isIndexFile: draft.isIndexFile,\n      keyPath,\n      inEditorComponent: !!componentName,\n    })\n  );\n};\n\n/**\n * Check whether another entry in the same collection has the same value in the same field, like a\n * `UNIQUE` constraint in a relational database. Both the published and unpublished entries are\n * looked at, leaving out any version of the entry being edited, as well as the special index file.\n * An empty value never counts as a duplicate.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale of the value.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {any} args.value Field value.\n * @param {string} args.fieldType Field type.\n * @returns {boolean} Whether the value is taken by another entry.\n * @see https://github.com/decaporg/decap-cms/issues/1069\n */\nexport const isValueTaken = ({ draft, locale, keyPath, value, fieldType }) => {\n  const normalized = normalizeUniqueValue(value, fieldType);\n\n  if (normalized === undefined) {\n    return false;\n  }\n\n  const { collection } = draft;\n\n  return getOtherEntries(draft, { inFolder: false }).some(\n    (entry) =>\n      !isCollectionIndexFile(collection, entry) &&\n      normalizeUniqueValue(entry.locales[locale]?.content[keyPath], fieldType) === normalized,\n  );\n};\n","import { getField } from '$lib/services/contents/entry/fields';\nimport { getCurrentStorableValue } from '$lib/services/contents/fields/date-time/value';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { isValueEmpty } from '$lib/services/utils/object';\n\n/**\n * @import { EntryDraft } from '$lib/types/private';\n * @import { DateTimeAutoNowStage, DateTimeField, Field } from '$lib/types/public';\n */\n\n/**\n * Get the stages at which a DateTime field is set to the current date/time.\n * @param {Field} fieldConfig Field configuration.\n * @returns {DateTimeAutoNowStage[]} Stages. Empty if the field isn’t a DateTime field or the\n * `auto_now` option is not enabled.\n */\nexport const getAutoNowStages = (fieldConfig) => {\n  if (fieldConfig.widget !== 'datetime') {\n    return [];\n  }\n\n  const { auto_now: autoNow = false } = /** @type {DateTimeField} */ (fieldConfig);\n\n  if (typeof autoNow === 'boolean') {\n    return autoNow ? ['create', 'update'] : [];\n  }\n\n  // A value of another type is reported against the JSON schema\n  return Array.isArray(autoNow) ? autoNow : [];\n};\n\n/**\n * Check whether a field is a DateTime field whose value is set automatically on save. Such a field\n * is read-only and isn’t validated.\n * @param {Field} fieldConfig Field configuration.\n * @returns {boolean} Result.\n */\nexport const isAutoNowField = (fieldConfig) => getAutoNowStages(fieldConfig).length > 0;\n\n/**\n * Check whether a DateTime field with the `auto_now` option is to be set when the draft is saved.\n * `create` covers a new entry and a value that hasn’t been set yet, such as one in a List item\n * added to an existing entry, or one in an entry saved before the option was enabled. `update`\n * covers every save of an existing entry.\n * @param {object} args Arguments.\n * @param {DateTimeAutoNowStage[]} args.stages Stages enabled for the field.\n * @param {boolean} args.isNew Whether the draft is for a new entry.\n * @param {any} args.value Current value of the field.\n * @returns {boolean} Result.\n */\nconst isAutoNowDue = ({ stages, isNew, value }) =>\n  (stages.includes('create') && (isNew || isValueEmpty(value))) ||\n  (stages.includes('update') && !isNew);\n\n/**\n * Set the DateTime fields with the `auto_now` option to the current date/time in the draft’s\n * current values, if the option covers the stage being saved. Every locale gets the same time,\n * written in the locale with the `localize_format` option. A field in a rich text editor component\n * isn’t covered, because its value is stored in the Markdown rather than in the draft’s values; the\n * option is ignored there.\n * @param {EntryDraft} draft Draft to mutate in place.\n */\nexport const assignAutoNowValues = (draft) => {\n  const { isNew, collectionName, fileName, isIndexFile, currentValues } = draft;\n  // Take the time once, so every field, locale and list item saved together gets the same one\n  const date = new Date();\n\n  Object.entries(currentValues).forEach(([locale, valueMap]) => {\n    /**\n     * Values keyed by field configuration, so a field shared by list items is only formatted once\n     * per locale.\n     * @type {Map<Field, string>}\n     */\n    const valueCache = new Map();\n\n    Object.entries(valueMap).forEach(([keyPath, value]) => {\n      const fieldConfig = getField({ collectionName, fileName, keyPath, valueMap, isIndexFile });\n\n      if (fieldConfig && isAutoNowDue({ stages: getAutoNowStages(fieldConfig), isNew, value })) {\n        valueMap[keyPath] = getOrCreate(valueCache, fieldConfig, () =>\n          getCurrentStorableValue(/** @type {DateTimeField} */ (fieldConfig), {\n            date,\n            includeSeconds: true,\n            locale,\n          }),\n        );\n      }\n    });\n  });\n};\n","import { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isValueEmpty } from '$lib/services/utils/object';\nimport { getPullRequestEntries } from '$lib/services/workflow';\n\n/**\n * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Get the highest number stored under the given key path by the entries of a collection, in the\n * given locale. The entries still in a pull request count too, as a new entry saved with\n * Editorial Workflow has taken its number as well, including the new entries riding along in the\n * pull request of an entry of another collection. A value that isn’t a finite number is ignored.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Entry collection name.\n * @param {FieldKeyPath} args.keyPath Key path of the value.\n * @param {InternalLocaleCode} args.locale Locale of the values, usually the default locale.\n * @returns {number | undefined} Highest number, which can be zero or negative, or `undefined` if no\n * entry has a number.\n */\nexport const getMaxEntryNumber = ({ collectionName, keyPath, locale }) =>\n  [...getEntriesByCollection(collectionName), ...getPullRequestEntries(collectionName)].reduce(\n    (/** @type {number | undefined} */ max, entry) => {\n      const content = entry.locales[locale]?.content;\n      const rawValue = content?.[keyPath];\n      // `Number()` turns an empty value, like `null` or an empty string, into `0`, which isn’t a\n      // number the entry has\n      const value = isValueEmpty(rawValue) ? NaN : Number(rawValue);\n\n      return Number.isFinite(value) && (max === undefined || value > max) ? value : max;\n    },\n    undefined,\n  );\n\n/**\n * For new entries in reorder-enabled entry collections, assign a fresh manual sort order to the\n * draft’s current values: highest existing order + 1, or 1 if no entries have one yet. The entries\n * still in a pull request count too. Doing this at save time (rather than draft creation) makes the\n * assignment race-safe even when a draft has been backed up and restored after another entry took\n * the previously computed value. Callers must gate on `draft.isNew` and\n * `draft.collection._type === 'entry'` themselves.\n * @param {EntryDraft} draft Draft to mutate in place.\n * @param {number} [offset] Number of entries already given an order that isn’t in the collection\n * yet, such as the entries added from a Relation field that are saved along with the entry being\n * edited. Each of them takes the next order, so the new one comes after them.\n */\nexport const assignManualSortOrder = (draft, offset = 0) => {\n  const { collection, currentValues } = draft;\n  const orderKey = getOrderFieldKey(collection);\n\n  if (!orderKey) {\n    return;\n  }\n\n  const { defaultLocale } = getDraftI18nConfig(draft);\n\n  const maxOrder = getMaxEntryNumber({\n    collectionName: collection.name,\n    keyPath: orderKey,\n    locale: defaultLocale,\n  });\n\n  // The order starts from 1, even if an entry has a negative one\n  const nextOrder = Math.max(maxOrder ?? 0, 0) + offset + 1;\n\n  Object.values(currentValues).forEach((valueMap) => {\n    valueMap[orderKey] = nextOrder;\n  });\n};\n","import { getMaxEntryNumber } from '$lib/services/contents/draft/save/sort-order';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { isPerEntryField } from '$lib/services/contents/entry/per-entry';\nimport { isStringOutput } from '$lib/services/contents/fields/number/helpers';\nimport { isValueEmpty } from '$lib/services/utils/object';\n\n/**\n * @import { EntryDraft, InternalCollection } from '$lib/types/private';\n * @import { Field, FieldKeyPath, NumberField } from '$lib/types/public';\n */\n\n/**\n * Check whether a field is a Number field whose value is assigned automatically on save, like an\n * `AUTO_INCREMENT` column in a relational database. Such a field is read-only and isn’t validated.\n * The option only applies to a field holding one value per entry of an entry collection; it’s\n * ignored elsewhere, e.g. in a List field.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s special index file.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {boolean} [args.inEditorComponent] Whether the field is in a rich text editor component.\n * @returns {boolean} Result.\n * @see https://github.com/decaporg/decap-cms/issues/2367\n */\nexport const isAutoIncrementField = ({ fieldConfig, ...args }) =>\n  fieldConfig.widget === 'number' &&\n  /** @type {NumberField} */ (fieldConfig).auto_increment === true &&\n  isPerEntryField(args);\n\n/**\n * Get the number to assign to an auto-increment Number field: the integer after the highest one\n * any entry of the collection has, or the field’s `min` option, if it’s higher, so the numbering\n * can start from e.g. `1000`, or `0`. The first entry is numbered `min`, or `1` without it.\n * @param {object} args Arguments.\n * @param {NumberField} args.fieldConfig Field configuration.\n * @param {InternalCollection} args.collection Entry collection.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {number} args.offset Number of entries already given a number that aren’t in the\n * collection yet.\n * @returns {number | string} Number, as a string if the field stores its value as a string, like\n * with `value_type: int/string` or a custom type.\n */\nconst getNextNumber = ({ fieldConfig, collection, keyPath, offset }) => {\n  const { min } = fieldConfig;\n\n  const max = getMaxEntryNumber({\n    collectionName: collection.name,\n    keyPath,\n    locale: collection._i18n.defaultLocale,\n  });\n\n  const start = typeof min === 'number' && Number.isFinite(min) ? Math.ceil(min) : 1;\n  // The first entry takes the start number, which can be `0` or negative with the `min` option.\n  // Otherwise the number follows the highest one, but never goes below the start\n  const next = (max === undefined ? start : Math.max(Math.floor(max) + 1, start)) + offset;\n\n  return isStringOutput(fieldConfig) ? String(next) : next;\n};\n\n/**\n * Assign the next number to the auto-increment Number fields in the draft’s current values, at\n * save time rather than when the draft is created, so two entries created at the same time can’t\n * take the same number, as with the `reorder` collection option. A new entry always gets a number,\n * even if it was duplicated from another entry, while an existing entry gets one only if it had\n * none in the default locale when it was opened, such as an entry saved before the option was\n * enabled. That’s decided by the original value rather than the current one, so a save that failed\n * after numbering the entry doesn’t keep a number another entry may have taken since. Every locale\n * holding the field gets the same number.\n * @param {EntryDraft} draft Draft to mutate in place.\n * @param {number} [offset] Number of entries already given a number that aren’t in the collection\n * yet, such as the entries added from a Relation field that are saved along with the entry being\n * edited. Each of them takes the next number, so this entry comes after them.\n */\nexport const assignAutoIncrementValues = (draft, offset = 0) => {\n  const { isNew, collection, collectionName, isIndexFile, currentValues, originalValues } = draft;\n\n  // The option only applies to an entry collection, so don’t look up any field elsewhere\n  if (collection._type !== 'entry' || isIndexFile) {\n    return;\n  }\n\n  const { defaultLocale } = collection._i18n;\n  const defaultValueMap = currentValues[defaultLocale] ?? {};\n\n  Object.keys(defaultValueMap).forEach((keyPath) => {\n    const fieldConfig = getField({\n      collectionName,\n      keyPath,\n      valueMap: defaultValueMap,\n      isIndexFile,\n    });\n\n    if (\n      !fieldConfig ||\n      !isAutoIncrementField({ fieldConfig, collection, isIndexFile, keyPath }) ||\n      !(isNew || isValueEmpty(originalValues[defaultLocale]?.[keyPath]))\n    ) {\n      return;\n    }\n\n    const value = getNextNumber({\n      fieldConfig: /** @type {NumberField} */ (fieldConfig),\n      collection,\n      keyPath,\n      offset,\n    });\n\n    Object.values(currentValues).forEach((valueMap) => {\n      if (keyPath in valueMap) {\n        valueMap[keyPath] = value;\n      }\n    });\n  });\n};\n","import { validateCustomField } from '$lib/services/contents/draft/validate/custom-fields';\nimport { getFieldValidationMessages } from '$lib/services/contents/draft/validate/messages';\nimport {\n  PREPARE_FIELD_FUNCTIONS,\n  prepareListField,\n  relaxEmptyFieldValidity,\n  resolveMediaValue,\n} from '$lib/services/contents/draft/validate/prepare';\nimport { isRequiredEnforced } from '$lib/services/contents/draft/validate/required';\nimport {\n  VALIDATE_FIELD_FUNCTIONS,\n  validateScalarField,\n} from '$lib/services/contents/draft/validate/scalar';\nimport { isUniqueField, isValueTaken } from '$lib/services/contents/draft/validate/unique';\nimport { DEFAULT_VALIDITY, finalizeValidity } from '$lib/services/contents/draft/validate/validity';\nimport {\n  getDraftFieldArgs,\n  getField,\n  getFieldKind,\n  isFieldMultiple,\n  isFieldRequired,\n} from '$lib/services/contents/entry/fields';\nimport { ITEM_INDEX_SUFFIX_REGEX } from '$lib/services/contents/entry/key-paths';\nimport { MIN_MAX_VALUE_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getCodeField } from '$lib/services/contents/fields/code/validate';\nimport { isAutoNowField } from '$lib/services/contents/fields/date-time/auto-now';\nimport {\n  getKeyValueField,\n  PAIR_KEY_PATH_REGEX,\n} from '$lib/services/contents/fields/key-value/pairs';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport {\n  getMapKeyInfo,\n  getMapKeyPaths,\n  isArrayIndexKey,\n  isMapKeyTaken,\n} from '$lib/services/contents/fields/list/map';\nimport { isAutoIncrementField } from '$lib/services/contents/fields/number/auto-increment';\nimport {\n  COMPONENT_NAME_PREFIX_REGEX,\n  stripComponentNamePrefix,\n} from '$lib/services/contents/fields/rich-text';\nimport { isOptionValue } from '$lib/services/contents/fields/select/helpers';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isFieldI18nDisabled } from '$lib/services/contents/i18n/fields';\nimport { isSyncedField } from '$lib/services/contents/i18n/shared-values';\n\n/**\n * @import {\n * DraftValueStoreKey,\n * EntryDraft,\n * EntryValidityState,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * LocaleValidationMessagesMap,\n * LocaleValidityMap,\n * } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * ListField,\n * LocaleCode,\n * MinMaxValueField,\n * SelectField,\n * } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} ValidateFieldArgs\n * @property {EntryDraft} draft Entry draft.\n * @property {LocaleValidityMap} validities Validity state.\n * @property {LocaleCode} locale Current locale.\n * @property {FieldKeyPath} keyPath Field key path.\n * @property {FlattenedEntryContent} valueMap Entry values.\n * @property {any} value Field value.\n * @property {string} [componentName] Rich text editor component name.\n * @property {boolean} [enforceRequired] Whether an empty required field is marked as missing.\n */\n\n/**\n * @typedef {object} ValidationResults\n * @property {boolean} valid Whether the entry draft is valid.\n * @property {LocaleValidityMap} validities Validity state for each field in each locale.\n * @property {LocaleValidationMessagesMap} validationMessages Validation messages for each field in\n * each locale.\n */\n\n/**\n * Regular expression matching the item index of a List field within a key path when a subfield\n * follows, e.g. `.0` in `speakers.0.name`. What comes before the match is the list’s key path.\n */\nconst LIST_ITEM_SUBFIELD_REGEX = /\\.\\d+(?=\\.)/g;\n/**\n * Regular expression matching the item index of a List field within a key path, whether a subfield\n * follows or not, e.g. `.0` in `speakers.0.name` and `.3` in `tags.3`. What comes before the match\n * is the list’s key path.\n */\nconst LIST_ITEM_INDEX_REGEX = /\\.\\d+(?=\\.|$)/g;\n/**\n * Regular expression matching what follows a list’s key path in the key path of one of its direct\n * items, e.g. `.3` in `tags.3`, but not `.0.name` in `speakers.0.name`.\n */\nconst DIRECT_ITEM_SUFFIX_REGEX = /^\\.\\d+$/;\n\n/**\n * Compute the validation messages of a field from its validity state, if it has one, and record\n * them under the same key path.\n * @param {object} args Arguments.\n * @param {LocaleValidityMap} args.validities Validity state.\n * @param {LocaleValidationMessagesMap} args.validationMessages Validation messages, modified in\n * place.\n * @param {LocaleCode} args.locale Locale of the field.\n * @param {FieldKeyPath} args.keyPath Key path the field’s validity state is kept under.\n * @param {Field} args.fieldConfig Field configuration.\n */\nconst recordValidationMessages = ({\n  validities,\n  validationMessages,\n  locale,\n  keyPath,\n  fieldConfig,\n}) => {\n  const validity = validities[locale][keyPath];\n\n  if (validity) {\n    validationMessages[locale][keyPath] = getFieldValidationMessages({ validity, fieldConfig });\n  }\n};\n\n/**\n * Validate each field.\n * @param {ValidateFieldArgs} args Arguments.\n * @returns {EntryValidityState | undefined} Field validity.\n */\nexport const validateAnyField = (args) => {\n  const { draft, locale, valueMap, componentName, validities, enforceRequired = true } = args;\n  const { collection, files, isIndexFile } = draft;\n  let { keyPath, value } = args;\n\n  const getFieldArgs = getDraftFieldArgs(draft, {\n    keyPath: stripComponentNamePrefix(keyPath),\n    valueMap,\n    componentName,\n  });\n\n  const fieldConfig =\n    getField({ ...getFieldArgs }) ??\n    // A KeyValue pair is stored under an arbitrary key, e.g. `metadata.color`, that `getField()`\n    // can’t resolve. Without this, a KeyValue field holding pairs would never be validated, so its\n    // `min` and `max` options wouldn’t be checked, and a required one holding only a blank pair\n    // would pass\n    getKeyValueField({ ...getFieldArgs });\n\n  if (!fieldConfig) {\n    return undefined;\n  }\n\n  // @ts-ignore Some field types don’t have `pattern` property\n  const { widget: fieldType = 'string', i18n = false, pattern: validation } = fieldConfig;\n\n  const multiple =\n    isFieldMultiple(fieldConfig) ||\n    (getFieldKind(fieldConfig) === 'custom' && Array.isArray(value));\n\n  const { min = 0, max = Infinity } = /** @type {MinMaxValueField} */ (\n    MIN_MAX_VALUE_FIELD_TYPES.includes(fieldType) ? fieldConfig : {}\n  );\n\n  const { i18nEnabled, defaultLocale } = getDraftI18nConfig(draft);\n\n  // Skip validation on non-editable fields. A field without an `i18n` option of its own can still\n  // be edited in another locale along with an ancestor using the `sync` strategy\n  if (\n    !componentName && // Don’t skip validation if the field is within a rich text editor component\n    locale !== defaultLocale &&\n    (!i18nEnabled || isFieldI18nDisabled(i18n) || i18n === 'duplicate') &&\n    !isSyncedField({ fieldConfig, getFieldArgs })\n  ) {\n    return undefined;\n  }\n\n  // A DateTime field set automatically on save can’t be edited, and may be empty until then. The\n  // option is ignored in a rich text editor component, whose values aren’t set on save\n  if (!componentName && isAutoNowField(fieldConfig)) {\n    return undefined;\n  }\n\n  // The same goes for a Number field numbered automatically on save\n  if (\n    isAutoIncrementField({\n      fieldConfig,\n      collection,\n      isIndexFile,\n      keyPath,\n      inEditorComponent: !!componentName,\n    })\n  ) {\n    return undefined;\n  }\n\n  const required = isFieldRequired({ fieldConfig, locale });\n  // The key of an item of a List field stored as a map, which the configuration requires\n  const mapKeyInfo = getMapKeyInfo(getFieldArgs);\n  /** @type {EntryValidityState} */\n  const validity = { ...DEFAULT_VALIDITY };\n  /** Whether the field holds no value at all, which each widget decides its own way. */\n  let empty = false;\n\n  const prepareField =\n    fieldType === 'list' || multiple ? prepareListField : PREPARE_FIELD_FUNCTIONS[fieldType];\n\n  if (prepareField) {\n    const result = prepareField({\n      keyPath,\n      value,\n      valueMap,\n      fieldConfig,\n      getFieldArgs,\n      files,\n      validity,\n      validities,\n      locale,\n      required,\n      min,\n      max,\n    });\n\n    if (result.skip) return undefined;\n\n    ({ keyPath, value, empty } = result);\n  }\n\n  // A just uploaded file is validated by its name, but only the stored value tells it’s a new file\n  const storedValue = value;\n\n  value = resolveMediaValue({ fieldType, value, files });\n\n  if (!(['object', 'list', 'hidden', 'compute', 'keyvalue'].includes(fieldType) || multiple)) {\n    const selected =\n      fieldType === 'select' &&\n      isOptionValue({ fieldConfig: /** @type {SelectField} */ (fieldConfig), value });\n\n    ({ empty } = validateScalarField({ value, required, validation, validity, selected }));\n  }\n\n  const validateFieldFn = VALIDATE_FIELD_FUNCTIONS[fieldType];\n\n  if (validateFieldFn) {\n    Object.assign(validity, validateFieldFn({ fieldConfig, locale, value }).validity);\n  }\n\n  // An empty value is never a duplicate, so other entries are only looked at when there is a value\n  if (!empty && isUniqueField({ draft, fieldConfig, keyPath, componentName })) {\n    validity.duplicateError = isValueTaken({\n      draft,\n      locale,\n      keyPath,\n      value: storedValue,\n      fieldType,\n    });\n  }\n\n  // The key also has to be unique within the list, and can’t be a whole number, which a map moves\n  // to the front, so the items wouldn’t keep their order\n  if (!empty && mapKeyInfo) {\n    validity.mapKeyDuplicate = isMapKeyTaken({ ...mapKeyInfo, valueMap, keyPath, value });\n    validity.mapKeyNumeric = isArrayIndexKey(String(value));\n  }\n\n  // Validate custom field if applicable (uses cached result)\n  validateCustomField({ locale, keyPath, validity });\n\n  // The remaining rules all describe a value, and an empty field has none: a pattern can’t be\n  // matched by something that isn’t there, nothing is long enough to clear a minimum length, an\n  // empty list is under any minimum item count, and a Number field with no number in it reports a\n  // type mismatch. Whether the field is required is the only thing left worth saying about it,\n  // which is what makes `required: false` mean anything for a field that also carries constraints.\n  // `tooLong` and `rangeOverflow` are left alone — an empty field can’t trigger them — and\n  // `customError` is a custom field component’s own call to make\n  if (empty) {\n    // A keyed list item without a key can’t be saved even as an Editorial Workflow draft, so the\n    // key is always enforced\n    relaxEmptyFieldValidity(validity, enforceRequired || !!mapKeyInfo);\n  }\n\n  return finalizeValidity(validity);\n};\n\n/**\n * Validate a single field and update the validity state.\n * @param {ValidateFieldArgs} args Arguments.\n * @returns {boolean} Whether the field is valid.\n */\nexport const validateField = (args) => {\n  const { validities, locale, keyPath } = args;\n  const validity = validateAnyField(args);\n  let valid = true;\n\n  if (validity) {\n    validities[locale][keyPath] = validity;\n\n    if (!validity.valid) {\n      valid = false;\n    }\n  }\n\n  return valid;\n};\n\n/**\n * Re-validate a single field, if it has been validated already, and update its validity state and\n * validation messages.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft, modified in place.\n * @param {LocaleCode} args.locale Locale of the field.\n * @param {FieldKeyPath} args.keyPath Key path of the field.\n * @param {any} args.value Field value.\n * @param {FlattenedEntryContent} args.valueMap Entry values for the locale.\n */\nconst revalidateSingleField = ({ draft, locale, keyPath, value, valueMap }) => {\n  const { validities, validationMessages } = draft;\n  const getFieldArgs = getDraftFieldArgs(draft, { keyPath, valueMap });\n  // A KeyValue pair is validated as part of its field, whose state is kept under the field’s own\n  // key path, where the editor shows it. See `validateFields()`\n  const keyValueField = getField(getFieldArgs) ? undefined : getKeyValueField(getFieldArgs);\n  const stateKeyPath = keyValueField ? keyPath.replace(PAIR_KEY_PATH_REGEX, '') : keyPath;\n\n  // Nothing is shown for the field yet, so there is nothing to update\n  if (!validities?.[locale]?.[stateKeyPath]) {\n    return;\n  }\n\n  const validity = validateAnyField({\n    draft,\n    locale,\n    keyPath,\n    value,\n    valueMap,\n    // Match the last full validation, so a field the save deliberately left unmarked isn’t reported\n    // as missing the moment the user types in it\n    enforceRequired: isRequiredEnforced(draft),\n    // The List, KeyValue and Code field validators skip a field that already has a validity state,\n    // which is how {@link validateFields} validates such a field only once instead of once per\n    // flattened key path. Here a single field is validated on its own, so hide the state from them\n    validities: { [locale]: {} },\n  });\n\n  if (!validity) {\n    return;\n  }\n\n  validities[locale][stateKeyPath] = validity;\n\n  // The field is known to be configured, as `validateAnyField` bails out otherwise\n  const fieldConfig = /** @type {Field} */ (keyValueField ?? getField(getFieldArgs));\n\n  recordValidationMessages({\n    validities,\n    validationMessages,\n    locale,\n    keyPath: stateKeyPath,\n    fieldConfig,\n  });\n};\n\n/**\n * Re-validate a single field right after its value has been updated or deleted, so the error state\n * and message shown for the field reflect what the user has just done. The List fields the value is\n * an item of are re-validated as well, e.g. `tags` for `tags.3`, as their items are validated as\n * part of them. So are the List fields the value is in an item of, e.g. `speakers` for\n * `speakers.0.name`, but only when a key path has been added or deleted, as only their item count\n * may have changed: counting the items means going through the whole entry, which isn’t done again\n * on every keystroke. This is a no-op until the entry has been validated once, which normally\n * happens on a save attempt, because no error is displayed before that.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft, modified in place.\n * @param {LocaleCode} args.locale Locale of the updated field.\n * @param {FieldKeyPath} args.keyPath Key path of the updated field.\n * @param {any} args.value Updated field value, or `undefined` if the value has been deleted.\n * @param {FlattenedEntryContent} args.valueMap Entry values for the locale.\n * @param {boolean} [args.keyAdded] Whether the key path has been added or deleted rather than\n * having its value changed. Defaults to `true`, so the List fields are re-validated unless the\n * caller knows the key path existed already.\n */\nexport const revalidateField = ({ draft, locale, keyPath, value, valueMap, keyAdded = true }) => {\n  revalidateSingleField({ draft, locale, keyPath, value, valueMap });\n\n  const mapKeyInfo = getMapKeyInfo(getDraftFieldArgs(draft, { keyPath, valueMap }));\n\n  // Changing the key of a keyed list item may make or break a duplicate with the other items. Only\n  // the items marked as a duplicate, or now having the same key, can be affected, so the others,\n  // which can be many in a large list, aren’t validated again on every keystroke\n  if (mapKeyInfo) {\n    getMapKeyPaths({ ...mapKeyInfo, valueMap }).forEach((otherKeyPath) => {\n      if (\n        otherKeyPath !== keyPath &&\n        (draft.validities?.[locale]?.[otherKeyPath]?.mapKeyDuplicate ||\n          String(valueMap[otherKeyPath]) === String(value))\n      ) {\n        revalidateSingleField({\n          draft,\n          locale,\n          keyPath: otherKeyPath,\n          value: valueMap[otherKeyPath],\n          valueMap,\n        });\n      }\n    });\n  }\n\n  [...keyPath.matchAll(LIST_ITEM_INDEX_REGEX)].forEach(({ index }) => {\n    const listKeyPath = keyPath.slice(0, index);\n\n    // An item of a list without subfields, or a value of a multiple Relation or Select field, is\n    // validated as part of the list. A value inside an item only counts towards the item count\n    if (!keyAdded && !DIRECT_ITEM_SUFFIX_REGEX.test(keyPath.slice(index))) {\n      return;\n    }\n\n    const getFieldArgs = getDraftFieldArgs(draft, { keyPath: listKeyPath, valueMap });\n    const listFieldConfig = getField(getFieldArgs);\n\n    // A multiple-value Select or Relation field stores its values like a List field without\n    // subfields, e.g. `categories.0`, and keeps its validity state under its own key path\n    if (\n      listFieldConfig &&\n      (listFieldConfig.widget === 'list' || isFieldMultiple(listFieldConfig))\n    ) {\n      revalidateSingleField({\n        draft,\n        locale,\n        keyPath: listKeyPath,\n        value: valueMap[listKeyPath],\n        valueMap,\n      });\n    }\n  });\n};\n\n/**\n * Validate an array-type field.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {ValidateFieldArgs} args.validateArgs Arguments for field validation.\n * @returns {{ valid: boolean, validateItems: boolean }} Validation result.\n */\nexport const validateList = ({ fieldConfig, validateArgs }) => {\n  const { validities, locale, keyPath } = validateArgs;\n  const valid = validities[locale][keyPath]?.valid ?? validateField(validateArgs);\n  const { widget: fieldType = 'string' } = fieldConfig;\n\n  if (fieldType === 'list') {\n    if (!getListFieldInfo(/** @type {ListField} */ (fieldConfig)).hasSubFields) {\n      // Simple list field, so we don’t need to validate items\n      return { valid, validateItems: false };\n    }\n  }\n\n  if (isFieldMultiple(fieldConfig)) {\n    // Same as a simple list field, so we don’t need to validate items\n    return { valid, validateItems: false };\n  }\n\n  return { valid, validateItems: true };\n};\n\n/**\n * @typedef {object} FieldValidationContext\n * @property {Omit<ValidateFieldArgs, 'keyPath' | 'value'>} validateArgs Arguments shared by every\n * field validated for a value: the draft, locale, entry values, validity state, rich text editor\n * component name and whether required fields are enforced.\n * @property {LocaleValidationMessagesMap} validationMessages Validation messages, modified in\n * place.\n * @property {GetFieldArgs} getFieldArgs Arguments for the {@link getField} function, with the\n * value’s key path without the component name prefix.\n */\n\n/**\n * Get the configuration of a field in the value map.\n * @param {FieldValidationContext} context Validation context.\n * @param {FieldKeyPath} keyPath Key path, which may have a component name prefix.\n * @returns {Field | undefined} Field configuration.\n */\nconst getConfig = ({ getFieldArgs }, keyPath) =>\n  getField({\n    ...getFieldArgs,\n    keyPath: stripComponentNamePrefix(keyPath),\n  });\n\n/**\n * Validate a List field itself, e.g. its item count, and compute its messages. The list is\n * validated only once, however many of its items are in the value map.\n * @param {FieldValidationContext} context Validation context.\n * @param {object} args Arguments.\n * @param {FieldKeyPath} args.listKeyPath Key path of the list.\n * @param {Field} args.fieldConfig Configuration to validate the list with: the list’s own, or the\n * item’s for a list with `field`.\n * @param {Field} args.listFieldConfig The list’s own configuration, for the messages.\n * @returns {{ valid: boolean, validateItems: boolean }} Whether the list is valid, and whether its\n * items have to be validated too.\n */\nconst validateListItself = (context, { listKeyPath, fieldConfig, listFieldConfig }) => {\n  const { validateArgs, validationMessages } = context;\n  const { validities, locale } = validateArgs;\n\n  const result = validateList({\n    fieldConfig,\n    validateArgs: { ...validateArgs, keyPath: listKeyPath, value: '' },\n  });\n\n  // Compute messages for the list field itself (only on first item iteration)\n  if (!(listKeyPath in validationMessages[locale])) {\n    recordValidationMessages({\n      validities,\n      validationMessages,\n      locale,\n      keyPath: listKeyPath,\n      fieldConfig: listFieldConfig,\n    });\n  }\n\n  return result;\n};\n\n/**\n * Validate the field the value belongs to when the value’s key path has no field configuration of\n * its own, but its parent’s does, and record the result under the field’s key path, where the\n * editor shows it. The field is validated only once, however many of its sub-keys are in the value\n * map. A KeyValue pair is stored under an arbitrary key, e.g. `metadata.color`, so the field is\n * validated through its first pair and the result is moved to the field’s key path. Without this, a\n * KeyValue field holding pairs would never be validated. A Code field that stores an object is\n * flattened into its code and language, e.g. `snippet.code`, and an existing entry has no value at\n * the field’s own key path, so the field is validated through its sub-keys at the field’s key path.\n * @param {FieldValidationContext} context Validation context.\n * @param {object} args Arguments.\n * @param {FieldKeyPath} args.keyPath Key path of the value.\n * @param {any} args.value Value.\n * @param {(args: GetFieldArgs) => Field | undefined} args.getParentField Function to get the\n * configuration of the field the value belongs to.\n * @param {boolean} args.viaSubKey Whether to validate the field with the value at its own key path\n * and move the result to the field’s key path, instead of with the value at the field’s key path.\n * @returns {boolean} Whether the field is valid, or `true` if it hasn’t been validated.\n */\nconst validateParentField = (context, { keyPath, value, getParentField, viaSubKey }) => {\n  const { validateArgs, validationMessages, getFieldArgs } = context;\n  const { validities, locale, valueMap } = validateArgs;\n  const fieldConfig = getParentField({ ...getFieldArgs });\n  const fieldKeyPath = keyPath.replace(PAIR_KEY_PATH_REGEX, '');\n\n  if (!fieldConfig || fieldKeyPath in validities[locale]) {\n    return true;\n  }\n\n  const validateKeyPath = viaSubKey ? keyPath : fieldKeyPath;\n\n  const valid = validateField({\n    ...validateArgs,\n    keyPath: validateKeyPath,\n    value: viaSubKey ? value : valueMap[fieldKeyPath],\n  });\n\n  const validity = validities[locale][validateKeyPath];\n\n  // A field that can’t be edited in the locale isn’t validated, so there is nothing to move\n  if (viaSubKey && validity) {\n    delete validities[locale][keyPath];\n    validities[locale][fieldKeyPath] = validity;\n  }\n\n  recordValidationMessages({\n    validities,\n    validationMessages,\n    locale,\n    keyPath: fieldKeyPath,\n    fieldConfig,\n  });\n\n  return valid;\n};\n\n/**\n * Validate a single value of an entry draft, along with the List fields it’s in.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft to validate.\n * @param {LocaleCode} args.locale Locale of the value.\n * @param {FlattenedEntryContent} args.valueMap All the values in the locale.\n * @param {FieldKeyPath} args.keyPath Key path of the value.\n * @param {any} args.value Value.\n * @param {LocaleValidityMap} args.validities Validity state, modified in place.\n * @param {LocaleValidationMessagesMap} args.validationMessages Validation messages, modified in\n * place.\n * @param {boolean} args.enforceRequired Whether an empty required field is an error.\n * @returns {boolean} Whether the value and the lists it’s in are valid.\n */\nconst validateValueEntry = ({\n  draft,\n  locale,\n  valueMap,\n  keyPath,\n  value,\n  validities,\n  validationMessages,\n  enforceRequired,\n}) => {\n  const [prefix] = keyPath.match(COMPONENT_NAME_PREFIX_REGEX) ?? [];\n  const componentName = prefix ? valueMap[`${prefix}__sc_component_name`] : undefined;\n\n  // A value left behind by a rich text editor component that has since been removed has\n  // nothing to be validated against. Without the component name, its field would be looked up\n  // among the entry’s own fields instead, e.g. an image’s `title` as the entry title, and fail\n  // validation with no field to show the error in\n  if (prefix && !componentName) {\n    return true;\n  }\n\n  let valid = true;\n\n  /** @type {FieldValidationContext} */\n  const context = {\n    validateArgs: { draft, locale, valueMap, validities, enforceRequired, componentName },\n    validationMessages,\n    getFieldArgs: getDraftFieldArgs(draft, {\n      keyPath: stripComponentNamePrefix(keyPath),\n      valueMap,\n      componentName,\n    }),\n  };\n\n  // The items of a List field with subfields or types are flattened to their own subfields,\n  // e.g. `speakers.0.name`, so no key path stands for such a list. Validate each list the value\n  // is in through the path of its items, or its item count would never be checked\n  [...keyPath.matchAll(LIST_ITEM_SUBFIELD_REGEX)].forEach(({ index }) => {\n    const ancestorKeyPath = keyPath.slice(0, index);\n    const ancestorConfig = getConfig(context, ancestorKeyPath);\n\n    if (\n      ancestorConfig?.widget === 'list' &&\n      !validateListItself(context, {\n        listKeyPath: ancestorKeyPath,\n        fieldConfig: ancestorConfig,\n        listFieldConfig: ancestorConfig,\n      }).valid\n    ) {\n      valid = false;\n    }\n  });\n\n  const listKeyPath = ITEM_INDEX_SUFFIX_REGEX.test(keyPath)\n    ? keyPath.replace(ITEM_INDEX_SUFFIX_REGEX, '')\n    : undefined;\n\n  const listFieldConfig = listKeyPath === undefined ? undefined : getConfig(context, listKeyPath);\n\n  // An item of a List field without subfields has no config of its own, so the list stands in\n  // for it: the list is validated as a whole, while the items, plain strings, are left alone\n  const fieldConfig =\n    getConfig(context, keyPath) ??\n    (listFieldConfig?.widget === 'list' &&\n    !getListFieldInfo(/** @type {ListField} */ (listFieldConfig)).hasSubFields\n      ? listFieldConfig\n      : undefined);\n\n  if (!fieldConfig) {\n    // The value may be a KeyValue pair, or the code or language of a Code field\n    const pairValid = validateParentField(context, {\n      keyPath,\n      value,\n      getParentField: getKeyValueField,\n      viaSubKey: true,\n    });\n\n    const codeValid = validateParentField(context, {\n      keyPath,\n      value,\n      getParentField: getCodeField,\n      viaSubKey: false,\n    });\n\n    if (!pairValid || !codeValid) {\n      valid = false;\n    }\n\n    return valid;\n  }\n\n  // Skip unsupported field types: not built-in or custom\n  if (getFieldKind(fieldConfig) === 'unknown') {\n    return valid;\n  }\n\n  // Validate a list itself before the items. The item’s config is the subfield of a list with\n  // `field`, so the list’s own config has to be used for the list’s messages, such as the\n  // minimum item count\n  if (listKeyPath !== undefined) {\n    const { valid: listValid, validateItems } = validateListItself(context, {\n      listKeyPath,\n      fieldConfig,\n      listFieldConfig: /** @type {Field} */ (listFieldConfig),\n    });\n\n    if (!listValid) {\n      valid = false;\n    }\n\n    if (!validateItems) {\n      return valid;\n    }\n  }\n\n  if (!validateField({ ...context.validateArgs, keyPath, value })) {\n    valid = false;\n  }\n\n  recordValidationMessages({ validities, validationMessages, locale, keyPath, fieldConfig });\n\n  return valid;\n};\n\n/**\n * Validate the field values and return the results. Mimic the native `ValidityState` API.\n * @param {DraftValueStoreKey} valueStoreKey Key to store the values in {@link EntryDraft}.\n * @param {object} options Options.\n * @param {EntryDraft} options.draft Draft to validate.\n * @param {boolean} [options.enforceRequired] Whether an empty required field is an error. When\n * `false`, such a field is left unmarked, so nothing is shown for it in the editor either.\n * @returns {ValidationResults} Validation results.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/ValidityState\n */\nexport const validateFields = (valueStoreKey, { draft, enforceRequired = true }) => {\n  const { currentLocales } = draft;\n  /** @type {LocaleValidityMap} */\n  const validities = {};\n  /** @type {LocaleValidationMessagesMap} */\n  const validationMessages = {};\n  let valid = true;\n\n  Object.entries(draft[valueStoreKey]).forEach(([locale, valueMap]) => {\n    const valueEntries = Object.entries(valueMap);\n\n    // If the locale is disabled, skip the validation and mark all fields valid\n    if (!currentLocales[locale]) {\n      validities[locale] = Object.fromEntries(\n        valueEntries.map(([keyPath]) => [keyPath, { valid: true }]),\n      );\n      validationMessages[locale] = Object.fromEntries(\n        valueEntries.map(([keyPath]) => [keyPath, []]),\n      );\n\n      return;\n    }\n\n    // Reset the state first\n    validities[locale] = {};\n    validationMessages[locale] = {};\n\n    valueEntries.forEach(([keyPath, value]) => {\n      if (\n        !validateValueEntry({\n          draft,\n          locale,\n          valueMap,\n          keyPath,\n          value,\n          validities,\n          validationMessages,\n          enforceRequired,\n        })\n      ) {\n        valid = false;\n      }\n    });\n  });\n\n  return { valid, validities, validationMessages };\n};\n","import { getArrayItemTarget } from '$lib/services/contents/draft/save/changes';\nimport { buildEntryFileChanges } from '$lib/services/contents/draft/save/file-changes';\nimport { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\nimport { resolveFileConfig } from '$lib/services/contents/file/config';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * Entry,\n * FileChange,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * LocalizedEntry,\n * } from '$lib/types/private';\n * @import { EntryFilePlan } from '$lib/services/contents/draft/save/file-changes';\n */\n\n/**\n * Build a synthetic draft object suitable for {@link formatEntryData} and the field validator.\n * Bulk operations that re-save existing entries — reordering, cascading relation updates — don’t\n * go through the entry editor, so there’s no real draft to serialize with; only the few properties\n * read by the serializer and the validator are needed. The shape is identical for every entry in a\n * given collection, so callers working on a batch should build it once and pass it down to avoid\n * per-entry allocations.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entries belong to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file, for file/singleton\n * collections.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s special index file.\n * @returns {any} Synthetic draft.\n */\nexport const createSyntheticDraft = ({ collection, collectionFile, isIndexFile = false }) => ({\n  collection,\n  collectionName: collection.name,\n  collectionFile,\n  fileName: collectionFile?.name,\n  fields: collectionFile?.fields ?? /** @type {InternalEntryCollection} */ (collection).fields,\n  isIndexFile,\n});\n\n/**\n * Build the `update` {@link FileChange}(s) needed to re-save an existing entry whose content has\n * already been modified in place. One change is produced per file the entry occupies: a single one\n * unless the collection uses a file-per-locale i18n structure.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file, for file/singleton\n * collections.\n * @param {Entry} args.entry Entry with the updated content applied.\n * @param {any} args.draft Synthetic draft from {@link createSyntheticDraft}.\n * @param {IndexedDB} [args.cacheDB] File cache database, when available.\n * @returns {Promise<FileChange[]>} Update changes.\n */\nexport const buildEntryUpdateChanges = async ({\n  collection,\n  collectionFile,\n  entry,\n  draft,\n  cacheDB,\n}) => {\n  const config = /** @type {InternalCollectionFile} */ (collectionFile ?? collection);\n\n  return buildEntryFileChanges({\n    draft,\n    config,\n    _file: resolveFileConfig({ collection, collectionFile, isIndexFile: draft.isIndexFile }),\n    entry,\n    cacheDB,\n    /**\n     * Plan the change to a file of the entry.\n     * @param {InternalLocaleCode} [locale] Locale of the file, or `undefined` for the single file.\n     * @returns {EntryFilePlan | undefined} Planned change.\n     */\n    planChange: (locale) => {\n      if (locale === undefined) {\n        // The default locale can be missing from a single-file i18n entry, e.g. when the file was\n        // written before the locale became the default; another locale then has the same path\n        const { slug, path } = /** @type {LocalizedEntry} */ (\n          getEntryLocaleFile(entry, { defaultLocale: config._i18n.defaultLocale })\n        );\n\n        return { action: 'update', slug, path, currentPath: path, ...getArrayItemTarget(entry) };\n      }\n\n      const { slug, path, content } = entry.locales[locale] ?? {};\n\n      return content ? { action: 'update', slug, path, currentPath: path } : undefined;\n    },\n  });\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { isConfigReadonly } from '$lib/services/config/readonly';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { resolveCacheDB } from '$lib/services/contents/draft/save/file-changes';\nimport { validateAnyField } from '$lib/services/contents/draft/validate/fields';\nimport { getFieldValidationMessages } from '$lib/services/contents/draft/validate/messages';\nimport {\n  buildEntryUpdateChanges,\n  createSyntheticDraft,\n} from '$lib/services/contents/entry/changes';\nimport { getListItemKeys } from '$lib/services/contents/entry/key-paths';\nimport { refreshPermalinks } from '$lib/services/contents/entry/permalink';\nimport { isEntryReadonly } from '$lib/services/contents/entry/readonly';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * CascadeDeleteBlocker,\n * CascadeTarget,\n * Entry,\n * FileChange,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Remove some items from a multi-value field, which stores each of its values under its own index,\n * and renumber the rest, so that the remaining items are stored under consecutive indexes again.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.content Flattened entry content, modified in place.\n * @param {FieldKeyPath} args.listKeyPath Key path of the multi-value field.\n * @param {(key: FieldKeyPath, value: any) => boolean} args.isStale Whether the item stored under\n * the given key path is to be removed.\n */\nexport const compactList = ({ content, listKeyPath, isStale }) => {\n  // The content is being rewritten, so its keys are scanned rather than read from an index\n  const itemKeys = getListItemKeys(content, listKeyPath, { live: true });\n\n  const remainingValues = itemKeys\n    .filter((key) => !isStale(key, content[key]))\n    .map((key) => content[key]);\n\n  itemKeys.forEach((key) => {\n    delete content[key];\n  });\n\n  if (remainingValues.length) {\n    remainingValues.forEach((value, index) => {\n      content[`${listKeyPath}.${index}`] = value;\n    });\n  } else {\n    // This is how an emptied multi-value field is stored in a draft\n    content[listKeyPath] = [];\n  }\n};\n\n/**\n * Check the fields that lost a reference against their own validation rules, such as `required`\n * and `min`, the way a save of the entry would, and describe each one that no longer passes. An\n * entry that is read-only, because of its collection, its collection file or the whole CMS, can’t\n * be rewritten at all, so every one of its fields is described instead. That includes an entry\n * locked by another collection it also belongs to.\n * @param {object} args Arguments.\n * @param {any} args.draft Synthetic draft for the entry holding the fields, from\n * {@link createSyntheticDraft}.\n * @param {Entry} args.entry Entry holding the fields, as stored.\n * @param {InternalCollection} args.collection Collection the entry is edited under.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file, for file/singleton\n * collections.\n * @param {InternalLocaleCode} args.locale Locale of the updated content.\n * @param {FlattenedEntryContent} args.content Updated content.\n * @param {Map<FieldKeyPath, Field>} args.fields Fields to check, keyed by key path — the field\n * itself rather than an item within it, which is what the validator looks at.\n * @returns {CascadeDeleteBlocker[]} Blockers, one per invalid or read-only field.\n */\nexport const getFieldBlockers = ({\n  draft,\n  entry,\n  collection,\n  collectionFile,\n  locale,\n  content,\n  fields,\n}) => {\n  // Only the `readonly` option counts, as explained in `isEntryReadonly()`\n  const readonly = isConfigReadonly({ collection, collectionFile }) || isEntryReadonly(entry);\n\n  return [...fields].flatMap(([keyPath, fieldConfig]) => {\n    /** @type {string[]} */\n    let messages;\n\n    if (readonly) {\n      messages = [_('readonly_reference')];\n    } else {\n      const validity = validateAnyField({\n        draft,\n        locale,\n        keyPath,\n        value: content[keyPath],\n        valueMap: content,\n        // A fresh map, so the field is validated rather than skipped as already validated\n        validities: { [locale]: {} },\n      });\n\n      // The validator declines a field it doesn’t validate in this locale, e.g. a non-i18n field\n      // in a non-default locale, in which case the field is fine by definition\n      if (!validity || validity.valid) {\n        return [];\n      }\n\n      messages = getFieldValidationMessages({ validity, fieldConfig });\n    }\n\n    const collectionName = collection.name;\n\n    return [\n      /** @type {CascadeDeleteBlocker} */ ({\n        collectionName,\n        collectionLabel: collection.label || collectionName,\n        fieldLabel: getFieldLabel({ config: fieldConfig }),\n        entry,\n        summary: getEntrySummary(collection, entry),\n        locale,\n        keyPath,\n        messages,\n      }),\n    ];\n  });\n};\n\n/**\n * Report a field invalid in more than one locale once: the message is the same, and the editor\n * shows the errors locale by locale once the entry is opened.\n * @param {CascadeDeleteBlocker[]} blockers Blockers.\n * @returns {CascadeDeleteBlocker[]} Blockers, without the duplicates.\n */\nexport const dedupeBlockers = (blockers) => {\n  /** @type {Set<string>} */\n  const seen = new Set();\n\n  return blockers.filter(({ entry, keyPath }) => {\n    const key = `${entry.id}\\0${keyPath}`;\n\n    if (seen.has(key)) {\n      return false;\n    }\n\n    seen.add(key);\n\n    return true;\n  });\n};\n\n/**\n * Build the `update` file changes that write the given cascade targets back, one per file the\n * entry occupies.\n * @param {object} args Arguments.\n * @param {CascadeTarget[]} args.targets Cascade targets.\n * @param {IndexedDB} [args.cacheDB] Pre-opened file-cache database to reuse.\n * @returns {Promise<{ changes: FileChange[], savingEntries: Entry[] }>} Collected changes and the\n * entries to be saved.\n */\nexport const buildTargetChanges = async ({ targets, cacheDB }) => {\n  if (!targets.length) {\n    return { changes: [], savingEntries: [] };\n  }\n\n  const db = resolveCacheDB(cacheDB);\n\n  const savingTargets = targets.map(({ entry, collection, collectionFile }) => {\n    const isIndexFile = isCollectionIndexFile(collection, entry);\n\n    return {\n      collection,\n      collectionFile,\n      isIndexFile,\n      // A field referenced by the `preview_path` option may have changed\n      entry: refreshPermalinks({ collection, isIndexFile, entry }),\n    };\n  });\n\n  const perEntryChanges = await Promise.all(\n    savingTargets.map(({ entry, collection, collectionFile, isIndexFile }) =>\n      buildEntryUpdateChanges({\n        collection,\n        collectionFile,\n        entry,\n        draft: createSyntheticDraft({ collection, collectionFile, isIndexFile }),\n        cacheDB: db,\n      }),\n    ),\n  );\n\n  return {\n    changes: perEntryChanges.flat(),\n    savingEntries: savingTargets.map(({ entry }) => entry),\n  };\n};\n","import { getAssetReferenceTarget } from '$lib/services/assets/reference-target';\nimport {\n  createMediaSourceResolver,\n  getAssetReferences,\n  getComparableAssetURL,\n  matchAssetURL,\n} from '$lib/services/assets/references';\nimport { allAssets } from '$lib/services/assets/state';\nimport { cmsConfig } from '$lib/services/config';\nimport { allEntries } from '$lib/services/contents';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport {\n  compactList,\n  dedupeBlockers,\n  getFieldBlockers,\n} from '$lib/services/contents/entry/cascade';\nimport { createSyntheticDraft } from '$lib/services/contents/entry/changes';\nimport { isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { ITEM_INDEX_SUFFIX_REGEX } from '$lib/services/contents/entry/key-paths';\nimport { MEDIA_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getValueFormat } from '$lib/services/contents/fields/rich-text';\nimport { LINKED_IMAGE_REGEX } from '$lib/services/contents/fields/rich-text/constants';\nimport {\n  MARKDOWN_MEDIA_REGEX,\n  parseMediaSource,\n  rewriteMediaStartTag,\n  updateMediaElementURLs,\n} from '$lib/services/contents/fields/rich-text/previews/media-sources';\nimport { getMediaElements } from '$lib/services/contents/fields/rich-text/previews/media-urls';\nimport { parseHTMLFragment, serializeStartTag } from '$lib/services/utils/html';\n\n/**\n * @import {\n * Asset,\n * AssetReference,\n * CascadeDeleteBlocker,\n * CascadeDeletePlan,\n * CascadeTarget,\n * Entry,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * MarkdownField,\n * RichTextField,\n * RichTextValueFormat,\n * } from '$lib/types/public';\n * @import { AssetReferenceTarget } from '$lib/services/assets/references';\n * @import { MediaSource } from '$lib/services/contents/fields/rich-text/previews/media-sources';\n */\n\n/**\n * Get what the references to the given assets are matched by, see {@link getAssetReferenceTarget},\n * with the URLs in the form they’re stored in a field value — without the site’s base URL.\n * @param {Asset[]} assets Assets.\n * @returns {AssetReferenceTarget[]} Targets, without duplicate URLs.\n */\nexport const getReferenceTargets = (assets) => {\n  /** @type {AssetReferenceTarget[]} */\n  const targets = [];\n  /** @type {Set<string>} */\n  const urls = new Set();\n\n  assets.forEach((asset) => {\n    const { url, asset: target } = getAssetReferenceTarget(asset);\n\n    if (url === undefined) {\n      targets.push({ asset: /** @type {Asset} */ (target) });\n\n      return;\n    }\n\n    const comparableURL = getComparableAssetURL(url);\n\n    if (!urls.has(comparableURL)) {\n      urls.add(comparableURL);\n      targets.push({ url: comparableURL });\n    }\n  });\n\n  return targets;\n};\n\n/**\n * Cut a piece of markup out of a Markdown string. Markup on a line of its own — an image in a\n * paragraph of its own, typically — takes the line with it, along with one of the blank lines\n * around it, so no empty paragraph is left behind. Nothing else is touched: the rest of the text,\n * including any blank lines in a code block, is the author’s.\n * @param {string} text Markdown.\n * @param {number} index Position of the markup.\n * @param {number} length Length of the markup.\n * @returns {string} Markdown without the markup.\n */\nconst cutMarkup = (text, index, length) => {\n  const end = index + length;\n  const lineStart = text.lastIndexOf('\\n', index - 1) + 1;\n  const nextBreak = text.indexOf('\\n', end);\n  const lineEnd = nextBreak === -1 ? text.length : nextBreak;\n\n  if (text.slice(lineStart, index).trim() || text.slice(end, lineEnd).trim()) {\n    // The markup shares its line with something else\n    return text.slice(0, index) + text.slice(end);\n  }\n\n  const before = text.slice(0, lineStart);\n  // Everything from the line break ending the line, if any\n  const after = text.slice(lineEnd);\n  // A blank line on each side — or the start or end of the text — means one of the blank lines\n  // would be in excess once the line is gone\n  const blankBefore = !before || /\\n[ \\t]*\\n$/.test(before);\n  const blankAfter = !after || /^\\n[ \\t]*\\n/.test(after);\n\n  if (blankBefore && blankAfter) {\n    return after\n      ? // The line’s own break and the blank line after it\n        before + after.replace(/^\\n[ \\t]*\\n/, '')\n      : // The blank line before the last line\n        before.replace(/\\n[ \\t]*\\n$/, '\\n');\n  }\n\n  // The line’s own break goes, unless the line has none, in which case the preceding one does\n  return after ? before + after.slice(1) : before.replace(/\\n$/, '');\n};\n\n/**\n * Elements that are removed along with the media element they hold, once nothing else is left in\n * them, so no empty paragraph, figure or link is left behind.\n */\nconst MEDIA_WRAPPER_TAG_NAMES = ['a', 'div', 'figure', 'p', 'picture', 'span'];\n\n/**\n * Check if a media element has nothing left to display once its URLs pointing at the deleted assets\n * have been removed: an image or a `<source>` without a `src` or `srcset`, or a video or audio\n * without a `src` or a `<source>`. A video keeps playing without its `poster`.\n * @param {Element} element Media element.\n * @returns {boolean} Result.\n */\nconst isMediaElementEmpty = (element) =>\n  ['img', 'source'].includes(element.localName)\n    ? !element.hasAttribute('src') && !element.hasAttribute('srcset')\n    : !element.hasAttribute('src') && !element.querySelector(':scope > source');\n\n/**\n * Remove a media element left with nothing to display from the parsed HTML, along with any wrapper\n * left empty. An image in a `<picture>` takes the picture with it, as its `<source>` elements\n * display nothing without one.\n * @param {Element} element Media element.\n */\nconst removeMediaElement = (element) => {\n  /** @type {Element | null} */\n  let target = element;\n\n  if (element.localName === 'img' && element.parentElement?.localName === 'picture') {\n    target = element.parentElement;\n  }\n\n  for (;;) {\n    const parent = /** @type {Element | null} */ (target.parentElement);\n\n    target.remove();\n\n    if (\n      !parent ||\n      !MEDIA_WRAPPER_TAG_NAMES.includes(parent.localName) ||\n      parent.childElementCount ||\n      /** @type {string} */ (parent.textContent).trim()\n    ) {\n      break;\n    }\n\n    target = parent;\n  }\n};\n\n/**\n * Remove the media pointing at the deleted assets from an HTML string. A URL pointing at a deleted\n * asset is removed from its element, e.g. a `srcset` candidate or a video `poster`, and an element\n * left with nothing to display goes, along with any wrapper left empty.\n * @param {string} value HTML.\n * @param {(source: MediaSource) => boolean} isStale Function checking whether a URL, as parsed by\n * `parseMediaSource()`, points at a deleted asset.\n * @returns {string} HTML without the media, or the original one if nothing is removed.\n */\nconst removeHTMLMedia = (value, isStale) => {\n  const template = parseHTMLFragment(value);\n  const elements = getMediaElements(template);\n\n  const affected = new Set(\n    elements.filter((element) =>\n      updateMediaElementURLs(element, (_src, source) => (isStale(source) ? null : undefined)),\n    ),\n  );\n\n  if (!affected.size) {\n    return value;\n  }\n\n  // A `<source>` comes after its video or audio, so go backwards to have it removed first, then\n  // see if the video or audio has anything left. An element that had nothing to display in the\n  // first place is the author’s, and left as is\n  elements.reverse().forEach((element) => {\n    if (!affected.has(element) || !isMediaElementEmpty(element)) {\n      return;\n    }\n\n    const { parentElement: parent } = element;\n\n    if (element.localName === 'source' && parent && ['audio', 'video'].includes(parent.localName)) {\n      affected.add(parent);\n    }\n\n    removeMediaElement(element);\n  });\n\n  return template.innerHTML;\n};\n\n/**\n * Sticky version of `LINKED_IMAGE_REGEX`, to tell whether a Markdown image is the content of a\n * link.\n */\nconst STICKY_LINKED_IMAGE_REGEX = new RegExp(LINKED_IMAGE_REGEX.source, 'y');\n\n/**\n * Get the length of the linked image starting right before the given Markdown image, e.g.\n * `[![a](a.png)](a.png)`, if the image is the content of a link.\n * @param {string} value Markdown.\n * @param {number} index Position of the image.\n * @param {string} markup Image.\n * @returns {number | undefined} Length of the linked image, if any.\n */\nconst getLinkedImageLength = (value, index, markup) => {\n  if (value[index - 1] !== '[') {\n    return undefined;\n  }\n\n  STICKY_LINKED_IMAGE_REGEX.lastIndex = index - 1;\n\n  const [linkedImage] = STICKY_LINKED_IMAGE_REGEX.exec(value) ?? [];\n\n  return linkedImage?.startsWith(`[${markup}](`) ? linkedImage.length : undefined;\n};\n\n/**\n * Remove the media pointing at the deleted assets from a Markdown string: a Markdown image is cut\n * out, along with the link it’s the content of, if any, as the link has nothing left to display,\n * and so is an image or a `<source>` written as raw HTML once it has nothing left to display.\n * The start tag of a video or audio written as raw HTML only loses its URLs pointing at the deleted\n * assets, as its content and end tag aren’t matched along with it.\n * @param {string} value Markdown.\n * @param {(source: MediaSource) => boolean} isStale Function checking whether a URL, as parsed by\n * `parseMediaSource()`, points at a deleted asset.\n * @returns {string} Markdown without the media.\n */\nconst removeMarkdownMedia = (value, isStale) =>\n  // Cut from the end, so the positions of the earlier matches stay valid\n  [...value.matchAll(MARKDOWN_MEDIA_REGEX)].reduceRight((text, match) => {\n    const { index, 0: markup, groups: { src = '', tag = undefined } = {} } = match;\n\n    if (tag === undefined) {\n      if (!isStale(parseMediaSource(src, 'markdown'))) {\n        return text;\n      }\n\n      const linkedImageLength = getLinkedImageLength(value, index, markup);\n\n      return linkedImageLength === undefined\n        ? cutMarkup(text, index, markup.length)\n        : cutMarkup(text, index - 1, linkedImageLength);\n    }\n\n    const element = rewriteMediaStartTag({\n      value,\n      tag,\n      index,\n      /**\n       * Remove a URL pointing at a deleted asset.\n       * @param {string} _url URL.\n       * @param {MediaSource} source URL, as parsed by `parseMediaSource()`.\n       * @returns {null | undefined} `null` to remove the URL, or `undefined` to leave it as is.\n       */\n      callback: (_url, source) => (isStale(source) ? null : undefined),\n    });\n\n    if (!element) {\n      return text;\n    }\n\n    if (['img', 'source'].includes(element.localName) && isMediaElementEmpty(element)) {\n      return cutMarkup(text, index, markup.length);\n    }\n\n    return text.slice(0, index) + serializeStartTag(element) + text.slice(index + markup.length);\n  }, value);\n\n/**\n * Remove the media pointing at the deleted assets from a Markdown or RichText field value.\n * @param {object} args Arguments.\n * @param {string} args.value Field value.\n * @param {RichTextValueFormat} args.format Value format, as returned by `getValueFormat()`.\n * @param {Set<string>} args.urls URLs of the deleted assets.\n * @param {Set<string>} [args.paths] Paths of the deleted assets without a URL, as in an\n * entry-relative folder, which a media URL points at when it resolves to the asset.\n * @param {Entry} args.entry Entry holding the field.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name.\n * @param {InternalLocaleCode} [args.locale] Locale the field is in, which an entry-relative media\n * URL is relative to.\n * @param {FieldKeyPath} args.keyPath Key path of the field.\n * @param {FlattenedEntryContent} args.valueMap Content holding the field.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s special index file.\n * @param {MarkdownField | RichTextField} args.fieldConfig Field config, whose own `media_folder`\n * and those of its editor components a relative media URL may be resolved against.\n * @returns {string} Value without the media.\n */\nexport const removeEmbeddedMedia = ({\n  value,\n  format,\n  urls,\n  paths = new Set(),\n  entry,\n  collectionName,\n  fileName,\n  locale,\n  keyPath,\n  valueMap,\n  isIndexFile,\n  fieldConfig,\n}) => {\n  const resolve = createMediaSourceResolver({\n    entry,\n    collectionName,\n    fileName,\n    locale,\n    keyPath,\n    valueMap,\n    isIndexFile,\n    fieldConfig,\n  });\n\n  /**\n   * Check whether a media URL points at a deleted asset.\n   * @param {MediaSource} source URL, as parsed by `parseMediaSource()`.\n   * @returns {boolean} Result.\n   */\n  const isStale = (source) => {\n    // Matched the same way as the references are found, see `getAssetReferences()`, e.g. with a\n    // space encoded as `%20`, as the CMS writes it in a body, or with a fragment\n    if (matchAssetURL(source, (url) => urls.has(url))) {\n      return true;\n    }\n\n    if (!paths.size) {\n      return false;\n    }\n\n    // Resolve the path the way the editor does to display it, without loading the asset\n    const path = resolve(source.url)?.asset?.path;\n\n    return path !== undefined && paths.has(path);\n  };\n\n  return format === 'html' ? removeHTMLMedia(value, isStale) : removeMarkdownMedia(value, isStale);\n};\n\n/**\n * Remove the references to the deleted assets from a copy of the given content map: an Image or\n * File field is left empty, or loses the items in question and has its remaining items renumbered\n * if it holds several files, and a Markdown or rich text field loses the images and other media.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.content Flattened entry content. Not modified.\n * @param {AssetReference[]} args.references References to remove, all in this content.\n * @param {Set<string>} args.urls URLs of the deleted assets.\n * @param {Set<string>} [args.paths] Paths of the deleted assets without a URL.\n * @returns {{ content: FlattenedEntryContent, fields: Map<FieldKeyPath, Field> }}\n * Updated content and the fields that lost a reference, keyed by key path — the field itself\n * rather than an item within it, which is what the validator looks at.\n */\nexport const removeAssetReferences = ({ content, references, urls, paths = new Set() }) => {\n  const updatedContent = { ...content };\n  /** @type {Map<FieldKeyPath, Field>} */\n  const fields = new Map();\n  /** @type {Map<FieldKeyPath, Set<FieldKeyPath>>} */\n  const staleListItems = new Map();\n\n  references.forEach(({ entry, collection, collectionFile, locale, keyPath, fieldConfig }) => {\n    const { widget: fieldType = 'string' } = fieldConfig;\n\n    if (!MEDIA_FIELD_TYPES.includes(fieldType)) {\n      // The reference is an image or other media embedded in a Markdown or rich text field\n      const richTextField = /** @type {MarkdownField | RichTextField} */ (fieldConfig);\n\n      updatedContent[keyPath] = removeEmbeddedMedia({\n        value: content[keyPath],\n        format: getValueFormat(richTextField),\n        urls,\n        paths,\n        entry,\n        collectionName: collection.name,\n        fileName: collectionFile?.name,\n        locale,\n        keyPath,\n        valueMap: content,\n        isIndexFile: isCollectionIndexFile(collection, entry),\n        fieldConfig: richTextField,\n      });\n\n      fields.set(keyPath, fieldConfig);\n\n      return;\n    }\n\n    if (isFieldMultiple(fieldConfig)) {\n      // The items are removed together once every reference is known, as the rest have to be\n      // renumbered\n      const listKeyPath = keyPath.replace(ITEM_INDEX_SUFFIX_REGEX, '');\n\n      staleListItems.set(listKeyPath, (staleListItems.get(listKeyPath) ?? new Set()).add(keyPath));\n      fields.set(listKeyPath, fieldConfig);\n\n      return;\n    }\n\n    updatedContent[keyPath] = '';\n    fields.set(keyPath, fieldConfig);\n  });\n\n  staleListItems.forEach((staleKeys, listKeyPath) => {\n    /**\n     * Check whether an item holds a reference to a deleted asset.\n     * @param {FieldKeyPath} key Item key path.\n     * @returns {boolean} Result.\n     */\n    const isStale = (key) => staleKeys.has(key);\n\n    compactList({ content: updatedContent, listKeyPath, isStale });\n  });\n\n  return { content: updatedContent, fields };\n};\n\n/**\n * Work out what deleting the given assets means for the entries using them. The uncached\n * implementation of {@link planAssetDeletion}.\n * @param {Asset[]} assets Assets being deleted.\n * @returns {Promise<CascadeDeletePlan>} Plan.\n */\nconst createAssetDeletionPlan = async (assets) => {\n  const referenceTargets = getReferenceTargets(assets);\n  /** @type {Set<string>} */\n  const urls = new Set();\n  /** @type {Set<string>} */\n  const paths = new Set();\n\n  referenceTargets.forEach(({ url, asset }) => {\n    if (asset) {\n      paths.add(asset.path);\n    } else {\n      urls.add(/** @type {string} */ (url));\n    }\n  });\n\n  // One pass over the entries finds the references to every asset, however many there are\n  const references = await getAssetReferences(referenceTargets);\n  const referencesByEntry = Map.groupBy(references, ({ entry }) => entry.id);\n\n  const results = [...referencesByEntry.values()].map((entryReferences) => {\n    // An entry belonging to several collections is written once, under the first collection its\n    // fields resolve in, the way any save writes it under the collection it’s edited in\n    const [{ entry, collection, collectionFile }] = entryReferences;\n\n    const draft = createSyntheticDraft({\n      collection,\n      collectionFile,\n      isIndexFile: isCollectionIndexFile(collection, entry),\n    });\n\n    const referencesByLocale = Map.groupBy(\n      entryReferences.filter(\n        (r) => r.collection === collection && r.collectionFile === collectionFile,\n      ),\n      ({ locale }) => locale,\n    );\n\n    /** @type {Entry['locales']} */\n    const updatedLocales = {};\n    /** @type {CascadeDeleteBlocker[]} */\n    const blockers = [];\n\n    referencesByLocale.forEach((localeReferences, locale) => {\n      const localizedEntry = entry.locales[locale];\n\n      const { content, fields } = removeAssetReferences({\n        content: localizedEntry.content,\n        references: localeReferences,\n        urls,\n        paths,\n      });\n\n      updatedLocales[locale] = { ...localizedEntry, content };\n      blockers.push(\n        ...getFieldBlockers({ draft, entry, collection, collectionFile, locale, content, fields }),\n      );\n    });\n\n    /** @type {CascadeTarget} */\n    const target = {\n      entry: { ...entry, locales: { ...entry.locales, ...updatedLocales } },\n      collection,\n      collectionFile,\n    };\n\n    return { target, blockers };\n  });\n\n  return {\n    targets: results.map(({ target }) => target),\n    blockers: dedupeBlockers(results.flatMap(({ blockers }) => blockers)),\n  };\n};\n\n/**\n * The last plan worked out, along with what it was worked out from.\n * @type {{\n * key: string,\n * entries: Entry[],\n * assets: Asset[],\n * config: object | undefined,\n * plan: Promise<CascadeDeletePlan>,\n * } | undefined}\n */\nlet lastPlan = undefined;\n\n/* v8 ignore next */\n/**\n * Reset {@link lastPlan} for tests.\n */\nexport const _resetAssetDeletionPlan = () => {\n  lastPlan = undefined;\n};\n\n/**\n * Work out what deleting the given assets means for the entries using them: each reference is\n * removed, unless doing so would leave the field in breach of its own validation rules — a\n * `required` Image field with nothing left, a multi-file field with fewer than `min` files, a body\n * with nothing but the image — in which case the deletion is reported as blocked, so the entries\n * stay valid. See the counterpart for entries, `planCascadeDelete()`.\n *\n * The confirmation dialog works the plan out before the deletion does, so the last plan is kept and\n * handed out again for the same assets, as long as the entries, the assets and the configuration it\n * was worked out from haven’t been replaced since, which any change to them does.\n * @param {Asset[]} assets Assets being deleted.\n * @returns {Promise<CascadeDeletePlan>} Plan.\n */\nexport const planAssetDeletion = (assets) => {\n  const key = assets.map(({ path }) => path).join('\\n');\n  const { current: entries } = allEntries;\n  const { current: allAssetList } = allAssets;\n  const { current: config } = cmsConfig;\n\n  if (\n    lastPlan?.key === key &&\n    lastPlan.entries === entries &&\n    lastPlan.assets === allAssetList &&\n    lastPlan.config === config\n  ) {\n    return lastPlan.plan;\n  }\n\n  const plan = createAssetDeletionPlan(assets);\n\n  lastPlan = { key, entries, assets: allAssetList, config, plan };\n\n  // Don’t hand out a failed plan again; the next call tries anew\n  plan.catch(() => {\n    if (lastPlan?.plan === plan) {\n      lastPlan = undefined;\n    }\n  });\n\n  return plan;\n};\n","import { assetUpdatesToast } from '$lib/services/assets/data';\nimport { planAssetDeletion } from '$lib/services/assets/data/cascade';\nimport { assertOutsideCmsFolders } from '$lib/services/assets/reserved';\nimport { focusedAsset } from '$lib/services/assets/state';\nimport { saveChanges } from '$lib/services/backends/save';\nimport { UPDATE_TOAST_DEFAULT_STATE } from '$lib/services/contents/collection/data';\nimport { buildTargetChanges } from '$lib/services/contents/entry/cascade';\n\n/**\n * @import { Asset, FileChange } from '$lib/types/private';\n */\n\n/**\n * Update the asset stores after deleting assets.\n * @param {object} args Arguments.\n * @param {Asset[]} args.assets List of assets that have been deleted.\n * @param {boolean} [args.notify] Whether to show a toast reporting the deletion. Default: `true`.\n */\nexport const updateStores = ({ assets, notify = true }) => {\n  // Clear asset info in the sidebar\n  if (assets.some(({ path }) => focusedAsset.current?.path === path)) {\n    focusedAsset.current = undefined;\n  }\n\n  if (notify) {\n    assetUpdatesToast.current = {\n      ...UPDATE_TOAST_DEFAULT_STATE,\n      deleted: true,\n      count: assets.length,\n    };\n  }\n};\n\n/**\n * Delete the given assets from the backend and update the asset stores. The entries using the\n * assets are rewritten in the same commit so that no reference is left dangling.\n * @param {Asset[]} assets List of assets to be deleted.\n * @param {object} [options] Options.\n * @param {FileChange[]} [options.extraChanges] Changes to files other than the assets, committed\n * along with the deletion, e.g. the `.gitkeep` of a folder being deleted.\n * @param {boolean} [options.notify] Whether to show a toast reporting the deletion. Default:\n * `true`. A caller that reports the result in its own words, like a folder deletion, turns it off.\n * @throws {Error} When removing the references would leave an entry invalid, e.g. a required Image\n * field with nothing left. The dialog reports this before the deletion is confirmed, so this is\n * only a safeguard.\n */\nexport const deleteAssets = async (assets, { extraChanges = [], notify = true } = {}) => {\n  assertOutsideCmsFolders([...assets, ...extraChanges].map(({ path }) => path));\n\n  const { targets, blockers } = await planAssetDeletion(assets);\n\n  if (blockers.length) {\n    throw new Error('Cannot delete assets that entries require', { cause: blockers });\n  }\n\n  const { changes: cascadeChanges, savingEntries } = await buildTargetChanges({ targets });\n\n  await saveChanges({\n    changes: [\n      ...assets.map(\n        ({ path, sha }) => /** @type {FileChange} */ ({ action: 'delete', path, previousSha: sha }),\n      ),\n      ...cascadeChanges,\n      ...extraChanges,\n    ],\n    savingEntries,\n    options: { commitType: 'deleteMedia' },\n  });\n\n  updateStores({ assets, notify });\n};\n","import { getPathInfo } from '@sveltia/utils/file';\n\nimport { assetUpdatesToast } from '$lib/services/assets/data';\nimport { deleteAssets } from '$lib/services/assets/data/delete';\nimport { moveAssets } from '$lib/services/assets/data/move';\nimport { allAssetFolders } from '$lib/services/assets/folders';\nimport { assertOutsideCmsFolders } from '$lib/services/assets/reserved';\nimport { publishedAssets } from '$lib/services/assets/state';\nimport { focusedSubfolder } from '$lib/services/assets/subfolders';\nimport { gitConfigFiles } from '$lib/services/backends/git/shared/config';\nimport { saveChanges } from '$lib/services/backends/save';\nimport { UPDATE_TOAST_DEFAULT_STATE } from '$lib/services/contents/collection/data';\n\n/**\n * @import { Asset, BaseConfigListItem, FileChange } from '$lib/types/private';\n */\n\n/**\n * Name of the placeholder file that keeps an otherwise empty folder in a Git repository, which has\n * no way to store a folder on its own.\n */\nexport const GITKEEP_FILE_NAME = '.gitkeep';\n\n/**\n * Create a function that checks if a file belongs to a folder: whether it’s below the folder, at\n * any depth, but not in another asset folder configured below it, such as a collection’s\n * `media_folder` nested in the global one. The files of a nested asset folder are that folder’s,\n * which the Asset Library lists separately, so they’re neither moved along with a renamed subfolder\n * nor deleted with it — like the subfolder list, which leaves them out as well.\n * @param {string} dirPath Folder path, e.g. `static/images/2024`.\n * @returns {(path: string) => boolean} Function taking a file path.\n */\nconst createSubfolderFileFilter = (dirPath) => {\n  const prefix = `${dirPath}/`;\n\n  const nestedFolderPrefixes = allAssetFolders.current\n    .map(({ internalPath }) => internalPath)\n    .filter((path) => path !== undefined && (path === dirPath || path.startsWith(prefix)))\n    .map((path) => `${path}/`);\n\n  return (path) =>\n    path.startsWith(prefix) &&\n    !nestedFolderPrefixes.some((nestedPrefix) => path.startsWith(nestedPrefix));\n};\n\n/**\n * Get the assets below a folder, at any depth, leaving out those of another asset folder nested in\n * it. These are what a rename moves along and a deletion removes, and what the deletion dialog\n * checks the entries for.\n * @param {string} dirPath Folder path, e.g. `static/images/2024`.\n * @returns {Asset[]} Assets.\n */\nexport const getSubfolderAssets = (dirPath) => {\n  const filter = createSubfolderFileFilter(dirPath);\n\n  return publishedAssets.current.filter(({ path }) => filter(path));\n};\n\n/**\n * Get the Git config files below a folder, at any depth, leaving out those of another asset folder\n * nested in it: the `.gitkeep` files that keep the empty folders, and the odd `.gitignore`. Not\n * being assets, these have to be moved and deleted along with the folder separately.\n * @param {string} dirPath Folder path.\n * @returns {BaseConfigListItem[]} Files.\n */\nconst getSubfolderConfigFiles = (dirPath) => {\n  const filter = createSubfolderFileFilter(dirPath);\n\n  return gitConfigFiles.current.filter(({ path }) => filter(path));\n};\n\n/**\n * Create a subfolder in an asset folder by committing a `.gitkeep` file to it. The file is added to\n * the Git config file list once committed, which is what the Asset Library lists an empty folder\n * from, so the folder shows up without a reload.\n * @param {string} dirPath Path of the new folder, e.g. `static/images/2024`.\n * @throws {Error} When the commit fails.\n */\nexport const createSubfolder = async (dirPath) => {\n  const path = `${dirPath}/${GITKEEP_FILE_NAME}`;\n\n  assertOutsideCmsFolders([path]);\n\n  const { commit } = await saveChanges({\n    // An empty `File` rather than an empty string: the local backend takes a falsy `data` for a\n    // file that needs no writing\n    changes: [{ action: 'create', path, data: new File([], GITKEEP_FILE_NAME) }],\n    options: { commitType: 'uploadMedia' },\n  });\n\n  /** @type {BaseConfigListItem} */\n  const configFile = {\n    type: 'config',\n    path,\n    name: GITKEEP_FILE_NAME,\n    sha: commit.files[path]?.sha ?? '',\n    size: 0,\n    text: '',\n  };\n\n  gitConfigFiles.current = [...gitConfigFiles.current, configFile];\n  assetUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, folderCreated: true };\n};\n\n/**\n * Rename a subfolder of an asset folder, which moves everything below it — the assets, whose\n * references in the entries are updated along, and the Git config files — in one commit.\n * @param {object} args Arguments.\n * @param {string} args.dirPath Current folder path, e.g. `static/images/2024`.\n * @param {string} args.newDirPath New folder path, e.g. `static/images/2025`.\n * @throws {Error} When the commit fails.\n */\nexport const renameSubfolder = async ({ dirPath, newDirPath }) => {\n  const configFiles = getSubfolderConfigFiles(dirPath);\n  /**\n   * Get the path of a file once the folder has been renamed.\n   * @param {string} path Current path.\n   * @returns {string} New path.\n   */\n  const rebase = (path) => `${newDirPath}${path.slice(dirPath.length)}`;\n\n  await moveAssets(\n    'move',\n    getSubfolderAssets(dirPath).map((asset) => ({ asset, path: rebase(asset.path) })),\n    {\n      extraChanges: configFiles.map(\n        ({ path, sha, name, text }) =>\n          /** @type {FileChange} */ ({\n            action: 'move',\n            path: rebase(path),\n            previousPath: path,\n            previousSha: sha,\n            data: new File([text ?? ''], name),\n          }),\n      ),\n      notify: false,\n    },\n  );\n\n  gitConfigFiles.current = gitConfigFiles.current.map((file) =>\n    configFiles.includes(file) ? { ...file, path: rebase(file.path) } : file,\n  );\n\n  // Keep the sidebar on the folder under its new name\n  if (focusedSubfolder.current?.path === dirPath) {\n    focusedSubfolder.current = { name: getPathInfo(newDirPath).basename, path: newDirPath };\n  }\n\n  assetUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, folderRenamed: true };\n};\n\n/**\n * Delete a subfolder of an asset folder along with everything below it: the assets, whose\n * references are removed from the entries, and the Git config files, all in one commit.\n * @param {string} dirPath Folder path, e.g. `static/images/2024`.\n * @throws {Error} When the commit fails, or when removing an asset reference would leave an entry\n * invalid. The dialog checks the latter before the deletion is confirmed.\n */\nexport const deleteSubfolder = async (dirPath) => {\n  const configFiles = getSubfolderConfigFiles(dirPath);\n\n  await deleteAssets(getSubfolderAssets(dirPath), {\n    extraChanges: configFiles.map(\n      ({ path, sha }) => /** @type {FileChange} */ ({ action: 'delete', path, previousSha: sha }),\n    ),\n    notify: false,\n  });\n\n  gitConfigFiles.current = gitConfigFiles.current.filter((file) => !configFiles.includes(file));\n\n  // The sidebar has nothing to describe once the folder is gone\n  if (focusedSubfolder.current?.path === dirPath) {\n    focusedSubfolder.current = undefined;\n  }\n\n  assetUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, folderDeleted: true };\n};\n","<!--\n  @component\n  New Folder dialog, shared by the Asset Library and the asset picker. It creates a subfolder in the\n  given directory and reports the progress and the result, but leaves the user where they are: the\n  new folder is listed along with the others, ready to be opened.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import SubfolderNameDialog from '$lib/components/assets/list/subfolder-name-dialog.svelte';\n  import { runAssetCommit } from '$lib/services/assets/data/commit';\n  import { createSubfolder } from '$lib/services/assets/data/subfolder';\n  import { createPath } from '$lib/services/utils/file';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} open Whether the dialog is open.\n   * @property {string} dirPath Path of the directory the folder is created in, e.g.\n   * `static/images/2024`. An empty string for the repository root.\n   * @property {string[]} takenNames Names of the files and folders already in the directory.\n   */\n\n  /** @type {Props} */\n  let { open = $bindable(false), dirPath, takenNames } = $props();\n</script>\n\n<SubfolderNameDialog\n  bind:open\n  title={_('new_folder')}\n  okLabel={_('new_folder_create')}\n  description={_('new_folder_description', { values: { folder: `/${dirPath}` } })}\n  {takenNames}\n  onSubmit={(name) => {\n    runAssetCommit(() => createSubfolder(createPath([dirPath, name])), {\n      progress: 'creating_folder',\n      failure: 'creating_folder_failed',\n    });\n  }}\n/>\n","<!--\n  @component New Folder button, shared by repository folders and external locations.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon } from '@sveltia/ui';\n\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [disabled] Whether creating a folder is disabled.\n   * @property {() => void} onclick Click handler.\n   * @property {boolean} [floating] Whether the button becomes a floating button on a small screen,\n   * like the one on the Asset Library page.\n   */\n\n  /** @type {Props} */\n  let { disabled = false, onclick, floating = true } = $props();\n</script>\n\n<!-- The ghost button becomes a floating button on a small screen, where it needs a surface -->\n<Button\n  variant={floating && env.isSmallScreen ? 'secondary' : 'ghost'}\n  iconic\n  {disabled}\n  aria-label={_('new_folder')}\n  {onclick}\n>\n  {#snippet startIcon()}\n    <Icon name=\"create_new_folder\" />\n  {/snippet}\n</Button>\n","import { _, locale as appLocale } from '@sveltia/i18n';\n\nimport { allEntries } from '$lib/services/contents';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getIdentifierFieldName } from '$lib/services/contents/collection/identifier';\nimport { getSortKeyLabel } from '$lib/services/contents/collection/view/sort-keys';\nimport {\n  getConfiguredTableColumns,\n  isTemplateColumnKey,\n  METADATA_KEYS,\n  METADATA_TEMPLATE_TAGS,\n  SINGLE_TAG_REGEX,\n  SUMMARY_COLUMN_KEY,\n} from '$lib/services/contents/collection/view/table-keys';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getEntryDisplayLocale } from '$lib/services/contents/entry/paths';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { getFieldDisplayValue } from '$lib/services/contents/entry/values';\nimport { getLocalizedOption } from '$lib/services/contents/i18n/options';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { getCommitAuthorName } from '$lib/services/utils/commit-author';\nimport { formatDate } from '$lib/services/utils/date';\n\n/**\n * @import { Entry, EntryTableColumn, InternalEntryCollection } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Get the name of the only tag of a template column key, if it has no other content and no\n * transformations, e.g. `locales` for `{{locales}}` and `date` for `{{fields.date}}`.\n * @param {string} key Column key.\n * @returns {string | undefined} Tag name.\n */\nconst getSingleTagName = (key) => key.match(SINGLE_TAG_REGEX)?.[1];\n\n/**\n * Check whether a collection has the columns of its table view configured with the `table_columns`\n * option, or its alias `summary_fields`. Only such a collection offers the table view.\n * @param {InternalEntryCollection} collection Entry collection.\n * @returns {boolean} Result.\n */\nexport const hasConfiguredTableColumns = (collection) =>\n  !!getConfiguredTableColumns(collection)?.length;\n\n/**\n * Classify a column key: whether it can be shown in a collection’s table view, and if so, the field\n * it names. A column key is a special key, a template, the key path of a field defined in the\n * collection, or the canonical slug key, e.g. `translationKey`, which is part of the content of\n * each localized entry without being a field.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {any} key Column key.\n * @returns {{ fieldConfig?: Field } | undefined} `undefined` if the key can’t be shown. Otherwise,\n * the field configuration if the key is the key path of a field, which is read from the content of\n * the entry; a key without one is shown some other way.\n */\nconst classifyColumnKey = (collection, key) => {\n  if (typeof key !== 'string' || !key) {\n    return undefined;\n  }\n\n  if (key === SUMMARY_COLUMN_KEY || METADATA_KEYS.includes(key) || isTemplateColumnKey(key)) {\n    return {};\n  }\n\n  const fieldConfig = getField({ collectionName: collection.name, keyPath: key });\n\n  if (fieldConfig) {\n    return { fieldConfig };\n  }\n\n  const { i18nEnabled, canonicalSlug } = collection._i18n;\n\n  return i18nEnabled && key === canonicalSlug.key ? {} : undefined;\n};\n\n/**\n * Check whether a column key can be shown in a collection’s table view: a special key, a template,\n * the key path of a field defined in the collection, or the canonical slug key, e.g.\n * `translationKey`, which is part of the content of each localized entry without being a field.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {any} key Column key.\n * @returns {boolean} Result.\n */\nexport const isTableColumnKey = (collection, key) => !!classifyColumnKey(collection, key);\n\n/**\n * Get the default columns of a collection’s table view: the entry summary, followed by the keys the\n * Sort menu offers, as they are the fields that tell the entries apart. The identifier field, which\n * the summary shows by default, the manual order and the canonical slug are left out.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {string[]} sortKeys Available sort keys.\n * @returns {{ key: string, label?: string }[]} Columns.\n */\nconst getDefaultTableColumns = (collection, sortKeys) => {\n  const { i18nEnabled, canonicalSlug } = collection._i18n;\n  const excludedKeys = [SUMMARY_COLUMN_KEY, '_manual', getIdentifierFieldName(collection)];\n\n  if (i18nEnabled) {\n    excludedKeys.push(canonicalSlug.key);\n  }\n\n  return [\n    { key: SUMMARY_COLUMN_KEY },\n    ...sortKeys.filter((key) => !excludedKeys.includes(key)).map((key) => ({ key })),\n  ];\n};\n\n/**\n * Get the header label of a column.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {string} key Column key.\n * @returns {string} Label.\n */\nconst getColumnLabel = (collection, key) => {\n  if (key === SUMMARY_COLUMN_KEY) {\n    const { summary } = collection;\n    const identifierField = getIdentifierFieldName(collection);\n\n    // Without a summary template, the summary is the identifier field’s value\n    const field = summary\n      ? undefined\n      : getField({ collectionName: collection.name, keyPath: identifierField });\n\n    return getLocalizedOption({ config: field, option: 'label' }) || _('sort_keys._summary');\n  }\n\n  if (isTemplateColumnKey(key)) {\n    const tagName = getSingleTagName(key);\n\n    // A single tag is labelled like the metadata or field it shows; a longer template, such as\n    // `{{dirname}}/{{filename}}`, by itself, as there is nothing to name it after\n    if (!tagName) {\n      return key;\n    }\n\n    if (METADATA_TEMPLATE_TAGS.includes(tagName)) {\n      return _(`table_column_keys.${tagName}`);\n    }\n\n    return getSortKeyLabel({ collection, key: tagName });\n  }\n\n  return getSortKeyLabel({ collection, key });\n};\n\n/**\n * Resolve the given columns of a collection’s table view, leaving out the keys that name no field,\n * which the configuration parser reports. A key listed twice only gets one column.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {{ key: string, label?: string }[]} columns Columns, as configured or by default.\n * @returns {EntryTableColumn[]} Columns.\n */\nconst resolveTableColumns = (collection, columns) => {\n  /** @type {Set<string>} */\n  const seenKeys = new Set();\n\n  return columns.flatMap(({ key, label }) => {\n    const classified = classifyColumnKey(collection, key);\n\n    if (!classified || seenKeys.has(key)) {\n      return [];\n    }\n\n    seenKeys.add(key);\n\n    /** @type {EntryTableColumn} */\n    const column = { key, label: label || getColumnLabel(collection, key), ...classified };\n\n    return [column];\n  });\n};\n\n/**\n * Get the columns of a collection’s table view, which is only offered with the columns configured.\n * The configured columns are used, unless none of them can be shown, e.g. all naming a field the\n * collection doesn’t have; then the default columns, as a row needs something to tell which entry\n * it is.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {string[]} args.sortKeys Keys the Sort menu offers for the collection.\n * @returns {EntryTableColumn[]} Columns.\n */\nexport const getTableColumns = ({ collection, sortKeys }) => {\n  const configured = getConfiguredTableColumns(collection);\n  const columns = configured ? resolveTableColumns(collection, configured) : [];\n\n  return columns.length\n    ? columns\n    : resolveTableColumns(collection, getDefaultTableColumns(collection, sortKeys));\n};\n\n/**\n * Cache of the Relation field cells, keyed by entry, then by column key and locale. Each value is\n * recorded with the entry store’s array it was computed against, as the label comes from another\n * entry, which can change without the referencing entry being replaced.\n * @type {WeakMap<Entry, Map<string, { entries: Entry[], value: TableCellValue }>>}\n */\nconst relationCellCache = new WeakMap();\n\n/**\n * Value of a table view cell: either text, or a checked state for a Boolean field, which is shown\n * as a check mark rather than `true` or `false`.\n * @typedef {{ type: 'text', value: string } | { type: 'boolean', value: boolean }} TableCellValue\n */\n\n/**\n * Get the value of a table view cell for an entry. A field is read from the default locale, or the\n * first locale the entry has if it doesn’t have the default one, as the entry list does, and shown\n * the way a summary template would show it: a date formatted, a Relation field’s referenced entry\n * by its label, the Markdown syntax removed and so on.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {Entry} args.entry Entry.\n * @param {EntryTableColumn} args.column Column.\n * @returns {TableCellValue} Value.\n */\nexport const getTableCellValue = ({ collection, entry, column }) => {\n  const { fieldConfig } = column;\n  // A template made of a special key’s tag, e.g. `{{commit_date}}`, shows the same as the key\n  const tagName = isTemplateColumnKey(column.key) ? getSingleTagName(column.key) : undefined;\n  const key = tagName && METADATA_KEYS.includes(tagName) ? tagName : column.key;\n\n  if (key === SUMMARY_COLUMN_KEY) {\n    return { type: 'text', value: getEntrySummary(collection, entry, { useTemplate: true }) };\n  }\n\n  // A template is formatted the way a `summary` template is, for the index file as well\n  if (isTemplateColumnKey(key)) {\n    return {\n      type: 'text',\n      value: getEntrySummary(collection, entry, {\n        useTemplate: true,\n        template: key,\n        useIndexFileLabel: false,\n      }),\n    };\n  }\n\n  if (key === 'slug') {\n    return { type: 'text', value: entry.slug };\n  }\n\n  if (key === 'commit_author') {\n    return { type: 'text', value: getCommitAuthorName(entry.commitAuthor) || '' };\n  }\n\n  if (key === 'commit_date') {\n    const { commitDate } = entry;\n\n    return {\n      type: 'text',\n      value: commitDate ? formatDate(commitDate, /** @type {string} */ (appLocale.current)) : '',\n    };\n  }\n\n  const { defaultLocale } = collection._i18n;\n  const locale = /** @type {string} */ (getEntryDisplayLocale(entry.locales, defaultLocale));\n  const valueMap = entry.locales[locale]?.content ?? {};\n\n  if (/** @type {Field} */ (fieldConfig)?.widget === 'boolean') {\n    return { type: 'boolean', value: valueMap[key] === true };\n  }\n\n  /**\n   * Get the display value of the field.\n   * @returns {TableCellValue} Value.\n   */\n  const getValue = () => ({\n    type: 'text',\n    value: getFieldDisplayValue({\n      collectionName: collection.name,\n      valueMap,\n      keyPath: /** @type {FieldKeyPath} */ (key),\n      locale,\n      plainText: true,\n      isIndexFile: isCollectionIndexFile(collection, entry),\n    }),\n  });\n\n  // A Relation field’s label is looked up in the referenced collection, which is costly to repeat\n  // for every row on every render, so it’s cached until the entry or any other entry changes\n  if (/** @type {Field} */ (fieldConfig)?.widget === 'relation') {\n    const { current: entries } = allEntries;\n    const cacheKey = `${key}\\0${locale}`;\n    const entryCache = getOrCreate(relationCellCache, entry, () => new Map());\n    const cached = entryCache.get(cacheKey);\n\n    if (cached && cached.entries === entries) {\n      return cached.value;\n    }\n\n    const value = getValue();\n\n    entryCache.set(cacheKey, { entries, value });\n\n    return value;\n  }\n\n  return getValue();\n};\n\n/**\n * Get the sort key a column header sorts the entries by when clicked. The summary column sorts by\n * the summary if the Sort menu offers it, which it does with a summary template; otherwise by the\n * identifier field the summary shows. A template column made of a single tag sorts by the tag.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {EntryTableColumn} args.column Column.\n * @param {string[]} args.sortKeys Keys the Sort menu offers for the collection.\n * @returns {string | undefined} Sort key, or `undefined` if the column can’t be sorted.\n */\nexport const getColumnSortKey = ({ collection, column: { key }, sortKeys }) => {\n  if (key === SUMMARY_COLUMN_KEY && !sortKeys.includes(key)) {\n    const identifierField = getIdentifierFieldName(collection);\n\n    return sortKeys.includes(identifierField) ? identifierField : undefined;\n  }\n\n  // A template made of a single tag, e.g. `{{commit_date}}`, sorts by what the tag shows, if the\n  // entries can be sorted by it\n  const sortKey = isTemplateColumnKey(key) ? getSingleTagName(key) : key;\n\n  return sortKey && sortKeys.includes(sortKey) ? sortKey : undefined;\n};\n","import equal from 'fast-deep-equal';\nimport { untrack } from 'svelte';\n\nimport { initViewSettingsStorage } from '$lib/services/common/view';\nimport { selectedCollection } from '$lib/services/contents/collection';\nimport { hasConfiguredTableColumns } from '$lib/services/contents/collection/view/table';\nimport { createRawState, createRootEffect } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * BackendService,\n * EntryListView,\n * InternalEntryCollection,\n * ViewType,\n * } from '$lib/types/private';\n */\n\n/**\n * View settings for all the entry collections.\n * @type {{ current: Record<string, EntryListView> | undefined }}\n */\nexport const entryListSettings = createRawState();\n\n/**\n * View settings for the selected entry collection. The view type is left out until the user picks\n * one, so the default applies, and isn’t saved as if the user had chosen it. See\n * {@link getEntryViewType}.\n * @type {{ current: EntryListView }}\n */\nexport const currentView = createRawState({});\n\n/**\n * Get the view types offered for an entry collection, the first one being the default, which\n * applies until the user picks one. The table view is only offered if the collection has its\n * columns configured with the `table_columns` option, or its alias `summary_fields`, and the grid\n * view if its entries have thumbnails.\n * @param {InternalEntryCollection | undefined} collection Entry collection.\n * @returns {ViewType[]} View types.\n */\nexport const getEntryViewTypes = (collection) => [\n  ...(collection && hasConfiguredTableColumns(collection) ? /** @type {const} */ (['table']) : []),\n  'list',\n  ...(collection?._thumbnailFieldNames.length ? /** @type {const} */ (['grid']) : []),\n];\n\n/**\n * Pick the view type to show among those offered: the one the user has picked, or the first one,\n * which is the default, if there is none or it isn’t offered anymore, e.g. the grid view of a\n * collection that no longer has thumbnails.\n * @param {ViewType | undefined} type View type the user has picked, if any.\n * @param {ViewType[]} types View types offered, the first one being the default.\n * @returns {ViewType} View type.\n */\nexport const pickOfferedViewType = (type, types) =>\n  type && types.includes(type) ? type : types[0];\n\n/**\n * Get the view type the entry list is shown in. The default applies until the user picks one, and\n * also to a saved view that isn’t offered anymore, e.g. the grid view of a collection that no\n * longer has thumbnails. The list view is used instead of the table view on a screen too small for\n * it, and always in reorder mode.\n * @param {object} args Arguments.\n * @param {ViewType} [args.type] View type the user has picked, if any.\n * @param {ViewType[]} args.types View types offered. See {@link getEntryViewTypes}.\n * @param {boolean} args.isLargeScreen Whether the screen is large enough for the table view.\n * @param {boolean} [args.reordering] Whether the entry list is in reorder mode.\n * @returns {ViewType} View type.\n */\nexport const getEntryViewType = ({ type, types, isLargeScreen, reordering = false }) => {\n  if (reordering) {\n    return 'list';\n  }\n\n  const resolved = pickOfferedViewType(type, types);\n\n  return resolved === 'table' && !isLargeScreen ? 'list' : resolved;\n};\n\n/**\n * View of an entry collection as it was when reorder mode was entered, restored when the mode is\n * exited. `undefined` while not in reorder mode. It’s saved in place of the view applied for\n * reordering, so the user’s own view isn’t lost if the page is reloaded or another collection is\n * selected before reordering is over. This is a plain object, as nothing has to react to it.\n * @type {{ current: { collectionName: string | undefined, view: EntryListView } | undefined }}\n */\nexport const viewBeforeReorder = { current: undefined };\n\n/**\n * Get a key that changes whenever the given view would put the entries in another order or pick\n * other entries: its sorting, filtering or grouping conditions. The entry list starts again from\n * the top when it changes, rather than keeping every row rendered so far, which after a long scroll\n * can be thousands of rows for the new order to render all at once. The view type and the\n * collapsed groups are left out, as they leave the entries where they are.\n * @param {EntryListView} view View.\n * @returns {string} Key.\n */\nexport const getEntryOrderKey = ({ sort, filter, filters, group }) =>\n  JSON.stringify([sort, filter, filters, group]);\n\n/**\n * Initialize {@link entryListSettings} and relevant effects.\n * @param {BackendService} _backend Backend service.\n */\nexport const initSettings = async ({ repository }) => {\n  await initViewSettingsStorage(repository, 'contents-view', entryListSettings);\n\n  // Save the view settings when the view is changed\n  createRootEffect(() => {\n    const _view = currentView.current;\n\n    untrack(() => {\n      const { name } = selectedCollection.current ?? {};\n      const snapshot = viewBeforeReorder.current;\n      const view = snapshot && snapshot.collectionName === name ? snapshot.view : _view;\n      const savedView = entryListSettings.current?.[name ?? ''] ?? {};\n\n      if (name && !equal(view, savedView)) {\n        entryListSettings.current = { ...entryListSettings.current, [name]: view };\n      }\n    });\n  });\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, SelectButton, SelectButtonGroup } from '@sveltia/ui';\n\n  import { pickOfferedViewType } from '$lib/services/contents/collection/view/settings';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { AssetListView, EntryListView, SelectAssetsView, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [disabled] Whether to disable the buttons.\n   * @property {{ current: EntryListView | AssetListView | SelectAssetsView }} currentView Current\n   * view details.\n   * @property {ViewType[]} [types] View types to offer, in the order of the buttons, the first one\n   * being the default. Default: list and grid. The table view is only offered on a large screen,\n   * where it fits.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let { disabled = false, currentView, types = ['list', 'grid'], ...rest } = $props();\n\n  /**\n   * Icon of each view type.\n   * @type {Record<ViewType, string>}\n   */\n  const ICONS = { table: 'table', list: 'format_list_bulleted', grid: 'grid_view' };\n\n  // The first type is the default one, which applies until the user picks a view, and also to a\n  // saved view that isn’t offered anymore, e.g. the grid view of a collection without thumbnails\n  const selectedType = $derived(pickOfferedViewType(currentView.current.type, types));\n  const isGridView = $derived(selectedType === 'grid');\n  // A smaller screen only switches between the list and grid views; the table view is shown as a\n  // list there\n  const hasCompactToggle = $derived(types.includes('list') && types.includes('grid'));\n\n  /**\n   * Switch to the given view type.\n   * @param {ViewType} type View type.\n   */\n  const switchView = (type) => {\n    currentView.current = { ...currentView.current, type };\n  };\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  {#if env.isLargeScreen}\n    {#if types.length > 1}\n      <SelectButtonGroup {disabled} ariaLabel={_('switch_view')} {...rest}>\n        {#each types as type (type)}\n          <SelectButton\n            {disabled}\n            selected={selectedType === type}\n            variant=\"ghost\"\n            iconic\n            tooltip={_(`${type}_view`)}\n            aria-label={_(`${type}_view`)}\n            onSelect={() => {\n              switchView(type);\n            }}\n          >\n            {#snippet startIcon()}\n              <Icon name={ICONS[type]} />\n            {/snippet}\n          </SelectButton>\n        {/each}\n      </SelectButtonGroup>\n    {/if}\n  {:else if hasCompactToggle}\n    <Button\n      {disabled}\n      variant=\"ghost\"\n      iconic\n      tooltip={_(isGridView ? 'list_view' : 'grid_view')}\n      aria-label={_(isGridView ? 'switch_to_list_view' : 'switch_to_grid_view')}\n      onclick={() => {\n        switchView(isGridView ? 'list' : 'grid');\n      }}\n    >\n      {#snippet startIcon()}\n        <Icon name={isGridView ? ICONS.list : ICONS.grid} />\n      {/snippet}\n    </Button>\n  {/if}\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n\n    :global {\n      .select-button-group button {\n        border-radius: var(--sui-button-medium-border-radius) !important;\n      }\n    }\n  }\n</style>\n","import {\n  findPreferredLibraryName,\n  getUploadableServiceEntries,\n} from '$lib/services/integrations/media-libraries/options';\n\n/**\n * @import { MediaLibraryService } from '$lib/types/private';\n */\n\n/**\n * @typedef {{ type: 'wait' } | { type: 'upload' } | { type: 'reject' } | {\n * type: 'switch', serviceId: string }} PendingUploadAction\n */\n\n/**\n * Decide what to do with the files waiting to be uploaded to a cloud storage service, typically\n * dropped on a File field when only such a service is available, and passed to the Select Assets\n * dialog. They go up once the panel of the selected service can take them, which may only be after\n * the user has provided the credentials. The dialog stays mounted while closed, so the location\n * offered first was picked before the files were dropped, and may be a stock photo service: once\n * the dialog opens, another service that can take them is selected, or, if there is none, e.g. with\n * only Cloudinary, the files are rejected so the user can be told rather than leave them out\n * silently.\n * @param {object} args Arguments.\n * @param {boolean} args.open Whether the dialog is open.\n * @param {number} args.pendingFileCount Number of files waiting to be uploaded.\n * @param {string} args.libraryName Name of the selected location.\n * @param {[string, MediaLibraryService][]} args.cloudServiceEntries Cloud storage services offered.\n * @param {boolean} args.canUpload Whether the panel of the selected service can upload files now.\n * @param {string[]} [args.preferredLibraryNames] Names of the media libraries marked with the\n * `default` option, in order of precedence. A marked service that can upload is switched to first,\n * as the files were dropped for it.\n * @returns {PendingUploadAction} Action to take: `upload` the files to the selected service,\n * `switch` to another service, `reject` the files, or `wait` for the dialog to open or for the\n * credentials, or with nothing to upload.\n */\nexport const getPendingUploadAction = ({\n  open,\n  pendingFileCount,\n  libraryName,\n  cloudServiceEntries,\n  canUpload,\n  preferredLibraryNames = [],\n}) => {\n  if (!pendingFileCount) {\n    return { type: 'wait' };\n  }\n\n  const service = cloudServiceEntries.find(([serviceId]) => serviceId === libraryName)?.[1];\n\n  if (service && canUpload) {\n    return { type: 'upload' };\n  }\n\n  // The selected service can take the files once the user has provided the credentials\n  if (!open || !!service?.upload) {\n    return { type: 'wait' };\n  }\n\n  // Cloudinary, for one, only takes files through its own widget\n  const serviceId =\n    findPreferredLibraryName({\n      preferredLibraryNames,\n      repositoryAvailable: false,\n      cloudServiceEntries,\n      uploadRequired: true,\n    }) ?? getUploadableServiceEntries(cloudServiceEntries)[0]?.[0];\n\n  return serviceId ? { type: 'switch', serviceId } : { type: 'reject' };\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { replaceTemplatePlaceholder } from '$lib/services/common/template/replacers';\nimport { hasTemplateTags, replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { getIdentifierFieldName } from '$lib/services/contents/collection/identifier';\nimport { getFillSlugOptions } from '$lib/services/contents/draft/slugs';\nimport { findLibraryOptions } from '$lib/services/integrations/media-libraries/options';\n\n/**\n * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n * @import { ReplaceContext } from '$lib/services/common/template/replacers';\n * @import { MediaField, MediaLibraries } from '$lib/types/public';\n */\n\n/**\n * Result of {@link fillLibraryPrefix}.\n * @typedef {object} FilledLibraryPrefix\n * @property {MediaField} [fieldConfig] Field configuration to use the service with, with the\n * `prefix` option filled.\n * @property {boolean} unresolved Whether the prefix depends on a value the entry doesn’t have yet,\n * so the service can’t be used: its files would end up outside the folder they belong to.\n */\n\n/**\n * Fill the template tags in a prefix with the values of an entry draft.\n * @param {string} prefix The `prefix` option.\n * @param {EntryDraft} draft Entry draft.\n * @param {InternalLocaleCode} [locale] Locale the file is selected for. A field that’s not\n * translated only has a value in the default locale.\n * @returns {string} Filled prefix.\n * @throws {Error} If a tag has no value.\n */\nconst fillPrefixTemplate = (prefix, draft, locale) => {\n  const { collection, fileName, currentValues, isIndexFile, originalEntry } = draft;\n  const options = getFillSlugOptions({ draft });\n  const content = { ...options.content, ...(locale ? currentValues[locale] : undefined) };\n\n  const identifierField = getIdentifierFieldName(\n    collection._type === 'entry' ? collection : undefined,\n  );\n\n  /** @type {ReplaceContext} */\n  const context = {\n    replaceSubContext: {\n      ...options,\n      type: 'library_prefix',\n      content,\n      currentSlug: options.content._slug ?? originalEntry?.slug,\n      locale: locale ?? options.locale,\n      identifierField,\n      basePath: undefined,\n    },\n    getFieldArgs: {\n      collectionName: collection.name,\n      fileName,\n      keyPath: '',\n      valueMap: content,\n      isIndexFile,\n    },\n  };\n\n  return replaceTemplateTags(prefix, (_match, tag) =>\n    replaceTemplatePlaceholder(tag, context),\n  ).trim();\n};\n\n/**\n * Fill the template tags in the field-level `prefix` option of a cloud storage service, so that the\n * files of an entry can go to a folder named after one of its fields, e.g. `{{fields.release}}/`.\n * The options are set on a copy of the field configuration, which takes precedence over the\n * site-level ones when the service resolves them.\n * @param {object} args Arguments.\n * @param {keyof MediaLibraries} args.serviceId Service ID.\n * @param {MediaField} [args.fieldConfig] Field configuration.\n * @param {EntryDraft | null} [args.draft] Entry draft.\n * @param {InternalLocaleCode} [args.locale] Locale the file is selected for.\n * @returns {FilledLibraryPrefix} Field configuration to use, and whether the prefix is unresolved.\n */\nexport const fillLibraryPrefix = ({ serviceId, fieldConfig, draft, locale }) => {\n  const options = /** @type {Record<string, any> | false | undefined} */ (\n    findLibraryOptions(serviceId, fieldConfig)\n  );\n\n  const prefix = isObject(options) ? /** @type {any} */ (options).prefix : undefined;\n\n  if (typeof prefix !== 'string' || !hasTemplateTags(prefix)) {\n    return { fieldConfig, unresolved: false };\n  }\n\n  if (!draft) {\n    return { fieldConfig, unresolved: true };\n  }\n\n  try {\n    return {\n      fieldConfig: /** @type {MediaField} */ ({\n        ...fieldConfig,\n        media_libraries: {\n          .../** @type {MediaField} */ (fieldConfig).media_libraries,\n          [serviceId]: { ...options, prefix: fillPrefixTemplate(prefix, draft, locale) },\n        },\n      }),\n      unresolved: false,\n    };\n  } catch {\n    return { fieldConfig, unresolved: true };\n  }\n};\n","import { getDuplicateFiles } from '$lib/services/assets';\nimport { createRawState, requestAnswer } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Asset, DuplicatesRequest } from '$lib/types/private';\n */\n\n/**\n * The pending request asking the user what to do with duplicate files, which the UI turns into a\n * conflict resolution dialog. It’s `undefined` while no request is outstanding.\n * @type {{ current: DuplicatesRequest | undefined }}\n */\nexport const duplicatesRequest = createRawState();\n\n/**\n * Check for duplicate files and ask the user if they want to replace them. An earlier request still\n * waiting for an answer is cancelled.\n * @param {object} args Arguments.\n * @param {File[]} args.files File list.\n * @param {Asset[]} args.listedAssets Listed assets.\n * @returns {Promise<boolean | undefined>} `true` if the user chooses to replace the existing file,\n * `false` if not, or `undefined` if the dialog is closed without making a choice. When there are no\n * duplicate files, it returns `false` immediately.\n */\nexport const checkDuplicates = async ({ files, listedAssets }) => {\n  const dupFiles = getDuplicateFiles(files, listedAssets);\n  const count = dupFiles.length;\n\n  if (!count) {\n    return false;\n  }\n\n  return requestAnswer(duplicatesRequest, { count, name: dupFiles[0].name }, undefined);\n};\n","import { isURL } from '@sveltia/utils/string';\nimport equal from 'fast-deep-equal';\n\nimport { getExistingEntryAssetFolderPath } from '$lib/services/assets/entry-folder';\nimport { fillInternalPathTemplate } from '$lib/services/assets/entry-relative';\nimport { formatFileName } from '$lib/services/assets/file-name';\nimport { allAssetFolders, getAssetFolder, globalAssetFolder } from '$lib/services/assets/folders';\nimport { getPendingFileName } from '$lib/services/assets/name';\nimport { allAssets } from '$lib/services/assets/state';\nimport { TEMPLATE_TAG_REPLACE_REGEX } from '$lib/services/common/template/constants';\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport { createPublicURL, getAssetFolderPaths } from '$lib/services/contents/draft/save/assets';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { isAcceptedFile } from '$lib/services/integrations/media-libraries/default';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { createPath, getDirName } from '$lib/services/utils/file';\nimport { decodeURISafely } from '$lib/services/utils/url';\nimport { parseForkBranchName } from '$lib/services/workflow/forks';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * AssetLibraryFolderMap,\n * Entry,\n * EntryDraft,\n * InternalLocaleCode,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n */\n\n/**\n * Regular expression to match empty path segments, which are left when a template tag in a public\n * path cannot be resolved, typically because a field used in the entry slug is still empty.\n * @type {RegExp}\n */\nconst EMPTY_PATH_SEGMENT_REGEX = /(?<=.)\\/(?=\\/|$)/g;\n\n/**\n * Get the default library folder map for a File/Image field.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] File name.\n * @param {string} [args.componentName] Custom editor component name for a field-level asset folder.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Key path to the field.\n * @param {boolean} [args.isIndexFile] Whether the asset folder is for the special index file used\n * specifically in Hugo. It works only for field-level media folders in an entry collection.\n * @returns {AssetLibraryFolderMap} Default asset library folder map.\n */\nexport const getAssetLibraryFolderMap = ({\n  collectionName,\n  fileName,\n  componentName,\n  typedKeyPath,\n  isIndexFile,\n}) => {\n  const fieldAssetFolder = getAssetFolder({\n    collectionName,\n    fileName,\n    componentName,\n    typedKeyPath,\n    isIndexFile,\n  });\n\n  const fileAssetFolder = fileName ? getAssetFolder({ collectionName, fileName }) : undefined;\n  const collectionAssetFolder = getAssetFolder({ collectionName });\n  const entryAssetFolder = fileAssetFolder ?? collectionAssetFolder;\n  const globalFolder = globalAssetFolder.current;\n\n  /** @type {AssetLibraryFolderMap} */\n  const map = {\n    field: {\n      folder: fieldAssetFolder,\n      enabled: fieldAssetFolder !== undefined,\n    },\n    entry: {\n      folder: entryAssetFolder,\n      enabled:\n        !!entryAssetFolder && (entryAssetFolder.entryRelative || entryAssetFolder.hasTemplateTags),\n    },\n    file: {\n      folder: fileAssetFolder,\n      enabled:\n        !!fileAssetFolder && !fileAssetFolder.entryRelative && !fileAssetFolder.hasTemplateTags,\n    },\n    collection: {\n      folder: collectionAssetFolder,\n      enabled:\n        !!collectionAssetFolder &&\n        !collectionAssetFolder.entryRelative &&\n        !collectionAssetFolder.hasTemplateTags,\n    },\n    global: {\n      folder: globalFolder,\n      enabled: globalFolder !== undefined,\n    },\n  };\n\n  // Add asset collection folders\n  allAssetFolders.current.forEach((folder) => {\n    if (folder.isAssetCollection && folder.collectionName) {\n      map[folder.collectionName] = { folder, enabled: true };\n    }\n  });\n\n  return map;\n};\n\n/**\n * Get the default asset library folder for a File/Image field.\n * @param {AssetLibraryFolderMap} folderMap Asset library folder map.\n * @returns {AssetFolderInfo | undefined} Default asset library folder, or `undefined` if no folder\n * is enabled, which happens when no internal `media_folder` is configured and only an external\n * media library like Cloudinary is used.\n */\nexport const getDefaultAssetFolder = (folderMap) =>\n  Object.values(folderMap).find(({ enabled }) => enabled)?.folder;\n\n/**\n * Get the folder the field editor puts a newly picked file in, i.e. The default asset library\n * folder of a File/Image field, so a copy of a file ends up in the same place.\n * @param {Parameters<typeof getAssetLibraryFolderMap>[0]} args Arguments. See\n * {@link getAssetLibraryFolderMap}.\n * @returns {AssetFolderInfo | undefined} Folder, or `undefined` if there is no internal folder.\n */\nexport const getFieldAssetFolder = (args) => getDefaultAssetFolder(getAssetLibraryFolderMap(args));\n\n/**\n * Get the target folder path for a File/Image field.\n * @param {object} args Arguments.\n * @param {Entry | undefined} args.entry Original entry.\n * @param {AssetFolderInfo | undefined} args.folder Selected folder.\n * @param {InternalLocaleCode} [args.locale] Locale being edited. With the `multiple_folders` or\n * `multiple_root_folders` i18n structure, each locale’s entry file has a folder of its own, which\n * an entry-relative asset is stored beside. Default: the default locale.\n * @returns {string | undefined} Target folder path.\n */\nexport const getTargetFolderPath = ({ entry, folder, locale }) => {\n  const { collectionName, entryRelative, internalPath, internalSubPath } = folder ?? {};\n\n  if (!entryRelative) {\n    if (internalPath === undefined) {\n      return undefined;\n    }\n\n    return (\n      fillInternalPathTemplate({ internalPath, collectionName, entry, locale }) ??\n      // Replace the tags with a placeholder because the complete path is not determined until the\n      // entry is saved\n      internalPath.replaceAll(TEMPLATE_TAG_REPLACE_REGEX, '-')\n    );\n  }\n\n  // A non-empty `internalSubPath` means the field has its own `media_folder` subfolder (e.g.\n  // `media_folder: \"images1\"`). Append it so that only assets in that specific subfolder are shown,\n  // not assets from sibling field folders (e.g. `images2`).\n  const subPath = internalSubPath || undefined;\n\n  // The folder the entry’s relative assets are saved to, which is the folder the entry occupies if\n  // it has one of its own, e.g. `content/posts/2025/06/hello` for `content/posts/2025/06/hello.md`\n  // with a `{{year}}/{{month}}/{{slug}}` path option\n  if (entry) {\n    return createPath([\n      getExistingEntryAssetFolderPath({ entry, locale, collectionName }),\n      subPath,\n    ]);\n  }\n\n  // Append a placeholder because the complete path is not determined until the entry is saved\n  return subPath ? `${internalPath}/${subPath}/-` : `${internalPath}/-`;\n};\n\n/**\n * Get the name a file that has not been saved to the repository yet will be saved with, before\n * it’s made unique in the target folder. It’s filled with the current draft content if the\n * `filename_template` media library option applies to the file.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft holding the file.\n * @param {string} args.blobURL Blob URL of the file, which is the current field value.\n * @returns {string | undefined} File name, or `undefined` if the draft doesn’t hold the file.\n */\nexport const getUnsavedFileName = ({ draft, blobURL }) => {\n  const item = draft.files[blobURL];\n\n  if (!item) {\n    return undefined;\n  }\n\n  return getPendingFileName({\n    draft,\n    item,\n    defaultLocaleSlug: item.nameTemplate ? getSlugs({ draft }).defaultLocaleSlug : '',\n  });\n};\n\n/**\n * Get the public path to be displayed for a file that has not been saved to the repository yet. An\n * unsaved file is a pending upload cached in the draft and referenced with a temporary blob URL, so\n * the path has to be resolved the same way as it will be when the entry is saved, including any\n * template tags like `{{slug}}` and entry-relative paths.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft holding the file.\n * @param {string} args.blobURL Blob URL of the file, which is the current field value.\n * @param {string} args.fileName File name to be appended to the resolved folder path.\n * @returns {string} Path to be displayed. It’s the file name alone if the target folder is unknown\n * or the public path is empty.\n */\nexport const getUnsavedFileDisplayPath = ({ draft, blobURL, fileName }) => {\n  const { folder, subfolderPath } = draft.files[blobURL] ?? {};\n  const { entryRelative, publicPath = '' } = folder ?? {};\n  // The file sits in the subfolder it was picked for, if any\n  const subPath = createPath([subfolderPath, fileName]);\n\n  // Nothing has to be resolved if the path is absolute and has no template tags\n  if (!folder || (!entryRelative && !hasTemplateTags(publicPath))) {\n    return createPublicURL(publicPath, subPath);\n  }\n\n  const { defaultLocaleSlug } = getSlugs({ draft });\n  const { resolvedPublicPath } = getAssetFolderPaths({ draft, defaultLocaleSlug, folder });\n\n  return createPublicURL(resolvedPublicPath.replace(EMPTY_PATH_SEGMENT_REGEX, ''), subPath);\n};\n\n/**\n * Get the path to display for a File/Image field value. For an unsaved file, this is the public\n * path where the file will be stored, with any template tags like `{{slug}}` and entry-relative\n * paths resolved with the current draft content. It will be the same as the final path in most\n * cases, but it could be different if a file with the same name already exists in the assets\n * folder, and the new file is renamed to avoid conflicts, or if the entry slug changes before\n * saving.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.value Field value: a path, a complete URL or the blob URL of an unsaved\n * file.\n * @param {string} [args.unsavedFileName] Name the unsaved file will be saved with, if the value is\n * the blob URL of an unsaved file.\n * @returns {string} The path to display. If the folder could not be determined, it will only be\n * the file name. It’s empty for an empty value or a blob URL not referring to an unsaved file.\n */\nexport const getFileDisplayPath = ({ draft, value, unsavedFileName }) => {\n  // A value read from a file may be a number or another non-string value\n  if (!value || typeof value !== 'string') {\n    return '';\n  }\n\n  if (unsavedFileName) {\n    return getUnsavedFileDisplayPath({\n      draft,\n      blobURL: value,\n      fileName: decodeURISafely(unsavedFileName.normalize()),\n    });\n  }\n\n  if (value.startsWith('blob:')) {\n    return '';\n  }\n\n  const decodedValue = decodeURISafely(value);\n\n  // Truncate query string for display. This is mainly for Unsplash URLs which have a long query\n  // string for image parameters.\n  if (isURL(decodedValue)) {\n    const url = new URL(decodedValue);\n\n    if (url.search) {\n      url.search = '';\n\n      return `${url}…`;\n    }\n  }\n\n  return decodedValue;\n};\n\n/**\n * Check if a given path is in the target folder or its subfolders.\n * @param {object} args Arguments.\n * @param {string} args.path Path to check.\n * @param {string | undefined} args.folderPath Target folder path.\n * @returns {boolean} `true` if the path is in the target folder.\n */\nconst isInTargetFolder = ({ path, folderPath }) =>\n  folderPath !== undefined &&\n  // An empty path is the repository root, which holds every other path\n  (folderPath === '' ||\n    path === folderPath ||\n    // Handle the case where the target folder is a template with an unresolved placeholder\n    `${path}/-` === folderPath ||\n    path.startsWith(`${folderPath}/`));\n\n/**\n * Check if an asset is in the selected folder.\n * @param {object} args Arguments.\n * @param {Asset} args.asset Asset to check.\n * @param {AssetFolderInfo | undefined} args.folder Selected folder.\n * @param {string | undefined} args.folderPath Target folder path.\n * @returns {boolean} `true` if the asset is in the selected folder.\n */\nexport const isAssetInSelectedFolder = ({ asset, folder, folderPath }) => {\n  if (folder === undefined) {\n    return false;\n  }\n\n  if (!folder.entryRelative) {\n    return (\n      asset.folder?.internalPath === folder.internalPath &&\n      !asset.folder?.entryRelative &&\n      isInTargetFolder({ path: asset.path, folderPath })\n    );\n  }\n\n  // The target folder path of an entry-relative folder is resolved against the entry, so the path\n  // alone tells whether the asset is stored next to it. The folder the asset is filed under can’t\n  // be compared: a folder in a custom editor component has no collection, hence no base folder,\n  // and an asset may be filed under an enclosing global folder instead\n  return isInTargetFolder({ path: getDirName(asset.path), folderPath });\n};\n\n/**\n * Give unsaved assets the file names these will actually get once the entry is saved, so no two\n * assets in the list end up with the same path. An unsaved asset is created with a provisional path\n * made of the target folder path and the raw file name, which can collide with an existing asset or\n * with another pending file of the same name. The renaming logic mirrors `replaceBlobURL()`, which\n * determines the final names at save time.\n * @param {object} args Arguments.\n * @param {Asset[]} args.savedAssets Saved assets in the selected folder.\n * @param {Asset[]} args.unsavedAssets Unsaved assets in the selected folder.\n * @param {boolean} args.slugificationEnabled Whether the file names are slugified on upload.\n * @returns {{ savedAssets: Asset[], unsavedAssets: Asset[] }} Assets with unique paths. A saved\n * asset that a pending file is going to overwrite is excluded, because the pending file already\n * represents it in the list.\n */\nexport const resolveUnsavedAssetPaths = ({ savedAssets, unsavedAssets, slugificationEnabled }) => {\n  if (!unsavedAssets.length) {\n    return { savedAssets, unsavedAssets };\n  }\n\n  /** @type {Map<string, string[]>} Map of a directory name to the file names in that directory. */\n  const namesByDir = new Map();\n  /** @type {Set<string>} Paths of the saved assets to be overwritten. */\n  const replacedPaths = new Set();\n\n  savedAssets.forEach(({ path, name }) => {\n    getOrCreate(namesByDir, getDirName(path), () => []).push(name.normalize());\n  });\n\n  const resolvedUnsavedAssets = unsavedAssets.map((asset) => {\n    const { name, path, replace } = asset;\n    const dirName = getDirName(path);\n    const namesInDir = namesByDir.get(dirName) ?? [];\n\n    // A replacing file keeps its original name because it overwrites the existing asset\n    const newName = formatFileName(name, {\n      slugificationEnabled,\n      assetNamesInSameFolder: replace ? [] : namesInDir,\n    });\n\n    const newPath = dirName ? `${dirName}/${newName}` : newName;\n\n    if (replace) {\n      replacedPaths.add(newPath);\n    } else {\n      namesInDir.push(newName.normalize());\n      namesByDir.set(dirName, namesInDir);\n    }\n\n    return newPath === path ? asset : { ...asset, name: newName, path: newPath };\n  });\n\n  return {\n    savedAssets: replacedPaths.size\n      ? savedAssets.filter(({ path }) => !replacedPaths.has(path))\n      : savedAssets,\n    unsavedAssets: resolvedUnsavedAssets,\n  };\n};\n\n/**\n * Get the list of assets to show in the asset library, filtered by the selected folder, kind and\n * accepted file types.\n * @param {object} args Arguments.\n * @param {'image' | undefined} args.kind Asset kind.\n * @param {string} [args.accept] File types the field accepts, as given by `getAcceptedFileTypes()`.\n * An existing file is never transformed, so one of another type can’t be used.\n * @param {AssetFolderInfo | undefined} args.folder Selected folder.\n * @param {string | undefined} args.folderPath Target folder path.\n * @param {Asset[]} args.unsavedAssets Unsaved assets.\n * @param {File[]} [args.uncheckedFiles] Files just dropped or picked in the asset selection dialog.\n * Their assets are listed whatever their kind and type: a file is only checked once it’s processed,\n * as a transformation can change its format.\n * @param {boolean} [args.slugificationEnabled] Whether the file names are slugified on upload.\n * @returns {Asset[]} List of assets to show in the asset library.\n */\nexport const listAssets = ({\n  kind,\n  accept,\n  folder,\n  folderPath,\n  unsavedAssets,\n  uncheckedFiles = [],\n  slugificationEnabled = false,\n}) => {\n  /**\n   * Check if the given asset belongs to the selected folder.\n   * @param {Asset} asset Asset to check.\n   * @returns {boolean} `true` if the asset is in the selected folder.\n   */\n  const isInSelectedFolder = (asset) => isAssetInSelectedFolder({ asset, folder, folderPath });\n\n  const resolved = resolveUnsavedAssetPaths({\n    // An asset from a contributor’s pull request is theirs to show with their entry, not one to\n    // offer for any other: it isn’t on the configured branch, and it may shadow a published file\n    savedAssets: allAssets.current.filter(\n      (asset) => isInSelectedFolder(asset) && !parseForkBranchName(asset.workflow?.branch ?? ''),\n    ),\n    unsavedAssets: unsavedAssets.filter(isInSelectedFolder),\n    slugificationEnabled,\n  });\n\n  return (\n    [...resolved.unsavedAssets, ...resolved.savedAssets]\n      .filter(\n        (asset) =>\n          (!!asset.file && uncheckedFiles.includes(asset.file)) ||\n          // An asset’s `type` property isn’t a MIME type, so the file name alone gives one\n          ((!kind || kind === asset.kind) && isAcceptedFile({ name: asset.name }, accept)),\n      )\n      .sort((a, b) => a.name.localeCompare(b.name))\n      // Unsaved assets should go first\n      .sort((a, b) => Number(!!b.unsaved) - Number(!!a.unsaved))\n  );\n};\n\n/**\n * Check if an asset with the same content and folder already exists in the unsaved assets.\n * @param {object} args Arguments.\n * @param {string} args.sha Git object ID (SHA-1 hash) of the file.\n * @param {AssetFolderInfo | undefined} args.folder Asset folder.\n * @param {Asset[]} args.unsavedAssets Unsaved assets.\n * @returns {boolean} `true` if the asset already exists.\n */\nexport const hasSameAsset = ({ sha, folder, unsavedAssets }) =>\n  unsavedAssets.some((asset) => !!asset.file && asset.sha === sha && equal(asset.folder, folder));\n","import equal from 'fast-deep-equal';\nimport { sanitize } from 'isomorphic-dompurify';\n\nimport { getEntryAssetFolderPath } from '$lib/services/assets/entry-folder';\nimport { isSameFileName } from '$lib/services/assets/file-name';\nimport { createDisplayBlobURL, getAssetPublicURL } from '$lib/services/assets/info';\nimport { getAssetKind } from '$lib/services/assets/kinds';\nimport { createAssetNameTemplate, getPendingFileName } from '$lib/services/assets/name';\nimport { processFile } from '$lib/services/assets/process';\nimport { allAssets } from '$lib/services/assets/state';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { isAcceptedFile } from '$lib/services/integrations/media-libraries/default';\nimport { createPath, getGitHash } from '$lib/services/utils/file';\nimport { LINK_SANITIZE_OPTIONS } from '$lib/services/utils/string';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * EntryDraft,\n * InternalLocaleCode,\n * SelectedResource,\n * } from '$lib/types/private';\n * @import { DefaultMediaLibraryConfig } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} ProcessResourceResult\n * @property {string | undefined} value Field value for the resource: a public asset path, an\n * external URL, or a temporary blob URL for a file pending upload. `undefined` if the resource\n * cannot be used.\n * @property {string} credit Sanitized photo credit, if the resource comes from a stock photo\n * service.\n * @property {string | undefined} oversizedFileName File name if the file exceeds the size limit.\n * @property {string | undefined} invalidFileName File name if the file is corrupt or mislabeled and\n * therefore cannot be decoded.\n * @property {string | undefined} [mismatchedFileName] File name if the file, once processed, is not\n * one of the accepted file types.\n */\n\n/**\n * Get the blob URL of an unsaved file that matches the given file.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft containing the resource.\n * @param {File} args.file File to be searched.\n * @param {AssetFolderInfo} [args.folder] Asset folder for the field. When the folder is\n * entry-relative, only files in the same folder are considered a match.\n * @param {string} [args.subfolderPath] Subfolder the file is saved to. The same file pending for\n * another subfolder is a different upload.\n * @param {boolean} [args.replace] Whether the file replaces an existing asset with the same name.\n * Such a file must be saved under its own name, so only a pending file replacing one under the same\n * name is a match.\n * @returns {Promise<string | undefined>} Blob URL.\n */\nexport const getExistingBlobURL = async ({\n  draft,\n  file,\n  folder,\n  subfolderPath = '',\n  replace = false,\n}) => {\n  // The Git hash is memoized per file, so the files already in the draft aren’t read again\n  const hash = await getGitHash(file);\n  /** @type {string | undefined} */\n  let foundURL = undefined;\n\n  await Promise.all(\n    Object.entries(draft.files ?? {}).map(async ([blobURL, f]) => {\n      if (\n        !foundURL &&\n        (await getGitHash(f.file)) === hash &&\n        (!folder?.entryRelative || equal(f.folder, folder)) &&\n        (f.subfolderPath ?? '') === subfolderPath &&\n        (!replace || (!!f.replace && isSameFileName(f.file.name, file.name)))\n      ) {\n        foundURL = blobURL;\n      }\n    }),\n  );\n\n  return foundURL;\n};\n\n/**\n * Convert unsaved files to the `Asset` format so these can be browsed just like other assets.\n * @param {object} args Arguments.\n * @param {File} args.file Raw file.\n * @param {string} [args.name] Name the file is saved with. Default: the file’s own name.\n * @param {string} [args.blobURL] Blob URL of the file.\n * @param {AssetFolderInfo | undefined} args.folder Asset folder.\n * @param {string} [args.targetFolderPath] Target folder path.\n * @param {string} [args.subfolderPath] Subfolder below the target folder the file is saved to.\n * @param {boolean} [args.replace] Whether the file overwrites an existing asset with the same name.\n * @returns {Promise<Asset>} Asset.\n */\nexport const convertFileItemToAsset = async ({\n  file,\n  name = file.name,\n  blobURL,\n  folder,\n  targetFolderPath,\n  subfolderPath,\n  replace,\n}) => {\n  const { size } = file;\n\n  return /** @type {Asset} */ ({\n    unsaved: true,\n    replace: !!replace,\n    file,\n    blobURL: blobURL ?? (await createDisplayBlobURL(file)),\n    name,\n    // A provisional path. `listAssets` resolves it against the assets already in the folder,\n    // because the final file name is only determined when the entry is saved.\n    path: createPath([targetFolderPath, subfolderPath, name]),\n    sha: await getGitHash(file),\n    size,\n    kind: getAssetKind(name),\n    folder,\n  });\n};\n\n/**\n * Get all the unsaved assets, including already cached for the draft and dropped ones.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft containing the resource.\n * @param {string} [args.targetFolderPath] Target folder path.\n * @returns {Promise<Asset[]>} Assets.\n */\nexport const getUnsavedAssets = async ({ draft, targetFolderPath }) => {\n  const items = Object.entries(draft.files);\n\n  // The slug is only needed to fill a file name template, and generating it can be costly\n  const defaultLocaleSlug = items.some(([, { nameTemplate }]) => nameTemplate)\n    ? getSlugs({ draft }).defaultLocaleSlug\n    : '';\n\n  return Promise.all(\n    items.map(async ([blobURL, item]) => {\n      const { file, folder, replace, subfolderPath } = item;\n      const name = getPendingFileName({ draft, item, defaultLocaleSlug });\n\n      return convertFileItemToAsset({\n        file,\n        name,\n        blobURL,\n        folder,\n        targetFolderPath,\n        subfolderPath,\n        replace,\n      });\n    }),\n  );\n};\n\n/**\n * Get the saved assets relevant to the current entry draft and folder. For entry-relative folders,\n * the result is filtered to only include assets within the folder the entry’s relative assets are\n * saved to, preventing false duplicate detection across entries that share the same folder config\n * template. That’s the entry’s own folder if it has one, and otherwise the folder it shares with\n * the rest of the collection, as determined by {@link getEntryAssetFolderPath}.\n * @param {EntryDraft} draft Entry draft.\n * @param {AssetFolderInfo | undefined} folder Asset folder associated with the field.\n * @param {InternalLocaleCode} [locale] Locale being edited, whose entry file the assets are stored\n * beside. Default: the default locale.\n * @returns {Asset[]} Filtered saved assets.\n */\nconst getSavedAssetsForEntry = (draft, folder, locale) => {\n  const savedAssets = allAssets.current;\n\n  if (!folder?.entryRelative) {\n    return savedAssets;\n  }\n\n  const { originalEntry, defaultLocale, collection } = draft;\n\n  const entryFilePath = (\n    (locale ? originalEntry?.locales[locale] : undefined) ?? originalEntry?.locales[defaultLocale]\n  )?.path;\n\n  if (!entryFilePath) {\n    // New entry — no saved assets exist for this entry yet\n    return [];\n  }\n\n  const assetFolderPath = getEntryAssetFolderPath({\n    collection,\n    entryFilePath,\n    // An entry-relative folder is always configured with a path\n    internalPath: /** @type {string} */ (folder.internalPath),\n  });\n\n  const expectedPrefix = createPath([assetFolderPath, folder.internalSubPath]);\n\n  return savedAssets.filter((a) => a.path.startsWith(`${expectedPrefix}/`));\n};\n\n/**\n * Get the result of processing a file that is not one of the accepted file types.\n * @param {File} file File.\n * @returns {ProcessResourceResult} Result.\n */\nconst getMismatchedResult = (file) => ({\n  value: undefined,\n  credit: '',\n  oversizedFileName: undefined,\n  invalidFileName: undefined,\n  mismatchedFileName: file.name,\n});\n\n/**\n * Process a selected resource.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft containing the resource.\n * @param {SelectedResource} args.resource Resource to be processed.\n * @param {DefaultMediaLibraryConfig} args.libraryConfig Configuration for the media library.\n * @param {string} [args.accept] File types the field accepts, as given by `getAcceptedFileTypes()`.\n * A file to be uploaded is checked against them once it’s transformed, which can change its format,\n * e.g. a PNG image converted to WebP fits a field only taking WebP images. A file picked in the\n * browser’s file picker is checked as well as a dropped one, as a picker can offer every file.\n * @param {InternalLocaleCode} [args.locale] Locale the resource is selected for. An existing asset\n * in an entry-relative folder is referenced with a path relative to that locale’s entry file.\n * Default: the default locale.\n * @returns {Promise<ProcessResourceResult>} Result of processing the resource.\n */\nexport const processResource = async ({ draft, resource, libraryConfig, accept, locale }) => {\n  const { url, folderPath, credit, replace = false, subfolderPath } = resource;\n  let { asset, file } = resource;\n  /** @type {string | undefined} */\n  let value = '';\n\n  if (file) {\n    const { folder } = resource;\n\n    // A file is uploaded to a repository folder, which there isn’t when only a cloud media library\n    // is configured and neither the field nor the collection has its own `media_folder`\n    if (!folder) {\n      return {\n        value: undefined,\n        credit: '',\n        oversizedFileName: undefined,\n        invalidFileName: undefined,\n      };\n    }\n\n    /** @type {string | undefined} */\n    let existingBlobURL;\n\n    try {\n      existingBlobURL = await getExistingBlobURL({ draft, file, folder, subfolderPath, replace });\n    } catch {\n      // The file can’t be read any more, e.g. it was moved or deleted after being picked. It can’t\n      // be uploaded either way, so it’s reported along with the corrupt files rather than failing\n      // the whole batch and leaving the field stuck in the processing state.\n      return {\n        value: undefined,\n        credit: '',\n        oversizedFileName: undefined,\n        invalidFileName: file.name,\n      };\n    }\n\n    if (existingBlobURL) {\n      // The file is already pending, as processed for another field maybe, which can accept other\n      // file types\n      if (!isAcceptedFile(file, accept)) {\n        return getMismatchedResult(file);\n      }\n\n      value = existingBlobURL;\n    } else {\n      const {\n        file: processedFile,\n        oversized,\n        invalid,\n      } = await processFile(file, libraryConfig ?? {});\n\n      file = processedFile;\n\n      if (invalid) {\n        return {\n          value: undefined,\n          credit: '',\n          oversizedFileName: undefined,\n          invalidFileName: file.name,\n        };\n      }\n\n      // The original file is named, as the user knows it by that name\n      if (!isAcceptedFile(file, accept)) {\n        return getMismatchedResult(/** @type {File} */ (resource.file));\n      }\n\n      const sha = await getGitHash(file);\n      const { name } = file;\n\n      // Check if the selected file has already been uploaded or is pending upload, otherwise\n      // duplicate files lead to an `each_key_duplicate` error in Svelte. A file replacing an\n      // existing one must keep its name, so an identical file under another name doesn’t count\n      const existingAsset = [\n        ...getSavedAssetsForEntry(draft, folder, locale),\n        ...(await getUnsavedAssets({ draft })),\n      ].find(\n        (a) =>\n          a.sha === sha &&\n          equal(a.folder, folder) &&\n          (!replace || ((!a.unsaved || a.replace) && isSameFileName(a.name, name))),\n      );\n\n      if (existingAsset) {\n        // If the selected file has already been uploaded, use the existing asset instead of\n        // uploading the same file twice\n        asset = existingAsset;\n        file = undefined;\n      } else if (oversized) {\n        // Like a corrupt file, an oversized file leaves nothing to add to the field\n        return {\n          value: undefined,\n          credit: '',\n          oversizedFileName: file.name,\n          invalidFileName: undefined,\n        };\n      } else {\n        // Set a temporary blob URL, which will be later replaced with the actual file path. The URL\n        // is made for display, e.g. an SVG image can’t run script, while the file itself is cached\n        value = await createDisplayBlobURL(file);\n\n        // Cache the file itself for later upload. A file replacing an existing one keeps its name\n        const template = replace ? undefined : libraryConfig?.filename_template;\n\n        draft.files[value] = {\n          file,\n          folder,\n          replace,\n          subfolderPath,\n          ...(template\n            ? {\n                nameTemplate: createAssetNameTemplate(template, {\n                  slugificationEnabled: libraryConfig.slugify_filename,\n                }),\n              }\n            : {}),\n        };\n      }\n    }\n  }\n\n  if (asset) {\n    if (!asset.unsaved) {\n      value = getAssetPublicURL(asset, {\n        pathOnly: true,\n        allowSpecial: true,\n        entry: draft.originalEntry,\n        locale,\n      });\n    } else if (asset.blobURL) {\n      // A pending file listed by `getUnsavedAssets()` is referenced with its blob URL. It can’t be\n      // looked up by content, as it may be pending for a subfolder other than the selected one\n      value = asset.blobURL;\n    } else if (asset.file) {\n      value = await getExistingBlobURL({ draft, file: asset.file, folder: asset.folder });\n    }\n  }\n\n  if (url && !file && !asset) {\n    value = url;\n  }\n\n  if (folderPath) {\n    value = folderPath;\n  }\n\n  return {\n    value,\n    credit: credit ? sanitize(credit, LINK_SANITIZE_OPTIONS) : '',\n    oversizedFileName: undefined,\n    invalidFileName: undefined,\n  };\n};\n","import { getTargetFolderPath, listAssets } from '$lib/services/contents/fields/file/helpers';\nimport { getUnsavedAssets } from '$lib/services/contents/fields/file/process';\nimport { watchAsync } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * EntryDraft,\n * InternalLocaleCode,\n * MediaLibraryAssetKind,\n * } from '$lib/types/private';\n */\n\n/**\n * What a {@link FolderAssetListing} is made from.\n * @typedef {object} FolderAssetListingOptions\n * @property {EntryDraft | null | undefined} draft Entry draft.\n * @property {AssetFolderInfo | undefined} folder Folder.\n * @property {InternalLocaleCode | undefined} locale Locale being edited, which an entry-relative\n * folder depends on.\n * @property {MediaLibraryAssetKind | undefined} kind Asset kind.\n * @property {string | undefined} accept Accepted file types.\n * @property {boolean | undefined} slugificationEnabled Whether file names are slugified, which the\n * provisional names of unsaved files depend on.\n * @property {Asset[]} [droppedAssets] Assets created from files dropped in a dialog. They are\n * listed whatever their type, because a transformation may still change it, and only checked once\n * inserted.\n */\n\n/**\n * Stands in for the dropped assets of a listing without any, so that it stays the same value.\n * @type {Asset[]}\n */\nconst NO_ASSETS = [];\n\n/**\n * Reactive listing of the assets in a folder a File/Image field stores its files in, created with\n * {@link createFolderAssetListing}.\n * @typedef {object} FolderAssetListing\n * @property {string | undefined} targetFolderPath Path of the folder, resolved for the entry.\n * @property {Asset[]} listedAssets Assets in the folder, saved or not, that a file dropped there\n * could replace: those of the given kind and accepted types, unsaved ones first.\n * @property {Asset[]} unsavedAssets The draft’s files that have not been saved yet, plus the\n * dropped ones.\n * @property {() => void} reset Forget the unsaved assets until they are read again.\n */\n\n/**\n * Create a reactive listing of the assets in the folder a File/Image field stores its files in,\n * including the files held in the entry draft that have not been saved yet. A dropped file is\n * checked against it for a duplicate name. The draft’s files are read asynchronously whenever the\n * draft or the folder changes, and a read started for an earlier state is never taken over a later\n * one. Call it during component initialization, as it sets up an effect.\n * @param {() => FolderAssetListingOptions} getOptions Function returning the options, so the\n * listing follows their changes. A change of the accepted types, say, doesn’t read the draft’s\n * files again.\n * @returns {FolderAssetListing} Listing.\n */\nexport const createFolderAssetListing = (getOptions) => {\n  const options = $derived(getOptions());\n  // Kept apart as the effect below reads them. The other options only feed derived values, so a\n  // change of one stops there unless it moves the folder path\n  const draft = $derived(options.draft);\n  const droppedAssets = $derived(options.droppedAssets ?? NO_ASSETS);\n  /** @type {Asset[]} */\n  let unsavedAssets = $state([]);\n\n  const targetFolderPath = $derived(\n    getTargetFolderPath({\n      entry: draft?.originalEntry,\n      folder: options.folder,\n      locale: options.locale,\n    }),\n  );\n\n  const listedAssets = $derived(\n    listAssets({\n      kind: options.kind,\n      accept: options.accept,\n      folder: options.folder,\n      folderPath: targetFolderPath,\n      unsavedAssets,\n      uncheckedFiles: droppedAssets.map(({ file }) => /** @type {File} */ (file)),\n      slugificationEnabled: options.slugificationEnabled,\n    }),\n  );\n\n  watchAsync(\n    async () => {\n      // Copied before the first `await`, so that a dropped asset added later is tracked\n      const dropped = [...droppedAssets];\n\n      return [\n        // The draft’s files are read synchronously, so their changes are tracked as well\n        ...(draft ? await getUnsavedAssets({ draft, targetFolderPath }) : []),\n        ...dropped,\n      ];\n    },\n    (assets) => {\n      unsavedAssets = assets;\n    },\n  );\n\n  return {\n    /**\n     * Get the folder path.\n     * @returns {string | undefined} Path.\n     */\n    get targetFolderPath() {\n      return targetFolderPath;\n    },\n    /**\n     * Get the listed assets.\n     * @returns {Asset[]} Assets.\n     */\n    get listedAssets() {\n      return listedAssets;\n    },\n    /**\n     * Get the unsaved assets.\n     * @returns {Asset[]} Assets.\n     */\n    get unsavedAssets() {\n      return unsavedAssets;\n    },\n    /**\n     * Forget the unsaved assets until they are read again.\n     */\n    reset: () => {\n      unsavedAssets = [];\n    },\n  };\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import {\n    Alert,\n    Button,\n    Dialog,\n    EmptyState,\n    FilePicker,\n    Icon,\n    SearchBar,\n    TextInput,\n    Toast,\n  } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import CloudinaryPanel from '$lib/components/assets/browser/cloudinary-panel.svelte';\n  import ExternalAssetsPanel from '$lib/components/assets/browser/external-assets-panel.svelte';\n  import InternalAssetsPanel from '$lib/components/assets/browser/internal-assets-panel.svelte';\n  import LocationSelector from '$lib/components/assets/browser/location-selector.svelte';\n  import CreateSubfolderDialog from '$lib/components/assets/list/create-subfolder-dialog.svelte';\n  import NewFolderButton from '$lib/components/assets/list/new-folder-button.svelte';\n  import ViewSwitcher from '$lib/components/common/page-toolbar/view-switcher.svelte';\n  import { getPendingUploadAction } from '$lib/services/assets/browser/pending-uploads';\n  import {\n    getInitialLibraryName,\n    getInsertedResources,\n    getLocationResources,\n    getPickedFolderPublicPaths,\n    getStockAssetProviderEntries,\n    isFolderOffered,\n    sortServicesByName,\n  } from '$lib/services/assets/browser/select-assets-dialog.svelte';\n  import { fillLibraryPrefix } from '$lib/services/assets/external/prefix';\n  import { assetsLocked } from '$lib/services/assets/folders';\n  import { revokeBlobURLIfNeeded } from '$lib/services/assets/info';\n  import { isCmsFolderPath } from '$lib/services/assets/reserved';\n  import {\n    canBrowseSubfolders,\n    getRelativePath,\n    getSubfolders,\n    getTakenNames,\n  } from '$lib/services/assets/subfolders';\n  import { selectAssetsView, showContentOverlay } from '$lib/services/contents/editor';\n  import { checkDuplicates } from '$lib/services/contents/fields/file/duplicates.svelte';\n  import { hasSameAsset } from '$lib/services/contents/fields/file/helpers';\n  import { createFolderAssetListing } from '$lib/services/contents/fields/file/listing.svelte';\n  import { convertFileItemToAsset } from '$lib/services/contents/fields/file/process';\n  import { getMediaLibraryOptions } from '$lib/services/integrations/media-libraries';\n  import { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\n  import { getPreferredLibraryNames } from '$lib/services/integrations/media-libraries/options';\n  import { allStockAssetProviders } from '$lib/services/integrations/media-libraries/stock';\n  import { normalize } from '$lib/services/search/util';\n  import { getApiKey } from '$lib/services/user/api-keys';\n  import { env } from '$lib/services/user/env.svelte';\n  import { createPath, getDirName, getGitHash } from '$lib/services/utils/file';\n  import { SUPPORTED_IMAGE_TYPES } from '$lib/services/utils/media/image';\n\n  /**\n   * @import {\n   * Asset,\n   * AssetLibraryFolderMap,\n   * AssetLibraryFolderMapKey,\n   * AssetSubfolder,\n   * EntryDraft,\n   * InternalLocaleCode,\n   * MediaLibraryAssetKind,\n   * MediaLibraryService,\n   * SelectAssetsView,\n   * SelectedResource,\n   * } from '$lib/types/private';\n   * @import { MediaField, MediaLibraries, StockAssetProviderName } from '$lib/types/public';\n   * @import { FolderAssetListingOptions } from '$lib/services/contents/fields/file/listing.svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [open] Whether to open the dialog.\n   * @property {boolean} [multiple] Whether to allow selecting multiple assets.\n   * @property {MediaLibraryAssetKind} [kind] Asset kind.\n   * @property {string | undefined} [accept] Accepted file type specifiers.\n   * @property {boolean} [canEnterURL] Whether to allow entering a URL.\n   * @property {boolean} [selectFolder] Whether to select a folder instead of files, for a File\n   * field with the `select_folder` option. Only the repository folders that can be browsed by\n   * subfolder are offered, and the directory being browsed is what gets selected.\n   * @property {EntryDraft | null | undefined} [draft] Associated entry draft.\n   * @property {InternalLocaleCode} [locale] Locale the assets are selected for. With the\n   * `multiple_folders` or `multiple_root_folders` i18n structure, each locale’s entry file has a\n   * folder of its own, which entry-relative assets are listed from.\n   * @property {MediaField} [fieldConfig] Field configuration.\n   * @property {AssetLibraryFolderMap} assetLibraryFolderMap Default asset library folder map.\n   * @property {[string, MediaLibraryService][]} enabledCloudServiceEntries List of enabled cloud\n   * storage services.\n   * @property {File[]} [pendingFiles] Files to be uploaded to the cloud service panel when the\n   * dialog opens. These are typically files dropped on the file editor when only a cloud service is\n   * available.\n   * @property {(resources: SelectedResource[]) => void} [onSelect] Custom `Select` event handler\n   * that will be called when the dialog is closed with the Insert button.\n   * @property {() => void} [onClose] Custom `Close` event handler that will be called whenever the\n   * dialog is closed, after `onSelect` if the Insert button was clicked.\n   */\n\n  /** @type {Props} */\n  let {\n    open = $bindable(false),\n    multiple = false,\n    kind,\n    // svelte-ignore state_referenced_locally\n    accept = kind === 'image' ? SUPPORTED_IMAGE_TYPES.join(',') : undefined,\n    canEnterURL = true,\n    selectFolder = false,\n    draft = undefined,\n    locale = undefined,\n    fieldConfig,\n    assetLibraryFolderMap,\n    enabledCloudServiceEntries,\n    onSelect = undefined,\n    onClose = undefined,\n    pendingFiles = $bindable([]),\n  } = $props();\n\n  const elementIdPrefix = $props.id();\n\n  let enteredURL = $state('');\n  let rawSearchTerms = $state('');\n  /**\n   * Path of the subfolder being browsed below the selected folder, relative to it. Empty at the\n   * folder root.\n   */\n  let subfolderPath = $state('');\n  /**\n   * Paths of the subfolders selected when a folder is to be picked. Without any, the directory\n   * being browsed is what gets picked. A single selection is cleared on going to another directory,\n   * while a multiple selection is kept, like the selected assets, so folders can be picked from\n   * anywhere.\n   * @type {string[]}\n   */\n  let selectedSubfolderPaths = $state([]);\n  let showNewFolderDialog = $state(false);\n  /** @type {Asset[]} */\n  let droppedAssets = $state([]);\n  /** @type {FilePicker | undefined} */\n  let filePicker = $state();\n  /** @type {SelectedResource[]} */\n  let selectedResources = $state([]);\n  /** @type {ExternalAssetsPanel | undefined} */\n  let externalAssetsPanel = $state();\n  /** Whether the pending files have been rejected, as the location offered can’t take them. */\n  let pendingFilesRejected = $state(false);\n\n  /**\n   * View of the asset list, given to the view switcher, which is only rendered once it’s set.\n   */\n  const currentView = /** @type {{ current: SelectAssetsView }} */ (selectAssetsView);\n\n  const title = $derived(\n    selectFolder\n      ? _('assets_dialog.title.folder')\n      : kind === 'image'\n        ? _('assets_dialog.title.image')\n        : _('assets_dialog.title.file'),\n  );\n  const searchTerms = $derived(normalize(rawSearchTerms));\n  const isDefaultLibraryEnabled = $derived(\n    getMediaLibraryOptions({ fieldConfig }) !== false &&\n      Object.values(assetLibraryFolderMap).some((entry) => isFolderOffered(entry, selectFolder)),\n  );\n  /** Whether the URL input is offered. A folder can only be picked from the repository. */\n  const showURLInput = $derived(canEnterURL && !selectFolder);\n  /** Cloud storage services offered in the dialog. */\n  const cloudServiceEntries = $derived(selectFolder ? [] : enabledCloudServiceEntries);\n  const enabledStockAssetProviderEntries = $derived(\n    getStockAssetProviderEntries({ fieldConfig, selectFolder, isDefaultLibraryEnabled }),\n  );\n  const enabledExternalServiceEntries = $derived(\n    [...cloudServiceEntries, ...enabledStockAssetProviderEntries].sort(sortServicesByName),\n  );\n  /** Names of the media libraries marked with the `default` option, in order of precedence. */\n  const preferredLibraryNames = $derived(getPreferredLibraryNames(fieldConfig));\n  /**\n   * Name of the selected location: the first location marked with the `default` option that’s\n   * offered, or else the first location offered, until the user picks another, and again whenever\n   * the locations offered change.\n   */\n  let libraryName = $derived(\n    getInitialLibraryName({\n      assetLibraryFolderMap,\n      isDefaultLibraryEnabled,\n      selectFolder,\n      // The files are taken over by the location, so their removal doesn’t change it\n      hasPendingFiles: untrack(() => !!pendingFiles.length),\n      cloudServiceEntries,\n      externalServiceEntries: enabledExternalServiceEntries,\n      preferredLibraryNames,\n    }),\n  );\n  const isDefaultLibrary = $derived(libraryName.startsWith('default-'));\n  const selectedFolder = $derived.by(() => {\n    if (!isDefaultLibrary) {\n      return undefined;\n    }\n\n    const key = /** @type {AssetLibraryFolderMapKey} */ (libraryName.replace('default-', ''));\n    const { folder } = assetLibraryFolderMap[key];\n\n    return folder;\n  });\n  // Existing files are limited to the accepted types, while the files dropped or picked here are\n  // only checked once inserted and processed, as a transformation can change their format\n  const assetListing = createFolderAssetListing(\n    /**\n     * Get the listing options.\n     * @returns {FolderAssetListingOptions} Options.\n     */\n    () => ({\n      draft,\n      folder: selectedFolder,\n      locale,\n      kind,\n      accept,\n      slugificationEnabled: getDefaultMediaLibraryOptions({ fieldConfig }).config.slugify_filename,\n      droppedAssets,\n    }),\n  );\n  const targetFolderPath = $derived(assetListing.targetFolderPath);\n  const listedAssets = $derived(assetListing.listedAssets);\n  /**\n   * Whether the selected folder is browsed by subfolder, like in the Asset Library. A search looks\n   * through the whole folder instead, listing the matches with their paths.\n   */\n  const browsingSubfolders = $derived(\n    canBrowseSubfolders(selectedFolder) && targetFolderPath !== undefined && !searchTerms,\n  );\n  /** Path of the directory being browsed, which is where uploaded files go. */\n  const browsedPath = $derived(createPath([targetFolderPath, subfolderPath]));\n  /**\n   * Whether the directory being browsed is, or is below, a folder the CMS itself is usually served\n   * from, such as `admin`, whose files are read-only. Nothing can be uploaded or created there.\n   */\n  const browsingCmsFolder = $derived(isDefaultLibrary && isCmsFolderPath(browsedPath));\n  /**\n   * Whether nothing can be uploaded to the directory being browsed: one the CMS is served from, or\n   * one in a read-only folder, such as a read-only asset collection offered to every field.\n   */\n  const uploadDisabled = $derived(browsingCmsFolder || !!selectedFolder?.readonly);\n  /**\n   * Assets right in the browsed directory. Dropped files go there, even during a search, so only\n   * these can be replaced by one.\n   */\n  const browsedDirAssets = $derived(\n    listedAssets.filter(({ path }) => getDirName(path) === browsedPath),\n  );\n  /** Assets shown in the panel: those right in the browsed directory, or every asset listed. */\n  const panelAssets = $derived(browsingSubfolders ? browsedDirAssets : listedAssets);\n  const subfolders = $derived(\n    browsingSubfolders ? getSubfolders({ dirPath: browsedPath, assets: listedAssets }) : [],\n  );\n  /**\n   * Names already taken in the browsed directory, which a new folder can’t be given, including the\n   * names of the folders leading to another asset folder nested in it.\n   */\n  const takenNames = $derived(\n    getTakenNames({\n      subfolders,\n      fileNames: panelAssets.map(({ name }) => name),\n      // Only read by the new folder dialog, which is there while subfolders are browsed\n      dirPath: browsedPath,\n    }),\n  );\n  /** Label of the selected folder, at the start of the breadcrumb. */\n  const selectedFolderLabel = $derived(\n    selectedFolder?.label || _(`assets_dialog.folder.${libraryName.replace('default-', '')}`),\n  );\n  const isEnabledMediaService = $derived(\n    enabledStockAssetProviderEntries.some(\n      ([serviceId, { authType }]) =>\n        serviceId === libraryName && (authType === 'none' || !!getApiKey(libraryName)),\n    ),\n  );\n  const isCloudLibrary = $derived(\n    cloudServiceEntries.map(([serviceId]) => serviceId).includes(libraryName),\n  );\n  /** Field configuration for the selected service, with its `prefix` option filled, if any. */\n  const filledPrefix = $derived(\n    fillLibraryPrefix({\n      serviceId: /** @type {keyof MediaLibraries} */ (libraryName),\n      fieldConfig,\n      draft,\n      locale,\n    }),\n  );\n  /** Whether the files on the selected cloud storage service can be browsed and uploaded here. */\n  const canBrowseCloudLibrary = $derived(\n    isCloudLibrary && libraryName !== 'cloudinary' && !filledPrefix.unresolved,\n  );\n  const isStockLibrary = $derived(\n    enabledStockAssetProviderEntries\n      .map(([serviceId]) => serviceId)\n      .includes(/** @type {any} */ (libraryName)),\n  );\n  /**\n   * Public paths of the folders to be picked: the selected subfolders, or the directory being\n   * browsed. Empty unless a folder is to be picked from a folder that can be browsed.\n   */\n  const pickedFolderPublicPaths = $derived(\n    getPickedFolderPublicPaths({\n      selectFolder,\n      browsingSubfolders,\n      folder: selectedFolder,\n      basePath: targetFolderPath,\n      subfolderPath,\n      selectedSubfolderPaths,\n    }),\n  );\n\n  /**\n   * Select or deselect a subfolder when a folder is to be picked.\n   * @param {AssetSubfolder} subfolder Subfolder.\n   * @param {boolean} selected Whether the subfolder is now selected.\n   */\n  const onSelectSubfolder = ({ path }, selected) => {\n    const otherPaths = selectedSubfolderPaths.filter((p) => p !== path);\n\n    // The list box reports the folder that loses a single selection after the one that gets it, if\n    // it comes later in the list, so only the given folder is removed on deselection\n    selectedSubfolderPaths = selected ? [...(multiple ? otherPaths : []), path] : otherPaths;\n  };\n\n  /**\n   * Go to another directory within the selected folder, clearing a single subfolder selection.\n   * @param {string} path Subfolder path relative to the selected folder. Empty for its root.\n   */\n  const navigate = (path) => {\n    subfolderPath = path;\n\n    if (!multiple) {\n      selectedSubfolderPaths = [];\n    }\n  };\n\n  /**\n   * Process a dropped file.\n   * @param {File} file File to be processed.\n   * @param {boolean} replace Whether the file replaces an existing asset with the same name.\n   * @returns {Promise<Asset | undefined>} Processed asset or `undefined` if the file already\n   * exists.\n   */\n  const processFile = async (file, replace) => {\n    const sha = await getGitHash(file);\n    const folder = selectedFolder;\n\n    if (hasSameAsset({ sha, folder, unsavedAssets: assetListing.unsavedAssets })) {\n      return undefined;\n    }\n\n    const asset = await convertFileItemToAsset({\n      file,\n      folder,\n      targetFolderPath,\n      // The file goes to the subfolder being browsed, or the one the search started from\n      subfolderPath,\n      replace,\n    });\n\n    droppedAssets.push(asset);\n\n    return asset;\n  };\n\n  /**\n   * Handle dropped files.\n   * @param {File[]} files File list.\n   */\n  const onDrop = async (files) => {\n    // The files in a read-only folder, or one the CMS itself is served from, can’t be changed. The\n    // drop zone and the Upload button are disabled there, so this is only a safeguard\n    /* v8 ignore next 3 -- unreachable, as explained above */\n    if (uploadDisabled) {\n      return;\n    }\n\n    const replace = await checkDuplicates({ files, listedAssets: browsedDirAssets });\n\n    if (replace === undefined) {\n      // User cancelled the dialog\n      return;\n    }\n\n    selectedResources = (await Promise.all(files.map((file) => processFile(file, replace))))\n      .filter((asset) => !!asset)\n      .map((asset) => ({ asset, replace }));\n  };\n\n  /**\n   * Reset all the values.\n   */\n  const resetValues = () => {\n    enteredURL = '';\n    rawSearchTerms = '';\n    subfolderPath = '';\n    selectedSubfolderPaths = [];\n    // The blob URLs of dropped files belong to the dialog, since the field takes the file itself on\n    // Insert\n    droppedAssets.forEach((asset) => revokeBlobURLIfNeeded(asset.blobURL));\n    droppedAssets = [];\n    assetListing.reset();\n    selectedResources = [];\n    // Files that couldn’t be uploaded mustn’t go up the next time the dialog is opened\n    pendingFiles = [];\n  };\n\n  /**\n   * Handle the OK button click.\n   */\n  const onOk = () => {\n    if (selectFolder) {\n      /* v8 ignore next 3 -- the Select button is disabled until a folder is browsed */\n      if (!pickedFolderPublicPaths.length) {\n        return;\n      }\n\n      onSelect?.(pickedFolderPublicPaths.map((folderPath) => ({ folderPath })));\n\n      return;\n    }\n\n    /* v8 ignore next 3 -- the Insert button is disabled until something is selected */\n    if (!selectedResources.length) {\n      return;\n    }\n\n    // A stock asset service may need to know which of its assets have been used\n    externalAssetsPanel?.trackDownloads();\n    onSelect?.(getInsertedResources({ resources: selectedResources, targetFolderPath }));\n  };\n\n  $effect(() => {\n    if (!showContentOverlay.current) {\n      open = false;\n    }\n  });\n\n  // Take the pending files (e.g. dropped on the file editor) to a cloud storage service: upload\n  // them once its panel can take them, select one that can, or report that none can\n  $effect(() => {\n    const action = getPendingUploadAction({\n      open,\n      pendingFileCount: pendingFiles.length,\n      libraryName,\n      cloudServiceEntries,\n      canUpload: !!externalAssetsPanel?.canUpload(),\n      preferredLibraryNames,\n    });\n\n    if (action.type === 'upload') {\n      // The panel is there, as it says it can upload\n      /** @type {ExternalAssetsPanel} */ (externalAssetsPanel).uploadFiles(pendingFiles);\n      pendingFiles = [];\n    } else if (action.type === 'switch') {\n      libraryName = action.serviceId;\n    } else if (action.type === 'reject') {\n      pendingFiles = [];\n      pendingFilesRejected = true;\n    }\n  });\n</script>\n\n{#snippet headerItems()}\n  {#if isDefaultLibrary || canBrowseCloudLibrary || (isStockLibrary && libraryName !== 'picsum')}\n    {#if selectAssetsView.current}\n      <ViewSwitcher {currentView} aria-controls=\"select-assets-grid\" />\n    {/if}\n    <!-- A search lists matching files rather than folders, so it’s not offered for a folder -->\n    {#if !selectFolder}\n      <SearchBar\n        dir=\"auto\"\n        flex={env.isSmallScreen}\n        bind:value={rawSearchTerms}\n        debounce={!isDefaultLibrary}\n        disabled={selectedResources.some((r) => r.file)}\n        ariaLabel={_(`assets_dialog.search_for_${kind ?? 'file'}`)}\n      />\n    {/if}\n  {/if}\n  {#if browsingSubfolders}\n    <!--\n      Creating a folder commits straight to the configured branch rather than going through\n      review, so it’s not something an Open Authoring contributor or a user who can’t push to the\n      branch can do, nor anyone within a read-only folder\n    -->\n    <NewFolderButton\n      floating={false}\n      disabled={assetsLocked.current || uploadDisabled}\n      onclick={() => {\n        showNewFolderDialog = true;\n      }}\n    />\n  {:else if isCloudLibrary && externalAssetsPanel?.canCreateFolder()}\n    <!-- A folder on a cloud storage service is created by the service, not committed -->\n    <NewFolderButton\n      floating={false}\n      onclick={() => {\n        externalAssetsPanel?.showNewFolderDialog();\n      }}\n    />\n  {/if}\n  {#if !selectFolder && (isDefaultLibrary || canBrowseCloudLibrary)}\n    <!-- A cloud storage service takes files once the user has provided the credentials -->\n    <Button\n      variant=\"primary\"\n      label={_('upload')}\n      disabled={uploadDisabled || (isCloudLibrary && !externalAssetsPanel?.canUpload())}\n      onclick={() => {\n        filePicker?.open();\n      }}\n    >\n      {#snippet startIcon()}\n        <Icon name=\"cloud_upload\" />\n      {/snippet}\n    </Button>\n  {/if}\n{/snippet}\n\n<Dialog\n  {title}\n  size=\"x-large\"\n  okLabel={selectFolder ? _('select') : _('insert')}\n  okDisabled={selectFolder ? !pickedFolderPublicPaths.length : !selectedResources.length}\n  focusInput={false}\n  bind:open\n  {onOk}\n  onClose={() => {\n    resetValues();\n    onClose?.();\n  }}\n>\n  {#snippet headerExtra()}\n    {#if !env.isSmallScreen}\n      {@render headerItems()}\n    {/if}\n  {/snippet}\n  {#snippet footerExtra()}\n    {#if pickedFolderPublicPaths.length}\n      <div role=\"status\" class=\"selected-folder\" dir=\"auto\">\n        {#if pickedFolderPublicPaths.length === 1}\n          {_('assets_dialog.selected_folder', { values: { path: pickedFolderPublicPaths[0] } })}\n        {:else}\n          {_('assets_dialog.selected_folders', {\n            values: { count: pickedFolderPublicPaths.length },\n          })}\n        {/if}\n      </div>\n    {/if}\n    {#if isEnabledMediaService}\n      {@const { showServiceLink, serviceLabel, serviceURL } =\n        allStockAssetProviders[/** @type {StockAssetProviderName} */ (libraryName)]}\n      {#if showServiceLink}\n        <a href={serviceURL} class=\"service-link\">\n          {_('prefs.media.stock_photos.credit', { values: { service: serviceLabel } })}\n        </a>\n      {/if}\n    {/if}\n  {/snippet}\n  <div role=\"none\" class=\"wrapper\">\n    <div role=\"none\" class=\"nav\">\n      <LocationSelector\n        {libraryName}\n        {assetLibraryFolderMap}\n        showRepository={isDefaultLibraryEnabled}\n        {selectFolder}\n        {cloudServiceEntries}\n        {showURLInput}\n        stockAssetProviderEntries={enabledStockAssetProviderEntries}\n        controlsId=\"{elementIdPrefix}-content-pane\"\n        onChange={(name) => {\n          libraryName = name;\n          // Files dropped on the field were meant for the location first offered\n          pendingFiles = [];\n          subfolderPath = '';\n          selectedSubfolderPaths = [];\n          // The URL entered earlier is still in the text box, so it’s selected again\n          selectedResources = getLocationResources({ libraryName, enteredURL });\n        }}\n      />\n      {#if env.isSmallScreen}\n        <div role=\"none\" class=\"filter-tools\">\n          {@render headerItems()}\n        </div>\n      {/if}\n    </div>\n    <!-- The focus is kept here while the folders being browsed are replaced -->\n    <div role=\"none\" id=\"{elementIdPrefix}-content-pane\" class=\"content-pane\" data-focus-scope>\n      {#if isDefaultLibrary && selectedFolder}\n        <InternalAssetsPanel\n          {accept}\n          {multiple}\n          {kind}\n          {selectFolder}\n          {uploadDisabled}\n          assets={selectFolder ? [] : panelAssets}\n          bind:selectedResources\n          {searchTerms}\n          basePath={browsingSubfolders ? browsedPath : selectedFolder.internalPath}\n          folderLabel={selectedFolderLabel}\n          subfolderPath={browsingSubfolders ? subfolderPath : ''}\n          {subfolders}\n          onDrop={({ files }) => {\n            onDrop(files);\n          }}\n          {selectedSubfolderPaths}\n          onSelectSubfolder={selectFolder ? onSelectSubfolder : undefined}\n          onNavigate={navigate}\n          onOpenSubfolder={({ path }) => {\n            navigate(getRelativePath(path, /** @type {string} */ (targetFolderPath)));\n          }}\n        />\n      {/if}\n      {#if showURLInput && libraryName === 'enter-url'}\n        <EmptyState>\n          <div role=\"none\" id=\"{elementIdPrefix}-url-label\">\n            {kind === 'image'\n              ? _('assets_dialog.enter_image_url')\n              : _('assets_dialog.enter_file_url')}\n          </div>\n          <TextInput\n            dir=\"ltr\"\n            bind:value={enteredURL}\n            flex\n            aria-labelledby=\"{elementIdPrefix}-url-label\"\n            oninput={() => {\n              selectedResources = getLocationResources({ libraryName, enteredURL });\n            }}\n          />\n        </EmptyState>\n      {/if}\n      {#each enabledExternalServiceEntries as [serviceId, serviceProps] (serviceId)}\n        {#if serviceId === 'cloudinary'}\n          <CloudinaryPanel\n            {kind}\n            {fieldConfig}\n            {multiple}\n            hidden={libraryName !== 'cloudinary'}\n            onSelect={(resources) => {\n              // Close the dialog after selection\n              selectedResources = resources;\n              onOk();\n              open = false;\n            }}\n          />\n        {:else if libraryName === serviceId && filledPrefix.unresolved}\n          <EmptyState>\n            <span role=\"alert\">{_('assets_dialog.prefix_unresolved')}</span>\n          </EmptyState>\n        {:else if libraryName === serviceId}\n          <ExternalAssetsPanel\n            {kind}\n            fieldConfig={filledPrefix.fieldConfig}\n            {draft}\n            {multiple}\n            {searchTerms}\n            {serviceProps}\n            gridId=\"select-assets-grid\"\n            bind:selectedResources\n            bind:this={externalAssetsPanel}\n          />\n        {/if}\n      {/each}\n    </div>\n  </div>\n</Dialog>\n\n{#if browsingSubfolders}\n  <CreateSubfolderDialog bind:open={showNewFolderDialog} dirPath={browsedPath} {takenNames} />\n{/if}\n\n<Toast bind:show={pendingFilesRejected}>\n  <Alert status=\"error\">{_('uploading_files_failed')}</Alert>\n</Toast>\n\n<FilePicker\n  bind:this={filePicker}\n  {accept}\n  {multiple}\n  onSelect={({ files }) => {\n    if (isCloudLibrary) {\n      externalAssetsPanel?.uploadFiles(files);\n    } else {\n      onDrop(files);\n    }\n  }}\n/>\n\n<style>\n  .wrapper {\n    display: flex;\n    gap: 16px;\n    height: 60dvh;\n    max-height: 800px;\n    --tile-padding: 4px;\n\n    @media (width < 768px) {\n      flex-direction: column;\n      overflow: hidden;\n      height: 72dvh;\n    }\n\n    .nav {\n      flex: none;\n      display: flex;\n      gap: 4px;\n\n      @media (width < 768px) {\n        flex-direction: column;\n      }\n    }\n\n    :global {\n      .listbox {\n        flex: none;\n        background-color: transparent;\n\n        .option button .icon:not(.check) {\n          display: block;\n        }\n      }\n    }\n\n    .content-pane {\n      overflow: auto;\n      flex: auto;\n    }\n  }\n\n  .service-link,\n  .selected-folder {\n    font-size: var(--sui-font-size-small);\n  }\n\n  .selected-folder {\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n  }\n\n  .filter-tools {\n    display: flex;\n    gap: 8px;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, ConfirmationDialog, Spacer } from '@sveltia/ui';\n\n  import { duplicatesRequest } from '$lib/services/contents/fields/file/duplicates.svelte';\n\n  /* v8 ignore start -- these are only read while the dialog is open, when there’s a request */\n  const { count, name } = $derived(duplicatesRequest.current ?? { count: 0, name: '' });\n  /* v8 ignore stop */\n\n  /**\n   * Answer the pending request.\n   * @param {boolean | undefined} replace Whether to replace the existing files, or `undefined` to\n   * cancel.\n   */\n  const respond = (replace) => {\n    duplicatesRequest.current?.respond(replace);\n  };\n</script>\n\n<ConfirmationDialog\n  open={!!duplicatesRequest.current}\n  title={_('file_name_conflict_resolution')}\n  onCancel={() => respond(undefined)}\n>\n  {_('file_name_conflict_confirmation_with_name', { values: { count, name } })}\n  {#snippet footer()}\n    <Spacer flex />\n    <Button variant=\"primary\" onclick={() => respond(true)}>{_('replace')}</Button>\n    <Button variant=\"primary\" onclick={() => respond(false)}>{_('keep_both')}</Button>\n    <Button variant=\"secondary\" onclick={() => respond(undefined)}>{_('cancel')}</Button>\n  {/snippet}\n</ConfirmationDialog>\n","import {\n  getAssetLibraryFolderMap,\n  getDefaultAssetFolder,\n} from '$lib/services/contents/fields/file/helpers';\nimport { processResource } from '$lib/services/contents/fields/file/process';\nimport { allCloudStorageServices } from '$lib/services/integrations/media-libraries/cloud';\nimport { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\nimport {\n  findPreferredLibraryName,\n  getUploadableServiceEntries,\n} from '$lib/services/integrations/media-libraries/options';\n\n/**\n * @import {\n * AssetFolderInfo,\n * AssetLibraryFolderMap,\n * EntryDraft,\n * InternalLocaleCode,\n * MediaLibraryService,\n * SelectedResource,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import { DefaultMediaLibraryConfig, Field } from '$lib/types/public';\n * @import { ProcessResourceResult } from '$lib/services/contents/fields/file/process';\n */\n\n/**\n * @typedef {object} MediaFieldAssetOptions\n * @property {AssetLibraryFolderMap} folderMap Asset library folders available to the field.\n * @property {AssetFolderInfo | undefined} folder Folder a file added by the field is uploaded to.\n * @property {boolean} enabled Whether the default (repository) media library is enabled.\n * @property {DefaultMediaLibraryConfig} libraryConfig Default media library configuration.\n * @property {[string, MediaLibraryService][]} cloudServiceEntries Cloud storage services enabled\n * for the field.\n */\n\n/**\n * @typedef {object} RejectedFileNames\n * @property {string[]} oversizedFileNames Names of the files that exceed the size limit.\n * @property {string[]} invalidFileNames Names of the files that cannot be decoded.\n * @property {string[]} [mismatchedFileNames] Names of the files that are not one of the accepted\n * file types, even once transformed.\n */\n\n/**\n * Get the asset folders and media library options that apply to a field handling files: a\n * File/Image field, or a custom field that adds or picks files. They come from the field’s own\n * `media_folder` and `media_library` options if any, otherwise the collection’s or the global ones.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string | undefined} args.fileName Collection file name, if any.\n * @param {boolean} args.isIndexFile Whether the entry is the collection’s index file.\n * @param {string | undefined} args.componentName Name of the rich text editor component the field\n * is part of, if any.\n * @param {TypedFieldKeyPath} args.typedKeyPath Typed key path to the field.\n * @param {Field} args.fieldConfig Field configuration.\n * @returns {MediaFieldAssetOptions} Options.\n */\nexport const getMediaFieldAssetOptions = ({\n  collectionName,\n  fileName,\n  isIndexFile,\n  componentName,\n  typedKeyPath,\n  fieldConfig,\n}) => {\n  const folderMap = getAssetLibraryFolderMap({\n    collectionName,\n    fileName,\n    componentName,\n    typedKeyPath,\n    isIndexFile,\n  });\n\n  const { enabled, config: libraryConfig } = getDefaultMediaLibraryOptions({\n    fieldConfig: /** @type {any} */ (fieldConfig),\n  });\n\n  const cloudServiceEntries = Object.entries(allCloudStorageServices).filter(\n    ([, { isEnabled }]) => isEnabled?.(/** @type {any} */ (fieldConfig)) ?? true,\n  );\n\n  return {\n    folderMap,\n    folder: getDefaultAssetFolder(folderMap),\n    enabled,\n    libraryConfig,\n    cloudServiceEntries,\n  };\n};\n\n/**\n * @typedef {object} DroppedFileDestination\n * @property {'repository' | 'cloud' | undefined} destination Where the files go: the first\n * location marked with the `default` option that can take them, or else the repository, or else a\n * cloud storage service that can upload them. `undefined` if no location can take the files.\n * @property {boolean} ambiguous Whether the files could go to more than one location and none is\n * marked with the `default` option, so the destination is only a fallback.\n */\n\n/**\n * Decide where files dropped or pasted into a field go, rather than picked in the Select Assets\n * dialog. A cloud storage service without an upload function, like Cloudinary, can’t take them.\n * @param {object} args Arguments.\n * @param {boolean} args.repositoryAvailable Whether the default media library is enabled and has a\n * folder to upload the files to.\n * @param {[string, MediaLibraryService][]} args.cloudServiceEntries Cloud storage services enabled\n * for the field.\n * @param {string[]} [args.preferredLibraryNames] Names of the media libraries marked with the\n * `default` option, in order of precedence. `default` stands for the repository.\n * @returns {DroppedFileDestination} Destination.\n */\nexport const getDroppedFileDestination = ({\n  repositoryAvailable,\n  cloudServiceEntries,\n  preferredLibraryNames = [],\n}) => {\n  const uploadableEntries = getUploadableServiceEntries(cloudServiceEntries);\n\n  const preferredName = findPreferredLibraryName({\n    preferredLibraryNames,\n    repositoryAvailable,\n    cloudServiceEntries: uploadableEntries,\n  });\n\n  if (preferredName) {\n    return {\n      destination: preferredName === 'default' ? 'repository' : 'cloud',\n      ambiguous: false,\n    };\n  }\n\n  if (repositoryAvailable) {\n    return { destination: 'repository', ambiguous: uploadableEntries.length > 0 };\n  }\n\n  return uploadableEntries.length\n    ? { destination: 'cloud', ambiguous: uploadableEntries.length > 1 }\n    : { destination: undefined, ambiguous: false };\n};\n\n/**\n * Process the resources selected in the Select Assets dialog, or dropped or pasted into a field.\n * A file to be uploaded that doesn’t come with a folder of its own, including a stock photo that\n * isn’t hotlinked, goes to the given folder.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {SelectedResource[]} args.resources Resources. A missing `folder` is filled in.\n * @param {AssetFolderInfo | undefined} args.folder Default folder for uploads.\n * @param {DefaultMediaLibraryConfig} args.libraryConfig Default media library configuration.\n * @param {string} [args.accept] File types a file to be uploaded is checked against once processed.\n * @param {InternalLocaleCode} [args.locale] Locale the resources are selected for.\n * @returns {Promise<ProcessResourceResult[]>} Results, in the same order as the resources.\n */\nexport const processResources = ({ draft, resources, folder, libraryConfig, accept, locale }) =>\n  Promise.all(\n    resources.map((resource) => {\n      if (resource.file && !resource.folder) {\n        resource.folder = folder;\n      }\n\n      return processResource({ draft, resource, libraryConfig, accept, locale });\n    }),\n  );\n\n/**\n * Collect the names of the files that couldn’t be used, so they can be reported to the user.\n * @param {ProcessResourceResult[]} results Results of {@link processResources}.\n * @returns {RejectedFileNames} File names.\n */\nexport const getRejectedFileNames = (results) => ({\n  oversizedFileNames: results.flatMap(({ oversizedFileName }) => oversizedFileName ?? []),\n  invalidFileNames: results.flatMap(({ invalidFileName }) => invalidFileName ?? []),\n  mismatchedFileNames: results.flatMap(({ mismatchedFileName }) => mismatchedFileName ?? []),\n});\n\n/**\n * Get the value to store in a field for a processed resource. Spaces are encoded as `%20` in a\n * rich text editor component, because some Markdown parsers don’t support unencoded spaces in URLs.\n * @param {string} value Value, e.g. an asset path.\n * @param {boolean} inEditorComponent Whether the field is part of a rich text editor component.\n * @returns {string} Value to store.\n */\nexport const toFieldValue = (value, inEditorComponent) =>\n  inEditorComponent ? value.replaceAll(' ', '%20') : value;\n\n/**\n * Work out what a File/Image field takes from the resources the user has selected, once they have\n * been processed.\n * @param {object} args Arguments.\n * @param {ProcessResourceResult[]} args.resources Results of {@link processResources}.\n * @param {boolean} args.multiple Whether the field takes multiple files.\n * @param {string | string[] | undefined} args.previousValue Value of a single-file field before\n * the selection, which is restored if none of the resources can be used, so that a failed upload or\n * replacement doesn’t leave an empty or invalid reference behind. Without one, the field is left\n * empty.\n * @param {boolean} args.inEditorComponent Whether the field is part of a rich text editor\n * component.\n * @returns {{\n * values: string[],\n * value: string | string[] | undefined,\n * credit: string,\n * rejected: RejectedFileNames,\n * }} Values of the usable resources, to be added to a multiple-file field; value to be stored in a\n * single-file field, or `undefined` for a multiple-file field; photo credits, one per line; and\n * the names of the files that couldn’t be used.\n */\nexport const resolveSelectionResult = ({\n  resources,\n  multiple,\n  previousValue,\n  inEditorComponent,\n}) => {\n  const values = resources.flatMap(({ value }) => value ?? []);\n  /** @type {string | string[] | undefined} */\n  let value = undefined;\n\n  if (!multiple) {\n    // A single-value field takes the last file, like it would if they were picked in turn\n    value = values.length\n      ? toFieldValue(/** @type {string} */ (values.at(-1)), inEditorComponent)\n      : (previousValue ?? '');\n  }\n\n  return {\n    values,\n    value,\n    credit: resources.flatMap(({ credit }) => credit || []).join('\\n'),\n    rejected: getRejectedFileNames(resources),\n  };\n};\n","import { getAssetByPath } from '$lib/services/assets';\nimport { getAssetBlob } from '$lib/services/assets/info';\nimport { processResource } from '$lib/services/contents/fields/file/process';\nimport {\n  getMediaFieldAssetOptions,\n  getRejectedFileNames,\n  processResources,\n  toFieldValue,\n} from '$lib/services/contents/fields/file/resources';\n\n/**\n * @import {\n * EntryDraft,\n * InternalLocaleCode,\n * MediaLibraryAssetKind,\n * SelectedResource,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import {\n * CustomField,\n * CustomFieldAddFileOptions,\n * CustomFieldPickFileOptions,\n * CustomFieldPickedFile,\n * } from '$lib/types/public';\n * @import { MediaFieldAssetOptions } from '$lib/services/contents/fields/file/resources';\n */\n\n/**\n * @typedef {object} CustomFieldArgs\n * @property {EntryDraft} draft Entry draft.\n * @property {CustomField} fieldConfig Field configuration.\n * @property {TypedFieldKeyPath} typedKeyPath Typed key path to the field.\n * @property {string} [componentName] Name of the rich text editor component the field is part of,\n * if any.\n * @property {InternalLocaleCode} [locale] Locale the field is edited in, which an existing asset in\n * an entry-relative folder is referenced relative to. Default: the default locale.\n */\n\n/**\n * @typedef {object} PickedResourcesResult\n * @property {CustomFieldPickedFile[]} files Usable resources, in the order they were selected.\n * @property {string[]} oversizedFileNames Names of the files that exceed the size limit.\n * @property {string[]} invalidFileNames Names of the files that cannot be decoded.\n * @property {string[]} [mismatchedFileNames] Names of the files that are not one of the accepted\n * file types, even once transformed.\n */\n\n/**\n * Get the asset folders and media library options that apply to a custom field. These are the same\n * a File/Image field in the same place would use: the field’s own `media_folder` and\n * `media_library` options if any, otherwise the collection’s or the global ones.\n * @param {CustomFieldArgs} args Arguments.\n * @returns {MediaFieldAssetOptions} Options.\n */\nexport const getCustomFieldAssetOptions = ({ draft, fieldConfig, typedKeyPath, componentName }) => {\n  const { collectionName, fileName, isIndexFile } = draft;\n\n  return getMediaFieldAssetOptions({\n    collectionName,\n    fileName,\n    isIndexFile,\n    componentName,\n    typedKeyPath,\n    fieldConfig,\n  });\n};\n\n/**\n * Add a file to the entry draft on behalf of a custom field control, so that it’s committed along\n * with the entry when the entry is saved. The file is cached in the draft and referenced with a\n * temporary blob URL, exactly like a file picked in a built-in File/Image field, so everything\n * downstream — the target folder, file naming, deduplication, the backup and the editorial workflow\n * — works the same way. The target folder is the one a File/Image field in the same place would\n * upload to: the field’s own `media_folder` if any, otherwise the collection’s or the global one.\n * With the `replace` option, the file keeps its name and overwrites an existing asset with the same\n * name, like a file the user chose to replace in the Select Assets dialog.\n * @param {CustomFieldArgs & { file: File | Blob, options?: CustomFieldAddFileOptions }} args\n * Arguments, including the file to be added and the options.\n * @returns {Promise<string>} Blob URL to be stored in the field value. It’s replaced with the\n * public path of the uploaded file when the entry is saved. If an identical file has already been\n * uploaded, the public path of the existing asset is returned instead.\n * @throws {TypeError} When the file is not a `File`, or is a `Blob` given without a name.\n * @throws {Error} When the file cannot be decoded or exceeds the size limit configured for the\n * media library, or there is no asset folder to upload it to.\n */\nexport const addFileToDraft = async ({\n  draft,\n  fieldConfig,\n  typedKeyPath,\n  componentName,\n  locale,\n  file,\n  options = {},\n}) => {\n  const name = options.name ?? (file instanceof File ? file.name : '');\n\n  if (!(file instanceof Blob) || !name) {\n    throw new TypeError('addFile() expects a File, or a Blob along with the `name` option');\n  }\n\n  const namedFile =\n    file instanceof File && file.name === name ? file : new File([file], name, { type: file.type });\n\n  const { folder, libraryConfig } = getCustomFieldAssetOptions({\n    draft,\n    fieldConfig,\n    typedKeyPath,\n    componentName,\n  });\n\n  // Only a cloud media library is configured, and neither the field nor the collection has its own\n  // `media_folder`\n  if (!folder) {\n    throw new Error(`There is no asset folder to upload the file \"${name}\" to`);\n  }\n\n  const { value, oversizedFileName, invalidFileName } = await processResource({\n    draft,\n    resource: { file: namedFile, folder, replace: !!options.replace },\n    libraryConfig,\n    locale,\n  });\n\n  if (invalidFileName) {\n    throw new Error(`The file \"${invalidFileName}\" is corrupt or mislabeled and cannot be used`);\n  }\n\n  if (oversizedFileName) {\n    const { max_file_size: maxSize } = libraryConfig;\n\n    throw new Error(`The file \"${oversizedFileName}\" exceeds the maximum size of ${maxSize} bytes`);\n  }\n\n  return /** @type {string} */ (value);\n};\n\n/**\n * Get the asset kind the Select Assets dialog is opened for. The `kind` option wins; otherwise the\n * dialog is limited to images when every accepted type is an image type, so that a control can\n * simply ask for `image/*` the way it would with a file input.\n * @param {CustomFieldPickFileOptions} options Options given to `pickFile()`.\n * @returns {MediaLibraryAssetKind | undefined} Asset kind, or `undefined` for any file.\n */\nexport const getPickedAssetKind = ({ kind, accept }) => {\n  if (kind) {\n    return kind === 'image' ? 'image' : undefined;\n  }\n\n  const types = (accept ?? '')\n    .split(',')\n    .map((type) => type.trim())\n    .filter(Boolean);\n\n  return types.length && types.every((type) => type.startsWith('image/')) ? 'image' : undefined;\n};\n\n/**\n * Get the bytes of a resource the user picked in the dialog, once the resource has been processed.\n * A file being uploaded is read back from the draft, where {@link processResource} caches the\n * processed (possibly transformed) file, and an existing asset is fetched from wherever it’s\n * available. A file that turned out to be an identical copy of an asset already in the repository\n * is resolved to that asset, so the bytes always match the value. Nothing is returned for a URL.\n * @param {CustomFieldArgs & { resource: SelectedResource, value: string }} args Arguments,\n * including the resource and the value {@link processResource} has resolved it to.\n * @returns {Promise<Blob | undefined>} Blob, if the resource has one.\n */\nconst getPickedBlob = async ({ draft, typedKeyPath, componentName, locale, resource, value }) => {\n  if (value.startsWith('blob:')) {\n    return draft.files[value]?.file;\n  }\n\n  const { collectionName, fileName, originalEntry: entry } = draft;\n\n  const asset =\n    resource.asset ??\n    (resource.file\n      ? getAssetByPath({\n          value,\n          entry,\n          collectionName,\n          fileName,\n          componentName,\n          typedKeyPath,\n          locale,\n        })\n      : undefined);\n\n  return asset ? getAssetBlob(asset) : undefined;\n};\n\n/**\n * Resolve the resources picked in the Select Assets dialog on behalf of a custom field control.\n * Each resource is processed the way a built-in File/Image field would: an existing asset is\n * resolved to its public path, a file to be uploaded is cached in the draft and given a temporary\n * blob URL, and a URL is used as is. Files that are oversized, cannot be decoded or are not one of\n * the accepted types are reported separately, so the caller can show them the way a File/Image\n * field does.\n * @param {CustomFieldArgs & {\n * inEditorComponent?: boolean,\n * resources: SelectedResource[],\n * accept?: string,\n * }} args Arguments, including the resources picked in the dialog, whether the field is rendered in\n * a rich text editor component, and the file types a file to be uploaded is checked against once\n * processed.\n * @returns {Promise<PickedResourcesResult>} Result.\n * @throws {Error} When the bytes of a picked asset cannot be retrieved.\n */\nexport const resolvePickedResources = async ({\n  draft,\n  fieldConfig,\n  typedKeyPath,\n  componentName,\n  locale,\n  inEditorComponent = false,\n  resources,\n  accept,\n}) => {\n  const { folder, libraryConfig } = getCustomFieldAssetOptions({\n    draft,\n    fieldConfig,\n    typedKeyPath,\n    componentName,\n  });\n\n  const results = await processResources({\n    draft,\n    resources,\n    folder,\n    libraryConfig,\n    accept,\n    locale,\n  });\n\n  const files = await Promise.all(\n    results.map(async ({ value, credit }, index) =>\n      value\n        ? {\n            // The same value a built-in File/Image field would store\n            value: toFieldValue(value, inEditorComponent),\n            file: await getPickedBlob({\n              draft,\n              fieldConfig,\n              typedKeyPath,\n              componentName,\n              locale,\n              resource: resources[index],\n              value,\n            }),\n            credit: credit || undefined,\n          }\n        : undefined,\n    ),\n  );\n\n  return {\n    files: /** @type {CustomFieldPickedFile[]} */ (files.filter(Boolean)),\n    ...getRejectedFileNames(results),\n  };\n};\n","<!--\n  @component\n  Let a custom field control open the same Select Assets dialog as a built-in File/Image field. The\n  dialog is opened imperatively with `pick()`, which resolves with what the user picked, so that a\n  React control can `await` it the way it awaits `addFile()`.\n-->\n<script>\n  import { onDestroy } from 'svelte';\n\n  import SelectAssetsDialog from '$lib/components/assets/browser/select-assets-dialog.svelte';\n  import ConflictResolutionDialog from '$lib/components/assets/shared/conflict-resolution-dialog.svelte';\n  import RejectedFilesAlertDialog from '$lib/components/assets/shared/rejected-files-alert-dialog.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    getCustomFieldAssetOptions,\n    getPickedAssetKind,\n    resolvePickedResources,\n  } from '$lib/services/contents/fields/custom/files';\n  import { getAcceptedFileTypes } from '$lib/services/integrations/media-libraries/default';\n\n  /**\n   * @import { InternalLocaleCode, SelectedResource, TypedFieldKeyPath } from '$lib/types/private';\n   * @import {\n   * CustomField,\n   * CustomFieldPickFileOptions,\n   * CustomFieldPickedFile,\n   * MediaField,\n   * } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {CustomField} fieldConfig Field configuration.\n   * @property {TypedFieldKeyPath} typedKeyPath Typed key path to the field.\n   * @property {string} [componentName] Name of the rich text editor component the field is part\n   * of, if any.\n   * @property {boolean} [inEditorComponent] Whether the field is rendered in a rich text editor\n   * component.\n   * @property {InternalLocaleCode} [locale] Locale the field is edited in, which an existing asset\n   * in an entry-relative folder is referenced relative to.\n   */\n\n  /** @type {Props} */\n  let {\n    fieldConfig,\n    typedKeyPath,\n    componentName = undefined,\n    inEditorComponent = false,\n    locale = undefined,\n  } = $props();\n\n  const entryDraft = getEntryDraftContext();\n\n  let open = $state(false);\n  /** @type {CustomFieldPickFileOptions} */\n  let options = $state.raw({});\n  /** @type {RejectedFilesAlertDialog | undefined} */\n  let rejectedFilesAlert = $state();\n  /**\n   * Settles the promise returned by the pending `pick()` call. `undefined` while nothing is\n   * pending. The resolver is dropped as soon as a selection is made, so that the dialog closing\n   * afterwards doesn’t resolve the same call again with `null`.\n   * @type {PromiseWithResolvers<CustomFieldPickedFile | CustomFieldPickedFile[] | null> |\n   * undefined}\n   */\n  let pending;\n\n  const assetOptions = $derived(\n    entryDraft.current\n      ? getCustomFieldAssetOptions({\n          draft: entryDraft.current,\n          fieldConfig,\n          typedKeyPath,\n          componentName,\n        })\n      : undefined,\n  );\n  const kind = $derived(getPickedAssetKind(options));\n  // The dialog only falls back to the image types once, so give it the types for every pick. HEIC\n  // photos are accepted only if they’re converted on upload\n  const accept = $derived(\n    getAcceptedFileTypes({\n      accept: options.accept,\n      image: kind === 'image',\n      transformations: assetOptions?.libraryConfig.transformations,\n    }),\n  );\n  /* v8 ignore start -- only read to report a file exceeding the configured size */\n  const maxSize = $derived(assetOptions?.libraryConfig.max_file_size ?? Infinity);\n  /* v8 ignore stop */\n  // The dialog only reads the media library options from the field configuration, which a custom\n  // field may define the same way as a File/Image field\n  const mediaFieldConfig = $derived(/** @type {MediaField} */ (/** @type {any} */ (fieldConfig)));\n\n  /**\n   * Open the dialog and wait for the user to pick something. A call made while the dialog is\n   * already open shares the outcome of the pending call, since only one pick can be in progress.\n   * @param {CustomFieldPickFileOptions} [pickOptions] Options.\n   * @returns {Promise<CustomFieldPickedFile | CustomFieldPickedFile[] | null>} Picked file(s), or\n   * `null` if the dialog is dismissed or nothing usable is picked.\n   * @throws {Error} When no entry is being edited.\n   */\n  export const pick = async (pickOptions = {}) => {\n    if (!entryDraft.current) {\n      throw new Error('pickFile() can only be called while an entry is being edited');\n    }\n\n    if (!pending) {\n      pending = Promise.withResolvers();\n      options = pickOptions;\n      open = true;\n    }\n\n    return pending.promise;\n  };\n\n  /**\n   * Handle the resources selected in the dialog.\n   * @param {SelectedResource[]} resources Selected resources.\n   */\n  const onSelect = async (resources) => {\n    const draft = entryDraft.current;\n    /* v8 ignore start -- the dialog is only shown while a pick is pending and the draft is there */\n    const { resolve, reject } = pending ?? {};\n    // Read before the await below: another `pick()` call made in the meantime replaces the options\n    const { multiple = false } = options;\n\n    pending = undefined;\n\n    if (!resolve || !reject) {\n      return;\n    }\n\n    // The draft may have gone away while the dialog was closing; nothing can be picked then\n    if (!draft) {\n      resolve(null);\n\n      return;\n    }\n    /* v8 ignore stop */\n\n    try {\n      const { files, ...rejected } = await resolvePickedResources({\n        draft,\n        fieldConfig,\n        typedKeyPath,\n        componentName,\n        locale,\n        inEditorComponent,\n        resources,\n        accept,\n      });\n\n      rejectedFilesAlert?.report(rejected);\n\n      if (!files.length) {\n        resolve(null);\n      } else if (multiple) {\n        resolve(files);\n      } else {\n        resolve(files[0]);\n      }\n    } catch (error) {\n      reject(error);\n    }\n  };\n\n  /**\n   * Handle the dialog being closed. The call is still pending if the dialog was dismissed rather\n   * than closed with the Insert button.\n   */\n  const onClose = () => {\n    pending?.resolve(null);\n    pending = undefined;\n  };\n\n  // The dialog doesn’t get to close when the editor is left while it’s open, so settle the call\n  // here rather than leaving the control waiting forever\n  onDestroy(onClose);\n</script>\n\n{#if assetOptions}\n  <SelectAssetsDialog\n    {kind}\n    {accept}\n    multiple={!!options.multiple}\n    canEnterURL={options.allowURL ?? true}\n    draft={entryDraft.current}\n    {locale}\n    fieldConfig={mediaFieldConfig}\n    assetLibraryFolderMap={assetOptions.folderMap}\n    enabledCloudServiceEntries={assetOptions.cloudServiceEntries}\n    bind:open\n    {onSelect}\n    {onClose}\n  />\n\n  <ConflictResolutionDialog />\n\n  <RejectedFilesAlertDialog bind:this={rejectedFilesAlert} {maxSize} {accept} />\n{/if}\n","import { createContext } from 'react';\n\n/**\n * @import { Context } from 'react';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} FieldState\n * @property {string} [locale] Current pane’s locale.\n * @property {FieldKeyPath} [keyPath] Field key path.\n * @property {boolean} [required] Whether the field is required.\n * @property {boolean} [readonly] Whether the field is read-only.\n * @property {boolean} [invalid] Whether the field is invalid.\n */\n\n/**\n * React context that carries the state of the field being edited down to a built-in field component\n * reused within a custom field control. The field configuration passed to such a component is often\n * an ad hoc one that only describes how to render the input, so the state of the actual field has\n * to come from here. Otherwise a built-in editor wouldn’t know, for example, that the field is\n * required, and a Select editor would offer an “unselected” option that the CMS then rejects as\n * invalid.\n * @type {Context<FieldState>}\n */\nexport const fieldStateContext = createContext(/** @type {FieldState} */ ({}));\n","import { createLazyModule } from '$lib/services/api/lazy-module';\nimport { loadChunk } from '$lib/services/app/dependencies';\n\n/**\n * @import { LazyModule } from '$lib/services/api/lazy-module';\n */\n\n/**\n * @typedef {{ createRoot: typeof import('react-dom/client').createRoot }} ReactDomModule\n */\n\n/**\n * Loader for `react-dom`. Only the Netlify/Decap CMS-compatible API renders React components —\n * custom field types, preview templates and editor component previews — so the library is kept out\n * of the main bundle and fetched as a separate chunk when one of those is registered or used.\n * @type {LazyModule<ReactDomModule>}\n */\nconst reactDom = createLazyModule({\n  /**\n   * Fetch the library chunk.\n   * @returns {Promise<ReactDomModule>} The module.\n   */\n  loader: () => loadChunk('react-dom'),\n  notLoadedMessage: 'react-dom is not loaded yet. Call `loadReactDom()` first.',\n});\n\n/**\n * Whether `react-dom` has been loaded. Components that mount a React root synchronously can depend\n * on this to know when they can render.\n */\nexport const reactDomLoaded = reactDom.loaded;\n/**\n * Load `react-dom`. Calling this again returns the same promise.\n */\nexport const loadReactDom = reactDom.load;\n/**\n * Start loading `react-dom` in the background, so that it’s ready by the time a component needs it.\n * A failure is left for the eventual {@link loadReactDom} call to report.\n */\nexport const preloadReactDom = reactDom.preload;\n/**\n * Get the loaded `react-dom` module. The caller is responsible for awaiting {@link loadReactDom}\n * first.\n */\nexport const getReactDom = reactDom.get;\n/**\n * Forget the loaded module. Used in tests.\n */\nexport const _resetReactDom = reactDom.reset;\n\n/**\n * Create a handle on a React root for the element, which is only created on the first render and\n * can be unmounted. `react-dom` must have been loaded, as for {@link getReactDom}.\n * @param {HTMLElement} element Element to render into.\n * @returns {{\n * render: (node: import('react').ReactNode) => void,\n * unmount: () => void,\n * }} Handle.\n */\nexport const createReactRoot = (element) => {\n  /** @type {import('react-dom/client').Root | undefined} */\n  let root;\n\n  return {\n    /**\n     * Render a node, creating the root first if needed.\n     * @param {import('react').ReactNode} node React node.\n     */\n    render: (node) => {\n      root ??= reactDom.get().createRoot(element);\n      root.render(node);\n    },\n    /**\n     * Unmount the root, if it has been created.\n     */\n    unmount: () => {\n      root?.unmount();\n      root = undefined;\n    },\n  };\n};\n\n/**\n * Render a React node into the element once `react-dom` has been loaded, loading it if needed. The\n * returned function unmounts the node, and also keeps it from being rendered if the library is\n * still loading by then, e.g. because the element has been removed.\n * @param {HTMLElement} element Element to render into.\n * @param {import('react').ReactNode} node React node.\n * @returns {() => void} Function to unmount the node.\n */\nexport const mountReactNode = (element, node) => {\n  /** @type {ReturnType<typeof createReactRoot> | undefined} */\n  let handle;\n  let detached = false;\n\n  reactDom.load().then(\n    () => {\n      if (!detached) {\n        handle = createReactRoot(element);\n        handle.render(node);\n      }\n    },\n    (/** @type {Error} */ error) => {\n      // eslint-disable-next-line no-console\n      console.error(error);\n    },\n  );\n\n  return () => {\n    detached = true;\n    handle?.unmount();\n  };\n};\n","import { untrack } from 'svelte';\n\nimport { immutableLoaded, loadImmutable } from '$lib/services/api/immutable';\nimport { createReactRoot, loadReactDom, reactDomLoaded } from '$lib/services/api/react-dom';\n\n/**\n * @typedef {object} ReactRenderer\n * @property {boolean} ready Whether the React component can be rendered: `react-dom` and Immutable\n * have been loaded, and the container element is there. Reactive, so an effect checking it renders\n * the component once it’s ready.\n * @property {(node: import('react').ReactNode) => void} render Render a node into the container,\n * creating the root on the first render. Check {@link ReactRenderer.ready} first.\n */\n\n/**\n * Render a React component into an element of a Svelte component, the way a custom field control\n * or preview is rendered: the component receives Immutable Maps, so both libraries are loaded on\n * mount, and the root is unmounted along with the Svelte component. Call it while initializing the\n * Svelte component, as it creates an effect.\n * @param {() => HTMLElement | undefined} getContainer Function returning the element to render\n * into, typically bound with `bind:this`.\n * @returns {ReactRenderer} Renderer.\n */\nexport const createReactRenderer = (getContainer) => {\n  /**\n   * React root, created on the first render. Not reactive, as the effect rendering the component\n   * assigns it, and would otherwise run again right away.\n   * @type {ReturnType<typeof createReactRoot> | undefined}\n   */\n  let root;\n\n  // Like `onMount()`, which can only be called in a component\n  $effect(() =>\n    untrack(() => {\n      // Both libraries are normally loaded by the time the editor opens, as\n      // `CMS.registerFieldType()` starts loading them, but wait for them in any case; the effect\n      // rendering the component does so once they’re there\n      Promise.all([loadImmutable(), loadReactDom()]).catch((/** @type {Error} */ error) => {\n        // eslint-disable-next-line no-console\n        console.error(error);\n      });\n\n      return () => {\n        root?.unmount();\n      };\n    }),\n  );\n\n  return {\n    /**\n     * Get whether the React component can be rendered.\n     * @returns {boolean} Result.\n     */\n    get ready() {\n      return immutableLoaded.current && reactDomLoaded.current && !!getContainer();\n    },\n    /**\n     * Render a node into the container.\n     * @param {import('react').ReactNode} node React node.\n     */\n    render: (node) => {\n      root ??= createReactRoot(/** @type {HTMLElement} */ (getContainer()));\n      root.render(node);\n    },\n  };\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { resolveCollectionAndFile } from '$lib/services/contents/collection/files';\nimport { isAutoDuplicationEnabled, suspendAutoDuplication } from '$lib/services/contents/draft';\nimport { createValueMap } from '$lib/services/contents/draft/create/versioned-map.svelte';\nimport { revalidateField } from '$lib/services/contents/draft/validate/fields';\nimport { getDraftFieldArgs, getField } from '$lib/services/contents/entry/fields';\nimport { getValueOwnerField } from '$lib/services/contents/entry/owner-field';\nimport { getLocalizedFieldValue } from '$lib/services/contents/fields/locale';\nimport {\n  findDuplicateIfEmptyField,\n  followsDefaultLocale,\n  getMainValueKeyPath,\n} from '$lib/services/contents/i18n/duplicate-if-empty';\nimport { isDuplicatedField, isSyncedField } from '$lib/services/contents/i18n/shared-values';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * OwnerField,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath, LocaleCode } from '$lib/types/public';\n */\n\nconst PATH_MATCH_REGEX = /(?<path>.+?)\\.[^.]*$/;\n\n/**\n * Get a function to check if a duplicated field can be copied to, or deleted from, another locale\n * at the same key path. That depends on the items of the List fields the field belongs to: the\n * items of a List field that isn’t duplicated itself are translatable, so the other locale may have\n * fewer items, or an item of another type at the same position. The value is then only copied to\n * the locales that have the item, of the same type, so that no stray item is created there or a\n * value written into an unrelated item. The items of a duplicated List field are the same in every\n * locale.\n * @param {object} args Arguments.\n * @param {Field | undefined} args.fieldConfig Field configuration, as resolved for the source\n * locale.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the key\n * path of the field.\n * @returns {(content: FlattenedEntryContent) => boolean} Function taking the content of the other\n * locale and returning whether the field can be written there.\n * @see https://github.com/sveltia/sveltia-cms/issues/1075\n */\nexport const getListItemMatcher = ({ fieldConfig, getFieldArgs }) => {\n  const { keyPath } = getFieldArgs;\n  const segments = keyPath.split('.');\n\n  const itemKeyPaths = segments\n    .map((segment, index) => {\n      if (index === 0 || !isNumeric(segment)) {\n        return undefined;\n      }\n\n      const listKeyPath = segments.slice(0, index).join('.');\n      const listGetFieldArgs = { ...getFieldArgs, keyPath: listKeyPath };\n      const listField = getField(listGetFieldArgs);\n\n      // An index of a multi-value field such as `images.0` is not an item of its own\n      if (\n        listField?.widget !== 'list' ||\n        isDuplicatedField({ fieldConfig: listField, getFieldArgs: listGetFieldArgs })\n      ) {\n        return undefined;\n      }\n\n      return `${listKeyPath}.${segment}`;\n    })\n    .filter((itemKeyPath) => itemKeyPath !== undefined);\n\n  if (!itemKeyPaths.length) {\n    return () => true;\n  }\n\n  return (content) => {\n    /**\n     * Check if the other locale has the given list item. The key path itself is looked up first, so\n     * the key scan through the `$state` proxy only runs when the value is missing there.\n     * @param {string} itemKeyPath Key path of the list item, e.g. `blocks.1`.\n     * @returns {boolean} Result.\n     */\n    const hasItem = (itemKeyPath) =>\n      keyPath in content ||\n      itemKeyPath in content ||\n      Object.keys(content).some((_keyPath) => _keyPath.startsWith(`${itemKeyPath}.`));\n\n    // A variable type resolves to the same field only if the item has the same type in both\n    // locales. That’s checked first, as it rules out a missing variable type item without the scan\n    return (\n      getField({ ...getFieldArgs, valueMap: content }) === fieldConfig &&\n      itemKeyPaths.every(hasItem)\n    );\n  };\n};\n\n/**\n * Check if the parent of the given key path, if any, exists in another locale’s content, so that a\n * value can be copied there.\n * @param {object} args Arguments.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the key\n * path of the value.\n * @param {FlattenedEntryContent} args.content Content of the other locale.\n * @returns {boolean} Result.\n */\nconst hasParentInLocale = ({ getFieldArgs, content }) => {\n  const { keyPath } = getFieldArgs;\n\n  if (!keyPath.includes('.')) {\n    return true;\n  }\n\n  // The regex always matches since keyPath is guaranteed to contain a dot (checked above).\n  const parentKeyPath = /** @type {string} */ (keyPath.match(PATH_MATCH_REGEX)?.groups?.path);\n\n  // `getField()` is memoized, while the key scan walks the whole locale’s content through the\n  // `$state` proxy, so a configured parent — the usual case — never pays for the scan\n  return (\n    !!getField({ ...getFieldArgs, keyPath: parentKeyPath }) ||\n    Object.keys(content).some((_keyPath) => _keyPath.startsWith(`${parentKeyPath}.`))\n  );\n};\n\n/**\n * Call a function for each locale other than the source locale where a value can be copied to, i.e.\n * The parent object exists and the list items match.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the key\n * path of the value.\n * @param {LocaleCode} args.sourceLanguage Source locale.\n * @param {(content: FlattenedEntryContent) => boolean} args.matchesListItems Function returned by\n * {@link getListItemMatcher}.\n * @param {(content: FlattenedEntryContent, targetLanguage: LocaleCode) => void} callback Function\n * called with the content and code of the target locale.\n */\nconst forEachCopyTargetLocale = (\n  { draft, getFieldArgs, sourceLanguage, matchesListItems },\n  callback,\n) => {\n  Object.entries(draft.currentValues).forEach(([targetLanguage, content]) => {\n    // Don’t copy the value if the parent object doesn’t exist, or to a list item that doesn’t exist\n    // in the target locale, or that is of another type there\n    if (\n      targetLanguage !== sourceLanguage &&\n      hasParentInLocale({ getFieldArgs, content }) &&\n      matchesListItems(content)\n    ) {\n      callback(content, targetLanguage);\n    }\n  });\n};\n\n/**\n * Copy a value written in the source locale to the other locales, as the field holds the same\n * value in every locale: the source is the default locale for a field using the `duplicate` i18n\n * strategy, and any locale for one using `sync`.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the key\n * path of the value.\n * @param {Field} args.fieldConfig Configuration of the field the value belongs to.\n * @param {FieldKeyPath} [args.fieldKeyPath] Key path of the field, which differs from the key path\n * of the value for a value owned by a field, like a KeyValue pair. See {@link getValueOwnerField}.\n * @param {LocaleCode} args.sourceLanguage Source locale.\n * @param {any} args.value Value to copy to other locales.\n */\nexport const copyMirroredValue = ({\n  draft,\n  getFieldArgs,\n  fieldConfig,\n  fieldKeyPath = getFieldArgs.keyPath,\n  sourceLanguage,\n  value,\n}) => {\n  const { keyPath } = getFieldArgs;\n\n  const matchesListItems = getListItemMatcher({\n    fieldConfig,\n    getFieldArgs: { ...getFieldArgs, keyPath: fieldKeyPath },\n  });\n\n  forEachCopyTargetLocale(\n    { draft, getFieldArgs, sourceLanguage, matchesListItems },\n    (content, targetLanguage) => {\n      // Keep the source `value` intact, as it’s used for the remaining target locales\n      const localizedValue = getLocalizedFieldValue({\n        fieldConfig,\n        value,\n        sourceLocale: sourceLanguage,\n        targetLocale: targetLanguage,\n      });\n\n      if (content[keyPath] !== localizedValue) {\n        content[keyPath] = localizedValue;\n      }\n    },\n  );\n};\n\n/**\n * Copy a value written in the default locale to the other locales where the field, which uses the\n * `duplicate_if_empty` i18n strategy, is empty or still holds the default locale’s value from\n * before the write. The latter keeps a locale that follows the default locale in sync as the user\n * types, while a value of its own entered in the locale is left alone.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the key\n * path of the written value.\n * @param {Field} args.fieldConfig Configuration of the field the value belongs to.\n * @param {FieldKeyPath} args.fieldKeyPath Key path of the field, which differs from the key path of\n * the value for a Code field that outputs the language along with the code.\n * @param {LocaleCode} args.sourceLanguage Source locale, which is the default locale.\n * @param {any} args.value Written value.\n * @param {any} args.previousValue Value the key path held before the write.\n * @param {boolean} [args.deleted] Whether the value was deleted rather than written, as when a\n * field is reverted, which deletes the value before restoring the original one. It’s then deleted\n * from the locales that follow, so that the restored value is copied to them again.\n * @see https://github.com/sveltia/sveltia-cms/issues/120\n */\nexport const copyDefaultLocaleValueIfEmpty = ({\n  draft,\n  getFieldArgs,\n  fieldConfig,\n  fieldKeyPath,\n  sourceLanguage,\n  value,\n  previousValue,\n  deleted = false,\n}) => {\n  const { keyPath, valueMap } = getFieldArgs;\n  const mainKeyPath = getMainValueKeyPath(fieldConfig, fieldKeyPath);\n\n  // The value map is always given by the proxy\n  const previousMainValue =\n    keyPath === mainKeyPath\n      ? previousValue\n      : /** @type {FlattenedEntryContent} */ (valueMap)[mainKeyPath];\n\n  const matchesListItems = getListItemMatcher({\n    fieldConfig,\n    getFieldArgs: { ...getFieldArgs, keyPath: fieldKeyPath },\n  });\n\n  forEachCopyTargetLocale(\n    { draft, getFieldArgs, sourceLanguage, matchesListItems },\n    (content, targetLanguage) => {\n      const targetMainValue = content[mainKeyPath];\n\n      const follows = followsDefaultLocale({\n        fieldConfig,\n        targetValue: targetMainValue,\n        previousValue: previousMainValue,\n        sourceLocale: sourceLanguage,\n        targetLocale: targetLanguage,\n      });\n\n      if (deleted) {\n        if (follows && keyPath in content) {\n          delete content[keyPath];\n        }\n\n        return;\n      }\n\n      const localizedValue = getLocalizedFieldValue({\n        fieldConfig,\n        value,\n        sourceLocale: sourceLanguage,\n        targetLocale: targetLanguage,\n      });\n\n      if (\n        follows &&\n        // A Code field’s object value is replaced with an empty object of the same shape, so leave\n        // the one the locale already has\n        !(isObject(value) && isObject(content[keyPath])) &&\n        content[keyPath] !== localizedValue\n      ) {\n        content[keyPath] = localizedValue;\n      }\n    },\n  );\n};\n\n/**\n * Create a Proxy holding a locale’s field values, which revalidates a field as its value is written\n * or deleted, and automatically copies the value to the other locales if the field’s i18n strategy\n * is `duplicate` or `sync`, or to those where the field is empty if the strategy is\n * `duplicate_if_empty`.\n *\n * The values are held in a value map created with {@link createValueMap}.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft the values belong to. The draft is read as fields are\n * written, e.g. to find the other locales’ values and update the validities, so it has to be the\n * reactive draft object, not a plain copy.\n * @param {string} args.locale Source locale.\n * @param {FlattenedEntryContent} [args.target] Plain object holding the initial values.\n * @param {() => FlattenedEntryContent} [args.getValueMap] Optional function to get an object\n * holding the current entry values. It will be used for the `valueMap` argument of\n * {@link getField}. If omitted, the proxy target will be used instead.\n * @returns {any} Created proxy.\n */\nexport const createProxy = ({ draft, locale: sourceLanguage, target = {}, getValueMap }) => {\n  const { collectionName, fileName, isIndexFile } = draft;\n  const draftFieldArgs = { collectionName, fileName, isIndexFile };\n  const resolved = resolveCollectionAndFile(collectionName, fileName);\n\n  if (!resolved) {\n    return undefined;\n  }\n\n  const { collection, collectionFile } = resolved;\n\n  const {\n    defaultLocale,\n    canonicalSlug: { key: canonicalSlugKey },\n  } = (collectionFile ?? collection)._i18n;\n\n  /**\n   * Check if the value is written in the default locale with auto-duplication enabled, in which\n   * case it can be copied to the other locales.\n   * @returns {boolean} Result.\n   */\n  const isDefaultLocaleSource = () =>\n    isAutoDuplicationEnabled() && sourceLanguage === defaultLocale;\n\n  /**\n   * Check if auto-duplication should be performed for the given field: a value written in the\n   * default locale is copied if the field holds the same value in every locale, and one written in\n   * another locale only if the field uses the `sync` strategy, as a `duplicate` field can’t be\n   * edited there.\n   * @param {Field} fieldConfig Field configuration.\n   * @param {GetFieldArgs} getFieldArgs Arguments for the `getField` function.\n   * @returns {boolean} True if auto-duplication should be performed.\n   */\n  const shouldAutoDuplicate = (fieldConfig, getFieldArgs) =>\n    isAutoDuplicationEnabled() &&\n    (sourceLanguage === defaultLocale\n      ? isDuplicatedField({ fieldConfig, getFieldArgs })\n      : isSyncedField({ fieldConfig, getFieldArgs }));\n\n  /**\n   * Get field configuration for the given key path.\n   * @param {object} obj The proxy target object.\n   * @param {FieldKeyPath} keyPath The field key path.\n   * @returns {{ valueMap: any, getFieldArgs: GetFieldArgs, fieldConfig: Field | undefined }}\n   * Field info.\n   */\n  const getFieldInfo = (obj, keyPath) => {\n    const valueMap = typeof getValueMap === 'function' ? getValueMap() : obj;\n    const getFieldArgs = getDraftFieldArgs(draftFieldArgs, { keyPath, valueMap });\n    const fieldConfig = getField({ ...getFieldArgs });\n\n    return { valueMap, getFieldArgs, fieldConfig };\n  };\n\n  /**\n   * Get the field whose value has to be copied to, or deleted from, the other locales along with\n   * the value at the given key path: the field at the key path or, for a value without a field of\n   * its own, the field owning it. See {@link getValueOwnerField}.\n   * @param {Field | undefined} fieldConfig Configuration of the field at the key path, if any.\n   * @param {GetFieldArgs} getFieldArgs Arguments for the `getField` function, including the key\n   * path of the value.\n   * @returns {OwnerField | undefined} Key path and configuration of the field, or `undefined` if\n   * the value isn’t copied.\n   */\n  const getMirroredField = (fieldConfig, getFieldArgs) => {\n    const field = fieldConfig\n      ? { keyPath: getFieldArgs.keyPath, fieldConfig }\n      : getValueOwnerField(getFieldArgs);\n\n    return field &&\n      shouldAutoDuplicate(field.fieldConfig, { ...getFieldArgs, keyPath: field.keyPath })\n      ? field\n      : undefined;\n  };\n\n  /**\n   * Copy a value written to, or deleted from, the default locale to the other locales where the\n   * field uses the `duplicate_if_empty` i18n strategy and is empty or in sync with the default\n   * locale. See {@link copyDefaultLocaleValueIfEmpty}.\n   * @param {object} args Arguments.\n   * @param {Field | undefined} args.fieldConfig Configuration of the field at the key path.\n   * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the\n   * key path of the value.\n   * @param {any} [args.value] Written value.\n   * @param {any} args.previousValue Value the key path held before.\n   * @param {boolean} [args.deleted] Whether the value was deleted.\n   */\n  const followDefaultLocale = ({ fieldConfig, getFieldArgs, value, previousValue, deleted }) => {\n    if (!isDefaultLocaleSource()) {\n      return;\n    }\n\n    const { keyPath } = getFieldArgs;\n\n    const duplicateIfEmpty = findDuplicateIfEmptyField(keyPath, (_keyPath) =>\n      _keyPath === keyPath ? fieldConfig : getField({ ...getFieldArgs, keyPath: _keyPath }),\n    );\n\n    if (duplicateIfEmpty) {\n      copyDefaultLocaleValueIfEmpty({\n        draft,\n        getFieldArgs,\n        ...duplicateIfEmpty,\n        sourceLanguage,\n        value,\n        previousValue,\n        deleted,\n      });\n    }\n  };\n\n  return createValueMap(target, {\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    onSet: (obj, /** @type {FieldKeyPath} */ keyPath, value, previousValue, added) => {\n      // Skip the rest in some cases\n      if ([canonicalSlugKey].includes(keyPath)) {\n        return;\n      }\n\n      const { fieldConfig, getFieldArgs, valueMap } = getFieldInfo(obj, keyPath);\n\n      // Update the validity and validation message in real time if validation has already been\n      // performed. A value without a field of its own may be a KeyValue pair, which is validated\n      // as part of its field, so that’s left to `revalidateField()` to tell\n      revalidateField({ draft, locale: sourceLanguage, keyPath, value, valueMap, keyAdded: added });\n\n      const mirroredField = getMirroredField(fieldConfig, getFieldArgs);\n\n      // Copy value to other locales. The copies would otherwise be copied on again from each of\n      // them, as a `sync` field is copied from any locale\n      if (mirroredField) {\n        suspendAutoDuplication(() => {\n          copyMirroredValue({\n            draft,\n            getFieldArgs,\n            fieldConfig: mirroredField.fieldConfig,\n            fieldKeyPath: mirroredField.keyPath,\n            sourceLanguage,\n            value,\n          });\n        });\n      }\n\n      // Copy value to other locales where the field is empty\n      followDefaultLocale({ fieldConfig, getFieldArgs, value, previousValue });\n    },\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    onDelete: (obj, /** @type {FieldKeyPath} */ keyPath, previousValue) => {\n      const { fieldConfig, getFieldArgs, valueMap } = getFieldInfo(obj, keyPath);\n\n      // Update the validity and validation message in real time as well, e.g. when the last item of\n      // a List field is removed, which leaves the list with fewer items than it had\n      if (keyPath !== canonicalSlugKey) {\n        revalidateField({ draft, locale: sourceLanguage, keyPath, value: undefined, valueMap });\n      }\n\n      const mirroredField = getMirroredField(fieldConfig, getFieldArgs);\n\n      // Remove the property from other locales\n      if (mirroredField) {\n        const matchesListItems = getListItemMatcher({\n          fieldConfig: mirroredField.fieldConfig,\n          getFieldArgs: { ...getFieldArgs, keyPath: mirroredField.keyPath },\n        });\n\n        suspendAutoDuplication(() => {\n          forEachCopyTargetLocale(\n            { draft, getFieldArgs, sourceLanguage, matchesListItems },\n            (content) => {\n              if (keyPath in content) {\n                delete content[keyPath];\n              }\n            },\n          );\n        });\n      }\n\n      // Remove the property from other locales that follow the default locale\n      followDefaultLocale({ fieldConfig, getFieldArgs, previousValue, deleted: true });\n    },\n  });\n};\n","import { generateUUID } from '@sveltia/utils/crypto';\n\nimport { processNestedTemplates } from '$lib/services/common/template/nested';\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { applyTransformations, parseTransformations } from '$lib/services/common/transformations';\nimport { user } from '$lib/services/user/account.svelte';\n\n/**\n * @import { GetDefaultValueMapFuncArgs, User } from '$lib/types/private';\n * @import { FieldKeyPath, HiddenField } from '$lib/types/public';\n */\n\n/**\n * Replace a template tag with its corresponding value based on the provided context.\n * @param {string} tag The template tag to replace.\n * @param {object} context The context for replacement.\n * @param {string} context.locale The current locale.\n * @param {User} context.account The current user account.\n * @returns {string} The replaced value for the template tag.\n */\nconst replaceTemplateTag = (tag, { locale, account: { email = '', login = '', name = '' } }) => {\n  if (tag === 'locale') {\n    return locale;\n  }\n\n  if (tag === 'datetime') {\n    return new Date().toJSON().replace(/\\d+\\.\\d+Z$/, '00.000Z');\n  }\n\n  if (tag === 'uuid') {\n    return generateUUID();\n  }\n\n  if (tag === 'uuid_short') {\n    return generateUUID('short');\n  }\n\n  if (tag === 'uuid_shorter') {\n    return generateUUID('shorter');\n  }\n\n  if (tag === 'author-email') {\n    return email;\n  }\n\n  if (tag === 'author-login') {\n    return login;\n  }\n\n  if (tag === 'author-name') {\n    return name;\n  }\n\n  return '';\n};\n\n/**\n * Get the default value for a Hidden field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {any} Default value.\n */\nconst getDefaultValue = ({ fieldConfig, locale, dynamicValue }) => {\n  const { default: defaultValue } = /** @type {HiddenField} */ (fieldConfig);\n  const value = dynamicValue ?? defaultValue;\n\n  if (typeof value !== 'string') {\n    return value;\n  }\n\n  const context = { locale, account: /** @type {User} */ (user.account) };\n\n  /**\n   * Resolve a template tag of the value.\n   * @param {string} placeholder Tag content, e.g. `author-name | upper`.\n   * @returns {string} Resolved value.\n   */\n  const resolvePlaceholder = (placeholder) => {\n    const { value: tag, transformations: parsedTransformations } =\n      parseTransformations(placeholder);\n\n    const val = replaceTemplateTag(tag, context);\n    // Resolve the tags in the transformation arguments, e.g. `default('{{author-login}}')`\n    const transformations = processNestedTemplates(parsedTransformations, resolvePlaceholder);\n\n    if (transformations.length) {\n      return applyTransformations({ value: val, transformations, locale });\n    }\n\n    return val;\n  };\n\n  return replaceTemplateTags(value, (_match, placeholder) => resolvePlaceholder(placeholder));\n};\n\n/**\n * Get the default value map for a Hidden field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<FieldKeyPath, any>} Default value map.\n */\nexport const getDefaultValueMap = (args) => ({ [args.keyPath]: getDefaultValue(args) });\n","import { generateRandomId, generateUUID } from '@sveltia/utils/crypto';\n\n/**\n * @import { UuidField } from '$lib/types/public';\n */\n\n/**\n * Get the initial value for a UUID field.\n * @param {UuidField} fieldConfig Field configuration.\n * @returns {string} Initial value, either a UUID or a prefixed random ID.\n */\nexport const getInitialValue = (fieldConfig) => {\n  const { prefix, use_b32_encoding: useEncoding } = fieldConfig;\n  const value = useEncoding ? generateRandomId() : generateUUID();\n\n  return prefix ? `${prefix}${value}` : value;\n};\n","import { getField } from '$lib/services/contents/entry/fields';\nimport { hasUuidTag } from '$lib/services/contents/fields/compute/helpers';\nimport { getDefaultValueMap as getHiddenFieldDefaultValueMap } from '$lib/services/contents/fields/hidden/defaults';\nimport { getInitialValue } from '$lib/services/contents/fields/uuid/helpers';\nimport { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\nimport { isDuplicatedField } from '$lib/services/contents/i18n/shared-values';\n\n/**\n * @import {\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalLocaleCode,\n * LocaleContentMap,\n * } from '$lib/types/private';\n * @import { ComputeField, Field, FieldKeyPath, UuidField } from '$lib/types/public';\n */\n\n/**\n * Types of the fields whose values are unique to an entry or list item, and renewed when it’s\n * duplicated. See {@link getRenewedUniqueValue}.\n * @type {string[]}\n */\nexport const UNIQUE_VALUE_FIELD_TYPES = ['uuid', 'compute', 'hidden'];\n\n/**\n * Get a new value for the given field of a duplicated entry or list item, so the duplicate doesn’t\n * share the values unique to its source: a UUID field gets a new UUID, unless it’s empty, which is\n * filled in later as with a new entry or item; a Compute field with a UUID tag is cleared, as it\n * keeps the UUIDs found in its current value when it’s resolved again; and a Hidden field gets its\n * default value again, which can hold a UUID tag as well. Any other field keeps its value.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {any} [args.value] Current value.\n * @param {InternalLocaleCode} args.locale Locale of the value.\n * @param {InternalLocaleCode} args.defaultLocale Default locale.\n * @returns {any} New value.\n */\nexport const getRenewedUniqueValue = ({ fieldConfig, keyPath, value, locale, defaultLocale }) => {\n  const { widget: fieldType } = fieldConfig;\n\n  if (fieldType === 'uuid') {\n    return value ? getInitialValue(/** @type {UuidField} */ (fieldConfig)) : value;\n  }\n\n  if (fieldType === 'compute') {\n    return hasUuidTag(/** @type {ComputeField} */ (fieldConfig).value) ? '' : value;\n  }\n\n  if (fieldType === 'hidden') {\n    return getHiddenFieldDefaultValueMap({ fieldConfig, keyPath, locale, defaultLocale })[keyPath];\n  }\n\n  return value;\n};\n\n/**\n * Regular expression to match the key path of the innermost list item a field belongs to, e.g.\n * `blocks.0` for `blocks.0.meta.id`.\n */\nconst LIST_ITEM_KEY_PATH_REGEX = /^.*\\.\\d+(?=\\.)/;\n\n/**\n * Fill in the empty UUID fields of a new entry draft, so that every UUID is in place as soon as the\n * draft is created, whether or not the field is ever rendered in the editor. The default locale and\n * any locale where the field is translatable get a UUID of their own, while a duplicated field,\n * including one nested in a List or Object field with the `duplicate` i18n strategy, takes the\n * default locale’s value, as the default values of each locale are created separately. A value\n * that is already there, e.g. a dynamic default value, is kept.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.contentMap Flattened content of each locale, modified in place.\n * @param {InternalLocaleCode} args.defaultLocale Default locale.\n * @param {Omit<GetFieldArgs, 'keyPath' | 'valueMap'>} args.getFieldArgs Arguments for\n * {@link getField}, except the key path and value map.\n */\nexport const fillUuidValues = ({ contentMap, defaultLocale, getFieldArgs }) => {\n  const defaultContent = contentMap[defaultLocale];\n\n  /**\n   * Get the configuration of the UUID field at the given key path.\n   * @param {FlattenedEntryContent} content Content the key path belongs to.\n   * @param {string} keyPath Key path.\n   * @returns {UuidField | undefined} Field configuration, or `undefined` if it’s not a UUID field.\n   */\n  const getUuidField = (content, keyPath) => {\n    const fieldConfig = getField({ ...getFieldArgs, keyPath, valueMap: content });\n\n    return fieldConfig?.widget === 'uuid' ? /** @type {UuidField} */ (fieldConfig) : undefined;\n  };\n\n  if (defaultContent) {\n    Object.keys(defaultContent).forEach((keyPath) => {\n      const fieldConfig = getUuidField(defaultContent, keyPath);\n\n      if (fieldConfig && !defaultContent[keyPath]) {\n        defaultContent[keyPath] = getInitialValue(fieldConfig);\n      }\n    });\n  }\n\n  Object.entries(contentMap).forEach(([locale, content]) => {\n    if (locale === defaultLocale) {\n      return;\n    }\n\n    Object.keys(content).forEach((keyPath) => {\n      const fieldConfig = getUuidField(content, keyPath);\n\n      if (fieldConfig && !content[keyPath] && isFieldTranslatable(fieldConfig.i18n)) {\n        content[keyPath] = getInitialValue(fieldConfig);\n      }\n    });\n\n    if (!defaultContent) {\n      return;\n    }\n\n    // A duplicated field takes the default locale’s value. A field nested in a duplicated List or\n    // Object field isn’t among the locale’s default values unless it has an `i18n` option of its\n    // own, so copy it as long as the list item it belongs to, if any, is there as well\n    Object.entries(defaultContent).forEach(([keyPath, value]) => {\n      const fieldConfig = getUuidField(defaultContent, keyPath);\n      const listItemKeyPath = keyPath.match(LIST_ITEM_KEY_PATH_REGEX)?.[0];\n\n      if (\n        fieldConfig &&\n        !content[keyPath] &&\n        isDuplicatedField({\n          fieldConfig,\n          getFieldArgs: { ...getFieldArgs, keyPath, valueMap: defaultContent },\n        }) &&\n        (!listItemKeyPath ||\n          Object.keys(content).some((key) => key.startsWith(`${listItemKeyPath}.`)))\n      ) {\n        content[keyPath] = value;\n      }\n    });\n  });\n};\n","/**\n * @import { BooleanField, FieldKeyPath } from '$lib/types/public';\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n */\n\n/**\n * Get the default value for a Boolean field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {boolean} Default value.\n */\nconst getDefaultValue = ({ fieldConfig, dynamicValue }) => {\n  if (dynamicValue !== undefined) {\n    return dynamicValue === 'true';\n  }\n\n  const { default: defaultValue } = /** @type {BooleanField} */ (fieldConfig);\n\n  if (typeof defaultValue === 'boolean') {\n    return defaultValue;\n  }\n\n  return false;\n};\n\n/**\n * Get the default value map for a Boolean field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<FieldKeyPath, boolean>} Default value map.\n */\nexport const getDefaultValueMap = (args) => ({ [args.keyPath]: getDefaultValue(args) });\n","import { isObject } from '@sveltia/utils/object';\n\nimport { getSubtreeEntries } from '$lib/services/contents/entry/subtree';\nimport { getCodeKeys } from '$lib/services/contents/fields/code/helpers';\n\n/**\n * @import { CodeField, FieldKeyPath } from '$lib/types/public';\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n */\n\n/**\n * Get the default value map for a Code field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<FieldKeyPath, any>} Default value map.\n */\nexport const getDefaultValueMap = ({ fieldConfig, keyPath, dynamicValue }) => {\n  const { default: defaultValue } = /** @type {CodeField} */ (fieldConfig);\n  const outputKeys = getCodeKeys(/** @type {CodeField} */ (fieldConfig));\n  const value = dynamicValue !== undefined ? dynamicValue : defaultValue;\n\n  if (!outputKeys) {\n    return { [keyPath]: typeof value === 'string' ? value : '' };\n  }\n\n  const obj = isObject(value) ? value : undefined;\n  const code = obj?.[outputKeys.code] ?? value;\n  const lang = obj?.[outputKeys.lang] ?? '';\n\n  return getSubtreeEntries(keyPath, {\n    [outputKeys.code]: typeof code === 'string' ? code : '',\n    [outputKeys.lang]: typeof lang === 'string' ? lang : '',\n  });\n};\n","import { getCurrentStorableValue } from '$lib/services/contents/fields/date-time/value';\n\n/**\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n * @import { DateTimeField, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Get the default value for a DateTime field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {string} Default value.\n */\nconst getDefaultValue = ({ fieldConfig, dynamicValue, locale }) => {\n  const config = /** @type {DateTimeField} */ (fieldConfig);\n  const defaultValue = config.default;\n  const value = dynamicValue ?? defaultValue;\n\n  if (typeof value !== 'string') {\n    return '';\n  }\n\n  // Decap CMS 3.3.0 changed the default value from the current date/time to blank, requiring\n  // `{{now}}` to use the current date/time.\n  // @see https://github.com/decaporg/decap-cms/releases/tag/decap-cms%403.3.0\n  // @see https://github.com/decaporg/decap-website/commit/01e54d8392e368e5d7b9fec307f50af584b12c91\n  if (value === '{{now}}') {\n    return getCurrentStorableValue(config, { locale });\n  }\n\n  return value;\n};\n\n/**\n * Get the default value map for a DateTime field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<FieldKeyPath, string>} Default value map.\n */\nexport const getDefaultValueMap = (args) => ({ [args.keyPath]: getDefaultValue(args) });\n","import { getSubtreeEntries } from '$lib/services/contents/entry/subtree';\nimport { isMultiple } from '$lib/services/integrations/media-libraries/multiple';\n\n/**\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n * @import { MediaField } from '$lib/types/public';\n */\n\n/**\n * Get the default value map for a File/Image field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<string, string>} Default value map.\n */\nexport const getDefaultValueMap = ({ fieldConfig, keyPath, dynamicValue }) => {\n  const config = /** @type {MediaField} */ (fieldConfig);\n  const defaultValue = config.default;\n  const multiple = isMultiple(config);\n  /** @type {string | string[]} */\n  let value = '';\n\n  if (dynamicValue !== undefined) {\n    value = multiple ? dynamicValue.split(/,\\s*/) : dynamicValue;\n  } else if (multiple) {\n    value = Array.isArray(defaultValue) ? defaultValue : [];\n  } else {\n    value = typeof defaultValue === 'string' ? defaultValue : '';\n  }\n\n  /** @type {Record<string, any>} */\n  const content = {};\n\n  // An empty list is kept, like that of a List field, so an optional field without files is still\n  // written out as an empty value\n  if (multiple && Array.isArray(value)) {\n    value = value.map((val) => val.trim()).filter((val) => val !== '');\n    Object.assign(content, getSubtreeEntries(keyPath, value));\n  }\n\n  if (!multiple && typeof value === 'string') {\n    content[keyPath] = value.trim();\n  }\n\n  return content;\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { isFieldRequired } from '$lib/services/contents/entry/fields';\nimport { escapeKeySegment } from '$lib/services/utils/object';\n\n/**\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n * @import { FieldKeyPath, KeyValueField } from '$lib/types/public';\n */\n\n/**\n * Get the default value for a KeyValue field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<string, any>} Default value.\n */\nconst getDefaultValue = ({ fieldConfig, locale }) => {\n  const { default: defaultValue } = /** @type {KeyValueField} */ (fieldConfig);\n  const required = isFieldRequired({ fieldConfig, locale });\n\n  if (isObject(defaultValue)) {\n    return defaultValue;\n  }\n\n  if (required) {\n    return { '': '' };\n  }\n\n  return {};\n};\n\n/**\n * Get the default value map for a KeyValue field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<FieldKeyPath, string>} Default value map.\n */\nexport const getDefaultValueMap = (args) => {\n  const { keyPath, dynamicValue } = args;\n  /** @type {Record<string, any> | undefined} */\n  let valueMap;\n\n  if (dynamicValue !== undefined) {\n    try {\n      const jsonValue = JSON.parse(dynamicValue);\n\n      if (isObject(jsonValue)) {\n        // Valid JSON object, use it (even if empty)\n        valueMap = jsonValue;\n      }\n    } catch {\n      // Invalid JSON\n    }\n  }\n\n  valueMap ??= getDefaultValue(args);\n\n  return Object.fromEntries(\n    Object.entries(valueMap)\n      .filter(([, val]) => typeof val === 'string')\n      .map(([key, val]) => [`${keyPath}.${escapeKeySegment(key)}`, val]),\n  );\n};\n","import {\n  getNumberFieldValue,\n  getValueType,\n  isInvalidNumberValue,\n  isStringOutput,\n  parseNumber,\n} from '$lib/services/contents/fields/number/helpers';\n\n/**\n * @import { FieldKeyPath, NumberField } from '$lib/types/public';\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n */\n\n/**\n * Value types of a Number field.\n */\nconst VALUE_TYPES = ['int', 'float', 'int/string', 'float/string'];\n\n/**\n * Get the default value map for a Number field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<FieldKeyPath, number | string | null>} Default value map.\n */\nexport const getDefaultValueMap = ({ fieldConfig, keyPath, dynamicValue }) => {\n  const config = /** @type {NumberField} */ (fieldConfig);\n  const value = dynamicValue ?? config.default;\n\n  if (value === undefined) {\n    return { [keyPath]: isStringOutput(config) ? '' : null };\n  }\n\n  if (!VALUE_TYPES.includes(getValueType(config))) {\n    return {};\n  }\n\n  const number = parseNumber(value);\n\n  if (isInvalidNumberValue(number, config)) {\n    return {};\n  }\n\n  // The `int/string` and `float/string` types accept the same input as `int` and `float` but save\n  // it as a string, which is what the editor writes once the value is changed\n  return { [keyPath]: getNumberFieldValue({ inputValue: number, fieldConfig: config }) };\n};\n","import { stripTags } from '@sveltia/utils/string';\n\nimport { cmsConfig } from '$lib/services/config';\n\n/**\n * @import { MarkdownField, RichTextField } from '$lib/types/public';\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n */\n\n/**\n * Escape every `<` that would start a tag, comment or declaration in Markdown or HTML: one followed\n * by a letter, `/`, `!` or `?`.\n * @param {string} str Original string.\n * @returns {string} Escaped string.\n */\nconst escapeTagOpenings = (str) => str.replaceAll(/<(?=[!/?a-z])/gi, '&lt;');\n\n/**\n * Sanitize a value given in the URL for a new entry, e.g. `?body=…`, to prevent XSS attacks as the\n * preview may not be sanitized: anyone can craft such a URL. `stripTags()` returns `textContent`,\n * which decodes character references, e.g. `&lt;svg&gt;` becomes `<svg>`, so escape any `<` that\n * would start a tag again. Other ones are left as is, e.g. `a < b` in a code span, where Markdown\n * would show the reference itself.\n * @param {string} value Value given in the URL.\n * @returns {string} Sanitized value.\n */\nexport const sanitizeDynamicValue = (value) => {\n  try {\n    return escapeTagOpenings(stripTags(value));\n  } catch {\n    // Fallback for environments where DOMParser is not available (in Vitest). Use a simple regex\n    // to remove HTML tags as a basic sanitization measure\n    return escapeTagOpenings(value.replace(/<[^>]*>/g, ''));\n  }\n};\n\n/**\n * Get the default value map for a RichText/Markdown field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<string, string>} Default value map.\n */\nexport const getDefaultValueMap = ({ fieldConfig, keyPath, dynamicValue }) => {\n  const { default: defaultValue = cmsConfig.current?.field_defaults?.richtext?.default } =\n    /** @type {MarkdownField | RichTextField} */ (fieldConfig);\n\n  const value =\n    dynamicValue !== undefined ? sanitizeDynamicValue(dynamicValue) : defaultValue || '';\n\n  return { [keyPath]: value };\n};\n","import { getEmptyOptionValue, getOptionValue } from '$lib/services/contents/fields/select/helpers';\n\n/**\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n * @import { FieldKeyPath, RelationField, SelectField } from '$lib/types/public';\n */\n\n/**\n * Get the default value map for a Relation/Select field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<FieldKeyPath, any>} Default value map.\n */\nexport const getDefaultValueMap = ({ fieldConfig, keyPath, dynamicValue }) => {\n  const config = /** @type {RelationField | SelectField} */ (fieldConfig);\n  const { default: defaultValue, multiple = false } = config;\n  // A Relation field has no `options`, so its value is always a string\n  const options = /** @type {SelectField} */ (config).options ?? [];\n  const [firstOption] = options;\n\n  /**\n   * Convert a dynamic default value, which comes as a string, to the value of the matching option,\n   * so that a number or boolean option is saved as such rather than as a string.\n   * @param {string} token Value given in the URL.\n   * @returns {any} Option value, or the given string if no option matches.\n   */\n  const toOptionValue = (token) => {\n    const index = options.findIndex((option) => String(getOptionValue(option)) === token);\n\n    return index > -1 ? getOptionValue(options[index]) : token;\n  };\n\n  if (dynamicValue !== undefined && !multiple) {\n    // A single value is taken as a whole, as it may contain a comma, e.g. `Smith, John`\n    const token = dynamicValue.trim();\n\n    return {\n      [keyPath]: token ? toOptionValue(token) : getEmptyOptionValue(getOptionValue(firstOption)),\n    };\n  }\n\n  // A default can be given as an option object, whose `value` is what gets saved\n  const value =\n    dynamicValue !== undefined\n      ? dynamicValue\n          .split(/,\\s*/)\n          .map((val) => val.trim())\n          // Filter out empty strings, as in `?tags=` or `?tags=a,,b`, which would add empty items\n          .filter((val) => val !== '')\n          .map(toOptionValue)\n      : Array.isArray(defaultValue)\n        ? defaultValue.map(getOptionValue)\n        : getOptionValue(defaultValue);\n\n  if (!multiple) {\n    return {\n      [keyPath]: value !== undefined ? value : getEmptyOptionValue(getOptionValue(firstOption)),\n    };\n  }\n\n  if (Array.isArray(value) && value.length) {\n    return Object.fromEntries(value.map((val, index) => [`${keyPath}.${index}`, val]));\n  }\n\n  return { [keyPath]: [] };\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { isFieldRequired } from '$lib/services/contents/entry/fields';\nimport { isKeyPathWithin } from '$lib/services/contents/entry/key-paths';\nimport { getSubtreeEntries } from '$lib/services/contents/entry/subtree';\nimport { getDefaultValueMap as getBooleanDefaultValueMap } from '$lib/services/contents/fields/boolean/defaults';\nimport { getDefaultValueMap as getNumberDefaultValueMap } from '$lib/services/contents/fields/number/defaults';\nimport { getDefaultValueMap as getRichTextDefaultValueMap } from '$lib/services/contents/fields/rich-text/defaults';\nimport { getDefaultValueMap as getSelectDefaultValueMap } from '$lib/services/contents/fields/select/defaults';\n\n/**\n * @import { GetDefaultValueMapFuncArgs, InternalLocaleCode } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * ListField,\n * ListFieldWithSubField,\n * ListFieldWithSubFields,\n * ListFieldWithTypes,\n * } from '$lib/types/public';\n */\n\n/**\n * Fill in the subfields a default item leaves out, so that the item has the same shape as one\n * added in the editor: each missing subfield gets its own default value, or an empty value. Also\n * used for the `default` of an Object field, which is an item of the same kind.\n * @param {object} args Arguments.\n * @param {Record<FieldKeyPath, any>} args.content Default value map being built.\n * @param {FieldKeyPath} args.itemKeyPath Key path of the item, e.g. `links.0`, or of the Object\n * field, e.g. `author`.\n * @param {Field[]} args.fields Subfields of the item.\n * @param {GetDefaultValueMapFuncArgs} args.funcArgs Arguments given to the field’s function.\n */\nexport const populateMissingSubfields = ({ content, itemKeyPath, fields, funcArgs }) => {\n  const { locale, defaultLocale, populateDefault } = funcArgs;\n  const keys = Object.keys(content);\n\n  fields.forEach((subfield) => {\n    const subfieldKeyPath = `${itemKeyPath}.${subfield.name}`;\n\n    // An Object or List subfield given in the item is held under its child key paths\n    if (keys.some((key) => isKeyPathWithin(key, subfieldKeyPath))) {\n      return;\n    }\n\n    populateDefault?.({\n      content,\n      keyPath: subfieldKeyPath,\n      fieldConfig: subfield,\n      locale,\n      defaultLocale,\n      dynamicValues: {},\n    });\n  });\n};\n\n/**\n * Check whether a List field is to hold its one item from the start. A required field limited to\n * one item with `max: 1` can’t do without it, so the item is there for the user to fill in, like\n * the subfields of an Object field, rather than having to be added first. That doesn’t apply to a\n * list with variable types, as the user has to choose the type of the item, nor to a list without\n * subfields, whose editor always shows an input anyway.\n * @param {object} args Arguments.\n * @param {ListField} args.fieldConfig Field configuration.\n * @param {InternalLocaleCode} args.locale Locale.\n * @returns {boolean} Result.\n */\nexport const hasRequiredSingleItem = ({ fieldConfig, locale }) =>\n  fieldConfig.max === 1 &&\n  ('fields' in fieldConfig || 'field' in fieldConfig) &&\n  isFieldRequired({ fieldConfig, locale });\n\n/**\n * Get the default value map of a Select or Relation subfield for one item of a dynamic default\n * value, which is a single option even if the subfield allows multiple: a number or boolean option\n * is held as such rather than as a string.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<FieldKeyPath, any>} Default value map.\n */\nconst getOptionItemValueMap = (args) =>\n  getSelectDefaultValueMap({ ...args, fieldConfig: { ...args.fieldConfig, multiple: false } });\n\n/**\n * Functions converting a dynamic default value to the value of a field, for the field types whose\n * value isn’t the string given in the URL as is.\n * @type {Record<string, (args: GetDefaultValueMapFuncArgs) => Record<string, any>>}\n */\nconst DYNAMIC_ITEM_VALUE_FUNCTIONS = {\n  boolean: getBooleanDefaultValueMap,\n  number: getNumberDefaultValueMap,\n  markdown: getRichTextDefaultValueMap,\n  richtext: getRichTextDefaultValueMap,\n  relation: getOptionItemValueMap,\n  select: getOptionItemValueMap,\n};\n\n/**\n * Convert an item of a dynamic default value, which comes as a string, to the value the single\n * subfield of a List field holds, the way the subfield’s own dynamic default value is converted,\n * e.g. a number for a Number subfield, `true` or `false` for a Boolean subfield, or the sanitized\n * string for a RichText subfield, as the preview may not be sanitized.\n * @param {string} token Item given in the URL, e.g. `1` in `?ratings=1,2`.\n * @param {Field | undefined} subfield Single subfield of the List field, if any.\n * @param {Omit<GetDefaultValueMapFuncArgs, 'fieldConfig' | 'keyPath' | 'dynamicValue'>} args Other\n * arguments for the subfield’s default value function.\n * @returns {any} Item value, or `undefined` if the subfield can’t take it, e.g. `abc` for a Number\n * subfield.\n */\nconst toDynamicItemValue = (token, subfield, args) => {\n  const getValueMap = DYNAMIC_ITEM_VALUE_FUNCTIONS[subfield?.widget ?? 'string'];\n\n  if (!getValueMap) {\n    return token;\n  }\n\n  const fieldConfig = /** @type {Field} */ (subfield);\n  const value = getValueMap({ ...args, fieldConfig, keyPath: '_', dynamicValue: token })._;\n\n  return typeof value === 'string' ? value.trim() : value;\n};\n\n/**\n * Get the default value map for a List field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments.\n * @returns {Record<FieldKeyPath, any>} Default value map.\n */\nexport const getDefaultValueMap = (args) => {\n  const { fieldConfig, keyPath, dynamicValue, locale, defaultLocale, populateDefault } = args;\n  const { default: defaultValue } = /** @type {ListField} */ (fieldConfig);\n  const { field: subfield } = /** @type {ListFieldWithSubField} */ (fieldConfig);\n  const { fields } = /** @type {ListFieldWithSubFields} */ (fieldConfig);\n  const { types, typeKey = 'type' } = /** @type {ListFieldWithTypes} */ (fieldConfig);\n  /** @type {any[]} */\n  let value;\n\n  if (dynamicValue !== undefined) {\n    // Filter out empty strings (this handles the case where `dynamicValue` is ''), as well as the\n    // items the subfield can’t take\n    value = dynamicValue\n      .split(/,\\s*/)\n      .map((val) => val.trim())\n      // An empty item, as in `?tags=a,,b`, would be the empty value of a Select subfield, `null`\n      .filter((val) => val !== '')\n      .map((val) => toDynamicItemValue(val, subfield, { locale, defaultLocale }))\n      .filter((val) => val !== '' && val !== undefined);\n  } else {\n    value = Array.isArray(defaultValue) ? defaultValue : [];\n  }\n\n  const isArray = Array.isArray(value) && !!value.length;\n\n  if (!isArray) {\n    // Always return the main array, even if empty\n    const content = getSubtreeEntries(keyPath, []);\n\n    // Give a required single-item list its item, with the default values of the subfields\n    if (hasRequiredSingleItem({ fieldConfig: /** @type {ListField} */ (fieldConfig), locale })) {\n      const itemKeyPath = `${keyPath}.0`;\n\n      if (subfield) {\n        populateDefault?.({\n          content,\n          keyPath: itemKeyPath,\n          fieldConfig: subfield,\n          locale,\n          defaultLocale,\n          dynamicValues: {},\n        });\n      } else {\n        populateMissingSubfields({ content, itemKeyPath, fields, funcArgs: args });\n      }\n    }\n\n    return content;\n  }\n\n  // A simple List field holds scalars only, so drop any object that snuck into the default. A list\n  // with a single `field` holds whatever the subfield holds, so its default is taken as-is\n  const items = subfield || fields || types ? value : value.filter((val) => !isObject(val));\n  const content = getSubtreeEntries(keyPath, items);\n\n  // A default item of a list with `fields` or `types` may leave out some subfields\n  if (fields || types) {\n    items.forEach((item, index) => {\n      if (!isObject(item)) {\n        return;\n      }\n\n      const itemFields = fields ?? types.find(({ name }) => name === item[typeKey])?.fields;\n\n      if (itemFields) {\n        populateMissingSubfields({\n          content,\n          itemKeyPath: `${keyPath}.${index}`,\n          fields: itemFields,\n          funcArgs: args,\n        });\n      }\n    });\n  }\n\n  return content;\n};\n","import { getDefaultValueMap as getBooleanFieldDefaultValueMap } from '$lib/services/contents/fields/boolean/defaults';\nimport { getDefaultValueMap as getCodeFieldDefaultValueMap } from '$lib/services/contents/fields/code/defaults';\nimport { getDefaultValueMap as getDateTimeFieldDefaultValueMap } from '$lib/services/contents/fields/date-time/defaults';\nimport { getDefaultValueMap as getFileFieldDefaultValueMap } from '$lib/services/contents/fields/file/defaults';\nimport { getDefaultValueMap as getHiddenFieldDefaultValueMap } from '$lib/services/contents/fields/hidden/defaults';\nimport { getDefaultValueMap as getKeyValueFieldDefaultValueMap } from '$lib/services/contents/fields/key-value/defaults';\nimport { getDefaultValueMap as getListFieldDefaultValueMap } from '$lib/services/contents/fields/list/defaults';\nimport { getDefaultValueMap as getNumberFieldDefaultValueMap } from '$lib/services/contents/fields/number/defaults';\nimport { getDefaultValueMap as getObjectFieldDefaultValueMap } from '$lib/services/contents/fields/object/defaults';\nimport { getDefaultValueMap as getRichTextFieldDefaultValueMap } from '$lib/services/contents/fields/rich-text/defaults';\nimport { getDefaultValueMap as getSelectFieldDefaultValueMap } from '$lib/services/contents/fields/select/defaults';\n\n/**\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Map of functions to get default values for different field types.\n * @type {Record<string, (args: GetDefaultValueMapFuncArgs) => Record<FieldKeyPath, any>>}\n */\nexport const GET_DEFAULT_VALUE_MAP_FUNCTIONS = {\n  boolean: getBooleanFieldDefaultValueMap,\n  code: getCodeFieldDefaultValueMap,\n  datetime: getDateTimeFieldDefaultValueMap,\n  file: getFileFieldDefaultValueMap,\n  hidden: getHiddenFieldDefaultValueMap,\n  image: getFileFieldDefaultValueMap, // alias\n  keyvalue: getKeyValueFieldDefaultValueMap,\n  list: getListFieldDefaultValueMap,\n  markdown: getRichTextFieldDefaultValueMap, // alias\n  number: getNumberFieldDefaultValueMap,\n  object: getObjectFieldDefaultValueMap,\n  relation: getSelectFieldDefaultValueMap, // alias\n  richtext: getRichTextFieldDefaultValueMap,\n  select: getSelectFieldDefaultValueMap,\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { isFieldRequired } from '$lib/services/contents/entry/fields';\nimport { populateMissingSubfields } from '$lib/services/contents/fields/list/defaults';\nimport { flattenKeys } from '$lib/services/utils/object';\n\n/**\n * @import { FlattenedEntryContent, GetDefaultValueMapFuncArgs } from '$lib/types/private';\n * @import {\n * FieldKeyPath,\n * ObjectField,\n * ObjectFieldWithSubFields,\n * ObjectFieldWithTypes,\n * } from '$lib/types/public';\n */\n\n/**\n * Get the default value map for an Object field.\n * @param {GetDefaultValueMapFuncArgs} args Arguments. Note that `dynamicValue` is not used here, as\n * an Object field doesn’t take a dynamic value as a whole. Its subfields can have their own, e.g.\n * `?author.name=John`, which `populateDefault` passes down to them.\n * @returns {Record<FieldKeyPath, any>} Default value map.\n */\nexport const getDefaultValueMap = (args) => {\n  const { fieldConfig, keyPath, locale, defaultLocale, dynamicValues = {}, populateDefault } = args;\n  const { default: defaultValue } = /** @type {ObjectField} */ (fieldConfig);\n  const { fields: subFields } = /** @type {ObjectFieldWithSubFields} */ (fieldConfig);\n  const { types, typeKey = 'type' } = /** @type {ObjectFieldWithTypes} */ (fieldConfig);\n  const required = isFieldRequired({ fieldConfig, locale });\n  /** @type {FlattenedEntryContent} */\n  const content = {};\n\n  // If the default value is a valid object, flatten it and prefix keys\n  if (isObject(defaultValue)) {\n    // Flatten the object and prefix keys with the key path and index\n    Object.entries(flattenKeys(defaultValue)).forEach(([key, val]) => {\n      content[`${keyPath}.${key}`] = val;\n    });\n\n    // The default may leave out some subfields, which then get their own default values, as they\n    // do in a List item. With variable types, only the subfields of the chosen type count\n    const fields = Array.isArray(types)\n      ? types.find(({ name }) => name === defaultValue[typeKey])?.fields\n      : subFields;\n\n    if (fields) {\n      populateMissingSubfields({ content, itemKeyPath: keyPath, fields, funcArgs: args });\n    }\n\n    return content;\n  }\n\n  // An optional field is created after all when a subfield is given a dynamic value, e.g.\n  // `?meta.source=newsletter`, which would otherwise be lost\n  const hasDynamicSubfieldValues = Object.keys(dynamicValues).some((key) =>\n    key.startsWith(`${keyPath}.`),\n  );\n\n  if ((!required && !hasDynamicSubfieldValues) || Array.isArray(types)) {\n    // Enable validation - for optional fields or fields with variable types\n    content[keyPath] = null;\n\n    return content;\n  }\n\n  // For required fields, or optional ones with dynamic subfield values, without object-level\n  // default values and without types, populate default values from subfields if they exist and\n  // have defaults, or their dynamic values\n  if (subFields && subFields.length > 0) {\n    subFields.forEach((_subField) => {\n      populateDefault?.({\n        content,\n        keyPath: [keyPath, _subField.name].join('.'),\n        fieldConfig: _subField,\n        locale,\n        defaultLocale,\n        dynamicValues: {},\n      });\n    });\n  }\n\n  return content;\n};\n","import { GET_DEFAULT_VALUE_MAP_FUNCTIONS } from '$lib/services/contents/fields/defaults';\nimport { isFieldI18nDisabled } from '$lib/services/contents/i18n/fields';\nimport { localizeDefaultValue } from '$lib/services/contents/i18n/options';\n\n/**\n * @import {\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * PopulateDefaultValueArgs,\n * } from '$lib/types/private';\n * @import { Field } from '$lib/types/public';\n */\n\n/**\n * Populate the default value for the given field. Check if a dynamic default value is specified,\n * then look for the field configuration’s `default_localized` and `default` properties.\n * @param {PopulateDefaultValueArgs} args Arguments.\n * @returns {void} The `content` object is modified in place.\n */\nexport const populateDefaultValue = ({\n  content,\n  keyPath,\n  fieldConfig: _fieldConfig,\n  locale,\n  defaultLocale,\n  dynamicValues,\n}) => {\n  const fieldConfig = localizeDefaultValue({ fieldConfig: _fieldConfig, locale, defaultLocale });\n  // @ts-ignore `default` is not defined in the Compute and custom field types\n  const { widget: fieldType = 'string', default: defaultValue, i18n = false } = fieldConfig;\n\n  // For non-default locales, only set the default value if the field is i18n-enabled\n  if (locale !== defaultLocale && isFieldI18nDisabled(i18n)) {\n    return;\n  }\n\n  // The `compute` field type doesn’t have the `default` option, so we just set an empty string,\n  // otherwise the field won’t work properly\n  if (fieldType === 'compute') {\n    content[keyPath] = '';\n\n    return;\n  }\n\n  const dynamicValue =\n    // Ignore the dynamic value if the key path looks like an array item, e.g. `tags.0` or\n    // `tags.0.name`, because lists are complicated to handle\n    Object.hasOwn(dynamicValues, keyPath) && !/\\.\\d+(?:\\.|$)/.test(keyPath)\n      ? dynamicValues[keyPath].trim() || undefined\n      : undefined;\n\n  const getDefaultValue = GET_DEFAULT_VALUE_MAP_FUNCTIONS[fieldType];\n\n  if (getDefaultValue) {\n    /**\n     * Populate the default value of a subfield. A subfield of an Object field can have a dynamic\n     * value of its own, given with the dot notation, e.g. `?author.name=John`, so the dynamic\n     * values are passed down. Those of a List field item, e.g. `links.0.url`, are ignored above.\n     * @param {PopulateDefaultValueArgs} subfieldArgs Arguments for the subfield.\n     * @returns {void} The `content` object is modified in place.\n     */\n    const populateDefault = (subfieldArgs) =>\n      populateDefaultValue({ ...subfieldArgs, dynamicValues });\n\n    Object.assign(\n      content,\n      getDefaultValue({\n        fieldConfig,\n        keyPath,\n        locale,\n        defaultLocale,\n        dynamicValue,\n        dynamicValues,\n        populateDefault,\n      }),\n    );\n\n    return;\n  }\n\n  // Handle simple string-type fields, including the built-in `color`, `uuid`, `string` and `text`\n  // field types as well as custom field types. A falsy default like `0` or `false` is kept\n  content[keyPath] = dynamicValue ?? defaultValue ?? '';\n};\n\n/**\n * Get the default values for the given fields. If dynamic default values are given, these values\n * take precedence over static default values defined with the CMS configuration.\n * @param {object} args Arguments.\n * @param {Field[]} args.fields Field list of a collection.\n * @param {InternalLocaleCode} args.locale Locale.\n * @param {InternalLocaleCode} args.defaultLocale Default locale of the entry draft.\n * @param {Record<string, string>} [args.dynamicValues] Dynamic default values.\n * @returns {FlattenedEntryContent} Flattened entry content for creating a new draft content or\n * adding a new list item.\n */\nexport const getDefaultValues = ({ fields, locale, defaultLocale, dynamicValues = {} }) => {\n  /** @type {FlattenedEntryContent} */\n  const content = {};\n\n  fields.forEach((fieldConfig) => {\n    populateDefaultValue({\n      content,\n      keyPath: fieldConfig.name,\n      fieldConfig,\n      locale,\n      defaultLocale,\n      dynamicValues,\n    });\n  });\n\n  return content;\n};\n","import {\n  getKeyValueField,\n  getPairsFromContent,\n  PAIR_KEY_PATH_REGEX,\n  setPairs,\n} from '$lib/services/contents/fields/key-value/pairs';\n\n/**\n * @import { GetFieldArgs, InternalLocaleCode, LocaleContentMap } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Line up a locale’s key-value pairs with the default locale’s keys, as the `duplicate_keys` i18n\n * strategy requires. The locale keeps its own values: a key it already holds keeps its value, a key\n * that has just been renamed in the default locale — the pair at the same position, whose key is no\n * longer there — keeps the value it had under the old name, and a new key starts empty.\n * @param {[string, string][]} defaultPairs Pairs in the default locale.\n * @param {[string, string][]} localePairs Pairs in the locale to line up.\n * @returns {[string, string][]} Pairs for the locale, in the default locale’s order.\n */\nexport const alignPairs = (defaultPairs, localePairs) => {\n  const keys = defaultPairs.map(([key]) => key);\n\n  return defaultPairs.map(([key], index) => {\n    const existing = localePairs.find(([_key]) => _key === key);\n\n    if (existing) {\n      return existing;\n    }\n\n    const displaced = localePairs[index];\n\n    if (displaced && !keys.includes(displaced[0])) {\n      return [key, displaced[1]];\n    }\n\n    return [key, ''];\n  });\n};\n\n/**\n * Mirror the keys of a KeyValue field using the `duplicate_keys` i18n strategy from the default\n * locale to every other locale in the given value store, keeping each locale’s own values. See\n * {@link alignPairs} for how the values are carried over.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.valueStore Value store to update, e.g. `draft.currentValues`,\n * keyed by locale. Each locale’s content is modified in place.\n * @param {InternalLocaleCode} args.defaultLocale Default locale.\n * @param {FieldKeyPath} args.keyPath Field key path.\n */\nexport const syncDuplicateKeys = ({ valueStore, defaultLocale, keyPath }) => {\n  const defaultPairs = getPairsFromContent(valueStore[defaultLocale] ?? {}, keyPath);\n\n  Object.entries(valueStore).forEach(([locale, content]) => {\n    if (locale === defaultLocale) {\n      return;\n    }\n\n    const localePairs = getPairsFromContent(content, keyPath);\n    const alignedPairs = alignPairs(defaultPairs, localePairs);\n\n    // Leave the content alone if nothing has changed, so the draft isn’t marked as modified\n    if (\n      alignedPairs.length !== localePairs.length ||\n      alignedPairs.some(([key, value], index) => {\n        const [_key, _value] = localePairs[index];\n\n        return key !== _key || value !== _value;\n      })\n    ) {\n      setPairs(content, keyPath, alignedPairs);\n    }\n\n    // With no keys left, the default locale holds the placeholder the editor stores for an empty\n    // KeyValue field. Mirror it, or the locale would be saved as an empty object rather than the\n    // same empty value, depending on whether its own editor happens to be open to add it\n    if (\n      !alignedPairs.length &&\n      valueStore[defaultLocale]?.[keyPath] === null &&\n      content[keyPath] !== null\n    ) {\n      content[keyPath] = null;\n    }\n  });\n};\n\n/**\n * Find the KeyValue fields using the `duplicate_keys` i18n strategy that hold pairs in any locale\n * of the given value store. The pairs are stored under arbitrary keys that `getField()` can’t\n * resolve, so the fields are found through the parent key path of each pair instead.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.valueStore Value store, e.g. `draft.currentValues`, keyed by\n * locale.\n * @param {Omit<GetFieldArgs, 'keyPath' | 'valueMap'>} args.getFieldArgs Arguments for the\n * `getField()` function.\n * @returns {FieldKeyPath[]} Key paths of the fields.\n */\nexport const getDuplicateKeysFieldKeyPaths = ({ valueStore, getFieldArgs }) => {\n  /** @type {Set<FieldKeyPath>} */\n  const keyPaths = new Set();\n\n  Object.values(valueStore).forEach((valueMap) => {\n    Object.keys(valueMap).forEach((pairKeyPath) => {\n      const fieldConfig = getKeyValueField({ ...getFieldArgs, keyPath: pairKeyPath, valueMap });\n\n      if (fieldConfig?.i18n === 'duplicate_keys') {\n        keyPaths.add(pairKeyPath.replace(PAIR_KEY_PATH_REGEX, ''));\n      }\n    });\n  });\n\n  return [...keyPaths];\n};\n\n/**\n * Mirror the keys of every KeyValue field using the `duplicate_keys` i18n strategy from the default\n * locale to the other locales in the given value store. See {@link syncDuplicateKeys}.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.valueStore Value store to update, e.g. `draft.currentValues`,\n * keyed by locale. Each locale’s content is modified in place.\n * @param {InternalLocaleCode} args.defaultLocale Default locale.\n * @param {Omit<GetFieldArgs, 'keyPath' | 'valueMap'>} args.getFieldArgs Arguments for the\n * `getField()` function.\n */\nexport const syncAllDuplicateKeys = ({ valueStore, defaultLocale, getFieldArgs }) => {\n  getDuplicateKeysFieldKeyPaths({ valueStore, getFieldArgs }).forEach((keyPath) => {\n    syncDuplicateKeys({ valueStore, defaultLocale, keyPath });\n  });\n};\n","import { toRaw } from '@sveltia/utils/object';\n\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport { suspendAutoDuplication } from '$lib/services/contents/draft';\nimport { createProxy, getListItemMatcher } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { getRenewedUniqueValue } from '$lib/services/contents/draft/create/unique-values';\nimport { getDefaultValues } from '$lib/services/contents/draft/defaults';\nimport { getAliasesKey, removeAliases } from '$lib/services/contents/entry/aliases';\nimport { getDraftFieldArgs, getField } from '$lib/services/contents/entry/fields';\nimport { isKeyPathWithin } from '$lib/services/contents/entry/key-paths';\nimport { TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getDuplicateKeysFieldKeyPaths } from '$lib/services/contents/fields/key-value/duplicate-keys';\nimport { getPairsFromContent, setPairs } from '$lib/services/contents/fields/key-value/pairs';\nimport { getLocalizedFieldValue } from '$lib/services/contents/fields/locale';\nimport { getInitialValue as getInitialUuidValue } from '$lib/services/contents/fields/uuid/helpers';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport {\n  isFieldI18nDisabled,\n  isFieldLocalized,\n  isFieldMirrored,\n  isFieldTranslatable,\n} from '$lib/services/contents/i18n/fields';\nimport { isDuplicatedField } from '$lib/services/contents/i18n/shared-values';\n\n/**\n * @import { EntryDraft, FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * HiddenField,\n * ObjectFieldWithTypes,\n * UuidField,\n * } from '$lib/types/public';\n */\n\n/**\n * Run the given callback for every locale a field update has to be written to.\n *\n * A field with the `duplicate` or `sync` i18n strategy holds the same value in every locale, so an\n * update has to reach all of them, whichever locale it’s made in; any other field is written to the\n * given locale only.\n *\n * The draft proxy duplicates a `duplicate` field on its own whenever a value is assigned, which\n * would write every value twice here, so the callback runs with that suspended. Suspensions nest,\n * so a caller whose operation is wider than this loop can still suspend around the whole thing.\n *\n * A field nested in a List or Object field with the `duplicate` strategy is duplicated along with\n * it, even without the strategy of its own. Pass the draft and the key path to have that taken into\n * account, so that a list item or object added to such a field reaches every locale.\n * @param {object} args Arguments.\n * @param {Record<InternalLocaleCode, FlattenedEntryContent> | undefined} args.valueStore Value\n * store to update, e.g. `draft.currentValues`, keyed by locale.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @param {Field['i18n']} args.i18n Field i18n configuration.\n * @param {EntryDraft} [args.draft] Entry draft the value store belongs to.\n * @param {FieldKeyPath} [args.keyPath] Key path of the field being updated.\n * @param {(valueMap: FlattenedEntryContent, locale: InternalLocaleCode) => void} callback Function\n * to run for each target locale, taking that locale’s content and the locale code.\n */\nexport const forEachTargetLocale = ({ valueStore, locale, i18n, draft, keyPath }, callback) => {\n  // The field configuration can only be looked up for the entry’s own values, not for those of a\n  // rich text editor component, which live in another value store\n  const getFieldArgs =\n    draft && keyPath && valueStore === draft.currentValues\n      ? getDraftFieldArgs(draft, { keyPath, valueMap: valueStore[locale] })\n      : undefined;\n\n  // Resolve the field before any callback changes the values it’s resolved from. Look up the\n  // configuration rather than relying on the given `i18n`, which the caller may have defaulted to\n  // `false` for a field without the option, which would hide the ancestor’s strategy\n  const fieldConfig = getFieldArgs ? getField(getFieldArgs) : undefined;\n\n  const duplicated =\n    isFieldMirrored(i18n) ||\n    (!!getFieldArgs &&\n      isDuplicatedField({\n        fieldConfig: fieldConfig ?? /** @type {Field} */ ({ i18n }),\n        getFieldArgs,\n      }));\n\n  // A field in an item of a translatable List field is only written to the locales that have the\n  // same item\n  const matchesListItems =\n    duplicated && getFieldArgs ? getListItemMatcher({ fieldConfig, getFieldArgs }) : () => true;\n\n  suspendAutoDuplication(() => {\n    Object.entries(valueStore ?? {}).forEach(([_locale, valueMap]) => {\n      if (_locale === locale || (duplicated && matchesListItems(valueMap))) {\n        callback(valueMap, _locale);\n      }\n    });\n  });\n};\n\n/**\n * Check whether the given field is a Hidden field whose default value is a template, e.g.\n * `{{uuid}}`, which is filled in for each entry rather than shared by all of them.\n * @param {Field} field Field configuration.\n * @returns {boolean} Result.\n */\nconst hasTemplateDefault = (field) => {\n  const { widget, default: defaultValue } = /** @type {HiddenField} */ (field);\n\n  return widget === 'hidden' && typeof defaultValue === 'string' && hasTemplateTags(defaultValue);\n};\n\n/**\n * Check whether the default locale holds the same Object field as the target locale under the\n * given key path, so its values can be copied to the new object. The key path may resolve to\n * another field there, through a list item or a parent object of another variable type, and the\n * object itself may be of another type.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {FieldKeyPath} args.keyPath Key path of the Object field.\n * @param {FlattenedEntryContent} args.defaultLocaleContent Content of the default locale.\n * @param {FlattenedEntryContent} args.targetContent Content of the target locale, which already\n * holds the type of the new object, if any.\n * @returns {boolean} Result.\n */\nconst hasSameObject = ({ draft, keyPath, defaultLocaleContent, targetContent }) => {\n  const getFieldArgs = getDraftFieldArgs(draft, { keyPath, valueMap: targetContent });\n  const fieldConfig = getField(getFieldArgs);\n\n  if (\n    !fieldConfig ||\n    getField({ ...getFieldArgs, valueMap: defaultLocaleContent }) !== fieldConfig\n  ) {\n    return false;\n  }\n\n  const { types, typeKey = 'type' } = /** @type {ObjectFieldWithTypes} */ (fieldConfig);\n  const typeKeyPath = `${keyPath}.${typeKey}`;\n\n  return !types || defaultLocaleContent[typeKeyPath] === targetContent[typeKeyPath];\n};\n\n/**\n * Populate the given localized content with values from the default locale.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {FlattenedEntryContent} args.content Original content for the current locale.\n * @param {InternalLocaleCode} args.targetLanguage Target locale.\n * @param {FieldKeyPath} [args.keyPathPrefix] Key path of the parent Object field being populated,\n * e.g. `blocks.0.image`. When specified, only the keys under that key path are returned, so\n * unrelated default locale fields — including list items that don’t exist in the target locale —\n * are not copied over. The whole default locale content is still used to look up field\n * configurations, which requires sibling keys such as a variable type key. Nothing is copied if the\n * default locale holds another object under the key path, e.g. one of another type.\n * @returns {FlattenedEntryContent} Updated content.\n */\nexport const copyDefaultLocaleValues = ({ draft, content, targetLanguage, keyPathPrefix }) => {\n  const { collection, fields, currentValues } = draft;\n  const { defaultLocale } = getDraftI18nConfig(draft);\n  /** @type {FlattenedEntryContent} */\n  const defaultLocaleContent = toRaw(currentValues[defaultLocale]);\n\n  /**\n   * Pick the values under the key path of the Object field being populated.\n   * @param {FlattenedEntryContent} values Values.\n   * @returns {FlattenedEntryContent} Picked values.\n   */\n  const pickObjectValues = (values) =>\n    Object.fromEntries(\n      Object.entries(values).filter(([keyPath]) => keyPath.startsWith(`${keyPathPrefix}.`)),\n    );\n\n  // The default locale’s values under the key path may belong to another object, in which case the\n  // new one only gets its default values, just like in the default locale\n  if (\n    keyPathPrefix !== undefined &&\n    !hasSameObject({\n      draft,\n      keyPath: keyPathPrefix,\n      defaultLocaleContent,\n      targetContent: currentValues[targetLanguage] ?? {},\n    })\n  ) {\n    return pickObjectValues(content);\n  }\n\n  // URL aliases are redirects from the previous paths of each locale, added on save, so the default\n  // locale’s don’t apply to another locale\n  removeAliases(defaultLocaleContent, getAliasesKey({ collection, fields }));\n\n  const newContent = { ...toRaw(content), ...defaultLocaleContent };\n  const getFieldArgs = getDraftFieldArgs(draft, { valueMap: newContent });\n  /** @type {string[]} */\n  const noI18nFieldKeys = [];\n\n  // Process the merged content\n  Object.keys(newContent).forEach((keyPath) => {\n    const field = getField({ ...getFieldArgs, keyPath });\n\n    if (!field) {\n      return;\n    }\n\n    const { widget: fieldType = 'text' } = field;\n\n    // A field without an `i18n` option of its own is duplicated along with a List or Object field\n    // using the `duplicate` or `sync` strategy, so it has to be kept rather than removed as\n    // non-i18n\n    const i18n =\n      field.i18n ??\n      (isDuplicatedField({ fieldConfig: field, getFieldArgs: { ...getFieldArgs, keyPath } })\n        ? 'duplicate'\n        : false);\n\n    // Reset the field value to the default value or an empty string if the field is a text-like\n    // field type and i18n is enabled, because the content would likely be translated by the user.\n    // Otherwise, the content would be copied from the default locale. A `duplicate_if_empty` field\n    // keeps the default locale’s value until the user enters one of their own\n    if (\n      TEXT_FIELD_TYPES.includes(fieldType) &&\n      isFieldTranslatable(i18n) &&\n      i18n !== 'duplicate_if_empty'\n    ) {\n      newContent[keyPath] = content[keyPath] ?? '';\n    }\n\n    // A translatable field holding a value unique to the locale gets one of its own rather than the\n    // default locale’s, just like each locale of a new draft does. A UUID field keeps a UUID the\n    // locale already has (see `fillUuidValues()`); a Compute field generating UUIDs is cleared,\n    // and a Hidden field whose default is a template, like `{{locale}}` or `{{uuid}}`, gets it\n    // filled in again (see `getRenewedUniqueValue()`). A Hidden field with a static default is\n    // copied like any other value, so an entry keeps a value saved with an older configuration\n    if (isFieldTranslatable(i18n)) {\n      if (fieldType === 'uuid') {\n        newContent[keyPath] =\n          content[keyPath] || getInitialUuidValue(/** @type {UuidField} */ (field));\n      } else if (fieldType === 'compute' || hasTemplateDefault(field)) {\n        newContent[keyPath] = getRenewedUniqueValue({\n          fieldConfig: field,\n          keyPath,\n          value: newContent[keyPath],\n          locale: targetLanguage,\n          defaultLocale,\n        });\n      }\n    }\n\n    // A value copied from the default locale may be a Relation field value holding that locale as a\n    // prefix, or a DateTime field value written in its language with the `localize_format` option,\n    // so localize it for the target locale\n    if (keyPath in defaultLocaleContent) {\n      newContent[keyPath] = getLocalizedFieldValue({\n        fieldConfig: field,\n        value: newContent[keyPath],\n        sourceLocale: defaultLocale,\n        targetLocale: targetLanguage,\n      });\n    }\n\n    // Remove `null` values for object fields if i18n is enabled and the field is enabled in the\n    // default locale, otherwise the subfields will not be saved in the current locale\n    if (\n      fieldType === 'object' &&\n      isFieldLocalized(i18n) &&\n      defaultLocaleContent[keyPath] !== null\n    ) {\n      delete newContent[keyPath];\n    }\n\n    // Remove the field if i18n is disabled\n    if (isFieldI18nDisabled(i18n) || noI18nFieldKeys.some((key) => isKeyPathWithin(keyPath, key))) {\n      delete newContent[keyPath];\n      noI18nFieldKeys.push(keyPath);\n    }\n  });\n\n  // A KeyValue field with the `duplicate_keys` strategy takes its keys from the default locale but\n  // not its values, which are left for the user to fill in like a translatable text field. The\n  // merged content holds the pairs of every such field that is still enabled in this locale\n  getDuplicateKeysFieldKeyPaths({\n    valueStore: { [targetLanguage]: newContent },\n    getFieldArgs,\n  }).forEach((keyPath) => {\n    setPairs(\n      newContent,\n      keyPath,\n      getPairsFromContent(defaultLocaleContent, keyPath).map(([key]) => [\n        key,\n        content[`${keyPath}.${key}`] ?? '',\n      ]),\n    );\n  });\n\n  return keyPathPrefix !== undefined ? pickObjectValues(newContent) : newContent;\n};\n\n/**\n * Enable or disable the given locale’s content output for the entry draft.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale.\n */\nexport const toggleLocale = ({ draft, locale }) => {\n  const { fields, defaultLocale, currentLocales, currentValues, validities, validationMessages } =\n    draft;\n\n  const enabled = !currentLocales[locale];\n\n  currentLocales[locale] = enabled;\n\n  // Initialize the content for the locale\n  if (enabled && !currentValues[locale]) {\n    const newContent = getDefaultValues({ fields, locale, defaultLocale });\n\n    draft.originalValues[locale] = newContent;\n\n    currentValues[locale] = createProxy({\n      draft,\n      locale,\n      target: copyDefaultLocaleValues({ draft, content: newContent, targetLanguage: locale }),\n    });\n\n    return;\n  }\n\n  validities[locale] = {};\n  validationMessages[locale] = {};\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { forEachTargetLocale } from '$lib/services/contents/draft/update/locale';\nimport { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\nimport { setSubtree } from '$lib/services/contents/entry/subtree';\n\n/**\n * @import { DraftValueStoreKey, EntryDraft, InternalLocaleCode } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Update a field with a non-primitive value. Since our internal representation of such fields is a\n * flattened object, we need to flatten the new value and update the draft accordingly.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} args.valueStoreKey Value store key.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {Field['i18n']} args.i18n Field i18n configuration.\n * @param {any[] | Record<string, any>} args.value Value to set.\n */\nexport const updateNonPrimitiveValue = ({ draft, valueStoreKey, locale, keyPath, i18n, value }) => {\n  // Drop the existing subtree and write the new value in its place. The placeholder `setSubtree()`\n  // writes also keeps validation running when there are no items at all\n  forEachTargetLocale(\n    { valueStore: draft[valueStoreKey], locale, i18n, draft, keyPath },\n    (valueMap) => {\n      setSubtree(valueMap, keyPath, value);\n    },\n  );\n};\n\n/**\n * Update a field whose value can be of any type, like a custom field: an array or object is stored\n * under its child key paths, and a primitive replaces whatever the field held before. When a\n * control clears a list or object value with `null` or an empty string, the child key paths have\n * to go too, or they would still make up the old value, both in the control and in the saved file.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} args.valueStoreKey Value store key.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {Field['i18n']} args.i18n Field i18n configuration.\n * @param {any} args.value Value to set.\n */\nexport const updateFieldValue = ({ draft, valueStoreKey, locale, keyPath, i18n, value }) => {\n  if (Array.isArray(value) || isObject(value)) {\n    updateNonPrimitiveValue({ draft, valueStoreKey, locale, keyPath, i18n, value });\n\n    return;\n  }\n\n  forEachTargetLocale(\n    { valueStore: draft[valueStoreKey], locale, i18n, draft, keyPath },\n    (valueMap) => {\n      // Keep the field’s own key in place rather than deleting it as well, so that it isn’t moved\n      // to the end of the map\n      getKeysByPrefix(valueMap, `${keyPath}.`, { live: true }).forEach((key) => {\n        delete valueMap[key];\n      });\n\n      valueMap[keyPath] = value;\n    },\n  );\n};\n","/**\n * @import { ComponentType } from 'react';\n */\n\n/**\n * Types of the objects React’s `forwardRef()` and `memo()` return, which are components but not\n * functions.\n */\nconst WRAPPED_COMPONENT_TYPES = [Symbol.for('react.forward_ref'), Symbol.for('react.memo')];\n\n/**\n * Check if the given value is a React component the CMS can render: a function or class component,\n * or a component wrapped with `forwardRef()` or `memo()`.\n * @param {any} value Value to check.\n * @returns {value is ComponentType<any>} Result.\n */\nexport const isReactComponent = (value) =>\n  typeof value === 'function' || WRAPPED_COMPONENT_TYPES.includes(value?.$$typeof);\n","import { isReactComponent } from '$lib/services/api/react';\nimport { customFieldTypeRegistry } from '$lib/services/api/registries';\nimport { BUILTIN_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getFieldConfigMap, getPreviewData } from '$lib/services/contents/fields/custom/helpers';\n\n/**\n * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n * @import {\n * CustomField,\n * CustomFieldAddFileOptions,\n * CustomFieldControl,\n * CustomFieldControlProps,\n * CustomFieldPickFileOptions,\n * CustomFieldPickedFile,\n * } from '$lib/types/public';\n */\n\n/**\n * Resolve the actual control component from a string reference or return the component itself.\n * @param {CustomFieldControl | string | undefined} ctrl Control component or widget name.\n * @param {Set<string>} [visited] Names of the field types already looked up, used to avoid an\n * infinite loop when custom field types reference each other.\n * @returns {CustomFieldControl | undefined} Resolved control component or undefined.\n */\nexport const resolveControl = (ctrl, visited = new Set()) => {\n  if (isReactComponent(ctrl)) {\n    return ctrl;\n  }\n\n  if (typeof ctrl === 'string') {\n    if (visited.has(ctrl)) {\n      // eslint-disable-next-line no-console\n      console.warn(`Custom field type \"${ctrl}\" references itself through its control.`);\n\n      return undefined;\n    }\n\n    visited.add(ctrl);\n\n    const customFieldType = customFieldTypeRegistry.get(ctrl);\n\n    if (customFieldType?.control) {\n      if (isReactComponent(customFieldType.control)) {\n        return customFieldType.control;\n      }\n\n      return resolveControl(customFieldType.control, visited);\n    }\n\n    if (/** @type {string[]} */ (BUILTIN_FIELD_TYPES).includes(ctrl)) {\n      // Built-in editors are Svelte components, not React components. We can’t use them as React\n      // controls, so return `undefined`.\n      // eslint-disable-next-line no-console\n      console.warn(\n        `Custom field references built-in editor \"${ctrl}\" which is not a React component.`,\n      );\n\n      return undefined;\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Build the props for a custom field control component. The `entry` prop lets a control read any\n * value in the entry being edited, including the values of sibling fields, so that it can render\n * options derived from them. It’s rebuilt whenever the draft is updated, so the control is always\n * given the latest content. The `addFile` prop lets a control hand a file to the CMS, so that it’s\n * uploaded along with the entry; the blob URL it resolves to is meant to be stored in the value.\n * The `pickFile` prop opens the Select Assets dialog, so that a control can let the user pick an\n * existing asset the way a built-in File/Image field does. The `getAsset` prop resolves a stored\n * path to a URL the control can display, just like the prop of the same name a preview receives.\n * @param {object} args Arguments.\n * @param {string | null | undefined} args.fieldId Field ID.\n * @param {string | null | undefined} args.fieldClassName Class name for the wrapper element.\n * @param {CustomField} args.fieldConfig Field configuration.\n * @param {any} args.currentValue Current field value.\n * @param {EntryDraft | null | undefined} args.draft Draft entry state.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @param {(value: any) => void} args.onChange Change handler.\n * @param {(file: File | Blob, options?: CustomFieldAddFileOptions) => Promise<string>}\n * args.addFile Handler to add a file to the entry draft.\n * @param {(options?: CustomFieldPickFileOptions) => Promise<CustomFieldPickedFile |\n * CustomFieldPickedFile[] | null>} args.pickFile Handler to pick a file in the Select Assets\n * dialog.\n * @param {(instance: any) => void} args.handleRef Ref callback.\n * @returns {CustomFieldControlProps & { ref?: (instance: any) => void }} Props for React rendering.\n */\nexport const buildControlProps = ({\n  fieldId,\n  fieldClassName,\n  fieldConfig,\n  currentValue,\n  draft,\n  locale,\n  onChange,\n  addFile,\n  pickFile,\n  handleRef,\n}) => {\n  const previewData = draft ? getPreviewData({ draft, locale }) : undefined;\n\n  return {\n    value: currentValue,\n    field: getFieldConfigMap(fieldConfig),\n    forID: fieldId ?? '',\n    classNameWrapper: fieldClassName ?? '',\n    entry: previewData?.entryMap,\n    getAsset: previewData?.getAsset,\n    onChange,\n    addFile,\n    pickFile,\n    ref: handleRef,\n  };\n};\n","<!--\n  @component\n  Render a custom field control registered via `CMS.registerFieldType()`.\n  @see https://decapcms.org/docs/custom-widgets/\n  @see https://sveltiacms.app/en/docs/api/field-types\n-->\n<script module>\n  import { TextInput } from '@sveltia/ui';\n  import { mount } from 'svelte';\n\n  /** @type {string | undefined} */\n  let cachedFieldClassName = undefined;\n\n  /**\n   * Get the CSS class name of a built-in text input, so that a custom control can be styled\n   * consistently with built-in field types. The probe component is mounted once for the lifetime of\n   * the app and intentionally never unmounted, to keep its scoped CSS available.\n   *\n   * `mount()` creates the DOM synchronously, so the class is readable right away. Don’t\n   * `flushSync()` here: this is called from an effect, and a nested flush leaves Svelte without a\n   * current batch once the effect returns, which throws when the effect has written to state it\n   * also reads.\n   * @returns {string} Class name, or an empty string if it could not be determined.\n   */\n  const getInputClassName = () => {\n    if (cachedFieldClassName === undefined) {\n      const target = document.createElement('div');\n\n      mount(TextInput, { target });\n      cachedFieldClassName = /** @type {HTMLInputElement} */ (target.querySelector('input'))\n        .className;\n    }\n\n    return cachedFieldClassName;\n  };\n</script>\n\n<script>\n  import { createElement } from 'react';\n  import { onMount, untrack } from 'svelte';\n\n  import AssetPicker from '$lib/components/contents/details/fields/custom/asset-picker.svelte';\n  import { assetURLUpdates } from '$lib/services/api/asset-proxy';\n  import { fieldStateContext } from '$lib/services/api/field-state';\n  import { createReactRenderer } from '$lib/services/api/react-dom.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { updateFieldValue } from '$lib/services/contents/draft/update';\n  import {\n    registerCustomFieldInstance,\n    triggerCustomFieldValidation,\n    unregisterCustomFieldInstance,\n  } from '$lib/services/contents/draft/validate/custom-fields';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import {\n    getFieldEditorContext,\n    isInEditorComponent,\n  } from '$lib/services/contents/editor/field-context';\n  import { buildControlProps, resolveControl } from '$lib/services/contents/fields/custom/editor';\n  import { addFileToDraft } from '$lib/services/contents/fields/custom/files';\n\n  /**\n   * @import { FieldEditorProps, InternalLocaleCode } from '$lib/types/private';\n   * @import {\n   * CustomField,\n   * CustomFieldAddFileOptions,\n   * CustomFieldControl,\n   * CustomFieldPickFileOptions,\n   * CustomFieldPickedFile,\n   * FieldKeyPath,\n   * } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {CustomField} fieldConfig Field configuration.\n   * @property {any} currentValue Current field value.\n   * @property {CustomFieldControl | string} control React component or component name string.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const { valueStoreKey = 'currentValues', parentComponentNames = [] } = getFieldEditorContext();\n  const inEditorComponent = isInEditorComponent(valueStoreKey);\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    fieldId,\n    keyPath,\n    typedKeyPath,\n    fieldConfig,\n    currentValue,\n    required = true,\n    readonly = false,\n    invalid = false,\n    control,\n  } = $props();\n\n  /** @type {HTMLDivElement | undefined} */\n  let container = $state();\n  /**\n   * Renderer of the control, which is a React component receiving Immutable Maps. Created before\n   * the `onMount()` below, so the control is unmounted, and its instance detached, before the\n   * instance is unregistered.\n   */\n  const reactRenderer = createReactRenderer(() => container);\n  /**\n   * Control instance, or the handle a function control exposes with `useImperativeHandle()`. Not\n   * proxied, as it belongs to React.\n   * @type {any | undefined}\n   */\n  let componentInstance = $state.raw();\n  /** @type {AssetPicker | undefined} */\n  let assetPicker = $state();\n  /**\n   * Plain copies of the {@link locale} and {@link keyPath} props for unregistering the instance,\n   * which also happens in the teardown. A prop read there makes Svelte walk the derived graph above\n   * it without memoizing, which takes exponentially longer with each level of nesting.\n   * @type {{ locale: InternalLocaleCode, keyPath: FieldKeyPath }}\n   */\n  // svelte-ignore state_referenced_locally\n  let registration = { locale, keyPath };\n\n  const { i18n = false } = $derived(fieldConfig);\n  const resolvedControl = $derived(resolveControl(control));\n  const componentName = parentComponentNames.at(-1);\n\n  /**\n   * Handle value changes from the React component. Don’t use two-way binding here to avoid\n   * unexpected behavior.\n   * @param {any} value New value from the React component.\n   */\n  const handleChange = (value) => {\n    const draft = entryDraft.current;\n\n    if (!draft) {\n      return;\n    }\n\n    updateFieldValue({ draft, valueStoreKey, locale, keyPath, i18n, value });\n  };\n\n  /**\n   * Add a file to the entry draft on behalf of the React component, so that it’s uploaded along\n   * with the entry. The draft is read when the file is added rather than when the props are built,\n   * so a control that keeps the function around can still use it after the draft has been updated.\n   * @param {File | Blob} file File to be added.\n   * @param {CustomFieldAddFileOptions} [options] Options.\n   * @returns {Promise<string>} Blob URL to be stored in the field value.\n   */\n  const handleAddFile = async (file, options) => {\n    if (!entryDraft.current) {\n      throw new Error('addFile() can only be called while an entry is being edited');\n    }\n\n    return addFileToDraft({\n      draft: entryDraft.current,\n      fieldConfig,\n      typedKeyPath,\n      componentName,\n      locale,\n      file,\n      options,\n    });\n  };\n\n  /**\n   * Open the Select Assets dialog on behalf of the React component, so that the user can pick an\n   * existing asset, upload a file, enter a URL or choose a stock photo, the way a built-in\n   * File/Image field lets them.\n   * @param {CustomFieldPickFileOptions} [options] Options.\n   * @returns {Promise<CustomFieldPickedFile | CustomFieldPickedFile[] | null>} Picked file(s), or\n   * `null` if the dialog is dismissed.\n   * @throws {Error} When no entry is being edited.\n   */\n  const handlePickFile = async (options) => {\n    /* v8 ignore next 3 -- the picker is mounted along with the control, which can’t call earlier */\n    if (!assetPicker) {\n      throw new Error('pickFile() can only be called while an entry is being edited');\n    }\n\n    return assetPicker.pick(options);\n  };\n\n  /**\n   * React ref callback to capture the component instance. React calls this with `null` on detach.\n   * @param {any} instance The React component instance.\n   */\n  const handleRef = (instance) => {\n    const previousInstance = componentInstance;\n\n    componentInstance = instance;\n\n    if (instance) {\n      // Register the instance for validation when it’s available\n      registerCustomFieldInstance({ ...registration, instance });\n    } else {\n      unregisterCustomFieldInstance({ ...registration, instance: previousInstance });\n    }\n  };\n\n  /**\n   * Render the React component with the current props.\n   */\n  const renderComponent = () => {\n    /* v8 ignore next 3 -- the effect below only calls this once everything is ready */\n    if (!reactRenderer.ready || !resolvedControl) {\n      return;\n    }\n\n    const props = buildControlProps({\n      fieldId,\n      fieldClassName: getInputClassName(),\n      fieldConfig,\n      currentValue,\n      draft: entryDraft.current,\n      locale,\n      onChange: handleChange,\n      addFile: handleAddFile,\n      pickFile: handlePickFile,\n      handleRef,\n    });\n\n    // Provide the state of this field to any built-in field control reused within the custom\n    // control, which is typically given an ad hoc field configuration that doesn’t describe it\n    reactRenderer.render(\n      createElement(\n        fieldStateContext.Provider,\n        { value: { locale, keyPath, required, readonly, invalid } },\n        createElement(resolvedControl, props),\n      ),\n    );\n    container?.querySelector('input')?.setAttribute('aria-invalid', String(invalid));\n  };\n\n  onMount(() => () => {\n    // Unregister the instance on unmount\n    unregisterCustomFieldInstance({ ...registration, instance: componentInstance });\n  });\n\n  // Move the registration along when the key path changes: the editor is kept when the list item\n  // it belongs to is moved, or an item before it is removed, so the instance would otherwise stay\n  // registered under the old key path, which may now belong to another item\n  $effect(() => {\n    const newRegistration = { locale, keyPath };\n\n    untrack(() => {\n      if (componentInstance) {\n        unregisterCustomFieldInstance({ ...registration, instance: componentInstance });\n        registerCustomFieldInstance({ ...newRegistration, instance: componentInstance });\n      }\n    });\n\n    registration = newRegistration;\n  });\n\n  $effect(() => {\n    // Depend on every field in the locale, so that a control showing values derived from other\n    // fields, such as dynamically generated select options, stays up to date. The values are read\n    // through a cache shared between controls when the props are built, so they have to be tracked\n    // here\n    void getValueMapSnapshot(entryDraft.current, locale, valueStoreKey);\n    // Render again once an asset the control got with `getAsset()` has a blob URL\n    void assetURLUpdates.current;\n\n    // Render the component once the container and the library are ready, and update it when\n    // currentValue changes externally (e.g., via revert or copy)\n    if (reactRenderer.ready && resolvedControl) {\n      renderComponent();\n    }\n  });\n\n  // Trigger async validation when any field in the locale changes (if the component has `isValid`\n  // method), as the method can check the value against other fields. The result is cached;\n  // `awaitCustomFieldValidations()` lets a save attempt wait for it. This is a separate effect, so\n  // that a function control exposing a new handle on every render doesn’t make the control render\n  // again and again\n  $effect(() => {\n    void getValueMapSnapshot(entryDraft.current, locale, valueStoreKey);\n\n    if (typeof componentInstance?.isValid === 'function') {\n      triggerCustomFieldValidation({ locale, keyPath, value: currentValue, fieldConfig });\n    }\n  });\n</script>\n\n<div role=\"none\" bind:this={container}></div>\n\n<AssetPicker\n  bind:this={assetPicker}\n  {fieldConfig}\n  {typedKeyPath}\n  {componentName}\n  {inEditorComponent}\n  {locale}\n/>\n","import { getImmutable } from '$lib/services/api/immutable';\nimport { getMetaDataPath } from '$lib/services/api/preview-data';\nimport { isReactComponent } from '$lib/services/api/react';\nimport { customFieldTypeRegistry } from '$lib/services/api/registries';\nimport { getFieldConfigMap, getPreviewData } from '$lib/services/contents/fields/custom/helpers';\n\n/**\n * @import { MapOf } from 'immutable';\n * @import { EntryDraft } from '$lib/types/private';\n * @import {\n * CustomField,\n * CustomFieldPreviewProps,\n * CustomFieldSummary,\n * Field,\n * FieldKeyPath,\n * } from '$lib/types/public';\n */\n\n/**\n * Get the summary component of a custom field type, which draws a collapsed List field item when\n * the List field has a single subfield of the type.\n * @param {Field | undefined} fieldConfig Configuration of the single subfield.\n * @returns {CustomFieldSummary | undefined} React component, or `undefined` if the subfield isn’t\n * of a custom field type registered with a summary component.\n */\nexport const getCustomFieldSummary = (fieldConfig) => {\n  const { widget } = fieldConfig ?? {};\n\n  return widget ? customFieldTypeRegistry.get(widget)?.summary : undefined;\n};\n\n/**\n * Build props for a custom field preview React component.\n * @param {object} args Arguments.\n * @param {string} args.locale Current locale.\n * @param {FieldKeyPath} args.keyPath Key path of the field, e.g. `authors.0.name`.\n * @param {CustomField} args.fieldConfig Field configuration.\n * @param {any} args.currentValue Current field value.\n * @param {EntryDraft | null | undefined} args.draft Draft entry state.\n * @param {any} args.preview Preview component.\n * @returns {CustomFieldPreviewProps | undefined} Props object or `undefined` if prerequisites are\n * not met.\n */\nexport const buildPreviewProps = ({\n  locale,\n  keyPath,\n  fieldConfig,\n  currentValue,\n  draft,\n  preview,\n}) => {\n  if (!isReactComponent(preview) || !draft) {\n    return undefined;\n  }\n\n  const { entryMap, getFieldArgs, fieldsMetaData, getAsset } = getPreviewData({ draft, locale });\n\n  /** @type {CustomFieldPreviewProps} */\n  return {\n    value: currentValue,\n    field: getFieldConfigMap(fieldConfig),\n    metadata: /** @type {MapOf<any>} */ (\n      fieldsMetaData.getIn(getMetaDataPath({ getFieldArgs, keyPath })) ?? getImmutable().fromJS({})\n    ),\n    getAsset,\n    entry: entryMap,\n    fieldsMetaData,\n  };\n};\n","<!--\n  @component\n  Render a custom field preview registered via `CMS.registerFieldType()`, or the summary component\n  of a custom field type for a collapsed List field item, which receives the same props.\n  @see https://decapcms.org/docs/custom-widgets/\n  @see https://sveltiacms.app/en/docs/api/field-types\n-->\n<script>\n  import { createElement } from 'react';\n\n  import { assetURLUpdates } from '$lib/services/api/asset-proxy';\n  import { fieldStateContext } from '$lib/services/api/field-state';\n  import { createReactRenderer } from '$lib/services/api/react-dom.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { buildPreviewProps } from '$lib/services/contents/fields/custom/preview';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { CustomField, CustomFieldPreview } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {CustomField} fieldConfig Field configuration.\n   * @property {any} currentValue Current field value.\n   * @property {CustomFieldPreview} preview React component for preview, or a summary component.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, keyPath, fieldConfig, currentValue, preview } = $props();\n\n  /** @type {HTMLDivElement | undefined} */\n  let container = $state();\n  /**\n   * Renderer of the preview, which is a React component receiving Immutable Maps.\n   */\n  const reactRenderer = createReactRenderer(() => container);\n\n  /**\n   * Render the React component with the current props.\n   */\n  const renderComponent = () => {\n    /* v8 ignore next 3 -- the effect below only calls this once everything is ready */\n    if (!reactRenderer.ready) {\n      return;\n    }\n\n    const props = buildPreviewProps({\n      locale,\n      keyPath,\n      fieldConfig,\n      currentValue,\n      draft: entryDraft.current,\n      preview,\n    });\n\n    if (props) {\n      // Provide the state of this field to any built-in field preview reused within the custom\n      // preview, which is typically given an ad hoc field configuration that doesn’t describe it\n      reactRenderer.render(\n        createElement(\n          fieldStateContext.Provider,\n          { value: { locale, keyPath } },\n          createElement(preview, props),\n        ),\n      );\n    }\n  };\n\n  $effect(() => {\n    // A custom preview receives `entry` and `fieldsMetaData` and may render values from any field,\n    // so this depends on the whole content of the locale. The expensive part is shared between\n    // previews via a cache, which is why the values are not read through it and have to be tracked\n    // here. The re-render stays cheap.\n    void getValueMapSnapshot(entryDraft.current, locale);\n    // Render again once an asset the preview got with `getAsset()` has a blob URL\n    void assetURLUpdates.current;\n\n    // Render the preview once the container and the library are ready, then keep it up to date\n    if (reactRenderer.ready) {\n      renderComponent();\n    }\n  });\n</script>\n\n<div bind:this={container}></div>\n\n<style>\n  div {\n    /* Allow the React component to use the full width, but let it shrink beside a list item\n      thumbnail rather than overflow */\n    width: 100%;\n    min-width: 0;\n  }\n</style>\n","<!--\n  @component\n  Implement the preview for a DateTime field.\n  @see https://decapcms.org/docs/widgets/#Datetime\n  @see https://sveltiacms.app/en/docs/fields/datetime\n-->\n<script>\n  import { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\n  import { getDateTimeFieldDisplayValue } from '$lib/services/contents/fields/date-time/display';\n  import { getDate } from '$lib/services/contents/fields/date-time/parse';\n  import { getTimeZoneLabel } from '$lib/services/contents/fields/date-time/timezone';\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { DateTimeField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {DateTimeField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, fieldConfig, currentValue } = $props();\n\n  const { utc, singleCustomTimeZone } = $derived(parseDateTimeConfig(fieldConfig));\n  const displayValue = $derived(\n    getDateTimeFieldDisplayValue({ locale, fieldConfig, currentValue }),\n  );\n</script>\n\n{#if displayValue}\n  <p lang={getCanonicalLocale(locale)} dir={getDirection(locale)}>\n    {displayValue}\n    {#if singleCustomTimeZone}\n      — {getTimeZoneLabel(singleCustomTimeZone, getDate(currentValue, fieldConfig, locale))}\n    {:else if utc}\n      — UTC\n    {/if}\n  </p>\n{/if}\n","<!--\n  @component\n  Implement the editor for a DateTime field.\n  @see https://decapcms.org/docs/widgets/#Datetime\n  @see https://sveltiacms.app/en/docs/fields/datetime\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, DateTimeInput } from '@sveltia/ui';\n\n  import DateTimePreview from '$lib/components/contents/details/fields/date-time/date-time-preview.svelte';\n  import { isAutoNowField } from '$lib/services/contents/fields/date-time/auto-now';\n  import { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\n  import { getDate } from '$lib/services/contents/fields/date-time/parse';\n  import {\n    getInitialTimeZone,\n    getTimeZoneLabel,\n  } from '$lib/services/contents/fields/date-time/timezone';\n  import {\n    getCurrentDateTime,\n    getCurrentValue,\n    getInputValue,\n    shouldUpdateValue,\n  } from '$lib/services/contents/fields/date-time/value';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { DateTimeField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {DateTimeField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  let inputValue = $state('');\n  let isInputFocused = $state(false);\n\n  const { type, min, max, step, dateOnly, utc, singleCustomTimeZone } = $derived(\n    parseDateTimeConfig(fieldConfig),\n  );\n  const timeZone = $derived(getInitialTimeZone(currentValue, fieldConfig));\n\n  /**\n   * Value of the input right after it was last synced with {@link currentValue}. The value is only\n   * written back once the user has changed the input from this, so a stored value the input can’t\n   * represent isn’t replaced, or erased, as soon as the editor is opened. This also keeps a\n   * read-only field’s value as it is: the input drops the seconds with its default `step`, so\n   * writing it back would truncate a value like one set by `auto_now`.\n   */\n  let syncedInputValue = '';\n\n  /**\n   * Update {@link inputValue} based on {@link currentValue}. Only update if the input is not\n   * currently focused to avoid interfering with user typing.\n   */\n  const setInputValue = () => {\n    if (isInputFocused) {\n      return;\n    }\n\n    const _inputValue = getInputValue({ currentValue, fieldConfig, timeZone, locale });\n\n    // Avoid a cycle dependency & infinite loop\n    if (_inputValue !== undefined && _inputValue !== inputValue) {\n      inputValue = _inputValue;\n    }\n\n    syncedInputValue = inputValue;\n  };\n\n  /**\n   * Update {@link currentValue} based on {@link inputValue}, if the user has changed it.\n   */\n  const setCurrentValue = () => {\n    if (inputValue === syncedInputValue) {\n      return;\n    }\n\n    // The input now reflects the value written below. While the input is focused,\n    // `setInputValue()` doesn’t run, so record it here: otherwise changing the input back to the\n    // value it had when it was focused would be ignored\n    syncedInputValue = inputValue;\n\n    const newValue = getCurrentValue({ inputValue, currentValue, fieldConfig, timeZone, locale });\n\n    // Avoid a cycle dependency & infinite loop\n    if (shouldUpdateValue({ newValue, currentValue, fieldConfig, locale })) {\n      currentValue = /** @type {string} */ (newValue);\n    }\n  };\n\n  // Keep the displayed value in sync with the stored entry value.\n  watch(\n    () => currentValue,\n    () => {\n      setInputValue();\n    },\n  );\n\n  // Only update currentValue when inputValue changes (not when timezone changes)\n  watch(\n    () => inputValue,\n    () => {\n      setCurrentValue();\n    },\n  );\n\n  /**\n   * Handle input focus event.\n   */\n  const handleFocus = () => {\n    isInputFocused = true;\n  };\n\n  /**\n   * Handle input blur event - sync values when user finishes editing.\n   */\n  const handleBlur = () => {\n    isInputFocused = false;\n    // After losing focus, ensure inputValue is synced with currentValue\n    setInputValue();\n  };\n</script>\n\n{#if readonly && isAutoNowField(fieldConfig)}\n  <!-- The value is set on save, so it’s shown as text like in the preview rather than an input.\n  The field is editable in a rich text editor component, where the option is ignored -->\n  <DateTimePreview {locale} {keyPath} {typedKeyPath} {fieldConfig} {currentValue} />\n{:else}\n  <div role=\"none\">\n    <DateTimeInput\n      {type}\n      {min}\n      {max}\n      {step}\n      bind:value={inputValue}\n      {readonly}\n      {required}\n      {invalid}\n      aria-labelledby=\"{fieldId}-label\"\n      aria-errormessage=\"{fieldId}-error\"\n      onfocus={handleFocus}\n      onblur={handleBlur}\n    />\n    {#if !readonly}\n      <Button\n        variant=\"tertiary\"\n        label={_(dateOnly ? 'today' : 'now')}\n        onclick={() => {\n          inputValue = getCurrentDateTime(fieldConfig, timeZone);\n        }}\n      />\n    {/if}\n    {#if !readonly && !required}\n      <Button\n        variant=\"tertiary\"\n        label={_('clear')}\n        disabled={!currentValue}\n        onclick={() => {\n          currentValue = '';\n        }}\n      />\n    {/if}\n  </div>\n\n  {#if singleCustomTimeZone}\n    <div role=\"none\" class=\"timezone\">\n      {getTimeZoneLabel(singleCustomTimeZone, getDate(currentValue, fieldConfig, locale))}\n    </div>\n  {:else if utc}\n    <div role=\"none\" class=\"timezone\">UTC</div>\n  {/if}\n{/if}\n\n<style>\n  div {\n    display: flex;\n    align-items: center;\n  }\n\n  .timezone {\n    margin: 4px 8px 0;\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n    white-space: nowrap;\n  }\n</style>\n","<!--\n  @component\n  A confirmation dialog shown when a file extension is about to be changed, added or removed, which\n  could make the file unusable. The caller is responsible for determining whether the confirmation\n  is needed; use `isEquivalentFileExtension()` to ignore harmless changes, such as `JPG` to `jpg`.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { ConfirmationDialog } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [open] Whether to open the dialog.\n   * @property {string} [oldExtension] Original file extension without a leading dot. Can be\n   * `undefined` if the original file name has no extension.\n   * @property {string} [newExtension] New file extension without a leading dot. Can be `undefined`\n   * if the new file name has no extension.\n   * @property {string} [okLabel] Text label displayed on the OK button.\n   * @property {(() => void) | undefined} [onOk] Function to be called when the change is confirmed.\n   * @property {(() => void) | undefined} [onCancel] Function to be called when the change is\n   * canceled.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let {\n    open = $bindable(false),\n    oldExtension = undefined,\n    newExtension = undefined,\n    okLabel = '',\n    onOk = undefined,\n    onCancel = undefined,\n    ...restProps\n  } = $props();\n\n  const type = $derived.by(() => {\n    if (!oldExtension) return 'add';\n    if (!newExtension) return 'remove';\n    return 'change';\n  });\n</script>\n\n<ConfirmationDialog\n  {...restProps}\n  bind:open\n  title={_('change_file_extension')}\n  {okLabel}\n  {onOk}\n  {onCancel}\n>\n  <p>\n    {_(`confirm_file_extension_change.${type}`, { values: { oldExtension, newExtension } })}\n  </p>\n  <p>\n    {_('file_extension_change_warning')}\n  </p>\n</ConfirmationDialog>\n\n<style>\n  p {\n    margin: 0 0 8px;\n  }\n\n  p:last-child {\n    margin: 0;\n  }\n</style>\n","<!--\n  @component\n  Show a text value as read-only, with a pencil button to edit it inline. While it’s being edited,\n  the value is in a text field with the Done and Cancel buttons: Enter applies the change, and\n  Escape cancels it without closing the entry editor.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, TextInput } from '@sveltia/ui';\n  import { tick, untrack } from 'svelte';\n\n  import { activeInlineEditors } from '$lib/services/contents/editor';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} id ID of the value, which the buttons control.\n   * @property {string} value Value to show.\n   * @property {string} [initialText] Text to start editing with. Default: the value.\n   * @property {boolean} [editing] Whether the value is being edited.\n   * @property {string} [text] Text being edited.\n   * @property {HTMLInputElement} [inputElement] Text field shown while editing.\n   * @property {boolean} [canEdit] Whether the value can be edited, which shows the pencil button.\n   * @property {string} [editLabel] Accessible label of the pencil button. Required when the value\n   * can be edited.\n   * @property {string} [placeholder] Placeholder of the text field.\n   * @property {boolean} [readonly] Whether the field is read-only.\n   * @property {boolean} [invalid] Whether the value is invalid.\n   * @property {boolean} [required] Whether the value is required.\n   * @property {boolean} [applyDisabled] Whether to disable the Done button. The Enter key still\n   * calls `onApply`, which decides what to do with the text.\n   * @property {'ltr' | 'rtl' | 'auto'} [dir] Text direction of the value.\n   * @property {string} [ariaLabelledby] ID of the element labelling the value.\n   * @property {string} [ariaErrormessage] ID of the element describing an error.\n   * @property {(text: string) => number | undefined} [getSelectionEnd] Where the initial\n   * selection ends in the text field, e.g. before a file extension. The whole text is selected by\n   * default.\n   * @property {(text: string) => boolean | void} [onApply] Called with the edited text. Editing\n   * ends unless it returns `false`, e.g. when a confirmation is needed first. Required when the\n   * value can be edited.\n   */\n\n  /** @type {Props} */\n  let {\n    id,\n    value,\n    initialText = undefined,\n    // No fallback values, so they can be bound to properties that are yet to be set, e.g. in a\n    // list of values\n    editing = $bindable(),\n    text = $bindable(),\n    inputElement = $bindable(),\n    canEdit = true,\n    editLabel = undefined,\n    placeholder = undefined,\n    readonly = true,\n    invalid = false,\n    required = false,\n    applyDisabled = false,\n    dir = 'auto',\n    ariaLabelledby = undefined,\n    ariaErrormessage = undefined,\n    getSelectionEnd = undefined,\n    onApply = undefined,\n  } = $props();\n\n  /** @type {HTMLButtonElement | undefined} */\n  let editButton = $state();\n  /** @type {HTMLElement | undefined} */\n  let valueElement = $state();\n\n  /**\n   * Start editing the value. The text field is focused, with the text selected.\n   */\n  const startEditing = async () => {\n    const initial = initialText ?? value;\n\n    text = initial;\n    editing = true;\n    await tick();\n    inputElement?.focus();\n    inputElement?.setSelectionRange(0, getSelectionEnd?.(initial) ?? initial.length);\n  };\n\n  /**\n   * End editing the value. The text field is gone then, so the focus moves to the pencil button,\n   * or to the value when it can no longer be edited, rather than being lost. Nothing is focused\n   * when the component is gone, e.g. after the applied change removed it.\n   */\n  const stopEditing = async () => {\n    editing = false;\n    await tick();\n    (editButton ?? valueElement)?.focus();\n  };\n\n  /**\n   * Apply the edited text.\n   */\n  const apply = () => {\n    // The text is set as soon as the editing starts\n    // `onApply` is given whenever the value can be edited\n    const handler = /** @type {(text: string) => boolean | void} */ (onApply);\n\n    if (handler(/** @type {string} */ (text)) !== false) {\n      stopEditing();\n    }\n  };\n\n  $effect(() => {\n    if (!editing) {\n      return undefined;\n    }\n\n    // Let the Escape key cancel the editing instead of closing the entry editor. The count is read\n    // to be updated, which must not make it a dependency, or the effect would loop\n    untrack(() => {\n      activeInlineEditors.current += 1;\n    });\n\n    return () => {\n      activeInlineEditors.current -= 1;\n    };\n  });\n</script>\n\n<div role=\"none\" class=\"editable-text\">\n  {#if editing}\n    <TextInput\n      {id}\n      dir=\"auto\"\n      flex\n      bind:value={text}\n      bind:element={inputElement}\n      {placeholder}\n      {invalid}\n      {required}\n      aria-labelledby={ariaLabelledby}\n      aria-errormessage={ariaErrormessage}\n      onkeydown={(/** @type {KeyboardEvent} */ event) => {\n        const { key, isComposing } = event;\n\n        // Ignore the Enter key while the user is typing with an IME\n        if (isComposing || !(key === 'Enter' || key === 'Escape')) {\n          return;\n        }\n\n        event.preventDefault();\n        event.stopPropagation();\n\n        if (key === 'Escape') {\n          stopEditing();\n        } else {\n          apply();\n        }\n      }}\n    />\n    <Button\n      size=\"small\"\n      iconic\n      disabled={applyDisabled}\n      aria-label={_('done')}\n      aria-controls={id}\n      onclick={() => {\n        apply();\n      }}\n    >\n      {#snippet startIcon()}\n        <Icon name=\"check\" />\n      {/snippet}\n    </Button>\n    <Button\n      size=\"small\"\n      iconic\n      aria-label={_('cancel')}\n      aria-controls={id}\n      onclick={() => {\n        stopEditing();\n      }}\n    >\n      {#snippet startIcon()}\n        <Icon name=\"close\" />\n      {/snippet}\n    </Button>\n  {:else}\n    <div\n      role=\"textbox\"\n      {id}\n      tabindex=\"0\"\n      class=\"value\"\n      bind:this={valueElement}\n      {dir}\n      aria-readonly={readonly}\n      aria-invalid={invalid}\n      aria-required={required}\n      aria-labelledby={ariaLabelledby}\n      aria-errormessage={ariaErrormessage}\n    >\n      {value}\n    </div>\n    {#if canEdit}\n      <Button\n        size=\"small\"\n        iconic\n        aria-label={editLabel}\n        aria-controls={id}\n        bind:element={editButton}\n        onclick={() => {\n          startEditing();\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"edit\" />\n        {/snippet}\n      </Button>\n    {/if}\n  {/if}\n</div>\n\n<style>\n  .editable-text {\n    display: flex;\n    align-items: center;\n    gap: 4px;\n  }\n\n  .value {\n    flex: auto;\n    margin: var(--sui-focus-ring-width);\n    padding: 4px;\n    word-break: break-all;\n\n    &:empty {\n      margin: 0;\n      padding: 0;\n    }\n  }\n</style>\n","/**\n * Helpers for reordering the items of a vertical list with drag and drop.\n *\n * A drop position is expressed as an insertion index: the dragged item will be placed *before* the\n * item at that index, so `0` means before the first item and `itemCount` means after the last one.\n * That representation has one entry per gap, which is what a drop indicator needs, and it keeps the\n * “did this drag actually move anything?” test trivial — see {@link getMoveTarget}.\n */\n\n/**\n * Get the insertion index for a pointer position over a list item. The item’s vertical midpoint\n * splits it into a “drop above” and a “drop below” half.\n * @param {object} args Arguments.\n * @param {number} args.index Index of the item under the pointer.\n * @param {number} args.clientY Vertical pointer position.\n * @param {DOMRect} args.rect Bounding rectangle of the item under the pointer.\n * @returns {number} Insertion index.\n */\nexport const getDropIndex = ({ index, clientY, rect }) =>\n  clientY < rect.top + rect.height / 2 ? index : index + 1;\n\n/**\n * Move an item within a list to another position, without touching the original.\n * @param {any[]} list Original list.\n * @param {number} from Source index.\n * @param {number} to Destination index.\n * @returns {any[]} New list.\n */\nexport const moveListItem = (list, from, to) => {\n  const result = [...list];\n\n  result.splice(to, 0, ...result.splice(from, 1));\n\n  return result;\n};\n\n/**\n * Get the destination index of a completed drag.\n * @param {object} args Arguments.\n * @param {number | undefined} args.dragIndex Index of the item being dragged.\n * @param {number | undefined} args.dropIndex Insertion index the item was dropped at.\n * @returns {number | undefined} Destination index, or `undefined` if the drop wouldn’t move the\n * item. Removing the item shifts everything after it down by one, so an insertion index past the\n * dragged item has to be decremented to become a destination index.\n */\nexport const getMoveTarget = ({ dragIndex, dropIndex }) => {\n  if (\n    dragIndex === undefined ||\n    dropIndex === undefined ||\n    dropIndex === dragIndex ||\n    dropIndex === dragIndex + 1\n  ) {\n    return undefined;\n  }\n\n  return dropIndex > dragIndex ? dropIndex - 1 : dropIndex;\n};\n\n/**\n * Get the destination index for a keyboard shortcut pressed on a drag handle. This is the\n * accessible equivalent of dragging: Arrow Up/Down move the item by one, Home/End send it to either\n * end of the list.\n * @param {object} args Arguments.\n * @param {string} args.key Pressed key.\n * @param {number} args.index Index of the item the handle belongs to.\n * @param {number} args.itemCount Total number of items in the list.\n * @returns {number | undefined} Destination index, or `undefined` if the key isn’t a reorder\n * shortcut or the item is already at the requested position.\n */\nexport const getKeyboardMoveTarget = ({ key, index, itemCount }) => {\n  if (key === 'ArrowUp' || key === 'Home') {\n    const target = key === 'ArrowUp' ? index - 1 : 0;\n\n    return index > 0 ? target : undefined;\n  }\n\n  if (key === 'ArrowDown' || key === 'End') {\n    const target = key === 'ArrowDown' ? index + 1 : itemCount - 1;\n\n    return index < itemCount - 1 ? target : undefined;\n  }\n\n  return undefined;\n};\n\n/**\n * Minimum number of items for a list to offer Move to Top, Move to Bottom and Move To. With fewer,\n * Move Up and Move Down already reach every position in a single step.\n */\nexport const MOVE_TO_EDGE_MIN_ITEMS = 3;\n\n/**\n * Check if a list has enough items to offer Move to Top, Move to Bottom and Move To.\n * @param {number} itemCount Total number of items in the list.\n * @returns {boolean} Result.\n */\nexport const canMoveToEdge = (itemCount) => itemCount >= MOVE_TO_EDGE_MIN_ITEMS;\n\n/**\n * Get the destination index for a position entered in the Move To dialog.\n * @param {object} args Arguments.\n * @param {number | undefined} args.position Entered position. Positions are 1-based, like the\n * numbers shown on the items.\n * @param {number} args.itemCount Total number of items in the list.\n * @returns {number | undefined} Zero-based destination index, or `undefined` if the position isn’t\n * a whole number between 1 and the number of items.\n */\nexport const parseMovePosition = ({ position, itemCount }) => {\n  if (position === undefined || !Number.isInteger(position)) {\n    return undefined;\n  }\n\n  return position >= 1 && position <= itemCount ? position - 1 : undefined;\n};\n\n/**\n * Find the list item that contains the given drag event target.\n *\n * The list-level drag handlers run in the capture phase so that a nested drop zone or sortable list\n * never sees a reorder drag, which means the event target can be any descendant of an item. Walking\n * up to the direct child of the list element resolves it to the item that owns it, and an item of a\n * nested list resolves to the outer item containing it.\n * @param {object} args Arguments.\n * @param {EventTarget | null} args.target Event target.\n * @param {HTMLElement | undefined} args.listElement Element whose direct children are the list\n * items.\n * @returns {{ element: HTMLElement, index: number } | undefined} The item element and its index, or\n * `undefined` if the target is outside any item of the list.\n */\nexport const getListItemAt = ({ target, listElement }) => {\n  if (\n    !listElement ||\n    !(target instanceof Element) ||\n    target === listElement ||\n    !listElement.contains(target)\n  ) {\n    return undefined;\n  }\n\n  /** @type {Element} */\n  let element = target;\n\n  // The containment check above guarantees the walk stops at the list element\n  while (element.parentElement !== listElement) {\n    element = /** @type {Element} */ (element.parentElement);\n  }\n\n  return {\n    element: /** @type {HTMLElement} */ (element),\n    index: [...listElement.children].indexOf(element),\n  };\n};\n\n/**\n * Reorder control actions to fall back on, in order, when the control that moved an item can no\n * longer be used: the Move Up and Move Down buttons, the drag handle and the reorder menu.\n */\nconst REORDER_CONTROL_ACTIONS = ['move-up', 'move-down', 'reorder', 'move-options'];\n\n/**\n * Move the focus to a reorder control on a list item. Call it once the item has been moved with\n * one of its controls, so the control can be used repeatedly without having to find it again. If\n * that control is disabled now, as the Move Up button is once the item has reached the top of the\n * list, another enabled reorder control on the item gets the focus instead, so the focus doesn’t\n * fall back to the document body.\n * @param {object} args Arguments.\n * @param {Element | null | undefined} args.item List item element.\n * @param {string} [args.action] `data-action` of the control to focus.\n */\nexport const focusItemReorderControl = ({ item, action = 'reorder' }) => {\n  [action, ...REORDER_CONTROL_ACTIONS]\n    .map(\n      (name) =>\n        /** @type {HTMLButtonElement | null | undefined} */ (\n          item?.querySelector(`button[data-action=\"${name}\"]`)\n        ),\n    )\n    .find((button) => button && !button.disabled)\n    ?.focus();\n};\n\n/**\n * Move the focus to a reorder control on the list item at the given index, as\n * {@link focusItemReorderControl} does.\n * @param {object} args Arguments.\n * @param {HTMLElement | undefined} args.listElement Element whose direct children are the list\n * items.\n * @param {number} args.index Index the item was moved to.\n * @param {string} [args.action] `data-action` of the control to focus.\n */\nexport const focusReorderControl = ({ listElement, index, action }) => {\n  focusItemReorderControl({ item: listElement?.children[index], action });\n};\n\n/**\n * Move the focus to where it belongs once a list item has been removed, as the focused control is\n * gone along with the item: the matching element on the item now at the same position, or on the\n * previous item if the last one was removed, or else the given fallback, typically the control\n * that adds an item.\n * @param {object} args Arguments.\n * @param {number} args.index Index of the removed item.\n * @param {(index: number) => HTMLElement | null | undefined} args.getTarget Function returning the\n * element to focus on the item at the given index, if there is one. It may be called with `-1`.\n * @param {() => void} [args.fallback] Function moving the focus elsewhere if no item is left.\n */\nexport const focusAfterRemoval = ({ index, getTarget, fallback }) => {\n  const target = getTarget(index) ?? getTarget(index - 1);\n\n  if (target) {\n    target.focus();\n  } else {\n    fallback?.();\n  }\n};\n\n/**\n * Distance in pixels from a scroll container’s top or bottom edge where the auto-scroll kicks in.\n */\nconst AUTO_SCROLL_THRESHOLD = 64;\n/**\n * Maximum number of pixels the auto-scroll moves per animation frame, reached at the very edge of\n * the scroll container.\n */\nconst AUTO_SCROLL_MAX_SPEED = 16;\n/**\n * State of the auto-scroll running for the current drag. There can only ever be one drag in\n * progress, so a single module-level slot is enough.\n * @type {{ container: HTMLElement, speed: number, frame: number | undefined } | undefined}\n */\nlet autoScroll = undefined;\n\n/**\n * Get the nearest scrollable ancestor of the given element — the entry editor pane, in practice.\n * @param {HTMLElement} element Element to start the search from.\n * @returns {HTMLElement | undefined} Scrollable ancestor, or `undefined` if nothing above the\n * element scrolls.\n */\nexport const getScrollContainer = (element) => {\n  let ancestor = element.parentElement;\n\n  while (ancestor) {\n    const { overflowY } = globalThis.getComputedStyle(ancestor);\n\n    if (['auto', 'scroll'].includes(overflowY) && ancestor.scrollHeight > ancestor.clientHeight) {\n      return ancestor;\n    }\n\n    ancestor = ancestor.parentElement;\n  }\n\n  return undefined;\n};\n\n/**\n * Get the number of pixels the scroll container should move per frame for the given pointer\n * position. The speed ramps up linearly from nothing at the edge of the hot zone to the maximum\n * at the container’s edge, so a slow, precise drop near the middle of the list doesn’t start\n * scrolling.\n * @param {object} args Arguments.\n * @param {number} args.clientY Vertical pointer position.\n * @param {DOMRect} args.rect Bounding rectangle of the scroll container.\n * @returns {number} Pixels per frame. Negative scrolls up, positive scrolls down, `0` doesn’t\n * scroll. A pointer dragged past the container’s edge gets the maximum speed.\n */\nexport const getAutoScrollSpeed = ({ clientY, rect }) => {\n  const distanceFromTop = clientY - rect.top;\n  const distanceFromBottom = rect.bottom - clientY;\n\n  if (distanceFromTop < AUTO_SCROLL_THRESHOLD) {\n    return -AUTO_SCROLL_MAX_SPEED * (1 - Math.max(distanceFromTop, 0) / AUTO_SCROLL_THRESHOLD);\n  }\n\n  if (distanceFromBottom < AUTO_SCROLL_THRESHOLD) {\n    return AUTO_SCROLL_MAX_SPEED * (1 - Math.max(distanceFromBottom, 0) / AUTO_SCROLL_THRESHOLD);\n  }\n\n  return 0;\n};\n\n/**\n * Scroll the container by the current speed and schedule the next frame. The loop parks itself\n * whenever there’s nothing to do — the drag ended, the pointer left the hot zone, or the container\n * reached either end — and {@link onAutoScrollDragOver} starts it again when that changes.\n */\nconst stepAutoScroll = () => {\n  // The frame queued last may outlive the drag, in which case there is nothing left to scroll\n  if (!autoScroll) {\n    return;\n  }\n\n  const { container, speed } = autoScroll;\n  const { scrollTop, scrollHeight, clientHeight } = container;\n  const nextScrollTop = Math.min(Math.max(scrollTop + speed, 0), scrollHeight - clientHeight);\n\n  if (!speed || nextScrollTop === scrollTop) {\n    autoScroll.frame = undefined;\n\n    return;\n  }\n\n  container.scrollTop = nextScrollTop;\n  autoScroll.frame = requestAnimationFrame(stepAutoScroll);\n};\n\n/**\n * Track the pointer during a drag to keep the auto-scroll speed up to date.\n * @param {DragEvent} event `dragover` event.\n */\nconst onAutoScrollDragOver = (event) => {\n  // This listener is attached for exactly as long as the state exists, so it is always set here\n  const state = /** @type {NonNullable<typeof autoScroll>} */ (autoScroll);\n\n  state.speed = getAutoScrollSpeed({\n    clientY: event.clientY,\n    rect: state.container.getBoundingClientRect(),\n  });\n\n  if (state.speed && state.frame === undefined) {\n    state.frame = requestAnimationFrame(stepAutoScroll);\n  }\n};\n\n/**\n * Start scrolling the list’s scroll container whenever the pointer is dragged near its top or\n * bottom edge, so that an item can be moved beyond the visible part of a long list. Call this from\n * `dragstart`, and {@link stopAutoScroll} from both `drop` and `dragend`.\n *\n * The pointer is tracked on the window rather than on the list, for two reasons: the list’s own\n * `dragover` handler stops the event in the capture phase, and the hot zone reaches past the ends\n * of the list, where no `dragover` of ours would fire at all. A capture-phase listener sees the\n * event before anything can stop it.\n * @param {HTMLElement | undefined} listElement Element whose direct children are the list items.\n */\nexport const startAutoScroll = (listElement) => {\n  const container = listElement ? getScrollContainer(listElement) : undefined;\n\n  if (!container) {\n    return;\n  }\n\n  autoScroll = { container, speed: 0, frame: undefined };\n  globalThis.addEventListener('dragover', onAutoScrollDragOver, true);\n};\n\n/**\n * Stop the auto-scroll started by {@link startAutoScroll}.\n */\nexport const stopAutoScroll = () => {\n  if (!autoScroll) {\n    return;\n  }\n\n  globalThis.removeEventListener('dragover', onAutoScrollDragOver, true);\n  // A frame may already be queued; dropping the state is enough to make it park the loop\n  autoScroll = undefined;\n};\n","<!--\n  @component\n  Prompt dialog asking for the position an item of a list should be moved to.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { NumberInput, PromptDialog } from '@sveltia/ui';\n\n  import { parseMovePosition } from '$lib/services/utils/drag-sorting';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [open] Whether the dialog is open.\n   * @property {number} index Index of the item to move.\n   * @property {number} itemCount Total number of items in the list.\n   * @property {(index: number) => void} onMove Called with the destination index once a valid\n   * position is confirmed.\n   */\n\n  /** @type {Props} */\n  let { open = $bindable(false), index, itemCount, onMove } = $props();\n\n  /** @type {number | undefined} */\n  let position = $state();\n  const target = $derived(parseMovePosition({ position, itemCount }));\n\n  // Every item of a list has one of these, so the dialog isn’t built until the first time it opens\n  let everOpened = $state(false);\n\n  // Start over with the current position each time the dialog opens\n  $effect(() => {\n    if (open) {\n      everOpened = true;\n      position = index + 1;\n    }\n  });\n\n  /**\n   * Move the item to the entered position, if it’s valid.\n   * @returns {boolean} Whether the item was moved.\n   */\n  const submit = () => {\n    if (target === undefined) {\n      return false;\n    }\n\n    onMove(target);\n\n    return true;\n  };\n</script>\n\n{#if everOpened}\n  <PromptDialog\n    bind:open\n    size=\"x-small\"\n    title={_('move_to')}\n    okDisabled={target === undefined}\n    onOk={() => {\n      submit();\n    }}\n  >\n    {_('move_to_description', { values: { count: itemCount } })}\n    {#snippet input()}\n      <NumberInput\n        bind:value={position}\n        flex\n        autofocus\n        min={1}\n        max={itemCount}\n        required\n        ariaLabel={_('move_to_position')}\n        onkeydown={(/** @type {KeyboardEvent} */ event) => {\n          // Submit with the Enter key, unless it’s confirming an IME conversion\n          if (event.key === 'Enter' && !event.isComposing) {\n            event.preventDefault();\n\n            if (submit()) {\n              open = false;\n            }\n          }\n        }}\n      />\n    {/snippet}\n  </PromptDialog>\n{/if}\n","<!--\n  @component\n  Render the menu items that move a list item to either end of the list, and to a position of\n  the user’s choice. The caller hosts the Move To dialog the last item opens.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { MenuItem } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} Props\n   * @property {number} index Index of the item the menu belongs to.\n   * @property {number} itemCount Total number of items in the list.\n   * @property {(index: number, action: string) => void} onMove Called with the destination index\n   * and the `data-action` of the control to restore the focus to.\n   * @property {() => void} onMoveTo Called to ask for a position.\n   */\n\n  /** @type {Props} */\n  const { index, itemCount, onMove, onMoveTo } = $props();\n</script>\n\n<MenuItem\n  label={_('move_to_top')}\n  disabled={index === 0}\n  onclick={() => onMove(0, 'move-options')}\n/>\n<MenuItem\n  label={_('move_to_bottom')}\n  disabled={index === itemCount - 1}\n  onclick={() => onMove(itemCount - 1, 'move-options')}\n/>\n<MenuItem label={_('move_to')} onclick={onMoveTo} />\n","<!--\n  @component\n  Render the control(s) used to reorder an item within a vertical list.\n\n  With a fine pointer this is a drag handle: the item can be dragged with the mouse, or moved with\n  the Arrow Up/Down and Home/End keys while the handle has focus. Only the handle starts a drag, so\n  the rest of the item stays selectable and its own controls keep working. The item element itself\n  has to be the drag source, though — that’s what gives the drag its preview image — so the handle\n  asks the list to make the item `draggable` while it’s pressed, and to make it plain again once the\n  press or the drag is over.\n\n  A touch screen gets Move Up/Down buttons instead, because HTML drag and drop is mouse-only: a\n  touch gesture never fires `dragstart`, so a handle would do nothing at all there.\n\n  Once the list has enough items, a menu next to the handle or the buttons adds Move to Top and\n  Move to Bottom and Move to…, which asks for a position in a small dialog. A\n  list that renders the handle on its own with `part=\"handle\"` leaves the menu to its buttons.\n\n  A list with room for both can render the two parts separately with `part`: the handle, shown only\n  with a fine pointer, and the buttons, shown on any device.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, Menu, MenuButton, Spacer } from '@sveltia/ui';\n\n  import MoveToDialog from '$lib/components/common/move-to-dialog.svelte';\n  import ReorderMenuItems from '$lib/components/common/reorder-menu-items.svelte';\n  import { env } from '$lib/services/user/env.svelte';\n  import { canMoveToEdge, getKeyboardMoveTarget } from '$lib/services/utils/drag-sorting';\n\n  /**\n   * @typedef {object} Props\n   * @property {number} index Index of the item the controls belong to.\n   * @property {number} itemCount Total number of items in the list.\n   * @property {boolean} [disabled] Whether to disable reordering.\n   * @property {'small' | 'medium'} [size] Button size.\n   * @property {string} [icon] Name of the icon to use for the drag handle.\n   * @property {'auto' | 'handle' | 'buttons'} [part] Which control(s) to render: `auto` renders\n   * the drag handle with a fine pointer and the Move Up/Down buttons otherwise, `handle` renders\n   * only the drag handle, and only with a fine pointer, and `buttons` renders the Move Up/Down\n   * buttons on any device, side by side without a spacer.\n   * @property {boolean} [menu] Whether to render the reorder menu once the list has enough items. A\n   * list with an options menu of its own turns it off and adds the same items to that menu.\n   * @property {() => void} [onGrab] Called when the drag handle is pressed, so the list can make\n   * the item draggable. Never called on a touch screen.\n   * @property {() => void} [onRelease] Called when the press ends without starting a drag.\n   * @property {(index: number, action: string) => void} [onMove] Called with the destination index\n   * and the `data-action` of the activated control, so the list can restore the focus to the\n   * matching control once the item has moved.\n   */\n\n  /** @type {Props} */\n  const {\n    index,\n    itemCount,\n    disabled = false,\n    size = 'small',\n    icon = 'drag_indicator',\n    part = 'auto',\n    menu = true,\n    onGrab = undefined,\n    onRelease = undefined,\n    onMove = undefined,\n  } = $props();\n\n  /**\n   * Release the grabbed item. The press can end anywhere — the pointer may be lifted outside the\n   * handle, or the gesture may be cancelled by a scroll — so the release is caught on the window\n   * rather than on the button. Calling this once a drag is already under way is harmless: the\n   * browser has taken over by then, and `draggable` only matters at the start of the gesture.\n   */\n  const release = () => {\n    globalThis.removeEventListener('pointerup', release);\n    globalThis.removeEventListener('pointercancel', release);\n    onRelease?.();\n  };\n\n  const showHandle = $derived(env.hasMouse && part !== 'buttons');\n  let moveToDialogOpen = $state(false);\n\n  const showButtons = $derived(part === 'buttons' || (part === 'auto' && !env.hasMouse));\n  const showMenu = $derived(menu && part !== 'handle' && canMoveToEdge(itemCount));\n</script>\n\n{#if showHandle}\n  <Button\n    {size}\n    {disabled}\n    iconic\n    class=\"drag-handle\"\n    data-action=\"reorder\"\n    aria-label={_('reorder_item')}\n    aria-keyshortcuts=\"ArrowUp ArrowDown Home End\"\n    onpointerdown={() => {\n      onGrab?.();\n      globalThis.addEventListener('pointerup', release);\n      globalThis.addEventListener('pointercancel', release);\n    }}\n    onkeydown={(/** @type {KeyboardEvent} */ event) => {\n      const target = getKeyboardMoveTarget({ key: event.key, index, itemCount });\n\n      if (target === undefined) {\n        return;\n      }\n\n      // Keep the arrow and Home/End keys from scrolling the editor pane\n      event.preventDefault();\n      onMove?.(target, 'reorder');\n    }}\n  >\n    {#snippet startIcon()}\n      <Icon name={icon} />\n    {/snippet}\n  </Button>\n{/if}\n{#if showButtons}\n  <Button\n    {size}\n    iconic\n    disabled={disabled || index === 0}\n    data-action=\"move-up\"\n    aria-label={_('move_up')}\n    onclick={() => onMove?.(index - 1, 'move-up')}\n  >\n    {#snippet startIcon()}\n      <Icon name=\"arrow_upward\" />\n    {/snippet}\n  </Button>\n  {#if part !== 'buttons'}\n    <Spacer />\n  {/if}\n  <Button\n    {size}\n    iconic\n    disabled={disabled || index === itemCount - 1}\n    data-action=\"move-down\"\n    aria-label={_('move_down')}\n    onclick={() => onMove?.(index + 1, 'move-down')}\n  >\n    {#snippet startIcon()}\n      <Icon name=\"arrow_downward\" />\n    {/snippet}\n  </Button>\n{/if}\n{#if showMenu}\n  <MenuButton\n    variant=\"ghost\"\n    {size}\n    iconic\n    {disabled}\n    popupPosition=\"bottom-right\"\n    data-action=\"move-options\"\n    aria-label={_('reorder_options')}\n  >\n    {#snippet popup()}\n      <Menu ariaLabel={_('reorder_options')}>\n        <ReorderMenuItems\n          {index}\n          {itemCount}\n          onMove={(to, action) => onMove?.(to, action)}\n          onMoveTo={() => {\n            moveToDialogOpen = true;\n          }}\n        />\n      </Menu>\n    {/snippet}\n  </MenuButton>\n  <MoveToDialog\n    bind:open={moveToDialogOpen}\n    {index}\n    {itemCount}\n    onMove={(to) => onMove?.(to, 'move-options')}\n  />\n{/if}\n\n<style>\n  :global(button.drag-handle:not(:disabled)) {\n    cursor: grab;\n\n    &:active {\n      cursor: grabbing;\n    }\n  }\n</style>\n","import { getMediaKind } from '$lib/services/assets/kinds';\nimport { getMediaFieldURL } from '$lib/services/assets/media-field';\n\n/**\n * @import { AssetKind, Entry, InternalLocaleCode, TypedFieldKeyPath } from '$lib/types/private';\n * @import { MediaField } from '$lib/types/public';\n */\n\n/**\n * Get the media kind and source URL to preview a File/Image field value with.\n * @param {object} args Arguments.\n * @param {string} args.value Field value. It can be an absolute path, entry-relative path, blob URL\n * or a complete/external URL.\n * @param {AssetKind} [args.kind] Media kind if it’s already known, e.g. for an Image field, so it\n * doesn’t have to be determined from the value, which is rather problematic if the path doesn’t\n * have an extension.\n * @param {Entry} [args.entry] Associated entry. Can be `undefined` when editing a new draft.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} [args.componentName] Custom editor component name for a field-level asset folder.\n * @param {MediaField} [args.fieldConfig] Field configuration.\n * @param {TypedFieldKeyPath} [args.typedKeyPath] Field key path for field-level media folders.\n * @param {boolean} [args.thumbnail] Whether to use a thumbnail of the image.\n * @param {InternalLocaleCode} [args.locale] Locale the value is referenced in, which an\n * entry-relative path is relative to. Default: the default locale.\n * @returns {Promise<{ kind: AssetKind | undefined, src: string | undefined }>} Media kind and\n * source URL. Both are `undefined` if the value is not a media file, and the URL is `undefined` if\n * the file could not be found.\n */\nexport const getMediaFieldPreview = async ({ kind, ...urlArgs }) => {\n  const mediaKind = kind ?? (await getMediaKind(urlArgs.value));\n  const src = mediaKind ? await getMediaFieldURL(urlArgs) : undefined;\n\n  return { kind: mediaKind, src };\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon } from '@sveltia/ui';\n  import { getPathInfo } from '@sveltia/utils/file';\n\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import FileExtensionChangeDialog from '$lib/components/assets/shared/file-extension-change-dialog.svelte';\n  import EditableText from '$lib/components/common/editable-text.svelte';\n  import ReorderControls from '$lib/components/common/reorder-controls.svelte';\n  import { getAssetByPath } from '$lib/services/assets';\n  import { formatFileName } from '$lib/services/assets/file-name';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    getFileDisplayPath,\n    getUnsavedFileName,\n  } from '$lib/services/contents/fields/file/helpers';\n  import { getMediaFieldPreview } from '$lib/services/contents/fields/file/preview';\n  import { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\n  import { isEquivalentFileExtension } from '$lib/services/utils/file';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { Asset, AssetKind, Entry, EntryDraft, InternalLocaleCode } from '$lib/types/private';\n   * @import { FileField, MediaField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} value The file value (URL, blob URL, or file path).\n   * @property {string} fieldId The ID of the item, which its value element is identified with.\n   * @property {string} [groupFieldId] The ID of the field the item belongs to, whose label and\n   * error message describe the item. Defaults to {@link fieldId}, which is the same for a single\n   * file.\n   * @property {MediaField} fieldConfig Field configuration.\n   * @property {boolean} readonly Whether the field is readonly.\n   * @property {boolean} invalid Whether the field is invalid.\n   * @property {boolean} required Whether the field is required.\n   * @property {string} collectionName The collection name.\n   * @property {string | undefined} fileName The file name.\n   * @property {string} [typedKeyPath] Field key path for field-level media folders.\n   * @property {string} [componentName] Custom editor component name for a field-level asset folder.\n   * @property {Entry | undefined} entry The entry object.\n   * @property {InternalLocaleCode} [locale] Locale being edited, which an entry-relative path is\n   * relative to.\n   * @property {() => void} [onReplace] Event handler for replace action.\n   * @property {() => void} [onRemove] Event handler for remove action.\n   * @property {number} [index] Index of the item within a multi-value field.\n   * @property {number} [itemCount] Total number of items in a multi-value field.\n   * @property {boolean} [dragging] Whether this item is currently being dragged.\n   * @property {() => void} [onDragStart] Event handler for the start of a reorder drag.\n   * @property {() => void} [onDragEnd] Event handler for the end of a reorder drag.\n   * @property {(index: number, action: string) => void} [onMove] Event handler for a reorder\n   * shortcut or button, called with the destination index and the `data-action` of the activated\n   * control. Reordering is only offered when this is given.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  const {\n    value,\n    fieldId,\n    groupFieldId = fieldId,\n    fieldConfig,\n    readonly = false,\n    invalid = false,\n    required = false,\n    collectionName = '',\n    fileName = undefined,\n    typedKeyPath = undefined,\n    componentName = undefined,\n    entry = undefined,\n    locale = undefined,\n    onReplace,\n    onRemove,\n    index = 0,\n    itemCount = 1,\n    dragging = false,\n    onDragStart,\n    onDragEnd,\n    onMove,\n  } = $props();\n\n  /** @type {Asset | undefined} */\n  let asset = $state();\n  /** @type {File | undefined} */\n  let file = $state();\n  /** @type {AssetKind | undefined} */\n  let kind = $state();\n  /** @type {string | undefined} */\n  let src = $state();\n  /** Whether the file name is being edited. */\n  let editing = $state(false);\n  /** File name being edited. */\n  let newName = $state('');\n  /** @type {HTMLInputElement | undefined} */\n  let inputElement = $state();\n  let showExtensionChangeDialog = $state(false);\n  /**\n   * Whether the drag handle has been pressed, making this item draggable. Only the handle starts a\n   * drag, so the file name and path stay selectable.\n   */\n  let grabbed = $state(false);\n\n  const { widget: fieldType } = $derived(fieldConfig);\n  const isImageField = $derived(fieldType === 'image');\n  /** Whether the value is a folder path, with the File field’s `select_folder` option. */\n  const isFolder = $derived(\n    fieldType === 'file' && /** @type {FileField} */ (fieldConfig).select_folder === true,\n  );\n  const sortable = $derived(!!onMove && !readonly);\n  /**\n   * Whether the file is not yet saved to the repository. An unsaved file is a pending upload cached\n   * in the draft and referenced with a temporary blob URL, so it can still be renamed.\n   */\n  const unsaved = $derived(!!file && !!value?.startsWith('blob:'));\n  const canRename = $derived(unsaved && !readonly);\n  /**\n   * Name the unsaved file will be saved with, which is filled with the current draft content if the\n   * `filename_template` media library option applies to the file.\n   */\n  const unsavedFileName = $derived(\n    file\n      ? /** @type {string} */ (\n          getUnsavedFileName({\n            draft: /** @type {EntryDraft} */ (entryDraft.current),\n            blobURL: value,\n          })\n        )\n      : undefined,\n  );\n  const oldExtension = $derived(file ? getPathInfo(file.name).extension : undefined);\n  /**\n   * Sanitized, and possibly slugified, file name to be saved, which may be different from the\n   * entered name.\n   */\n  const finalName = $derived.by(() => {\n    const name = newName.trim();\n\n    // An empty name has nothing to slugify\n    return name\n      ? formatFileName(name, {\n          slugificationEnabled: getDefaultMediaLibraryOptions({ fieldConfig }).config\n            .slugify_filename,\n        })\n      : '';\n  });\n  const newExtension = $derived(getPathInfo(finalName).extension);\n\n  const getURLArgs = $derived({\n    value,\n    entry,\n    collectionName,\n    fileName,\n    componentName,\n    typedKeyPath,\n    fieldConfig,\n    locale,\n  });\n\n  /**\n   * Path to display for the asset or file. For an unsaved file, this is the public path where the\n   * file will be stored.\n   */\n  const fileDisplayPath = $derived(\n    getFileDisplayPath({\n      draft: /** @type {EntryDraft} */ (entryDraft.current),\n      value,\n      unsavedFileName,\n    }),\n  );\n\n  /**\n   * Rename the unsaved file by replacing the cached `File` object with a new one. The blob URL,\n   * which is the current field value, remains the same, so no other references have to be updated.\n   */\n  const renameFile = () => {\n    /* v8 ignore next 3 -- the file is held in the draft as long as it’s shown here */\n    if (!file || !entryDraft.current?.files[value]) {\n      return;\n    }\n\n    const newFile = new File([file], finalName, {\n      type: file.type,\n      lastModified: file.lastModified,\n    });\n\n    entryDraft.current.files[value].file = newFile;\n    // The name is set by hand, so the file name template no longer applies\n    delete entryDraft.current.files[value].nameTemplate;\n    file = newFile;\n    editing = false;\n  };\n\n  /**\n   * Apply the entered file name. If the file extension is being changed, ask for confirmation\n   * first, because a mismatched extension could make the file unusable.\n   * @returns {boolean} Whether the editing ends, which it doesn’t while waiting for the\n   * confirmation.\n   */\n  const applyNewName = () => {\n    if (!file || !finalName || finalName === unsavedFileName) {\n      return true;\n    }\n\n    if (isEquivalentFileExtension(oldExtension, newExtension)) {\n      renameFile();\n\n      return true;\n    }\n\n    // Keep editing until the change is confirmed\n    showExtensionChangeDialog = true;\n\n    return false;\n  };\n\n  /**\n   * Update properties when value changes.\n   * @param {() => boolean} isStale Function telling whether the value has changed since, so the\n   * result of a slow lookup for an earlier value doesn’t replace the preview of the current one.\n   */\n  const updateProps = async (isStale) => {\n    // Restore `file` after a draft backup is restored, and drop it once the value is no longer an\n    // unsaved file, e.g. after the changes are reverted, so its name isn’t shown for another value\n    file = value?.startsWith('blob:') ? entryDraft.current?.files[value]?.file : undefined;\n\n    // Remove the preview of the previous value, so it’s not shown for another one, e.g. a saved\n    // asset or an unsaved file replaced with another unsaved file\n    asset = undefined;\n    kind = undefined;\n    src = undefined;\n\n    // A folder has no preview, nor has an empty value\n    if (isFolder || !value) {\n      return;\n    }\n\n    if (isImageField && /^https?:/.test(value)) {\n      kind = 'image';\n      src = value;\n\n      return;\n    }\n\n    // Update the `src` when an asset is selected\n    if (!value.startsWith('blob:')) {\n      asset = getAssetByPath({ ...getURLArgs });\n    }\n\n    if (!asset) {\n      // Take the arguments before waiting, as the value may have changed by then\n      const preview = await getMediaFieldPreview({ ...getURLArgs, thumbnail: true });\n\n      if (!isStale()) {\n        ({ kind, src } = preview);\n      }\n    }\n  };\n\n  watch(\n    () => value,\n    () => {\n      let stale = false;\n\n      updateProps(() => stale);\n\n      return () => {\n        stale = true;\n      };\n    },\n  );\n</script>\n\n<div\n  role=\"none\"\n  class=\"filled\"\n  class:sortable\n  class:drag-placeholder={dragging}\n  draggable={grabbed}\n  ondragstart={(/** @type {DragEvent} */ event) => {\n    onDragStart?.();\n\n    if (event.dataTransfer) {\n      event.dataTransfer.effectAllowed = 'move';\n      // Firefox doesn’t start a drag unless some data is attached to it\n      event.dataTransfer.setData('text/plain', fileDisplayPath);\n    }\n  }}\n  ondragend={() => {\n    grabbed = false;\n    onDragEnd?.();\n  }}\n>\n  {#if sortable}\n    <div role=\"none\" class=\"reorder-controls\">\n      <ReorderControls\n        {index}\n        {itemCount}\n        disabled={itemCount < 2}\n        onGrab={() => {\n          grabbed = true;\n        }}\n        onRelease={() => {\n          grabbed = false;\n        }}\n        {onMove}\n      />\n    </div>\n  {/if}\n  {#if kind && src}\n    <AssetPreview {kind} {src} variant=\"tile\" checkerboard={true} />\n  {:else if asset}\n    <AssetPreview kind={asset.kind} {asset} variant=\"tile\" checkerboard={true} />\n  {:else}\n    <span role=\"none\" class=\"preview no-thumbnail\">\n      <Icon name={isFolder ? 'folder' : 'draft'} />\n    </span>\n  {/if}\n  <div role=\"none\">\n    <div role=\"none\" class=\"path\">\n      <EditableText\n        id=\"{fieldId}-value\"\n        value={fileDisplayPath}\n        initialText={unsavedFileName}\n        bind:editing\n        bind:text={newName}\n        bind:inputElement\n        canEdit={canRename}\n        editLabel={_('rename')}\n        {readonly}\n        {invalid}\n        {required}\n        applyDisabled={!finalName}\n        dir=\"ltr\"\n        ariaLabelledby=\"{groupFieldId}-label\"\n        ariaErrormessage=\"{groupFieldId}-error\"\n        getSelectionEnd={(name) => getPathInfo(name).filename.length}\n        onApply={applyNewName}\n      />\n    </div>\n    {#if editing && finalName !== newName.trim()}\n      <div role=\"status\" class=\"note\">\n        {_('file_will_be_saved_as', { values: { name: finalName } })}\n      </div>\n    {/if}\n    <div role=\"none\">\n      {#if onReplace}\n        <Button\n          disabled={readonly}\n          variant=\"tertiary\"\n          size=\"small\"\n          label={_('replace')}\n          aria-label={_(`replace_${fieldType}`)}\n          aria-controls=\"{fieldId}-value\"\n          onclick={() => {\n            onReplace();\n          }}\n        />\n      {/if}\n      {#if onRemove}\n        <Button\n          disabled={readonly}\n          variant=\"tertiary\"\n          size=\"small\"\n          label={_('remove')}\n          aria-label={_(`remove_${fieldType}`)}\n          aria-controls=\"{fieldId}-value\"\n          onclick={() => {\n            onRemove();\n          }}\n        />\n      {/if}\n    </div>\n  </div>\n</div>\n\n<FileExtensionChangeDialog\n  bind:open={showExtensionChangeDialog}\n  {oldExtension}\n  {newExtension}\n  okLabel={_('rename')}\n  onOk={() => {\n    renameFile();\n  }}\n  onCancel={() => {\n    // Go back to the input field, keeping the entered name\n    inputElement?.focus();\n  }}\n/>\n\n<style>\n  .filled {\n    display: flex !important;\n    align-items: center;\n    position: relative;\n    gap: 12px;\n    margin: var(--sui-focus-ring-width);\n    background-color: var(--sui-primary-background-color); /* for dragging opacity */\n\n    :global {\n      .preview {\n        flex: none;\n        width: 120px !important;\n        height: 120px !important;\n        border-color: var(--sui-control-border-color) !important;\n        border-radius: var(--sui-control-medium-border-radius);\n        padding: 8px !important;\n\n        &.no-thumbnail {\n          display: flex;\n          align-items: center;\n          justify-content: center;\n          background-color: var(--sui-secondary-background-color);\n\n          .icon {\n            font-size: 64px;\n          }\n        }\n      }\n\n      .sui.button.tertiary.small {\n        margin: var(--sui-focus-ring-width);\n      }\n    }\n\n    & > div {\n      flex: auto;\n      overflow: hidden;\n\n      .note {\n        margin: 4px 0;\n        color: var(--sui-secondary-foreground-color);\n        font-size: var(--sui-font-size-small);\n      }\n\n      .path {\n        @media (width < 768px) {\n          font-size: var(--sui-font-size-small);\n        }\n      }\n    }\n\n    &.sortable {\n      gap: 0;\n      border-width: 1px;\n      border-style: solid;\n      border-color: var(--sui-control-border-color) !important;\n      border-radius: var(--sui-control-medium-border-radius);\n\n      :global {\n        .preview {\n          margin-inline-end: 12px;\n          border-radius: 0;\n          border-width: 0 1px 0 0;\n        }\n      }\n    }\n  }\n\n  .reorder-controls {\n    flex: none !important;\n    display: flex;\n    flex-direction: column;\n    justify-content: center;\n    align-items: center;\n    gap: 4px;\n    align-self: stretch;\n    width: 28px;\n    background-color: var(--sui-secondary-border-color);\n  }\n</style>\n","import { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\nimport { getInheritedI18nOption } from '$lib/services/contents/i18n/shared-values';\n\n/**\n * @import { EntryDraft, FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} FieldLocaleAccess\n * @property {boolean} canTranslate Whether the field has a value of its own in each locale.\n * @property {boolean} isDuplicated Whether the field’s value is copied from the default locale to\n * the given locale, which is another locale, so it’s shown read-only there.\n * @property {boolean} isSynced Whether the field’s value is kept the same in every locale while it\n * can be edited in the given locale, which is another locale, with the `sync` i18n strategy.\n * @property {boolean} areKeysDuplicated Whether the field’s keys are copied from the default\n * locale to the given locale, which is another locale, while the values can be edited. KeyValue\n * field only.\n * @property {boolean} isShown Whether the field is shown in the given locale.\n */\n\n/**\n * Work out how the given field can be edited or previewed in the given locale, according to its\n * `i18n` option. A field without an option of its own is duplicated along with an ancestor using\n * the `duplicate` strategy, so it’s shown read-only in the other locales like the ancestor, rather\n * than leaving an empty List item or Object field there. The same goes for the `sync` strategy,\n * except that the field can be edited there. A rich text editor component’s subfield isn’t part of\n * the entry’s fields, so it only has its own option.\n * @param {object} args Arguments.\n * @param {EntryDraft | null | undefined} args.draft Entry draft.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {InternalLocaleCode} args.locale Locale of the pane.\n * @param {FlattenedEntryContent} args.valueMap Values in the locale.\n * @param {boolean} [args.inEditorComponent] Whether the field is a subfield of a rich text editor\n * component, which is always shown.\n * @returns {FieldLocaleAccess} Result.\n */\nexport const getFieldLocaleAccess = ({\n  draft,\n  fieldConfig,\n  keyPath,\n  locale,\n  valueMap,\n  inEditorComponent = false,\n}) => {\n  const { i18n = false } = fieldConfig;\n  const { i18nEnabled, defaultLocale } = getDraftI18nConfig(draft);\n  const inOtherLocale = i18nEnabled && locale !== defaultLocale;\n  const canTranslate = i18nEnabled && isFieldTranslatable(i18n);\n  // Another locale only comes with i18n, which comes with the draft\n  const _draft = /** @type {EntryDraft} */ (draft);\n\n  // The default locale doesn’t follow itself, so the ancestors are only looked up for the others\n  const inheritedI18n = !inOtherLocale\n    ? undefined\n    : inEditorComponent\n      ? i18n\n      : getInheritedI18nOption({\n          fieldConfig,\n          getFieldArgs: {\n            collectionName: _draft.collectionName,\n            fileName: _draft.fileName,\n            isIndexFile: _draft.isIndexFile,\n            keyPath,\n            valueMap,\n          },\n        });\n\n  const isDuplicated = inheritedI18n === 'duplicate';\n  // A rich text editor component’s values live in the document of each locale, so they can’t be\n  // kept in sync, and a subfield using the `sync` strategy works like a translatable one there\n  const isSynced = !inEditorComponent && inheritedI18n === 'sync';\n  const areKeysDuplicated = inOtherLocale && i18n === 'duplicate_keys';\n\n  return {\n    canTranslate,\n    isDuplicated,\n    isSynced,\n    areKeysDuplicated,\n    isShown:\n      inEditorComponent ||\n      locale === defaultLocale ||\n      canTranslate ||\n      isDuplicated ||\n      isSynced ||\n      areKeysDuplicated,\n  };\n};\n","import { updateFieldValue } from '$lib/services/contents/draft/update';\nimport { getFieldLocaleAccess } from '$lib/services/contents/editor/locale';\nimport { RICH_TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getValueFormat } from '$lib/services/contents/fields/rich-text';\nimport { getComponentDef } from '$lib/services/contents/fields/rich-text/components/definitions';\nimport { removeStockCredits } from '$lib/services/integrations/media-libraries/stock/credit';\n\n/**\n * @import { DraftValueStoreKey, EntryDraft, InternalLocaleCode } from '$lib/types/private';\n * @import {\n * FieldKeyPath,\n * MarkdownField,\n * RichTextField,\n * RichTextValueFormat,\n * VisibleField,\n * } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} CreditTargetField\n * @property {FieldKeyPath} keyPath Key path of the field, which is its name.\n * @property {MarkdownField | RichTextField} fieldConfig Field configuration.\n * @property {RichTextValueFormat} format Format of the field value.\n */\n\n/**\n * Find the field a photo credit can be inserted into: the first top-level Markdown or RichText\n * field that takes multiple paragraphs and can be edited in the given locale. A field nested in a\n * List or Object field is left out, as there’s no telling which item the credit would belong to.\n * @param {object} args Arguments.\n * @param {EntryDraft | null | undefined} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @returns {CreditTargetField | undefined} Field, if any.\n */\nexport const getCreditTargetField = ({ draft, locale }) => {\n  if (!draft) {\n    return undefined;\n  }\n\n  const valueMap = draft.currentValues[locale] ?? {};\n\n  const fieldConfig = /** @type {MarkdownField | RichTextField | undefined} */ (\n    draft.fields.find((field) => {\n      const { name, widget = 'string' } = field;\n\n      if (!RICH_TEXT_FIELD_TYPES.includes(widget)) {\n        return false;\n      }\n\n      const { readonly, multiline } = /** @type {MarkdownField | RichTextField} */ (field);\n\n      if (readonly === true || multiline === false) {\n        return false;\n      }\n\n      const { isShown, isDuplicated } = getFieldLocaleAccess({\n        draft,\n        fieldConfig: field,\n        keyPath: name,\n        locale,\n        valueMap,\n      });\n\n      return isShown && !isDuplicated;\n    })\n  );\n\n  if (!fieldConfig) {\n    return undefined;\n  }\n\n  return { keyPath: fieldConfig.name, fieldConfig, format: getValueFormat(fieldConfig) };\n};\n\n/**\n * Split photo credits into lines, trimmed, leaving out empty ones.\n * @param {string} credit Photo credits in HTML, one per line.\n * @returns {string[]} Credits.\n */\nconst splitCredits = (credit) =>\n  credit\n    .split('\\n')\n    .map((line) => line.trim())\n    .filter(Boolean);\n\n/**\n * Escape the characters that have a meaning in Markdown inline text. `!` is escaped too, as it\n * would make a link right after it an image.\n * @param {string} text Plain text.\n * @returns {string} Escaped text.\n */\nconst escapeMarkdown = (text) => text.replace(/[\\\\`*_[\\]<>!]/g, '\\\\$&');\n\n/**\n * Convert a single photo credit from HTML to Markdown. A credit is sanitized to contain only text\n * and links, so the links become Markdown links and everything else becomes text.\n * @param {string} html Photo credit HTML, e.g. `Photo by <a href=\"…\">Name</a> on <a…>Unsplash</a>`.\n * @returns {string} Markdown.\n */\nconst convertCreditLine = (html) => {\n  const { body } = new DOMParser().parseFromString(html, 'text/html');\n\n  // The text content of an element or a text node is never `null`, only that of a document\n  return [...body.childNodes]\n    .map((node) => {\n      const text = escapeMarkdown(/** @type {string} */ (node.textContent));\n\n      if (node instanceof HTMLAnchorElement) {\n        // These would end the link early or make it read otherwise. `encodeURIComponent()` can’t be\n        // used, as it leaves the parentheses alone and encodes the rest of the URL as well\n        const href = (node.getAttribute('href') ?? '').replace(\n          /[ ()<>]/g,\n          (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,\n        );\n\n        return `[${text}](${href})`;\n      }\n\n      return text;\n    })\n    .join('')\n    .trim();\n};\n\n/**\n * Convert photo credits from HTML to Markdown.\n * @param {string} credit Photo credits in HTML, one per line.\n * @returns {string} Markdown, one paragraph per credit.\n */\nexport const convertCreditToMarkdown = (credit) =>\n  splitCredits(credit).map(convertCreditLine).filter(Boolean).join('\\n\\n');\n\n/**\n * Format photo credits for a field value in the given format.\n * @param {string} credit Photo credits in HTML, one per line.\n * @param {RichTextValueFormat} format Field value format.\n * @returns {string} Formatted credits.\n */\nexport const formatCredit = (credit, format) =>\n  format === 'html'\n    ? splitCredits(credit)\n        .map((line) => `<p>${line}</p>`)\n        .join('\\n')\n    : convertCreditToMarkdown(credit);\n\n/**\n * Append photo credits to the end of the given field’s value, as a new paragraph.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @param {CreditTargetField} args.target Field to insert the credits into.\n * @param {string} args.credit Photo credits in HTML, one per line.\n */\nexport const insertCredit = ({ draft, locale, target, credit }) => {\n  const { keyPath, fieldConfig, format } = target;\n  const formatted = formatCredit(credit, format);\n\n  if (!formatted) {\n    return;\n  }\n\n  const currentValue = draft.currentValues[locale]?.[keyPath];\n  const existing = typeof currentValue === 'string' ? currentValue.trimEnd() : '';\n\n  updateFieldValue({\n    draft,\n    valueStoreKey: 'currentValues',\n    locale,\n    keyPath,\n    i18n: fieldConfig.i18n,\n    value: existing ? `${existing}\\n\\n${formatted}` : formatted,\n  });\n};\n\n/**\n * Field types a Caption field can have to take a photo credit.\n */\nconst CAPTION_FIELD_TYPES = ['string', 'text'];\n\n/**\n * Get the key path of the Caption field of the rich text editor component a file field belongs to,\n * so a photo credit can be inserted there, e.g. `body:c12:caption` for `body:c12:src`. The built-in\n * image components have one, and so can a custom component: a String or Text field named `caption`\n * next to the file field, which can be edited.\n * @param {object} args Arguments.\n * @param {DraftValueStoreKey} args.valueStoreKey Value store key of the file field.\n * @param {string | undefined} args.componentName Name of the component the field belongs to.\n * @param {FieldKeyPath} args.keyPath Key path of the file field.\n * @returns {FieldKeyPath | undefined} Key path, or `undefined` if the field doesn’t belong to such\n * a component, or is nested in another field of the component.\n */\nexport const getCreditCaptionKeyPath = ({ valueStoreKey, componentName, keyPath }) => {\n  if (valueStoreKey !== 'extraValues' || !componentName) {\n    return undefined;\n  }\n\n  const { fields = [] } = getComponentDef(componentName) ?? {};\n\n  const { prefix, name: fieldName } =\n    keyPath.match(/^(?<prefix>.+:)(?<name>[^:.]+)$/)?.groups ?? {};\n\n  const isComponentField = fields.some(\n    ({ name, widget }) => name === fieldName && (widget === 'image' || widget === 'file'),\n  );\n\n  const hasCaptionField = fields.some(\n    (field) =>\n      field.name === 'caption' &&\n      CAPTION_FIELD_TYPES.includes(field.widget ?? 'string') &&\n      /** @type {VisibleField} */ (field).readonly !== true,\n  );\n\n  return isComponentField && hasCaptionField ? `${prefix}caption` : undefined;\n};\n\n/**\n * Add photo credits to the Caption field of a rich text editor component, found with\n * {@link getCreditCaptionKeyPath}. The credits are joined with a space, as the built-in image\n * components write the caption on a single line, and added after any caption already there. A\n * credit already in the caption is removed, as it belongs to the image the component held before.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @param {FieldKeyPath} args.keyPath Key path of the Caption field.\n * @param {string} args.credit Photo credits in HTML, one per line.\n */\nexport const insertCreditCaption = ({ draft, locale, keyPath, credit }) => {\n  const formatted = splitCredits(credit).join(' ');\n\n  if (!formatted) {\n    return;\n  }\n\n  const valueMap = draft.extraValues[locale] ?? (draft.extraValues[locale] = {});\n  const currentValue = valueMap[keyPath];\n  const existing = typeof currentValue === 'string' ? removeStockCredits(currentValue) : '';\n\n  valueMap[keyPath] = existing ? `${existing} ${formatted}` : formatted;\n};\n","<!--\n  @component\n  Show the credit of a stock photo selected in a File or Image field, which can be inserted into the\n  entry or copied.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Dialog, Menu, MenuItem, Spacer, SplitButton, TextArea } from '@sveltia/ui';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { isInEditorComponent } from '$lib/services/contents/editor/field-context';\n  import {\n    convertCreditToMarkdown,\n    getCreditCaptionKeyPath,\n    getCreditTargetField,\n    insertCredit,\n    insertCreditCaption,\n  } from '$lib/services/contents/fields/file/credit';\n  import { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n  /**\n   * @import { DraftValueStoreKey, InternalLocaleCode } from '$lib/types/private';\n   * @import { FieldKeyPath } from '$lib/types/public';\n   * @import { CreditTargetField } from '$lib/services/contents/fields/file/credit';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [open] Whether the dialog is open.\n   * @property {string} credit Photo credits in HTML, one per line.\n   * @property {InternalLocaleCode} locale Locale being edited.\n   * @property {FieldKeyPath} keyPath Key path of the File or Image field.\n   * @property {DraftValueStoreKey} valueStoreKey Value store key of the field.\n   * @property {string} [componentName] Name of the rich text editor component the field belongs\n   * to, if any.\n   */\n\n  /** @type {Props} */\n  let {\n    open = $bindable(false),\n    credit,\n    locale,\n    keyPath,\n    valueStoreKey,\n    componentName = undefined,\n  } = $props();\n\n  const entryDraft = getEntryDraftContext();\n\n  /**\n   * The Caption field of the rich text editor component the field belongs to, if any, where the\n   * credit is inserted. Looked up only while the dialog is open, as every File and Image field has\n   * the dialog.\n   */\n  const captionKeyPath = $derived(\n    open ? getCreditCaptionKeyPath({ valueStoreKey, componentName, keyPath }) : undefined,\n  );\n  /**\n   * Otherwise, the Markdown field the credit can be inserted into, looked up only while the dialog\n   * is open. Within any other component, that would be the field holding the component, which is\n   * being edited, so the credit can only be copied there.\n   */\n  const fieldTarget = $derived(\n    open && !isInEditorComponent(valueStoreKey)\n      ? getCreditTargetField({ draft: entryDraft.current, locale })\n      : undefined,\n  );\n  const canInsert = $derived(!!captionKeyPath || !!fieldTarget);\n\n  /**\n   * Close the dialog.\n   */\n  const close = () => {\n    open = false;\n  };\n\n  /**\n   * Insert the credit into the component’s caption or the Markdown field, and close the dialog.\n   */\n  const insert = () => {\n    const draft = entryDraft.current;\n    // The fields are only looked up while the dialog is open\n    const captionField = captionKeyPath;\n    const markdownField = fieldTarget;\n\n    close();\n\n    /* v8 ignore next 3 -- the dialog is closed along with the editor */\n    if (!draft) {\n      return;\n    }\n\n    if (captionField) {\n      insertCreditCaption({ draft, locale, keyPath: captionField, credit });\n    } else {\n      // The button is only shown with either target\n      insertCredit({\n        draft,\n        locale,\n        target: /** @type {CreditTargetField} */ (markdownField),\n        credit,\n      });\n    }\n  };\n\n  /**\n   * Copy the given text to the clipboard, and close the dialog.\n   * @param {string} text Text.\n   */\n  const copy = (text) => {\n    navigator.clipboard.writeText(text);\n    close();\n  };\n</script>\n\n<Dialog bind:open role=\"alertdialog\" title={_('assets_dialog.photo_credit.title')}>\n  <div role=\"none\">{_('assets_dialog.photo_credit.description')}</div>\n  <div role=\"none\">\n    <TextArea\n      dir=\"auto\"\n      flex\n      readonly\n      value={credit}\n      onclick={(event) => {\n        /** @type {HTMLTextAreaElement} */ (event.target).focus();\n        /** @type {HTMLTextAreaElement} */ (event.target).select();\n      }}\n    />\n  </div>\n  {#snippet footer()}\n    <Spacer flex />\n    {#if canInsert}\n      <Button\n        variant=\"primary\"\n        label={fieldTarget\n          ? _('assets_dialog.photo_credit.insert_to_field', {\n              values: { field: getFieldLabel({ config: fieldTarget.fieldConfig, locale }) },\n            })\n          : _('insert')}\n        onclick={insert}\n      />\n    {/if}\n    <SplitButton\n      variant={canInsert ? 'secondary' : 'primary'}\n      label={_('copy')}\n      onclick={() => {\n        copy(credit);\n      }}\n    >\n      {#snippet popup()}\n        <Menu>\n          <MenuItem\n            label={_('assets_dialog.photo_credit.copy_as_markdown')}\n            onclick={() => {\n              copy(convertCreditToMarkdown(credit));\n            }}\n          />\n        </Menu>\n      {/snippet}\n    </SplitButton>\n    <Button variant=\"secondary\" label={_('cancel')} onclick={close} />\n  {/snippet}\n</Dialog>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Button, Icon, Toast } from '@sveltia/ui';\n  import { matchesShortcuts } from '@sveltia/utils/events';\n\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} allowDrop Whether to allow dropping files.\n   * @property {boolean} invalid Whether the field is invalid.\n   * @property {boolean} readonly Whether the field is readonly.\n   * @property {boolean} processing Whether the field is processing.\n   * @property {boolean} isImageField Whether the field is an image field.\n   * @property {boolean} multiple Whether the field allows multiple files.\n   * @property {boolean} [selectFolder] Whether the field takes a folder instead of files.\n   * @property {boolean} showSelectAssetsDialog Whether to show the select assets dialog.\n   * @property {boolean} replaceMode Whether the dialog is in replace mode.\n   * @property {(file: File) => void} [onFilePaste] Callback invoked when an image is pasted from\n   * the clipboard instead of opening the asset selection dialog.\n   */\n\n  /** @type {Props} */\n  let {\n    allowDrop,\n    invalid,\n    readonly,\n    processing,\n    isImageField,\n    multiple,\n    selectFolder = false,\n    showSelectAssetsDialog = $bindable(false),\n    replaceMode = $bindable(false),\n    onFilePaste = undefined,\n  } = $props();\n\n  const toast = $state({ show: false, message: '' });\n  const disabled = $derived(readonly || processing);\n  /** @type {HTMLButtonElement | undefined} */\n  let browseButton = $state();\n\n  /**\n   * Move the focus to the Browse button, e.g. once the file it replaces has been removed.\n   */\n  export const focus = () => {\n    browseButton?.focus();\n  };\n\n  /**\n   * Handle click on the paste button. If `onFilePaste` is provided, it will attempt to read an\n   * image from the clipboard and invoke the callback with the pasted file.\n   */\n  const onPasteButtonClick = async () => {\n    /* v8 ignore next 3 -- the button is disabled, or not offered, in these cases */\n    if (disabled || !onFilePaste) {\n      return;\n    }\n\n    try {\n      const clipboardItems = await navigator.clipboard.read();\n      /** @type {string | undefined} */\n      let imageType;\n\n      const imageItem = clipboardItems.find((item) =>\n        item.types.some((type) => {\n          const isImage = type.startsWith('image/');\n\n          if (isImage) {\n            imageType = type;\n          }\n\n          return isImage;\n        }),\n      );\n\n      if (imageItem && imageType) {\n        const blob = await imageItem.getType(imageType);\n        const ext = imageType.split('/')[1].replace('+xml', '');\n        const file = new File([blob], `pasted-image-${Date.now()}.${ext}`, { type: imageType });\n\n        onFilePaste(file);\n\n        return;\n      }\n\n      Object.assign(toast, {\n        message: _('no_image_in_clipboard'),\n        show: true,\n      });\n    } catch {\n      Object.assign(toast, {\n        message: _('clipboard_access_denied'),\n        show: true,\n      });\n    }\n  };\n</script>\n\n{#snippet buttons()}\n  <div role=\"none\" class=\"buttons\">\n    <Button\n      bind:element={browseButton}\n      label={_('browse')}\n      variant=\"tertiary\"\n      size=\"small\"\n      {disabled}\n      onclick={(event) => {\n        event.stopPropagation();\n        replaceMode = false;\n        showSelectAssetsDialog = true;\n      }}\n    />\n    {#if onFilePaste}\n      <Button\n        label={_(isImageField ? 'paste_image' : 'paste')}\n        variant=\"tertiary\"\n        size=\"small\"\n        {disabled}\n        onclick={(event) => {\n          event.stopPropagation();\n          onPasteButtonClick();\n        }}\n      />\n    {/if}\n  </div>\n{/snippet}\n\n<!-- The area is a drop target and, for mouse users, a large click target that opens the dialog.\nIt isn’t a control of its own: the buttons inside are the keyboard path, and a focusable wrapper\nwould nest them in a “button” that Enter does nothing with. The paste shortcut is handled here so it\nworks while any of the buttons has focus. -->\n<div\n  role=\"none\"\n  class=\"empty\"\n  class:invalid\n  class:processing\n  class:disabled\n  onclick={() => {\n    if (env.hasMouse && !disabled) {\n      replaceMode = false;\n      showSelectAssetsDialog = true;\n    }\n  }}\n  onkeydown={(event) => {\n    if (!disabled && matchesShortcuts(event, 'Accel+V')) {\n      event.preventDefault();\n      onPasteButtonClick();\n    }\n  }}\n>\n  <Icon name={selectFolder ? 'folder' : 'cloud_upload'} />\n  <div role=\"none\" class=\"label\">\n    {#if processing}\n      <div role=\"status\">\n        {_('processing_files', { values: { count: multiple ? 2 : 1 } })}\n      </div>\n    {:else if env.hasMouse}\n      {#if !allowDrop}\n        {_('click_to_browse')}\n      {:else if isImageField}\n        {_('drop_image_files_or', { values: { count: multiple ? 2 : 1 } })}\n      {:else}\n        {_('drop_files_or', { values: { count: multiple ? 2 : 1 } })}\n      {/if}\n      {@render buttons()}\n    {:else}\n      {@render buttons()}\n    {/if}\n  </div>\n</div>\n\n<Toast bind:show={toast.show}>\n  <Alert status=\"error\">\n    {toast.message}\n  </Alert>\n</Toast>\n\n<style>\n  .empty {\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-content: center;\n    gap: 4px;\n    height: 120px;\n    margin: var(--sui-focus-ring-width);\n    border-width: 1px;\n    border-style: solid;\n    border-color: var(--sui-button-tertiary-border-color, var(--sui-button-border-color));\n    border-radius: var(--sui-button-medium-border-radius);\n    color: var(--sui-button-tertiary-foreground-color, var(--sui-highlight-foreground-color));\n    background-color: var(\n      --sui-button-tertiary-background-color,\n      var(--sui-button-background-color)\n    );\n    font-family: var(--sui-control-font-family);\n    font-size: var(--sui-font-size-small);\n    cursor: pointer;\n    transition: all 200ms;\n\n    &:not(.disabled):hover {\n      background-color: var(\n        --sui-button-tertiary-background-color-focus,\n        var(--sui-hover-background-color)\n      );\n    }\n\n    &:not(.disabled):active {\n      background-color: var(\n        --sui-button-tertiary-background-color-active,\n        var(--sui-active-background-color)\n      );\n    }\n\n    :global(.icon) {\n      color: var(--sui-secondary-foreground-color);\n      font-size: 48px;\n    }\n\n    &.disabled {\n      pointer-events: none !important;\n\n      :global(*) {\n        opacity: 0.5;\n      }\n    }\n\n    @media (pointer: coarse) {\n      cursor: default;\n\n      &:active {\n        /* Reset the style because the element is non-interactive on touch devices */\n        background-color: var(--sui-button-background-color) !important;\n      }\n    }\n\n    &.invalid {\n      border-color: var(--sui-error-border-color);\n    }\n  }\n\n  .label {\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    flex-wrap: wrap;\n    gap: 0 4px;\n    white-space: nowrap;\n\n    :global {\n      .button {\n        margin-block: 0;\n      }\n    }\n  }\n</style>\n","import { suspendAutoDuplication } from '$lib/services/contents/draft';\nimport { forEachTargetLocale } from '$lib/services/contents/draft/update/locale';\nimport { isKeyPathWithin } from '$lib/services/contents/entry/key-paths';\nimport { getSubtree } from '$lib/services/contents/entry/subtree';\nimport { getLocalizedRelationValue } from '$lib/services/contents/fields/relation/helpers/locale';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { flattenKeys } from '$lib/services/utils/object';\n\n/**\n * @import {\n * DraftValueStoreKey,\n * EntryDraft,\n * ExpanderStateList,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Update a flatten object with new properties by adding, updating and deleting properties.\n * @param {Record<string, any>} obj Original object.\n * @param {Record<string, any>} newProps New properties.\n */\nexport const updateObject = (obj, newProps) => {\n  Object.entries(newProps).forEach(([key, value]) => {\n    if (obj[key] !== value) {\n      obj[key] = value;\n    }\n  });\n\n  Object.keys(obj).forEach((key) => {\n    if (!(key in newProps)) {\n      delete obj[key];\n    }\n  });\n};\n\n/**\n * Traverse the given object by decoding dot-notated key path.\n *\n * The object is a draft’s live content, not a snapshot of it, and the caller writes the manipulated\n * list straight back into it, so the key paths have to be read as they are right now.\n * @param {Record<string, any>} obj Original object.\n * @param {FieldKeyPath} keyPath Dot-notated field name.\n * @returns {[values: any, remainder: any]} Unflatten values and flatten remainder.\n */\nexport const getItemList = (obj, keyPath) => [\n  getSubtree(obj, keyPath, { live: true }) ?? [],\n  // Only the list itself and the key paths below it belong to the list, not a sibling whose name\n  // merely begins with the list’s, such as `tags-extra` for `tags`\n  Object.fromEntries(Object.entries(obj).filter(([k]) => !isKeyPathWithin(k, keyPath))),\n];\n\n/**\n * Move the expander states of a list’s items to follow the items once the list has been\n * manipulated. The states are flattened, so an item’s own state, e.g. `authors.1`, comes with the\n * states of the objects and lists nested in it, e.g. `authors.1.details#` or `authors.1.books.0`,\n * which all have to be renumbered along with the item.\n * @param {Record<string, boolean>} states Flattened expander states.\n * @param {FieldKeyPath} keyPath Dot-notated field name of the list.\n * @param {ExpanderStateList} expanderStateList Manipulated list.\n * @returns {Record<string, boolean>} New expander states.\n */\nexport const moveListExpanderStates = (states, keyPath, expanderStateList) => {\n  const prefix = `${keyPath}.`;\n  /** @type {Record<string, boolean>} */\n  const newStates = {};\n  /** @type {Map<number, [suffix: string, state: boolean][]>} */\n  const itemStates = new Map();\n\n  Object.entries(states).forEach(([key, state]) => {\n    // The list’s own state, e.g. `authors#`, stays as it is, as do the states of other fields\n    const [, index, suffix] = key.startsWith(prefix)\n      ? (key.slice(prefix.length).match(/^(\\d+)($|[.#].*)/) ?? [])\n      : [];\n\n    if (index === undefined) {\n      newStates[key] = state;\n    } else {\n      itemStates.set(Number(index), [...(itemStates.get(Number(index)) ?? []), [suffix, state]]);\n    }\n  });\n\n  expanderStateList.forEach((item, index) => {\n    if (typeof item === 'number') {\n      itemStates.get(item)?.forEach(([suffix, state]) => {\n        newStates[`${prefix}${index}${suffix}`] = state;\n      });\n    } else {\n      newStates[`${prefix}${index}`] = item;\n    }\n  });\n\n  return newStates;\n};\n\n/**\n * Update the value in a list field.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Target locale.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {FieldKeyPath} args.keyPath Dot-notated field name.\n * @param {(arg: { valueList: any[], expanderStateList: ExpanderStateList }) => void }\n * args.manipulate A function to manipulate the list, which takes one object argument containing the\n * value list and the expander state list, to be manipulated in the same way. The typical usage is\n * `list.splice()`.\n */\nexport const updateListField = ({\n  draft,\n  locale,\n  valueStoreKey = 'currentValues',\n  keyPath,\n  manipulate,\n}) => {\n  const { defaultLocale } = getDraftI18nConfig(draft);\n  const [valueList, valueListRemainder] = getItemList(draft[valueStoreKey][locale], keyPath);\n  const isDefaultLocale = locale === defaultLocale;\n  // Manipulation should only happen once with the default locale\n  /** @type {ExpanderStateList} */\n  const expanderStateList = isDefaultLocale ? [...Array(valueList.length).keys()] : [];\n\n  manipulate({ valueList, expanderStateList });\n\n  suspendAutoDuplication(() => {\n    updateObject(draft[valueStoreKey][locale], {\n      ...flattenKeys(valueList, keyPath),\n      ...valueListRemainder,\n    });\n\n    if (isDefaultLocale) {\n      updateObject(\n        draft.expanderStates._,\n        moveListExpanderStates(draft.expanderStates._, keyPath, expanderStateList),\n      );\n    }\n  });\n};\n\n/**\n * Update the value in a list field for every locale the update has to be written to: the given\n * locale, or every locale if the field has the `duplicate` i18n strategy. See\n * {@link forEachTargetLocale} and {@link updateListField}.\n *\n * The items of a translatable list with a subfield using the `duplicate` strategy are paired across\n * the locales by their position, so an item added, removed or moved in the default locale is added,\n * removed or moved in every other locale as well. Otherwise the remaining items would no longer\n * line up, and a duplicated value would be copied to the wrong item.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @param {Field['i18n']} args.i18n Field-level `i18n` option.\n * @param {boolean} [args.pairedItems] Whether the list’s items are paired across the locales,\n * because the list has a subfield with the `duplicate` or `duplicate_if_empty` strategy.\n * @param {Field} [args.fieldConfig] Field configuration. If given, the values of another locale are\n * localized for the manipulation, which works with the values of the locale being edited. This is\n * for a Relation field whose `value_field` option has a locale prefix, e.g. `{{locale}}/{{slug}}`,\n * so that its value is stored as `fr/foo` rather than `en/foo` in the French content.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {FieldKeyPath} args.keyPath Dot-notated field name.\n * @param {(arg: {\n * valueList: any[], expanderStateList: ExpanderStateList, locale: InternalLocaleCode\n * }) => void } args.manipulate A function to manipulate the list, which also takes the locale the\n * values are for, so that an item added to every locale can be created for each. See\n * {@link updateListField}.\n */\nexport const updateListFieldForLocales = ({\n  draft,\n  locale,\n  i18n,\n  pairedItems = false,\n  fieldConfig,\n  valueStoreKey = 'currentValues',\n  keyPath,\n  manipulate,\n}) => {\n  /**\n   * Localize the values in a list.\n   * @param {any[]} list Values.\n   * @param {InternalLocaleCode} sourceLocale Locale the values are for.\n   * @param {InternalLocaleCode} targetLocale Locale to localize the values for.\n   * @returns {any[]} Localized values.\n   */\n  const localize = (list, sourceLocale, targetLocale) =>\n    list.map((value) =>\n      getLocalizedRelationValue({\n        fieldConfig: /** @type {Field} */ (fieldConfig),\n        value,\n        sourceLocale,\n        targetLocale,\n      }),\n    );\n\n  const { defaultLocale } = getDraftI18nConfig(draft);\n\n  forEachTargetLocale(\n    {\n      valueStore: draft[valueStoreKey],\n      locale,\n      // The structure of a list with paired items is duplicated from the default locale, even\n      // though the list itself is translatable (https://github.com/sveltia/sveltia-cms/issues/1065)\n      i18n: pairedItems && locale === defaultLocale ? 'duplicate' : i18n,\n      draft,\n      keyPath,\n    },\n    (_valueMap, _locale) => {\n      updateListField({\n        draft,\n        locale: _locale,\n        valueStoreKey,\n        keyPath,\n        manipulate:\n          !fieldConfig || _locale === locale\n            ? ({ valueList, expanderStateList }) =>\n                manipulate({ valueList, expanderStateList, locale: _locale })\n            : ({ valueList, expanderStateList }) => {\n                // Manipulate the values as they would be in the locale being edited, as the\n                // manipulation compares and adds values of that locale, then localize them back\n                const sourceList = localize(valueList, _locale, locale);\n\n                manipulate({ valueList: sourceList, expanderStateList, locale });\n                valueList.splice(0, valueList.length, ...localize(sourceList, locale, _locale));\n              },\n      });\n    },\n  );\n};\n\n/**\n * Read a multi-value field out of the draft as a plain list. Our internal representation of such a\n * field is a flattened object with one numbered key per item, e.g. `images.0`, `images.1`. Just\n * like {@link getItemList}, this reads a draft’s live content, which the caller then mutates.\n * @param {Record<string, any>} values Flattened entry content.\n * @param {FieldKeyPath} keyPath Dot-notated field name.\n * @returns {any[]} Item values in list order.\n */\nconst getMultiValueList = (values, keyPath) => getSubtree(values, keyPath, { live: true }) ?? [];\n\n/**\n * Move an item of a multi-value field, such as a File or Image field with the `multiple` option\n * enabled, to another position. The reordered list is written back over the existing numbered keys,\n * which all still exist because reordering doesn’t change the item count.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Target locale.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {FieldKeyPath} args.keyPath Dot-notated field name.\n * @param {number} args.from Index of the item to move.\n * @param {number} args.to Index to move the item to.\n */\nexport const moveMultiValueItem = ({\n  draft,\n  locale,\n  valueStoreKey = 'currentValues',\n  keyPath,\n  from,\n  to,\n}) => {\n  const values = draft[valueStoreKey][locale];\n  const list = getMultiValueList(values, keyPath);\n\n  if (from === to || !(from in list) || !(to in list)) {\n    return;\n  }\n\n  list.splice(to, 0, ...list.splice(from, 1));\n\n  list.forEach((value, index) => {\n    values[`${keyPath}.${index}`] = value;\n  });\n};\n\n/**\n * Add values to a multi-value field, such as a File or Image field with the `multiple` option\n * enabled, after its existing items, or put a value in place of an existing item.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Target locale.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {FieldKeyPath} args.keyPath Dot-notated field name.\n * @param {any[]} args.newValues Values to add.\n * @param {number} [args.replaceIndex] Index of the item to replace with the first value. The other\n * values are ignored, because an item can only be replaced by one.\n * @param {number} [args.max] Maximum number of items the field takes. The values that don’t fit are\n * ignored, so dropping or picking more files than there’s room for doesn’t exceed the limit.\n */\nexport const addMultiValueItems = ({\n  draft,\n  locale,\n  valueStoreKey = 'currentValues',\n  keyPath,\n  newValues,\n  replaceIndex,\n  max = Infinity,\n}) => {\n  const values = draft[valueStoreKey][locale];\n\n  if (replaceIndex !== undefined) {\n    const [newValue] = newValues;\n\n    if (newValue !== undefined) {\n      values[`${keyPath}.${replaceIndex}`] = newValue;\n    }\n\n    return;\n  }\n\n  const { length } = getMultiValueList(values, keyPath);\n\n  newValues.slice(0, Math.max(0, max - length)).forEach((value, index) => {\n    values[`${keyPath}.${length + index}`] = value;\n  });\n};\n\n/**\n * Remove an item from a multi-value field, such as a File or Image field with the `multiple` option\n * enabled. Our internal representation of such a field is a flattened object, so the item is\n * removed by shifting the subsequent values down by one and dropping the now-unused last key.\n *\n * The draft is the single source of truth for the field editor, so nothing is returned; the editor\n * re-renders from the updated draft.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Target locale.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {FieldKeyPath} args.keyPath Dot-notated field name.\n * @param {number} args.index Index of the item to remove.\n */\nexport const removeMultiValueItem = ({\n  draft,\n  locale,\n  valueStoreKey = 'currentValues',\n  keyPath,\n  index,\n}) => {\n  const values = draft[valueStoreKey][locale];\n\n  for (let i = index; ; i += 1) {\n    const currentKey = `${keyPath}.${i}`;\n    const nextKey = `${keyPath}.${i + 1}`;\n\n    if (nextKey in values) {\n      values[currentKey] = values[nextKey];\n    } else {\n      // Assign `null` before deleting the property, so the draft proxy can revalidate the field\n      values[currentKey] = null;\n      delete values[currentKey];\n      break;\n    }\n  }\n};\n","import { tick } from 'svelte';\n\nimport {\n  focusReorderControl,\n  getDropIndex,\n  getListItemAt,\n  getMoveTarget,\n  moveListItem,\n  startAutoScroll,\n  stopAutoScroll,\n} from '$lib/services/utils/drag-sorting';\n\n/**\n * Reactive state and event handlers of a sortable list, created with {@link createDragSorter}.\n * @typedef {object} DragSorter\n * @property {number | undefined} grabbedIndex Index of the item made draggable by its handle.\n * @property {number | undefined} dragIndex Index of the item currently being dragged.\n * @property {number[]} displayOrder The order the items are rendered in.\n * @property {(index: number) => void} grab Make the item at the given index draggable.\n * @property {() => void} release Make no item draggable.\n * @property {(from: number, to: number, action?: string) => Promise<void>} move Move an item to\n * another position, and move the focus to the matching reorder control on it.\n * @property {(index: number, event?: DragEvent, data?: string) => void} onDragStart Start\n * dragging the item at the given index.\n * @property {(event: DragEvent) => void} onDragOver Handle a `dragover` event on the list.\n * @property {(event: DragEvent) => void} onDrop Handle a `drop` event on the list.\n * @property {() => void} onDragEnd End the drag.\n * @property {(index: number, options?: DragItemOptions) => DragItemProps} itemProps Get the\n * attributes and event handlers to spread on the element of the item at the given index.\n * @property {DragListProps} listProps Event handlers to spread on the list element.\n * @property {(index: number) => ReorderControlProps} reorderControlProps Get the event handlers to\n * spread on the reorder controls of the item at the given index.\n */\n\n/**\n * Event handlers of a sortable list element, attached in the capture phase. See\n * {@link createDragSorter}.\n * @typedef {object} DragListProps\n * @property {(event: DragEvent) => void} ondragovercapture `dragover` event handler.\n * @property {(event: DragEvent) => void} ondropcapture `drop` event handler.\n */\n\n/**\n * Event handlers of an item’s reorder controls, returned by {@link DragSorter.reorderControlProps}.\n * @typedef {object} ReorderControlProps\n * @property {() => void} onGrab Make the item draggable, when its drag handle is pressed.\n * @property {() => void} onRelease Make no item draggable, when the drag handle is released.\n * @property {(to: number, action?: string) => Promise<void>} onMove Move the item to another\n * position, then move the focus to the control with the given `data-action` on it.\n */\n\n/**\n * Options for {@link DragSorter.itemProps}.\n * @typedef {object} DragItemOptions\n * @property {boolean} [ownEventsOnly] Whether to ignore the drag events bubbling up from a nested\n * sortable list, which starts its own drag.\n */\n\n/**\n * Attributes and event handlers of a sortable item element, returned by\n * {@link DragSorter.itemProps}.\n * @typedef {object} DragItemProps\n * @property {boolean} draggable Whether the item can be dragged, which is only while its drag\n * handle is pressed.\n * @property {(event: DragEvent) => void} ondragstart `dragstart` event handler.\n * @property {(event: DragEvent) => void} ondragend `dragend` event handler.\n */\n\n/**\n * Create the reactive state and event handlers of a list whose items can be reordered by dragging\n * them. The list element must have the items as its direct children, rendered in `displayOrder`.\n *\n * The list-level `dragover` and `drop` handlers should be attached in the capture phase, so that a\n * drop zone or another sortable list nested in an item — a File subfield, say — never sees a\n * reorder drag and doesn’t light up as a drop target. Anything else being dragged, such as a file\n * from the desktop, is passed through untouched.\n * @param {object} args Arguments.\n * @param {() => number} args.getItemCount Function returning the number of items in the list.\n * @param {() => HTMLElement | undefined} args.getListElement Function returning the list element.\n * @param {(from: number, to: number) => void} args.onMove Function moving the item at the source\n * index to the destination index, called once an item has been dropped somewhere else or moved\n * with {@link DragSorter.move}.\n * @param {(index: number) => string} [args.getItemData] Function returning plain text describing\n * the item at the given index, to be attached to a drag started with {@link DragSorter.itemProps}.\n * @param {() => Promise<void>} [args.settle] Function waiting for the moved item to be rendered in\n * its new position, before its reorder control gets the focus. Defaults to Svelte’s `tick`.\n * @param {(element: HTMLElement) => DOMRect} [args.getItemRect] Function returning the bounding\n * rectangle of the item element under the pointer, whose vertical midpoint decides whether the\n * dragged item goes above or below it. Defaults to the element’s own rectangle; give it for an\n * element that holds more than the item itself.\n * @returns {DragSorter} Reactive state and event handlers.\n */\nexport const createDragSorter = ({\n  getItemCount,\n  getListElement,\n  onMove,\n  getItemData,\n  settle = tick,\n  getItemRect = (element) => element.getBoundingClientRect(),\n}) => {\n  /** @type {number | undefined} */\n  let grabbedIndex = $state();\n  /**\n   * The drag in progress: the index of the item being dragged, and the item indexes in the order\n   * they are displayed meanwhile. `undefined` while no drag is in progress.\n   * @type {{ index: number, previewOrder: number[] } | undefined}\n   */\n  let drag = $state.raw();\n  /**\n   * The order returned last by {@link displayOrder}. A plain variable, as it’s only a memo.\n   * @type {number[]}\n   */\n  let lastOrder = [];\n\n  const displayOrder = $derived.by(() => {\n    const itemCount = getItemCount();\n\n    const order =\n      drag?.previewOrder.length === itemCount ? drag.previewOrder : [...Array(itemCount).keys()];\n\n    // Hand back the same array while the order is the same. The item count is read from the list,\n    // which is rebuilt whenever any of its values changes, e.g. on every keystroke in an item, and\n    // a new array would make the keyed `each` block over it run again. With an `animate:`\n    // directive, that measures the position of every item, which forces a layout on each keystroke\n    if (order.length !== lastOrder.length || order.some((index, i) => index !== lastOrder[i])) {\n      lastOrder = order;\n    }\n\n    return lastOrder;\n  });\n\n  /**\n   * Reset the state, so nothing is dragged or draggable.\n   */\n  const reset = () => {\n    stopAutoScroll();\n    grabbedIndex = undefined;\n    drag = undefined;\n  };\n\n  /**\n   * Move an item to another position, and move the focus to a reorder control on it once it has\n   * moved, so the control can be used repeatedly without having to find it again.\n   * @param {number} from Source index.\n   * @param {number} to Destination index.\n   * @param {string} [action] `data-action` of the reorder control that triggered the move, so the\n   * focus can be restored to the matching control on the item.\n   */\n  const move = async (from, to, action = 'reorder') => {\n    onMove(from, to);\n    await settle();\n    focusReorderControl({ listElement: getListElement(), index: to, action });\n  };\n\n  /**\n   * Start dragging the item at the given index.\n   * @param {number} index Item index.\n   * @param {DragEvent} [event] `dragstart` event. When given, the drag is marked as a move, and\n   * the given data is attached to it, because Firefox doesn’t start a drag unless some data is\n   * attached.\n   * @param {string} [data] Plain text describing the item, to be attached to the drag.\n   */\n  const onDragStart = (index, event, data) => {\n    drag = { index, previewOrder: [...displayOrder] };\n    // Let the editor pane scroll while the pointer is dragged near its top or bottom edge, so a\n    // long list can be reordered without letting go\n    startAutoScroll(getListElement());\n\n    if (event?.dataTransfer) {\n      event.dataTransfer.effectAllowed = 'move';\n      // Firefox doesn’t start a drag unless some data is attached to it\n      event.dataTransfer.setData('text/plain', data ?? '');\n    }\n  };\n\n  /** @type {DragSorter} */\n  const sorter = {\n    /**\n     * Index of the item made draggable by a press on its drag handle. Only the handle starts a\n     * drag, so the rest of the item stays selectable and its own controls keep working.\n     * @returns {number | undefined} Index.\n     */\n    get grabbedIndex() {\n      return grabbedIndex;\n    },\n    /**\n     * Index of the item currently being dragged.\n     * @returns {number | undefined} Index.\n     */\n    get dragIndex() {\n      return drag?.index;\n    },\n    /**\n     * The order the items are rendered in. This is the identity order except during a drag, when it\n     * holds the provisional order, so the other items slide out of the way and the gap the dragged\n     * item would land in follows the pointer. A stale preview left over from a list that changed\n     * length underneath is discarded.\n     * @returns {number[]} Item indexes.\n     */\n    get displayOrder() {\n      return displayOrder;\n    },\n    /**\n     * Make the item at the given index draggable. Call it when its drag handle is pressed.\n     * @param {number} index Item index.\n     */\n    grab: (index) => {\n      grabbedIndex = index;\n    },\n    /**\n     * Make no item draggable. Call it when the drag handle is released.\n     */\n    release: () => {\n      grabbedIndex = undefined;\n    },\n    move,\n    /**\n     * Start dragging the item at the given index. Call it from the item’s `dragstart` event.\n     */\n    onDragStart,\n    /**\n     * Handle a `dragover` event on the list, moving the dragged item’s gap under the pointer.\n     * @param {DragEvent} event `dragover` event.\n     */\n    onDragOver: (event) => {\n      if (!drag) {\n        return;\n      }\n\n      event.stopPropagation();\n      // The browser rejects the drop and never fires the `drop` event unless the default is\n      // prevented\n      event.preventDefault();\n\n      if (event.dataTransfer) {\n        event.dataTransfer.dropEffect = 'move';\n      }\n\n      const item = getListItemAt({ target: event.target, listElement: getListElement() });\n\n      // Keep the current order while the pointer is over a gap between two items\n      if (!item) {\n        return;\n      }\n\n      const { index, previewOrder } = drag;\n      const from = previewOrder.indexOf(index);\n\n      const to = getMoveTarget({\n        dragIndex: from,\n        dropIndex: getDropIndex({\n          index: item.index,\n          clientY: event.clientY,\n          rect: getItemRect(item.element),\n        }),\n      });\n\n      if (to !== undefined) {\n        drag = { index, previewOrder: moveListItem(previewOrder, from, to) };\n      }\n    },\n    /**\n     * Handle a `drop` event on the list, committing the previewed order.\n     * @param {DragEvent} event `drop` event.\n     */\n    onDrop: (event) => {\n      if (!drag) {\n        return;\n      }\n\n      event.stopPropagation();\n      event.preventDefault();\n\n      const { index: from, previewOrder } = drag;\n      // Where the item ended up in the preview is where it should be committed\n      const to = previewOrder.indexOf(from);\n\n      // The committed order matches the preview, so the items don’t move again on the way out\n      reset();\n\n      if (to !== from) {\n        move(from, to);\n      }\n    },\n    /**\n     * End the drag. Call it from the item’s `dragend` event, which fires whether the item was\n     * dropped or the drag was cancelled; a cancelled drag puts every item back where it started.\n     */\n    onDragEnd: reset,\n    /**\n     * Get the event handlers to spread on the list element, which handle a drag in the capture\n     * phase.\n     * @returns {DragListProps} Event handlers.\n     */\n    get listProps() {\n      return { ondragovercapture: sorter.onDragOver, ondropcapture: sorter.onDrop };\n    },\n    /**\n     * Get the event handlers to spread on the reorder controls of the item at the given index.\n     * @param {number} index Item index.\n     * @returns {ReorderControlProps} Event handlers.\n     */\n    reorderControlProps: (index) => ({\n      /**\n       * Make the item draggable.\n       */\n      onGrab: () => {\n        grabbedIndex = index;\n      },\n      /**\n       * Make no item draggable.\n       */\n      onRelease: () => {\n        grabbedIndex = undefined;\n      },\n      /**\n       * Move the item to another position.\n       * @param {number} to Destination index.\n       * @param {string} [action] `data-action` of the reorder control that triggered the move.\n       * @returns {Promise<void>} Resolves once the focus has moved.\n       */\n      onMove: (to, action) => move(index, to, action),\n    }),\n    /**\n     * Get the attributes and event handlers to spread on the element of the item at the given\n     * index: it’s draggable while its handle is pressed, and its `dragstart` and `dragend` events\n     * start and end the drag. The `dragging` class marking the item being dragged is left to the\n     * element’s own `class:` directive, which can’t be spread.\n     * @param {number} index Item index.\n     * @param {DragItemOptions} [options] Options.\n     * @returns {DragItemProps} Attributes and event handlers.\n     */\n    itemProps: (index, { ownEventsOnly = false } = {}) => ({\n      draggable: grabbedIndex === index,\n      /**\n       * Start dragging the item.\n       * @param {DragEvent} event `dragstart` event.\n       */\n      ondragstart: (event) => {\n        if (!ownEventsOnly || event.target === event.currentTarget) {\n          onDragStart(index, event, getItemData?.(index));\n        }\n      },\n      /**\n       * End the drag.\n       * @param {DragEvent} event `dragend` event.\n       */\n      ondragend: (event) => {\n        if (!ownEventsOnly || event.target === event.currentTarget) {\n          reset();\n        }\n      },\n    }),\n  };\n\n  return sorter;\n};\n","<!--\n  @component\n  Implement the editor for the File and Image field types.\n  @see https://decapcms.org/docs/widgets/#File\n  @see https://decapcms.org/docs/widgets/#Image\n  @see https://sveltiacms.app/en/docs/fields/file\n  @see https://sveltiacms.app/en/docs/fields/image\n-->\n<script>\n  import { sleep } from '@sveltia/utils/misc';\n  import { flushSync, tick } from 'svelte';\n  import { flip } from 'svelte/animate';\n\n  import SelectAssetsDialog from '$lib/components/assets/browser/select-assets-dialog.svelte';\n  import ConflictResolutionDialog from '$lib/components/assets/shared/conflict-resolution-dialog.svelte';\n  import DropZone from '$lib/components/assets/shared/drop-zone.svelte';\n  import RejectedFilesAlertDialog from '$lib/components/assets/shared/rejected-files-alert-dialog.svelte';\n  import FileEditorItem from '$lib/components/contents/details/fields/file/file-editor-item.svelte';\n  import PhotoCreditDialog from '$lib/components/contents/details/fields/file/photo-credit-dialog.svelte';\n  import UploadButton from '$lib/components/contents/details/fields/file/upload-button.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    addMultiValueItems,\n    moveMultiValueItem,\n    removeMultiValueItem,\n  } from '$lib/services/contents/draft/update/list';\n  import {\n    getFieldEditorContext,\n    isInEditorComponent,\n  } from '$lib/services/contents/editor/field-context';\n  import { trackPendingWhile } from '$lib/services/contents/editor/pending.svelte';\n  import { checkDuplicates } from '$lib/services/contents/fields/file/duplicates.svelte';\n  import { createFolderAssetListing } from '$lib/services/contents/fields/file/listing.svelte';\n  import {\n    getDroppedFileDestination,\n    getMediaFieldAssetOptions,\n    processResources,\n    resolveSelectionResult,\n  } from '$lib/services/contents/fields/file/resources';\n  import { getAcceptedFileTypes } from '$lib/services/integrations/media-libraries/default';\n  import { isMultiple } from '$lib/services/integrations/media-libraries/multiple';\n  import { getPreferredLibraryNames } from '$lib/services/integrations/media-libraries/options';\n  import { focusAfterRemoval } from '$lib/services/utils/drag-sorting';\n  import { createDragSorter } from '$lib/services/utils/drag-sorting.svelte';\n\n  /**\n   * @import { FieldEditorProps, SelectedResource } from '$lib/types/private';\n   * @import { FileField, MediaField } from '$lib/types/public';\n   * @import { FolderAssetListingOptions } from '$lib/services/contents/fields/file/listing.svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {MediaField} fieldConfig Field configuration.\n   * @property {string | string[] | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const {\n    valueStoreKey = 'currentValues',\n    fieldContext = undefined,\n    parentComponentNames = [],\n  } = getFieldEditorContext();\n  const inEditorComponent = isInEditorComponent(valueStoreKey);\n  const componentName = parentComponentNames.at(-1);\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  let showSelectAssetsDialog = $state(false);\n  let replaceMode = $state(false);\n  let replaceIndex = $state(-1);\n  let showPhotoCreditDialog = $state(false);\n  let photoCredit = $state('');\n  /** @type {DropZone | undefined} */\n  let dropZone = $state();\n  let processing = $state(false);\n  /** @type {RejectedFilesAlertDialog | undefined} */\n  let rejectedFilesAlert = $state();\n  /** @type {File[]} */\n  let pendingFiles = $state([]);\n  /** @type {HTMLElement | undefined} */\n  let itemList = $state();\n  /** @type {UploadButton | undefined} */\n  let uploadButton = $state();\n\n  const {\n    widget: fieldType,\n    // Field type-specific options\n    max = Infinity,\n    accept,\n    choose_url: canEnterURL = true,\n  } = $derived(fieldConfig);\n  /** Whether the field takes a folder instead of a file, with the File field’s own option. */\n  const selectFolder = $derived(\n    fieldType === 'file' && /** @type {FileField} */ (fieldConfig).select_folder === true,\n  );\n  const entry = $derived(entryDraft.current?.originalEntry);\n  /* v8 ignore start -- the editor is only rendered while the draft is there */\n  const collectionName = $derived(entryDraft.current?.collectionName ?? '');\n  const fileName = $derived(entryDraft.current?.fileName);\n  const isIndexFile = $derived(entryDraft.current?.isIndexFile ?? false);\n  /* v8 ignore stop */\n  const isImageField = $derived(fieldType === 'image');\n  const kind = $derived(isImageField ? 'image' : undefined);\n  const assetOptions = $derived(\n    getMediaFieldAssetOptions({\n      collectionName,\n      fileName,\n      isIndexFile,\n      componentName,\n      typedKeyPath,\n      fieldConfig,\n    }),\n  );\n  const libraryConfig = $derived(assetOptions.libraryConfig);\n  // An image field accepts HEIC photos only if they’re converted on upload\n  const acceptedTypes = $derived(\n    getAcceptedFileTypes({\n      accept,\n      image: isImageField,\n      transformations: libraryConfig.transformations,\n    }),\n  );\n  const assetLibraryFolderMap = $derived(assetOptions.folderMap);\n  const targetFolder = $derived(assetOptions.folder);\n  // The existing files a dropped one could replace. One of another type isn’t listed: a dropped\n  // file of that type is refused, unless a transformation gives it another name\n  const assetListing = createFolderAssetListing(\n    /**\n     * Get the listing options.\n     * @returns {FolderAssetListingOptions} Options.\n     */\n    () => ({\n      draft: entryDraft.current,\n      folder: targetFolder,\n      locale,\n      kind,\n      accept: acceptedTypes,\n      slugificationEnabled: libraryConfig.slugify_filename,\n    }),\n  );\n  const multiple = $derived(isMultiple(fieldConfig));\n  const itemCount = $derived(Array.isArray(currentValue) ? currentValue.length : 0);\n  /** Whether a multiple-file field has as many files as it takes, so no more can be dropped. */\n  const isFull = $derived(multiple && itemCount >= max);\n  const maxSize = $derived(/** @type {number} */ (libraryConfig.max_file_size));\n  /**\n   * Whether a single file can be removed here. A required field can’t go without one, and within a\n   * rich text editor component or a list item it’s the component or the item that gets removed.\n   * @see https://github.com/sveltia/sveltia-cms/issues/372\n   */\n  const showRemoveButton = $derived(\n    !required &&\n      (!fieldContext ||\n        !['rich-text-editor-component', 'single-subfield-list-field'].includes(fieldContext)),\n  );\n  const itemArgs = $derived({\n    fieldConfig,\n    readonly,\n    invalid,\n    required,\n    collectionName,\n    fileName,\n    componentName,\n    typedKeyPath,\n    entry,\n    locale,\n  });\n  const enabledCloudServiceEntries = $derived(assetOptions.cloudServiceEntries);\n  /**\n   * Where dropped files go: the repository or a cloud storage service that can upload them.\n   */\n  const dropTarget = $derived(\n    getDroppedFileDestination({\n      repositoryAvailable: assetOptions.enabled && !!targetFolder,\n      cloudServiceEntries: enabledCloudServiceEntries,\n      preferredLibraryNames: getPreferredLibraryNames(fieldConfig),\n    }),\n  );\n  /**\n   * Disable the drop zone if no location can take the files, or if several can and none is marked\n   * with the `default` option, to avoid confusion about where dropped files will be stored. A\n   * folder can’t be dropped at all.\n   */\n  const allowDrop = $derived(!!dropTarget.destination && !dropTarget.ambiguous && !selectFolder);\n\n  /**\n   * Reset the current selection.\n   */\n  const resetSelection = () => {\n    dropZone?.reset();\n\n    if (!multiple) {\n      currentValue = '';\n      flushSync();\n    }\n  };\n\n  /**\n   * Remove the single file, and move the focus to the upload button that takes its place, as the\n   * focused Remove button is gone along with the file.\n   */\n  const removeSingleFile = async () => {\n    resetSelection();\n    await tick();\n    uploadButton?.focus();\n  };\n\n  /**\n   * Handle selected resources.\n   * @param {SelectedResource[]} selectedResources Selected resources.\n   */\n  const onResourcesSelect = async (selectedResources) => {\n    const draft = entryDraft.current;\n\n    // The dialog is closed along with the editor, so this is only a race with the editor closing\n    /* v8 ignore next 3 */\n    if (!draft) {\n      return;\n    }\n\n    // The editor is reused when the pane switches to another locale, so the value has to be written\n    // to the locale the files were picked in, not the one shown once they have been processed\n    const _locale = locale;\n    const _keyPath = keyPath;\n    // Save the current value so it can be restored if all resources fail validation\n    const previousValue = multiple ? undefined : currentValue;\n\n    resetSelection();\n    processing = true;\n\n    // The field must not stay in the processing state if something goes wrong along the way\n    try {\n      const resources = await processResources({\n        draft,\n        resources: selectedResources,\n        folder: targetFolder,\n        libraryConfig,\n        accept: acceptedTypes,\n        locale: _locale,\n      });\n\n      // Another entry may have been opened while the files were being processed, e.g. a large\n      // HEIC photo being converted. The value would then be written to that entry’s draft, as\n      // `<FieldEditor>` writes a single value to the current draft\n      if (entryDraft.current !== draft) {\n        return;\n      }\n\n      const { values, value, credit, rejected } = resolveSelectionResult({\n        resources,\n        multiple,\n        previousValue,\n        inEditorComponent,\n      });\n\n      if (multiple) {\n        addMultiValueItems({\n          draft,\n          locale: _locale,\n          valueStoreKey,\n          keyPath: _keyPath,\n          newValues: values,\n          replaceIndex: replaceMode ? replaceIndex : undefined,\n          max,\n        });\n      } else if (locale === _locale) {\n        currentValue = value;\n      } else {\n        // `<FieldEditor>` would write the bound value to the locale now shown, so write it to the\n        // draft directly\n        draft[valueStoreKey][_locale][_keyPath] = value;\n      }\n\n      photoCredit = credit;\n\n      if (credit) {\n        showPhotoCreditDialog = true;\n      }\n\n      rejectedFilesAlert?.report(rejected);\n    } finally {\n      processing = false;\n    }\n  };\n\n  /**\n   * Handle drop event.\n   * @param {object} detail Drop event detail.\n   * @param {File[]} detail.files Dropped files.\n   */\n  const onDrop = async ({ files }) => {\n    if (!files.length) {\n      return;\n    }\n\n    // Dropped files are added, not taken as a replacement for the file last replaced\n    replaceMode = false;\n\n    if (dropTarget.destination === 'repository') {\n      const replace = await checkDuplicates({ files, listedAssets: assetListing.listedAssets });\n\n      if (replace === undefined) {\n        // User cancelled the dialog\n        return;\n      }\n\n      onResourcesSelect(files.map((file) => ({ file, folder: targetFolder, replace })));\n    } else {\n      // Open the dialog and pass files to the cloud service panel for upload\n      pendingFiles = files;\n      showSelectAssetsDialog = true;\n    }\n  };\n\n  /**\n   * Remove an item from the list.\n   *\n   * The new list is deliberately not assigned to {@link currentValue}: `<FieldEditor>` binds the\n   * prop with a getter that recomputes it from the draft, so writing to it here would be discarded\n   * anyway. Updating the draft is what makes the list re-render.\n   * @param {number} index Index of the item to remove.\n   */\n  const removeItem = async (index) => {\n    const draft = entryDraft.current;\n\n    // The items are gone along with the draft, so this is only a race with the editor closing\n    /* v8 ignore next 3 */\n    if (!draft) {\n      return;\n    }\n\n    removeMultiValueItem({ draft, locale, valueStoreKey, keyPath, index });\n    await tick();\n\n    /**\n     * Get the Remove button of an item, which is the last of the buttons controlling its value.\n     * @param {number} _index Item index.\n     * @returns {HTMLButtonElement | undefined} Button.\n     */\n    const getRemoveButton = (_index) => {\n      const buttons = itemList?.querySelectorAll(\n        `button[aria-controls=\"${fieldId}-${_index}-value\"]`,\n      );\n\n      return /** @type {HTMLButtonElement | undefined} */ (buttons?.[buttons.length - 1]);\n    };\n\n    // The focused Remove button is gone along with the item, so move the focus to the Remove button\n    // of the item now at the same position, the previous item if the last one was removed, or the\n    // upload button if no item is left\n    focusAfterRemoval({\n      index,\n      getTarget: getRemoveButton,\n      /**\n       * Focus the upload button.\n       */\n      fallback: () => {\n        uploadButton?.focus();\n      },\n    });\n  };\n\n  /**\n   * Move an item to another position in the list.\n   * @param {number} from Source index.\n   * @param {number} to Destination index.\n   */\n  const moveItem = (from, to) => {\n    const draft = entryDraft.current;\n\n    // The items are gone along with the draft, so this is only a race with the editor closing\n    /* v8 ignore next 3 */\n    if (!draft) {\n      return;\n    }\n\n    moveMultiValueItem({ draft, locale, valueStoreKey, keyPath, from, to });\n  };\n\n  // Register the processing of the selected files as a pending update: the previous value has been\n  // cleared, and processing, e.g. converting a large HEIC photo, can take a while, so a save or a\n  // locale switch has to wait for the new value to land rather than take the field as empty or\n  // write the value to another locale. The photo credit dialog that may follow isn’t covered, as\n  // the value has landed by then\n  trackPendingWhile(() => processing);\n\n  const sorter = createDragSorter({\n    /**\n     * Get the number of items in the list.\n     * @returns {number} Item count.\n     */\n    getItemCount: () => itemCount,\n    /**\n     * Get the list element.\n     * @returns {HTMLElement | undefined} Element.\n     */\n    getListElement: () => itemList,\n    onMove: moveItem,\n    /**\n     * Wait for the moved item to be rendered in its new position.\n     * @returns {Promise<void>} Promise.\n     */\n    settle: () => sleep(50),\n  });\n</script>\n\n{#snippet uploadButtonSnippet()}\n  <UploadButton\n    bind:this={uploadButton}\n    {allowDrop}\n    {invalid}\n    {readonly}\n    {processing}\n    {isImageField}\n    {multiple}\n    {selectFolder}\n    bind:showSelectAssetsDialog\n    bind:replaceMode\n    onFilePaste={selectFolder\n      ? undefined\n      : (file) => {\n          // A pasted file is added, not taken as a replacement for the file last replaced\n          replaceMode = false;\n          onResourcesSelect([{ file, folder: targetFolder }]);\n        }}\n  />\n{/snippet}\n\n{#snippet content()}\n  {#if !!currentValue?.length && !processing}\n    {#if multiple}\n      {#if Array.isArray(currentValue)}\n        <div role=\"none\" class=\"item-list\" bind:this={itemList} {...sorter.listProps}>\n          {#each sorter.displayOrder as index (`${currentValue[index]}|${index}`)}\n            <!--\n              The wrapper is what the `flip` animation moves: `animate:` only works on an element at\n              the top level of a keyed `each` block, not on a component.\n            -->\n            <div role=\"none\" animate:flip={{ duration: 200 }}>\n              <FileEditorItem\n                {...itemArgs}\n                {index}\n                {itemCount}\n                value={currentValue[index]}\n                fieldId=\"{fieldId}-{index}\"\n                groupFieldId={fieldId}\n                dragging={sorter.dragIndex === index}\n                onReplace={() => {\n                  replaceMode = true;\n                  replaceIndex = index;\n                  showSelectAssetsDialog = true;\n                }}\n                onRemove={() => removeItem(index)}\n                onDragStart={() => sorter.onDragStart(index)}\n                onDragEnd={sorter.onDragEnd}\n                onMove={(to, action) => sorter.move(index, to, action)}\n              />\n            </div>\n          {/each}\n        </div>\n        {#if currentValue.length < max}\n          {@render uploadButtonSnippet()}\n        {/if}\n      {/if}\n    {:else if typeof currentValue === 'string' && currentValue}\n      <FileEditorItem\n        {...itemArgs}\n        value={currentValue}\n        {fieldId}\n        onReplace={() => {\n          replaceMode = true;\n          showSelectAssetsDialog = true;\n        }}\n        onRemove={showRemoveButton ? removeSingleFile : undefined}\n      />\n    {/if}\n  {:else}\n    {@render uploadButtonSnippet()}\n  {/if}\n{/snippet}\n\n{#if allowDrop}\n  <!--\n    The drop zone is disabled while an item is being reordered: a reorder drag carries no file, so\n    letting it land anywhere outside the item list would only report an unsupported file type. It’s\n    also disabled once a multiple-file field is full, like the upload button is hidden then.\n    Dropped files are not filtered by `accept` here, just like the files chosen in the file picker:\n    `processResources()` checks the format once the files have been processed, which is the only\n    point a transformation could have changed it. The attribute still narrows the file picker.\n  -->\n  <DropZone\n    bind:this={dropZone}\n    {multiple}\n    disabled={readonly || sorter.dragIndex !== undefined || isFull}\n    accept={acceptedTypes}\n    filterDroppedFiles={false}\n    {onDrop}\n  >\n    {@render content()}\n  </DropZone>\n{:else}\n  {@render content()}\n{/if}\n\n<SelectAssetsDialog\n  {kind}\n  multiple={replaceMode ? false : multiple}\n  accept={acceptedTypes}\n  {canEnterURL}\n  {selectFolder}\n  draft={entryDraft.current}\n  {locale}\n  {fieldConfig}\n  {assetLibraryFolderMap}\n  {enabledCloudServiceEntries}\n  bind:open={showSelectAssetsDialog}\n  bind:pendingFiles\n  onSelect={onResourcesSelect}\n/>\n\n<ConflictResolutionDialog />\n\n<RejectedFilesAlertDialog bind:this={rejectedFilesAlert} {maxSize} accept={acceptedTypes} />\n\n<PhotoCreditDialog\n  bind:open={showPhotoCreditDialog}\n  credit={photoCredit}\n  {locale}\n  {keyPath}\n  {valueStoreKey}\n  {componentName}\n/>\n\n<style>\n  .item-list {\n    display: flex;\n    flex-direction: column;\n    gap: 4px;\n\n    & ~ :global([role='button']) {\n      margin-top: calc(4px + var(--sui-focus-ring-width));\n    }\n  }\n</style>\n","<script>\n  import { untrack } from 'svelte';\n\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getMediaFieldPreview } from '$lib/services/contents/fields/file/preview';\n  import { watchAsync } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { AssetKind, InternalLocaleCode } from '$lib/types/private';\n   * @import { MediaField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} value Field value, either a URL or a file path.\n   * @property {MediaField} fieldConfig Field configuration.\n   * @property {string} [typedKeyPath] Field key path for field-level media folders.\n   * @property {InternalLocaleCode} [locale] Locale being previewed, which an entry-relative path is\n   * relative to.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { value, fieldConfig, typedKeyPath = undefined, locale = undefined } = $props();\n\n  /** @type {AssetKind | undefined} */\n  let kind = $state();\n  /** @type {string | undefined} */\n  let src = $state();\n\n  const { widget: fieldType } = $derived(fieldConfig);\n  const isImageField = $derived(fieldType === 'image');\n  const entry = $derived(entryDraft.current?.originalEntry);\n  /* v8 ignore start -- the preview is only rendered while the draft is there */\n  const collectionName = $derived(entryDraft.current?.collectionName ?? '');\n  /* v8 ignore stop */\n  const fileName = $derived(entryDraft.current?.fileName);\n\n  // The lookup for an earlier value can be answered after the one for a later value, which\n  // `watchAsync` takes care of\n  watchAsync(\n    () => {\n      void [value];\n\n      return untrack(async () =>\n        value\n          ? getMediaFieldPreview({\n              value,\n              // Skip the detection if it’s an Image field because we already know it’s an image\n              kind: isImageField ? 'image' : undefined,\n              entry,\n              collectionName,\n              fileName,\n              fieldConfig,\n              typedKeyPath,\n              locale,\n            })\n          : { kind: undefined, src: undefined },\n      );\n    },\n    (preview) => {\n      ({ kind, src } = preview);\n    },\n  );\n</script>\n\n{#if kind && src}\n  <p>\n    <AssetPreview {kind} {src} controls={['audio', 'video'].includes(kind)} />\n  </p>\n{:else if typeof value === 'string' && value.trim() && !value.startsWith('blob:')}\n  <p>{value}</p>\n{/if}\n","<!--\n  @component\n  Implement the preview for the File and Image field types.\n  @see https://decapcms.org/docs/widgets/#File\n  @see https://decapcms.org/docs/widgets/#Image\n  @see https://sveltiacms.app/en/docs/fields/file\n  @see https://sveltiacms.app/en/docs/fields/image\n-->\n<script>\n  import FilePreviewItem from '$lib/components/contents/details/fields/file/file-preview-item.svelte';\n  import { isMultiple } from '$lib/services/integrations/media-libraries/multiple';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { MediaField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {MediaField} fieldConfig Field configuration.\n   * @property {string | string[] | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, typedKeyPath, fieldConfig, currentValue } = $props();\n</script>\n\n{#if isMultiple(fieldConfig)}\n  {#if Array.isArray(currentValue)}\n    {#each currentValue as value, index (`${value}-${index}`)}\n      <FilePreviewItem {value} {fieldConfig} {typedKeyPath} {locale} />\n    {/each}\n  {/if}\n{:else if typeof currentValue === 'string' && currentValue}\n  <FilePreviewItem value={currentValue} {fieldConfig} {typedKeyPath} {locale} />\n{/if}\n","<script>\n  import { Icon } from '@sveltia/ui';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [id] Alert ID referenced by `aria-errormessage`.\n   * @property {'polite' | 'off'} [live] Value for `aria-live` attribute. Default is \"polite\".\n   * @property {Snippet} children Slot content.\n   */\n\n  /** @type {Props} */\n  let { id = undefined, live = 'polite', children } = $props();\n</script>\n\n<div role=\"alert\" {id} class=\"validation\" aria-live={live}>\n  <div role=\"none\">\n    <Icon name=\"error\" />\n    {@render children()}\n  </div>\n</div>\n\n<style>\n  .validation {\n    color: var(--sui-error-foreground-color) !important;\n    font-size: var(--sui-font-size-small);\n\n    div {\n      display: flex;\n      align-items: center;\n      gap: 4px;\n      margin: 4px 0 0;\n\n      :global(.icon) {\n        flex: none;\n        font-size: 16px; /* !hardcoded */\n      }\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, Menu, MenuButton, MenuItem } from '@sveltia/ui';\n\n  import { getFieldLabel, getLocalizedOption } from '$lib/services/contents/i18n/options';\n\n  /**\n   * @import { InternalLocaleCode } from '$lib/types/private';\n   * @import { FieldWithTypes, KeyValueField, ListField, ObjectField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [disabled] Whether to disable the button.\n   * @property {ListField | ObjectField | KeyValueField} fieldConfig Field configuration.\n   * @property {InternalLocaleCode} [locale] Current pane’s locale, used to localize the labels.\n   * @property {unknown[]} [items] List items or key-value pairs. `<ListEditor>` and\n   * `<KeyValueEditor>` only.\n   * @property {(args?: { type?: string }) => void} [addItem] Function to add a new item.\n   */\n\n  /** @type {Props} */\n  let {\n    disabled = false,\n    fieldConfig,\n    locale = undefined,\n    items = [],\n    addItem = () => undefined,\n  } = $props();\n\n  const { types } = $derived(/** @type {FieldWithTypes} */ (fieldConfig));\n  // A List or KeyValue field can be given a singular label and a maximum number of items\n  const multiValueField = $derived(fieldConfig.widget === 'object' ? undefined : fieldConfig);\n  const labelSingular = $derived(\n    multiValueField\n      ? getLocalizedOption({ config: multiValueField, option: 'label_singular', locale })\n      : undefined,\n  );\n  const max = $derived(multiValueField?.max ?? Infinity);\n  const label = $derived(\n    _('add_x', {\n      values: { name: labelSingular || getFieldLabel({ config: fieldConfig, locale }) },\n    }),\n  );\n  // Hide the button instead of disabling it once the list is full, as a disabled button confuses\n  // users, especially when `max` is `1`\n  const hasMaxItems = $derived(items.length >= max);\n\n  const menuId = $props.id();\n</script>\n\n{#if hasMaxItems}\n  <!-- The list is full -->\n{:else if Array.isArray(types)}\n  <MenuButton variant=\"tertiary\" size=\"small\" {label} {disabled}>\n    {#snippet startIcon()}\n      <Icon name=\"add\" />\n    {/snippet}\n    {#snippet endIcon()}{/snippet}\n    {#snippet popup()}\n      <Menu ariaLabel={_('select_list_type')}>\n        {#each types as type, index (type.name)}\n          {@const { name, description } = type}\n          {@const itemLabel = getFieldLabel({ config: type, locale })}\n          {#if description}\n            {@const descriptionId = `${menuId}-type-${index}-description`}\n            <!-- The description isn’t part of the item’s name, but describes it -->\n            <MenuItem\n              class=\"variable-type-described\"\n              aria-label={itemLabel}\n              aria-describedby={descriptionId}\n              onclick={() => addItem({ type: name })}\n            >\n              <span role=\"none\" class=\"type-label\">{itemLabel}</span>\n              <span role=\"none\" class=\"type-description\" id={descriptionId}>{description}</span>\n            </MenuItem>\n          {:else}\n            <MenuItem label={itemLabel} onclick={() => addItem({ type: name })} />\n          {/if}\n        {/each}\n      </Menu>\n    {/snippet}\n  </MenuButton>\n{:else}\n  <Button variant=\"tertiary\" size=\"small\" {label} {disabled} onclick={() => addItem()}>\n    {#snippet startIcon()}\n      <Icon name=\"add\" />\n    {/snippet}\n  </Button>\n{/if}\n\n<style>\n  :global(.sui.menuitem.variable-type-described) {\n    --sui-menuitem-height: auto;\n    --sui-menuitem-padding: 8px 16px;\n\n    :global(.content) {\n      display: flex;\n      flex-direction: column;\n      gap: 2px;\n    }\n  }\n\n  .type-description {\n    max-width: 320px;\n    white-space: normal;\n    text-align: start;\n    font-size: var(--sui-font-size-small);\n    line-height: var(--sui-line-height-compact);\n    color: var(--sui-tertiary-foreground-color);\n  }\n\n  :global(button:hover) .type-description {\n    color: inherit;\n  }\n</style>\n","import equal from 'fast-deep-equal';\n\nimport { forEachTargetLocale } from '$lib/services/contents/draft/update/locale';\nimport { syncDuplicateKeys } from '$lib/services/contents/fields/key-value/duplicate-keys';\nimport { getPairsFromContent, setPairs } from '$lib/services/contents/fields/key-value/pairs';\n\n/**\n * @import { DraftValueStoreKey, EntryDraft, InternalLocaleCode } from '$lib/types/private';\n * @import { FieldKeyPath, KeyValueField } from '$lib/types/public';\n */\n\n/**\n * Get key-value pairs from the entry draft.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {InternalLocaleCode} args.locale Current pane’s locale.\n * @returns {[string, string][]} Key-value pairs.\n */\nexport const getPairs = ({ draft, valueStoreKey = 'currentValues', keyPath, locale }) =>\n  getPairsFromContent(draft[valueStoreKey][locale] ?? {}, keyPath);\n\n/**\n * Validate the given key-value pairs.\n * @param {object} args Arguments.\n * @param {[string, string][]} args.pairs Key-value pairs.\n * @param {boolean[]} args.edited Whether each pair’s key is edited.\n * @returns {('empty' | 'duplicate' | undefined)[]} Result.\n */\nexport const validatePairs = ({ pairs, edited }) =>\n  pairs.map(([key], index, arr) => {\n    if (!key.trim() && edited[index]) {\n      return 'empty';\n    }\n\n    if (key.trim() && arr.findIndex((i) => i[0] === key) !== index) {\n      return 'duplicate';\n    }\n\n    return undefined;\n  });\n\n/**\n * Get the rows of the editor that have a key. A row whose key is still empty isn’t written to the\n * draft.\n * @param {[string, string][]} rows Key-value pairs shown in the editor.\n * @returns {[string, string][]} Pairs.\n */\nconst getKeyedRows = (rows) => rows.filter(([key]) => key.trim());\n\n/**\n * Check whether the pairs stored in the draft differ from the rows of the editor, so the rows have\n * to be replaced with them. A row whose key is still empty hasn’t been written to the draft, so it\n * doesn’t count as a difference: adding one removes the `null` placeholder from the draft, which\n * makes the editor read the stored pairs again.\n * @param {object} args Arguments.\n * @param {[string, string][]} args.rows Key-value pairs shown in the editor.\n * @param {[string, string][]} args.storedPairs Key-value pairs stored in the draft.\n * @returns {boolean} Result.\n */\nexport const haveStoredPairsChanged = ({ rows, storedPairs }) =>\n  !equal(getKeyedRows(rows), storedPairs);\n\n/**\n * Check whether the `null` placeholder has to be stored for a field without pairs. A blank row\n * isn’t stored, so the field holds nothing until a key is filled in, and the placeholder enables\n * its validation.\n * @param {object} args Arguments.\n * @param {[string, string][]} args.storedPairs Key-value pairs stored in the draft.\n * @param {unknown} args.storedValue Value stored at the field’s key path.\n * @returns {boolean} Result.\n */\nexport const shouldStorePlaceholder = ({ storedPairs, storedValue }) =>\n  !storedPairs.length && storedValue !== null;\n\n/**\n * Get the pairs to be saved to the draft after the rows of the editor have changed.\n * @param {object} args Arguments.\n * @param {[string, string][]} args.rows Key-value pairs shown in the editor.\n * @param {('empty' | 'duplicate' | undefined)[]} args.validations Validation result of each row.\n * @param {() => [string, string][]} args.getStoredPairs Function returning the pairs stored in the\n * draft, only called when no row has a key.\n * @returns {[string, string][] | undefined} Pairs, or `undefined` if nothing is to be saved: a row\n * is invalid, or a row is waiting for its key, or there are no pairs to save and none to remove.\n */\nexport const getPairsToSave = ({ rows, validations, getStoredPairs }) => {\n  if (validations.some(Boolean)) {\n    return undefined;\n  }\n\n  const keyedRows = getKeyedRows(rows);\n\n  if (keyedRows.length) {\n    // Wait until every row has a key before saving\n    return keyedRows.length === rows.length ? keyedRows : undefined;\n  }\n\n  // With no key in any row, the field holds no pairs, which only has to be saved when the last\n  // pair has just been removed, leaving a blank row that isn’t stored. A blank pair stored as the\n  // default value of a required field is left alone, so opening an entry changes nothing\n  return getStoredPairs().some(([key]) => key.trim()) ? keyedRows : undefined;\n};\n\n/**\n * Save the key-value pairs to the entry draft.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {KeyValueField} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {InternalLocaleCode} args.locale Current pane’s locale.\n * @param {[string, string][]} args.pairs Key-value pairs.\n */\nexport const savePairs = ({\n  draft,\n  valueStoreKey = 'currentValues',\n  keyPath,\n  locale,\n  fieldConfig,\n  pairs,\n}) => {\n  const { i18n } = fieldConfig;\n  const valueStore = draft[valueStoreKey];\n\n  forEachTargetLocale({ valueStore, locale, i18n, draft, keyPath }, (content) => {\n    setPairs(content, keyPath, pairs);\n\n    // Without pairs, store the placeholder the editor uses for an empty field right away rather\n    // than leaving it to the editor, so that the keys synced below take it along\n    if (!pairs.length) {\n      content[keyPath] = null;\n    }\n  });\n\n  // Keys edited in the default locale have to reach the other locales\n  if (i18n === 'duplicate_keys' && locale === draft.defaultLocale) {\n    syncDuplicateKeys({ valueStore, defaultLocale: locale, keyPath });\n  }\n};\n","import { moveListItem } from '$lib/services/utils/drag-sorting';\n\n/**\n * Reactive rows of a list editor, created with {@link createKeyedRows}.\n * @template T\n * @typedef {object} KeyedRows\n * @property {T[]} values Row values, deeply reactive, so a row can be bound to with `bind:`.\n * @property {number[]} ids Stable row identifiers, in the same order as the values.\n * @property {(index: number, value: T) => void} insert Insert a row with a new identifier.\n * @property {(index: number) => void} remove Remove a row.\n * @property {(from: number, to: number) => void} move Move a row to another position.\n * @property {(values: T[], options?: { keepIds?: boolean }) => void} replace Replace all the rows.\n */\n\n/**\n * Create the rows of a list editor, each with a stable identifier to key an `{#each}` block with,\n * so the block keeps following a row as the list is reordered rather than following its position.\n * That way the input a user is typing into keeps the focus, and a dragged row keeps its element.\n * @template T\n * @param {T[]} [initialValues] Initial row values.\n * @returns {KeyedRows<T>} Rows.\n */\nexport const createKeyedRows = (initialValues = []) => {\n  let nextId = 0;\n\n  /**\n   * Get a new row identifier.\n   * @returns {number} Identifier.\n   */\n  const getNextId = () => {\n    nextId += 1;\n\n    return nextId - 1;\n  };\n\n  /** @type {T[]} */\n  let values = $state(initialValues);\n  /** @type {number[]} */\n  let ids = $state(initialValues.map(getNextId));\n\n  return {\n    /**\n     * Row values.\n     * @returns {T[]} Values.\n     */\n    get values() {\n      return values;\n    },\n    /**\n     * Row identifiers.\n     * @returns {number[]} Identifiers.\n     */\n    get ids() {\n      return ids;\n    },\n    /**\n     * Insert a row, giving it a new identifier.\n     * @param {number} index Index to insert at.\n     * @param {T} value Row value.\n     */\n    insert: (index, value) => {\n      values.splice(index, 0, value);\n      ids.splice(index, 0, getNextId());\n    },\n    /**\n     * Remove a row.\n     * @param {number} index Row index.\n     */\n    remove: (index) => {\n      values.splice(index, 1);\n      ids.splice(index, 1);\n    },\n    /**\n     * Move a row, along with its identifier, to another position.\n     * @param {number} from Source index.\n     * @param {number} to Destination index.\n     */\n    move: (from, to) => {\n      values = moveListItem(values, from, to);\n      ids = moveListItem(ids, from, to);\n    },\n    /**\n     * Replace all the rows, giving each a new identifier.\n     * @param {T[]} newValues Row values.\n     * @param {object} [options] Options.\n     * @param {boolean} [options.keepIds] Whether to keep the existing identifiers by position\n     * instead, so the rows already rendered are reused for the new values, and only the rows\n     * beyond the current count get new identifiers.\n     */\n    replace: (newValues, { keepIds = false } = {}) => {\n      const currentIds = ids;\n\n      values = newValues;\n      ids = newValues.map((_value, index) =>\n        keepIds && index < currentIds.length ? currentIds[index] : getNextId(),\n      );\n    },\n  };\n};\n","<!--\n  @component\n  Implement the editor for a KeyValue field compatible with Static CMS.\n\n  Like a simple List field, the editor always offers a row to type into: a field without pairs shows\n  one blank row, which isn’t stored until its key is filled in.\n  @see https://staticjscms.netlify.app/docs/widget-keyvalue\n  @see https://sveltiacms.app/en/docs/fields/keyvalue\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { TextInput } from '@sveltia/ui';\n  import { tick } from 'svelte';\n  import { flip } from 'svelte/animate';\n\n  import RemoveButton from '$lib/components/common/remove-button.svelte';\n  import ReorderControls from '$lib/components/common/reorder-controls.svelte';\n  import ValidationError from '$lib/components/contents/details/editor/validation-error.svelte';\n  import AddItemButton from '$lib/components/contents/details/fields/object/add-item-button.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { deferDraftWrite } from '$lib/services/contents/draft/update/deferred';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getFieldEditorContext } from '$lib/services/contents/editor/field-context';\n  import {\n    getPairs,\n    getPairsToSave,\n    haveStoredPairsChanged,\n    savePairs,\n    shouldStorePlaceholder,\n    validatePairs,\n  } from '$lib/services/contents/fields/key-value/helpers';\n  import { getPairsFromContent } from '$lib/services/contents/fields/key-value/pairs';\n  import { getDirection } from '$lib/services/contents/i18n';\n  import { focusAfterRemoval, moveListItem } from '$lib/services/utils/drag-sorting';\n  import { createDragSorter } from '$lib/services/utils/drag-sorting.svelte';\n  import { createKeyedRows } from '$lib/services/utils/keyed-rows.svelte';\n  import { createStableDerivedState, watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { KeyValueField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {KeyValueField} fieldConfig Field configuration.\n   * @property {Record<string, string> | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const { valueStoreKey = 'currentValues' } = getFieldEditorContext();\n\n  /** @type {FieldEditorProps & Props} */\n  let { locale, keyPath, fieldId, fieldConfig, readonly = false } = $props();\n\n  const {\n    i18n = false,\n    // Field type-specific options\n    key_label: _keyLabel,\n    value_label: _valueLabel,\n    max = Infinity,\n  } = $derived(fieldConfig);\n  const keyLabel = $derived(_keyLabel || _('key_value.key'));\n  const valueLabel = $derived(_valueLabel || _('key_value.value'));\n  const defaultLocale = $derived(entryDraft.current?.defaultLocale);\n  // With the `duplicate_keys` i18n strategy, the keys are mirrored from the default locale, so they\n  // can only be edited — and pairs added or removed — there; the values are editable in any locale\n  const keysReadonly = $derived(\n    readonly || (i18n === 'duplicate_keys' && locale !== defaultLocale),\n  );\n\n  /**\n   * Key-value pairs shown in the editor, one per row.\n   */\n  const rows = createKeyedRows(/** @type {[string, string][]} */ ([]));\n  /** @type {HTMLTableRowElement[]} */\n  const rowElements = $state([]);\n  /** @type {HTMLTableSectionElement | undefined} */\n  let tableBody = $state();\n  /** @type {boolean[]} */\n  let edited = $state([]);\n  /**\n   * Validation results of the {@link rows}, one per row.\n   * @type {('empty' | 'duplicate' | undefined)[]}\n   */\n  const validations = $derived(validatePairs({ pairs: rows.values, edited }));\n\n  // Removing the blank row offered for an empty field would just bring it back\n  const isOnlyBlankRow = $derived(\n    rows.values.length === 1 && !rows.values[0][0] && !rows.values[0][1],\n  );\n\n  /**\n   * Add a blank row if there are no pairs, so there’s always somewhere to type, unless the keys\n   * can’t be edited, in which case there’s nothing to type into.\n   */\n  const ensureBlankRow = () => {\n    if (!rows.values.length && !keysReadonly) {\n      rows.insert(rows.values.length, ['', '']);\n      edited.push(false);\n    }\n  };\n\n  /**\n   * Update the {@link rows} whenever the current values are changed.\n   */\n  const updatePairs = () => {\n    const draft = entryDraft.current;\n\n    /* v8 ignore next 3 -- the editor is only rendered while the draft is there */\n    if (!draft) {\n      return;\n    }\n\n    const updatedPairs = getPairs({ draft, valueStoreKey, keyPath, locale });\n    const valueStore = draft[valueStoreKey][locale];\n\n    if (haveStoredPairsChanged({ rows: rows.values, storedPairs: updatedPairs })) {\n      // Preserve existing IDs for unchanged positions; assign new IDs for new pairs\n      rows.replace([...updatedPairs], { keepIds: true });\n      edited = updatedPairs.map(() => false);\n    }\n\n    ensureBlankRow();\n\n    if (shouldStorePlaceholder({ storedPairs: updatedPairs, storedValue: valueStore[keyPath] })) {\n      const _keyPath = keyPath;\n\n      // Enable validation. This runs from an effect, so the write is deferred\n      deferDraftWrite(() => {\n        valueStore[_keyPath] = null;\n      });\n    }\n  };\n\n  /**\n   * Add an empty pair to the {@link rows}.\n   */\n  const addPair = () => {\n    rows.insert(rows.values.length, ['', '']);\n    edited.push(false);\n\n    window.requestAnimationFrame(() => {\n      /** @type {HTMLInputElement} */ (\n        rowElements[rows.values.length - 1].querySelector('input')\n      ).focus();\n    });\n  };\n\n  /**\n   * Remove a pair from {@link rows}.\n   * @param {number} index Row index.\n   */\n  const removePair = async (index) => {\n    rows.remove(index);\n    edited.splice(index, 1);\n    ensureBlankRow();\n    await tick();\n\n    // The focused Remove button is gone along with the row, so move the focus to the Remove button\n    // of the row now at the same position, or the previous row if the last one was removed. The\n    // blank row left once the last pair is removed can’t be removed, so its key takes the focus\n    // There’s always a row left, as the blank row takes the place of the last pair\n    const { rows: rowList } = /** @type {HTMLTableSectionElement} */ (tableBody);\n\n    focusAfterRemoval({\n      index,\n      /**\n       * Get the Remove button of a row, or the key input if the row can’t be removed.\n       * @param {number} _index Row index.\n       * @returns {HTMLElement | null | undefined} Element.\n       */\n      getTarget: (_index) => {\n        const row = rowList[_index];\n\n        return (\n          row &&\n          /** @type {HTMLElement | null} */ (\n            row.querySelector('td.action button:enabled') ?? row.querySelector('td.key input')\n          )\n        );\n      },\n    });\n  };\n\n  /**\n   * Move a pair to another position in {@link rows}. The pairs are saved in the new order.\n   * @param {number} from Source index.\n   * @param {number} to Destination index.\n   */\n  const movePair = (from, to) => {\n    rows.move(from, to);\n    edited = moveListItem(edited, from, to);\n  };\n\n  const sorter = createDragSorter({\n    /**\n     * Get the number of pairs.\n     * @returns {number} Pair count.\n     */\n    getItemCount: () => rows.values.length,\n    /**\n     * Get the table body, whose rows are the pairs.\n     * @returns {HTMLTableSectionElement | undefined} Element.\n     */\n    getListElement: () => tableBody,\n    onMove: movePair,\n    /**\n     * Get the key of a pair, to be attached to its drag.\n     * @param {number} index Row index.\n     * @returns {string} Key.\n     */\n    getItemData: (index) => rows.values[index][0],\n  });\n\n  /**\n   * Update the draft store whenever the {@link rows} is updated.\n   */\n  const updateStore = () => {\n    const draft = entryDraft.current;\n\n    /* v8 ignore next 3 -- the editor is only rendered while the draft is there */\n    if (!draft) {\n      return;\n    }\n\n    const pairs = getPairsToSave({\n      rows: rows.values,\n      validations,\n      /**\n       * Get the pairs stored in the draft.\n       * @returns {[string, string][]} Pairs.\n       */\n      getStoredPairs: () => getPairs({ draft, valueStoreKey, keyPath, locale }),\n    });\n\n    if (!pairs) {\n      return;\n    }\n\n    const args = {\n      draft,\n      valueStoreKey,\n      fieldConfig,\n      keyPath,\n      locale,\n      pairs: $state.snapshot(pairs),\n    };\n\n    // This runs from an effect, so the write to the draft is deferred\n    deferDraftWrite(() => {\n      savePairs(args);\n    });\n  };\n\n  /**\n   * The pairs stored in the draft and the value at the field’s key path, which is all\n   * {@link updatePairs} reads. It only changes when the field does, rather than whenever anything\n   * else in the entry is changed, e.g. on every keystroke in another field.\n   */\n  const storedField = createStableDerivedState(() => {\n    const valueMap = getFieldValueMapSnapshot(entryDraft.current, locale, keyPath, valueStoreKey);\n\n    // A snapshot isn’t mutated, so its key paths are read from the index kept for it\n    return [getPairsFromContent(valueMap, keyPath, { live: false }), valueMap[keyPath]];\n  });\n\n  watch(\n    () => [storedField.current],\n    () => {\n      updatePairs();\n    },\n  );\n\n  watch(\n    () => $state.snapshot(rows.values),\n    () => {\n      updateStore();\n    },\n  );\n</script>\n\n{#if rows.values.length}\n  <table>\n    <thead>\n      <tr>\n        {#if !keysReadonly}\n          <th scope=\"col\" class=\"reorder\" aria-label={_('reorder')}></th>\n        {/if}\n        <th scope=\"col\" class=\"key\">{keyLabel}</th>\n        <th scope=\"col\" class=\"value\">{valueLabel}</th>\n        {#if !keysReadonly}\n          <th scope=\"col\" class=\"action\" aria-label={_('key_value.action')}></th>\n        {/if}\n      </tr>\n    </thead>\n    <tbody bind:this={tableBody} {...sorter.listProps}>\n      {#each sorter.displayOrder as index (rows.ids[index])}\n        <tr\n          bind:this={rowElements[index]}\n          class:drag-placeholder={sorter.dragIndex === index}\n          {...sorter.itemProps(index)}\n          animate:flip={{ duration: 200 }}\n        >\n          {#if !keysReadonly}\n            <td class=\"reorder\">\n              <div role=\"none\">\n                <ReorderControls\n                  {index}\n                  itemCount={rows.values.length}\n                  disabled={rows.values.length < 2}\n                  {...sorter.reorderControlProps(index)}\n                />\n              </div>\n            </td>\n          {/if}\n          <td class=\"key\">\n            <TextInput\n              dir=\"ltr\"\n              readonly={keysReadonly}\n              flex\n              bind:value={rows.values[index][0]}\n              invalid={!!validations[index]}\n              ariaLabel={keyLabel}\n              aria-errormessage={validations[index] ? `${fieldId}-kv-error` : undefined}\n              oninput={() => {\n                edited[index] = true;\n              }}\n              onkeydown={(event) => {\n                // Move focus with Enter key\n                if (event.key === 'Enter' && !event.isComposing) {\n                  /** @type {HTMLInputElement} */ (\n                    rowElements[index].querySelector('td.value input')\n                  ).focus();\n                }\n              }}\n            />\n          </td>\n          <td class=\"value\">\n            <TextInput\n              dir={getDirection(locale)}\n              {readonly}\n              flex\n              bind:value={rows.values[index][1]}\n              ariaLabel={valueLabel}\n              onkeydown={(event) => {\n                // Move focus or add a new pair with Enter key. The next key is skipped when it’s\n                // read-only\n                if (event.key === 'Enter' && !event.isComposing) {\n                  if (index < rows.values.length - 1) {\n                    /** @type {HTMLInputElement} */ (\n                      rowElements[index + 1].querySelector(\n                        keysReadonly ? 'td.value input' : 'td.key input',\n                      )\n                    ).focus();\n                  } else if (!keysReadonly && rows.values.length < max) {\n                    addPair();\n                  }\n                }\n              }}\n            />\n          </td>\n          {#if !keysReadonly}\n            <td class=\"action\">\n              <RemoveButton\n                variant=\"ghost\"\n                disabled={isOnlyBlankRow}\n                onclick={() => {\n                  removePair(index);\n                }}\n              />\n            </td>\n          {/if}\n        </tr>\n      {/each}\n    </tbody>\n  </table>\n{/if}\n\n{#if validations.some(Boolean)}\n  <ValidationError id=\"{fieldId}-kv-error\">\n    {#if validations.includes('empty')}\n      {_('key_value.empty_key')}\n    {/if}\n    {#if validations.includes('duplicate')}\n      {_('key_value.duplicate_key')}\n    {/if}\n  </ValidationError>\n{/if}\n\n{#if rows.values.length < max}\n  <div role=\"none\" class=\"toolbar\">\n    <AddItemButton\n      disabled={keysReadonly}\n      {fieldConfig}\n      {locale}\n      items={rows.values}\n      addItem={() => {\n        addPair();\n      }}\n    />\n  </div>\n{/if}\n\n<style>\n  .toolbar {\n    display: flex;\n    align-items: center;\n    margin-block-start: 8px;\n\n    &:first-child {\n      margin-block-start: 0;\n    }\n  }\n\n  table {\n    /* Space the cells like the items of a List field. The outer spacing is cancelled out by the\n      negative margins, which the stretched width makes up for */\n    margin: -4px;\n    border-collapse: separate;\n    border-spacing: 4px;\n    width: -moz-available;\n    width: -webkit-fill-available;\n    width: stretch;\n  }\n\n  th,\n  td {\n    border-width: 0;\n  }\n\n  th {\n    padding-block: 4px;\n    color: var(--sui-tertiary-foreground-color);\n    font-size: var(--sui-font-size-small);\n    font-weight: var(--sui-font-weight-normal);\n    text-align: start;\n\n    &.key,\n    &.value {\n      width: 50%;\n    }\n  }\n\n  td {\n    padding: 0;\n    vertical-align: middle;\n\n    &.reorder div {\n      display: flex;\n      align-items: center;\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the preview for a KeyValue field compatible with Static CMS.\n  @see https://staticjscms.netlify.app/docs/widget-keyvalue\n  @see https://sveltiacms.app/en/docs/fields/keyvalue\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getPairsFromContent } from '$lib/services/contents/fields/key-value/pairs';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { KeyValueField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {KeyValueField} fieldConfig Field configuration.\n   * @property {Record<string, string> | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, keyPath, fieldConfig } = $props();\n\n  const {\n    // Field type-specific options\n    key_label: _keyLabel,\n    value_label: _valueLabel,\n  } = $derived(fieldConfig);\n  const keyLabel = $derived(_keyLabel || _('key_value.key'));\n  const valueLabel = $derived(_valueLabel || _('key_value.value'));\n\n  // The shared snapshot of the locale’s values is only taken once per change, and its key paths are\n  // indexed, so the pairs are looked up without going through all the values\n  const pairs = $derived(\n    getPairsFromContent(getFieldValueMapSnapshot(entryDraft.current, locale, keyPath), keyPath, {\n      live: false,\n    }),\n  );\n</script>\n\n{#if pairs.length}\n  <table>\n    <thead>\n      <tr>\n        <th scope=\"col\">{keyLabel}</th>\n        <th scope=\"col\">{valueLabel}</th>\n      </tr>\n    </thead>\n    <tbody>\n      {#each pairs as [key, value], index (`${key}-${index}`)}\n        <tr>\n          <td>{key}</td>\n          <td>{value}</td>\n        </tr>\n      {/each}\n    </tbody>\n  </table>\n{/if}\n\n<style>\n  table {\n    width: -moz-available;\n    width: -webkit-fill-available;\n    width: stretch;\n  }\n\n  th {\n    padding-block: 4px;\n    width: 50%;\n    color: var(--sui-tertiary-foreground-color);\n    background-color: var(--sui-tertiary-background-color);\n    font-size: var(--sui-font-size-small);\n    font-weight: var(--sui-font-weight-normal);\n    text-align: start;\n  }\n\n  td {\n    &:empty::after {\n      content: '\\00a0'; /* nbsp */\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the options menu of an item in a List field with subfield(s): copy, paste, duplicate and\n  add buttons, as well as the reorder items for a list with enough items.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Menu, MenuButton, MenuItem } from '@sveltia/ui';\n\n  import MoveToDialog from '$lib/components/common/move-to-dialog.svelte';\n  import ReorderMenuItems from '$lib/components/common/reorder-menu-items.svelte';\n  import { getFieldLabel } from '$lib/services/contents/i18n/options';\n  import { canMoveToEdge } from '$lib/services/utils/drag-sorting';\n\n  /**\n   * @import { InternalLocaleCode } from '$lib/types/private';\n   * @import { ListFieldWithTypes } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {number} index Index of the item.\n   * @property {InternalLocaleCode} locale Locale being edited.\n   * @property {NonNullable<ListFieldWithTypes['types']> | undefined} variableTypes Variable types\n   * the new items can have, if the list has them.\n   * @property {boolean} unknownType Whether the item has an unknown type.\n   * @property {boolean} allowAdd Whether items can be added.\n   * @property {boolean} allowRemove Whether items can be removed.\n   * @property {boolean} allowDuplicate Whether items can be duplicated.\n   * @property {boolean} hasMaxItems Whether the list is full.\n   * @property {boolean} isAddDisabled Whether adding items is disabled.\n   * @property {number} itemCount Total number of items in the list.\n   * @property {boolean} canReorder Whether the item can be moved.\n   * @property {(index: number, action: string) => void} moveItem Move the item to another index,\n   * then restore the focus to the control with the given `data-action`.\n   * @property {(index: number) => void} copyItem Copy the item.\n   * @property {(index: number, options?: { replace?: boolean }) => void} pasteItem Paste an item.\n   * @property {(args: { index: number, dupIndex?: number, type?: string }) => void} addItem Add an\n   * item.\n   */\n\n  /** @type {Props} */\n  const {\n    index,\n    locale,\n    variableTypes = undefined,\n    unknownType,\n    allowAdd,\n    allowRemove,\n    allowDuplicate,\n    hasMaxItems,\n    isAddDisabled,\n    itemCount,\n    canReorder,\n    moveItem,\n    copyItem,\n    pasteItem,\n    addItem,\n  } = $props();\n\n  const showReorder = $derived(canReorder && canMoveToEdge(itemCount));\n  let moveToDialogOpen = $state(false);\n</script>\n\n{#snippet addPositionItems(/** @type {number} */ insertIndex, /** @type {string} */ position)}\n  {#if variableTypes}\n    <MenuItem label={_(`add_item_${position}`)} disabled={isAddDisabled}>\n      <!-- eslint-disable-next-line no-shadow -->\n      {#snippet items()}\n        {#each variableTypes as type (type.name)}\n          <MenuItem\n            label={getFieldLabel({ config: type, locale })}\n            onclick={() => addItem({ index: insertIndex, type: type.name })}\n          />\n        {/each}\n      {/snippet}\n    </MenuItem>\n  {:else}\n    <MenuItem\n      label={_(`add_item_${position}`)}\n      disabled={isAddDisabled}\n      onclick={() => addItem({ index: insertIndex })}\n    />\n  {/if}\n{/snippet}\n\n<MenuButton\n  variant=\"ghost\"\n  size=\"small\"\n  iconic\n  popupPosition=\"bottom-right\"\n  data-action=\"move-options\"\n  aria-label={_('list_item_options')}\n>\n  {#snippet popup()}\n    <Menu ariaLabel={_('list_item_options')}>\n      {#if allowAdd && !hasMaxItems}\n        {#if allowDuplicate}\n          <MenuItem\n            label={_('duplicate')}\n            disabled={isAddDisabled || unknownType}\n            onclick={() => addItem({ index: index + 1, dupIndex: index })}\n          />\n        {/if}\n        {@render addPositionItems(index, 'above')}\n        {@render addPositionItems(index + 1, 'below')}\n        <Divider />\n      {/if}\n      <!-- An item can be copied from a read-only list as well -->\n      <MenuItem label={_('copy')} disabled={unknownType} onclick={() => copyItem(index)} />\n      {#if allowAdd && allowRemove}\n        <!-- Replacing an item doesn’t change the number of items -->\n        <MenuItem\n          label={_('paste_item_to_replace')}\n          disabled={isAddDisabled}\n          onclick={() => pasteItem(index, { replace: true })}\n        />\n      {/if}\n      {#if allowAdd && !hasMaxItems}\n        <MenuItem\n          label={_('paste_item_above')}\n          disabled={isAddDisabled}\n          onclick={() => pasteItem(index)}\n        />\n        <MenuItem\n          label={_('paste_item_below')}\n          disabled={isAddDisabled}\n          onclick={() => pasteItem(index + 1)}\n        />\n      {/if}\n      {#if showReorder}\n        <Divider />\n        <ReorderMenuItems\n          {index}\n          {itemCount}\n          onMove={moveItem}\n          onMoveTo={() => {\n            moveToDialogOpen = true;\n          }}\n        />\n      {/if}\n    </Menu>\n  {/snippet}\n</MenuButton>\n{#if showReorder}\n  <MoveToDialog\n    bind:open={moveToDialogOpen}\n    {index}\n    {itemCount}\n    onMove={(to) => moveItem(to, 'move-options')}\n  />\n{/if}\n","<script>\n  import { isRTL } from '@sveltia/i18n';\n  import { Icon } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [expanded] Whether the icon indicates an expanded state.\n   */\n\n  /** @type {Props} */\n  let { expanded = false } = $props();\n</script>\n\n<Icon name={expanded ? 'expand_more' : isRTL() ? 'chevron_left' : 'chevron_right'} />\n","<!--\n  @component\n  Implement the toolbar above or below the items of a List field with subfield(s): the item count,\n  the expander button, the Add and Paste buttons, and the Expand All and Collapse All buttons.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, Spacer } from '@sveltia/ui';\n\n  import ExpandIcon from '$lib/components/common/expand-icon.svelte';\n  import AddItemButton from '$lib/components/contents/details/fields/object/add-item-button.svelte';\n\n  /**\n   * @import { InternalLocaleCode } from '$lib/types/private';\n   * @import { ComplexListField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'top' | 'bottom'} position Where the toolbar is. The top one shows the item count\n   * and the expand and collapse buttons, while the bottom one only has the buttons to add an item.\n   * @property {HTMLElement} [element] The toolbar element, bound for the parent.\n   * @property {string} fieldId ID of the field, to refer to the item list with.\n   * @property {string} [summaryId] ID for the item count, which labels the list.\n   * @property {ComplexListField} fieldConfig Field configuration.\n   * @property {InternalLocaleCode} locale Locale being edited.\n   * @property {Record<string, any>[]} items List items.\n   * @property {string} fieldName Field name.\n   * @property {string | undefined} label Field label.\n   * @property {string | undefined} labelSingular Singular field label.\n   * @property {boolean} singleItem Whether the list is limited to one item.\n   * @property {boolean} parentExpanded Whether the list is expanded.\n   * @property {string} parentExpandedKeyPath Key path of the list’s expander state.\n   * @property {[string, boolean][]} itemExpanderStates Key path and expander state of each item.\n   * @property {boolean} allowAdd Whether items can be added.\n   * @property {boolean} addToTop Whether new items are added to the top of the list.\n   * @property {boolean} isAddDisabled Whether the Add and Paste buttons are disabled.\n   * @property {boolean} hasMaxItems Whether the list is full.\n   * @property {(args?: { index?: number, type?: string }) => void} addItem Add an item.\n   * @property {(index: number) => void} pasteItem Paste an item at the index.\n   * @property {(stateMap: Record<string, boolean>) => void} updateExpanderStates Update the\n   * expander states.\n   */\n\n  /** @type {Props} */\n  let {\n    position,\n    element = $bindable(),\n    fieldId,\n    summaryId = undefined,\n    fieldConfig,\n    locale,\n    items,\n    fieldName,\n    label,\n    labelSingular,\n    singleItem,\n    parentExpanded,\n    parentExpandedKeyPath,\n    itemExpanderStates,\n    allowAdd,\n    addToTop,\n    isAddDisabled,\n    hasMaxItems,\n    addItem,\n    pasteItem,\n    updateExpanderStates,\n  } = $props();\n</script>\n\n{#snippet pasteButton()}\n  {#if !hasMaxItems}\n    <Button\n      variant=\"tertiary\"\n      size=\"small\"\n      iconic\n      aria-label={_('paste_item')}\n      disabled={isAddDisabled}\n      onclick={() => pasteItem(addToTop ? 0 : items.length)}\n    >\n      {#snippet startIcon()}\n        <Icon name=\"content_paste\" />\n      {/snippet}\n    </Button>\n  {/if}\n{/snippet}\n\n{#if position === 'top'}\n  <div role=\"none\" class=\"toolbar top\" class:single={singleItem} bind:this={element}>\n    {#if !singleItem}\n      <div role=\"none\" class=\"label\">\n        <Button\n          iconic\n          disabled={!items.length}\n          aria-label={parentExpanded ? _('collapse') : _('expand')}\n          aria-expanded={parentExpanded}\n          aria-controls=\"list-{fieldId}-item-list\"\n          onclick={() => {\n            updateExpanderStates({ [parentExpandedKeyPath]: !parentExpanded });\n          }}\n        >\n          {#snippet startIcon()}\n            <ExpandIcon expanded={parentExpanded} />\n          {/snippet}\n        </Button>\n        <div role=\"none\" class=\"summary\" id={summaryId}>\n          {items.length}\n          {(items.length === 1 ? labelSingular : undefined) || label || fieldName}\n        </div>\n      </div>\n    {/if}\n    <div role=\"none\" class=\"actions\">\n      {#if allowAdd && (addToTop || !items.length || !parentExpanded)}\n        <AddItemButton disabled={isAddDisabled} {fieldConfig} {locale} {items} {addItem} />\n        {@render pasteButton()}\n      {/if}\n      {#if parentExpanded && items.length > 1}\n        {#each [true, false] as expanded (expanded)}\n          <Button\n            variant=\"tertiary\"\n            size=\"small\"\n            label={_(expanded ? 'expand_all' : 'collapse_all')}\n            disabled={itemExpanderStates.every(([, value]) => value === expanded)}\n            onclick={() => {\n              updateExpanderStates(\n                Object.fromEntries(itemExpanderStates.map(([key]) => [key, expanded])),\n              );\n            }}\n          />\n        {/each}\n      {/if}\n    </div>\n  </div>\n{:else}\n  <div role=\"none\" class=\"toolbar bottom add\">\n    <Spacer flex />\n    <AddItemButton disabled={isAddDisabled} {fieldConfig} {locale} {items} {addItem} />\n    {@render pasteButton()}\n  </div>\n{/if}\n\n<style>\n  .toolbar {\n    display: flex;\n    align-items: center;\n    flex-wrap: wrap;\n    gap: 0 8px;\n    position: sticky;\n    z-index: 10;\n    background-color: var(--sui-primary-background-color);\n    min-height: var(--sui-secondary-toolbar-size);\n\n    &.top {\n      /* Below the sticky toolbars of the rich text editors the field is in, if any */\n      top: var(--sui-text-editor-inner-toolbar-top, 0);\n    }\n\n    &.bottom {\n      bottom: 0;\n    }\n\n    & > div {\n      display: flex;\n      align-items: center;\n\n      &.actions {\n        flex-wrap: wrap;\n        margin-block: 8px;\n        margin-inline-start: auto;\n      }\n    }\n\n    &.single > div.actions {\n      /* With no item count on the left, the Add button goes where the item would be */\n      margin-inline-start: 0;\n    }\n  }\n</style>\n","/**\n * Get the message of a thrown value to show the user. Anything can be thrown, not only an `Error`,\n * and a value without a working `toString()`, like an object with a `null` prototype, would make\n * plain stringification throw in turn.\n * @param {unknown} error Thrown value.\n * @returns {string} Message. Empty if there is nothing to show.\n */\nexport const describeError = (error) => {\n  if (error instanceof Error) {\n    return error.message;\n  }\n\n  try {\n    return String(error ?? '');\n  } catch {\n    return '';\n  }\n};\n","<!--\n  @component\n  Catch an error thrown while the content is rendered or in one of its effects, and show a message\n  in its place, so a bug or unexpected data takes down only that part of the UI rather than leaving\n  a blank page. An error thrown in an event handler or after an `await` isn’t caught.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Button, EmptyState } from '@sveltia/ui';\n\n  import { describeError } from '$lib/services/utils/error';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'page' | 'field'} [scope] What the content is. A page gets a full-size message with\n   * a button to reload the CMS, as the app may be left in a state it can’t recover from; a field\n   * gets an inline message.\n   * @property {Snippet} children Content.\n   */\n\n  /** @type {Props} */\n  let { scope = 'field', children } = $props();\n\n  /* v8 ignore start -- reloading the page would tear the test down */\n  /**\n   * Reload the CMS, which starts it over from a clean state.\n   */\n  const reload = () => {\n    window.location.reload();\n  };\n  /* v8 ignore stop */\n</script>\n\n<svelte:boundary\n  onerror={(error) => {\n    // eslint-disable-next-line no-console\n    console.error(error);\n  }}\n>\n  {@render children()}\n\n  {#snippet failed(error, reset)}\n    {@const message = _(`${scope}_crashed`, { values: { message: describeError(error) } })}\n    {#if scope === 'page'}\n      <EmptyState>\n        <span role=\"alert\">{message}</span>\n        <div role=\"none\" class=\"buttons\">\n          <Button variant=\"secondary\" label={_('try_again')} onclick={reset} />\n          <Button variant=\"primary\" label={_('reload_cms')} onclick={reload} />\n        </div>\n      </EmptyState>\n    {:else}\n      <!-- The field preview highlights the field in the editor when it’s clicked or Enter is\n      pressed, which the button mustn’t do as well. Other keys, like Escape, are left to their\n      shortcuts -->\n      <!-- svelte-ignore a11y_no_static_element_interactions -->\n      <div\n        role=\"none\"\n        class=\"field-error\"\n        onclick={(event) => event.stopPropagation()}\n        onkeydown={(event) => {\n          if (event.key === 'Enter') {\n            event.stopPropagation();\n          }\n        }}\n      >\n        <Alert status=\"error\">{message}</Alert>\n        <Button variant=\"tertiary\" size=\"small\" label={_('try_again')} onclick={reset} />\n      </div>\n    {/if}\n  {/snippet}\n</svelte:boundary>\n\n<style>\n  .buttons {\n    display: flex;\n    flex-wrap: wrap;\n    justify-content: center;\n    gap: 8px;\n  }\n\n  .field-error {\n    display: flex;\n    flex-direction: column;\n    align-items: flex-start;\n    gap: 8px;\n  }\n</style>\n","import { parse } from 'marked';\nimport { SvelteSet } from 'svelte/reactivity';\n\nimport { createLazyModule } from '$lib/services/api/lazy-module';\nimport { loadModule } from '$lib/services/app/dependencies';\nimport { getListItemMatcher } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { copyFromLocaleToast, translatorApiKeyDialogState } from '$lib/services/contents/editor';\nimport { getDraftFieldArgs, getField } from '$lib/services/contents/entry/fields';\nimport { isKeyPathWithin } from '$lib/services/contents/entry/key-paths';\nimport { RICH_TEXT_FIELD_TYPES, TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport { getValueFormat } from '$lib/services/contents/fields/rich-text';\nimport { isDuplicateIfEmptyField } from '$lib/services/contents/i18n/duplicate-if-empty';\nimport { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\nimport { translator } from '$lib/services/integrations/translators';\nimport { getApiKey } from '$lib/services/user/api-keys';\nimport { isNumeric } from '$lib/services/utils/number';\nimport { escapeHTML } from '$lib/services/utils/string';\n\n/**\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalLocaleCode,\n * LocaleContentMap,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath, ListField, RichTextField } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} OwnerField\n * @property {FieldKeyPath} keyPath Key path of the field.\n * @property {Field} field Field configuration.\n */\n\n/**\n * @typedef {object} CopyOptions\n * @property {InternalLocaleCode} sourceLanguage Source locale, e.g. `en`.\n * @property {InternalLocaleCode} targetLanguage Target locale, e.g. `ja`.\n * @property {FieldKeyPath} [keyPath] Flattened (dot-notated) object keys that will be used for\n * searching the source values. Omit this if copying all the fields. If the triggered field is the\n * List or Object type, this will likely match multiple fields.\n * @property {boolean} [translate] Whether to translate the copied text fields.\n */\n\n/**\n * @typedef {Record<FieldKeyPath, { value: string, format: 'plain' | 'markdown' | 'html' }>}\n * CopyingFieldMap\n */\n\n/**\n * @typedef {object} PendingTranslation\n * @property {EntryDraft} draft Entry draft being translated into.\n * @property {InternalLocaleCode} targetLanguage Target locale.\n * @property {FieldKeyPath} keyPath Field key path, or an empty string for all the fields.\n */\n\n/**\n * Translations in flight. A request costs money and takes a while, so the same one isn’t sent again\n * until it’s settled, and the UI disables the button that would send it.\n * @type {SvelteSet<PendingTranslation>}\n */\nexport const pendingTranslations = new SvelteSet();\n\n/**\n * Check if the fields at the given key path are being translated into the given locale.\n * @param {object} args Arguments.\n * @param {EntryDraft | null | undefined} args.draft Entry draft.\n * @param {InternalLocaleCode} args.targetLanguage Target locale.\n * @param {FieldKeyPath} [args.keyPath] Field key path. Omit this for all the fields.\n * @returns {boolean} Result.\n */\nexport const isTranslationPending = ({ draft, targetLanguage, keyPath = '' }) =>\n  [...pendingTranslations].some(\n    (translation) =>\n      translation.draft === draft &&\n      translation.targetLanguage === targetLanguage &&\n      translation.keyPath === keyPath,\n  );\n\n/**\n * Loader for a Turndown service instance, created on first use. A failed load isn’t remembered, so\n * a later call can try again, e.g. once the network is back.\n */\nconst turndownLoader = createLazyModule({\n  /**\n   * Fetch the library from the CDN and create a service instance.\n   * @returns {Promise<import('turndown')>} Service instance.\n   */\n  loader: async () => {\n    const { default: TurndownService } = /** @type {{ default: typeof import('turndown') }} */ (\n      await loadModule('turndown', 'lib/turndown.browser.es.js')\n    );\n\n    const service = new TurndownService({\n      headingStyle: 'atx',\n      bulletListMarker: '-',\n      codeBlockStyle: 'fenced',\n    });\n\n    // @ts-ignore Silence a false type error\n    service.keep(['span', 'div']);\n\n    return service;\n  },\n  notLoadedMessage: 'Turndown is not loaded yet. Call `getTurndownService()` first.',\n});\n\n/**\n * Get a Turndown service instance for converting HTML to Markdown. The library is only needed when\n * a translator without Markdown support hands HTML back, so it’s loaded from the CDN on demand\n * rather than shipped in the bundle.\n * @returns {Promise<import('turndown')>} Service instance.\n * @see https://github.com/mixmark-io/turndown\n */\nexport const getTurndownService = turndownLoader.load;\n\n/**\n * Named HTML character references a translator may return, besides numeric ones.\n * @type {Record<string, string>}\n */\nconst HTML_ENTITY_MAP = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" };\n\n/**\n * Decode the HTML character references in text returned by a translator taking HTML, which\n * escapes special characters such as `&` and `\"` in its output. Each reference is decoded once,\n * so text escaped with {@link escapeHTML} comes back as it was. An unknown named reference is left\n * as is.\n * @param {string} text Text with character references.\n * @returns {string} Decoded text.\n */\nconst decodeHTMLEntities = (text) =>\n  text.replace(/&(?:#(\\d+)|#x([\\da-f]+)|(amp|lt|gt|quot|apos));/gi, (ref, dec, hex, name) => {\n    if (name) {\n      return HTML_ENTITY_MAP[name.toLowerCase()];\n    }\n\n    const codePoint = dec ? Number(dec) : Number.parseInt(hex, 16);\n\n    return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : ref;\n  });\n\n/**\n * @typedef {object} ListItemState\n * @property {boolean} exists Whether the item exists.\n * @property {string | undefined} id ID given to the item once it’s added, moved or removed: its\n * `__sc_item_id` property.\n * @property {string | undefined} originalKeyPath Key path the item had before the items of its list\n * were first shifted: its `__sc_item_original_key_path` property.\n */\n\n/**\n * Get the state of each list item the given key path is in, from the outermost one, so that it can\n * be told later whether the key path still points to the same items.\n * @param {FlattenedEntryContent} content Content of a locale.\n * @param {FieldKeyPath} keyPath Key path of a value, e.g. `faq.1.question`.\n * @returns {ListItemState[]} Item states. Empty if the key path is not in a list.\n */\nexport const getListItemStates = (content, keyPath) => {\n  const segments = keyPath.split('.');\n\n  return segments.flatMap((segment, index) => {\n    if (index === 0 || !isNumeric(segment)) {\n      return [];\n    }\n\n    const itemKeyPath = segments.slice(0, index + 1).join('.');\n\n    return [\n      {\n        exists:\n          keyPath in content ||\n          itemKeyPath in content ||\n          Object.keys(content).some((_keyPath) => _keyPath.startsWith(`${itemKeyPath}.`)),\n        id: content[`${itemKeyPath}.__sc_item_id`],\n        originalKeyPath: content[`${itemKeyPath}.__sc_item_original_key_path`],\n      },\n    ];\n  });\n};\n\n/**\n * Check if the list items a key path is in are still the same ones: none of them has been removed,\n * or replaced with another item by a removal, insertion or move. An item is tagged with an\n * ID and its original key path just before its list is first changed by the user, so an item\n * untagged before may have been tagged since: it’s still the same item if its original key path is\n * the one it had then. A new item gets an ID but no original key path.\n * @param {ListItemState[]} before Item states taken before, with {@link getListItemStates}.\n * @param {ListItemState[]} after Item states taken now, for the same key path.\n * @param {FieldKeyPath} keyPath Key path of the value.\n * @returns {boolean} Result.\n */\nexport const isSameListItems = (before, after, keyPath) => {\n  const segments = keyPath.split('.');\n\n  const itemKeyPaths = segments\n    .map((segment, index) => segments.slice(0, index + 1).join('.'))\n    .filter((_keyPath, index) => index > 0 && isNumeric(segments[index]));\n\n  return before.every((state, index) => {\n    const { exists, id, originalKeyPath } = after[index];\n    const itemKeyPath = itemKeyPaths[index];\n\n    if (exists !== state.exists) {\n      return false;\n    }\n\n    if (state.id !== undefined) {\n      return id === state.id;\n    }\n\n    return (\n      (id === undefined || originalKeyPath !== undefined) &&\n      (originalKeyPath ?? itemKeyPath) === (state.originalKeyPath ?? itemKeyPath)\n    );\n  });\n};\n\n/**\n * Regular expression matching the key path of a list item, capturing the key path of the list.\n */\nconst LIST_ITEM_KEY_PATH_REGEX = /^(.+)\\.\\d+$/;\n\n/**\n * Get the field that owns the value at the given key path. It’s the field configured for the key\n * path, except for an item of a List field without subfields, which has no configuration of its own\n * and goes along with the List field, which the editor shows as a whole.\n * @param {object} args Arguments.\n * @param {Field | undefined} args.field Field configuration, if the key path has one.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function, including the key\n * path of the value.\n * @returns {OwnerField | undefined} Key path and configuration of the owner field, or `undefined`\n * if the value has none.\n */\nconst getOwnerField = ({ field, getFieldArgs }) => {\n  const { keyPath } = getFieldArgs;\n\n  if (field) {\n    return { keyPath, field };\n  }\n\n  const [, listKeyPath] = keyPath.match(LIST_ITEM_KEY_PATH_REGEX) ?? [];\n  const listField = listKeyPath ? getField({ ...getFieldArgs, keyPath: listKeyPath }) : undefined;\n\n  return listField?.widget === 'list' &&\n    !getListFieldInfo(/** @type {ListField} */ (listField)).hasSubFields\n    ? { keyPath: listKeyPath, field: listField }\n    : undefined;\n};\n\n/**\n * Check if the value owned by the given field can be written into the target locale’s content. A\n * value inside the items of a translatable List field is only written where the target locale has\n * the same item, of the same type, so that no stray item is created there or a value written into\n * an unrelated item. An item of a List field without subfields is owned by the List field, so only\n * the items the List field belongs to have to exist. See {@link getListItemMatcher}.\n * @param {object} args Arguments.\n * @param {OwnerField} args.owner Owner field of the value, as returned by {@link getOwnerField}.\n * @param {Omit<GetFieldArgs, 'keyPath'>} args.getFieldArgs Arguments for the `getField` function.\n * @param {Record<FieldKeyPath, any>} args.content Content of the target locale.\n * @returns {boolean} Result.\n */\nconst canWriteInLocale = ({ owner: { keyPath, field }, getFieldArgs, content }) =>\n  getListItemMatcher({ fieldConfig: field, getFieldArgs: { ...getFieldArgs, keyPath } })(content);\n\n/**\n * Get a list of fields to be copied or translated from the source locale to the target locale.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {CopyOptions} args.options Copy options.\n * @returns {CopyingFieldMap} Copied or translated field values.\n */\nexport const getCopyingFieldMap = ({ draft, options }) => {\n  const { currentValues } = draft;\n  const { sourceLanguage, targetLanguage, keyPath = '', translate = false } = options;\n  const valueMap = currentValues[sourceLanguage];\n  const getFieldArgs = getDraftFieldArgs(draft, { valueMap });\n\n  return Object.fromEntries(\n    Object.entries(valueMap)\n      .map(([_keyPath, value]) => {\n        if (keyPath && !isKeyPathWithin(_keyPath, keyPath)) {\n          return null;\n        }\n\n        const targetLocaleValue = currentValues[targetLanguage][_keyPath];\n        const field = getField({ ...getFieldArgs, keyPath: _keyPath });\n        const fieldType = field?.widget ?? 'string';\n\n        const owner = getOwnerField({\n          field,\n          getFieldArgs: { ...getFieldArgs, keyPath: _keyPath },\n        });\n\n        if (\n          // Only a translatable field has a value of its own in each locale: a field that isn’t\n          // localized is only saved in the default locale, and a duplicated one can’t be edited\n          // in the other locales. Like the editor (`getFieldLocaleAccess()`), the validator and the\n          // default values, it’s the owner field’s own `i18n` option, so a subfield without one\n          // isn’t written in a locale where the editor hides it, even if the List or Object field\n          // it belongs to is translatable\n          !isFieldTranslatable(owner?.field.i18n) ||\n          typeof value !== 'string' ||\n          !value ||\n          ![...TEXT_FIELD_TYPES, 'list'].includes(fieldType) ||\n          // prettier-ignore\n          (fieldType === 'list' &&\n          getListFieldInfo(/** @type {ListField} */ (field)).hasSubFields) ||\n          (!translate && value === targetLocaleValue) ||\n          // Skip populated fields when translating all the fields, except for a field using the\n          // `duplicate_if_empty` strategy that still holds the source locale’s value, which hasn’t\n          // been translated yet\n          (!keyPath &&\n            translate &&\n            !!targetLocaleValue &&\n            !(!!field && isDuplicateIfEmptyField(field) && value === targetLocaleValue)) ||\n          // The owner field is there, as a value without one isn’t translatable\n          !canWriteInLocale({\n            owner: /** @type {OwnerField} */ (owner),\n            getFieldArgs,\n            content: currentValues[targetLanguage],\n          })\n        ) {\n          return null;\n        }\n\n        const format = RICH_TEXT_FIELD_TYPES.includes(fieldType)\n          ? getValueFormat(/** @type {RichTextField} */ (field))\n          : 'plain';\n\n        return [_keyPath, { value, format }];\n      })\n      .filter((entry) => !!entry),\n  );\n};\n\n/**\n * Update the toast notification.\n * @param {'info' | 'success' | 'error'} status Status.\n * @param {string} message Message key.\n * @param {object} context Context.\n * @param {number} context.count Number of fields copied or translated.\n * @param {InternalLocaleCode} context.sourceLanguage Source locale, e.g. `en`.\n */\nexport const updateToast = (status, message, { count, sourceLanguage }) => {\n  copyFromLocaleToast.current = {\n    id: Date.now(),\n    show: true,\n    status,\n    message,\n    count,\n    sourceLanguage,\n  };\n};\n\n/**\n * Translate the field value(s) from another locale.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.currentValues Current values for the entry draft. This will be\n * updated with the translated values.\n * @param {CopyOptions} args.options Copy options.\n * @param {CopyingFieldMap} args.copingFieldMap Copied or translated field values.\n * @param {() => boolean} [args.isDraftClosed] Function telling whether the draft has been closed\n * since the request was made, in which case the results are dropped.\n */\nexport const translateFields = async ({\n  currentValues,\n  options,\n  copingFieldMap,\n  isDraftClosed = () => false,\n}) => {\n  const { serviceId } = translator.current;\n  const { sourceLanguage, targetLanguage, keyPath } = options;\n  const count = Object.keys(copingFieldMap).length;\n\n  // The target values as they were when the fields to translate were picked, so that a field the\n  // user fills in while the request is in flight isn’t overwritten when translating all the fields\n  const targetValues = Object.fromEntries(\n    Object.keys(copingFieldMap).map((_keyPath) => [\n      _keyPath,\n      currentValues[targetLanguage][_keyPath],\n    ]),\n  );\n\n  // The list items the fields belong to, as they were when the fields were picked, so that a value\n  // isn’t written into an item that the user has removed or moved while the request is in flight,\n  // which would bring back a removed item or overwrite another one\n  const listItemStates = Object.fromEntries(\n    Object.keys(copingFieldMap).map((_keyPath) => [\n      _keyPath,\n      getListItemStates(currentValues[targetLanguage], _keyPath),\n    ]),\n  );\n\n  let apiKey = getApiKey(serviceId);\n\n  if (!apiKey) {\n    const { promise, resolve } = Promise.withResolvers();\n\n    // An earlier request still waiting for a key, e.g. one whose dialog is closing, is settled\n    // without one, as the dialog now answers this request only\n    translatorApiKeyDialogState.current.resolve?.();\n    translatorApiKeyDialogState.current = { show: true, multiple: count > 1, resolve };\n\n    // The promise will be resolved once the user enters an API key on the dialog\n    apiKey = await promise;\n  }\n\n  if (!apiKey) {\n    return;\n  }\n\n  // Get the translator service again in case the user has selected a different service in the API\n  // key dialog, which will update the `translator` store\n  const { markdownSupported, translate } = translator.current;\n\n  updateToast('info', 'translation.started', { count, sourceLanguage });\n\n  try {\n    // A translator without Markdown support takes HTML, e.g. Google Translate with the `html`\n    // format. A Markdown value is converted to HTML for it, a plain text value is escaped, so that\n    // its special characters are read as text, and an HTML value is passed as is\n    const translatedValues = await translate(\n      Object.entries(copingFieldMap).map(([, { value, format }]) =>\n        markdownSupported || format === 'html'\n          ? value\n          : format === 'markdown'\n            ? /** @type {string} */ (parse(value))\n            : escapeHTML(value),\n      ),\n      { apiKey, sourceLanguage, targetLanguage },\n    );\n\n    const needsTurndown =\n      !markdownSupported &&\n      Object.values(copingFieldMap).some(({ format }) => format === 'markdown');\n\n    const turndownService = needsTurndown ? await getTurndownService() : undefined;\n\n    // The user has opened another entry in the meantime\n    if (isDraftClosed()) {\n      return;\n    }\n\n    let translatedCount = 0;\n\n    Object.entries(copingFieldMap).forEach(([_keyPath, { format }], index) => {\n      const value = translatedValues[index];\n\n      if (\n        (!keyPath && currentValues[targetLanguage][_keyPath] !== targetValues[_keyPath]) ||\n        !isSameListItems(\n          listItemStates[_keyPath],\n          getListItemStates(currentValues[targetLanguage], _keyPath),\n          _keyPath,\n        )\n      ) {\n        return;\n      }\n\n      translatedCount += 1;\n\n      // Convert the value back to Markdown or plain text if needed. The HTML comes back with its\n      // special characters as entities, which Turndown decodes for a Markdown value\n      currentValues[targetLanguage][_keyPath] =\n        markdownSupported || format === 'html'\n          ? value\n          : format === 'markdown'\n            ? // @ts-ignore Silence a false type error\n              /** @type {import('turndown')} */ (turndownService).turndown(value)\n            : decodeHTMLEntities(value);\n    });\n\n    updateToast('success', 'translation.complete', { count: translatedCount, sourceLanguage });\n  } catch (ex) {\n    if (!isDraftClosed()) {\n      // @todo Show a detailed error message.\n      updateToast('error', 'translation.error', { count, sourceLanguage });\n    }\n\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  }\n};\n\n/**\n * Copy the field value(s) from another locale.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.currentValues Current values for the entry draft. This will be\n * updated with the copied values.\n * @param {CopyOptions} args.options Copy options.\n * @param {CopyingFieldMap} args.copingFieldMap Copied or translated field values.\n */\nexport const copyFields = ({ currentValues, options, copingFieldMap }) => {\n  const { sourceLanguage, targetLanguage } = options;\n  const count = Object.keys(copingFieldMap).length;\n\n  Object.entries(copingFieldMap).forEach(([_keyPath, { value }]) => {\n    currentValues[targetLanguage][_keyPath] = value;\n  });\n\n  updateToast('success', 'copy.complete', { count, sourceLanguage });\n};\n\n/**\n * Copy or translate field value(s) from another locale. A translation already in flight for the\n * same fields and locale isn’t requested again.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {CopyOptions} args.options Copy options.\n * @param {EntryDraftState} [args.entryDraft] Entry draft state of the editor. If given, the results\n * of a translation are dropped once the draft is no longer the one in the editor.\n */\nexport const copyFromLocale = async ({ draft, options, entryDraft }) => {\n  const { sourceLanguage, targetLanguage, keyPath = '', translate = false } = options;\n\n  if (translate && isTranslationPending({ draft, targetLanguage, keyPath })) {\n    return;\n  }\n\n  const { currentValues } = draft;\n  const copingFieldMap = getCopyingFieldMap({ draft, options });\n  const count = Object.keys(copingFieldMap).length;\n\n  if (!count) {\n    updateToast('info', `${translate ? 'translation' : 'copy'}.none`, { count, sourceLanguage });\n\n    return;\n  }\n\n  if (translate) {\n    /** @type {PendingTranslation} */\n    const pendingTranslation = { draft, targetLanguage, keyPath };\n    /**\n     * Check whether the draft is no longer the one in the editor.\n     * @returns {boolean} Result.\n     */\n    const isDraftClosed = () => !!entryDraft && entryDraft.current !== draft;\n\n    pendingTranslations.add(pendingTranslation);\n\n    try {\n      await translateFields({ currentValues, options, copingFieldMap, isDraftClosed });\n    } finally {\n      pendingTranslations.delete(pendingTranslation);\n    }\n  } else {\n    copyFields({ currentValues, options, copingFieldMap });\n  }\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { MenuItem } from '@sveltia/ui';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { copyFromLocale, getCopyingFieldMap } from '$lib/services/contents/draft/update/copy';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n  import { translator } from '$lib/services/integrations/translators';\n\n  /**\n   * @import { InternalLocaleCode, LanguagePair } from '$lib/types/private';\n   * @import { FieldKeyPath } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   * @property {InternalLocaleCode[]} otherLocales Other locales.\n   * @property {FieldKeyPath} [keyPath] Field key path.\n   * @property {boolean} [translate] Whether to translate the field.\n   * @property {boolean} [submenu] Whether to gather the source locales in a submenu when there’s\n   * more than one of them. Useful where the options share a menu with unrelated commands, which a\n   * long list of locales would otherwise bury.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { locale, otherLocales, keyPath = '', translate = false, submenu = false } = $props();\n\n  const useSubmenu = $derived(submenu && otherLocales.length > 1);\n\n  /**\n   * Check if a menu item should be disabled.\n   * @param {LanguagePair} languages Language pair.\n   * @returns {Promise<boolean>} Whether the menu item should be disabled.\n   */\n  const isMenuDisabled = async ({ sourceLanguage, targetLanguage }) =>\n    !entryDraft.current?.currentLocales[targetLanguage] ||\n    !entryDraft.current.currentLocales[sourceLanguage] ||\n    // A List or Object field’s value is stored under its child key paths, so look for anything to\n    // copy within the field rather than for a value at the key path itself\n    (!!keyPath &&\n      !Object.keys(\n        getCopyingFieldMap({\n          draft: entryDraft.current,\n          options: { sourceLanguage, targetLanguage, keyPath, translate },\n        }),\n      ).length) ||\n    (translate && !(await translator.current?.availability({ sourceLanguage, targetLanguage })));\n\n  /**\n   * Copy or translate the field from another locale.\n   * @param {LanguagePair} languagePair Language pair.\n   */\n  const copy = (languagePair) => {\n    /* v8 ignore next 7 -- the menu is only offered while the draft is there */\n    if (entryDraft.current) {\n      copyFromLocale({\n        draft: entryDraft.current,\n        options: { ...languagePair, keyPath, translate },\n        entryDraft,\n      });\n    }\n  };\n</script>\n\n{#snippet localeItems()}\n  {#each otherLocales as otherLocale (otherLocale)}\n    {@const localeLabel = getLocaleLabel(otherLocale) ?? otherLocale}\n    {@const languagePair = { sourceLanguage: otherLocale, targetLanguage: locale }}\n    {#await isMenuDisabled(languagePair) then disabled}\n      <MenuItem\n        label={useSubmenu\n          ? localeLabel\n          : _(translate ? 'translate_from_x' : 'copy_from_x', { values: { locale: localeLabel } })}\n        {disabled}\n        onclick={() => {\n          copy(languagePair);\n        }}\n      />\n    {/await}\n  {/each}\n{/snippet}\n\n{#if useSubmenu}\n  <MenuItem label={_(translate ? 'translate_from' : 'copy_from')}>\n    {#snippet items()}\n      {@render localeItems()}\n    {/snippet}\n  </MenuItem>\n{:else}\n  {@render localeItems()}\n{/if}\n","<script>\n  import { onMount } from 'svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Snippet} [children] Slot content.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let { children = undefined, ...rest } = $props();\n\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n\n  // eslint-disable-next-line arrow-body-style\n  onMount(() => {\n    // onUnmount\n    return () => {\n      wrapper?.dispatchEvent(new CustomEvent('Unmount'));\n    };\n  });\n</script>\n\n<section role=\"group\" class=\"field\" {...rest} bind:this={wrapper}>\n  {@render children?.()}\n</section>\n\n<style>\n  section {\n    position: relative;\n    padding: var(--field-editor-padding);\n\n    &:not(:last-child)::after {\n      position: absolute;\n      inset: auto var(--field-editor-padding) 0 var(--field-editor-padding);\n      overflow: hidden;\n      height: 1px;\n      background-color: var(--sui-tertiary-background-color);\n      content: '';\n    }\n\n    :global {\n      & > * {\n        margin-inline: auto !important;\n        max-width: 768px;\n      }\n\n      & > header {\n        display: flex;\n        align-items: center;\n        margin: 0 -8px 8px;\n        height: var(--sui-button-small-height);\n\n        h4 {\n          margin-inline: var(--sui-focus-ring-width) 0;\n          font-size: var(--sui-font-size-small);\n          font-weight: var(--sui-font-weight-bold);\n          color: var(--sui-secondary-foreground-color);\n        }\n\n        .required {\n          margin-block: 2px 0;\n          margin-inline: 2px 0;\n          color: var(--sui-error-foreground-color);\n          font-size: var(--sui-font-size-large);\n        }\n      }\n\n      /* The buttons are shown on hover, and kept visible while a keyboard user is in the field, so\n        the focused one isn’t invisible */\n      @media (hover: hover) {\n        &:not(:hover, :focus-within) > header button {\n          opacity: 0;\n        }\n      }\n    }\n  }\n</style>\n","import { _ } from '@sveltia/i18n';\n\nimport { getLocaleLabel } from '$lib/services/contents/i18n';\nimport { DEFAULT_LOCALE_KEY } from '$lib/services/contents/i18n/config/constants';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * @typedef {'revert' | 'restore' | 'clear'} ResetAction\n * Action taken on the values of the entry draft: revert the changes, restore the default values,\n * or clear the fields.\n */\n\n/**\n * @typedef {'field' | 'locale' | 'entry'} ResetScope\n * What the action applies to: a single field, the fields in a locale, as the content options menu\n * of an editor pane offers, or the fields in every locale, as the editor options menu offers.\n */\n\n/**\n * The actions in the order the menus list them.\n * @type {ResetAction[]}\n */\nexport const RESET_ACTIONS = ['revert', 'restore', 'clear'];\n\n/**\n * I18n keys of the menu item labels, keyed by scope and action.\n * @type {Record<ResetScope, Record<ResetAction, string>>}\n */\nconst LABEL_KEYS = {\n  field: { revert: 'revert_changes', restore: 'restore_default', clear: 'clear' },\n  locale: { revert: 'revert_changes', restore: 'restore_default', clear: 'clear_all' },\n  entry: { revert: 'revert_all_changes', restore: 'restore_default', clear: 'clear_all' },\n};\n\n/**\n * I18n keys of the confirmation messages, keyed by action.\n * @type {Record<ResetAction, string>}\n */\nconst MESSAGE_KEYS = {\n  revert: 'confirm_reverting_changes',\n  restore: 'confirm_restoring_defaults',\n  clear: 'confirm_clearing_fields',\n};\n\n/**\n * Get the label of a menu item, which is also the title and the OK button label of the dialog\n * confirming the action.\n * @param {ResetAction} action Action.\n * @param {ResetScope} scope Scope.\n * @returns {string} Localized label.\n */\nexport const getResetLabel = (action, scope) => _(LABEL_KEYS[scope][action]);\n\n/**\n * Get the message of the dialog confirming an action on the fields in a locale or the entire entry.\n * The content of a monolingual entry has no locale to name, so it’s referred to as the entry.\n * @param {ResetAction} action Action.\n * @param {InternalLocaleCode} [locale] Locale, if the action applies to a single locale.\n * @returns {string} Localized message.\n */\nexport const getResetConfirmation = (action, locale) =>\n  locale && locale !== DEFAULT_LOCALE_KEY\n    ? _(`${MESSAGE_KEYS[action]}_x_locale`, {\n        values: { locale: getLocaleLabel(locale) ?? locale },\n      })\n    : _(MESSAGE_KEYS[action]);\n","<!--\n  @component\n  Render the menu items that revert the changes, restore the default values and clear the fields,\n  preceded by a separator. The field options menu, the content options menu of an editor pane and\n  the editor options menu all list them.\n-->\n<script>\n  import { Divider, MenuItem } from '@sveltia/ui';\n\n  import { getResetLabel, RESET_ACTIONS } from '$lib/services/contents/editor/reset';\n\n  /**\n   * @import { ResetAction, ResetScope } from '$lib/services/contents/editor/reset';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ResetScope} scope What the actions apply to.\n   * @property {Partial<Record<ResetAction, boolean>>} available Whether each action would change\n   * anything, keyed by action. An action missing from it isn’t offered.\n   * @property {boolean} [separator] Whether to show a separator above the items, which is left out\n   * when nothing comes before them.\n   * @property {(action: ResetAction) => void} onSelect Function called with the chosen action.\n   */\n\n  /** @type {Props} */\n  let { scope, available, separator = true, onSelect } = $props();\n</script>\n\n{#if separator}\n  <Divider />\n{/if}\n{#each RESET_ACTIONS.filter((action) => action in available) as action (action)}\n  <MenuItem\n    label={getResetLabel(action, scope)}\n    disabled={!available[action]}\n    onclick={() => {\n      onSelect(action);\n    }}\n  />\n{/each}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, Menu, MenuButton } from '@sveltia/ui';\n\n  import CopyMenuItems from '$lib/components/contents/details/editor/copy-menu-items.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { copyFromLocale, isTranslationPending } from '$lib/services/contents/draft/update/copy';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n  import { translator } from '$lib/services/integrations/translators';\n  import { isPendingDeletion } from '$lib/services/workflow';\n\n  /**\n   * @import { InternalLocaleCode, LanguagePair } from '$lib/types/private';\n   * @import { FieldKeyPath } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'medium' | 'small'} [size] Button size.\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   * @property {InternalLocaleCode[]} otherLocales Other locales.\n   * @property {FieldKeyPath} [keyPath] Field key path.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { size = 'medium', locale, otherLocales, keyPath = '' } = $props();\n\n  const sourceDisabled = $derived(\n    !entryDraft.current?.currentLocales[locale] ||\n      // An entry awaiting deletion is read-only, so there’s nothing to translate into\n      isPendingDeletion(entryDraft.current?.originalEntry),\n  );\n\n  // A request in flight isn’t sent again until it’s settled\n  const translating = $derived(\n    isTranslationPending({ draft: entryDraft.current, targetLanguage: locale, keyPath }),\n  );\n\n  /**\n   * Check if the translate button should be disabled.\n   * @param {LanguagePair} languages Language pair.\n   * @returns {Promise<boolean>} Whether the button should be disabled.\n   */\n  const isButtonDisabled = async ({ sourceLanguage, targetLanguage }) =>\n    sourceDisabled ||\n    !entryDraft.current?.currentLocales[sourceLanguage] ||\n    !(await translator.current?.availability({ sourceLanguage, targetLanguage }));\n\n  /**\n   * Translate the field from another locale.\n   * @param {LanguagePair} languagePair Language pair.\n   */\n  const translate = (languagePair) => {\n    /* v8 ignore next 7 -- the button is only offered while the draft is there */\n    if (entryDraft.current) {\n      copyFromLocale({\n        draft: entryDraft.current,\n        options: { ...languagePair, keyPath, translate: true },\n        entryDraft,\n      });\n    }\n  };\n</script>\n\n{#if otherLocales.length === 1}\n  {@const [otherLocale] = otherLocales}\n  {@const label = _('translate_from_x', {\n    values: { locale: getLocaleLabel(otherLocale) ?? otherLocale },\n  })}\n  {@const languagePair = { sourceLanguage: otherLocale, targetLanguage: locale }}\n  {#await isButtonDisabled(languagePair) then disabled}\n    <Button\n      variant=\"ghost\"\n      {size}\n      iconic\n      popupPosition=\"bottom-right\"\n      tooltip={label}\n      aria-label={label}\n      disabled={disabled || translating}\n      onclick={() => {\n        translate(languagePair);\n      }}\n    >\n      {#snippet startIcon()}\n        <Icon name=\"translate\" />\n      {/snippet}\n    </Button>\n  {/await}\n{:else}\n  <MenuButton\n    variant=\"ghost\"\n    {size}\n    iconic\n    popupPosition=\"bottom-right\"\n    tooltip={_('translate')}\n    aria-label={_('translate')}\n    disabled={sourceDisabled}\n  >\n    {#snippet endIcon()}\n      <Icon name=\"translate\" />\n    {/snippet}\n    {#snippet popup()}\n      <Menu ariaLabel={_('translation_options')}>\n        <CopyMenuItems {locale} {otherLocales} {keyPath} translate={true} />\n      </Menu>\n    {/snippet}\n  </MenuButton>\n{/if}\n","import { isObject } from '@sveltia/utils/object';\nimport equal from 'fast-deep-equal';\n\nimport {\n  collectFieldValues,\n  filterRealValues,\n  suspendAutoDuplication,\n} from '$lib/services/contents/draft';\nimport { populateDefaultValue } from '$lib/services/contents/draft/defaults';\nimport { getDraftFieldArgs } from '$lib/services/contents/entry/fields';\nimport { deleteSubtree } from '$lib/services/contents/entry/subtree';\nimport { syncAllDuplicateKeys } from '$lib/services/contents/fields/key-value/duplicate-keys';\nimport { getListFieldInfo, isPairedList } from '$lib/services/contents/fields/list/helpers';\nimport { getFlatSubFields } from '$lib/services/contents/fields/list/subfields';\nimport { isFieldMirrored, isFieldTranslatable } from '$lib/services/contents/i18n/fields';\nimport { localizeDefaultValue } from '$lib/services/contents/i18n/options';\nimport { getInheritedI18nOption } from '$lib/services/contents/i18n/shared-values';\n\n/**\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * LocaleContentMap,\n * } from '$lib/types/private';\n * @import {\n * ComplexListField,\n * Field,\n * FieldKeyPath,\n * ListField,\n * ObjectField,\n * } from '$lib/types/public';\n */\n\n/**\n * Field types whose value a user doesn’t enter, so it’s kept when the field, or the Object field\n * holding it, is cleared or restored to its default value: a Hidden field holds a value set by the\n * developer, a UUID field identifies the entry or object, and a Compute field is derived from the\n * other fields anyway.\n */\nconst PRESERVED_FIELD_TYPES = ['compute', 'hidden', 'uuid'];\n\n/**\n * @typedef {object} ResetOptions\n * @property {boolean} [restore] Whether to restore the default values rather than clearing them.\n */\n\n/**\n * @typedef {object} ResetContentArgs\n * @property {FlattenedEntryContent} content Flattened content for the locale, modified in place.\n * @property {Field} fieldConfig Field configuration.\n * @property {FieldKeyPath} keyPath Field key path.\n * @property {InternalLocaleCode} locale Locale of the content.\n * @property {InternalLocaleCode} defaultLocale Default locale of the entry draft.\n * @property {Field['i18n']} [inheritedI18n] `i18n` option of the nearest ancestor field that has\n * one. A field without the option of its own is duplicated along with an ancestor using the\n * `duplicate` or `sync` strategy, but it’s only translatable with an `i18n` option of its own.\n * @property {boolean} [mirror] Whether the content belongs to another locale than the one being\n * reset, which holds the same values as that locale for the fields using the `duplicate` or `sync`\n * strategy, and the same items for the paired List fields. Only those fields are reset then.\n * @property {boolean} [syncOnly] Whether only the fields using the `sync` strategy are mirrored,\n * as the locale being reset isn’t the default locale, where a `duplicate` field can’t be edited and\n * the items of a paired List field can’t be added or removed.\n * @property {boolean} [restore] Whether to restore the default values rather than clearing them.\n */\n\n/**\n * Reset the value of the given field in the given content, recursing into the subfields of an\n * Object field, whose type is kept along with the object itself.\n *\n * Clearing leaves a List field without items and a KeyValue field without pairs, although the\n * editor of a KeyValue field or a List field without subfields still shows a blank row to type\n * into. Any other field gets the value it would have without a default, e.g. an empty string or\n * `false`. Restoring gives every field the value a new entry would have instead, taking the\n * `default` option into account.\n *\n * The subfields the user can’t edit in the locale are left alone, as are the read-only ones, those\n * listed in {@link PRESERVED_FIELD_TYPES}, and a List field whose items can’t be removed or, when\n * restoring, added.\n * @param {ResetContentArgs} args Arguments.\n */\nconst resetContent = (args) => {\n  const { content, fieldConfig, keyPath, locale, defaultLocale, inheritedI18n } = args;\n  const { mirror = false, syncOnly = false, restore = false } = args;\n  const { widget: fieldType = 'string', i18n: ownI18n } = fieldConfig;\n  const i18n = ownI18n ?? inheritedI18n;\n\n  if (PRESERVED_FIELD_TYPES.includes(fieldType) || /** @type {any} */ (fieldConfig).readonly) {\n    return;\n  }\n\n  // A List field with subfields keeps its items if the user can’t remove them: clearing removes\n  // every item, and restoring the default value can remove items as well as add them\n  if (\n    fieldType === 'list' &&\n    getListFieldInfo(/** @type {ListField} */ (fieldConfig)).hasSubFields\n  ) {\n    const { allow_add: allowAdd = true, allow_remove: allowRemove = true } =\n      /** @type {ComplexListField} */ (fieldConfig);\n\n    if (!allowRemove || (restore && !allowAdd)) {\n      return;\n    }\n  }\n\n  // The subfields of an Object field are checked one by one, as their `i18n` options can differ\n  if (fieldType === 'object') {\n    // A `null` value means the optional Object field is collapsed, so it has nothing to reset\n    if (content[keyPath] === null) {\n      return;\n    }\n\n    // With the `i18n` option that applies to the field, so a duplicated field takes the default\n    // locale’s localized default\n    const objectConfig = /** @type {ObjectField} */ ({ ...fieldConfig, i18n });\n\n    const { default: objectDefault } = /** @type {ObjectField} */ (\n      localizeDefaultValue({ fieldConfig: objectConfig, locale, defaultLocale })\n    );\n\n    (getFlatSubFields(fieldConfig, content, keyPath) ?? []).forEach((subField) => {\n      // The default value of the Object field as a whole takes precedence over the subfield’s own,\n      // including its localized one\n      const subFieldConfig =\n        restore && isObject(objectDefault) && Object.hasOwn(objectDefault, subField.name)\n          ? /** @type {Field} */ ({\n              ...subField,\n              default: objectDefault[subField.name],\n              default_localized: undefined,\n            })\n          : subField;\n\n      resetContent({\n        ...args,\n        fieldConfig: subFieldConfig,\n        keyPath: `${keyPath}.${subField.name}`,\n        inheritedI18n: i18n,\n      });\n    });\n\n    return;\n  }\n\n  const resettable = mirror\n    ? // Another locale follows the locale being reset where the field holds the same value in every\n      // locale, and a paired List field holds the same items in every locale, although their values\n      // are translatable\n      syncOnly\n      ? i18n === 'sync'\n      : isFieldMirrored(i18n) || isPairedList(fieldConfig)\n    : // A field that isn’t translatable follows the default locale, so it can’t be edited in\n      // another locale, unless it’s kept in sync with the other locales\n      locale === defaultLocale || isFieldTranslatable(ownI18n) || i18n === 'sync';\n\n  if (!resettable) {\n    return;\n  }\n\n  deleteSubtree(content, keyPath);\n\n  if (!restore) {\n    if (fieldType === 'keyvalue') {\n      // No pairs, just the placeholder the editor stores for an empty KeyValue field, so that the\n      // field still gets validated\n      content[keyPath] = null;\n\n      return;\n    }\n\n    if (fieldType === 'list') {\n      // An empty list, even for a required List field limited to one item, which would get an\n      // item from its default value\n      content[keyPath] = [];\n\n      return;\n    }\n  }\n\n  populateDefaultValue({\n    content,\n    keyPath,\n    // With the `i18n` option that applies to the field, so a value duplicated along with an\n    // ancestor is written in another locale as well. Clearing ignores the default value\n    fieldConfig: /** @type {Field} */ ({\n      ...fieldConfig,\n      i18n,\n      ...(restore ? {} : { default: undefined, default_localized: undefined }),\n    }),\n    locale,\n    defaultLocale,\n    dynamicValues: {},\n  });\n};\n\n/**\n * Reset the given field in a locale of the given value store and in the other locales where the\n * field holds the same value: any locale where it’s duplicated if that’s the default locale, and\n * any locale where it’s synced otherwise.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.valueStore Value store keyed by locale, modified in place.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {InternalLocaleCode} args.locale Locale to reset the field in.\n * @param {InternalLocaleCode} args.defaultLocale Default locale of the entry draft.\n * @param {Field['i18n']} [args.inheritedI18n] `i18n` option that applies to the field.\n * @param {boolean} [args.restore] Whether to restore the default values rather than clearing them.\n */\nconst resetFieldInStore = ({ valueStore, locale, ...args }) => {\n  const syncOnly = locale !== args.defaultLocale;\n\n  resetContent({ ...args, content: valueStore[locale], locale });\n\n  Object.entries(valueStore).forEach(([otherLocale, content]) => {\n    if (otherLocale !== locale) {\n      resetContent({ ...args, content, locale: otherLocale, mirror: true, syncOnly });\n    }\n  });\n};\n\n/**\n * Get the arguments for {@link resetContent} to reset the given field of the given entry draft,\n * including the `i18n` option that applies to the field, looked up in its ancestors.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {FlattenedEntryContent} args.valueMap Flattened content for the locale, where the\n * ancestors are looked up.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {InternalLocaleCode} args.locale Locale to reset the field in.\n * @param {boolean} [args.restore] Whether to restore the default values rather than clearing them.\n * @returns {Omit<ResetContentArgs, 'content'>} Arguments.\n */\nconst getResetArgs = ({ draft, valueMap, ...args }) => ({\n  ...args,\n  defaultLocale: draft.defaultLocale,\n  inheritedI18n: getInheritedI18nOption({\n    fieldConfig: args.fieldConfig,\n    getFieldArgs: getDraftFieldArgs(draft, { keyPath: args.keyPath, valueMap }),\n  }),\n});\n\n/**\n * Check whether resetting the given field would change anything in the given locale.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {FlattenedEntryContent} args.valueMap Flattened content for the locale.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {InternalLocaleCode} args.locale Locale of the content.\n * @param {boolean} [args.restore] Whether to restore the default values rather than clearing them.\n * @returns {boolean} Result.\n */\nexport const canResetField = (args) => {\n  const values = collectFieldValues(args.valueMap, args.keyPath);\n  const resetValues = { ...values };\n\n  resetContent({ ...getResetArgs(args), content: resetValues });\n\n  return !equal(values, resetValues);\n};\n\n/**\n * Clear the value of the given field in the entry draft, or restore its default value, so the\n * user can start over. See {@link resetContent} for what that means for each field type. Resetting\n * a field in the default locale resets it in the other locales as well where it’s duplicated,\n * whether with its own `duplicate` or `sync` strategy or along with an ancestor’s, and resetting a\n * `sync` field in any other locale resets it in every locale. A field using the\n * `duplicate_if_empty` strategy is left alone in the other locales, which take the default locale’s\n * value again as soon as it’s next edited. A paired List field loses its items in the other locales\n * as well, or gets their default items, as its items are the same in every locale. See\n * {@link isPairedList}.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {InternalLocaleCode} args.locale Locale to reset the field in.\n * @param {boolean} [args.restore] Whether to restore the default values rather than clearing them.\n */\nexport const resetField = (args) => {\n  const { draft, locale } = args;\n  const { currentValues, defaultLocale } = draft;\n\n  // The other locales are reset here rather than by the value proxy, which copies a value to them\n  // as it’s written, as the proxy can’t tell which field a List item or a KeyValue pair belongs to\n  suspendAutoDuplication(() => {\n    resetFieldInStore({\n      ...getResetArgs({ ...args, valueMap: currentValues[locale] }),\n      valueStore: currentValues,\n    });\n\n    // The keys of a KeyValue field using the `duplicate_keys` i18n strategy, whether it’s the\n    // reset field or one nested in it, have to be updated in the other locales as well\n    if (locale === defaultLocale) {\n      syncAllDuplicateKeys({\n        valueStore: currentValues,\n        defaultLocale,\n        getFieldArgs: getDraftFieldArgs(draft),\n      });\n    }\n  });\n};\n\n/**\n * Get the locales to reset in the given draft.\n * @param {EntryDraft} draft Entry draft.\n * @param {InternalLocaleCode} [locale] Locale to reset. If omitted, every enabled locale.\n * @returns {InternalLocaleCode[]} Locales.\n */\nconst getTargetLocales = ({ currentValues, currentLocales }, locale) =>\n  locale ? [locale] : Object.keys(currentValues).filter((_locale) => currentLocales[_locale]);\n\n/**\n * Reset every field of the given value store in the given locales.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.valueStore Value store keyed by locale, modified in place.\n * @param {Field[]} args.fields Fields of the entry.\n * @param {InternalLocaleCode[]} args.locales Locales to reset.\n * @param {InternalLocaleCode} args.defaultLocale Default locale of the entry draft.\n * @param {boolean} args.restore Whether to restore the default values rather than clearing them.\n */\nconst resetAllFields = ({ valueStore, fields, locales, defaultLocale, restore }) => {\n  locales.forEach((locale) => {\n    fields.forEach((fieldConfig) => {\n      resetFieldInStore({\n        valueStore,\n        fieldConfig,\n        keyPath: fieldConfig.name,\n        locale,\n        defaultLocale,\n        restore,\n      });\n    });\n  });\n};\n\n/**\n * Check whether resetting every field of the given entry draft would change anything.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} [args.locale] Locale to reset. If omitted, every enabled locale.\n * @param {boolean} [args.restore] Whether to restore the default values rather than clearing them.\n * @returns {boolean} Result.\n */\nexport const canResetEntry = ({ draft, locale, restore = false }) => {\n  const { fields, currentValues, defaultLocale } = draft;\n\n  /**\n   * Take a plain copy of the current values, without the internal properties.\n   * @returns {LocaleContentMap} Copy.\n   */\n  const copyValues = () =>\n    Object.fromEntries(\n      Object.entries(currentValues).map(([_locale, valueMap]) => [\n        _locale,\n        filterRealValues(valueMap),\n      ]),\n    );\n\n  const values = copyValues();\n  const resetValues = copyValues();\n\n  resetAllFields({\n    valueStore: resetValues,\n    fields,\n    locales: getTargetLocales(draft, locale),\n    defaultLocale,\n    restore,\n  });\n\n  return !equal(values, resetValues);\n};\n\n/**\n * Clear every field of the given entry draft, or restore their default values. See\n * {@link resetContent} for what that means for each field type.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} [args.locale] Locale to reset. If omitted, every enabled locale.\n * Resetting the default locale resets the fields duplicated in the other locales as well, and\n * resetting any locale resets the synced fields in every locale.\n * @param {boolean} [args.restore] Whether to restore the default values rather than clearing them.\n */\nexport const resetEntry = ({ draft, locale, restore = false }) => {\n  const { fields, currentValues, defaultLocale } = draft;\n  const locales = getTargetLocales(draft, locale);\n\n  suspendAutoDuplication(() => {\n    resetAllFields({ valueStore: currentValues, fields, locales, defaultLocale, restore });\n\n    if (locales.includes(defaultLocale)) {\n      syncAllDuplicateKeys({\n        valueStore: currentValues,\n        defaultLocale,\n        getFieldArgs: getDraftFieldArgs(draft),\n      });\n    }\n  });\n};\n","import equal from 'fast-deep-equal';\n\nimport { collectFieldValues, suspendAutoDuplication } from '$lib/services/contents/draft';\nimport { getDraftFieldArgs, getField } from '$lib/services/contents/entry/fields';\nimport { isKeyPathWithin } from '$lib/services/contents/entry/key-paths';\nimport { getValueOwnerField } from '$lib/services/contents/entry/owner-field';\nimport { syncAllDuplicateKeys } from '$lib/services/contents/fields/key-value/duplicate-keys';\nimport { getPairedListKeyPaths } from '$lib/services/contents/fields/list/helpers';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\nimport { isSyncedField } from '$lib/services/contents/i18n/shared-values';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import {\n * EntryDraft,\n * GetFieldArgs,\n * InternalLocaleCode,\n * LocaleContentMap,\n * } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Resolve the original key path for a field that may be inside a reordered list item. When list\n * items are reordered, added, or removed, each item’s `__sc_item_original_key_path` property tracks\n * where it was originally located. Every list item along the key path is resolved, as an item of a\n * nested list keeps its original index in its own list, while the item holding that list may have\n * moved as well. Only the index is taken from each tag, since the tag holds the key path at the\n * time the item was tagged, which may come before or after an outer item was moved.\n * @param {Record<string, any>} valueMap Current flat value map for the locale.\n * @param {FieldKeyPath} keyPath Current field key path.\n * @returns {{ originalKeyPath: FieldKeyPath, currentPrefix: string, originalPrefix: string } |\n * undefined} The resolved paths, or `undefined` if no remapping is needed. The prefixes are the\n * current and original key paths of the innermost tagged list item.\n */\nexport const resolveOriginalKeyPath = (valueMap, keyPath) => {\n  const parts = keyPath.split('.');\n  const originalParts = [...parts];\n  let innermostIndex = 0;\n\n  parts.forEach((part, i) => {\n    if (i >= 1 && isNumeric(part)) {\n      /** @type {string | undefined} */\n      const originalItemKeyPath =\n        valueMap[`${parts.slice(0, i + 1).join('.')}.__sc_item_original_key_path`];\n\n      if (originalItemKeyPath !== undefined) {\n        originalParts[i] = /** @type {string} */ (originalItemKeyPath.split('.').at(-1));\n        innermostIndex = i;\n      }\n    }\n  });\n\n  if (!innermostIndex) {\n    return undefined;\n  }\n\n  return {\n    originalKeyPath: originalParts.join('.'),\n    currentPrefix: parts.slice(0, innermostIndex + 1).join('.'),\n    originalPrefix: originalParts.slice(0, innermostIndex + 1).join('.'),\n  };\n};\n\n/**\n * Collect the values stored at the given key path and under it, keyed by their path relative to it,\n * leaving out empty object/array placeholders. See {@link collectFieldValues}.\n * @param {Record<string, any>} valueMap Flat value map for a locale.\n * @param {FieldKeyPath} keyPath Field key path.\n * @returns {Record<string, any>} Values keyed by their relative key path; the field’s own value, if\n * any, is keyed by an empty string.\n */\nconst getFieldValues = (valueMap, keyPath) =>\n  collectFieldValues(valueMap, keyPath, { relative: true, dropEmptyPlaceholders: true });\n\n/**\n * Check if the given field has been changed from its original value, so its changes can be\n * reverted. The field’s own value and all the values under it are compared, because a List,\n * Object, KeyValue or custom field stores its value under its child key paths.\n * @param {object} args Arguments.\n * @param {Record<string, any>} args.currentValueMap Current flat value map for the locale.\n * @param {Record<string, any>} args.originalValueMap Original flat value map for the locale.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @returns {boolean} Whether the field has been changed.\n */\nexport const isFieldChanged = ({ currentValueMap, originalValueMap, keyPath }) => {\n  // For fields inside list items, use the original key path if the item was reordered\n  const originalKeyPath =\n    resolveOriginalKeyPath(currentValueMap, keyPath)?.originalKeyPath ?? keyPath;\n\n  return !equal(\n    getFieldValues(currentValueMap, keyPath),\n    getFieldValues(originalValueMap, originalKeyPath),\n  );\n};\n\n/**\n * Revert the changes made to the given field or all the fields to the default value(s).\n * @param {object} args Arguments.\n * @param {FieldKeyPath} args.keyPath Field key path to revert. If empty, all the fields will be\n * reverted.\n * @param {InternalLocaleCode} args.locale Iterating locale.\n * @param {boolean} args.isDefaultLocale Whether the locale is the default locale.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the {@link getField} function.\n * @param {LocaleContentMap} args.currentValues Current values to revert. This will be modified.\n * @param {boolean} [args.reset] Whether ro remove the current value.\n * @param {{ from: string, to: string }} [args.remapPrefix] When restoring values from a different\n * key path prefix (e.g. after list item reordering), remap `from` prefix to `to` prefix.\n */\nexport const revertFields = ({\n  locale,\n  isDefaultLocale,\n  keyPath,\n  getFieldArgs,\n  currentValues,\n  reset = false,\n  remapPrefix,\n}) => {\n  const { valueMap = {} } = getFieldArgs;\n\n  Object.entries(valueMap).forEach(([_keyPath, value]) => {\n    if (!keyPath || isKeyPathWithin(_keyPath, keyPath)) {\n      const ownField = getField({ ...getFieldArgs, keyPath: _keyPath });\n\n      // A value without a field of its own, like a KeyValue pair, an item of a List field without\n      // subfields or the code of a Code field, is governed by the field owning it\n      const field = ownField\n        ? { keyPath: _keyPath, fieldConfig: ownField }\n        : getValueOwnerField({ ...getFieldArgs, keyPath: _keyPath });\n\n      const i18n = field?.fieldConfig.i18n;\n\n      // A field using the `sync` i18n strategy, with its own option or along with an ancestor, can\n      // be edited in any locale, and the value proxy copies the reverted value to the others\n      if (\n        isDefaultLocale ||\n        isFieldTranslatable(i18n) ||\n        i18n === 'duplicate_keys' ||\n        (!!field &&\n          isSyncedField({\n            fieldConfig: field.fieldConfig,\n            getFieldArgs: { ...getFieldArgs, keyPath: field.keyPath },\n          }))\n      ) {\n        if (reset) {\n          delete currentValues[locale][_keyPath];\n        } else {\n          const targetKeyPath = remapPrefix\n            ? `${remapPrefix.to}${_keyPath.slice(remapPrefix.from.length)}`\n            : _keyPath;\n\n          currentValues[locale][targetKeyPath] = value;\n        }\n      }\n    }\n  });\n};\n\n/**\n * Revert the changes made to the given locale.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {FieldKeyPath} args.keyPath Field key path to revert. If empty, all the fields will be\n * reverted.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {boolean} [args.revertAll] Whether to revert every field in another locale as well, not\n * just the translatable ones, like in the default locale.\n */\nexport const revertLocale = ({ draft, keyPath, locale, revertAll = false }) => {\n  const { currentValues, originalValues } = draft;\n  const { defaultLocale } = getDraftI18nConfig(draft);\n  const isDefaultLocale = revertAll || locale === defaultLocale;\n  const getFieldArgs = getDraftFieldArgs(draft, { keyPath: '' });\n  // Resolve original key path for fields inside reordered list items\n  const resolved = keyPath ? resolveOriginalKeyPath(currentValues[locale], keyPath) : undefined;\n  const originalKeyPath = resolved?.originalKeyPath ?? keyPath;\n\n  const remapPrefix = resolved\n    ? { from: resolved.originalPrefix, to: resolved.currentPrefix }\n    : undefined;\n\n  // Remove all the current values except for i18n-duplicate ones\n  revertFields({\n    locale,\n    isDefaultLocale,\n    keyPath,\n    getFieldArgs: { ...getFieldArgs, valueMap: currentValues[locale] },\n    currentValues,\n    reset: true,\n  });\n\n  // Restore the original values, remapping key paths if the item was reordered\n  revertFields({\n    locale,\n    isDefaultLocale,\n    keyPath: originalKeyPath,\n    getFieldArgs: { ...getFieldArgs, valueMap: originalValues[locale] },\n    currentValues,\n    remapPrefix,\n  });\n};\n\n/**\n * Get the key paths of the paired List fields that reverting the given field reverts: the field\n * itself or those nested in it, or every one if all the fields are reverted. See\n * {@link getPairedListKeyPaths}.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {FieldKeyPath} args.keyPath Field key path to revert, or an empty string for every field.\n * @returns {FieldKeyPath[]} Key paths.\n */\nconst getRevertedPairedListKeyPaths = ({ draft, keyPath }) => {\n  if (!keyPath) {\n    return getPairedListKeyPaths(draft.fields);\n  }\n\n  const { currentValues } = draft;\n  const { defaultLocale } = getDraftI18nConfig(draft);\n\n  const fieldConfig = getField(\n    getDraftFieldArgs(draft, { keyPath, valueMap: currentValues[defaultLocale] }),\n  );\n\n  return fieldConfig\n    ? getPairedListKeyPaths([fieldConfig], keyPath.split('.').slice(0, -1).join('.'))\n    : [];\n};\n\n/**\n * Revert the changes made to the given field or all the fields to the default value(s).\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} [args.locale] Target locale, e.g. `ja`. Can be empty if reverting\n * everything.\n * @param {FieldKeyPath} [args.keyPath] Flattened (dot-notated) object keys that will be used for\n * searching the source values. Omit this if copying all the fields. If the triggered field is the\n * List or Object type, this will likely match multiple fields.\n */\nexport const revertChanges = ({ draft, locale: targetLanguage = '', keyPath = '' }) => {\n  const { currentValues, originalLocales, originalPath, originalSlugs } = draft;\n  const { allLocales, defaultLocale } = getDraftI18nConfig(draft);\n  // Reverting one field or one locale only touches values. Reverting everything restores where the\n  // entry goes as well — the folder chosen with the path editor and the slugs, which name the file\n  // or its folder in each locale — and which locales it’s output in, or a move, rename or disabled\n  // locale would survive the revert and still be committed on the next save, which deletes the file\n  // of a locale left disabled\n  const revertsEverything = !targetLanguage && !keyPath;\n\n  if (targetLanguage) {\n    revertLocale({ draft, keyPath, locale: targetLanguage });\n  } else {\n    // Every locale gets its own original values back, including those of the fields holding the\n    // same value in every locale, so nothing is copied from one locale to another. Otherwise a\n    // `sync` field reverted in one locale would overwrite the original value of another locale,\n    // which may differ if the files were edited elsewhere\n    suspendAutoDuplication(() => {\n      allLocales.forEach((locale) => {\n        revertLocale({ draft, keyPath, locale, revertAll: true });\n      });\n    });\n  }\n\n  // The items of a paired List field are added, removed and moved in every locale at once, so\n  // reverting them in the default locale alone would leave them out of line with the other locales.\n  // Each locale gets its own original values back, as above, so a subfield using the `sync`\n  // strategy isn’t copied from another locale over the one just reverted\n  if (targetLanguage === defaultLocale) {\n    suspendAutoDuplication(() => {\n      getRevertedPairedListKeyPaths({ draft, keyPath }).forEach((pairedKeyPath) => {\n        allLocales.forEach((locale) => {\n          if (locale !== defaultLocale && currentValues[locale]) {\n            revertLocale({ draft, keyPath: pairedKeyPath, locale, revertAll: true });\n          }\n        });\n      });\n    });\n  }\n\n  // Keys reverted in the default locale have to reach the other locales, and pairs reverted in\n  // another locale have to line up with the default locale again\n  syncAllDuplicateKeys({\n    valueStore: currentValues,\n    defaultLocale,\n    getFieldArgs: getDraftFieldArgs(draft),\n  });\n\n  if (revertsEverything) {\n    draft.currentLocales = { ...originalLocales };\n    draft.currentPath = originalPath;\n    draft.currentSlugs = { ...originalSlugs };\n  }\n};\n","/**\n * @import {\n * BooleanField,\n * Field,\n * NumberField,\n * StringField,\n * UuidField,\n * VisibleField,\n * } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} FieldInputLabels\n * @property {string | undefined} prefix Text shown right before the input, String field only.\n * @property {string | undefined} suffix Text shown right after the input, String field only.\n * @property {string | undefined} beforeInputLabel Label shown before the input, as Markdown.\n * @property {string | undefined} afterInputLabel Label shown after the input, as Markdown.\n * @property {boolean} hasExtraLabels Whether any of the above is set.\n */\n\n/**\n * Field types that the Translate button in the field header supports: the ones holding text, or\n * subfields that hold text.\n * @type {string[]}\n */\nexport const TRANSLATABLE_FIELD_TYPES = [\n  'richtext',\n  'markdown',\n  'string',\n  'text',\n  'list',\n  'object',\n];\n\n/**\n * Get the extra labels shown around a field’s input. The `prefix` and `suffix` options apply to\n * the String field type only, and the `before_input` and `after_input` options to the Boolean,\n * Number and String field types.\n * @param {Field} fieldConfig Field configuration.\n * @returns {FieldInputLabels} Labels.\n */\nexport const getFieldInputLabels = (fieldConfig) => {\n  const { widget: fieldType = 'string' } = fieldConfig;\n  const allowPrefix = fieldType === 'string';\n  const allowExtraLabels = ['boolean', 'number', 'string'].includes(fieldType);\n  const { prefix, suffix } = allowPrefix ? /** @type {StringField} */ (fieldConfig) : {};\n\n  const { before_input: beforeInputLabel, after_input: afterInputLabel } = allowExtraLabels\n    ? /** @type {BooleanField | NumberField | StringField} */ (fieldConfig)\n    : {};\n\n  return {\n    prefix,\n    suffix,\n    beforeInputLabel,\n    afterInputLabel,\n    hasExtraLabels: !!(prefix || suffix || beforeInputLabel || afterInputLabel),\n  };\n};\n\n/**\n * Get whether a field is hidden from the editor and whether it can’t be edited.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {boolean} args.autoSet Whether the field’s value is set on save, as with the `auto_now`\n * option of a DateTime field or the `auto_increment` option of a Number field.\n * @param {boolean} args.locked Whether the whole entry is shown for reference only, e.g. pending\n * deletion or in a read-only collection.\n * @param {boolean} args.isDuplicated Whether the field’s value follows the default locale.\n * @param {boolean} args.isNew Whether the entry is being created.\n * @param {boolean} [args.parentReadonly] Whether the field belongs to a List or Object field, or a\n * rich text editor component, that can’t be edited, which no subfield can opt out of.\n * @returns {{ hidden: boolean, readonly: boolean, subfieldsReadonly: boolean }} Flags. The last one\n * tells the subfields whether they can’t be edited because of this field. It leaves out whether\n * the value follows the default locale, as a subfield made translatable has a value of its own,\n * and whether the entry is locked, which each subfield works out itself.\n */\nexport const getFieldEditorFlags = ({\n  fieldConfig,\n  autoSet,\n  locked,\n  isDuplicated,\n  isNew,\n  parentReadonly = false,\n}) => {\n  const { widget: fieldType = 'string' } = fieldConfig;\n  const { readonly: readonlyOption } = /** @type {VisibleField} */ (fieldConfig);\n  const isCompute = fieldType === 'compute';\n  const subfieldsReadonly = readonlyOption === true || parentReadonly;\n\n  return {\n    // A field set on save has no meaningful value until the entry is saved for the first time\n    hidden: isCompute || (autoSet && isNew),\n    readonly:\n      // The `readonly` option defaults to `true` for the UUID field type, which can be unlocked,\n      // also with the field type’s own `read_only` option, as in Decap CMS\n      (readonlyOption ??\n        (fieldType === 'uuid' && /** @type {UuidField} */ (fieldConfig).read_only !== false)) ||\n      subfieldsReadonly ||\n      autoSet ||\n      locked ||\n      isDuplicated ||\n      isCompute,\n    subfieldsReadonly,\n  };\n};\n\n/**\n * Get the field configuration passed to a field’s editor. An inline Select or Relation field\n * always shows a dropdown list, as radio buttons wouldn’t fit within a line of text.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {boolean} args.inline Whether the field is rendered inline.\n * @returns {Field} Field configuration, which is the given one unless it has to be changed.\n */\nexport const getEditorFieldConfig = ({ fieldConfig, inline }) => {\n  const { widget: fieldType = 'string' } = fieldConfig;\n\n  return /** @type {Field} */ (\n    inline && ['select', 'relation'].includes(fieldType)\n      ? { ...fieldConfig, dropdown_threshold: 0 }\n      : fieldConfig\n  );\n};\n","/**\n * @import { ResetAction } from '$lib/services/contents/editor/reset';\n */\n\n/**\n * Whether restoring the default values or clearing the fields would change anything.\n * @typedef {{ restore: boolean, clear: boolean }} ResetAvailability\n */\n\n/**\n * State of a menu listing the reset actions, created with {@link createResetMenuState}.\n * @typedef {object} ResetMenuState\n * @property {ResetAvailability} availability Whether each of the costly actions would change\n * anything, as of the last {@link ResetMenuState.update} call.\n * @property {ResetAction} action Action last chosen from the menu, to be confirmed in a dialog.\n * @property {boolean} dialogOpen Whether the confirmation dialog is open. It can be bound to.\n * @property {() => void} update Check the availability again. Call it as the menu opens.\n * @property {(action: ResetAction) => void} select Choose an action, opening the confirmation\n * dialog.\n */\n\n/**\n * Create the state of a menu listing the reset actions: the field options menu, the content options\n * menu of an editor pane or the editor options menu. Checking whether restoring the default values\n * or clearing the fields would change anything takes going through the whole field, locale or\n * entry, so it’s only done as the menu opens rather than on every change. Use it in a component.\n * @param {() => ResetAvailability | undefined} checkAvailability Function checking the\n * availability. It can return `undefined` to leave the availability as it is.\n * @returns {ResetMenuState} State.\n */\nexport const createResetMenuState = (checkAvailability) => {\n  /** @type {ResetAvailability} */\n  let availability = $state({ restore: false, clear: false });\n  /** @type {ResetAction} */\n  let action = $state('revert');\n  let dialogOpen = $state(false);\n\n  return {\n    /**\n     * Availability of the costly actions.\n     * @returns {ResetAvailability} Availability.\n     */\n    get availability() {\n      return availability;\n    },\n    /**\n     * Action last chosen.\n     * @returns {ResetAction} Action.\n     */\n    get action() {\n      return action;\n    },\n    /**\n     * Whether the confirmation dialog is open.\n     * @returns {boolean} Result.\n     */\n    get dialogOpen() {\n      return dialogOpen;\n    },\n    /**\n     * Open or close the confirmation dialog.\n     * @param {boolean} open Whether the dialog is open.\n     */\n    set dialogOpen(open) {\n      dialogOpen = open;\n    },\n    /**\n     * Check the availability again.\n     */\n    update: () => {\n      availability = checkAvailability() ?? availability;\n    },\n    /**\n     * Choose an action, opening the confirmation dialog.\n     * @param {ResetAction} selectedAction Action.\n     */\n    select: (selectedAction) => {\n      action = selectedAction;\n      dialogOpen = true;\n    },\n  };\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Menu, MenuButton, Spacer } from '@sveltia/ui';\n\n  import ErrorBoundary from '$lib/components/common/error-boundary.svelte';\n  import CopyMenuItems from '$lib/components/contents/details/editor/copy-menu-items.svelte';\n  import FieldEditorGroup from '$lib/components/contents/details/editor/field-editor-group.svelte';\n  import ResetMenuItems from '$lib/components/contents/details/editor/reset-menu-items.svelte';\n  import TranslateButton from '$lib/components/contents/details/editor/translate-button.svelte';\n  import ValidationError from '$lib/components/contents/details/editor/validation-error.svelte';\n  import { CustomEditor, editors } from '$lib/components/contents/details/fields';\n  import { customFieldTypeRegistry } from '$lib/services/api/registries';\n  import { isDraftReadonly } from '$lib/services/config/readonly';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { deferDraftWrite } from '$lib/services/contents/draft/update/deferred';\n  import { canResetField, resetField } from '$lib/services/contents/draft/update/reset';\n  import { isFieldChanged, revertChanges } from '$lib/services/contents/draft/update/revert';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import {\n    getFieldEditorContext,\n    isInEditorComponent,\n    setFieldEditorContext,\n  } from '$lib/services/contents/editor/field-context';\n  import {\n    getEditorFieldConfig,\n    getFieldEditorFlags,\n    getFieldInputLabels,\n    TRANSLATABLE_FIELD_TYPES,\n  } from '$lib/services/contents/editor/field-flags';\n  import { getFieldLocaleAccess } from '$lib/services/contents/editor/locale';\n  import { createResetMenuState } from '$lib/services/contents/editor/reset-menu.svelte';\n  import {\n    getCurrentValue,\n    getFieldKind,\n    isFieldMultiple,\n    isFieldRequired,\n  } from '$lib/services/contents/entry/fields';\n  import { isAutoNowField } from '$lib/services/contents/fields/date-time/auto-now';\n  import { isAutoIncrementField } from '$lib/services/contents/fields/number/auto-increment';\n  import { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\n  import { getFieldLabel, getLocalizedOption } from '$lib/services/contents/i18n/options';\n  import { createRawState } from '$lib/services/utils/state.svelte';\n  import { sanitizeHelpText } from '$lib/services/utils/string';\n  import { isPendingDeletion } from '$lib/services/workflow';\n\n  /**\n   * @import { Component } from 'svelte';\n   * @import {\n   * DraftValueStoreKey,\n   * EntryDraft,\n   * FieldContext,\n   * FieldEditorContext,\n   * InternalLocaleCode,\n   * TypedFieldKeyPath,\n   * } from '$lib/types/private';\n   * @import { CustomField, Field, FieldKeyPath } from '$lib/types/public';\n   */\n\n  const parent = getFieldEditorContext();\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   * @property {FieldKeyPath} keyPath Field key path.\n   * @property {TypedFieldKeyPath} typedKeyPath Typed field key path.\n   * @property {Field} fieldConfig Field configuration.\n   * @property {FieldContext} [context] Where the field is rendered.\n   * @property {string} [componentName] Name of the parent rich text editor component, if any.\n   * @property {DraftValueStoreKey} [valueStoreKey] Key to store the values in {@link EntryDraft}.\n   * @property {boolean} [inline] Whether to render only the field’s control, without the label,\n   * the hint or the validation message, to be placed within a line of text, as an editor component\n   * in the `inline` mode does. A Select or Relation field then always shows a dropdown list, as\n   * radio buttons wouldn’t fit.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let {\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldConfig,\n    context: fieldContext = parent.fieldContext ?? undefined,\n    componentName,\n    valueStoreKey = parent.valueStoreKey ?? 'currentValues',\n    inline = false,\n  } = $props();\n\n  const fieldId = $props.id();\n\n  /**\n   * Write a value coming from the widget editor back to the entry draft. Widget editors sync their\n   * local state to this binding from an `$effect`, so the write is deferred; see\n   * {@link deferDraftWrite}.\n   * @param {any} value New value.\n   */\n  const writeValue = (value) => {\n    // Only primitive value fields support two-way binding. Updating an array and object in the\n    // draft store has to be handled in each field editor.\n    /* v8 ignore next 3 */\n    if (typeof value === 'object' && value !== null) {\n      return;\n    }\n\n    const draft = entryDraft.current;\n    const store = valueStoreKey;\n    const _locale = locale;\n    const _keyPath = keyPath;\n\n    deferDraftWrite(() => {\n      /* v8 ignore next 3 -- the editor may have been closed in the meantime */\n      if (draft) {\n        draft[store][_locale][_keyPath] = value;\n      }\n    });\n  };\n\n  /** @type {{ current: Component | undefined }} */\n  const extraHint = createRawState();\n\n  const inEditorComponent = $derived(isInEditorComponent(valueStoreKey));\n  const { widget: fieldType = 'string' } = $derived(fieldConfig);\n  const hint = $derived(getLocalizedOption({ config: fieldConfig, option: 'hint', locale }) ?? '');\n  const required = $derived(isFieldRequired({ fieldConfig, locale }));\n  const multiple = $derived(isFieldMultiple(fieldConfig));\n  const { prefix, suffix, beforeInputLabel, afterInputLabel, hasExtraLabels } = $derived(\n    getFieldInputLabels(fieldConfig),\n  );\n  const isList = $derived(fieldType === 'list' || multiple);\n  const originalValues = $derived(entryDraft.current?.originalValues);\n  const { allLocales } = $derived(getDraftI18nConfig(entryDraft.current));\n  // Without i18n, the only locale is the one being edited, which leaves none\n  const otherLocales = $derived(allLocales.filter((l) => l !== locale));\n  // Only the field’s own values are depended on, so the editor isn’t updated whenever another\n  // field in the entry changes\n  const valueMap = $derived(\n    getFieldValueMapSnapshot(entryDraft.current, locale, keyPath, valueStoreKey),\n  );\n  // Whether the field is shown, and whether it follows the default locale, in this locale\n  const {\n    canTranslate,\n    isDuplicated,\n    areKeysDuplicated,\n    isShown: canEdit,\n  } = $derived(\n    getFieldLocaleAccess({\n      draft: entryDraft.current,\n      fieldConfig,\n      keyPath,\n      locale,\n      valueMap,\n      inEditorComponent,\n    }),\n  );\n  const canCopy = $derived(!inEditorComponent && canTranslate && otherLocales.length);\n  const canRevert = $derived(!inEditorComponent && !isDuplicated);\n  const customFieldType = $derived(customFieldTypeRegistry.get(fieldType));\n  const currentValue = $derived(\n    getCurrentValue({ valueMap, keyPath, isList, isCustomFieldType: !!customFieldType }),\n  );\n  const isRevertDisabled = $derived(\n    !isFieldChanged({\n      currentValueMap: valueMap,\n      originalValueMap: originalValues?.[locale] ?? {},\n      keyPath,\n    }),\n  );\n  const validity = $derived(entryDraft.current?.validities[locale][keyPath]);\n  const fieldLabel = $derived(getFieldLabel({ config: fieldConfig, locale }));\n  // An entry awaiting deletion is shown for reference only. Unlike `readonly`, which is also set\n  // for a duplicated locale, this hides the options that would change the content\n  const pendingDeletion = $derived(isPendingDeletion(entryDraft.current?.originalEntry));\n  // An entry in a read-only collection, or a read-only collection file, is shown for reference only\n  // as well\n  const draftReadonly = $derived(isDraftReadonly(entryDraft.current));\n  const locked = $derived(pendingDeletion || draftReadonly);\n  // A DateTime field with the `auto_now` option is set on save, so it can’t be edited, and it’s\n  // hidden while the entry is being created because it has no meaningful value until then. The\n  // option is ignored in a rich text editor component, whose values aren’t set on save\n  const autoNow = $derived(!inEditorComponent && isAutoNowField(fieldConfig));\n  // A Number field with the `auto_increment` option is numbered on save, the same way. It only\n  // applies to a field holding one value per entry of an entry collection\n  /* v8 ignore start -- The field is only rendered along with a draft, but the draft can be gone\n  while the editor is torn down */\n  const autoIncrement = $derived(\n    !!entryDraft.current &&\n      isAutoIncrementField({\n        fieldConfig,\n        collection: entryDraft.current.collection,\n        isIndexFile: entryDraft.current.isIndexFile,\n        keyPath,\n        inEditorComponent,\n      }),\n  );\n  /* v8 ignore stop */\n  const autoSet = $derived(autoNow || autoIncrement);\n  const { hidden, readonly, subfieldsReadonly } = $derived(\n    getFieldEditorFlags({\n      fieldConfig,\n      autoSet,\n      locked,\n      isDuplicated,\n      isNew: !!entryDraft.current?.isNew,\n      parentReadonly: !!parent.readonly,\n    }),\n  );\n\n  setFieldEditorContext(\n    // svelte-ignore state_referenced_locally\n    /** @type {FieldEditorContext} */ ({\n      fieldContext,\n      parentComponentNames: [...(parent.parentComponentNames ?? []), componentName].filter(Boolean),\n      extraHint,\n      valueStoreKey,\n      /**\n       * Get whether the subfields can’t be edited because this field can’t be.\n       * @returns {boolean} Result.\n       */\n      get readonly() {\n        return subfieldsReadonly;\n      },\n    }),\n  );\n\n  // A field can be restored to its default value or cleared, unless it can’t be edited or its keys\n  // follow the default locale, as with a KeyValue field using the `duplicate_keys` i18n strategy\n  const canReset = $derived(!inEditorComponent && !readonly && !areKeysDuplicated);\n  // The field’s reset actions are taken right away rather than confirmed in a dialog, so only the\n  // availability is used\n  const resetMenu = createResetMenuState(() => {\n    const draft = /** @type {EntryDraft} */ (entryDraft.current);\n    const args = { draft, valueMap, fieldConfig, keyPath, locale };\n\n    return {\n      restore: canResetField({ ...args, restore: true }),\n      clear: canResetField(args),\n    };\n  });\n  const invalid = $derived(validity?.valid === false);\n  const editorFieldConfig = $derived(getEditorFieldConfig({ fieldConfig, inline }));\n  const editorProps = $derived({\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldId,\n    fieldLabel,\n    fieldConfig: editorFieldConfig,\n    readonly,\n    required,\n    invalid,\n  });\n</script>\n\n{#snippet beforeInput()}\n  {#if beforeInputLabel}\n    <div role=\"none\" class=\"before-input\">{@html sanitizeHelpText(beforeInputLabel)}</div>\n  {/if}\n  {#if prefix}\n    <div role=\"none\" class=\"prefix\">{prefix}</div>\n  {/if}\n{/snippet}\n\n{#snippet afterInput()}\n  {#if suffix}\n    <div role=\"none\" class=\"suffix\">{suffix}</div>\n  {/if}\n  {#if afterInputLabel}\n    <div role=\"none\" class=\"after-input\">{@html sanitizeHelpText(afterInputLabel)}</div>\n  {/if}\n{/snippet}\n\n{#if entryDraft.current && canEdit && fieldType !== 'hidden' && inline}\n  <!-- Only the field types with a compact control can be inline, which excludes a custom one; see\n  `isInlineComponentFieldList()` -->\n  {@const Editor = editors[fieldType]}\n  <span\n    role=\"none\"\n    class=\"field inline\"\n    data-field-type={fieldType}\n    data-key-path={keyPath}\n    data-typed-key-path={typedKeyPath}\n  >\n    <!-- The control is labelled with this, as it is with the heading otherwise -->\n    <span id=\"{fieldId}-label\" hidden>{fieldLabel}</span>\n    <ErrorBoundary>\n      <Editor\n        {...editorProps}\n        bind:currentValue={() => currentValue, (value) => writeValue(value)}\n      />\n    </ErrorBoundary>\n  </span>\n{:else if entryDraft.current && canEdit && fieldType !== 'hidden'}\n  <FieldEditorGroup\n    aria-label={_('x_field', { values: { field: fieldLabel } })}\n    data-field-type={fieldType}\n    data-key-path={keyPath}\n    data-typed-key-path={typedKeyPath}\n    {hidden}\n  >\n    <header role=\"none\">\n      <h4 role=\"none\" id=\"{fieldId}-label\">{fieldLabel}</h4>\n      {#if !readonly && required}\n        <span class=\"required\" aria-hidden=\"true\">*</span>\n      {/if}\n      <Spacer flex />\n      {#if canCopy && !draftReadonly && TRANSLATABLE_FIELD_TYPES.includes(fieldType)}\n        <TranslateButton size=\"small\" {locale} {otherLocales} {keyPath} />\n      {/if}\n      <!-- Every option in the menu edits the content, which a read-only entry doesn’t allow -->\n      {#if !draftReadonly && (canCopy || canRevert || canReset)}\n        <MenuButton\n          variant=\"ghost\"\n          size=\"small\"\n          iconic\n          disabled={pendingDeletion}\n          popupPosition=\"bottom-right\"\n          aria-label={_('show_field_options')}\n          onclick={resetMenu.update}\n          onkeydown={resetMenu.update}\n        >\n          {#snippet popup()}\n            <Menu ariaLabel={_('field_options')}>\n              {#if canCopy}\n                <CopyMenuItems {locale} {otherLocales} {keyPath} submenu />\n              {/if}\n              <!-- A field that can be copied from another locale can be reverted as well, so the\n              menu always offers it -->\n              <ResetMenuItems\n                scope=\"field\"\n                separator={!!canCopy}\n                available={{\n                  revert: !isRevertDisabled,\n                  ...(canReset ? resetMenu.availability : {}),\n                }}\n                onSelect={(action) => {\n                  const draft = /** @type {EntryDraft} */ (entryDraft.current);\n\n                  if (action === 'revert') {\n                    revertChanges({ draft, locale, keyPath });\n                  } else {\n                    resetField({\n                      draft,\n                      fieldConfig,\n                      keyPath,\n                      locale,\n                      restore: action === 'restore',\n                    });\n                  }\n                }}\n              />\n            </Menu>\n          {/snippet}\n        </MenuButton>\n      {/if}\n    </header>\n    {#if validity?.valid === false}\n      <ValidationError id=\"{fieldId}-error\">\n        {entryDraft.current?.validationMessages[locale][keyPath]?.join(' ')}\n      </ValidationError>\n    {/if}\n    <div role=\"none\" class=\"field-wrapper\" class:has-extra-labels={hasExtraLabels}>\n      <ErrorBoundary>\n        {#if customFieldType}\n          {@render beforeInput()}\n          <CustomEditor\n            {...{ ...editorProps, fieldConfig: /** @type {CustomField} */ (fieldConfig) }}\n            control={customFieldType.control}\n            {currentValue}\n          />\n          {@render afterInput()}\n        {:else if getFieldKind(fieldConfig) === 'unknown'}\n          <Alert status=\"warning\">\n            {_('unsupported_field_type_x', { values: { name: fieldType } })}\n          </Alert>\n        {:else}\n          {@const Editor = editors[fieldType]}\n          {@render beforeInput()}\n          <Editor\n            {...editorProps}\n            bind:currentValue={() => currentValue, (value) => writeValue(value)}\n          />\n          {@render afterInput()}\n        {/if}\n      </ErrorBoundary>\n    </div>\n    {#if !readonly && (hint || extraHint.current)}\n      {@const ExtraHint = extraHint.current}\n      <div role=\"none\" class=\"footer\">\n        {#if hint}\n          <p class=\"hint\">{@html sanitizeHelpText(hint)}</p>\n        {/if}\n        <ExtraHint {fieldConfig} {locale} {currentValue} />\n      </div>\n    {/if}\n  </FieldEditorGroup>\n{/if}\n\n<style>\n  .field-wrapper {\n    &.has-extra-labels {\n      display: flex;\n      align-items: center;\n      justify-content: flex-start;\n      gap: 4px;\n    }\n\n    :global {\n      :is(input[type='text'], textarea) {\n        width: 100%;\n      }\n\n      /* A native color, date or time input is still styled for a custom field type that renders\n        one. The built-in editors use Sveltia UI components instead, which have the `sui` class and\n        styles of their own, so they’re left out */\n\n      input:is([type='color']:not(.sui), [type='number']) {\n        border-width: 1px;\n        border-color: var(--sui-primary-border-color);\n        border-radius: var(--sui-control-medium-border-radius);\n        height: var(--sui-button-medium-height);\n        color: inherit;\n        background-color: var(--sui-textbox-background-color);\n      }\n\n      input:is([type='file'], [type='checkbox']) {\n        color: inherit;\n      }\n\n      & > div {\n        color: inherit;\n      }\n\n      input:is([type='date'], [type='datetime-local'], [type='time']):not(.sui) {\n        margin: var(--sui-focus-ring-width);\n        border-width: var(--sui-textbox-border-width, 1px);\n        border-color: var(--sui-primary-border-color);\n        border-radius: var(--sui-control-medium-border-radius);\n        padding: var(--sui-textbox-singleline-padding);\n        width: auto;\n        height: var(--sui-textbox-height);\n        color: var(--sui-textbox-foreground-color);\n        background-color: var(--sui-textbox-background-color);\n        font-family: var(--sui-textbox-font-family);\n        font-size: var(--sui-textbox-font-size);\n        text-transform: uppercase;\n\n        &:disabled {\n          opacity: 0.4;\n        }\n      }\n\n      input[aria-invalid='true']:is(\n          [type='color'],\n          [type='date'],\n          [type='datetime-local'],\n          [type='time']\n        ):not(.sui) {\n        border-color: var(--sui-error-border-color);\n      }\n\n      input:read-only {\n        /* Make readonly inputs selectable */\n        -webkit-user-select: text;\n        user-select: text;\n        pointer-events: auto;\n      }\n    }\n  }\n\n  .before-input,\n  .after-input,\n  .prefix,\n  .suffix {\n    color: var(--sui-secondary-foreground-color);\n    white-space: nowrap;\n  }\n\n  .hint {\n    flex: auto;\n    margin-inline: var(--sui-focus-ring-width) !important;\n    margin-block: var(--sui-focus-ring-width) 0 !important;\n    font-size: var(--sui-font-size-small);\n    line-height: var(--sui-line-height-compact);\n    color: var(--sui-tertiary-foreground-color);\n  }\n\n  .footer {\n    display: flex;\n    gap: 16px;\n    justify-content: flex-end;\n    margin-top: 4px;\n  }\n</style>\n","<!--\n  @component\n  Body of an Object field value or a complex List field item: the editors of its subfields when\n  expanded, a summary when collapsed, or a warning when its type isn’t defined.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, TruncatedText, VisibilityObserver } from '@sveltia/ui';\n\n  import Image from '$lib/components/assets/shared/image.svelte';\n  import FieldEditor from '$lib/components/contents/details/editor/field-editor.svelte';\n  import { getLocalizedOption } from '$lib/services/contents/i18n/options';\n  import { env } from '$lib/services/user/env.svelte';\n  import { sanitizeHelpText } from '$lib/services/utils/string';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import {\n   * FieldContext,\n   * InternalLocaleCode,\n   * MediaFieldSource,\n   * TypedFieldKeyPath,\n   * } from '$lib/types/private';\n   * @import { Field, FieldKeyPath, VariableFieldType } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} SubFieldProps\n   * @property {FieldKeyPath} keyPath Key path of the subfield.\n   * @property {TypedFieldKeyPath} typedKeyPath Typed key path of the subfield.\n   * @property {FieldContext} [context] Where the subfield is rendered.\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   * @property {Field[]} subFields Subfields of the value.\n   * @property {(subField: Field) => SubFieldProps} getSubFieldProps Function returning the key\n   * paths and context of a subfield.\n   * @property {boolean} expanded Whether the subfields are shown.\n   * @property {boolean} unknownType Whether the value has a type the field doesn’t define, in which\n   * case nothing can be edited.\n   * @property {() => string} getSummary Function returning the summary shown while collapsed.\n   * @property {() => MediaFieldSource | undefined} getThumbnail Function returning the thumbnail\n   * shown along with the summary.\n   * @property {Snippet} [summaryContent] Content drawn in place of the summary text while\n   * collapsed, e.g. by a custom field type’s summary component.\n   * @property {string} [summaryId] `id` of the summary, so the value can be labelled by it.\n   * @property {VariableFieldType} [typeConfig] Configuration of the value’s variable type, whose\n   * help message is shown above the subfields unless the field is read-only.\n   * @property {boolean} [readonly] Whether the field is read-only.\n   */\n\n  /** @type {Props} */\n  let {\n    locale,\n    subFields,\n    getSubFieldProps,\n    expanded,\n    unknownType,\n    getSummary,\n    getThumbnail,\n    summaryContent = undefined,\n    summaryId = undefined,\n    typeConfig = undefined,\n    readonly = false,\n  } = $props();\n\n  const hint = $derived(\n    readonly || !typeConfig\n      ? undefined\n      : getLocalizedOption({ config: typeConfig, option: 'hint', locale }),\n  );\n</script>\n\n{#if unknownType}\n  <Alert status=\"warning\">{_('unknown_variable_type')}</Alert>\n{:else if expanded}\n  {#if hint}\n    <p class=\"type-hint\">{@html sanitizeHelpText(hint)}</p>\n  {/if}\n  {#each subFields as subField (subField.name)}\n    <VisibilityObserver>\n      <FieldEditor {...getSubFieldProps(subField)} {locale} fieldConfig={subField} />\n    </VisibilityObserver>\n  {/each}\n{:else}\n  <!-- The summary is only worked out while it’s shown, and only if it’s not drawn otherwise -->\n  {@const summary = summaryContent ? '' : getSummary()}\n  {@const thumbnail = getThumbnail()}\n  {#if summaryContent || summary || thumbnail}\n    <div role=\"none\" class=\"summary\" id={summaryId}>\n      {#if thumbnail}\n        <Image asset={thumbnail.asset} src={thumbnail.url} variant=\"icon\" cover />\n      {/if}\n      {#if summaryContent}\n        {@render summaryContent()}\n      {:else}\n        <TruncatedText lines={env.isSmallScreen ? 2 : 1}>\n          {summary}\n        </TruncatedText>\n      {/if}\n    </div>\n  {/if}\n{/if}\n\n<style>\n  /* The warning fills the Object field value or the List field item, which clips its corners */\n  :global(.object-unknown-type) {\n    overflow: hidden;\n\n    :global(.sui.alert) {\n      border-width: 0;\n      border-radius: 0;\n    }\n  }\n\n  .type-hint {\n    margin: 0 !important;\n    padding: 12px var(--field-editor-padding) 0;\n    font-size: var(--sui-font-size-small);\n    line-height: var(--sui-line-height-compact);\n    color: var(--sui-tertiary-foreground-color);\n  }\n\n  .summary {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    padding: 8px;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button } from '@sveltia/ui';\n\n  import ExpandIcon from '$lib/components/common/expand-icon.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [label] Item label.\n   * @property {number} [position] 1-based position of the item in its list, shown before the\n   * label. Omitted for an Object field.\n   * @property {string} controlId `aria-controls` ID.\n   * @property {boolean} expanded Whether the item is expanded.\n   * @property {boolean} [expandable] Whether the item can be expanded and collapsed. If `false`,\n   * the label is displayed without the expander button, as there is nothing to show or hide.\n   * Default: `true`.\n   * @property {() => void} [toggleExpanded] Function to toggle the item.\n   * @property {Snippet | undefined} [centerContent] Center slot content.\n   * @property {Snippet | undefined} [endContent] End slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    label = '',\n    position = undefined,\n    controlId,\n    expanded = $bindable(),\n    expandable = true,\n    toggleExpanded,\n    centerContent = undefined,\n    endContent = undefined,\n  } = $props();\n</script>\n\n{#snippet itemLabel()}\n  {#if position !== undefined}\n    <span role=\"none\" class=\"position\">{position}</span>\n  {/if}\n  {#if label}\n    <span role=\"none\" class=\"type\">{label}</span>\n  {/if}\n{/snippet}\n\n<div role=\"none\" class=\"header\">\n  <div role=\"none\" class=\"start\">\n    {#if expandable}\n      <Button\n        size=\"small\"\n        iconic={!label && position === undefined}\n        aria-label={expanded ? _('collapse') : _('expand')}\n        aria-expanded={expanded}\n        aria-controls={controlId}\n        onclick={() => {\n          expanded = !expanded;\n          toggleExpanded?.();\n        }}\n      >\n        {#snippet startIcon()}\n          <ExpandIcon {expanded} />\n        {/snippet}\n        {@render itemLabel()}\n      </Button>\n    {:else}\n      <span role=\"none\" class=\"label\">\n        {@render itemLabel()}\n      </span>\n    {/if}\n  </div>\n  <div role=\"none\" class=\"center\">\n    {@render centerContent?.()}\n  </div>\n  <div role=\"none\" class=\"end\">\n    {@render endContent?.()}\n  </div>\n</div>\n\n<style>\n  .header {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    height: 28px;\n    background-color: var(--sui-secondary-border-color);\n\n    & > div {\n      display: flex;\n      align-items: center;\n    }\n\n    .start {\n      justify-content: flex-start;\n      width: 40%;\n    }\n\n    .center {\n      justify-content: center;\n      width: 20%;\n    }\n\n    .end {\n      justify-content: flex-end;\n      width: 40%;\n    }\n\n    /* Make the expander button full-width when there is no other content */\n    &:has(.center:empty):has(.end:empty) {\n      .start {\n        width: 100%;\n\n        :global(button) {\n          justify-content: flex-start;\n          padding: var(--sui-button-small-padding);\n          width: -moz-available;\n          width: -webkit-fill-available;\n          width: stretch;\n          aspect-ratio: auto;\n        }\n      }\n\n      .center,\n      .end {\n        display: none;\n      }\n    }\n\n    .label {\n      display: flex;\n      align-items: center;\n      gap: 8px;\n      padding: var(--sui-button-small-padding);\n    }\n\n    .position {\n      min-width: 1.5em;\n      font-size: var(--sui-font-size-small);\n      font-weight: var(--sui-font-weight-bold);\n      font-variant-numeric: tabular-nums;\n      color: var(--sui-secondary-foreground-color);\n      text-align: center;\n    }\n\n    .type {\n      font-size: var(--sui-font-size-small);\n      font-weight: var(--sui-font-weight-bold);\n      color: var(--sui-secondary-foreground-color);\n    }\n  }\n</style>\n","<!--\n  @component\n  Notice shown in place of a removed List field item or Object field, with a button to restore it.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Button, Spacer } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} id `id` attribute of the Restore button, so it can be focused.\n   * @property {boolean} [disabled] Whether to disable the Restore button.\n   * @property {() => void} onRestore Function called when the Restore button is clicked.\n   */\n\n  /** @type {Props} */\n  let { id, disabled = false, onRestore } = $props();\n</script>\n\n<Alert status=\"info\">\n  <span role=\"none\">{_('item_removed')}</span>\n  <Spacer flex />\n  <Button\n    {id}\n    variant=\"secondary\"\n    size=\"small\"\n    label={_('restore')}\n    {disabled}\n    onclick={onRestore}\n  />\n</Alert>\n","import { sleep } from '@sveltia/utils/misc';\n\nimport { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getKeysByPrefix, ITEM_INDEX_SUFFIX_REGEX } from '$lib/services/contents/entry/key-paths';\n\n/**\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, ObjectField, ListField } from '$lib/types/public';\n */\n\n/**\n * Expander state changes accumulated by {@link syncExpanderStates}, waiting to be written to the\n * entry draft, keyed by draft. A draft has no entry when no flush is scheduled for it.\n * @type {WeakMap<EntryDraft, Record<FieldKeyPath, boolean>>}\n */\nconst pendingExpanderStates = new WeakMap();\n\n/**\n * Apply the accumulated expander state changes to the entry draft in one go.\n * @param {EntryDraft} draft Entry draft.\n */\nconst flushExpanderStates = (draft) => {\n  // Always set, because the flush is only scheduled right after the map is created\n  const stateMap = /** @type {Record<FieldKeyPath, boolean>} */ (pendingExpanderStates.get(draft));\n\n  pendingExpanderStates.delete(draft);\n\n  Object.entries(stateMap).forEach(([keyPath, expanded]) => {\n    draft.expanderStates._[keyPath] = expanded;\n  });\n};\n\n/**\n * Get the initial object/list expander state based on the `collapsed` option. If `collapsed` is set\n * to `auto`, it checks if there are any values in the object. Otherwise, it uses the `collapsed`\n * option directly, which defaults to `false` (expanded).\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {string} args.key Key path of the item. For a List field, it’s a key path of the list\n * item, e.g. `authors.0`. For an Object field, it’s a key path of the object with the `#` suffix,\n * e.g. `details#`.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {boolean | 'auto'} [args.collapsed] The `collapsed` option value.\n * @returns {boolean} Whether th expander should be expanded.\n */\nexport const getInitialExpanderState = ({ draft, key, locale, collapsed = false }) => {\n  // A state that is queued but not written yet is still the authoritative one\n  const currentState = pendingExpanderStates.get(draft)?.[key] ?? draft.expanderStates?._[key];\n\n  if (currentState !== undefined) {\n    return currentState;\n  }\n\n  if (collapsed === 'auto') {\n    // This runs for every item of a list as it’s rendered, so the direct children are looked up in\n    // the shared snapshot’s sorted key index, rather than by going through every value of the\n    // draft’s live values each time\n    const valueMap = getValueMapSnapshot(draft, locale);\n    const prefix = `${key.replace(/#$/, '')}.`;\n\n    return !getKeysByPrefix(valueMap, prefix).some(\n      (keyPath) => !keyPath.slice(prefix.length).includes('.') && !!valueMap[keyPath],\n    );\n  }\n\n  return !collapsed;\n};\n\n/**\n * Check whether the object/list expander at the given key path is expanded, which it is until it’s\n * collapsed.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @param {string} key Key path of the expander, e.g. `authors.0` for a list item or `details#` for\n * an Object field or a List field itself.\n * @returns {boolean} Result.\n */\nexport const isExpanded = (draft, key) => draft?.expanderStates?._[key] ?? true;\n\n/**\n * Sync the field object/list expander states between locales.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Record<FieldKeyPath, boolean>} args.stateMap Map of key path and state.\n */\nexport const syncExpanderStates = ({ draft, stateMap }) => {\n  const currentStates = draft.expanderStates?._;\n\n  if (!currentStates) {\n    return;\n  }\n\n  let pendingStates = pendingExpanderStates.get(draft);\n\n  const changes = Object.entries(stateMap).filter(\n    ([keyPath, expanded]) => (pendingStates?.[keyPath] ?? currentStates[keyPath]) !== expanded,\n  );\n\n  // Object/List editors call this as they mount, so revealing n of them — by expanding a field or\n  // merely scrolling — would write to the draft n times in a row. Drop no-op changes, and coalesce\n  // the rest into a single write per tick, which is enough to collapse a whole mount storm into\n  // one update.\n  if (!changes.length) {\n    return;\n  }\n\n  if (!pendingStates) {\n    pendingStates = {};\n    pendingExpanderStates.set(draft, pendingStates);\n    queueMicrotask(() => flushExpanderStates(draft));\n  }\n\n  Object.assign(pendingStates, Object.fromEntries(changes));\n};\n\n/**\n * Get a list of keys for the expander states, given the key path. The returned keys could include\n * nested lists and objects.\n * @param {object} args Partial arguments for {@link getField}.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {FlattenedEntryContent} args.valueMap Object holding current entry values.\n * @param {FieldKeyPath} args.keyPath Key path, e.g. `testimonials.0.authors.2.foo`.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @returns {string[]} Keys, e.g. `['testimonials', 'testimonials.0', 'testimonials.0.authors',\n * 'testimonials.0.authors.2', 'testimonials.0.authors.2.foo']`.\n */\nexport const getExpanderKeys = ({\n  collectionName,\n  fileName,\n  valueMap,\n  keyPath,\n  isIndexFile = false,\n}) => {\n  const keys = new Set();\n  const getFieldArgs = { collectionName, fileName, valueMap, isIndexFile };\n\n  keyPath.split('.').forEach((_keyPart, index, arr) => {\n    const _keyPath = arr.slice(0, index + 1).join('.');\n    const config = getField({ ...getFieldArgs, keyPath: _keyPath });\n    const endingWithNumber = ITEM_INDEX_SUFFIX_REGEX.test(_keyPath);\n\n    if (config?.widget === 'object') {\n      if (endingWithNumber) {\n        keys.add(_keyPath);\n      }\n\n      keys.add(`${_keyPath}#`);\n    } else if (config?.widget === 'list') {\n      keys.add(endingWithNumber ? _keyPath : `${_keyPath}#`);\n    } else if (index > 0) {\n      const parentKeyPath = arr.slice(0, index).join('.');\n      const parentConfig = getField({ ...getFieldArgs, keyPath: parentKeyPath });\n\n      if (\n        parentConfig?.widget === 'object' &&\n        'fields' in /** @type {ObjectField} */ (parentConfig)\n      ) {\n        keys.add(`${parentKeyPath}.${parentConfig.name}#`);\n      }\n\n      // A list item is expanded by its own key: `config` is the subfield of a List field with\n      // `field`, or the resolved type of a List field with `types`, which has no `widget`\n      if (\n        parentConfig?.widget === 'list' &&\n        ('field' in /** @type {ListField} */ (parentConfig) ||\n          'types' in /** @type {ListField} */ (parentConfig))\n      ) {\n        keys.add(_keyPath);\n      }\n    }\n  });\n\n  return [...keys];\n};\n\n/**\n * Expand any invalid fields, including the parent list/object(s).\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n */\nexport const expandInvalidFields = ({ draft }) => {\n  const { collectionName, fileName, currentValues, validities, isIndexFile } = draft;\n  /** @type {Record<FieldKeyPath, boolean>} */\n  const stateMap = {};\n\n  Object.entries(validities ?? {}).forEach(([locale, validityMap]) => {\n    Object.entries(validityMap).forEach(([keyPath, { valid }]) => {\n      if (!valid) {\n        getExpanderKeys({\n          collectionName,\n          fileName,\n          valueMap: currentValues[locale],\n          keyPath,\n          isIndexFile,\n        }).forEach((key) => {\n          stateMap[key] = true;\n        });\n      }\n    });\n  });\n\n  syncExpanderStates({ draft, stateMap });\n};\n\n/**\n * Highlight the corresponding field in the editor by posting a message to the window.\n * @param {object} args Arguments object.\n * @param {InternalLocaleCode} args.locale The locale of the field to highlight.\n * @param {FieldKeyPath} args.keyPath The key path of the field to highlight.\n */\nexport const highlightEditorField = ({ locale, keyPath }) => {\n  window.postMessage(\n    { type: 'highlight-editor-field', payload: { locale, keyPath } },\n    window.location.origin,\n  );\n};\n\n/**\n * Get the last rendered field of the deepest rendered parent of the given field in an edit pane,\n * or the parent field itself if none of its subfields are rendered, e.g. a List field whose\n * collapsed items have none.\n * @param {HTMLElement} pane Edit pane element.\n * @param {FieldKeyPath} keyPath Key path of the field.\n * @returns {HTMLElement | undefined} Field element.\n * @see https://github.com/sveltia/sveltia-cms/issues/1070\n */\nconst getLastRenderedParentField = (pane, keyPath) => {\n  const parts = keyPath.split('.');\n\n  // Deepest parent first, then the root\n  for (let depth = parts.length - 1; depth >= 0; depth -= 1) {\n    const parentKeyPath = parts.slice(0, depth).join('.');\n\n    /** @type {NodeListOf<HTMLElement>} */\n    const fields = pane.querySelectorAll(\n      parentKeyPath\n        ? `.field[data-key-path^=\"${CSS.escape(`${parentKeyPath}.`)}\"]`\n        : '.field[data-key-path]',\n    );\n\n    if (fields.length) {\n      return fields[fields.length - 1];\n    }\n\n    // Moving up to the grandparent would scroll to its last subfield, which may be well past the\n    // field, e.g. a field below the List field the field is in\n    /** @type {HTMLElement | null} */\n    const parentField = parentKeyPath\n      ? pane.querySelector(`.field[data-key-path=\"${CSS.escape(parentKeyPath)}\"]`)\n      : null;\n\n    if (parentField) {\n      return parentField;\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Find the field with the given key path in the edit pane for the given locale. The pane renders\n * fields lazily as they scroll into view, so a field just revealed by expanding its parents may not\n * be rendered yet, especially near the bottom of the pane. In that case, scroll the pane towards\n * the field, to the last rendered field of its deepest rendered parent or to that parent itself,\n * until it’s rendered or no more fields are rendered.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Locale of the edit pane.\n * @param {FieldKeyPath} args.keyPath Key path of the field. The path editor isn’t a field, so it’s\n * marked with a validation key instead of a key path; that’s matched as well.\n * @param {number} [args.maxAttempts] How many times to scroll the pane before giving up.\n * @param {number} [args.interval] How long to wait for fields to render after scrolling, in\n * milliseconds.\n * @returns {Promise<HTMLElement | null>} Field element, or `null` if it couldn’t be found.\n */\nexport const findEditorField = async ({ locale, keyPath, maxAttempts = 20, interval = 100 }) => {\n  const key = CSS.escape(keyPath);\n  const selector = `.field:is([data-key-path=\"${key}\"], [data-validation-key=\"${key}\"])`;\n\n  // Let the expanded parents render first\n  await new Promise((resolve) => {\n    window.requestAnimationFrame(resolve);\n  });\n\n  /** @type {HTMLElement | null} */\n  const pane = document.querySelector(\n    `.content-editor .pane[data-mode=\"edit\"][data-locale=\"${CSS.escape(locale)}\"]`,\n  );\n\n  if (!pane) {\n    return null;\n  }\n\n  /** @type {HTMLElement | undefined} */\n  let previousLastRenderedField;\n\n  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {\n    /** @type {HTMLElement | null} */\n    const field = pane.querySelector(selector);\n\n    if (field || !pane.isConnected) {\n      return field;\n    }\n\n    const lastRenderedField = getLastRenderedParentField(pane, keyPath);\n\n    // Stop if no more fields are rendered after scrolling, e.g. when the field doesn’t exist or is\n    // hidden by a condition\n    if (!lastRenderedField || lastRenderedField === previousLastRenderedField) {\n      return null;\n    }\n\n    previousLastRenderedField = lastRenderedField;\n    lastRenderedField.scrollIntoView({ block: 'center' });\n\n    // eslint-disable-next-line no-await-in-loop\n    await sleep(interval);\n  }\n\n  return pane.querySelector(selector);\n};\n\n/**\n * Reveal the field with the given key path in the edit pane for the given locale: expand its parent\n * List and Object fields, move it into the viewport, and focus any control within it, such as a\n * text input or button.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale of the edit pane.\n * @param {FieldKeyPath} args.keyPath Key path of the field.\n * @param {() => boolean} [args.isOutdated] Function telling whether the request has been\n * superseded by a newer one while the field was being looked up, in which case it’s left alone.\n * @returns {Promise<void>} A promise that resolves once the field has been revealed, or couldn’t\n * be found.\n */\nexport const revealEditorField = async ({ draft, locale, keyPath, isOutdated = () => false }) => {\n  const { collectionName, fileName, currentValues, isIndexFile } = draft;\n\n  const expanderKeys = getExpanderKeys({\n    collectionName,\n    fileName,\n    valueMap: currentValues[locale] ?? {},\n    keyPath,\n    isIndexFile,\n  });\n\n  syncExpanderStates({\n    draft,\n    stateMap: Object.fromEntries(expanderKeys.map((key) => [key, true])),\n  });\n\n  const targetField = await findEditorField({ locale, keyPath });\n\n  // Finding the field can take a while, so leave it to a newer request that came in meanwhile\n  if (!targetField || isOutdated()) {\n    return;\n  }\n\n  // `scrollIntoViewIfNeeded()` is non-standard; Firefox doesn’t have it\n  if (typeof targetField.scrollIntoViewIfNeeded === 'function') {\n    targetField.scrollIntoViewIfNeeded();\n  } else {\n    targetField.scrollIntoView();\n  }\n\n  const widgetWrapper = targetField.querySelector('.field-wrapper');\n\n  /** @type {HTMLElement | null} */ (\n    widgetWrapper?.querySelector('[contenteditable=\"true\"], [tabindex=\"0\"]') ??\n      widgetWrapper?.querySelector('input, textarea, button')\n  )?.focus();\n};\n\n/**\n * Highlight the Edit Pane field that corresponds to an element in a custom preview template, just\n * like clicking a field in the default preview does. The template marks the element with the\n * `data-key-path` attribute, which Scroll Synchronization also uses. A click on the element or\n * anything inside it highlights the field of the innermost marked element, while the Enter key\n * does so only when the marked element itself has the focus, so it doesn’t get in the way of a\n * focused link or form control. The template can opt out by calling `preventDefault()`.\n * @param {object} args Arguments.\n * @param {MouseEvent | KeyboardEvent} args.event `click` or `keydown` event on the preview frame’s\n * document.\n * @param {InternalLocaleCode} args.locale Locale of the Preview Pane.\n * @see https://github.com/sveltia/sveltia-cms/issues/1029\n */\nexport const highlightPreviewTemplateField = ({ event, locale }) => {\n  const isKeyDown = event.type === 'keydown';\n\n  if (\n    event.defaultPrevented ||\n    (isKeyDown && /** @type {KeyboardEvent} */ (event).key !== 'Enter')\n  ) {\n    return;\n  }\n\n  // The target comes from the frame’s realm, so `instanceof Element` can’t be used. A key event\n  // always targets an element, while a click event can be dispatched to the document\n  const { target } = event;\n\n  const element = /** @type {Element | null | undefined} */ (\n    isKeyDown ? target : /** @type {Element} */ (target).closest?.('[data-key-path]')\n  );\n\n  const keyPath = element?.getAttribute('data-key-path');\n\n  if (keyPath) {\n    highlightEditorField({ locale, keyPath });\n  }\n};\n","import { sleep } from '@sveltia/utils/misc';\n\n/**\n * Get the scroll position of another pane that matches the given pane’s scroll position in\n * proportion, when no field can be matched between the panes.\n * @param {object} args Arguments.\n * @param {number} args.scrollTop Scroll position of the pane being scrolled.\n * @param {number} args.scrollHeight Scroll height of the pane being scrolled.\n * @param {number} args.clientHeight Client height of the pane being scrolled.\n * @param {number} args.targetScrollHeight Scroll height of the other pane.\n * @param {number} args.targetClientHeight Client height of the other pane.\n * @returns {number} Scroll position for the other pane.\n */\nexport const getProportionalScrollTop = ({\n  scrollTop,\n  scrollHeight,\n  clientHeight,\n  targetScrollHeight,\n  targetClientHeight,\n}) => {\n  const scrollRange = scrollHeight - clientHeight;\n\n  // The pane being scrolled can’t actually scroll, so there is no proportion to match\n  if (scrollRange <= 0) {\n    return 0;\n  }\n\n  return Math.max(0, targetScrollHeight - targetClientHeight) * (scrollTop / scrollRange);\n};\n\n/**\n * Get the scroll position of another pane that brings the field matching the one at the top of the\n * pane being scrolled to the same place, at the same relative position within the field.\n * @param {object} args Arguments.\n * @param {number} args.y Top of the content area being scrolled, in the viewport.\n * @param {number} args.top Top of the field at the top of the content area, in the viewport.\n * @param {number} args.height Height of that field.\n * @param {number} args.targetTop Top of the matching field in the other pane’s scrollable content:\n * the other pane’s scroll position that would bring it to the top of the pane.\n * @param {number} args.targetHeight Height of the matching field.\n * @returns {number | undefined} Scroll position for the other pane, or `undefined` if the top of\n * the content area isn’t within the field.\n */\nexport const getFieldAlignedScrollTop = ({ y, top, height, targetTop, targetHeight }) => {\n  const ratio = (y - top) / height;\n\n  if (ratio < 0 || ratio > 1) {\n    return undefined;\n  }\n\n  return targetTop + targetHeight * ratio;\n};\n\n/**\n * Find the element in another pane that shows the given field, or the one that shows its nearest\n * parent, e.g. the section for a field that isn’t shown on its own. The default preview renders its\n * fields lazily, and marks the element around each of them with the `data-lazy-key-path` attribute,\n * which Scroll Synchronization and Click-to-Highlight don’t use, so a field not rendered yet falls\n * back to that wrapper rather than its parent or nothing at all. An element that isn’t rendered,\n * e.g. one with `display: none`, can’t be scrolled to, so it’s skipped, and so is a wrapper with\n * neither a placeholder nor the field in it, as the field isn’t shown in the preview.\n * @param {HTMLElement} container Content area of the other pane.\n * @param {string} keyPath Key path of the field.\n * @returns {HTMLElement | undefined} Element, if any.\n */\nexport const findFieldElement = (container, keyPath) => {\n  const parts = keyPath.split('.');\n\n  for (let depth = parts.length; depth > 0; depth -= 1) {\n    const path = CSS.escape(parts.slice(0, depth).join('.'));\n\n    // Prefer the field’s own element to the wrapper around it\n    const element = /** @type {HTMLElement | null} */ (\n      container.querySelector(`[data-key-path=\"${path}\"]`)\n    );\n\n    if (element?.getClientRects().length) {\n      return element;\n    }\n\n    // Prefer the innermost wrapper, e.g. the one around the single subfield of a List item to the\n    // one around the item, which have the same key path. A wrapper around the field’s own element,\n    // which was skipped above, has rendered it already, so it has nothing more to show\n    const wrapper = /** @type {HTMLElement[]} */ ([\n      ...container.querySelectorAll(`[data-lazy-key-path=\"${path}\"]`),\n    ]).findLast(\n      (_wrapper) =>\n        _wrapper.childElementCount &&\n        _wrapper.getClientRects().length &&\n        !(element && _wrapper.contains(element)),\n    );\n\n    if (wrapper) {\n      return wrapper;\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Find the element in another pane that shows the given field, like `findFieldElement()`, in a pane\n * that renders its fields lazily as they scroll into view: the default preview. While only the\n * wrapper of a field or one of its parents is found, scroll the pane to it and look again once the\n * fields that came into view are rendered, until the field is found or scrolling makes no more\n * progress. Scrolling past the placeholders above the field renders them, which moves the field,\n * and a parent renders the wrappers of its subfields in turn, so it can take a few rounds.\n * @param {object} args Arguments.\n * @param {HTMLElement} args.container Content area of the other pane.\n * @param {string} args.keyPath Key path of the field.\n * @param {(element: HTMLElement) => boolean} args.scrollTo Function scrolling the pane to the given\n * element instantly, and telling whether the pane has been scrolled.\n * @param {() => boolean} [args.isOutdated] Function telling whether the request has been superseded\n * by a newer one, in which case the search is abandoned.\n * @param {number} [args.maxAttempts] How many times to scroll the pane before giving up.\n * @param {number} [args.interval] How long to wait for fields to render after scrolling, in\n * milliseconds.\n * @returns {Promise<HTMLElement | undefined>} Element showing the field or, if it couldn’t be\n * rendered, its nearest parent or wrapper. `undefined` if there’s none or the request is outdated.\n * @see https://github.com/sveltia/sveltia-cms/issues/1073\n */\nexport const findLazyFieldElement = async ({\n  container,\n  keyPath,\n  scrollTo,\n  isOutdated = () => false,\n  maxAttempts = 20,\n  interval = 100,\n}) => {\n  /** @type {HTMLElement | undefined} */\n  let previousElement;\n\n  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {\n    const element = findFieldElement(container, keyPath);\n\n    // Only a wrapper renders its content lazily. Any other element found is the field’s own or a\n    // parent that has rendered everything in it, so there’s nothing more to look for\n    if (element?.dataset.lazyKeyPath === undefined) {\n      return element;\n    }\n\n    const scrolled = scrollTo(element);\n\n    // Stop if the pane can’t get any closer to the field, e.g. when it isn’t shown in the preview\n    if (!scrolled && element === previousElement) {\n      return element;\n    }\n\n    previousElement = element;\n\n    // eslint-disable-next-line no-await-in-loop\n    await sleep(interval);\n\n    if (isOutdated()) {\n      return undefined;\n    }\n  }\n\n  return findFieldElement(container, keyPath);\n};\n\n/**\n * Get the scroll position of a pane that reveals the given element: centered in the pane, or\n * aligned to its top if the element is taller than the pane.\n * @param {object} args Arguments.\n * @param {number} args.viewTop Top of the pane’s visible area, in the viewport.\n * @param {number} args.viewHeight Height of the pane’s visible area.\n * @param {number} args.scrollTop Current scroll position of the pane.\n * @param {number} args.top Top of the element, in the viewport.\n * @param {number} args.height Height of the element.\n * @param {boolean} [args.always] Whether to get the position even if the element is already\n * visible.\n * @returns {number | undefined} Scroll position, or `undefined` if the element is already visible:\n * entirely, or partly if it’s taller than the pane.\n */\nexport const getRevealingScrollTop = ({\n  viewTop,\n  viewHeight,\n  scrollTop,\n  top,\n  height,\n  always = false,\n}) => {\n  const offset = top - viewTop;\n  const viewBottom = viewTop + viewHeight;\n  const bottom = top + height;\n\n  if (height > viewHeight) {\n    return !always && bottom > viewTop && top < viewBottom\n      ? undefined\n      : Math.max(0, scrollTop + offset);\n  }\n\n  if (!always && top >= viewTop && bottom <= viewBottom) {\n    return undefined;\n  }\n\n  return Math.max(0, scrollTop + offset - (viewHeight - height) / 2);\n};\n\n/**\n * Get how far down the bottom of a sticky toolbar is in the viewport, so that an item scrolled to\n * can leave room for it, rather than scroll back for it, which shows as a bump. The toolbar sticks\n * below the toolbars of the rich text editors the field is in, if any.\n * @param {HTMLElement | undefined} toolbar Sticky toolbar, if it is rendered.\n * @returns {number} Offset in pixels, or 0 without a toolbar.\n */\nexport const getStickyToolbarBottom = (toolbar) =>\n  toolbar\n    ? Number.parseFloat(getComputedStyle(toolbar).top) + toolbar.getBoundingClientRect().height\n    : 0;\n\n/**\n * Scroll a newly added List field item into view. The fields above it are only rendered once the\n * scroll brings them into view, which can push the item out of view again, so it’s followed until\n * it stays in place. It’s not followed otherwise, as the editor pane doesn’t scroll smoothly, so\n * every scroll shows as a jump, nor once the list is scrolled elsewhere.\n * @param {object} args Arguments.\n * @param {HTMLElement} args.item List item element, whose first child is its header.\n * @param {HTMLElement} args.list Element containing the items.\n * @param {() => boolean} [args.isOutdated] Function telling whether another item has been added\n * since, in which case this one is no longer followed.\n * @param {number} [args.maxAttempts] How many times to scroll to the item at most.\n * @param {number} [args.interval] How long to wait for fields to render after scrolling, in\n * milliseconds.\n */\nexport const scrollToAddedListItem = async ({\n  item,\n  list,\n  isOutdated = () => false,\n  maxAttempts = 5,\n  interval = 100,\n}) => {\n  const header = /** @type {Element} */ (item.firstElementChild);\n  /**\n   * Get the position of the item in the list, which changes as the items above it grow.\n   * @returns {number} Offset in pixels.\n   */\n  const getOffset = () => item.getBoundingClientRect().top - list.getBoundingClientRect().top;\n\n  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {\n    item.scrollIntoView();\n\n    const offset = getOffset();\n\n    // eslint-disable-next-line no-await-in-loop\n    await sleep(interval);\n\n    if (\n      isOutdated() ||\n      getOffset() === offset ||\n      header.getBoundingClientRect().bottom <= window.innerHeight\n    ) {\n      return;\n    }\n  }\n};\n","import { createDisplayBlobURL, getAssetBlob } from '$lib/services/assets/info';\nimport {\n  getRichTextMediaSources,\n  replaceRichTextMediaSources,\n} from '$lib/services/contents/fields/rich-text/previews/media-sources';\n\n/**\n * @import { Asset, AssetFolderInfo, EntryFileMap } from '$lib/types/private';\n * @import { RichTextValueFormat } from '$lib/types/public';\n */\n\n/**\n * Get a copy of the given asset as a file, so it can be uploaded as a new asset.\n * @param {Asset} asset Asset.\n * @returns {Promise<File>} File.\n * @throws {Error} When the blob of the asset cannot be retrieved.\n */\nexport const getAssetFile = async (asset) => {\n  const blob = await getAssetBlob(asset);\n\n  return new File([blob], asset.name, { type: blob.type });\n};\n\n/**\n * Create a function that adds files to an entry as pending uploads, the same as if the user had\n * picked them for a field, so saving the entry writes them alongside it. A file is added once per\n * key, so one referenced more than once, e.g. from another locale or field, shares the blob URL.\n * @param {object} args Arguments.\n * @param {EntryFileMap} args.files Files to be uploaded, where the pending files are added.\n * @param {(file: File, folder: AssetFolderInfo) => Promise<string | undefined>} [args.findExisting]\n * Function to find the blob URL of the file if it’s already pending, so it isn’t added again.\n * @returns {(\n * key: string,\n * getFile: () => Promise<File | undefined>,\n * folder: AssetFolderInfo,\n * ) => Promise<string | undefined>} Function that takes the key of the file, e.g. the asset path\n * it comes from, a function to get the file, and the folder the file is saved to, and returns the\n * blob URL of the pending file, or `undefined` if there’s no file. An error thrown while getting or\n * adding the file is not handled, and the same error is returned for the same key.\n */\nexport const createPendingFileAdder = ({ files, findExisting }) => {\n  /** @type {Map<string, Promise<string | undefined>>} */\n  const copies = new Map();\n\n  return (key, getFile, folder) => {\n    let copy = copies.get(key);\n\n    if (!copy) {\n      copy = (async () => {\n        const file = await getFile();\n\n        if (!file) {\n          return undefined;\n        }\n\n        const existingBlobURL = await findExisting?.(file, folder);\n\n        if (existingBlobURL) {\n          return existingBlobURL;\n        }\n\n        // The file may come from the repository, so its URL must not let an SVG image run script\n        const blobURL = await createDisplayBlobURL(file);\n\n        files[blobURL] = { file, folder, replace: false };\n\n        return blobURL;\n      })();\n\n      copies.set(key, copy);\n    }\n\n    return copy;\n  };\n};\n\n/**\n * Get the asset references in a field value: the value itself for a File or Image field, or the\n * media URLs in a Markdown or HTML body.\n * @param {string} value Field value.\n * @param {RichTextValueFormat} [format] Format of a Markdown or RichText field value.\n * @returns {string[]} References.\n */\nexport const getFieldMediaSources = (value, format) =>\n  format ? getRichTextMediaSources(value, format) : [value];\n\n/**\n * Rewrite the asset references in a field value.\n * @param {object} args Arguments.\n * @param {string} args.value Field value.\n * @param {RichTextValueFormat} [args.format] Format of a Markdown or RichText field value, or\n * `undefined` for a File or Image field value.\n * @param {(src: string) => Promise<string | undefined>} args.rewrite Function to get the new\n * reference for each reference in the value, or `undefined` to leave it as is.\n * @returns {Promise<string | undefined>} New value: the whole value of a Markdown or RichText\n * field, or `undefined` for a File or Image field value that is not rewritten.\n */\nexport const rewriteAssetReferences = async ({ value, format, rewrite }) => {\n  const newSources = new Map(\n    await Promise.all(\n      getFieldMediaSources(value, format).map(\n        async (src) => /** @type {[string, string | undefined]} */ ([src, await rewrite(src)]),\n      ),\n    ),\n  );\n\n  return format ? replaceRichTextMediaSources(value, newSources, format) : newSources.get(value);\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { isRelativePath } from '$lib/services/assets';\nimport { MEDIA_FIELD_TYPES, RICH_TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getTypeSubFields, mapSubValues } from '$lib/services/contents/fields/list/subfields';\nimport { getTypedKeyPath } from '$lib/services/contents/fields/object/helpers';\nimport { getValueFormat } from '$lib/services/contents/fields/rich-text';\n\n/**\n * @import { TypedFieldKeyPath } from '$lib/types/private';\n * @import {\n * ComplexListField,\n * Field,\n * ListFieldWithSubField,\n * ListFieldWithSubFields,\n * ListFieldWithTypes,\n * MarkdownField,\n * RichTextField,\n * RichTextValueFormat,\n * } from '$lib/types/public';\n */\n\n/**\n * Callback for each value that can reference an asset. `format` is the format of a Markdown or\n * RichText field value, and `undefined` for a File or Image field value.\n * @typedef {(args: {\n * value: string,\n * format?: RichTextValueFormat,\n * typedKeyPath: TypedFieldKeyPath,\n * set: (newValue: string) => void,\n * }) => void} AssetValueCallback\n */\n\n/**\n * Find the values that can reference an asset in a field value: the value of a File or Image\n * field, and the body of a Markdown or RichText field. Object and List fields are walked down.\n * @param {object} args Arguments.\n * @param {Record<string, any> | any[]} args.container Object or array holding the value.\n * @param {string | number} args.key Property name or index of the value.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {TypedFieldKeyPath} args.typedKeyPath Typed key path of the field.\n * @param {AssetValueCallback} args.callback Function called for each value.\n */\nconst walkFieldValue = ({ container, key, fieldConfig, typedKeyPath, callback }) => {\n  const value = /** @type {any} */ (container)[key];\n  const { widget: fieldType = 'string' } = fieldConfig;\n  const isRichText = RICH_TEXT_FIELD_TYPES.includes(fieldType);\n\n  if (isRichText || MEDIA_FIELD_TYPES.includes(fieldType)) {\n    /** @type {[Record<string, any> | any[], string | number][]} */\n    const targets =\n      Array.isArray(value) && !isRichText\n        ? value.map((_value, index) => [value, index])\n        : [[container, key]];\n\n    targets.forEach(([_container, _key]) => {\n      const _value = /** @type {any} */ (_container)[_key];\n\n      if (typeof _value === 'string' && _value) {\n        callback({\n          value: _value,\n          format: isRichText\n            ? getValueFormat(/** @type {MarkdownField | RichTextField} */ (fieldConfig))\n            : undefined,\n          typedKeyPath,\n          /**\n           * Replace the value.\n           * @param {string} newValue New value.\n           */\n          set: (newValue) => {\n            /** @type {any} */ (_container)[_key] = newValue;\n          },\n        });\n      }\n    });\n\n    return;\n  }\n\n  const { types, typeKey = 'type' } = /** @type {ListFieldWithTypes} */ (fieldConfig);\n\n  mapSubValues(\n    value,\n    fieldConfig,\n    (obj, fields, index) => {\n      if (isObject(obj)) {\n        // eslint-disable-next-line no-use-before-define\n        walkObject({\n          obj,\n          fields,\n          typedKeyPath: getTypedKeyPath(\n            index === undefined ? typedKeyPath : `${typedKeyPath}.*`,\n            types ? obj[typeKey] : undefined,\n          ),\n          callback,\n        });\n      }\n    },\n    (_item, field, index) => {\n      walkFieldValue({\n        container: value,\n        key: index,\n        fieldConfig: field,\n        typedKeyPath: `${typedKeyPath}.*.${field.name}`,\n        callback,\n      });\n    },\n  );\n};\n\n/**\n * Find the values that can reference an asset in an object. See {@link walkFieldValue}.\n * @param {object} args Arguments.\n * @param {Record<string, any>} args.obj Object.\n * @param {Field[]} args.fields Subfields of the object.\n * @param {TypedFieldKeyPath} args.typedKeyPath Typed key path of the object.\n * @param {AssetValueCallback} args.callback Function called for each value.\n */\nexport const walkObject = ({ obj, fields, typedKeyPath, callback }) => {\n  fields.forEach((fieldConfig) => {\n    const { name } = fieldConfig;\n\n    if (name in obj) {\n      walkFieldValue({\n        container: obj,\n        key: name,\n        fieldConfig,\n        typedKeyPath: `${typedKeyPath}.${name}`,\n        callback,\n      });\n    }\n  });\n};\n\n/**\n * Check if the given asset reference is a path relative to the entry, which has to be rewritten\n * when the item is pasted into another entry. An absolute path, a URL or a blob URL isn’t.\n * @param {string} src Reference.\n * @returns {boolean} Result.\n */\nexport const isEntryRelativeReference = (src) =>\n  isRelativePath(src) && !/^[a-z][a-z\\d+.-]*:/i.test(src);\n\n/**\n * Get the subfields of a list item as an object: those of its variable type, or the single subfield\n * of a list whose items are the subfield values themselves.\n * @param {ComplexListField} fieldConfig Field configuration.\n * @param {string} [type] Variable type name of the item, if the list has variable types.\n * @returns {Field[] | undefined} Subfields, or `undefined` if the list has variable types but no\n * such type.\n */\nexport const getItemSubFields = (fieldConfig, type) => {\n  const { field } = /** @type {ListFieldWithSubField} */ (fieldConfig);\n  const { fields } = /** @type {ListFieldWithSubFields} */ (fieldConfig);\n  const { types } = /** @type {ListFieldWithTypes} */ (fieldConfig);\n\n  if (types) {\n    return getTypeSubFields(types, type);\n  }\n\n  return fields ?? [field];\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { getAssetByPath } from '$lib/services/assets';\nimport { getFieldMediaSources } from '$lib/services/assets/copy';\nimport { getItemList } from '$lib/services/contents/draft/update/list';\nimport { isInternalPropKey } from '$lib/services/contents/fields/internal-props';\nimport {\n  getItemSubFields,\n  isEntryRelativeReference,\n  walkObject,\n} from '$lib/services/contents/fields/list/clipboard/walk';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport { getTypedKeyPath } from '$lib/services/contents/fields/object/helpers';\n\n/**\n * @import {\n * DraftValueStoreKey,\n * EntryDraft,\n * InternalLocaleCode,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import {\n * ComplexListField,\n * FieldKeyPath,\n * ListFieldWithSubField,\n * ListFieldWithTypes,\n * } from '$lib/types/public';\n * @import { AssetValueCallback } from '$lib/services/contents/fields/list/clipboard/walk';\n */\n\n/**\n * Value of the `format` property that marks a list item copied to the clipboard.\n */\nexport const LIST_ITEM_CLIPBOARD_FORMAT = 'sveltia-cms/list-item';\n\n/**\n * Version of the clipboard data format. Data in another version, e.g. copied with a newer release\n * of the CMS, can’t be read.\n */\nconst LIST_ITEM_CLIPBOARD_VERSION = 1;\n\n/**\n * List item copied to the clipboard as JSON, so it can be pasted into any compatible list, in\n * another entry, collection, browser tab or even another site using Sveltia CMS.\n * @typedef {object} ListItemClipboardData\n * @property {typeof LIST_ITEM_CLIPBOARD_FORMAT} format Format marker.\n * @property {number} version Format version.\n * @property {string} id Random ID, which tells whether the clipboard still holds the item copied\n * in this tab, along with the files that can’t go to the clipboard.\n * @property {number} [copiedAt] Time the item was copied, which tells whether the clipboard holds\n * an item copied elsewhere after the one copied in this tab.\n * @property {InternalLocaleCode} locale Locale the item was copied in. Its values are pasted in a\n * locale the item doesn’t have.\n * @property {string} [type] Variable type name of the item, if the list has variable types.\n * @property {Record<InternalLocaleCode, Record<string, any>>} values The item in each locale it was\n * copied from: the item itself, without the variable type property, or, in a list with a single\n * subfield, an object holding the value under the subfield name.\n * @property {Record<InternalLocaleCode, Record<string, string>>} assets Repository paths of the\n * assets referenced with a path relative to the source entry, keyed by the reference, in each\n * locale, so the references can be rewritten for the entry the item is pasted into.\n */\n\n/**\n * Remove the internal properties the CMS adds to list items, e.g. `__sc_item_id`, from a value and\n * the objects nested in it, in place.\n * @param {any} value Value.\n * @returns {any} Value.\n */\nconst removeInternalProps = (value) => {\n  if (Array.isArray(value)) {\n    value.forEach(removeInternalProps);\n  } else if (isObject(value)) {\n    Object.keys(value).forEach((key) => {\n      if (isInternalPropKey(key)) {\n        delete value[key];\n      } else {\n        removeInternalProps(value[key]);\n      }\n    });\n  }\n\n  return value;\n};\n\n/**\n * Create the clipboard data for a list item.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key of the values in the draft.\n * @param {ComplexListField} args.fieldConfig List field configuration.\n * @param {FieldKeyPath} args.keyPath Key path of the list.\n * @param {TypedFieldKeyPath} args.typedKeyPath Typed key path of the list.\n * @param {number} args.index List index of the item.\n * @param {InternalLocaleCode} args.locale Locale the item is copied in.\n * @param {boolean} [args.pairedItems] Whether the items are paired across the locales, in which\n * case the item is copied in every locale.\n * @param {string} [args.componentName] Name of the rich text editor component the list is in, if\n * any, for a field-level asset folder.\n * @returns {{ data: ListItemClipboardData, files: Map<string, File> }} Clipboard data, and the\n * unsaved files the item references, keyed by blob URL.\n */\nexport const createListItemClipboardData = ({\n  draft,\n  valueStoreKey = 'currentValues',\n  fieldConfig,\n  keyPath,\n  typedKeyPath,\n  index,\n  locale,\n  pairedItems = false,\n  componentName,\n}) => {\n  const { originalEntry: entry, collectionName, fileName } = draft;\n  const { hasSingleSubField } = getListFieldInfo(fieldConfig);\n  const { field } = /** @type {ListFieldWithSubField} */ (fieldConfig);\n  const { typeKey = 'type' } = /** @type {ListFieldWithTypes} */ (fieldConfig);\n  const locales = pairedItems ? Object.keys(draft[valueStoreKey]) : [locale];\n\n  /** @type {ListItemClipboardData} */\n  const data = {\n    format: LIST_ITEM_CLIPBOARD_FORMAT,\n    version: LIST_ITEM_CLIPBOARD_VERSION,\n    id: crypto.randomUUID(),\n    copiedAt: Date.now(),\n    locale,\n    values: {},\n    assets: {},\n  };\n\n  /** @type {Map<string, File>} */\n  const files = new Map();\n\n  locales.forEach((_locale) => {\n    const [valueList] = getItemList(draft[valueStoreKey][_locale], keyPath);\n\n    if (!(index in valueList)) {\n      return;\n    }\n\n    const item = removeInternalProps(structuredClone(valueList[index]));\n    /** @type {Record<string, any>} */\n    const value = hasSingleSubField ? { [field.name]: item } : item;\n    /** @type {Record<string, string>} */\n    const assets = {};\n\n    if (!hasSingleSubField && 'types' in fieldConfig) {\n      data.type ??= value[typeKey];\n      delete value[typeKey];\n    }\n\n    walkObject({\n      obj: value,\n      fields: getItemSubFields(fieldConfig, data.type) ?? [],\n      typedKeyPath: getTypedKeyPath(`${typedKeyPath}.*`, data.type),\n      /**\n       * Record the assets an entry-relative reference in the field value points at, and the unsaved\n       * files the value references.\n       * @param {Parameters<AssetValueCallback>[0]} args Arguments.\n       */\n      callback: ({ value: fieldValue, format, typedKeyPath: fieldTypedKeyPath }) => {\n        getFieldMediaSources(fieldValue, format).forEach((src) => {\n          if (src.startsWith('blob:')) {\n            const file = draft.files[src]?.file;\n\n            if (file) {\n              files.set(src, file);\n            }\n\n            return;\n          }\n\n          if (!isEntryRelativeReference(src) || src in assets) {\n            return;\n          }\n\n          const asset = getAssetByPath({\n            value: src,\n            entry,\n            collectionName,\n            fileName,\n            componentName,\n            typedKeyPath: fieldTypedKeyPath,\n            locale: _locale,\n          });\n\n          if (asset) {\n            assets[src] = asset.path;\n          }\n        });\n      },\n    });\n\n    data.values[_locale] = value;\n    data.assets[_locale] = assets;\n  });\n\n  return { data, files };\n};\n\n/**\n * Parse the clipboard text as a copied list item.\n * @param {string} text Clipboard text.\n * @returns {ListItemClipboardData | undefined} Clipboard data, or `undefined` if the text isn’t a\n * copied list item.\n */\nexport const parseListItemClipboardData = (text) => {\n  /** @type {any} */\n  let data;\n\n  try {\n    // The text comes from anywhere, so leave out the internal properties of the CMS, as well as a\n    // prototype that would be set once the values are written to an object\n    data = JSON.parse(text, (key, value) =>\n      key === '__proto__' || isInternalPropKey(key) ? undefined : value,\n    );\n  } catch {\n    return undefined;\n  }\n\n  if (\n    !isObject(data) ||\n    data.format !== LIST_ITEM_CLIPBOARD_FORMAT ||\n    data.version !== LIST_ITEM_CLIPBOARD_VERSION ||\n    typeof data.locale !== 'string' ||\n    (data.copiedAt !== undefined && typeof data.copiedAt !== 'number') ||\n    (data.type !== undefined && typeof data.type !== 'string') ||\n    !isObject(data.values) ||\n    !isObject(data.values[data.locale]) ||\n    !Object.values(data.values).every(isObject) ||\n    (data.assets !== undefined &&\n      !(isObject(data.assets) && Object.values(data.assets).every(isObject)))\n  ) {\n    return undefined;\n  }\n\n  return /** @type {ListItemClipboardData} */ ({ assets: {}, ...data });\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { getDefaultValues } from '$lib/services/contents/draft/defaults';\nimport { isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport {\n  MEDIA_FIELD_TYPES,\n  MULTI_VALUE_FIELD_TYPES,\n  SIMPLE_VALUE_FIELD_TYPES,\n  STRING_VALUE_FIELD_TYPES,\n} from '$lib/services/contents/fields';\nimport { getTypeSubFields } from '$lib/services/contents/fields/list/subfields';\nimport { getNumberFieldValue, parseNumber } from '$lib/services/contents/fields/number/helpers';\nimport { unflattenKeys } from '$lib/services/utils/object';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { Field, NumberField, ObjectField } from '$lib/types/public';\n */\n\n/**\n * Check if a pasted value is a string or a number, which most of the fields take.\n * @param {any} value Value.\n * @returns {boolean} Result.\n */\nconst isStringOrNumber = (value) => typeof value === 'string' || typeof value === 'number';\n\n/**\n * Conform a pasted value to a Number field: a number or text that is one is cast like the editor\n * does with its input, while other text is left out.\n * @param {string | number} value Value.\n * @param {NumberField} fieldConfig Field configuration.\n * @returns {string | number | null | undefined} Conformed value, or `undefined` if the field\n * doesn’t take the value.\n */\nconst conformNumberValue = (value, fieldConfig) => {\n  const number = parseNumber(value);\n\n  return Number.isNaN(number)\n    ? undefined\n    : getNumberFieldValue({ inputValue: number, fieldConfig });\n};\n\n/**\n * Conform a pasted value to a field that doesn’t have subfields. A number is converted to the type\n * the field takes, like `normalizeContent()` does with a value read from a file: a field holding a\n * string, like a String, DateTime or Image field, calls string methods on its value.\n * @param {any} value Value.\n * @param {Field} fieldConfig Field configuration.\n * @returns {any} Conformed value, or `undefined` if the field doesn’t take the value.\n */\nconst conformPrimitiveValue = (value, fieldConfig) => {\n  const { widget: fieldType = 'string' } = fieldConfig;\n\n  if (value === null) {\n    return null;\n  }\n\n  if (fieldType === 'boolean') {\n    return typeof value === 'boolean' ? value : undefined;\n  }\n\n  if (fieldType === 'code') {\n    return typeof value === 'string' || isObject(value) ? value : undefined;\n  }\n\n  if (fieldType === 'keyvalue') {\n    return isObject(value) ? value : undefined;\n  }\n\n  if (\n    !SIMPLE_VALUE_FIELD_TYPES.includes(fieldType) &&\n    !MULTI_VALUE_FIELD_TYPES.includes(fieldType)\n  ) {\n    // Hidden field and custom field types, which can take anything\n    return value;\n  }\n\n  if (!isStringOrNumber(value)) {\n    return undefined;\n  }\n\n  if (fieldType === 'number') {\n    return conformNumberValue(value, /** @type {NumberField} */ (fieldConfig));\n  }\n\n  // A Relation or Select field can hold a number, which an option value can be\n  return STRING_VALUE_FIELD_TYPES.includes(fieldType) || MEDIA_FIELD_TYPES.includes(fieldType)\n    ? String(value)\n    : value;\n};\n\n/**\n * Options for conforming a pasted value to the fields it’s pasted into.\n * @typedef {object} ConformOptions\n * @property {InternalLocaleCode} locale Locale the value is pasted in, for default values.\n * @property {InternalLocaleCode} defaultLocale Default locale of the draft.\n * @property {{ dropped: number }} stats Number of the values left out because the fields they’re\n * pasted into don’t have them, or don’t take them.\n */\n\n/**\n * Conform a pasted value to the field it’s pasted into. See {@link conformObject}.\n * @param {any} value Pasted value.\n * @param {Field} fieldConfig Field configuration.\n * @param {ConformOptions} options Options.\n * @returns {any} Conformed value, or `undefined` if the field doesn’t take the value.\n */\nconst conformValue = (value, fieldConfig, options) => {\n  const { widget: fieldType = 'string' } = fieldConfig;\n\n  if (fieldType === 'object') {\n    return isObject(value)\n      ? // eslint-disable-next-line no-use-before-define\n        conformObjectField(value, /** @type {ObjectField} */ (fieldConfig), options)\n      : undefined;\n  }\n\n  if (fieldType === 'list') {\n    // eslint-disable-next-line no-use-before-define\n    return Array.isArray(value) ? conformList(value, fieldConfig, options) : undefined;\n  }\n\n  if (isFieldMultiple(fieldConfig) && value !== null) {\n    const values = (Array.isArray(value) ? value : [value]).map((v) =>\n      conformPrimitiveValue(v, fieldConfig),\n    );\n\n    return values.includes(undefined) ? undefined : values;\n  }\n\n  // A single value can be taken from a multiple-value field holding one value\n  const _value =\n    MULTI_VALUE_FIELD_TYPES.includes(fieldType) && Array.isArray(value) && value.length === 1\n      ? value[0]\n      : value;\n\n  return conformPrimitiveValue(_value, fieldConfig);\n};\n\n/**\n * Conform a pasted object to the subfields it’s pasted into: a property the subfields don’t have,\n * or don’t take the value of, is left out, while a subfield the object doesn’t have gets its\n * default value.\n * @param {Record<string, any>} obj Pasted object.\n * @param {Field[]} fields Subfields.\n * @param {ConformOptions} options Options.\n * @returns {{ value: Record<string, any>, matched: number }} Conformed object and the number of\n * the properties taken.\n */\nexport const conformObject = (obj, fields, options) => {\n  const { locale, defaultLocale, stats } = options;\n  /** @type {Record<string, any>} */\n  const value = {};\n  let matched = 0;\n\n  fields.forEach((fieldConfig) => {\n    const { name } = fieldConfig;\n\n    if (name in obj) {\n      const conformed = conformValue(obj[name], fieldConfig, options);\n\n      if (conformed !== undefined) {\n        value[name] = conformed;\n        matched += 1;\n\n        return;\n      }\n    }\n\n    const defaults = unflattenKeys(\n      getDefaultValues({ fields: [fieldConfig], locale, defaultLocale }),\n    );\n\n    if (name in defaults) {\n      value[name] = defaults[name];\n    }\n  });\n\n  stats.dropped += Object.keys(obj).length - matched;\n\n  return { value, matched };\n};\n\n/**\n * Conform a pasted Object field value. See {@link conformObject}.\n * @param {Record<string, any>} obj Pasted object.\n * @param {ObjectField} fieldConfig Field configuration.\n * @param {ConformOptions} options Options.\n * @returns {Record<string, any> | undefined} Conformed object, or `undefined` if the field has\n * variable types but not the one of the object.\n */\nconst conformObjectField = (obj, fieldConfig, options) => {\n  const { fields, types, typeKey = 'type' } = /** @type {any} */ (fieldConfig);\n\n  if (!types) {\n    return conformObject(obj, fields ?? [], options).value;\n  }\n\n  const { [typeKey]: type, ...rest } = obj;\n  const typeFields = getTypeSubFields(types, type);\n\n  if (!typeFields) {\n    return undefined;\n  }\n\n  return { ...conformObject(rest, typeFields, options).value, [typeKey]: type };\n};\n\n/**\n * Conform a pasted List field value: an item that doesn’t fit is left out.\n * @param {any[]} list Pasted list.\n * @param {Field} fieldConfig Field configuration.\n * @param {ConformOptions} options Options.\n * @returns {any[]} Conformed list.\n */\nconst conformList = (list, fieldConfig, options) => {\n  const { field, fields, types } = /** @type {any} */ (fieldConfig);\n\n  if (field) {\n    return list.flatMap((item) => {\n      const conformed = conformValue(item, field, options);\n\n      if (conformed === undefined) {\n        options.stats.dropped += 1;\n\n        return [];\n      }\n\n      return [conformed];\n    });\n  }\n\n  if (fields || types) {\n    return list.flatMap((item) => {\n      const conformed = isObject(item)\n        ? conformObjectField(item, /** @type {ObjectField} */ (fieldConfig), options)\n        : undefined;\n\n      if (conformed === undefined) {\n        options.stats.dropped += 1;\n\n        return [];\n      }\n\n      return [conformed];\n    });\n  }\n\n  // A simple list of strings\n  return list.flatMap((item) => {\n    if (!isStringOrNumber(item)) {\n      options.stats.dropped += 1;\n\n      return [];\n    }\n\n    return [String(item)];\n  });\n};\n","import { getAssetByInternalPath } from '$lib/services/assets';\nimport {\n  createPendingFileAdder,\n  getAssetFile,\n  rewriteAssetReferences,\n} from '$lib/services/assets/copy';\nimport { getAssetPublicURL } from '$lib/services/assets/info';\nimport { getFieldAssetFolder } from '$lib/services/contents/fields/file/helpers';\nimport { getExistingBlobURL } from '$lib/services/contents/fields/file/process';\nimport { conformObject } from '$lib/services/contents/fields/list/clipboard/conform';\nimport { getItemSubFields, walkObject } from '$lib/services/contents/fields/list/clipboard/walk';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport { getTypedKeyPath } from '$lib/services/contents/fields/object/helpers';\n\n/**\n * @import {\n * AssetFolderInfo,\n * DraftValueStoreKey,\n * EntryDraft,\n * InternalLocaleCode,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import { ComplexListField, ListFieldWithSubField } from '$lib/types/public';\n * @import { AssetValueCallback } from '$lib/services/contents/fields/list/clipboard/walk';\n * @import { ListItemClipboardData } from '$lib/services/contents/fields/list/clipboard/data';\n */\n\n/**\n * Result of preparing a copied list item to be pasted.\n * @typedef {object} ListItemPasteResult\n * @property {string} [type] Variable type name of the item, if the list has variable types.\n * @property {Record<InternalLocaleCode, any>} items Item to be added in each locale of the draft.\n * @property {number} droppedCount Number of the values left out, as the list doesn’t have the\n * fields or they don’t take the values.\n * @property {number} missingFileCount Number of the files the item references that couldn’t be\n * found, so the references couldn’t be rewritten for the entry.\n */\n\n/**\n * Prepare a copied list item to be pasted into a list: conform the item to the subfields, and\n * rewrite the references to the source entry’s assets, so they keep pointing at the same files. An\n * asset that can’t be referenced from the entry, e.g. one stored beside another entry, is copied\n * and cached in the draft as a pending upload, the same as if the user had picked the file for the\n * field, so saving the entry writes the copy alongside it.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key of the values in the draft.\n * @param {{ data: ListItemClipboardData, files: Map<string, File> }} args.copied Copied item.\n * @param {ComplexListField} args.fieldConfig List field configuration.\n * @param {TypedFieldKeyPath} args.typedKeyPath Typed key path of the list.\n * @param {string} [args.componentName] Name of the rich text editor component the list is in, if\n * any, for a field-level asset folder.\n * @param {boolean} [args.inEditorComponent] Whether the list is in a rich text editor component,\n * whose values live in the document of the locale they’re edited in, so the subfields get their\n * defaults as in the default locale, like a new item.\n * @returns {Promise<ListItemPasteResult | undefined>} Result, or `undefined` if the item doesn’t\n * fit the list.\n */\nexport const prepareListItemPaste = async ({\n  draft,\n  valueStoreKey = 'currentValues',\n  copied: { data, files },\n  fieldConfig,\n  typedKeyPath,\n  componentName,\n  inEditorComponent = false,\n}) => {\n  const { originalEntry: entry, collectionName, fileName, isIndexFile } = draft;\n  const { hasSingleSubField, hasVariableTypes } = getListFieldInfo(fieldConfig);\n  const { field } = /** @type {ListFieldWithSubField} */ (fieldConfig);\n  const type = hasVariableTypes ? data.type : undefined;\n  const fields = getItemSubFields(fieldConfig, type);\n\n  if (!fields) {\n    return undefined;\n  }\n\n  const stats = { dropped: 0 };\n  /**\n   * References that couldn’t be rewritten, as the files can’t be found or copied. A file referenced\n   * in every locale is only counted once.\n   * @type {Set<string>}\n   */\n  const missingFiles = new Set();\n  /** @type {Record<InternalLocaleCode, any>} */\n  const items = {};\n  /** @type {Promise<void>[]} */\n  const tasks = [];\n\n  // Copies are keyed by asset path or blob URL, so an asset referenced more than once, from another\n  // locale or field, is copied once and shares the blob URL. The file may already be pending for\n  // the folder, e.g. if the item was pasted before\n  const addPendingFileOrThrow = createPendingFileAdder({\n    files: draft.files,\n    /**\n     * Find the file among the pending files of the draft.\n     * @param {File} file File.\n     * @param {AssetFolderInfo} folder Folder the file is saved to.\n     * @returns {Promise<string | undefined>} Blob URL.\n     */\n    findExisting: (file, folder) => getExistingBlobURL({ draft, file, folder }),\n  });\n\n  /**\n   * Cache a file in the draft as a pending upload.\n   * @param {string} key Asset path or blob URL the file comes from.\n   * @param {() => Promise<File>} getFile Function to get the file.\n   * @param {AssetFolderInfo} folder Folder the file is saved to.\n   * @returns {Promise<string | undefined>} Blob URL of the pending file, or `undefined` if the file\n   * can’t be retrieved.\n   */\n  const addPendingFile = (key, getFile, folder) =>\n    addPendingFileOrThrow(key, getFile, folder).catch(() => undefined);\n\n  /**\n   * Get the reference to use in place of a copied one.\n   * @param {object} args Arguments.\n   * @param {string} args.src Copied reference.\n   * @param {Record<string, string>} args.assetPaths Repository paths of the copied entry-relative\n   * assets, keyed by reference.\n   * @param {TypedFieldKeyPath} args.fieldTypedKeyPath Typed key path of the field.\n   * @param {InternalLocaleCode} args.locale Locale the reference is pasted in.\n   * @returns {Promise<string | undefined>} New reference, or `undefined` if the reference doesn’t\n   * have to be rewritten or it couldn’t be.\n   */\n  const rewriteReference = async ({ src, assetPaths, fieldTypedKeyPath, locale }) => {\n    const isBlobURL = src.startsWith('blob:');\n    const assetPath = assetPaths[src];\n\n    // A pending file of the draft, or a reference that’s the same anywhere, e.g. an absolute path\n    if ((isBlobURL && src in draft.files) || (!isBlobURL && !assetPath)) {\n      return undefined;\n    }\n\n    /**\n     * Get the folder the field editor puts a newly picked file in, so a copy ends up in the same\n     * place. It’s only looked up when a file has to be copied.\n     * @returns {AssetFolderInfo | undefined} Folder.\n     */\n    const getFolder = () =>\n      getFieldAssetFolder({\n        collectionName,\n        fileName,\n        componentName,\n        typedKeyPath: fieldTypedKeyPath,\n        isIndexFile,\n      });\n\n    if (isBlobURL) {\n      const file = files.get(src);\n      const folder = file ? getFolder() : undefined;\n\n      const blobURL =\n        file && folder ? await addPendingFile(src, async () => file, folder) : undefined;\n\n      if (!blobURL) {\n        missingFiles.add(src);\n      }\n\n      return blobURL;\n    }\n\n    const asset = getAssetByInternalPath(assetPath);\n\n    if (!asset) {\n      missingFiles.add(assetPath);\n\n      return undefined;\n    }\n\n    const publicPath = getAssetPublicURL(asset, {\n      pathOnly: true,\n      allowSpecial: true,\n      entry,\n      locale,\n    });\n\n    if (publicPath !== undefined) {\n      return publicPath === src ? undefined : publicPath;\n    }\n\n    const folder = getFolder();\n\n    const blobURL = folder\n      ? await addPendingFile(assetPath, () => getAssetFile(asset), folder)\n      : undefined;\n\n    if (!blobURL) {\n      missingFiles.add(assetPath);\n    }\n\n    return blobURL;\n  };\n\n  /**\n   * The item conformed to the subfields in each locale of the draft. The item’s own values are\n   * pasted in a locale it doesn’t have.\n   * @type {{ locale: InternalLocaleCode, value: Record<string, any>, assetPaths: Record<string,\n   * string> }[]}\n   */\n  const conformed = [];\n\n  const fits = Object.keys(draft[valueStoreKey]).every((locale, index) => {\n    const sourceLocale = locale in data.values ? locale : data.locale;\n    /** @type {Record<string, any>} */\n    let obj = structuredClone(data.values[sourceLocale]);\n\n    // The values left out are counted once, as the locales have the same fields\n    const options = {\n      locale,\n      defaultLocale: inEditorComponent ? locale : draft.defaultLocale,\n      stats: index ? { dropped: 0 } : stats,\n    };\n\n    // A single value is taken from an item with another subfield name\n    if (hasSingleSubField && !(field.name in obj) && Object.keys(obj).length === 1) {\n      obj = { [field.name]: Object.values(obj)[0] };\n    }\n\n    const { value, matched } = conformObject(obj, fields, options);\n\n    // Nothing in the item fits the list. An item without values, e.g. of a variable type without\n    // subfields, fits any list having the type\n    if (Object.keys(obj).length && !matched) {\n      return false;\n    }\n\n    conformed.push({ locale, value, assetPaths: data.assets[sourceLocale] ?? {} });\n\n    return true;\n  });\n\n  if (!fits) {\n    return undefined;\n  }\n\n  conformed.forEach(({ locale, value, assetPaths }) => {\n    walkObject({\n      obj: value,\n      fields,\n      typedKeyPath: getTypedKeyPath(`${typedKeyPath}.*`, type),\n      /**\n       * Rewrite the asset references in the field value for the entry.\n       * @param {Parameters<AssetValueCallback>[0]} args Arguments.\n       */\n      callback: ({ value: fieldValue, format, typedKeyPath: fieldTypedKeyPath, set }) => {\n        tasks.push(\n          (async () => {\n            const newValue = await rewriteAssetReferences({\n              value: fieldValue,\n              format,\n              /**\n               * Get the new reference for the entry.\n               * @param {string} src Copied reference.\n               * @returns {Promise<string | undefined>} New reference.\n               */\n              rewrite: (src) => rewriteReference({ src, assetPaths, fieldTypedKeyPath, locale }),\n            });\n\n            if (newValue !== undefined) {\n              set(newValue);\n            } else if (!format && fieldValue.startsWith('blob:') && !(fieldValue in draft.files)) {\n              // A pending file that can’t be found any more, e.g. copied in another tab, would be\n              // a broken reference once the entry is saved\n              set('');\n            }\n          })(),\n        );\n      },\n    });\n\n    items[locale] = hasSingleSubField ? value[field.name] : value;\n  });\n\n  await Promise.all(tasks);\n\n  return { type, items, droppedCount: stats.dropped, missingFileCount: missingFiles.size };\n};\n","import {\n  createListItemClipboardData,\n  parseListItemClipboardData,\n} from '$lib/services/contents/fields/list/clipboard/data';\n\n/**\n * @import { ListItemClipboardData } from '$lib/services/contents/fields/list/clipboard/data';\n */\n\n/**\n * Item copied in this tab, along with the unsaved files it references, keyed by blob URL. Those are\n * pending uploads of the source draft, which can’t be put to the clipboard.\n * @type {{ data: ListItemClipboardData, files: Map<string, File> } | undefined}\n */\nlet lastCopied;\n\n/**\n * Copy a list item to the clipboard. The item is also kept in this tab, so it can be pasted even if\n * the clipboard can’t be read, along with the unsaved files it references.\n * @param {Parameters<typeof createListItemClipboardData>[0]} args Arguments.\n * @returns {Promise<boolean>} Whether the item was written to the clipboard as well.\n */\nexport const copyListItem = async (args) => {\n  lastCopied = createListItemClipboardData(args);\n\n  try {\n    await navigator.clipboard.writeText(JSON.stringify(lastCopied.data));\n\n    return true;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Get the list item to be pasted: the one in the clipboard, or the one last copied in this tab if\n * the clipboard can’t be read or holds something else.\n * @returns {Promise<{ data: ListItemClipboardData, files: Map<string, File> } | undefined>} Item\n * and the unsaved files it references, or `undefined` if there’s nothing to paste.\n */\nexport const readListItem = async () => {\n  /** @type {ListItemClipboardData | undefined} */\n  let data;\n\n  try {\n    data = parseListItemClipboardData(await navigator.clipboard.readText());\n  } catch {\n    // Clipboard access denied\n  }\n\n  // An item copied elsewhere is pasted unless it’s older than the one copied here, which the\n  // clipboard doesn’t hold if it couldn’t be written\n  if (\n    data &&\n    data.id !== lastCopied?.data.id &&\n    !(lastCopied && (data.copiedAt ?? 0) < /** @type {number} */ (lastCopied.data.copiedAt))\n  ) {\n    return { data, files: new Map() };\n  }\n\n  return lastCopied;\n};\n\n/**\n * Reset the item last copied in this tab. For testing purposes.\n */\nexport const resetCopiedListItem = () => {\n  lastCopied = undefined;\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport {\n  getRenewedUniqueValue,\n  UNIQUE_VALUE_FIELD_TYPES,\n} from '$lib/services/contents/draft/create/unique-values';\nimport { getDefaultValues } from '$lib/services/contents/draft/defaults';\nimport { getInitialExpanderState } from '$lib/services/contents/editor/fields';\nimport { tagListItems } from '$lib/services/contents/fields/list/helpers';\nimport { getValueSubFields, mapSubValues } from '$lib/services/contents/fields/list/subfields';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { unflattenKeys } from '$lib/services/utils/object';\n\n/**\n * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * VariableFieldType,\n * } from '$lib/types/public';\n */\n\n/**\n * New values given to the fields of a duplicated item, keyed by the field configuration and the\n * source item’s value, serialized as JSON.\n * @typedef {Map<Field, Map<string | undefined, any>>} RenewedValueMap\n */\n\n/**\n * @typedef {object} RenewContext\n * @property {RenewedValueMap} renewedValues New values given to the fields of a duplicated item.\n * @property {InternalLocaleCode} locale Locale code.\n * @property {InternalLocaleCode} defaultLocale Default locale code.\n */\n\n/**\n * Renew the unique values in the given field value of a duplicated list item, so the duplicate\n * doesn’t share them with its source, just like a duplicated entry. See\n * {@link getRenewedUniqueValue}. Object and List fields are walked down, and an object value is\n * modified in place.\n * @param {any} value Field value.\n * @param {Field} fieldConfig Field configuration.\n * @param {RenewContext} context Context.\n * @returns {any} Renewed value.\n */\nconst renewUniqueValue = (value, fieldConfig, context) => {\n  const { widget: fieldType = 'string' } = fieldConfig;\n\n  if (fieldType !== 'object' && fieldType !== 'list') {\n    if (!UNIQUE_VALUE_FIELD_TYPES.includes(fieldType)) {\n      return value;\n    }\n\n    // A value duplicated across the locales gets the same new one in each, while a translatable\n    // one, which differs between the locales, gets one per locale\n    const renewed = getOrCreate(\n      getOrCreate(context.renewedValues, fieldConfig, () => new Map()),\n      JSON.stringify(value),\n      () => getRenewedUniqueValue({ ...context, fieldConfig, keyPath: fieldConfig.name, value }),\n    );\n\n    // An object or array, like a Hidden field’s default, is copied so the locales don’t share it\n    return typeof renewed === 'object' && renewed !== null ? structuredClone(renewed) : renewed;\n  }\n\n  return mapSubValues(\n    value,\n    fieldConfig,\n    (obj, fields) => {\n      if (isObject(obj)) {\n        // eslint-disable-next-line no-use-before-define\n        renewUniqueValues(obj, fields, context);\n      }\n\n      return obj;\n    },\n    (item, field) => renewUniqueValue(item, field, context),\n  );\n};\n\n/**\n * Renew the unique values in the given object, a duplicated list item or an Object field value, in\n * place. See {@link renewUniqueValue}.\n * @param {Record<string, any>} obj Object.\n * @param {Field[]} fields Subfields of the object.\n * @param {RenewContext} context Context.\n */\nconst renewUniqueValues = (obj, fields, context) => {\n  fields.forEach((fieldConfig) => {\n    const { name } = fieldConfig;\n\n    if (name in obj) {\n      obj[name] = renewUniqueValue(obj[name], fieldConfig, context);\n    }\n  });\n};\n\n/**\n * Remove the original key paths of the given duplicated list item and the items of the lists\n * nested in it, in place. A duplicated or pasted item is a new one, so it mustn’t keep the original\n * positions of its source, or a revert would treat it as the source item.\n * @param {any} value Item or a value in it.\n */\nconst removeOriginalKeyPaths = (value) => {\n  if (Array.isArray(value)) {\n    value.forEach(removeOriginalKeyPaths);\n  } else if (isObject(value)) {\n    delete value.__sc_item_original_key_path;\n    Object.values(value).forEach(removeOriginalKeyPaths);\n  }\n};\n\n/**\n * Get the initial expander states of a List field with subfield(s) and its items.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {FieldKeyPath} args.keyPath Key path of the list.\n * @param {number} args.itemCount Number of items in the list.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {boolean | 'auto'} [args.collapsed] The `collapsed` option of the field, which applies to\n * the items.\n * @param {boolean | 'auto'} [args.minimizeCollapsed] The `minimize_collapsed` option of the field,\n * which applies to the list itself. With `auto`, an empty list is expanded.\n * @returns {Record<string, boolean>} Map of key path and state. The list itself is keyed by its key\n * path with the `#` suffix.\n */\nexport const getInitialListExpanderStates = ({\n  draft,\n  keyPath,\n  itemCount,\n  locale,\n  collapsed,\n  minimizeCollapsed = false,\n}) => ({\n  [`${keyPath}#`]: minimizeCollapsed === 'auto' ? !itemCount : !minimizeCollapsed,\n  ...Object.fromEntries(\n    Array.from({ length: itemCount }, (__, index) => {\n      const key = `${keyPath}.${index}`;\n\n      return [key, getInitialExpanderState({ draft, key, locale, collapsed })];\n    }),\n  ),\n});\n\n/**\n * Create an item to be added to a List field with subfield(s): a copy of an existing item or a\n * pasted one, or a new one filled with the default values.\n * @param {object} args Arguments.\n * @param {any[]} args.valueList Current items of the list. Unless the list has a single subfield,\n * the items are tagged with their original key paths in place, as they’re about to shift.\n * @param {FieldKeyPath} args.keyPath Key path of the list.\n * @param {number} [args.dupIndex] List index of the item to be duplicated, if any. If the list has\n * no item there, e.g. in another locale whose items don’t line up with the default locale’s, a new\n * item is created instead.\n * @param {any} [args.sourceItem] Item to be copied instead, e.g. one pasted from the clipboard,\n * conformed to the subfields.\n * @param {Field[]} args.subFields Subfields of the new item, used to fill in the default values.\n * @param {boolean} args.hasSingleSubField Whether the list has a single subfield, in which case the\n * items are the subfield values themselves rather than objects.\n * @param {Field} [args.field] Single subfield of the list, if any.\n * @param {string} [args.type] Variable type name of the new item, if the list has variable types.\n * @param {VariableFieldType[]} [args.types] Variable types of the list, if any, used to find the\n * subfields of a duplicated item.\n * @param {string} args.typeKey Property name holding the variable type name.\n * @param {RenewedValueMap} [args.renewedValues] New unique values given to a duplicated item, such\n * as UUIDs. An item is duplicated in every locale the list is written to, one call each, so pass\n * the same map to all of them: a value duplicated across the locales then gets the same new one in\n * each, while a translatable one, which differs between the locales, gets one per locale.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {InternalLocaleCode} args.defaultLocale Default locale code.\n * @returns {any} New item.\n */\nexport const createListItem = ({\n  valueList,\n  keyPath,\n  dupIndex,\n  sourceItem,\n  subFields,\n  hasSingleSubField,\n  field,\n  type,\n  types,\n  typeKey,\n  renewedValues = new Map(),\n  locale,\n  defaultLocale,\n}) => {\n  const newItem = (() => {\n    const context = { renewedValues, locale, defaultLocale };\n    const isDuplicate = typeof dupIndex === 'number' && dupIndex in valueList;\n\n    if (sourceItem !== undefined || isDuplicate) {\n      const item = structuredClone(isDuplicate ? valueList[dupIndex] : sourceItem);\n\n      removeOriginalKeyPaths(item);\n\n      if (hasSingleSubField && field) {\n        return renewUniqueValue(item, field, context);\n      }\n\n      if (isObject(item)) {\n        renewUniqueValues(\n          item,\n          getValueSubFields({ value: item, fields: types ? undefined : subFields, types, typeKey }),\n          context,\n        );\n      }\n\n      return item;\n    }\n\n    const item = unflattenKeys(getDefaultValues({ fields: subFields, locale, defaultLocale }));\n\n    return hasSingleSubField && field ? item[field.name] : item;\n  })();\n\n  if (type) {\n    newItem[typeKey] = type;\n  }\n\n  if (!hasSingleSubField) {\n    // Add a random ID to the new item to ensure it is unique. This is necessary for the `key`\n    // attribute in the `each` block.\n    newItem.__sc_item_id = crypto.randomUUID();\n\n    // Track original key paths for existing items before they shift due to the insertion\n    tagListItems(valueList, keyPath);\n  }\n\n  return newItem;\n};\n","import { tagListItems } from '$lib/services/contents/fields/list/helpers';\n\n/**\n * @import { ExpanderStateList } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Items of a List field in one locale, along with their expander states, as handed to a list\n * update. Both lists are mutated in place. The expander states are only kept with the default\n * locale, so the list may be empty in the others.\n * @typedef {object} ListMutationTarget\n * @property {any[]} valueList List items.\n * @property {ExpanderStateList} expanderStateList Expander states of the items.\n */\n\n/**\n * Insert an item into the list, or replace the item at the index with it. The new item is expanded.\n * @param {ListMutationTarget} target List items and their expander states.\n * @param {object} args Arguments.\n * @param {number} args.index List index where the item goes.\n * @param {any} args.item New item.\n * @param {boolean} [args.replace] Whether to replace the item at the index.\n */\nexport const insertListItem = (\n  { valueList, expanderStateList },\n  { index, item, replace = false },\n) => {\n  valueList.splice(index, replace ? 1 : 0, item);\n  expanderStateList.splice(index, replace ? 1 : 0, true);\n};\n\n/**\n * Remove the item at the given index from the list.\n * @param {ListMutationTarget} target List items and their expander states.\n * @param {object} args Arguments.\n * @param {number} args.index List index of the item.\n * @param {FieldKeyPath} args.keyPath Key path of the List field.\n * @param {boolean} args.tagItems Whether the items are objects to tag with their original key path\n * and an ID before they shift, to revert the change and tell whether they’re replaced later. A\n * list with a single subfield holds primitive values, which can’t be tagged.\n * @returns {any} Removed item, or `undefined` if there was none at the index.\n */\nexport const removeListItem = ({ valueList, expanderStateList }, { index, keyPath, tagItems }) => {\n  if (tagItems) {\n    tagListItems(valueList, keyPath, { assignIds: true });\n  }\n\n  const [value] = valueList.splice(index, 1);\n\n  expanderStateList.splice(index, 1);\n\n  return value;\n};\n\n/**\n * Put a removed item back at the given index.\n * @param {ListMutationTarget} target List items and their expander states.\n * @param {object} args Arguments.\n * @param {number} args.index List index where the item goes.\n * @param {any} args.item Removed item.\n * @param {boolean} args.expanded Whether the item was expanded.\n * @param {FieldKeyPath} args.keyPath Key path of the List field.\n * @param {boolean} args.tagItems Whether the items are objects to tag with their original key path\n * before they shift.\n */\nexport const restoreListItem = (\n  { valueList, expanderStateList },\n  { index, item, expanded, keyPath, tagItems },\n) => {\n  if (tagItems) {\n    tagListItems(valueList, keyPath);\n  }\n\n  valueList.splice(index, 0, item);\n  expanderStateList.splice(index, 0, expanded);\n};\n\n/**\n * Move an item to another position in the list.\n * @param {ListMutationTarget} target List items and their expander states.\n * @param {object} args Arguments.\n * @param {number} args.from Source index.\n * @param {number} args.to Destination index.\n * @param {FieldKeyPath} args.keyPath Key path of the List field.\n * @param {boolean} args.tagItems Whether the items are objects to tag with their original key path\n * and a unique ID before they’re reordered, so a keyed `each` block keeps following each item\n * rather than its position, and the change can be reverted.\n */\nexport const moveListItem = ({ valueList, expanderStateList }, { from, to, keyPath, tagItems }) => {\n  if (tagItems) {\n    tagListItems(valueList, keyPath, { assignIds: true });\n  }\n\n  valueList.splice(to, 0, ...valueList.splice(from, 1));\n  expanderStateList.splice(to, 0, ...expanderStateList.splice(from, 1));\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { listItemClipboardToast } from '$lib/services/contents/editor';\n\n/**\n * @typedef {typeof listItemClipboardToast.current.status} ListItemClipboardToastStatus\n */\n\n/**\n * Show a notification once a List field item is copied or pasted.\n * @param {ListItemClipboardToastStatus} status Status.\n * @param {string} message Message.\n */\nexport const showListItemClipboardToast = (status, message) => {\n  listItemClipboardToast.current = {\n    id: listItemClipboardToast.current.id + 1,\n    show: true,\n    status,\n    message,\n  };\n};\n\n/**\n * Get the notification to show after a List field item has been pasted. Files missing from the\n * entry take precedence over values left out, as they are the bigger loss.\n * @param {object} result Result of preparing the paste.\n * @param {number} result.droppedCount Number of values that didn’t fit the list and were left out.\n * @param {number} result.missingFileCount Number of referenced files that could not be copied.\n * @returns {{ status: ListItemClipboardToastStatus, message: string } | undefined} Notification, or\n * `undefined` if the item was pasted as it was copied.\n */\nexport const getPastedItemToast = ({ droppedCount, missingFileCount }) => {\n  if (missingFileCount) {\n    return {\n      status: 'warning',\n      message: _('list_item_pasted_without_files', { values: { count: missingFileCount } }),\n    };\n  }\n\n  if (droppedCount) {\n    return {\n      status: 'info',\n      message: _('list_item_pasted_without_values', { values: { count: droppedCount } }),\n    };\n  }\n\n  return undefined;\n};\n","/**\n * @import { RemovedListItem } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Add a removed item to the list of removed items, which are shown in place of the items until\n * they’re restored. The removed items at a later position move up by one along with the items\n * after the removed one, while the new entry goes after the removed items already shown in the same\n * place, as they were before the removed item.\n * @param {RemovedListItem[]} removedItems Removed items, in the order they’re shown.\n * @param {RemovedListItem} removedItem Item just removed, whose `index` is the position it was\n * removed from.\n * @returns {RemovedListItem[]} New list of removed items.\n */\nexport const addRemovedItem = (removedItems, removedItem) => {\n  const { index } = removedItem;\n  const position = removedItems.findIndex((item) => item.index > index);\n\n  const shifted = removedItems.map((item) =>\n    item.index > index ? { ...item, index: item.index - 1 } : item,\n  );\n\n  if (position === -1) {\n    return [...shifted, removedItem];\n  }\n\n  return [...shifted.slice(0, position), removedItem, ...shifted.slice(position)];\n};\n\n/**\n * Update the positions of the removed items once a new item has been added to the list. The removed\n * items after the new one move down by one, while those shown right where it was added stay before\n * it.\n * @param {RemovedListItem[]} removedItems Removed items, in the order they’re shown.\n * @param {number} index Position the new item was added to.\n * @returns {RemovedListItem[]} New list of removed items.\n */\nexport const shiftRemovedItems = (removedItems, index) =>\n  removedItems.map((item) => (item.index > index ? { ...item, index: item.index + 1 } : item));\n\n/**\n * Remove a restored item from the list of removed items. The removed items shown after it move down\n * by one, as the restored item is put back before them.\n * @param {RemovedListItem[]} removedItems Removed items, in the order they’re shown.\n * @param {string} id ID of the restored item.\n * @returns {RemovedListItem[]} New list of removed items.\n */\nexport const dropRestoredItem = (removedItems, id) => {\n  const position = removedItems.findIndex((item) => item.id === id);\n\n  return removedItems\n    .filter((_item, i) => i !== position)\n    .map((item, i) =>\n      position !== -1 && i >= position ? { ...item, index: item.index + 1 } : item,\n    );\n};\n\n/**\n * Get the expander states of the objects and lists nested in a list item, so they can be put back\n * once the item is restored. The item’s own state is restored along with its value.\n * @param {Record<string, boolean>} states Flattened expander states.\n * @param {FieldKeyPath} keyPath Key path of the List field.\n * @param {number} index Item index.\n * @returns {[suffix: string, state: boolean][]} Key path suffixes after the item’s own key path,\n * e.g. `.details#` or `.books.0`, and states.\n */\nexport const getNestedExpanderStates = (states, keyPath, index) => {\n  const prefix = `${keyPath}.${index}`;\n\n  return Object.entries(states)\n    .filter(([key]) => key.startsWith(prefix) && /^[.#]/.test(key.slice(prefix.length)))\n    .map(([key, state]) => [key.slice(prefix.length), state]);\n};\n","import { _ } from '@sveltia/i18n';\nimport { sleep } from '@sveltia/utils/misc';\n\nimport { updateListFieldForLocales } from '$lib/services/contents/draft/update/list';\nimport { isExpanded, syncExpanderStates } from '$lib/services/contents/editor/fields';\nimport {\n  getStickyToolbarBottom,\n  scrollToAddedListItem,\n} from '$lib/services/contents/editor/scroll';\nimport {\n  copyListItem,\n  prepareListItemPaste,\n  readListItem,\n} from '$lib/services/contents/fields/list/clipboard';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport {\n  createListItem,\n  getInitialListExpanderStates,\n} from '$lib/services/contents/fields/list/items';\nimport {\n  insertListItem,\n  moveListItem,\n  removeListItem,\n  restoreListItem,\n} from '$lib/services/contents/fields/list/mutations';\nimport {\n  getPastedItemToast,\n  showListItemClipboardToast,\n} from '$lib/services/contents/fields/list/paste-toast';\nimport { getNestedExpanderStates } from '$lib/services/contents/fields/list/removed-items';\n\n/**\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n * @import {\n * RemovedItemsState,\n * } from '$lib/services/contents/fields/list/removed-items-state.svelte';\n * @import { resolveVariableType } from '$lib/services/contents/fields/object/helpers';\n * @import {\n * DraftValueStoreKey,\n * EntryDraft,\n * ExpanderStateList,\n * InternalLocaleCode,\n * RemovedListItem,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import {\n * ComplexListField,\n * FieldKeyPath,\n * ListFieldWithSubField,\n * ListFieldWithTypes,\n * } from '$lib/types/public';\n */\n\n/**\n * What the actions need to know about the list at the moment they’re run.\n * @typedef {object} ListActionState\n * @property {InternalLocaleCode} locale Locale being edited.\n * @property {FieldKeyPath} keyPath Key path of the list.\n * @property {TypedFieldKeyPath} typedKeyPath Typed key path of the list.\n * @property {ComplexListField} fieldConfig List field configuration.\n * @property {boolean} pairedItems Whether the items are paired across the locales by position.\n */\n\n/**\n * Actions of a List field, created with {@link createListActions}.\n * @typedef {object} ListActions\n * @property {number | undefined} addedItemIndex The index of the item being added.\n * @property {(stateMap: Record<string, boolean>) => void} updateExpanderStates Update the expander\n * states of the list and its items.\n * @property {() => void} initializeExpanderStates Initialize the expander states.\n * @property {(args?: ListItemAddArgs) => Promise<void> | undefined} addItem Add an item.\n * @property {(index: number) => Promise<void> | undefined} copyItem Copy an item to the clipboard.\n * @property {(index: number, options?: { replace?: boolean }) => Promise<void> | undefined\n * } pasteItem Paste a copied item.\n * @property {(index: number) => Promise<void> | undefined} removeItem Remove an item.\n * @property {(removedItem: RemovedListItem) => Promise<void> | undefined} restoreItem Restore a\n * removed item.\n * @property {(from: number, to: number) => void} moveItem Move an item to another position.\n */\n\n/**\n * Arguments for adding an item to a List field.\n * @typedef {object} ListItemAddArgs\n * @property {number} [index] List index where a new item will be inserted.\n * @property {number} [dupIndex] List index of an item to be duplicated.\n * @property {string} [type] Variable type name. If the field doesn’t have variable types, it will\n * be `undefined`.\n * @property {Record<InternalLocaleCode, any>} [sourceItems] Pasted item in each locale.\n * @property {boolean} [replace] Whether to replace the item at the index with the new one.\n */\n\n/**\n * Time to wait for a change to the list to be rendered, in milliseconds.\n */\nexport const LIST_RENDER_DELAY = 50;\n\n/**\n * Create the actions of a List field with subfield(s): the changes made to the items, along with\n * the expander states and the focus that go with them. Use it in a component.\n * @param {object} args Arguments.\n * @param {EntryDraftState} args.entryDraft Entry draft state.\n * @param {string} args.fieldId ID of the field, which the IDs of its elements are based on.\n * @param {DraftValueStoreKey} args.valueStoreKey Key of the values in the draft.\n * @param {string} [args.componentName] Name of the rich text editor component the list is in, if\n * any.\n * @param {boolean} args.inEditorComponent Whether the list is in a rich text editor component.\n * @param {RemovedItemsState} args.removedItems State of the removed items.\n * @param {(type?: string) => ReturnType<typeof resolveVariableType>} args.resolveType Resolve the\n * type of an item.\n * @param {() => ListActionState} args.getListState Get the current state of the list.\n * @param {() => number} args.getItemCount Get the number of items in the list. Separate from the\n * state, as the items take assembling once they’ve changed, and few actions need the count.\n * @param {() => HTMLElement | undefined} args.getListElement Get the list element.\n * @param {() => HTMLElement | undefined} args.getTopToolbar Get the top toolbar element.\n * @returns {ListActions} Actions.\n */\nexport const createListActions = ({\n  entryDraft,\n  fieldId,\n  valueStoreKey,\n  componentName,\n  inEditorComponent,\n  removedItems,\n  resolveType,\n  getListState,\n  getItemCount,\n  getListElement,\n  getTopToolbar,\n}) => {\n  /**\n   * The index of the item being added, which is rendered right away rather than once it comes into\n   * view, so it can be scrolled into view and focused at once.\n   * @type {number | undefined}\n   */\n  let addedItemIndex = $state();\n  /**\n   * The item added last, which is followed until it stays in view.\n   * @type {HTMLElement | undefined}\n   */\n  let latestAddedItem;\n\n  /**\n   * Wrap an action to run it with the draft. The controls are disabled once the draft is gone, so\n   * the action is only left out in a race with the editor closing.\n   * @template {any[]} A\n   * @template R\n   * @param {(draft: EntryDraft, ...args: A) => R} action Action.\n   * @returns {(...args: A) => R | undefined} Wrapped action.\n   */\n  const withDraft =\n    (action) =>\n    (...args) => {\n      const draft = entryDraft.current;\n\n      return draft ? action(draft, ...args) : undefined;\n    };\n\n  /**\n   * Update the items in every locale they’re changed in.\n   * @param {EntryDraft} draft Entry draft.\n   * @param {(arg: {\n   * valueList: any[], expanderStateList: ExpanderStateList, locale: InternalLocaleCode\n   * }) => void} manipulate See {@link updateListFieldForLocales}.\n   */\n  const updateItems = (draft, manipulate) => {\n    const { locale, keyPath, fieldConfig, pairedItems } = getListState();\n\n    updateListFieldForLocales({\n      draft,\n      locale,\n      i18n: fieldConfig.i18n,\n      pairedItems,\n      valueStoreKey,\n      keyPath,\n      /**\n       * Update the items in a locale, and remember the outcome for the removed items.\n       * @param {Parameters<typeof manipulate>[0]} args Arguments.\n       */\n      manipulate: (args) => {\n        manipulate(args);\n        removedItems.remember(args.valueList, args.locale);\n      },\n    });\n  };\n\n  /**\n   * Get the options the mutations of an existing item share. The items are tagged to tell whether\n   * they’re replaced later. See `expectedListState` in the removed items state.\n   * @returns {{ keyPath: FieldKeyPath, tagItems: boolean }} Options.\n   */\n  const getMutationOptions = () => {\n    const { keyPath, fieldConfig } = getListState();\n\n    return { keyPath, tagItems: !getListFieldInfo(fieldConfig).hasSingleSubField };\n  };\n\n  /**\n   * Get the list item element at the specified index.\n   * @param {number} index Target index.\n   * @returns {HTMLElement | null | undefined} List item element.\n   */\n  const getItem = (index) =>\n    /** @type {HTMLElement | null | undefined} */ (\n      getListElement()?.children[index]?.querySelector('.item')\n    );\n\n  const updateExpanderStates = withDraft(\n    /**\n     * Update the expander states of the list and its items.\n     * @param {EntryDraft} draft Entry draft.\n     * @param {Record<string, boolean>} stateMap Map of key path and state.\n     */\n    (draft, stateMap) => {\n      syncExpanderStates({ draft, stateMap });\n    },\n  );\n\n  const initializeExpanderStates = withDraft(\n    /**\n     * Initialize the expander states of the list and its items.\n     * @param {EntryDraft} draft Entry draft.\n     */\n    (draft) => {\n      const { locale, keyPath, fieldConfig } = getListState();\n      const { collapsed, minimize_collapsed: minimizeCollapsed = false } = fieldConfig;\n\n      syncExpanderStates({\n        draft,\n        stateMap: getInitialListExpanderStates({\n          draft,\n          keyPath,\n          itemCount: getItemCount(),\n          locale,\n          collapsed,\n          minimizeCollapsed,\n        }),\n      });\n    },\n  );\n\n  /**\n   * Scroll a newly added item into view and move focus to it.\n   * @param {number} index List index of the item.\n   */\n  const revealAddedItem = async (index) => {\n    await sleep(LIST_RENDER_DELAY);\n    addedItemIndex = undefined;\n\n    const item = getItem(index);\n\n    // The item is rendered right away, so this is only a race with the editor closing\n    if (!item) {\n      return;\n    }\n\n    // Leave room for the sticky toolbar, which sticks below the toolbars of the rich text editors\n    // the field is in, if any, rather than scroll back for it, which shows as a bump\n    const toolbarBottom = getStickyToolbarBottom(getTopToolbar());\n\n    latestAddedItem = item;\n    item.style.scrollMarginTop = `${toolbarBottom}px`;\n    // Move focus to the expander button, without scrolling for it\n    item.querySelector('button')?.focus({ preventScroll: true });\n    await scrollToAddedListItem({\n      item,\n      list: /** @type {HTMLElement} */ (getListElement()),\n      /**\n       * Tell whether another item has been added since.\n       * @returns {boolean} Result.\n       */\n      isOutdated: () => item !== latestAddedItem,\n    });\n  };\n\n  const addItem = withDraft(\n    /**\n     * Add a new subfield to the list.\n     * @param {EntryDraft} draft Entry draft.\n     * @param {ListItemAddArgs} [args] Arguments.\n     */\n    async (draft, { index: targetIndex, dupIndex, type, sourceItems, replace = false } = {}) => {\n      const { keyPath, fieldConfig } = getListState();\n      const { hasSingleSubField } = getListFieldInfo(fieldConfig);\n      const { add_to_top: addToTop = false } = fieldConfig;\n      const { field } = /** @type {ListFieldWithSubField} */ (fieldConfig);\n      const { types, typeKey = 'type' } = /** @type {ListFieldWithTypes} */ (fieldConfig);\n      const index = targetIndex ?? (addToTop ? 0 : getItemCount());\n      // Shared by the locales, so a duplicated unique value that is the same in each, like a UUID,\n      // gets the same new one\n      /** @type {Map<any, any>} */\n      // eslint-disable-next-line svelte/prefer-svelte-reactivity\n      const renewedValues = new Map();\n\n      addedItemIndex = index;\n\n      // A replaced item keeps its position, so the removed items shown around it stay where they\n      // are\n      if (!replace) {\n        removedItems.shift(index);\n      }\n\n      updateItems(draft, ({ valueList, expanderStateList, locale: targetLocale }) => {\n        const { subFields } = resolveType(type);\n\n        const newItem = createListItem({\n          valueList,\n          keyPath,\n          dupIndex,\n          sourceItem: sourceItems?.[targetLocale],\n          subFields,\n          hasSingleSubField,\n          field,\n          type,\n          types,\n          typeKey,\n          renewedValues,\n          locale: targetLocale,\n          defaultLocale: inEditorComponent ? targetLocale : draft.defaultLocale,\n        });\n\n        insertListItem({ valueList, expanderStateList }, { index, item: newItem, replace });\n      });\n\n      // Expand the parent if it is collapsed to show the newly added item\n      syncExpanderStates({ draft, stateMap: { [`${keyPath}#`]: true } });\n\n      await revealAddedItem(index);\n    },\n  );\n\n  const copyItem = withDraft(\n    /**\n     * Copy an item to the clipboard, so it can be pasted into this list or another one that takes\n     * it, in any entry.\n     * @param {EntryDraft} draft Entry draft.\n     * @param {number} index List index of the item.\n     */\n    async (draft, index) => {\n      const { locale, keyPath, typedKeyPath, fieldConfig, pairedItems } = getListState();\n\n      await copyListItem({\n        draft,\n        valueStoreKey,\n        fieldConfig,\n        keyPath,\n        typedKeyPath,\n        index,\n        locale,\n        pairedItems,\n        componentName,\n      });\n\n      showListItemClipboardToast('success', _('list_item_copied'));\n    },\n  );\n\n  const pasteItem = withDraft(\n    /**\n     * Paste a copied item into the list. The values that don’t fit the list are left out, and the\n     * references to the files the item uses are rewritten for the entry.\n     * @param {EntryDraft} draft Entry draft.\n     * @param {number} index List index where the item will be inserted.\n     * @param {object} [options] Options.\n     * @param {boolean} [options.replace] Whether to replace the item at the index.\n     */\n    async (draft, index, { replace = false } = {}) => {\n      const copied = await readListItem();\n\n      if (!copied) {\n        showListItemClipboardToast('info', _('no_list_item_to_paste'));\n\n        return;\n      }\n\n      const { typedKeyPath, fieldConfig } = getListState();\n\n      const result = await prepareListItemPaste({\n        draft,\n        valueStoreKey,\n        copied,\n        fieldConfig,\n        typedKeyPath,\n        componentName,\n        inEditorComponent,\n      });\n\n      // Another entry may have been opened while the files were being copied\n      if (entryDraft.current !== draft) {\n        return;\n      }\n\n      if (!result) {\n        showListItemClipboardToast('error', _('list_item_not_compatible'));\n\n        return;\n      }\n\n      const { type, items: sourceItems, droppedCount, missingFileCount } = result;\n\n      await addItem({ index, type, sourceItems, replace });\n\n      const toast = getPastedItemToast({ droppedCount, missingFileCount });\n\n      if (toast) {\n        showListItemClipboardToast(toast.status, toast.message);\n      }\n    },\n  );\n\n  const removeItem = withDraft(\n    /**\n     * Remove a subfield.\n     * @param {EntryDraft} draft Entry draft.\n     * @param {number} index Target index.\n     */\n    async (draft, index) => {\n      const options = getMutationOptions();\n      const { keyPath } = options;\n      const id = crypto.randomUUID();\n      /** @type {RemovedListItem['values']} */\n      const values = {};\n\n      removedItems.add({\n        id,\n        index,\n        values,\n        expanded: isExpanded(draft, `${keyPath}.${index}`),\n        nestedExpanderStates: getNestedExpanderStates(draft.expanderStates._, keyPath, index),\n      });\n\n      updateItems(draft, ({ valueList, expanderStateList, locale: targetLocale }) => {\n        const value = removeListItem({ valueList, expanderStateList }, { ...options, index });\n\n        // Keep the value, so the item can be restored\n        if (value !== undefined) {\n          values[targetLocale] = value;\n        }\n      });\n\n      await sleep(LIST_RENDER_DELAY);\n      // Move focus to the Restore button shown in place of the item, to restore it right away\n      document.getElementById(`list-${fieldId}-restore-${id}`)?.focus();\n    },\n  );\n\n  const restoreItem = withDraft(\n    /**\n     * Restore a removed item to the position it’s shown at.\n     * @param {EntryDraft} draft Entry draft.\n     * @param {RemovedListItem} removedItem Removed item.\n     */\n    async (draft, { id, index, values, expanded, nestedExpanderStates }) => {\n      const options = getMutationOptions();\n      const { keyPath } = options;\n\n      removedItems.drop(id);\n\n      updateItems(draft, ({ valueList, expanderStateList, locale: targetLocale }) => {\n        if (targetLocale in values) {\n          restoreListItem(\n            { valueList, expanderStateList },\n            { ...options, index, item: values[targetLocale], expanded },\n          );\n        }\n      });\n\n      // Put back the expander states of the objects and lists nested in the item\n      syncExpanderStates({\n        draft,\n        stateMap: Object.fromEntries(\n          nestedExpanderStates.map(([suffix, state]) => [`${keyPath}.${index}${suffix}`, state]),\n        ),\n      });\n\n      await sleep(LIST_RENDER_DELAY);\n      // Move focus to the expander button of the restored item\n      getItem(index)?.querySelector('button')?.focus();\n    },\n  );\n\n  const moveItem = withDraft(\n    /**\n     * Move a subfield to another position in the list.\n     * @param {EntryDraft} draft Entry draft.\n     * @param {number} from Source index.\n     * @param {number} to Destination index.\n     */\n    (draft, from, to) => {\n      const options = getMutationOptions();\n\n      updateItems(draft, ({ valueList, expanderStateList }) => {\n        moveListItem({ valueList, expanderStateList }, { ...options, from, to });\n      });\n    },\n  );\n\n  return {\n    /**\n     * The index of the item being added.\n     * @returns {number | undefined} Index.\n     */\n    get addedItemIndex() {\n      return addedItemIndex;\n    },\n    updateExpanderStates,\n    initializeExpanderStates,\n    addItem,\n    copyItem,\n    pasteItem,\n    removeItem,\n    restoreItem,\n    moveItem,\n  };\n};\n","import equal from 'fast-deep-equal';\n\nimport { getListItemKey } from '$lib/services/contents/fields/list/helpers';\nimport {\n  addRemovedItem,\n  dropRestoredItem,\n  shiftRemovedItems,\n} from '$lib/services/contents/fields/list/removed-items';\n\n/**\n * @import { InternalLocaleCode, RemovedListItem } from '$lib/types/private';\n */\n\n/**\n * State of the items removed from a List field, created with {@link createRemovedItemsState}.\n * @typedef {object} RemovedItemsState\n * @property {RemovedListItem[]} shown The removed items to show, unless they’re out of place.\n * @property {Map<number, RemovedListItem[]>} byIndex The removed items to show, grouped by the\n * position they’re shown at.\n * @property {(valueList: any[], targetLocale: InternalLocaleCode) => void} remember Remember the\n * item keys of the list in the locale being edited, once it’s been manipulated here.\n * @property {(removedItem: RemovedListItem) => void} add Add an item that has just been removed.\n * @property {(id: string) => void} drop Drop an item that has just been restored.\n * @property {(index: number) => void} shift Move the removed items along with the items after the\n * one just added at the position.\n */\n\n/**\n * Create the state of the items removed from a List field since the editor was opened, which are\n * shown in their place with a button to restore them. Use it in a component.\n * @param {object} args Arguments.\n * @param {() => InternalLocaleCode} args.getLocale Get the locale being edited.\n * @param {() => (string | number)[]} args.getItemKeys Get the current keys of the list items.\n * @returns {RemovedItemsState} State.\n */\nexport const createRemovedItemsState = ({ getLocale, getItemKeys }) => {\n  /**\n   * Items removed since the editor was opened, which are shown in their place with a button to\n   * restore them.\n   * @type {RemovedListItem[]}\n   */\n  let removedItems = $state.raw([]);\n  /**\n   * Locale and item keys after the last item was removed, restored or added here, to tell whether\n   * the editor has since been switched to another locale, or the list changed elsewhere, e.g.\n   * reverted, which leaves the removed items out of place. The object items are given an ID as one\n   * is removed, so a revert, which brings back the original items without the IDs, changes the keys\n   * even if the item count stays the same.\n   * @type {{ locale: InternalLocaleCode, keys: (string | number)[] } | undefined}\n   */\n  let expectedListState = $state.raw();\n\n  /** The removed items to show, unless they’re out of place. */\n  const shown = $derived(\n    expectedListState?.locale === getLocale() && equal(expectedListState.keys, getItemKeys())\n      ? removedItems\n      : [],\n  );\n\n  /** The removed items grouped by the position they’re shown at. */\n  const byIndex = $derived(Map.groupBy(shown, ({ index }) => index));\n\n  return {\n    /**\n     * The removed items to show.\n     * @returns {RemovedListItem[]} Items.\n     */\n    get shown() {\n      return shown;\n    },\n    /**\n     * The removed items to show, grouped by position.\n     * @returns {Map<number, RemovedListItem[]>} Map.\n     */\n    get byIndex() {\n      return byIndex;\n    },\n    /**\n     * Remember the item keys of the list once it’s been manipulated here.\n     * @param {any[]} valueList Manipulated list.\n     * @param {InternalLocaleCode} targetLocale Locale the list is for.\n     */\n    remember: (valueList, targetLocale) => {\n      const locale = getLocale();\n\n      if (targetLocale === locale) {\n        expectedListState = {\n          locale,\n          keys: valueList.map((_item, index) => getListItemKey(valueList, index)),\n        };\n      }\n    },\n    /**\n     * Add an item that has just been removed.\n     * @param {RemovedListItem} removedItem Item.\n     */\n    add: (removedItem) => {\n      removedItems = addRemovedItem(shown, removedItem);\n    },\n    /**\n     * Drop an item that has just been restored.\n     * @param {string} id ID of the item.\n     */\n    drop: (id) => {\n      removedItems = dropRestoredItem(shown, id);\n    },\n    /**\n     * Move the removed items along with the items after the one just added.\n     * @param {number} index Position the new item was added to.\n     */\n    shift: (index) => {\n      removedItems = shiftRemovedItems(shown, index);\n    },\n  };\n};\n","import {\n  canCreateThumbnail,\n  getMediaKindFromPath,\n  getMediaKindFromType,\n} from '$lib/services/assets/kinds';\nimport { getMediaFieldSource } from '$lib/services/assets/media-field';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { MEDIA_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getTypedKeyPath } from '$lib/services/contents/fields/object/helpers';\nimport { isMultiple } from '$lib/services/integrations/media-libraries/multiple';\n\n/**\n * @import {\n * Entry,\n * EntryDraft,\n * EntryFileMap,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * MediaFieldSource,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, MediaField } from '$lib/types/public';\n */\n\n/**\n * Get the thumbnail of a collapsed Object field or List field item, which is the file held by the\n * subfield named with the `thumbnail` option.\n * @param {object} args Arguments.\n * @param {string} [args.thumbnailFieldName] The `thumbnail` option: the name of a subfield, or the\n * key path of a nested one like `mobile.src`, optionally prefixed with `fields.` like a summary\n * template tag.\n * @param {FieldKeyPath} args.keyPath Key path of the object, e.g. `hero` or `gallery.0`, or an\n * empty string if the subfields are at the top level of {@link args.valueMap}, as with the values\n * of a rich text editor component.\n * @param {TypedFieldKeyPath} args.typedKeyPath Typed key path of the object, e.g. `hero`,\n * `gallery.*` or `sections.*<hero>`, used to find a field-level media folder, or an empty string\n * along with an empty `keyPath`.\n * @param {boolean} [args.hasSingleSubField] Whether the object is an item of a List field with the\n * `field` option, whose value is stored at the item key path itself rather than under the subfield\n * name.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} [args.componentName] Custom editor component name, if the object is part of a\n * rich text editor component.\n * @param {FlattenedEntryContent} args.valueMap Entry content.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @param {Entry} [args.entry] Entry being edited, used to locate an asset from a relative path.\n * @param {EntryFileMap} [args.files] Files uploaded in the draft but not saved yet, keyed by the\n * blob URL the field holds meanwhile.\n * @param {InternalLocaleCode} [args.locale] Locale being edited, which an entry-relative path is\n * relative to. Default: the default locale.\n * @returns {MediaFieldSource | undefined} The file to preview, or `undefined` if the option is not\n * set, the subfield is not an Image/File field, it’s empty, or the file has no thumbnail.\n */\nexport const getObjectThumbnail = ({\n  thumbnailFieldName,\n  keyPath,\n  typedKeyPath,\n  hasSingleSubField = false,\n  collectionName,\n  fileName,\n  componentName,\n  valueMap,\n  isIndexFile = false,\n  entry,\n  files,\n  locale,\n}) => {\n  if (!thumbnailFieldName) {\n    return undefined;\n  }\n\n  const [subFieldName, ...nestedFieldNames] = stripFieldTagPrefix(thumbnailFieldName).split('.');\n  const getFieldArgs = { collectionName, fileName, componentName, valueMap, isIndexFile };\n\n  // The single subfield of a list item is stored at the item key path itself, so the option has to\n  // name that subfield, which `getField()` traverses into on its own\n  if (hasSingleSubField && getField({ ...getFieldArgs, keyPath })?.name !== subFieldName) {\n    return undefined;\n  }\n\n  const fieldNames = hasSingleSubField ? nestedFieldNames : [subFieldName, ...nestedFieldNames];\n  const fieldKeyPath = [keyPath, ...fieldNames].filter(Boolean).join('.');\n\n  // The typed key path names the single subfield all the same, like `gallery.*.photo`, which the\n  // config parser registers a field-level media folder under\n  const fieldTypedKeyPath = [typedKeyPath, subFieldName, ...nestedFieldNames]\n    .filter(Boolean)\n    .join('.');\n\n  const fieldConfig = getField({ ...getFieldArgs, keyPath: fieldKeyPath });\n  const { widget: fieldType = 'string' } = fieldConfig ?? {};\n\n  if (!fieldConfig || !MEDIA_FIELD_TYPES.includes(fieldType)) {\n    return undefined;\n  }\n\n  const mediaFieldConfig = /** @type {MediaField} */ (fieldConfig);\n  // A field holding several files is previewed with the first one\n  const value = valueMap[isMultiple(mediaFieldConfig) ? `${fieldKeyPath}.0` : fieldKeyPath];\n\n  if (typeof value !== 'string' || !value) {\n    return undefined;\n  }\n\n  const source = getMediaFieldSource({\n    value,\n    entry,\n    collectionName,\n    fileName,\n    componentName,\n    fieldConfig: mediaFieldConfig,\n    typedKeyPath: fieldTypedKeyPath,\n    locale,\n  });\n\n  if (!source) {\n    return undefined;\n  }\n\n  const { asset, url } = source;\n\n  // A File field can hold anything, but only some files have a thumbnail generated\n  if (asset) {\n    return canCreateThumbnail(asset) ? source : undefined;\n  }\n\n  // A file elsewhere is shown as it is, so it has to be an image: a file uploaded in the draft is\n  // held as a blob URL until it’s saved, and its type is known; an external one has an extension\n  const kind = /** @type {string} */ (url).startsWith('blob:')\n    ? getMediaKindFromType(files?.[/** @type {string} */ (url)]?.file.type ?? '')\n    : getMediaKindFromPath(/** @type {string} */ (url));\n\n  return kind === 'image' ? source : undefined;\n};\n\n/**\n * Get the thumbnail of a collapsed Object field or List field item in the entry editor, with the\n * collection, entry and files taken from the draft.\n * @param {object} args Arguments.\n * @param {EntryDraft | null | undefined} args.draft Entry draft.\n * @param {string} [args.thumbnailFieldName] The `thumbnail` option.\n * @param {FieldKeyPath} args.keyPath Key path of the object.\n * @param {TypedFieldKeyPath} args.typedKeyPath Typed key path of the object, without its type.\n * @param {string} [args.type] Type of the object, if the field has variable types.\n * @param {boolean} [args.hasSingleSubField] Whether the object is an item of a List field with the\n * `field` option.\n * @param {string} [args.componentName] Custom editor component name, if the object is part of a\n * rich text editor component.\n * @param {FlattenedEntryContent} args.valueMap Entry content.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @returns {MediaFieldSource | undefined} The file to preview, if any.\n * @see {@link getObjectThumbnail}\n */\nexport const getDraftObjectThumbnail = ({ draft, typedKeyPath, type, ...args }) =>\n  getObjectThumbnail({\n    ...args,\n    typedKeyPath: getTypedKeyPath(typedKeyPath, type),\n    collectionName: draft?.collectionName ?? '',\n    fileName: draft?.fileName,\n    isIndexFile: !!draft?.isIndexFile,\n    entry: draft?.originalEntry,\n    files: draft?.files,\n  });\n","<!--\n  @component\n  Implement the editor for a List field with subfield(s).\n  @see https://decapcms.org/docs/widgets/#List\n  @see https://decapcms.org/docs/variable-type-widgets/\n  @see https://sveltiacms.app/en/docs/fields/list\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { VisibilityObserver } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import { onMount } from 'svelte';\n  import { flip } from 'svelte/animate';\n\n  import RemoveButton from '$lib/components/common/remove-button.svelte';\n  import ReorderControls from '$lib/components/common/reorder-controls.svelte';\n  import CustomPreview from '$lib/components/contents/details/fields/custom/custom-preview.svelte';\n  import ListItemMenu from '$lib/components/contents/details/fields/list/list-item-menu.svelte';\n  import ListToolbar from '$lib/components/contents/details/fields/list/list-toolbar.svelte';\n  import ObjectBody from '$lib/components/contents/details/fields/object/object-body.svelte';\n  import ObjectHeader from '$lib/components/contents/details/fields/object/object-header.svelte';\n  import RemovedItemNotice from '$lib/components/contents/details/fields/object/removed-item-notice.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import {\n    getFieldEditorContext,\n    isInEditorComponent,\n  } from '$lib/services/contents/editor/field-context';\n  import { isExpanded } from '$lib/services/contents/editor/fields';\n  import { getMemoizedSubtree } from '$lib/services/contents/entry/subtree';\n  import { getCustomFieldSummary } from '$lib/services/contents/fields/custom/preview';\n  import {\n    createListActions,\n    LIST_RENDER_DELAY,\n  } from '$lib/services/contents/fields/list/actions.svelte';\n  import {\n    formatSummary,\n    getListFieldInfo,\n    getListItemKey,\n    isPairedList,\n    isSingleItemList,\n  } from '$lib/services/contents/fields/list/helpers';\n  import { createRemovedItemsState } from '$lib/services/contents/fields/list/removed-items-state.svelte';\n  import {\n    getTypedSubKeyPath,\n    resolveVariableType,\n    warnUnknownType,\n  } from '$lib/services/contents/fields/object/helpers';\n  import { getDraftObjectThumbnail } from '$lib/services/contents/fields/object/thumbnail';\n  import { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\n  import { getFieldLabel, getLocalizedOption } from '$lib/services/contents/i18n/options';\n  import { isSyncedField } from '$lib/services/contents/i18n/shared-values';\n  import { createDragSorter } from '$lib/services/utils/drag-sorting.svelte';\n  import { createStableDerivedState } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { SubtreeMemo } from '$lib/services/contents/entry/subtree';\n   * @import {\n   * FieldEditorProps,\n   * FlattenedEntryContent,\n   * MediaFieldSource,\n   * } from '$lib/types/private';\n   * @import {\n   * ComplexListField,\n   * CustomField,\n   * CustomFieldSummary,\n   * ListFieldWithSubField,\n   * ListFieldWithSubFields,\n   * ListFieldWithTypes,\n   * } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ComplexListField} fieldConfig Field configuration.\n   * @property {Record<string, any>[]} currentValue Field value.\n   * @property {string} [summaryId] ID for the item count, which labels the list.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const { valueStoreKey = 'currentValues', parentComponentNames = [] } = getFieldEditorContext();\n  const componentName = parentComponentNames.at(-1);\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldConfig,\n    required = true,\n    readonly = false,\n    summaryId,\n  } = $props();\n\n  const fieldId = $props.id();\n\n  const {\n    name: fieldName,\n    i18n,\n    // Field type-specific options\n    allow_add: allowAdd = true,\n    allow_remove: allowRemove = true,\n    allow_duplicate: allowDuplicate = true,\n    allow_reorder: allowReorder = true,\n    summary,\n    thumbnail: thumbnailFieldName,\n    max = Infinity,\n    add_to_top: addToTop = false,\n  } = $derived(/** @type {ComplexListField} */ (fieldConfig));\n  const label = $derived(getLocalizedOption({ config: fieldConfig, option: 'label', locale }));\n  const labelSingular = $derived(\n    getLocalizedOption({ config: fieldConfig, option: 'label_singular', locale }),\n  );\n  const { field } = $derived(/** @type {ListFieldWithSubField} */ (fieldConfig));\n  const { fields } = $derived(/** @type {ListFieldWithSubFields} */ (fieldConfig));\n  const { types, typeKey = 'type' } = $derived(/** @type {ListFieldWithTypes} */ (fieldConfig));\n  const { hasSingleSubField, hasVariableTypes } = $derived(getListFieldInfo(fieldConfig));\n  /* v8 ignore start -- a list has either types, subfields or a single subfield */\n  /** The types of a list with variable types. */\n  const variableTypes = $derived(types ?? []);\n  /** The subfields of an item in a list without variable types. */\n  const singleSubFields = $derived(fields ?? (field ? [field] : []));\n  /* v8 ignore stop */\n  /** The summary component of the single subfield’s custom field type, if any. */\n  const customSummary = $derived(hasSingleSubField ? getCustomFieldSummary(field) : undefined);\n\n  /**\n   * Resolve the type of an item, along with the subfields and the summary template for it.\n   * @param {string | undefined} type Type name, if any.\n   * @returns {ReturnType<typeof resolveVariableType>} Resolved type.\n   */\n  const resolveType = (type) =>\n    resolveVariableType({\n      types: hasVariableTypes ? variableTypes : undefined,\n      fields: singleSubFields,\n      summary,\n      type,\n    });\n\n  /* v8 ignore start -- the editor is only rendered while the draft is there */\n  const isIndexFile = $derived(!!entryDraft.current?.isIndexFile);\n  const collectionName = $derived(entryDraft.current?.collectionName ?? '');\n  /* v8 ignore stop */\n  const fileName = $derived(entryDraft.current?.fileName);\n  const defaultLocale = $derived(entryDraft.current?.defaultLocale);\n  // A rich text editor component’s values live in the document of the locale they’re edited in,\n  // so its items can be added in any locale, with the subfields getting their defaults there\n  const inEditorComponent = isInEditorComponent(valueStoreKey);\n  // The items of a translatable list with a duplicated subfield are paired across the locales by\n  // their position, so they’re added, removed and moved in the default locale for every locale\n  const pairedItems = $derived(!inEditorComponent && isPairedList(fieldConfig));\n  // The items can’t be added, removed or reordered in a read-only field, which includes a field\n  // duplicated from the default locale, whether with its own `duplicate` strategy or along with an\n  // ancestor’s, in another locale. Changing them there would change the default locale as well. The\n  // same goes for paired items, which would no longer line up with those of the default locale\n  const isLocked = $derived(\n    readonly || (locale !== defaultLocale && (i18n === 'duplicate' || pairedItems)),\n  );\n  const valueMap = $derived(\n    getFieldValueMapSnapshot(entryDraft.current, locale, keyPath, valueStoreKey),\n  );\n  // A list using the `sync` i18n strategy, with its own option or along with an ancestor, is kept\n  // the same in every locale while it can be edited in any of them, subfields included\n  const synced = $derived(\n    !inEditorComponent &&\n      locale !== defaultLocale &&\n      isSyncedField({\n        fieldConfig,\n        getFieldArgs: { collectionName, fileName, isIndexFile, keyPath, valueMap },\n      }),\n  );\n  const parentExpandedKeyPath = $derived(`${keyPath}#`);\n  /**\n   * What the items were last assembled from, so they’re only assembled again once they’ve changed.\n   * A plain object, as it’s only a memo.\n   * @type {SubtreeMemo}\n   */\n  const itemsMemo = {};\n  /** @type {Record<string, any>[]} */\n  const items = $derived(getMemoizedSubtree(itemsMemo, valueMap, keyPath) ?? []);\n  // A list limited to one item is shown like an Object field: no item count, list toggle or reorder\n  // controls, and no way to remove the item if it’s required. A list with variable types keeps the\n  // Remove button though, as that’s the only way to choose another type for the item\n  const singleItem = $derived(isSingleItemList({ fieldConfig, itemCount: items.length }));\n  const canRemoveItem = $derived(allowRemove && !(singleItem && required && !hasVariableTypes));\n  // The single item can’t be collapsed along with the list, as there is no toggle to expand it\n  const parentExpanded = $derived(\n    singleItem || isExpanded(entryDraft.current, parentExpandedKeyPath),\n  );\n  const itemExpanderStates = $derived(\n    items.map((_item, index) => {\n      const key = `${keyPath}.${index}`;\n\n      return /** @type {[string, boolean]} */ ([key, isExpanded(entryDraft.current, key)]);\n    }),\n  );\n  /**\n   * The key of each item. The items are rebuilt whenever any of their values changes, e.g. on every\n   * keystroke in an item, while the keys only change when an item is added, removed or moved.\n   * Reading them through this keeps the keyed `each` block below from running again, which with its\n   * `animate:` directive would measure the position of every item and force a layout each time.\n   */\n  const itemKeys = createStableDerivedState(() =>\n    items.map((_item, index) => getListItemKey(items, index)),\n  );\n  const hasMaxItems = $derived(items.length >= max);\n  /** The subfields of every item, regardless of its type. */\n  const allSubFields = $derived(\n    hasVariableTypes\n      ? variableTypes.flatMap(({ fields: typeFields = [] }) => typeFields)\n      : singleSubFields,\n  );\n  const hasEditableSubFields = $derived(\n    locale === defaultLocale ||\n      inEditorComponent ||\n      synced ||\n      allSubFields.some(({ i18n: subI18n }) => isFieldTranslatable(subI18n)),\n  );\n  const isAddDisabled = $derived(isLocked || !hasEditableSubFields);\n  const showReorderControls = $derived(allowReorder && !singleItem);\n  const isReorderDisabled = $derived(isLocked || items.length < 2);\n\n  /* eslint-disable jsdoc/require-jsdoc */\n  const removedItems = createRemovedItemsState({\n    getLocale: () => locale,\n    getItemKeys: () => itemKeys.current,\n  });\n  /* eslint-enable jsdoc/require-jsdoc */\n\n  /**\n   * @type {HTMLElement | undefined}\n   */\n  let itemList = $state();\n  /**\n   * @type {HTMLElement | undefined}\n   */\n  let topToolbar = $state();\n  /* eslint-disable jsdoc/require-jsdoc */\n  const listActions = createListActions({\n    entryDraft,\n    fieldId,\n    valueStoreKey,\n    componentName,\n    inEditorComponent,\n    removedItems,\n    resolveType,\n    getListState: () => ({\n      locale,\n      keyPath,\n      typedKeyPath,\n      fieldConfig,\n      pairedItems,\n    }),\n    getItemCount: () => items.length,\n    getListElement: () => itemList,\n    getTopToolbar: () => topToolbar,\n  });\n  /* eslint-enable jsdoc/require-jsdoc */\n\n  const {\n    updateExpanderStates,\n    initializeExpanderStates,\n    addItem,\n    copyItem,\n    pasteItem,\n    removeItem,\n    restoreItem,\n    moveItem,\n  } = listActions;\n\n  /**\n   * Get the values to summarize a list item with. Called from the item’s markup, this only depends\n   * on the item’s own values, so typing in one item doesn’t make every collapsed item work out its\n   * summary and thumbnail again; a summary only ever reads the values of its item.\n   * @param {number} index List index.\n   * @returns {FlattenedEntryContent} Entry values.\n   */\n  const getItemValueMap = (index) =>\n    getFieldValueMapSnapshot(entryDraft.current, locale, `${keyPath}.${index}`, valueStoreKey);\n\n  /**\n   * Format the summary template.\n   * @param {number} index List index.\n   * @param {string} [summaryTemplate] Summary template, e.g. `{{fields.slug}}`.\n   * @param {FlattenedEntryContent} [itemValueMap] Entry values to read the item’s values from.\n   * Defaults to those of the whole list.\n   * @returns {string} Formatted summary.\n   */\n  const _formatSummary = (index, summaryTemplate, itemValueMap = valueMap) =>\n    formatSummary({\n      collectionName,\n      fileName,\n      keyPath,\n      valueMap: itemValueMap,\n      locale,\n      summaryTemplate,\n      hasSingleSubField,\n      index,\n      isIndexFile,\n    });\n\n  const sorter = createDragSorter({\n    /**\n     * Get the number of items in the list.\n     * @returns {number} Item count.\n     */\n    getItemCount: () => items.length,\n    /**\n     * Get the list element.\n     * @returns {HTMLElement | undefined} Element.\n     */\n    getListElement: () => itemList,\n    onMove: moveItem,\n    /**\n     * Get the summary of an item, to be attached to its drag.\n     * @param {number} index List index.\n     * @returns {string} Summary.\n     */\n    getItemData: (index) =>\n      _formatSummary(\n        index,\n        resolveType(hasVariableTypes ? items[index][typeKey] : undefined).summaryTemplate,\n      ),\n    /**\n     * Wait for the moved item to be rendered in its new position.\n     * @returns {Promise<void>} Promise.\n     */\n    settle: () => sleep(LIST_RENDER_DELAY),\n    /**\n     * Get the bounding rectangle of the item in a wrapper, leaving out the removed items shown\n     * before it.\n     * @param {HTMLElement} element Item wrapper.\n     * @returns {DOMRect} Rectangle.\n     */\n    getItemRect: (element) =>\n      /** @type {Element} */ (element.lastElementChild).getBoundingClientRect(),\n  });\n\n  /**\n   * Get the thumbnail of a collapsed list item.\n   * @param {number} index List index.\n   * @param {string} [type] Variable type name of the item, if the list has variable types.\n   * @returns {MediaFieldSource | undefined} Thumbnail.\n   */\n  const getThumbnail = (index, type) =>\n    getDraftObjectThumbnail({\n      draft: entryDraft.current,\n      thumbnailFieldName,\n      keyPath: `${keyPath}.${index}`,\n      typedKeyPath: `${typedKeyPath}.*`,\n      type,\n      hasSingleSubField,\n      componentName,\n      valueMap: getItemValueMap(index),\n      locale,\n    });\n\n  /**\n   * Warn about unknown variable types used in the list items.\n   */\n  const warnUnknownTypes = () => {\n    if (!hasVariableTypes) {\n      return;\n    }\n\n    items.forEach((item, index) => {\n      const type = item?.[typeKey];\n\n      if (resolveType(type).unknownType) {\n        warnUnknownType({\n          fieldType: 'list',\n          keyPath: `${keyPath}.${index}`,\n          type,\n          typeKey,\n          types,\n        });\n      }\n    });\n  };\n\n  /** The props the top and bottom toolbars share. */\n  const toolbarProps = $derived({\n    fieldId,\n    summaryId,\n    fieldConfig,\n    locale,\n    items,\n    fieldName,\n    label,\n    labelSingular,\n    singleItem,\n    parentExpanded,\n    parentExpandedKeyPath,\n    itemExpanderStates,\n    allowAdd,\n    addToTop,\n    isAddDisabled,\n    hasMaxItems,\n    addItem,\n    pasteItem,\n    updateExpanderStates,\n  });\n\n  onMount(() => {\n    initializeExpanderStates();\n    warnUnknownTypes();\n  });\n</script>\n\n{#snippet removedItemNotices(/** @type {number} */ index)}\n  {#each removedItems.byIndex.get(index) ?? [] as removedItem (removedItem.id)}\n    <RemovedItemNotice\n      id=\"list-{fieldId}-restore-{removedItem.id}\"\n      disabled={isLocked || hasMaxItems}\n      onRestore={() => restoreItem(removedItem)}\n    />\n  {/each}\n{/snippet}\n\n{#if singleItem}\n  <!-- There is no item count to label the list with, so label it with the field name instead -->\n  <div role=\"none\" id={summaryId} hidden>{labelSingular || label || fieldName}</div>\n{/if}\n{#if !singleItem || !items.length}\n  <ListToolbar position=\"top\" bind:element={topToolbar} {...toolbarProps} />\n{/if}\n<div\n  role=\"none\"\n  id=\"list-{fieldId}-item-list\"\n  class=\"item-list\"\n  class:collapsed={!parentExpanded}\n  bind:this={itemList}\n  {...sorter.listProps}\n>\n  <!-- The display index is the position on screen, which follows a drag preview as well -->\n  {#each sorter.displayOrder as index, displayIndex (itemKeys.current[index])}\n    {@const item = items[index]}\n    <!--\n      The wrapper is what the `flip` animation moves: `animate:` only works on an element at the top\n      level of a keyed `each` block, and the item itself sits inside `VisibilityObserver`.\n    -->\n    <div role=\"none\" class=\"item-wrapper\" animate:flip={{ duration: 200 }}>\n      <!-- The items removed from this position are shown before the item now there -->\n      {@render removedItemNotices(displayIndex)}\n      <VisibilityObserver eager={index === listActions.addedItemIndex}>\n        {@const itemKeyPath = `${keyPath}.${index}`}\n        {@const type = hasVariableTypes ? item[typeKey] : undefined}\n        {@const { typeConfig, unknownType, subFields, summaryTemplate } = resolveType(type)}\n        {@const expanded = isExpanded(entryDraft.current, itemKeyPath)}\n        {@const reorderControlProps = sorter.reorderControlProps(index)}\n        <div\n          role=\"group\"\n          aria-label={singleItem\n            ? undefined\n            : _('list_item_position', {\n                values: { position: displayIndex + 1, count: items.length },\n              })}\n          class=\"item\"\n          class:object-unknown-type={unknownType}\n          class:drag-placeholder={sorter.dragIndex === index}\n          {...sorter.itemProps(index, {\n            // A nested sortable list starts its own drag; the event just bubbles through here\n            ownEventsOnly: true,\n          })}\n        >\n          <ObjectHeader\n            label={hasVariableTypes && typeConfig\n              ? getFieldLabel({ config: typeConfig, locale })\n              : ''}\n            position={singleItem ? undefined : displayIndex + 1}\n            controlId=\"list-{fieldId}-item-{index}-body\"\n            {expanded}\n            expandable={subFields.length > 0}\n            toggleExpanded={() => updateExpanderStates({ [itemKeyPath]: !expanded })}\n          >\n            {#snippet centerContent()}\n              {#if showReorderControls}\n                <ReorderControls\n                  {index}\n                  itemCount={items.length}\n                  disabled={isReorderDisabled}\n                  icon=\"drag_handle\"\n                  part=\"handle\"\n                  {...reorderControlProps}\n                />\n              {/if}\n            {/snippet}\n            {#snippet endContent()}\n              {#if showReorderControls}\n                <ReorderControls\n                  {index}\n                  itemCount={items.length}\n                  disabled={isReorderDisabled}\n                  part=\"buttons\"\n                  menu={false}\n                  onMove={reorderControlProps.onMove}\n                />\n              {/if}\n              <ListItemMenu\n                {index}\n                {locale}\n                variableTypes={hasVariableTypes ? variableTypes : undefined}\n                {unknownType}\n                {allowAdd}\n                {allowRemove}\n                {allowDuplicate}\n                {hasMaxItems}\n                {isAddDisabled}\n                itemCount={items.length}\n                canReorder={showReorderControls && !isLocked}\n                moveItem={reorderControlProps.onMove}\n                {copyItem}\n                {pasteItem}\n                {addItem}\n              />\n              {#if canRemoveItem}\n                <RemoveButton\n                  variant=\"ghost\"\n                  disabled={isLocked}\n                  onclick={() => removeItem(index)}\n                />\n              {/if}\n            {/snippet}\n          </ObjectHeader>\n          <div role=\"none\" class=\"item-body\" id=\"list-{fieldId}-item-{index}-body\">\n            {#snippet customSummaryContent()}\n              <CustomPreview\n                {locale}\n                keyPath={itemKeyPath}\n                typedKeyPath=\"{typedKeyPath}.*\"\n                currentValue={item}\n                {...{\n                  fieldConfig: /** @type {CustomField} */ (field),\n                  preview: /** @type {CustomFieldSummary} */ (customSummary),\n                }}\n              />\n            {/snippet}\n            <ObjectBody\n              {locale}\n              {subFields}\n              getSubFieldProps={(subField) => ({\n                keyPath: hasSingleSubField ? itemKeyPath : `${itemKeyPath}.${subField.name}`,\n                typedKeyPath: getTypedSubKeyPath({\n                  typedKeyPath: `${typedKeyPath}.*`,\n                  type,\n                  subFieldName: subField.name,\n                }),\n                context: hasSingleSubField ? 'single-subfield-list-field' : undefined,\n              })}\n              {expanded}\n              {unknownType}\n              {typeConfig}\n              {readonly}\n              getSummary={() => _formatSummary(index, summaryTemplate, getItemValueMap(index))}\n              getThumbnail={() => getThumbnail(index, type)}\n              summaryContent={customSummary ? customSummaryContent : undefined}\n            />\n          </div>\n        </div>\n      </VisibilityObserver>\n    </div>\n  {/each}\n</div>\n{#if removedItems.byIndex.has(items.length) && (parentExpanded || !items.length)}\n  <!-- The items removed from the end of the list -->\n  <div role=\"none\" class=\"removed-item-list\">\n    {@render removedItemNotices(items.length)}\n  </div>\n{/if}\n{#if allowAdd && !addToTop && items.length && parentExpanded && !hasMaxItems}\n  <ListToolbar position=\"bottom\" {...toolbarProps} />\n{/if}\n\n<style>\n  .item-list {\n    display: flex;\n    flex-direction: column;\n    gap: 16px;\n\n    &.collapsed {\n      display: none;\n    }\n  }\n\n  .item-wrapper,\n  .removed-item-list {\n    display: flex;\n    flex-direction: column;\n    gap: 16px;\n  }\n\n  .removed-item-list {\n    margin-block-start: 16px;\n  }\n\n  .item {\n    flex: none;\n    position: relative;\n    border-width: 2px;\n    border-color: var(--sui-secondary-border-color);\n    border-radius: var(--sui-control-medium-border-radius);\n    background-color: var(--sui-primary-background-color); /* for dragging opacity */\n\n    /* Like the field menus, the buttons at the end of the header (Move Up/Down, options and\n      remove) are shown on hover, and kept visible while a keyboard user is in the item, so the\n      focused one isn’t invisible, or while the options menu is open */\n    @media (hover: hover) {\n      &:not(:hover, :focus-within) > :global(.header > .end button:not([aria-expanded='true'])) {\n        opacity: 0;\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the editor for a List field without subfield(s).\n\n  Each item is a row with its own single-line input, so items can be reordered and removed\n  individually. The rows are held locally rather than being read straight from the draft: a blank\n  row is a real editing state that has no representation in the stored value, which is always the\n  trimmed, blank-free projection of the rows. There is always at least one row, so an empty list\n  still offers somewhere to type.\n  @see https://decapcms.org/docs/widgets/#List\n  @see https://sveltiacms.app/en/docs/fields/list\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { TextInput } from '@sveltia/ui';\n  import equal from 'fast-deep-equal';\n  import { onMount, tick } from 'svelte';\n  import { flip } from 'svelte/animate';\n\n  import RemoveButton from '$lib/components/common/remove-button.svelte';\n  import ReorderControls from '$lib/components/common/reorder-controls.svelte';\n  import AddItemButton from '$lib/components/contents/details/fields/object/add-item-button.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { updateNonPrimitiveValue } from '$lib/services/contents/draft/update';\n  import { deferDraftWrite } from '$lib/services/contents/draft/update/deferred';\n  import { getFieldEditorContext } from '$lib/services/contents/editor/field-context';\n  import { isSingleItemList } from '$lib/services/contents/fields/list/helpers';\n  import { getDirection } from '$lib/services/contents/i18n';\n  import { focusAfterRemoval } from '$lib/services/utils/drag-sorting';\n  import { createDragSorter } from '$lib/services/utils/drag-sorting.svelte';\n  import { createKeyedRows } from '$lib/services/utils/keyed-rows.svelte';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { SimpleListField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {SimpleListField} fieldConfig Field configuration.\n   * @property {string[]} currentValue Field value.\n   */\n\n  const { valueStoreKey = 'currentValues' } = getFieldEditorContext();\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    fieldId,\n    fieldConfig,\n    currentValue,\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  /**\n   * Rows shown in the editor, one per item. Unlike the stored value, the rows can be blank, and\n   * there is always at least one.\n   */\n  const rows = createKeyedRows(['']);\n  /**\n   * @type {HTMLElement | undefined}\n   */\n  let itemList = $state();\n  /**\n   * Whether the editor has been unmounted, e.g. along with a removed list item, after which a\n   * deferred write must not put its value back into the draft. A plain variable, as it’s read\n   * outside of any reactive context.\n   */\n  let unmounted = false;\n\n  const { i18n, max = Infinity } = $derived(fieldConfig);\n  const canEdit = $derived(!readonly);\n  // Removing or reordering the only row would leave nothing to type into, and has nothing to do\n  const hasMultipleItems = $derived(rows.values.length > 1);\n  // A list limited to one item is shown like a single input, without the controls to reorder or\n  // remove the item, which can’t do anything with one row anyway\n  const singleItem = $derived(isSingleItemList({ fieldConfig, itemCount: rows.values.length }));\n\n  /**\n   * Get the rows as they should be stored: trimmed, with the blank ones dropped.\n   * @returns {string[]} List value.\n   */\n  const getStoredValue = () => rows.values.map((item) => item.trim()).filter(Boolean);\n\n  /**\n   * Adopt a value that changed outside the editor, such as a locale switch or a restored backup.\n   *\n   * A write of our own comes back through the `currentValue` prop, and adopting that would discard\n   * any blank row the user is part-way through filling in. The stored value is exactly the rows’\n   * projection, so anything matching it is our own echo and the rows are already up to date.\n   */\n  const syncFromValue = () => {\n    const value = currentValue ?? [];\n\n    if (equal(getStoredValue(), value)) {\n      return;\n    }\n\n    rows.replace(value.length ? [...value] : ['']);\n  };\n\n  /**\n   * Write the rows to the draft, unless they already hold the stored value. Rewriting an unchanged\n   * value isn’t harmless: it adds the placeholder of a non-empty list, which the loaded content\n   * doesn’t have, so merely opening an entry would count as a change.\n   *\n   * This runs from an effect, so the write to the draft is deferred. The value and its location are\n   * worked out now, from the rows as they are.\n   */\n  const updateValue = () => {\n    const draft = entryDraft.current;\n    const value = getStoredValue();\n\n    /* v8 ignore next 3 -- the editor is only rendered while the draft is there */\n    if (!draft) {\n      return;\n    }\n\n    if (equal(value, currentValue ?? [])) {\n      return;\n    }\n\n    const args = { draft, valueStoreKey, locale, keyPath, i18n, value };\n\n    deferDraftWrite(() => {\n      if (!unmounted) {\n        updateNonPrimitiveValue(args);\n      }\n    });\n  };\n\n  /**\n   * Get the input in the row at the given index.\n   * @param {number} index Target index.\n   * @returns {HTMLInputElement | null | undefined} Input element.\n   */\n  const getInput = (index) => itemList?.children[index]?.querySelector('input');\n\n  /**\n   * Insert a blank row and move the focus into it.\n   * @param {number} index Index to insert at.\n   */\n  const addItem = async (index) => {\n    rows.insert(index, '');\n\n    await tick();\n    getInput(index)?.focus();\n  };\n\n  /**\n   * Remove a row and move the focus to the row that takes its place, or to the last one.\n   * @param {number} index Target index.\n   */\n  const removeItem = async (index) => {\n    rows.remove(index);\n\n    await tick();\n    focusAfterRemoval({ index, getTarget: getInput });\n  };\n\n  /**\n   * Move a row to another position in the list.\n   * @param {number} from Source index.\n   * @param {number} to Destination index.\n   */\n  const moveItem = (from, to) => {\n    rows.move(from, to);\n  };\n\n  const sorter = createDragSorter({\n    /**\n     * Get the number of items in the list.\n     * @returns {number} Item count.\n     */\n    getItemCount: () => rows.values.length,\n    /**\n     * Get the list element.\n     * @returns {HTMLElement | undefined} Element.\n     */\n    getListElement: () => itemList,\n    onMove: moveItem,\n    /**\n     * Get the value of a row, to be attached to its drag.\n     * @param {number} index Row index.\n     * @returns {string} Value.\n     */\n    getItemData: (index) => rows.values[index],\n  });\n\n  onMount(() => () => {\n    unmounted = true;\n  });\n\n  watch(\n    () => currentValue,\n    () => {\n      syncFromValue();\n    },\n  );\n\n  watch(\n    () => $state.snapshot(rows.values),\n    () => {\n      updateValue();\n    },\n  );\n</script>\n\n<div role=\"none\" class=\"item-list\" bind:this={itemList} {...sorter.listProps}>\n  {#each sorter.displayOrder as index (rows.ids[index])}\n    <div\n      role=\"none\"\n      class=\"item\"\n      class:drag-placeholder={sorter.dragIndex === index}\n      {...sorter.itemProps(index)}\n      animate:flip={{ duration: 200 }}\n    >\n      {#if canEdit && !singleItem}\n        <ReorderControls\n          {index}\n          itemCount={rows.values.length}\n          disabled={!hasMultipleItems}\n          {...sorter.reorderControlProps(index)}\n        />\n      {/if}\n      <TextInput\n        dir={getDirection(locale)}\n        flex\n        bind:value={rows.values[index]}\n        {readonly}\n        {invalid}\n        required={required && rows.values.length === 1}\n        ariaLabel={_('list_item_value')}\n        aria-errormessage=\"{fieldId}-error\"\n        onkeydown={(/** @type {KeyboardEvent} */ event) => {\n          // Ignore the Enter key while the user is typing with an IME, or in a read-only field\n          if (event.key !== 'Enter' || event.isComposing || !canEdit || rows.values.length >= max) {\n            return;\n          }\n\n          event.preventDefault();\n          addItem(index + 1);\n        }}\n      />\n      {#if canEdit && !singleItem}\n        <RemoveButton\n          variant=\"ghost\"\n          disabled={!hasMultipleItems}\n          onclick={() => {\n            removeItem(index);\n          }}\n        />\n      {/if}\n    </div>\n  {/each}\n</div>\n{#if canEdit && rows.values.length < max}\n  <div role=\"none\" class=\"toolbar\">\n    <AddItemButton\n      {fieldConfig}\n      {locale}\n      items={rows.values}\n      addItem={() => addItem(rows.values.length)}\n    />\n  </div>\n{/if}\n\n<style>\n  .item-list {\n    display: flex;\n    flex-direction: column;\n    gap: 4px;\n  }\n\n  .toolbar {\n    display: flex;\n    align-items: center;\n    margin-block-start: 8px;\n  }\n\n  .item {\n    display: flex;\n    align-items: center;\n    gap: 4px;\n  }\n</style>\n","<!--\n  @component\n  Implement the editor for a List field.\n  @see https://decapcms.org/docs/widgets/#List\n  @see https://sveltiacms.app/en/docs/fields/list\n-->\n<script>\n  import { Group } from '@sveltia/ui';\n\n  import ListEditorComplex from '$lib/components/contents/details/fields/list/list-editor-complex.svelte';\n  import ListEditorSimple from '$lib/components/contents/details/fields/list/list-editor-simple.svelte';\n  import { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { ComplexListField, SimpleListField, ListField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ListField} fieldConfig Field configuration.\n   * @property {any[]} currentValue Field value.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let { fieldConfig: config, ...rest } = $props();\n\n  const fieldId = $props.id();\n  const summaryId = `list-${fieldId}-summary`;\n  const { hasSubFields } = $derived(getListFieldInfo(config));\n</script>\n\n<!-- Only a list with subfields shows the item count that labels it -->\n<Group aria-labelledby={hasSubFields ? summaryId : undefined}>\n  {#if hasSubFields}\n    <ListEditorComplex\n      {...{ ...rest, fieldConfig: /** @type {ComplexListField} */ (config), summaryId }}\n    />\n  {:else}\n    <ListEditorSimple {...{ ...rest, fieldConfig: /** @type {SimpleListField} */ (config) }} />\n  {/if}\n</Group>\n","<script>\n  import ErrorBoundary from '$lib/components/common/error-boundary.svelte';\n  import { CustomPreview, previews } from '$lib/components/contents/details/fields';\n  import { customFieldTypeRegistry } from '$lib/services/api/registries';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { highlightEditorField } from '$lib/services/contents/editor/fields';\n  import { getFieldLocaleAccess } from '$lib/services/contents/editor/locale';\n  import { getCurrentValue, isFieldMultiple } from '$lib/services/contents/entry/fields';\n  import { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n  /**\n   * @import { InternalLocaleCode, TypedFieldKeyPath } from '$lib/types/private';\n   * @import { CustomField, Field, FieldKeyPath, VisibleField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   * @property {FieldKeyPath} keyPath Field key path.\n   * @property {TypedFieldKeyPath} typedKeyPath Typed field key path.\n   * @property {Field} fieldConfig Field configuration.\n   * @property {boolean} [showLabel] Whether to show the field label/header. Defaults to `true`.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { locale, keyPath, typedKeyPath, fieldConfig, showLabel = true } = $props();\n\n  const { widget: fieldType = 'string' } = $derived(fieldConfig);\n  const { preview = true } = $derived(/** @type {VisibleField} */ (fieldConfig));\n  const fieldLabel = $derived(getFieldLabel({ config: fieldConfig, locale }));\n  const multiple = $derived(isFieldMultiple(fieldConfig));\n  const isList = $derived(fieldType === 'list' || multiple);\n  const valueMap = $derived(getFieldValueMapSnapshot(entryDraft.current, locale, keyPath));\n  // A field duplicated along with an ancestor is shown in the other locales like in `FieldEditor`\n  const { isShown } = $derived(\n    getFieldLocaleAccess({ draft: entryDraft.current, fieldConfig, keyPath, locale, valueMap }),\n  );\n  const customFieldType = $derived(customFieldTypeRegistry.get(fieldType));\n  const currentValue = $derived(\n    getCurrentValue({ valueMap, keyPath, isList, isCustomFieldType: !!customFieldType }),\n  );\n  const previewProps = $derived({ locale, keyPath, typedKeyPath, fieldConfig, currentValue });\n</script>\n\n<!-- Render nothing for a missing field configuration, e.g. when a custom preview template asks\n  for a key path that isn’t a configured field. The derived values above are read past the check -->\n{#if fieldConfig && fieldType !== 'hidden' && preview && isShown}\n  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n  <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->\n  <section\n    role=\"group\"\n    data-field-type={fieldType}\n    data-key-path={keyPath}\n    data-typed-key-path={typedKeyPath}\n    tabindex=\"0\"\n    onkeydown={(event) => {\n      if (event.key === 'Enter') {\n        event.stopPropagation();\n        highlightEditorField({ locale, keyPath });\n      }\n    }}\n    onclick={(event) => {\n      event.stopPropagation();\n      highlightEditorField({ locale, keyPath });\n    }}\n  >\n    {#if showLabel}\n      <h4>{fieldLabel}</h4>\n    {/if}\n    <ErrorBoundary>\n      {#if customFieldType?.preview}\n        <CustomPreview\n          {...{ ...previewProps, fieldConfig: /** @type {CustomField} */ (fieldConfig) }}\n          preview={customFieldType.preview}\n        />\n      {:else if fieldType in previews}\n        {@const Preview = previews[fieldType]}\n        <Preview {...previewProps} />\n      {/if}\n    </ErrorBoundary>\n  </section>\n{/if}\n\n<style>\n  :global([role='document']) section {\n    overflow: hidden;\n    /* Don’t set margin here because it makes scroll sync bumpy */\n    padding: 12px 0;\n\n    h4 {\n      color: var(--sui-secondary-foreground-color);\n      font-size: var(--sui-font-size-small);\n\n      &:not(:last-child) {\n        margin-bottom: 8px;\n      }\n    }\n\n    :global {\n      & > * {\n        margin-inline: auto;\n        max-width: 768px;\n      }\n\n      p {\n        margin: 8px auto 0;\n        -webkit-user-select: text;\n        user-select: text;\n      }\n\n      img {\n        max-height: 800px !important;\n      }\n\n      .sui.alert {\n        margin-block: 16px;\n      }\n    }\n  }\n\n  @media (width < 768px) {\n    /* Remove the padding to make an image or an embedded video full-width */\n    :global([role='document']) section > :global(p:has(img, iframe)) {\n      margin-inline: calc(var(--entry-preview-padding-inline) * -1);\n    }\n\n    /* A top-level field, which is wrapped for the Edit Pane to find it before it’s rendered */\n    :global([role='document'] > [data-lazy-key-path]) {\n      & > section:is([data-field-type='file'], [data-field-type='image']):has(:global(img)),\n      & > section:is([data-field-type='string']):has(:global(iframe)) {\n        overflow: visible;\n      }\n\n      & > section:is([data-field-type='file'], [data-field-type='image']) :global(img) {\n        width: 100%;\n        max-height: none !important;\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Previews of the subfields of an Object field value or a complex List field item, grouped under the\n  label of its variable type, if any. Nothing is rendered for a type the field doesn’t define: a\n  warning is displayed in the editor.\n-->\n<script>\n  import { VisibilityObserver } from '@sveltia/ui';\n\n  import FieldPreview from '$lib/components/contents/details/preview/field-preview.svelte';\n  import {\n    getTypedSubKeyPath,\n    resolveVariableType,\n  } from '$lib/services/contents/fields/object/helpers';\n  import { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n  /**\n   * @import { InternalLocaleCode, TypedFieldKeyPath } from '$lib/types/private';\n   * @import { Field, FieldKeyPath, VariableFieldType } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   * @property {FieldKeyPath} keyPath Key path of the value.\n   * @property {TypedFieldKeyPath} typedKeyPath Typed key path of the value, e.g. `sections.*`.\n   * @property {VariableFieldType[]} [types] Types the field defines. `undefined` if the field\n   * doesn’t have variable types.\n   * @property {Field[]} [fields] Subfields of a field without variable types.\n   * @property {string} [type] Type the value has, if any.\n   * @property {boolean} [single] Whether the value is a List field item holding its single subfield\n   * as the item itself, so the subfield has the item’s key path.\n   */\n\n  /** @type {Props} */\n  let { locale, keyPath, typedKeyPath, types, fields, type, single = false } = $props();\n\n  const sectionId = $props.id();\n  const headerId = `${sectionId}-header`;\n\n  const { typeConfig, unknownType, subFields } = $derived(\n    resolveVariableType({ types, fields, type }),\n  );\n  const label = $derived(typeConfig ? getFieldLabel({ config: typeConfig, locale }) : undefined);\n</script>\n\n{#if !unknownType}\n  <div role=\"group\" class=\"subsection\" aria-labelledby={label ? headerId : undefined}>\n    {#if label}\n      <div role=\"none\" id={headerId} class=\"header\">\n        {label}\n      </div>\n    {/if}\n    <div role=\"none\" class=\"items\">\n      {#each subFields as subField (subField.name)}\n        {@const subFieldKeyPath = single ? keyPath : `${keyPath}.${subField.name}`}\n        <!-- Mark the subfield outside its observer, so that focusing it can scroll the preview to\n          it even before it’s rendered -->\n        <div role=\"none\" data-lazy-key-path={subFieldKeyPath}>\n          <VisibilityObserver>\n            <FieldPreview\n              keyPath={subFieldKeyPath}\n              typedKeyPath={getTypedSubKeyPath({\n                typedKeyPath,\n                type: typeConfig?.name,\n                subFieldName: subField.name,\n              })}\n              {locale}\n              fieldConfig={subField}\n            />\n          </VisibilityObserver>\n        </div>\n      {/each}\n    </div>\n  </div>\n{/if}\n\n<style>\n  .subsection {\n    margin: 16px auto;\n    border: 2px solid var(--sui-secondary-border-color);\n    border-radius: var(--sui-control-medium-border-radius);\n\n    :global(.title) {\n      font-size: inherit;\n      font-weight: var(--sui-font-weight-normal);\n    }\n  }\n\n  .header {\n    display: flex;\n    align-items: center;\n    height: 24px;\n    padding-inline: 8px;\n    color: var(--sui-secondary-foreground-color);\n    background-color: var(--sui-secondary-border-color);\n    font-size: var(--sui-font-size-small);\n    font-weight: var(--sui-font-weight-bold);\n  }\n\n  .items {\n    padding: 8px 16px;\n\n    /* Hide when no subfield is shown, leaving only the empty wrappers marking the subfields */\n    &:not(:has(> :not(:empty))) {\n      display: none;\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the preview for a List field with subfield(s).\n  @see https://decapcms.org/docs/widgets/#List\n  @see https://sveltiacms.app/en/docs/fields/list\n-->\n<script>\n  import { VisibilityObserver } from '@sveltia/ui';\n\n  import SubfieldPreviews from '$lib/components/contents/details/fields/object/subfield-previews.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getMemoizedSubtree } from '$lib/services/contents/entry/subtree';\n  import { getListFieldInfo, getListItemKey } from '$lib/services/contents/fields/list/helpers';\n\n  /**\n   * @import { SubtreeMemo } from '$lib/services/contents/entry/subtree';\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import {\n   * ComplexListField,\n   * ListFieldWithSubField,\n   * ListFieldWithSubFields,\n   * ListFieldWithTypes,\n   * } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ComplexListField} fieldConfig Field configuration.\n   * @property {string[] | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, keyPath, typedKeyPath, fieldConfig } = $props();\n\n  const { field } = $derived(/** @type {ListFieldWithSubField} */ (fieldConfig));\n  const { fields } = $derived(/** @type {ListFieldWithSubFields} */ (fieldConfig));\n  const { types, typeKey = 'type' } = $derived(/** @type {ListFieldWithTypes} */ (fieldConfig));\n  const { hasSingleSubField, hasVariableTypes } = $derived(getListFieldInfo(fieldConfig));\n  /* v8 ignore start -- a list field has either subfields or a single subfield */\n  const singleSubFields = $derived(fields ?? (field ? [field] : []));\n  /* v8 ignore stop */\n  /**\n   * What the items were last assembled from, so they’re only assembled again once they’ve changed.\n   * A plain object, as it’s only a memo.\n   * @type {SubtreeMemo}\n   */\n  const itemsMemo = {};\n  /** @type {Record<string, any>[]} */\n  const items = $derived(\n    getMemoizedSubtree(\n      itemsMemo,\n      getFieldValueMapSnapshot(entryDraft.current, locale, keyPath),\n      keyPath,\n    ) ?? [],\n  );\n  /**\n   * The variable type of each item, or `undefined` for a list without variable types. The `each`\n   * block below iterates over these primitives rather than over the items: the items are rebuilt\n   * from the snapshot on every update, and a keyed `each` block over them would rewrite the source\n   * of every item on every keystroke, which Svelte then walks through every nested preview.\n   * @type {(string | undefined)[]}\n   */\n  const itemTypes = $derived(items.map((item) => (hasVariableTypes ? item[typeKey] : undefined)));\n</script>\n\n{#each itemTypes as type, index (getListItemKey(items, index))}\n  {@const itemKeyPath = `${keyPath}.${index}`}\n  <!-- Mark the item outside its observer, so that focusing a field in it can scroll the preview to\n    the item even before it’s rendered -->\n  <div role=\"none\" data-lazy-key-path={itemKeyPath}>\n    <VisibilityObserver>\n      <SubfieldPreviews\n        {locale}\n        keyPath={itemKeyPath}\n        typedKeyPath=\"{typedKeyPath}.*\"\n        types={hasVariableTypes ? types : undefined}\n        fields={singleSubFields}\n        {type}\n        single={hasSingleSubField}\n      />\n    </VisibilityObserver>\n  </div>\n{/each}\n","<!--\n  @component\n  Implement the preview for a List field without subfield(s).\n  @see https://decapcms.org/docs/widgets/#List\n  @see https://sveltiacms.app/en/docs/fields/list\n-->\n<script>\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { SimpleListField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {SimpleListField} fieldConfig Field configuration.\n   * @property {string[] | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, currentValue } = $props();\n</script>\n\n{#if Array.isArray(currentValue) && currentValue.length}\n  <ul lang={getCanonicalLocale(locale)} dir={getDirection(locale)}>\n    {#each currentValue as item, index (`${item}-${index}`)}\n      <li>{item}</li>\n    {/each}\n  </ul>\n{/if}\n","<!--\n  @component\n  Implement the preview for a List field.\n  @see https://decapcms.org/docs/widgets/#List\n  @see https://sveltiacms.app/en/docs/fields/list\n-->\n<script>\n  import ListPreviewComplex from '$lib/components/contents/details/fields/list/list-preview-complex.svelte';\n  import ListPreviewSimple from '$lib/components/contents/details/fields/list/list-preview-simple.svelte';\n  import { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { ComplexListField, SimpleListField, ListField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ListField} fieldConfig Field configuration.\n   * @property {string[] | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { fieldConfig: config, ...rest } = $props();\n</script>\n\n{#if getListFieldInfo(config).hasSubFields}\n  <ListPreviewComplex {...{ ...rest, fieldConfig: /** @type {ComplexListField} */ (config) }} />\n{:else}\n  <ListPreviewSimple {...{ ...rest, fieldConfig: /** @type {SimpleListField} */ (config) }} />\n{/if}\n","<!--\n  @component\n  Implement a static map using Leaflet, showing a marker at the specified coordinates.\n  @see https://leafletjs.com/\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { onMount, untrack } from 'svelte';\n\n  import { getLeafletMarkerIconURL, loadModule } from '$lib/services/app/dependencies';\n\n  /**\n   * @import Leaflet from 'leaflet';\n   * @import { GeoCoordinates } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {GeoCoordinates} [coordinates] GeoCoordinates of the location to show on the map.\n   * @property {string} [class] Additional CSS classes to apply to the map container.\n   * @property {HTMLElement} [mapElement] The HTML element to bind the map to.\n   * @property {(args: { leaflet: Leaflet, map: Leaflet.Map }) => void} [onReady] Callback function\n   * invoked when the map is ready.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let {\n    coordinates,\n    class: className = '',\n    mapElement = $bindable(),\n    onReady = undefined,\n    ...rest\n  } = $props();\n\n  /** @type {ResizeObserver | undefined} */\n  let resizeObserver;\n  /** Whether the component has been destroyed, possibly before the map is initialized. */\n  let destroyed = false;\n  /**\n   * Leaflet library, map instance and marker icon, once the map is initialized.\n   * @type {{ leaflet: Leaflet, map: Leaflet.Map, iconUrl: string } | undefined}\n   */\n  let instance = $state.raw();\n  /** @type {Leaflet.Marker | undefined} */\n  let marker;\n  /** @type {GeoCoordinates | undefined} */\n  let shownCoordinates;\n\n  /**\n   * Show a marker at the current coordinates, and centre the map on them. The component can stay\n   * mounted while the coordinates change, e.g. in the info panel of the Asset Library as the focus\n   * moves from one photo to another, so the previous marker is removed first.\n   */\n  const showLocation = () => {\n    const { latitude, longitude } = coordinates ?? {};\n\n    if (latitude === shownCoordinates?.latitude && longitude === shownCoordinates?.longitude) {\n      return;\n    }\n\n    // Only called once the map is initialized\n    const { leaflet, map, iconUrl } = /** @type {NonNullable<typeof instance>} */ (instance);\n\n    shownCoordinates = coordinates;\n    marker?.remove();\n    marker = undefined;\n\n    if (coordinates) {\n      const icon = leaflet.icon({ iconUrl, iconSize: [25, 41] });\n\n      marker = leaflet.marker([coordinates.latitude, coordinates.longitude], { icon }).addTo(map);\n      map.setView([coordinates.latitude, coordinates.longitude], 12);\n    }\n  };\n\n  /**\n   * Load the Leaflet library and initialize the map. We don’t bundle the library because of the\n   * bundle size. The component may not be used often, and multiple map services, including Google\n   * Maps and Here Maps, may be supported in the future.\n   */\n  const init = async () => {\n    /* v8 ignore next 3 -- called once mounted, when the element is bound */\n    if (!mapElement) {\n      return;\n    }\n\n    /** @type {Leaflet} */\n    const leaflet = await loadModule('leaflet', 'dist/leaflet-src.esm.js');\n    const iconUrl = await getLeafletMarkerIconURL();\n\n    // The component may have been destroyed while the library was being loaded\n    if (destroyed) {\n      return;\n    }\n\n    const map = leaflet.map(mapElement, { center: [0, 0], zoom: 2 });\n\n    leaflet\n      .tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {\n        attribution:\n          '&copy; <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors',\n        // Set the referrer policy explicitly to avoid issues when loading tiles from OpenStreetMap.\n        // Otherwise, the global `same-origin` policy set in Sveltia CMS will apply.\n        // @see https://github.com/sveltia/sveltia-cms/issues/742\n        referrerPolicy: 'strict-origin',\n      })\n      .addTo(map);\n\n    instance = { leaflet, map, iconUrl };\n    showLocation();\n\n    mapElement.querySelectorAll('a[href^=\"https:\"]').forEach((a) => {\n      a.setAttribute('target', '_blank');\n      a.setAttribute('rel', 'noopener noreferrer');\n    });\n\n    resizeObserver = new ResizeObserver(() => {\n      map?.invalidateSize();\n    });\n\n    resizeObserver.observe(mapElement);\n\n    onReady?.({ leaflet, map });\n  };\n\n  // Move the marker when the coordinates change\n  $effect(() => {\n    void [instance, coordinates?.latitude, coordinates?.longitude];\n\n    untrack(() => {\n      if (instance) {\n        showLocation();\n      }\n    });\n  });\n\n  onMount(() => {\n    init();\n\n    return () => {\n      destroyed = true;\n      resizeObserver?.disconnect();\n\n      // Remove the map, along with the window resize listener Leaflet keeps until then\n      if (instance) {\n        // Leaflet ends a zoom animation with a timer that `remove()` doesn’t clear, and that then\n        // throws on the removed map, so mark the animation as over first\n        /** @type {any} */ (instance.map)._animatingZoom = false;\n        instance.map.remove();\n      }\n    };\n  });\n</script>\n\n<div\n  role=\"application\"\n  class=\"map {className}\"\n  bind:this={mapElement}\n  aria-label={coordinates ? _('map_lat_lng', { values: coordinates }) : undefined}\n  {...rest}\n></div>\n\n<style>\n  /* Leaflet default styles copied from `node_modules/leaflet/dist/leaflet.css`. Somehow we can’t */\n  /* import it directly here; Vite emits it as a separate CSS file, which we want to avoid. */\n  /* Rules for the features we don’t use — popups, tooltips, the Layers and Scale controls, */\n  /* image/video overlays, div icons, marker shadows, the Canvas renderer and the legacy IE/VML */\n  /* hacks — have been dropped. */\n  :global {\n    .leaflet-pane,\n    .leaflet-tile,\n    .leaflet-marker-icon,\n    .leaflet-tile-container,\n    .leaflet-pane > svg,\n    .leaflet-zoom-box,\n    .leaflet-layer {\n      position: absolute;\n      left: 0;\n      top: 0;\n    }\n\n    .leaflet-container {\n      overflow: hidden;\n      -webkit-tap-highlight-color: transparent;\n      background: #ddd;\n      outline-offset: 1px;\n      font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif;\n      font-size: 12px;\n      font-size: 0.75rem;\n      line-height: 1.5;\n    }\n\n    .leaflet-tile,\n    .leaflet-marker-icon {\n      -webkit-user-select: none;\n      -moz-user-select: none;\n      user-select: none;\n      -webkit-user-drag: none;\n    }\n\n    .leaflet-tile::selection {\n      background: transparent;\n    }\n\n    .leaflet-safari .leaflet-tile {\n      image-rendering: -webkit-optimize-contrast;\n    }\n\n    .leaflet-safari .leaflet-tile-container {\n      width: 1600px;\n      height: 1600px;\n      -webkit-transform-origin: 0 0;\n      transform-origin: 0 0;\n    }\n\n    .leaflet-marker-icon {\n      display: block;\n    }\n\n    .leaflet-container .leaflet-overlay-pane svg {\n      max-width: none !important;\n      max-height: none !important;\n    }\n\n    .leaflet-container .leaflet-marker-pane img,\n    .leaflet-container .leaflet-tile-pane img,\n    .leaflet-container .leaflet-tile {\n      max-width: none !important;\n      max-height: none !important;\n      width: auto;\n      padding: 0;\n    }\n\n    .leaflet-container img.leaflet-tile {\n      mix-blend-mode: plus-lighter;\n    }\n\n    .leaflet-container.leaflet-touch-zoom {\n      -ms-touch-action: pan-x pan-y;\n      touch-action: pan-x pan-y;\n    }\n\n    .leaflet-container.leaflet-touch-drag {\n      -ms-touch-action: pinch-zoom;\n      touch-action: none;\n      touch-action: pinch-zoom;\n    }\n\n    .leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {\n      -ms-touch-action: none;\n      touch-action: none;\n    }\n\n    .leaflet-container a {\n      -webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);\n      color: #0078a8;\n    }\n\n    .leaflet-tile {\n      filter: inherit;\n      visibility: hidden;\n    }\n\n    .leaflet-tile-loaded {\n      visibility: inherit;\n    }\n\n    .leaflet-zoom-box {\n      width: 0;\n      height: 0;\n      -moz-box-sizing: border-box;\n      box-sizing: border-box;\n      z-index: 800;\n      border: 2px dotted #38f;\n      background: rgba(255, 255, 255, 0.5);\n    }\n\n    .leaflet-overlay-pane svg {\n      -moz-user-select: none;\n      user-select: none;\n    }\n\n    .leaflet-pane {\n      z-index: 400;\n    }\n\n    .leaflet-tile-pane {\n      z-index: 200;\n    }\n\n    .leaflet-overlay-pane {\n      z-index: 400;\n    }\n\n    .leaflet-marker-pane {\n      z-index: 600;\n    }\n\n    .leaflet-map-pane svg {\n      z-index: 200;\n    }\n\n    .leaflet-control {\n      position: relative;\n      z-index: 800;\n      pointer-events: visiblePainted;\n      pointer-events: auto;\n      float: left;\n      clear: both;\n      cursor: auto;\n    }\n\n    .leaflet-top,\n    .leaflet-bottom {\n      position: absolute;\n      z-index: 1000;\n      pointer-events: none;\n    }\n\n    .leaflet-top {\n      top: 0;\n    }\n\n    .leaflet-right {\n      right: 0;\n    }\n\n    .leaflet-bottom {\n      bottom: 0;\n    }\n\n    .leaflet-left {\n      left: 0;\n    }\n\n    .leaflet-right .leaflet-control {\n      float: right;\n      margin-right: 10px;\n    }\n\n    .leaflet-top .leaflet-control {\n      margin-top: 10px;\n    }\n\n    .leaflet-bottom .leaflet-control {\n      margin-bottom: 10px;\n    }\n\n    .leaflet-left .leaflet-control {\n      margin-left: 10px;\n    }\n\n    .leaflet-zoom-animated {\n      -webkit-transform-origin: 0 0;\n      -ms-transform-origin: 0 0;\n      transform-origin: 0 0;\n    }\n\n    svg.leaflet-zoom-animated {\n      will-change: transform;\n    }\n\n    .leaflet-zoom-anim .leaflet-zoom-animated {\n      -webkit-transition: -webkit-transform 0.25s cubic-bezier(0, 0, 0.25, 1);\n      -moz-transition: -moz-transform 0.25s cubic-bezier(0, 0, 0.25, 1);\n      transition: transform 0.25s cubic-bezier(0, 0, 0.25, 1);\n    }\n\n    .leaflet-zoom-anim .leaflet-tile,\n    .leaflet-pan-anim .leaflet-tile {\n      -webkit-transition: none;\n      -moz-transition: none;\n      transition: none;\n    }\n\n    .leaflet-zoom-anim .leaflet-zoom-hide {\n      visibility: hidden;\n    }\n\n    .leaflet-interactive {\n      cursor: pointer;\n    }\n\n    .leaflet-grab {\n      /* stylelint-disable-next-line declaration-property-value-no-unknown */\n      cursor: -webkit-grab;\n      /* stylelint-disable-next-line declaration-property-value-no-unknown */\n      cursor: -moz-grab;\n      cursor: grab;\n    }\n\n    .leaflet-crosshair,\n    .leaflet-crosshair .leaflet-interactive {\n      cursor: crosshair;\n    }\n\n    .leaflet-dragging .leaflet-grab,\n    .leaflet-dragging .leaflet-grab .leaflet-interactive {\n      cursor: move;\n      /* stylelint-disable-next-line declaration-property-value-no-unknown */\n      cursor: -webkit-grabbing;\n      /* stylelint-disable-next-line declaration-property-value-no-unknown */\n      cursor: -moz-grabbing;\n      cursor: grabbing;\n    }\n\n    .leaflet-marker-icon,\n    .leaflet-pane > svg path,\n    .leaflet-tile-container {\n      pointer-events: none;\n    }\n\n    .leaflet-marker-icon.leaflet-interactive,\n    .leaflet-pane > svg path.leaflet-interactive {\n      pointer-events: visiblePainted;\n      pointer-events: auto;\n    }\n\n    .leaflet-bar {\n      box-shadow: 0 1px 5px rgba(0, 0, 0, 0.65);\n      border-radius: 4px;\n    }\n\n    .leaflet-bar a {\n      background-color: #fff;\n      background-position: 50% 50%;\n      background-repeat: no-repeat;\n      border-bottom: 1px solid #ccc;\n      width: 26px;\n      height: 26px;\n      line-height: 26px;\n      display: block;\n      text-align: center;\n      text-decoration: none;\n      color: black;\n    }\n\n    .leaflet-bar a:hover,\n    .leaflet-bar a:focus {\n      background-color: #f4f4f4;\n    }\n\n    .leaflet-bar a:first-child {\n      border-top-left-radius: 4px;\n      border-top-right-radius: 4px;\n    }\n\n    .leaflet-bar a:last-child {\n      border-bottom-left-radius: 4px;\n      border-bottom-right-radius: 4px;\n      border-bottom: none;\n    }\n\n    .leaflet-bar a.leaflet-disabled {\n      cursor: default;\n      background-color: #f4f4f4;\n      color: #bbb;\n    }\n\n    .leaflet-touch .leaflet-bar a {\n      width: 30px;\n      height: 30px;\n      line-height: 30px;\n    }\n\n    .leaflet-touch .leaflet-bar a:first-child {\n      border-top-left-radius: 2px;\n      border-top-right-radius: 2px;\n    }\n\n    .leaflet-touch .leaflet-bar a:last-child {\n      border-bottom-left-radius: 2px;\n      border-bottom-right-radius: 2px;\n    }\n\n    .leaflet-control-zoom-in,\n    .leaflet-control-zoom-out {\n      font:\n        bold 18px 'Lucida Console',\n        Monaco,\n        monospace;\n      text-indent: 1px;\n    }\n\n    .leaflet-touch .leaflet-control-zoom-in,\n    .leaflet-touch .leaflet-control-zoom-out {\n      font-size: 22px;\n    }\n\n    .leaflet-container .leaflet-control-attribution {\n      background: #fff;\n      background: rgba(255, 255, 255, 0.8);\n      margin: 0;\n    }\n\n    .leaflet-control-attribution {\n      padding: 0 5px;\n      color: #333;\n      line-height: 1.4;\n    }\n\n    .leaflet-control-attribution a {\n      text-decoration: none;\n    }\n\n    .leaflet-control-attribution a:hover,\n    .leaflet-control-attribution a:focus {\n      text-decoration: underline;\n    }\n\n    .leaflet-attribution-flag {\n      display: inline !important;\n      vertical-align: baseline !important;\n      width: 1em;\n      height: 0.6669em;\n    }\n\n    .leaflet-touch .leaflet-control-attribution,\n    .leaflet-touch .leaflet-bar {\n      box-shadow: none;\n    }\n\n    .leaflet-touch .leaflet-bar {\n      border: 2px solid rgba(0, 0, 0, 0.2);\n      background-clip: padding-box;\n    }\n  }\n\n  .map {\n    margin: var(--sui-focus-ring-width);\n    border: 1px solid var(--sui-textbox-border-color);\n    border-radius: var(--sui-textbox-border-radius);\n    overflow: hidden;\n    aspect-ratio: 1 / 1;\n    background-clip: text;\n  }\n\n  :global(.leaflet-container) {\n    font-family: inherit !important;\n    font-size: var(--sui-font-size-small) !important;\n  }\n\n  :global(.leaflet-container a) {\n    color: var(--sui-primary-accent-color-text) !important;\n    text-decoration: none !important;\n  }\n\n  :global(.leaflet-bar a) {\n    border-color: var(--sui-button-border-color) !important;\n    color: var(--sui-secondary-foreground-color) !important;\n    background-color: var(--sui-button-background-color) !important;\n  }\n\n  :global(.leaflet-control) {\n    color: var(--sui-secondary-foreground-color) !important;\n    background-color: var(--sui-secondary-background-color-translucent) !important;\n  }\n\n  :global(.leaflet-control-attribution) {\n    padding: 4px 8px;\n  }\n\n  /* Dark theme: https://stackoverflow.com/q/59819792 */\n  :global(:root[data-theme='dark'] .leaflet-layer) {\n    filter: invert(100%) hue-rotate(180deg);\n  }\n</style>\n","import { createLazyModule } from '$lib/services/api/lazy-module';\nimport { loadChunk } from '$lib/services/app/dependencies';\n\n/**\n * @import { LazyModule } from '$lib/services/api/lazy-module';\n */\n\n/**\n * @typedef {typeof import('$lib/chunks/map')} MapServices\n */\n\n/**\n * Loader of the Map field services. Few sites have the field, so the services are kept in the `map`\n * chunk and fetched when a Map field editor is opened. This module is imported by the editor, so it\n * stays in the main bundle while the rest of the directory goes into the chunk, see\n * `getChunkModules()` in `scripts/vite/chunk-modules.js`.\n * @type {LazyModule<MapServices>}\n */\nexport const mapServices = createLazyModule({\n  /**\n   * Fetch the chunk.\n   * @returns {Promise<MapServices>} Services.\n   */\n  loader: () => loadChunk('map'),\n  notLoadedMessage: 'The map chunk is not loaded yet.',\n});\n","<!--\n  @component\n  Implement the editor for a Map field.\n  @see https://decapcms.org/docs/widgets/#Map\n  @see https://sveltiacms.app/en/docs/fields/map\n  @see https://leafletjs.com/\n  @see https://github.com/JamesLMilner/terra-draw\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { AlertDialog, Button, Icon, Listbox, Option, SearchBar } from '@sveltia/ui';\n  import { onDestroy, tick, untrack } from 'svelte';\n\n  import LeafletMap from '$lib/components/common/leaflet-map.svelte';\n  import { mapServices } from '$lib/services/contents/fields/map/services';\n  import { watch, watchAsync } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import Leaflet from 'leaflet';\n   * @import { MapDrawController } from '$lib/services/contents/fields/map/draw';\n   * @import { LocationSearchResult } from '$lib/services/contents/fields/map/geocoding';\n   * @import { MapServices } from '$lib/services/contents/fields/map/services';\n   * @import { FieldEditorProps, GeoCoordinates } from '$lib/types/private';\n   * @import { MapField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {MapField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value. Stringified GeoJSON geometry object.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    fieldConfig,\n    currentValue = $bindable(),\n    // required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  const { decimals = 7, type: geometryType = 'Point', center, zoom } = $derived(fieldConfig);\n\n  /** @type {HTMLElement | undefined} */\n  let mapElement = $state();\n  /** @type {HTMLElement | undefined} */\n  let toolbar = $state();\n  /** @type {MapDrawController | undefined} */\n  let draw = $state.raw(undefined);\n  /** @type {string} */\n  let inputValue = $state('');\n  /** @type {string} */\n  let searchQuery = $state('');\n  /** @type {LocationSearchResult[] | undefined} */\n  let searchResults = $state(undefined);\n  /** @type {boolean} */\n  let searching = $state(false);\n  /** @type {boolean} */\n  let showAlertDialog = $state(false);\n  /** @type {string} */\n  let errorMessage = $state('');\n\n  /** Whether the component has been destroyed, possibly before the drawing tools are loaded. */\n  let destroyed = false;\n\n  // Fetch the services while Leaflet is loading, rather than once the map is ready\n  mapServices.preload();\n\n  /**\n   * Start the drawing tools once the Leaflet map is ready.\n   * @param {object} args Arguments.\n   * @param {Leaflet} args.leaflet Leaflet library.\n   * @param {Leaflet.Map} args.map Leaflet map instance.\n   */\n  const onReady = async ({ leaflet, map }) => {\n    const { createMapDrawController, isValidGeoJSON } = await mapServices.load();\n\n    const controller = await createMapDrawController({\n      leaflet,\n      map,\n      geometryType,\n      decimals,\n      /**\n       * Take the value of a feature the user has drawn.\n       * @param {string} value Stringified GeoJSON geometry.\n       */\n      onChange: (value) => {\n        inputValue = value;\n      },\n      /**\n       * Check whether the component has been destroyed while the libraries were loading.\n       * @returns {boolean} Result.\n       */\n      isCancelled: () => destroyed,\n    });\n\n    // The component may have been destroyed, and the map removed, while the libraries were loading\n    if (!controller) {\n      return;\n    }\n\n    draw = controller;\n\n    // The watcher below will handle fitting the map to an existing valid value. Apply the\n    // configured center/zoom defaults here for the case where there is no valid value\n    if (!currentValue || !isValidGeoJSON(currentValue, geometryType)) {\n      controller.showDefaultView({ center, zoom });\n    }\n  };\n\n  /**\n   * Update {@link inputValue} based on {@link currentValue}.\n   */\n  const setInputValue = () => {\n    if (!draw) {\n      return;\n    }\n\n    // Validate the value. The services are loaded before the drawing tools\n    const geometry = mapServices.get().parseGeoJSON(currentValue ?? '', geometryType);\n    const newValue = geometry ? /** @type {string} */ (currentValue) : '';\n\n    if (inputValue === newValue) {\n      return;\n    }\n\n    inputValue = newValue;\n    draw.showGeometry(geometry);\n  };\n\n  /**\n   * Update {@link currentValue} based on {@link inputValue}.\n   */\n  const setCurrentValue = () => {\n    if (!draw) {\n      return;\n    }\n\n    const newValue = inputValue;\n\n    // Avoid a cycle dependency & infinite loop\n    if (currentValue !== newValue) {\n      currentValue = newValue;\n    }\n  };\n\n  /**\n   * Set the location on the map editor.\n   * @param {GeoCoordinates} coordinates GeoCoordinates of the location to set.\n   */\n  const setLocation = (coordinates) => {\n    /* v8 ignore next 3 -- the drawing tools are loaded right after the map, before any input */\n    if (!draw) {\n      return;\n    }\n\n    const value = draw.setLocation(coordinates);\n\n    if (value !== undefined) {\n      inputValue = value;\n    }\n  };\n\n  /**\n   * Handle the selection of a search result. Move the map to the selected location and add a point\n   * feature to the map.\n   * @param {LocationSearchResult} result Selected search result.\n   */\n  const onSearchResultSelect = ({ lat, lon }) => {\n    setLocation({ latitude: parseFloat(lat), longitude: parseFloat(lon) });\n  };\n\n  /**\n   * Use the browser’s geolocation API to get the current location of the user and set it as the\n   * value of the map editor. This function is called when the Use Current Location button is\n   * clicked. It retrieves the user’s current position and updates the map with a point feature at\n   * the user’s location.\n   * @see https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API\n   */\n  const useCurrentLocation = async () => {\n    /** @type {MapServices | undefined} */\n    let services;\n    /** @type {GeoCoordinates} */\n    let coordinates;\n\n    try {\n      services = await mapServices.load();\n      coordinates = await services.getCurrentPosition();\n    } catch (error) {\n      showAlertDialog = true;\n\n      // A failure to load the services is reported as any other error\n      if (services && error instanceof services.GeolocationUnsupportedError) {\n        errorMessage = _('geolocation_unsupported');\n      } else {\n        errorMessage = _('geolocation_error_body');\n        // eslint-disable-next-line no-console\n        console.error('Error getting current location:', error);\n      }\n\n      return;\n    }\n\n    setLocation(coordinates);\n  };\n\n  /**\n   * Clear the current value of the map editor. This is called when the Clear button is clicked.\n   * It sets the `currentValue` to an empty string, effectively clearing the map. The Clear button\n   * is then disabled, which would drop its focus, so the place search box takes it.\n   */\n  const clearValue = async () => {\n    currentValue = '';\n    await tick();\n    /** @type {HTMLInputElement} */ (\n      /** @type {HTMLElement} */ (toolbar).querySelector('input')\n    ).focus();\n  };\n\n  onDestroy(() => {\n    destroyed = true;\n    draw?.stop();\n  });\n\n  watch(\n    () => [draw, currentValue],\n    () => {\n      setInputValue();\n    },\n  );\n\n  watch(\n    () => inputValue,\n    () => {\n      setCurrentValue();\n    },\n  );\n\n  // Search for locations matching the query. The debounced search bar can send another query\n  // before the results for the previous one arrive, which `watchAsync` takes care of\n  watchAsync(\n    () => {\n      const query = searchQuery;\n\n      if (!query.trim()) {\n        searching = false;\n\n        return undefined;\n      }\n\n      searching = true;\n\n      return untrack(async () => (await mapServices.load()).searchLocations(query));\n    },\n    (results) => {\n      searchResults = results;\n      searching = false;\n    },\n    () => {\n      // The services failed to load: show no results, as `searchLocations()` does on an error\n      searchResults = [];\n      searching = false;\n    },\n  );\n</script>\n\n<div role=\"none\" class=\"toolbar\" bind:this={toolbar}>\n  <!-- @todo Replace this with `<Combobox>` -->\n  <SearchBar\n    bind:value={searchQuery}\n    debounce\n    {readonly}\n    flex\n    placeholder={_('find_place')}\n    aria-label={_('find_place')}\n  />\n  <Button\n    variant=\"tertiary\"\n    iconic\n    tooltip={_('use_your_location')}\n    aria-label={_('use_your_location')}\n    disabled={readonly}\n    onclick={() => {\n      useCurrentLocation();\n    }}\n  >\n    {#snippet startIcon()}\n      <Icon name=\"near_me\" />\n    {/snippet}\n  </Button>\n  <Button\n    variant=\"tertiary\"\n    label={_('clear')}\n    disabled={readonly || !currentValue}\n    onclick={() => {\n      clearValue();\n    }}\n  />\n</div>\n\n{#if searching}\n  <div role=\"alert\" class=\"search-result searching\">{_('searching')}</div>\n{:else if searchQuery}\n  {#if searchResults}\n    {#if searchResults.length}\n      <Listbox ariaLabel={_('search_results')}>\n        {#each searchResults as result (result.place_id)}\n          <Option\n            label={result.display_name}\n            onSelect={() => {\n              onSearchResultSelect(result);\n            }}\n          />\n        {/each}\n      </Listbox>\n    {:else}\n      <div role=\"alert\" class=\"search-result no-result\">{_('no_results')}</div>\n    {/if}\n  {/if}\n{/if}\n\n<div class=\"map-wrapper\">\n  <LeafletMap bind:mapElement inert={readonly} class={invalid ? 'invalid' : undefined} {onReady} />\n</div>\n\n<AlertDialog bind:open={showAlertDialog} title={_('geolocation_error_title')}>\n  {errorMessage}\n</AlertDialog>\n\n<style>\n  .toolbar {\n    display: flex;\n    align-items: center;\n    margin-bottom: var(--sui-spacing-2x);\n  }\n\n  .search-result {\n    padding: 12px;\n    color: var(--sui-secondary-foreground-color);\n  }\n\n  .map-wrapper {\n    display: contents;\n\n    :global {\n      .map {\n        aspect-ratio: auto;\n        height: 400px;\n\n        &.invalid {\n          border-color: var(--sui-error-border-color);\n        }\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the preview for a Map field.\n  @see https://decapcms.org/docs/widgets/#Map\n  @see https://sveltiacms.app/en/docs/fields/map\n-->\n<script>\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { MapField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {MapField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value. Stringified GeoJSON geometry object.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { currentValue } = $props();\n</script>\n\n{#if currentValue}\n  <pre>{currentValue}</pre>\n{/if}\n\n<style>\n  pre {\n    white-space: pre-wrap;\n  }\n</style>\n","<!--\n  @component\n  Implement the editor for a Number field.\n  @see https://decapcms.org/docs/widgets/#Number\n  @see https://sveltiacms.app/en/docs/fields/number\n-->\n<script>\n  import { NumberInput } from '@sveltia/ui';\n\n  import {\n    getNumberFieldValue,\n    getNumberInputValue,\n    isFloatType,\n  } from '$lib/services/contents/fields/number/helpers';\n  import { syncValues } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { NumberField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {NumberField} fieldConfig Field configuration.\n   * @property {string | number | null | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  /** @type {number | undefined} */\n  let inputValue = $state();\n  /**\n   * Text in the input, which `inputValue` is `undefined` for if it can’t be parsed as a number.\n   */\n  let inputText = $state('');\n\n  const { min, max, step = 1 } = $derived(fieldConfig);\n\n  /**\n   * Get the input value, or the text in the input if it holds something other than a number, so\n   * that text is stored and reported as invalid rather than silently stored as an empty value.\n   * @returns {number | string | undefined} Input value.\n   */\n  const getInput = () => (inputValue === undefined && inputText.trim() ? inputText : inputValue);\n\n  // Sync `inputValue` with `currentValue` in both directions, casting the value according to the\n  // `value_type` configuration\n  const { updateInput } = syncValues(\n    () => currentValue,\n    (value) => {\n      currentValue = value;\n    },\n    getInput,\n    (input) => {\n      // A string, the text in the input, is only converted from the stored value when it’s the\n      // input already, so it never gets here\n      inputValue = /** @type {number | undefined} */ (input);\n    },\n    (value) => getNumberInputValue({ currentValue: value, fieldConfig, inputValue: getInput() }),\n    (input) => getNumberFieldValue({ inputValue: input, fieldConfig }),\n  );\n</script>\n\n<NumberInput\n  bind:value={inputValue}\n  {min}\n  {max}\n  {step}\n  fractional={isFloatType(fieldConfig)}\n  {readonly}\n  {required}\n  {invalid}\n  aria-labelledby=\"{fieldId}-label\"\n  aria-errormessage=\"{fieldId}-error\"\n  oninput={(event) => {\n    inputText = /** @type {HTMLInputElement} */ (event.target).value;\n  }}\n  onblur={() => {\n    // Ensure synchronization on blur\n    updateInput();\n  }}\n/>\n","<!--\n  @component\n  Implement the preview for a Number field.\n  @see https://decapcms.org/docs/widgets/#Number\n  @see https://sveltiacms.app/en/docs/fields/number\n-->\n<script>\n  import { getNumberFormatter } from '$lib/services/contents/fields/number/helpers';\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { NumberField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {NumberField} fieldConfig Field configuration.\n   * @property {string | number | null | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, currentValue } = $props();\n\n  const canonicalLocale = $derived(getCanonicalLocale(locale));\n  const number = $derived(Number(currentValue));\n  // Text that isn’t a number, which the editor stores so it can be reported as invalid, is shown as\n  // is rather than as `NaN`\n  const displayValue = $derived(\n    Number.isNaN(number) ? currentValue : getNumberFormatter(canonicalLocale).format(number),\n  );\n</script>\n\n{#if currentValue !== undefined && currentValue !== null && currentValue !== ''}\n  <p lang={canonicalLocale} dir={getDirection(locale)}>\n    {displayValue}\n  </p>\n{/if}\n","import { toRaw } from '@sveltia/utils/object';\n\nimport { suspendAutoDuplication } from '$lib/services/contents/draft';\nimport { getDefaultValues } from '$lib/services/contents/draft/defaults';\nimport {\n  copyDefaultLocaleValues,\n  forEachTargetLocale,\n} from '$lib/services/contents/draft/update/locale';\nimport { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\n\n/**\n * @import {\n * DraftValueStoreKey,\n * EntryDraft,\n * InternalLocaleCode,\n * RemovedObjectValues,\n * } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * ObjectField,\n * ObjectFieldWithSubFields,\n * ObjectFieldWithTypes,\n * } from '$lib/types/public';\n */\n\n/**\n * Add the subfields of an Object field to the entry draft, populated with their default values. For\n * a field with variable types, the type is written first and the subfields of that type are added.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @param {FieldKeyPath} args.keyPath Key path of the Object field.\n * @param {ObjectField} args.fieldConfig Field configuration.\n * @param {string} [args.type] Variable type name. `undefined` if the field doesn’t have variable\n * types.\n */\nexport const addObjectFields = ({\n  draft,\n  valueStoreKey = 'currentValues',\n  locale,\n  keyPath,\n  fieldConfig,\n  type,\n}) => {\n  const { i18n = false } = fieldConfig;\n  const { types, typeKey = 'type' } = /** @type {ObjectFieldWithTypes} */ (fieldConfig);\n  const { fields } = /** @type {ObjectFieldWithSubFields} */ (fieldConfig);\n  const valueStore = draft[valueStoreKey];\n  /** @type {Field[]} */\n  const subFields = (type ? types?.find(({ name }) => name === type)?.fields : fields) ?? [];\n  // A rich text editor component’s values live in the document of the locale they’re edited in,\n  // so its subfields get their defaults in every locale, with nothing to copy from the default\n  // locale, unlike an entry field\n  const defaultLocale = valueStoreKey === 'extraValues' ? locale : draft.defaultLocale;\n\n  // Avoid triggering the Proxy’s i18n duplication strategy for descendant fields\n  suspendAutoDuplication(() => {\n    if (type) {\n      forEachTargetLocale({ valueStore, locale, i18n, draft, keyPath }, (valueMap) => {\n        valueMap[`${keyPath}.${typeKey}`] = type;\n      });\n    }\n\n    const newContent = Object.fromEntries(\n      Object.entries(getDefaultValues({ fields: subFields, locale, defaultLocale })).map(\n        ([_keyPath, value]) => [`${keyPath}.${_keyPath}`, value],\n      ),\n    );\n\n    const newValueMap =\n      locale === defaultLocale\n        ? newContent\n        : copyDefaultLocaleValues({\n            draft,\n            content: newContent,\n            targetLanguage: locale,\n            keyPathPrefix: keyPath,\n          });\n\n    forEachTargetLocale({ valueStore, locale, i18n, draft, keyPath }, (valueMap) => {\n      // Apply the new values through the Proxy, keeping any value already there\n      Object.assign(valueMap, toRaw({ ...newValueMap, ...valueMap }));\n\n      // Disable validation\n      delete valueMap[keyPath];\n    });\n  });\n};\n\n/**\n * Remove the subfields of an Object field from the entry draft.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @param {FieldKeyPath} args.keyPath Key path of the Object field.\n * @param {ObjectField} args.fieldConfig Field configuration.\n * @returns {RemovedObjectValues} Removed values, so they can be put back with\n * {@link restoreObjectFields}. They’re keyed by their key path relative to the object’s, as the\n * object may have moved by then, e.g. along with a list item.\n */\nexport const removeObjectFields = ({\n  draft,\n  valueStoreKey = 'currentValues',\n  locale,\n  keyPath,\n  fieldConfig,\n}) => {\n  const { i18n = false } = fieldConfig;\n  /** @type {RemovedObjectValues} */\n  const removedValues = {};\n\n  forEachTargetLocale(\n    { valueStore: draft[valueStoreKey], locale, i18n, draft, keyPath },\n    (valueMap, targetLocale) => {\n      /** @type {Record<FieldKeyPath, any>} */\n      const values = {};\n\n      // Assign `null` before deleting each property, so the draft proxy can revalidate the field.\n      // The value map is the draft’s live map, which is mutated right below, so its key paths have\n      // to be read as they are right now\n      getKeysByPrefix(valueMap, `${keyPath}.`, { live: true }).forEach((_keyPath) => {\n        values[_keyPath.slice(keyPath.length)] = toRaw(valueMap[_keyPath]);\n        valueMap[_keyPath] = null;\n        delete valueMap[_keyPath];\n      });\n\n      removedValues[targetLocale] = values;\n      // Enable validation\n      valueMap[keyPath] = null;\n    },\n  );\n\n  return removedValues;\n};\n\n/**\n * Put back the subfields of an Object field removed with {@link removeObjectFields}, in the locales\n * they were removed from, under the object’s current key path.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} [args.valueStoreKey] Key to store the values in {@link EntryDraft}.\n * @param {FieldKeyPath} args.keyPath Key path of the Object field.\n * @param {RemovedObjectValues} args.removedValues Removed values.\n */\nexport const restoreObjectFields = ({\n  draft,\n  valueStoreKey = 'currentValues',\n  keyPath,\n  removedValues,\n}) => {\n  // Avoid triggering the Proxy’s i18n duplication strategy for descendant fields, as the values are\n  // put back in each locale they were removed from\n  suspendAutoDuplication(() => {\n    Object.entries(removedValues).forEach(([locale, values]) => {\n      const valueMap = draft[valueStoreKey][locale];\n\n      // The locale may have been disabled since\n      if (!valueMap) {\n        return;\n      }\n\n      Object.entries(values).forEach(([suffix, value]) => {\n        valueMap[`${keyPath}${suffix}`] = value;\n      });\n\n      // Disable validation\n      delete valueMap[keyPath];\n    });\n  });\n};\n","<!--\n  @component\n  Implement the editor for an Object field.\n  @see https://decapcms.org/docs/widgets/#Object\n  @see https://sveltiacms.app/en/docs/fields/object\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Checkbox } from '@sveltia/ui';\n  import { onMount, tick } from 'svelte';\n\n  import RemoveButton from '$lib/components/common/remove-button.svelte';\n  import AddItemButton from '$lib/components/contents/details/fields/object/add-item-button.svelte';\n  import ObjectBody from '$lib/components/contents/details/fields/object/object-body.svelte';\n  import ObjectHeader from '$lib/components/contents/details/fields/object/object-header.svelte';\n  import RemovedItemNotice from '$lib/components/contents/details/fields/object/removed-item-notice.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    addObjectFields,\n    removeObjectFields,\n    restoreObjectFields,\n  } from '$lib/services/contents/draft/update/object';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getFieldEditorContext } from '$lib/services/contents/editor/field-context';\n  import {\n    getInitialExpanderState,\n    isExpanded,\n    syncExpanderStates,\n  } from '$lib/services/contents/editor/fields';\n  import { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\n  import {\n    formatSummary,\n    getTypedSubKeyPath,\n    resolveVariableType,\n    warnUnknownType,\n  } from '$lib/services/contents/fields/object/helpers';\n  import { getDraftObjectThumbnail } from '$lib/services/contents/fields/object/thumbnail';\n  import { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n  /**\n   * @import {\n   * EntryDraft,\n   * FieldEditorProps,\n   * InternalLocaleCode,\n   * MediaFieldSource,\n   * RemovedObjectValues,\n   * } from '$lib/types/private';\n   * @import {\n   * ObjectField,\n   * ObjectFieldWithSubFields,\n   * ObjectFieldWithTypes,\n   * } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ObjectField} fieldConfig Field configuration.\n   * @property {object | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const {\n    fieldContext,\n    valueStoreKey = 'currentValues',\n    parentComponentNames = [],\n  } = getFieldEditorContext();\n  const componentName = parentComponentNames.at(-1);\n  // Hide the header/expander if in a single subfield list field because it’s redundant\n  const hideHeader = fieldContext === 'single-subfield-list-field';\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldLabel,\n    fieldConfig,\n    required = true,\n    // `FieldEditor` only renders the editor in a locale where the field is shown, and makes it\n    // read-only in a locale whose values follow the default locale\n    readonly = false,\n  } = $props();\n\n  const fieldId = $props.id();\n\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n  /**\n   * Values removed with the Remove button or the checkbox, along with the locale they were removed\n   * in, which can be restored while the object is gone.\n   * @type {{ locale: InternalLocaleCode, values: RemovedObjectValues } | undefined}\n   */\n  let removed = $state.raw();\n\n  const {\n    name: fieldName,\n    // Field type-specific options\n    collapsed,\n    summary,\n    thumbnail: thumbnailFieldName,\n  } = $derived(fieldConfig);\n  const { fields } = $derived(/** @type {ObjectFieldWithSubFields} */ (fieldConfig));\n  const { types, typeKey = 'type' } = $derived(/** @type {ObjectFieldWithTypes} */ (fieldConfig));\n  /* v8 ignore start -- the editor is only rendered while the draft is there */\n  const isIndexFile = $derived(entryDraft.current?.isIndexFile ?? false);\n  const collectionName = $derived(entryDraft.current?.collectionName ?? '');\n  /* v8 ignore stop */\n  const fileName = $derived(entryDraft.current?.fileName);\n  const valueMap = $derived(\n    getFieldValueMapSnapshot(entryDraft.current, locale, keyPath, valueStoreKey),\n  );\n  const getFieldArgs = $derived({ collectionName, fileName, valueMap, isIndexFile });\n  // Ask the shared key path index rather than scanning the whole value map: the editor renders one\n  // component per field, and a large entry would otherwise be walked once per Object field on\n  // every keystroke\n  const hasValues = $derived(\n    getKeysByPrefix(valueMap, `${keyPath}.`).some((_keyPath) => valueMap[_keyPath] !== undefined),\n  );\n  const parentExpandedKeyPath = $derived(`${keyPath}#`);\n  const parentExpanded = $derived(isExpanded(entryDraft.current, parentExpandedKeyPath));\n  const hasVariableTypes = $derived(Array.isArray(types));\n  const typeKeyPath = $derived(`${keyPath}.${typeKey}`);\n  // The editor isn’t created again for another locale, so the removed values are only offered in\n  // the locale they were removed in\n  const canRestore = $derived(!hasValues && removed?.locale === locale);\n  /* v8 ignore start -- only read for an object with variable types */\n  const type = $derived(hasVariableTypes ? valueMap[typeKeyPath] : undefined);\n  /* v8 ignore stop */\n  const { typeConfig, unknownType, subFields, summaryTemplate } = $derived(\n    resolveVariableType({ types: hasVariableTypes ? types : undefined, fields, summary, type }),\n  );\n  // An unknown type is labelled with its name\n  const typeLabel = $derived(typeConfig ? getFieldLabel({ config: typeConfig, locale }) : type);\n\n  /**\n   * Initialize the expander state.\n   */\n  const initializeExpanderState = () => {\n    const draft = entryDraft.current;\n\n    if (hideHeader || !draft) {\n      return;\n    }\n\n    const key = parentExpandedKeyPath;\n\n    syncExpanderStates({\n      draft,\n      stateMap: { [key]: getInitialExpanderState({ draft, key, locale, collapsed }) },\n    });\n  };\n\n  /**\n   * Add the object’s subfields to the entry draft with the default values populated.\n   * @param {object} [args] Arguments.\n   * @param {string} [args.type] Variable type name. If the field doesn’t have variable types, it\n   * will be `undefined`.\n   */\n  const addFields = ({ type: _type } = {}) => {\n    const draft = entryDraft.current;\n\n    /* v8 ignore next 3 -- the button is only offered while the draft is there */\n    if (!draft) {\n      return;\n    }\n\n    addObjectFields({ draft, valueStoreKey, locale, keyPath, fieldConfig, type: _type });\n    removed = undefined;\n  };\n\n  /**\n   * Remove the object’s subfields from the entry draft.\n   */\n  const removeFields = () => {\n    removed = {\n      locale,\n      values: removeObjectFields({\n        // The Remove button is only offered while the draft is there\n        draft: /** @type {EntryDraft} */ (entryDraft.current),\n        valueStoreKey,\n        locale,\n        keyPath,\n        fieldConfig,\n      }),\n    };\n  };\n\n  /**\n   * Move the focus to the object’s expander button. The header is hidden within a single-subfield\n   * list, whose item has an expander of its own.\n   */\n  const focusExpander = () => {\n    /** @type {HTMLElement | null} */ (\n      /** @type {HTMLElement} */ (wrapper).querySelector(':scope > .header button')\n    )?.focus();\n  };\n\n  /**\n   * Put back the removed values. The Restore button is gone along with the notice once the object\n   * takes its place, so move the focus to the object’s expander button.\n   */\n  const restoreFields = async () => {\n    restoreObjectFields({\n      // The Restore button is only offered while the draft is there, with the removed values\n      draft: /** @type {EntryDraft} */ (entryDraft.current),\n      valueStoreKey,\n      keyPath,\n      removedValues: /** @type {{ values: RemovedObjectValues }} */ (removed).values,\n    });\n    removed = undefined;\n    await tick();\n    focusExpander();\n  };\n\n  /**\n   * Add the subfields of the type picked from the Add menu. The menu button is gone along with the\n   * menu once the object takes its place, so move the focus to the object’s expander button.\n   * @param {object} args Arguments.\n   * @param {string} [args.type] Variable type name.\n   */\n  const addTypedFields = async ({ type: _type }) => {\n    addFields({ type: _type });\n    await tick();\n    focusExpander();\n  };\n\n  /**\n   * Remove the subfields of an object with variable types. The focused Remove button is gone along\n   * with them, so move the focus to the Restore button shown in the object’s place, so it can be\n   * restored right away.\n   */\n  const removeTypedFields = async () => {\n    removeFields();\n    await tick();\n    document.getElementById(`object-${fieldId}-restore`)?.focus();\n  };\n\n  /**\n   * Format the summary template.\n   * @returns {string} Formatted summary.\n   */\n  const _formatSummary = () => formatSummary({ ...getFieldArgs, keyPath, locale, summaryTemplate });\n\n  /**\n   * Get the thumbnail of the collapsed object.\n   * @returns {MediaFieldSource | undefined} Thumbnail.\n   */\n  const getThumbnail = () =>\n    getDraftObjectThumbnail({\n      draft: entryDraft.current,\n      thumbnailFieldName,\n      keyPath,\n      typedKeyPath,\n      type,\n      componentName,\n      valueMap,\n      locale,\n    });\n\n  // Worked out only while the object is collapsed, and shared with the body showing them\n  const summaryText = $derived(_formatSummary());\n  const thumbnailSource = $derived(getThumbnail());\n  const summaryId = `object-${fieldId}-summary`;\n  // The summary labels the object while collapsed, but the body only renders it for a known type\n  // if there’s something to show\n  const labelledBy = $derived(\n    !parentExpanded && !unknownType && (summaryText || thumbnailSource) ? summaryId : undefined,\n  );\n\n  onMount(() => {\n    initializeExpanderState();\n\n    if (hasValues && unknownType) {\n      warnUnknownType({ fieldType: 'object', keyPath, type, typeKey, types });\n    }\n  });\n</script>\n\n{#if !hasVariableTypes && !required}\n  <Checkbox\n    label={_('add_x', { values: { name: fieldLabel || fieldName } })}\n    checked={hasValues}\n    disabled={readonly}\n    onChange={({ detail: { checked } }) => {\n      if (checked) {\n        addFields();\n      } else {\n        removeFields();\n      }\n    }}\n  />\n{/if}\n\n{#if hasVariableTypes && !hasValues}\n  <AddItemButton\n    disabled={readonly}\n    {fieldConfig}\n    {locale}\n    addItem={(args) => addTypedFields(/** @type {{ type: string }} */ (args))}\n  />\n{/if}\n\n{#if canRestore}\n  <div role=\"none\" class=\"removed-item\">\n    <RemovedItemNotice\n      id=\"object-{fieldId}-restore\"\n      disabled={readonly}\n      onRestore={restoreFields}\n    />\n  </div>\n{/if}\n\n{#if !(!required || hasVariableTypes) || hasValues}\n  <div\n    bind:this={wrapper}\n    role=\"group\"\n    class=\"wrapper\"\n    class:object-unknown-type={unknownType}\n    class:expanded={parentExpanded}\n    aria-labelledby={labelledBy}\n  >\n    {#if !hideHeader}\n      <ObjectHeader\n        label={hasVariableTypes ? typeLabel : ''}\n        controlId=\"object-{fieldId}-item-list\"\n        expanded={parentExpanded}\n        expandable={subFields.length > 0}\n        toggleExpanded={() =>\n          syncExpanderStates({\n            draft: /** @type {EntryDraft} */ (entryDraft.current),\n            stateMap: { [parentExpandedKeyPath]: !parentExpanded },\n          })}\n      >\n        {#snippet endContent()}\n          {#if hasVariableTypes}\n            <RemoveButton\n              disabled={readonly}\n              onclick={() => {\n                removeTypedFields();\n              }}\n            />\n          {/if}\n        {/snippet}\n      </ObjectHeader>\n    {/if}\n    <div role=\"none\" class=\"item-list\" id=\"object-{fieldId}-item-list\">\n      <ObjectBody\n        {locale}\n        {subFields}\n        getSubFieldProps={(subField) => ({\n          keyPath: `${keyPath}.${subField.name}`,\n          typedKeyPath: getTypedSubKeyPath({ typedKeyPath, type, subFieldName: subField.name }),\n        })}\n        expanded={parentExpanded}\n        {unknownType}\n        {typeConfig}\n        {readonly}\n        getSummary={() => summaryText}\n        getThumbnail={() => thumbnailSource}\n        {summaryId}\n      />\n    </div>\n  </div>\n{/if}\n\n<style>\n  .wrapper {\n    border-inline-width: 2px;\n    border-color: var(--sui-secondary-border-color);\n    border-radius: var(--sui-control-medium-border-radius);\n\n    &.expanded,\n    &:has(:global(.summary)) {\n      border-bottom-width: 2px;\n    }\n  }\n\n  .removed-item {\n    margin-top: 8px;\n  }\n\n  :global(.sui.checkbox) + .wrapper {\n    & > :global(.group) {\n      margin-top: 8px;\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the preview for an Object field.\n  @see https://decapcms.org/docs/widgets/#Object\n  @see https://sveltiacms.app/en/docs/fields/object\n-->\n<script>\n  import SubfieldPreviews from '$lib/components/contents/details/fields/object/subfield-previews.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\n  import { isValueEmpty } from '$lib/services/utils/object';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import {\n   * ObjectField,\n   * ObjectFieldWithSubFields,\n   * ObjectFieldWithTypes,\n   * } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ObjectField} fieldConfig Field configuration.\n   * @property {object | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, keyPath, typedKeyPath, fieldConfig } = $props();\n\n  const { fields } = $derived(/** @type {ObjectFieldWithSubFields} */ (fieldConfig));\n  const { types, typeKey = 'type' } = $derived(/** @type {ObjectFieldWithTypes} */ (fieldConfig));\n  const valueMap = $derived(getFieldValueMapSnapshot(entryDraft.current, locale, keyPath));\n  // Ask the shared key path index rather than scanning the whole value map, like the Object field\n  // editor does. Unlike the editor, which asks whether the object is there at all, this asks\n  // whether there’s anything to show: a number, `0` included, is, but `false`, which a Boolean\n  // field holds until it’s turned on, isn’t\n  const hasValues = $derived(\n    getKeysByPrefix(valueMap, `${keyPath}.`).some((_keyPath) => {\n      const value = valueMap[_keyPath];\n\n      return value !== false && !isValueEmpty(value);\n    }),\n  );\n  const hasVariableTypes = $derived(Array.isArray(types));\n  const typeKeyPath = $derived(`${keyPath}.${typeKey}`);\n  const type = $derived(hasVariableTypes ? valueMap[typeKeyPath] : undefined);\n</script>\n\n{#if hasValues}\n  <SubfieldPreviews {locale} {keyPath} {typedKeyPath} {types} {fields} {type} />\n{/if}\n","<!--\n  @component\n  Show that a locale is disabled on the entry draft, with a button to enable it, in place of the\n  locale’s fields. Used by the entry editor’s pane and the Relation field’s quick-add dialog, so a\n  disabled locale can’t be edited without enabling it first.\n  @see https://github.com/sveltia/sveltia-cms/issues/1176\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, EmptyState } from '@sveltia/ui';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { toggleLocale } from '$lib/services/contents/draft/update/locale';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n  import { isDraftLocked } from '$lib/services/workflow';\n\n  /**\n   * @import { InternalLocaleCode } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Disabled locale.\n   */\n\n  /** @type {Props} */\n  let { locale } = $props();\n\n  const entryDraft = getEntryDraftContext();\n\n  const hasContent = $derived(!!entryDraft.current?.currentValues[locale]);\n  // A locked entry is shown for reference only, so its locales can’t be enabled\n  const locked = $derived(isDraftLocked(entryDraft.current));\n  /* v8 ignore start -- a locale configured for the site always has a label */\n  const labelOptions = $derived({ values: { locale: getLocaleLabel(locale) ?? locale } });\n  /* v8 ignore stop */\n</script>\n\n<EmptyState>\n  <span role=\"alert\">\n    {_(hasContent ? 'locale_x_now_disabled' : 'locale_x_has_been_disabled', labelOptions)}\n  </span>\n  {#if !locked}\n    <Button\n      variant=\"tertiary\"\n      label={_(hasContent ? 'reenable_x_locale' : 'enable_x_locale', labelOptions)}\n      onclick={() => {\n        /* v8 ignore next 3 -- the draft is there while the component is rendered */\n        if (entryDraft.current) {\n          toggleLocale({ draft: entryDraft.current, locale });\n        }\n      }}\n    />\n  {/if}\n</EmptyState>\n","<script>\n  import { Icon, TreeItem } from '@sveltia/ui';\n\n  // The component recursively renders itself for the child folders\n  import ParentFolderTreeItem from '$lib/components/contents/details/editor/parent-folder-tree-item.svelte';\n\n  /**\n   * @import { NestedTreeNode } from '$lib/services/contents/collection/nested/tree';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {NestedTreeNode} node Folder to display.\n   * @property {string} selectedPath Path of the folder the entry is currently filed in.\n   * @property {(path: string) => void} onSelectPath Called with the path of the chosen folder.\n   */\n\n  /** @type {Props} */\n  let { node, selectedPath, onSelectPath } = $props();\n\n  const { path, label, children } = $derived(node);\n  const selected = $derived(selectedPath === path);\n  // Keep the branch that holds the current folder open, so it can be seen without any digging\n  const expanded = $derived(!path || selected || selectedPath.startsWith(`${path}/`));\n</script>\n\n{#snippet childItems()}\n  {#each children as child (child.path)}\n    <ParentFolderTreeItem node={child} {selectedPath} {onSelectPath} />\n  {/each}\n{/snippet}\n\n<TreeItem\n  {label}\n  {selected}\n  {expanded}\n  items={children.length ? childItems : undefined}\n  onSelect={() => {\n    onSelectPath(path);\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name={path ? 'folder' : 'bookmark_manager'} />\n  {/snippet}\n</TreeItem>\n","import { compare } from '@sveltia/utils/string';\n\nimport {\n  DEFAULT_INDEX_FILE_NAMES,\n  getEntryDirPath,\n  getNestedConfig,\n  getSharedEntryFileName,\n} from '$lib/services/contents/collection/nested';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { getBaseName } from '$lib/services/utils/file';\n\n/**\n * @import { Entry, InternalCollection, InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * A folder within a collection with nested entries, shown as an item in the collection tree.\n * @typedef {object} NestedTreeNode\n * @property {string} path Directory path relative to the collection folder, without leading and\n * trailing slashes.\n * @property {string} label Human-readable label.\n * @property {NestedTreeNode[]} children Child folders, sorted by label.\n */\n\n/**\n * Count the segments of a path.\n * @param {string} path Path relative to the collection folder, e.g. `about/team`.\n * @returns {number} Number of segments, `0` for the collection folder itself.\n */\nconst countSegments = (path) => (path ? path.split('/').length : 0);\n\n/**\n * Rate how well an entry represents the folder it’s stored in, so a folder that holds more than one\n * entry is labelled with its index file rather than with whichever entry happens to come first.\n * @param {string} fileName Entry’s file name, without an extension.\n * @param {string | undefined} indexFileName Configured index file name, if any.\n * @returns {number} `2` for a folder’s own entry, `1` for a usable fallback, `0` for an entry that\n * must not label the folder.\n * @see https://github.com/decaporg/decap-cms/issues/7651\n */\nconst getIndexEntryRank = (fileName, indexFileName) => {\n  if (indexFileName) {\n    return fileName === indexFileName ? 2 : 0;\n  }\n\n  return DEFAULT_INDEX_FILE_NAMES.includes(fileName) ? 2 : 1;\n};\n\n/**\n * Collect every folder that holds an entry, along with all of their ancestors, and remember the\n * entry that gives each folder its label.\n * @param {object} args Arguments.\n * @param {Entry[]} args.entries Entries in the collection.\n * @param {string | undefined} args.indexFileName Shared index file name, if configured.\n * @param {boolean} args.subfolders Whether the collection uses the `subfolders` mode.\n * @returns {Map<string, Entry | undefined>} Key is a folder path, value is the folder’s index\n * entry, which is only looked up in the `subfolders` mode.\n */\nconst collectFolders = ({ entries, indexFileName, subfolders }) => {\n  /** @type {Map<string, Entry | undefined>} */\n  const folders = new Map();\n  /** @type {Map<string, number>} */\n  const ranks = new Map();\n\n  entries.forEach((entry) => {\n    const dirPath = getEntryDirPath(entry.subPath);\n\n    if (!dirPath) {\n      return;\n    }\n\n    if (subfolders) {\n      const fileName = entry.subPath.slice(dirPath.length + 1);\n      const rank = getIndexEntryRank(fileName, indexFileName);\n\n      if (rank > (ranks.get(dirPath) ?? 0)) {\n        ranks.set(dirPath, rank);\n        folders.set(dirPath, entry);\n      } else if (!folders.has(dirPath)) {\n        folders.set(dirPath, undefined);\n      }\n    } else if (!folders.has(dirPath)) {\n      folders.set(dirPath, undefined);\n    }\n\n    // Register the ancestors, which don’t necessarily hold an entry of their own\n    let ancestorPath = getEntryDirPath(dirPath);\n\n    while (ancestorPath && !folders.has(ancestorPath)) {\n      folders.set(ancestorPath, undefined);\n      ancestorPath = getEntryDirPath(ancestorPath);\n    }\n  });\n\n  return folders;\n};\n\n/**\n * Get the label for a folder in the collection tree.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {string} args.path Folder path.\n * @param {Entry | undefined} args.indexEntry Entry that represents the folder, if any.\n * @param {string | undefined} args.summaryTemplate Summary template from the `nested.summary`\n * option.\n * @param {InternalLocaleCode} [args.locale] Locale to label the folder in. Defaults to the default\n * locale.\n * @returns {string} Label.\n */\nconst getNodeLabel = ({ collection, path, indexEntry, summaryTemplate, locale }) => {\n  const folderName = getBaseName(path);\n\n  if (!indexEntry) {\n    return folderName;\n  }\n\n  return (\n    getEntrySummary(collection, indexEntry, {\n      locale,\n      useTemplate: true,\n      template: summaryTemplate,\n    }) || folderName\n  );\n};\n\n/**\n * Build a folder tree for a collection with nested entries.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {Entry[]} args.entries Entries in the collection.\n * @param {boolean} args.pruneLeaves Whether to leave out a folder that has no subfolder of its own.\n * @param {string} [args.excludePath] Folder to leave out along with everything below it.\n * @param {number} [args.maxDepth] Number of path segments a folder can have at most. A deeper one\n * is left out along with everything below it.\n * @param {InternalLocaleCode} [args.locale] Locale to label the folders in.\n * @returns {NestedTreeNode[]} Top-level folders, sorted by label. An empty array if the collection\n * has no nested entries or has no folder to show.\n */\nconst buildTree = ({\n  collection,\n  entries,\n  pruneLeaves,\n  excludePath,\n  maxDepth = Infinity,\n  locale,\n}) => {\n  const config = getNestedConfig(collection);\n\n  if (!config) {\n    return [];\n  }\n\n  const { summary: summaryTemplate, subfolders } = config;\n  const indexFileName = getSharedEntryFileName(collection);\n  const folders = collectFolders({ entries, indexFileName, subfolders });\n  /** @type {Map<string, string[]>} */\n  const childPaths = new Map();\n\n  [...folders.keys()].forEach((path) => {\n    const parentPath = getEntryDirPath(path);\n\n    getOrCreate(childPaths, parentPath, () => []).push(path);\n  });\n\n  /**\n   * Recursively build the nodes for the given folder’s children.\n   * @param {string} parentPath Parent folder path.\n   * @returns {NestedTreeNode[]} Child nodes.\n   */\n  const buildNodes = (parentPath) =>\n    (childPaths.get(parentPath) ?? [])\n      .filter(\n        (path) =>\n          // A leaf folder in the `subfolders` mode is an entry, not a container\n          (!pruneLeaves || !subfolders || !!childPaths.get(path)?.length) &&\n          path !== excludePath &&\n          countSegments(path) <= maxDepth,\n      )\n      .map((path) => ({\n        path,\n        label: getNodeLabel({\n          collection,\n          path,\n          indexEntry: folders.get(path),\n          summaryTemplate,\n          locale,\n        }),\n        children: buildNodes(path),\n      }))\n      .sort((a, b) => compare(a.label, b.label));\n\n  return buildNodes('');\n};\n\n/**\n * Build the folder tree shown below a collection with nested entries in the primary sidebar. Only\n * folders are included; the entries themselves are listed in the main area once a folder is\n * selected.\n *\n * In the default `subfolders` mode, a folder that has no subfolder of its own is left out, because\n * such a folder is an entry rather than a container: it holds nothing but its own index file, and\n * it’s already listed in its parent folder’s entry list.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {Entry[]} args.entries Entries in the collection.\n * @returns {NestedTreeNode[]} Top-level folders, sorted by label. An empty array if the collection\n * has no nested entries or has no subfolder.\n */\nexport const getNestedTree = ({ collection, entries }) =>\n  buildTree({ collection, entries, pruneLeaves: true });\n\n/**\n * Get the number of path segments a folder offered by the entry path editor can have at most, so an\n * entry filed in it stays within the collection’s `nested.depth`. Anything deeper isn’t part of the\n * collection, so an entry saved there would vanish from the CMS as soon as it’s saved. An entry\n * takes one segment below its folder as a file, or two in the `subfolders` mode, where it’s a\n * folder of its own holding an index file. An existing entry takes the pages below it along, so\n * they need room too.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {Entry[]} args.entries Entries in the collection.\n * @param {string} [args.ownFolderPath] Folder of the entry being moved, in the `subfolders` mode.\n * @returns {number} Maximum number of segments, `Infinity` if the depth is unlimited.\n */\nexport const getMaxParentFolderDepth = ({ collection, entries, ownFolderPath }) => {\n  const depth = getNestedConfig(collection)?.depth ?? Infinity;\n\n  if (!getSharedEntryFileName(collection)) {\n    return depth - 1;\n  }\n\n  if (!ownFolderPath) {\n    return depth - 2;\n  }\n\n  const baseDepth = countSegments(getEntryDirPath(ownFolderPath));\n\n  const height = Math.max(\n    2,\n    ...entries\n      .filter(({ subPath }) => subPath.startsWith(`${ownFolderPath}/`))\n      .map(({ subPath }) => countSegments(subPath) - baseDepth),\n  );\n\n  return depth - height;\n};\n\n/**\n * Build the folder tree offered by the entry path editor, which lists every folder an entry can be\n * filed in. Unlike the sidebar tree, a folder that holds nothing but its own entry is included,\n * because an entry can be filed below any other entry. A folder too deep for the entry to stay\n * within the collection’s depth is left out; see {@link getMaxParentFolderDepth}.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {Entry[]} args.entries Entries in the collection.\n * @param {string} [args.excludePath] Folder of the entry being moved, in the `subfolders` mode.\n * It’s left out along with everything below it, so an entry can’t be filed within itself.\n * @param {InternalLocaleCode} [args.locale] Locale to label the folders in, which is the locale of\n * the pane showing the tree. A folder is labelled with its entry’s summary, so with localized\n * content each pane names the folders in its own language.\n * @returns {NestedTreeNode[]} Top-level folders, sorted by label.\n */\nexport const getParentFolderTree = ({ collection, entries, excludePath, locale }) =>\n  buildTree({\n    collection,\n    entries,\n    pruneLeaves: false,\n    excludePath,\n    maxDepth: getMaxParentFolderDepth({ collection, entries, ownFolderPath: excludePath }),\n    locale,\n  });\n\n/**\n * Add a folder that holds no entry yet to a tree, creating any missing folders above it, so that it\n * can be chosen with the parent folder picker before anything is stored in it. A folder is labelled\n * with its own name here, because a label of its own only comes from the entry it holds.\n * @param {object} args Arguments.\n * @param {NestedTreeNode[]} args.nodes Folders at the top level of the tree.\n * @param {string} args.path Folder path relative to the collection folder.\n * @returns {NestedTreeNode[]} Folders at the top level, with the new one in place and each level\n * sorted by label. The tree is returned unchanged if the folder is already in it, or if the path is\n * empty, which is the collection folder itself.\n */\nexport const addFolderToTree = ({ nodes, path }) => {\n  const segments = path.split('/').filter(Boolean);\n\n  /**\n   * Put the next segment in place among the given folders, recursing until the path runs out.\n   * @param {NestedTreeNode[]} siblings Folders sharing a parent.\n   * @param {string[]} remainingSegments Segments still to be added.\n   * @param {string} parentPath Path of the folder holding the siblings.\n   * @returns {NestedTreeNode[]} Folders sharing a parent, with the segment in place.\n   */\n  const addSegment = (siblings, [name, ...remaining], parentPath) => {\n    const nodePath = parentPath ? `${parentPath}/${name}` : name;\n    const existingNode = siblings.find((node) => node.path === nodePath);\n\n    if (existingNode) {\n      // The folder is already there, so only the folders below it can still be missing\n      return remaining.length\n        ? siblings.map((node) =>\n            node === existingNode\n              ? { ...node, children: addSegment(node.children, remaining, nodePath) }\n              : node,\n          )\n        : siblings;\n    }\n\n    const newNode = {\n      path: nodePath,\n      label: name,\n      children: remaining.length ? addSegment([], remaining, nodePath) : [],\n    };\n\n    return [...siblings, newNode].sort((a, b) => compare(a.label, b.label));\n  };\n\n  return segments.length ? addSegment(nodes, segments, '') : nodes;\n};\n\n/**\n * Look up a folder in a tree by its path.\n * @param {NestedTreeNode[]} nodes Nodes to search, at any level.\n * @param {string} path Folder path relative to the collection folder.\n * @returns {NestedTreeNode | undefined} Found node.\n */\nexport const findNestedTreeNode = (nodes, path) =>\n  nodes.reduce(\n    (/** @type {NestedTreeNode | undefined} */ found, node) =>\n      found ?? (node.path === path ? node : findNestedTreeNode(node.children, path)),\n    undefined,\n  );\n\n/**\n * Get the name of the folder an entry occupies, which travels with it when the entry is filed\n * elsewhere with the parent folder picker. Only an entry that’s already saved in a collection where\n * every entry shares one file name has one: a new entry’s folder is named after its slug at save\n * time, and in the other modes an entry is a file rather than a folder.\n * @param {object} args Arguments.\n * @param {InternalCollection | undefined} args.collection Collection.\n * @param {string | undefined} args.subPath Entry’s sub path, e.g. `docs/guides/_index`.\n * @param {boolean} [args.isNew] Whether the entry is new.\n * @returns {string | undefined} Folder name, e.g. `guides`, or `undefined` if the entry doesn’t\n * occupy a folder, including the collection’s own index file.\n */\nexport const getMovableFolderName = ({ collection, subPath, isNew = false }) => {\n  if (isNew || !subPath || !collection || !getSharedEntryFileName(collection)) {\n    return undefined;\n  }\n\n  const dirPath = getEntryDirPath(subPath);\n\n  return dirPath ? getBaseName(dirPath) : undefined;\n};\n\n/**\n * Get the tree the parent folder picker offers: the collection folder, with the folders an entry\n * can be filed in below it, along with the folders created with the picker that hold no entry yet.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection.\n * @param {string} args.label Label of the collection folder.\n * @param {Entry[]} args.entries Entries in the collection, including the unpublished ones, so a\n * folder that only exists as a draft can be chosen too.\n * @param {string[]} args.newFolderPaths Paths of the folders created with the picker.\n * @param {string} [args.excludePath] Folder of the entry being moved, which is left out.\n * @param {InternalLocaleCode} [args.locale] Locale to label the folders in.\n * @returns {NestedTreeNode} Root node, standing for the collection folder.\n */\nexport const getParentFolderPickerTree = ({\n  collection,\n  label,\n  entries,\n  newFolderPaths,\n  excludePath,\n  locale,\n}) => ({\n  path: '',\n  label,\n  children: newFolderPaths.reduce(\n    (nodes, path) => addFolderToTree({ nodes, path }),\n    getParentFolderTree({ collection, entries, excludePath, locale }),\n  ),\n});\n\n/**\n * Get the names of the folders directly within the given one, which a new folder there can’t take.\n * @param {NestedTreeNode | undefined} node Folder.\n * @returns {string[]} Folder names.\n */\nexport const getChildFolderNames = (node) =>\n  (node?.children ?? []).map(({ path }) => getBaseName(path));\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Dialog, Icon, Popup, TextInput, Tree } from '@sveltia/ui';\n  import { stripSlashes } from '@sveltia/utils/string';\n\n  import FieldEditorGroup from '$lib/components/contents/details/editor/field-editor-group.svelte';\n  import ParentFolderTreeItem from '$lib/components/contents/details/editor/parent-folder-tree-item.svelte';\n  import ValidationError from '$lib/components/contents/details/editor/validation-error.svelte';\n  import { getNewFolderName, validateNewFolderName } from '$lib/services/common/slug';\n  import { isDraftReadonly } from '$lib/services/config/readonly';\n  import { getCollectionLabel } from '$lib/services/contents/collection';\n  import {\n    getEntryDirPath,\n    getMetaPathConfig,\n    getNestedConfig,\n  } from '$lib/services/contents/collection/nested';\n  import { getAllEntries, localizeDirPath } from '$lib/services/contents/collection/nested/i18n';\n  import {\n    findNestedTreeNode,\n    getChildFolderNames,\n    getMaxParentFolderDepth,\n    getMovableFolderName,\n    getParentFolderPickerTree,\n  } from '$lib/services/contents/collection/nested/tree';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getPathValidationMessages } from '$lib/services/contents/draft/validate/messages';\n  import { createPath } from '$lib/services/utils/file';\n\n  /**\n   * @import { NestedTreeNode } from '$lib/services/contents/collection/nested/tree';\n   * @import { InternalCollection, InternalLocaleCode } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { locale } = $props();\n\n  const fieldId = $props.id();\n\n  const collection = $derived(/** @type {InternalCollection} */ (entryDraft.current?.collection));\n  const config = $derived(collection ? getMetaPathConfig(collection) : undefined);\n  const validity = $derived(entryDraft.current?.validities[locale]._path);\n  const invalid = $derived(validity?.valid === false);\n  /**\n   * Whether this pane is the one that decides where the entry goes. The folder is chosen once, in\n   * the default locale’s pane, and the others show it without offering to change it. With localized\n   * slugs the folders go by localized names, so the other panes show the folder as it’s named in\n   * their own locale.\n   * @see https://github.com/sveltia/sveltia-cms/issues/962\n   */\n  const isDefaultLocale = $derived(locale === collection?._i18n.defaultLocale);\n  /** Whether the entry can be moved, which a read-only entry can’t. */\n  const canMove = $derived(isDefaultLocale && !isDraftReadonly(entryDraft.current));\n\n  /**\n   * Name of the folder the entry occupies, which travels with it when the entry is filed elsewhere.\n   * Only an entry that’s already saved in a collection where every entry shares one file name has\n   * one: a new entry’s folder is named after its slug at save time, and in the other modes an entry\n   * is a file rather than a folder.\n   */\n  const ownFolderName = $derived(\n    getMovableFolderName({\n      collection,\n      subPath: entryDraft.current?.originalEntry?.subPath,\n      isNew: entryDraft.current?.isNew,\n    }),\n  );\n\n  /* v8 ignore next -- the editor is only rendered for nested entries, where the path is set */\n  const currentPath = $derived(stripSlashes(entryDraft.current?.currentPath ?? ''));\n  /** Folder the entry is filed in, which is the parent of its own folder if it has one. */\n  const selectedPath = $derived(ownFolderName ? getEntryDirPath(currentPath) : currentPath);\n\n  /**\n   * Whether a folder can be created with the picker. In the `subfolders` mode a folder is an entry,\n   * so the tree grows as entries are created; otherwise entries are files, which never make a\n   * folder, leaving this as the only way to add one.\n   */\n  const canCreateFolder = $derived(\n    !!collection && getNestedConfig(collection)?.subfolders === false,\n  );\n\n  /**\n   * Whether the selected folder has room for another one below it. An entry filed in a folder\n   * deeper than the collection’s `nested.depth` allows wouldn’t be part of the collection.\n   */\n  const hasRoomForFolder = $derived(\n    !!collection &&\n      selectedPath.split('/').filter(Boolean).length <\n        getMaxParentFolderDepth({ collection, entries: [] }),\n  );\n\n  let newFolderDialogOpen = $state(false);\n  let newFolderName = $state('');\n  /**\n   * Whether the folder name has been typed in yet. An empty name is only reported once the field\n   * has been used, so the dialog doesn’t open with an error against a field nobody has touched.\n   */\n  let newFolderNameEdited = $state(false);\n  /**\n   * Folders created with the picker but not yet stored, because a folder only appears in the\n   * repository once an entry is saved in it.\n   * @type {string[]}\n   */\n  let newFolderPaths = $state([]);\n\n  const rootNode = $derived.by(() => {\n    /* v8 ignore next 3 -- only read once the collection’s path configuration is known */\n    if (!collection) {\n      return /** @type {NestedTreeNode} */ ({ path: '', label: '', children: [] });\n    }\n\n    return getParentFolderPickerTree({\n      collection,\n      label: getCollectionLabel(collection),\n      // With Editorial Workflow a section can be started and filled in one sitting: a page that\n      // only exists as a draft has to be offered as a parent too, or its sub-pages couldn’t be\n      // filed under it until it’s published. A pending move is reflected the same way, so the tree\n      // shows the folders as they’ll be once the drafts land\n      entries: getAllEntries(collection),\n      newFolderPaths,\n      // An entry can’t be filed within itself\n      excludePath: ownFolderName\n        ? getEntryDirPath(/** @type {string} */ (entryDraft.current?.originalEntry?.subPath))\n        : undefined,\n      // Each pane names the folders in its own language\n      locale,\n    });\n  });\n\n  /**\n   * Folder path as it is in this pane’s locale. The tree is keyed by the default locale’s paths,\n   * which is how the entry is identified, but a localized file is stored below the localized\n   * folder chain, so that’s what this pane describes the choice with.\n   */\n  const localizedSelectedPath = $derived.by(() => {\n    if (!collection || isDefaultLocale) {\n      return selectedPath;\n    }\n\n    return localizeDirPath({ collection, dirPath: selectedPath, locale });\n  });\n\n  const selectedNode = $derived(findNestedTreeNode([rootNode], selectedPath));\n  const selectedLabel = $derived(selectedNode?.label ?? localizedSelectedPath);\n\n  /** @type {HTMLButtonElement | undefined} */\n  let buttonElement = $state();\n  let popupOpen = $state(false);\n  /** Names of the folders already in the folder the new one would be created in. */\n  const takenFolderNames = $derived(getChildFolderNames(selectedNode));\n\n  const newFolderError = $derived(\n    validateNewFolderName({ takenNames: takenFolderNames, name: newFolderName }),\n  );\n\n  const showNewFolderError = $derived(newFolderNameEdited && !!newFolderError);\n  /**\n   * Whether there’s a folder to choose. A collection whose entries all sit at the top level has\n   * nothing below the collection folder, leaving the picker with a single item and nothing to do.\n   */\n  const hasFolderChoice = $derived(!!rootNode.children.length);\n\n  /**\n   * File the entry in the given folder. An entry that owns a folder keeps its name and takes\n   * everything below it along.\n   * @param {string} path Chosen folder path.\n   */\n  const selectPath = (path) => {\n    /* v8 ignore next 3 -- the picker is only offered while the draft is there */\n    if (entryDraft.current) {\n      entryDraft.current.currentPath = ownFolderName ? createPath([path, ownFolderName]) : path;\n    }\n\n    // The popup closes itself for a menu item or an option, so a tree has to say when it’s done\n    popupOpen = false;\n  };\n</script>\n\n<!-- A collection whose entries all sit at the top level has no folder to choose and, in the\n`subfolders` mode, no way to make one, which leaves nothing for the field to do -->\n{#if entryDraft.current && config && (hasFolderChoice || canCreateFolder)}\n  <FieldEditorGroup data-validation-key=\"_path\">\n    <header role=\"none\">\n      <h4 role=\"none\" id=\"{fieldId}-label\">{_('entry_parent_folder')}</h4>\n    </header>\n    {#if invalid}\n      <ValidationError id=\"{fieldId}-error\">\n        {getPathValidationMessages(validity).join(' ')}\n      </ValidationError>\n    {/if}\n    <div role=\"none\" class=\"field-wrapper\">\n      <Button\n        bind:element={buttonElement}\n        class=\"parent-folder-button\"\n        variant=\"tertiary\"\n        disabled={!hasFolderChoice || !canMove}\n        aria-haspopup=\"tree\"\n        aria-invalid={invalid}\n        aria-labelledby=\"{fieldId}-label\"\n        aria-errormessage=\"{fieldId}-error\"\n        aria-description={localizedSelectedPath || undefined}\n      >\n        {#snippet startIcon()}\n          <Icon name={selectedPath ? 'folder' : 'bookmark_manager'} />\n        {/snippet}\n        {#snippet endIcon()}\n          <Icon name=\"expand_more\" />\n        {/snippet}\n        <span role=\"none\" class=\"label\">{selectedLabel}</span>\n      </Button>\n      <Popup bind:open={popupOpen} anchor={buttonElement} position=\"bottom-left\">\n        <!-- Choosing a folder closes the popup, so it has to be a deliberate action rather than\n        something that happens while arrowing through the tree -->\n        <Tree\n          ariaLabel={_('entry_parent_folder')}\n          class=\"parent-folder-tree\"\n          selectionFollowsFocus={false}\n        >\n          <ParentFolderTreeItem node={rootNode} {selectedPath} onSelectPath={selectPath} />\n        </Tree>\n      </Popup>\n      {#if canCreateFolder}\n        <!-- A folder that holds no entry can’t be in the tree, so it has to be created here. It\n        sits outside the picker, which is disabled when there’s nothing in the tree to choose -->\n        <Button\n          variant=\"ghost\"\n          iconic\n          class=\"new-parent-folder-button\"\n          disabled={!canMove || !hasRoomForFolder}\n          aria-label={_('new_parent_folder')}\n          onclick={() => {\n            newFolderName = '';\n            newFolderNameEdited = false;\n            newFolderDialogOpen = true;\n          }}\n        >\n          {#snippet startIcon()}\n            <Icon name=\"create_new_folder\" />\n          {/snippet}\n        </Button>\n      {/if}\n    </div>\n  </FieldEditorGroup>\n  <Dialog\n    bind:open={newFolderDialogOpen}\n    title={_('new_parent_folder')}\n    okLabel={_('new_parent_folder_create')}\n    okDisabled={!!newFolderError}\n    onOk={() => {\n      const path = createPath([selectedPath, getNewFolderName(newFolderName)]);\n\n      newFolderPaths = [...newFolderPaths, path];\n      selectPath(path);\n    }}\n  >\n    <div role=\"none\" class=\"new-parent-folder\">\n      <div role=\"none\">\n        <TextInput\n          dir=\"auto\"\n          flex\n          ariaLabel={_('new_parent_folder_name')}\n          aria-errormessage=\"{fieldId}-new-folder-error\"\n          invalid={showNewFolderError}\n          bind:value={newFolderName}\n          oninput={() => {\n            newFolderNameEdited = true;\n          }}\n        />\n        {#if showNewFolderError}\n          <ValidationError id=\"{fieldId}-new-folder-error\">\n            {_(`new_parent_folder_error.${newFolderError}`)}\n          </ValidationError>\n        {/if}\n      </div>\n      <p role=\"none\">\n        {_('new_parent_folder_description', {\n          values: { folder: selectedLabel },\n        })}\n      </p>\n    </div>\n  </Dialog>\n{/if}\n\n<style>\n  .field-wrapper {\n    display: flex;\n    align-items: center;\n\n    :global {\n      /* Look like the `<Select>` trigger, which is a styled div rather than a button */\n      .parent-folder-button {\n        justify-content: flex-start;\n        border-color: var(--sui-control-border-color);\n        border-radius: var(--sui-textbox-border-radius);\n        padding-inline: calc(var(--sui-textbox-height) / 4);\n        flex: auto;\n        min-width: 0;\n        height: var(--sui-textbox-height);\n        color: var(--sui-control-foreground-color);\n        background-color: var(--sui-disabled-background-color);\n        font-family: var(--sui-control-font-family);\n        font-size: var(--sui-control-font-size);\n        font-weight: var(--sui-font-weight-normal, normal);\n        line-height: var(--sui-control-line-height);\n\n        &:is(:hover, :focus-visible, [aria-expanded='true']) {\n          color: var(--sui-control-foreground-color);\n          background-color: var(--sui-hover-background-color);\n        }\n\n        &[aria-invalid='true'] {\n          border-color: var(--sui-error-border-color);\n        }\n\n        .icon {\n          font-size: var(--sui-font-size-xx-large);\n          opacity: 0.5;\n        }\n\n        .label {\n          flex: auto;\n          overflow: hidden;\n          text-align: start;\n          text-overflow: ellipsis;\n          white-space: nowrap;\n        }\n      }\n\n      .parent-folder-tree {\n        min-width: 240px;\n        max-height: 50vh;\n      }\n\n      /* Stand beside the picker without stretching, so the folder name gets the room */\n      .new-parent-folder-button {\n        flex: none;\n        height: var(--sui-textbox-height);\n        white-space: nowrap;\n      }\n    }\n  }\n\n  .new-parent-folder {\n    display: flex;\n    flex-direction: column;\n    gap: 8px;\n    min-width: 320px;\n\n    p {\n      margin: 0;\n      color: var(--sui-secondary-foreground-color);\n      font-size: var(--sui-font-size-small);\n    }\n  }\n</style>\n","<script>\n  import { VisibilityObserver } from '@sveltia/ui';\n\n  import FieldEditor from '$lib/components/contents/details/editor/field-editor.svelte';\n  import PathEditor from '$lib/components/contents/details/editor/path-editor.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n\n  /**\n   * @import { InternalLocaleCode } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { locale } = $props();\n\n  const fields = $derived(entryDraft.current?.fields ?? []);\n  const showPathEditor = $derived(\n    entryDraft.current?.currentPath !== undefined && !entryDraft.current?.isIndexFile,\n  );\n</script>\n\n<VisibilityObserver>\n  {#if showPathEditor}\n    <PathEditor {locale} />\n  {/if}\n  {#each fields as fieldConfig (fieldConfig.name)}\n    <VisibilityObserver>\n      <FieldEditor\n        keyPath={fieldConfig.name}\n        typedKeyPath={fieldConfig.name}\n        {locale}\n        {fieldConfig}\n      />\n    </VisibilityObserver>\n  {/each}\n</VisibilityObserver>\n","import { getBlobRegex } from '@sveltia/utils/file';\nimport { IndexedDB } from '@sveltia/utils/storage';\nimport equal from 'fast-deep-equal';\n\nimport { createDisplayBlobURL } from '$lib/services/assets/info';\nimport { backend } from '$lib/services/backends';\nimport { getBackupDatabaseName } from '$lib/services/backends/fs/test';\nimport { cmsConfigVersion } from '$lib/services/config';\nimport {\n  isDraftConfigReadonly,\n  isDraftLockedByOthers,\n  isDraftReadonly,\n} from '$lib/services/config/readonly';\nimport { getIndexFileName } from '$lib/services/contents/collection/entries/index-file';\nimport { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport {\n  getDraftValues,\n  isDraftModified,\n  suspendAutoDuplication,\n} from '$lib/services/contents/draft';\nimport { createProxy } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { updateObject } from '$lib/services/contents/draft/update/list';\nimport { hasChildKeys, indexContent } from '$lib/services/contents/entry/content-index';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { createDeepState, createRootEffect, getSnapshot } from '$lib/services/utils/state.svelte';\nimport { isForkEntry } from '$lib/services/workflow/forks';\n\n/**\n * @import {\n * Entry,\n * EntryDraft,\n * EntryDraftBackup,\n * EntryDraftValues,\n * UnpublishedEntry,\n * } from '$lib/types/private';\n */\n\n/**\n * @type {number | NodeJS.Timeout}\n */\nlet backupTimeout = 0;\n/**\n * @type {IndexedDB | null | undefined}\n */\nlet backupDB = undefined;\n/**\n * Name of the database {@link backupDB} was opened for.\n * @type {string | undefined}\n */\nlet backupDBName = undefined;\n/**\n * Incremented as each draft is checked for a backup by {@link restoreBackupIfNeeded}, so only the\n * latest check can ask about its backup, even if an earlier one is slower to look it up.\n */\nlet restoreCheckCount = 0;\n\n/**\n * Default for {@link backupToastState}.\n */\nconst BACKUP_TOAST_DEFAULT_STATE = {\n  saved: false,\n  restored: false,\n  deleted: false,\n};\n\n/**\n * @type {{ current: { show: boolean, timestamp?: Date, resolve?: (value?: boolean) => void } }}\n */\nexport const restoreDialogState = createDeepState({ show: false });\n\n/**\n * @type {{ current: { saved: boolean, restored: boolean, deleted: boolean } }}\n */\nexport const backupToastState = createDeepState({ ...BACKUP_TOAST_DEFAULT_STATE });\n\n/**\n * Delete a draft stored in IndexedDB.\n * @param {string} collectionName Collection name.\n * @param {string} [slug] Entry slug. Existing entry only.\n * @returns {Promise<void>} Result.\n */\nexport const deleteBackup = async (collectionName, slug = '') => {\n  await backupDB?.delete([collectionName, slug]);\n};\n\n/**\n * Get a draft backup stored in IndexedDB.\n * @param {string} collectionName Collection name.\n * @param {string} [slug] Entry slug. Existing entry only.\n * @returns {Promise<EntryDraftBackup | null>} Backup.\n */\nexport const getBackup = async (collectionName, slug = '') => {\n  /** @type {EntryDraftBackup | undefined} */\n  const backup = await backupDB?.get([collectionName, slug]);\n\n  if (!backup) {\n    return null;\n  }\n\n  if (backup.cmsConfigVersion === cmsConfigVersion.current) {\n    return backup;\n  }\n\n  // Discard the backup if the CMS configuration has been changed since the backup was created,\n  // because there is a risk of data corruption\n  await deleteBackup(collectionName, slug);\n\n  return null;\n};\n\n/**\n * Get the slug part of the key a draft’s backup is stored under. For an existing entry, it’s the\n * entry’s `subPath`, which is its file path relative to the collection folder, rather than its\n * slug. The collection `path` option, like `{{year}}/{{slug}}`, lets two entries share a slug, as\n * `2023/hello` and `2024/hello` do, and a backup stored under the slug would be offered to,\n * restored to, or deleted with the other entry. The `subPath` is the same as the slug for the\n * common `{{slug}}` path, so the backups stored before the change are still found there.\n * @param {object} draft Draft, or the parts of it the key is made of.\n * @param {EntryDraft['collection']} draft.collection Collection.\n * @param {string} [draft.fileName] Collection file name, if the entry is a collection file.\n * @param {boolean} [draft.isIndexFile] Whether the draft is for a new index file.\n * @param {Entry} [draft.originalEntry] Entry being edited. `undefined` for a new entry.\n * @returns {string} The file name for a collection file, or the entry’s `subPath` for an existing\n * entry. The index file name, e.g. `_index`, for a new index file, which has fields of its own, so\n * its backup mustn’t be offered to a new entry or the other way round. An empty string for any\n * other new entry. An entry from a contributor’s pull request has the pull request number appended,\n * e.g. `hello?_pr=12`, as its backup holds the contributor’s changes and mustn’t be offered to the\n * entry opened from anywhere else, nor be deleted with it.\n */\nexport const getBackupSlug = ({ collection, fileName, isIndexFile, originalEntry }) => {\n  const slug =\n    fileName ??\n    originalEntry?.subPath ??\n    (isIndexFile ? /** @type {string} */ (getIndexFileName(collection)) : '');\n\n  const number = isForkEntry(originalEntry)\n    ? /** @type {UnpublishedEntry} */ (originalEntry).workflow.pullRequest.number\n    : undefined;\n\n  return number === undefined ? slug : `${slug}?_pr=${number}`;\n};\n\n/**\n * Get the backup of the given draft, if there is one. A backup made from another entry than the one\n * the draft is for is ignored: its values belong to that entry, and restoring it would also put the\n * draft on that entry, so a save would write to the other entry’s file. Such a backup can be one\n * stored under the slug before the backups of existing entries were keyed by their `subPath`. It’s\n * left alone, as it’s not this draft’s to discard.\n * @param {EntryDraft} draft Draft.\n * @returns {Promise<EntryDraftBackup | null>} Backup.\n */\nconst getDraftBackup = async (draft) => {\n  const backup = await getBackup(draft.collectionName, getBackupSlug(draft));\n  // Missing from a backup of a new entry, and from one taken before the base entry was stored\n  const baseSubPath = backup?.baseEntry?.subPath;\n\n  if (baseSubPath !== undefined && baseSubPath !== draft.originalEntry?.subPath) {\n    return null;\n  }\n\n  return backup;\n};\n\n/**\n * Check if the given draft is for an existing entry stored in a file with the other entries of the\n * collection. Its slug is its position in the array, which another entry can take after a reorder\n * or a deletion, so a backup stored under it could be restored to the wrong entry.\n * @param {EntryDraft} draft Draft.\n * @returns {boolean} Result.\n */\nconst isArrayItemDraft = ({ originalEntry }) => originalEntry?.arrayIndex !== undefined;\n\n/**\n * Backup the entry draft to IndexedDB.\n * @param {EntryDraft} draft Draft.\n */\nexport const saveBackup = async (draft) => {\n  // Skip if the user hasn’t manually interacted with the editor, so that only programmatic changes,\n  // e.g. Lexical markdown reformatting, don’t trigger a backup\n  if (!(prefs.useDraftBackup ?? true) || !draft.interacted || isArrayItemDraft(draft)) {\n    return;\n  }\n\n  // Nothing is backed up, or deleted, while the draft is read-only, e.g. while the user is asked\n  // whether to restore a backup, which a click in the editor mustn’t delete. The exception is\n  // someone else taking over the entry, which makes the draft read-only, but the changes made until\n  // then are still backed up, so they aren’t lost. An unchanged draft of an entry someone else is\n  // editing keeps the backup of earlier changes until it can be edited again\n  if (\n    isDraftLockedByOthers(draft)\n      ? !!draft.restorePending || isDraftConfigReadonly(draft) || !isDraftModified(draft)\n      : isDraftReadonly(draft)\n  ) {\n    return;\n  }\n\n  const { collectionName, isNew, originalEntry, pendingEntries = [] } = draft;\n  const slug = getBackupSlug(draft);\n\n  if (isDraftModified(draft)) {\n    /** @type {EntryDraftBackup} */\n    const backup = {\n      timestamp: new Date(),\n      cmsConfigVersion: /** @type {string} */ (cmsConfigVersion.current),\n      collectionName,\n      slug,\n      ...getDraftValues(draft),\n      // The entries hold `File` objects among their changes, so a JSON round trip won’t do\n      pendingEntries: getSnapshot(pendingEntries),\n      // The version of an existing entry the edits were made to, so a restore can tell whether\n      // someone else has changed the entry since\n      ...(!isNew && originalEntry ? { baseEntry: getSnapshot(originalEntry) } : {}),\n    };\n\n    await backupDB?.put(backup);\n  } else {\n    const backup = await getBackup(collectionName, slug);\n\n    if (backup) {\n      await deleteBackup(collectionName, slug);\n    }\n  }\n};\n\n/**\n * Create a new blob URL for every file referenced in the given backup. The old URLs are dead once\n * the page has been reloaded. A file can be a copy of an asset in the repository, e.g. an SVG image\n * copied when the entry was duplicated, so the URLs are made for display.\n * @param {EntryDraftValues} backup Backup to restore.\n * @returns {Promise<Map<File, string>>} New blob URLs keyed by file. A file referenced more than\n * once gets one URL.\n */\nconst createFileURLs = async ({ currentValues, files }) => {\n  /** @type {Set<File>} */\n  const referencedFiles = new Set();\n\n  Object.values(currentValues).forEach((valueMap) => {\n    Object.values(valueMap).forEach((value) => {\n      if (typeof value === 'string') {\n        [...value.matchAll(getBlobRegex('g'))].forEach(([blobURL]) => {\n          const file = files[blobURL]?.file;\n\n          if (file) {\n            referencedFiles.add(file);\n          }\n        });\n      }\n    });\n  });\n\n  return new Map(\n    await Promise.all(\n      [...referencedFiles].map(\n        async (file) => /** @type {[File, string]} */ ([file, await createDisplayBlobURL(file)]),\n      ),\n    ),\n  );\n};\n\n/**\n * Put the draft back on the version of its entry the backup was made from, if the entry has been\n * changed since. The draft has been made from the entry as it is now, so saving the restored edits\n * would otherwise silently undo the other change: the entry would look unchanged since the draft\n * was opened. Now the editor tells the user about the change, and saving asks before overwriting\n * it, as if the draft had been open all along.\n * @param {object} args Arguments.\n * @param {Entry} [args.baseEntry] Entry the backup was made from. Missing from a backup of a new\n * entry, and from one taken before it was introduced.\n * @param {EntryDraft} args.draft Entry draft the backup is restored to.\n */\nconst restoreBaseEntry = ({ baseEntry, draft }) => {\n  const { originalEntry, originalLocales } = draft;\n\n  if (\n    !baseEntry ||\n    !originalEntry ||\n    equal(baseEntry.locales, getSnapshot(originalEntry.locales))\n  ) {\n    return;\n  }\n\n  draft.originalEntry = baseEntry;\n  // The locales the entry had then, so a save doesn’t delete a locale added since, which the\n  // backup knows nothing about\n  draft.originalLocales = Object.fromEntries(\n    Object.keys(originalLocales).map((locale) => [locale, !!baseEntry.locales[locale]?.content]),\n  );\n};\n\n/**\n * Restore a draft backup to the given entry draft. It also restores the values of an entry draft\n * kept elsewhere, e.g. those of an entry added with a quick-add dialog, which is opened again.\n * @param {object} args Arguments.\n * @param {EntryDraftValues & Pick<EntryDraftBackup, 'pendingEntries' | 'baseEntry'>} args.backup\n * Backup to restore.\n * @param {EntryDraft} args.draft Entry draft to restore the backup to.\n */\nexport const restoreBackup = async ({ backup, draft }) => {\n  const {\n    baseEntry,\n    currentLocales,\n    currentPath,\n    currentSlugs,\n    currentValues,\n    files,\n    pendingEntries = [],\n  } = backup;\n\n  // Created up front, because the draft is updated in one go below\n  const fileURLs = await createFileURLs(backup);\n\n  suspendAutoDuplication(() => {\n    draft.currentLocales = currentLocales;\n    draft.currentSlugs = currentSlugs;\n\n    // Missing from a backup taken before the folder was stored, which then leaves the entry where\n    // it is\n    if (currentPath !== undefined) {\n      draft.currentPath = currentPath;\n    }\n\n    // The entries created from a Relation field are what the restored values refer to\n    draft.pendingEntries = pendingEntries;\n\n    // Reconcile a stale manual-sort order field. The backup may have been taken before another\n    // reorder/renumber operation rewrote this entry’s `order`. For existing entries, prefer the\n    // value persisted on the live entry; for new entries, drop the field entirely so\n    // `assignManualSortOrder` can compute a fresh value at save time. Without this, restoring an\n    // old backup would clobber the latest order with a stale one.\n    const orderKey = getOrderFieldKey(draft.collection);\n\n    Object.entries(currentValues).forEach(([locale, valueMap]) => {\n      if (orderKey && orderKey in valueMap) {\n        const liveOrder = draft.originalEntry?.locales[locale]?.content?.[orderKey];\n\n        if (liveOrder !== undefined) {\n          valueMap[orderKey] = liveOrder;\n        } else {\n          delete valueMap[orderKey];\n        }\n      }\n\n      Object.entries(valueMap).forEach(([keyPath, value]) => {\n        if (typeof value === 'string') {\n          [...value.matchAll(getBlobRegex('g'))].forEach(([blobURL]) => {\n            const cache = files[blobURL];\n            const { file } = cache ?? {};\n\n            if (!cache || !file) {\n              return;\n            }\n\n            const newURL = /** @type {string} */ (fileURLs.get(file));\n\n            // The first reference to the file decides its upload options\n            draft.files[newURL] ??= cache;\n            value = value.replaceAll(blobURL, newURL);\n          });\n\n          valueMap[keyPath] = value;\n        }\n      });\n\n      if (draft.currentValues[locale]) {\n        // The backup is the whole content, so replace the loaded content rather than merging the\n        // backup into it. A merge can only add or overwrite keys, and the flattened keys of a list\n        // shift when an item is removed or inserted, so a merge would leave the keys the backup no\n        // longer has in place: after removing the first item, the stale trailing keys of every\n        // shifted item would be saved as extra nested values\n        // @see https://github.com/sveltia/sveltia-cms/issues/985\n        updateObject(draft.currentValues[locale], valueMap);\n      } else {\n        draft.currentValues[locale] = createProxy({\n          draft,\n          locale,\n          target: structuredClone(valueMap),\n        });\n      }\n\n      const newValueMap = draft.currentValues[locale];\n      const keys = Object.keys(newValueMap);\n      // The loop only overwrites existing keys, so one index built up front stays valid throughout,\n      // and the child lookup is constant time instead of a scan per key path\n      const index = indexContent(newValueMap);\n\n      keys.forEach((keyPath) => {\n        const value = newValueMap[keyPath];\n\n        // Remove an optional object field’s default `null` value when subfields are added\n        // @see https://github.com/sveltia/sveltia-cms/issues/840\n        if (value === null && hasChildKeys(index, keyPath)) {\n          newValueMap[keyPath] = {};\n        }\n      });\n\n      if (!draft.originalValues[locale]) {\n        draft.originalValues[locale] = {};\n      }\n    });\n\n    // After the order field has been reconciled with the entry as it is now\n    restoreBaseEntry({ baseEntry, draft });\n  });\n};\n\n/**\n * Drop the backup check of the draft open so far, which a new draft replaces or the closed editor\n * leaves behind: close its restore dialog, if any, and keep a lookup still under way from opening\n * one. The dialog doesn’t block the editor, so the draft it was opened for may have been replaced,\n * e.g. when the user has reloaded the entry.\n * @returns {number} Number identifying the new check, if any.\n */\nexport const cancelRestoreCheck = () => {\n  // Without an answer, which leaves the backup alone\n  if (restoreDialogState.current.show) {\n    restoreDialogState.current.show = false;\n    restoreDialogState.current.resolve?.();\n  }\n\n  restoreCheckCount += 1;\n\n  return restoreCheckCount;\n};\n\n/**\n * Check if a draft backup is available, and restore it if requested by the user.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft to restore the backup to.\n */\nexport const restoreBackupIfNeeded = async ({ draft }) => {\n  const checkCount = cancelRestoreCheck();\n\n  // A read-only entry can’t be changed, so leave any backup alone until it can be edited again\n  if (!(prefs.useDraftBackup ?? true) || isDraftReadonly(draft) || isArrayItemDraft(draft)) {\n    return;\n  }\n\n  const { collectionName } = draft;\n  const slug = getBackupSlug(draft);\n  const backup = await getDraftBackup(draft);\n\n  // Another draft has been opened in the meantime\n  if (!backup || checkCount !== restoreCheckCount) {\n    return;\n  }\n\n  const { timestamp } = backup;\n  const { promise, resolve } = Promise.withResolvers();\n\n  // The dialog doesn’t block the editor, so the user can look through the entry before deciding,\n  // but the draft can’t be changed until then\n  draft.restorePending = true;\n  restoreDialogState.current = { show: true, timestamp, resolve };\n\n  /** @type {boolean | undefined} */\n  let doRestore;\n\n  try {\n    // The promise will be resolved once the Restore or Discard button is clicked on the dialog\n    doRestore = await promise;\n\n    if (doRestore === undefined) {\n      return;\n    }\n\n    if (doRestore) {\n      await restoreBackup({ backup, draft });\n      draft.interacted = true;\n    } else {\n      await deleteBackup(collectionName, slug);\n    }\n  } finally {\n    // Even if the restore has failed, so the entry doesn’t stay locked\n    draft.restorePending = false;\n  }\n\n  backupToastState.current = { restored: doRestore, deleted: !doRestore, saved: false };\n};\n\n/**\n * Check if the given entry draft’s backup has been saved, and if so, show a toast notification.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n */\nexport const showBackupToastIfNeeded = async (draft) => {\n  if (!(prefs.useDraftBackup ?? true)) {\n    return;\n  }\n\n  if (!draft || backupToastState.current.saved) {\n    return;\n  }\n\n  const backup = await getDraftBackup(draft);\n\n  if (backup) {\n    backupToastState.current = { restored: false, deleted: false, saved: true };\n  }\n};\n\n/**\n * Reset {@link backupToastState}.\n */\nexport const resetBackupToastState = () => {\n  backupToastState.current = { ...BACKUP_TOAST_DEFAULT_STATE };\n};\n\ncreateRootEffect(() => {\n  // The test backend has no repository, but its drafts are worth backing up all the same, e.g. on\n  // the demo site\n  const databaseName = getBackupDatabaseName(backend.current);\n\n  if (!databaseName) {\n    backupDB = null;\n    backupDBName = undefined;\n\n    return;\n  }\n\n  // Reopen the database when the backend or repository has changed, e.g. when the user signs in\n  // with the local backend after the GitHub backend was selected\n  if (databaseName !== backupDBName) {\n    backupDBName = databaseName;\n    backupDB = new IndexedDB(databaseName, 'draft-backups', {\n      keyPath: ['collectionName', 'slug'], // Composite key\n    });\n  }\n});\n\n/**\n * Drop the backup scheduled by {@link scheduleBackup}, if it hasn’t been made yet.\n */\nexport const cancelBackup = () => {\n  globalThis.clearTimeout(backupTimeout);\n};\n\n/**\n * Schedule a backup of the given entry draft, cancelling any backup scheduled before. The editor\n * calls this whenever the draft changes; the timer avoids typing lag. Call it with no draft when\n * the editor is closed, so that a pending backup of the draft that is gone is dropped as well.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n */\nexport const scheduleBackup = (draft) => {\n  cancelBackup();\n\n  if (draft && backupDB) {\n    backupTimeout = globalThis.setTimeout(() => {\n      saveBackup(draft);\n    }, 500);\n  }\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { populateDefaultValue } from '$lib/services/contents/draft/defaults';\nimport {\n  getItemIndexes,\n  hasChildKeys,\n  indexContent,\n} from '$lib/services/contents/entry/content-index';\nimport { getFieldKind, isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { isKeyPathWithin } from '$lib/services/contents/entry/key-paths';\nimport { deleteSubtree, isPlaceholder } from '$lib/services/contents/entry/subtree';\nimport { MEDIA_FIELD_TYPES, STRING_VALUE_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { syncDuplicateKeys } from '$lib/services/contents/fields/key-value/duplicate-keys';\nimport { alignPairOrder } from '$lib/services/contents/fields/key-value/pairs';\nimport { hasRequiredSingleItem } from '$lib/services/contents/fields/list/defaults';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport { getFlatSubFields } from '$lib/services/contents/fields/list/subfields';\nimport { getLocalizedFieldValue } from '$lib/services/contents/fields/locale';\nimport {\n  isDuplicateIfEmptyField,\n  isFieldEmpty,\n} from '$lib/services/contents/i18n/duplicate-if-empty';\nimport { isFieldMirrored } from '$lib/services/contents/i18n/fields';\n\n/**\n * @import {\n * ContentIndex,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * NormalizeContentArgs,\n * } from '$lib/types/private';\n * @import {\n * Field,\n * FieldKeyPath,\n * FieldWithSubFields,\n * FieldWithTypes,\n * ListField,\n * ListFieldWithSubField,\n * NumberField,\n * } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} NormalizeFieldArgs\n * @property {Field} field Field configuration.\n * @property {FieldKeyPath} keyPath Key path of the field within the content.\n * @property {FlattenedEntryContent} content Flattened entry content, modified in place.\n * @property {ContentIndex} index Index of the content as it was before normalization.\n * @property {InternalLocaleCode} locale Locale of the content.\n * @property {InternalLocaleCode} defaultLocale Default locale of the entry draft.\n * @property {FlattenedEntryContent} [defaultLocaleContent] Already normalized content for the\n * default locale, used as the source for fields with the `duplicate` i18n strategy.\n * @property {boolean} [fillDefaults] Whether to fill in the values missing from the content.\n * @property {Field['i18n']} [inheritedI18n] `i18n` option of the nearest ancestor field that has\n * one, which applies to a field without the option of its own.\n * @property {Record<FieldKeyPath, string>} [variableTypes] Type names of the variable type objects\n * and list items along the key path, keyed by the key path of their type key, e.g.\n * `{ 'blocks.1.type': 'latest' }`. The field resolves to the same configuration in the default\n * locale only if it holds the same types there.\n */\n\n/**\n * @typedef {NormalizeFieldArgs & { fieldType: string }} ReconcileScalarValueArgs\n */\n\n/**\n * @typedef {NormalizeFieldArgs & { hasSubFields: boolean }} ReconcileListValueArgs\n */\n\n/**\n * Field types holding a value whose shape we can’t predict, so it’s taken as-is: the Hidden field\n * accepts anything, the KeyValue and Code fields have their own nested shape, and custom field\n * types are up to the developer.\n */\nconst OPAQUE_FIELD_TYPES = ['code', 'hidden', 'keyvalue'];\n/**\n * Values read as `true` in a Boolean field, in lowercase. Besides `true`, a YAML 1.1 parser, which\n * tools like Jekyll still use, reads `yes`, `on` and `y` as `true`, while the YAML 1.2 parser gives\n * them as strings. A number is converted to a string first, so `1` is included too.\n */\nconst TRUTHY_BOOLEAN_STRINGS = ['true', 'yes', 'on', 'y', '1'];\n/**\n * Values read as `false` in a Boolean field, in lowercase. See {@link TRUTHY_BOOLEAN_STRINGS}.\n */\nconst FALSY_BOOLEAN_STRINGS = ['false', 'no', 'off', 'n', '0'];\n\n/**\n * Drop a value stored at a key path that also has children. `unflatten()` lets such a value win and\n * silently throws the children away, so an Object field whose file value is a plain string would\n * lose everything the user typed into its sub-fields on the next save.\n * @param {FlattenedEntryContent} content Flattened entry content, modified in place.\n * @param {FieldKeyPath} keyPath Key path.\n */\nconst discardConflictingValue = (content, keyPath) => {\n  if (Object.hasOwn(content, keyPath) && !isPlaceholder(content[keyPath])) {\n    delete content[keyPath];\n  }\n};\n\n/**\n * Reconcile the value of a scalar field with its configuration.\n * @param {ReconcileScalarValueArgs} args Arguments.\n * @returns {boolean} Whether the stored value can be kept, after coercion if needed. `false` means\n * it has been discarded and the caller should fill in the default value instead.\n */\nconst reconcileScalarValue = ({ field, fieldType, keyPath, content, index }) => {\n  if (hasChildKeys(index, keyPath)) {\n    const [firstItemIndex] = getItemIndexes(index, keyPath);\n\n    // The file holds a list where a single value is expected, which happens when a field is changed\n    // from multiple to single. Keep the first item and drop the rest\n    if (firstItemIndex !== undefined) {\n      const firstItem = content[`${keyPath}.${firstItemIndex}`];\n\n      deleteSubtree(content, keyPath);\n      content[keyPath] = firstItem;\n    } else {\n      // The file holds an object where a single value is expected; there is nothing to salvage\n      deleteSubtree(content, keyPath);\n\n      return false;\n    }\n  }\n\n  const value = content[keyPath];\n\n  // An empty object or array is as good as no value at all\n  if (isObject(value) || Array.isArray(value)) {\n    deleteSubtree(content, keyPath);\n\n    return false;\n  }\n\n  if (STRING_VALUE_FIELD_TYPES.includes(fieldType)) {\n    if (typeof value !== 'string') {\n      // A number, boolean or null read from the file: stringify it rather than dropping it, which\n      // is also what the field editor would end up writing back\n      content[keyPath] = String(value ?? '');\n    }\n\n    return true;\n  }\n\n  if (fieldType === 'boolean') {\n    if (typeof value !== 'boolean') {\n      const normalized = typeof value === 'string' ? value.trim().toLowerCase() : String(value);\n      const isTrue = TRUTHY_BOOLEAN_STRINGS.includes(normalized);\n\n      if (!isTrue && !FALSY_BOOLEAN_STRINGS.includes(normalized)) {\n        return false;\n      }\n\n      content[keyPath] = isTrue;\n    }\n\n    return true;\n  }\n\n  if (fieldType === 'number') {\n    const { value_type: valueType = 'int' } = /** @type {NumberField} */ (field);\n\n    // The `int` and `float` value types are stored as a number or `null`; the string variants keep\n    // whatever the user typed, so any primitive will do\n    if (valueType !== 'int' && valueType !== 'float') {\n      return true;\n    }\n\n    if (typeof value === 'number' || value === null) {\n      return true;\n    }\n\n    const parsedValue = typeof value === 'string' ? Number(value.trim()) : Number.NaN;\n\n    if (value === '' || Number.isNaN(parsedValue)) {\n      return false;\n    }\n\n    content[keyPath] = parsedValue;\n  }\n\n  return true;\n};\n\n/**\n * Reconcile the value of a List or other multi-value field with its configuration.\n * @param {ReconcileListValueArgs} args Arguments.\n * @returns {boolean} Whether the stored value can be kept, after coercion if needed.\n */\nconst reconcileListValue = ({ keyPath, content, index, hasSubFields }) => {\n  if (getItemIndexes(index, keyPath).length) {\n    discardConflictingValue(content, keyPath);\n\n    return true;\n  }\n\n  // Non-numeric children: the file holds an object where a list is expected\n  if (hasChildKeys(index, keyPath)) {\n    deleteSubtree(content, keyPath);\n\n    return false;\n  }\n\n  const value = content[keyPath];\n\n  if (Array.isArray(value)) {\n    return true;\n  }\n\n  // The file holds a single value where a list is expected, which happens when a field is changed\n  // from single to multiple. Keep it as the sole item, unless the items are objects, in which case\n  // a scalar can’t be turned into one\n  if (!hasSubFields && value !== null && value !== undefined && !isObject(value)) {\n    delete content[keyPath];\n    content[`${keyPath}.0`] = value;\n\n    return true;\n  }\n\n  deleteSubtree(content, keyPath);\n\n  return false;\n};\n\n/**\n * Types of the scalar values, other than strings and `null`, a file can hold.\n */\nconst SCALAR_TYPES = ['number', 'boolean', 'bigint'];\n\n/**\n * Stringify the scalar items of a list whose items are always strings: a simple List field, or a\n * File or Image field with `multiple`. A number, boolean or `null` read from the file would\n * otherwise reach an editor calling string methods on it. An item that isn’t a scalar is left\n * alone, as it’s not stored at the item key path itself and so never makes it to the editor.\n * @param {FlattenedEntryContent} content Flattened entry content, modified in place.\n * @param {FieldKeyPath} keyPath Key path of the list.\n * @param {ContentIndex} index Index of the content as it was before normalization.\n */\nconst stringifyListItems = (content, keyPath, index) => {\n  const itemIndexes = getItemIndexes(index, keyPath);\n\n  // A single value turned into the sole item by `reconcileListValue()` isn’t in the index\n  (itemIndexes.length ? itemIndexes : [0]).forEach((itemIndex) => {\n    const itemKeyPath = `${keyPath}.${itemIndex}`;\n    const value = content[itemKeyPath];\n\n    if (\n      Object.hasOwn(content, itemKeyPath) &&\n      (value === null || SCALAR_TYPES.includes(typeof value))\n    ) {\n      content[itemKeyPath] = String(value ?? '');\n    }\n  });\n};\n\n/**\n * Reconcile the value of an Object field with its configuration.\n * @param {NormalizeFieldArgs} args Arguments.\n * @returns {boolean} Whether the stored value can be kept, after coercion if needed.\n */\nconst reconcileObjectValue = ({ keyPath, content, index }) => {\n  if (hasChildKeys(index, keyPath)) {\n    discardConflictingValue(content, keyPath);\n\n    return true;\n  }\n\n  // A `null` value means the optional Object field is collapsed\n  if (content[keyPath] === null) {\n    return true;\n  }\n\n  // A scalar or an empty object where sub-values are expected\n  deleteSubtree(content, keyPath);\n\n  return false;\n};\n\n/**\n * Reconcile the stored value with the field configuration, coercing what can be coerced and\n * discarding what can’t.\n *\n * Entries aren’t necessarily written by the CMS, and a field’s type can change after the fact, so\n * the value map may hold a shape no editor for that field type can render. Left alone, the mismatch\n * either shows up as an empty editor or, worse, silently destroys data on the next save, because\n * `unflatten()` lets a value stored at a key path win over everything below it.\n * @param {NormalizeFieldArgs} args Arguments.\n * @returns {boolean} Whether the stored value can be kept, after coercion if needed. `false` means\n * it has been discarded and the caller should fill in the default value instead.\n * @see https://github.com/decaporg/decap-cms/issues/836\n * @see https://github.com/decaporg/decap-cms/issues/3524\n */\nconst reconcileValue = (args) => {\n  const { field, keyPath, content, index } = args;\n  const { widget: fieldType = 'string' } = field;\n\n  // Custom field types may hold anything, so leave them alone apart from a value that would destroy\n  // its own children\n  if (OPAQUE_FIELD_TYPES.includes(fieldType) || getFieldKind(field) !== 'builtin') {\n    if (hasChildKeys(index, keyPath)) {\n      discardConflictingValue(content, keyPath);\n    }\n\n    return true;\n  }\n\n  if (fieldType === 'object') {\n    return reconcileObjectValue(args);\n  }\n\n  if (fieldType === 'list') {\n    const { hasSubFields } = getListFieldInfo(/** @type {ListField} */ (field));\n\n    return reconcileListValue({ ...args, hasSubFields });\n  }\n\n  if (isFieldMultiple(field)) {\n    return reconcileListValue({ ...args, hasSubFields: false });\n  }\n\n  return reconcileScalarValue({ ...args, fieldType });\n};\n\n/**\n * Copy a field’s entire subtree from the default locale’s content.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.content Flattened entry content, modified in place.\n * @param {FlattenedEntryContent} args.defaultLocaleContent Content for the default locale.\n * @param {Field} args.field Field configuration.\n * @param {FieldKeyPath} args.keyPath Key path of the field.\n * @param {InternalLocaleCode} args.locale Locale of the content.\n * @param {InternalLocaleCode} args.defaultLocale Default locale of the entry draft.\n * @returns {boolean} Whether anything was copied.\n */\nconst copyFromDefaultLocale = ({\n  content,\n  defaultLocaleContent,\n  field,\n  keyPath,\n  locale,\n  defaultLocale,\n}) => {\n  const keys = Object.keys(defaultLocaleContent).filter((key) => isKeyPathWithin(key, keyPath));\n\n  keys.forEach((key) => {\n    // The copied value may be a Relation field value holding the source locale as a prefix, which\n    // has to be replaced with the target locale, or a DateTime field value written in the source\n    // locale. A `multiple` Relation field stores each value under a numbered key path, so every\n    // copied key is localized the same way\n    content[key] = getLocalizedFieldValue({\n      fieldConfig: field,\n      value: defaultLocaleContent[key],\n      sourceLocale: defaultLocale,\n      targetLocale: locale,\n    });\n  });\n\n  return !!keys.length;\n};\n\n/**\n * Check if the default locale holds the same variable types along the key path, so that a value\n * copied from it belongs to the same field. A translatable List field’s items are paired by index\n * across locales, and the item at the same index may well be of another type in the default locale.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.defaultLocaleContent Content for the default locale.\n * @param {Record<FieldKeyPath, string>} args.variableTypes Type names along the key path.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/1075\n */\nconst hasSameVariableTypes = ({ defaultLocaleContent, variableTypes }) =>\n  Object.entries(variableTypes).every(\n    ([typeKeyPath, typeName]) => defaultLocaleContent[typeKeyPath] === typeName,\n  );\n\n/**\n * Get the sub-fields of an Object field or List field item, along with the variable types leading\n * to them.\n * @param {object} args Arguments.\n * @param {Field} args.field Object or List field configuration.\n * @param {FlattenedEntryContent} args.content Flattened entry content.\n * @param {FieldKeyPath} args.keyPath Key path of the object or list item.\n * @param {Record<FieldKeyPath, string>} args.variableTypes Type names along the key path.\n * @returns {{ fields: Field[] | undefined, variableTypes: Record<FieldKeyPath, string> }} Result:\n * the sub-fields, or those of the variable type matching the type name stored in the content, if\n * any, and the type names along their key path.\n */\nconst getSubFields = ({ field, content, keyPath, variableTypes }) => {\n  const { fields } = /** @type {FieldWithSubFields} */ (field);\n\n  if (fields) {\n    return { fields, variableTypes };\n  }\n\n  const { typeKey = 'type' } = /** @type {FieldWithTypes} */ (field);\n  const typeKeyPath = `${keyPath}.${typeKey}`;\n  const typeName = content[typeKeyPath];\n  const typeFields = getFlatSubFields(field, content, keyPath);\n\n  return {\n    fields: typeFields,\n    variableTypes: typeFields ? { ...variableTypes, [typeKeyPath]: typeName } : variableTypes,\n  };\n};\n\n/**\n * Fill in the values missing from the given field and reconcile the ones that are there, recursing\n * into sub-fields.\n *\n * A field that holds nothing at all — the common case for a field added to the configuration after\n * the entry was written — gets the same default value a new entry would get. A field that does hold\n * something keeps it, as long as its shape matches the field type, but its sub-fields are visited\n * so that a newly added sub-field shows up in every existing object and list item.\n * @param {NormalizeFieldArgs} args Arguments.\n */\nconst normalizeField = (args) => {\n  const { field, keyPath, content, index, locale, defaultLocale, defaultLocaleContent } = args;\n  const { fillDefaults = true, inheritedI18n, variableTypes = {} } = args;\n  const i18n = field.i18n ?? inheritedI18n;\n\n  // Content of the default locale a duplicated field mirrors. The value at the same key path there\n  // belongs to another field if a variable type object or list item along the way is of another\n  // type, in which case the field is left to its own value or the configured default\n  const sourceContent =\n    locale !== defaultLocale &&\n    defaultLocaleContent &&\n    hasSameVariableTypes({ defaultLocaleContent, variableTypes })\n      ? defaultLocaleContent\n      : undefined;\n\n  // A `duplicate_keys` KeyValue field mirrors the default locale’s keys, so line its pairs up with\n  // them whether or not the locale holds any, keeping the values it does have\n  if (field.widget === 'keyvalue' && field.i18n === 'duplicate_keys' && sourceContent) {\n    syncDuplicateKeys({\n      valueStore: { [defaultLocale]: sourceContent, [locale]: content },\n      defaultLocale,\n      keyPath,\n    });\n\n    return;\n  }\n\n  // A `duplicate_if_empty` field takes the default locale’s value where it’s missing or empty\n  if (\n    fillDefaults &&\n    sourceContent &&\n    isDuplicateIfEmptyField(field) &&\n    isFieldEmpty({ content, fieldConfig: field, keyPath }) &&\n    !isFieldEmpty({ content: sourceContent, fieldConfig: field, keyPath })\n  ) {\n    copyFromDefaultLocale({\n      content,\n      defaultLocaleContent: sourceContent,\n      field,\n      keyPath,\n      locale,\n      defaultLocale,\n    });\n\n    return;\n  }\n\n  const occupied = Object.hasOwn(content, keyPath) || hasChildKeys(index, keyPath);\n\n  if (\n    !occupied ||\n    !reconcileValue(args) ||\n    // A required single-item list saved without its item gets one, like a new entry does\n    (field.widget === 'list' &&\n      hasRequiredSingleItem({ fieldConfig: /** @type {ListField} */ (field), locale }) &&\n      !getItemIndexes(index, keyPath).length)\n  ) {\n    if (!fillDefaults) {\n      return;\n    }\n\n    // A `duplicate` or `sync` field mirrors the default locale, so take the value from there rather\n    // than filling in the configured default, which may not be what the default locale actually\n    // holds. That includes a subfield duplicated along with its Object or List field, e.g. one\n    // added to the configuration after the other locales were saved\n    if (\n      isFieldMirrored(i18n) &&\n      sourceContent &&\n      copyFromDefaultLocale({\n        content,\n        defaultLocaleContent: sourceContent,\n        field,\n        keyPath,\n        locale,\n        defaultLocale,\n      })\n    ) {\n      return;\n    }\n\n    populateDefaultValue({\n      content,\n      keyPath,\n      fieldConfig: field,\n      locale,\n      defaultLocale,\n      dynamicValues: {},\n    });\n\n    return;\n  }\n\n  const { widget: fieldType = 'string' } = field;\n\n  if (MEDIA_FIELD_TYPES.includes(fieldType) && isFieldMultiple(field)) {\n    stringifyListItems(content, keyPath, index);\n\n    return;\n  }\n\n  // A duplicated KeyValue field holds the default locale’s pairs, and its editor writes them to the\n  // other locales in that order as soon as it’s rendered. Put them in that order now, so merely\n  // opening an entry whose locales list the pairs in different orders doesn’t count as a change\n  if (fieldType === 'keyvalue') {\n    if (isFieldMirrored(i18n) && sourceContent) {\n      alignPairOrder({ content, referenceContent: sourceContent, keyPath });\n    }\n\n    return;\n  }\n\n  if (fieldType === 'object') {\n    // A `null` value means the optional Object field is collapsed, so it has no sub-values to fill\n    if (content[keyPath] === null) {\n      return;\n    }\n\n    const subFieldInfo = getSubFields({ field, content, keyPath, variableTypes });\n\n    subFieldInfo.fields?.forEach((subField) => {\n      normalizeField({\n        ...args,\n        field: subField,\n        keyPath: `${keyPath}.${subField.name}`,\n        inheritedI18n: i18n,\n        variableTypes: subFieldInfo.variableTypes,\n      });\n    });\n\n    return;\n  }\n\n  if (fieldType !== 'list') {\n    return;\n  }\n\n  const { field: subField } = /** @type {ListFieldWithSubField} */ (field);\n  const { fields: subFields } = /** @type {FieldWithSubFields} */ (field);\n  const { types } = /** @type {FieldWithTypes} */ (field);\n\n  // A simple List field holds strings only, so there is nothing to recurse into\n  if (!subField && !subFields && !types) {\n    stringifyListItems(content, keyPath, index);\n\n    return;\n  }\n\n  getItemIndexes(index, keyPath).forEach((itemIndex) => {\n    const itemKeyPath = `${keyPath}.${itemIndex}`;\n\n    // A single-subfield List field stores the item itself at the item key path, so hand the item\n    // over to the sub-field as-is; it recurses further only if the sub-field is an Object or List\n    if (subField) {\n      normalizeField({ ...args, field: subField, keyPath: itemKeyPath, inheritedI18n: i18n });\n\n      return;\n    }\n\n    // The file holds a scalar where an object is expected. It can’t be salvaged, and leaving it in\n    // place would make `unflatten()` drop every sub-field value on save\n    discardConflictingValue(content, itemKeyPath);\n\n    const itemFieldInfo = getSubFields({ field, content, keyPath: itemKeyPath, variableTypes });\n\n    itemFieldInfo.fields?.forEach((itemField) => {\n      normalizeField({\n        ...args,\n        field: itemField,\n        keyPath: `${itemKeyPath}.${itemField.name}`,\n        inheritedI18n: i18n,\n        variableTypes: itemFieldInfo.variableTypes,\n      });\n    });\n  });\n};\n\n/**\n * Fill in the values missing from an existing entry’s content and reconcile the ones that don’t\n * match the field configuration, so that the draft holds one well-shaped key path per configured\n * field just like a new entry does.\n *\n * Entries written before a field was added to the collection configuration — or before an optional\n * field was made required — lack that field entirely, and anything keyed by the content’s own key\n * paths then skips it: the editor renders no value for it, and the validator never checks it.\n * Entries not written by the CMS at all may hold a value of the wrong type for the field editing\n * it. Both are fixed by normalizing the content up front.\n * @param {NormalizeContentArgs} args Arguments.\n * @returns {FlattenedEntryContent} The same `content` object, modified in place.\n * @see https://github.com/sveltia/sveltia-cms/issues/395\n * @see https://github.com/sveltia/sveltia-cms/issues/650\n */\nexport const normalizeContent = ({\n  fields,\n  content,\n  locale,\n  defaultLocale,\n  defaultLocaleContent,\n  fillDefaults = true,\n}) => {\n  const index = indexContent(content);\n\n  fields.forEach((field) => {\n    normalizeField({\n      field,\n      keyPath: field.name,\n      fillDefaults,\n      content,\n      index,\n      locale,\n      defaultLocale,\n      defaultLocaleContent,\n    });\n  });\n\n  return content;\n};\n\n/**\n * Normalize the content of every enabled locale. The default locale is normalized first so that\n * fields using the `duplicate` i18n strategy can be mirrored from it.\n * @param {object} args Arguments.\n * @param {Field[]} args.fields Field list of a collection, collection file or index file.\n * @param {Record<InternalLocaleCode, FlattenedEntryContent>} args.contentMap Flattened entry\n * content for each enabled locale, modified in place.\n * @param {InternalLocaleCode} args.defaultLocale Default locale of the entry draft.\n * @returns {Record<InternalLocaleCode, FlattenedEntryContent>} The same `contentMap` object.\n */\nexport const normalizeContentMap = ({ fields, contentMap, defaultLocale }) => {\n  const defaultLocaleContent = contentMap[defaultLocale];\n\n  if (defaultLocaleContent) {\n    normalizeContent({\n      fields,\n      content: defaultLocaleContent,\n      locale: defaultLocale,\n      defaultLocale,\n    });\n  }\n\n  Object.entries(contentMap).forEach(([locale, content]) => {\n    if (locale !== defaultLocale) {\n      normalizeContent({ fields, content, locale, defaultLocale, defaultLocaleContent });\n    }\n  });\n\n  return contentMap;\n};\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { cmsConfig } from '$lib/services/config';\nimport {\n  getIndexFile,\n  isCollectionIndexFile,\n} from '$lib/services/contents/collection/entries/index-file';\nimport {\n  getEntryDirPath,\n  getMetaPathConfig,\n  nestedFilterPath,\n} from '$lib/services/contents/collection/nested';\nimport { getSlugOptions, hasLocalizedSlugs } from '$lib/services/contents/collection/slug';\nimport { revokeDraftFileURLs, STATIC_DRAFT_KEYS } from '$lib/services/contents/draft';\nimport { cancelRestoreCheck, restoreBackupIfNeeded } from '$lib/services/contents/draft/backup';\nimport { normalizeContentMap } from '$lib/services/contents/draft/create/normalize';\nimport { createProxy } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { fillUuidValues } from '$lib/services/contents/draft/create/unique-values';\nimport { createValueMap } from '$lib/services/contents/draft/create/versioned-map.svelte';\nimport { getDefaultValues } from '$lib/services/contents/draft/defaults';\nimport { resetCustomFieldValidation } from '$lib/services/contents/draft/validate/custom-fields';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { isDuplicatedField } from '$lib/services/contents/i18n/shared-values';\nimport { createState, getSnapshot } from '$lib/services/utils/state.svelte';\nimport { isPendingDeletion } from '$lib/services/workflow';\n\n/**\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n * @import {\n * EntryDraft,\n * GetFieldArgs,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * LocaleContentMap,\n * LocaleExpanderMap,\n * LocaleSlugMap,\n * } from '$lib/types/private';\n */\n\n/**\n * Get the `slugEditor` property for an entry draft.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection that the entry belongs to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only.\n * @param {LocaleSlugMap} args.originalSlugs Original slugs for each locale.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s index file, whose name\n * is fixed.\n * @returns {Record<string, boolean | 'readonly'>} Whether to show the slug editor for each locale.\n * If the slug is editable on creation, the slug editor will be enabled for the default locale and\n * disabled (read-only) for other locales, which share its slug, or enabled for all locales if the\n * slug is localized. Otherwise, the slug editor will be disabled for all locales. Note that the\n * slug editor will only be shown for new entries in entry collections.\n * @see https://github.com/sveltia/sveltia-cms/issues/499\n * @see https://github.com/sveltia/sveltia-cms/issues/999\n */\nexport const getSlugEditorProp = ({\n  collection,\n  collectionFile,\n  originalSlugs,\n  isIndexFile = false,\n}) => {\n  const isEntryCollection = collection._type === 'entry';\n  const { allLocales, defaultLocale } = (collectionFile ?? collection)._i18n;\n\n  // The slug editor is only relevant for entry collections\n  if (!isEntryCollection || isIndexFile) {\n    return Object.fromEntries(allLocales.map((locale) => [locale, false]));\n  }\n\n  const {\n    editable: { create: slugEditorEnabled },\n  } = getSlugOptions(collection);\n\n  // Each locale has a slug of its own when the slug is localized, with the `i18n` slug option or\n  // the `localize` flag in the template, e.g. `{{title | localize}}`\n  const localized = hasLocalizedSlugs(collection);\n\n  return Object.fromEntries(\n    allLocales.map((locale) => {\n      if (!slugEditorEnabled || originalSlugs._ || originalSlugs[locale]) {\n        return [locale, false];\n      }\n\n      return [locale, locale === defaultLocale || localized || 'readonly'];\n    }),\n  );\n};\n\n/**\n * Get the locales whose slug is set when the slug editor of the given locale is filled in: the\n * locale itself and, for the default locale, the read-only locales that share its slug.\n * @param {object} args Arguments.\n * @param {Record<string, boolean | 'readonly'>} args.slugEditor Whether the slug editor is shown\n * for each locale. See {@link getSlugEditorProp}.\n * @param {string} args.locale Locale of the slug editor.\n * @param {string} args.defaultLocale Default locale.\n * @returns {string[]} Locales.\n */\nexport const getSlugTargetLocales = ({ slugEditor, locale, defaultLocale }) =>\n  Object.entries(slugEditor)\n    .filter(\n      ([_locale, enabled]) =>\n        _locale === locale || (locale === defaultLocale && enabled === 'readonly'),\n    )\n    .map(([_locale]) => _locale);\n\n/**\n * Get the slugs a new entry starts with, when a slug is given through the `_slug` URL parameter.\n * The slug is only accepted where the user could type it in: the default locale’s slug editor, and\n * the read-only locales that share its slug. Otherwise it’s ignored, so a link can’t set a slug the\n * collection doesn’t let users edit.\n * @param {object} args Arguments.\n * @param {Record<string, boolean | 'readonly'>} args.slugEditor Whether the slug editor is shown\n * for each locale. See {@link getSlugEditorProp}.\n * @param {string} args.defaultLocale Default locale.\n * @param {string} [args.initialSlug] Slug given through the URL parameter.\n * @returns {LocaleSlugMap} Slugs.\n * @see https://github.com/sveltia/sveltia-cms/discussions/938\n */\nexport const getInitialSlugs = ({ slugEditor, defaultLocale, initialSlug }) => {\n  if (!initialSlug?.trim() || slugEditor[defaultLocale] !== true) {\n    return {};\n  }\n\n  return Object.fromEntries(\n    getSlugTargetLocales({ slugEditor, locale: defaultLocale, defaultLocale }).map((locale) => [\n      locale,\n      initialSlug,\n    ]),\n  );\n};\n\n/**\n * Get the `originalPath` property for an entry draft, which is the folder an entry is stored in,\n * relative to the collection folder. It’s only used when the `meta.path` option is enabled, which\n * lets the user move an entry by editing the path in the editor.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection that the entry belongs to.\n * @param {any} args.originalEntry Entry to be edited, or a partial {@link Entry} object.\n * @param {string} [args.initialPath] Folder for a new entry, passed through the `path` URL\n * parameter. Defaults to the folder the user is currently browsing.\n * @returns {string | undefined} Folder path, or `undefined` if the path editor is disabled.\n */\nexport const getOriginalPath = ({ collection, originalEntry, initialPath }) => {\n  if (!getMetaPathConfig(collection)) {\n    return undefined;\n  }\n\n  const { subPath } = originalEntry;\n\n  if (typeof subPath === 'string') {\n    return getEntryDirPath(subPath);\n  }\n\n  return stripSlashes(initialPath ?? nestedFilterPath.current);\n};\n\n/**\n * Give the Hidden fields that hold the same value in every locale, with the `duplicate` or `sync`\n * i18n strategy of their own or along with an ancestor, the default locale’s value in the other\n * locales of a new entry draft. The default values of each locale are created separately, so a\n * default value like `{{uuid}}` would otherwise differ from one locale to another, just like the\n * value of a UUID field, which `fillUuidValues()` takes care of.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.contentMap Flattened content of each locale, modified in place.\n * @param {InternalLocaleCode} args.defaultLocale Default locale.\n * @param {Omit<GetFieldArgs, 'keyPath' | 'valueMap'>} args.getFieldArgs Arguments for\n * {@link getField}, except the key path and value map.\n */\nexport const fillDuplicatedHiddenValues = ({ contentMap, defaultLocale, getFieldArgs }) => {\n  const defaultContent = contentMap[defaultLocale];\n\n  if (!defaultContent) {\n    return;\n  }\n\n  Object.entries(defaultContent).forEach(([keyPath, value]) => {\n    const args = { ...getFieldArgs, keyPath, valueMap: defaultContent };\n    const fieldConfig = getField(args);\n\n    if (\n      fieldConfig?.widget !== 'hidden' ||\n      !isDuplicatedField({ fieldConfig, getFieldArgs: args })\n    ) {\n      return;\n    }\n\n    Object.entries(contentMap).forEach(([locale, content]) => {\n      // Only a locale holding the field gets the value, as one that doesn’t isn’t meant to\n      if (locale !== defaultLocale && keyPath in content) {\n        content[keyPath] = structuredClone(value);\n      }\n    });\n  });\n};\n\n/**\n * Build an entry draft object. This only assembles the values; it’s {@link createDraft} that opens\n * the draft in the editor. A draft can also be built on its own to check an entry that isn’t being\n * edited, in which case the application state is left untouched.\n *\n * The draft is a deeply reactive `$state` object, so the editor components can read and mutate it\n * directly, and each of them is only updated when a value it actually reads changes.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection that the entry belongs to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only.\n * @param {any} [args.originalEntry] Entry to be edited, or a partial {@link Entry} object.\n * @param {Record<string, string>} [args.dynamicValues] Dynamic default values for a new entry\n * passed through URL parameters.\n * @param {LocaleContentMap} [args.extraValues] Key is a locale code, value is a flattened object\n * containing field values in rich text editor components. Can be set when resetting an entry draft.\n * @param {LocaleExpanderMap} [args.expanderStates] Expander UI state. Can be set when resetting an\n * entry draft.\n * @param {string} [args.initialPath] Folder for a new entry in a collection with the `meta.path`\n * option enabled, passed through the `path` URL parameter.\n * @param {string} [args.initialSlug] Slug for a new entry, passed through the `_slug` URL\n * parameter. See {@link getInitialSlugs}.\n * @param {boolean} [args.isIndexFile] Whether to edit the collection’s index file.\n * @returns {EntryDraft} Entry draft.\n */\nexport const buildDraft = ({\n  collection,\n  collectionFile,\n  originalEntry = {},\n  dynamicValues,\n  extraValues,\n  expanderStates,\n  initialPath,\n  initialSlug,\n  isIndexFile = isCollectionIndexFile(collection, originalEntry),\n}) => {\n  const collectionName = collection.name;\n  const fileName = collectionFile?.name;\n  const { id, locales } = originalEntry;\n  const isNew = id === undefined;\n\n  const { fields: regularFields = [], _i18n } =\n    collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  const indexFile = isIndexFile ? getIndexFile(collection) : undefined;\n  const fields = indexFile?.fields ?? regularFields;\n\n  const canPreview =\n    indexFile?.editor?.preview ??\n    collectionFile?.editor?.preview ??\n    collection.editor?.preview ??\n    cmsConfig.current?.editor?.preview ??\n    true;\n\n  const canShowSecondPane =\n    indexFile?.editor?.second_pane ??\n    collectionFile?.editor?.second_pane ??\n    collection.editor?.second_pane ??\n    cmsConfig.current?.editor?.second_pane ??\n    true;\n\n  const {\n    allLocales,\n    initialLocales,\n    defaultLocale,\n    // `canonicalSlug.key` is always set by config normalization (defaults to 'translationKey')\n    canonicalSlug: { key: canonicalSlugKey },\n  } = _i18n;\n\n  const enabledLocales = isNew\n    ? initialLocales\n    : allLocales.filter((locale) => !!locales?.[locale]?.content);\n\n  const originalLocales = Object.fromEntries(\n    allLocales.map((locale) => [locale, enabledLocales.includes(locale)]),\n  );\n\n  const originalPath = getOriginalPath({ collection, originalEntry, initialPath });\n\n  // An entry can lack the default locale, as with Editorial Workflow when a pull request only\n  // touches another locale, or when a localized file has lost the link to its counterparts. The\n  // entry’s own slug, which another locale stands in for, then applies to every locale\n  // @see https://github.com/sveltia/sveltia-cms/issues/984\n  const originalSlugs = isNew\n    ? {}\n    : canonicalSlugKey in (locales?.[defaultLocale]?.content ?? {})\n      ? Object.fromEntries(allLocales.map((locale) => [locale, locales?.[locale]?.slug]))\n      : { _: locales?.[defaultLocale]?.slug ?? originalEntry.slug };\n\n  /** @type {LocaleContentMap} */\n  const originalValues = Object.fromEntries(\n    enabledLocales.map((locale) =>\n      isNew\n        ? [locale, getDefaultValues({ fields, locale, defaultLocale, dynamicValues })]\n        : [locale, structuredClone(locales?.[locale]?.content)],\n    ),\n  );\n\n  if (isNew) {\n    const fillArgs = {\n      contentMap: originalValues,\n      defaultLocale,\n      getFieldArgs: { collectionName, fileName, isIndexFile },\n    };\n\n    // Give every UUID field its value up front rather than when its editor is rendered, which may\n    // never happen in a long form or in a locale the user doesn’t open\n    fillUuidValues(fillArgs);\n    // A Hidden field isn’t rendered at all, while its default value may be generated as well\n    fillDuplicatedHiddenValues(fillArgs);\n  } else {\n    // Existing entries can predate the current field configuration: a field added since, or an\n    // optional field left empty and later made required, is simply absent from the file. Fill those\n    // in so the editor shows their default values and the validator sees them\n    normalizeContentMap({ fields, contentMap: originalValues, defaultLocale });\n  }\n\n  const slugEditor = getSlugEditorProp({ collection, collectionFile, originalSlugs, isIndexFile });\n\n  /** @type {EntryDraft} */\n  const draft = createState(\n    {\n      id: isNew ? crypto.randomUUID() : id,\n      createdAt: Date.now(),\n      isNew,\n      isIndexFile,\n      canPreview,\n      canShowSecondPane,\n      collectionName,\n      collection,\n      fileName,\n      collectionFile,\n      fields,\n      originalEntry: isNew ? undefined : originalEntry,\n      defaultLocale,\n      originalLocales,\n      currentLocales: structuredClone(originalLocales),\n      originalSlugs,\n      currentSlugs: {\n        ...structuredClone(originalSlugs),\n        ...getInitialSlugs({ slugEditor, defaultLocale, initialSlug }),\n      },\n      originalPath,\n      currentPath: originalPath,\n      originalValues,\n      // The value proxies are created below, as they need a reference to the reactive draft\n      currentValues: {},\n      files: {},\n      // Versioned like `currentValues`, so the component editors can share a value map snapshot\n      // rather than each taking its own on every change\n      extraValues: Object.fromEntries(\n        allLocales.map((locale) => [\n          locale,\n          createValueMap(extraValues?.[locale] ? getSnapshot(extraValues[locale]) : {}),\n        ]),\n      ),\n      validities: Object.fromEntries(allLocales.map((locale) => [locale, {}])),\n      validationMessages: Object.fromEntries(allLocales.map((locale) => [locale, {}])),\n      // Any locale-agnostic view states will be put under the `_` key\n      expanderStates: expanderStates ?? { _: {} },\n      slugEditor,\n      interacted: false,\n      pendingEntries: [],\n    },\n    STATIC_DRAFT_KEYS,\n  );\n\n  enabledLocales.forEach((locale) => {\n    draft.currentValues[locale] = createProxy({\n      draft,\n      locale,\n      target: structuredClone(originalValues[locale]),\n    });\n  });\n\n  return draft;\n};\n\n/**\n * Create an entry draft and open it in the editor.\n * @param {object} args Arguments. See {@link buildDraft} for the rest.\n * @param {EntryDraftState} args.entryDraft Entry draft state of the editor to open the draft in.\n * Any draft currently held there is replaced.\n * @param {InternalCollection} args.collection Collection that the entry belongs to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only.\n * @param {any} [args.originalEntry] Entry to be edited, or a partial {@link Entry} object.\n * @param {Record<string, string>} [args.dynamicValues] Dynamic default values for a new entry\n * passed through URL parameters.\n * @param {LocaleContentMap} [args.extraValues] Key is a locale code, value is a flattened object\n * containing field values in rich text editor components. Can be set when resetting an entry draft.\n * @param {LocaleExpanderMap} [args.expanderStates] Expander UI state. Can be set when resetting an\n * entry draft.\n * @param {string} [args.initialPath] Folder for a new entry in a collection with the `meta.path`\n * option enabled, passed through the `path` URL parameter.\n * @param {string} [args.initialSlug] Slug for a new entry, passed through the `_slug` URL\n * parameter.\n * @param {boolean} [args.isIndexFile] Whether to edit the collection’s index file.\n * @returns {EntryDraft} Created draft.\n */\nexport const createDraft = ({ entryDraft, ...args }) => {\n  const { originalEntry = {} } = args;\n\n  // Custom field validation state is keyed by locale and key path only, so discard it to prevent\n  // verdicts from a previous draft leaking into this one\n  resetCustomFieldValidation();\n  // The outgoing draft’s unsaved files are about to become unreachable; release what they hold\n  revokeDraftFileURLs(entryDraft.current);\n\n  const draft = buildDraft(args);\n\n  entryDraft.current = draft;\n\n  // An entry awaiting deletion is read-only, so a cached draft would be neither restorable nor\n  // useful\n  if (!isPendingDeletion(originalEntry)) {\n    restoreBackupIfNeeded({ draft });\n  } else {\n    // The previous draft’s backup isn’t this one’s to ask about\n    cancelRestoreCheck();\n  }\n\n  return draft;\n};\n","import { getPathInfo } from '@sveltia/utils/file';\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport { getNewFolderName, slugify } from '$lib/services/common/slug';\nimport { isDraftReadonly } from '$lib/services/config/readonly';\nimport {\n  getEntryDirPath,\n  getSharedEntryFileName,\n  hasNestedEntries,\n} from '$lib/services/contents/collection/nested';\nimport { getOwnFolderName } from '$lib/services/contents/collection/nested/i18n';\nimport { getSlugOptions, hasLocalizedSlugs } from '$lib/services/contents/collection/slug';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { getOtherEntries } from '$lib/services/contents/draft/validate/slugs';\nimport { createPath, getBaseName } from '$lib/services/utils/file';\nimport { getUnpublishedEntryByDraft, isPendingDeletion } from '$lib/services/workflow';\n\n/**\n * @import {\n * EntryDraft,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * SlugPreview,\n * } from '$lib/types/private';\n */\n\n/**\n * Check whether the entry has a slug the Slug panel can show. Only an entry collection has slugs;\n * the slug of a file/singleton collection’s entry is the file name, and the collection’s index file\n * has a fixed name.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {boolean} Result.\n */\nexport const hasEntrySlug = (draft) =>\n  !!draft && draft.collection._type === 'entry' && !draft.isIndexFile;\n\n/**\n * Check whether the slug of an existing entry can be updated. The collection’s `editable` slug\n * option has to allow it, and the entry has to be identified by a name of its own: an entry in a\n * collection with nested entries that doesn’t store every entry as an index file is identified by\n * its path within the collection folder, which can’t be renamed without relocating the entry. An\n * entry awaiting deletion is read-only, and so is an entry in a read-only collection.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {boolean} Result.\n */\nexport const canUpdateSlug = (draft) => {\n  if (\n    !draft ||\n    draft.isNew ||\n    !hasEntrySlug(draft) ||\n    isDraftReadonly(draft) ||\n    // Look the entry up in the store, as its status can be changed while the editor is open\n    isPendingDeletion(getUnpublishedEntryByDraft(draft))\n  ) {\n    return false;\n  }\n\n  // The collection is an entry collection, as checked above\n  const { collection } = /** @type {EntryDraft & { collection: InternalEntryCollection }} */ (\n    draft\n  );\n\n  if (hasNestedEntries(collection) && !getSharedEntryFileName(collection)) {\n    return false;\n  }\n\n  return getSlugOptions(collection).editable.update;\n};\n\n/**\n * Check whether a new entry’s slug has to be given with the slug editor, which is when the slug\n * template can’t fill it. The Slug panel is opened for such an entry, so the field isn’t missed.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {boolean} Result.\n */\nexport const needsSlugInput = (draft) =>\n  !!draft?.isNew &&\n  hasEntrySlug(draft) &&\n  Object.values(draft.slugEditor).includes(true) &&\n  getSlugOptions(draft.collection).editorRequired;\n\n/**\n * Get the slug a new entry would be saved with if it was saved now, which is shown while the entry\n * is being edited, along with the slug the template fills if a number has to be added to it. Date\n * and time tags in the slug template are filled with the current date and time, as they will be\n * with the time of the save.\n * @param {EntryDraft} draft Entry draft.\n * @param {object} [options] Options.\n * @param {boolean} [options.templateOnly] Whether to ignore a filled-in slug editor, to get the\n * slugs the template fills.\n * @returns {Record<InternalLocaleCode, SlugPreview>} Slug for each enabled locale if the slug is\n * localized. Otherwise the slug shared by every locale, under the `_` key.\n * @see https://github.com/sveltia/sveltia-cms/discussions/736\n */\nexport const getSlugPreviewDetails = (draft, { templateOnly = false } = {}) => {\n  /** @type {Map<InternalLocaleCode, string>} */\n  const numberedSlugs = new Map();\n  const { defaultLocaleSlug, localizedSlugs } = getSlugs({ draft, templateOnly, numberedSlugs });\n\n  /**\n   * Get the preview of a slug.\n   * @param {string} slug Slug.\n   * @param {InternalLocaleCode} locale Locale the slug is filled in.\n   * @returns {SlugPreview} Preview.\n   */\n  const getPreview = (slug, locale) => {\n    const takenSlug = numberedSlugs.get(locale);\n\n    return takenSlug === undefined ? { slug } : { slug, takenSlug };\n  };\n\n  if (!localizedSlugs) {\n    // A slug shared by every locale is filled in the default locale\n    return { _: getPreview(defaultLocaleSlug, draft.collection._i18n.defaultLocale) };\n  }\n\n  // Every enabled locale has a slug\n  return Object.fromEntries(\n    Object.entries(localizedSlugs)\n      .filter(([locale]) => !!draft.currentLocales[locale])\n      .map(([locale, slug]) => [locale, getPreview(/** @type {string} */ (slug), locale)]),\n  );\n};\n\n/**\n * Get the slugs the Slug panel shows read-only, in the enabled locales: the ones a new entry would\n * be saved with if it was saved now, or an existing entry’s current slugs. A locale-agnostic slug\n * is under the `_` key.\n * @param {EntryDraft} draft Entry draft.\n * @returns {[InternalLocaleCode, SlugPreview][]} Slugs.\n */\nexport const getReadonlySlugs = (draft) => {\n  /** @type {[InternalLocaleCode, SlugPreview | undefined][]} */\n  const slugs = draft.isNew\n    ? Object.entries(getSlugPreviewDetails(draft))\n    : Object.entries(draft.currentSlugs).map(([locale, slug]) => [\n        locale,\n        slug === undefined ? undefined : { slug },\n      ]);\n\n  return /** @type {[InternalLocaleCode, SlugPreview][]} */ (\n    slugs.filter(\n      ([locale, preview]) =>\n        preview !== undefined && (locale === '_' || !!draft.currentLocales[locale]),\n    )\n  );\n};\n\n/**\n * Update the slugs of an existing entry. The slugs are slugified the way a new entry’s slug is.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Record<InternalLocaleCode, string>} args.slugs Slugs as typed, for the locales to update.\n * The other locales’ slugs are left as is.\n */\nexport const updateSlugs = ({ draft, slugs }) => {\n  draft.currentSlugs = {\n    ...draft.currentSlugs,\n    ...Object.fromEntries(\n      Object.entries(slugs).map(([locale, slug]) => [locale, slugify(slug, { locale })]),\n    ),\n  };\n};\n\n/**\n * Get the folder the entry occupies in each locale, in a collection where every entry is an index\n * file within a folder of its own. The folder name is what identifies the entry, so renaming it is\n * what the slug editor does there. The default locale’s folder is the one the path editor points\n * at; the other locales are only there when the folder is localized, and their folder is the one in\n * the localized slug, which is the entry’s sub path in that locale.\n * @param {EntryDraft} draft Entry draft.\n * @returns {Record<InternalLocaleCode, string> | undefined} Folder paths, or `undefined` if the\n * entry doesn’t occupy a folder of its own, including a new entry, which has no folder yet.\n * @see https://github.com/sveltia/sveltia-cms/issues/962\n */\nexport const getOwnFolderPaths = (draft) => {\n  const { collection, isNew, defaultLocale, currentPath, currentLocales, currentSlugs } = draft;\n\n  if (isNew || !getSharedEntryFileName(collection)) {\n    return undefined;\n  }\n\n  /* v8 ignore next -- an existing entry always has a path */\n  const ownFolderPath = stripSlashes(currentPath ?? '');\n\n  // The folder is shared by every locale unless the slugs are localized, as the folder is named\n  // after the slug\n  if (!hasLocalizedSlugs(collection)) {\n    return { [defaultLocale]: ownFolderPath };\n  }\n\n  return {\n    [defaultLocale]: ownFolderPath,\n    ...Object.fromEntries(\n      Object.entries(currentSlugs)\n        .filter(\n          ([locale, slug]) =>\n            locale !== defaultLocale &&\n            !!currentLocales[locale] &&\n            !!getOwnFolderName(/** @type {string} */ (slug)),\n        )\n        .map(([locale, slug]) => [locale, getEntryDirPath(/** @type {string} */ (slug))]),\n    ),\n  };\n};\n\n/**\n * Get the names of the folders sharing a parent with the entry’s own folder in each locale, which\n * are the only ones that can be in the way when renaming it. In another locale than the default,\n * the siblings are the folders next to the entry’s localized folder.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Record<InternalLocaleCode, string>} args.ownFolderPaths Folder the entry occupies in each\n * locale. See {@link getOwnFolderPaths}.\n * @returns {Record<InternalLocaleCode, string[]>} Taken folder names for each locale.\n */\nexport const getTakenFolderNames = ({ draft, ownFolderPaths }) => {\n  const { defaultLocale, originalEntry } = draft;\n  const otherEntries = getOtherEntries(draft).filter((entry) => entry.id !== originalEntry?.id);\n\n  return Object.fromEntries(\n    Object.entries(ownFolderPaths).map(([locale, dirPath]) => {\n      const parentPath = getEntryDirPath(dirPath);\n\n      return [\n        locale,\n        otherEntries\n          .map((entry) => (locale === defaultLocale ? entry.subPath : entry.locales[locale]?.slug))\n          .filter((otherSubPath) => typeof otherSubPath === 'string')\n          .map((otherSubPath) => getEntryDirPath(otherSubPath))\n          .filter((otherDirPath) => getEntryDirPath(otherDirPath) === parentPath)\n          .map((otherDirPath) => getBaseName(otherDirPath)),\n      ];\n    }),\n  );\n};\n\n/**\n * Rename the entry’s own folder in each locale, in a collection where every entry is an index file\n * within a folder of its own. Renaming the folder is what moves the entry, so the rest of the save\n * takes care of the entries and assets stored below it.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Record<InternalLocaleCode, string>} args.ownFolderPaths Folder the entry occupies in each\n * locale.\n * @param {Record<InternalLocaleCode, string>} args.folderNames New folder names as typed, for each\n * locale.\n */\nexport const renameEntryFolders = ({ draft, ownFolderPaths, folderNames }) => {\n  const { defaultLocale } = draft;\n  let { currentPath, currentSlugs: slugs } = draft;\n\n  Object.entries(folderNames).forEach(([locale, name]) => {\n    const dirPath = createPath([getEntryDirPath(ownFolderPaths[locale]), getNewFolderName(name)]);\n\n    if (locale === defaultLocale) {\n      currentPath = dirPath;\n    } else {\n      // The localized slug of an existing entry is its sub path in the locale, so the folder is\n      // renamed within it, leaving the file name in place\n      slugs = {\n        ...slugs,\n        [locale]: createPath([\n          dirPath,\n          getPathInfo(/** @type {string} */ (slugs[locale])).basename,\n        ]),\n      };\n    }\n  });\n\n  draft.currentPath = currentPath;\n  draft.currentSlugs = slugs;\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { TextInput } from '@sveltia/ui';\n\n  import EditableText from '$lib/components/common/editable-text.svelte';\n  import FieldEditorGroup from '$lib/components/contents/details/editor/field-editor-group.svelte';\n  import ValidationError from '$lib/components/contents/details/editor/validation-error.svelte';\n  import { getSlugOptions } from '$lib/services/contents/collection/slug';\n  import { getSlugTargetLocales } from '$lib/services/contents/draft/create';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    getSlugValidationMessage,\n    getTakenSlugs,\n    validateSlug,\n  } from '$lib/services/contents/draft/validate/slugs';\n  import { getSlugPreviewDetails } from '$lib/services/contents/editor/slug';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { EntryDraft, EntryValidityState, InternalLocaleCode } from '$lib/types/private';\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Locale of the slug.\n   * @property {string} [ariaLabelledby] ID of the element labelling the field, e.g. the heading of\n   * a Slug panel section. Without it, the field has a heading of its own.\n   */\n\n  /** @type {Props} */\n  let { locale, ariaLabelledby = undefined } = $props();\n\n  const fieldId = $props.id();\n  const labelId = $derived(ariaLabelledby ?? `${fieldId}-label`);\n  const slugEditor = $derived(entryDraft.current?.slugEditor[locale]);\n  /**\n   * The collection’s slug options. The slug editor is only shown in an entry collection, and\n   * they’re only read while the editor is rendered, when the draft is there.\n   */\n  const slugOptions = $derived(\n    getSlugOptions(/** @type {EntryDraft} */ (entryDraft.current).collection),\n  );\n  /**\n   * Whether the slug comes from the slug editor alone, in which case it’s typed in a regular text\n   * field. Otherwise, the slug the template fills is shown, and it can be edited if needed.\n   */\n  const required = $derived(slugEditor === true && slugOptions.editorRequired);\n  const readonly = $derived(slugEditor === 'readonly');\n  const validity = $derived(entryDraft.current?.validities[locale]._slug);\n  const invalid = $derived(!readonly && validity?.valid === false);\n  // Only read while the slug is invalid, when the validity is there\n  const errorMessage = $derived(/** @type {EntryValidityState} */ (validity).customErrorMessage);\n  /**\n   * Slug in the draft. Besides the editor itself, it can be set before the editor is shown, e.g.\n   * through the `_slug` URL parameter, or while it’s shown, by restoring a backup or reverting the\n   * changes. An empty slug makes the entry follow the slug template until it’s saved.\n   */\n  const draftSlug = $derived(entryDraft.current?.currentSlugs[locale] ?? '');\n  /**\n   * Slug the template fills, which the entry is saved with unless another slug is given. There’s\n   * none when the slug comes from the slug editor alone, e.g. in a read-only locale sharing the\n   * default locale’s slug, which is shown once it’s typed in. It’s only read while the editor is\n   * rendered, when the draft is there.\n   */\n  const templatePreview = $derived.by(() => {\n    if (slugOptions.editorRequired) {\n      return undefined;\n    }\n\n    const previews = getSlugPreviewDetails(/** @type {EntryDraft} */ (entryDraft.current), {\n      templateOnly: true,\n    });\n\n    return previews[locale] ?? previews._;\n  });\n  const templateSlug = $derived(templatePreview?.slug ?? '');\n  /**\n   * Slug the entry would be saved with.\n   */\n  const shownSlug = $derived(draftSlug || templateSlug);\n\n  let editing = $state(false);\n  /** Slug being edited, or typed in the regular text field. */\n  let text = $state('');\n\n  /**\n   * Slug the template fills that another entry uses, so the entry is saved with a number added to\n   * it. The user is told why, while the entry follows the template.\n   */\n  const takenTemplateSlug = $derived(draftSlug || editing ? undefined : templatePreview?.takenSlug);\n\n  /**\n   * Slugs taken by the other entries in this locale. Kept apart from the check below, which runs on\n   * every keystroke, so the collection’s entries aren’t walked again each time. It’s only read\n   * while the slug is edited, when the draft is there.\n   */\n  const takenSlugs = $derived(\n    getTakenSlugs(/** @type {EntryDraft} */ (entryDraft.current), [locale])[locale],\n  );\n\n  /**\n   * What stops the slug being edited from being used, checked as it’s typed. An empty slug is\n   * fine, as it makes the entry follow the slug template again.\n   */\n  const editError = $derived.by(() => {\n    if (!editing) {\n      return undefined;\n    }\n\n    return validateSlug({\n      slug: text,\n      required: false,\n      pattern: slugOptions.pattern,\n      takenSlugs,\n      locale,\n    });\n  });\n\n  /**\n   * Update the slug for the current locale and for the other readonly locales.\n   * @param {string} slug New slug.\n   */\n  const updateSlug = (slug) => {\n    const draft = entryDraft.current;\n\n    /* v8 ignore next 3 -- the editor is only rendered while the draft is there */\n    if (!draft) {\n      return;\n    }\n\n    getSlugTargetLocales({\n      slugEditor: draft.slugEditor,\n      locale,\n      defaultLocale: draft.defaultLocale,\n    }).forEach((_locale) => {\n      draft.currentSlugs[_locale] = slug;\n    });\n  };\n\n  /**\n   * Apply the edited slug. The slug the template fills is never written to the draft as is, so the\n   * entry keeps following the template until it’s saved, with the date and a unique name of the\n   * save.\n   * @param {string} slug Edited slug.\n   * @returns {boolean} Whether the editing ends, which it doesn’t while the slug is invalid.\n   */\n  const applySlug = (slug) => {\n    if (editError) {\n      return false;\n    }\n\n    if (slug !== shownSlug) {\n      updateSlug(slug.trim());\n    }\n\n    return true;\n  };\n\n  // Keep the regular text field in sync with the draft, which can be updated elsewhere\n  watch(\n    () => draftSlug,\n    () => {\n      if (required && text !== draftSlug) {\n        text = draftSlug;\n      }\n    },\n  );\n</script>\n\n{#if entryDraft.current}\n  <FieldEditorGroup>\n    {#if !ariaLabelledby}\n      <header role=\"none\">\n        <h4 role=\"none\" id=\"{fieldId}-label\">{_('slug')}</h4>\n        {#if required}\n          <span class=\"required\" aria-hidden=\"true\">*</span>\n        {/if}\n      </header>\n    {/if}\n    {#if editError}\n      <ValidationError id=\"{fieldId}-error\">\n        {getSlugValidationMessage({ error: editError, pattern: slugOptions.pattern })}\n      </ValidationError>\n    {:else if invalid && !editing}\n      <ValidationError id=\"{fieldId}-error\">\n        {errorMessage}\n      </ValidationError>\n    {/if}\n    <div role=\"none\" class=\"field-wrapper\">\n      {#if required}\n        <TextInput\n          dir=\"auto\"\n          bind:value={text}\n          oninput={() => {\n            updateSlug(text);\n          }}\n          flex\n          {required}\n          {invalid}\n          aria-labelledby={labelId}\n          aria-errormessage=\"{fieldId}-error\"\n        />\n      {:else}\n        <EditableText\n          id=\"{fieldId}-value\"\n          value={shownSlug}\n          bind:editing\n          bind:text\n          canEdit={!readonly}\n          editLabel={_('edit_slug')}\n          placeholder={templateSlug}\n          invalid={!!editError || (invalid && !editing)}\n          applyDisabled={!!editError}\n          ariaLabelledby={labelId}\n          ariaErrormessage=\"{fieldId}-error\"\n          onApply={applySlug}\n        />\n      {/if}\n    </div>\n    <!-- Kept in place so a screen reader announces the note when it appears -->\n    <div role=\"status\">\n      {#if takenTemplateSlug}\n        <p class=\"note\">{_('slug_numbered', { values: { slug: takenTemplateSlug } })}</p>\n      {/if}\n    </div>\n  </FieldEditorGroup>\n{/if}\n\n<style>\n  .note {\n    margin-block: 4px 0;\n    font-size: var(--sui-font-size-small);\n    line-height: var(--sui-line-height-compact);\n    color: var(--sui-tertiary-foreground-color);\n  }\n</style>\n","<!--\n  @component\n  Toast telling the user how many fields have errors after a save or an addition failed validation.\n  The entry editor toolbar and the Relation field’s quick add dialog both show it.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Button, Toast } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [show] Whether the toast is shown.\n   * @property {number} count Number of invalid fields.\n   * @property {() => void} [onShowErrors] Function called when the Show Errors button is clicked,\n   * once the toast has been hidden. The button is only shown if this is given.\n   */\n\n  /** @type {Props} */\n  let { show = $bindable(false), count, onShowErrors = undefined } = $props();\n</script>\n\n<Toast bind:show>\n  <Alert status=\"error\">\n    {_('entry_validation_errors', { values: { count } })}\n    {#if onShowErrors}\n      <Button\n        variant=\"secondary\"\n        size=\"small\"\n        label={_('show_errors')}\n        onclick={() => {\n          show = false;\n          onShowErrors();\n        }}\n      />\n    {/if}\n  </Alert>\n</Toast>\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { getEntriesInCollectionFolder } from '$lib/services/contents/collection/entries';\nimport {\n  getMetaPathConfig,\n  getNestedConfig,\n  getSharedEntryFileName,\n  isDescendantPath,\n  usesCustomEntryPath,\n} from '$lib/services/contents/collection/nested';\nimport {\n  buildCustomEntryPath,\n  keepsOriginalPath,\n} from '$lib/services/contents/draft/save/entry-path';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { getPullRequestEntries } from '$lib/services/workflow';\n\n/**\n * @import { EntryDraft, LocaleValidityMap } from '$lib/types/private';\n */\n\n/**\n * Path segments that would let an entry escape the collection folder or produce an unusable file\n * name.\n */\nconst INVALID_SEGMENT_REGEX = /(?:^|\\/)(?:\\.{1,2})(?:\\/|$)/;\n\n/**\n * Check whether another entry is already stored where this one is headed. The path editor decides\n * the folder, so an overlooked collision would quietly overwrite a page: either a folder already\n * taken by another entry, where every entry in the collection shares one file name, or a file of\n * the same name in the chosen folder otherwise, e.g. when moving or duplicating an entry. With\n * localized slugs, each locale has a destination of its own, so every enabled locale is checked\n * against the other entries’ files in that locale. Every entry stored in the collection folder\n * counts, including those the collection’s `filter` option leaves out.\n * @param {EntryDraft} draft Entry draft.\n * @returns {boolean} Whether the destination is taken.\n * @see https://github.com/decaporg/decap-cms/issues/7094\n */\nconst isPathTaken = (draft) => {\n  const { id, collection, currentLocales } = draft;\n  const { defaultLocale } = collection._i18n;\n  const indexFileName = getSharedEntryFileName(collection);\n\n  // A blank folder hands the destination back to the collection’s own `path` option and slug, which\n  // this check knows nothing about\n  if (!usesCustomEntryPath(draft)) {\n    return false;\n  }\n\n  const { defaultLocaleSlug, localizedSlugs } = getSlugs({ draft });\n\n  // The unpublished entries count too, or a folder already claimed by a draft awaiting review\n  // would be handed out twice and the two would collide when the branches are merged. So do the new\n  // entries riding along in the pull request of an entry of another collection. The entry\n  // being edited doesn’t count, and it’s told apart by the draft’s ID rather than the original\n  // entry’s: a new entry has no original, yet it’s saved under the draft’s ID, and once it is,\n  // the draft is validated again — to see whether the entry can be sent for review — while the\n  // saved entry already sits at the destination\n  const otherEntries = [\n    ...getEntriesInCollectionFolder(collection.name),\n    ...getPullRequestEntries(collection.name),\n  ].filter((entry) => entry.id !== id);\n\n  return Object.entries(currentLocales)\n    .filter(([, enabled]) => enabled)\n    .some(([locale]) => {\n      const slug = localizedSlugs?.[locale] ?? defaultLocaleSlug;\n\n      // A file that stays where it is can’t collide with anything, and rebuilding its path could\n      // point somewhere it will never go, e.g. a locale stored under folders that weren’t\n      // localized at the time\n      if (keepsOriginalPath({ draft, locale, slug })) {\n        return false;\n      }\n\n      // Ask for the same sub path the save will build, so the two can’t disagree\n      const subPath = buildCustomEntryPath({ draft, slug, indexFileName, locale });\n\n      return otherEntries.some((entry) =>\n        locale === defaultLocale\n          ? entry.subPath === subPath\n          : entry.locales[locale]?.slug === subPath,\n      );\n    });\n};\n\n/**\n * Validate the folder chosen with the entry path editor. The path editor is only shown when the\n * collection’s `meta.path` option is enabled, so an entry without one is always valid.\n * @param {EntryDraft} draft Draft to validate.\n * @returns {{ valid: boolean, validities: LocaleValidityMap }} Validation results.\n */\nexport const validatePath = (draft) => {\n  const { collection, currentLocales, originalPath, currentPath } = draft;\n\n  if (!getMetaPathConfig(collection)) {\n    return { valid: true, validities: {} };\n  }\n\n  const path = stripSlashes(currentPath ?? '');\n  const patternMismatch = INVALID_SEGMENT_REGEX.test(path) || path.includes('\\\\');\n\n  // Moving an entry moves the whole subtree below it, so a folder can’t be moved into itself\n  const customError =\n    !patternMismatch &&\n    !!originalPath &&\n    path !== originalPath &&\n    !!getNestedConfig(collection)?.subfolders &&\n    isDescendantPath(originalPath, path);\n\n  const duplicateError = !patternMismatch && !customError && isPathTaken(draft);\n  const invalid = patternMismatch || customError || duplicateError;\n  /** @type {LocaleValidityMap} */\n  const validities = {};\n\n  Object.keys(currentLocales).forEach((locale) => {\n    validities[locale] = {\n      _path: { patternMismatch, customError, duplicateError, valid: !invalid },\n    };\n  });\n\n  return { valid: !invalid, validities };\n};\n","import { validateFields } from '$lib/services/contents/draft/validate/fields';\nimport { validatePath } from '$lib/services/contents/draft/validate/path';\nimport { validateSlugs } from '$lib/services/contents/draft/validate/slugs';\n\n/**\n * @import {\n * EntryDraft,\n * LocaleValidationMessagesMap,\n * LocaleValidityMap,\n * } from '$lib/types/private';\n */\n\n/**\n * Validate the given entry draft and return the results, without touching any application state.\n * The draft doesn’t have to be the one open in the editor: an entry shown on the Editorial Workflow\n * board can be checked with a throwaway draft built from its content.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft to validate.\n * @param {boolean} [args.enforceRequired] Whether an empty required field is an error. Set to\n * `false` to save an Editorial Workflow draft that hasn’t been filled in yet, which leaves those\n * fields unmarked: the save succeeds, so the editor has nothing to report.\n * @returns {{ valid: boolean, validities: LocaleValidityMap,\n * validationMessages: LocaleValidationMessagesMap }} Validation results.\n */\nexport const validateDraft = ({ draft, enforceRequired = true }) => {\n  const {\n    valid: currentValuesValid,\n    validities: currentValuesValidities,\n    validationMessages: currentValuesMessages,\n  } = validateFields('currentValues', { enforceRequired, draft });\n\n  const {\n    valid: extraValuesValid,\n    validities: extraValuesValidities,\n    validationMessages: extraValuesMessages,\n  } = validateFields('extraValues', { enforceRequired, draft });\n\n  // The slug is what the entry’s file is named after, so an empty or malformed one blocks the save\n  // whether or not the entry is complete\n  const { valid: slugsValid, validities: slugsValidities } = validateSlugs(draft);\n  // Likewise for the folder chosen with the path editor, which decides where the file goes\n  const { valid: pathValid, validities: pathValidities } = validatePath(draft);\n\n  return {\n    valid: currentValuesValid && extraValuesValid && slugsValid && pathValid,\n    validities: Object.fromEntries(\n      Object.keys(currentValuesValidities).map((locale) => [\n        locale,\n        {\n          ...currentValuesValidities[locale],\n          ...extraValuesValidities[locale],\n          ...slugsValidities[locale],\n          ...pathValidities[locale],\n        },\n      ]),\n    ),\n    validationMessages: Object.fromEntries(\n      Object.keys(currentValuesMessages).map((locale) => [\n        locale,\n        {\n          ...currentValuesMessages[locale],\n          ...extraValuesMessages[locale],\n        },\n      ]),\n    ),\n  };\n};\n\n/**\n * Validate the field values, update the validity for all the fields in the draft, and return the\n * final results as a boolean.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft to validate.\n * @param {boolean} [args.enforceRequired] Whether an empty required field makes the entry invalid.\n * See {@link validateDraft}.\n * @returns {boolean} Whether the entry draft is valid.\n */\nexport const validateEntry = ({ draft, enforceRequired = true }) => {\n  const { valid, validities, validationMessages } = validateDraft({ draft, enforceRequired });\n\n  draft.validities = validities;\n  draft.validationMessages = validationMessages;\n\n  return valid;\n};\n","import { validateEntry } from '$lib/services/contents/draft/validate';\nimport { awaitCustomFieldValidations } from '$lib/services/contents/draft/validate/custom-fields';\nimport { expandInvalidFields } from '$lib/services/contents/editor/fields';\nimport { awaitPendingFieldUpdates } from '$lib/services/contents/editor/pending';\n\n/**\n * @import {\n * EntryDraft,\n * FlattenedEntryValidityStateMap,\n * LocaleValidityMap,\n * } from '$lib/types/private';\n */\n\n/**\n * Validate the given draft, update the validity for all the fields in it, and expand the invalid\n * fields so the errors are visible.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft to validate.\n * @param {boolean} [args.enforceRequired] Whether an empty required field makes the entry invalid.\n * See {@link validateEntry}.\n * @returns {boolean} Whether the entry draft is valid.\n */\nexport const revealInvalidFields = ({ draft, enforceRequired = true }) => {\n  if (validateEntry({ draft, enforceRequired })) {\n    return true;\n  }\n\n  expandInvalidFields({ draft });\n\n  return false;\n};\n\n/**\n * Wait for the field values and the custom field validations to settle, then validate the given\n * draft and expand the invalid fields, as a save does.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft to validate.\n * @param {boolean} [args.enforceRequired] Whether an empty required field makes the entry invalid.\n * See {@link validateEntry}.\n * @param {boolean} [args.awaitFieldUpdates] Whether to wait for the field editors to write what was\n * just typed to the draft. A rich text editor does so with a short delay, so validating right after\n * typing would otherwise check the field’s previous value.\n * @returns {Promise<boolean>} Whether the entry draft is valid.\n */\nexport const validateAndRevealErrors = async ({\n  draft,\n  enforceRequired = true,\n  awaitFieldUpdates = true,\n}) => {\n  if (awaitFieldUpdates) {\n    await awaitPendingFieldUpdates();\n  }\n\n  // Custom field validators can be async, so wait for any in-flight results before validating.\n  // Otherwise a field made invalid moments ago would be validated against a stale verdict.\n  await awaitCustomFieldValidations();\n\n  return revealInvalidFields({ draft, enforceRequired });\n};\n\n/**\n * Check whether any of the fields in the given validity map of a locale is invalid.\n * @param {FlattenedEntryValidityStateMap | undefined} validityMap Validity of each field, keyed by\n * key path.\n * @returns {boolean} Result.\n */\nexport const hasInvalidFields = (validityMap) =>\n  Object.values(validityMap ?? {}).some(({ valid }) => !valid);\n\n/**\n * Count the invalid fields across all the locales in the given validity map.\n * @param {LocaleValidityMap} validities Validity of each field, keyed by locale and key path.\n * @returns {number} Number of invalid fields.\n */\nexport const countInvalidFields = (validities) =>\n  Object.values(validities).flatMap((validityMap) =>\n    Object.values(validityMap).filter(({ valid }) => !valid),\n  ).length;\n","import equal from 'fast-deep-equal';\nimport { untrack } from 'svelte';\n\nimport { backend } from '$lib/services/backends';\nimport { initViewSettingsStorage } from '$lib/services/common/view';\nimport { selectAssetsView } from '$lib/services/contents/editor';\nimport { createRawState, createRootEffect } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { BackendService, EntryEditorView } from '$lib/types/private';\n */\n\n/**\n * View settings for the entry editor.\n * @type {{ current: EntryEditorView | undefined }}\n */\nexport const entryEditorSettings = createRawState();\n\n/**\n * Turn the given entry editor setting on or off.\n * @param {'showSecondPane' | 'showPreview' | 'syncScrolling'} key Setting name.\n * @param {boolean} [defaultValue] Value the setting has when it hasn’t been stored yet.\n */\nexport const toggleEntryEditorSetting = (key, defaultValue = false) => {\n  entryEditorSettings.current = {\n    ...entryEditorSettings.current,\n    [key]: !(entryEditorSettings.current?.[key] ?? defaultValue),\n  };\n};\n\n/**\n * Functions to stop the effects created by {@link initSettings}, so that they don’t pile up when\n * the settings are initialized again.\n * @type {{ entryEditorSettings?: () => void, selectAssetsView?: () => void }}\n */\nconst effectStoppers = {};\n\n/**\n * Initialize {@link entryEditorSettings}, {@link selectAssetsView} and relevant effects.\n * @param {BackendService} _backend Backend service.\n */\nexport const initSettings = async ({ repository }) => {\n  // Stop the previous effects to prevent memory leaks\n  effectStoppers.entryEditorSettings?.();\n  effectStoppers.selectAssetsView?.();\n\n  effectStoppers.entryEditorSettings = await initViewSettingsStorage(\n    repository,\n    'entry-view',\n    entryEditorSettings,\n    {\n      defaults: {\n        showSecondPane: true,\n        showPreview: true,\n        syncScrolling: true,\n        selectAssetsView: { type: 'grid' },\n      },\n    },\n  );\n\n  selectAssetsView.current = entryEditorSettings.current?.selectAssetsView;\n\n  effectStoppers.selectAssetsView = createRootEffect(() => {\n    const view = selectAssetsView.current;\n\n    if (!view || !Object.keys(view).length) {\n      return;\n    }\n\n    untrack(() => {\n      const _settings = entryEditorSettings.current;\n      const savedView = _settings?.selectAssetsView ?? {};\n\n      if (!equal(view, savedView)) {\n        entryEditorSettings.current = { ..._settings, selectAssetsView: view };\n      }\n    });\n  });\n};\n\ncreateRootEffect(() => {\n  const { current: _backend } = backend;\n\n  if (_backend && !untrack(() => entryEditorSettings.current)) {\n    initSettings(_backend);\n  }\n});\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Icon, Option, Select, SelectButton, SelectButtonGroup } from '@sveltia/ui';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { hasInvalidFields } from '$lib/services/contents/draft/validate/reveal';\n  import { afterPendingFieldUpdates } from '$lib/services/contents/editor/pending';\n  import { entryEditorSettings } from '$lib/services/contents/editor/settings';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n  import { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\n  import { env } from '$lib/services/user/env.svelte';\n  import { createRawState } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { EntryEditorPane } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} id The wrapper element’s `id` attribute.\n   * @property {{ current: ?EntryEditorPane }} thisPane This pane’s mode and locale.\n   * @property {{ current: ?EntryEditorPane }} [thatPane] Another pane’s mode and locale.\n   * @property {boolean} [previewInThisPane] Whether to offer the preview in this pane, which takes\n   * turns with the editor when there’s no other pane to hold it.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { id, thisPane, thatPane = createRawState(null), previewInThisPane = false } = $props();\n\n  const { i18nEnabled, allLocales } = $derived(getDraftI18nConfig(entryDraft.current));\n  // With a single locale, the only option is the editor, which takes turns with the preview\n  const hasMultipleLocales = $derived(i18nEnabled && allLocales.length > 1);\n  /* v8 ignore start -- the switcher is only rendered while the draft is there */\n  const validities = $derived(entryDraft.current?.validities ?? {});\n  const canPreview = $derived(entryDraft.current?.canPreview ?? true);\n  /* v8 ignore stop */\n  const listedLocales = $derived(\n    env.isSmallScreen || env.isMediumScreen\n      ? [...allLocales]\n      : allLocales.filter(\n          (locale) => !(thatPane.current?.mode === 'edit' && thatPane.current.locale === locale),\n        ),\n  );\n  // The preview can take this pane’s place when the other pane edits a locale\n  const previewOffered = $derived(\n    previewInThisPane ||\n      (thatPane.current?.mode === 'edit' &&\n        canPreview &&\n        !!entryEditorSettings.current?.showPreview),\n  );\n  const hasAnyError = $derived(\n    Object.entries(validities).some(\n      ([locale, validityMap]) => listedLocales.includes(locale) && hasInvalidFields(validityMap),\n    ),\n  );\n  const useDropDown = $derived(env.isSmallScreen || env.isMediumScreen || allLocales.length >= 5);\n  const SelectComponent = $derived(useDropDown ? Select : SelectButtonGroup);\n  const OptionComponent = $derived(useDropDown ? Option : SelectButton);\n  const variant = $derived(useDropDown ? undefined : 'tertiary');\n  const size = $derived(useDropDown ? undefined : 'small');\n  const currentValue = $derived(\n    thisPane.current?.mode === 'edit'\n      ? thisPane.current.locale\n      : thisPane.current?.mode === 'preview'\n        ? 'preview'\n        : undefined,\n  );\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <SelectComponent\n    value={currentValue}\n    class={hasAnyError && useDropDown ? 'error' : undefined}\n    ariaLabel={_(hasMultipleLocales ? 'switch_locale' : 'switch_view')}\n    aria-controls={id.replace('-header', '-body')}\n  >\n    <!-- Need an inner to style elements inside the <dialog> -->\n    <div role=\"none\" class=\"inner\">\n      {#each listedLocales as locale (locale)}\n        {@const label = hasMultipleLocales ? (getLocaleLabel(locale) ?? locale) : _('edit')}\n        {@const disabled = !entryDraft.current?.currentLocales[locale]}\n        <!-- A locale without content, e.g. a disabled one, is left out of the validation -->\n        {@const hasError = hasInvalidFields(validities[locale])}\n        <OptionComponent\n          {variant}\n          {size}\n          {label}\n          value={locale}\n          aria-label=\"{label} {disabled\n            ? _('locale_content_disabled_short')\n            : hasError\n              ? _('locale_content_error_short')\n              : ''}\"\n          selected={thisPane.current?.mode === 'edit' && thisPane.current.locale === locale}\n          class={hasError ? 'error' : ''}\n          data-mode=\"edit\"\n          onSelect={() => {\n            afterPendingFieldUpdates(() => {\n              thisPane.current = { mode: 'edit', locale };\n\n              if (thatPane.current?.mode === 'preview') {\n                thatPane.current = { mode: 'preview', locale };\n              }\n            });\n          }}\n        >\n          {#snippet startIcon()}\n            {#if disabled}\n              <Icon name=\"edit_off\" />\n            {:else if hasError}\n              <Icon name=\"error\" />\n            {/if}\n          {/snippet}\n        </OptionComponent>\n      {/each}\n      {#if previewOffered}\n        {#if useDropDown}\n          <Divider />\n        {/if}\n        <OptionComponent\n          {variant}\n          {size}\n          label={_('preview')}\n          value=\"preview\"\n          selected={thisPane.current?.mode === 'preview'}\n          data-mode=\"preview\"\n          onSelect={() => {\n            // Read the locale now: the other pane may change while the updates land. Without one,\n            // this pane previews the locale it edits\n            const { locale } = /** @type {EntryEditorPane} */ (\n              thatPane.current ?? thisPane.current\n            );\n\n            afterPendingFieldUpdates(() => {\n              thisPane.current = { mode: 'preview', locale };\n            });\n          }}\n        />\n      {/if}\n    </div>\n  </SelectComponent>\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n\n    :global {\n      .combobox {\n        @media (width < 1024px) {\n          min-width: 128px;\n          --sui-textbox-height: 32px;\n          --sui-button-medium-height: 32px;\n        }\n\n        &.error [role='combobox'] {\n          border-color: var(--sui-error-border-color);\n        }\n      }\n    }\n  }\n\n  .inner {\n    display: contents;\n\n    :global {\n      :is(.error, .error button[data-mode='edit']) {\n        color: var(--sui-error-foreground-color) !important;\n      }\n    }\n  }\n</style>\n","import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\nimport { getListItemIndexes, indexListItems } from '$lib/services/contents/entry/content-index';\nimport { getComputedValue } from '$lib/services/contents/fields/compute/helpers';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport { getFlatSubFields, someSubField } from '$lib/services/contents/fields/list/subfields';\nimport { COMPONENT_NAME_PREFIX_REGEX } from '$lib/services/contents/fields/rich-text';\nimport { getComponentDef } from '$lib/services/contents/fields/rich-text/components/definitions';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isFieldLocalized } from '$lib/services/contents/i18n/fields';\nimport { addSharedValues } from '$lib/services/contents/i18n/shared-values';\n\n/**\n * @import {\n * DraftValueStoreKey,\n * EntryDraft,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * ListItemIndex,\n * } from '$lib/types/private';\n * @import {\n * ComputeField,\n * Field,\n * FieldKeyPath,\n * ListField,\n * ListFieldWithSubField,\n * } from '$lib/types/public';\n */\n\n/**\n * A Compute field found in the content, paired with the key path it occupies.\n * @typedef {object} ComputeFieldInfo\n * @property {FieldKeyPath} keyPath Key path of the field.\n * @property {ComputeField} fieldConfig Field configuration.\n */\n\n/**\n * @typedef {object} CollectArgs\n * @property {Field} field Field configuration.\n * @property {FieldKeyPath} keyPath Key path the field occupies.\n * @property {FlattenedEntryContent} valueMap Flattened entry content.\n * @property {() => ListItemIndex} getIndex Get the index of the list items in the content. The\n * index is only built once a list is actually reached, so a Compute field that sits outside one\n * costs no scan at all.\n * @property {ComputeFieldInfo[]} results Collected fields, appended to in place.\n */\n\n/**\n * Cache of {@link containsComputeField} results, keyed by the field configuration. Configurations\n * are stable objects, so each one is answered once per session rather than on every draft update.\n * @type {WeakMap<Field, boolean>}\n */\nconst computeFieldCacheMap = new WeakMap();\n\n/**\n * Check whether the given field is a Compute field or holds one anywhere below it. Unlike\n * {@link collectFromField}, this only looks at the configuration, so every branch of a variable\n * type field is visited and the answer holds for the whole session.\n * @param {Field} field Field configuration.\n * @returns {boolean} Result.\n */\nconst containsComputeField = (field) =>\n  someSubField(field, ({ widget }) => widget === 'compute', computeFieldCacheMap);\n\n/**\n * Collect the Compute fields in the given field, which may be one itself or hold some below it.\n * @param {CollectArgs} args Arguments.\n */\nconst collectFromField = (args) => {\n  const { field, keyPath, valueMap, getIndex, results } = args;\n\n  // Stop before descending into a subtree the configuration says holds nothing to compute. This is\n  // what keeps an entry’s other content — a long list of plain fields, say — out of the walk\n  if (!containsComputeField(field)) {\n    return;\n  }\n\n  const { widget: fieldType = 'string' } = field;\n\n  if (fieldType === 'compute') {\n    results.push({ keyPath, fieldConfig: /** @type {ComputeField} */ (field) });\n\n    return;\n  }\n\n  if (fieldType === 'object') {\n    // A `null` value means the optional Object field is collapsed, so it holds no sub-values\n    if (valueMap[keyPath] === null) {\n      return;\n    }\n\n    (getFlatSubFields(field, valueMap, keyPath) ?? []).forEach((subField) => {\n      collectFromField({ ...args, field: subField, keyPath: `${keyPath}.${subField.name}` });\n    });\n\n    return;\n  }\n\n  // Only a List field is left: the guard above lets nothing else with sub-fields through, and a\n  // simple List field holding primitives can’t contain a Compute field either\n  const listField = /** @type {ListField} */ (field);\n  const { hasSingleSubField } = getListFieldInfo(listField);\n\n  getListItemIndexes(getIndex(), keyPath).forEach((itemIndex) => {\n    const itemKeyPath = `${keyPath}.${itemIndex}`;\n\n    // The single sub-field of a List field occupies the item’s own key path, with no name of its\n    // own appended to it\n    if (hasSingleSubField) {\n      collectFromField({\n        ...args,\n        field: /** @type {ListFieldWithSubField} */ (listField).field,\n        keyPath: itemKeyPath,\n      });\n\n      return;\n    }\n\n    (getFlatSubFields(listField, valueMap, itemKeyPath) ?? []).forEach((subField) => {\n      collectFromField({ ...args, field: subField, keyPath: `${itemKeyPath}.${subField.name}` });\n    });\n  });\n};\n\n/**\n * Collect the Compute fields in the given field list, descending into the Object fields and list\n * items that exist in the content.\n *\n * The fields are found from the configuration rather than from the content’s key paths, so a\n * Compute field is picked up even before it holds anything — which is the case for a field added to\n * the configuration after the entry was written, and for one inside a rich text editor component,\n * where missing values are deliberately not filled in.\n * @param {object} args Arguments.\n * @param {Field[]} args.fields Field list.\n * @param {FlattenedEntryContent} args.valueMap Flattened entry content.\n * @param {() => ListItemIndex} args.getIndex Get the index of the list items in the content.\n * @param {string} [args.keyPathPrefix] Key path prefix of the containing object, including its\n * trailing separator, e.g. `body:c12:` for a rich text editor component. Empty at the top level.\n * @returns {ComputeFieldInfo[]} Collected fields.\n */\nexport const collectComputeFields = ({ fields, valueMap, getIndex, keyPathPrefix = '' }) => {\n  /** @type {ComputeFieldInfo[]} */\n  const results = [];\n\n  fields.forEach((field) => {\n    collectFromField({\n      field,\n      keyPath: `${keyPathPrefix}${field.name}`,\n      valueMap,\n      getIndex,\n      results,\n    });\n  });\n\n  return results;\n};\n\n/**\n * Collect the Compute fields within the rich text editor components stored in the given content.\n *\n * Unlike an entry’s own fields, these aren’t known from the collection configuration: each\n * component instance records the component it was created from under its own key path prefix, and\n * the fields come from that component’s definition.\n * @param {FlattenedEntryContent} valueMap Flattened content of the `extraValues` store.\n * @param {() => ListItemIndex} getIndex Get the index of the list items in the content.\n * @returns {ComputeFieldInfo[]} Collected fields.\n */\nexport const collectComponentComputeFields = (valueMap, getIndex) => {\n  /** @type {ComputeFieldInfo[]} */\n  const results = [];\n  /** @type {Set<string>} */\n  const visitedPrefixes = new Set();\n\n  Object.keys(valueMap).forEach((key) => {\n    const [keyPathPrefix] = key.match(COMPONENT_NAME_PREFIX_REGEX) ?? [];\n\n    if (keyPathPrefix === undefined || visitedPrefixes.has(keyPathPrefix)) {\n      return;\n    }\n\n    visitedPrefixes.add(keyPathPrefix);\n\n    const { fields } = getComponentDef(valueMap[`${keyPathPrefix}__sc_component_name`]) ?? {};\n\n    if (fields) {\n      results.push(...collectComputeFields({ fields, valueMap, getIndex, keyPathPrefix }));\n    }\n  });\n\n  return results;\n};\n\n/**\n * Check whether a field’s value has to be computed for the given locale. This mirrors the condition\n * under which the editor shows the field: a field that can’t be edited in a locale doesn’t hold a\n * value there either, and writing one would add it to the saved file. A field using the `sync` i18n\n * strategy is only computed in the default locale, from which the value is copied to the others:\n * computed in each locale from a translatable field, it would be copied back and forth for good.\n * @param {object} args Arguments.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {InternalLocaleCode} args.defaultLocale Default locale code.\n * @param {boolean} args.i18nEnabled Whether i18n is enabled for the collection.\n * @returns {boolean} Result.\n */\nconst isLocaleTarget = ({ fieldConfig, locale, defaultLocale, i18nEnabled }) =>\n  locale === defaultLocale ||\n  (i18nEnabled && isFieldLocalized(fieldConfig.i18n) && fieldConfig.i18n !== 'sync');\n\n/**\n * Resolve every Compute field in the given locale’s content and write the results back. The content\n * is modified in place.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {DraftValueStoreKey} args.valueStoreKey Key the values are stored under.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FlattenedEntryContent} args.valueMap Flattened entry content for the locale, a snapshot\n * the values are read from.\n * @param {FlattenedEntryContent} args.target Value map of the draft to write the values to.\n * @returns {boolean} Whether any value has changed.\n */\nconst updateLocaleComputedValues = ({ draft, valueStoreKey, locale, valueMap, target }) => {\n  const { collectionName, fileName, fields, isIndexFile } = draft;\n  const { i18nEnabled, defaultLocale } = getDraftI18nConfig(draft);\n  /** @type {ListItemIndex | undefined} */\n  let index;\n\n  /**\n   * Get the index of the list items in the content, building it on first use.\n   * @returns {ListItemIndex} Index.\n   */\n  const getIndex = () => {\n    index ??= indexListItems(valueMap);\n\n    return index;\n  };\n\n  const computeFields =\n    valueStoreKey === 'extraValues'\n      ? collectComponentComputeFields(valueMap, getIndex)\n      : collectComputeFields({ fields, valueMap, getIndex });\n\n  // Nothing to resolve, e.g. in a rich text field that holds no editor component with a Compute\n  // field, so the values aren’t prepared either\n  if (!computeFields.length) {\n    return false;\n  }\n\n  let changed = false;\n\n  /**\n   * The entry’s values in the locale. In another locale than the default, the fields that aren’t\n   * localized, which only hold a value in the default locale, are added, so a Compute field\n   * referring to one gets the same value in every locale.\n   * @type {FlattenedEntryContent}\n   */\n  const entryValues = addSharedValues({\n    getFieldArgs: { collectionName, fileName, isIndexFile },\n    locale,\n    defaultLocale,\n    content: valueStoreKey === 'extraValues' ? getValueMapSnapshot(draft, locale) : valueMap,\n    defaultContent: getValueMapSnapshot(draft, defaultLocale),\n  });\n\n  /**\n   * Values to compute the fields from: the snapshot, until a field changes.\n   * @type {FlattenedEntryContent}\n   */\n  let values = valueStoreKey === 'extraValues' ? valueMap : entryValues;\n\n  computeFields.forEach(({ keyPath, fieldConfig }) => {\n    // The values of a rich text editor component belong to the document text, which is edited in\n    // every locale the parent field is, so the entry’s own locale rules don’t apply to them\n    if (\n      valueStoreKey !== 'extraValues' &&\n      !isLocaleTarget({ fieldConfig, locale, defaultLocale, i18nEnabled })\n    ) {\n      return;\n    }\n\n    const value = getComputedValue({\n      fieldConfig,\n      keyPath,\n      locale,\n      valueMap: values,\n      collectionName,\n      fileName,\n      isIndexFile,\n      // A field of a rich text editor component can refer to the component’s other fields as well\n      // as to the entry’s fields\n      ...(valueStoreKey === 'extraValues'\n        ? {\n            // Every key path collected from the store starts with a component’s prefix\n            keyPathPrefix: /** @type {RegExpMatchArray} */ (\n              keyPath.match(COMPONENT_NAME_PREFIX_REGEX)\n            )[0],\n            entryValueMap: entryValues,\n          }\n        : {}),\n    });\n\n    if (values[keyPath] !== value) {\n      target[keyPath] = value;\n      // A Compute field can refer to another one, which is resolved first, so the value is updated\n      // in a copy of the snapshot as well. The snapshot is shared, so it’s left as it is\n      values = values === valueMap ? { ...valueMap } : values;\n      values[keyPath] = value;\n      changed = true;\n    }\n  });\n\n  return changed;\n};\n\n/**\n * Resolve every Compute field in the given entry draft and write the results back.\n *\n * A Compute field derives its value from the rest of the content, so it has to be resolved again\n * whenever anything changes — including a change the user can’t see, such as a list item removed\n * while its parent is collapsed, which shifts the index of every item below it. That’s why the\n * draft is walked here rather than letting each field editor compute its own value: an editor only\n * runs while it’s rendered, and neither a collapsed list item nor one that has yet to be scrolled\n * into view renders its fields.\n *\n * A value is written only when it actually changes, so an effect calling this settles on the next\n * run instead of looping.\n * @param {EntryDraft} draft Entry draft.\n * @returns {boolean} Whether any value has changed.\n */\nexport const updateComputedValues = (draft) => {\n  const { currentLocales, fields } = draft;\n  let changed = false;\n\n  /** @type {DraftValueStoreKey[]} */ (['currentValues', 'extraValues']).forEach(\n    (valueStoreKey) => {\n      // The entry’s own fields are known up front, so an entry configured without a Compute field\n      // skips the content walk entirely. A rich text editor component’s fields aren’t, but nothing\n      // has to be walked while the document holds no component either\n      if (valueStoreKey === 'currentValues' && !fields.some(containsComputeField)) {\n        return;\n      }\n\n      Object.entries(draft[valueStoreKey]).forEach(([locale, target]) => {\n        // The values are read from the shared snapshot, rather than through the draft’s value map,\n        // whose every read is tracked and whose keys are listed by a proxy trap\n        const valueMap = getValueMapSnapshot(draft, locale, valueStoreKey);\n\n        if (!currentLocales[locale] || !Object.keys(valueMap).length) {\n          return;\n        }\n\n        if (updateLocaleComputedValues({ draft, valueStoreKey, locale, valueMap, target })) {\n          changed = true;\n        }\n      });\n    },\n  );\n\n  return changed;\n};\n","import { getValueMapVersion } from '$lib/services/contents/draft/create/versioned-map.svelte';\nimport { updateComputedValues } from '$lib/services/contents/draft/update/compute';\nimport { deferDraftWrite } from '$lib/services/contents/draft/update/deferred';\n\n/**\n * @import { EntryDraft } from '$lib/types/private';\n */\n\n/**\n * Drafts whose Compute fields are waiting to be resolved in a microtask, so the effect running more\n * than once before it fires still resolves them once.\n * @type {WeakSet<EntryDraft>}\n */\nconst pendingDrafts = new WeakSet();\n\n/**\n * Resolve the Compute fields of the given draft, and make the calling effect depend on everything\n * they can be computed from, so it runs again whenever a value changes. Call it from an `$effect`\n * of the editor holding the draft: the fields are resolved there rather than in their own editors,\n * which only run while they are rendered — a collapsed or off-screen list item renders none of its\n * fields.\n *\n * The fields are resolved outside the effect, as computed values are written to the draft; see\n * {@link deferDraftWrite}.\n * @param {EntryDraft} draft Entry draft.\n */\nexport const trackComputedValues = (draft) => {\n  // Depend on every field value, including those of rich text editor components, at the cost of\n  // one dependency per locale, without walking the values: each value map proxy counts its writes\n  [draft.currentValues, draft.extraValues].forEach((store) => {\n    Object.values(store).forEach(getValueMapVersion);\n  });\n  void $state.snapshot(draft.currentLocales);\n\n  if (pendingDrafts.has(draft)) {\n    return;\n  }\n\n  pendingDrafts.add(draft);\n\n  deferDraftWrite(() => {\n    pendingDrafts.delete(draft);\n    updateComputedValues(draft);\n  });\n};\n","import { setEntryDraftRoot } from '$lib/services/contents/draft/state.svelte';\nimport { trackComputedValues } from '$lib/services/contents/draft/update/compute-tracking.svelte';\n\n/**\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n */\n\n/**\n * Wire up an editor holding the given entry draft state: register its root element, so rich text\n * editor components, which are mounted outside the component tree, can look the draft up through\n * the DOM rather than the context, and resolve the Compute fields of whichever draft is open. Call\n * it while initializing the editor component.\n * @param {() => EntryDraftState} getEntryDraft Function returning the entry draft state of the\n * editor.\n * @param {() => HTMLElement | undefined} getRoot Function returning the editor root element, which\n * is `undefined` until it’s bound.\n */\nexport const initEntryDraftEditor = (getEntryDraft, getRoot) => {\n  $effect(() => {\n    const root = getRoot();\n\n    if (root) {\n      setEntryDraftRoot(root, getEntryDraft());\n    }\n  });\n\n  $effect(() => {\n    const draft = getEntryDraft().current;\n\n    if (draft) {\n      trackComputedValues(draft);\n    }\n  });\n};\n","import {\n  countCollectionEntries,\n  getEntriesByCollection,\n} from '$lib/services/contents/collection/entries';\nimport {\n  getCompanionEntries,\n  mergeUnpublishedEntries,\n  unpublishedEntries,\n} from '$lib/services/workflow';\n\n/**\n * Count the entries in the entry collection that take up a slot of its `limit` quota: the\n * published ones, plus the unpublished entries that have never been published, which Editorial\n * Workflow keeps out of {@link getEntriesByCollection}, including the new ones riding along in the\n * pull request of an entry of another collection. Like the count shown next to the collection in\n * the sidebar, it leaves Hugo’s special index file out — see {@link countCollectionEntries}.\n * @param {string} collectionName Collection name.\n * @returns {number} Count.\n */\nexport const countQuotaEntries = (collectionName) =>\n  countCollectionEntries(collectionName, [\n    ...mergeUnpublishedEntries(\n      getEntriesByCollection(collectionName),\n      unpublishedEntries.current.filter(\n        ({ workflow }) => workflow.collectionName === collectionName,\n      ),\n    ),\n    ...getCompanionEntries(collectionName),\n  ]);\n","import { _ } from '@sveltia/i18n';\nimport equal from 'fast-deep-equal';\n\nimport { checkForRemoteChanges } from '$lib/services/backends/refresh';\nimport { allEntries } from '$lib/services/contents';\nimport { getCommitAuthorName } from '$lib/services/utils/commit-author';\nimport { formatDate } from '$lib/services/utils/date';\n\n/**\n * @import { Entry, EntryDraft } from '$lib/types/private';\n */\n\n/**\n * What stands in the way of saving a draft: the entry it was made from is no longer what’s on the\n * branch.\n * @typedef {object} EntryConflict\n * @property {'modified' | 'deleted'} type Whether the entry has been changed or removed by someone\n * else since the draft was opened.\n * @property {Entry} [entry] The entry as it is on the branch now, with the commit author and date\n * when known. Only for a modified entry.\n * @property {boolean} canOverwrite Whether the entry can be saved over the change. An entry stored\n * in a file with the other entries of the collection can’t, as it’s told by its position, and the\n * item at the position may now be another entry that has moved there.\n */\n\n/**\n * Compare the version of an entry that edits were started from with the entry as it is now to tell\n * whether the entry has been changed since. The caller finds the current entry, as where it’s kept\n * depends on the caller: the configured branch, a pull request or an earlier save of a host entry.\n * @param {Entry} originalEntry Version the edits were started from.\n * @param {Entry | undefined} current Entry as it is now, or `undefined` if it has been deleted.\n * @returns {EntryConflict | undefined} The conflict, if any.\n */\nexport const compareEntries = (originalEntry, current) => {\n  const canOverwrite = originalEntry.arrayIndex === undefined;\n\n  if (!current) {\n    return { type: 'deleted', canOverwrite };\n  }\n\n  // The parsed content is compared rather than the file, so a commit that rewrote the file without\n  // changing what it says doesn’t count, nor does one that only touched the entry’s assets. A\n  // locale file added or removed does\n  if (!equal(current.locales, originalEntry.locales)) {\n    return { type: 'modified', entry: current, canOverwrite };\n  }\n\n  return undefined;\n};\n\n/**\n * Compare the draft’s original entry with the one on the configured branch to tell whether the\n * entry has been changed since the draft was opened.\n * @param {Entry} originalEntry Entry the draft was made from.\n * @returns {EntryConflict | undefined} The conflict, if any.\n */\nexport const compareWithStore = (originalEntry) =>\n  compareEntries(\n    originalEntry,\n    allEntries.current.find(({ id }) => id === originalEntry.id),\n  );\n\n/**\n * Find out whether saving the draft would overwrite someone else’s change: the repository is\n * checked for commits made since the site data was loaded, and the entry the draft was made from is\n * then compared with the entry as it is now. The check is only about an existing entry on the\n * configured branch; a new entry has nothing to overwrite, and an Editorial Workflow draft is\n * compared with the branch it lives on by {@link detectWorkflowConflict} instead.\n *\n * If the repository can’t be reached, the comparison is still made against what’s known, and the\n * commit that follows is left to fail on its own if the backend is really down.\n * @param {EntryDraft} draft Draft about to be saved.\n * @returns {Promise<EntryConflict | undefined>} The conflict, if any.\n */\nexport const detectEntryConflict = async (draft) => {\n  const { isNew, originalEntry } = draft;\n\n  if (isNew || !originalEntry) {\n    return undefined;\n  }\n\n  try {\n    await checkForRemoteChanges();\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to check the repository for changes.', ex);\n  }\n\n  return compareWithStore(originalEntry);\n};\n\n/**\n * Put the conflict into words for the user.\n * @param {EntryConflict} conflict Conflict.\n * @param {string} [locale] Locale to format the date in.\n * @returns {{ description: string, warning: string }} What happened, and what saving would do.\n */\nexport const describeConflict = ({ type, entry, canOverwrite }, locale) => {\n  if (type === 'deleted') {\n    return {\n      description: _('save_conflict.deleted'),\n      warning: _(canOverwrite ? 'save_conflict.recreate_warning' : 'save_conflict.reload_warning'),\n    };\n  }\n\n  // A modified entry always comes with its current version\n  const { commitAuthor, commitDate } = /** @type {Entry} */ (entry);\n  const name = getCommitAuthorName(commitAuthor);\n\n  return {\n    // Not every backend reports who made a commit along with the file\n    description:\n      name && commitDate\n        ? _('save_conflict.modified_by', {\n            values: { name, date: formatDate(commitDate, locale) },\n          })\n        : _('save_conflict.modified'),\n    warning: _(canOverwrite ? 'save_conflict.overwrite_warning' : 'save_conflict.reload_warning'),\n  };\n};\n","import { assignManualSortOrder } from '$lib/services/contents/draft/save/sort-order';\nimport { assignAutoNowValues } from '$lib/services/contents/fields/date-time/auto-now';\nimport { assignAutoIncrementValues } from '$lib/services/contents/fields/number/auto-increment';\n\n/**\n * @import { EntryDraft } from '$lib/types/private';\n */\n\n/**\n * Assign the values that are only given when the entry draft is saved: the manual sort order of a\n * new entry, the auto-increment numbers and the `auto_now` dates. The numbers are assigned before\n * the slugs are created, so a slug template can use them, and the dates tell when the entry was\n * actually saved rather than when the draft was created.\n * @param {EntryDraft} draft Draft to save, updated in place.\n * @param {number} offset Number of new entries of the same collection saved along with this one\n * that have already taken the orders and numbers after the highest ones, so this one comes after\n * them.\n */\nexport const assignSaveTimeValues = (draft, offset) => {\n  if (draft.isNew && draft.collection._type === 'entry') {\n    assignManualSortOrder(draft, offset);\n  }\n\n  assignAutoIncrementValues(draft, offset);\n  assignAutoNowValues(draft);\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { getCollection, getCollectionLabel } from '$lib/services/contents/collection';\nimport { getCollectionFile, getCollectionFileLabel } from '$lib/services/contents/collection/files';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { getListFormatter } from '$lib/services/contents/i18n';\nimport { WORKFLOW_STAGES, WORKFLOW_STATUS_LABELS } from '$lib/services/workflow/constants';\n\n/**\n * @import {\n * CompanionEntry,\n * InternalLocaleCode,\n * UnpublishedEntry,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Column headings of the Editorial Workflow board. The `drafts` heading is plural, unlike the\n * singular status label used in the entry editor’s status button.\n * @type {Record<WorkflowStatus, string>}\n */\nexport const COLUMN_LABELS = { ...WORKFLOW_STATUS_LABELS, draft: 'status.drafts' };\n\n/**\n * I18n string keys of the toast notification reporting an Editorial Workflow action.\n * @typedef {object} ToastMessages\n * @property {string} info Key shown while the action is in progress.\n * @property {string} success Key shown once the action has completed.\n * @property {string} error Key shown when the action has failed.\n */\n\n/** @type {ToastMessages} */\nexport const STATUS_UPDATE_MESSAGES = {\n  info: 'workflow.updating_status',\n  success: 'workflow.status_updated',\n  error: 'workflow.status_change_failed',\n};\n\n/**\n * Messages of the toast notification reporting a reload of the pull requests at the user’s request.\n * @type {ToastMessages}\n */\nexport const REFRESH_MESSAGES = {\n  info: 'workflow.refreshing',\n  success: 'workflow.refreshed',\n  error: 'workflow.refresh_failed',\n};\n\n/** @type {ToastMessages} */\nconst DELETION_MESSAGES = {\n  info: 'workflow.deleting_entry',\n  success: 'workflow.entry_deleted',\n  error: 'deleting_entry_failed',\n};\n\n/** @type {ToastMessages} */\nconst CANCELLATION_MESSAGES = {\n  info: 'workflow.cancelling_deletion',\n  success: 'workflow.deletion_cancelled',\n  error: 'workflow.cancelling_deletion_failed',\n};\n\n/** @type {ToastMessages} */\nconst PUBLISHING_MESSAGES = {\n  info: 'workflow.publishing_entry',\n  success: 'workflow.entry_published',\n  error: 'workflow.publishing_entry_failed',\n};\n\n/**\n * Get the toast messages for discarding an unpublished entry. Discarding a pending deletion calls\n * the deletion off.\n * @param {boolean} pendingDeletion Whether the entry is a pending deletion.\n * @returns {ToastMessages} Messages.\n */\nexport const getDiscardMessages = (pendingDeletion) =>\n  pendingDeletion ? CANCELLATION_MESSAGES : DELETION_MESSAGES;\n\n/**\n * Get the toast messages for publishing an unpublished entry. Publishing a pending deletion carries\n * the deletion out.\n * @param {boolean} pendingDeletion Whether the entry is a pending deletion.\n * @returns {ToastMessages} Messages.\n */\nexport const getPublishMessages = (pendingDeletion) =>\n  pendingDeletion ? DELETION_MESSAGES : PUBLISHING_MESSAGES;\n\n/**\n * Get the message announcing the Editorial Workflow page to screen readers, with the number of\n * entries in each column. A column the board doesn’t have is left out of the announcement rather\n * than reported as zero: there’s no Ready column for an Open Authoring contributor, no In Review\n * column when the review stage is left out, and no column but the drafts with Preview Workflow.\n * @param {{ status: WorkflowStatus, entries: UnpublishedEntry[] }[]} columns Stage columns. The\n * board always has a Drafts column.\n * @param {UnpublishedEntry[]} pendingDeletions Pending deletions.\n * @returns {{ key: string, values: Record<string, number> }} I18n string key and its values.\n */\nexport const getBoardAnnouncement = (columns, pendingDeletions) => {\n  /**\n   * Get the number of entries in the given column.\n   * @param {WorkflowStatus} status Column status.\n   * @returns {number | undefined} Count, or `undefined` if the board has no such column.\n   */\n  const count = (status) => columns.find((column) => column.status === status)?.entries.length;\n  const draft = /** @type {number} */ (count('draft'));\n  const [review, ready] = [count('pending_review'), count('pending_publish')];\n  const deletion = pendingDeletions.length;\n\n  if (review === undefined) {\n    return ready === undefined\n      ? { key: 'viewing_preview_workflow', values: { draft, deletion } }\n      : { key: 'viewing_editorial_workflow_without_review', values: { draft, ready, deletion } };\n  }\n\n  return ready === undefined\n    ? { key: 'viewing_open_authoring_workflow', values: { draft, review, deletion } }\n    : { key: 'viewing_editorial_workflow', values: { draft, review, ready, deletion } };\n};\n\n/**\n * Sort the unpublished entries into the columns of the Editorial Workflow board. A pending deletion\n * has a status of its own, so it never lands in a stage column; such entries are listed separately.\n * An entry is placed by the stage it’s in, which may differ from its status: see `resolveStage()`\n * in the stages module. A stage that isn’t configured for the board still gets a column while it\n * holds an entry, e.g. one left in a pull request of a collection that no longer uses a workflow,\n * so no entry goes missing.\n * @param {WorkflowStatus[]} stages Statuses of the stage columns, in order.\n * @param {UnpublishedEntry[]} entries Unpublished entries.\n * @param {(entry: UnpublishedEntry) => WorkflowStatus} [getStage] Function to get the stage an\n * entry is in. Default: the entry’s status.\n * @returns {{ columns: { status: WorkflowStatus, entries: UnpublishedEntry[] }[],\n * pendingDeletions: UnpublishedEntry[] }} Stage columns and pending deletions.\n */\nexport const groupEntriesByStatus = (\n  stages,\n  entries,\n  getStage = (entry) => entry.workflow.status,\n) => {\n  const entryStages = new Map(entries.map((entry) => [entry, getStage(entry)]));\n  const occupied = new Set(entryStages.values());\n\n  return {\n    columns: WORKFLOW_STAGES.filter(\n      (status) => stages.includes(status) || occupied.has(status),\n    ).map((status) => ({\n      status,\n      entries: entries.filter((entry) => entryStages.get(entry) === status),\n    })),\n    pendingDeletions: entries.filter((entry) => entryStages.get(entry) === 'pending_deletion'),\n  };\n};\n\n/**\n * Get the label naming the given unpublished entry, e.g. its title, or the label of the collection\n * file it stands for.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {string} Label, or the entry slug if its collection has been removed from the\n * configuration since the entry was saved.\n */\nexport const getUnpublishedEntryLabel = (entry) => {\n  const { collectionName, fileName } = entry.workflow;\n  const collection = getCollection(collectionName);\n\n  if (!collection) {\n    return entry.slug;\n  }\n\n  const collectionFile = fileName ? getCollectionFile(collection, fileName) : undefined;\n\n  return collectionFile\n    ? getCollectionFileLabel(collectionFile)\n    : getEntrySummary(collection, entry);\n};\n\n/**\n * Get the notes listing the entries that ride along in the pull request of the given entry, which\n * are published with it, for the entry’s card on the board: one for the new entries, and one for\n * the existing entries it changes.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {InternalLocaleCode | null | undefined} locale App locale, which the lists are formatted\n * for. Nothing is listed until it’s set, which is when the UI strings have been loaded.\n * @returns {string[]} Notes, e.g. `Also adds Section: Getting Started` and `Also changes Author:\n * Ada Lovelace`, without the one for which there are no entries.\n */\nexport const getCompanionNotes = (entry, locale) => {\n  const { companions = [] } = entry.workflow;\n\n  if (!locale) {\n    return [];\n  }\n\n  /**\n   * Get a note listing the given entries.\n   * @param {CompanionEntry[]} entries Entries.\n   * @param {string} key Message key of the note.\n   * @returns {string[]} Note, or nothing if there are no entries.\n   */\n  const getNote = (entries, key) => {\n    if (!entries.length) {\n      return [];\n    }\n\n    const items = entries.map(({ collectionName, entry: companion }) => {\n      const collection = getCollection(collectionName);\n\n      // The collection may have been removed from the configuration since the entry was saved\n      if (collection?._type !== 'entry') {\n        return companion.slug;\n      }\n\n      return _('workflow.companion_entry', {\n        values: {\n          collection: getCollectionLabel(collection, { useSingular: true }),\n          title: getEntrySummary(collection, companion),\n        },\n      });\n    });\n\n    return [_(key, { values: { entries: getListFormatter(locale).format(items) } })];\n  };\n\n  return [\n    ...getNote(\n      companions.filter(({ edited }) => !edited),\n      'workflow.companion_entries',\n    ),\n    ...getNote(\n      companions.filter(({ edited }) => edited),\n      'workflow.edited_companion_entries',\n    ),\n  ];\n};\n","import { unique } from '@sveltia/utils/array';\n\nimport { isReadonly } from '$lib/services/config/readonly';\nimport { allEntries } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { countQuotaEntries } from '$lib/services/contents/collection/entries/count';\nimport { getDraftValues, isDraftModified } from '$lib/services/contents/draft';\nimport { restoreBackup } from '$lib/services/contents/draft/backup';\nimport { buildDraft } from '$lib/services/contents/draft/create';\nimport {\n  getNewPendingEntriesByCollection,\n  getPendingEntriesByCollection,\n  getReferencedPendingEntrySet,\n  isRelationFieldOf,\n} from '$lib/services/contents/draft/pending-entries';\nimport {\n  createSavingEntryData,\n  removeDisabledLocales,\n} from '$lib/services/contents/draft/save/changes';\nimport { compareEntries } from '$lib/services/contents/draft/save/conflict';\nimport { assignSaveTimeValues } from '$lib/services/contents/draft/save/save-time';\nimport { getCanonicalSlug, getFillSlugOptions, getSlugs } from '$lib/services/contents/draft/slugs';\nimport { updateComputedValues } from '$lib/services/contents/draft/update/compute';\nimport { updateListFieldForLocales } from '$lib/services/contents/draft/update/list';\nimport { isEntryEditableAlong } from '$lib/services/contents/entry/editable';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getListItemKeys } from '$lib/services/contents/entry/key-paths';\nimport { getEntryOptions, getRefEntries } from '$lib/services/contents/fields/relation/helpers';\nimport { renameIfNeeded } from '$lib/services/utils/file';\nimport { getSnapshot } from '$lib/services/utils/state.svelte';\nimport {\n  findEditingUnpublishedEntry,\n  getCompanionEntries,\n  getEditedCompanionEntries,\n  getUnpublishedEntry,\n  getUnpublishedEntryByBranch,\n  getUnpublishedEntryByDraft,\n  isPendingDeletion,\n  isWorkflowDraft,\n  isWorkflowEnabled,\n} from '$lib/services/workflow';\nimport { getUnpublishedEntryLabel } from '$lib/services/workflow/board';\n\n/**\n * @import {\n * DraftValueStoreKey,\n * Entry,\n * EntryDraft,\n * EntrySlugVariants,\n * FlattenedEntryContent,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * PendingEntry,\n * QuickAddHost,\n * UnlistedEntry,\n * UnpublishedEntry,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, RelationField } from '$lib/types/public';\n * @import { EntryConflict } from '$lib/services/contents/draft/save/conflict';\n */\n\n/**\n * Get the entry the pending entries of the given draft are saved along with: the entry being\n * edited, or, in a quick-add dialog, the one the dialog was opened from, however deeply nested.\n * @param {EntryDraft} draft Draft.\n * @returns {QuickAddHost} Host entry.\n */\nexport const getQuickAddHost = (draft) =>\n  draft.quickAddHost ?? {\n    collectionName: draft.collectionName,\n    workflow: isWorkflowDraft(draft),\n    branch: getUnpublishedEntryByDraft(draft)?.workflow.pullRequest.branch,\n    entryIds: [draft.id],\n  };\n\n/**\n * Get the host to give the draft of a quick-add dialog opened from the given draft: the same host,\n * along with the given draft’s own entry, so none of the entries being edited in the dialogs opened\n * so far can be edited again from a nested dialog, where its changes would be overwritten.\n * @param {EntryDraft} parentDraft Draft the dialog is opened from.\n * @returns {QuickAddHost} Host entry.\n */\nexport const getNestedQuickAddHost = (parentDraft) => {\n  const host = getQuickAddHost(parentDraft);\n\n  return { ...host, entryIds: unique([...host.entryIds, parentDraft.id]) };\n};\n\n/**\n * Get the unpublished entry the host entry of the given draft has been saved as, whose pull request\n * holds the entries created or edited from it earlier.\n * @param {EntryDraft} draft Draft.\n * @returns {UnpublishedEntry | undefined} Unpublished entry, or `undefined` if the host entry has\n * no pull request.\n */\nconst getHostUnpublishedEntry = (draft) => {\n  const { branch } = getQuickAddHost(draft);\n\n  return branch ? getUnpublishedEntryByBranch(branch) : undefined;\n};\n\n/**\n * Get the new entries in the given collection that an earlier save of the host entry has committed\n * to its pull request, along with it. They aren’t in the collection until the pull request is\n * published.\n * @param {EntryDraft} draft Draft.\n * @param {string} collectionName Collection name.\n * @returns {Entry[]} Entries.\n */\nconst getHostCompanionEntries = (draft, collectionName) => {\n  const hostEntry = getHostUnpublishedEntry(draft);\n\n  return hostEntry ? getCompanionEntries(collectionName, [hostEntry]) : [];\n};\n\n/**\n * Get the entries a Relation field value of the given draft can refer to before they’re among the\n * entries of their collection: those an earlier save of the host entry has created or changed in\n * its pull request, and the entries pending on the draft, which come last, so they take the place\n * of an earlier version. A label resolved through a Relation field of a referenced entry finds them\n * there, as they aren’t in the collection until they’re saved, or the pull request is published.\n * @param {EntryDraft | null | undefined} draft Draft being edited.\n * @param {PendingEntry[]} [pendingEntries] Pending entries to include. Default: those of the draft.\n * @returns {UnlistedEntry[] | undefined} Entries, or `undefined` without a draft.\n */\nexport const getUnlistedEntries = (draft, pendingEntries = undefined) => {\n  if (!draft) {\n    return undefined;\n  }\n\n  const entries = pendingEntries ?? draft.pendingEntries;\n  const companions = getHostUnpublishedEntry(draft)?.workflow.companions ?? [];\n\n  return companions.length ? [...companions, ...entries] : entries;\n};\n\n/**\n * Get the given existing entry as it is now for the host entry of the given draft: as an earlier\n * save of the host entry has created or changed it in its pull request, or as it is on the\n * configured branch.\n * @param {EntryDraft} draft Draft.\n * @param {string} id Entry ID.\n * @returns {Entry | undefined} Entry, or `undefined` if it has been deleted.\n */\nexport const getLatestEntry = (draft, id) => {\n  const hostEntry = getHostUnpublishedEntry(draft);\n\n  return (\n    (hostEntry?.workflow.companions ?? []).find(({ entry }) => entry.id === id)?.entry ??\n    allEntries.current.find((entry) => entry.id === id)\n  );\n};\n\n/**\n * Compare the given version of an existing entry edited from a Relation field with the entry as it\n * is now for the host entry of the given draft, to tell whether someone else has changed it since.\n * See {@link getLatestEntry}.\n * @param {EntryDraft} draft Draft.\n * @param {Entry} baseEntry Version of the entry the edits were made to.\n * @returns {EntryConflict | undefined} The conflict, if any.\n */\nexport const compareWithLatest = (draft, baseEntry) =>\n  compareEntries(baseEntry, getLatestEntry(draft, baseEntry.id));\n\n/**\n * Check whether an entry of the given collection can be saved along with the host entry. While the\n * host entry is saved through Editorial Workflow, the entry goes into its pull request, where it’s\n * reviewed and published along with it, unless it’s in the same collection: the pull request\n * stands for the host entry, whose card lists the other entries, so one of the same collection\n * couldn’t be told apart from it. Otherwise, the entry is committed along with the host entry, so\n * it can’t be in a collection under the workflow, which would skip the review the collection asks\n * for. The same goes for publishing the host entry without its review: see `canSkipReviewAlong()`\n * in the workflow service.\n * @param {QuickAddHost} host Host entry.\n * @param {InternalEntryCollection} collection Collection of the entry.\n * @returns {boolean} Result.\n */\nconst canSaveAlongHost = (host, collection) =>\n  host.workflow ? collection.name !== host.collectionName : !isWorkflowEnabled(collection);\n\n/**\n * Get the collection a Relation field can have a new entry created in, so the entry can be\n * referenced right away. That’s the referenced collection, provided it holds entries that can be\n * created: a file/singleton collection has a fixed set of files, and a reference to one of them\n * points at a list item within the file, so there is nothing to create there. Nor can anything be\n * created in a hidden collection, whose entries aren’t meant to be edited, in a read-only\n * collection, or in one whose entries can’t be saved along with the host entry: see\n * {@link canSaveAlongHost}.\n * @param {object} args Arguments.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {EntryDraft} args.draft Draft being edited.\n * @returns {InternalEntryCollection | undefined} Collection, or `undefined` if entries can’t be\n * created for the field.\n * @see https://github.com/sveltia/sveltia-cms/issues/1112\n * @see https://github.com/sveltia/sveltia-cms/issues/1147\n */\nexport const getCreatableCollection = ({\n  fieldConfig: { collection: collectionName, file: fileName },\n  draft,\n}) => {\n  if (fileName) {\n    return undefined;\n  }\n\n  const collection = getCollection(collectionName);\n\n  if (\n    collection?._type !== 'entry' ||\n    collection.hide ||\n    collection.create === false ||\n    isReadonly({ collection })\n  ) {\n    return undefined;\n  }\n\n  return canSaveAlongHost(getQuickAddHost(draft), collection) ? collection : undefined;\n};\n\n/**\n * Check whether the collection’s entry quota leaves room for another entry, counting the entries\n * already added from the draft, which aren’t in the collection yet.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Collection to create an entry in.\n * @param {EntryDraft} args.draft Draft being edited.\n * @returns {boolean} Whether an entry can be added.\n */\nexport const hasCreationRoom = ({ collection, draft }) => {\n  const { name, limit = Infinity } = collection;\n  // The entries only existing in a pull request take up a slot as well, while the collection’s\n  // index file, its own page rather than one of the entries in it, doesn’t — see\n  // `countQuotaEntries()`. That includes the new entries riding along in one, which a pending entry\n  // becomes once the draft is saved, while the editor may stay open on the draft\n  const companionIds = new Set(getCompanionEntries(name).map(({ id }) => id));\n\n  const pendingCount = getNewPendingEntriesByCollection(draft, name).filter(\n    ({ entry }) => !companionIds.has(entry.id),\n  ).length;\n\n  return countQuotaEntries(name) + pendingCount < limit;\n};\n\n/**\n * Get the pending entries of the draft that the given Relation field can refer to, in the shape of\n * the entries the field is offered otherwise, followed by the entries an earlier save of the host\n * entry has committed to its pull request.\n * @param {object} args Arguments.\n * @param {EntryDraft | null | undefined} args.draft Draft being edited.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {Entry[]} args.refEntries Entries the field refers to otherwise. A pending entry that is\n * among them is left out: once the draft is saved, the entries land in the collection a moment\n * before the draft goes away, and the field would offer each of them twice meanwhile.\n * @returns {Entry[]} Entries.\n */\nexport const getPendingRefEntries = ({\n  draft,\n  fieldConfig: { collection: collectionName },\n  refEntries,\n}) => {\n  if (!draft) {\n    return [];\n  }\n\n  // A pending entry becomes one riding along in the pull request once the draft is saved, while the\n  // editor may stay open on the draft, so each entry is only offered once\n  const seenIds = new Set(refEntries.map(({ id }) => id));\n\n  return [\n    ...getPendingEntriesByCollection(draft, collectionName).map(({ entry }) => entry),\n    ...getHostCompanionEntries(draft, collectionName),\n  ].filter(({ id }) => {\n    if (seenIds.has(id)) {\n      return false;\n    }\n\n    seenIds.add(id);\n\n    return true;\n  });\n};\n\n/**\n * Get the entries the given Relation field refers to, followed by the pending entries of the draft\n * it can refer to: the entries created from the field, or another one referring to the same\n * collection, are offered and shown along with the saved ones until they’re saved too. An entry\n * edited from such a field is offered as edited, in its own place, including one an earlier save\n * of the host entry has changed in its pull request.\n * @param {object} args Arguments.\n * @param {EntryDraft | null | undefined} args.draft Draft being edited.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @returns {Entry[]} Entries.\n */\nexport const getRefEntriesWithPending = ({ draft, fieldConfig }) => {\n  const savedEntries = getRefEntries(fieldConfig);\n  const hostEntry = draft ? getHostUnpublishedEntry(draft) : undefined;\n\n  // An entry edited from the field since is offered as edited, and one changed in the pull request\n  // of the host entry by an earlier save as it stands there\n  const editedEntries = new Map([\n    ...(hostEntry ? getEditedCompanionEntries(fieldConfig.collection, [hostEntry]) : []).map(\n      (entry) => /** @type {[string, Entry]} */ ([entry.id, entry]),\n    ),\n    ...(draft ? getPendingEntriesByCollection(draft, fieldConfig.collection) : [])\n      .filter(({ baseEntry }) => !!baseEntry)\n      .map(({ entry }) => /** @type {[string, Entry]} */ ([entry.id, entry])),\n  ]);\n\n  const refEntries = editedEntries.size\n    ? savedEntries.map((entry) => editedEntries.get(entry.id) ?? entry)\n    : savedEntries;\n\n  const pendingEntries = getPendingRefEntries({ draft, fieldConfig, refEntries });\n\n  return pendingEntries.length ? [...refEntries, ...pendingEntries] : refEntries;\n};\n\n/**\n * Determine the slugs of an entry to be added to the draft. The slug is made unique among the\n * entries in the collection, but the entries pending on the draft aren’t there yet, so a second\n * entry added with the same title would get the same slug — and overwrite the first one on save.\n * The default locale’s slug is renamed if it’s taken by a pending entry, along with the slugs that\n * derive from it.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft of the entry to be added.\n * @param {PendingEntry[]} args.pendingEntries Entries pending on the draft being edited, apart\n * from an earlier version of the entry to be added, if it’s added again after a change.\n * @returns {EntrySlugVariants} Slugs.\n */\nexport const getPendingEntrySlugs = ({ draft, pendingEntries }) => {\n  // A numbered slug comes after the ones the entries pending on the parent draft have taken\n  const slugs = getSlugs({ draft, pendingEntries });\n  const { defaultLocaleSlug, localizedSlugs } = slugs;\n\n  // The entries riding along in a pull request, this one’s or another’s, aren’t there either\n  const pendingSlugs = [\n    ...pendingEntries\n      .filter((pendingEntry) => pendingEntry.collectionName === draft.collectionName)\n      .map(({ entry }) => entry),\n    ...getCompanionEntries(draft.collectionName),\n  ].map(({ slug }) => slug);\n\n  if (renameIfNeeded(defaultLocaleSlug, pendingSlugs) === defaultLocaleSlug) {\n    return slugs;\n  }\n\n  // The new slug has to be free among the saved entries as well, which the slug above was made\n  // unique against, but a renamed one wasn’t. A dot in a slug is part of the name rather than a\n  // file extension, so the number goes at the end\n  const renamedSlug = renameIfNeeded(\n    defaultLocaleSlug,\n    [...pendingSlugs, ...getEntriesByCollection(draft.collectionName).map(({ slug }) => slug)],\n    { hasExtension: false },\n  );\n\n  const renamedLocalizedSlugs = localizedSlugs\n    ? { ...localizedSlugs, [draft.defaultLocale]: renamedSlug }\n    : undefined;\n\n  return {\n    defaultLocaleSlug: renamedSlug,\n    localizedSlugs: renamedLocalizedSlugs,\n    canonicalSlug: getCanonicalSlug({\n      draft,\n      defaultLocaleSlug: renamedSlug,\n      localizedSlugs: renamedLocalizedSlugs,\n      fillSlugOptions: getFillSlugOptions({ draft }),\n    }),\n  };\n};\n\n/**\n * Turn the draft of an entry into a pending entry of the draft being edited: the entry is prepared\n * for saving the same way any entry is, and the file changes are held on the parent draft until\n * that one is saved. The draft can be a new entry, an entry already pending on the parent draft\n * that is opened again, or an existing entry being edited. The draft has to be valid; the caller\n * checks that, as it also reports the errors.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft of the entry to be added.\n * @param {EntryDraft} args.parentDraft Draft being edited.\n * @param {RelationField} args.fieldConfig Configuration of the Relation field the entry is added\n * from, which decides the values the entry goes by.\n * @returns {Promise<PendingEntry>} Pending entry.\n */\nexport const createPendingEntry = async ({ draft, parentDraft, fieldConfig }) => {\n  const { id, isNew, collectionName, originalEntry } = draft;\n  // The values the draft holds before they’re prepared for saving, blob URLs included, so the entry\n  // can be opened again. Taken before the save-time values below are assigned, which the entry\n  // gets anew when it’s added again\n  const source = getDraftValues(draft);\n  // An entry added again after a change takes the place of its earlier version\n  const otherPendingEntries = parentDraft.pendingEntries.filter(({ entry }) => entry.id !== id);\n  const newPendingEntries = getNewPendingEntriesByCollection(parentDraft, collectionName);\n  const index = newPendingEntries.findIndex(({ entry }) => entry.id === id);\n  // Each new entry takes the next order and number, the same way an entry saved on its own would.\n  // One added again keeps its place among the others\n  const offset = index > -1 ? index : newPendingEntries.length;\n\n  // The dates are set when the entry is added rather than when it’s saved along with the parent,\n  // which is when the changes were made\n  assignSaveTimeValues(draft, offset);\n  // A Compute field may refer to one of those values\n  updateComputedValues(draft);\n\n  // An existing entry keeps its slug; the slug editor isn’t offered for it in the dialog\n  const slugs = isNew\n    ? getPendingEntrySlugs({ draft, pendingEntries: otherPendingEntries })\n    : getSlugs({ draft });\n\n  // The `preSave` event hooks are called when the entry is actually saved, along with the parent\n  const prepared = await createSavingEntryData({ draft, slugs, runPreSave: false });\n  const { changes, savingAssets } = prepared;\n  // The locales turned off have no file to save, so they’re left out of the entry the stores get\n  const savingEntry = removeDisabledLocales(prepared.savingEntry);\n\n  // The value can be localized, e.g. `{{locale}}/{{slug}}`, so collect it for every locale the\n  // parent entry has\n  const values = unique(\n    Object.keys(parentDraft.currentValues).flatMap((locale) =>\n      getEntryOptions({\n        locale,\n        fieldConfig,\n        refEntry: savingEntry,\n        pendingEntries: getUnlistedEntries(parentDraft, otherPendingEntries),\n      }).map(({ value }) => value),\n    ),\n  );\n\n  return {\n    collectionName,\n    entry: savingEntry,\n    changes,\n    savingAssets,\n    values,\n    ...(isNew || !originalEntry ? {} : { baseEntry: getSnapshot(originalEntry) }),\n    source,\n  };\n};\n\n/**\n * Work out what the quick-add dialog opens to edit the given entry: the pending entry it stands\n * for, if it has been added or edited from the parent draft already, and the version of an existing\n * entry the dialog’s draft is built from. That’s the latest version of the entry, so a change made\n * by someone else since the entry was edited is picked up, and reported, rather than undone without\n * notice. An entry deleted since is edited from the version it was edited from. See\n * {@link getLatestEntry}.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.parentDraft Draft being edited, holding the pending entries.\n * @param {Entry} [args.entry] Entry to edit, as the field offers it. `undefined` for a new entry.\n * @returns {{ pendingEntry?: PendingEntry, baseEntry?: Entry, changedSince: boolean }} Pending\n * entry, base entry, and whether the entry has been changed by someone else since it was edited.\n */\nexport const getEditTarget = ({ parentDraft, entry }) => {\n  if (!entry) {\n    return { changedSince: false };\n  }\n\n  const pendingEntry = parentDraft.pendingEntries.find(({ entry: { id } }) => id === entry.id);\n\n  if (!pendingEntry) {\n    return { baseEntry: entry, changedSince: false };\n  }\n\n  const { baseEntry } = pendingEntry;\n\n  if (!baseEntry) {\n    return { pendingEntry, changedSince: false };\n  }\n\n  const latestEntry = getLatestEntry(parentDraft, baseEntry.id);\n\n  return {\n    pendingEntry,\n    baseEntry: latestEntry ?? baseEntry,\n    changedSince: !!latestEntry && !!compareWithLatest(parentDraft, baseEntry),\n  };\n};\n\n/**\n * Build the draft the quick-add dialog edits: a new entry, or the given entry. An entry pending on\n * the parent draft is opened with the values it was added with, on top of the latest version of the\n * entry if it’s an existing one, so the changes made by someone else since can be reviewed. See\n * {@link getEditTarget}.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Collection of the entry.\n * @param {EntryDraft} args.parentDraft Draft the dialog is opened from.\n * @param {Entry} [args.entry] Entry to edit. `undefined` for a new entry.\n * @returns {Promise<{ draft: EntryDraft, changedSince: boolean }>} Draft, and whether the entry has\n * been changed by someone else since it was edited.\n */\nexport const buildQuickAddDraft = async ({ collection, parentDraft, entry }) => {\n  const parentPendingEntries = parentDraft.pendingEntries;\n  const { pendingEntry, baseEntry, changedSince } = getEditTarget({ parentDraft, entry });\n\n  // A new entry starts at the root of the collection folder. The default is the folder being\n  // browsed, which belongs to the parent entry’s collection. The entry kept on the parent draft is\n  // a `$state` proxy, which the draft can’t clone\n  const draft = baseEntry\n    ? buildDraft({ collection, originalEntry: getSnapshot(baseEntry) })\n    : buildDraft({ collection, initialPath: '' });\n\n  if (pendingEntry?.source) {\n    // A new entry keeps its ID, so it takes the place of its earlier version when added again\n    draft.id = pendingEntry.entry.id;\n    // The values are copied, as the restore updates them in place\n    await restoreBackup({ backup: getSnapshot(pendingEntry.source), draft });\n  }\n\n  // The entries pending on the parent draft are offered to the Relation fields of the entry as\n  // well, and a nested quick-add takes them into account when it names and counts entries\n  draft.pendingEntries = [...parentPendingEntries];\n  // The entry is saved along with the entry being edited, which decides what can be added from the\n  // Relation fields of the entry in turn\n  draft.quickAddHost = getNestedQuickAddHost(parentDraft);\n\n  return { draft, changedSince };\n};\n\n/**\n * Check whether saving the given pending entry would move one of its files, e.g. when the path\n * template of the collection uses a field that has been changed. Moving an entry takes the entries\n * nested under it and the assets stored next to it along, and rewrites the entries referencing it,\n * which a save of the entry on its own does, but not one along with another entry.\n * @param {PendingEntry} pendingEntry Pending entry.\n * @returns {boolean} Result.\n */\nexport const isPendingEntryMoved = ({ baseEntry, changes }) =>\n  !!baseEntry && changes.some(({ action }) => action === 'move');\n\n/**\n * Take back the values assigned to the given draft when it was turned into the given pending entry,\n * e.g. the `auto_now` dates, if the entry isn’t added after all. They would otherwise count as a\n * change to the draft, so an entry put back as it was would be saved for nothing. A value is only\n * taken back while it’s still the one the entry was prepared with, so anything typed in the\n * meantime is kept.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft of the entry that wasn’t added.\n * @param {PendingEntry} args.pendingEntry Pending entry made from the draft.\n */\nexport const revertSaveTimeValues = ({ draft, pendingEntry: { entry, source } }) => {\n  Object.entries(source?.currentValues ?? {}).forEach(([locale, valueMap]) => {\n    const preparedValues = entry.locales[locale]?.content ?? {};\n    const currentValueMap = draft.currentValues[locale];\n\n    // The values are only ever assigned to the fields the draft already has\n    Object.entries(valueMap).forEach(([keyPath, value]) => {\n      if (\n        currentValueMap[keyPath] !== value &&\n        currentValueMap[keyPath] === preparedValues[keyPath]\n      ) {\n        currentValueMap[keyPath] = value;\n      }\n    });\n  });\n};\n\n/**\n * Add the given pending entries to the draft being edited. An entry already pending there, which\n * has been opened again and changed, takes the place of its earlier version.\n * @param {EntryDraft} draft Draft being edited.\n * @param {PendingEntry[]} pendingEntries Pending entries to add.\n */\nexport const addPendingEntries = (draft, pendingEntries) => {\n  pendingEntries.forEach((pendingEntry) => {\n    const index = draft.pendingEntries.findIndex(({ entry }) => entry.id === pendingEntry.entry.id);\n\n    if (index > -1) {\n      draft.pendingEntries[index] = pendingEntry;\n    } else {\n      draft.pendingEntries.push(pendingEntry);\n    }\n  });\n};\n\n/**\n * Get the pending entries to carry over to the draft being edited from the draft of an entry that\n * is being added to it: the entries created or edited from the Relation fields of that entry with a\n * nested quick-add dialog, as long as the entry still refers to them. The ones the draft inherited\n * from the parent when it was started are already there, unless they’ve been changed since.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft of the entry being added.\n * @param {EntryDraft} args.parentDraft Draft being edited.\n * @returns {PendingEntry[]} Pending entries.\n */\nexport const getNestedPendingEntries = ({ draft, parentDraft }) => {\n  const referenced = getReferencedPendingEntrySet(draft);\n\n  return draft.pendingEntries\n    .filter(\n      (pendingEntry) =>\n        referenced.has(pendingEntry) && !parentDraft.pendingEntries.includes(pendingEntry),\n    )\n    .map((pendingEntry) => getSnapshot(pendingEntry));\n};\n\n/**\n * Select the given pending entry in the Relation field it was added from, so the user doesn’t have\n * to pick it from the options after creating it.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft being edited.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @param {FieldKeyPath} args.keyPath Key path of the Relation field.\n * @param {DraftValueStoreKey} args.valueStoreKey Key to store the values in {@link EntryDraft}.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {PendingEntry} args.pendingEntry Pending entry to select.\n */\nexport const selectPendingEntry = ({\n  draft,\n  locale,\n  keyPath,\n  valueStoreKey,\n  fieldConfig,\n  pendingEntry,\n}) => {\n  const { i18n, multiple, max } = fieldConfig;\n\n  // An entry with list fields in its templates can have more than one value; take the first\n  const [value] = getEntryOptions({\n    locale,\n    fieldConfig,\n    refEntry: pendingEntry.entry,\n    // The same entries as the value the pending entry is saved for is worked out with\n    pendingEntries: getUnlistedEntries(draft),\n  }).map((option) => option.value);\n\n  if (value === undefined) {\n    return;\n  }\n\n  if (!multiple) {\n    // Writing the locale being edited is enough: the value store duplicates the value to the other\n    // locales if the field is configured so\n    draft[valueStoreKey][locale][keyPath] = value;\n\n    return;\n  }\n\n  /**\n   * Add the value to the list, unless it’s already there or the list is full.\n   * @param {{ valueList: any[] }} args Arguments.\n   */\n  const manipulate = ({ valueList }) => {\n    if (!valueList.includes(value) && (typeof max !== 'number' || valueList.length < max)) {\n      valueList.push(value);\n    }\n  };\n\n  updateListFieldForLocales({\n    draft,\n    locale,\n    i18n,\n    fieldConfig,\n    valueStoreKey,\n    keyPath,\n    manipulate,\n  });\n};\n\n/**\n * Check whether the given draft of an existing entry, opened in the quick-add dialog, has been left\n * as it was, in which case there’s nothing to save along with the parent: adding it anyway would\n * rewrite the entry’s files for nothing. An entry edited before is still added again, as the user\n * may have undone the earlier changes, which then have to replace them. The entries the draft\n * inherited from the parent don’t count as a change, while those added from its own Relation\n * fields do.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft of the entry opened in the dialog.\n * @param {EntryDraft} args.parentDraft Draft being edited.\n * @returns {boolean} Result.\n */\nexport const isEditUnchanged = ({ draft, parentDraft }) =>\n  !draft.isNew &&\n  !parentDraft.pendingEntries.some(({ entry }) => entry.id === draft.id) &&\n  !isDraftModified({ ...draft, pendingEntries: [] }) &&\n  !getNestedPendingEntries({ draft, parentDraft }).length;\n\n/**\n * Replace the values the entry being edited holds for an entry that has been changed with the\n * quick-add dialog, in every locale, if the change has changed the values the entry goes by, e.g.\n * the title of an entry referenced by its title, or the slug of a new entry that follows its title.\n * A field would otherwise be left pointing at an entry that no longer goes by the value. Not only\n * the Relation field the dialog was opened from is updated, but every Relation field of the entry\n * pointing at the same collection, e.g. `author` and `reviewers` both pointing at `authors`, each\n * with the values its own `value_field` gives. The values of a rich text editor component, whose\n * fields can’t be looked up, are only updated in the Relation field the dialog was opened from.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft being edited.\n * @param {FieldKeyPath} args.keyPath Key path of the Relation field.\n * @param {DraftValueStoreKey} args.valueStoreKey Key to store the values in {@link EntryDraft}.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {Entry} args.previousEntry Entry as it was before the change.\n * @param {Entry} args.entry Entry as it is now.\n */\nexport const replaceEntryValues = ({\n  draft,\n  keyPath,\n  valueStoreKey,\n  fieldConfig,\n  previousEntry,\n  entry,\n}) => {\n  const pendingEntries = getUnlistedEntries(draft);\n  const { collectionName, fileName, isIndexFile } = draft;\n  const refCollectionName = fieldConfig.collection;\n\n  /**\n   * Get the values to replace in the given locale for the given Relation field, keyed by the values\n   * the entry went by.\n   * @param {InternalLocaleCode} locale Locale.\n   * @param {RelationField} config Field configuration.\n   * @returns {Map<any, any>} Replacements, which are empty if the values haven’t changed, or can’t\n   * be paired, as a list field used in the templates has gained or lost an item.\n   */\n  const getReplacements = (locale, config) => {\n    /**\n     * Get the values the given entry goes by in the locale.\n     * @param {Entry} refEntry Entry.\n     * @returns {any[]} Values.\n     */\n    const getValues = (refEntry) =>\n      getEntryOptions({ locale, fieldConfig: config, refEntry, pendingEntries }).map(\n        ({ value }) => value,\n      );\n\n    const oldValues = getValues(previousEntry);\n    const newValues = getValues(entry);\n\n    if (oldValues.length !== newValues.length) {\n      return new Map();\n    }\n\n    return new Map(\n      oldValues\n        .map((value, index) => /** @type {[any, any]} */ ([value, newValues[index]]))\n        .filter(([oldValue, newValue]) => oldValue !== newValue),\n    );\n  };\n\n  /**\n   * Replace the values held at the given key paths.\n   * @param {FlattenedEntryContent} valueMap Values of a locale.\n   * @param {FieldKeyPath[]} keyPaths Key paths.\n   * @param {Map<any, any>} replacements Replacements.\n   */\n  const replaceValues = (valueMap, keyPaths, replacements) => {\n    keyPaths.forEach((key) => {\n      if (replacements.has(valueMap[key])) {\n        valueMap[key] = replacements.get(valueMap[key]);\n      }\n    });\n  };\n\n  Object.entries(draft.currentValues).forEach(([locale, valueMap]) => {\n    /**\n     * Replacements for each Relation field found, as the fields of a list share the configuration.\n     * @type {Map<RelationField, Map<any, any>>}\n     */\n    const replacementsByField = new Map();\n\n    Object.keys(valueMap).forEach((key) => {\n      const relationField = getField({\n        collectionName,\n        fileName,\n        isIndexFile,\n        valueMap,\n        keyPath: key,\n      });\n\n      if (!isRelationFieldOf(relationField, refCollectionName)) {\n        return;\n      }\n\n      if (!replacementsByField.has(relationField)) {\n        replacementsByField.set(relationField, getReplacements(locale, relationField));\n      }\n\n      replaceValues(\n        valueMap,\n        [key],\n        /** @type {Map<any, any>} */ (replacementsByField.get(relationField)),\n      );\n    });\n  });\n\n  if (valueStoreKey === 'extraValues') {\n    Object.entries(draft.extraValues).forEach(([locale, valueMap]) => {\n      const keyPaths = fieldConfig.multiple\n        ? getListItemKeys(valueMap, keyPath, { live: true })\n        : [keyPath];\n\n      replaceValues(valueMap, keyPaths, getReplacements(locale, fieldConfig));\n    });\n  }\n};\n\n/**\n * Check whether the given entry, referenced by a Relation field, can be edited with the quick-add\n * dialog, and saved along with the entry being edited. An entry created from a Relation field can\n * be changed until it’s saved. An existing entry can be edited if it’s in an entry collection that\n * isn’t hidden, as a hidden one isn’t meant to be edited, and where it can be saved on its own,\n * provided it’s not the entry being edited itself, and can be saved along with the entry being\n * edited: see {@link canSaveAlongHost} and {@link isEntryEditableAlong}. Nor is an entry offered\n * that another pull request changes already: its own, or that of another entry it has been edited\n * along with. Nor one that has been changed on the configured branch since the pull request of the\n * entry being edited was opened, as its branch, which is never rebased, still has the entry as it\n * was then, or not at all: the edit would then be refused as an unexpected change on publishing, or\n * conflict with the newer version when merged.\n * @param {object} args Arguments.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {EntryDraft} args.draft Draft being edited.\n * @param {Entry} args.entry Referenced entry.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/1147\n */\nexport const canEditEntry = ({\n  fieldConfig: { collection: collectionName, file },\n  draft,\n  entry,\n}) => {\n  const pendingEntry = getPendingEntriesByCollection(draft, collectionName).find(\n    (_pendingEntry) => _pendingEntry.entry.id === entry.id,\n  );\n\n  // The dialog can only be opened again with the values of the draft, which an entry added before\n  // they were kept doesn’t have\n  if (pendingEntry && !pendingEntry.source) {\n    return false;\n  }\n\n  if (pendingEntry && !pendingEntry.baseEntry) {\n    return true;\n  }\n\n  const collection = getCollection(collectionName);\n\n  if (\n    file ||\n    collection?._type !== 'entry' ||\n    collection.hide ||\n    isReadonly({ collection }) ||\n    !isEntryEditableAlong(collection, entry) ||\n    isPendingDeletion(entry)\n  ) {\n    return false;\n  }\n\n  const host = getQuickAddHost(draft);\n\n  if (!canSaveAlongHost(host, collection)) {\n    return false;\n  }\n\n  // Another pull request changes the entry already: its own, or that of another entry it has been\n  // edited along with\n  const editingEntry = findEditingUnpublishedEntry(entry);\n\n  if (\n    !!getUnpublishedEntry({ collectionName, subPath: entry.subPath }) ||\n    (!!editingEntry && editingEntry.workflow.pullRequest.branch !== host.branch)\n  ) {\n    return false;\n  }\n\n  // An entry the pull request already changes, or holds as a new entry, is on its branch as it is\n  if (!editingEntry && host.branch && entry.commitDate) {\n    const { pullRequest, companions = [] } =\n      getUnpublishedEntryByBranch(host.branch)?.workflow ?? {};\n\n    if (\n      pullRequest &&\n      entry.commitDate > pullRequest.createdDate &&\n      !companions.some((companion) => companion.entry.id === entry.id)\n    ) {\n      return false;\n    }\n  }\n\n  return entry.id !== draft.id && !host.entryIds.includes(entry.id);\n};\n\n/**\n * Get the entries selected in the given Relation field that can be edited with the quick-add\n * dialog. A value matching more than one entry, e.g. a title two entries share, can’t tell which\n * entry it refers to, so it’s left out.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft being edited.\n * @param {InternalLocaleCode} args.locale Locale being edited.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {Entry[]} args.refEntries Entries the field can refer to, pending ones included. See\n * {@link getRefEntriesWithPending}.\n * @param {any} args.currentValue Field value: a single value, or a list of values if the field\n * allows multiple values.\n * @returns {{ value: any, label: string, entry: Entry }[]} Selected entries with the value and the\n * label they’re selected by.\n */\nexport const getEditableEntries = ({ draft, locale, fieldConfig, refEntries, currentValue }) => {\n  const values = (Array.isArray(currentValue) ? currentValue : [currentValue]).filter(\n    (value) => value !== undefined && value !== null && value !== '',\n  );\n\n  if (!values.length) {\n    return [];\n  }\n\n  const pendingEntries = getUnlistedEntries(draft);\n  const valueSet = new Set(values);\n\n  // Only the options going by a selected value are kept, grouped by the value\n  const optionsByValue = Map.groupBy(\n    refEntries.flatMap((entry) =>\n      getEntryOptions({ locale, fieldConfig, refEntry: entry, pendingEntries })\n        .filter(({ value }) => valueSet.has(value))\n        .map(({ label, value }) => ({ value, label, entry })),\n    ),\n    ({ value }) => value,\n  );\n\n  // Two values can go by the same entry, e.g. two items of a list field used as the value, which is\n  // then offered once\n  const seenIds = new Set();\n\n  return values.flatMap((value) => {\n    const [match, ...others] = optionsByValue.get(value) ?? [];\n\n    if (\n      !match ||\n      others.some(({ entry }) => entry.id !== match.entry.id) ||\n      seenIds.has(match.entry.id) ||\n      !canEditEntry({ fieldConfig, draft, entry: match.entry })\n    ) {\n      return [];\n    }\n\n    seenIds.add(match.entry.id);\n\n    return [match];\n  });\n};\n\n/**\n * Get the name of the entry whose pull request changes the entry of the given draft along with it,\n * the entry having been edited from a Relation field of that entry. Saving the draft on its own\n * then changes the entry in two places, which Git combines or refuses to combine when the pull\n * request is published.\n * @param {EntryDraft | null | undefined} draft Draft being edited.\n * @returns {string | undefined} Name of the entry, e.g. its title, or `undefined` if no other pull\n * request changes the entry.\n */\nexport const getEditingHostName = (draft) => {\n  if (!draft || draft.isNew || !draft.originalEntry) {\n    return undefined;\n  }\n\n  const hostEntry = findEditingUnpublishedEntry(draft.originalEntry);\n\n  return hostEntry ? getUnpublishedEntryLabel(hostEntry) : undefined;\n};\n","<!--\n  @component\n  Implement the dialog to create a new entry in the collection a Relation field refers to, or edit\n  one selected in the field, without leaving the entry being edited. The entry is not saved on its\n  own: it’s added to the parent draft as a pending entry, selected in the field, and committed\n  together with the parent entry. A pending entry can be opened again and changed until then.\n  @see https://github.com/sveltia/sveltia-cms/issues/493\n  @see https://github.com/sveltia/sveltia-cms/issues/1129\n-->\n<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Alert, Button, Dialog, Spacer, Toast } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import DisabledLocaleState from '$lib/components/contents/details/disabled-locale-state.svelte';\n  import EntryEditor from '$lib/components/contents/details/editor/entry-editor.svelte';\n  import SlugEditor from '$lib/components/contents/details/editor/slug-editor.svelte';\n  import ValidationErrorsToast from '$lib/components/contents/details/editor/validation-errors-toast.svelte';\n  import LocaleSwitcher from '$lib/components/contents/details/locale-switcher.svelte';\n  import { getCollectionLabel } from '$lib/services/contents/collection';\n  import { revokeDraftFileURLs } from '$lib/services/contents/draft';\n  import { initEntryDraftEditor } from '$lib/services/contents/draft/editor.svelte';\n  import {\n    EntryDraftState,\n    getEntryDraftContext,\n    setEntryDraftContext,\n  } from '$lib/services/contents/draft/state.svelte';\n  import {\n    countInvalidFields,\n    validateAndRevealErrors,\n  } from '$lib/services/contents/draft/validate/reveal';\n  import { setFieldEditorContext } from '$lib/services/contents/editor/field-context';\n  import { awaitPendingFieldUpdates } from '$lib/services/contents/editor/pending';\n  import { needsSlugInput } from '$lib/services/contents/editor/slug';\n  import {\n    addPendingEntries,\n    buildQuickAddDraft,\n    createPendingEntry,\n    getNestedPendingEntries,\n    isEditUnchanged,\n    isPendingEntryMoved,\n    revertSaveTimeValues,\n  } from '$lib/services/contents/fields/relation/quick-add';\n  import { createRawState } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import {\n   * Entry,\n   * EntryDraft,\n   * EntryEditorPane,\n   * FieldEditorContext,\n   * InternalEntryCollection,\n   * PendingEntry,\n   * } from '$lib/types/private';\n   * @import { RelationField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [open] Whether the dialog is open.\n   * @property {InternalEntryCollection} collection Collection to create or edit an entry in.\n   * @property {RelationField} fieldConfig Configuration of the Relation field the entry is created\n   * or edited from.\n   * @property {Entry} [entry] Entry to edit, as the field offers it: an existing entry, or one\n   * pending on the parent draft. A new entry is created without it.\n   * @property {(pendingEntry: PendingEntry, previousEntry?: Entry) => void} onAdd Called with the\n   * entry once it’s been added to the parent draft, along with the entry as it was before when it\n   * has been edited.\n   */\n\n  /** @type {Props} */\n  let { open = $bindable(false), collection, fieldConfig, entry = undefined, onAdd } = $props();\n\n  // The parent draft is the one provided by the editor this dialog is opened from. The new entry’s\n  // draft is provided to the field editors below in its place, so they edit the new entry\n  const parentDraft = getEntryDraftContext();\n  const entryDraft = setEntryDraftContext(new EntryDraftState());\n\n  // The fields of the entry are rendered at the top level of its draft, like in the entry editor,\n  // not as the subfields of the Relation field, which may be in a rich text editor component whose\n  // values are stored in `extraValues` instead of `currentValues`\n  setFieldEditorContext(/** @type {FieldEditorContext} */ ({}));\n\n  /**\n   * Locale being edited. The dialog has a single pane, so the locale switcher is the only way to\n   * get to the other locales.\n   * @type {{ current: ?EntryEditorPane }}\n   */\n  const pane = createRawState(/** @type {?EntryEditorPane} */ (null));\n\n  const componentId = $props.id();\n\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n  let adding = $state(false);\n  /** Whether the entry has been added, so the draft is kept when the dialog closes. */\n  let added = false;\n  let showValidationToast = $state(false);\n  let errorCount = $state(0);\n  let showErrorToast = $state(false);\n  let showMoveToast = $state(false);\n  /** Whether the entry being edited has been changed by someone else since it was edited. */\n  let changedSince = $state(false);\n  /** Entry being edited, as it was when the dialog was opened. */\n  let previousEntry = $state.raw(/** @type {Entry | undefined} */ (undefined));\n  /** Incremented each time a draft is started, so a draft started earlier can tell it’s stale. */\n  let draftCount = 0;\n\n  /* v8 ignore start -- the app locale is always set once the UI strings are loaded */\n  // `appLocale.current` is a key, because `getCollectionLabel` can return a localized label\n  const name = $derived(\n    appLocale.current ? getCollectionLabel(collection, { useSingular: true }) : '',\n  );\n  /* v8 ignore stop */\n  const { i18nEnabled, allLocales, defaultLocale } = $derived(collection._i18n);\n  const hasMultipleLocales = $derived(i18nEnabled && allLocales.length > 1);\n  const editing = $derived(!!previousEntry);\n\n  /**\n   * Show the error toast for an unexpected error, and log the error.\n   * @param {unknown} ex Error.\n   */\n  const reportError = (ex) => {\n    showErrorToast = true;\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  };\n\n  /**\n   * Start a draft for the dialog: a new entry, or the entry to edit. See\n   * {@link buildQuickAddDraft}.\n   */\n  const startDraft = async () => {\n    draftCount += 1;\n\n    const count = draftCount;\n    const editingEntry = entry;\n\n    previousEntry = editingEntry;\n    changedSince = false;\n\n    // The dialog is only opened from a field editor while the draft is there\n    const { draft, changedSince: changedSinceEdited } = await buildQuickAddDraft({\n      collection,\n      parentDraft: /** @type {EntryDraft} */ (parentDraft.current),\n      entry: editingEntry,\n    });\n\n    // The dialog may have been closed, or opened again for another entry, in the meantime\n    if (count !== draftCount || !open) {\n      revokeDraftFileURLs(draft);\n\n      return;\n    }\n\n    entryDraft.current = draft;\n    pane.current = { mode: 'edit', locale: defaultLocale };\n    changedSince = changedSinceEdited;\n    added = false;\n  };\n\n  /**\n   * Discard the draft once the dialog is closed. Its files are only kept when the entry has been\n   * added, as they go into the commit.\n   */\n  const discardDraft = () => {\n    if (!added) {\n      revokeDraftFileURLs(entryDraft.current);\n    }\n\n    // A draft still being started is not to be shown\n    draftCount += 1;\n    entryDraft.current = undefined;\n    pane.current = null;\n    previousEntry = undefined;\n  };\n\n  /**\n   * Validate the draft and add it to the parent draft as a pending entry.\n   */\n  const add = async () => {\n    const draft = entryDraft.current;\n\n    /* v8 ignore next 3 -- the button is only there while the draft is being edited */\n    if (!draft || !parentDraft.current) {\n      return;\n    }\n\n    adding = true;\n\n    try {\n      // Wait for what was just typed to reach the draft first, e.g. in a rich text editor, which\n      // converts its content with a short delay, or the change would be taken for no change at all\n      await awaitPendingFieldUpdates();\n\n      // The dialog can be closed with the Escape key in the meantime\n      if (!open || entryDraft.current !== draft) {\n        return;\n      }\n\n      // Nothing to save for an entry opened only to have a look\n      if (isEditUnchanged({ draft, parentDraft: parentDraft.current })) {\n        open = false;\n\n        return;\n      }\n\n      // The entry is committed along with the parent, so it has to be complete. Wait for custom\n      // validators to report, the same way a save does\n      if (\n        !(await validateAndRevealErrors({ draft, enforceRequired: true, awaitFieldUpdates: false }))\n      ) {\n        errorCount = countInvalidFields(draft.validities);\n        showValidationToast = true;\n\n        return;\n      }\n\n      const pendingEntry = await createPendingEntry({\n        draft,\n        parentDraft: parentDraft.current,\n        fieldConfig,\n      });\n\n      // The dialog can be closed with the Escape key in the meantime, and even opened again. The\n      // draft is then discarded, along with the URLs of its files, so the entry is not to be added\n      if (!open || entryDraft.current !== draft) {\n        return;\n      }\n\n      if (isPendingEntryMoved(pendingEntry)) {\n        revertSaveTimeValues({ draft, pendingEntry });\n        showMoveToast = true;\n\n        return;\n      }\n\n      // The entries created or edited from the entry’s own Relation fields come along with it\n      addPendingEntries(parentDraft.current, [\n        ...getNestedPendingEntries({ draft, parentDraft: parentDraft.current }),\n        pendingEntry,\n      ]);\n      onAdd(pendingEntry, previousEntry);\n      added = true;\n      open = false;\n    } catch (ex) {\n      reportError(ex);\n    } finally {\n      adding = false;\n    }\n  };\n\n  $effect(() => {\n    if (open) {\n      untrack(() => {\n        startDraft().catch(reportError);\n      });\n    }\n  });\n\n  // Register the editor root and resolve the Compute fields the same way the main editor does\n  initEntryDraftEditor(\n    () => entryDraft,\n    () => wrapper,\n  );\n</script>\n\n<Dialog\n  bind:open\n  title={_(editing ? 'relation_field.edit_entry_title' : 'create_entry_title', {\n    values: { name },\n  })}\n  size=\"large\"\n  showOk={false}\n  showCancel={false}\n  onClose={() => {\n    discardDraft();\n  }}\n>\n  {#snippet headerExtra()}\n    {#if hasMultipleLocales && entryDraft.current}\n      <LocaleSwitcher id=\"{componentId}-header\" thisPane={pane} />\n    {/if}\n  {/snippet}\n  <div role=\"none\" class=\"wrapper\" bind:this={wrapper}>\n    <p class=\"hint\">\n      {_(editing ? 'relation_field.edit_together_hint' : 'relation_field.save_together_hint', {\n        values: { name },\n      })}\n    </p>\n    {#if changedSince}\n      <Alert status=\"warning\">\n        {_('relation_field.changed_since_edit', { values: { name } })}\n      </Alert>\n    {/if}\n    {#if entryDraft.current && pane.current}\n      {@const { locale } = pane.current}\n      <!-- A rich text editor component, mounted outside the component tree, reads the locale from\n        `data-locale` through the DOM, like in the entry editor’s pane -->\n      <div role=\"none\" id=\"{componentId}-body\" class=\"fields\" data-locale={locale}>\n        <!-- There’s no sidebar with the Slug panel in the dialog, so a slug that has to be typed\n          in is edited here. Otherwise, the slug template fills it -->\n        {#if !entryDraft.current.currentLocales[locale]}\n          <!-- A disabled locale has no values to edit, so it has to be enabled first, like in the\n            entry editor’s pane -->\n          <DisabledLocaleState {locale} />\n        {:else}\n          {#if needsSlugInput(entryDraft.current) && entryDraft.current.slugEditor[locale]}\n            {#key locale}\n              <SlugEditor {locale} />\n            {/key}\n          {/if}\n          <EntryEditor {locale} />\n        {/if}\n      </div>\n    {/if}\n  </div>\n  {#snippet footer()}\n    <Spacer flex={true} />\n    <Button\n      variant=\"primary\"\n      label={_(editing ? 'update' : 'add')}\n      disabled={adding}\n      onclick={() => {\n        add();\n      }}\n    />\n    <Button\n      variant=\"secondary\"\n      label={_('cancel')}\n      disabled={adding}\n      onclick={() => {\n        open = false;\n      }}\n    />\n  {/snippet}\n</Dialog>\n\n<ValidationErrorsToast bind:show={showValidationToast} count={errorCount} />\n\n<Toast bind:show={showErrorToast}>\n  <Alert status=\"error\">\n    {_(editing ? 'relation_field.edit_failed' : 'relation_field.add_failed', {\n      values: { name },\n    })}\n  </Alert>\n</Toast>\n\n<Toast bind:show={showMoveToast}>\n  <Alert status=\"error\">\n    {_('relation_field.move_unsupported', { values: { name } })}\n  </Alert>\n</Toast>\n\n<style>\n  .wrapper {\n    --field-editor-padding: 16px;\n    display: flex;\n    flex-direction: column;\n    gap: 16px;\n  }\n\n  .hint {\n    margin: 0;\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n  }\n\n  .fields {\n    display: flex;\n    flex-direction: column;\n  }\n</style>\n","<script>\n  import { Checkbox, CheckboxGroup, SelectTags } from '@sveltia/ui';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { updateListFieldForLocales } from '$lib/services/contents/draft/update/list';\n  import { getFieldEditorContext } from '$lib/services/contents/editor/field-context';\n\n  /**\n   * @import { SelectFieldSelectorProps } from '$lib/types/private';\n   * @import { SelectFieldValue } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {SelectFieldValue[] | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const { valueStoreKey = 'currentValues' } = getFieldEditorContext();\n\n  /** @type {SelectFieldSelectorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    fieldId,\n    fieldConfig,\n    currentValue,\n    required = true,\n    readonly = false,\n    invalid = false,\n    options,\n  } = $props();\n\n  const { i18n, max, dropdown_threshold: dropdownThreshold = 5 } = $derived(fieldConfig);\n\n  /**\n   * Update the value for the list.\n   * @param {(arg: { valueList: any[], expanderStateList: any[] }) => void} manipulate See\n   * {@link updateListFieldForLocales}.\n   */\n  const updateList = (manipulate) => {\n    const draft = entryDraft.current;\n\n    // Avoid an error while navigating pages\n    /* v8 ignore next 11 */\n    if (draft) {\n      updateListFieldForLocales({\n        draft,\n        locale,\n        i18n,\n        fieldConfig,\n        valueStoreKey,\n        keyPath,\n        manipulate,\n      });\n    }\n  };\n\n  /**\n   * Add a value to the list.\n   * @param {SelectFieldValue} value Value to be added.\n   */\n  const addValue = (value) => {\n    updateList(({ valueList }) => {\n      valueList.push(value);\n    });\n  };\n\n  /**\n   * Remove a value from the list.\n   * @param {SelectFieldValue} value Value to be removed.\n   */\n  const removeValue = (value) => {\n    updateList(({ valueList }) => {\n      const index = valueList.indexOf(value);\n\n      // A duplicated locale may not have the value; `-1` would remove its last value instead\n      if (index > -1) {\n        valueList.splice(index, 1);\n      }\n    });\n  };\n</script>\n\n{#if options.length > dropdownThreshold}\n  <SelectTags\n    disabled={readonly}\n    {readonly}\n    {required}\n    {invalid}\n    {options}\n    {...{ values: /** @type {any} */ (currentValue) }}\n    {max}\n    aria-labelledby=\"{fieldId}-label\"\n    aria-errormessage=\"{fieldId}-error\"\n    onAddValue={({ detail: { value } }) => {\n      addValue(value);\n    }}\n    onRemoveValue={({ detail: { value } }) => {\n      removeValue(value);\n    }}\n    onReorder={({ detail: { values } }) => {\n      updateList(({ valueList }) => {\n        valueList.splice(0, valueList.length, ...values);\n      });\n    }}\n  />\n{:else}\n  <CheckboxGroup aria-labelledby=\"{fieldId}-label\">\n    {#each options as { label, value }, index (`${index}-${value}`)}\n      <Checkbox\n        {label}\n        {value}\n        {readonly}\n        {required}\n        {invalid}\n        checked={currentValue?.includes(value) ?? false}\n        aria-errormessage=\"{fieldId}-error\"\n        onChange={({ detail: { checked } }) => {\n          if (checked) {\n            addValue(value);\n          } else {\n            removeValue(value);\n          }\n        }}\n      />\n    {/each}\n  </CheckboxGroup>\n{/if}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Option, Radio, RadioGroup, Select } from '@sveltia/ui';\n\n  import {\n    getEmptyOptionValue,\n    getOptionValueType,\n  } from '$lib/services/contents/fields/select/helpers';\n\n  /**\n   * @import { SelectFieldSelectorOption, SelectFieldSelectorProps } from '$lib/types/private';\n   * @import { SelectFieldValue } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {SelectFieldValue | undefined} currentValue Field value.\n   */\n\n  /** @type {SelectFieldSelectorProps & Props} */\n  let {\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    options,\n  } = $props();\n\n  const { dropdown_threshold: dropdownThreshold = 5 } = $derived(fieldConfig);\n  /** Whether one of the options already clears the value, so no “unselected” option is needed. */\n  const hasEmptyOption = $derived(options.some(({ value }) => value === null || value === ''));\n  /**\n   * Options to render, with an extra “unselected” option prepended so the user can clear the value\n   * if the field is optional. This is derived rather than written back to the `options` prop from\n   * an `$effect`. An effect that reads and writes the same state renders the field twice, and the\n   * second pass tears down and rebuilds every option, because the `{#each}` key contains the\n   * option index and prepending invalidates all of them. Worse, the write happens inside a running\n   * reaction, where Svelte cannot memoize its dirty-marking traversal, so the cost grows with the\n   * depth of the editor tree — a select nested in a list can lock up the browser for minutes.\n   * @type {SelectFieldSelectorOption[]}\n   */\n  const allOptions = $derived(\n    !required && !hasEmptyOption\n      ? [\n          {\n            label: _('unselected_option'),\n            value: getEmptyOptionValue(options[0]?.value),\n            searchValue: '',\n          },\n          ...options,\n        ]\n      : options,\n  );\n</script>\n\n{#if allOptions.length > dropdownThreshold}\n  <Select\n    bind:value={currentValue}\n    {readonly}\n    {required}\n    {invalid}\n    aria-labelledby=\"{fieldId}-label\"\n    aria-errormessage=\"{fieldId}-error\"\n  >\n    {#each allOptions as { label, value, searchValue }, index (`${index}-${value}`)}\n      <Option\n        {label}\n        {value}\n        valueType={getOptionValueType(value)}\n        {searchValue}\n        selected={value === currentValue}\n        wrap\n      />\n    {/each}\n  </Select>\n{:else}\n  <RadioGroup\n    {readonly}\n    {required}\n    {invalid}\n    aria-labelledby=\"{fieldId}-label\"\n    aria-errormessage=\"{fieldId}-error\"\n    onChange={({ detail: { value } }) => {\n      currentValue = value;\n    }}\n  >\n    {#each allOptions as { label, value }, index (`${index}-${value}`)}\n      <Radio\n        {label}\n        {value}\n        valueType={getOptionValueType(value)}\n        checked={value === currentValue}\n      />\n    {/each}\n  </RadioGroup>\n{/if}\n","<!--\n  @component\n  Implement the editor for a Select field.\n  @see https://decapcms.org/docs/widgets/#Select\n  @see https://sveltiacms.app/en/docs/fields/select\n-->\n<script>\n  import { isObject } from '@sveltia/utils/object';\n\n  import SelectMultiple from '$lib/components/contents/details/fields/select/select-multiple.svelte';\n  import SelectSingle from '$lib/components/contents/details/fields/select/select-single.svelte';\n  import { createStableDerivedState } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorProps, SelectFieldSelectorOption } from '$lib/types/private';\n   * @import { SelectField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {SelectField} fieldConfig Field configuration.\n   * @property {any} currentValue Field value.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  const {\n    // Field type-specific options\n    options: fieldOptions,\n    multiple,\n  } = $derived(fieldConfig);\n  const Select = $derived(multiple ? SelectMultiple : SelectSingle);\n  /**\n   * Selector options. A Relation field hands over a new list whenever anything in the entry\n   * changes, so the list is kept as long as it holds the same options, and a different list means\n   * they have changed. The selector doesn’t follow a change to the options, so it’s rendered again\n   * then, which is cheaper to tell by the identity of the list than by serializing every option.\n   */\n  const options = createStableDerivedState(() =>\n    fieldOptions.map(\n      (option) =>\n        /** @type {SelectFieldSelectorOption} */ (\n          isObject(option) ? option : { label: option, value: option }\n        ),\n    ),\n  );\n</script>\n\n{#key options.current}\n  <Select\n    {locale}\n    {keyPath}\n    {fieldId}\n    {fieldConfig}\n    bind:currentValue\n    {readonly}\n    {required}\n    {invalid}\n    options={options.current}\n  />\n{/key}\n","import { getContext, setContext } from 'svelte';\n\n/**\n * @import { Entry, FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Entry of a bulk editor row, which the field controls in the row read in place of an entry draft\n * through `getEditorEntryValues()`, e.g. to resolve the `{{slug}}` and `{{fields.x}}` templates in\n * the filters of a Relation field.\n * @typedef {object} BulkEditRowContext\n * @property {FlattenedEntryContent} values Values of the entry in the default locale, with the\n * pending edits applied.\n * @property {string} slug Slug of the entry in the default locale.\n */\n\n/**\n * Key of the context a bulk editor cell provides to its field control.\n */\nconst CONTEXT_KEY = 'bulk-edit-row';\n\n/**\n * Get the context provided by a bulk editor cell.\n * @returns {BulkEditRowContext | undefined} Context, or `undefined` outside of the bulk editor.\n */\nexport const getBulkEditRowContext = () => getContext(CONTEXT_KEY);\n\n/**\n * Provide the context to the field control of a bulk editor cell.\n * @param {BulkEditRowContext} context Context. Use getters to keep the values reactive.\n */\nexport const setBulkEditRowContext = (context) => {\n  setContext(CONTEXT_KEY, context);\n};\n\n/**\n * Get the values of an entry as they are shown in a bulk editor row: the stored content in the\n * given locale with the pending edits of the entry applied. An edited list value replaces the\n * stored items, which are flattened into `name.0`, `name.1` and so on.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry.\n * @param {InternalLocaleCode} args.locale Locale, which is the collection’s default locale.\n * @param {Record<FieldKeyPath, any> | undefined} args.edits Pending edits of the entry, keyed by\n * field name.\n * @returns {FlattenedEntryContent} Values.\n */\nexport const getBulkEditRowValues = ({ entry, locale, edits }) => {\n  /** @type {FlattenedEntryContent} */\n  const values = { ...entry.locales[locale]?.content };\n\n  Object.entries(edits ?? {}).forEach(([keyPath, value]) => {\n    Object.keys(values).forEach((key) => {\n      if (key.startsWith(`${keyPath}.`)) {\n        delete values[key];\n      }\n    });\n\n    values[keyPath] = value;\n  });\n\n  return values;\n};\n\n/**\n * Get the slug of an entry in a locale, falling back to its canonical slug.\n * @param {Entry} entry Entry.\n * @param {InternalLocaleCode} locale Locale.\n * @returns {string} Slug.\n */\nexport const getBulkEditRowSlug = (entry, locale) => entry.locales[locale]?.slug ?? entry.slug;\n","import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\nimport { getBulkEditRowContext } from '$lib/services/contents/editor/bulk-edit-row';\nimport { getFieldEditorContext } from '$lib/services/contents/editor/field-context';\nimport { getDraftSharedValues } from '$lib/services/contents/i18n/shared-values';\n\n/**\n * @import { FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n * @import { SharedValues } from '$lib/services/contents/i18n/shared-values';\n */\n\n/**\n * Accessor to the entry a field editor belongs to. Each getter is reactive when called in a\n * reaction, e.g. a `$derived()`.\n * @typedef {object} EditorEntryValues\n * @property {(locale: InternalLocaleCode) => FlattenedEntryContent | undefined} getValues Get the\n * values of the entry in the given locale: those of the draft, or of the rich text editor component\n * being edited, in the entry editor, or those of the row with its pending edits applied in the bulk\n * editor.\n * @property {(locale: InternalLocaleCode) => SharedValues | undefined} getSharedValues Get the\n * values of the fields that aren’t localized, for reading them while another locale than the\n * default is edited. `undefined` in the bulk editor, which only edits the default locale, and in a\n * rich text editor component, whose values are localized along with the document.\n * @property {(locale: InternalLocaleCode) => string | undefined} getSlug Get the slug of the entry\n * in the given locale.\n */\n\n/**\n * Get an accessor to the entry a field editor belongs to: the entry draft in the entry editor, or\n * the entry of the row in the bulk editor, which has no draft. A field editor reads the entry\n * through this, e.g. to resolve the `{{slug}}` and `{{fields.x}}` templates in the filters of a\n * Relation field, so it needs no special case for the bulk editor. The draft itself is not given to\n * the bulk editor, as it would turn on draft-only features there, like creating an entry with the\n * Relation field’s quick-add dialog. Call this while a component is being initialized, as it reads\n * the component contexts.\n * @returns {EditorEntryValues} Accessor.\n */\nexport const getEditorEntryValues = () => {\n  const entryDraft = getEntryDraftContext();\n  const { valueStoreKey = 'currentValues' } = getFieldEditorContext();\n  const bulkEditRow = getBulkEditRowContext();\n\n  /**\n   * Get the values of the entry in a locale.\n   * @type {EditorEntryValues['getValues']}\n   */\n  const getValues = (locale) => {\n    const draft = entryDraft?.current;\n\n    return draft ? draft[valueStoreKey]?.[locale] : bulkEditRow?.values;\n  };\n\n  /**\n   * Get the values of the fields that aren’t localized.\n   * @type {EditorEntryValues['getSharedValues']}\n   */\n  const getSharedValues = (locale) =>\n    valueStoreKey === 'currentValues'\n      ? getDraftSharedValues(entryDraft?.current, locale)\n      : undefined;\n\n  /**\n   * Get the slug of the entry in a locale.\n   * @type {EditorEntryValues['getSlug']}\n   */\n  const getSlug = (locale) => {\n    const draft = entryDraft?.current;\n\n    return draft ? (draft.currentSlugs[locale] ?? draft.currentSlugs._) : bulkEditRow?.slug;\n  };\n\n  return { getValues, getSharedValues, getSlug };\n};\n","<!--\n  @component\n  Implement the editor for a Relation field.\n  @see https://decapcms.org/docs/widgets/#Relation\n  @see https://sveltiacms.app/en/docs/fields/relation\n-->\n<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Button, Icon, Menu, MenuButton, MenuItem } from '@sveltia/ui';\n\n  import QuickAddDialog from '$lib/components/contents/details/fields/relation/quick-add-dialog.svelte';\n  import SelectEditor from '$lib/components/contents/details/fields/select/select-editor.svelte';\n  import { getCollection, getCollectionLabel } from '$lib/services/contents/collection';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getEditorEntryValues } from '$lib/services/contents/editor/entry-values';\n  import { getFieldEditorContext } from '$lib/services/contents/editor/field-context';\n  import { getOptions } from '$lib/services/contents/fields/relation/helpers';\n  import {\n    getCreatableCollection,\n    getEditableEntries,\n    getRefEntriesWithPending,\n    getUnlistedEntries,\n    hasCreationRoom,\n    replaceEntryValues,\n    selectPendingEntry,\n  } from '$lib/services/contents/fields/relation/quick-add';\n\n  /**\n   * @import { Entry, FieldEditorProps, InternalEntryCollection } from '$lib/types/private';\n   * @import { RelationField, SelectField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {RelationField} fieldConfig Field configuration.\n   * @property {string | string[] | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const { valueStoreKey = 'currentValues' } = getFieldEditorContext();\n  // The entry the field belongs to: the draft, or the row in the bulk editor, which has no draft\n  const editorEntry = getEditorEntryValues();\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldId,\n    fieldLabel,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  let showQuickAddDialog = $state(false);\n  /**\n   * Entry to edit with the dialog, or `undefined` to create a new one.\n   * @type {Entry | undefined}\n   */\n  let editingEntry = $state.raw();\n  /**\n   * Whether the dialog has been opened, which keeps it mounted while it closes, even if the field\n   * no longer offers to create or edit an entry by then.\n   */\n  let dialogOpened = $state(false);\n\n  // The entries created from this field, or another one referring to the same collection, are\n  // offered along with the saved ones until they’re saved too\n  const refEntries = $derived(getRefEntriesWithPending({ draft: entryDraft.current, fieldConfig }));\n  /** @type {SelectField} */\n  const selectFieldConfig = $derived({\n    ...fieldConfig,\n    widget: 'select',\n    options: getOptions({\n      locale,\n      fieldConfig,\n      refEntries,\n      currentLocaleValues: editorEntry.getValues(locale),\n      currentSlug: editorEntry.getSlug(locale),\n      // A filter can refer to a field that isn’t localized, which only has a value in the default\n      // locale\n      sharedValues: editorEntry.getSharedValues(locale),\n      // A label can refer to another pending entry through a Relation field of the entry\n      pendingEntries: getUnlistedEntries(entryDraft.current),\n    }),\n  });\n  const creatableCollection = $derived(\n    readonly || !entryDraft.current\n      ? undefined\n      : getCreatableCollection({ fieldConfig, draft: entryDraft.current }),\n  );\n  const canCreate = $derived(\n    !!creatableCollection &&\n      !!entryDraft.current &&\n      hasCreationRoom({ collection: creatableCollection, draft: entryDraft.current }),\n  );\n  // The selected entries that can be edited with the dialog\n  const editableEntries = $derived(\n    readonly || !entryDraft.current\n      ? []\n      : getEditableEntries({\n          draft: entryDraft.current,\n          locale,\n          fieldConfig,\n          refEntries,\n          currentValue,\n        }),\n  );\n  // The collection the dialog creates or edits an entry in. An entry can only be edited in an\n  // entry collection, see `canEditEntry()`\n  const refCollection = $derived(\n    /** @type {InternalEntryCollection} */ (getCollection(fieldConfig.collection)),\n  );\n  // Whether an entry can be created or edited with the dialog. The collection that can have an\n  // entry created in is the referenced one, see `getCreatableCollection()`\n  const hasDialogActions = $derived(!!creatableCollection || !!editableEntries.length);\n  /* v8 ignore start -- the app locale is always set once the UI strings are loaded */\n  // `appLocale.current` is a key, because `getCollectionLabel` can return a localized label. Only\n  // read while a button is rendered, which needs the collection\n  const collectionName = $derived(\n    appLocale.current ? getCollectionLabel(refCollection, { useSingular: true }) : '',\n  );\n  /* v8 ignore stop */\n\n  /**\n   * Open the dialog to create a new entry, or edit the given one.\n   * @param {Entry} [entry] Entry to edit.\n   */\n  const openDialog = (entry) => {\n    dialogOpened = true;\n    editingEntry = entry;\n    showQuickAddDialog = true;\n  };\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <SelectEditor\n    {locale}\n    {keyPath}\n    {typedKeyPath}\n    {fieldId}\n    {fieldLabel}\n    fieldConfig={selectFieldConfig}\n    bind:currentValue\n    {readonly}\n    {required}\n    {invalid}\n  />\n  {#if hasDialogActions}\n    <div role=\"none\" class=\"actions\">\n      {#if creatableCollection}\n        <Button\n          variant=\"tertiary\"\n          size=\"small\"\n          label={_('add_x', { values: { name: collectionName } })}\n          disabled={!canCreate}\n          aria-haspopup=\"dialog\"\n          onclick={() => {\n            openDialog();\n          }}\n        >\n          {#snippet startIcon()}\n            <Icon name=\"add\" />\n          {/snippet}\n        </Button>\n      {/if}\n      {#if fieldConfig.multiple && editableEntries.length}\n        <MenuButton\n          variant=\"tertiary\"\n          size=\"small\"\n          label={_('edit_x', { values: { name: collectionName } })}\n        >\n          {#snippet startIcon()}\n            <Icon name=\"edit\" />\n          {/snippet}\n          {#snippet endIcon()}{/snippet}\n          {#snippet popup()}\n            <Menu ariaLabel={_('relation_field.select_entry_to_edit')}>\n              {#each editableEntries as { label, entry } (entry.id)}\n                <MenuItem\n                  {label}\n                  aria-haspopup=\"dialog\"\n                  onclick={() => {\n                    openDialog(entry);\n                  }}\n                />\n              {/each}\n            </Menu>\n          {/snippet}\n        </MenuButton>\n      {:else if editableEntries.length}\n        {@const [{ label, entry }] = editableEntries}\n        <Button\n          variant=\"tertiary\"\n          size=\"small\"\n          label={_('edit_x', { values: { name: label } })}\n          aria-haspopup=\"dialog\"\n          onclick={() => {\n            openDialog(entry);\n          }}\n        >\n          {#snippet startIcon()}\n            <Icon name=\"edit\" />\n          {/snippet}\n        </Button>\n      {/if}\n    </div>\n  {/if}\n  {#if hasDialogActions || dialogOpened}\n    <QuickAddDialog\n      bind:open={showQuickAddDialog}\n      collection={refCollection}\n      {fieldConfig}\n      entry={editingEntry}\n      onAdd={(pendingEntry, previousEntry) => {\n        /* v8 ignore next -- the entry is only added while the draft is being edited */\n        if (!entryDraft.current) {\n          return;\n        }\n\n        const args = { draft: entryDraft.current, keyPath, valueStoreKey, fieldConfig };\n\n        if (previousEntry) {\n          replaceEntryValues({ ...args, previousEntry, entry: pendingEntry.entry });\n        } else {\n          selectPendingEntry({ ...args, locale, pendingEntry });\n        }\n      }}\n    />\n  {/if}\n</div>\n\n<style>\n  .wrapper {\n    display: flex;\n    flex-direction: column;\n    gap: 8px;\n  }\n\n  .actions {\n    display: flex;\n  }\n</style>\n","/**\n * @import { RelationOption } from '$lib/types/private';\n * @import { RelationField } from '$lib/types/public';\n */\n\n/**\n * Value field templates that resolve to the referenced entry’s slug. A slug is not shown next to\n * the label, because the label is enough to identify the entry.\n */\nconst SLUG_VALUE_FIELDS = ['slug', '{{slug}}', '{{fields.slug}}'];\n\n/**\n * Get the labels to be shown in the preview of a Relation field. A stored value that is found in\n * the options is shown by its label, followed by the value itself in parentheses unless the value\n * is the referenced entry’s slug; a value that is not found, e.g. a reference to a deleted entry,\n * is shown as is.\n * @param {object} args Arguments.\n * @param {RelationField} args.fieldConfig Field configuration.\n * @param {string | string[] | undefined} args.currentValue Stored value(s).\n * @param {RelationOption[]} args.options Field options.\n * @returns {string[]} Labels, in the stored order. Empty if there is no value.\n */\nexport const getPreviewLabels = ({ fieldConfig, currentValue, options }) => {\n  const { multiple = false, value_field: valueField = '{{slug}}' } = fieldConfig;\n  const values = multiple ? (currentValue ?? []) : [currentValue];\n\n  // A value read from a file may be a number or `null`, while the option values are always strings\n  return /** @type {any[]} */ (values)\n    .filter((value) => value !== undefined && value !== null && value !== '')\n    .map((value) => String(value))\n    .map((value) => {\n      const label = options.find((option) => option.value === value)?.label;\n\n      if (!label || label === value) {\n        return value;\n      }\n\n      return SLUG_VALUE_FIELDS.includes(valueField) ? label : `${label} (${value})`;\n    });\n};\n","<!--\n  @component\n  Implement the preview for a Relation field.\n  @see https://decapcms.org/docs/widgets/#Relation\n  @see https://sveltiacms.app/en/docs/fields/relation\n-->\n<script>\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getOptions } from '$lib/services/contents/fields/relation/helpers';\n  import { getPreviewLabels } from '$lib/services/contents/fields/relation/helpers/preview';\n  import {\n    getRefEntriesWithPending,\n    getUnlistedEntries,\n  } from '$lib/services/contents/fields/relation/quick-add';\n  import { getCanonicalLocale, getDirection, getListFormatter } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { RelationField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {RelationField} fieldConfig Field configuration.\n   * @property {string | string[] | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, fieldConfig, currentValue } = $props();\n\n  const listFormatter = $derived(getListFormatter(locale));\n  // The entries created from the editor are shown by their labels, like the saved ones\n  const refEntries = $derived(getRefEntriesWithPending({ draft: entryDraft.current, fieldConfig }));\n  const options = $derived(\n    getOptions({\n      locale,\n      fieldConfig,\n      refEntries,\n      pendingEntries: getUnlistedEntries(entryDraft.current),\n    }),\n  );\n  const refValues = $derived(getPreviewLabels({ fieldConfig, currentValue, options }));\n</script>\n\n{#if refValues.length}\n  <p lang={getCanonicalLocale(locale)} dir={getDirection(locale)}>\n    {listFormatter.format(refValues)}\n  </p>\n{/if}\n","import { _, locale as appLocale } from '@sveltia/i18n';\n\nimport { COMPATIBILITY_URL } from '$lib/services/api/compatibility';\nimport { DOCS_BASE_URL } from '$lib/services/app';\nimport { getListFormatter } from '$lib/services/contents/i18n';\nimport { getRegex } from '$lib/services/utils/regex';\nimport { makeLink } from '$lib/services/utils/string';\n\n/**\n * @import {\n * ConfigParserContext,\n * ConfigParserCollectors,\n * UnsupportedOption,\n * } from '$lib/types/private';\n */\n\n// eslint-disable-next-line @stylistic/max-len\nconst INVALID_FIELD_NAME_DOC_URL = `${DOCS_BASE_URL}/troubleshooting#using-proper-naming-conventions`;\n\n/**\n * Add an error or warning message to the error collector with context information.\n * @param {object} args Arguments.\n * @param {'error' | 'warning'} [args.type] The type of the message.\n * @param {string} args.strKey The i18n string key for the message.\n * @param {Record<string, string | undefined>} [args.values] Values for the i18n string.\n * @param {string} [args.extraStrKey] An extra i18n string key to append to the message.\n * @param {ConfigParserContext} [args.context] The field parser context.\n * @param {ConfigParserCollectors} args.collectors The collectors.\n */\nexport const addMessage = ({\n  type = 'error',\n  strKey,\n  values = {},\n  extraStrKey,\n  context = {},\n  collectors,\n}) => {\n  const { collection, collectionFile, componentName, typedKeyPath } = context;\n  const { errors, warnings } = collectors;\n  const locators = [];\n\n  if (collection) {\n    locators.push(\n      _('config.error_locator.collection', {\n        // An empty label is as good as none, so fall back the same way the UI does\n        values: { collection: collection.label_singular || collection.label || collection.name },\n      }),\n    );\n  }\n\n  if (collectionFile) {\n    locators.push(\n      _('config.error_locator.file', {\n        values: { file: collectionFile.label || collectionFile.name },\n      }),\n    );\n  }\n\n  if (componentName) {\n    locators.push(\n      _('config.error_locator.component', {\n        values: { component: componentName },\n      }),\n    );\n  }\n\n  if (typedKeyPath) {\n    locators.push(\n      _('config.error_locator.field', {\n        values: { field: typedKeyPath },\n      }),\n    );\n  }\n\n  const collector = type === 'error' ? errors : warnings;\n  const locale = appLocale.current;\n  const locatorStr = locators.length ? `${getListFormatter(locale).format(locators)}: ` : '';\n  let message = _(`config.${type}.${strKey}`, { values });\n\n  if (strKey === 'invalid_field_name') {\n    message = makeLink(message, INVALID_FIELD_NAME_DOC_URL);\n  }\n\n  const extraMessage = extraStrKey\n    ? _(`config.${extraStrKey}`, {\n        values: { link: extraStrKey === 'compatibility_link' ? COMPATIBILITY_URL : undefined },\n      })\n    : '';\n\n  collector.add(`${locatorStr}${message}${extraMessage ? ` ${extraMessage}` : ''}`);\n};\n\n/**\n * Check for unsupported deprecated options in a configuration and add messages if found.\n * @param {object} args Arguments.\n * @param {UnsupportedOption[]} args.UNSUPPORTED_OPTIONS Array of unsupported option mappings.\n * @param {Record<string, any>} args.config Configuration to check. Usually a field config.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkUnsupportedOptions = ({ UNSUPPORTED_OPTIONS, config, context, collectors }) => {\n  UNSUPPORTED_OPTIONS.forEach(\n    ({ type = 'error', prop, newProp, value, strKey = 'unsupported_deprecated_option' }) => {\n      if (prop in config && (value === undefined || config[prop] === value)) {\n        addMessage({\n          type,\n          strKey,\n          values: { prop, newProp },\n          extraStrKey: 'compatibility_link',\n          context,\n          collectors,\n        });\n      }\n    },\n  );\n};\n\n/**\n * Regular expression to validate names. A valid name is a non-empty string that does not contain\n * spaces, dots, asterisks, colons or angle brackets. Dots are used as separators in key paths,\n * asterisks are used for wildcard matching for relation fields, colons are used for editor\n * component identification, and angle brackets are used for variable type placeholders.\n */\nconst VALID_NAME_REGEX = /^[^\\s.*:<>]+$/;\n\n/**\n * Checks if the given name is valid. `__proto__` is also invalid: a value can’t be stored under\n * that key in a plain object, which is how entry content and many lookups keyed by name are held,\n * so a field with the name would silently lose its value.\n * @param {string} name Name to check.\n * @returns {boolean} `true` if the name is valid, `false` otherwise.\n */\nexport const isValidName = (name) => VALID_NAME_REGEX.test(name) && name !== '__proto__';\n\n/**\n * Check if the given collection name, collection file name, field name or variable type name is\n * valid and not duplicated. Adds messages to the collectors if invalid or duplicated.\n * @param {object} args Arguments.\n * @param {any} args.name Name to check.\n * @param {number} args.index Index of the item in the array, used for error messages.\n * @param {Record<string, number>} args.nameCounts Record of name counts. The keys are the names and\n * the values are the counts.\n * @param {string} args.strKeyBase I18n string key for the name message, excluding \"missing_\" or\n * \"invalid_\".\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n * @param {boolean} [args.required] Whether a missing name must be reported even when the JSON\n * schema has been applied. The schema requires a `name` almost everywhere, so this is only needed\n * where it can’t, such as a view group or filter in the object format.\n * @returns {boolean} `true` if the name is valid, `false` otherwise.\n */\nexport const checkName = ({\n  name,\n  index,\n  nameCounts,\n  strKeyBase,\n  context,\n  collectors,\n  required = false,\n}) => {\n  // A name that is absent or of the wrong type is reported against the JSON schema, so repeating it\n  // here would show two messages for one mistake. An empty string satisfies the schema but is just\n  // as unusable, and a name the schema can’t require has to be reported here or nowhere.\n  if (typeof name !== 'string' || !name) {\n    if (name === '' || (required && name === undefined)) {\n      // Use count (1-based index) for user-facing messages\n      const count = String(index + 1);\n\n      addMessage({ strKey: `missing_${strKeyBase}`, context, values: { count }, collectors });\n    }\n\n    return false;\n  }\n\n  if (!isValidName(name)) {\n    addMessage({ strKey: `invalid_${strKeyBase}`, context, values: { name }, collectors });\n\n    return false;\n  }\n\n  // Check for duplicates, the second occurrence will be caught here. A name like `constructor`\n  // mustn’t pick up the `Object.prototype` member of the same name\n  const count = Object.hasOwn(nameCounts, name) ? nameCounts[name] : 0;\n\n  if (count === 1) {\n    addMessage({ strKey: `duplicate_${strKeyBase}`, context, values: { name }, collectors });\n\n    return false;\n  }\n\n  nameCounts[name] = count + 1;\n\n  return true;\n};\n\n/**\n * Check that a pattern option holds a regular expression that can be compiled. The runtime uses\n * `getRegex()`, which returns `undefined` for a pattern it can’t compile, so a mistyped expression\n * doesn’t fail loudly: a validation `pattern` stops validating, and a collection `filter` stops\n * matching. A `RegExp` object, which the JS API accepts, is valid by construction, and a value of\n * another type is reported against the JSON schema.\n * @param {object} args Arguments.\n * @param {string} args.option Name of the option holding the pattern, for the message.\n * @param {any} args.pattern Pattern to check.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkRegex = ({ option, pattern, context, collectors }) => {\n  if (typeof pattern === 'string' && getRegex(pattern) === undefined) {\n    addMessage({ strKey: 'invalid_regex', values: { option, pattern }, context, collectors });\n  }\n};\n","import { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { isInlinePatternComponent } from '$lib/services/contents/fields/rich-text/components/inline-pattern';\nimport { isMultiLinePattern } from '$lib/services/contents/fields/rich-text/components/utils';\n\n/**\n * @import { ConfigParserCollectors } from '$lib/types/private';\n * @import { CmsConfig, CustomEditorComponentDefinition, Field } from '$lib/types/public';\n */\n\n/**\n * Field types a component in the `inline` mode can have. They all hold a single simple value\n * edited with a compact control, which fits in a line of text.\n */\nexport const INLINE_COMPONENT_FIELD_TYPES = [\n  'boolean',\n  'color',\n  'datetime',\n  'number',\n  'relation',\n  'select',\n  'string',\n];\n\n/**\n * Check if the given fields can be edited in a component in the `inline` mode: a single field of\n * one of the {@link INLINE_COMPONENT_FIELD_TYPES}, holding one value rather than several.\n * @param {Field[]} fields Fields of the component.\n * @returns {boolean} Result.\n */\nexport const isInlineComponentFieldList = (fields) => {\n  if (fields.length !== 1) {\n    return false;\n  }\n\n  const [field] = fields;\n  const fieldType = field.widget ?? 'string';\n\n  return (\n    INLINE_COMPONENT_FIELD_TYPES.includes(fieldType) &&\n    !(/** @type {{ multiple?: boolean }} */ (field).multiple)\n  );\n};\n\n/**\n * Parse and validate the definition of a custom editor component registered with the\n * `CMS.registerEditorComponent()` API, apart from its fields, which are parsed like any other. A\n * pattern-based inline component has no fields, but its pattern has to match within a paragraph:\n * one with the `m` or `s` flag, or `[\\s\\S]`, is meant to span lines, which it can’t.\n * @param {object} args Arguments.\n * @param {CustomEditorComponentDefinition} args.definition Component definition.\n * @param {string} args.componentName Name the component is registered with.\n * @param {CmsConfig} args.cmsConfig CMS configuration.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const parseEditorComponent = ({ definition, componentName, cmsConfig, collectors }) => {\n  const context = { cmsConfig, componentName };\n\n  if (isInlinePatternComponent(definition)) {\n    if (isMultiLinePattern(definition.pattern)) {\n      addMessage({\n        type: 'warning',\n        strKey: 'inline_component_multiline_pattern',\n        context,\n        collectors,\n      });\n    }\n\n    return;\n  }\n\n  const { mode, fields } = definition;\n\n  if (mode === 'inline' && !isInlineComponentFieldList(fields)) {\n    addMessage({ strKey: 'invalid_inline_component_fields', context, collectors });\n  }\n};\n","import { processNestedTemplates } from '$lib/services/common/template/nested';\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { applyTransformations, parseTransformations } from '$lib/services/common/transformations';\nimport { flattenKeys } from '$lib/services/utils/object';\n\n/**\n * @import { Field, RawEntryContent } from '$lib/types/public';\n */\n\n/**\n * Format the summary template of a rich text editor component, replacing `{{fieldName}}`\n * placeholders with the component’s values. Nested properties and transformations are supported\n * like the summary of an Object field, but the values are looked up in the component’s own values\n * rather than in the entry draft, so there is no key path to resolve.\n * @param {object} args Arguments.\n * @param {string} [args.template] Summary template, e.g. `{{title}} - {{linkType.url | upper}}`.\n * @param {RawEntryContent} [args.values] Current values (unflattened).\n * @param {Field[]} args.fields Field definitions of the component.\n * @param {string} [args.locale] Locale code passed to the transformations.\n * @returns {string | null} Formatted summary, or `null` if the template is blank or every\n * placeholder resolved to an empty value. A template without placeholders is returned as is.\n */\nexport const formatComponentSummary = ({ template, values, fields, locale }) => {\n  if (!template) {\n    return null;\n  }\n\n  const strippedTemplate = replaceTemplateTags(template, () => '');\n\n  // A template without placeholders is plain text, shown as is unless it’s blank\n  if (strippedTemplate === template) {\n    return template.trim() || null;\n  }\n\n  if (!values) {\n    return null;\n  }\n\n  /** @type {Record<string, any>} */\n  const flatValues = flattenKeys(values);\n\n  /**\n   * Resolve a template tag of the summary template.\n   * @param {string} placeholder Tag content, e.g. `title | upper`.\n   * @returns {string} Resolved value.\n   */\n  const resolvePlaceholder = (placeholder) => {\n    const { value: tag, transformations: parsedTransformations } =\n      parseTransformations(placeholder);\n\n    const fieldName = stripFieldTagPrefix(tag);\n    let value = flatValues[fieldName];\n\n    if (value === undefined || value === null) {\n      return '';\n    }\n\n    // Resolve the tags in the transformation arguments, e.g. `ternary('{{url}}', '{{title}}')`\n    const transformations = processNestedTemplates(parsedTransformations, resolvePlaceholder);\n\n    if (transformations.length) {\n      value = applyTransformations({\n        fieldConfig: fields.find((f) => f.name === fieldName),\n        value,\n        transformations,\n        locale,\n      });\n    }\n\n    return String(value);\n  };\n\n  const result = replaceTemplateTags(template, (__, placeholder) =>\n    resolvePlaceholder(placeholder),\n  );\n\n  // Return `null` if the result (after stripping all placeholder-based content) is empty. This\n  // handles the case where all field values are empty but literal text (e.g. ' — ') remains.\n  if (result !== strippedTemplate && result.trim()) {\n    return result.trim();\n  }\n\n  return null;\n};\n\n/**\n * Get the values to display in the placeholder of a rich text editor component in `dialog` mode:\n * the values stored in the entry draft, or the values parsed from the document while the draft has\n * no field values yet, e.g. on the initial render.\n * @param {object} args Arguments.\n * @param {RawEntryContent} [args.currentValues] Values stored in the entry draft.\n * @param {RawEntryContent} [args.values] Values parsed from the document.\n * @param {Field[]} args.fields Field definitions of the component.\n * @returns {RawEntryContent | undefined} Values.\n */\nexport const getComponentDisplayValues = ({ currentValues, values, fields }) =>\n  fields.some((f) => currentValues?.[f.name] !== undefined) ? currentValues : values;\n\n/**\n * Get the text shown in the placeholder of a rich text editor component in `dialog` mode: the\n * formatted summary template if it produces anything, the value of the first string or text field\n * otherwise, or the component label as a last resort. The label is omitted if a thumbnail is shown\n * instead, as the image identifies the component well enough.\n * @param {object} args Arguments.\n * @param {string} [args.template] Summary template, e.g. `{{title}}`.\n * @param {RawEntryContent} [args.currentValues] Values stored in the entry draft.\n * @param {RawEntryContent} [args.values] Values parsed from the document, used while the entry\n * draft has no field values yet, e.g. on the initial render.\n * @param {Field[]} args.fields Field definitions of the component.\n * @param {string} [args.locale] Locale code passed to the transformations.\n * @param {string} args.label Component label.\n * @param {boolean} [args.hasThumbnail] Whether the placeholder shows a thumbnail.\n * @returns {string} Text, which can be empty if {@link args.hasThumbnail} is `true`.\n */\nexport const getComponentDisplayText = ({\n  template,\n  currentValues,\n  values,\n  fields,\n  locale,\n  label,\n  hasThumbnail = false,\n}) => {\n  const _values = getComponentDisplayValues({ currentValues, values, fields });\n  const formatted = formatComponentSummary({ template, values: _values, fields, locale });\n\n  if (formatted) {\n    return formatted;\n  }\n\n  const displayField = fields.find(\n    (f) => f.widget === 'string' || f.widget === 'text' || !f.widget,\n  );\n\n  if (displayField && _values) {\n    const value = _values[displayField.name];\n\n    if (typeof value === 'string' && value.trim()) {\n      return value.trim();\n    }\n  }\n\n  return hasThumbnail ? '' : label;\n};\n","import { getObjectThumbnail } from '$lib/services/contents/fields/object/thumbnail';\nimport { flattenKeys } from '$lib/services/utils/object';\n\n/**\n * @import { Entry, EntryFileMap, InternalLocaleCode, MediaFieldSource } from '$lib/types/private';\n * @import { RawEntryContent } from '$lib/types/public';\n */\n\n/**\n * Get the thumbnail shown in the placeholder of a rich text editor component in `dialog` mode,\n * which is the image held by the field named with the component’s `thumbnail` option.\n * @param {object} args Arguments.\n * @param {string} [args.thumbnailFieldName] The `thumbnail` option: the name of a field, or the key\n * path of a nested one like `mobile.src`, optionally prefixed with `fields.`.\n * @param {RawEntryContent} [args.values] Component values (unflattened).\n * @param {string} args.componentName Component name, e.g. `x-icon`.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {boolean} [args.isIndexFile] Whether the corresponding entry is the collection’s special\n * index file used specifically in Hugo.\n * @param {Entry} [args.entry] Entry being edited, used to locate an asset from a relative path.\n * @param {EntryFileMap} [args.files] Files uploaded in the draft but not saved yet, keyed by the\n * blob URL the field holds meanwhile.\n * @param {InternalLocaleCode} [args.locale] Locale being edited, which an entry-relative path is\n * relative to.\n * @returns {MediaFieldSource | undefined} The image to preview, or `undefined` if the option is not\n * set, the field is not an Image/File field, it’s empty, or the file is not an image.\n */\nexport const getComponentThumbnail = ({ thumbnailFieldName, values, ...args }) => {\n  if (!thumbnailFieldName || !values) {\n    return undefined;\n  }\n\n  // The component values are at the top level, so there is no key path to prefix\n  return getObjectThumbnail({\n    ...args,\n    thumbnailFieldName,\n    keyPath: '',\n    typedKeyPath: '',\n    valueMap: flattenKeys(values),\n  });\n};\n","import { validateFields } from '$lib/services/contents/draft/validate/fields';\n\n/**\n * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * Validate the values of the rich text editor components in the given entry draft, which are\n * stored in its `extraValues`, and merge the results into the draft so the field editors show the\n * messages. Used when the dialog of a component in `dialog` mode is confirmed.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {InternalLocaleCode} args.locale Locale the component is edited in.\n * @param {string} args.keyPathPrefix Key path prefix of the component, e.g. `body:c12:`.\n * @returns {boolean} Whether the values of the given component are valid.\n */\nexport const validateComponentValues = ({ draft, locale, keyPathPrefix }) => {\n  const { validities, validationMessages } = validateFields('extraValues', { draft });\n\n  Object.keys(draft.validities).forEach((loc) => {\n    Object.assign(draft.validities[loc], validities[loc]);\n    // The field editors show the messages, not the validity flags\n    Object.assign(draft.validationMessages[loc], validationMessages[loc]);\n  });\n\n  return !Object.entries(validities[locale] ?? {}).some(\n    ([key, validity]) => key.startsWith(keyPathPrefix) && !validity.valid,\n  );\n};\n","import equal from 'fast-deep-equal';\n\nimport { normalizeContent } from '$lib/services/contents/draft/create/normalize';\nimport { getDefaultValues } from '$lib/services/contents/draft/defaults';\nimport { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\nimport { flattenKeys, unflattenKeys, unflattenMap } from '$lib/services/utils/object';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { Field, RawEntryContent } from '$lib/types/public';\n */\n\n/**\n * Remove the values of a rich text editor component from the given flattened value map, e.g. the\n * `extraValues` or the validities of a locale in an entry draft. The map is modified in place.\n * @param {Record<string, any> | undefined} valueMap Flattened value map.\n * @param {string} keyPathPrefix Key path prefix of the component, e.g. `body:c12:`.\n */\nexport const deleteKeysByPrefix = (valueMap, keyPathPrefix) => {\n  Object.keys(valueMap ?? {}).forEach((key) => {\n    if (key.startsWith(keyPathPrefix)) {\n      delete (/** @type {Record<string, any>} */ (valueMap)[key]);\n    }\n  });\n};\n\n/**\n * Remove the values of a rich text editor component’s own fields from the given flattened value\n * map, leaving those of the components nested in its rich text fields, whose keys carry a prefix\n * of their own, e.g. `body:c12:text:c34:alt` within `body:c12:`. The map is modified in place.\n * @param {Record<string, any>} valueMap Flattened value map.\n * @param {string} keyPathPrefix Key path prefix of the component, e.g. `body:c12:`.\n */\nexport const deleteOwnKeysByPrefix = (valueMap, keyPathPrefix) => {\n  Object.keys(valueMap).forEach((key) => {\n    if (key.startsWith(keyPathPrefix) && !key.slice(keyPathPrefix.length).includes(':')) {\n      delete valueMap[key];\n    }\n  });\n};\n\n/**\n * Flatten the values of a rich text editor component, and prefix the keys with the component’s key\n * path prefix, so they can be stored in the `extraValues` of an entry draft.\n * @param {Record<string, any>} values Component values.\n * @param {string} keyPathPrefix Key path prefix of the component, e.g. `body:c12:`.\n * @returns {Record<string, any>} Flattened value map.\n */\nexport const flattenWithPrefix = (values, keyPathPrefix) =>\n  Object.fromEntries(\n    Object.entries(flattenKeys(values)).map(([key, value]) => [`${keyPathPrefix}${key}`, value]),\n  );\n\n/**\n * Get the values of a rich text editor component from the given flattened value map, e.g. the\n * `extraValues` of a locale in an entry draft, without the component’s key path prefix.\n * @param {Record<string, any>} valueMap Flattened value map.\n * @param {string} keyPathPrefix Key path prefix of the component, e.g. `body:c12:`.\n * @returns {RawEntryContent} Component values (unflattened).\n */\nexport const getValuesByPrefix = (valueMap, keyPathPrefix) =>\n  unflattenMap(\n    Object.fromEntries(\n      getKeysByPrefix(valueMap, keyPathPrefix).map((key) => [\n        key.slice(keyPathPrefix.length),\n        valueMap[key],\n      ]),\n    ),\n  );\n\n/**\n * Reconcile the values of a rich text editor component, as parsed from the document, with the\n * component’s field definitions, which may have changed since the document was written. A freshly\n * inserted component without values gets the default values. Unlike an entry draft, missing values\n * are not filled in, because these values live in the document text and doing so would rewrite it\n * just by opening the entry.\n * @param {object} args Arguments.\n * @param {Record<string, any> | undefined} args.values Component values. The component name is\n * added to them in place.\n * @param {Field[]} args.fields Field definitions of the component.\n * @param {string} args.componentName Component name.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {InternalLocaleCode} args.defaultLocale Default locale code.\n * @returns {Record<string, any>} Reconciled values: the given values themselves if nothing has\n * changed, or a new object otherwise, so a caller can tell whether to reassign them.\n */\nexport const reconcileComponentValues = ({\n  values,\n  fields,\n  componentName,\n  locale,\n  defaultLocale,\n}) => {\n  const _values = /** @type {Record<string, any>} */ (\n    values ??\n      // The component values live in the document of the locale they’re inserted in, so they have\n      // no i18n options of their own: give them the defaults in every locale, rather than only in\n      // the default locale as with an entry field without the `i18n` option\n      unflattenKeys(getDefaultValues({ fields, locale, defaultLocale: locale }))\n  );\n\n  _values.__sc_component_name = componentName;\n\n  /** @type {Record<string, any>} */\n  const normalizedValues = unflattenKeys(\n    normalizeContent({\n      fields,\n      content: flattenKeys(_values),\n      locale,\n      defaultLocale,\n      fillDefaults: false,\n    }),\n  );\n\n  // `normalizeContent()` is idempotent, but a fresh object every time would make a caller that\n  // reassigns the values react to them forever\n  return equal(normalizedValues, _values) ? _values : normalizedValues;\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Dialog, Spacer, VisibilityObserver } from '@sveltia/ui';\n  import equal from 'fast-deep-equal';\n  import { onMount } from 'svelte';\n  import { on } from 'svelte/events';\n\n  import Image from '$lib/components/assets/shared/image.svelte';\n  import RemoveButton from '$lib/components/common/remove-button.svelte';\n  import FieldEditor from '$lib/components/contents/details/editor/field-editor.svelte';\n  import ObjectHeader from '$lib/components/contents/details/fields/object/object-header.svelte';\n  import { isInlineComponentFieldList } from '$lib/services/config/parser/editor-components';\n  import {\n    getEntryDraftByElement,\n    setEntryDraftContext,\n    setEntryDraftRoot,\n  } from '$lib/services/contents/draft/state.svelte';\n  import { deferDraftWrite } from '$lib/services/contents/draft/update/deferred';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { setFieldEditorContext } from '$lib/services/contents/editor/field-context';\n  import { awaitPendingFieldUpdates } from '$lib/services/contents/editor/pending';\n  import {\n    getComponentDisplayText,\n    getComponentDisplayValues,\n  } from '$lib/services/contents/fields/rich-text/components/summary';\n  import { getComponentThumbnail } from '$lib/services/contents/fields/rich-text/components/thumbnail';\n  import {\n    followReadonly,\n    getParentComponentNames,\n  } from '$lib/services/contents/fields/rich-text/components/utils';\n  import { validateComponentValues } from '$lib/services/contents/fields/rich-text/components/validate';\n  import {\n    deleteKeysByPrefix,\n    deleteOwnKeysByPrefix,\n    flattenWithPrefix,\n    getValuesByPrefix,\n    reconcileComponentValues,\n  } from '$lib/services/contents/fields/rich-text/components/values';\n  import { createStableDerivedState, watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n   * @import {\n   * DraftValueStoreKey,\n   * EntryDraft,\n   * FieldEditorContext,\n   * InternalLocaleCode,\n   * MediaFieldSource,\n   * TypedFieldKeyPath,\n   * } from '$lib/types/private';\n   * @import { EditorComponentMode, Field, FieldKeyPath, RawEntryContent } from '$lib/types/public';\n   */\n\n  /**\n   * Entry draft state of the editor this component is rendered in. Lexical mounts the component\n   * outside the Svelte component tree, so the state can’t come from the context; it’s looked up\n   * through the DOM once the component is in place, along with the locale and key path below.\n   * @type {EntryDraftState | undefined}\n   */\n  let entryDraft = $state();\n\n  // The field editors rendered below expect the state in the context, which has to be set now,\n  // before the state is resolved, so hand them a stand-in that follows it\n  setEntryDraftContext({\n    /**\n     * Get the current draft.\n     * @returns {EntryDraft | null | undefined} Draft.\n     */\n    get current() {\n      return entryDraft?.current;\n    },\n    /* v8 ignore start -- only the entry editor toolbar and overlay, which are never rendered within\n    a component, replace the draft or check whether it’s been modified */\n    /**\n     * Replace the current draft.\n     * @param {EntryDraft | null | undefined} draft Draft.\n     */\n    set current(draft) {\n      if (entryDraft) {\n        entryDraft.current = draft;\n      }\n    },\n    /**\n     * Get whether the current draft has been modified.\n     * @returns {boolean} Result.\n     */\n    get modified() {\n      return entryDraft?.modified ?? false;\n    },\n    /* v8 ignore stop */\n  });\n\n  /**\n   * Names of the components this one is nested in, the outermost first. They’re looked up through\n   * the DOM like the draft state, as the context doesn’t reach here, and handed down to the field\n   * editors below, so a rich text field among them knows every component it’s nested in.\n   * @type {string[]}\n   */\n  let parentComponentNames = $state.raw([]);\n  /**\n   * Whether the rich text field this component is in can’t be edited, e.g. with the `readonly`\n   * option or in a locale that follows the default one. It’s also looked up through the DOM, and\n   * handed down to the field editors below, which are otherwise unaware of it.\n   */\n  let readonly = $state(false);\n\n  setFieldEditorContext(\n    /** @type {FieldEditorContext} */ ({\n      /**\n       * Get the names of the components this one is nested in.\n       * @returns {string[]} Names.\n       */\n      get parentComponentNames() {\n        return parentComponentNames;\n      },\n      /**\n       * Get whether the fields can’t be edited.\n       * @returns {boolean} Result.\n       */\n      get readonly() {\n        return readonly;\n      },\n    }),\n  );\n\n  /**\n   * @typedef {object} Props\n   * @property {string} componentName Rich text editor component name.\n   * @property {string} label Field label.\n   * @property {EditorComponentMode} [mode] Editing mode for the component. Default: `'block'`.\n   * @property {boolean} [inline] Whether the component is inline. Default: `false`.\n   * @property {boolean} [collapsed] Whether to collapse the object by default (`block` mode only).\n   * Default: `false`.\n   * @property {string} [summary] Summary template for the placeholder text (`dialog` mode only),\n   * e.g. `{{title}}`.\n   * @property {string} [thumbnail] Name of an Image or File field whose image is displayed as a\n   * thumbnail in the placeholder (`dialog` mode only), e.g. `icon`.\n   * @property {Field[]} fields Subfield definitions.\n   * @property {Record<string, any> | undefined} values Value map.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `change` event handler.\n   */\n\n  /** @type {Props} */\n  let {\n    componentName,\n    label,\n    mode = 'block',\n    inline = false,\n    collapsed = false,\n    summary,\n    thumbnail,\n    fields,\n    values,\n    onChange = () => undefined,\n  } = $props();\n\n  const fieldId = $props.id();\n\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n  /** @type {InternalLocaleCode} */\n  let locale = $state('');\n  /** @type {FieldKeyPath} */\n  let keyPath = $state('');\n  // Block mode only\n  /** @type {TypedFieldKeyPath} */\n  let typedKeyPath = $state('');\n  /** @type {boolean} */\n  // svelte-ignore state_referenced_locally\n  let expanded = $state(!collapsed);\n  // Dialog mode only\n  /** @type {boolean} */\n  let dialogOpen = $state(false);\n  /**\n   * Snapshot of values when dialog opens, used to restore on cancel.\n   * @type {Record<string, any> | undefined}\n   */\n  let valuesSnapshot = $state(undefined);\n  /**\n   * Whether this is a freshly inserted component (no existing values). Initialized once in\n   * `onMount` so it doesn’t change when `values` is later assigned defaults.\n   */\n  let isNewComponent = $state(false);\n\n  /**\n   * Whether the component has any fields to edit. A component without fields can still be used as\n   * a placeholder, but there is nothing to expand or collapse in block mode, or to edit in a dialog\n   * in dialog mode.\n   */\n  const hasFields = $derived(fields.length > 0);\n  /**\n   * Whether the field’s control is rendered within the text (inline mode). The fields are checked\n   * when the configuration is parsed, but a component registered later isn’t, so one with fields\n   * the mode can’t have falls back to the block mode.\n   */\n  const inlineControl = $derived(mode === 'inline' && isInlineComponentFieldList(fields));\n  /**\n   * Names of this component and those it’s nested in, which the components nested in its fields\n   * read with {@link getParentComponentNames}.\n   */\n  const componentPath = $derived(JSON.stringify([...parentComponentNames, componentName]));\n\n  /* v8 ignore start -- the key paths are resolved together once the component is in place */\n  const keyPathPrefix = $derived(!keyPath ? '' : `${keyPath}:${fieldId}:`);\n  const typedKeyPathPrefix = $derived(!typedKeyPath ? '' : `${typedKeyPath}:${fieldId}:`);\n  /* v8 ignore stop */\n  /**\n   * Get the wrapper element.\n   * @returns {HTMLElement | undefined} Wrapper.\n   */\n  export const getElement = () => wrapper;\n\n  /**\n   * Handle a key pressed within the block, once the field controls in it have handled the key. The\n   * listener is added with `on()` in the bubble phase rather than as an `onkeydown` attribute or in\n   * the capture phase: Svelte delegates `keydown` to the root, which the event must not reach, and\n   * stopping it any earlier would keep it from the controls, e.g. the Enter key in a list or the\n   * arrow keys in a combobox. `on()` runs the delegated listeners below the block first.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  const handleBlockKeyDown = (event) => {\n    const { target } = /** @type {KeyboardEvent & { target: HTMLElement }} */ (event);\n\n    // A nested rich text editor handles its own keys, so leave the event alone when it comes from\n    // one: cancelling it would block typing there. The outer editor ignores the event once it\n    // bubbles up, as Lexical marks it as handled by the nested one\n    if (target.closest('[contenteditable]') !== wrapper) {\n      return;\n    }\n\n    // Keep the outer editor from acting on the key, e.g. selecting all of its content with Ctrl+A\n    // pressed in a `TextInput` within the block\n    event.stopPropagation();\n\n    // Keep the browser from editing the outer editor’s content, except in a text field or button,\n    // and let Tab move the focus\n    if (!target.matches('button, input, textarea') && event.key !== 'Tab') {\n      event.preventDefault();\n    }\n\n    if (target === wrapper && event.key === 'Backspace' && !readonly) {\n      onChange(new CustomEvent('remove'));\n    }\n  };\n\n  /**\n   * Key to store the current values in the {@link entryDraft}. Usually `currentValues`, but we use\n   * `extraValues` here to store additional values for a rich text editor component.\n   * @type {DraftValueStoreKey}\n   */\n  const valueStoreKey = 'extraValues';\n  /**\n   * Previous values for the editor component, used to detect changes (block mode only).\n   * @type {RawEntryContent | undefined}\n   */\n  let previousValues = undefined;\n  /**\n   * Whether `values` has just been replaced with the data of the node with {@link setValues}, e.g.\n   * after an undo, so the values are written to the draft as they are, and not reported back to the\n   * node, which would add a step to the history and drop what can be redone.\n   */\n  let valuesFromNode = false;\n  /**\n   * Whether the component has been unmounted, after which a deferred write must not put its values\n   * back into the draft. A plain variable, as it’s read outside of any reactive context.\n   */\n  let unmounted = false;\n  /**\n   * Plain copies of the draft, locale and key path prefix, updated from an effect, which the\n   * teardown reads instead of the reactive state: reading a derived value in a teardown makes\n   * Svelte walk the graph below it, which costs exponentially more with each level of nesting.\n   * @type {{ draft?: EntryDraft | null, locale: InternalLocaleCode, keyPathPrefix: string }}\n   */\n  let teardownState = { locale: '', keyPathPrefix: '' };\n\n  /**\n   * Current values for the editor component. These values are stored in the {@link entryDraft}\n   * under the `extraValues` key, with the key path prefixed with the parent field’s key path, e.g.\n   * `body:c12:image`.\n   *\n   * The values are picked out of a snapshot of all the `extraValues`, which changes whenever any\n   * component in the entry is edited. The prefixed key paths aren’t subtrees the value map keeps a\n   * version of, so the values are kept as long as they’re the same instead, and what depends on\n   * them only reacts to a change of this component’s own values.\n   */\n  const _currentValues = createStableDerivedState(() => {\n    if (!(entryDraft?.current && locale && keyPath)) {\n      return undefined;\n    }\n\n    return getValuesByPrefix(\n      getValueMapSnapshot(entryDraft.current, locale, valueStoreKey),\n      keyPathPrefix,\n    );\n  });\n  /** @type {RawEntryContent | undefined} */\n  const currentValues = $derived(_currentValues.current);\n\n  /**\n   * Attach the draft state to the element holding the fields in the dialog (dialog mode only). The\n   * dialog is rendered outside the entry editor, so a component nested in a rich text field there\n   * would otherwise never find the draft with {@link getEntryDraftByElement}; the element also\n   * carries the locale in its `data-locale` attribute, while the field editors carry the key paths.\n   * @param {HTMLElement} element Element.\n   */\n  const attachEntryDraft = (element) => {\n    if (entryDraft) {\n      setEntryDraftRoot(element, entryDraft);\n    }\n  };\n\n  /**\n   * Replace the component values with the data of the node, which changes without the component\n   * knowing when the change is undone or redone.\n   * @param {Record<string, any>} newValues New values.\n   */\n  export const setValues = (newValues) => {\n    if (!equal(newValues, values)) {\n      valuesFromNode = true;\n      values = newValues;\n    }\n  };\n\n  /**\n   * Open the dialog and take a snapshot of current values (dialog mode only).\n   */\n  const openDialog = () => {\n    // There is nothing to edit, so the component is inserted and kept as is\n    if (!hasFields) {\n      return;\n    }\n\n    /* v8 ignore next -- the values are set up before the dialog can be opened */\n    valuesSnapshot = currentValues ? { ...currentValues } : undefined;\n    dialogOpen = true;\n  };\n\n  /**\n   * Restore values from snapshot, used on cancel (dialog mode only).\n   */\n  const restoreValues = () => {\n    const draft = entryDraft?.current;\n\n    /* v8 ignore next -- the dialog is only open while the draft is there, with a snapshot */\n    if (draft && locale && keyPath && valuesSnapshot) {\n      // Clear current values\n      deleteKeysByPrefix(draft[valueStoreKey][locale], keyPathPrefix);\n      // Restore snapshot\n      Object.assign(draft[valueStoreKey][locale], flattenWithPrefix(valuesSnapshot, keyPathPrefix));\n    }\n  };\n\n  /**\n   * Handle remove action (dialog mode only).\n   */\n  const handleRemove = () => {\n    dialogOpen = false;\n    onChange(new CustomEvent('remove'));\n  };\n\n  /**\n   * Handle OK button click. Validates fields and only closes if valid (dialog mode only). A change\n   * just made in a rich text field in the dialog, including one in a component nested there, only\n   * reaches the draft a moment later, so wait for it first, or the previous values would be used.\n   */\n  const handleOk = async () => {\n    await awaitPendingFieldUpdates();\n\n    const draft = entryDraft?.current;\n\n    /* v8 ignore next 3 -- the dialog can only be confirmed while the draft is being edited */\n    if (!draft) {\n      return;\n    }\n\n    if (validateComponentValues({ draft, locale, keyPathPrefix })) {\n      isNewComponent = false;\n      dialogOpen = false;\n      onChange(new CustomEvent('update', { detail: currentValues }));\n      valuesSnapshot = undefined;\n    }\n  };\n\n  /**\n   * Handle Cancel button click. Restores values from snapshot and closes dialog (dialog mode only).\n   * If the component was newly inserted, remove it entirely instead of leaving it with empty state.\n   */\n  const handleCancel = () => {\n    if (isNewComponent) {\n      dialogOpen = false;\n      onChange(new CustomEvent('remove'));\n    } else {\n      restoreValues();\n      dialogOpen = false;\n      valuesSnapshot = undefined;\n    }\n  };\n\n  /**\n   * The asset or URL of a thumbnail that couldn’t be shown, which is then replaced with the text.\n   * Raw, as a deep state would wrap the asset in a proxy that never equals the asset itself.\n   * @type {MediaFieldSource['asset'] | string | undefined}\n   */\n  let brokenThumbnail = $state.raw();\n\n  /**\n   * The image to display as a thumbnail in the placeholder (dialog mode only), taken from the field\n   * named with the `thumbnail` option. The draft is required to look up the field’s collection.\n   * Only the dialog mode placeholder reads this, so it’s never worked out in block mode.\n   * @type {MediaFieldSource | undefined}\n   */\n  const thumbnailSource = $derived.by(() => {\n    const draft = entryDraft?.current;\n\n    if (!draft) {\n      return undefined;\n    }\n\n    const source = getComponentThumbnail({\n      thumbnailFieldName: thumbnail,\n      values: getComponentDisplayValues({ currentValues, values, fields }),\n      componentName,\n      collectionName: draft.collectionName,\n      fileName: draft.fileName,\n      isIndexFile: draft.isIndexFile,\n      entry: draft.originalEntry,\n      files: draft.files,\n      locale,\n    });\n\n    return source && (source.asset ?? source.url) !== brokenThumbnail ? source : undefined;\n  });\n\n  /**\n   * The text to display in the placeholder (dialog mode only). Priority:\n   * 1. Formatted summary template (if provided and produces non-empty result)\n   * 2. First string field’s value\n   * 3. Component label, which is omitted when a thumbnail is shown.\n   */\n  const displayText = $derived(\n    // Fall back to the `values` prop when `currentValues` has no field data yet, e.g. on initial\n    // render or before the store has been notified with the values\n    getComponentDisplayText({\n      template: summary,\n      currentValues,\n      values,\n      fields,\n      locale,\n      label,\n      hasThumbnail: !!thumbnailSource,\n    }),\n  );\n\n  onMount(() => {\n    // Requested before the frame below, so the state is known by the time the field editors render\n    const stopFollowingReadonly = followReadonly(wrapper, (value) => {\n      readonly = value;\n    });\n\n    window.requestAnimationFrame(() => {\n      // The component may have been removed before the frame came, e.g. by an undo right after\n      // inserting it, in which case it must neither write to the draft nor open the dialog\n      if (unmounted) {\n        return;\n      }\n\n      // Get the draft state, locale and key path from the closest containers\n      entryDraft = getEntryDraftByElement(wrapper);\n      // Before the locale and key path, which render the field editors: they read the names once\n      parentComponentNames = getParentComponentNames(wrapper);\n\n      const localeContainer = /** @type {HTMLElement} */ (wrapper?.closest('[data-locale]'));\n      const keyPathContainer = /** @type {HTMLElement} */ (wrapper?.closest('[data-key-path]'));\n\n      locale = /** @type {string} */ (localeContainer?.dataset.locale);\n      keyPath = /** @type {string} */ (keyPathContainer?.dataset.keyPath);\n\n      if (mode !== 'dialog') {\n        typedKeyPath = /** @type {string} */ (keyPathContainer?.dataset.typedKeyPath);\n      }\n\n      // Capture whether this is a newly inserted component (before $effect assigns defaults)\n      isNewComponent = !values;\n\n      // Auto-open dialog for freshly inserted components (dialog mode only)\n      if (mode === 'dialog' && isNewComponent) {\n        openDialog();\n      }\n    });\n\n    return () => {\n      // Read the plain copies: reading reactive state here would make Svelte walk the graph below\n      const { draft, locale: _locale, keyPathPrefix: _keyPathPrefix } = teardownState;\n\n      unmounted = true;\n      stopFollowingReadonly();\n\n      // Remove the values and validities from the draft when the component is unmounted. The\n      // deletion is deferred like a write, as an unmount can happen while an effect is running. The\n      // prefix carries the ID of this component instance, so nothing else, e.g. the component\n      // mounted again in its place, can have written values under it in the meantime\n      if (draft) {\n        deferDraftWrite(() => {\n          deleteKeysByPrefix(draft[valueStoreKey][_locale], _keyPathPrefix);\n          deleteKeysByPrefix(draft.validities[_locale], _keyPathPrefix);\n        });\n      }\n    };\n  });\n\n  // Keep plain copies of what the teardown above needs\n  $effect(() => {\n    teardownState = {\n      draft: entryDraft?.current,\n      locale,\n      keyPathPrefix,\n    };\n  });\n\n  watch(\n    () => [values, locale, keyPath],\n    () => {\n      if (entryDraft?.current && locale && keyPath) {\n        const fromNode = valuesFromNode;\n\n        valuesFromNode = false;\n\n        const reconciledValues = reconcileComponentValues({\n          values,\n          fields,\n          componentName,\n          locale,\n          defaultLocale: entryDraft.current.defaultLocale,\n        });\n\n        // Only reassign when something actually changed, or this would run forever\n        if (reconciledValues !== values) {\n          values = reconciledValues;\n        }\n\n        // The node already holds these values, so they don’t have to be reported to it (block mode)\n        if (fromNode) {\n          previousValues = values;\n        }\n\n        if (!equal(values, currentValues)) {\n          const draftState = /** @type {EntryDraftState} */ (entryDraft);\n\n          const flatValues = flattenWithPrefix(\n            /** @type {Record<string, any>} */ (values),\n            keyPathPrefix,\n          );\n\n          // This runs from an effect, so the write to the draft is deferred. The draft is looked up\n          // again, as it may have been replaced by then, e.g. reset after a save\n          deferDraftWrite(() => {\n            const draft = draftState.current;\n\n            // Lexical unmounts the component on its own schedule, which may come after the draft\n            // has been closed\n            /* v8 ignore next 3 -- the editor is closed between the effect and this microtask */\n            if (!draft) {\n              return;\n            }\n\n            if (!unmounted) {\n              // The node’s data replaces the values as a whole, e.g. a list item an undo removes,\n              // while the components nested in the fields keep theirs\n              if (fromNode) {\n                deleteOwnKeysByPrefix(draft[valueStoreKey][locale], keyPathPrefix);\n              }\n\n              Object.assign(draft[valueStoreKey][locale], flatValues);\n            }\n          });\n        }\n\n        // A new component without fields skips the dialog, so it’s inserted right away (dialog mode\n        // only; block mode reports the values whenever they change)\n        if (mode === 'dialog' && !hasFields && isNewComponent) {\n          isNewComponent = false;\n          onChange(new CustomEvent('update', { detail: values }));\n        }\n      }\n    },\n  );\n\n  // Block mode: forward onChange whenever currentValues change\n  watch(\n    () => [mode, currentValues],\n    () => {\n      if (mode !== 'dialog' && !equal(previousValues, currentValues)) {\n        onChange(new CustomEvent('update', { detail: currentValues }));\n        previousValues = currentValues;\n      }\n    },\n  );\n</script>\n\n{#snippet fieldEditors(\n  /**\n   * @type {{\n   * typedPrefix: string,\n   * observe: boolean,\n   * inline?: boolean,\n   * }}\n   */ { typedPrefix, observe, inline: inlineField = false },\n)}\n  {#each fields as fieldConfig (fieldConfig.name)}\n    {#snippet fieldEditor()}\n      <FieldEditor\n        {locale}\n        keyPath=\"{keyPathPrefix}{fieldConfig.name}\"\n        typedKeyPath=\"{typedPrefix}{fieldConfig.name}\"\n        {fieldConfig}\n        context=\"rich-text-editor-component\"\n        {componentName}\n        {valueStoreKey}\n        inline={inlineField}\n      />\n    {/snippet}\n    {#if observe}\n      <VisibilityObserver>\n        {@render fieldEditor()}\n      </VisibilityObserver>\n    {:else}\n      {@render fieldEditor()}\n    {/if}\n  {/each}\n{/snippet}\n\n{#if mode === 'dialog'}\n  <!-- Dialog mode: compact placeholder that opens a dialog on click, unless there are no fields;\n  it can still be focused then, to be removed with the Backspace key -->\n  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n  <span\n    role={hasFields ? 'button' : 'img'}\n    class=\"component {inline ? 'inline' : 'block'} placeholder\"\n    class:static={!hasFields}\n    class:thumbnail-only={!!thumbnailSource && !displayText}\n    bind:this={wrapper}\n    contenteditable=\"false\"\n    tabindex=\"0\"\n    aria-label={label}\n    title={label}\n    data-key-path-prefix={keyPathPrefix}\n    data-component-name={componentName}\n    onclick={() => {\n      openDialog();\n    }}\n    onkeydown={(event) => {\n      // Activate the button with the Enter or Space key, like a native one. The Space key would\n      // otherwise reach the rich text editor\n      if (event.key === 'Enter' || event.key === ' ') {\n        event.preventDefault();\n        openDialog();\n      }\n\n      if (event.key === 'Backspace') {\n        event.preventDefault();\n\n        if (!readonly) {\n          onChange(new CustomEvent('remove'));\n        }\n      }\n    }}\n  >\n    {#if thumbnailSource}\n      <Image\n        asset={thumbnailSource.asset}\n        src={thumbnailSource.url}\n        variant=\"icon\"\n        cover\n        onError={() => {\n          // Show the text instead of a generic file icon\n          const { asset, url } = /** @type {MediaFieldSource} */ (thumbnailSource);\n\n          brokenThumbnail = asset ?? url;\n        }}\n      />\n    {/if}\n    {#if displayText}\n      <span role=\"none\">{displayText}</span>\n    {/if}\n  </span>\n\n  {#if hasFields}\n    <Dialog\n      title={label}\n      bind:open={dialogOpen}\n      size=\"large\"\n      showOk={false}\n      showCancel={false}\n      onCancel={() => {\n        // The Escape key dismisses the dialog just like the Cancel button\n        handleCancel();\n      }}\n    >\n      <div\n        role=\"none\"\n        class=\"fields\"\n        data-locale={locale}\n        data-component-path={componentPath}\n        {@attach attachEntryDraft}\n      >\n        {#if locale && keyPath}\n          {@render fieldEditors({ typedPrefix: keyPathPrefix, observe: false })}\n        {/if}\n      </div>\n      {#snippet footer()}\n        <!-- A read-only component can only be viewed, so the dialog can only be dismissed -->\n        {#if !readonly}\n          <Button\n            variant=\"secondary\"\n            label={_('remove')}\n            onclick={() => {\n              handleRemove();\n            }}\n          />\n        {/if}\n        <Spacer flex={true} />\n        {#if !readonly}\n          <Button\n            variant=\"primary\"\n            label={_(isNewComponent ? 'insert' : 'update')}\n            onclick={() => {\n              handleOk();\n            }}\n          />\n        {/if}\n        <Button\n          variant=\"secondary\"\n          label={_('cancel')}\n          onclick={() => {\n            handleCancel();\n          }}\n        />\n      {/snippet}\n    </Dialog>\n  {/if}\n{:else if inlineControl}\n  <!-- Inline mode: the control of the only field, right within the text -->\n  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n  <span\n    role=\"group\"\n    class=\"component inline-field\"\n    bind:this={wrapper}\n    contenteditable=\"false\"\n    tabindex=\"0\"\n    aria-label={label}\n    title={label}\n    data-key-path-prefix={keyPathPrefix}\n    data-component-name={componentName}\n    data-component-path={componentPath}\n    {@attach (element) => on(element, 'keydown', handleBlockKeyDown)}\n  >\n    {#if locale && keyPath}\n      {@render fieldEditors({ typedPrefix: typedKeyPathPrefix, observe: false, inline: true })}\n    {/if}\n  </span>\n{:else}\n  <!-- Block mode: expandable block with ObjectHeader -->\n  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n  <div\n    role=\"group\"\n    class=\"component {inline ? 'inline' : 'block'} wrapper\"\n    class:expanded={hasFields && expanded}\n    bind:this={wrapper}\n    contenteditable=\"false\"\n    tabindex=\"0\"\n    aria-label={label}\n    data-key-path-prefix={keyPathPrefix}\n    data-component-name={componentName}\n    data-component-path={componentPath}\n    {@attach (element) => on(element, 'keydown', handleBlockKeyDown)}\n  >\n    <ObjectHeader\n      {label}\n      controlId=\"object-{fieldId}-item-list\"\n      expandable={hasFields}\n      bind:expanded\n    >\n      {#snippet endContent()}\n        {#if !readonly}\n          <RemoveButton\n            onclick={() => {\n              onChange(new CustomEvent('remove'));\n            }}\n          />\n        {/if}\n      {/snippet}\n    </ObjectHeader>\n    {#if hasFields}\n      <div role=\"none\" class=\"item-list\" id=\"object-{fieldId}-item-list\">\n        {#if locale && keyPath && expanded}\n          {@render fieldEditors({ typedPrefix: typedKeyPathPrefix, observe: true })}\n        {/if}\n      </div>\n    {/if}\n  </div>\n{/if}\n\n<style>\n  .component {\n    &.block {\n      display: block;\n\n      &:not(:first-child) {\n        margin-top: var(--sui-paragraph-margin);\n      }\n\n      &:not(:last-child) {\n        margin-bottom: var(--sui-paragraph-margin);\n      }\n    }\n\n    &.inline {\n      display: inline-block;\n    }\n  }\n\n  .wrapper {\n    border-inline-width: 2px;\n    border-color: var(--sui-secondary-border-color);\n    border-radius: var(--sui-control-medium-border-radius);\n    width: 100%;\n    color: var(--sui-secondary-foreground-color); /* Reset color within a link */\n    background-color: var(--sui-primary-background-color);\n    white-space: normal;\n    -webkit-user-select: none;\n    user-select: none;\n\n    &.expanded {\n      border-bottom-width: 2px;\n    }\n\n    &:focus {\n      outline-color: var(--sui-primary-accent-color-translucent);\n    }\n\n    /* Make the input fields compact within the built-in image component */\n    &:is(\n      [data-component-name='image'],\n      [data-component-name='linked-image'],\n      [data-component-name='uncaptioned-image'],\n      [data-component-name='uncaptioned-linked-image']\n    ) {\n      :global {\n        @media (768px <= width) {\n          /* Hide the bottom border */\n          [data-field-type]::after {\n            display: none;\n          }\n\n          [data-field-type='string'] {\n            display: flex;\n            align-items: center;\n            gap: 8px;\n            padding-block: 0 16px;\n\n            h4 {\n              margin-bottom: 0 !important;\n            }\n\n            .field-wrapper {\n              flex: auto;\n            }\n          }\n        }\n\n        button {\n          margin: var(--sui-focus-ring-width);\n        }\n      }\n    }\n  }\n\n  .inline-field {\n    /* Make the controls as compact as the text around them allows */\n    --sui-textbox-singleline-min-width: 8em;\n    --sui-combobox-min-width: 6em;\n    display: inline-flex;\n    align-items: center;\n    vertical-align: middle;\n    margin-inline: 2px;\n    border-radius: var(--sui-control-medium-border-radius);\n    padding: 2px;\n    background-color: var(--sui-secondary-background-color);\n    white-space: normal;\n    -webkit-user-select: none;\n    user-select: none;\n\n    &:focus {\n      outline: 2px solid var(--sui-primary-accent-color-translucent);\n      outline-offset: 1px;\n    }\n\n    :global {\n      .field.inline {\n        display: inline-flex;\n        align-items: center;\n      }\n\n      /* Only the control itself, not the text box within a number input */\n      .field.inline > .sui:is(.text-input, .number-input, .combobox) {\n        margin: 0;\n        width: auto;\n      }\n    }\n  }\n\n  .placeholder {\n    --icon-size: 20px; /* Thumbnail size */\n    align-items: center;\n    gap: 0.4em;\n    border: dashed 1px currentColor;\n    border-color: hsl(from currentColor h s l / 0.5);\n    border-radius: 2px;\n    padding-inline: 0.4em;\n    cursor: pointer;\n    -webkit-user-select: none;\n    user-select: none;\n\n    &:not(.static):hover {\n      border-color: currentColor;\n    }\n\n    &:focus {\n      outline: 2px solid var(--sui-primary-accent-color-translucent);\n      outline-offset: 1px;\n    }\n\n    &.inline {\n      display: inline-flex;\n    }\n\n    &.block {\n      display: flex;\n      width: fit-content;\n    }\n\n    /* Center the thumbnail on the line rather than sitting it on the baseline */\n    &:has(:global(.preview)) {\n      vertical-align: middle;\n    }\n\n    &.thumbnail-only {\n      padding: 2px;\n    }\n\n    /* A component without fields can’t be edited */\n    &.static {\n      cursor: default;\n    }\n  }\n\n  .fields {\n    display: flex;\n    flex-direction: column;\n    gap: 16px;\n  }\n</style>\n","/**\n * @typedef {[start: number, end: number]} TextRange A range of a string, with an exclusive end.\n */\n\n/**\n * Regex to match the opening line of a fenced code block, capturing the fence. It allows any\n * indentation, so a fence within a list item counts as well; a fence indented further is within an\n * indented code block, which is code anyway.\n */\nconst FENCE_OPEN_REGEX = /^([ \\t]*)(`{3,}|~{3,})(.*)$/;\n/**\n * Regex to match a run of backticks.\n */\nconst BACKTICKS_REGEX = /`+/g;\n/**\n * Regex to match a blank line, which ends a paragraph and therefore a code span.\n */\nconst BLANK_LINE_REGEX = /\\n[ \\t]*\\n/;\n\n/**\n * Regex to match the start of an HTML block that ends at a blank line: a block-level tag, which can\n * interrupt a paragraph (type 6 in CommonMark). The tag names are the ones Marked recognizes.\n * @see https://spec.commonmark.org/0.31.2/#html-blocks\n */\nconst BLOCK_TAG_REGEX = new RegExp(\n  '^ {0,3}</?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|' +\n    'dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|' +\n    'h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|' +\n    'optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|' +\n    'ul)(?:[ \\\\t]|/?>|$)',\n  'i',\n);\n\n/**\n * Regex to match the start of an HTML block that ends at a blank line: a line with nothing but an\n * opening or closing tag of any other element, which cannot interrupt a paragraph (type 7).\n */\nconst LONE_TAG_REGEX =\n  /^ {0,3}(?:<(?!(?:pre|script|style|textarea)[\\s/>])[a-z][a-z\\d-]*(?:[ \\t]+[a-z_:][\\w.:-]*(?:[ \\t]*=[ \\t]*(?:[^\\s\"'=<>`]+|'[^']*'|\"[^\"]*\"))?)*[ \\t]*\\/?>|<\\/[a-z][a-z\\d-]*[ \\t]*>)[ \\t]*$/i;\n\n/**\n * Check if the character at the given index is escaped with a backslash, which is itself not\n * escaped.\n * @param {string} text Text.\n * @param {number} index Index of the character.\n * @param {number} from Index to look for backslashes from.\n * @returns {boolean} Result.\n */\nconst isEscaped = (text, index, from) => {\n  let count = 0;\n\n  while (index - count > from && text[index - count - 1] === '\\\\') {\n    count += 1;\n  }\n\n  return count % 2 === 1;\n};\n\n/**\n * Match the opening line of a fenced code block. The info string of a backtick fence cannot\n * contain a backtick, so a line like ```` ```code``` ```` is a code span instead.\n * @param {string} line Line.\n * @returns {{ indent: string, char: string, length: number, info: string } | undefined}\n * Indentation, fence character, fence length and info string, or `undefined` if the line doesn’t\n * open a fence.\n * @see https://spec.commonmark.org/0.31.2/#fenced-code-blocks\n */\nexport const matchFenceOpen = (line) => {\n  const [, indent = '', run = '', info = ''] = line.match(FENCE_OPEN_REGEX) ?? [];\n\n  if (!run || (run[0] === '`' && info.includes('`'))) {\n    return undefined;\n  }\n\n  return { indent, char: run[0], length: run.length, info };\n};\n\n/**\n * Check if the given line closes a fenced code block: a run of the fence character, at least as\n * long as the opening fence, with nothing else but whitespace.\n * @param {string} line Line.\n * @param {{ char: string, length: number }} fence Opening fence. See {@link matchFenceOpen}.\n * @returns {boolean} Result.\n */\nexport const isFenceClose = (line, { char, length }) => {\n  const closing = line.trim();\n\n  return closing.length >= length && closing === char.repeat(closing.length);\n};\n\n/**\n * Get the ranges of the fenced code blocks and code spans in the given Markdown, where any other\n * syntax is literal text. Indented code blocks are not detected, as an indented line can also be\n * the continuation of a list item.\n * @param {string} markdown Markdown.\n * @returns {TextRange[]} Ranges, sorted by position.\n * @see https://spec.commonmark.org/0.31.2/#fenced-code-blocks\n * @see https://spec.commonmark.org/0.31.2/#code-spans\n */\nexport const getCodeRanges = (markdown) => {\n  /** @type {TextRange[]} */\n  const ranges = [];\n  /** @type {{ start: number, char: string, length: number } | undefined} */\n  let fence;\n  /** Start of the text outside fences that hasn’t been searched for code spans yet. */\n  let textStart = 0;\n  let lineStart = 0;\n\n  /**\n   * Add the code spans in the given part of the Markdown.\n   * @param {number} start Start index.\n   * @param {number} end End index.\n   */\n  const addCodeSpans = (start, end) => {\n    const text = markdown.slice(start, end);\n    const runs = [...text.matchAll(BACKTICKS_REGEX)];\n    let cursor = 0;\n\n    runs.forEach(({ 0: run, index }, runIndex) => {\n      // Skip a run within a code span found already, or one escaped with a backslash\n      if (index < cursor || isEscaped(text, index, cursor)) {\n        return;\n      }\n\n      // A code span ends with the next run of the same length, within the same paragraph\n      const closing = runs.find((r, i) => i > runIndex && r[0].length === run.length);\n\n      if (closing && !BLANK_LINE_REGEX.test(text.slice(index, closing.index))) {\n        cursor = closing.index + run.length;\n        ranges.push([start + index, start + cursor]);\n      }\n    });\n  };\n\n  markdown.split('\\n').forEach((line) => {\n    const lineEnd = lineStart + line.length;\n\n    if (fence) {\n      if (isFenceClose(line, fence)) {\n        ranges.push([fence.start, lineEnd]);\n        fence = undefined;\n        textStart = lineEnd;\n      }\n    } else {\n      const opening = matchFenceOpen(line);\n\n      // The range starts with the fence, so a component matching the fenced block from there isn’t\n      // taken for code\n      if (opening) {\n        addCodeSpans(textStart, lineStart);\n        fence = {\n          start: lineStart + opening.indent.length,\n          char: opening.char,\n          length: opening.length,\n        };\n      }\n    }\n\n    lineStart = lineEnd + 1;\n  });\n\n  if (fence) {\n    // An unclosed fence runs to the end\n    ranges.push([fence.start, markdown.length]);\n  } else {\n    addCodeSpans(textStart, markdown.length);\n  }\n\n  return ranges.sort(([a], [b]) => a - b);\n};\n\n/**\n * Check if the given index is within any of the given ranges, after their start.\n * @param {number} index Index.\n * @param {TextRange[]} ranges Ranges.\n * @returns {boolean} Result.\n */\nexport const isWithinRanges = (index, ranges) =>\n  ranges.some(([start, end]) => index > start && index < end);\n\n/**\n * Check if the given line starts an HTML block that runs until a blank line.\n * @param {string} line Line.\n * @param {object} [options] Options.\n * @param {boolean} [options.afterParagraph] Whether the line follows a paragraph line, which only a\n * block-level tag can interrupt.\n * @returns {boolean} Result.\n */\nexport const startsHTMLBlock = (line, { afterParagraph = false } = {}) =>\n  BLOCK_TAG_REGEX.test(line) || (!afterParagraph && LONE_TAG_REGEX.test(line));\n\n/**\n * Check if the line at the given index is within an HTML block that runs until a blank line, as one\n * of the lines before it, since the previous blank line, starts such a block.\n * @param {string} markdown Markdown.\n * @param {number} lineStart Index of the start of the line.\n * @returns {boolean} Result.\n */\nexport const isWithinHTMLBlock = (markdown, lineStart) => {\n  const lines = markdown.slice(0, Math.max(0, lineStart - 1)).split('\\n');\n  const runStart = lines.findLastIndex((line) => !line.trim()) + 1;\n\n  return lines\n    .slice(runStart)\n    .some((line, index) => startsHTMLBlock(line, { afterParagraph: index > 0 }));\n};\n","import { getImmutable, immutableLoaded } from '$lib/services/api/immutable';\nimport { IMAGE_COMPONENT_IDS } from '$lib/services/contents/fields/rich-text/components/definitions';\nimport { findInlineMatches } from '$lib/services/contents/fields/rich-text/components/inline-pattern';\nimport { supportsHTML } from '$lib/services/contents/fields/rich-text/components/utils';\nimport { IMAGE_OR_LINKED_IMAGE_REGEX } from '$lib/services/contents/fields/rich-text/constants';\nimport {\n  getCodeRanges,\n  isWithinHTMLBlock,\n  isWithinRanges,\n  startsHTMLBlock,\n} from '$lib/services/contents/fields/rich-text/previews/syntax';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { List, MapOf } from 'immutable';\n * @import { ReactElement } from 'react';\n * @import { ResolvedEditorComponentDefinition } from '$lib/types/private';\n * @import {\n * ApiAsset,\n * EditorComponentDefinition,\n * Field,\n * GetAsset,\n * RichTextValueFormat,\n * } from '$lib/types/public';\n */\n\n/**\n * @typedef {string | HTMLElement | ReactElement | undefined} ComponentPreview\n */\n\n/**\n * Asset getter used when a preview is built outside an entry draft, e.g. to learn the tag a\n * component renders. It never finds an asset.\n * @type {GetAsset}\n */\nexport const getNoAsset = () => undefined;\n\n/**\n * Cache of {@link getComponentFieldList} results, keyed by the `fields` array of a component.\n * @type {WeakMap<Field[], List<MapOf<Record<string, any>>>>}\n */\nconst fieldListCache = new WeakMap();\n\n/**\n * Get the fields of an editor component as an Immutable List, which `toPreview()` receives as the\n * third argument for compatibility with Netlify/Decap CMS.\n * @param {EditorComponentDefinition} componentDef Component definition.\n * @returns {List<MapOf<Record<string, any>>> | undefined} Field list, or `undefined` if\n * Immutable.js isn’t loaded. It’s loaded when a component whose `toPreview()` takes three\n * parameters is registered.\n */\nexport const getComponentFieldList = ({ fields }) =>\n  immutableLoaded.current\n    ? getOrCreate(\n        fieldListCache,\n        fields,\n        () => /** @type {List<MapOf<Record<string, any>>>} */ (getImmutable().fromJS(fields)),\n      )\n    : undefined;\n\n/**\n * Selector for the container element of a RichText field preview. Used to determine which preview\n * owns a placeholder or image, as a preview can be nested within another preview’s element preview\n * using `CMS.renderRichText()`.\n */\nexport const CONTAINER_QUERY_SELECTOR = '[data-rich-text-preview]';\n\n/**\n * Selector for finding component placeholder elements in the rendered HTML, used by the\n * `MutationObserver` to identify where to render React element previews.\n */\nexport const COMPONENT_QUERY_SELECTOR = 'span[data-component-key]';\n\n/**\n * A simple FNV-1a 32-bit hash of a string, returned as a hex string. Used to produce stable, short,\n * attribute-safe keys from matched component text.\n * @param {string} str The string to hash.\n * @returns {string} Lowercase hex hash string.\n */\nconst hashString = (str) => {\n  /* eslint-disable no-bitwise */\n  const hash = Array.from(str).reduce(\n    (h, ch) => (((h ^ ch.charCodeAt(0)) >>> 0) * 0x01000193) >>> 0,\n    0x811c9dc5,\n  );\n  /* eslint-enable no-bitwise */\n\n  return hash.toString(16);\n};\n\n/**\n * Encode image URLs in Markdown to ensure spaces are properly handled, including the link of a\n * linked image. E.g. `![alt](my image.png)` -> `![alt](my%20image.png)`.\n * @param {...any} args Arguments from a match of `IMAGE_OR_LINKED_IMAGE_REGEX` or `IMAGE_REGEX`.\n * @returns {string} The encoded image Markdown string.\n * @see https://github.com/markedjs/marked/issues/1639\n */\nexport const encodeImageSrc = (...args) => {\n  const { alt, src, title, singleQuotedTitle, alt2, src2, title2, singleQuotedTitle2, link } =\n    args.at(-1);\n\n  if (src2 !== undefined) {\n    // A link with a quote may have a title, which has to be kept apart\n    const eLink = /[\"']/.test(link) ? link : link.replaceAll(' ', '%20');\n\n    const img = encodeImageSrc({\n      alt: alt2,\n      src: src2,\n      title: title2,\n      singleQuotedTitle: singleQuotedTitle2,\n    });\n\n    return `[${img}](${eLink})`;\n  }\n\n  const eSrc = src.replaceAll(' ', '%20');\n\n  // The title is kept in the quotes it’s written in, as it can contain the other kind\n  return title\n    ? `![${alt}](${eSrc} \"${title}\")`\n    : singleQuotedTitle\n      ? `![${alt}](${eSrc} '${singleQuotedTitle}')`\n      : `![${alt}](${eSrc})`;\n};\n\n/**\n * Global version of `IMAGE_OR_LINKED_IMAGE_REGEX`.\n */\nconst GLOBAL_IMAGE_OR_LINKED_IMAGE_REGEX = new RegExp(IMAGE_OR_LINKED_IMAGE_REGEX, 'g');\n/**\n * Cache for global-flag versions of component definition patterns. Keyed by\n * `${pattern.source}|${pattern.flags}` so the same logical pattern always resolves to the same\n * global `RegExp`, even if the pattern object is recreated across reactive evaluations.\n * @type {Map<string, RegExp>}\n */\nconst globalPatternCache = new Map();\n/**\n * Maximum number of substitution passes in {@link buildMarkdownWithPreviews}. A string preview can\n * expose further component syntax (e.g. a nested component in a `richtext` field), which is picked\n * up by the next pass. The cap guards against a field value that keeps reproducing its own syntax.\n */\nconst MAX_SUBSTITUTION_PASSES = 10;\n\n/**\n * @typedef {object} PreviewRegion\n * @property {number} start Start index of the substituted string preview.\n * @property {number} end End index of the substituted string preview (exclusive).\n * @property {string[]} values String field values the preview was built from.\n */\n\n/**\n * Collect the string values in the given field props, including those nested in objects and\n * arrays, e.g. the items of a list field.\n * @param {any} props Field props.\n * @returns {string[]} String values.\n */\nconst collectStringValues = (props) => {\n  if (typeof props === 'string') {\n    return [props];\n  }\n\n  if (props && typeof props === 'object') {\n    return Object.values(props).flatMap(collectStringValues);\n  }\n\n  return [];\n};\n\n/**\n * Get the global-flag version of a component pattern, so `matchAll()` can be used.\n * @param {RegExp} pattern Component pattern.\n * @returns {RegExp} Global pattern.\n */\nconst getGlobalPattern = (pattern) => {\n  const cacheKey = `${pattern.source}|${pattern.flags}`;\n\n  return getOrCreate(globalPatternCache, cacheKey, () =>\n    pattern.global ? pattern : new RegExp(pattern.source, `${pattern.flags}g`),\n  );\n};\n\n/**\n * @typedef {object} ComponentMatch\n * @property {ResolvedEditorComponentDefinition} def Matched component definition.\n * @property {RegExpExecArray} match Match result.\n * @property {number} index Start index of the match.\n * @property {number} end End index of the match (exclusive).\n * @property {number} order Index of the definition in the given list, used as a tie-breaker.\n */\n\n/**\n * Check if the given match is legitimate within the string previews substituted on the previous\n * pass. Component syntax can only come out of a preview through a field value, typically the\n * verbatim content of a nested `richtext` field, so a match is only accepted when it lies within a\n * preview and its text occurs in one of the values the preview was built from. This rules out a\n * preview that reproduces its own syntax, e.g. one that mirrors `toBlock()` with HTML tags, which\n * would otherwise be substituted again on every pass until the cap is reached.\n * @param {ComponentMatch} candidate Candidate match.\n * @param {PreviewRegion[]} regions Regions of the string previews substituted on the previous pass.\n * @returns {boolean} Result.\n */\nconst isMatchWithinPreviewValues = ({ match, index, end }, regions) =>\n  regions.some(\n    (region) =>\n      index >= region.start &&\n      end <= region.end &&\n      region.values.some((value) => value.includes(match[0])),\n  );\n\n/**\n * Find all the outermost component matches in the given string. When matches overlap, only the\n * one starting first is kept; on a tie, the longest match wins, then the earliest definition. Any\n * match inside another match is dropped, so a component always receives the raw content of a\n * nested `richtext` field, including any nested component syntax, rather than a partially\n * substituted string. This makes the result independent of the component registration order.\n * @param {string} string String to search.\n * @param {ResolvedEditorComponentDefinition[]} componentDefs Component definitions.\n * @param {PreviewRegion[]} [regions] Regions of the string previews substituted on the previous\n * pass, if any. On a later pass, only a match within one of these regions that comes from a\n * field value is kept; the rest of the string has already been scanned.\n * @returns {ComponentMatch[]} Non-overlapping matches sorted by position. A match starting within a\n * code span or fenced code block is left out, as the syntax is literal text there; one starting\n * with the code, e.g. a component made of a fenced code block, is kept.\n */\nconst findOutermostMatches = (string, componentDefs, regions) => {\n  /** @type {ComponentMatch[]} */\n  const candidates = [];\n  const codeRanges = getCodeRanges(string);\n\n  componentDefs.forEach((def, order) => {\n    // A pattern-based inline component is only matched where its trigger text is found, if any,\n    // just like in the rich text editor\n    const matches = def.inlinePattern\n      ? findInlineMatches(string, def.pattern, def.inlinePattern)\n      : string.matchAll(getGlobalPattern(def.pattern));\n\n    matches.forEach((match) => {\n      const candidate = {\n        def,\n        match,\n        index: match.index,\n        end: match.index + match[0].length,\n        order,\n      };\n\n      // A zero-length match cannot be a component and would be re-substituted on every pass\n      if (\n        match[0] &&\n        !isWithinRanges(match.index, codeRanges) &&\n        (!regions || isMatchWithinPreviewValues(candidate, regions))\n      ) {\n        candidates.push(candidate);\n      }\n    });\n  });\n\n  candidates.sort((a, b) => a.index - b.index || b.end - a.end || a.order - b.order);\n\n  let cursor = 0;\n\n  return candidates.filter((candidate) => {\n    if (candidate.index < cursor) {\n      return false;\n    }\n\n    cursor = candidate.end;\n\n    return true;\n  });\n};\n\n/**\n * @typedef {object} PreviewContext\n * @property {Map<string, number>} seenHashes Number of occurrences of each block hash so far, used\n * to make the keys unique across passes.\n * @property {Map<string, ComponentPreview>} previewMap Preview map to be populated.\n * @property {Map<string, ComponentPreview>} [previousPreviewMap] Preview map from the previous run,\n * if any.\n * @property {GetAsset} getAsset Asset getter passed to `toPreview()`.\n * @property {Map<string, ApiAsset[]>} assetMap Map to be populated with the assets each newly\n * computed preview has got with the asset getter, keyed by the preview’s key.\n */\n\n/**\n * Create the state shared by the previews computed in a single run.\n * @param {Map<string, ComponentPreview> | undefined} previousPreviewMap Preview map from the\n * previous run, if any.\n * @param {GetAsset} getAsset Asset getter passed to `toPreview()`.\n * @returns {PreviewContext} Context.\n */\nconst createPreviewContext = (previousPreviewMap, getAsset) => ({\n  seenHashes: new Map(),\n  previewMap: new Map(),\n  previousPreviewMap,\n  getAsset,\n  assetMap: new Map(),\n});\n\n/**\n * Compute the preview of a component instance, or reuse the one computed in the previous run, and\n * add it to the preview map.\n * @param {PreviewContext} context Preview context.\n * @param {object} args Arguments.\n * @param {EditorComponentDefinition} args.def Component definition.\n * @param {Record<string, any>} args.fieldProps Field values of the instance.\n * @param {string} args.source Markdown or HTML of the instance, which its key is computed from.\n * @returns {{ key: string, preview: ComponentPreview }} Key and preview.\n */\nconst addComponentPreview = (context, { def, fieldProps, source }) => {\n  const { seenHashes, previewMap, previousPreviewMap, getAsset, assetMap } = context;\n  const { toPreview } = def;\n  const baseHash = hashString(source);\n  const count = seenHashes.get(baseHash) ?? 0;\n  const key = count === 0 ? baseHash : `${baseHash}-${count}`;\n  let preview = previousPreviewMap?.get(key);\n\n  if (preview == null && toPreview) {\n    /** @type {ApiAsset[]} */\n    const assets = [];\n\n    preview = toPreview(\n      fieldProps,\n      (path, field) => {\n        const asset = getAsset(path, field);\n\n        if (asset) {\n          assets.push(asset);\n        }\n\n        return asset;\n      },\n      getComponentFieldList(def),\n    );\n\n    if (assets.length) {\n      assetMap.set(key, assets);\n    }\n  }\n\n  seenHashes.set(baseHash, count + 1);\n  previewMap.set(key, preview);\n\n  return { key, preview };\n};\n\n/**\n * Get the line break at the end of the line the given index is on, if the following line has any\n * text.\n * @param {string} string String.\n * @param {number} index Index.\n * @returns {number | undefined} Index of the line break, or `undefined` if there is no following\n * line with text.\n */\nconst getLineEndBeforeText = (string, index) => {\n  const lineEnd = string.indexOf('\\n', index);\n\n  return lineEnd >= 0 &&\n    string\n      .slice(lineEnd + 1)\n      .split('\\n', 1)[0]\n      .trim()\n    ? lineEnd\n    : undefined;\n};\n\n/**\n * Get the end of the line of an HTML block that a string preview substituted at the given range\n * starts, if the block would otherwise run on to the following lines, which would then be left\n * unparsed. That is when the preview starts a line with a block-level tag, or an opening or closing\n * tag alone on the line, the line is not within an HTML block already, and the following line has\n * any text. A blank line has to be added there to end the block.\n * @param {string} string String the preview is substituted in.\n * @param {object} args Arguments.\n * @param {string} args.preview String preview.\n * @param {number} args.index Start index of the match.\n * @param {number} args.end End index of the match (exclusive).\n * @returns {number | undefined} Index of the line break at the end of the line, or `undefined` if\n * no blank line is needed.\n */\nconst getHTMLBlockEnd = (string, { preview, index, end }) => {\n  const lineStart = string.lastIndexOf('\\n', index - 1) + 1;\n  const indent = string.slice(lineStart, index);\n\n  if (!/^ {0,3}$/.test(indent) || preview.includes('\\n\\n')) {\n    return undefined;\n  }\n\n  const [firstLine] = preview.split('\\n');\n  const lineEnd = getLineEndBeforeText(string, end);\n\n  const line =\n    indent +\n    firstLine +\n    (firstLine === preview ? string.slice(end, lineEnd ?? string.indexOf('\\n', end)) : '');\n\n  const previousLine = lineStart\n    ? string.slice(string.lastIndexOf('\\n', lineStart - 2) + 1, lineStart - 1)\n    : '';\n\n  return lineEnd !== undefined &&\n    startsHTMLBlock(line, { afterParagraph: !!previousLine.trim() }) &&\n    !isWithinHTMLBlock(string, lineStart)\n    ? lineEnd\n    : undefined;\n};\n\n/**\n * Substitute the given component matches in the string with their previews.\n * @param {PreviewContext} context Preview context.\n * @param {object} args Arguments.\n * @param {string} args.string String to process.\n * @param {ComponentMatch[]} args.matches Outermost matches found in the string.\n * @returns {{ string: string, regions: PreviewRegion[] }} The processed string, and the regions of\n * the substituted string previews, which may expose further component syntax.\n */\nconst substituteMatches = (context, { string, matches }) => {\n  /** @type {string[]} */\n  const chunks = [];\n  /** @type {PreviewRegion[]} */\n  const regions = [];\n  let cursor = 0;\n  let length = 0;\n  /**\n   * Index of the line break to be doubled to end the HTML block a string preview has started. See\n   * {@link getHTMLBlockEnd}.\n   * @type {number | undefined}\n   */\n  let blockEnd;\n\n  /**\n   * Add the text from the cursor to the given index, with a blank line at {@link blockEnd}.\n   * @param {number} index End index (exclusive).\n   */\n  const addText = (index) => {\n    let text = string.slice(cursor, index);\n\n    if (blockEnd !== undefined && blockEnd < index) {\n      text = `${string.slice(cursor, blockEnd)}\\n${string.slice(blockEnd, index)}`;\n      blockEnd = undefined;\n    }\n\n    chunks.push(text);\n    length += text.length;\n  };\n\n  matches.forEach(({ def, match, index, end }) => {\n    const fieldProps = def.fromBlock?.(match) ?? match.groups ?? {};\n    const { key, preview } = addComponentPreview(context, { def, fieldProps, source: match[0] });\n\n    addText(index);\n\n    // Replace the component syntax with a direct preview string or placeholder, depending on the\n    // type of the preview value. This allows simple text previews to be rendered directly without\n    // needing the `MutationObserver` to find and replace a placeholder element, while still\n    // supporting complex React element previews.\n    if (typeof preview === 'string') {\n      regions.push({\n        start: length,\n        end: length + preview.length,\n        values: collectStringValues(fieldProps),\n      });\n      chunks.push(preview);\n      length += preview.length;\n      blockEnd = getHTMLBlockEnd(string, { preview, index, end }) ?? blockEnd;\n    } else {\n      // Return a placeholder element with a unique key that can be used by the `MutationObserver`\n      // to find the correct location to render the React element preview. A `<span>` with its\n      // closing tag doesn’t start an HTML block.\n      const placeholder = `<span data-component-key=\"${key}\"></span>`;\n\n      chunks.push(placeholder);\n      length += placeholder.length;\n    }\n\n    // A block still open past this match ends at the end of the line the match ends on\n    if (blockEnd !== undefined && blockEnd < end) {\n      blockEnd = getLineEndBeforeText(string, end);\n    }\n\n    cursor = end;\n  });\n\n  addText(string.length);\n\n  return { string: chunks.join(''), regions };\n};\n\n/**\n * Process an HTML string by finding editor component instances with their `htmlSelector` and\n * `fromBlockHTML` options, computing their previews and replacing each instance with its string\n * preview or a placeholder `<span>` keyed to the preview map, like\n * {@link buildMarkdownWithPreviews} does for Markdown. The HTML is parsed into an inert template,\n * so nothing in it runs or loads. The outermost instance wins, as its content is part of it.\n * Components without HTML support or `toPreview()` are left out, and their HTML is rendered as is.\n * A string preview isn’t searched for nested components; an element preview can render its nested\n * content with `CMS.renderRichText()`.\n * @param {string} html The raw HTML field value.\n * @param {ResolvedEditorComponentDefinition[]} componentDefs The resolved component definitions.\n * @param {Map<string, ComponentPreview>} [previousPreviewMap] Preview map from the previous run.\n * @param {GetAsset} [getAsset] Asset getter passed to `toPreview()`.\n * @returns {{\n * markdown: string,\n * previewMap: Map<string, ComponentPreview>,\n * assetMap: Map<string, ApiAsset[]>,\n * }} The processed HTML string, a map of component keys to their preview values, and a map of\n * the keys of the previews computed in this run to the assets they’ve got with `getAsset`.\n */\nconst buildHTMLWithPreviews = (html, componentDefs, previousPreviewMap, getAsset = getNoAsset) => {\n  const defs = componentDefs.filter((def) => supportsHTML(def) && !!def.toPreview);\n  const context = createPreviewContext(previousPreviewMap, getAsset);\n  const { previewMap, assetMap } = context;\n\n  if (!defs.length) {\n    return { markdown: html, previewMap, assetMap };\n  }\n\n  const template = document.createElement('template');\n\n  template.innerHTML = html;\n\n  /**\n   * Replace the component instances among the descendants of the given node with their previews.\n   * @param {ParentNode} parent Parent node.\n   */\n  const replaceInstances = (parent) => {\n    [...parent.children].forEach((element) => {\n      /** @type {Record<string, any> | undefined} */\n      let fieldProps;\n\n      const def = defs.find((d) => {\n        fieldProps = element.matches(/** @type {string} */ (d.htmlSelector))\n          ? /** @type {NonNullable<EditorComponentDefinition['fromBlockHTML']>} */ (\n              d.fromBlockHTML\n            )(/** @type {HTMLElement} */ (element))\n          : undefined;\n\n        return !!fieldProps;\n      });\n\n      if (!def) {\n        replaceInstances(element);\n\n        return;\n      }\n\n      const { key, preview } = addComponentPreview(context, {\n        def,\n        fieldProps: /** @type {Record<string, any>} */ (fieldProps),\n        source: element.outerHTML,\n      });\n\n      if (typeof preview === 'string') {\n        // Parse the preview into an inert template as well\n        const previewTemplate = document.createElement('template');\n\n        previewTemplate.innerHTML = preview;\n        element.replaceWith(previewTemplate.content);\n      } else {\n        // A placeholder for the `MutationObserver` to render an element or React element preview\n        const placeholder = document.createElement('span');\n\n        placeholder.dataset.componentKey = key;\n        element.replaceWith(placeholder);\n      }\n    });\n  };\n\n  replaceInstances(template.content);\n\n  return { markdown: template.innerHTML, previewMap, assetMap };\n};\n\n/**\n * Process a Markdown string by extracting editor component instances, computing their previews and\n * replacing each match with a placeholder `<span>` keyed to the preview map. The built-in image\n * components are left to Marked, and component syntax within code is left as is.\n *\n * Components are matched outermost-first, so `toPreview()` always receives the raw block content.\n * Since a string preview may itself contain component syntax (typically the verbatim value of a\n * nested `richtext` field), the substituted previews are scanned again until no component is left\n * or {@link MAX_SUBSTITUTION_PASSES} is reached; only syntax that comes from a field value counts,\n * not any the preview template reproduces by itself. An element preview, on the other hand, can\n * render its nested content with `CMS.renderRichText()`, which runs this whole process recursively.\n * @param {string | undefined} currentValue The raw Markdown field value.\n * @param {ResolvedEditorComponentDefinition[]} componentDefs The resolved component definitions.\n * @param {Map<string, ComponentPreview>} [previousPreviewMap] Preview map from the previous run, if\n * any. Keys are content hashes, so an entry can be reused as long as the matched block is\n * unchanged. This avoids calling `toPreview()` again for every unmodified component on each\n * keystroke, which would orphan the DOM element and any component mounted on it in the case of an\n * element preview.\n * @param {GetAsset} [getAsset] Asset getter passed to `toPreview()`, which resolves a file path to\n * the asset in the context of the entry draft. Defaults to one that never finds an asset.\n * @param {RichTextValueFormat} [format] Format of the value. With `html`, the value is processed by\n * {@link buildHTMLWithPreviews} instead.\n * @returns {{\n * markdown: string,\n * previewMap: Map<string, ComponentPreview>,\n * assetMap: Map<string, ApiAsset[]>,\n * }} The processed Markdown string, a map of component keys to their precomputed preview values,\n * and a map of the keys of the previews computed in this run to the assets they’ve got with\n * `getAsset`, whose URL may still change.\n */\nexport const buildMarkdownWithPreviews = (\n  currentValue,\n  componentDefs,\n  previousPreviewMap,\n  getAsset = getNoAsset,\n  format = 'markdown',\n) => {\n  if (format === 'html') {\n    return buildHTMLWithPreviews(currentValue ?? '', componentDefs, previousPreviewMap, getAsset);\n  }\n\n  const context = createPreviewContext(previousPreviewMap, getAsset);\n  const { previewMap, assetMap } = context;\n  const value = currentValue ?? '';\n  const codeRanges = getCodeRanges(value);\n  // The Markdown of the built-in image components is left to Marked. Their previews are `<img>`\n  // HTML, which would show as text within code, and start an HTML block that leaves the following\n  // lines unparsed when the image is alone on a line, e.g. above a caption.\n  const defs = componentDefs.filter(({ id }) => !IMAGE_COMPONENT_IDS.includes(id));\n\n  let string = value.replace(GLOBAL_IMAGE_OR_LINKED_IMAGE_REGEX, (...args) =>\n    // The offset comes before the whole string and the named groups\n    isWithinRanges(args.at(-3), codeRanges) ? args[0] : encodeImageSrc(...args),\n  );\n\n  /** @type {PreviewRegion[] | undefined} */\n  let regions;\n\n  for (let pass = 0; pass < MAX_SUBSTITUTION_PASSES && defs.length; pass += 1) {\n    const matches = findOutermostMatches(string, defs, regions);\n\n    if (!matches.length) {\n      break;\n    }\n\n    const result = substituteMatches(context, { string, matches });\n\n    string = result.string;\n    regions = result.regions;\n\n    // Only a string preview can expose further component syntax\n    if (!regions.length) {\n      break;\n    }\n  }\n\n  return { markdown: string, previewMap, assetMap };\n};\n","import { parseInline } from 'marked';\nimport { isValidElement } from 'react';\n\nimport { mountReactNode } from '$lib/services/api/react-dom';\nimport { getNoAsset } from '$lib/services/contents/fields/rich-text/previews/components';\nimport { sanitizeRichTextHTML } from '$lib/services/contents/fields/rich-text/sanitize';\n\n/**\n * @import { ReactElement } from 'react';\n * @import { ResolvedEditorComponentDefinition } from '$lib/types/private';\n */\n\n/**\n * @typedef {string | HTMLElement | ReactElement | undefined} InlinePreview\n */\n\n/**\n * Get the preview of a pattern-based inline component shown within the text in the rich text\n * editor: the output of `toPreview`, or that of `toInline` as plain text if the former is missing\n * or returns another type of value. A function that throws, e.g. by reading a missing value, is\n * treated as if it returned nothing, so a broken component doesn’t break the editor.\n * @param {object} functions Functions of the component.\n * @param {ResolvedEditorComponentDefinition['toPreview']} [functions.toPreview] Function to convert\n * the component data to its preview.\n * @param {ResolvedEditorComponentDefinition['toBlock']} functions.toInline Function to convert the\n * component data to Markdown, which the resolved definition holds as `toBlock`.\n * @param {Record<string, any>} data Component data.\n * @returns {{ preview?: string | HTMLElement | ReactElement, text: string }} The preview, if any,\n * and the text to show otherwise, which is an empty string if `toInline` fails as well.\n */\nexport const getInlinePreview = ({ toPreview, toInline }, data) => {\n  /** @type {unknown} */\n  let preview;\n  let text = '';\n\n  try {\n    preview = toPreview?.(data, getNoAsset, undefined);\n  } catch {\n    preview = undefined;\n  }\n\n  if (typeof preview === 'string' || preview instanceof HTMLElement || isValidElement(preview)) {\n    return { preview: /** @type {string | HTMLElement | ReactElement} */ (preview), text };\n  }\n\n  try {\n    text = String(toInline(data) ?? '');\n  } catch {\n    //\n  }\n\n  return { text };\n};\n\n/**\n * Render the preview of a pattern-based inline component into the given element. A string is\n * parsed as inline Markdown, so `**bold**` or a link work as well as HTML, and always sanitized, as\n * the editor doesn’t know the field options. An `HTMLElement` is inserted as is, and receives an\n * `Unmount` event once it’s removed, like in the preview pane. A React element is mounted on the\n * element once `react-dom` has been loaded. Without a preview, the text is shown.\n * @param {HTMLElement} element Element to render the preview in.\n * @param {{ preview?: InlinePreview, text: string }} args Return value of\n * {@link getInlinePreview}.\n * @returns {() => void} Function to remove the preview, unmounting a React element or notifying an\n * `HTMLElement`.\n */\nexport const renderInlinePreview = (element, { preview, text }) => {\n  if (typeof preview === 'string') {\n    element.innerHTML = sanitizeRichTextHTML(/** @type {string} */ (parseInline(preview)));\n\n    return () => element.replaceChildren();\n  }\n\n  if (preview instanceof HTMLElement) {\n    element.replaceChildren(preview);\n\n    return () => {\n      element.replaceChildren();\n      preview.dispatchEvent(new CustomEvent('Unmount'));\n    };\n  }\n\n  if (preview) {\n    // `react-dom` is only loaded once a preview actually needs it\n    return mountReactNode(element, preview);\n  }\n\n  element.textContent = text;\n\n  return () => element.replaceChildren();\n};\n","<script>\n  import { onMount } from 'svelte';\n\n  import {\n    getInlinePreview,\n    renderInlinePreview,\n  } from '$lib/services/contents/fields/rich-text/components/inline-preview';\n  import { followReadonly } from '$lib/services/contents/fields/rich-text/components/utils';\n\n  /**\n   * @import { ResolvedEditorComponentDefinition } from '$lib/types/private';\n   * @import { InlineEditorComponentDefinition } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} componentName Rich text editor component name.\n   * @property {string} label Component label.\n   * @property {ResolvedEditorComponentDefinition['toPreview']} [toPreview] Function to convert the\n   * component data to its preview.\n   * @property {ResolvedEditorComponentDefinition['toBlock']} toInline Function to convert the\n   * component data to Markdown.\n   * @property {InlineEditorComponentDefinition['onEdit']} [onEdit] Function called when the\n   * component is clicked, returning its new data.\n   * @property {Record<string, any> | undefined} values Initial component data.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `change` event handler.\n   */\n\n  /** @type {Props} */\n  let {\n    componentName,\n    label,\n    toPreview,\n    toInline,\n    onEdit,\n    values,\n    onChange = () => undefined,\n  } = $props();\n\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n  /**\n   * Current component data. Initialized from the `values` prop once, then replaced with the result\n   * of `onEdit`, or with {@link setValues} by the node.\n   * @type {Record<string, any>}\n   */\n  // svelte-ignore state_referenced_locally\n  let data = $state.raw(values ?? {});\n  /**\n   * Whether the rich text field this component is in can’t be edited, e.g. with the `readonly`\n   * option or in a locale that follows the default one. It’s looked up through the DOM.\n   */\n  let readonly = $state(false);\n  /**\n   * Whether the `onEdit` function is in progress, so another click doesn’t call it again.\n   */\n  let editing = false;\n\n  /**\n   * Preview of the component shown within the text.\n   */\n  const preview = $derived(getInlinePreview({ toPreview, toInline }, data));\n\n  /**\n   * Get the wrapper element.\n   * @returns {HTMLElement | undefined} Wrapper.\n   */\n  export const getElement = () => wrapper;\n\n  /**\n   * Replace the component data, e.g. once an asynchronous `onInsert` function has resolved.\n   * @param {Record<string, any>} newValues New data.\n   */\n  export const setValues = (newValues) => {\n    data = newValues;\n  };\n\n  /**\n   * Call the developer’s `onEdit` function, and update the component with the data it returns, if\n   * any. An error thrown by the function is logged, leaving the component unchanged.\n   */\n  const edit = async () => {\n    if (!onEdit || readonly || editing) {\n      return;\n    }\n\n    editing = true;\n\n    try {\n      const result = await onEdit({ data });\n\n      if (result && typeof result === 'object') {\n        data = result;\n        onChange(new CustomEvent('update', { detail: result }));\n      }\n    } catch (ex) {\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      editing = false;\n    }\n  };\n\n  onMount(() =>\n    followReadonly(wrapper, (value) => {\n      readonly = value;\n    }),\n  );\n</script>\n\n<!-- The preview of the component, right within the text. It opens the developer’s own UI on click\nunless there is no `onEdit` function; it can still be focused then, to be removed with the Backspace\nor Delete key. The preview, e.g. a linked page name, is what assistive technology reads: a button\ntakes its name from it and the label as its description, while a group keeps it readable -->\n<!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n<span\n  bind:this={wrapper}\n  role={onEdit ? 'button' : 'group'}\n  class=\"component inline-pattern\"\n  class:editable={!!onEdit && !readonly}\n  contenteditable=\"false\"\n  tabindex=\"0\"\n  aria-label={onEdit ? undefined : label}\n  title={label}\n  data-component-name={componentName}\n  onclick={(event) => {\n    // Keep a link in the preview, e.g. a wikilink, from navigating away from the editor\n    event.preventDefault();\n    edit();\n  }}\n  onkeydown={(event) => {\n    // Activate the button with the Enter or Space key, like a native one. The Space key would\n    // otherwise reach the rich text editor\n    if (event.key === 'Enter' || event.key === ' ') {\n      event.preventDefault();\n      edit();\n    }\n\n    if (event.key === 'Backspace' || event.key === 'Delete') {\n      event.preventDefault();\n\n      if (!readonly) {\n        onChange(new CustomEvent('remove'));\n      }\n    }\n  }}\n>\n  <span role=\"none\" class=\"preview\" {@attach (element) => renderInlinePreview(element, preview)}\n  ></span>\n</span>\n\n<style>\n  .inline-pattern {\n    display: inline-flex;\n    align-items: baseline;\n    vertical-align: baseline;\n    border-radius: var(--sui-control-medium-border-radius);\n    padding-inline: 2px;\n    cursor: default;\n    -webkit-user-select: none;\n    user-select: none;\n\n    &.editable {\n      cursor: pointer;\n\n      &:hover {\n        background-color: var(--sui-hover-background-color);\n      }\n    }\n\n    &:focus {\n      outline: 2px solid var(--sui-primary-accent-color-translucent);\n      outline-offset: 1px;\n    }\n  }\n</style>\n","import { IMPORT_UPDATE_TAG } from '@sveltia/ui';\nimport {\n  $hasUpdateTag,\n  $createTextNode as createTextNode,\n  DecoratorNode,\n  getNearestEditorFromDOMNode,\n  $getNodeByKey as getNodeByKey,\n  HISTORY_MERGE_TAG,\n  SKIP_DOM_SELECTION_TAG,\n} from 'lexical';\nimport { flushSync, mount, tick, unmount } from 'svelte';\n\nimport EditorComponent from '$lib/components/contents/details/fields/rich-text/editor-component.svelte';\nimport InlinePatternComponent from '$lib/components/contents/details/fields/rich-text/inline-pattern-component.svelte';\nimport {\n  getSelectorTagNames,\n  isInlineComponentDef,\n  normalizeProps,\n  supportsHTML,\n} from '$lib/services/contents/fields/rich-text/components/utils';\nimport {\n  getComponentFieldList,\n  getNoAsset,\n} from '$lib/services/contents/fields/rich-text/previews/components';\n\n/**\n * @import {\n * DOMConversion,\n * DOMConversionMap,\n * DOMConversionOutput,\n * DOMExportOutput,\n * EditorConfig,\n * LexicalEditor,\n * NodeKey,\n * SerializedLexicalNode,\n * } from 'lexical';\n * @import { ReactElement } from 'react';\n * @import { ResolvedEditorComponentDefinition } from '$lib/types/private';\n */\n\nconst TAG_NAME_REGEX = /^<(?<tagName>[a-z]+)/i;\n/**\n * Mounted components, keyed by their element, so a node can hand the latest data to its component\n * in `updateDOM()`, which only receives the element.\n * @type {WeakMap<HTMLElement, { setValues: (values: Record<string, any>) => void }>}\n */\nconst mountedComponents = new WeakMap();\n\n/**\n * Get the name of the HTML tag that a component renders, so that the equivalent tag in a pasted\n * HTML document can be converted back to the component.\n * @param {string | HTMLElement | ReactElement | undefined} preview Return value of the component’s\n * `toPreview()` method, if any.\n * @param {string | undefined} block Return value of the component’s `toBlock()` method, if it\n * could be called.\n * @returns {string | undefined} Tag name, e.g. `img`, or `undefined` if it cannot be determined,\n * including when the preview is a React element.\n */\nconst getTagName = (preview, block) => {\n  // An element preview, e.g. an element with a Svelte or Vue component mounted on it. Duck typing\n  // is used here because the DOM globals are unavailable outside a browser context\n  if (preview && typeof preview === 'object' && 'localName' in preview) {\n    return /** @type {HTMLElement} */ (preview).localName;\n  }\n\n  if (typeof preview === 'string') {\n    return (\n      preview.trim().match(TAG_NAME_REGEX)?.groups?.tagName ??\n      (typeof block === 'string' ? block.trim().match(TAG_NAME_REGEX)?.groups?.tagName : undefined)\n    );\n  }\n\n  return undefined;\n};\n\n/**\n * Call a method of a component with empty field values, to learn the HTML tag it renders. A method\n * that needs the values can throw, e.g. by reading a property of `undefined`. The tag is then left\n * unknown, rather than the error breaking the editor, which creates the node class of every\n * registered component, whether an entry uses it or not.\n * @param {((props: Record<string, any>, ...args: any[]) => any) | undefined} method `toPreview()`\n * or `toBlock()`.\n * @param {any[]} [args] Other arguments, e.g. the asset getter and field list for `toPreview()`.\n * @returns {any} Return value, or `undefined` if the method is missing or has thrown.\n */\nconst callWithEmptyProps = (method, args = []) => {\n  try {\n    return method?.({}, ...args);\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Dynamically create a custom {@link DecoratorNode} class.\n * @param {ResolvedEditorComponentDefinition} componentDef Component definition passed with the\n * `CMS.registerEditorComponent()` API.\n * @returns {any} Custom node class.\n */\nexport const createCustomNodeClass = (componentDef) => {\n  const {\n    id: componentName,\n    label,\n    collapsed,\n    mode,\n    summary,\n    thumbnail,\n    fields,\n    toBlock,\n    toPreview,\n    htmlSelector,\n    fromBlockHTML,\n    toBlockHTML,\n    inlinePattern,\n  } = componentDef;\n\n  const inline = isInlineComponentDef(componentDef);\n  const htmlSupported = supportsHTML(componentDef);\n  // A pattern-based inline component has no fields to fill in from a pasted element, so it’s never\n  // imported from one\n  const guessTagName = !htmlSupported && !inlinePattern;\n\n  // The selector has been validated when the component was registered\n  const htmlTagNames = htmlSupported\n    ? /** @type {string[]} */ (getSelectorTagNames(/** @type {string} */ (htmlSelector)))\n    : [];\n\n  // Without the HTML syntax, guess the element from the preview to convert a pasted element\n  const preview = guessTagName\n    ? callWithEmptyProps(toPreview, [getNoAsset, getComponentFieldList(componentDef)])\n    : undefined;\n\n  const block = guessTagName ? callWithEmptyProps(toBlock) : undefined;\n  const tagName = guessTagName ? getTagName(preview, block) : undefined;\n\n  /**\n   * Get the field values of the component from the given element, using the `htmlSelector` and\n   * `fromBlockHTML` options.\n   * @param {HTMLElement} element Element.\n   * @returns {Record<string, any> | undefined} Values, or `undefined` if the element is not an\n   * instance of the component.\n   */\n  const getPropsFromElement = (element) =>\n    element.matches(/** @type {string} */ (htmlSelector))\n      ? /** @type {(element: HTMLElement) => Record<string, any> | undefined} */ (fromBlockHTML)(\n          element,\n        )\n      : undefined;\n\n  /**\n   * Genetic custom node.\n   * @augments {DecoratorNode<null>}\n   * @see https://lexical.dev/docs/concepts/nodes#extending-decoratornode\n   * @see https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/nodes/ImageNode.tsx\n   */\n  class CustomNode extends DecoratorNode {\n    /**\n     * Field properties.\n     * @type {Record<string, any> | undefined}\n     */\n    __props;\n\n    /**\n     * Text that was selected when a pattern-based inline component with the `onInsert` option\n     * was inserted from the toolbar, which the component replaces once `onInsert` has returned its\n     * data. It’s only set on the node created for the insertion, and not copied to a clone, so\n     * `onInsert` is called once.\n     * @type {string | undefined}\n     */\n    __selectedText;\n\n    /**\n     * Create a new {@link CustomNode} instance.\n     * @param {Record<string, any>} [props] Field properties.\n     * @param {NodeKey} [key] Node key.\n     */\n    constructor(props, key) {\n      super(key);\n      this.__props = props;\n    }\n\n    /**\n     * Get the node type.\n     * @returns {string} Type.\n     */\n    static getType() {\n      return componentName;\n    }\n\n    /**\n     * Whether the node is an inline node.\n     * @returns {boolean} Result.\n     */\n    isInline() {\n      return inline;\n    }\n\n    /**\n     * Clone the given node.\n     * @param {CustomNode} node Node.\n     * @returns {CustomNode} New node.\n     */\n    static clone(node) {\n      return new CustomNode(node.__props, node.__key);\n    }\n\n    /**\n     * Import JSON, as exported by {@link exportJSON}, e.g. when a component is pasted or moved by\n     * dragging. The base `updateFromJSON()` only restores Lexical’s own node state, so the field\n     * properties are read here.\n     * @param {SerializedLexicalNode & { props?: Record<string, any> }} serializedNode Input.\n     * @returns {CustomNode} New node.\n     */\n    static importJSON(serializedNode) {\n      return new CustomNode(serializedNode.props).updateFromJSON(serializedNode);\n    }\n\n    /**\n     * Export the node as JSON. The field properties are kept under a key of their own, so a field\n     * named `type` or `version` doesn’t clash with Lexical’s keys.\n     * @returns {SerializedLexicalNode & { props: Record<string, any> }} Output.\n     */\n    exportJSON() {\n      return {\n        props: normalizeProps(this.__props ?? {}),\n        type: componentName,\n        version: 1,\n      };\n    }\n\n    /**\n     * Create a DOM node.\n     * @param {EditorConfig} [_config] Editor configuration.\n     * @param {LexicalEditor} [lexicalEditor] Editor rendering the node. The reconciler passes it,\n     * but {@link exportDOM} doesn’t.\n     * @returns {HTMLElement} New element.\n     */\n    createDOM(_config, lexicalEditor) {\n      // Only a node the user has just added, e.g. with the toolbar or a paste, takes the focus. A\n      // node rendered when the editor loads a value, or when the editor is attached to its root\n      // element and renders the existing content again, doesn’t, as the focus would move away from\n      // where the user is and the editor would scroll to the component. The former update is\n      // tagged as an import, the latter as a history merge. The update tags can only be read now,\n      // while the reconciler is running\n      const isAddedByUser =\n        !!lexicalEditor && !$hasUpdateTag(IMPORT_UPDATE_TAG) && !$hasUpdateTag(HISTORY_MERGE_TAG);\n\n      const { __selectedText: selectedText } = this;\n      /** @type {HTMLElement} */\n      let wrapper;\n      /** @type {LexicalEditor | null} */\n      let editor = null;\n      /** @type {{ getElement: () => HTMLElement | undefined }} */\n      let component;\n      let destroyed = false;\n\n      /**\n       * Unmount the component exactly once, regardless of how many times cleanup is triggered.\n       */\n      const cleanup = () => {\n        /* v8 ignore next */\n        if (destroyed) {\n          return;\n        }\n\n        destroyed = true;\n        unmount(component);\n      };\n\n      /**\n       * Custom `Change` event handler.\n       * @param {CustomEvent} event `Change` event.\n       */\n      const onChange = async ({ type, detail }) => {\n        await tick();\n\n        editor ??= getNearestEditorFromDOMNode(wrapper);\n\n        // Save the currently focused element and selection to restore after the update, in case\n        // the parent Lexical editor takes the focus while updating the node.\n        const { activeElement } = document;\n        const activeEl = /** @type {HTMLElement | null} */ (activeElement);\n\n        const selection = activeEl?.matches('[contenteditable=\"true\"]')\n          ? window.getSelection()\n          : null;\n\n        const selectionRange =\n          selection && selection.rangeCount > 0 ? selection.getRangeAt(0).cloneRange() : null;\n\n        editor?.update(\n          () => {\n            if (type === 'update') {\n              try {\n                this.getWritable().__props = detail;\n              } catch {\n                //\n              }\n            }\n\n            if (type === 'remove') {\n              cleanup();\n              this.remove();\n            }\n          },\n          {\n            discrete: true,\n            // Leave the DOM selection alone while the component is edited. The parent editor\n            // would otherwise move it back to its own selection, if the user selected something in\n            // the parent before, and scroll to it\n            tag: type === 'update' ? SKIP_DOM_SELECTION_TAG : undefined,\n            /**\n             * Restore focus and selection after the Lexical update completes.\n             */\n            onUpdate: () => {\n              if (activeEl && document.body.contains(activeEl)) {\n                // Don’t scroll to the element, e.g. a nested rich text editor taller than the\n                // pane, whose top would be brought into view whenever the user pauses typing\n                activeEl.focus({ preventScroll: true });\n\n                if (selectionRange && selection) {\n                  selection.removeAllRanges();\n                  selection.addRange(selectionRange);\n                }\n              }\n            },\n          },\n        );\n      };\n\n      /**\n       * Get the data of a new pattern-based inline component with its `onInsert` function, then\n       * fill in the component, or restore the text it has replaced if the insertion is cancelled.\n       * The update is merged into the insertion in the history, so the whole insertion is undone at\n       * once.\n       * @param {string} replacedText Text the component has replaced.\n       */\n      const insertInlineComponent = async (replacedText) => {\n        /** @type {unknown} */\n        let data;\n\n        try {\n          // The text is only remembered for a component with the function\n          const { onInsert } = /** @type {Required<NonNullable<typeof inlinePattern>>} */ (\n            inlinePattern\n          );\n\n          data = await onInsert({ selectedText: replacedText });\n        } catch (error) {\n          // eslint-disable-next-line no-console\n          console.error(error);\n        }\n\n        editor ??= getNearestEditorFromDOMNode(wrapper);\n\n        editor?.update(\n          () => {\n            const node = /** @type {CustomNode | null} */ (getNodeByKey(this.getKey()));\n\n            // A component removed while waiting takes its element out of the editor, which then\n            // isn’t found above, so this is only a safeguard\n            /* v8 ignore next 3 */\n            if (!node) {\n              return;\n            }\n\n            if (data && typeof data === 'object') {\n              node.getWritable().__props = /** @type {Record<string, any>} */ (data);\n              node.selectNext(0, 0);\n            } else if (replacedText) {\n              const textNode = createTextNode(replacedText);\n\n              node.replace(textNode);\n              textNode.select(0, replacedText.length);\n            } else {\n              node.selectPrevious();\n              node.remove();\n            }\n          },\n          { discrete: true, tag: HISTORY_MERGE_TAG },\n        );\n\n        // `onInsert` may have opened a dialog, which has taken the focus\n        editor?.focus();\n      };\n\n      component = inlinePattern\n        ? mount(InlinePatternComponent, {\n            target: document.createElement('div'),\n            props: {\n              componentName,\n              // `getComponentDef()` falls back to the registered name if the label is omitted\n              label: /** @type {string} */ (label),\n              toPreview,\n              // The resolved definition holds the component’s `toInline` function as `toBlock`\n              toInline: toBlock,\n              onEdit: inlinePattern.onEdit,\n              values: this.__props,\n              onChange,\n            },\n          })\n        : mount(EditorComponent, {\n            target: document.createElement('div'),\n            props: {\n              componentName,\n              // `getComponentDef()` falls back to the registered name if the label is omitted\n              label: /** @type {string} */ (label),\n              collapsed,\n              mode,\n              inline,\n              summary,\n              thumbnail,\n              fields,\n              values: this.__props,\n              onChange,\n            },\n          });\n\n      // Wait for the component to be mounted\n      // @see https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes\n      flushSync();\n\n      wrapper = /** @type {HTMLElement} */ (component.getElement());\n\n      mountedComponents.set(wrapper, /** @type {any} */ (component));\n\n      window.requestAnimationFrame(() => {\n        // Lexical inserts the element as soon as it’s created, so one that’s still detached won’t\n        // ever be rendered, e.g. an element exported to copy the node to the clipboard, or a node\n        // removed right after it was created\n        const root = wrapper.isConnected ? wrapper.closest('[data-lexical-editor]') : null;\n\n        if (!root) {\n          cleanup();\n\n          return;\n        }\n\n        if (inlinePattern) {\n          // A pattern-based inline component leaves the caret in the text after it, where Lexical\n          // has put it. One inserted from the toolbar with the `onInsert` option gets its data now\n          if (isAddedByUser && selectedText !== undefined) {\n            insertInlineComponent(selectedText);\n          }\n        } else if (isAddedByUser && wrapper.closest('[role=\"textbox\"][aria-readonly=\"false\"]')) {\n          // Focus the wrapper of a new component if the parent field is editable. This is necessary\n          // because `i18n: duplicate` field is rendered as a read-only textbox in non-default\n          // locales, which may steal focus from the wrapper of the default locale\n          wrapper.focus();\n        }\n\n        // Clean up when the parent field is unmounted (e.g. navigating away).\n        wrapper.closest('.field')?.addEventListener('Unmount', cleanup, { once: true });\n\n        // Clean up when the Lexical node is removed directly (e.g. keyboard Delete, undo) without\n        // going through onChange. Lexical has no destroyDOM() hook, so watch the DOM. The whole\n        // editor is watched rather than the parent element: an inline component sits in a\n        // paragraph, which can be removed along with it while its own children stay untouched.\n        // A component left mounted would keep writing its field values to the draft, where they\n        // would fail validation with no field to show the errors in\n        const observer = new MutationObserver(() => {\n          if (!wrapper.isConnected) {\n            cleanup();\n            observer.disconnect();\n          }\n        });\n\n        observer.observe(root, { childList: true, subtree: true });\n      });\n\n      return wrapper;\n    }\n\n    /**\n     * Export the node as a DOM node: the HTML written with the `toBlockHTML` option, which is saved\n     * in a RichText field with the `html` format, and copied to the clipboard in any field. Without\n     * the option, the component’s editor UI is exported instead.\n     * @returns {DOMExportOutput} Output.\n     */\n    exportDOM() {\n      if (!toBlockHTML) {\n        return { element: this.createDOM() };\n      }\n\n      const output = /** @type {unknown} */ (toBlockHTML(normalizeProps(this.__props ?? {})));\n\n      if (output && typeof output === 'object') {\n        return { element: /** @type {HTMLElement} */ (output) };\n      }\n\n      const template = document.createElement('template');\n\n      // Anything other than a string, e.g. `undefined` for an empty component, exports nothing\n      template.innerHTML = typeof output === 'string' ? output : '';\n\n      return { element: template.content };\n    }\n\n    /**\n     * Import a DOM node. With the `htmlSelector` option, an element the selector matches is\n     * converted to the component, e.g. when HTML is loaded in a RichText field with the `html`\n     * format or pasted to the editor. Otherwise, a pasted element of the type the preview renders\n     * is.\n     * @returns {DOMConversionMap} Conversion map.\n     */\n    static importDOM() {\n      /** @type {DOMConversionMap} */\n      const conversionMap = {};\n\n      if (htmlSupported) {\n        htmlTagNames.forEach((name) => {\n          /**\n           * Conversion map item.\n           * @param {HTMLElement} element Element.\n           * @returns {DOMConversion | null} Conversion, or `null` if the element is not an\n           * instance of the component.\n           */\n          conversionMap[name] = (element) => {\n            const props = getPropsFromElement(element);\n\n            if (!props) {\n              return null;\n            }\n\n            return {\n              /**\n               * Conversion.\n               * @returns {DOMConversionOutput} Output.\n               */\n              conversion: () => ({\n                node: new CustomNode(props),\n                // The content of the element is part of the component\n                // eslint-disable-next-line jsdoc/require-jsdoc\n                after: () => [],\n              }),\n              // Take priority over Lexical’s own conversions, e.g. a link\n              priority: 4,\n            };\n          };\n        });\n\n        return conversionMap;\n      }\n\n      if (tagName) {\n        /**\n         * Conversion map item.\n         * @returns {DOMConversion} Conversion.\n         */\n        conversionMap[tagName] = () => ({\n          /**\n           * Conversion.\n           * @param {HTMLElement} element Element.\n           * @returns {DOMConversionOutput} Output.\n           */\n          conversion: (element) => ({\n            node: new CustomNode(\n              Object.fromEntries(\n                fields.map(({ name }) => [\n                  name,\n                  /** @type {Record<string, any>} */ (element)[name] ?? '',\n                ]),\n              ),\n            ),\n          }),\n          priority: 3,\n        });\n      }\n\n      return conversionMap;\n    }\n\n    /**\n     * Update the DOM. A component shows the data of the latest node, which changes when a field is\n     * edited, `onInsert` or `onEdit` returns data, or the change is undone or redone; the element\n     * is kept, and the component is told about the data instead.\n     * @param {CustomNode} prevNode Previous version of the node.\n     * @param {HTMLElement} dom Element created with {@link createDOM}.\n     * @returns {boolean} Whether to create the element again, which is never needed.\n     */\n    updateDOM(prevNode, dom) {\n      if (prevNode.__props !== this.__props) {\n        mountedComponents.get(dom)?.setValues(this.__props ?? {});\n      }\n\n      return false;\n    }\n  }\n\n  return CustomNode;\n};\n","import { createInlineMatcher } from '$lib/services/contents/fields/rich-text/components/inline-pattern';\nimport {\n  isInlineComponentDef,\n  normalizeProps,\n} from '$lib/services/contents/fields/rich-text/components/utils';\n\n/**\n * @import { LexicalNode } from 'lexical';\n * @import {\n * MultilineElementTransformer,\n * TextMatchTransformer,\n * Transformer,\n * } from '@lexical/markdown';\n * @import { ResolvedEditorComponentDefinition } from '$lib/types/private';\n */\n\n/**\n * Create a singleline/inline or multiline transformer for the given component definition.\n * @param {object} args Arguments.\n * @param {ResolvedEditorComponentDefinition} args.componentDef Component definition passed with the\n * `CMS.registerEditorComponent()` API.\n * @param {any} args.CustomNode Lexical node class implementation.\n * @returns {Transformer} Transformer.\n * @see https://decapcms.org/docs/custom-widgets/#registereditorcomponent\n * @see https://sveltiacms.app/en/docs/api/editor-components\n * @see https://lexical.dev/docs/packages/lexical-markdown#transformers\n * @see https://lexical.dev/docs/api/modules/lexical_markdown\n * @see https://github.com/sveltia/sveltia-cms/issues/410\n * @see https://github.com/decaporg/decap-cms/issues/1044\n * @see https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/plugins/MarkdownTransformers/index.ts#L75-L97\n * @see https://github.com/facebook/lexical/blob/main/packages/lexical-markdown/src/MarkdownTransformers.ts#L81-L148\n * @see https://github.com/facebook/lexical/blob/main/packages/lexical-markdown/src/MarkdownTransformers.ts#L376-L457\n * @see https://github.com/facebook/lexical/blob/main/packages/lexical-markdown/src/__tests__/unit/LexicalMarkdown.test.ts#L86-L115\n * @see https://github.com/facebook/lexical/blob/main/packages/lexical-markdown/src/__tests__/unit/LexicalMarkdown.test.ts#L117-L224\n */\nexport const createTransformer = ({ componentDef, CustomNode }) => {\n  const { id: componentName, pattern, fromBlock, toBlock, inlinePattern } = componentDef;\n  const nonGlobalPattern = new RegExp(pattern.source, pattern.flags.replace('g', ''));\n  /**\n   * Get node properties from the given regex match array.\n   * @param {RegExpMatchArray} matchArray Match array.\n   * @returns {Record<string, any>} Properties.\n   */\n  const getProps = (matchArray) => fromBlock?.(matchArray) ?? matchArray.groups ?? {};\n  /**\n   * Whether the given node is an instance of {@link CustomNode}.\n   * @param {LexicalNode} node Node.\n   * @returns {boolean} Result.\n   */\n  const isCustomNode = (node) => node instanceof CustomNode && node.getType() === componentName;\n\n  /**\n   * Convert the given node to Markdown.\n   * @param {LexicalNode} node Node.\n   * @returns {string | null} Markdown string.\n   */\n  const exportNode = (node) => {\n    if (isCustomNode(node)) {\n      return toBlock(normalizeProps(/** @type {any} */ (node).__props ?? {}));\n    }\n\n    return null;\n  };\n\n  if (!isInlineComponentDef(componentDef)) {\n    return /** @type {MultilineElementTransformer} */ ({\n      /* eslint-disable jsdoc/require-jsdoc */\n      type: 'multiline-element',\n      dependencies: [CustomNode],\n      // Match every line to check for a multiline pattern. It’s not great for performance, but\n      // (part of) the developer-defined `pattern` cannot be used because it can be complex\n      regExpStart: /^./,\n      regExpEnd: { optional: true, regExp: /.$/ },\n      handleImportAfterStartMatch: ({ lines, rootNode, startLineIndex }) => {\n        const fullString = lines.slice(startLineIndex).join('\\n');\n        const [matchString] = fullString.match(nonGlobalPattern) ?? [];\n\n        if (!matchString || !fullString.startsWith(matchString)) {\n          return null;\n        }\n\n        const matchArray = matchString.match(nonGlobalPattern);\n        // A newline at the end of the match only ends its last line\n        const matchLines = matchString.replace(/\\n$/, '').split('\\n');\n        const endLineIndex = startLineIndex + matchLines.length - 1;\n\n        // The node replaces every line the match spans, so leave a match followed by any text on\n        // its last line as text, like one preceded by text on its first line, rather than drop that\n        // text, e.g. ` trailing` in `<aside>Note</aside> trailing`. The lines then round-trip as is\n        if (lines[endLineIndex].slice(/** @type {string} */ (matchLines.at(-1)).length).trim()) {\n          return null;\n        }\n\n        if (!matchArray) {\n          // this should not happen\n          return [false, endLineIndex];\n        }\n\n        rootNode.append(new CustomNode(getProps(matchArray)));\n\n        return [true, endLineIndex];\n      },\n      // The node is created on import by `handleImportAfterStartMatch` above. `false` also makes\n      // the Markdown shortcuts skip the transformer, which would otherwise remove the first\n      // character of a line typed with a space or Enter after it, as `regExpStart` matches any\n      // character\n      replace: () => false,\n      export: exportNode,\n      /* eslint-enable jsdoc/require-jsdoc */\n    });\n  }\n\n  return /** @type {TextMatchTransformer} */ ({\n    /* eslint-disable jsdoc/require-jsdoc */\n    type: 'text-match',\n    dependencies: [CustomNode],\n    // A pattern-based inline component is only matched where its trigger text is found, if any\n    importRegExp: inlinePattern\n      ? createInlineMatcher(nonGlobalPattern, inlinePattern)\n      : nonGlobalPattern,\n    regExp: nonGlobalPattern,\n    replace: (textNode, matchArray) => {\n      textNode.replace(new CustomNode(getProps(matchArray)));\n    },\n    export: exportNode,\n    /* eslint-enable jsdoc/require-jsdoc */\n  });\n};\n","import { $getSelection as getSelection } from 'lexical';\n\nimport { createCustomNodeClass } from '$lib/components/contents/details/fields/rich-text/custom-node';\nimport { createTransformer } from '$lib/services/contents/fields/rich-text/components/transformers';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { LexicalNode } from 'lexical';\n * @import { Transformer } from '@lexical/markdown';\n * @import { ResolvedEditorComponentDefinition } from '$lib/types/private';\n */\n\n/**\n * Custom Lexical node features.\n * @typedef {object} LexicalNodeFeatures\n * @property {any} node Lexical node class implementation.\n * @property {(props?: Record<string, any>) => LexicalNode} createNode Function to create a new node\n * instance.\n * @property {Transformer} transformer Node transformer.\n */\n\n/**\n * Cache the class and related features to avoid a Lexical error saying “Type ... In node CustomNode\n * does not match registered node CustomNode with the same type”.\n * @type {Map<string, LexicalNodeFeatures>}\n */\nexport const featureCacheMap = new Map();\n\n/**\n * Dynamically create a custom {@link DecoratorNode} class and related features for the Lexical\n * editor to enable support for rich text editor components.\n * @param {ResolvedEditorComponentDefinition} componentDef Component definition passed with the\n * `CMS.registerEditorComponent()` API.\n * @returns {LexicalNodeFeatures} The {@link CustomNode} class, a method to create a new node, and\n * the transformer definition.\n * @see https://decapcms.org/docs/custom-widgets/#registereditorcomponent\n * @see https://sveltiacms.app/en/docs/api/editor-components\n */\nexport const createLexicalNodeFeatures = (componentDef) => {\n  const CustomNode = createCustomNodeClass(componentDef);\n\n  return {\n    node: CustomNode,\n    /**\n     * Create a new node. A pattern-based inline component with the `onInsert` option, created\n     * without data when it’s inserted from the toolbar, remembers the selected text it replaces,\n     * which `onInsert` receives. The function runs within the editor update that inserts the node,\n     * where the selection can still be read.\n     * @param {Record<string, any>} [props] Field properties.\n     * @returns {LexicalNode} Node.\n     */\n    createNode: (props) => {\n      const node = new CustomNode(props);\n\n      if (!props && componentDef.inlinePattern?.onInsert) {\n        node.__selectedText = getSelection()?.getTextContent() ?? '';\n      }\n\n      return node;\n    },\n    transformer: createTransformer({ componentDef, CustomNode }),\n  };\n};\n\n/**\n * Text editor component implementation.\n */\nexport class EditorComponent {\n  /**\n   * Create an `EditorComponent` instance.\n   * @param {ResolvedEditorComponentDefinition} componentDef Component definition passed with the\n   * `CMS.registerEditorComponent()` API.\n   */\n  constructor(componentDef) {\n    const features = getOrCreate(featureCacheMap, componentDef.id, () =>\n      createLexicalNodeFeatures(componentDef),\n    );\n\n    Object.assign(this, { ...componentDef, ...features });\n  }\n}\n","import { getDroppedFileDestination } from '$lib/services/contents/fields/file/resources';\nimport { getPreferredLibraryNames } from '$lib/services/integrations/media-libraries/options';\n\n/**\n * @import { EditorComponentDefinition, ImageField } from '$lib/types/public';\n * @import { MediaFieldAssetOptions } from '$lib/services/contents/fields/file/resources';\n * @import { ImageEntry } from '$lib/services/contents/fields/rich-text/images';\n */\n\n/**\n * @typedef {object} SortedImages\n * @property {ImageEntry[]} inlineImages Images inserted right away: remote images linked by their\n * URL, and files saved to the repository along with the entry.\n * @property {File[]} uploadFiles Files to be uploaded to a cloud storage service in the Select\n * Assets dialog, which asks for the credentials if needed.\n * @property {boolean} rejected Whether some files have been left out, as no location can take them.\n */\n\n/**\n * Get the `src` field of the image component, which holds the media library options that apply to\n * images dropped or pasted into the rich text editor.\n * @param {EditorComponentDefinition | undefined} component Image component.\n * @returns {ImageField | undefined} Field configuration.\n */\nexport const getImageSrcFieldConfig = (component) =>\n  /** @type {ImageField | undefined} */ (component?.fields?.find(({ name }) => name === 'src'));\n\n/**\n * Sort the images dropped or pasted into the rich text editor by how they’re inserted. A file goes\n * to the location marked with the `default` option, so it’s not saved to the repository when it\n * should go to a cloud storage service, or when the repository is disabled.\n * @param {object} args Arguments.\n * @param {ImageEntry[]} args.images Images.\n * @param {ImageField | undefined} args.srcFieldConfig Configuration of the image component’s `src`\n * field.\n * @param {MediaFieldAssetOptions} args.assetOptions Asset options for the field.\n * @returns {SortedImages} Sorted images.\n * @see https://github.com/sveltia/sveltia-cms/issues/1172\n */\nexport const sortDroppedImages = ({ images, srcFieldConfig, assetOptions }) => {\n  const { enabled, folder, cloudServiceEntries } = assetOptions;\n\n  const { destination } = getDroppedFileDestination({\n    repositoryAvailable: enabled && !!folder,\n    cloudServiceEntries,\n    preferredLibraryNames: getPreferredLibraryNames(srcFieldConfig),\n  });\n\n  if (destination === 'repository') {\n    return { inlineImages: images, uploadFiles: [], rejected: false };\n  }\n\n  const files = images.flatMap(({ file }) => file ?? []);\n\n  return {\n    inlineImages: images.filter(({ file }) => !file),\n    uploadFiles: destination ? files : [],\n    rejected: !destination && !!files.length,\n  };\n};\n","import { getDateTimeParts } from '@sveltia/utils/datetime';\nimport { getPathInfo } from '@sveltia/utils/file';\n\nimport { isEquivalentFileExtension } from '$lib/services/utils/file';\nimport {\n  RASTER_IMAGE_EXTENSION_REGEX,\n  SUPPORTED_IMAGE_TYPES,\n  VECTOR_IMAGE_EXTENSION_REGEX,\n} from '$lib/services/utils/media/image';\nimport mime from '$lib/services/utils/mime';\nimport { decodeURIComponentSafely } from '$lib/services/utils/url';\n\n/**\n * An image to be inserted into the rich text editor.\n * @typedef {object} ImageEntry\n * @property {File} [file] Image file to be uploaded. `undefined` for a remote image that is linked\n * rather than downloaded.\n * @property {string} [src] Image URL. Used when there is no file to upload.\n * @property {string} [alt] Alternative text.\n */\n\n/**\n * Regular expression matching a base64-encoded image data URL, capturing its MIME type.\n */\nconst DATA_URL_REGEX = /^data:(?<type>image\\/.+?);base64,.+/;\n/**\n * The name browsers give to an image pasted from the clipboard, which says nothing about the image.\n */\nconst GENERIC_PASTED_FILE_NAME = 'image.png';\n\n/**\n * Check whether the given file name has a known image extension.\n * @param {string} name File name.\n * @returns {boolean} Result.\n */\nconst hasImageExtension = (name) =>\n  RASTER_IMAGE_EXTENSION_REGEX.test(name) || VECTOR_IMAGE_EXTENSION_REGEX.test(name);\n\n/**\n * Get a file name made of the current date and time, for an image that has no meaningful name of\n * its own, e.g. `20260912-103000.png`.\n * @param {string} extension File extension without a dot.\n * @param {string} [suffix] Suffix to be added before the extension, e.g. `-2`.\n * @returns {string} File name.\n */\nexport const getTimestampFileName = (extension, suffix = '') => {\n  const { year, month, day, hour, minute, second } = getDateTimeParts();\n\n  return `${year}${month}${day}-${hour}${minute}${second}${suffix}.${extension}`;\n};\n\n/**\n * Get the name of a pasted image file from the URL of the remote image it was copied from. The\n * last path segment is decoded, and its extension is replaced to match the file’s MIME type, which\n * can differ from the remote image’s: a browser typically puts a PNG image on the clipboard,\n * whatever the format of the image copied.\n * @param {string} url Remote image URL starting with `http:` or `https:`.\n * @param {string} type MIME type of the pasted file, one of the supported image types.\n * @returns {string | undefined} File name, e.g. `my photo.png` for `/my%20photo.jpg`. `undefined`\n * if the URL doesn’t end with a file name that has an image extension.\n */\nconst getRemoteImageFileName = (url, type) => {\n  const name = decodeURIComponentSafely(\n    // `split()` always yields at least one segment, so `pop()` never returns `undefined`\n    /** @type {string} */ (new URL(url).pathname.split('/').pop()),\n  );\n\n  if (!hasImageExtension(name)) {\n    return undefined;\n  }\n\n  const { filename, extension } = getPathInfo(name);\n  // Every supported image type has a known extension\n  const typeExtension = /** @type {string} */ (mime.getExtension(type));\n\n  return isEquivalentFileExtension(extension, typeExtension)\n    ? name\n    : `${filename}.${typeExtension}`;\n};\n\n/**\n * Parse the given HTML and find the first image in it.\n * @param {string} html HTML string.\n * @returns {HTMLImageElement | null} Image element, if any.\n */\nconst findImageInHTML = (html) =>\n  new DOMParser().parseFromString(html, 'text/html').querySelector('img');\n\n/**\n * Get the images pasted into the rich text editor. A remote image copied within the browser comes\n * with both the file and HTML holding an `<img>`, so the file name and alternative text are scraped\n * from the HTML; the event is stopped in that case, so the editor doesn’t paste the HTML as well.\n * Images pasted as local files are used as they are. Either way, a file that has the generic name\n * browsers give to pasted images is renamed after the current date and time.\n * @param {ClipboardEvent} event `paste` event.\n * @returns {Promise<ImageEntry[]>} Images. Empty if nothing pasted is an image.\n */\nexport const getPastedImages = async (event) => {\n  const { clipboardData } = event;\n  const pastedItems = clipboardData?.items;\n\n  if (!pastedItems) {\n    return [];\n  }\n\n  /** @type {ImageEntry[]} */\n  let images = [];\n\n  const fileIndex = [...pastedItems].findIndex(\n    ({ kind, type }) => kind === 'file' && SUPPORTED_IMAGE_TYPES.includes(type),\n  );\n\n  const htmlIndex = [...pastedItems].findIndex(\n    ({ kind, type }) => kind === 'string' && type === 'text/html',\n  );\n\n  if (fileIndex > -1 && htmlIndex > -1) {\n    const file = pastedItems[fileIndex].getAsFile();\n\n    if (!file) {\n      return [];\n    }\n\n    // Clear the clipboard to prevent the editor from pasting the HTML\n    pastedItems.clear();\n    event.stopPropagation();\n\n    let alt = '';\n    let fileName = file.name;\n\n    /** @type {HTMLImageElement | null} */\n    const img = await new Promise((resolve) => {\n      pastedItems[htmlIndex].getAsString((str) => {\n        resolve(findImageInHTML(str));\n      });\n    });\n\n    if (img) {\n      alt = img.alt;\n\n      if (/^https?:/.test(img.src)) {\n        fileName = getRemoteImageFileName(img.src, file.type) ?? fileName;\n      }\n    }\n\n    images = [{ file: new File([file], fileName, { type: file.type }), alt }];\n  } else {\n    images = [...clipboardData.files]\n      .filter(({ type }) => SUPPORTED_IMAGE_TYPES.includes(type))\n      .map((file) => ({ file }));\n  }\n\n  return images.map(({ file, alt }, index) => {\n    if (file?.name === GENERIC_PASTED_FILE_NAME) {\n      const suffix = images.length > 1 ? `-${index + 1}` : '';\n\n      file = new File([file], getTimestampFileName('png', suffix), { type: file.type });\n    }\n\n    return { file, alt };\n  });\n};\n\n/**\n * Get the images dropped onto the rich text editor. Local files are used as they are. A remote\n * image dragged from another page comes as HTML holding an `<img>` rather than a file, so its\n * `src` and `alt` are used to link it instead; the image is only downloaded when the `src` is a\n * data URL, because fetching it from another site would most likely fail due to its CORS policy.\n * @param {DragEvent} event `drop` event.\n * @returns {Promise<ImageEntry[]>} Images. Empty if nothing dropped is an image, or the dropped\n * data URL couldn’t be read.\n */\nexport const getDroppedImages = async (event) => {\n  const { dataTransfer } = event;\n  const droppedFiles = dataTransfer?.files;\n\n  if (droppedFiles?.length) {\n    return [...droppedFiles]\n      .filter(({ type }) => SUPPORTED_IMAGE_TYPES.includes(type))\n      .map((file) => ({ file }));\n  }\n\n  const html = dataTransfer?.getData('text/html');\n  const img = html ? findImageInHTML(html) : null;\n\n  if (!img) {\n    return [];\n  }\n\n  const { src, alt } = img;\n  const type = src.match(DATA_URL_REGEX)?.groups?.type ?? '';\n  /** @type {File | undefined} */\n  let file = undefined;\n\n  if (SUPPORTED_IMAGE_TYPES.includes(type)) {\n    try {\n      const blob = await (await fetch(src)).blob();\n      // Drop the structured syntax suffix, e.g. `svg+xml` → `svg`\n      const extension = type.split('/')[1].replace(/\\+.*$/, '');\n\n      file = new File([blob], getTimestampFileName(extension), { type });\n    } catch {\n      return [];\n    }\n  }\n\n  return [{ file, src, alt }];\n};\n","<!--\n  @component\n  Implement the editor for a Markdown/RichText field.\n  @see https://decapcms.org/docs/widgets/#Markdown\n  @see https://sveltiacms.app/en/docs/fields/richtext\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, TextEditor, Toast } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import {\n    $createParagraphNode as createParagraphNode,\n    getNearestEditorFromDOMNode,\n    $insertNodes as insertNodes,\n  } from 'lexical';\n\n  import SelectAssetsDialog from '$lib/components/assets/browser/select-assets-dialog.svelte';\n  import { EditorComponent } from '$lib/components/contents/details/fields/rich-text/custom-node-features';\n  import { cmsConfig } from '$lib/services/config';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getFieldValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import {\n    getFieldEditorContext,\n    isInEditorComponent,\n  } from '$lib/services/contents/editor/field-context';\n  import { trackPendingWhile } from '$lib/services/contents/editor/pending.svelte';\n  import { getField } from '$lib/services/contents/entry/fields';\n  import { processResource } from '$lib/services/contents/fields/file/process';\n  import {\n    getMediaFieldAssetOptions,\n    processResources,\n  } from '$lib/services/contents/fields/file/resources';\n  import {\n    DEFAULT_BUTTONS,\n    DEFAULT_MODES,\n    getValueFormat,\n    NODE_NAME_MAP,\n  } from '$lib/services/contents/fields/rich-text';\n  import { IMAGE_COMPONENT_IDS } from '$lib/services/contents/fields/rich-text/components/definitions';\n  import {\n    getImageSrcFieldConfig,\n    sortDroppedImages,\n  } from '$lib/services/contents/fields/rich-text/image-uploads';\n  import {\n    getDroppedImages,\n    getPastedImages,\n  } from '$lib/services/contents/fields/rich-text/images';\n  import {\n    getAvailableComponentDefs,\n    getEditorComponentNames,\n    getRootFieldName,\n    getStaleExtraValueKeys,\n    getToolbarButtons,\n    resolveAllowNestedComponents,\n  } from '$lib/services/contents/fields/rich-text/options';\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n  import { syncValues, watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { ImageEntry } from '$lib/services/contents/fields/rich-text/images';\n   * @import { FieldEditorProps, SelectedResource } from '$lib/types/private';\n   * @import {\n   * EditorComponentDefinition,\n   * ImageField,\n   * MarkdownField,\n   * RichTextField,\n   * } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {MarkdownField | RichTextField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const defaultConfig = cmsConfig.current?.field_defaults?.richtext ?? {};\n  /* v8 ignore start -- the editor is always rendered within a field editor */\n  const { parentComponentNames, valueStoreKey } = getFieldEditorContext();\n  /* v8 ignore stop */\n  const inEditorComponent = isInEditorComponent(valueStoreKey);\n  const componentName = parentComponentNames.at(-1);\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n  } = $props();\n\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n  let inputValue = $state('');\n\n  let cleanupTimeout = 0;\n  /**\n   * Whether the editor has yet to write a change made by the user back to {@link inputValue}.\n   */\n  let pending = $state(false);\n  /**\n   * Number of dropped or pasted image batches being processed before they’re inserted.\n   */\n  let processingImages = $state(0);\n  let showSelectAssetsDialog = $state(false);\n  /**\n   * Files dropped or pasted into the editor, to be uploaded to a cloud storage service in the\n   * Select Assets dialog.\n   * @type {File[]}\n   */\n  let pendingFiles = $state([]);\n  /**\n   * Inserts the images uploaded in the Select Assets dialog into the editor the files were dropped\n   * or pasted into.\n   * @type {((resources: SelectedResource[]) => Promise<void>) | undefined}\n   */\n  let insertUploadedImages = undefined;\n  /** Whether dropped or pasted files have been rejected, as no location can take them. */\n  let filesRejected = $state(false);\n\n  const {\n    // Field type-specific options\n    modes: _modes = defaultConfig.modes ?? [...DEFAULT_MODES],\n    buttons: _buttons = defaultConfig.buttons ?? [...DEFAULT_BUTTONS],\n    use_emoji_autocomplete: useEmojiAutocomplete = defaultConfig.use_emoji_autocomplete ?? true,\n    use_markdown_shortcuts: useMarkdownShortcuts = defaultConfig.use_markdown_shortcuts ?? true,\n    minimal = defaultConfig.minimal ?? false,\n    multiline = defaultConfig.multiline ?? true,\n  } = $derived(fieldConfig);\n  const format = $derived(getValueFormat(fieldConfig));\n  const modes = $derived(_modes.map((name) => NODE_NAME_MAP[name]).filter(Boolean));\n  /* v8 ignore start -- the editor is only rendered while the draft is there */\n  const isIndexFile = $derived(entryDraft.current?.isIndexFile ?? false);\n  const collectionName = $derived(entryDraft.current?.collectionName ?? '');\n  /* v8 ignore stop */\n  const fileName = $derived(entryDraft.current?.fileName);\n  const valueMap = $derived(\n    getFieldValueMapSnapshot(entryDraft.current, locale, keyPath, valueStoreKey),\n  );\n  const componentNames = $derived(getEditorComponentNames(fieldConfig));\n  const buttons = $derived(getToolbarButtons(_buttons, componentNames));\n  const allowNestedComponents = $derived(\n    resolveAllowNestedComponents(\n      inEditorComponent\n        ? // Retrieve the parent Markdown or RichText field config\n          /** @type {MarkdownField | RichTextField | undefined} */ (\n            getField({\n              collectionName,\n              fileName,\n              isIndexFile,\n              valueMap,\n              keyPath: getRootFieldName(keyPath),\n            })\n          )\n        : fieldConfig,\n    ),\n  );\n  const components = $derived(\n    getAvailableComponentDefs({\n      fieldConfig,\n      format,\n      allowNestedComponents,\n      inEditorComponent,\n      parentComponentNames,\n    }).map(\n      (def) => /** @type {import('@sveltia/ui').TextEditorComponent} */ (new EditorComponent(def)),\n    ),\n  );\n  const imageComponent = $derived(components.find(({ id }) => IMAGE_COMPONENT_IDS.includes(id)));\n  const srcFieldConfig = $derived(\n    getImageSrcFieldConfig(\n      /** @type {import('@sveltia/ui').TextEditorComponent & EditorComponentDefinition} */ (\n        imageComponent\n      ),\n    ),\n  );\n  const assetOptions = $derived(\n    getMediaFieldAssetOptions({\n      collectionName,\n      fileName,\n      isIndexFile,\n      componentName,\n      typedKeyPath,\n      fieldConfig: /** @type {ImageField} */ (srcFieldConfig),\n    }),\n  );\n\n  /**\n   * Insert images to the editor content.\n   * @param {object} args Arguments.\n   * @param {EventTarget | null} args.target Event target.\n   * @param {ImageEntry[]} args.images Image list.\n   */\n  const insertImages = async ({ target, images }) => {\n    const outer = /** @type {HTMLElement} */ (target)?.closest('div');\n    const editor = getNearestEditorFromDOMNode(outer);\n\n    if (!entryDraft.current || !imageComponent || !outer?.matches('.lexical-root') || !editor) {\n      return;\n    }\n\n    const { folder, libraryConfig } = assetOptions;\n    const draft = entryDraft.current;\n    const _locale = locale;\n    const component = imageComponent;\n\n    const { inlineImages, uploadFiles, rejected } = sortDroppedImages({\n      images,\n      srcFieldConfig,\n      assetOptions,\n    });\n\n    /**\n     * Whether the editor still shows the content the images were dropped in. The editor is reused\n     * when the pane switches to another locale or another entry is opened, so the image would be\n     * inserted into the content it shows now, with a path resolved for the one it was dropped in.\n     * @returns {boolean} Result.\n     */\n    const isSameContent = () => entryDraft.current === draft && locale === _locale;\n\n    /**\n     * Insert an image.\n     * @param {string} src Image URL.\n     * @param {string} alt Alternative text.\n     */\n    const insertImage = (src, alt) => {\n      editor.update(() => {\n        const node = component.createNode({ src, alt });\n\n        // Start a new paragraph after the image, unless the field holds a single one\n        insertNodes(multiline ? [node, createParagraphNode()] : [node]);\n      });\n    };\n\n    processingImages += 1;\n\n    try {\n      // eslint-disable-next-line no-restricted-syntax\n      for (const { file, src: externalSrc, alt = '' } of inlineImages) {\n        let src = externalSrc;\n\n        if (file) {\n          // eslint-disable-next-line no-await-in-loop\n          const { value } = await processResource({\n            draft,\n            resource: { file, folder },\n            libraryConfig,\n            locale: _locale,\n          });\n\n          if (!isSameContent()) {\n            return;\n          }\n\n          src = value;\n        }\n\n        if (src) {\n          insertImage(src, alt);\n        }\n      }\n    } finally {\n      processingImages -= 1;\n    }\n\n    if (rejected) {\n      filesRejected = true;\n    }\n\n    if (!uploadFiles.length) {\n      return;\n    }\n\n    /**\n     * Insert the images the user has selected in the Select Assets dialog, which uploads the files\n     * to the cloud storage service, asking for the credentials if needed.\n     * @param {SelectedResource[]} resources Selected resources.\n     */\n    insertUploadedImages = async (resources) => {\n      // A save made right after the images have been selected waits for them to be inserted\n      processingImages += 1;\n\n      try {\n        const results = await processResources({\n          draft,\n          resources,\n          folder,\n          libraryConfig,\n          locale: _locale,\n        });\n\n        if (isSameContent()) {\n          results.forEach(({ value }) => {\n            if (value) {\n              insertImage(value, '');\n            }\n          });\n        }\n      } finally {\n        processingImages -= 1;\n      }\n    };\n\n    pendingFiles = uploadFiles;\n    showSelectAssetsDialog = true;\n  };\n\n  /**\n   * Create a handler for pasted or dropped content. If it includes images, they’re inserted to the\n   * editor content.\n   * @template {ClipboardEvent | DragEvent} E\n   * @param {(event: E) => Promise<ImageEntry[]>} getImages Function getting the images from the\n   * event.\n   * @returns {(event: E) => Promise<void>} Event handler.\n   */\n  const createImageHandler = (getImages) => async (event) => {\n    // Lexical applies an update even while the editor isn’t editable, so nothing is inserted to a\n    // read-only field, nor is the file added to the draft\n    if (readonly) {\n      return;\n    }\n\n    const { target } = event;\n    const images = await getImages(event);\n\n    if (images.length) {\n      await insertImages({ target, images });\n    }\n  };\n\n  const onPaste = createImageHandler(getPastedImages);\n  const onDrop = createImageHandler(getDroppedImages);\n\n  /**\n   * Remove the extra values of the components that are no longer present in the editor, shortly\n   * after {@link currentValue} has changed.\n   */\n  const scheduleExtraValueCleanup = () => {\n    // Skip cleanup when used as a nested component editor\n    const draft = entryDraft.current;\n\n    if (!draft || inEditorComponent) {\n      return;\n    }\n\n    window.clearTimeout(cleanupTimeout);\n\n    // Remove values that are not present in the editor anymore. Otherwise, they will trigger\n    // validation errors when the entry is saved.\n    cleanupTimeout = window.setTimeout(() => {\n      getStaleExtraValueKeys(\n        draft.extraValues[locale],\n        keyPath,\n        (prefix) => !!wrapper?.querySelector(`[data-key-path-prefix=\"${prefix}\"]`),\n      ).forEach((key) => {\n        delete draft.extraValues[locale][key];\n      });\n    }, 500);\n  };\n\n  // Sync `inputValue` with `currentValue` in both directions\n  syncValues(\n    () => currentValue,\n    (value) => {\n      currentValue = value;\n    },\n    () => inputValue,\n    (input) => {\n      inputValue = input;\n    },\n    (value) => (typeof value === 'string' ? value : ''),\n  );\n\n  // Registered after the sync above, so it runs right after the input value has been updated\n  watch(\n    () => currentValue,\n    () => {\n      scheduleExtraValueCleanup();\n    },\n  );\n\n  // Cancel the pending cleanup when the component is destroyed, e.g. when the content details\n  // overlay is closed. Otherwise, the callback would read reactive state belonging to a destroyed\n  // effect, causing a `derived_inert` warning.\n  $effect(() => () => {\n    window.clearTimeout(cleanupTimeout);\n  });\n\n  // While the editor holds a change made by the user, register it as a pending update: the editor\n  // converts the content to Markdown with a short delay, so a save right after a change would\n  // otherwise validate and write the previous value. A dropped or pasted image is only inserted\n  // once it has been processed, which can take a while, e.g. converting a large HEIC photo, so a\n  // save or a locale switch has to wait for that as well\n  trackPendingWhile(() => pending || !!processingImages);\n</script>\n\n<div role=\"none\" class=\"wrapper\" bind:this={wrapper}>\n  {#await sleep() then}\n    <!--\n      Reset the editor when the configuration changes. It happens when fields are reordered or\n      removed in a variable type list field. @see https://github.com/sveltia/sveltia-cms/issues/480\n    -->\n    {#key JSON.stringify(fieldConfig)}\n      <TextEditor\n        lang={getCanonicalLocale(locale)}\n        dir={getDirection(locale)}\n        {format}\n        {modes}\n        {buttons}\n        {components}\n        {useEmojiAutocomplete}\n        {useMarkdownShortcuts}\n        {minimal}\n        {multiline}\n        bind:value={inputValue}\n        bind:pending\n        flex\n        {readonly}\n        {required}\n        {invalid}\n        aria-labelledby=\"{fieldId}-label\"\n        aria-errormessage=\"{fieldId}-error\"\n        autoResize={true}\n        onpastecapture={(/** @type {ClipboardEvent} */ event) => {\n          // Use `capture` to handle the event before Lexical does\n          onPaste(event);\n        }}\n        ondrop={(/** @type {DragEvent} */ event) => {\n          onDrop(event);\n        }}\n      />\n    {/key}\n  {/await}\n</div>\n\n{#if srcFieldConfig}\n  <SelectAssetsDialog\n    kind=\"image\"\n    multiple\n    draft={entryDraft.current}\n    {locale}\n    fieldConfig={srcFieldConfig}\n    assetLibraryFolderMap={assetOptions.folderMap}\n    enabledCloudServiceEntries={assetOptions.cloudServiceEntries}\n    bind:open={showSelectAssetsDialog}\n    bind:pendingFiles\n    onSelect={(resources) => {\n      insertUploadedImages?.(resources);\n    }}\n    onClose={() => {\n      insertUploadedImages = undefined;\n    }}\n  />\n{/if}\n\n<Toast bind:show={filesRejected}>\n  <Alert status=\"error\">{_('uploading_files_failed')}</Alert>\n</Toast>\n\n<style>\n  .wrapper {\n    --sui-paragraph-margin: 20px;\n    display: contents;\n\n    :global {\n      @media (width < 768px) {\n        .sui.text-editor {\n          /* Remove the section padding */\n          margin: 0 calc(var(--field-editor-padding) * -1) calc(var(--field-editor-padding) * -1);\n          width: 100dvw;\n        }\n\n        :is(.sui.toolbar, .lexical-root, textarea) {\n          border: 0;\n          border-radius: 0;\n        }\n      }\n    }\n  }\n</style>\n","import { highlightCodeToHTML } from '@sveltia/ui';\nimport { Renderer, use } from 'marked';\n\n/**\n * @import { RendererObject, Tokens } from 'marked';\n */\n\n/**\n * Whether {@link addMarkedExtensions} has added the extensions.\n */\nlet extensionsAdded = false;\n\n/**\n * Wrap one of Marked’s default block renderers to add `dir=\"auto\"` to the opening tag, so the\n * browser picks the direction of the block from its first strong character, e.g. right-to-left for\n * Arabic or Hebrew text.\n * @param {'heading' | 'list' | 'paragraph'} type Block type.\n * @returns {(this: Renderer, token: any) => string} Renderer.\n */\nconst withDirAuto = (type) =>\n  function render(token) {\n    return Renderer.prototype[type].call(this, token).replace(/^<(\\w+)/, '<$1 dir=\"auto\"');\n  };\n\n/**\n * Renderers that add `dir=\"auto\"` to the text blocks for bidirectional text support.\n * @type {RendererObject}\n */\nconst bidiRenderers = {\n  heading: withDirAuto('heading'),\n  list: withDirAuto('list'),\n  paragraph: withDirAuto('paragraph'),\n};\n\n/**\n * Render a code block with syntax highlighting using Shiki. This is done in the renderer to ensure\n * it runs before sanitization, allowing the highlighted HTML to be preserved in the preview. Shiki\n * loads its engine and grammars on demand, so this returns nothing until the language is ready;\n * the preview fetches it with `loadCodeHighlighter()` and renders the block again.\n * @param {Tokens.Code} token Code token.\n * @returns {string | false} Highlighted HTML, or `false` to fall back to the default renderer.\n */\nexport const renderCode = ({ text, lang }) =>\n  (lang ? highlightCodeToHTML(text, lang) : undefined) ?? false;\n\n/**\n * Add the extensions the RichText field preview needs to the shared Marked instance: `dir=\"auto\"`\n * on the text blocks for bidirectional text, and syntax highlighting for the code blocks. They’re\n * added only once, as `use()` adds another layer on every call, and the shared instance outlives\n * any preview: adding them for each preview would make every code block go through one renderer\n * per preview ever rendered, until the stack overflows. The instance is shared rather than private,\n * so the extensions a site adds with `window.marked.use()` also apply to the preview.\n */\nexport const addMarkedExtensions = () => {\n  if (extensionsAdded) {\n    return;\n  }\n\n  extensionsAdded = true;\n  use({ renderer: { ...bidiRenderers, code: renderCode } });\n};\n","import { lexer } from 'marked';\n\nimport {\n  isFenceClose,\n  matchFenceOpen,\n} from '$lib/services/contents/fields/rich-text/previews/syntax';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { escapeHTML } from '$lib/services/utils/string';\n\n/**\n * @import { Token, Tokens } from 'marked';\n */\n\n/**\n * HTML void elements that cannot have children or a closing tag. Used to avoid incorrectly\n * entering HTML block mode when a void element starts a line.\n * @see https://developer.mozilla.org/en-US/docs/Glossary/Void_element\n */\nconst VOID_ELEMENTS = new Set([\n  'area',\n  'base',\n  'br',\n  'col',\n  'embed',\n  'hr',\n  'img',\n  'input',\n  'link',\n  'meta',\n  'param',\n  'source',\n  'track',\n  'wbr',\n]);\n\n/**\n * Match the opening line of a fenced code block at the top level, with at most 3 spaces before the\n * fence. A fence indented further is within an indented code block or a list item.\n * @param {string} line Line.\n * @returns {ReturnType<typeof matchFenceOpen>} Fence. See {@link matchFenceOpen}.\n */\nconst matchBlockFenceOpen = (line) => {\n  const opening = matchFenceOpen(line);\n\n  return opening && /^ {0,3}$/.test(opening.indent) ? opening : undefined;\n};\n\n/**\n * Regex to detect a line that opens an HTML block element, capturing the tag name.\n */\nconst HTML_OPEN_TAG_REGEX = /^<([a-zA-Z][a-zA-Z0-9]*)(?:[\\s>])/;\n\n/**\n * Starts of the HTML blocks that run until a line with the given end marker rather than a blank\n * line: raw text elements, comments, processing instructions, declarations and CDATA sections\n * (types 1 to 5 in CommonMark). The end marker can be on the same line.\n * @type {{ start: RegExp, end: RegExp }[]}\n * @see https://spec.commonmark.org/0.31.2/#html-blocks\n */\nconst RAW_HTML_BLOCKS = [\n  {\n    start: /^ {0,3}<(?:pre|script|style|textarea)(?:[\\s>]|$)/i,\n    end: /<\\/(?:pre|script|style|textarea)>/i,\n  },\n  { start: /^ {0,3}<!--/, end: /-->/ },\n  { start: /^ {0,3}<\\?/, end: /\\?>/ },\n  { start: /^ {0,3}<![a-z]/i, end: />/ },\n  { start: /^ {0,3}<!\\[CDATA\\[/, end: /\\]\\]>/ },\n];\n\n/**\n * Regex to detect a list item, whose content can continue after a blank line.\n */\nconst LIST_ITEM_REGEX = /^ {0,3}(?:[-+*]|\\d{1,9}[.)])(?:[ \\t]|$)/;\n/**\n * @type {Map<string, { openRe: RegExp, closeRe: RegExp }>}\n */\nconst htmlTagRegexCache = new Map();\n\n/**\n * Split an HTML string into its top-level nodes, so a preview only re-renders the nodes that have\n * changed, like {@link splitMarkdownBlocks} does for Markdown. Elements and text are kept,\n * including the whitespace between them, while comments are dropped.\n * @param {string} html The full HTML string.\n * @returns {string[]} Array of non-empty block strings.\n */\nexport const splitHTMLBlocks = (html) => {\n  const template = document.createElement('template');\n\n  template.innerHTML = html;\n\n  return [...template.content.childNodes]\n    .map((node) => {\n      if (node.nodeType === Node.ELEMENT_NODE) {\n        return /** @type {Element} */ (node).outerHTML;\n      }\n\n      return node.nodeType === Node.TEXT_NODE ? escapeHTML(/** @type {Text} */ (node).data) : '';\n    })\n    .filter(Boolean);\n};\n\n/**\n * Check if the given line opens a raw HTML block, which runs until its end marker, and the marker\n * is not on the same line.\n * @param {string} line Line.\n * @returns {RegExp | undefined} End marker regex, if the block continues on the next lines.\n */\nconst getRawHTMLBlockEnd = (line) => {\n  const block = RAW_HTML_BLOCKS.find(({ start }) => start.test(line));\n\n  return block && !block.end.test(line.replace(block.start, '')) ? block.end : undefined;\n};\n\n/**\n * Split a Markdown string into logical blocks at blank lines, keeping fenced code blocks (backtick\n * or tilde fences), HTML block elements (e.g. `<div>`), raw HTML blocks such as comments, and lists\n * whose items continue after a blank line intact even when they contain blank lines.\n * @param {string} markdown The full Markdown string.\n * @returns {string[]} Array of non-empty block strings.\n */\nexport const splitMarkdownBlocks = (markdown) => {\n  if (!markdown) return [];\n\n  const lines = markdown.split('\\n');\n  /** @type {string[]} */\n  const blocks = [];\n  /** @type {string[]} */\n  const current = [];\n  /** @type {{ char: string, length: number } | null} */\n  let fence = null;\n  /** @type {{ tag: string, depth: number, openRe: RegExp, closeRe: RegExp } | null} */\n  let htmlBlock = null;\n  /** @type {RegExp | undefined} */\n  let rawHTMLBlockEnd;\n  /** Whether the current block has a list item. */\n  let inList = false;\n\n  /**\n   * Check if the next line with any text after the given line continues a list: an indented line,\n   * which is part of the last item, or another item.\n   * @param {number} index Index of a blank line.\n   * @returns {boolean} Result.\n   */\n  const continuesList = (index) => {\n    const nextLine = lines.find((line, i) => i > index && line.trim()) ?? '';\n\n    return /^[ \\t]/.test(nextLine) || LIST_ITEM_REGEX.test(nextLine);\n  };\n\n  lines.forEach((line, index) => {\n    if (fence) {\n      current.push(line);\n\n      // A closing fence can have at most 3 leading spaces\n      if (line.length - line.trimStart().length <= 3 && isFenceClose(line, fence)) {\n        fence = null;\n      }\n    } else if (rawHTMLBlockEnd) {\n      current.push(line);\n\n      if (rawHTMLBlockEnd.test(line)) {\n        rawHTMLBlockEnd = undefined;\n      }\n    } else if (htmlBlock) {\n      current.push(line);\n\n      // Reuse pre-compiled regexes stored when the block was opened (avoids two regex allocations\n      // per line for potentially long HTML blocks).\n      const { openRe, closeRe } = htmlBlock;\n\n      htmlBlock.depth += [...line.matchAll(openRe)].length - [...line.matchAll(closeRe)].length;\n\n      if (htmlBlock.depth <= 0) {\n        htmlBlock = null;\n      }\n    } else {\n      const fenceMatch = matchBlockFenceOpen(line);\n\n      rawHTMLBlockEnd = fenceMatch ? undefined : getRawHTMLBlockEnd(line);\n\n      if (fenceMatch) {\n        current.push(line);\n        fence = { char: fenceMatch.char, length: fenceMatch.length };\n      } else if (rawHTMLBlockEnd) {\n        current.push(line);\n      } else {\n        const htmlOpenMatch = HTML_OPEN_TAG_REGEX.exec(line);\n\n        if (htmlOpenMatch) {\n          const tag = htmlOpenMatch[1].toLowerCase();\n\n          current.push(line);\n\n          if (!VOID_ELEMENTS.has(tag)) {\n            const tagRegexes = getOrCreate(htmlTagRegexCache, tag, () => ({\n              openRe: new RegExp(`<${tag}(?:[\\\\s>])`, 'gi'),\n              closeRe: new RegExp(`<\\\\/${tag}>`, 'gi'),\n            }));\n\n            const { openRe, closeRe } = tagRegexes;\n            const depth = [...line.matchAll(openRe)].length - [...line.matchAll(closeRe)].length;\n\n            if (depth > 0) {\n              // Store the regexes in the block so subsequent lines reuse them.\n              htmlBlock = { tag, depth, openRe, closeRe };\n            }\n          }\n        } else if (line === '') {\n          if (inList && continuesList(index)) {\n            current.push(line);\n          } else if (current.length) {\n            blocks.push(current.splice(0).join('\\n'));\n            inList = false;\n          }\n        } else {\n          current.push(line);\n          inList ||= LIST_ITEM_REGEX.test(line);\n        }\n      }\n    }\n  });\n\n  if (current.length) blocks.push(current.join('\\n'));\n\n  return blocks;\n};\n\n/**\n * Get the link reference definitions in the given Markdown blocks, e.g. `[1]: https://example.com`,\n * so they can be added to each block parsed on its own: a reference link and its definition are\n * usually in different blocks. The blocks that can have a definition are lexed, as a definition\n * can’t span blocks, so one is only found where Marked takes it for one, not in code for instance.\n * @param {string[]} blocks Blocks. See {@link splitMarkdownBlocks}.\n * @returns {string} The definitions, one per line, or an empty string if there are none.\n * @see https://spec.commonmark.org/0.31.2/#link-reference-definitions\n */\nexport const getLinkDefinitions = (blocks) => {\n  /** @type {string[]} */\n  const definitions = [];\n\n  /**\n   * Collect the definitions in the given tokens, including those in a blockquote or list item.\n   * @param {Token[]} tokens Tokens.\n   */\n  const collect = (tokens) => {\n    tokens.forEach((token) => {\n      if (token.type === 'def') {\n        definitions.push(token.raw.trim());\n      } else if (token.type === 'list') {\n        token.items.forEach((/** @type {Tokens.ListItem} */ item) => {\n          collect(item.tokens);\n        });\n      } else if (token.type === 'blockquote') {\n        collect(/** @type {Tokens.Blockquote} */ (token).tokens);\n      }\n    });\n  };\n\n  // A definition has a colon after its label\n  blocks.filter((block) => block.includes(']:')).forEach((block) => collect(lexer(block)));\n\n  return definitions.join('\\n');\n};\n\n/**\n * Add the link reference definitions in the given blocks to the start of each block, so a\n * reference link is resolved wherever its definition is. A definition renders nothing. It comes\n * first, as a block can end within an unclosed fenced code block.\n * @param {string[]} blocks Blocks. See {@link splitMarkdownBlocks}.\n * @returns {string[]} Blocks.\n */\nexport const addLinkDefinitions = (blocks) => {\n  const definitions = getLinkDefinitions(blocks);\n\n  return definitions ? blocks.map((block) => `${definitions}\\n\\n${block}`) : blocks;\n};\n\n/**\n * Split the value of a rich text field into the blocks its preview renders one by one.\n * @param {string} value Markdown or HTML.\n * @param {object} options Options.\n * @param {boolean} options.isHTML Whether the value is HTML rather than Markdown.\n * @returns {string[]} Blocks. See {@link splitHTMLBlocks} and {@link splitMarkdownBlocks}.\n */\nexport const splitPreviewBlocks = (value, { isHTML }) =>\n  // The link reference definitions are added to each Markdown block, as a block is parsed on its\n  // own while a reference link and its definition are usually in different blocks\n  isHTML ? splitHTMLBlocks(value) : addLinkDefinitions(splitMarkdownBlocks(value));\n\n/**\n * A block of a rich text preview with its key.\n * @typedef {{ key: string, block: string }} KeyedBlock\n */\n\n/**\n * Key the given blocks by content rather than by position: editing near the top of a long document\n * then only re-renders the block that changed, instead of every block after it. Identical blocks\n * are told apart by their occurrence. An unchanged block keeps its item object from the previous\n * run, so the block isn’t parsed again: a keyed `{#each}` would otherwise update every item with a\n * new object and render every block again.\n * @param {string[]} blocks Blocks.\n * @param {Map<string, KeyedBlock>} previousItems Items of the previous run by key.\n * @returns {{ list: KeyedBlock[], items: Map<string, KeyedBlock> }} Keyed blocks, and the same\n * items by key, to be passed as `previousItems` next time.\n */\nexport const keyBlocks = (blocks, previousItems) => {\n  /** @type {Map<string, number>} */\n  const occurrences = new Map();\n  /** @type {Map<string, KeyedBlock>} */\n  const items = new Map();\n\n  const list = blocks.map((block) => {\n    const occurrence = occurrences.get(block) ?? 0;\n    const key = `${occurrence}\\n${block}`;\n    const item = previousItems.get(key) ?? { key, block };\n\n    occurrences.set(block, occurrence + 1);\n    items.set(key, item);\n\n    return item;\n  });\n\n  return { list, items };\n};\n\n/**\n * Get the languages of the fenced code blocks in the given Markdown, with backtick or tilde fences.\n * @param {string} markdown Markdown.\n * @returns {string[]} Unique language names, sorted.\n */\nexport const getFencedCodeLanguages = (markdown) =>\n  markdown\n    .split('\\n')\n    .map((line) => /^[ \\t]*([^\\s`]+)/.exec(matchBlockFenceOpen(line)?.info ?? '')?.[1])\n    .filter((lang) => lang !== undefined)\n    .filter((lang, index, list) => list.indexOf(lang) === index)\n    .sort();\n","/**\n * Local names of the attributes that can navigate to a URL or load one into a frame, where a\n * `javascript:` URL would run a script: `href` also covers `xlink:href` in SVG. An SVG `<animate>`\n * or `<set>` element can also set a link’s `href` with `from`, `to` or `values`, the last one being\n * a semicolon-separated list.\n */\nconst URL_ATTRIBUTE_NAMES = ['href', 'src', 'action', 'formaction', 'data', 'from', 'to', 'values'];\n/**\n * Regular expression testing if an HTML string may contain one of the {@link URL_ATTRIBUTE_NAMES}.\n * An attribute name can’t be written with character references, unlike its value.\n */\nconst URL_ATTRIBUTE_REGEX = new RegExp(`(?:${URL_ATTRIBUTE_NAMES.join('|')})\\\\s*=`, 'i');\n/**\n * Regular expression matching the characters a browser removes from a URL before reading its\n * scheme: leading C0 control characters and spaces, and ASCII tabs and newlines anywhere, so\n * `java\\tscript:` is still a `javascript:` URL.\n * @see https://url.spec.whatwg.org/#concept-basic-url-parser\n */\n// eslint-disable-next-line no-control-regex\nconst IGNORED_URL_CHARS_REGEX = /^[\\u0000-\\u0020]+|[\\t\\n\\r]/g;\n/**\n * Check if the given attribute value is a `javascript:` URL.\n * @param {string} value Attribute value, with any character references decoded.\n * @returns {boolean} Result.\n */\nconst isScriptURL = (value) => /^javascript:/i.test(value.replaceAll(IGNORED_URL_CHARS_REGEX, ''));\n\n/**\n * Remove the attributes holding a `javascript:` URL from the given HTML, e.g. a Markdown link like\n * `[Click me](javascript:alert(1))`. This is used for the preview of a RichText field with the\n * `sanitize_preview` option disabled, which otherwise renders the HTML as is: a new entry’s body\n * can be given in the URL, so anyone can craft a link to the CMS with one.\n * @param {string} html HTML.\n * @returns {string} HTML without `javascript:` URLs, or the same string if there was none.\n */\nexport const removeScriptURLs = (html) => {\n  // Avoid parsing the HTML if there’s no URL attribute\n  if (!URL_ATTRIBUTE_REGEX.test(html)) {\n    return html;\n  }\n\n  const template = document.createElement('template');\n  let removed = false;\n\n  // The content of a template is inert, so nothing is loaded or run here\n  template.innerHTML = html;\n\n  template.content.querySelectorAll('*').forEach((element) => {\n    [...element.attributes].forEach(({ localName, name, value }) => {\n      if (URL_ATTRIBUTE_NAMES.includes(localName) && value.split(';').some(isScriptURL)) {\n        element.removeAttribute(name);\n        removed = true;\n      }\n    });\n  });\n\n  // Keep the HTML as written unless something was removed\n  return removed ? template.innerHTML : html;\n};\n","<!--\n  @component\n  Implement the preview for a Markdown/RichText field.\n  @see https://decapcms.org/docs/widgets/#Markdown\n  @see https://sveltiacms.app/en/docs/fields/richtext\n-->\n<script module>\n  import { addMarkedExtensions } from '$lib/services/contents/fields/rich-text/previews/marked';\n\n  // Only once, not for each preview\n  addMarkedExtensions();\n</script>\n\n<script>\n  import { loadCodeHighlighter } from '@sveltia/ui';\n  import { parse } from 'marked';\n  import { isValidElement } from 'react';\n  import { onMount, tick } from 'svelte';\n  import { SvelteMap, SvelteSet } from 'svelte/reactivity';\n\n  import { waitForAssetURL } from '$lib/services/api/asset-proxy';\n  import { createGetAsset } from '$lib/services/api/preview-data';\n  import { createReactRoot, loadReactDom, reactDomLoaded } from '$lib/services/api/react-dom';\n  import { getRichTextMediaURL } from '$lib/services/assets/media-field';\n  import { cmsConfig } from '$lib/services/config';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getValueFormat } from '$lib/services/contents/fields/rich-text';\n  import { getEditorComponentDefs } from '$lib/services/contents/fields/rich-text/options';\n  import {\n    getFencedCodeLanguages,\n    keyBlocks,\n    splitPreviewBlocks,\n  } from '$lib/services/contents/fields/rich-text/previews/blocks';\n  import {\n    buildMarkdownWithPreviews,\n    COMPONENT_QUERY_SELECTOR,\n    CONTAINER_QUERY_SELECTOR,\n  } from '$lib/services/contents/fields/rich-text/previews/components';\n  import {\n    deferMediaURLs,\n    MEDIA_QUERY_SELECTOR,\n    resolveMediaURLs,\n  } from '$lib/services/contents/fields/rich-text/previews/media-urls';\n  import { removeScriptURLs } from '$lib/services/contents/fields/rich-text/previews/script-urls';\n  import { sanitizeRichTextHTML } from '$lib/services/contents/fields/rich-text/sanitize';\n\n  /**\n   * @import { ReactElement } from 'react';\n   * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { ApiAsset, MarkdownField, RichTextField } from '$lib/types/public';\n   * @import {\n   * ComponentPreview,\n   * } from '$lib/services/contents/fields/rich-text/previews/components';\n   * @import { KeyedBlock } from '$lib/services/contents/fields/rich-text/previews/blocks';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {MarkdownField | RichTextField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /**\n   * Entry draft state of the editor. It’s missing when `CMS.renderRichText()` mounts the preview\n   * outside a Svelte update, e.g. from a React effect, where no component context can be inherited.\n   * @type {EntryDraftState | undefined}\n   */\n  const entryDraft = getEntryDraftContext();\n\n  const defaultConfig = cmsConfig.current?.field_defaults?.richtext ?? {};\n  /** @type {SvelteMap<HTMLElement, ReturnType<typeof createReactRoot>>} */\n  const reactRoots = new SvelteMap();\n  /**\n   * DOM element previews currently inserted in the preview pane. Used to notify each element with\n   * an `Unmount` event once it’s removed, so the developer can destroy the component mounted on it.\n   * @type {SvelteSet<Element>}\n   */\n  const previewNodes = new SvelteSet();\n\n  /**\n   * Component previews by key. Deliberately not reactive: it is written while `markdown` is\n   * computed.\n   * @type {Map<string, ComponentPreview>}\n   */\n  // eslint-disable-next-line svelte/prefer-svelte-reactivity\n  let previewMap = new Map();\n  /**\n   * Assets the component previews computed in the latest run have got with `getAsset()`, keyed by\n   * the preview key. Deliberately not reactive, like `previewMap`.\n   * @type {Map<string, ApiAsset[]>}\n   */\n  let newPreviewAssets = new Map();\n  /**\n   * Items of the latest {@link keyedBlocks} by key, reused for an unchanged block so the keyed\n   * `{#each}` sees the same object and doesn’t parse and sanitize the block again. Deliberately not\n   * reactive, like `previewMap`.\n   * @type {Map<string, KeyedBlock>}\n   */\n  let blockItems = new Map();\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, typedKeyPath, fieldConfig, currentValue } = $props();\n\n  /** @type {HTMLElement | undefined} */\n  let container = $state();\n  let observerReady = $state(false);\n  /**\n   * Bumped whenever a syntax highlighting grammar finishes loading. `parseMarkdown()` reads it so\n   * the preview is rendered again with the code blocks highlighted.\n   */\n  let highlighterVersion = $state(0);\n  /**\n   * Bumped whenever a component preview has been dropped because an asset it got with `getAsset()`\n   * has a new URL. `markdown` reads it so the preview is computed again with the new URL.\n   */\n  let assetURLVersion = $state(0);\n  /**\n   * Sorted, comma-separated languages already handed to the highlighter, so a repeated edit doesn’t\n   * request them again. Deliberately not reactive: it is written while rendering is in progress.\n   */\n  let requestedLanguages = '';\n\n  const entry = $derived(entryDraft?.current?.originalEntry);\n  const collectionName = $derived(entryDraft?.current?.collectionName ?? '');\n  const fileName = $derived(entryDraft?.current?.fileName);\n  const { sanitize_preview: doSanitize = defaultConfig.sanitize_preview ?? true } =\n    $derived(fieldConfig);\n  const format = $derived(getValueFormat(fieldConfig));\n  const isHTML = $derived(format === 'html');\n  const componentDefs = $derived(getEditorComponentDefs(fieldConfig));\n  const componentNames = $derived(componentDefs.map(({ id }) => id));\n  /**\n   * Asset getter passed to each editor component’s `toPreview()`, which resolves a file path the\n   * same way as an image in the preview, including a file that hasn’t been saved yet.\n   */\n  const getAsset = $derived(\n    createGetAsset({\n      entry,\n      collectionName,\n      fileName,\n      files: entryDraft?.current?.files,\n      typedKeyPath,\n      componentNames,\n      locale,\n    }),\n  );\n\n  const markdown = $derived.by(() => {\n    if (typeof currentValue !== 'string' || !currentValue.trim()) {\n      return '';\n    }\n\n    // Compute again a preview dropped because an asset URL has changed\n    void assetURLVersion;\n\n    // Pass the current map so unchanged components keep their existing preview instead of being\n    // computed again, which would orphan an element preview along with any component mounted on it\n    const {\n      markdown: string,\n      previewMap: newMap,\n      assetMap,\n    } = buildMarkdownWithPreviews(currentValue, componentDefs, previewMap, getAsset, format);\n\n    previewMap = newMap;\n    newPreviewAssets = assetMap;\n\n    return string;\n  });\n\n  /**\n   * The Markdown or HTML split into blocks, each with a key that identifies it by content rather\n   * than by position. See {@link keyBlocks}.\n   */\n  const keyedBlocks = $derived.by(() => {\n    const { list, items } = keyBlocks(splitPreviewBlocks(markdown, { isHTML }), blockItems);\n\n    blockItems = items;\n\n    return list;\n  });\n\n  /**\n   * Fetch the syntax highlighter for any language used in the given Markdown, then trigger a\n   * re-render so the code blocks pick up the highlighting.\n   *\n   * Shiki fetches its engine and grammars on demand, while the Marked renderer is synchronous, so\n   * the first render of a code block has no highlighting and this brings it up to date.\n   * @param {string} value Markdown to scan for fenced code blocks.\n   */\n  const preloadHighlighter = async (value) => {\n    const languages = getFencedCodeLanguages(value).join(',');\n\n    // Once requested, a set of languages is never requested again, whether or not each turned out\n    // to be supported\n    if (!languages || languages === requestedLanguages) {\n      return;\n    }\n\n    requestedLanguages = languages;\n\n    await Promise.all(languages.split(',').map((lang) => loadCodeHighlighter(lang)));\n\n    highlighterVersion += 1;\n  };\n\n  /**\n   * Check if the given element belongs to this preview rather than a nested preview rendered with\n   * `CMS.renderRichText()` inside an element preview. Since the `MutationObserver` watches the\n   * whole subtree, a placeholder or image added by a nested preview is also reported here, but it\n   * has to be handled by the nested preview, which owns the corresponding preview map.\n   * @param {Element} element Element to check.\n   * @returns {boolean} `true` if the element is owned by this preview.\n   */\n  const isOwnElement = (element) => element.closest(CONTAINER_QUERY_SELECTOR) === container;\n\n  /**\n   * Mount a React element preview on the given placeholder element.\n   * @param {HTMLElement} element Placeholder element.\n   * @param {ReactElement} preview React element to be rendered.\n   */\n  const mountReactPreview = (element, preview) => {\n    const root = createReactRoot(element);\n\n    reactRoots.set(element, root);\n    root.render(preview);\n  };\n\n  /* v8 ignore start -- the library is bundled with the tests, so loading can’t fail */\n  /**\n   * Report a failure to load the React DOM library.\n   * @param {Error} error Error.\n   */\n  const reportLoadError = (error) => {\n    // eslint-disable-next-line no-console\n    console.error(error);\n  };\n  /* v8 ignore stop */\n\n  /**\n   * Render a component preview into the specified placeholder element based on its\n   * `data-component-key` attribute.\n   * @param {HTMLElement} element The placeholder element to render the component preview into.\n   */\n  const renderComponent = (element) => {\n    // A placeholder within a nested field preview belongs to that preview\n    /* v8 ignore next 3 */\n    if (!isOwnElement(element)) {\n      return;\n    }\n\n    const key = element.dataset.componentKey;\n    const preview = key ? previewMap.get(key) : undefined;\n\n    if (preview instanceof Element) {\n      // Insert the DOM element as is, e.g. an element with a Svelte or Vue component mounted on it.\n      // The element is not sanitized, just like a React element preview, so escaping any content\n      // written by other users is up to the component developer\n      element.replaceChildren(preview);\n      previewNodes.add(preview);\n    } else if (isValidElement(preview)) {\n      // Mount the React component. `react-dom` is only loaded once a preview actually needs it, as\n      // nothing else in the rich text editor does\n      if (reactDomLoaded.current) {\n        mountReactPreview(element, preview);\n      } else {\n        loadReactDom()\n          .then(() => {\n            // The placeholder may be gone, or mounted by a later mutation, by the time it’s loaded\n            if (element.isConnected && !reactRoots.has(element)) {\n              mountReactPreview(element, preview);\n            }\n          })\n          .catch(reportLoadError);\n      }\n    } else {\n      // Remove the placeholder if there’s no valid preview to render\n      element.remove();\n    }\n  };\n\n  /**\n   * Unmount any React component previews that are removed from the DOM.\n   * @param {HTMLElement} element The removed element to check for mounted React components.\n   */\n  const unmountRemovedRoots = (element) => {\n    [element, ...element.querySelectorAll(COMPONENT_QUERY_SELECTOR)].forEach((el) => {\n      const root = reactRoots.get(/** @type {HTMLElement} */ (el));\n\n      if (root) {\n        root.unmount();\n        reactRoots.delete(/** @type {HTMLElement} */ (el));\n      }\n    });\n  };\n\n  /**\n   * Dispatch an `Unmount` event on any DOM element preview that’s no longer in the container, so\n   * the developer can destroy the component mounted on the element. The container itself may be\n   * detached from the document when this is a nested preview rendered with `CMS.renderRichText()`\n   * inside an element preview that’s not yet inserted, so `isConnected` cannot be used here.\n   * @param {boolean} [all] Whether to notify every element preview regardless of its state. Used\n   * when the field preview itself is being destroyed.\n   */\n  const notifyRemovedPreviews = (all = false) => {\n    previewNodes.forEach((node) => {\n      if (all || !container?.contains(node)) {\n        previewNodes.delete(node);\n        node.dispatchEvent(new CustomEvent('Unmount'));\n      }\n    });\n  };\n\n  /**\n   * Compute a component preview again once an asset it got with `getAsset()` has a new URL: the\n   * blob URL of a file that had to be retrieved first. The file may not have been published, in\n   * which case the public path the asset initially had doesn’t point to it. A string preview is\n   * then rendered again with the rest of the Markdown, while an element or React element preview\n   * replaces the current one in its placeholder, which stays as is.\n   * @param {Map<string, ApiAsset[]>} assetMap Assets the newly computed previews have got, keyed by\n   * the preview key.\n   */\n  const refreshOnAssetURLChange = (assetMap) => {\n    assetMap.forEach((assets, key) => {\n      const preview = previewMap.get(key);\n\n      Promise.all(assets.map(waitForAssetURL)).then(async (results) => {\n        // The preview may have been replaced meanwhile, e.g. because the component was edited\n        if (!results.includes(true) || previewMap.get(key) !== preview) {\n          return;\n        }\n\n        previewMap.delete(key);\n        assetURLVersion += 1;\n        await tick();\n\n        container?.querySelectorAll(`[data-component-key=\"${key}\"]`).forEach((element) => {\n          const root = reactRoots.get(/** @type {HTMLElement} */ (element));\n\n          root?.unmount();\n          reactRoots.delete(/** @type {HTMLElement} */ (element));\n          renderComponent(/** @type {HTMLElement} */ (element));\n        });\n\n        notifyRemovedPreviews();\n      });\n    });\n  };\n\n  /**\n   * Resolve the file paths in the URL attributes of a media element, e.g. an image `src`. This is\n   * needed to properly display media fields in the preview, as the markdown may contain internal\n   * paths that have to be resolved to blob URLs.\n   * @param {Element} element Image, video, audio or source element.\n   */\n  const replaceMediaURLs = async (element) => {\n    // An element within a nested field preview belongs to that preview\n    /* v8 ignore next 3 */\n    if (!isOwnElement(element)) {\n      return;\n    }\n\n    /** @type {HTMLElement} */ (element).dataset.processed = 'true';\n\n    await resolveMediaURLs(element, (value) =>\n      getRichTextMediaURL({\n        value,\n        entry,\n        collectionName,\n        fileName,\n        typedKeyPath,\n        componentNames,\n        locale,\n      }),\n    );\n  };\n\n  /**\n   * Callback for the `MutationObserver` to detect added and removed nodes in the container. It\n   * renders component previews for added nodes and unmounts React roots for removed nodes. Also\n   * handles replacing the URLs of images, videos and audio for media fields.\n   * @param {MutationRecord[]} mutations The list of mutations observed.\n   */\n  const mutationCallback = (mutations) => {\n    /** @type {HTMLElement[]} */\n    const removedElements = [];\n\n    mutations.forEach(({ removedNodes, addedNodes }) => {\n      removedNodes.forEach((node) => {\n        if (node.nodeType === Node.ELEMENT_NODE) {\n          removedElements.push(/** @type {HTMLElement} */ (node));\n        }\n      });\n\n      addedNodes.forEach((node) => {\n        if (node.nodeType !== Node.ELEMENT_NODE) return;\n\n        const element = /** @type {HTMLElement} */ (node);\n\n        if (element.matches(COMPONENT_QUERY_SELECTOR)) {\n          renderComponent(element);\n        } else {\n          element.querySelectorAll(COMPONENT_QUERY_SELECTOR).forEach((el) => {\n            renderComponent(/** @type {HTMLElement} */ (el));\n          });\n        }\n\n        if (element.matches(MEDIA_QUERY_SELECTOR)) {\n          replaceMediaURLs(element);\n        }\n\n        element.querySelectorAll(MEDIA_QUERY_SELECTOR).forEach((media) => {\n          replaceMediaURLs(media);\n        });\n      });\n    });\n\n    // Handle removals after additions, so that an element preview moved to a new placeholder within\n    // the same batch of mutations is not reported as unmounted\n    removedElements.forEach((element) => {\n      unmountRemovedRoots(element);\n    });\n\n    notifyRemovedPreviews();\n  };\n\n  /**\n   * Parse a block of markdown into HTML, replacing component placeholders with their previews and\n   * sanitizing the result if needed, or else removing `javascript:` URLs, which could come from a\n   * new entry’s body given in the URL. An HTML value is only sanitized. The media URLs are\n   * deferred, so the browser doesn’t request a file path before `replaceMediaURLs()` resolves it.\n   * @param {string} block The markdown block to parse, or the whole HTML value.\n   * @returns {string} The parsed (and possibly sanitized) HTML string.\n   */\n  const parseMarkdown = (block) => {\n    // Re-parse once a grammar has loaded, so the renderer can highlight what it previously couldn’t\n    void highlighterVersion;\n\n    const rawHTML = isHTML ? block : /** @type {string} */ (parse(block, { breaks: true }));\n\n    return deferMediaURLs(doSanitize ? sanitizeRichTextHTML(rawHTML) : removeScriptURLs(rawHTML));\n  };\n\n  $effect(() => {\n    if (markdown && !isHTML) {\n      preloadHighlighter(markdown);\n    }\n  });\n\n  $effect(() => {\n    // Watch the assets of the previews computed along with the latest Markdown\n    void markdown;\n    refreshOnAssetURLChange(newPreviewAssets);\n  });\n\n  onMount(() => {\n    const observer = new MutationObserver(mutationCallback);\n\n    // Make sure to render the markdown after the observer is set up, otherwise the callback may not\n    // be called for the initial content.\n    // @see https://github.com/sveltia/sveltia-cms/issues/805\n    observer.observe(/** @type {HTMLElement} */ (container), { childList: true, subtree: true });\n    observerReady = true;\n\n    return () => {\n      observer.disconnect();\n      reactRoots.forEach((root) => root.unmount());\n      reactRoots.clear();\n      notifyRemovedPreviews(true);\n    };\n  });\n</script>\n\n<div role=\"none\" data-rich-text-preview bind:this={container}>\n  {#if observerReady && markdown}\n    {#each keyedBlocks as { key, block } (key)}\n      {@html parseMarkdown(block)}\n    {/each}\n  {/if}\n</div>\n\n<style>\n  :global([role='document']) div {\n    :global {\n      :is(h1, h2, h3, h4, h5, h6, p, ul, ol) {\n        margin: 1em 0 0;\n      }\n\n      :is(video, img) {\n        max-width: 100%;\n        max-height: 100%;\n      }\n\n      :is(a:has(img)) {\n        display: inline-block;\n\n        img {\n          pointer-events: none;\n        }\n      }\n\n      pre.shiki {\n        background-color: var(--sui-code-background-color) !important;\n      }\n    }\n  }\n\n  div {\n    /* Make the preview the containing block of any positioned element in the content, so an element\n       with `position: fixed` from an inline style can’t cover the rest of the app */\n    translate: 0;\n\n    :global {\n      [data-component-key] {\n        display: contents;\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the preview for a Select field.\n  @see https://decapcms.org/docs/widgets/#Select\n  @see https://sveltiacms.app/en/docs/fields/select\n-->\n<script>\n  import { getPreviewLabels } from '$lib/services/contents/fields/select/helpers';\n  import { getCanonicalLocale, getDirection, getListFormatter } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { SelectField, SelectFieldValue } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {SelectField} fieldConfig Field configuration.\n   * @property {SelectFieldValue | SelectFieldValue[] | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, fieldConfig, currentValue } = $props();\n\n  const listFormatter = $derived(getListFormatter(locale));\n  const labels = $derived(getPreviewLabels({ fieldConfig, currentValue }));\n</script>\n\n{#if labels.length}\n  <p lang={getCanonicalLocale(locale)} dir={getDirection(locale)}>\n    {listFormatter.format(labels)}\n  </p>\n{/if}\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import { validateStringField } from '$lib/services/contents/fields/string/validate';\n\n  /**\n   * @import { InternalLocaleCode } from '$lib/types/private';\n   * @import { StringField, TextField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {StringField | TextField} fieldConfig Field configuration.\n   * @property {InternalLocaleCode} locale Current locale.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /** @type {Props} */\n  let { fieldConfig, locale, currentValue } = $props();\n\n  const { minlength, maxlength } = $derived(fieldConfig);\n  const { count, hasMin, hasMax, invalid } = $derived(\n    validateStringField({ fieldConfig, locale, value: currentValue }).detail,\n  );\n</script>\n\n{#if hasMin || hasMax}\n  <div\n    class=\"wrapper\"\n    aria-label={_(\n      hasMin && hasMax\n        ? 'character_counter.min_max'\n        : hasMin\n          ? 'character_counter.min'\n          : 'character_counter.max',\n      { values: { count, min: minlength, max: maxlength } },\n    )}\n  >\n    {#if hasMin}\n      {minlength}\n      <!-- eslint-disable-next-line svelte/no-useless-mustaches -->\n      {' / '}\n    {/if}\n    <span role=\"none\" class=\"count\" class:invalid>{count}</span>\n    {#if hasMax}\n      <!-- eslint-disable-next-line svelte/no-useless-mustaches -->\n      {' / '}\n      {maxlength}\n    {/if}\n  </div>\n{/if}\n\n<style>\n  .wrapper {\n    flex: none;\n    color: var(--sui-tertiary-foreground-color) !important;\n    font-size: var(--sui-font-size-small);\n    line-height: var(--sui-line-height-compact);\n    text-align: end;\n  }\n\n  .count {\n    &.invalid {\n      color: var(--sui-error-foreground-color);\n    }\n\n    &:not(.invalid) {\n      color: var(--sui-success-foreground-color);\n    }\n  }\n</style>\n","import { getFieldEditorContext } from '$lib/services/contents/editor/field-context';\n\n/**\n * @import { Component } from 'svelte';\n */\n\n/**\n * Show the given component as an extra hint below the field, e.g. a character counter, if the\n * editor is rendered in a field editor that provides a place for it. Call it while initializing a\n * field’s editor component, as it reads the `field-editor` context and creates an effect.\n * @param {Component<any>} component Component to render.\n */\nexport const setExtraHint = (component) => {\n  const { extraHint } = getFieldEditorContext();\n\n  $effect(() => {\n    if (extraHint) {\n      extraHint.current = component;\n    }\n  });\n};\n","/**\n * @import { StringField } from '$lib/types/public';\n */\n\n/**\n * Get the value to be shown in the editor’s text input for the given stored value: the value as a\n * string, without the field’s `prefix` and `suffix`, which the editor adds on its own.\n * @param {object} args Arguments.\n * @param {any} args.currentValue Value in the entry draft. A non-string value, e.g. a number from a\n * hand-edited file, is shown as a string.\n * @param {StringField} args.fieldConfig Field configuration.\n * @returns {string} Value to be shown.\n */\nexport const getStringInputValue = ({ currentValue, fieldConfig }) => {\n  const { prefix = '', suffix = '' } = fieldConfig;\n  let value = typeof currentValue === 'string' ? currentValue : String(currentValue ?? '');\n\n  if (prefix && value.startsWith(prefix)) {\n    value = value.slice(prefix.length);\n  }\n\n  if (suffix && value.endsWith(suffix)) {\n    value = value.slice(0, -suffix.length);\n  }\n\n  return value;\n};\n\n/**\n * Get the value to be stored in the entry draft for the given text input value: the value with the\n * field’s `prefix` and `suffix` added, unless it’s blank, so an empty field stays empty.\n * @param {object} args Arguments.\n * @param {string} args.inputValue Value of the text input.\n * @param {StringField} args.fieldConfig Field configuration.\n * @returns {string} Value to be stored.\n */\nexport const getStringFieldValue = ({ inputValue, fieldConfig }) => {\n  const { prefix = '', suffix = '' } = fieldConfig;\n\n  if (inputValue.trim() && (prefix || suffix)) {\n    return `${prefix}${inputValue}${suffix}`;\n  }\n\n  return inputValue;\n};\n","<!--\n  @component\n  Implement the editor for a String field, and, with `multiline`, for a Text field.\n  @see https://decapcms.org/docs/widgets/#String\n  @see https://sveltiacms.app/en/docs/fields/string\n-->\n<script>\n  import { TextArea, TextInput } from '@sveltia/ui';\n\n  import CharacterCounter from '$lib/components/contents/details/fields/string/character-counter.svelte';\n  import { setExtraHint } from '$lib/services/contents/editor/extra-hint.svelte';\n  import {\n    getStringFieldValue,\n    getStringInputValue,\n  } from '$lib/services/contents/fields/string/helpers';\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n  import { syncValues } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { StringField, TextField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {StringField | TextField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   * @property {boolean} [multiline] Whether to edit a Text field in an auto-resizing text area,\n   * which takes the value as is, without the String field’s `type`, `prefix` and `suffix`.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    multiline = false,\n  } = $props();\n\n  let inputValue = $state('');\n\n  /** The configuration, with the String field options, which a Text field lacks. */\n  const stringFieldConfig = $derived(/** @type {StringField} */ (fieldConfig));\n  const {\n    type = 'text',\n    // svelte-ignore state_referenced_locally\n    use_emoji_autocomplete: useEmojiAutocomplete = multiline || type === 'text',\n  } = $derived(stringFieldConfig);\n\n  // Sync `inputValue` with `currentValue` in both directions\n  syncValues(\n    () => currentValue,\n    (value) => {\n      currentValue = value;\n    },\n    () => inputValue,\n    (input) => {\n      inputValue = input;\n    },\n    (value) => {\n      if (multiline) {\n        return typeof value === 'string' ? value : '';\n      }\n\n      return getStringInputValue({ currentValue: value, fieldConfig: stringFieldConfig });\n    },\n    (input) =>\n      multiline\n        ? input\n        : getStringFieldValue({ inputValue: input, fieldConfig: stringFieldConfig }),\n  );\n\n  setExtraHint(CharacterCounter);\n</script>\n\n<!-- The props are written out rather than spread from one object: a spread object recreated when\n  `invalid` changes makes the input report an `undefined` value back through the binding -->\n{#if multiline}\n  <TextArea\n    lang={getCanonicalLocale(locale)}\n    dir={getDirection(locale)}\n    flex\n    {readonly}\n    {required}\n    {invalid}\n    aria-labelledby=\"{fieldId}-label\"\n    aria-errormessage=\"{fieldId}-error\"\n    {useEmojiAutocomplete}\n    bind:value={inputValue}\n    autoResize={true}\n  />\n{:else}\n  <TextInput\n    lang={getCanonicalLocale(locale)}\n    dir={getDirection(locale)}\n    flex\n    {readonly}\n    {required}\n    {invalid}\n    aria-labelledby=\"{fieldId}-label\"\n    aria-errormessage=\"{fieldId}-error\"\n    {useEmojiAutocomplete}\n    bind:value={inputValue}\n    {type}\n    inputmode={type}\n  />\n{/if}\n","import { isURL } from '@sveltia/utils/string';\n\n/**\n * Check if the given string is a YouTube video URL.\n * @param {string} string URL-like string.\n * @returns {boolean} Result.\n */\nexport const isYouTubeVideoURL = (string) => {\n  if (!isURL(string)) {\n    return false;\n  }\n\n  const { origin, pathname, searchParams } = new URL(string);\n\n  if (\n    (origin === 'https://www.youtube.com' || origin === 'https://www.youtube-nocookie.com') &&\n    ((pathname === '/watch' && searchParams.has('v')) ||\n      (pathname === '/playlist' && searchParams.has('list')) ||\n      pathname.startsWith('/embed/'))\n  ) {\n    return true;\n  }\n\n  if (origin === 'https://youtu.be' && !!pathname) {\n    return true;\n  }\n\n  return false;\n};\n\n/**\n * Get an embeddable YouTube video URL from the given string.\n * @param {string} string URL-like string.\n * @returns {string} URL with privacy-enhanced mode enabled.\n */\nexport const getYouTubeEmbedURL = (string) => {\n  const origin = 'https://www.youtube-nocookie.com';\n  const { pathname, search, searchParams } = new URL(string);\n\n  if (pathname === '/watch') {\n    const params = new URLSearchParams(searchParams);\n    let src = `${origin}/embed/${params.get('v')}`;\n\n    if (params.get('list')) {\n      params.delete('v');\n      params.set('listType', 'playlist');\n      src += `?${params}`;\n    }\n\n    return src;\n  }\n\n  if (pathname === '/playlist') {\n    return `${origin}/embed/videoseries${search}`;\n  }\n\n  if (pathname.startsWith('/embed/')) {\n    return `${origin}${pathname}${search}`;\n  }\n\n  // https://youtu.be\n  return `${origin}/embed${pathname}${search}`;\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { VisibilityObserver } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import { getYouTubeEmbedURL } from '$lib/services/utils/media/video/youtube';\n  import { encodeURLSafely } from '$lib/services/utils/url';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} url Video URL.\n   */\n\n  /** @type {Props} */\n  let { url } = $props();\n\n  let embeddable = $state(true);\n\n  const embedURL = $derived(getYouTubeEmbedURL(url));\n\n  /**\n   * Listener for Content Security Policy violations. Hide the iframe if CSP is violated.\n   * @param {SecurityPolicyViolationEvent} event Event.\n   */\n  const onViolation = ({ blockedURI, violatedDirective }) => {\n    if (blockedURI === new URL(embedURL).origin && violatedDirective === 'frame-src') {\n      embeddable = false;\n      window.removeEventListener('securitypolicyviolation', onViolation);\n    }\n  };\n\n  onMount(() => {\n    window.addEventListener('securitypolicyviolation', onViolation);\n\n    return () => {\n      window.removeEventListener('securitypolicyviolation', onViolation);\n    };\n  });\n</script>\n\n<div role=\"none\">\n  {#if embeddable}\n    <VisibilityObserver>\n      <iframe\n        src={encodeURLSafely(embedURL)}\n        title={_('youtube_video_player')}\n        frameborder=\"0\"\n        allow=\"autoplay; encrypted-media; picture-in-picture; clipboard-write\"\n        referrerpolicy=\"strict-origin-when-cross-origin\"\n        allowfullscreen\n        sandbox=\"allow-same-origin allow-scripts allow-popups\"\n      ></iframe>\n    </VisibilityObserver>\n  {:else}\n    <a href={encodeURLSafely(url)}>{url}</a>\n  {/if}\n</div>\n\n<style>\n  iframe {\n    display: block;\n    margin: 0 auto;\n    width: 100%;\n    height: auto;\n    aspect-ratio: 16 / 9;\n  }\n</style>\n","import { isURL } from '@sveltia/utils/string';\n\nimport { isYouTubeVideoURL } from '$lib/services/utils/media/video/youtube';\n\n/**\n * @import { StringField } from '$lib/types/public';\n */\n\n/**\n * How a String field value is shown in the preview.\n * @typedef {'youtube' | 'link' | 'email' | 'text'} StringPreviewType\n */\n\n/**\n * Protocols a value is linked with. Anything else, e.g. `javascript:` or plain `http:`, is shown as\n * text.\n */\nconst SAFE_PROTOCOL_REGEX = /^(?:https|mailto|tel):/;\n\n/**\n * Determine how a String field value is shown in the preview: a YouTube video is embedded, a URL\n * with a safe protocol is linked, an email address is linked with `mailto:`, and anything else is\n * shown as text.\n * @param {object} args Arguments.\n * @param {StringField} args.fieldConfig Field configuration.\n * @param {string} args.value Field value.\n * @returns {StringPreviewType} Preview type.\n */\nexport const getPreviewType = ({ fieldConfig, value }) => {\n  const { type = 'text' } = fieldConfig;\n\n  if (type === 'url' || isURL(value)) {\n    if (isYouTubeVideoURL(value)) {\n      return 'youtube';\n    }\n\n    return SAFE_PROTOCOL_REGEX.test(value) ? 'link' : 'text';\n  }\n\n  return type === 'email' ? 'email' : 'text';\n};\n","<!--\n  @component\n  Implement the preview for a String field.\n  @see https://decapcms.org/docs/widgets/#String\n  @see https://sveltiacms.app/en/docs/fields/string\n-->\n<script>\n  import YouTubeEmbed from '$lib/components/contents/details/fields/string/youtube-embed.svelte';\n  import { getPreviewType } from '$lib/services/contents/fields/string/preview';\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n  import { encodeURLSafely } from '$lib/services/utils/url';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { StringField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {StringField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, fieldConfig, currentValue } = $props();\n\n  const { name: fieldName } = $derived(fieldConfig);\n  /** The value to be shown. Empty if there is no value or it’s whitespace only. */\n  const value = $derived(\n    typeof currentValue === 'string' && currentValue.trim() ? currentValue : '',\n  );\n  /* v8 ignore start -- only read while there’s a value */\n  const previewType = $derived(value ? getPreviewType({ fieldConfig, value }) : 'text');\n  /* v8 ignore stop */\n</script>\n\n{#if value}\n  <p\n    lang={getCanonicalLocale(locale)}\n    dir={getDirection(locale)}\n    class:title={fieldName === 'title'}\n  >\n    {#if previewType === 'youtube'}\n      <YouTubeEmbed url={value} />\n    {:else if previewType === 'link'}\n      <a href={encodeURLSafely(value)}>{value}</a>\n    {:else if previewType === 'email'}\n      <a href={encodeURLSafely(`mailto:${value}`)}>{value}</a>\n    {:else}\n      {value}\n    {/if}\n  </p>\n{/if}\n\n<style>\n  .title {\n    font-size: var(--sui-font-size-xxx-large);\n    font-weight: var(--sui-font-weight-bold);\n  }\n</style>\n","<!--\n  @component\n  Implement the editor for a Text field: the String field editor with a text area.\n  @see https://decapcms.org/docs/widgets/#Text\n  @see https://sveltiacms.app/en/docs/fields/text\n-->\n<script>\n  import StringEditor from '$lib/components/contents/details/fields/string/string-editor.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { TextField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {TextField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldEditorProps & Props} */\n  let { currentValue = $bindable(), ...rest } = $props();\n</script>\n\n<StringEditor {...rest} bind:currentValue multiline />\n","<!--\n  @component\n  Implement the preview for a Text field.\n  @see https://decapcms.org/docs/widgets/#Text\n  @see https://sveltiacms.app/en/docs/fields/text\n-->\n<script>\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { TextField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {TextField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { locale, currentValue } = $props();\n</script>\n\n{#if typeof currentValue === 'string' && currentValue.trim()}\n  <p lang={getCanonicalLocale(locale)} dir={getDirection(locale)}>{currentValue}</p>\n{/if}\n\n<style>\n  p {\n    white-space: pre-wrap;\n  }\n</style>\n","<!--\n  @component\n  Implement the editor for a UUID field.\n  @see https://staticjscms.netlify.app/docs/widget-uuid\n  @see https://sveltiacms.app/en/docs/fields/uuid\n-->\n<script>\n  import { TextInput } from '@sveltia/ui';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    getFieldEditorContext,\n    isInEditorComponent,\n  } from '$lib/services/contents/editor/field-context';\n  import { getInitialValue } from '$lib/services/contents/fields/uuid/helpers';\n  import { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorProps } from '$lib/types/private';\n   * @import { UuidField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {UuidField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  const { valueStoreKey = 'currentValues' } = getFieldEditorContext();\n  // A rich text editor component’s values live in the document of the locale they’re edited in,\n  // so its UUID is filled in whatever the locale\n  const inEditorComponent = isInEditorComponent(valueStoreKey);\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    locale,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = true,\n    invalid = false,\n  } = $props();\n\n  const defaultLocale = $derived(entryDraft.current?.defaultLocale);\n\n  // A new draft has its UUIDs filled in when it’s created, but an existing entry can lack one, e.g.\n  // when the field was added after the entry was saved, and so can a newly added list item. Fill\n  // in the value once the field is shown in a locale where it’s editable. The editor is reused when\n  // the user switches the locale, so do it on every locale change rather than only on mount\n  watch(\n    () => locale,\n    () => {\n      if (\n        !currentValue &&\n        (locale === defaultLocale || inEditorComponent || isFieldTranslatable(fieldConfig?.i18n))\n      ) {\n        currentValue = getInitialValue(fieldConfig);\n      }\n    },\n  );\n</script>\n\n<TextInput\n  dir=\"ltr\"\n  bind:value={currentValue}\n  flex\n  {readonly}\n  {required}\n  {invalid}\n  aria-labelledby=\"{fieldId}-label\"\n  aria-errormessage=\"{fieldId}-error\"\n/>\n","<!--\n  @component\n  Implement the preview for a UUID field.\n  @see https://staticjscms.netlify.app/docs/widget-uuid\n  @see https://sveltiacms.app/en/docs/fields/uuid\n-->\n<script>\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { UuidField } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {UuidField} fieldConfig Field configuration.\n   * @property {string | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let { currentValue } = $props();\n</script>\n\n{#if typeof currentValue === 'string' && currentValue.trim()}\n  <p>{currentValue}</p>\n{/if}\n\n<style>\n  p {\n    font-family: var(--sui-font-family-monospace);\n  }\n</style>\n","import BooleanEditor from '$lib/components/contents/details/fields/boolean/boolean-editor.svelte';\nimport BooleanPreview from '$lib/components/contents/details/fields/boolean/boolean-preview.svelte';\nimport CodeEditor from '$lib/components/contents/details/fields/code/code-editor.svelte';\nimport CodePreview from '$lib/components/contents/details/fields/code/code-preview.svelte';\nimport ColorEditor from '$lib/components/contents/details/fields/color/color-editor.svelte';\nimport ColorPreview from '$lib/components/contents/details/fields/color/color-preview.svelte';\nimport ComputeEditor from '$lib/components/contents/details/fields/compute/compute-editor.svelte';\nimport ComputePreview from '$lib/components/contents/details/fields/compute/compute-preview.svelte';\nimport CustomEditor from '$lib/components/contents/details/fields/custom/custom-editor.svelte';\nimport CustomPreview from '$lib/components/contents/details/fields/custom/custom-preview.svelte';\nimport DateTimeEditor from '$lib/components/contents/details/fields/date-time/date-time-editor.svelte';\nimport DateTimePreview from '$lib/components/contents/details/fields/date-time/date-time-preview.svelte';\nimport FileEditor from '$lib/components/contents/details/fields/file/file-editor.svelte';\nimport FilePreview from '$lib/components/contents/details/fields/file/file-preview.svelte';\nimport KeyValueEditor from '$lib/components/contents/details/fields/key-value/key-value-editor.svelte';\nimport KeyValuePreview from '$lib/components/contents/details/fields/key-value/key-value-preview.svelte';\nimport ListEditor from '$lib/components/contents/details/fields/list/list-editor.svelte';\nimport ListPreview from '$lib/components/contents/details/fields/list/list-preview.svelte';\nimport MapEditor from '$lib/components/contents/details/fields/map/map-editor.svelte';\nimport MapPreview from '$lib/components/contents/details/fields/map/map-preview.svelte';\nimport NumberEditor from '$lib/components/contents/details/fields/number/number-editor.svelte';\nimport NumberPreview from '$lib/components/contents/details/fields/number/number-preview.svelte';\nimport ObjectEditor from '$lib/components/contents/details/fields/object/object-editor.svelte';\nimport ObjectPreview from '$lib/components/contents/details/fields/object/object-preview.svelte';\nimport RelationEditor from '$lib/components/contents/details/fields/relation/relation-editor.svelte';\nimport RelationPreview from '$lib/components/contents/details/fields/relation/relation-preview.svelte';\nimport RichTextEditor from '$lib/components/contents/details/fields/rich-text/rich-text-editor.svelte';\nimport RichTextPreview from '$lib/components/contents/details/fields/rich-text/rich-text-preview.svelte';\nimport SelectEditor from '$lib/components/contents/details/fields/select/select-editor.svelte';\nimport SelectPreview from '$lib/components/contents/details/fields/select/select-preview.svelte';\nimport StringEditor from '$lib/components/contents/details/fields/string/string-editor.svelte';\nimport StringPreview from '$lib/components/contents/details/fields/string/string-preview.svelte';\nimport TextEditor from '$lib/components/contents/details/fields/text/text-editor.svelte';\nimport TextPreview from '$lib/components/contents/details/fields/text/text-preview.svelte';\nimport UuidEditor from '$lib/components/contents/details/fields/uuid/uuid-editor.svelte';\nimport UuidPreview from '$lib/components/contents/details/fields/uuid/uuid-preview.svelte';\n\n/**\n * @import { Component } from 'svelte';\n */\n\n/**\n * @type {Record<string, Component>}\n */\nexport const editors = {\n  boolean: BooleanEditor,\n  code: CodeEditor,\n  color: ColorEditor,\n  compute: ComputeEditor,\n  datetime: DateTimeEditor,\n  file: FileEditor,\n  image: FileEditor, // alias\n  keyvalue: KeyValueEditor,\n  list: ListEditor,\n  map: MapEditor,\n  markdown: RichTextEditor, // alias\n  number: NumberEditor,\n  object: ObjectEditor,\n  relation: RelationEditor,\n  richtext: RichTextEditor,\n  select: SelectEditor,\n  string: StringEditor,\n  text: TextEditor,\n  uuid: UuidEditor,\n};\n\n/**\n * @type {Record<string, Component>}\n */\nexport const previews = {\n  boolean: BooleanPreview,\n  code: CodePreview,\n  color: ColorPreview,\n  compute: ComputePreview,\n  datetime: DateTimePreview,\n  file: FilePreview,\n  image: FilePreview, // alias\n  keyvalue: KeyValuePreview,\n  list: ListPreview,\n  map: MapPreview,\n  markdown: RichTextPreview, // alias\n  number: NumberPreview,\n  object: ObjectPreview,\n  relation: RelationPreview,\n  richtext: RichTextPreview,\n  select: SelectPreview,\n  string: StringPreview,\n  text: TextPreview,\n  uuid: UuidPreview,\n};\n\n// Export custom field components for use in field editor\nexport { CustomEditor, CustomPreview };\n","import equal from 'fast-deep-equal';\n\n/**\n * @typedef {object} SvelteProps\n * @property {Record<string, any>} values Reactive state holding the current prop values.\n * @property {Record<string, any>} props Object to be passed to Svelte’s `mount()` function, where\n * each property is backed by {@link SvelteProps.values}.\n */\n\n/**\n * Create a props object for a Svelte component to be mounted. Each property is defined with a\n * getter reading reactive state, so that the component is updated whenever the state is updated,\n * just like a prop passed from a Svelte parent. The `currentValue` property also gets a setter,\n * because editor components write back to that prop, which is bindable.\n * @param {object} args Arguments.\n * @param {Record<string, any>} args.initialProps Initial prop values.\n * @param {Record<string, (value: any) => any>} [args.transforms] Functions to convert stored values\n * when they are read, keyed by prop name. The conversion is done on read rather than on write, so\n * that the state holds the original value, which can be compared with a new one to detect a change.\n * @param {(value: any) => void} args.onValueChange Function to be called when the component writes\n * to the `currentValue` prop.\n * @returns {SvelteProps} Reactive state and props object.\n */\nexport const createSvelteProps = ({ initialProps, transforms = {}, onValueChange }) => {\n  const values = $state({ ...initialProps });\n  /** @type {Record<string, any>} */\n  const props = {};\n\n  Object.keys(initialProps).forEach((key) => {\n    const transform = transforms[key];\n\n    Object.defineProperty(props, key, {\n      enumerable: true,\n      get: transform ? () => transform(values[key]) : () => values[key],\n      set: key === 'currentValue' ? onValueChange : undefined,\n    });\n  });\n\n  return { values, props };\n};\n\n/**\n * Update the reactive state of a mounted Svelte component with new prop values. Only the changed\n * properties are written, so that the component is not invalidated unnecessarily.\n * @param {Record<string, any>} values Reactive state to be updated.\n * @param {Record<string, any>} newValues New prop values.\n */\nexport const updateSvelteProps = (values, newValues) => {\n  Object.entries(newValues).forEach(([key, value]) => {\n    if (!equal(values[key], value)) {\n      values[key] = value;\n    }\n  });\n};\n","import { isObject } from '@sveltia/utils/object';\nimport equal from 'fast-deep-equal';\nimport { createElement, useCallback, useContext, useRef } from 'react';\nimport { mount, unmount } from 'svelte';\n\nimport { editors, previews } from '$lib/components/contents/details/fields';\nimport { fieldStateContext } from '$lib/services/api/field-state';\nimport { createSvelteProps, updateSvelteProps } from '$lib/services/api/field-types.svelte';\nimport { customFieldTypeRegistry } from '$lib/services/api/registries';\nimport { BUILTIN_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n/**\n * @import { ReactElement } from 'react';\n * @import { Component } from 'svelte';\n * @import { SvelteProps } from '$lib/services/api/field-types.svelte';\n * @import { FieldState } from '$lib/services/api/field-state';\n * @import { CustomField, FieldTypeDefinition } from '$lib/types/public';\n */\n\n/**\n * List of built-in field types that can be reused in a custom field type with the\n * `CMS.getFieldType()` API. The editor and preview components for these field types are driven\n * solely by their props, so they can be rendered anywhere. The other built-in field types read from\n * and write to the entry draft store directly, so they only work within the entry editor.\n */\nexport const REUSABLE_BUILTIN_FIELD_TYPES = [\n  'boolean',\n  'color',\n  'datetime',\n  'map',\n  'number',\n  'select',\n  'string',\n  'text',\n  'uuid',\n];\n\n/**\n * Cache of the field type definitions created with {@link createBuiltInFieldType}, so that repeated\n * `CMS.getFieldType()` calls return the same React components. React remounts a component whenever\n * its type changes, so returning a new component each time would reset the field on every render.\n * @type {Map<string, FieldTypeDefinition>}\n */\nconst builtInFieldTypeCache = new Map();\n/**\n * Cache of the field configurations converted with {@link normalizeFieldConfig}. The conversion is\n * done whenever a built-in Svelte component reads the `fieldConfig` prop, which happens several\n * times per render as the prop is passed down the component tree, and deep-converting an Immutable\n * Map that often is wasteful. Both an Immutable Map and a plain field configuration are immutable\n * objects, so the result stays valid as long as the source object is alive.\n * @type {WeakMap<object, CustomField>}\n */\nconst normalizedFieldConfigCache = new WeakMap();\n\n/**\n * Convert the `field` prop passed to a React component to a field configuration object that a\n * built-in Svelte component can read. Three shapes are accepted: an Immutable Map, as passed to a\n * custom field control by the CMS; a plain object, which is handy when a custom field type composes\n * a built-in field type with an ad hoc configuration; and any other object exposing an Immutable\n * Map-like `get` method. Netlify/Decap CMS custom widgets are often given the last shape, because\n * their controls only ever call `field.get()`. Its keys cannot be enumerated, so the options are\n * read lazily through the method.\n * @param {any} field Field configuration.\n * @returns {CustomField} Field configuration.\n */\nconst convertFieldConfig = (field) => {\n  if (typeof field.toJS === 'function') {\n    return field.toJS();\n  }\n\n  if (typeof field.get === 'function') {\n    return /** @type {CustomField} */ (\n      new Proxy(/** @type {any} */ ({}), {\n        // eslint-disable-next-line jsdoc/require-jsdoc\n        get: (_target, key) => (typeof key === 'string' ? field.get(key) : undefined),\n        // eslint-disable-next-line jsdoc/require-jsdoc\n        has: (_target, key) => typeof key === 'string' && field.get(key) !== undefined,\n      })\n    );\n  }\n\n  return /** @type {CustomField} */ (isObject(field) ? field : {});\n};\n\n/**\n * Convert the `field` prop with {@link convertFieldConfig}, reusing the result of a previous\n * conversion of the same object.\n * @param {any} field Field configuration.\n * @returns {CustomField} Field configuration.\n */\nconst normalizeFieldConfig = (field) => {\n  if (field === null || (typeof field !== 'object' && typeof field !== 'function')) {\n    return /** @type {CustomField} */ ({});\n  }\n\n  const cache = normalizedFieldConfigCache.get(field);\n\n  if (cache) {\n    return cache;\n  }\n\n  const fieldConfig = convertFieldConfig(field);\n\n  normalizedFieldConfigCache.set(field, fieldConfig);\n\n  return fieldConfig;\n};\n\n/**\n * Build the props for a built-in field editor component. Each prop given to the React component\n * takes precedence over the state of the field being edited, which in turn takes precedence over\n * the field configuration. Props that are left `undefined` fall back to the defaults defined in the\n * editor component.\n * @param {Record<string, any>} props Props passed to the React component.\n * @param {FieldState} fieldState State of the field being edited.\n * @returns {Record<string, any>} Props for the Svelte component.\n */\nconst buildEditorProps = (props, fieldState) => {\n  const { value, field, forID, locale, keyPath, required, readonly, invalid } = props;\n  const fieldConfig = normalizeFieldConfig(field);\n  const { name, required: requiredOption } = fieldConfig;\n  const _locale = locale ?? fieldState.locale ?? '';\n\n  return {\n    locale: _locale,\n    keyPath: keyPath ?? fieldState.keyPath ?? name ?? '',\n    typedKeyPath: '',\n    fieldId: forID ?? '',\n    // An empty label is as good as none, matching what the field editor renders\n    fieldLabel: getFieldLabel({ config: fieldConfig, locale: _locale }),\n    // Store the field configuration as given, so that a change can be detected. It’s converted\n    // when the Svelte component reads the prop.\n    fieldConfig: field,\n    currentValue: value,\n    required: required ?? fieldState.required ?? requiredOption,\n    readonly: readonly ?? fieldState.readonly,\n    invalid: invalid ?? fieldState.invalid,\n  };\n};\n\n/**\n * Build the props for a built-in field preview component.\n * @param {Record<string, any>} props Props passed to the React component.\n * @param {FieldState} fieldState State of the field being previewed.\n * @returns {Record<string, any>} Props for the Svelte component.\n */\nconst buildPreviewProps = ({ value, field, locale, keyPath }, fieldState) => ({\n  locale: locale ?? fieldState.locale ?? '',\n  keyPath: keyPath ?? fieldState.keyPath ?? normalizeFieldConfig(field).name ?? '',\n  typedKeyPath: '',\n  fieldConfig: field,\n  currentValue: value,\n});\n\n/**\n * Create a React component that renders a built-in Svelte field component, so that a custom field\n * type registered with the `CMS.registerFieldType()` API can reuse it. The Svelte component is\n * mounted once and then updated in place, instead of being remounted on every React render, so that\n * the user’s input, including the focus and selection state, is retained.\n * @param {object} args Arguments.\n * @param {Component} args.SvelteComponent Built-in editor or preview component.\n * @param {(props: Record<string, any>, fieldState: FieldState) => Record<string, any>}\n * args.buildProps Function to convert the React props to the Svelte component props.\n * @returns {(props: Record<string, any>) => ReactElement} React function component.\n */\nconst createFieldComponent =\n  ({ SvelteComponent, buildProps }) =>\n  /**\n   * Render the built-in Svelte component within a wrapper element.\n   * @param {Record<string, any>} props Props passed by React.\n   * @returns {ReactElement} React element.\n   */\n  (props) => {\n    // The state of the field being edited, provided by the custom field control wrapper\n    const fieldState = useContext(fieldStateContext);\n    /** @type {{ current: Record<string, any> }} */\n    const latestProps = useRef(props);\n    /** @type {{ current: SvelteProps | undefined }} */\n    const context = useRef(undefined);\n\n    // Keep the latest props available to the callbacks below, which are created only once\n    latestProps.current = props;\n\n    if (context.current) {\n      updateSvelteProps(context.current.values, buildProps(props, fieldState));\n    } else {\n      context.current = createSvelteProps({\n        initialProps: buildProps(props, fieldState),\n        transforms: { fieldConfig: normalizeFieldConfig },\n        /**\n         * Handle a value written back to the bindable `currentValue` prop by the built-in editor.\n         * @param {any} value New value.\n         */\n        onValueChange: (value) => {\n          const { values } = /** @type {SvelteProps} */ (context.current);\n\n          // Guard against an infinite loop, given that the new value is sent back to this component\n          // as the `value` prop once the entry draft is updated\n          if (!equal(values.currentValue, value)) {\n            values.currentValue = value;\n            latestProps.current.onChange?.(value);\n          }\n        },\n      });\n    }\n\n    const ref = useCallback(\n      /**\n       * Mount the Svelte component when the wrapper element is added to the DOM, and unmount it\n       * when the element is removed. The callback is memoized, so React doesn’t call it on every\n       * render, which would otherwise remount the component.\n       * @param {HTMLElement | null} target Wrapper element. React calls the callback with `null`\n       * instead of the cleanup function below if the component failed to be mounted.\n       * @returns {(() => void) | undefined} Cleanup function called by React.\n       */\n      (target) => {\n        if (!target) {\n          return undefined;\n        }\n\n        const { props: svelteProps } = /** @type {SvelteProps} */ (context.current);\n        const instance = mount(SvelteComponent, { target, props: svelteProps });\n\n        return () => {\n          unmount(instance);\n        };\n      },\n      [],\n    );\n\n    return createElement('div', { ref });\n  };\n\n/**\n * Create a field type definition for a built-in field type, comprising React components that render\n * the built-in editor and preview components.\n * @param {string} name Field type name.\n * @returns {FieldTypeDefinition} Field type definition.\n */\nconst createBuiltInFieldType = (name) => ({\n  control: /** @type {any} */ (\n    createFieldComponent({ SvelteComponent: editors[name], buildProps: buildEditorProps })\n  ),\n  preview: /** @type {any} */ (\n    createFieldComponent({ SvelteComponent: previews[name], buildProps: buildPreviewProps })\n  ),\n});\n\n/**\n * Get the definition of a built-in field type.\n * @param {string} name Field type name.\n * @returns {FieldTypeDefinition | undefined} Field type definition, or `undefined` if the field\n * type cannot be reused.\n */\nconst getBuiltInFieldType = (name) => {\n  if (!REUSABLE_BUILTIN_FIELD_TYPES.includes(name)) {\n    if (/** @type {string[]} */ (BUILTIN_FIELD_TYPES).includes(name)) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `The built-in \"${name}\" field type cannot be reused in a custom field type, because its ` +\n          'editor works only within the entry editor. Reusable field types are: ' +\n          `${REUSABLE_BUILTIN_FIELD_TYPES.join(', ')}.`,\n      );\n    }\n\n    return undefined;\n  }\n\n  const cache = builtInFieldTypeCache.get(name);\n\n  if (cache) {\n    return cache;\n  }\n\n  const definition = createBuiltInFieldType(name);\n\n  builtInFieldTypeCache.set(name, definition);\n\n  return definition;\n};\n\n/**\n * Get the definition of a custom or built-in field type.\n * @param {string} name Field type name.\n * @param {Set<string>} [visited] Names of the field types already looked up, used to avoid an\n * infinite loop when custom field types reference each other.\n * @returns {FieldTypeDefinition | undefined} Field type definition, or `undefined` if the field\n * type is not available.\n */\nexport const getFieldTypeDefinition = (name, visited = new Set()) => {\n  const customFieldType = customFieldTypeRegistry.get(name);\n\n  if (!customFieldType) {\n    return getBuiltInFieldType(name);\n  }\n\n  const { control, preview, summary, schema } = customFieldType;\n\n  if (typeof control !== 'string') {\n    return { control, preview, summary, schema };\n  }\n\n  visited.add(name);\n\n  return {\n    // The control can be the name of another field type, which is resolved recursively\n    control: visited.has(control) ? undefined : getFieldTypeDefinition(control, visited)?.control,\n    preview,\n    summary,\n    schema,\n  };\n};\n","/**\n * Throw a `TypeError` with the given message unless the condition holds. The helpers for the\n * `CMS.*()` methods’ arguments below build their error messages on top of it.\n * @param {boolean} valid Whether the value is valid.\n * @param {string} message Error message.\n * @throws {TypeError} If `valid` is `false`.\n */\nexport const assertValid = (valid, message) => {\n  if (!valid) {\n    throw new TypeError(message);\n  }\n};\n\n/**\n * Check an option of a `CMS.*()` method, throwing a `TypeError` that names the option and method.\n * @param {boolean} valid Whether the option is valid.\n * @param {string} method Method name, e.g. `registerFieldType`.\n * @param {string} option Option name.\n * @param {string} expected What the option must be, e.g. `a non-empty string`.\n * @throws {TypeError} If `valid` is `false`.\n */\nexport const assertOption = (valid, method, option, expected) => {\n  assertValid(valid, `The \\`${option}\\` option for \\`CMS.${method}()\\` must be ${expected}`);\n};\n\n/**\n * Check a property of the definition object given to a `CMS.*()` method, throwing a `TypeError`\n * that names the property.\n * @param {boolean} valid Whether the property is valid.\n * @param {string} property Property name, without the `definition.` prefix.\n * @param {string} expected What the property must be, e.g. `a function`.\n * @throws {TypeError} If `valid` is `false`.\n */\nexport const assertDefinition = (valid, property, expected) => {\n  assertValid(valid, `The \\`definition.${property}\\` must be ${expected}`);\n};\n\n/**\n * Throw an error if the name is reserved for a built-in feature, so a custom one can’t shadow it.\n * @param {object} args Arguments.\n * @param {string} args.name Name the developer chose.\n * @param {readonly string[]} args.reserved Names of the built-in features.\n * @param {string} args.subject What is named, e.g. `field type`.\n * @param {string} args.builtin The built-in feature, e.g. `built-in field type`.\n * @param {string} args.custom The custom feature, e.g. `custom field type`.\n * @throws {Error} If the name is reserved.\n */\nexport const assertNotReserved = ({ name, reserved, subject, builtin, custom }) => {\n  if (reserved.includes(name)) {\n    throw new Error(\n      `The ${subject} name \"${name}\" is reserved for a ${builtin}. ` +\n        `Choose a different name for your ${custom}.`,\n    );\n  }\n};\n\n/**\n * Parse a URL or file path given by a developer, resolving a relative one against the page that\n * loaded the CMS now, as the CMS URL hash changes as the user navigates.\n * @param {string} url URL or file path.\n * @returns {URL | null} Absolute URL, or `null` if it can’t be parsed.\n */\nexport const parseURLFromPage = (url) => URL.parse(url, window.location.href);\n","import { getFieldTypeDefinition } from '$lib/services/api/field-types';\nimport { assertOption } from '$lib/services/api/validate';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { FieldTypeDefinition } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\n/**\n * Get the definition of a field type (widget), so that a custom field type can reuse the control\n * and/or preview component of another field type. The components are React components; for a\n * built-in field type, they render the built-in Svelte components internally. Only the built-in\n * field types that work outside the entry editor can be reused: `boolean`, `color`, `datetime`,\n * `map`, `number`, `select`, `string`, `text` and `uuid`. `CMS.getWidget()` is an alias of this\n * method for compatibility with Netlify/Decap CMS.\n * @param {string} name Field type name.\n * @returns {FieldTypeDefinition | undefined} Field type definition, or `undefined` if the field\n * type is not registered or cannot be reused.\n * @throws {TypeError} If `name` is not a non-empty string.\n * @see https://sveltiacms.app/en/docs/api/field-types\n */\nconst getFieldType = (name) => {\n  assertOption(isNonEmptyString(name), 'getFieldType', 'name', 'a non-empty string');\n\n  return getFieldTypeDefinition(name);\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `get-field-type.d.ts` file\nexport { getFieldType };\n","import { isAdditionsEnabled } from '$lib/services/app/additions';\nimport { getAuthRoot } from '$lib/services/backends/git/gitea/config';\nimport { isGiteaBackendName } from '$lib/services/backends/git/gitea/constants';\n\n/**\n * @import { Backend, ForgejoBackend, GitBackend, GiteaBackend } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} SignInOptions\n * @property {string | undefined} serviceLabel The label to use for the Sign In button, which is\n * usually the backend’s label but can be overridden for specific backends (e.g. Forgejo on\n * Codeberg) to provide a better UX.\n * @property {boolean} tokenOptionHidden Whether the option to sign in using a PAT should be hidden.\n * @property {boolean} oauthOptionHidden Whether the option to sign in using OAuth should be hidden.\n * @property {boolean} oauthOptionDisabled Whether the option to sign in using OAuth should be\n * disabled. This is used for Gitea with PKCE authentication, which requires an app ID to be\n * provided. We can’t check this during config validation because token authentication doesn’t\n * require an ID, so we check it here instead.\n * @see https://github.com/sveltia/sveltia-cms/issues/721\n */\n\n/**\n * Determine how to present the sign-in options for the configured backend.\n * @param {Backend} backendConfig Backend configuration.\n * @param {string | undefined} backendLabel Label of the backend service, if it’s supported.\n * @returns {SignInOptions} Sign-in options.\n */\nexport const getSignInOptions = (backendConfig, backendLabel) => {\n  const { name } = backendConfig;\n  const isTestRepo = name === 'test-repo';\n  const { auth_methods: authMethods } = /** @type {GitBackend} */ (backendConfig);\n  const giteaConfig = /** @type {GiteaBackend | ForgejoBackend} */ (backendConfig);\n  const isGitea = isGiteaBackendName(name);\n  // Sveltia CMS Additions replaces both the OAuth and the token options with its own\n  const additionsEnabled = isAdditionsEnabled(/** @type {any} */ ({ backend: backendConfig }));\n\n  return {\n    serviceLabel:\n      isGitea && getAuthRoot(giteaConfig) === 'https://codeberg.org' ? 'Codeberg' : backendLabel,\n    tokenOptionHidden:\n      additionsEnabled || (!isTestRepo && authMethods?.includes('token') === false),\n    oauthOptionHidden:\n      additionsEnabled || (!isTestRepo && authMethods?.includes('oauth') === false),\n    oauthOptionDisabled: isGitea && !giteaConfig.app_id,\n  };\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, ConfirmationDialog, Icon, PromptDialog, Spacer } from '@sveltia/ui';\n  import { onMount, untrack } from 'svelte';\n\n  import { DOCS_BASE_URL } from '$lib/services/app';\n  import { getAdditions } from '$lib/services/app/additions';\n  import { loadBackendService } from '$lib/services/backends';\n  import { isDemoSite } from '$lib/services/backends/fs/seed';\n  import { cancelAuthorization } from '$lib/services/backends/git/shared/auth';\n  import { cmsConfig } from '$lib/services/config';\n  import {\n    auth,\n    magicLinkConfirmation,\n    signInAutomatically,\n    signInManually,\n  } from '$lib/services/user/auth.svelte';\n  import { env } from '$lib/services/user/env.svelte';\n  import { getSignInOptions } from '$lib/services/user/sign-in-options';\n  import { makeLink } from '$lib/services/utils/string';\n  import { isWorkflowConfigured } from '$lib/services/workflow/config';\n\n  /**\n   * @import { BackendService } from '$lib/types/private';\n   * @import { Backend, GitBackend } from '$lib/types/public';\n   */\n\n  let showTokenDialog = $state(false);\n  let token = $state('');\n\n  const configuredBackend = $derived(/** @type {Backend} */ (cmsConfig.current?.backend));\n  const backendName = $derived(/** @type {string} */ (configuredBackend.name));\n  /**\n   * The configured backend service, once loaded: a Git backend other than GitHub is kept in a chunk\n   * of its own, which is only fetched for a site that uses it.\n   * @type {BackendService | undefined}\n   */\n  let backend = $state.raw();\n  const isTestRepo = $derived(backendName === 'test-repo');\n  const isDemo = $derived(isDemoSite(backendName));\n  const testRepoUnsupported = $derived(isTestRepo && !env.isTestBackendSupported);\n  // The test repository has no `repo` option, and the name only goes with the local option\n  const repositoryName = $derived(\n    /** @type {GitBackend} */ (configuredBackend).repo?.split('/').pop(),\n  );\n  const showLocalBackendOption = $derived(env.isLocalHost && !isTestRepo);\n  const trimmedToken = $derived(token.trim());\n  /**\n   * Whether to tell the user that the token also needs pull request access. Only a GitHub\n   * fine-grained token has that permission separate from the content one; a GitLab token with the\n   * `api` scope covers merge requests already.\n   */\n  const showWorkflowNote = $derived(\n    backendName === 'github' && isWorkflowConfigured(cmsConfig.current),\n  );\n\n  const { serviceLabel, tokenOptionHidden, oauthOptionHidden, oauthOptionDisabled } = $derived(\n    getSignInOptions(configuredBackend, backend?.label),\n  );\n\n  // Sveltia CMS Additions, whose chunk is loaded along with the backend if it’s enabled\n  const additions = $derived(getAdditions());\n\n  /* v8 ignore start -- the name is only read while the dialog is open, when the account is set */\n  /**\n   * Account name to show when the user is asked whether to sign in with a magic link.\n   */\n  const magicLinkAccountName = $derived.by(() => {\n    const { login, name } = magicLinkConfirmation.current?.account ?? {};\n\n    return login || name || '';\n  });\n  /* v8 ignore stop */\n\n  $effect(() => {\n    const name = backendName;\n\n    // Don’t offer the previous backend while the configured one is being loaded\n    backend = undefined;\n\n    loadBackendService(name).then(\n      (service) => {\n        // The configuration may have changed while the service was being loaded\n        if (name === backendName) {\n          backend = service;\n        }\n      },\n      () => {\n        // The automatic sign-in loads the same service and reports the failure\n      },\n    );\n  });\n\n  $effect(() => {\n    // With Sveltia CMS Additions, once its chunk is loaded: read the outcome of connecting the\n    // service to GitHub, if the user is coming back from there, and the sign-in methods it offers\n    if (additions) {\n      untrack(() => additions.prepareSignIn());\n    }\n  });\n\n  onMount(() => {\n    // Skip automatic sign-in if there’s already an error (e.g. repository access denied), so the\n    // error message is preserved and the user can try again with different credentials. Also skip\n    // it while a sign-in is in progress, which would otherwise select the configured backend while\n    // the user is signing in with the local one\n    if (!auth.signInError.message && !auth.signingIn) {\n      signInAutomatically();\n    }\n  });\n</script>\n\n<div role=\"none\" class=\"buttons\">\n  {#if auth.signingIn}\n    <div role=\"alert\" class=\"message\">{_('signing_in')}</div>\n    {#if cancelAuthorization.current}\n      <!--\n        The app can’t always tell when the user closes the sign-in popup, e.g. when GitLab’s sign-in\n        page has severed it from this window, so let the user get out of the pending sign-in\n      -->\n      <Button variant=\"secondary\" label={_('cancel')} onclick={cancelAuthorization.current} />\n    {/if}\n  {:else if additions?.additionsSetup.open}\n    <additions.SetupWizard />\n  {:else if backend}\n    {#if showLocalBackendOption}\n      <Button\n        variant=\"primary\"\n        label={_('work_with_local_repo')}\n        disabled={!env.isLocalBackendSupported}\n        onclick={async () => {\n          await signInManually('local');\n        }}\n      />\n      {#if !env.isLocalBackendSupported}\n        <div role=\"alert\">\n          {#if env.isBrave}\n            {@html makeLink(\n              _('local_workflow.disabled'),\n              `${DOCS_BASE_URL}/workflows/local#enabling-file-system-access-api-in-brave`,\n            )}\n          {:else}\n            {_('local_workflow.unsupported_browser')}\n          {/if}\n        </div>\n      {:else if !auth.signInError.message}\n        <div role=\"none\">\n          {#if repositoryName}\n            {_('work_with_local_repo_description', { values: { repo: repositoryName } })}\n          {:else}\n            {_('work_with_local_repo_description_no_repo')}\n          {/if}\n        </div>\n      {/if}\n      <Spacer />\n    {/if}\n    {#if additions}\n      <additions.SignInForm {backendName} primary={!showLocalBackendOption} />\n    {/if}\n    {#if !oauthOptionHidden}\n      <Button\n        variant={showLocalBackendOption ? 'secondary' : 'primary'}\n        label={isDemo\n          ? _('start_demo')\n          : isTestRepo\n            ? _('work_with_test_repo')\n            : _('sign_in_with_x', { values: { service: serviceLabel } })}\n        disabled={oauthOptionDisabled || testRepoUnsupported}\n        onclick={async () => {\n          await signInManually(backendName);\n        }}\n      />\n      {#if testRepoUnsupported}\n        <div role=\"alert\">{_('test_repo_unsupported_browser')}</div>\n      {/if}\n    {/if}\n    {#if !isTestRepo && !tokenOptionHidden}\n      <Button\n        variant=\"secondary\"\n        label={_('sign_in_using_access_token', { values: { service: serviceLabel } })}\n        onclick={() => {\n          showTokenDialog = true;\n        }}\n      />\n    {/if}\n  {/if}\n  {#if auth.signInError.message && auth.signInError.context === 'authentication'}\n    <div role=\"alert\" class=\"error iconic\">\n      <Icon name=\"error\" />\n      {auth.signInError.message}\n    </div>\n  {/if}\n</div>\n\n<PromptDialog\n  bind:open={showTokenDialog}\n  bind:value={token}\n  title={_('sign_in_using_access_token')}\n  textboxAttrs={{ spellcheck: false, ariaLabel: _('personal_access_token') }}\n  okLabel={_('sign_in')}\n  okDisabled={!trimmedToken}\n  onOk={() => {\n    signInManually(backendName, trimmedToken);\n  }}\n  onkeydown={(event) => {\n    if (!event.isComposing && event.key === 'Enter' && trimmedToken) {\n      event.preventDefault();\n      showTokenDialog = false;\n      signInManually(backendName, trimmedToken);\n    }\n  }}\n>\n  {_('sign_in_using_access_token_description')}\n  {#if showWorkflowNote}\n    {_('sign_in_using_access_token_workflow_note')}\n  {/if}\n  {#if backend?.repository?.tokenPageURL}\n    {@html makeLink(\n      _('sign_in_using_access_token_link', { values: { service: serviceLabel } }),\n      backend.repository.tokenPageURL,\n    )}\n  {/if}\n</PromptDialog>\n\n<ConfirmationDialog\n  open={!!magicLinkConfirmation.current}\n  title={_('sign_in_with_link')}\n  okLabel={_('sign_in')}\n  onOk={() => {\n    magicLinkConfirmation.current?.respond(true);\n  }}\n  onClose={() => {\n    // Covers the Cancel button, the Escape key and any other way out. Signing in has already\n    // settled the prompt, so this leaves it alone\n    magicLinkConfirmation.current?.respond(false);\n  }}\n>\n  {_('sign_in_with_link_confirmation', {\n    values: { account: magicLinkAccountName, service: serviceLabel },\n  })}\n</ConfirmationDialog>\n\n<style>\n  .buttons {\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    gap: 12px;\n\n    /* Only the buttons of the page itself, not the one that shows a password */\n    & > :global(.button) {\n      width: 320px;\n    }\n  }\n\n  [role='alert'] {\n    &.iconic {\n      display: flex;\n      align-items: center;\n      gap: 8px;\n    }\n\n    &.error {\n      color: var(--sui-error-foreground-color);\n    }\n  }\n</style>\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @typedef {object} BrowserFeature\n * @property {string} name Name of the feature, logged when it’s missing.\n * @property {() => boolean} test Function that tells whether the browser supports the feature.\n */\n\n/**\n * The most recently added JavaScript built-ins the app relies on. A browser lacking any of them is\n * too old to run the app: it would fail while loading the configuration, or later in ways the user\n * can’t make sense of, e.g. a rich text field that never updates the entry. Syntax the browser\n * doesn’t support can’t be detected here, as the bundle wouldn’t even load.\n * @type {BrowserFeature[]}\n */\nconst REQUIRED_FEATURES = [\n  {\n    name: 'Uint8Array Base64/hex conversion',\n    /**\n     * Supported by Chrome/Edge 140, Firefox 133 and Safari 18.2.\n     * @returns {boolean} Result.\n     */\n    test: () =>\n      typeof Uint8Array.fromBase64 === 'function' &&\n      typeof Uint8Array.prototype.toHex === 'function',\n  },\n  {\n    name: 'Iterator helpers',\n    /**\n     * Supported by Chrome/Edge 122, Firefox 131 and Safari 18.4.\n     * @returns {boolean} Result.\n     */\n    test: () =>\n      typeof globalThis.Iterator === 'function' &&\n      typeof globalThis.Iterator.prototype.map === 'function',\n  },\n];\n\n/**\n * Get the names of the features the app requires that the browser doesn’t support.\n * @returns {string[]} Feature names. Empty if the browser is supported.\n */\nexport const getMissingBrowserFeatures = () =>\n  REQUIRED_FEATURES.filter(({ test }) => !test()).map(({ name }) => name);\n\n/**\n * Names of the features the app requires that the browser doesn’t support. If there are any, the\n * app doesn’t load the configuration, and asks the user to update the browser instead.\n * @type {{ current: string[] }}\n */\nexport const missingBrowserFeatures = createRawState(getMissingBrowserFeatures());\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Progressbar } from '@sveltia/ui';\n\n  import SignIn from '$lib/components/entrance/sign-in.svelte';\n  import { appLogoURL, appTitle, DEFAULT_APP_TITLE } from '$lib/services/app/branding';\n  import { missingBrowserFeatures } from '$lib/services/app/browser-support';\n  import { announcedPageStatus } from '$lib/services/app/navigation';\n  import { inAuthPopup } from '$lib/services/backends/git/shared/auth';\n  import { cmsConfig, cmsConfigErrors, cmsConfigLoaded } from '$lib/services/config';\n  import { dataLoaded, dataLoadedProgress } from '$lib/services/contents';\n  import { user } from '$lib/services/user/account.svelte';\n  import { auth } from '$lib/services/user/auth.svelte';\n  import { prefs, prefsError } from '$lib/services/user/prefs.svelte';\n  import { sanitizeInlineMarkdown } from '$lib/services/utils/string';\n\n  const unsupportedBrowser = $derived(!!missingBrowserFeatures.current.length);\n  const dataFetchError = $derived(\n    !!auth.signInError.message && auth.signInError.context === 'dataFetch',\n  );\n\n  $effect(() => {\n    if (cmsConfigLoaded.current) {\n      announcedPageStatus.current = _('welcome_message', { values: { name: appTitle.current } });\n    }\n  });\n</script>\n\n{#snippet parseMarkdown(/** @type {string} */ str)}\n  {@html sanitizeInlineMarkdown(str, { allowedTags: ['a', 'code'] })}\n{/snippet}\n\n<div role=\"none\" class=\"container\">\n  <div role=\"none\" class=\"inner\">\n    <!-- An unsupported browser doesn’t load the configuration, so it gets the default branding -->\n    {#if cmsConfigLoaded.current || unsupportedBrowser}\n      <img src={appLogoURL.current} alt=\"\" class=\"logo\" />\n      <h1>{appTitle.current}</h1>\n    {/if}\n    {#if unsupportedBrowser}\n      <div role=\"alert\" class=\"message\">{_('unsupported_browser_error')}</div>\n    {:else if cmsConfigErrors.current.length}\n      <div role=\"alert\" class=\"message\">\n        <div role=\"none\">\n          {_('config.errors', { values: { count: cmsConfigErrors.current.length } })}\n        </div>\n        <ul class=\"error\">\n          {#each cmsConfigErrors.current as error (error)}\n            <li>\n              {@render parseMarkdown(error)}\n            </li>\n          {/each}\n        </ul>\n      </div>\n    {:else if prefsError.current}\n      <div role=\"alert\" class=\"message\">\n        {_(`prefs.error.${prefsError.current.type}`)}\n      </div>\n    {:else if !cmsConfig.current || !Object.keys(prefs).length}\n      <div role=\"alert\" class=\"message\">{_('loading_cms_config')}</div>\n    {:else if dataFetchError || (!inAuthPopup.current && (!user.account || auth.unauthenticated))}\n      <!--\n        One branch for both cases, so that the sign-in form isn’t mounted again — which would start\n        an automatic sign-in — when a manual sign-in clears the data loading error\n      -->\n      {#if dataFetchError}\n        <div role=\"alert\">\n          <div role=\"none\" class=\"message\">{_('loading_site_data_error')}</div>\n          <div role=\"none\" class=\"error\">\n            {@render parseMarkdown(auth.signInError.message)}\n          </div>\n        </div>\n      {/if}\n      <SignIn />\n    {:else if inAuthPopup.current}\n      <div role=\"alert\" class=\"message\">{_('authorizing')}</div>\n    {:else if !dataLoaded.current}\n      <div role=\"alert\" class=\"message\">{_('loading_site_data')}</div>\n      {#if dataLoadedProgress.current !== undefined}\n        <Progressbar now={dataLoadedProgress.current} />\n      {/if}\n    {/if}\n  </div>\n</div>\n\n{#if cmsConfigLoaded.current && appTitle.current !== DEFAULT_APP_TITLE}\n  <div role=\"none\" class=\"powered-by\">\n    {_('powered_by', { values: { name: DEFAULT_APP_TITLE } })}\n  </div>\n{/if}\n\n<style>\n  .container {\n    position: absolute;\n    inset: 0;\n    z-index: 101;\n    flex: auto;\n    display: flex;\n    gap: 16px;\n    padding: 32px;\n    overflow-y: auto;\n\n    .inner {\n      /* Centered with margins rather than `align-items`, so a tall form, e.g. the setup wizard,\n         scrolls from its top instead of overflowing above the window */\n      margin: auto;\n      display: flex;\n      flex-direction: column;\n      align-items: center;\n      gap: 32px;\n      min-width: 240px;\n      max-width: 800px;\n      min-height: 240px;\n    }\n\n    .logo {\n      width: auto;\n      height: 160px;\n\n      @media (width < 768px) {\n        height: 120px;\n      }\n    }\n\n    h1 {\n      font-size: 48px;\n    }\n\n    .logo ~ h1 {\n      font-size: var(--sui-font-size-xxx-large);\n    }\n\n    .error {\n      border-radius: var(--sui-control-medium-border-radius);\n      padding: 12px;\n      background-color: var(--sui-tertiary-background-color);\n      font-size: var(--sui-font-size-default);\n      text-align: center;\n      -webkit-user-select: text;\n      user-select: text;\n      cursor: text;\n    }\n\n    :global {\n      /* `<SignIn>` also has `.message` */\n      .message {\n        margin: 0 0 16px;\n        font-size: var(--sui-font-size-large);\n        font-weight: var(--sui-font-weight-normal);\n        text-align: center;\n\n        ul {\n          margin: 12px 0 0;\n          padding: 0;\n          max-height: 160px;\n          overflow-y: auto;\n          list-style: none;\n        }\n\n        li {\n          margin: 12px;\n          padding: 0;\n        }\n      }\n    }\n  }\n\n  .powered-by {\n    position: absolute;\n    inset: auto 24px 24px;\n    color: var(--sui-tertiary-foreground-color);\n    font-size: var(--sui-font-size-small);\n    text-align: center;\n  }\n</style>\n","<!--\n  @component\n  Prompt dialog asking the user for a commit message when the `prompt_commit_messages` backend\n  option is set. The save waits here until the user answers or cancels.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { PromptDialog, TextInput } from '@sveltia/ui';\n\n  import { commitMessageRequest } from '$lib/services/backends/commit-prompt';\n\n  /**\n   * @import { CommitMessageRequest } from '$lib/types/private';\n   */\n\n  const id = $props.id();\n  const request = $derived(commitMessageRequest.current);\n  // Writable, because the dialog sets it back to `false` when it’s dismissed\n  let open = $derived(!!request);\n  /**\n   * Whether the user has submitted the text with the Enter key. The answer is only sent once the\n   * dialog has closed, so the content can still read the request during the closing transition.\n   */\n  let submitted = false;\n\n  // These are only read while the dialog is open, for a request\n  const { mode, defaultMessage } = $derived(/** @type {CommitMessageRequest} */ (request));\n  // Writable, because the user edits it. It starts over with each new request, even if the initial\n  // value is the same as the last one’s\n  let value = $derived(/** @type {CommitMessageRequest} */ (request).initialValue);\n\n  /**\n   * Message as it will be recorded, shown with the `prefix` and `suffix` modes.\n   */\n  const preview = $derived.by(() => {\n    const text = value.trim();\n\n    if (!text) {\n      return defaultMessage;\n    }\n\n    return mode === 'prefix' ? `${text} ${defaultMessage}` : `${defaultMessage} ${text}`;\n  });\n</script>\n\n<PromptDialog\n  bind:open\n  title={_('commit_message.title')}\n  onOk={() => {\n    request?.respond(value);\n  }}\n  onClose={() => {\n    // Covers the Cancel button, the Escape key and any other way out of the dialog, as well as the\n    // Enter key. Clicking OK has already settled the request, so this leaves it alone\n    request?.respond(submitted ? value : null);\n    submitted = false;\n  }}\n>\n  {_(mode === true ? 'commit_message.description_replace' : 'commit_message.description_addition')}\n  {#snippet input()}\n    <TextInput\n      dir=\"auto\"\n      bind:value\n      flex\n      autofocus\n      ariaLabel={_(mode === true ? 'commit_message.message' : 'commit_message.addition')}\n      aria-describedby={mode === true ? undefined : `${id}-preview`}\n      onkeydown={(/** @type {KeyboardEvent} */ event) => {\n        // Submit with the Enter key, unless it’s confirming an IME conversion\n        if (event.key === 'Enter' && !event.isComposing) {\n          event.preventDefault();\n          submitted = true;\n          open = false;\n        }\n      }}\n    />\n    {#if mode !== true}\n      <div role=\"none\" id=\"{id}-preview\" class=\"preview\">\n        {_('commit_message.preview', { values: { message: preview } })}\n      </div>\n    {/if}\n  {/snippet}\n</PromptDialog>\n\n<style lang=\"scss\">\n  .preview {\n    margin: 8px 0 0;\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n    overflow-wrap: anywhere;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Infobar } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import { backend } from '$lib/services/backends';\n  import { cmsConfig } from '$lib/services/config';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @import { BackendServiceStatus } from '$lib/types/private';\n   */\n\n  const interval = 5 * 60 * 1000; // 5 minutes\n  let timer = 0;\n\n  /** @type {BackendServiceStatus} */\n  let status = $state('none');\n\n  /**\n   * Check if an update is available.\n   */\n  const checkStatus = async () => {\n    /* v8 ignore next 3 -- the checks only run for a backend that reports its status */\n    if (!backend.current?.checkStatus) {\n      return;\n    }\n\n    status = await backend.current.checkStatus();\n  };\n\n  /**\n   * Start checking the status.\n   */\n  const startChecking = () => {\n    // The effect below can start the checks again, so don’t leave the previous timer running\n    window.clearInterval(timer);\n    checkStatus();\n\n    timer = window.setInterval(() => {\n      checkStatus();\n    }, interval);\n  };\n\n  /**\n   * Stop checking the status.\n   */\n  const stopChecking = () => {\n    window.clearInterval(timer);\n    status = 'none';\n  };\n\n  /**\n   * Initialize the status checker.\n   */\n  const init = () => {\n    // Cannot get the status of the local backend or a self-hosted Git instance\n    if (backend.current?.checkStatus && !backend.current.repository?.isSelfHosted) {\n      startChecking();\n    } else {\n      stopChecking();\n    }\n  };\n\n  onMount(() =>\n    // onUnmount\n    () => {\n      stopChecking();\n    },\n  );\n\n  // Runs once mounted, and again whenever the backend or the configuration changes\n  $effect(() => {\n    void [backend.current, cmsConfig.current];\n    init();\n  });\n</script>\n\n{#if ['minor', 'major'].includes(status)}\n  <Infobar\n    status={status === 'major' ? 'error' : 'warning'}\n    --sui-infobar-message-justify-content=\"center\"\n  >\n    {_(`backend_status.${status}_incident`, { values: { service: backend.current?.label } })}\n    <Button\n      variant=\"link\"\n      label={_('details')}\n      onclick={() => {\n        openNewTab(backend.current?.statusDashboardURL);\n      }}\n    />\n  </Infobar>\n{/if}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Infobar } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import {\n    isUpdateAvailable,\n    UPDATE_CACHE_TIMEOUT,\n    UPDATE_CHECK_INTERVAL,\n  } from '$lib/services/app/update';\n\n  let interval = 0;\n  let timeout = 0;\n\n  let updateAvailable = $state(false);\n\n  /**\n   * Check for a new version of the application, and show the notification after a delay if a\n   * reload would pick it up. See {@link UPDATE_CACHE_TIMEOUT} for the reason of the delay.\n   */\n  const checkForUpdates = async () => {\n    if (await isUpdateAvailable()) {\n      timeout = window.setTimeout(() => {\n        updateAvailable = true;\n      }, UPDATE_CACHE_TIMEOUT);\n    }\n  };\n\n  /* v8 ignore start -- reloading the page would tear the test down */\n  /**\n   * Reload the page to pick up the new version.\n   */\n  const reload = () => {\n    window.location.reload();\n  };\n  /* v8 ignore stop */\n\n  onMount(() => {\n    // An npm install is updated with the package manager, not by reloading the page\n    if (import.meta.env.DEV || import.meta.env.NPM_BUILD) {\n      return undefined;\n    }\n\n    checkForUpdates();\n\n    interval = window.setInterval(() => {\n      checkForUpdates();\n    }, UPDATE_CHECK_INTERVAL);\n\n    // onUnmount\n    return () => {\n      window.clearInterval(interval);\n      window.clearTimeout(timeout);\n    };\n  });\n</script>\n\n{#if updateAvailable}\n  <Infobar --sui-infobar-message-justify-content=\"center\">\n    {_('update_available')}\n    <Button variant=\"link\" label={_('update_now')} onclick={reload} />\n  </Infobar>\n{/if}\n","export default {\"create\":\"New\",\"select\":\"Select\",\"select_all\":\"Select All\",\"select_item\":\"Select {$name}\",\"upload\":\"Upload\",\"copy\":\"Copy\",\"download\":\"Download\",\"duplicate\":\"Duplicate\",\"delete\":\"Delete\",\"reorder\":\"Reorder\",\"cancel\":\"Cancel\",\"done\":\"Done\",\"save\":\"Save\",\"saving\":\"Saving…\",\"publish\":\"Publish\",\"publishing\":\"Publishing…\",\"rename\":\"Rename\",\"update\":\"Update\",\"replace\":\"Replace\",\"add\":\"Add\",\"remove\":\"Remove\",\"clear\":\"Clear\",\"expand\":\"Expand\",\"expand_all\":\"Expand All\",\"collapse\":\"Collapse\",\"collapse_all\":\"Collapse All\",\"insert\":\"Insert\",\"restore\":\"Restore\",\"discard\":\"Discard\",\"searching\":\"Searching…\",\"no_results\":\"No results found.\",\"global\":\"Global\",\"primary\":\"Primary\",\"secondary\":\"Secondary\",\"collection\":\"Collection\",\"folder\":\"Folder\",\"folders\":\"Folders\",\"more_folders\":\"More Folders\",\"api_key\":\"API Key\",\"details\":\"Details\",\"back\":\"Back\",\"automatic\":\"Automatic\",\"loading\":\"Loading…\",\"later\":\"Later\",\"slug\":\"Slug\",\"singleton\":\"Singleton\",\"singletons\":\"Singletons\",\"clipboard_error\":\"Couldn’t copy to clipboard.\",\"welcome_message\":\"Welcome to {$name}\",\"powered_by\":\"Powered by {$name}\",\"unsupported_browser_error\":\"Your browser is not supported. Please update it to the latest version or use another browser.\",\"loading_cms_config\":\"Loading CMS Configuration…\",\"loading_site_data\":\"Loading Site Data…\",\"loading_site_data_error\":\"There was an error while loading site data.\",\"sign_in_with_x\":\"Sign In with {$service}\",\"sign_in_using_access_token\":\"Sign In Using Access Token\",\"sign_in_using_access_token_description\":\"Enter your token below. It must have read/write access to the repository content.\",\"sign_in_using_access_token_workflow_note\":\"Since Editorial Workflow is enabled, it must also have read/write access to pull requests.\",\"sign_in_using_access_token_link\":\"You can generate a token on the <a>{$service} user settings page</a>.\",\"personal_access_token\":\"Personal Access Token\",\"authorizing\":\"Authorizing…\",\"signing_in\":\"Signing in…\",\"work_with_local_repo\":\"Work with Local Repository\",\"work_with_local_repo_description\":\"Once prompted, select the root directory of the “{$repo}” repository.\",\"work_with_local_repo_description_no_repo\":\"Once prompted, select the root directory of your Git repository.\",\"work_with_test_repo\":\"Work with Test Repository\",\"start_demo\":\"Start Demo\",\"test_repo_unsupported_browser\":\"Your browser can’t save the files of the test repository. Please update it to the latest version or use another browser.\",\"sign_in_error\":{\"not_project_root\":\"The selected folder is not a repository root directory. Please try again.\",\"picker_dismissed\":\"A repository root directory could not be selected. Please try again.\",\"authentication_aborted\":\"Authentication aborted. Please try again.\",\"invalid_token\":\"The provided token is invalid. Please check and try again.\",\"UNSUPPORTED_BACKEND\":\"Your Git backend is not supported by the authenticator.\",\"UNSUPPORTED_DOMAIN\":\"Your domain is not allowed to use the authenticator.\",\"MISCONFIGURED_CLIENT\":\"OAuth app client ID or secret is not configured.\",\"AUTH_CODE_REQUEST_FAILED\":\"Failed to receive an authorization code. Please try again later.\",\"CSRF_DETECTED\":\"Potential CSRF attack detected. Authentication flow aborted.\",\"TOKEN_REQUEST_FAILED\":\"Failed to request an access token. Please try again later.\",\"TOKEN_REFRESH_FAILED\":\"Failed to refresh the access token. Please try again later.\",\"MALFORMED_RESPONSE\":\"Server responded with malformed data. Please try again later.\"},\"backend_unsupported_version\":\"The {$name} backend requires {$name} {$version} or later.\",\"repository_no_access\":\"You don’t have access to the “{$repo}” repository.\",\"repository_no_write_access\":\"You don’t have write access to the “{$repo}” repository.\",\"repository_not_found\":\"The “{$repo}” repository doesn’t exist.\",\"repository_empty\":\"The “{$repo}” repository has no branches.\",\"branch_not_found\":\"The “{$repo}” repository doesn’t have the “{$branch}” branch.\",\"root_dir_not_found\":\"The root directory “{$dir}” doesn’t exist in the “{$repo}” repository.\",\"unexpected_error\":\"Unexpected Error\",\"page_crashed\":\"Something went wrong, and this page can’t be displayed. {$message}\",\"field_crashed\":\"Something went wrong, and this field can’t be displayed. {$message}\",\"try_again\":\"Try Again\",\"reload_cms\":\"Reload CMS\",\"entry_parse_errors\":\".input {$count :integer} .match $count one {{There was an error while parsing an entry file. Check the browser console for details.}} * {{There were errors while parsing entry files. Check the browser console for details.}}\",\"username\":\"Username\",\"password\":\"Password\",\"sign_in\":\"Sign In\",\"sign_in_with_mobile\":\"Sign In with Mobile\",\"sign_in_with_mobile_instruction\":\"Scan the QR code below with your phone or tablet for passwordless sign-in. Your settings will be automatically copied.\",\"sign_in_with_link\":\"Sign In with Link\",\"sign_in_with_link_confirmation\":\"This link signs you in as {$account} on {$service} and copies the settings from the device it was created on. Continue only if you created the link yourself.\",\"signed_in_as_x\":\"Signed In as {$name}\",\"working_with_local_repo\":\"Working with Local Repository\",\"working_with_test_repo\":\"Working with Test Repository\",\"working_in_demo_mode\":\"Demo Mode\",\"demo_welcome\":{\"title\":\"Welcome to Sveltia CMS Demo\",\"description\":\"Feel free to explore the CMS and edit the sample content. Your changes are only saved in this browser. Nothing is published online, and no one else can see them.\",\"reset_hint\":\"To start over with the original content, select Erase All Data under Settings > Data Management.\",\"button_label\":\"Get Started\"},\"sign_out\":\"Sign Out\",\"install_as_app\":\"Install as App\",\"contents\":\"Contents\",\"assets\":\"Assets\",\"editorial_workflow\":\"Editorial Workflow\",\"drafts\":\"Drafts\",\"cms_config\":\"CMS Configuration\",\"menu\":\"Menu\",\"custom_pages\":\"Pages\",\"mobile_promo_title\":\"Sveltia CMS is now available on mobile!\",\"mobile_promo_button\":\"Give it a try\",\"new_language_available\":\"Sveltia CMS is now available in {$locale}!\",\"change_language\":\"Change Language\",\"live_reload_warning\":\"Your development server reloads this page whenever a file changes, which can interrupt saving and leave your files broken. Serve the CMS from a static HTML file instead. <a>Learn more</a>\",\"switching_language\":\"Switching to {$locale}…\",\"locale_load_failed\":\"Couldn’t load the {$locale} translation. Please try again later.\",\"local_git_not_committed\":\"Your changes have been saved but not committed to Git. {$reason} To only save the files, turn off Git commits under Settings > Developer.\",\"local_git_skip_reasons\":{\"unsupported_repository\":\"Your repository uses a Git feature the CMS doesn’t support, such as a linked worktree, SHA-256 object names, the reftable format, a sparse index, or an index in version 3 or 4, which the feature.manyFiles option and git add -N use.\",\"missing_identity\":\"Your name and email address aren’t set in the repository’s Git configuration, and the CMS can’t read your global one. Set them in the repository with git config --local user.name \\\"Your Name\\\" and git config --local user.email \\\"you@example.com\\\".\",\"locked\":\"Another Git process is using the repository. If none is running, delete the .git/index.lock file.\",\"operation_in_progress\":{\"merge\":\"A merge is in progress. Finish it with git commit, or cancel it with git merge --abort.\",\"rebase\":\"A rebase is in progress. Finish it with git rebase --continue, or cancel it with git rebase --abort. If you’ve moved on, git rebase --quit drops it without changing your files.\",\"cherry_pick\":\"A cherry-pick is in progress. Finish it with git cherry-pick --continue, or cancel it with git cherry-pick --abort.\",\"revert\":\"A revert is in progress. Finish it with git revert --continue, or cancel it with git revert --abort.\",\"am\":\"Applying patches with git am is in progress. Finish it with git am --continue, or cancel it with git am --abort.\",\"conflict\":\"Some files have conflicts. Resolve them and stage the results first.\"},\"detached_head\":\"No branch is checked out.\",\"staged_changes\":\"You have other changes staged for commit. Commit or unstage them first.\",\"lfs\":\"{$path} is tracked with Git LFS, which the CMS can’t commit to.\",\"error\":\"An unexpected error occurred. {$message}\"},\"visit_live_site\":\"Visit Live Site\",\"switch_page\":\"Switch Page\",\"search_placeholder_contents\":\"Search for contents…\",\"search_placeholder_assets\":\"Search for assets…\",\"search_placeholder_all\":\"Search for contents and assets…\",\"create_entry_or_assets\":\"Create Entry or Assets\",\"publish_changes\":\"Publish Changes\",\"publishing_changes\":\"Publishing Changes…\",\"publishing_changes_failed\":\"Couldn’t publish changes. Please try again.\",\"show_notifications\":\"Show Notifications\",\"notifications\":\"Notifications\",\"show_account_menu\":\"Show Account Menu\",\"account\":\"Account\",\"live_site\":\"Live Site\",\"git_repository\":\"Git Repository\",\"settings\":\"Settings\",\"administration\":\"Administration\",\"show_help_menu\":\"Show Help Menu\",\"help\":\"Help\",\"keyboard_shortcuts\":\"Keyboard Shortcuts\",\"documentation\":\"Documentation\",\"release_notes\":\"Release Notes\",\"announcements\":\"Announcements\",\"version_x\":\"Version {$version}\",\"report_issue\":\"Report Issue\",\"share_feedback\":\"Share Feedback\",\"get_help\":\"Get Help\",\"donate\":\"Donate\",\"join_discord\":\"Join Us on Discord\",\"bluesky\":\"Follow Us on Bluesky\",\"update_available\":\"The latest version of Sveltia CMS is available.\",\"update_now\":\"Update Now\",\"backend_status\":{\"minor_incident\":\"{$service} is experiencing a minor incident. Your workflow may be affected.\",\"major_incident\":\"{$service} is experiencing a major incident. You may want to wait until the situation has improved.\"},\"content_library\":\"Content Library\",\"asset_library\":\"Asset Library\",\"collections\":\"Collections\",\"entries\":\"Entries\",\"files\":\"Files\",\"asset_location\":{\"repository\":\"Your Site\",\"external\":\"External Locations\",\"stock_photos\":\"Stock Photos\"},\"collection_assets\":\"Collection Assets\",\"entry_list\":\"Entry List\",\"file_list\":\"File List\",\"asset_list\":\"Asset List\",\"x_collection\":\"{$collection} Collection\",\"x_asset_folder\":\"{$folder} Asset Folder\",\"viewing_collection_list\":\"You’re now viewing the collection list.\",\"viewing_asset_folder_list\":\"You’re now viewing the asset folder list.\",\"viewing_x_collection\":\".input {$count :integer} .match $count 0 {{You’re now viewing the “{$collection}” collection, which has no entries yet.}} one {{You’re now viewing the “{$collection}” collection, which has one entry.}} * {{You’re now viewing the “{$collection}” collection, which has {$count} entries.}}\",\"viewing_x_asset_folder\":\".input {$count :integer} .match $count 0 {{You’re now viewing the “{$folder}” asset folder, which has no assets yet.}} one {{You’re now viewing the “{$folder}” asset folder, which has one asset.}} * {{You’re now viewing the “{$folder}” asset folder, which has {$count} assets.}}\",\"viewing_x_external_location\":\"You’re now viewing the assets on {$service}.\",\"viewing_admin_section_list\":\"You’re now viewing the list of Administration sections.\",\"viewing_x_admin_section\":\"You’re now viewing the “{$section}” section of the Administration page.\",\"singleton_selected_announcement\":\"Press Enter to edit the “{$file}” file.\",\"page_not_found\":\"Page not found.\",\"collection_not_found\":\"Collection not found.\",\"asset_folder_not_found\":\"Asset folder not found.\",\"file_not_found\":\"File not found.\",\"x_of_x_selected\":\"{$selected} of {$total} selected\",\"switch_view\":\"Switch View\",\"table_view\":\"Table View\",\"list_view\":\"List View\",\"grid_view\":\"Grid View\",\"switch_to_list_view\":\"Switch to List View\",\"switch_to_grid_view\":\"Switch to Grid View\",\"sort\":\"Sort\",\"sorting_options\":\"Sorting Options\",\"table_column_keys\":{\"dirname\":\"Folder\",\"filename\":\"File Name\",\"extension\":\"Extension\",\"locales\":\"Languages\"},\"sort_keys\":{\"none\":\"None\",\"name\":\"Name\",\"slug\":\"Slug\",\"commit_author\":\"Updated by\",\"commit_date\":\"Updated on\",\"last_modified\":\"Modified on\",\"size\":\"Size\",\"_summary\":\"Summary\",\"_manual\":\"Manual\"},\"ascending\":\"{$label}, A to Z\",\"ascending_date\":\"{$label}, old to new\",\"descending\":\"{$label}, Z to A\",\"descending_date\":\"{$label}, new to old\",\"ascending_number\":\"{$label}, small to large\",\"descending_number\":\"{$label}, large to small\",\"filter\":\"Filter\",\"filtering_options\":\"Filtering Options\",\"group\":\"Group\",\"grouping_options\":\"Grouping Options\",\"type\":\"Type\",\"all\":\"All\",\"domain\":\"Domain\",\"image\":\"Image\",\"video\":\"Video\",\"audio\":\"Audio\",\"document\":\"Document\",\"other\":\"Other\",\"show_assets\":\"Show Assets\",\"hide_assets\":\"Hide Assets\",\"show_info\":\"Show Info\",\"hide_info\":\"Hide Info\",\"all_assets\":\"All Assets\",\"global_assets\":\"Global Assets\",\"linked_files\":\"Linked Files\",\"file_unavailable\":\"Unavailable\",\"file_unavailable_description\":\"This file couldn’t be loaded. It may have been moved or deleted.\",\"loading_entries\":\".input {$count :integer} .match $count one {{Loading entry…}} * {{Loading entries…}}\",\"entry_not_found\":\"Entry not found.\",\"creating_entries_disabled_by_admin\":\"Creating new entries in this collection is disabled by the administrator.\",\"creating_entries_disabled_by_quota\":\".input {$quota :integer} .match $quota one {{You cannot add new entries to this collection because it has reached its limit of {$quota} entry.}} * {{You cannot add new entries to this collection because it has reached its limit of {$quota} entries.}}\",\"creating_entries_nearing_quota\":\".input {$quota :integer} .input {$remaining :integer} .match $quota $remaining one one {{This collection is nearing its limit of {$quota} entry. You can only create {$remaining} more entry.}} one * {{This collection is nearing its limit of {$quota} entry. You can only create {$remaining} more entries.}} * one {{This collection is nearing its limit of {$quota} entries. You can only create {$remaining} more entry.}} * * {{This collection is nearing its limit of {$quota} entries. You can only create {$remaining} more entries.}}\",\"readonly_cms\":\"The CMS is in read-only mode. You can view content and assets but cannot make any changes.\",\"readonly_collection\":\"This collection is read-only. You can view its content but cannot make any changes.\",\"readonly_entry\":\"This entry is read-only. You can view it but cannot make any changes.\",\"readonly_asset_folder\":\"This folder is read-only. You can view its assets but cannot make any changes.\",\"readonly_branch\":\"You don’t have permission to push to the “{$branch}” branch. You can view this content but cannot make any changes.\",\"readonly_role\":\"You have view-only access. You can view content and assets but cannot make any changes.\",\"readonly_reference\":\"The entry is read-only, so the reference can’t be removed.\",\"cannot_rename_referenced_entry\":\"This entry can’t be renamed, because the following read-only entries refer to it by its current name: {$entries}.\",\"cannot_move_referenced_asset\":\"This asset can’t be moved or renamed, because the following read-only entries use it: {$entries}.\",\"back_to_collection\":\"Back to Collection\",\"collection_list\":\"Collection List\",\"back_to_collection_list\":\"Back to Collection List\",\"asset_folder_list\":\"Asset Folder List\",\"back_to_asset_folder_list\":\"Back to Asset Folder List\",\"back_to_parent_folder\":\"Back to Parent Folder\",\"search_results\":\"Search Results\",\"search_results_for_x\":\"Search Results for “{$terms}”\",\"viewing_entry_search_results\":\".input {$count :integer} .match $count 0 {{You’re now viewing search results for “{$terms}”. We couldn’t find any entries.}} one {{You’re now viewing search results for “{$terms}”. We’ve found one entry.}} * {{You’re now viewing search results for “{$terms}”. We’ve found {$count} entries.}}\",\"viewing_asset_search_results\":\".input {$count :integer} .match $count 0 {{You’re now viewing search results for “{$terms}”. We couldn’t find any assets.}} one {{You’re now viewing search results for “{$terms}”. We’ve found one asset.}} * {{You’re now viewing search results for “{$terms}”. We’ve found {$count} assets.}}\",\"x_entries\":\".input {$count :integer} .match $count 0 {{No entries}} one {{{$count} entry}} * {{{$count} entries}}\",\"x_assets\":\".input {$count :integer} .match $count 0 {{No assets}} one {{{$count} asset}} * {{{$count} assets}}\",\"no_files_found\":\"No files found.\",\"no_entries_found\":\"No entries found.\",\"upload_assets\":\"Upload New Assets\",\"new_folder\":\"New Folder\",\"new_folder_name\":\"Folder Name\",\"new_folder_create\":\"Create\",\"new_folder_description\":\"The new folder will be created in “{$folder}”.\",\"new_folder_error\":{\"empty\":\"The folder name cannot be empty.\",\"invalid\":\"The folder name cannot contain slashes or start with a dot.\",\"reserved\":\"The files in a folder with this name are read-only, as the CMS itself is usually served from it.\",\"duplicate\":\"A folder or file with this name already exists here.\"},\"creating_folder\":\"Creating the folder…\",\"creating_folder_failed\":\"Couldn’t create the folder.\",\"folder_options\":\"Folder Options\",\"show_folder_options\":\"Show Folder Options\",\"rename_folder\":\"Rename Folder\",\"delete_folder\":\"Delete Folder\",\"enter_new_name_for_folder\":\".input {$count :integer} .match $count 0 {{Enter a new name below.}} one {{Enter a new name below. The asset in the folder will be moved along, and any entry using it will be updated.}} * {{Enter a new name below. The {$count} assets in the folder will be moved along, and any entries using them will be updated.}}\",\"confirm_deleting_folder\":\".input {$count :integer} .match $count 0 {{Are you sure you want to delete the empty “{$name}” folder?}} one {{Are you sure you want to delete the “{$name}” folder and the asset in it?}} * {{Are you sure you want to delete the “{$name}” folder and the {$count} assets in it?}}\",\"renaming_folder\":\"Renaming the folder…\",\"renaming_folder_failed\":\"Couldn’t rename the folder.\",\"deleting_folder\":\"Deleting the folder…\",\"deleting_folder_failed\":\"Couldn’t delete the folder.\",\"external_assets_truncated\":\"There are too many files on the service to list them all, so some of them are left out.\",\"edit_options\":\"Edit Options\",\"show_edit_options\":\"Show Edit Options\",\"copy_options\":\"Copy Options\",\"edit_asset\":\"Edit Asset\",\"edit_x\":\"Edit {$name}\",\"wrap_long_lines\":\"Wrap Long Lines\",\"move\":\"Move\",\"move_asset\":\"Move Asset\",\"move_assets_title\":\".input {$count :integer} .match $count one {{Move {$name}}} * {{Move {$count} Assets}}\",\"select_asset_move_destination\":\".input {$count :integer} .match $count 0 {{Select the folder to move to.}} one {{Select the folder to move to. An entry using the assets will also be updated.}} * {{Select the folder to move to. {$count} entries using the assets will also be updated.}}\",\"asset_move_destination\":\"Destination Folder\",\"assets_already_in_folder\":\".input {$count :integer} .match $count one {{The asset is already in this folder.}} * {{The assets are already in this folder.}}\",\"asset_move_conflict\":\"The following files already exist in this folder: {$names}.\",\"moving_assets\":\"Moving the assets…\",\"moving_assets_failed\":\"Couldn’t move the assets.\",\"asset_move_cleanup_failed\":\"The files have been moved, but the originals couldn’t be deleted from the storage service.\",\"cannot_change_used_external_files\":\".input {$count :integer} .match $count one {{This file can’t be renamed or moved, because the entries using it can’t be updated.}} * {{These files can’t be renamed or moved, because the entries using them can’t be updated.}}\",\"rename_asset\":\"Rename Asset\",\"rename_x\":\"Rename {$name}\",\"enter_new_name_for_asset\":\".input {$count :integer} .match $count 0 {{Enter a new name below.}} one {{Enter a new name below. An entry using the asset will also be updated.}} * {{Enter a new name below. {$count} entries using the asset will also be updated.}}\",\"enter_new_name_for_asset_error\":{\"empty\":\"File name cannot be empty.\",\"character\":\"File name cannot contain special characters.\",\"duplicate\":\"This file name is used for another asset.\",\"leading_dot\":\"File name cannot start with a dot.\",\"file_duplicate\":\"Another file with this name already exists here.\",\"folder_duplicate\":\"A folder with this name already exists here.\"},\"file_will_be_saved_as\":\"The file will be saved as “{$name}”.\",\"change_file_extension\":\"Change File Extension\",\"confirm_file_extension_change\":{\"change\":\"Are you sure you want to change the extension from “.{$oldExtension}” to “.{$newExtension}”?\",\"add\":\"Are you sure you want to add the extension “.{$newExtension}”?\",\"remove\":\"Are you sure you want to remove the extension “.{$oldExtension}”?\"},\"file_extension_change_warning\":\"The file may not be displayed or handled correctly if the extension doesn’t match the actual file format.\",\"replace_asset\":\"Replace Asset\",\"replace_x\":\"Replace {$name}\",\"replace_file\":\"Replace File\",\"replace_image\":\"Replace Image\",\"remove_file\":\"Remove File\",\"remove_image\":\"Remove Image\",\"click_to_browse\":\"Click to browse…\",\"tap_to_browse\":\"Tap to browse…\",\"drop_files_or_click_to_browse\":\".input {$count :integer} .match $count one {{Drop a file here or click to browse…}} * {{Drop files here or click to browse…}}\",\"drop_files_or\":\".input {$count :integer} .match $count one {{Drop a file here or}} * {{Drop files here or}}\",\"drop_image_files_or\":\".input {$count :integer} .match $count one {{Drop an image file here or}} * {{Drop image files here or}}\",\"browse\":\"Browse\",\"paste\":\"Paste\",\"paste_image\":\"Paste Image\",\"no_image_in_clipboard\":\"No image found in clipboard.\",\"clipboard_access_denied\":\"Clipboard access denied.\",\"drop_files_here\":\".input {$count :integer} .match $count one {{Drop a file here}} * {{Drop files here}}\",\"unsupported_file_type\":\"Unsupported File Type\",\"dropped_file_type_mismatch\":\"The dropped file is not one of the following types: {$types}. Please try again.\",\"dropped_image_type_mismatch\":\"The dropped file is not supported. Only an image of the following types is accepted: {$types}. Please try again.\",\"choose_files\":\".input {$count :integer} .match $count one {{Choose File}} * {{Choose Files}}\",\"delete_assets\":\".input {$count :integer} .match $count one {{Delete Asset}} * {{Delete Assets}}\",\"delete_selected_assets\":\".input {$count :integer} .match $count one {{Delete Selected Asset}} * {{Delete Selected Assets}}\",\"confirm_deleting_this_asset\":\"Are you sure you want to delete this asset?\",\"confirm_deleting_selected_assets\":\".input {$count :integer} .match $count one {{Are you sure you want to delete the selected asset?}} * {{Are you sure you want to delete the selected {$count} assets?}}\",\"confirm_deleting_all_assets\":\"Are you sure you want to delete all the assets?\",\"deleting_referenced_assets_note\":\".input {$count :integer} .match $count one {{The reference to it in an entry will be removed as well.}} * {{The references to it in {$count} entries will be removed as well.}}\",\"cannot_delete_referenced_assets\":\".input {$count :integer} .match $count one {{This asset can’t be deleted, because the following fields in the entries using it would no longer be valid without it. Update those entries first.}} * {{These assets can’t be deleted, because the following fields in the entries using them would no longer be valid without them. Update those entries first.}}\",\"checking_asset_references_failed\":\".input {$count :integer} .match $count one {{Couldn’t check which entries use this asset. Close this dialog and try again.}} * {{Couldn’t check which entries use these assets. Close this dialog and try again.}}\",\"delete_entries\":\".input {$count :integer} .match $count one {{Delete Entry}} * {{Delete Entries}}\",\"delete_selected_entries\":\".input {$count :integer} .match $count one {{Delete Selected Entry}} * {{Delete Selected Entries}}\",\"confirm_deleting_this_entry\":\"Are you sure you want to delete this entry?\",\"confirm_deleting_this_entry_with_assets\":\"Are you sure you want to delete this entry and associated assets?\",\"deleting_entry_failed\":\"Couldn’t delete the entry. Please try again.\",\"confirm_deleting_selected_entries\":\".input {$count :integer} .match $count one {{Are you sure you want to delete the selected entry?}} * {{Are you sure you want to delete the selected {$count} entries?}}\",\"confirm_deleting_selected_entries_with_assets\":\".input {$count :integer} .match $count one {{Are you sure you want to delete the selected entry and associated assets?}} * {{Are you sure you want to delete the selected {$count} entries and associated assets?}}\",\"confirm_deleting_all_entries\":\"Are you sure you want to delete all the entries?\",\"confirm_deleting_all_entries_with_assets\":\"Are you sure you want to delete all the entries and associated assets?\",\"deleting_referenced_entries_note\":\".input {$count :integer} .match $count one {{The reference to it in another entry will be removed as well.}} * {{The references to it in {$count} other entries will be removed as well.}}\",\"cannot_delete_referenced_entries\":\".input {$count :integer} .match $count one {{This entry can’t be deleted, because the following fields in other entries would no longer be valid without it. Update those entries first.}} * {{These entries can’t be deleted, because the following fields in other entries would no longer be valid without them. Update those entries first.}}\",\"reorder_entries\":\"Reorder Entries\",\"done_reordering_entries\":\"Done Reordering Entries\",\"cancel_reordering_entries\":\"Cancel Reordering Entries\",\"saving_reorder_failed\":\"Failed to save new entry order. Please try again.\",\"bulk_edit_entries\":\"Edit Entries in Bulk\",\"save_bulk_edits\":\"Save Bulk Edits\",\"cancel_bulk_edits\":\"Cancel Bulk Edits\",\"bulk_edit_entry\":\"Entry\",\"bulk_edit_table\":\"Bulk Editor\",\"bulk_edit_cell\":\"{$field} of {$entry}\",\"bulk_edit_count\":\".input {$count :integer} .match $count 0 {{No changes}} one {{1 change}} * {{{$count} changes}}\",\"bulk_edit_invalid\":\"Some of the values aren’t valid. Fix the highlighted fields and try again.\",\"saving_bulk_edits_failed\":\"Failed to save the changes. Please try again.\",\"discard_bulk_edits_confirm\":\"Discard the changes made to the entries?\",\"processing_files\":\".input {$count :integer} .match $count one {{Processing a file. This may take a while.}} * {{Processing files. This may take a while.}}\",\"uploading_files\":\"Uploading Files\",\"confirm_replacing_file\":\"“{$name}” will be replaced with this file:\",\"confirm_uploading_files\":\".input {$count :integer} .match $count one {{This file will be saved to the “{$folder}” folder:}} * {{These {$count} files will be saved to the “{$folder}” folder:}}\",\"oversized_files\":\"Oversized Files\",\"warning_oversized_files\":\".input {$count :integer} .match $count one {{This file cannot be uploaded because it exceeds the maximum size of {$size}. Please reduce the size or select a different file.}} * {{These files cannot be uploaded because they exceed the maximum size of {$size}. Please reduce the sizes or select different files.}}\",\"invalid_files\":\"Invalid Files\",\"warning_invalid_files\":\".input {$count :integer} .match $count one {{This file cannot be uploaded because it’s damaged, or its content doesn’t match its file extension. This often happens when a photo is renamed rather than converted, such as a HEIC image saved as a JPEG file. Please convert the file and try again.}} * {{These files cannot be uploaded because they’re damaged, or their content doesn’t match their file extensions. This often happens when photos are renamed rather than converted, such as HEIC images saved as JPEG files. Please convert the files and try again.}}\",\"warning_unsupported_files\":\".input {$count :integer} .match $count one {{This file cannot be uploaded because it’s not one of the following types: {$types}.}} * {{These files cannot be uploaded because they’re not one of the following types: {$types}.}}\",\"warning_unsupported_image_files\":\".input {$count :integer} .match $count one {{This file cannot be uploaded because only an image of the following types is accepted: {$types}.}} * {{These files cannot be uploaded because only images of the following types are accepted: {$types}.}}\",\"mismatched_files\":\"Mismatched Files\",\"warning_mismatched_files\":\".input {$count :integer} .match $count one {{This file cannot replace “{$name}” because it’s in a different format. Please convert the file to the same format and try again.}} * {{These files cannot replace “{$name}” because they’re in a different format. Please convert the files to the same format and try again.}}\",\"file_name_conflict_confirmation\":\".input {$count :integer} .match $count one {{A file with the same name already exists in this folder. Do you want to replace it?}} * {{{$count} files with the same names already exist in this folder. Do you want to replace them?}}\",\"file_name_conflict_confirmation_with_name\":\".input {$count :integer} .input {$name :string} .match $count one {{A file named “{$name}” already exists in this folder. Do you want to replace it?}} * {{{$count} files with the same names already exist in this folder. Do you want to replace them?}}\",\"file_name_conflict_resolution\":\"File Name Conflict Resolution\",\"keep_both\":\"Keep Both\",\"uploading_files_progress\":\"Uploading…\",\"uploading_files_failed\":\"Upload failed.\",\"deleting_assets_failed\":\"Delete failed.\",\"renaming_asset_failed\":\"Rename failed.\",\"saving_asset_failed\":\"Save failed.\",\"file_meta_converted_from_x\":\"(converted from {$type})\",\"no_entries_created\":\"This collection has no entries yet.\",\"create_new_entry\":\"Create New Entry\",\"entry\":\"Entry\",\"index_file\":\"Index File\",\"no_files_in_collection\":\"No files available in this collection.\",\"duplicate_entry\":\"Duplicate Entry\",\"entry_duplicated\":\"Entry duplicated as a new draft.\",\"entry_validation_errors\":\".input {$count :integer} .match $count one {{One field has an error. Please correct it to save the entry.}} * {{{$count} fields have errors. Please correct them to save the entry.}}\",\"show_errors\":\"Show Errors\",\"entry_saved\":\".input {$count :integer} .match $count one {{Entry saved.}} * {{{$count} entries saved.}}\",\"entry_saved_and_published\":\".input {$count :integer} .match $count one {{Entry saved and published.}} * {{{$count} entries saved and published.}}\",\"entries_deleted\":\".input {$count :integer} .match $count one {{Entry deleted.}} * {{{$count} entries deleted.}}\",\"assets_saved\":\".input {$count :integer} .match $count one {{Asset saved.}} * {{{$count} assets saved.}}\",\"assets_saved_and_published\":\".input {$count :integer} .match $count one {{Asset saved and published.}} * {{{$count} assets saved and published.}}\",\"asset_urls_copied\":\".input {$count :integer} .match $count one {{URL copied to clipboard.}} * {{{$count} URLs copied to clipboard.}}\",\"asset_paths_copied\":\".input {$count :integer} .match $count one {{File path copied to clipboard.}} * {{{$count} file paths copied to clipboard.}}\",\"asset_ids_copied\":\".input {$count :integer} .match $count one {{File ID copied to clipboard.}} * {{{$count} file IDs copied to clipboard.}}\",\"asset_data_copied\":\".input {$count :integer} .match $count one {{File data copied to clipboard.}} * {{{$count} files’ data copied to clipboard.}}\",\"assets_downloaded\":\".input {$count :integer} .match $count one {{Asset downloaded.}} * {{{$count} assets downloaded.}}\",\"assets_moved\":\".input {$count :integer} .match $count one {{Asset moved.}} * {{{$count} assets moved.}}\",\"assets_renamed\":\".input {$count :integer} .match $count one {{Asset renamed.}} * {{{$count} assets renamed.}}\",\"assets_deleted\":\".input {$count :integer} .match $count one {{Asset deleted.}} * {{{$count} assets deleted.}}\",\"folder_created\":\"Folder created.\",\"folder_path\":\"Folder Path\",\"folder_contents\":\"Contents\",\"x_folders\":\".input {$count :integer} .match $count 0 {{No folders}} one {{{$count} folder}} * {{{$count} folders}}\",\"folder_renamed\":\"Folder renamed.\",\"folder_deleted\":\"Folder deleted.\",\"content_editor\":\"Content Editor\",\"restore_backup_title\":\"Restore Draft\",\"restore_backup_description\":\"This entry has a backup from {$datetime}. Do you want to restore the edited draft?\",\"draft_backup_saved\":\"Draft backup saved.\",\"draft_backup_restored\":\"Draft backup restored.\",\"draft_backup_deleted\":\"Draft backup deleted.\",\"cancel_editing\":\"Cancel Editing\",\"create_entry_title\":\"Creating {$name}\",\"create_entry_announcement\":\"You’re now creating a new entry in the “{$collection}” collection.\",\"edit_entry_announcement\":\"You’re now editing the “{$entry}” entry in the “{$collection}” collection.\",\"edit_file_announcement\":\"You’re now editing the “{$file}” file in the “{$collection}” collection.\",\"edit_singleton_announcement\":\"You’re now editing the “{$file}” file.\",\"save_and_publish\":\"Save and Publish\",\"save_without_publishing\":\"Save without Publishing\",\"save_and_publish_needs_review\":\"Save and Publish (Related Entries Need Review)\",\"show_editor_options\":\"Show Editor Options\",\"editor_options\":\"Editor Options\",\"show_second_pane\":\"Show Second Pane\",\"show_preview\":\"Show Preview\",\"sync_scrolling\":\"Sync Scrolling\",\"switch_locale\":\"Switch Locale\",\"locale_content_disabled_short\":\"(disabled)\",\"locale_content_error_short\":\"(error)\",\"edit\":\"Edit\",\"preview\":\"Preview\",\"swap_panes\":\"Swap Panes\",\"edit_x_locale\":\"Edit {$locale} Content\",\"preview_x_locale\":\"Preview {$locale} Content\",\"edit_content\":\"Edit Content\",\"preview_content\":\"Preview Content\",\"content_preview\":\"Content Preview\",\"show_content_options_x_locale\":\"Show {$locale} Content Options\",\"content_options_x_locale\":\"{$locale} Content Options\",\"show_content_options\":\"Show Content Options\",\"content_options\":\"Content Options\",\"x_field\":\"“{$field}” Field\",\"show_field_options\":\"Show Field Options\",\"field_options\":\"Field Options\",\"unsupported_field_type_x\":\"Unsupported field type: {$name}\",\"enable_x_locale\":\"Enable {$locale}\",\"reenable_x_locale\":\"Reenable {$locale}\",\"disable_x_locale\":\"Disable {$locale}\",\"locale_x_has_been_disabled\":\"The {$locale} content has been disabled.\",\"locale_x_now_disabled\":\"The {$locale} content is now disabled. It will be deleted when you save the entry.\",\"view_in_repository\":\"View in Repository\",\"view_on_x\":\"View on {$service}\",\"view_on_live_site\":\"View on Live Site\",\"deploy_preview\":{\"view\":\"View Preview\",\"building\":\"The preview is still being built.\",\"build_failed\":\"The preview couldn’t be built. This isn’t necessarily caused by your changes. If the problem persists, contact your site administrator.\",\"checking\":\"Checking for a preview…\",\"check_again\":\"Check for Preview\",\"awaiting\":\"Checking for Preview\",\"short\":{\"building\":\"Building…\",\"failed\":\"Build Failed\"}},\"copy_from\":\"Copy from…\",\"copy_from_x\":\"Copy from {$locale}\",\"translation_options\":\"Translation Options\",\"translate\":\"Translate\",\"translate_fields\":\".input {$count :integer} .match $count one {{Translate Field}} * {{Translate Fields}}\",\"translate_from\":\"Translate from…\",\"translate_from_x\":\"Translate from {$locale}\",\"revert_changes\":\"Revert Changes\",\"revert_all_changes\":\"Revert All Changes\",\"restore_default\":\"Restore Default\",\"clear_all\":\"Clear All\",\"confirm_reverting_changes\":\"Are you sure you want to revert all the changes made to this entry?\",\"confirm_reverting_changes_x_locale\":\"Are you sure you want to revert all the changes made to the {$locale} content?\",\"confirm_restoring_defaults\":\"Are you sure you want to restore the default values of all the fields in this entry? Your changes will be lost.\",\"confirm_restoring_defaults_x_locale\":\"Are you sure you want to restore the default values of all the fields in the {$locale} content? Your changes will be lost.\",\"confirm_clearing_fields\":\"Are you sure you want to clear all the fields in this entry? Your changes will be lost.\",\"confirm_clearing_fields_x_locale\":\"Are you sure you want to clear all the fields in the {$locale} content? Your changes will be lost.\",\"edit_slug\":\"Edit Slug\",\"edit_slug_error\":{\"empty\":\"The slug cannot be empty.\",\"invalid\":\"The slug cannot contain special characters, including slashes and spaces.\",\"duplicate\":\"This slug is used for another entry.\"},\"slug_numbered\":\"The slug “{$slug}” is used for another entry, so a number will be added to it.\",\"entry_parent_folder\":\"Parent Folder\",\"new_parent_folder\":\"New Folder\",\"new_parent_folder_create\":\"Create\",\"new_parent_folder_name\":\"Folder Name\",\"new_parent_folder_description\":\"The new folder will be created in “{$folder}”.\",\"new_parent_folder_error\":{\"empty\":\"The folder name cannot be empty.\",\"invalid\":\"The folder name cannot contain slashes or start with a dot, and must include letters or numbers.\",\"duplicate\":\"A folder with this name already exists here.\"},\"edit_path_error\":{\"invalid\":\"The path cannot contain relative segments such as “..”.\",\"recursive\":\"The entry cannot be moved into one of its own subfolders.\",\"duplicate\":\"This path is used for another entry.\"},\"required\":\"Required\",\"editor\":{\"translation\":{\"none\":\"Nothing to translate.\",\"started\":\"Translating…\",\"error\":\"Translation failed.\",\"complete\":\".input {$count :integer} .match $count 0 {{No fields translated from {$source}.}} one {{Field translated from {$source}.}} * {{{$count} fields translated from {$source}.}}\"},\"copy\":{\"none\":\"Nothing to copy.\",\"complete\":\".input {$count :integer} .match $count 0 {{No fields copied from {$source}.}} one {{Field copied from {$source}.}} * {{{$count} fields copied from {$source}.}}\"}},\"validation\":{\"value_missing\":\"This field is required.\",\"range_underflow\":{\"datetime-local\":\"The date/time must be at or after {$min}.\",\"date\":\"The date must be on or after {$min}.\",\"time\":\"The time must be at or after {$min}.\",\"number\":\"The value must be greater than or equal to {$min}.\",\"select\":\".input {$min :integer} .match $min one {{You must select at least {$min} option.}} * {{You must select at least {$min} options.}}\",\"add\":\".input {$min :integer} .match $min one {{You must add at least {$min} item.}} * {{You must add at least {$min} items.}}\"},\"range_overflow\":{\"datetime-local\":\"The date/time must be at or before {$max}.\",\"date\":\"The date must be on or before {$max}.\",\"time\":\"The time must be at or before {$max}.\",\"number\":\"The value must be less than or equal to {$max}.\",\"select\":\".input {$max :integer} .match $max one {{You cannot select more than {$max} option.}} * {{You cannot select more than {$max} options.}}\",\"add\":\".input {$max :integer} .match $max one {{You cannot add more than {$max} item.}} * {{You cannot add more than {$max} items.}}\"},\"too_short\":\".input {$min :integer} .match $min one {{You must enter at least {$min} character.}} * {{You must enter at least {$min} characters.}}\",\"too_long\":\".input {$max :integer} .match $max one {{You cannot enter more than {$max} character.}} * {{You cannot enter more than {$max} characters.}}\",\"type_mismatch\":{\"number\":\"Please enter a number.\",\"email\":\"Please enter a valid email.\",\"url\":\"Please enter a valid URL.\"},\"value_not_unique\":\"This value is used for another entry.\",\"key_not_unique\":\"This key is used for another item.\",\"key_numeric\":\"The key can’t be a whole number, as the items would lose their order.\",\"invalid_value\":\"Invalid value.\",\"unexpected_error\":\"Unexpected error occurred.\"},\"entry_sidebar\":{\"sidebar_panels\":\"Sidebar Panels\",\"validation\":{\"title\":\"Validation\",\"placeholder\":\"Validation results will be shown here.\",\"no_errors_found\":\"No errors found.\",\"validate\":\"Validate\"},\"slug\":{\"title\":\"Slug\",\"generated_on_save\":\"The slug is generated from the entry’s content when it’s saved. Any date and time in it will be those of the save.\",\"unavailable\":\"This entry doesn’t have a slug.\"},\"history\":{\"title\":\"History\",\"fetch_failed\":\"Failed to load history.\",\"no_history\":\"No history found.\"},\"backlinks\":{\"title\":\"Backlinks\",\"no_entries\":\"No entries are referencing this entry.\"},\"title_with_count\":\"{$title} ({$count})\"},\"save_progress\":{\"preparing\":\"Preparing files: {$done} of {$total}\",\"committing\":\"Saving to GitHub: {$done} of about {$total} commits\"},\"saving_entry\":{\"error\":{\"title\":\"Error\",\"description\":\"There was an error while saving the entry. Please try again later.\"}},\"save_conflict\":{\"title\":\"Entry Changed by Someone Else\",\"modified_by\":\"{$name} changed this entry on {$date}, after you opened it.\",\"modified\":\"This entry has been changed in the repository after you opened it.\",\"deleted\":\"This entry has been deleted from the repository after you opened it.\",\"overwrite_warning\":\"If you save now, their changes will be lost.\",\"recreate_warning\":\"If you save now, the entry will be created again.\",\"reload_warning\":\"As the entry is stored in the same file as other entries, it can’t be saved over the change. Cancel editing, then open the entry again from the list and make your edits.\",\"save_anyway\":\"Save Anyway\",\"branch_moved\":\"The repository has been updated by someone else while saving. Please try again.\",\"array_item_changed\":\"An entry stored in the same file has been changed by someone else. Please try again.\",\"array_file_invalid\":\"The {$path} file can’t be updated, as it doesn’t contain a valid list of entries.\"},\"remote_change\":{\"reload_entry\":\"Reload Entry\",\"confirm_reloading_entry\":\"Are you sure you want to reload the entry? Your unsaved changes will be lost.\"},\"viewing_x_asset_details\":\"You’re viewing the details of the “{$name}” asset.\",\"asset_editor\":\"Asset Editor\",\"previous_asset\":\"Previous Asset\",\"next_asset\":\"Next Asset\",\"preview_unavailable\":\"Preview Unavailable.\",\"public_urls\":\".input {$count :integer} .match $count one {{Public URL}} * {{Public URLs}}\",\"file_paths\":\".input {$count :integer} .match $count one {{File Path}} * {{File Paths}}\",\"file_ids\":\".input {$count :integer} .match $count one {{File ID}} * {{File IDs}}\",\"file_data\":\"File Data\",\"asset_info\":\"Asset Info\",\"select_asset_show_info\":\"Select an asset to show its info.\",\"kind\":\"Kind\",\"size\":\"Size\",\"dimensions\":\"Dimensions\",\"duration\":\"Duration\",\"used_in\":\"Used in\",\"created_date\":\"Created Date\",\"location\":\"Location\",\"map_lat_lng\":\"Map showing latitude {$latitude}, longitude {$longitude}\",\"remove_this_item\":\"Remove This Item\",\"move_up\":\"Move Up\",\"move_down\":\"Move Down\",\"reorder_options\":\"Reorder Options\",\"move_to_top\":\"Move to Top\",\"move_to_bottom\":\"Move to Bottom\",\"move_to\":\"Move to…\",\"move_to_description\":\"Enter a position from 1 to {$count}.\",\"move_to_position\":\"Position\",\"reorder_item\":\"Reorder Item\",\"list_item_value\":\"Item Value\",\"list_item_position\":\"Item {$position} of {$count}\",\"item_removed\":\"Item removed.\",\"add_x\":\"Add {$name}\",\"list_item_options\":\"List Item Options\",\"add_item_above\":\"Add Item Above\",\"add_item_below\":\"Add Item Below\",\"paste_item_above\":\"Paste Item Above\",\"paste_item_below\":\"Paste Item Below\",\"paste_item_to_replace\":\"Paste to Replace\",\"paste_item\":\"Paste Item\",\"list_item_copied\":\"Item copied.\",\"no_list_item_to_paste\":\"There’s no copied item to paste. To copy one, open an item’s ⋮ (List Item Options) menu and select Copy.\",\"list_item_not_compatible\":\"The copied item doesn’t fit in this list.\",\"list_item_pasted_without_values\":\".input {$count :integer} .match $count one {{Item pasted. A value this list doesn’t take was left out.}} * {{Item pasted. {$count} values this list doesn’t take were left out.}}\",\"list_item_pasted_without_files\":\".input {$count :integer} .match $count one {{Item pasted, but a file it uses couldn’t be found. Check the file fields in the item.}} * {{Item pasted, but {$count} files it uses couldn’t be found. Check the file fields in the item.}}\",\"select_list_type\":\"Select List Type\",\"unknown_variable_type\":\"This item can’t be displayed due to an unknown type. Check the browser console for details.\",\"opacity\":\"Opacity\",\"unselected_option\":\"(None)\",\"relation_field\":{\"save_together_hint\":\"The new {$name} will be saved along with the entry you’re editing.\",\"add_failed\":\"The {$name} couldn’t be added. Check the browser console for details.\",\"edit_entry_title\":\"Editing {$name}\",\"edit_together_hint\":\"Your changes to the {$name} will be saved along with the entry you’re editing.\",\"edit_failed\":\"The changes to the {$name} couldn’t be applied. Check the browser console for details.\",\"move_unsupported\":\"These changes would move the {$name} to another location, which can only be done by editing it on its own.\",\"edit_conflict\":\"“{$name}” has been changed by someone else since you edited it. Open it again from the field to review your changes against the latest version.\",\"edit_deleted\":\"“{$name}” has been deleted by someone else since you edited it. Remove it from the field to save the entry.\",\"select_entry_to_edit\":\"Select an Entry to Edit\",\"edited_with_entry\":\"Changes to this entry are waiting to be published along with “{$name}”. If you save it now, the two sets of changes will be combined when that entry is published, which may fail if they overlap.\",\"changed_since_edit\":\"This {$name} has been changed by someone else since you edited it. Your changes are shown on top of the latest version. Review them before updating.\"},\"assets_dialog\":{\"title\":{\"file\":\"Select File\",\"image\":\"Select Image\",\"folder\":\"Select Folder\"},\"search_for_file\":\"Search for Files\",\"search_for_image\":\"Search for Images\",\"locations\":\"Locations\",\"selected_folder\":\"Selected folder: {$path}\",\"selected_folders\":\".input {$count :integer} .match $count one {{{$count} folder selected}} * {{{$count} folders selected}}\",\"no_subfolders\":\"This folder has no subfolders.\",\"prefix_unresolved\":\"Fill in the fields this location depends on to browse and upload its files.\",\"folder\":{\"field\":\"Field Assets\",\"entry\":\"Entry Assets\",\"file\":\"File Assets\",\"collection\":\"Collection Assets\",\"global\":\"Global Assets\"},\"error\":{\"invalid_key\":\"Your API key is invalid or expired. Please double-check and try again.\",\"search_fetch_failed\":\"There was an error while searching assets. Please try again later.\",\"image_fetch_failed\":\"There was an error while downloading the selected asset. Please try again later.\"},\"available_images\":\"Available Images\",\"available_files\":\"Available Files\",\"enter_url\":\"Enter URL\",\"enter_file_url\":\"Enter URL of the file:\",\"enter_image_url\":\"Enter URL of the image:\",\"large_file\":{\"title\":\"Large File\"},\"invalid_file\":{\"title\":\"Invalid File\"},\"rejected_files\":{\"title\":\"Files Cannot Be Uploaded\"},\"photo_credit\":{\"title\":\"Photo Credit\",\"description\":\"Use the following credit if possible:\",\"insert_to_field\":\"Insert to {$field}\",\"copy_as_markdown\":\"Copy as Markdown\"},\"unsaved\":\"Unsaved\"},\"character_counter\":{\"min_max\":\".input {$count :integer} .match $count 0 {{No character entered. Minimum: {$min}. Maximum: {$max}.}} one {{{$count} character entered. Minimum: {$min}. Maximum: {$max}.}} * {{{$count} characters entered. Minimum: {$min}. Maximum: {$max}.}}\",\"min\":\".input {$count :integer} .match $count 0 {{No character entered. Minimum: {$min}.}} one {{{$count} character entered. Minimum: {$min}.}} * {{{$count} characters entered. Minimum: {$min}.}}\",\"max\":\".input {$count :integer} .match $count 0 {{No character entered. Maximum: {$max}.}} one {{{$count} character entered. Maximum: {$max}.}} * {{{$count} characters entered. Maximum: {$max}.}}\"},\"youtube_video_player\":\"YouTube video player\",\"today\":\"Today\",\"now\":\"Now\",\"editor_components\":{\"image\":\"Image\",\"src\":\"Source\",\"alt\":\"Alt Text\",\"title\":\"Title\",\"link\":\"Link\",\"caption\":\"Caption\"},\"key_value\":{\"key\":\"Key\",\"value\":\"Value\",\"action\":\"Action\",\"empty_key\":\"Key is required.\",\"duplicate_key\":\"Key must be unique.\"},\"find_place\":\"Find a Place\",\"use_your_location\":\"Use Your Location\",\"geolocation_error_title\":\"Geolocation Error\",\"geolocation_error_body\":\"There was an error while retrieving your location.\",\"geolocation_unsupported\":\"Geolocation API is not supported by this browser.\",\"boolean\":{\"true\":\"Yes\",\"false\":\"No\"},\"cloud_storage\":{\"invalid\":\"The service is not configured properly.\",\"auth\":{\"api_key\":{\"key_label\":\"API Key\",\"initial\":\"Enter your {$key} for {$service}.\",\"requested\":\"Validating…\",\"error\":\"The provided {$key} is invalid. Please double-check and try again.\"},\"password\":{\"initial\":\"Enter your password for {$service}.\",\"requested\":\"Signing in…\",\"error\":\"Username or password is incorrect. Please double-check and try again.\"}},\"s3\":{\"auth_key_label\":\"Secret Access Key\"},\"cloudinary\":{\"iframe_title\":\"Cloudinary media library\",\"activate\":{\"button_label\":\"Activate Cloudinary\",\"description\":\"After signing in, click the Sign In button again to continue.\"},\"auth_key_label\":\"API Secret\",\"open_library\":\"Open Cloudinary\"},\"uploadcare\":{\"auth_key_label\":\"API Secret Key\"},\"azure_blob_storage\":{\"auth_key_label\":\"SAS Token\"},\"backblaze_b2\":{\"auth_key_label\":\"Application Key\"},\"bunny_storage\":{\"auth_key_label\":\"Storage Zone Password\"}},\"config\":{\"errors\":\".input {$count :integer} .match $count one {{There is an error in the CMS configuration. Please solve the issue and try again.}} * {{There are errors in the CMS configuration. Please solve the issues and try again.}}\",\"error_locator\":{\"collection\":\"{$collection} collection\",\"file\":\"{$file} file\",\"component\":\"{$component} component\",\"field\":\"`{$field}` field\"},\"error\":{\"no_secure_context\":\"Sveltia CMS only works with HTTPS or localhost URLs.\",\"insecure_urls\":\".input {$count :integer} .match $count one {{The configuration file URL must use HTTPS protocol or a localhost address.}} * {{The configuration file URLs must use HTTPS protocol or localhost addresses.}}\",\"fetch_failed\":\"The configuration file could not be retrieved.\",\"fetch_failed_not_ok\":\"HTTP response returned with status {$status}.\",\"fetch_failed_with_manual_init\":\"The configuration file could not be retrieved. To prevent the `config.yml` file from loading, add <a>`load_config_file: false`</a> to the configuration object passed to `CMS.init()`.\",\"parse_failed\":\"The configuration file could not be parsed.\",\"parse_failed_invalid_object\":\"The configuration file is not a valid JavaScript object.\",\"parse_failed_unsupported_type\":\"The configuration file is not a valid file type. Only YAML, TOML and JSON are supported.\",\"no_collection\":\"Collections are not defined.\",\"no_visible_collection\":\"At least one collection must be visible. Check the `hide` option.\",\"missing_backend\":\"The backend is not defined.\",\"missing_backend_name\":\"The backend name is not defined.\",\"unsupported_known_backend\":\"The {$name} backend is <a>not supported</a> in Sveltia CMS.\",\"unsupported_deprecated_backend\":\"The deprecated {$name} backend is <a>not supported</a> in Sveltia CMS.\",\"unsupported_custom_backend\":\"Custom backends are <a>not supported</a> in Sveltia CMS.\",\"unsupported_backend_suggestion\":\"Use one of the <a>supported backends</a> instead.\",\"missing_repository\":\"The repository is not defined.\",\"invalid_repository\":\"The configured repository is invalid. It must be in “owner/repo” format.\",\"missing_api_root\":\"The `api_root` option is not defined. It’s required for the Forgejo backend.\",\"invalid_root_dir\":\"The root directory is invalid. It must be a path within the repository, without “..”.\",\"invalid_root_dir_branch\":\"The root directory can’t be used in the branch names of the `editorial_workflow` and `preview` publish modes. No part of its path can start with a dot, end with “.lock” or contain a space or a special character such as a colon or an asterisk.\",\"path_outside_root_dir\":\"The path “{$path}” leads outside the root directory, where the CMS can’t list files.\",\"oauth_implicit_flow\":\"The configured authentication method (implicit flow) is not supported in Sveltia CMS. Use a different <a>authentication method</a> instead.\",\"github_pkce_unsupported\":\"PKCE authorization is not yet supported due to GitHub’s limitations. Use a different <a>authentication method</a> instead.\",\"additions_no_base_url\":\"The `base_url` option must be the URL of your Sveltia CMS Additions service.\",\"oauth_no_app_id\":\"OAuth application ID is not defined.\",\"open_authoring_no_workflow\":\"The `open_authoring` option requires the `editorial_workflow` or `preview` publish mode. See the <a>documentation</a> for details.\",\"no_auth_methods\":\"The `auth_methods` option must contain at least one method.\",\"auth_scope_no_repo\":\"The `auth_scope` option must include `repo` or `public_repo`.\",\"missing_media_folder\":\"The media folder is not defined.\",\"public_folder_relative_path\":\"The configured public folder is invalid. It must be an absolute path starting with “/”.\",\"public_folder_absolute_url\":\"An absolute URL for the public folder option is not supported in Sveltia CMS.\",\"unsupported_folder_template_tag\":\"The `{$option}` option contains the `{$tag}` template tag, which isn’t supported there. Only the slug template tags, such as `\\\\{\\\\{slug\\\\}\\\\}` and `\\\\{\\\\{year\\\\}\\\\}`, and the `\\\\{\\\\{dirname\\\\}\\\\}`, `\\\\{\\\\{filename\\\\}\\\\}`, `\\\\{\\\\{extension\\\\}\\\\}`, `\\\\{\\\\{media_folder\\\\}\\\\}` and `\\\\{\\\\{public_folder\\\\}\\\\}` tags can be used.\",\"global_folder_template_tag\":\"The `{$option}` option contains the `{$tag}` template tag, which can only be used in the option of a collection, a collection file or a field, where there is an entry to fill it in with.\",\"invalid_sanitize_replacement\":\"The `sanitize_replacement` option is set to `{$replacement}`, but it contains a character that can’t be used in a slug, so it can’t stand in for one.\",\"invalid_url_option\":\"The `{$option}` option is set to `{$url}`, but it must be an absolute URL starting with `https://` or `http://`.\",\"invalid_publish_mode_stages\":\"The `stages` option of `publish_mode` must start with `draft` and list the stages in the order `draft`, `pending_review`, `pending_publish`, without repeating any.\",\"i18n_no_locales\":\"The `i18n.locales` option must list at least one locale.\",\"i18n_invalid_default_locale\":\"The `default_locale` option is set to `{$locale}`, but it’s not one of the `locales`.\",\"i18n_invalid_initial_locale\":\"The `initial_locales` option contains `{$locale}`, but it’s not one of the `locales`.\",\"i18n_no_collections\":\"The `i18n` option is configured at the top level, but none of the collections or singletons have the `i18n` option, so no content can be translated. Add `i18n: true` to the collections and singletons to translate.\",\"invalid_transformation_key\":\"The `transformations` option contains an unsupported `{$key}` key. It must be `raster_image`, `svg` or a supported raster image format.\",\"invalid_transformation_quality\":\"The `quality` option for the `{$key}` transformation is invalid. It must be an integer between 0 and 100.\",\"invalid_transformation_size\":\"The `{$prop}` option for the `{$key}` transformation is invalid. It must be a positive integer.\",\"missing_asset_collection_name\":\"The asset collection {$count} must have the `name` option defined as a non-empty string.\",\"invalid_asset_collection_name\":\"The asset collection name `{$name}` is invalid. It must not contain special characters.\",\"duplicate_asset_collection_name\":\"Asset collection names must be unique, but `{$name}` is used more than once.\",\"invalid_collection_no_options\":\"The collection must have either the `folder`, `file`, `files` or `divider` option defined.\",\"invalid_collection_multiple_options\":\"The collection cannot have more than one of the `folder`, `file`, `files` and `divider` options.\",\"file_format_mismatch\":\"The `{$extension}` extension doesn’t match the `{$format}` format.\",\"front_matter_body_field_not_text\":\"The `{$name}` field is saved as the body below the front matter, which can only hold text, not a number, a boolean, a list or an object as a `{$widget}` field does. Use a field type holding text, or rename the field.\",\"invalid_collection_data_file\":\"The `file` option `{$file}` is invalid. It must be the path to a JSON file, without the `\\\\{\\\\{locale\\\\}\\\\}` placeholder.\",\"unsupported_collection_data_file_option\":\"The `{$prop}` option is not supported in a collection with the `file` option.\",\"collection_data_file_workflow\":\"Editorial Workflow and Preview Workflow, including Open Authoring, are not supported in a collection with the `file` option. Set the collection’s `publish_mode` option to `simple`.\",\"collection_data_file_slug_tag\":\"The `{$prop}` option can’t contain the `\\\\{\\\\{slug\\\\}\\\\}` tag in a collection with the `file` option, as an entry’s slug is its position, which changes when the entries are reordered or deleted. Use a field with a unique value instead.\",\"invalid_slug_slash\":\"The slug template `{$slug}` is invalid as it cannot contain slashes. To organize entries in subfolders, use the `path` option instead of `slug`.\",\"invalid_identifier_field\":\"The `identifier_field` option refers to `{$name}`, but no such field is defined in the collection.\",\"invalid_filter_field\":\"The `filter` option refers to `{$name}`, but no such field is defined in the collection.\",\"invalid_filter_no_condition\":\"The `filter` option must have either the `value` or `pattern` option to match entries against.\",\"option_field_not_found\":\"The `{$option}` option refers to `{$name}`, but no such field is defined.\",\"thumbnail_field_not_media\":\"The `thumbnail` option refers to `{$name}`, but it must be an Image or File field, not a `{$widget}` field.\",\"invalid_inline_component_fields\":\"The `inline` mode requires a single Boolean, Color, DateTime, Number, Relation, Select or String field. A Relation or Select field can’t have the `multiple` option enabled.\",\"invalid_regex\":\"The `{$option}` option contains an invalid regular expression `{$pattern}`, which is ignored.\",\"invalid_reorder_group\":\"The `reorder` option refers to a view group named `{$name}`, but no such group is defined in the `view_groups` option.\",\"invalid_bulk_edit_field\":\"The `fields` list of the `bulk_edit` option refers to a field named `{$name}`, but no such top-level field is defined in the collection.\",\"unsupported_bulk_edit_field\":\"The `{$name}` field in the `fields` list of the `bulk_edit` option can’t be edited in bulk. Only a Boolean, Color, DateTime, Number, Relation, Select or String field that isn’t read-only, doesn’t have the `multiple` option enabled and isn’t set automatically on save is supported.\",\"invalid_sortable_field\":\"The `sortable_fields` option refers to a field named `{$name}`, but no such field is defined in the collection.\",\"multiple_sortable_field_defaults\":\"Only one item in the `sortable_fields` option can have the `default_sort` option.\",\"invalid_table_column_field\":\"The `{$option}` option refers to a field named `{$name}`, but no such field is defined in the collection.\",\"invalid_view_group_field\":\"The `view_groups` option refers to a field named `{$name}`, but no such field is defined in the collection.\",\"invalid_view_filter_field\":\"The `view_filters` option refers to a field named `{$name}`, but no such field is defined in the collection.\",\"missing_view_group_name\":\"The view group {$count} must have the `name` option defined as a non-empty string.\",\"invalid_view_group_name\":\"The view group name `{$name}` is invalid. It must not contain special characters.\",\"duplicate_view_group_name\":\"View group names must be unique, but `{$name}` is used more than once.\",\"missing_view_filter_name\":\"The view filter {$count} must have the `name` option defined as a non-empty string.\",\"invalid_view_filter_no_condition\":\"The view filter {$count} must have the `pattern` option or a comparison option such as `eq` or `gte` to match entries against.\",\"invalid_view_filter_name\":\"The view filter name `{$name}` is invalid. It must not contain special characters.\",\"duplicate_view_filter_name\":\"View filter names must be unique, but `{$name}` is used more than once.\",\"invalid_view_group_default\":\"The `default` option of `view_groups` is set to `{$name}`, but no view group has that name.\",\"invalid_view_filter_default\":\"The `default` option of `view_filters` is set to `{$name}`, but no view filter has that name.\",\"missing_collection_name\":\"The collection {$count} must have the `name` option defined as a non-empty string.\",\"invalid_collection_name\":\"The collection name `{$name}` is invalid. It must not contain special characters.\",\"duplicate_collection_name\":\"Collection names must be unique, but `{$name}` is used more than once.\",\"missing_collection_file_name\":\"The collection file {$count} must have the `name` option defined as a non-empty string.\",\"invalid_collection_file_name\":\"The collection file name `{$name}` is invalid. It must not contain special characters.\",\"duplicate_collection_file_name\":\"Collection file names must be unique, but `{$name}` is used more than once.\",\"collection_no_fields\":\"The collection must have the `fields` option defined with at least one field.\",\"collection_file_no_fields\":\"The collection file must have the `fields` option defined with at least one field.\",\"collection_folder_i18n_required\":\"The collection must have the `i18n` option defined if the `locale` placeholder is used in the `folder` path.\",\"invalid_collection_folder_locale\":\"The `folder` path `{$folder}` is invalid. The `locale` placeholder must be used only once as a whole folder name, like `content/\\\\{\\\\{locale\\\\}\\\\}/posts`.\",\"collection_file_i18n_required\":\"The collection file must have the `i18n` option defined if the `locale` placeholder is used in the `file` path.\",\"collection_i18n_no_fields\":\"The collection has the `i18n` option, but none of its fields have the `i18n` option, so no field can be translated. Add `i18n: true` or `i18n: duplicate` to the fields to translate.\",\"collection_i18n_no_files\":\"The collection has the `i18n` option, but none of its files have the `i18n` option, so no file can be translated. Add `i18n: true` to the files to translate.\",\"collection_file_i18n_no_fields\":\"The collection file has the `i18n` option, but none of its fields have the `i18n` option, so no field can be translated. Add `i18n: true` or `i18n: duplicate` to the fields to translate.\",\"missing_field_name\":\"The field {$count} must have the `name` option defined as a non-empty string.\",\"invalid_field_name\":\"The field name `{$name}` is invalid. It must not contain special characters. If you want to nest fields, <a>use Object fields instead of dot notation</a>.\",\"duplicate_field_name\":\"Field names must be unique, but `{$name}` is used more than once.\",\"missing_variable_type\":\"The variable type {$count} must have the `name` option defined as a non-empty string.\",\"invalid_variable_type\":\"The variable type name `{$name}` is invalid. It must not contain special characters.\",\"duplicate_variable_type\":\"Variable type names must be unique, but `{$name}` is used more than once.\",\"date_field_type\":\"The deprecated Date field type is not supported in Sveltia CMS. Use the DateTime field type with the `type: date` option instead.\",\"hidden_field_locale_without_i18n\":\"The `default` option of a Hidden field uses the `\\\\{\\\\{locale\\\\}\\\\}` placeholder, but i18n isn’t enabled for the collection, so the content has no locale to fill it with.\",\"invalid_timezone\":\"Invalid timezone: {$timeZone}. Must be a valid IANA timezone identifier like `America/New_York` or `Asia/Tokyo`.\",\"unsupported_deprecated_option\":\"The deprecated `{$prop}` option is not supported in Sveltia CMS. Use the `{$newProp}` option instead.\",\"allow_multiple\":\"The `allow_multiple` option is not supported in Sveltia CMS. Use the `multiple` option instead, which defaults to `false`.\",\"invalid_list_field\":\"The List field cannot have the `field`, `fields` and `types` options together.\",\"invalid_list_variable_type\":\"The List field’s variable type is invalid. The `widget` option is set to `{$widget}` but it must be `object`.\",\"invalid_object_field\":\"The Object field cannot have the `fields` and `types` options together.\",\"invalid_range_options\":\"The `{$min}` option must not be greater than the `{$max}` option.\",\"invalid_step\":\"The `step` option is set to `{$step}`, but it must be greater than zero, or `-1` to turn stepping off.\",\"select_field_no_options\":\"The Select field must have at least one item in the `options` option.\",\"select_field_duplicate_option\":\"The Select field’s `options` must be unique, but `{$value}` is used more than once.\",\"select_field_invalid_default\":\"The Select field’s `default` option is set to `{$value}`, but it’s not one of the `options`.\",\"list_field_no_subfields\":\"The List field’s `fields` or `types` option must have at least one item. Omit the option for a list of plain values.\",\"list_field_invalid_default_object\":\"The List field’s `default` option contains an object, but each item must be a plain value because the field has no `fields` or `types`.\",\"list_field_invalid_default_item\":\"The List field’s `default` option contains `{$value}`, but each item must be an object because the field has `fields` or `types`.\",\"list_field_invalid_default_key\":\"The List field’s `default` option contains an item with the `{$key}` property, but no subfield has that name.\",\"list_field_default_missing_type\":\"The List field’s `default` option contains an item without the `{$typeKey}` property, which identifies one of the `types`.\",\"list_field_invalid_default_type\":\"The List field’s `default` option contains an item whose `{$typeKey}` property is `{$value}`, but it’s not one of the `types`.\",\"list_field_map_key_no_subfields\":\"The List field’s `map_key_field` option requires the `fields` or `types` option, as each key is taken from a subfield.\",\"list_field_map_key_not_found\":\"The List field’s `map_key_field` option refers to `{$name}`, but no subfield has that name.\",\"list_field_map_key_missing_in_type\":\"The List field’s `map_key_field` option refers to `{$name}`, but the `{$type}` type has no subfield with that name.\",\"list_field_map_key_invalid_type\":\"The List field’s `map_key_field` option refers to `{$name}`, but it must be a String, Relation or Select field, not a `{$widget}` field.\",\"list_field_map_key_multiple\":\"The List field’s `map_key_field` option refers to `{$name}`, but the subfield can’t take multiple values, as each item needs a single key. Remove its `multiple` option.\",\"list_field_map_key_option_not_string\":\"The List field’s `map_key_field` option refers to `{$name}`, but the subfield’s options must have string values, as each key is stored as a string.\",\"list_field_map_key_not_required\":\"The List field’s `map_key_field` option refers to `{$name}`, but the subfield can’t be optional, as each item needs a key. Remove its `required` option.\",\"list_field_map_key_not_localized\":\"The List field’s `map_key_field` option refers to `{$name}`, but the subfield can’t have `i18n: false`, as the items need a key in every locale. Use `i18n: duplicate` or remove the option.\",\"duplicate_if_empty_multiple\":\"The `i18n: duplicate_if_empty` option is not supported for a field with the `multiple` option, so the field works like one with `i18n: true`.\",\"invalid_default_multiple\":\"The `default` option must be an array because the `multiple` option is `true`.\",\"invalid_default_single\":\"The `default` option must be a single value, not an array, because the `multiple` option is not `true`.\",\"object_field_invalid_default_key\":\"The Object field’s `default` option has the `{$key}` property, but no subfield has that name.\",\"object_field_default_missing_type\":\"The Object field’s `default` option doesn’t have the `{$typeKey}` property, which identifies one of the `types`.\",\"object_field_invalid_default_type\":\"The `{$typeKey}` property of the Object field’s `default` option is `{$value}`, but it’s not one of the `types`.\",\"code_field_invalid_default_object\":\"The Code field’s `default` option must be a string because the `output_code_only` option is `true`.\",\"code_field_invalid_default_key\":\"The Code field’s `default` option has the `{$key}` property, but the `keys` option only allows `{$code}` and `{$lang}`.\",\"compute_field_invalid_expression\":\"The Compute field’s `value` option must be a valid arithmetic expression, like `\\\\{\\\\{fields.price\\\\}\\\\} * \\\\{\\\\{fields.quantity\\\\}\\\\}`, because the `value_type` option is `{$valueType}`.\",\"compute_field_uuid_in_expression\":\"The Compute field’s `value` option can’t use a UUID tag like `\\\\{\\\\{uuid\\\\}\\\\}` because the `value_type` option is `{$valueType}`, which makes it an arithmetic expression.\",\"number_field_default_not_integer\":\"The Number field’s `default` option is set to `{$value}`, but it must be an integer because the `value_type` option is `{$valueType}`.\",\"number_field_default_not_number\":\"The Number field’s `default` option is set to `{$value}`, but it must be a number because the `value_type` option is `{$valueType}`.\",\"object_field_no_subfields\":\"The Object field’s `fields` or `types` option must have at least one item.\",\"relation_field_invalid_collection\":\"The referenced `{$collection}` collection is invalid or not defined.\",\"relation_field_invalid_collection_file\":\"The referenced `{$file}` file is invalid or not defined.\",\"relation_field_missing_file_name\":\"The `file` option must be defined for a relation to a file collection.\",\"relation_field_invalid_value_field\":\"The referenced value field `{$field}` is invalid or not defined.\",\"relation_field_array_file_slug\":\"The relation to the `{$collection}` collection can’t store the `\\\\{\\\\{slug\\\\}\\\\}` value, as an entry’s slug in a collection with the `file` option is its position, which changes when the entries are reordered or deleted. Set the `value_field` option to a field with a unique value instead.\",\"relation_field_array_file_workflow\":\"A collection with the `file` option can’t have a relation to the `{$collection}` collection, which uses Editorial Workflow or Preview Workflow, as the references to an entry renamed or deleted there can’t be updated in the file.\",\"relation_field_invalid_display_field\":\"The referenced display field `{$field}` is invalid or not defined.\",\"relation_field_invalid_search_field\":\"The referenced search field `{$field}` is invalid or not defined.\",\"relation_field_invalid_filter_field\":\"The referenced filter field `{$field}` is invalid or not defined.\",\"relation_field_invalid_sort_field\":\"The referenced sort field `{$field}` is invalid or not defined.\",\"relation_field_sort_by_file_ignored\":\"The `sort_by` option doesn’t apply to a relation to a file, whose options follow the order of the list items. It will be ignored.\",\"unexpected\":\"Unexpected error\",\"schema_invalid_type\":\"The `{$option}` option must be {$type}.\",\"schema_invalid_enum\":\"The `{$option}` option must be one of these values: {$values}.\",\"schema_invalid_const\":\"The `{$option}` option must be `{$value}`.\",\"schema_invalid_empty_value\":\"The `{$option}` option must be an empty string.\",\"schema_invalid_item_count\":\"The `{$option}` option must be an array of {$count} items.\",\"schema_invalid_value\":\"The `{$option}` option has an invalid value.\",\"schema_missing_option\":\"The `{$option}` option is required.\",\"schema_missing_one_of\":\"One of these options is required: {$options}.\",\"schema_value_type\":{\"string\":\"a string\",\"number\":\"a number\",\"integer\":\"an integer\",\"boolean\":\"a boolean\",\"array\":\"an array\",\"object\":\"an object\",\"null\":\"empty\"}},\"warning\":{\"oauth_no_app_id\":\"OAuth application ID is not defined. Users are required to provide an access token to sign in.\",\"site_library_prefix_template\":\"The `prefix` option of a media library contains template tags, which are only supported at the field level, as there is no entry to fill them with at the top level.\",\"unsupported_ignored_option\":\"The `{$prop}` option is not supported in Sveltia CMS. It will be ignored.\",\"publish_mode_stages_ignored\":\"The `stages` option of `publish_mode` only applies to the `editorial_workflow` publish mode, so it’s ignored with `{$type}`.\",\"inline_component_multiline_pattern\":\"The `pattern` of this inline component has the `m` or `s` flag or matches line breaks, but an inline component is only matched within a paragraph.\",\"single_line_block_item\":\"The `{$name}` item of the `{$option}` option is ignored, as a field with `multiline: false` can only hold inline content.\",\"conflicting_timezone_options\":\"Both `picker_utc` and newer timezone options (`input_timezone` or `output_utc`) are set. The new options take precedence. Consider removing `picker_utc` from your configuration.\",\"localize_format_without_format\":\"The `localize_format` option has no effect, because the field has no `format` option and its value is stored in the ISO 8601 format.\",\"compute_field_wildcard_without_item\":\"The Compute field’s `value` option refers to `{$name}`, but the field isn’t in an item of the list that `*` stands for, so it resolves to nothing. Only an aggregate function like `sum()` can use every item of a list.\",\"compute_field_self_reference\":\"The Compute field’s `value` option refers to the field itself as `{$name}`, so its value changes every time it’s computed and never settles.\",\"compute_field_reference_cycle\":\"The Compute field’s `value` option refers to `{$name}`, another Compute field that refers back to this field, directly or through other fields, so their values never settle.\",\"localize_format_without_i18n\":\"The `localize_format` option is `true`, but i18n isn’t enabled for the collection, so the value is written in English. Set the option to a locale code like `de` instead.\",\"localize_format_unsupported_locale\":\"The `localize_format` option is set to `{$locale}`, which isn’t a supported locale, so the value is written in English.\",\"preview_path_no_date_field\":\"The `preview_path` option uses date and time tags, but the collection has no DateTime field to read them from, so the preview link won’t be shown.\",\"preview_path_date_field_not_found\":\"The `preview_path_date_field` option refers to a field named `{$name}`, but no DateTime field with that name is defined, so the preview link won’t be shown.\",\"preview_path_field_not_found\":\"The `preview_path` option refers to `{$name}`, but no such field is defined in the collection, so the preview link won’t be shown.\",\"missing_identifier_field\":\"The collection has no `{$name}` field to name new entries with, so each new entry gets a random slug. Add a `{$name}` field, or set the `identifier_field` or `slug` option.\",\"slug_i18n_ineffective\":\"The `i18n` option of `slug` has no effect, because the collection doesn’t use the `multiple_files`, `multiple_folders` or `multiple_root_folders` i18n structure, where each locale has a file of its own.\",\"slug_template_ignored\":\"The `template` option of `slug` is ignored, because the `auto_increment` option numbers the slugs instead.\",\"locale_not_omitted_from_file_path\":\"The `locale` placeholder can’t be removed from the `file` path `{$file}`, so the default locale is kept in it despite the `omit_default_locale_from_file_path` i18n option. To leave the locale out, use the placeholder as a whole folder name, like `\\\\{\\\\{locale\\\\}\\\\}/about.md`, or between the file name and the extension, like `about.\\\\{\\\\{locale\\\\}\\\\}.md`. To keep it, set the option to `false` in the file’s `i18n` option.\",\"i18n_not_configured\":\"The `i18n` option is enabled, but i18n is not configured at the top level of the configuration or in the collection, so the option has no effect.\",\"empty_public_folder\":\"The `public_folder` option is an empty string, so the `media_folder` path is used for the asset paths saved in entries instead. Remove the option, or set it to the path you want to use, such as `/images`.\",\"schema_unknown_option\":\"The `{$option}` option is not defined in the Sveltia CMS configuration schema. It will be ignored. Check for a typo or a syntax mistake.\",\"default_localized_without_i18n\":\"The `default_localized` option has no effect, because i18n isn’t enabled for the collection. Use the `default` option instead.\",\"default_localized_unknown_locale\":\"The `default_localized` option has a value for `{$locale}`, which isn’t one of the collection’s locales, so the value is never used.\"},\"compatibility_link\":\"See the compatibility notes for details: {$link}\",\"schema_tip\":\"For a better developer experience, you can validate your configuration file against the JSON schema of Sveltia CMS. See {$link} for details.\"},\"local_workflow\":{\"indicator\":\"Local\",\"unsupported_browser\":\"Local Workflow is not supported in your browser. Please use Chrome or Edge instead.\",\"disabled\":\"Local Workflow is disabled in your browser. <a>Here’s how to enable it</a>.\"},\"viewing_editorial_workflow\":\"You’re now viewing the Editorial Workflow board. Drafts: {$draft}. In Review: {$review}. Ready: {$ready}. Pending Deletion: {$deletion}.\",\"viewing_open_authoring_workflow\":\"You’re now viewing the Editorial Workflow board. Drafts: {$draft}. In Review: {$review}. Pending Deletion: {$deletion}.\",\"viewing_editorial_workflow_without_review\":\"You’re now viewing the Editorial Workflow board. Drafts: {$draft}. Ready: {$ready}. Pending Deletion: {$deletion}.\",\"viewing_preview_workflow\":\"You’re now viewing the Drafts page. Drafts: {$draft}. Pending Deletion: {$deletion}.\",\"status\":{\"draft\":\"Draft\",\"drafts\":\"Drafts\",\"in_review\":\"In Review\",\"ready\":\"Ready\",\"pending_deletion\":\"Pending Deletion\",\"deploying\":\"Deploying\"},\"workflow\":{\"cancel_deletion\":\"Cancel Deletion\",\"confirm_cancelling_deletion\":\"Are you sure you want to cancel this deletion? The entry will remain published.\",\"confirm_completing_deletion\":\"Are you sure you want to delete this entry? It will be removed right away.\",\"deletion_pending\":\".input {$count :integer} .match $count one {{Entry marked for deletion.}} * {{{$count} entries marked for deletion.}}\",\"changes_discarded\":\".input {$count :integer} .match $count one {{Changes discarded.}} * {{Changes to {$count} entries discarded.}}\",\"cancelling_deletion\":\"Cancelling Deletion…\",\"deletion_cancelled\":\"Deletion cancelled.\",\"cancelling_deletion_failed\":\"Couldn’t cancel the deletion. Please try again.\",\"unpublished_entries\":\"Unpublished Entries\",\"published_entries\":\"Published Entries\",\"entry_status_value\":\"Status: {$status}\",\"change_entry_status\":\"Change Entry Status\",\"changing_status\":\"Changing Status…\",\"updating_status\":\"Updating Status…\",\"status_updated\":\"Status updated.\",\"status_change_failed\":\"Couldn’t change the status. Please try again.\",\"refresh\":\"Refresh\",\"refreshing\":\"Refreshing…\",\"refreshed\":\"The board is up to date.\",\"refresh_failed\":\"Couldn’t refresh the board. Please try again.\",\"status_change_blocked\":\"The entry has errors. Please correct them before changing the status.\",\"publish_blocked\":\"The entry has errors. Please correct them before publishing it.\",\"send_for_review\":\"Send for Review\",\"confirm_sending_for_review\":\"Your changes have been saved as a draft. Send the entry for review so someone can look at it and publish it?\",\"mark_as_ready\":\"Mark as Ready\",\"confirm_marking_as_ready\":\"Your changes have been saved as a draft. Mark the entry as ready so it can be published?\",\"publish_entry\":\"Publish Entry\",\"discard_changes\":\"Discard Changes\",\"confirm_deleting_published_entry\":\"Are you sure you want to delete this entry? It won’t be removed until the deletion is published. Until then you’ll still find it in the entry list, marked Pending Deletion.\",\"confirm_deleting_unpublished_entry\":\"This entry hasn’t been published yet, so deleting it will discard it completely.\",\"confirm_discarding_entry_changes\":\"This entry has unpublished changes. Discarding them will restore the published version. The entry itself won’t be deleted.\",\"deleting_unpublished_note_all\":\".input {$count :integer} .match $count one {{It hasn’t been published yet, so your unpublished changes will be discarded. Any published version will remain published.}} * {{They haven’t been published yet, so your unpublished changes will be discarded. Any published versions will remain published.}}\",\"deleting_unpublished_note_some\":\".input {$count :integer} .match $count one {{One of them hasn’t been published yet, so your unpublished changes will be discarded. Any published version will remain published.}} * {{{$count} of them haven’t been published yet, so your unpublished changes will be discarded. Any published versions will remain published.}}\",\"confirm_publishing_entry_after_build\":\"Are you sure you want to publish this entry? Your changes will go live once your site has been rebuilt.\",\"publishing_entry\":\"Publishing Entry…\",\"entry_published\":\"Entry published.\",\"deleting_entry\":\"Deleting Entry…\",\"discarding_changes\":\"Discarding Changes…\",\"entry_deleted\":\"Entry deleted.\",\"publishing_entry_failed\":\"Couldn’t publish the entry. Please try again.\",\"publish_refused_other_changes\":\"This entry can’t be published here, because it comes with other changes the CMS can’t show you. Ask a developer to review it.\",\"publish_refused_entry_changed\":\"The entry has been changed since you opened it. Reload the page to review the latest version before publishing it.\",\"review_on_x\":\"Review on {$service}\",\"from_fork\":\"From a fork\",\"fork_entry_editable\":\"This entry comes from a contributor’s pull request opened from “{$fork}”. Your changes are saved to their branch. Review and merge the pull request on the Git service.\",\"fork_entry_locked\":\"This entry comes from a contributor’s pull request opened from “{$fork}”. The contributor doesn’t allow maintainers to edit it, so it can only be viewed here.\",\"fork_not_editable\":\"The contributor doesn’t allow maintainers to edit this pull request.\",\"fork_entry_gone\":\"The contributor’s pull request is no longer open, so the changes can’t be saved to it.\",\"branch_in_use\":\"Another request ({$number}) is already open for this entry outside the CMS. Ask a developer to close it first.\",\"no_entries\":\"No entries.\",\"drag_entry\":\"Drag to change the status\",\"deploying_deletion\":\"Deletion\",\"companion_entries\":\"Also adds {$entries}\",\"edited_companion_entries\":\"Also changes {$entries}\",\"companion_entry\":\"{$collection}: {$title}\"},\"commit_message\":{\"title\":\"Commit Message\",\"description_replace\":\"Describe your changes. The message is recorded in the history along with them.\",\"description_addition\":\"Add a note to the message recorded in the history along with your changes, such as an issue number. It can be left empty.\",\"message\":\"Commit message\",\"addition\":\"Note\",\"preview\":\"Message: {$message}\"},\"open_authoring\":{\"fork_repository\":\"Fork Repository\",\"fork\":\"Fork\",\"confirm_forking_repository\":\"To suggest changes to “{$repo}”, a fork of the repository has to be created on your account. Your changes are saved to that fork, and a maintainer reviews them before they go live.\",\"fork_declined\":\"You need a fork of the repository on your account to suggest changes.\",\"fork_failed\":\"Couldn’t create a fork of the “{$repo}” repository on your account.\",\"fork_branch_missing\":\"Your “{$fork}” fork doesn’t have the “{$branch}” branch. Update the fork from the “{$repo}” repository, then sign in again.\",\"permission_check_failed\":\"Couldn’t check your access to the “{$repo}” repository. Please try again in a moment.\",\"forking_disabled\":\"The “{$repo}” repository doesn’t allow forks. Ask a maintainer to enable forking for it.\",\"invitation_pending\":\"You have a pending invitation to the “{$repo}” repository. Accept it on GitHub, then sign in again.\",\"private_repo_scope_required\":\"Your sign-in doesn’t include access to private repositories, so the “{$repo}” repository can’t be read. Ask a maintainer to check the CMS authentication settings.\",\"publish_unsupported\":\"Only a maintainer can publish changes to this site. Mark your entry as In Review instead, and someone will take a look.\",\"entry_already_published\":\"A maintainer has already published this entry, so there’s nothing left to review.\",\"direct_commit_unsupported\":\"This change can’t be made directly. Only edits to entries can be suggested for review.\",\"contributing_via_fork\":\"Your changes are saved to your fork of this repository at “{$repo}” and reviewed before they go live.\",\"view_fork\":\"View Fork\"},\"categories\":\"Categories\",\"prefs\":{\"account\":{\"title\":\"Account\"},\"changes\":{\"api_key_saved\":\"API key saved.\",\"api_key_removed\":\"API key removed.\",\"api_key_invalid\":\"The provided API key is invalid. Please double-check and try again.\"},\"error\":{\"permission_denied\":\"Cookie storage access has been denied. Please check your browser permissions and try again.\"},\"appearance\":{\"title\":\"Appearance\",\"theme\":\"Theme\",\"select_theme\":\"Select Theme\"},\"theme\":{\"dark\":\"Dark\",\"light\":\"Light\"},\"language\":{\"title\":\"Language\",\"ui_language\":{\"title\":\"User Interface Language\",\"select_language\":\"Select Language\"}},\"contents\":{\"title\":\"Contents\",\"editor\":{\"title\":\"Editor\",\"use_draft_backup\":{\"switch_label\":\"Automatically back up entry drafts\"},\"close_on_save\":{\"switch_label\":\"Close the editor after saving a draft\"},\"close_with_escape\":{\"switch_label\":\"Close the editor with the Escape key\"}}},\"i18n\":{\"title\":\"Internationalization\",\"translators\":{\"default\":{\"title\":\"Default Translation Service\",\"select_service\":\"Select Service\"},\"api_keys\":{\"title\":\"Translation Service API Keys\",\"description\":\"Manage API keys for <a>translation services</a>. API keys for generic AI services can be managed in the AI settings.\"},\"field_label\":\"{$service} Key\",\"description\":\"Sign up for <a {$homeHref}>{$service}</a> and enter <a {$apiKeyHref}>your API Key</a> here to enable quick translation of text entry fields.\"}},\"media\":{\"title\":\"Media\",\"stock_photos\":{\"api_keys\":{\"title\":\"Stock Photo Service API Keys\",\"description\":\"Manage API keys for <a>stock photo services</a>.\"},\"field_label\":\"{$service} API Key\",\"description\":\"Sign up for <a {$homeHref}>{$service} API</a> and enter <a {$apiKeyHref}>your API Key</a> here to insert free stock photos to image entry fields.\",\"credit\":\"Photos provided by {$service}\",\"no_services\":\"No <a>stock photo services</a> are configured.\"},\"cloud_storage\":{\"api_keys\":{\"title\":\"Cloud Storage Service API Keys\",\"description\":\"Manage API keys for <a>cloud storage services</a>.\"},\"field_label\":\"{$service} API Key\",\"no_services\":\"No <a>cloud storage services</a> are configured.\"}},\"ai\":{\"title\":\"AI\",\"api_keys\":{\"title\":\"AI Service API Keys\",\"description\":\"Manage API keys for AI services.\"},\"field_label\":\"{$service} API Key\"},\"accessibility\":{\"title\":\"Accessibility\",\"underline_links\":{\"title\":\"Underline Links\",\"description\":\"Show underline for links in the entry preview and user interface labels.\",\"switch_label\":\"Always Underline Links\"}},\"data\":{\"title\":\"Data Management\",\"clear_data\":{\"title\":\"Clear Data\",\"file_cache\":{\"description\":\"Delete the locally cached file contents and image thumbnails to free up storage space or resolve issues caused by stale data.\",\"button_label\":\"Clear File Cache\",\"confirmation\":\"The locally cached file contents and image thumbnails will be deleted. Your unsaved drafts and settings will be kept, and any deleted data will be downloaded or generated again as needed. The CMS will be reloaded once done.\"},\"all_data\":{\"description\":\"Delete everything the CMS keeps in this browser, including the cached files, unsaved drafts and settings. Anything already saved to your repository won’t be affected.\",\"button_label\":\"Erase All Data\",\"confirmation\":\"All the data stored in this browser will be deleted, including the cached file contents, image thumbnails, unsaved drafts, settings and sign-in state. Your repository won’t be affected, but any change you haven’t saved will be lost, and you’ll have to sign in again. The CMS will be reloaded once done.\"}}},\"developer\":{\"title\":\"Developer\",\"developer_mode\":{\"title\":\"Developer Mode\",\"description\":\"Enable some developer-oriented features, including detailed console logs and native context menus.\",\"switch_label\":\"Enable Developer Mode\"},\"local_git\":{\"title\":\"Git Commits\",\"description\":\"Commit your changes to the current branch of your local repository whenever you save them, as the CMS does when you work with a remote repository. You can then review and push the commits with your usual Git tools.\",\"switch_label\":\"Commit Changes to Git\",\"checking\":\"Checking the repository…\",\"ready\":\"Changes will be committed to the {$branch} branch as {$name} ({$email}).\",\"not_ready\":\"Changes can’t be committed right now. {$reason}\"},\"deploy_hook\":{\"title\":\"Deploy Hook\",\"description\":\"Enter a webhook URL to be called when you manually trigger a deployment by selecting Publish Changes. This can be left blank if you’re using GitHub Actions or GitLab CI/CD.\",\"url\":{\"field_label\":\"Hook URL\",\"saved\":\"Hook URL saved.\",\"removed\":\"Hook URL removed.\"},\"auth\":{\"field_label\":\"Authorization header (e.g., Bearer <token>) (optional)\",\"saved\":\"Authorization header saved.\",\"removed\":\"Authorization header removed.\"}}}},\"keyboard_shortcuts_\":{\"view_content_library\":\"View Content Library\",\"view_asset_library\":\"View Asset Library\",\"search\":\"Search for entries and assets\",\"create_entry\":\"Create a new entry\",\"save_entry\":\"Save an entry\",\"cancel_editing\":\"Cancel entry editing\"},\"file_type_labels\":{\"avif\":\"AVIF image\",\"bmp\":\"Bitmap image\",\"gif\":\"GIF image\",\"heic\":\"HEIC image\",\"heif\":\"HEIF image\",\"ico\":\"Icon\",\"jpeg\":\"JPEG image\",\"jpg\":\"JPEG image\",\"png\":\"PNG image\",\"svg\":\"SVG image\",\"tif\":\"TIFF image\",\"tiff\":\"TIFF image\",\"webp\":\"WebP image\",\"avi\":\"AVI video\",\"m4v\":\"MP4 video\",\"mov\":\"QuickTime video\",\"mp4\":\"MP4 video\",\"mpeg\":\"MPEG video\",\"mpg\":\"MPEG video\",\"ogg\":\"Ogg video\",\"ogv\":\"Ogg video\",\"ts\":\"MPEG video\",\"webm\":\"WebM video\",\"3gp\":\"3GPP video\",\"3g2\":\"3GPP2 video\",\"aac\":\"AAC audio\",\"mid\":\"MIDI\",\"midi\":\"MIDI\",\"m4a\":\"MP4 audio\",\"mp3\":\"MP3 audio\",\"oga\":\"Ogg audio\",\"opus\":\"OPUS audio\",\"wav\":\"WAV audio\",\"weba\":\"WebM audio\",\"csv\":\"CSV spreadsheet\",\"doc\":\"Word document\",\"docx\":\"Word document\",\"odp\":\"OpenDocument presentation\",\"ods\":\"OpenDocument spreadsheet\",\"odt\":\"OpenDocument text\",\"pdf\":\"PDF document\",\"ppt\":\"PowerPoint presentation\",\"pptx\":\"PowerPoint presentation\",\"rtf\":\"Rich text document\",\"xls\":\"Excel spreadsheet\",\"xlsx\":\"Excel spreadsheet\",\"html\":\"HTML text\",\"js\":\"JavaScript\",\"json\":\"JSON text\",\"md\":\"Markdown text\",\"toml\":\"TOML text\",\"yaml\":\"YAML text\",\"yml\":\"YAML text\"},\"file_size_units\":{\"b\":\"{$size} bytes\",\"kb\":\"{$size} KB\",\"mb\":\"{$size} MB\",\"gb\":\"{$size} GB\",\"tb\":\"{$size} TB\"}};","import {\n  addMessages,\n  locale as appLocale,\n  getLocaleFromNavigator,\n  init,\n  register,\n} from '@sveltia/i18n';\nimport { strings as componentStrings } from '@sveltia/ui';\nimport defaultComponentStrings from '@sveltia/ui/locales/en-US.yaml';\nimport { getPathInfo } from '@sveltia/utils/file';\nimport { LocalStorage } from '@sveltia/utils/storage';\n\n// The strings of Sveltia CMS Additions come with its chunk\nimport defaultLocaleStrings from '$lib/locales/en-US.yaml?omit=additions';\nimport { UNPKG_BASE_URL, version } from '$lib/services/app';\nimport { PUBLISHED_LOCALE_LOADERS } from '$lib/services/app/published-locales';\nimport { navigatorLocale, PREFS_STORAGE_KEY } from '$lib/services/user/prefs.svelte';\nimport {\n  createDerivedState,\n  createRawState,\n  createRootEffect,\n} from '$lib/services/utils/state.svelte';\n\n/**\n * Default application locale. This is the only locale bundled with the app; the strings for the\n * other locales are loaded from the CDN on demand.\n */\nconst DEFAULT_APP_LOCALE = 'en-US';\n\n/**\n * List of all the available application locales, injected by Vite at build time based on the file\n * names in the `$lib/locales` directory.\n * @type {string[]}\n */\nexport const APP_LOCALES = import.meta.env.VITE_APP_LOCALES.split(',');\n\n/**\n * Get the application locale that best matches the browser’s language settings. The negotiation\n * itself is done by `sveltia-i18n`, which tries the user’s preferred languages in order and matches\n * them by language and script, so a locale written in another script is never offered, e.g.\n * Simplified Chinese (`zh-CN`) to a reader of Traditional Chinese (`zh-TW`). Where several of our\n * locales match equally well, it picks the region CLDR considers most likely, so a browser asking\n * for a bare `en` gets `en-US` rather than `en-CA` or `en-GB`.\n * @returns {string} Locale code, falling back to {@link DEFAULT_APP_LOCALE} when none of the\n * preferred languages is available. `getLocaleFromNavigator()` returns the first preferred language\n * as is in that case, which the app can’t activate.\n */\nexport const getNavigatorLocale = () => {\n  const locale = getLocaleFromNavigator();\n\n  return locale && APP_LOCALES.includes(locale) ? locale : DEFAULT_APP_LOCALE;\n};\n\n/**\n * Base URL for the JSON locale files published to the UNPKG CDN. These files are generated at build\n * time by the `generate-extra-files` Vite plugin.\n */\nconst REMOTE_LOCALES_BASE_URL = `${UNPKG_BASE_URL}@${version}/locales`;\n/**\n * How long to wait for a remote locale file, in milliseconds. If the CDN is slow or unreachable, we\n * give up rather than blocking the app, and the strings fall back to {@link DEFAULT_APP_LOCALE}.\n */\nconst REMOTE_LOCALE_FETCH_TIMEOUT = 5000;\n/**\n * Local storage key for the cached locale strings. Only one locale is cached at a time, given that\n * users rarely switch languages.\n */\nconst LOCALE_CACHE_KEY = 'sveltia-cms.locale';\n/**\n * Strings for the locales loaded during the session, keyed with the locale code. The `dictionary`\n * of `sveltia-i18n` holds compiled `Intl.MessageFormat` objects rather than the original strings,\n * so we keep our own copy to be able to update the cache later.\n * @type {Map<string, Record<string, any>>}\n */\nconst loadedLocaleStrings = new Map();\n\n/**\n * Locale being loaded from the CDN, if any. Bundled locales are switched instantly, so this is only\n * set while a remote locale file is being fetched.\n * @type {{ current: string | undefined }}\n */\nexport const appLocaleLoading = createRawState();\n\n/**\n * Locale that couldn’t be loaded from the CDN, if any. A new object is stored for each failure, so\n * that retrying the same locale still triggers a new notification.\n * @type {{ current: { locale: string } | undefined }}\n */\nexport const appLocaleLoadError = createRawState();\n\n/**\n * Number formatter for the application locale, used to show counts such as the number of entries\n * or assets in a folder. It’s shared, so every row of a long list doesn’t create its own, and it’s\n * replaced when the locale changes.\n */\nexport const appNumberFormatter = createDerivedState(() => Intl.NumberFormat(appLocale.current));\n\n/**\n * Whether the strings loaded for a locale are cached in the local storage. The cache saves a CDN\n * request on the next visit; the npm build loads them from a chunk of the consumer’s app instead,\n * which the browser caches anyway, so the copy would only take up the site’s storage quota.\n * @returns {boolean} Result.\n */\nconst isLocaleCacheEnabled = () => !import.meta.env.NPM_BUILD;\n\n/**\n * Get the cached strings for the given locale from the local storage. The cache is discarded when\n * the locale or the app version doesn’t match, as the strings can change with each release.\n * @param {string} locale Locale code.\n * @returns {Promise<Record<string, any> | undefined>} Strings, or `undefined` if the cache is\n * unavailable, empty, stale or disabled.\n */\nconst getCachedLocaleStrings = async (locale) => {\n  if (!isLocaleCacheEnabled()) {\n    return undefined;\n  }\n\n  try {\n    const { _locale, _version, ...strings } = (await LocalStorage.get(LOCALE_CACHE_KEY)) ?? {};\n\n    if (_locale === locale && _version === version && Object.keys(strings).length) {\n      return strings;\n    }\n  } catch {\n    // The local storage may be unavailable, e.g. when cookies are blocked\n  }\n\n  return undefined;\n};\n\n/**\n * Cache the strings for the given locale in the local storage, overwriting the previously cached\n * locale, if any.\n * @param {string} locale Locale code.\n * @param {Record<string, any>} strings Strings.\n */\nconst cacheLocaleStrings = async (locale, strings) => {\n  if (!isLocaleCacheEnabled()) {\n    return;\n  }\n\n  try {\n    await LocalStorage.set(LOCALE_CACHE_KEY, { _locale: locale, _version: version, ...strings });\n  } catch {\n    // The local storage may be unavailable or the quota may be exceeded\n  }\n};\n\n/**\n * Discard the cached strings, whichever locale they belong to.\n */\nconst deleteCachedLocaleStrings = async () => {\n  try {\n    await LocalStorage.delete(LOCALE_CACHE_KEY);\n  } catch {\n    // The local storage may be unavailable\n  }\n};\n\n/**\n * Load the strings for the given locale in the npm build, from the JSON file published with the\n * package, which the other builds fetch from the CDN. The consumer’s bundler emits each file as a\n * chunk loaded on demand.\n * @param {string} locale Locale code, one of {@link APP_LOCALES}.\n * @returns {Promise<Record<string, any>>} Strings.\n */\nconst loadPublishedLocaleStrings = async (locale) =>\n  (await PUBLISHED_LOCALE_LOADERS[locale]()).default;\n\n/**\n * Fetch the strings for the given locale from the CDN, or load them from the package in the npm\n * build. The remote JSON files already contain the Sveltia UI strings under the `_sui` key, so no\n * merge is needed here.\n * @param {string} locale Locale code.\n * @returns {Promise<Record<string, any>>} Strings.\n * @throws {Error} When the file cannot be fetched within {@link REMOTE_LOCALE_FETCH_TIMEOUT}.\n */\nconst fetchLocaleStrings = async (locale) => {\n  if (import.meta.env.NPM_BUILD) {\n    return loadPublishedLocaleStrings(locale);\n  }\n\n  const response = await fetch(`${REMOTE_LOCALES_BASE_URL}/${locale}.json`, {\n    signal: AbortSignal.timeout(REMOTE_LOCALE_FETCH_TIMEOUT),\n  });\n\n  if (!response.ok) {\n    throw new Error(`Failed to load the ${locale} locale strings`, { cause: response });\n  }\n\n  return response.json();\n};\n\n/**\n * Load the strings for the given locale, from the local storage cache if possible, or from the CDN\n * otherwise. A cache hit is instant, so no loading notification is shown in that case.\n * @param {string} locale Locale code.\n * @returns {Promise<Record<string, any>>} Strings.\n * @throws {Error} When the strings cannot be fetched.\n */\nconst loadLocaleStrings = async (locale) => {\n  const cachedStrings = await getCachedLocaleStrings(locale);\n\n  if (cachedStrings) {\n    loadedLocaleStrings.set(locale, cachedStrings);\n\n    return cachedStrings;\n  }\n\n  appLocaleLoading.current = locale;\n\n  try {\n    const strings = await fetchLocaleStrings(locale);\n\n    loadedLocaleStrings.set(locale, strings);\n    await cacheLocaleStrings(locale, strings);\n\n    return strings;\n  } catch (ex) {\n    // Let the caller know about the failure, then rethrow so that `sveltia-i18n` falls back to the\n    // default locale\n    appLocaleLoadError.current = { locale };\n    throw ex;\n  } finally {\n    // Another locale may have started loading in the meantime, whose notice stays\n    if (appLocaleLoading.current === locale) {\n      appLocaleLoading.current = undefined;\n    }\n  }\n};\n\n/**\n * Update the local storage cache so that it holds the strings for the given locale, or no strings\n * at all if the locale is bundled with the app. `sveltia-i18n` calls a registered loader only once\n * per locale, so switching back to a language already used earlier in the session doesn’t go\n * through {@link loadLocaleStrings} again, leaving the cache pointing at another locale. Without\n * this, the strings would be fetched from the CDN again on the next visit.\n * @param {string} locale Locale code.\n */\nexport const updateLocaleCache = async (locale) => {\n  const strings = loadedLocaleStrings.get(locale);\n\n  if (!strings) {\n    // The {@link DEFAULT_APP_LOCALE} strings are bundled with the app, so the cache is useless once\n    // the user switches back to that locale. It’s only discarded after another locale has been\n    // active in this session, so that a cache left by a previous session survives a startup where\n    // the requested locale couldn’t be loaded and the app fell back to the default one.\n    if (locale === DEFAULT_APP_LOCALE && loadedLocaleStrings.size) {\n      await deleteCachedLocaleStrings();\n    }\n\n    // Anything else is a locale whose loader is still running; that loader caches the strings once\n    // it’s done\n    return;\n  }\n\n  // Avoid a redundant write when the cache is already up to date, e.g. right after a CDN fetch\n  if (await getCachedLocaleStrings(locale)) {\n    return;\n  }\n\n  await cacheLocaleStrings(locale, strings);\n};\n\n/**\n * Get the language preference stored in the local storage, if it points at an available locale.\n *\n * The preference is read here rather than taken from `prefs`, because the preferences are loaded\n * asynchronously and are therefore still empty when the app starts. Falling back to the browser’s\n * language in the meantime would activate a locale the user never asked for, fetch its strings from\n * the CDN, cache them, and then have {@link updateLocaleCache} overwrite or discard that cache once\n * the preference is finally applied — repeating on every visit. The `LocalStorage` wrapper is\n * `async`, but the underlying Web Storage API is synchronous, so the value is available right away.\n * @returns {string | undefined} Locale code, or `undefined` if there’s no usable preference.\n */\nconst getStoredLocale = () => {\n  try {\n    const { locale } = JSON.parse(globalThis.localStorage.getItem(PREFS_STORAGE_KEY) || '{}') ?? {};\n\n    // Ignore anything that’s not an available locale: the default `auto` value, which is resolved\n    // from the browser’s language settings below, a locale that’s no longer available, as well as\n    // the legacy `en` value, which is migrated once the preferences are loaded\n    return APP_LOCALES.includes(locale) ? locale : undefined;\n  } catch {\n    // The local storage may be unavailable, e.g. when cookies are blocked, or the stored data may\n    // be corrupt\n    return undefined;\n  }\n};\n\n/**\n * Load strings and initialize the locales. The Sveltia CMS strings are merged with the Sveltia UI\n * strings, the latter being prefixed with `_sui` to avoid collision. Only the\n * {@link DEFAULT_APP_LOCALE} strings are bundled with the app to keep the bundle size small. The\n * other locales are registered without strings, and those strings are fetched from the CDN once the\n * locale is first used. During development, all the locales are bundled instead, so that new\n * translations can be tested without publishing them.\n * @see https://github.com/sveltia/sveltia-i18n\n * @see https://vitejs.dev/guide/features.html#glob-import\n */\nexport const initAppLocale = () => {\n  if (import.meta.env.DEV) {\n    // YAML files are transformed into JS objects by the `yamlToJS` Vite plugin at build time\n    const modules = import.meta.glob('$lib/locales/*.yaml', { eager: true, import: 'default' });\n\n    const localeStrings = Object.fromEntries(\n      Object.entries(modules).map(([path, content]) => [\n        getPathInfo(path).filename,\n        /** @type {Record<string, any>} */ (content),\n      ]),\n    );\n\n    // Add the default locale first, just like the production branch below, so that both branches\n    // register in the same order and negotiate identically. Which variant a browser language\n    // without a region resolves to, e.g. `en` → `en-US`, is decided by `sveltia-i18n` from CLDR\n    // data; registration order only breaks the ties CLDR has no opinion on.\n    [\n      DEFAULT_APP_LOCALE,\n      ...Object.keys(localeStrings).filter((locale) => locale !== DEFAULT_APP_LOCALE),\n    ].forEach((locale) => {\n      addMessages(locale, {\n        ...localeStrings[locale],\n        _sui: componentStrings[locale] ?? {},\n      });\n    });\n  } else {\n    addMessages(DEFAULT_APP_LOCALE, {\n      ...defaultLocaleStrings,\n      _sui: defaultComponentStrings,\n    });\n\n    APP_LOCALES.filter((locale) => locale !== DEFAULT_APP_LOCALE).forEach((locale) => {\n      // Register the locale without strings so it’s listed in the language switcher; the strings\n      // are loaded lazily when the locale is activated with `waitLocale()` or `locale.set()`\n      register(locale, () => loadLocaleStrings(locale));\n    });\n  }\n\n  navigatorLocale.current = getNavigatorLocale();\n\n  // Follow the browser’s language settings, which the user can change without reloading the page.\n  // The listener lives as long as the app, so it’s never removed.\n  window.addEventListener('languagechange', () => {\n    navigatorLocale.current = getNavigatorLocale();\n  });\n\n  // `init()` triggers the loader for the initial locale, but we don’t wait for it: the app is\n  // rendered with the default locale strings, which are always bundled, then switches to the\n  // requested locale as soon as its strings are loaded\n  init({\n    fallbackLocale: DEFAULT_APP_LOCALE,\n    initialLocale: getStoredLocale() ?? navigatorLocale.current,\n  });\n\n  // Keep the cache in sync with the active locale, including when the language is switched with the\n  // app settings. The effect lives as long as the app, so it’s never stopped.\n  createRootEffect(() => {\n    updateLocaleCache(appLocale.current);\n  });\n};\n","<!--\n  @component\n  Notify the user that the strings for the selected language couldn’t be downloaded from the CDN,\n  and that the UI is displayed in the default locale instead.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Toast } from '@sveltia/ui';\n\n  import { appLocaleLoadError } from '$lib/services/app/i18n';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n\n  let showToast = $state(false);\n\n  $effect(() => {\n    if (appLocaleLoadError.current) {\n      showToast = true;\n    }\n  });\n</script>\n\n{#if appLocaleLoadError.current}\n  {@const { locale } = appLocaleLoadError.current}\n  <Toast bind:show={showToast}>\n    <Alert status=\"error\">\n      {_('locale_load_failed', { values: { locale: getLocaleLabel(locale) ?? locale } })}\n    </Alert>\n  </Toast>\n{/if}\n","<!--\n  @component\n  The CMS configuration, as loaded, for developers.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { stringify } from 'yaml';\n\n  import MainArea from '$lib/components/admin/main-area.svelte';\n  import { rawCmsConfig } from '$lib/services/config';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} title Title of the section.\n   */\n\n  /** @type {Props} */\n  let { title } = $props();\n</script>\n\n<MainArea {title}>\n  <div role=\"blockquote\" aria-label={_('cms_config')}>\n    <pre>{stringify(rawCmsConfig)}</pre>\n  </div>\n</MainArea>\n\n<style>\n  div {\n    flex: auto;\n    overflow: auto;\n    margin: -16px;\n  }\n\n  pre {\n    margin: 0;\n    padding: 16px;\n    width: 100%;\n    min-width: fit-content;\n    min-height: -moz-available;\n    min-height: -webkit-fill-available;\n    min-height: stretch;\n    background-color: var(--sui-primary-background-color);\n  }\n</style>\n","<!--\n  @component\n  The list of Administration sections. On a small screen, it’s the whole page until a section is\n  chosen, with a way back to the Menu page, which lists the sections too.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, Listbox, Option, Toolbar } from '@sveltia/ui';\n\n  import BackButton from '$lib/components/common/page-toolbar/back-button.svelte';\n  import { getAdminSectionPath } from '$lib/services/app/admin';\n  import { goBack, goto } from '$lib/services/app/navigation';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { AdminSection } from '$lib/services/app/admin';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {AdminSection[]} sections Sections to list.\n   * @property {string | undefined} selectedKey Key of the section shown, if any.\n   */\n\n  /** @type {Props} */\n  let { sections, selectedKey } = $props();\n</script>\n\n<nav class=\"primary-sidebar\" aria-label={_('administration')}>\n  {#if env.isSmallScreen}\n    <Toolbar variant=\"primary\">\n      <BackButton onclick={() => goBack('/menu')} />\n      <h2 role=\"none\">{_('administration')}</h2>\n    </Toolbar>\n  {/if}\n  <!-- The sections are shown next to the list, except on a small screen -->\n  <Listbox\n    ariaLabel={_('administration')}\n    aria-controls={env.isSmallScreen ? undefined : 'admin-container'}\n  >\n    {#each sections as { key, labelKey, icon } (key)}\n      <Option\n        selected={!env.isSmallScreen && key === selectedKey}\n        label={_(labelKey)}\n        onSelect={() => {\n          goto(getAdminSectionPath(key), { transitionType: 'forwards' });\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name={icon} />\n        {/snippet}\n      </Option>\n    {/each}\n  </Listbox>\n</nav>\n","import { backend } from '$lib/services/backends';\nimport { getRepositoryDatabase } from '$lib/services/utils/database';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n */\n\n/**\n * Width of a page’s primary sidebar, in pixels, until the user resizes it.\n */\nexport const DEFAULT_SIDEBAR_WIDTH = 240;\n\n/**\n * UI settings store of the current repository’s database, along with the name of that database.\n * The sidebar width is read every time an overlay is closed, and each handle opens a connection of\n * its own that’s never closed, so the handle is reused for as long as the repository stays the\n * same.\n * @type {{ databaseName: string, db: IndexedDB } | undefined}\n */\nlet uiSettingsDB;\n\n/**\n * Forget the UI settings store. Used in tests.\n */\nexport const _resetUISettingsDB = () => {\n  uiSettingsDB = undefined;\n};\n\n/**\n * Get the UI settings store of the current repository’s database.\n * @returns {IndexedDB | undefined} Store, or `undefined` if the backend has no database yet.\n */\nexport const getUISettingsDB = () => {\n  const repository = backend.current?.repository;\n  const databaseName = repository?.databaseName;\n\n  if (!databaseName) {\n    uiSettingsDB = undefined;\n\n    return undefined;\n  }\n\n  if (uiSettingsDB?.databaseName !== databaseName) {\n    uiSettingsDB = {\n      databaseName,\n      db: /** @type {IndexedDB} */ (getRepositoryDatabase(repository, 'ui-settings')),\n    };\n  }\n\n  return uiSettingsDB.db;\n};\n\n/**\n * Get the saved width of a page’s primary sidebar.\n * @param {string} key UI settings key of the page, e.g. `contents-page`.\n * @returns {Promise<number>} Width in pixels, or {@link DEFAULT_SIDEBAR_WIDTH} if none is saved.\n */\nexport const getSidebarWidth = async (key) => {\n  try {\n    const width = (await getUISettingsDB()?.get(key))?.sidebarWidth;\n\n    if (typeof width === 'number' && Number.isFinite(width)) {\n      return width;\n    }\n  } catch {\n    // The sidebar is only shown once its width is known, so an IndexedDB failure mustn’t hide it\n  }\n\n  return DEFAULT_SIDEBAR_WIDTH;\n};\n\n/**\n * Save the width of a page’s primary sidebar, along with the other UI settings of the page.\n * @param {string} key UI settings key of the page, e.g. `contents-page`.\n * @param {number} width Width in pixels.\n */\nexport const saveSidebarWidth = async (key, width) => {\n  const db = getUISettingsDB();\n\n  if (!db) {\n    return;\n  }\n\n  try {\n    await db.set(key, { ...(await db.get(key)), sidebarWidth: width });\n  } catch {\n    // The width is only a convenience, so an IndexedDB failure is ignored\n  }\n};\n","<script>\n  import { ResizableHandle, ResizablePane, ResizablePaneGroup } from '@sveltia/ui';\n\n  import { hasOverlay } from '$lib/services/app/navigation';\n  import { getSidebarWidth, saveSidebarWidth } from '$lib/services/app/ui-settings';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] CSS class name on the button.\n   * @property {string} [uiSettingsKey] Key for storing UI settings in IndexedDB. If not provided,\n   * the sidebar width will not be persisted.\n   * @property {Snippet} [primarySidebar] Primary sidebar content.\n   * @property {Snippet} [main] Main content.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let {\n    class: className = '',\n    uiSettingsKey = undefined,\n    primarySidebar = undefined,\n    main = undefined,\n    ...rest\n  } = $props();\n\n  /** @type {HTMLElement | undefined} */\n  let container = $state();\n  /** @type {number | undefined} */\n  let sidebarWidth = $state();\n\n  /**\n   * Restore the sidebar width from the UI settings, or use the default width if not set.\n   */\n  const restoreSidebarWidth = async () => {\n    if (!uiSettingsKey) return;\n\n    sidebarWidth = await getSidebarWidth(uiSettingsKey);\n  };\n\n  /**\n   * Save the sidebar width to the UI settings.\n   * @param {number} percent Sidebar width as a percentage of the container’s width.\n   */\n  const onResize = async (percent) => {\n    // The panes are only shown once the width has been restored, which takes a settings key, and\n    // the container is there by then\n    const { clientWidth } = /** @type {HTMLElement} */ (container);\n\n    await saveSidebarWidth(\n      /** @type {string} */ (uiSettingsKey),\n      Math.round(clientWidth * (percent / 100)),\n    );\n  };\n\n  $effect.pre(() => {\n    void [hasOverlay.current];\n\n    // `ResizablePaneGroup` doesn’t work well when the container is inert, so we need to wait until\n    // the overlay is actually gone before restoring the sidebar width.\n    window.requestAnimationFrame(() => {\n      if (!hasOverlay.current) {\n        restoreSidebarWidth();\n      }\n    });\n  });\n</script>\n\n<div\n  role=\"group\"\n  id=\"page-container\"\n  class=\"outer {className}\"\n  inert={hasOverlay.current}\n  {...rest}\n  bind:this={container}\n>\n  {#if env.isSmallScreen || !primarySidebar || !main}\n    {@render primarySidebar?.()}\n    {@render main?.()}\n  {:else if sidebarWidth !== undefined}\n    <ResizablePaneGroup\n      onResize={({ sizes }) => {\n        onResize(sizes[0]);\n      }}\n    >\n      <ResizablePane defaultSize=\"{sidebarWidth}px\" minSize=\"160px\" maxSize=\"480px\">\n        {@render primarySidebar()}\n      </ResizablePane>\n      <ResizableHandle />\n      <ResizablePane>\n        {@render main()}\n      </ResizablePane>\n    </ResizablePaneGroup>\n  {/if}\n</div>\n\n<style>\n  .outer {\n    flex: auto;\n    display: flex;\n    overflow: hidden;\n\n    &[inert] {\n      display: none;\n    }\n\n    :global {\n      .primary-sidebar {\n        display: flex;\n        flex-direction: column;\n        flex: none;\n        overflow-y: auto;\n        height: 100%;\n\n        @media (width < 768px) {\n          flex: auto;\n          width: auto;\n          background-color: var(--sui-primary-background-color);\n        }\n\n        /* Mobile header */\n        header {\n          display: flex;\n          align-items: center;\n          justify-content: space-between;\n          padding: 0 10px;\n          height: var(--sui-primary-toolbar-size);\n\n          h2 {\n            padding: 0 10px;\n            font-size: var(--sui-font-size-x-large);\n          }\n        }\n\n        .sui.search-bar {\n          margin-inline: 12px;\n          --sui-textbox-background-color: var(--sui-tertiary-background-color);\n        }\n\n        [role='radiogroup'] {\n          width: 100%;\n        }\n\n        [role='listbox'] {\n          margin: 8px;\n          border-width: 0;\n          background-color: transparent;\n\n          button {\n            display: flex;\n            justify-content: flex-start;\n            border-radius: var(--sui-control-medium-border-radius);\n            width: 100%;\n            text-align: start;\n\n            @media (pointer: coarse) {\n              height: 48px;\n            }\n\n            &:not(:first-child) {\n              margin-top: 4px;\n            }\n\n            &:not(:focus) {\n              border-color: transparent;\n            }\n\n            span {\n              flex: none;\n            }\n\n            .label {\n              flex: auto;\n              overflow: hidden;\n            }\n\n            .icon {\n              transition: color 200ms;\n            }\n\n            .icon.check {\n              display: none;\n            }\n\n            .count {\n              padding: 2px;\n              color: var(--sui-tertiary-foreground-color);\n              font-size: var(--sui-font-size-small);\n              transition: color 200ms;\n            }\n          }\n\n          [role='option'][aria-selected='true'] {\n            color: var(--sui-highlight-foreground-color);\n            background-color: var(--sui-selected-background-color);\n\n            .count {\n              color: var(--sui-highlighted-foreground-color);\n            }\n          }\n\n          [role='option'].dragover {\n            color: var(--sui-primary-accent-color-inverted) !important;\n            background-color: var(--sui-primary-accent-color) !important;\n          }\n        }\n\n        /* Styled like the listbox above, so the two sidebars look alike */\n        [role='tree'] {\n          margin: 8px;\n          border-width: 0;\n          background-color: transparent;\n\n          /* No item can expand, so the space kept for the chevrons is dropped */\n          &.flat .chevron.placeholder {\n            display: none;\n          }\n\n          [role='treeitem'] {\n            > .row {\n              border-radius: var(--sui-control-medium-border-radius);\n\n              @media (pointer: coarse) {\n                min-height: 48px;\n              }\n\n              .icon {\n                flex: none;\n                transition: color 200ms;\n              }\n\n              .count {\n                flex: none;\n                padding: 2px;\n                color: var(--sui-tertiary-foreground-color);\n                font-size: var(--sui-font-size-small);\n                transition: color 200ms;\n              }\n            }\n\n            &[aria-selected='true'] > .row .count {\n              color: var(--sui-highlighted-foreground-color);\n            }\n\n            &.dragover > .row {\n              color: var(--sui-primary-accent-color-inverted) !important;\n              background-color: var(--sui-primary-accent-color) !important;\n            }\n          }\n        }\n\n        .sui.divider {\n          margin: 8px 0;\n        }\n      }\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, EmptyState } from '@sveltia/ui';\n\n  import { goBack } from '$lib/services/app/navigation';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} message Message describing what couldn’t be found.\n   * @property {string} [backPath] URL path to navigate to when there’s no previous page to return\n   * to, which is the case when the user has opened the dead link directly.\n   */\n\n  /** @type {Props} */\n  let { message, backPath = '/collections' } = $props();\n\n  /**\n   * Accept any previous page to go back to, as a dead link can be followed from anywhere.\n   * @returns {boolean} Always `true`.\n   */\n  const anyPage = () => true;\n</script>\n\n<EmptyState>\n  <span role=\"none\">{message}</span>\n  <Button\n    variant=\"primary\"\n    onclick={() => {\n      goBack(backPath, { returnTo: anyPage });\n    }}\n  >\n    {_('back')}\n  </Button>\n</EmptyState>\n","<!--\n  @component\n  Administration of the CMS, as opposed to the user’s own settings: the people who can use it and\n  how they sign in, with Sveltia CMS Additions, and the CMS configuration. A section is chosen in\n  the sidebar, and each has its own path, e.g. `/admin/users`.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { onMount, untrack } from 'svelte';\n\n  import MainArea from '$lib/components/admin/main-area.svelte';\n  import ConfigPanel from '$lib/components/admin/panels/config-panel.svelte';\n  import Sidebar from '$lib/components/admin/sidebar.svelte';\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import { getAdditions, requireAdditions } from '$lib/services/app/additions';\n  import {\n    ADMIN_PATH,\n    getAdminPageAnnouncement,\n    getAdminSectionKey,\n    getAdminSectionPath,\n    getAdminSections,\n    lastAdminSectionKey,\n  } from '$lib/services/app/admin';\n  import {\n    announcedPageStatus,\n    parseLocation,\n    updateContentFromHashChange,\n  } from '$lib/services/app/navigation';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * Component showing each section. Those of Sveltia CMS Additions come with its chunk, which is\n   * loaded along with the backend if it’s enabled.\n   * @type {Record<string, any>}\n   */\n  const panels = $derived({\n    ...Object.fromEntries(\n      (getAdditions()?.adminSections ?? []).map(({ key, component }) => [key, component]),\n    ),\n    config: ConfigPanel,\n  });\n\n  /** Paths of the page, between which Back and Forward move like the other pages. */\n  const ADMIN_ROUTE_REGEX = /^\\/admin(?:\\/|$)/;\n\n  /**\n   * Key of the section in the URL: an empty string for the page itself, or `undefined` for a path\n   * that goes deeper than a section.\n   */\n  let sectionKey = $state(getAdminSectionKey(parseLocation().path));\n\n  const sections = $derived(getAdminSections());\n  const section = $derived(sections.find(({ key }) => key === sectionKey));\n\n  // Say what’s shown now, as the other pages do. Only the section in the URL matters: the list of\n  // sections changing, e.g. with developer mode, isn’t a page change\n  $effect(() => {\n    const key = sectionKey;\n\n    announcedPageStatus.current = untrack(() =>\n      getAdminPageAnnouncement({ sectionKey: key, sections, isSmallScreen: env.isSmallScreen }),\n    );\n  });\n\n  // Remembered for the Administration button\n  $effect(() => {\n    if (section) {\n      lastAdminSectionKey.current = section.key;\n    }\n  });\n\n  // On a large screen, the page opens on its first section rather than on an empty area. The page\n  // is only offered with at least one section\n  $effect(() => {\n    if (sectionKey === '' && !env.isSmallScreen) {\n      window.location.replace(`#${getAdminSectionPath(sections[0].key)}`);\n    }\n  });\n\n  onMount(() => {\n    // Admins of Sveltia CMS Additions are the ones who update it\n    // Their sections are only offered with Sveltia CMS Additions, whose chunk is loaded by then\n    if (sections.some(({ key }) => key === 'users')) {\n      requireAdditions().checkForUpdate();\n    }\n  });\n</script>\n\n<svelte:window\n  onhashchange={(event) => {\n    updateContentFromHashChange(\n      event,\n      () => {\n        sectionKey = getAdminSectionKey(parseLocation().path);\n      },\n      ADMIN_ROUTE_REGEX,\n    );\n  }}\n/>\n\n<PageContainer uiSettingsKey=\"admin-page\" aria-label={_('administration')}>\n  {#snippet primarySidebar()}\n    {#if !env.isSmallScreen || sectionKey === ''}\n      <Sidebar {sections} selectedKey={sectionKey} />\n    {/if}\n  {/snippet}\n  {#snippet main()}\n    {#if section}\n      {@const Panel = panels[section.key]}\n      <Panel title={_(section.labelKey)} />\n    {:else if sectionKey !== ''}\n      <MainArea title={_('page_not_found')}>\n        <NotFound message={_('page_not_found')} backPath={ADMIN_PATH} />\n      </MainArea>\n    {/if}\n  {/snippet}\n</PageContainer>\n","<!--\n  @component\n  Preview of a plaintext asset in the details overlay. Markdown is rendered as HTML, anything else\n  is shown as is.\n-->\n<script>\n  import { parse } from 'marked';\n\n  import { sanitizeRichTextHTML } from '$lib/services/contents/fields/rich-text/sanitize';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} text File content.\n   * @property {string} name File name, used to detect Markdown.\n   */\n\n  /** @type {Props} */\n  let { text, name } = $props();\n</script>\n\n{#if name.endsWith('.md')}\n  {#await parse(text, { breaks: true, async: true }) then rawHTML}\n    <div role=\"figure\" class=\"markdown\">\n      <!-- Unlike in the entry preview, a file from the repository can’t embed frames -->\n      {@html sanitizeRichTextHTML(rawHTML, { ADD_TAGS: [] })}\n    </div>\n  {:catch}\n    <pre role=\"figure\">{text}</pre>\n  {/await}\n{:else}\n  <pre role=\"figure\">{text}</pre>\n{/if}\n\n<style>\n  .markdown {\n    /* Make the preview the containing block of any positioned element in the content, so an element\n       with `position: fixed` from an inline style can’t cover the rest of the app */\n    translate: 0;\n  }\n\n  pre,\n  .markdown {\n    display: block;\n    margin: 0;\n    padding: 16px;\n    width: 100%;\n    height: 100%;\n    overflow: auto;\n  }\n\n  pre {\n    white-space: pre-wrap;\n  }\n</style>\n","<!--\n  @component\n  Preview of an asset in the details overlay, shared by repository folders and external locations:\n  a media player or image for a media file, a sandboxed frame for a PDF, the content of a text file,\n  or a notice that the file can’t be previewed.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState } from '@sveltia/ui';\n  import { isTextFileType } from '@sveltia/utils/file';\n\n  import TextPreview from '$lib/components/assets/list/text-preview.svelte';\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import { isMediaKind } from '$lib/services/assets/kinds';\n\n  /**\n   * @import { Asset, AssetKind } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {AssetKind | undefined} kind Asset kind.\n   * @property {string} name File name.\n   * @property {string | null | undefined} type MIME type of the file, if known.\n   * @property {Asset} [asset] Repository asset to preview. If given, a media file is previewed from\n   * it rather than from `src`.\n   * @property {string | undefined} src URL of the file.\n   * @property {boolean} [pending] Whether the file’s type is still being looked up, in which case\n   * a file other than a media file is shown as loading rather than unavailable.\n   * @property {() => Promise<string> | string} getText Function to get the content of a text file.\n   */\n\n  /** @type {Props} */\n  let { kind, name, type, asset = undefined, src, pending = false, getText } = $props();\n\n  /** A media file is previewed from the asset if there is one, as the URL may not be ready yet. */\n  const mediaSrc = $derived(asset ? undefined : src);\n</script>\n\n{#if kind && isMediaKind(kind)}\n  <AssetPreview\n    {kind}\n    {asset}\n    src={mediaSrc}\n    blurBackground={['image', 'video'].includes(kind)}\n    checkerboard={kind === 'image'}\n    alt={kind === 'image' ? name : undefined}\n    controls={['audio', 'video'].includes(kind)}\n    loading=\"eager\"\n    dissolve={false}\n    holdTransition={true}\n  />\n{:else if pending}\n  <EmptyState>\n    <span role=\"alert\">{_('loading')}</span>\n  </EmptyState>\n{:else if type === 'application/pdf'}\n  <iframe {src} title={name} sandbox=\"allow-scripts\"></iframe>\n{:else if type && isTextFileType(type)}\n  {#await getText()}\n    <EmptyState>\n      <span role=\"alert\">{_('loading')}</span>\n    </EmptyState>\n  {:then text}\n    <TextPreview {text} {name} />\n  {:catch}\n    <EmptyState>\n      <span role=\"alert\">{_('preview_unavailable')}</span>\n    </EmptyState>\n  {/await}\n{:else}\n  <EmptyState>\n    <span role=\"alert\">{_('preview_unavailable')}</span>\n  </EmptyState>\n{/if}\n","<!--\n  @component\n  Note shown in a deletion dialog about the entries referencing what’s being deleted — other\n  entries, through Relation fields, or assets, through Image, File and Markdown fields: either that\n  the references will be removed along with the deletion, or that the deletion can’t go ahead\n  because a field would be left invalid, along with the fields in question. Nothing is rendered when\n  no entry references what’s being deleted.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  /**\n   * @import { CascadeDeletePlan } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {CascadeDeletePlan} plan Plan from `planCascadeDelete()` or `planAssetDeletion()`.\n   * @property {'entry' | 'asset'} [kind] What’s being deleted.\n   * @property {number} count Number of entries or assets being deleted.\n   */\n\n  /** @type {Props} */\n  let { plan, kind = 'entry', count } = $props();\n</script>\n\n{#if plan.blockers.length}\n  <div role=\"alert\">\n    {_(kind === 'asset' ? 'cannot_delete_referenced_assets' : 'cannot_delete_referenced_entries', {\n      values: { count },\n    })}\n  </div>\n  <ul class=\"blockers\">\n    {#each plan.blockers as blocker (`${blocker.entry.id}:${blocker.keyPath}`)}\n      <li>\n        <span class=\"entry\"><bdi>{blocker.collectionLabel} › {blocker.summary}</bdi></span>\n        <span class=\"field\"><bdi>{blocker.fieldLabel}</bdi>: {blocker.messages.join(' ')}</span>\n      </li>\n    {/each}\n  </ul>\n{:else if plan.targets.length}\n  <div>\n    {_(kind === 'asset' ? 'deleting_referenced_assets_note' : 'deleting_referenced_entries_note', {\n      values: { count: plan.targets.length },\n    })}\n  </div>\n{/if}\n\n<style>\n  div {\n    margin-top: 8px;\n  }\n\n  .blockers {\n    margin: 8px 0 0;\n    border-radius: var(--sui-control-medium-border-radius);\n    padding: 12px;\n    background-color: var(--sui-tertiary-background-color);\n    font-size: var(--sui-font-size-default);\n    list-style: none;\n\n    li {\n      margin: 0;\n      padding: 0;\n\n      &:not(:first-child) {\n        margin-top: 8px;\n      }\n    }\n\n    span {\n      display: block;\n    }\n\n    .field {\n      color: var(--sui-secondary-foreground-color);\n    }\n  }\n</style>\n","<!--\n  @component\n  Delete button with a confirmation dialog, shared by repository assets and assets on external\n  locations. The caller provides the function that performs the deletion, and optionally one that\n  works out what the deletion means for the entries using the assets, which the dialog then reports\n  or, if a field would be left invalid, refuses the deletion over.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, ConfirmationDialog, MenuItem } from '@sveltia/ui';\n  import { tick } from 'svelte';\n\n  import CascadeDeleteNote from '$lib/components/common/cascade-delete-note.svelte';\n  import { focusList } from '$lib/services/app/focus';\n\n  /**\n   * @import { Asset, CascadeDeletePlan, ExternalAsset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {(Asset | ExternalAsset)[]} [assets] Selected assets.\n   * @property {boolean} [disabled] Whether deleting is not possible for the location, regardless\n   * of the selection.\n   * @property {(assets: any[]) => Promise<boolean | void> | void} deleteAssets Function that\n   * deletes the assets. `onDelete` is called once it returns, unless it resolves with `false`, so\n   * a function that starts the deletion without returning its promise lets the caller move on\n   * right away.\n   * @property {(assets: any[]) => Promise<CascadeDeletePlan>} [planDeletion] Function that works\n   * out what the deletion means for the entries using the assets. Deleting is held off until it\n   * has answered, and refused if it reports a field that would be left invalid.\n   * @property {number} [listedCount] Number of the assets listed in the view, given when the button\n   * deletes the selected assets, which may be all of them, rather than the asset shown in the\n   * details overlay. The button and the dialog describe the deletion accordingly.\n   * @property {(() => void) | undefined} [onDelete] Called once the assets have been deleted.\n   * @property {boolean} [useButton] Whether to use the Button component.\n   */\n\n  /** @type {Props} */\n  let {\n    assets = [],\n    disabled = false,\n    deleteAssets,\n    planDeletion = undefined,\n    listedCount = undefined,\n    onDelete = undefined,\n    useButton = true,\n  } = $props();\n\n  let showDialog = $state(false);\n  /**\n   * Plan for the assets the dialog was opened for, or `undefined` while it’s being worked out.\n   * @type {CascadeDeletePlan | undefined}\n   */\n  let plan = $state();\n  /** Whether the plan couldn’t be worked out, which leaves nothing to delete the assets with. */\n  let planFailed = $state(false);\n  /** @type {HTMLButtonElement | undefined} */\n  let button = $state();\n\n  const count = $derived(assets.length);\n  const buttonDescription = $derived(\n    listedCount === undefined\n      ? _('delete_assets', { values: { count: 1 } })\n      : _('delete_selected_assets', { values: { count } }),\n  );\n  const dialogDescription = $derived(\n    listedCount === undefined\n      ? _('confirm_deleting_this_asset')\n      : _(\n          count > 1 && count === listedCount\n            ? 'confirm_deleting_all_assets'\n            : 'confirm_deleting_selected_assets',\n          { values: { count } },\n        ),\n  );\n  const buttonDisabled = $derived(disabled || !count);\n  const blocked = $derived(!!plan?.blockers.length);\n\n  // Work out the plan whenever the dialog opens. The lookup is asynchronous, so the dialog starts\n  // without a plan, and the Delete button waits for it. The deletion then reuses the plan, unless\n  // the entries have changed in the meantime\n  $effect(() => {\n    if (!showDialog || !planDeletion) {\n      return;\n    }\n\n    const selection = assets;\n\n    plan = undefined;\n    planFailed = false;\n\n    planDeletion(selection).then(\n      (result) => {\n        // The dialog may have been reopened for another selection meanwhile\n        if (showDialog && assets === selection) {\n          plan = result;\n        }\n      },\n      (/** @type {any} */ ex) => {\n        // eslint-disable-next-line no-console\n        console.error(ex);\n\n        // Say why the assets can’t be deleted. A failed plan isn’t kept, so it’s worked out again\n        // once the dialog is reopened\n        if (showDialog && assets === selection) {\n          planFailed = true;\n        }\n      },\n    );\n  });\n\n  // The Delete button is disabled once the selected assets are deleted, which would drop its focus\n  // on `<body>`, so move it to the asset list. This runs before the button is updated, while it\n  // still has the focus\n  $effect.pre(() => {\n    if (buttonDisabled && document.activeElement === button) {\n      tick().then(() => focusList());\n    }\n  });\n</script>\n\n{#if useButton}\n  <Button\n    bind:element={button}\n    variant=\"ghost\"\n    disabled={buttonDisabled}\n    label={_('delete')}\n    aria-label={buttonDescription}\n    onclick={() => {\n      showDialog = true;\n    }}\n  />\n{:else}\n  <MenuItem\n    variant=\"ghost\"\n    disabled={buttonDisabled}\n    label={_('delete')}\n    aria-label={buttonDescription}\n    onclick={() => {\n      showDialog = true;\n    }}\n  />\n{/if}\n\n<ConfirmationDialog\n  bind:open={showDialog}\n  title={_('delete_assets', { values: { count } })}\n  okLabel={_('delete')}\n  okDisabled={!!planDeletion && (!plan || blocked)}\n  onOk={async () => {\n    if ((await deleteAssets(assets)) !== false) {\n      onDelete?.();\n    }\n  }}\n>\n  <!-- There’s nothing to confirm when the deletion is refused or can’t go ahead; the note or the\n  error explains why -->\n  {#if planFailed}\n    <div role=\"alert\">\n      {_('checking_asset_references_failed', { values: { count } })}\n    </div>\n  {:else if !blocked}\n    {dialogDescription}\n  {/if}\n  {#if plan}\n    <CascadeDeleteNote {plan} kind=\"asset\" {count} />\n  {/if}\n</ConfirmationDialog>\n","/**\n * @import { AssetNavigationDirection } from '$lib/types/private';\n */\n\n/**\n * Minimum horizontal travel of a touch, in pixels, to count as a swipe rather than a tap.\n */\nexport const SWIPE_MIN_DISTANCE = 50;\n\n/**\n * Elements that use the arrow keys themselves, e.g. to move the caret or to seek in a video, and\n * composite widgets that move the focus between their children with the keys.\n */\nexport const ARROW_KEY_USER_SELECTOR = [\n  'input',\n  'textarea',\n  'select',\n  'audio',\n  'video',\n  '[role=\"grid\"]',\n  '[role=\"listbox\"]',\n  '[role=\"menu\"]',\n  '[role=\"menubar\"]',\n  '[role=\"radiogroup\"]',\n  '[role=\"slider\"]',\n  '[role=\"tablist\"]',\n].join(', ');\n\n/**\n * Elements that are dragged sideways themselves, e.g. the timeline and volume controls of a media\n * player, so a touch on them is never a swipe.\n */\nexport const SWIPE_USER_SELECTOR = 'audio, video, input, [role=\"slider\"]';\n\n/**\n * Get the direction to move in with an arrow key: the left arrow key moves to the previous asset\n * and the right arrow key to the next asset, or the other way around in a right-to-left locale. Key\n * presses outside the overlay, e.g. in a dialog, and those that mean something else where the focus\n * is are left alone.\n * @param {KeyboardEvent} event `keydown` event.\n * @param {object} options Options.\n * @param {HTMLElement | undefined} options.container Overlay element.\n * @param {boolean} options.rtl Whether the UI locale is written right to left.\n * @returns {AssetNavigationDirection | undefined} Direction, or `undefined` if the key press isn’t\n * a move.\n */\nexport const getArrowKeyDirection = (event, { container, rtl }) => {\n  const { key, ctrlKey, metaKey, altKey, shiftKey, target } = event;\n\n  if (!['ArrowLeft', 'ArrowRight'].includes(key) || ctrlKey || metaKey || altKey || shiftKey) {\n    return undefined;\n  }\n\n  // The focus lands on the body when the focused button gets disabled at the end of the list\n  if (\n    !(target instanceof HTMLElement) ||\n    !(target === document.body || container?.contains(target)) ||\n    target.isContentEditable ||\n    target.closest(ARROW_KEY_USER_SELECTOR)\n  ) {\n    return undefined;\n  }\n\n  return key === (rtl ? 'ArrowRight' : 'ArrowLeft') ? 'previous' : 'next';\n};\n\n/**\n * Check if a touch starting on the given element can be a swipe.\n * @param {EventTarget | null} target Element the touch started on.\n * @returns {boolean} Result.\n */\nexport const canSwipeOn = (target) =>\n  !(target instanceof Element && target.closest(SWIPE_USER_SELECTOR));\n\n/**\n * Get the direction to move in with a swipe: a swipe towards the end of the line moves to the\n * previous asset, and a swipe towards the start to the next asset, as if the assets were laid out\n * in a row. A mostly vertical move is a scroll, not a swipe.\n * @param {object} args Arguments.\n * @param {{ x: number, y: number }} args.start Where the touch started.\n * @param {{ x: number, y: number }} args.end Where the touch ended.\n * @param {boolean} args.rtl Whether the UI locale is written right to left.\n * @returns {AssetNavigationDirection | undefined} Direction, or `undefined` if the touch isn’t a\n * swipe.\n */\nexport const getSwipeDirection = ({ start, end, rtl }) => {\n  const dx = end.x - start.x;\n  const dy = end.y - start.y;\n\n  if (Math.abs(dx) < SWIPE_MIN_DISTANCE || Math.abs(dx) < Math.abs(dy)) {\n    return undefined;\n  }\n\n  return (rtl ? dx < 0 : dx > 0) ? 'previous' : 'next';\n};\n","<!--\n  @component\n  Full-screen overlay showing an asset’s details, shared by repository assets and assets on\n  external locations: a toolbar with the back button, title, previous/next buttons, action buttons\n  and edit options menu, the preview and the info panel. On small screens, the action buttons move\n  into the edit options menu, so they are rendered with `useButton` set to `false` there.\n\n  The overlay is usually opened from a list of assets, so the user can move between the listed\n  assets with the previous/next buttons, the left/right arrow keys, or a horizontal swipe on a touch\n  screen.\n-->\n<script>\n  import { _, isRTL } from '@sveltia/i18n';\n  import { Button, Icon, Toolbar, TruncatedText } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import BackButton from '$lib/components/common/page-toolbar/back-button.svelte';\n  import { focusOverlay, rememberFocus } from '$lib/services/app/focus';\n  import { showAssetOverlay } from '$lib/services/assets/view';\n  import {\n    canSwipeOn,\n    getArrowKeyDirection,\n    getSwipeDirection,\n  } from '$lib/services/assets/view/overlay-navigation';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { AssetNavigationDirection } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [title] Asset name.\n   * @property {string} [contentKey] Value that identifies the shown asset; the content is\n   * re-rendered when it changes.\n   * @property {() => void} onBack Called when the back button is clicked or Escape is pressed.\n   * @property {() => void} [onPrevious] Called when the user moves to the previous asset with the\n   * button, the arrow key or a swipe. Omit it when there is no previous asset.\n   * @property {() => void} [onNext] Called when the user moves to the next asset with the button,\n   * the arrow key or a swipe. Omit it when there is no next asset.\n   * @property {Snippet<[boolean]>} actions Action buttons, given whether to render them as buttons\n   * (`true`) or as menu items (`false`).\n   * @property {Snippet<[Snippet]>} editOptions Edit options menu button, given the snippet of extra\n   * menu items to be placed at the top of the menu.\n   * @property {Snippet} preview Preview of the asset, or a not-found message.\n   * @property {Snippet} [info] Info panel.\n   */\n\n  /** @type {Props} */\n  let {\n    title = undefined,\n    contentKey = undefined,\n    onBack,\n    onPrevious = undefined,\n    onNext = undefined,\n    actions,\n    editOptions,\n    preview,\n    info = undefined,\n  } = $props();\n\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n\n  /**\n   * Where the current touch started, or `undefined` while nothing is touching the screen.\n   * @type {{ x: number, y: number } | undefined}\n   */\n  let touchStart;\n\n  $effect(() => {\n    if (showAssetOverlay.current) {\n      focusOverlay(() => wrapper);\n    }\n  });\n\n  // The row that opened the overlay gets the focus back once it closes\n  onMount(rememberFocus);\n\n  /**\n   * Get the handler moving to the previous or next asset.\n   * @param {AssetNavigationDirection | undefined} direction Direction to move in, if any.\n   * @returns {(() => void) | undefined} Handler, or `undefined` if there is no asset to move to.\n   */\n  const getHandler = (direction) =>\n    direction === 'previous' ? onPrevious : direction === 'next' ? onNext : undefined;\n\n  /**\n   * Move to the previous or next asset with the left/right arrow key.\n   * @param {KeyboardEvent} event `keydown` event.\n   */\n  const onKeyDown = (event) => {\n    const handler = getHandler(getArrowKeyDirection(event, { container: wrapper, rtl: isRTL() }));\n\n    if (handler) {\n      event.preventDefault();\n      handler();\n    }\n  };\n\n  /**\n   * Remember where a touch started to detect a swipe later.\n   * @param {TouchEvent} event `touchstart` event.\n   */\n  const onTouchStart = ({ touches, target }) => {\n    const { clientX: x, clientY: y } = touches[0];\n\n    touchStart = canSwipeOn(target) ? { x, y } : undefined;\n  };\n\n  /**\n   * Move to the previous or next asset with a horizontal swipe.\n   * @param {TouchEvent} event `touchend` event.\n   */\n  const onTouchEnd = ({ changedTouches }) => {\n    if (!touchStart) {\n      return;\n    }\n\n    const { clientX: x, clientY: y } = changedTouches[0];\n    const direction = getSwipeDirection({ start: touchStart, end: { x, y }, rtl: isRTL() });\n\n    touchStart = undefined;\n    getHandler(direction)?.();\n  };\n</script>\n\n<svelte:window onkeydown={onKeyDown} />\n\n{#snippet overflowItems()}\n  {#if env.isSmallScreen}\n    {@render actions(false)}\n  {/if}\n{/snippet}\n\n<div role=\"group\" class=\"wrapper\" aria-label={_('asset_editor')} bind:this={wrapper}>\n  {#key contentKey}\n    <Toolbar variant=\"primary\" ariaLabel={_('primary')}>\n      <BackButton aria-label={_('cancel_editing')} useShortcut={true} onclick={onBack} />\n      <h2 role=\"none\">\n        <TruncatedText>\n          <bdi>{title}</bdi>\n        </TruncatedText>\n      </h2>\n      {#if !env.isSmallScreen}\n        {@render actions(true)}\n      {/if}\n      {@render editOptions(overflowItems)}\n    </Toolbar>\n  {/key}\n  <div role=\"none\" class=\"row\" ontouchstart={onTouchStart} ontouchend={onTouchEnd}>\n    <div role=\"none\" class=\"main\">\n      <!-- The preview is remounted for each asset, so the previous/next transition slides it -->\n      {#key contentKey}\n        <div role=\"none\" class=\"preview\">\n          {@render preview()}\n        </div>\n      {/key}\n      <!--\n        The navigation buttons stay mounted across assets, so a button keeps the focus while the\n        user clicks it repeatedly\n      -->\n      <Button\n        variant=\"tertiary\"\n        iconic\n        class=\"nav-button previous\"\n        aria-label={_('previous_asset')}\n        disabled={!onPrevious}\n        onclick={() => onPrevious?.()}\n      >\n        {#snippet startIcon()}\n          <Icon name={isRTL() ? 'arrow_forward' : 'arrow_back'} />\n        {/snippet}\n      </Button>\n      <Button\n        variant=\"tertiary\"\n        iconic\n        class=\"nav-button next\"\n        aria-label={_('next_asset')}\n        disabled={!onNext}\n        onclick={() => onNext?.()}\n      >\n        {#snippet startIcon()}\n          <Icon name={isRTL() ? 'arrow_back' : 'arrow_forward'} />\n        {/snippet}\n      </Button>\n    </div>\n    {#key contentKey}\n      {@render info?.()}\n    {/key}\n  </div>\n</div>\n\n<style>\n  @keyframes slide-out-to-left {\n    to {\n      transform: translateX(-100%);\n    }\n  }\n\n  @keyframes slide-out-to-right {\n    to {\n      transform: translateX(100%);\n    }\n  }\n\n  @keyframes slide-in-from-left {\n    from {\n      transform: translateX(-100%);\n    }\n  }\n\n  @keyframes slide-in-from-right {\n    from {\n      transform: translateX(100%);\n    }\n  }\n\n  /*\n   * Slide the preview sideways when moving between the listed assets, as if they were laid out in\n   * a row: the next asset comes in from the end of the line, the previous one from the start. The\n   * toolbar, navigation buttons and info panel aren’t part of the transition, so they stay put and\n   * the info panel simply dissolves.\n   */\n\n  :global {\n    html:active-view-transition-type(next),\n    html:active-view-transition-type(previous) {\n      /* Keep the sliding snapshots within the preview area, off the info panel and the buttons */\n      &::view-transition-image-pair(asset-details) {\n        overflow: clip;\n      }\n\n      &::view-transition-old(asset-details),\n      &::view-transition-new(asset-details) {\n        animation-duration: 200ms;\n        animation-timing-function: ease-out;\n        animation-fill-mode: both;\n\n        @media (prefers-reduced-motion) {\n          animation: none;\n        }\n      }\n    }\n\n    html:active-view-transition-type(next) {\n      &::view-transition-old(asset-details) {\n        animation-name: slide-out-to-left;\n      }\n\n      &::view-transition-new(asset-details) {\n        animation-name: slide-in-from-right;\n      }\n\n      &:dir(rtl) {\n        &::view-transition-old(asset-details) {\n          animation-name: slide-out-to-right;\n        }\n\n        &::view-transition-new(asset-details) {\n          animation-name: slide-in-from-left;\n        }\n      }\n    }\n\n    html:active-view-transition-type(previous) {\n      &::view-transition-old(asset-details) {\n        animation-name: slide-out-to-right;\n      }\n\n      &::view-transition-new(asset-details) {\n        animation-name: slide-in-from-left;\n      }\n\n      &:dir(rtl) {\n        &::view-transition-old(asset-details) {\n          animation-name: slide-out-to-left;\n        }\n\n        &::view-transition-new(asset-details) {\n          animation-name: slide-in-from-right;\n        }\n      }\n    }\n  }\n\n  /*\n   * The preview and the navigation buttons are named only for the previous/next transition: the\n   * buttons to be layered above the sliding preview, and the preview to slide on its own. During\n   * the page transitions, e.g. when the overlay is opened or closed on a small screen, they must\n   * stay unnamed to move along with the rest of the page.\n   */\n\n  :global(html:is(:active-view-transition-type(next), :active-view-transition-type(previous))) {\n    .preview {\n      view-transition-name: asset-details;\n    }\n\n    .row :global(.nav-button.previous) {\n      view-transition-name: asset-nav-previous;\n    }\n\n    .row :global(.nav-button.next) {\n      view-transition-name: asset-nav-next;\n    }\n  }\n\n  .wrapper {\n    position: fixed;\n    inset: 0;\n    z-index: 100;\n    display: flex;\n    flex-direction: column;\n    background-color: var(--sui-secondary-background-color);\n\n    .row {\n      flex: auto;\n      display: flex;\n      overflow: hidden;\n\n      @media (width < 768px) {\n        flex-direction: column;\n\n        .main {\n          flex: none;\n          aspect-ratio: 1 / 1;\n        }\n\n        :global {\n          .detail {\n            flex: auto;\n            border-block-start: var(--area-border);\n            width: auto;\n          }\n        }\n      }\n\n      @media (768px <= width) {\n        :global {\n          .detail {\n            border-inline-start: var(--area-border);\n          }\n        }\n      }\n\n      .main {\n        position: relative;\n        flex: auto;\n        display: flex;\n        overflow: hidden;\n      }\n\n      .preview {\n        flex: auto;\n        overflow: hidden;\n\n        :global {\n          iframe {\n            display: block;\n            width: 100%;\n            height: 100%;\n          }\n        }\n      }\n\n      :global {\n        .nav-button {\n          position: absolute;\n          top: 50%;\n          translate: 0 -50%;\n          margin: 0;\n          border-radius: 50%;\n          opacity: 0.5;\n\n          &:hover,\n          &:focus-visible {\n            opacity: 1;\n          }\n\n          &.previous {\n            inset-inline-start: 16px;\n          }\n\n          &.next {\n            inset-inline-end: 16px;\n          }\n        }\n\n        .detail {\n          background-color: var(--sui-primary-background-color);\n        }\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Download button, shared by repository assets and assets on external locations. The caller\n  provides how to get each file’s name and content.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Button, MenuItem, Toast } from '@sveltia/ui';\n  import { saveFile } from '@sveltia/utils/file';\n  import { sleep } from '@sveltia/utils/misc';\n\n  /**\n   * @import { Asset, ExternalAsset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {(Asset | ExternalAsset)[]} [assets] Selected assets.\n   * @property {(asset: any) => string} getName Function that returns an asset’s file name.\n   * @property {(asset: any) => Promise<Blob>} getBlob Function that returns an asset’s content.\n   * @property {boolean} [useButton] Whether to use the Button component.\n   */\n\n  /** @type {Props} */\n  let { assets = [], getName, getBlob, useButton = true } = $props();\n\n  /** @type {{ show: boolean, status: 'success' | 'error' }} */\n  const toast = $state({ show: false, status: 'success' });\n\n  const Component = $derived(useButton ? Button : MenuItem);\n\n  /**\n   * Download the assets.\n   */\n  const downloadFiles = async () => {\n    try {\n      // eslint-disable-next-line no-restricted-syntax\n      for (const asset of assets) {\n        // eslint-disable-next-line no-await-in-loop\n        saveFile(await getBlob(asset), getName(asset));\n        // eslint-disable-next-line no-await-in-loop\n        await sleep(300);\n      }\n\n      toast.status = 'success';\n    } catch (ex) {\n      toast.status = 'error';\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      toast.show = true;\n    }\n  };\n</script>\n\n<Component\n  variant=\"ghost\"\n  disabled={!assets.length}\n  label={_('download')}\n  onclick={() => {\n    downloadFiles();\n  }}\n/>\n\n<Toast bind:show={toast.show}>\n  <Alert status={toast.status}>\n    {#if toast.status === 'success'}\n      {_('assets_downloaded', { values: { count: assets.length } })}\n    {:else}\n      {_('assets_dialog.error.image_fetch_failed')}\n    {/if}\n  </Alert>\n</Toast>\n","<!--\n  @component\n  Copy menu of the asset toolbar, shared by repository assets and assets on external locations. The\n  caller defines the items and how each one copies its data to clipboard.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Menu, MenuButton, MenuItem, Toast } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} CopyMenuItem\n   * @property {string} label Item label.\n   * @property {boolean} [disabled] Whether the item is disabled.\n   * @property {() => Promise<void>} copy Function that copies the data to clipboard.\n   * @property {string} toastKey Key of the success message, which takes `count`.\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {CopyMenuItem[]} items Menu items.\n   * @property {number} count Number of selected assets, used in the messages.\n   * @property {boolean} [useButton] Whether to use the Button component.\n   */\n\n  /** @type {Props} */\n  let { items, count, useButton = true } = $props();\n\n  /** @type {{ show: boolean, text: string, status: 'success' | 'error' }} */\n  const toast = $state({ show: false, text: '', status: 'success' });\n\n  /**\n   * Execute a copy action.\n   * @param {CopyMenuItem} item Menu item.\n   */\n  const doCopyAction = async ({ copy, toastKey }) => {\n    try {\n      await copy();\n      toast.status = 'success';\n      toast.text = _(toastKey, { values: { count } });\n    } catch (ex) {\n      toast.status = 'error';\n      toast.text = _('clipboard_error');\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      toast.show = true;\n    }\n  };\n</script>\n\n{#snippet menuItems()}\n  {#each items as item (item.label)}\n    <MenuItem\n      label={item.label}\n      disabled={item.disabled}\n      onclick={() => {\n        doCopyAction(item);\n      }}\n    />\n  {/each}\n{/snippet}\n\n{#if useButton}\n  <MenuButton variant=\"ghost\" disabled={!count} label={_('copy')} popupPosition=\"bottom-right\">\n    {#snippet popup()}\n      <Menu ariaLabel={_('copy_options')}>\n        {@render menuItems()}\n      </Menu>\n    {/snippet}\n  </MenuButton>\n{:else}\n  <MenuItem disabled={!count} label={_('copy')} popupPosition=\"left-top\">\n    {#snippet items()}\n      {@render menuItems()}\n    {/snippet}\n  </MenuItem>\n{/if}\n\n<Toast bind:show={toast.show}>\n  <Alert status={toast.status}>{toast.text}</Alert>\n</Toast>\n","import { isTextFileType } from '@sveltia/utils/file';\n\nimport { SUPPORTED_IMAGE_TYPES } from '$lib/services/utils/media/image';\nimport { transformImage } from '$lib/services/utils/media/image/transform';\nimport mime from '$lib/services/utils/mime';\n\n/**\n * Check if the data of a file of the given type can be copied to clipboard. Browsers typically\n * support only plaintext and PNG image, so the file has to be plaintext or an image that can be\n * converted to PNG, and the `write()` method used for an image has to be available.\n * @param {string} type MIME type.\n * @returns {boolean} Result.\n */\nexport const canCopyFileData = (type) => {\n  if (isTextFileType(type)) {\n    return true;\n  }\n\n  if (SUPPORTED_IMAGE_TYPES.includes(type)) {\n    return typeof navigator.clipboard.write === 'function';\n  }\n\n  return false;\n};\n\n/**\n * Check if the data of the given file can be copied to clipboard, going by its name, for a file\n * that hasn’t been fetched yet. See {@link canCopyFileData}.\n * @param {string} fileName File name.\n * @param {object} [options] Options.\n * @param {boolean} [options.isImage] Whether the file is known to be an image, e.g. as a cloud\n * service says so. Such a file is taken as copyable when its name has no extension to tell the\n * type by, as the image is most likely in a common format.\n * @returns {boolean} Result.\n */\nexport const canCopyFileDataByName = (fileName, { isImage = false } = {}) => {\n  const type = mime.getType(fileName);\n\n  return type ? canCopyFileData(type) : isImage;\n};\n\n/**\n * Copy the file data to clipboard. Given that browsers typically support only plaintext and PNG\n * image, convert the file if necessary.\n * @param {Blob} blob File.\n * @throws {Error} If the file is neither plaintext nor a supported image.\n */\nexport const copyFileData = async (blob) => {\n  const { type } = blob;\n\n  if (isTextFileType(type)) {\n    await navigator.clipboard.writeText(await blob.text());\n\n    return;\n  }\n\n  if (!SUPPORTED_IMAGE_TYPES.includes(type)) {\n    throw new Error('Unsupported type');\n  }\n\n  await navigator.clipboard.write([\n    new ClipboardItem({\n      'image/png': type === 'image/png' ? blob : await transformImage(blob),\n    }),\n  ]);\n};\n","<!--\n  @component\n  Copy menu for an asset on a cloud storage service: public URLs, file paths, file IDs and file\n  data. The file path is the asset’s location on the service, and the file ID is the identifier the\n  service uses, e.g. an object key or a UUID, which is what an API call or a `prefix`-relative path\n  would need.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import CopyMenu from '$lib/components/assets/list/copy-menu.svelte';\n  import { fetchExternalAssetBlob } from '$lib/services/assets/external/data';\n  import { canCopyFileDataByName, copyFileData } from '$lib/services/utils/clipboard';\n\n  /**\n   * @import { ExternalAsset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ExternalAsset[]} [assets] Selected assets.\n   * @property {boolean} [useButton] Whether to use the Button component.\n   */\n\n  /** @type {Props} */\n  let { assets = [], useButton = true } = $props();\n\n  /**\n   * Whether the file data can be copied: a single plaintext file or an image the clipboard can take\n   * is selected. Unlike repository assets, the file has to be fetched from the service first, so\n   * the type is guessed from the file name, and the fetch may still fail if the service doesn’t\n   * allow cross-origin requests.\n   */\n  const canCopyData = $derived(\n    assets.length === 1 &&\n      canCopyFileDataByName(assets[0].fileName, { isImage: assets[0].kind === 'image' }),\n  );\n\n  /**\n   * Copy the asset public URL(s) to clipboard.\n   */\n  const copyPublicURLs = async () => {\n    await navigator.clipboard.writeText(assets.map((a) => a.downloadURL).join('\\n'));\n  };\n\n  /**\n   * Copy the asset file path(s) on the service to clipboard.\n   */\n  const copyFilePaths = async () => {\n    await navigator.clipboard.writeText(assets.map((a) => a.description).join('\\n'));\n  };\n\n  /**\n   * Copy the asset ID(s) to clipboard.\n   */\n  const copyFileIDs = async () => {\n    await navigator.clipboard.writeText(assets.map((a) => a.id).join('\\n'));\n  };\n\n  // A file linked from an entry has nothing but its URL, so the path and ID items are left out\n  const hasPath = $derived(assets.some((a) => a.description !== a.downloadURL));\n  const hasId = $derived(assets.some((a) => a.id !== a.downloadURL));\n\n  const items = $derived(\n    [\n      {\n        label: _('public_urls', { values: { count: assets.length } }),\n        copy: copyPublicURLs,\n        toastKey: 'asset_urls_copied',\n      },\n      hasPath && {\n        label: _('file_paths', { values: { count: assets.length } }),\n        copy: copyFilePaths,\n        toastKey: 'asset_paths_copied',\n      },\n      hasId && {\n        label: _('file_ids', { values: { count: assets.length } }),\n        copy: copyFileIDs,\n        toastKey: 'asset_ids_copied',\n      },\n      {\n        label: _('file_data'),\n        disabled: !canCopyData,\n        /**\n         * Fetch the file and copy its data to clipboard.\n         */\n        copy: async () => {\n          await copyFileData(await fetchExternalAssetBlob(assets[0]));\n        },\n        toastKey: 'asset_data_copied',\n      },\n    ].filter((item) => !!item),\n  );\n</script>\n\n<CopyMenu {items} count={assets.length} {useButton} />\n","<!--\n  @component\n  Edit options menu button, shared by repository assets and assets on external locations. The\n  caller provides the handlers for the built-in Edit, Rename, Move and Replace items, and any extra\n  items.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Menu, MenuButton, MenuItem } from '@sveltia/ui';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [readOnly] Whether every edit operation is unavailable, e.g. for an Open\n   * Authoring contributor.\n   * @property {boolean} [canEdit] Whether the asset can be edited.\n   * @property {boolean} [canRename] Whether the asset can be renamed.\n   * @property {boolean} [canReplace] Whether the asset can be replaced.\n   * @property {boolean} [canMove] Whether the asset can be moved to another folder.\n   * @property {() => void} [onEdit] Called when the Edit item is selected. The item is omitted\n   * when this is not given, which means the location doesn’t support the operation at all.\n   * @property {() => void} [onRename] Called when the Rename item is selected. Same as above.\n   * @property {() => void} [onReplace] Called when the Replace item is selected. Same as above.\n   * @property {() => void} [onMove] Called when the Move item is selected. Same as above.\n   * @property {Snippet} [extraItems] Items placed at the top of the menu.\n   * @property {Snippet} [moreItems] Items placed at the bottom of the menu, after a divider.\n   */\n\n  /** @type {Props} */\n  let {\n    readOnly = false,\n    canEdit = false,\n    canRename = false,\n    canReplace = false,\n    canMove = false,\n    onEdit = undefined,\n    onRename = undefined,\n    onReplace = undefined,\n    onMove = undefined,\n    extraItems = undefined,\n    moreItems = undefined,\n  } = $props();\n</script>\n\n<MenuButton variant=\"ghost\" iconic popupPosition=\"bottom-right\" aria-label={_('show_edit_options')}>\n  {#snippet popup()}\n    <Menu ariaLabel={_('edit_options')}>\n      {@render extraItems?.()}\n      {#if onEdit}\n        <MenuItem\n          variant=\"ghost\"\n          label={_('edit')}\n          aria-label={_('edit_asset')}\n          disabled={readOnly || !canEdit}\n          onclick={onEdit}\n        />\n      {/if}\n      {#if onRename}\n        <MenuItem\n          variant=\"ghost\"\n          label={_('rename')}\n          aria-label={_('rename_asset')}\n          disabled={readOnly || !canRename}\n          onclick={onRename}\n        />\n      {/if}\n      {#if onMove}\n        <MenuItem\n          variant=\"ghost\"\n          label={_('move')}\n          aria-label={_('move_asset')}\n          disabled={readOnly || !canMove}\n          onclick={onMove}\n        />\n      {/if}\n      {#if onReplace}\n        <MenuItem\n          variant=\"ghost\"\n          label={_('replace')}\n          aria-label={_('replace_asset')}\n          disabled={readOnly || !canReplace}\n          onclick={onReplace}\n        />\n      {/if}\n      {#if moreItems}\n        <Divider />\n        {@render moreItems()}\n      {/if}\n    </Menu>\n  {/snippet}\n</MenuButton>\n","<!--\n  @component\n  Edit options menu for an asset on a cloud storage service: Rename, Move and Replace.\n-->\n<script>\n  import { FilePicker } from '@sveltia/ui';\n\n  import EditOptionsMenu from '$lib/components/assets/list/edit-options-menu.svelte';\n  import { renamingExternalAsset, selectedCloudService } from '$lib/services/assets/external';\n  import { uploadingExternalAssets } from '$lib/services/assets/external/data';\n  import { canMoveExternalAssets } from '$lib/services/assets/movable';\n  import { assetMoveRequest } from '$lib/services/assets/state';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ExternalAsset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ExternalAsset} [asset] Selected asset.\n   * @property {ExternalAsset[]} [assets] Assets the Move item applies to, as several can be\n   * selected in the list. Default: the selected asset.\n   * @property {Snippet} [extraItems] Slot content.\n   */\n\n  /** @type {Props} */\n  let { asset, assets = asset ? [asset] : [], extraItems = undefined } = $props();\n\n  /** @type {FilePicker | undefined} */\n  let replaceFilePicker = $state();\n\n  const service = $derived(selectedCloudService.current);\n\n  /**\n   * Replace the asset with the given file.\n   * @param {File} file File.\n   */\n  const replaceAsset = (file) => {\n    /* v8 ignore next 3 -- the picker is only opened for an asset */\n    if (asset) {\n      uploadingExternalAssets.current = { files: [file], originalAsset: asset };\n    }\n  };\n</script>\n\n<!-- The items for operations the service doesn’t support are omitted rather than disabled -->\n<EditOptionsMenu\n  canRename={!!asset}\n  canReplace={!!asset}\n  canMove={!!service && canMoveExternalAssets(service, assets)}\n  onRename={service?.rename\n    ? () => {\n        renamingExternalAsset.current = asset;\n      }\n    : undefined}\n  onMove={service?.delete\n    ? () => {\n        assetMoveRequest.current = { externalAssets: [...assets], service };\n      }\n    : undefined}\n  onReplace={service?.replace\n    ? () => {\n        replaceFilePicker?.open();\n      }\n    : undefined}\n  {extraItems}\n/>\n\n<FilePicker\n  bind:this={replaceFilePicker}\n  onSelect={({ file }) => {\n    replaceAsset(file);\n  }}\n/>\n","/**\n * Format the given duration in the `hh:mm:ss` format. Note that it assumes the duration is less\n * than 24 hours.\n * @param {number} duration Duration in seconds.\n * @returns {string} Formatted duration, or `–` if the duration is not a finite number. A media\n * element reports `Infinity` for a stream or a WebM file recorded with `MediaRecorder`, which has\n * no duration in its header, and a `Date` can’t hold that.\n */\nexport const formatDuration = (duration) =>\n  Number.isFinite(duration) ? new Date(duration * 1000).toISOString().substr(11, 8) : '–';\n","<!--\n  @component\n  Sections of the asset info panel describing the file itself, shared by repository assets and\n  assets on external locations: kind, size, and the dimensions and duration of a media file.\n-->\n<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { getPathInfo } from '@sveltia/utils/file';\n\n  import { formatSize } from '$lib/services/assets/file-size';\n  import { getFileTypeLabel } from '$lib/services/assets/file-type';\n  import { formatDuration } from '$lib/services/utils/media/video';\n  import mime from '$lib/services/utils/mime';\n\n  /**\n   * @import { AssetKind, MediaDimensions } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} fileName File name or path, whose extension tells the file type.\n   * @property {AssetKind} kind Asset kind, shown as the file type when there is no extension.\n   * @property {number} [size] File size in bytes, if known.\n   * @property {boolean} [hasDimensions] Whether the file is one with dimensions, e.g. an image, so\n   * the section is shown even while they are still being read.\n   * @property {MediaDimensions} [dimensions] Media dimensions, once read.\n   * @property {number} [duration] Media duration in seconds, once read.\n   */\n\n  /** @type {Props} */\n  let {\n    fileName,\n    kind,\n    size = undefined,\n    hasDimensions = false,\n    dimensions = undefined,\n    duration = undefined,\n  } = $props();\n\n  const { extension = '' } = $derived(getPathInfo(fileName));\n</script>\n\n<section>\n  <h4>{_('kind')}</h4>\n  <p>\n    <!-- A linked file may have no extension, e.g. an avatar URL, so fall back to the kind -->\n    {getFileTypeLabel(fileName, {\n      fallback: mime.getType(fileName) ?? (extension ? extension.toUpperCase() : _(kind)),\n    })}\n  </p>\n</section>\n{#if !!size}\n  <section>\n    <h4>{_('size')}</h4>\n    <p>\n      {#key appLocale.current}\n        {formatSize(size)}\n      {/key}\n    </p>\n  </section>\n{/if}\n{#if hasDimensions}\n  <section>\n    <h4>{_('dimensions')}</h4>\n    <p>{dimensions ? `${dimensions.width}×${dimensions.height}` : '–'}</p>\n  </section>\n{/if}\n{#if ['audio', 'video'].includes(kind)}\n  <section>\n    <h4>{_('duration')}</h4>\n    <p>{duration ? formatDuration(duration) : '–'}</p>\n  </section>\n{/if}\n","<!--\n  @component\n  Layout of the asset info panel, shared by repository assets and assets on external locations: an\n  optional preview followed by sections with a heading and a value.\n-->\n<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Snippet} [preview] Media preview.\n   * @property {Snippet} children Sections.\n   */\n\n  /** @type {Props} */\n  let { preview = undefined, children } = $props();\n</script>\n\n<div role=\"none\" class=\"detail\">\n  {#if preview}\n    <div role=\"none\" class=\"preview\">\n      {@render preview()}\n    </div>\n  {/if}\n  {@render children()}\n</div>\n\n<style>\n  .detail {\n    flex: none;\n    overflow-x: hidden;\n    overflow-y: auto;\n    padding: 16px;\n    width: 320px;\n\n    .preview {\n      overflow: hidden;\n      margin: 0 0 16px;\n      border-radius: var(--sui-control-large-border-radius);\n      background-color: var(--sui-content-background-color);\n      aspect-ratio: 1 / 1;\n    }\n\n    :global {\n      section {\n        &:not(:last-child) {\n          margin: 0 0 16px;\n        }\n\n        & > * {\n          margin: 0 0 4px;\n          word-break: break-all;\n        }\n      }\n\n      h4 {\n        font-size: var(--sui-font-size-small);\n        font-weight: var(--sui-font-weight-bold);\n        color: var(--sui-secondary-foreground-color);\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  “Used in” section of the asset info panel, listing the entries that reference the asset with\n  links to the entry editor. Shared by repository assets and assets on external locations.\n-->\n<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Button } from '@sveltia/ui';\n\n  import { goto } from '$lib/services/app/navigation';\n  import { getCollectionLabel } from '$lib/services/contents/collection';\n  import { getListedCollections } from '$lib/services/contents/collection/entries';\n  import {\n    getCollectionFileLabel,\n    getCollectionFilesByEntry,\n  } from '$lib/services/contents/collection/files';\n  import { getEntryEditorPath } from '$lib/services/contents/editor/route';\n  import { getEntrySummary } from '$lib/services/contents/entry/summary';\n\n  /**\n   * @import { Entry } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Entry[] | undefined} entries Entries using the asset. `undefined` while the\n   * information is being fetched.\n   */\n\n  /** @type {Props} */\n  let { entries } = $props();\n\n  /**\n   * Entries using the asset, each with the collections it’s listed in. A collection that filters\n   * the entry out or is hidden can’t open it, so the entry isn’t linked from there, and an entry\n   * no collection lists isn’t shown at all.\n   */\n  const usages = $derived(\n    entries\n      ?.map((entry) => ({ entry, collections: getListedCollections(entry) }))\n      .filter(({ collections }) => collections.length),\n  );\n</script>\n\n{#snippet usedEntryLink(\n  /** @type {Record<string, string>} */ { link, collectionLabel, entryLabel },\n)}\n  <p>\n    <Button role=\"link\" variant=\"link\" onclick={() => goto(link, { transitionType: 'forwards' })}>\n      <span role=\"none\">{collectionLabel} › {entryLabel}</span>\n    </Button>\n  </p>\n{/snippet}\n\n<section>\n  <h4>{_('used_in')}</h4>\n  {#if !usages}\n    <p>{_('loading')}</p>\n  {:else}\n    {#each usages as { entry, collections } (entry.id)}\n      {#each collections as collection (collection.name)}\n        {#key appLocale.current}\n          {@const collectionLabel = getCollectionLabel(collection)}\n          {#each getCollectionFilesByEntry(collection, entry) as file (file.name)}\n            {@render usedEntryLink({\n              link: getEntryEditorPath(collection.name, file.name),\n              collectionLabel,\n              entryLabel: getCollectionFileLabel(file),\n            })}\n          {:else}\n            {@render usedEntryLink({\n              link: getEntryEditorPath(collection.name, entry.subPath),\n              collectionLabel,\n              entryLabel: getEntrySummary(collection, entry, { useTemplate: true }),\n            })}\n          {/each}\n        {/key}\n      {/each}\n    {:else}\n      <p>{_('sort_keys.none')}</p>\n    {/each}\n  {/if}\n</section>\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Alert } from '@sveltia/ui';\n\n  import FileInfoSections from '$lib/components/assets/list/file-info-sections.svelte';\n  import InfoPanelLayout from '$lib/components/assets/list/info-panel-layout.svelte';\n  import UsedEntries from '$lib/components/assets/list/used-entries.svelte';\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import { externalAssetAvailability } from '$lib/services/assets/external/availability';\n  import {\n    getExternalAssetDetails,\n    getExternalAssetUsedEntries,\n  } from '$lib/services/assets/external/details';\n  import { isMediaKind } from '$lib/services/assets/kinds';\n  import { formatDate } from '$lib/services/utils/date';\n  import { createLatestGuard } from '$lib/services/utils/scheduling';\n\n  /**\n   * @import { ExternalAssetDetails } from '$lib/services/assets/external/details';\n   * @import { Entry, ExternalAsset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ExternalAsset} asset Asset.\n   */\n\n  /** @type {Props} */\n  let { asset } = $props();\n\n  /** @type {ExternalAssetDetails} */\n  let details = $state({});\n  /** @type {Entry[] | undefined} */\n  let usedEntries = $state();\n\n  const { fileName, description, previewURL, downloadURL, kind, size, lastModified } =\n    $derived(asset);\n  const { dimensions, duration } = $derived(details);\n  const canPreview = $derived(isMediaKind(kind));\n  /** Only a file linked from an entry is checked, so this is never `true` on a cloud service. */\n  const unavailable = $derived(externalAssetAvailability.current[asset.id] === false);\n\n  /**\n   * Guard for {@link updateProps}. The panel stays mounted while the focus moves from one asset\n   * to another, so a slow lookup for an asset focused earlier must not overwrite the details of the\n   * one focused now.\n   */\n  const requestGuard = createLatestGuard();\n\n  /**\n   * Update the properties above.\n   * @param {ExternalAsset} _asset Asset to look up. Passed rather than read from the prop, because\n   * the prop is gone once the panel is destroyed, e.g. when the Info pane is hidden by a window\n   * resize, while this is still awaiting the service.\n   */\n  const updateProps = async (_asset) => {\n    const isLatest = requestGuard.next();\n\n    details = {};\n    usedEntries = undefined;\n\n    try {\n      const _details = await getExternalAssetDetails(_asset);\n\n      if (!isLatest()) {\n        return;\n      }\n\n      details = _details;\n    } catch {\n      // The file could not be loaded; leave the media info out\n    }\n\n    try {\n      const _usedEntries = await getExternalAssetUsedEntries(_asset);\n\n      if (isLatest()) {\n        usedEntries = _usedEntries;\n      }\n    } catch (/** @type {any} */ ex) {\n      // eslint-disable-next-line no-console\n      console.error(ex);\n\n      if (isLatest()) {\n        // Stop showing the used entries as being loaded\n        usedEntries = [];\n      }\n    }\n  };\n\n  $effect(() => {\n    updateProps(asset);\n  });\n</script>\n\n{#snippet preview()}\n  <AssetPreview\n    {kind}\n    src={kind === 'image' ? previewURL : downloadURL}\n    alt={fileName}\n    variant=\"tile\"\n    checkerboard={kind === 'image'}\n    controls={['audio', 'video'].includes(kind)}\n  />\n{/snippet}\n\n<InfoPanelLayout preview={canPreview ? preview : undefined}>\n  {#if unavailable}\n    <div role=\"none\" class=\"unavailable\">\n      <!-- Not announced on focus: the badge in the list has already told the user -->\n      <Alert status=\"error\" ariaLive=\"off\">{_('file_unavailable_description')}</Alert>\n    </div>\n  {/if}\n  <FileInfoSections {fileName} {kind} {size} hasDimensions={canPreview} {dimensions} {duration} />\n  <section>\n    <h4>{_('public_urls', { values: { count: 1 } })}</h4>\n    <p>\n      <a href={downloadURL} dir=\"ltr\" target=\"_blank\" rel=\"noopener noreferrer\">{downloadURL}</a>\n    </p>\n  </section>\n  <!-- A file linked from an entry has nothing but its URL, so the path is left out -->\n  {#if description && description !== fileName && description !== downloadURL}\n    <section>\n      <h4>{_('file_paths', { values: { count: 1 } })}</h4>\n      <p><bdi dir=\"ltr\">{description}</bdi></p>\n    </section>\n  {/if}\n  <UsedEntries entries={usedEntries} />\n  {#if lastModified}\n    <section>\n      <h4>{_('sort_keys.last_modified')}</h4>\n      <p>{formatDate(lastModified, appLocale.current)}</p>\n    </section>\n  {/if}\n</InfoPanelLayout>\n\n<style>\n  .unavailable {\n    margin: 0 0 16px;\n  }\n</style>\n","<!--\n  @component\n  Details overlay for an asset on a cloud storage service. The file is previewed straight from the\n  service’s URL, so a text file can only be shown when the service allows cross-origin requests.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState } from '@sveltia/ui';\n\n  import AssetPreviewContent from '$lib/components/assets/list/asset-preview-content.svelte';\n  import DeleteAssetsButton from '$lib/components/assets/list/delete-assets-button.svelte';\n  import DetailsOverlay from '$lib/components/assets/list/details-overlay.svelte';\n  import DownloadAssetsButton from '$lib/components/assets/list/download-assets-button.svelte';\n  import CopyAssetsButton from '$lib/components/assets/list/external/copy-assets-button.svelte';\n  import EditOptionsButton from '$lib/components/assets/list/external/edit-options-button.svelte';\n  import InfoPanel from '$lib/components/assets/list/external/info-panel.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import { goBack, goto } from '$lib/services/app/navigation';\n  import {\n    canPreviewExternalAsset,\n    externalAssets,\n    getCloudServicePath,\n    getExternalAssetPath,\n    overlaidExternalAssetId,\n    selectedCloudService,\n  } from '$lib/services/assets/external';\n  import { deleteExternalAssets, fetchExternalAssetBlob } from '$lib/services/assets/external/data';\n  import { externalAssetGroups } from '$lib/services/assets/external/view';\n  import { getAdjacentAssets } from '$lib/services/assets/view';\n  import { env } from '$lib/services/user/env.svelte';\n  import mime from '$lib/services/utils/mime';\n\n  /**\n   * @import { ViewTransitionType } from '$lib/services/app/navigation';\n   * @import { ExternalAsset, MediaLibraryService } from '$lib/types/private';\n   */\n\n  /** The component is only rendered while a service is selected. */\n  const service = $derived(/** @type {MediaLibraryService} */ (selectedCloudService.current));\n  /** Whether the asset list has been loaded, so the asset can be looked up. */\n  const loaded = $derived(!!externalAssets.current);\n  const asset = $derived(\n    externalAssets.current?.find(({ id }) => id === overlaidExternalAssetId.current),\n  );\n  const kind = $derived(asset?.kind);\n  const fileName = $derived(asset?.fileName ?? '');\n  /* v8 ignore start -- only read while the asset is shown */\n  const downloadURL = $derived(asset?.downloadURL ?? '');\n  /* v8 ignore stop */\n  const type = $derived(mime.getType(fileName));\n  const assets = $derived(asset ? [asset] : []);\n  const backPath = $derived(getCloudServicePath(service));\n  /** The assets right before and after the shown one in the list the overlay was opened from. */\n  const { previous, next } = $derived(\n    getAdjacentAssets(\n      externalAssetGroups.current,\n      ({ id }) => id === asset?.id,\n      canPreviewExternalAsset,\n    ),\n  );\n\n  /**\n   * Show another listed asset in place of the current one. The history entry is replaced, so the\n   * browser’s back button still returns to the list however many assets have been flipped through.\n   * @param {ExternalAsset} target Asset to be shown.\n   * @param {ViewTransitionType} transitionType View transition type.\n   */\n  const showAsset = (target, transitionType) => {\n    goto(getExternalAssetPath(service, target), { replaceState: true, transitionType });\n  };\n</script>\n\n<DetailsOverlay\n  title={fileName}\n  contentKey={asset?.id}\n  onBack={() => {\n    goBack(backPath);\n  }}\n  onPrevious={previous ? () => showAsset(previous, 'previous') : undefined}\n  onNext={next ? () => showAsset(next, 'next') : undefined}\n>\n  {#snippet actions(useButton)}\n    <CopyAssetsButton {assets} {useButton} />\n    <DownloadAssetsButton\n      {assets}\n      getName={(a) => a.fileName}\n      getBlob={fetchExternalAssetBlob}\n      {useButton}\n    />\n    {#if service.delete}\n      <DeleteAssetsButton\n        {assets}\n        deleteAssets={deleteExternalAssets}\n        onDelete={() => {\n          goBack(backPath);\n        }}\n        {useButton}\n      />\n    {/if}\n  {/snippet}\n  {#snippet editOptions(extraItems)}\n    <!-- On small screens, the menu also holds the other actions, so it’s always needed there -->\n    {#if service.rename || service.replace || env.isSmallScreen}\n      <EditOptionsButton {asset} {extraItems} />\n    {/if}\n  {/snippet}\n  {#snippet preview()}\n    {#if !loaded}\n      <EmptyState>\n        <span role=\"alert\">{_('loading')}</span>\n      </EmptyState>\n    {:else if !asset || !kind}\n      <NotFound message={_('file_not_found')} {backPath} />\n    {:else}\n      <AssetPreviewContent\n        {kind}\n        name={fileName}\n        {type}\n        src={downloadURL}\n        getText={() => fetchExternalAssetBlob(asset).then((blob) => blob.text())}\n      />\n    {/if}\n  {/snippet}\n  {#snippet info()}\n    {#if asset}\n      <InfoPanel {asset} />\n    {/if}\n  {/snippet}\n</DetailsOverlay>\n","<!--\n  @component A container for the entry list or asset list.\n-->\n<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Snippet} [children] Slot content.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let { children = undefined, ...rest } = $props();\n</script>\n\n<div role=\"group\" class=\"list-container\" {...rest}>\n  {@render children?.()}\n</div>\n\n<style>\n  .list-container {\n    --icon-size: 36px;\n\n    flex: auto;\n    position: relative;\n    height: 100%;\n    overflow-x: hidden;\n    overflow-y: auto;\n    overscroll-behavior-y: contain;\n  }\n</style>\n","<!--\n  @component A wrapper of the `Grid` component that can display a list of entries, files or assets\n  in a simple table or grid.\n-->\n<script>\n  import { Grid } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ViewType} viewType View type.\n   * @property {string} [aria-label] Accessible name of the grid.\n   * @property {any} [scrollKey] Value whose change scrolls the list back to the top, e.g. when the\n   * items are sorted differently.\n   * @property {Snippet} [children] Slot content.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let {\n    viewType,\n    // The `Grid` component takes its accessible name as a prop; a spread `aria-label` is dropped\n    'aria-label': ariaLabel = undefined,\n    scrollKey = undefined,\n    children = undefined,\n    ...rest\n  } = $props();\n\n  /**\n   * Scrolling element. A plain variable, as nothing has to react to it.\n   * @type {HTMLElement | undefined}\n   */\n  let scroller;\n\n  $effect(() => {\n    void scrollKey;\n\n    /* v8 ignore next -- the element is attached before the effect runs */\n    if (scroller) {\n      scroller.scrollTop = 0;\n    }\n  });\n</script>\n\n<div\n  role=\"none\"\n  class=\"{viewType}-view\"\n  {@attach (element) => {\n    scroller = element;\n  }}\n>\n  {#await sleep() then}\n    <Grid multiple clickToSelect={false} {ariaLabel} {...rest}>\n      {@render children?.()}\n    </Grid>\n  {/await}\n</div>\n\n<style>\n  :is(.grid-view, .list-view, .table-view) {\n    display: block;\n    padding: 0 16px 16px;\n    height: 100%;\n    overflow-y: auto;\n  }\n\n  .grid-view {\n    @media (width < 768px) {\n      padding: 4px;\n    }\n\n    :global {\n      .row-group-caption {\n        display: block;\n        grid-column: 1 / -1; /* span the entire row */\n\n        th {\n          display: block;\n        }\n      }\n\n      .row-group:not(:first-child) .row-group-caption {\n        margin-top: 16px;\n      }\n\n      .grid-body {\n        display: grid;\n        grid-template-columns: repeat(auto-fill, minmax(var(--grid-size, 200px), 1fr));\n        gap: 16px;\n        border-width: 0;\n\n        @media (width < 768px) {\n          grid-template-columns: repeat(auto-fill, minmax(var(--grid-size, 160px), 1fr));\n          gap: 8px;\n        }\n      }\n\n      .grid-row {\n        display: block;\n        position: relative;\n        overflow: hidden;\n        height: auto;\n        text-align: start;\n\n        .grid-cell {\n          display: block;\n\n          &.image:empty {\n            aspect-ratio: 1 / 1;\n          }\n        }\n\n        .checkbox {\n          position: absolute;\n          inset-block-start: 4px;\n          inset-inline-start: 4px;\n          z-index: 2;\n        }\n\n        .title {\n          .label {\n            overflow: hidden;\n            margin: 12px;\n            height: calc(var(--sui-line-height-compact) * 2);\n            line-height: var(--sui-line-height-compact);\n          }\n        }\n\n        /* Editorial Workflow status, shown below the title on a tile */\n        .status {\n          margin: -4px 12px 12px;\n        }\n\n        &[tabindex] {\n          border-radius: var(--sui-control-large-border-radius);\n          background-color: var(--sui-secondary-background-color);\n          cursor: pointer;\n          transition: background-color 200ms;\n\n          &:is(:hover, :focus, :active) {\n            background-color: var(--sui-hover-background-color);\n          }\n        }\n      }\n    }\n  }\n\n  :is(.list-view, .table-view) {\n    @media (width < 768px) {\n      padding: 0;\n    }\n\n    :global {\n      [role='grid'] {\n        @media (width < 768px) {\n          width: 100%;\n          --sui-focus-ring-width: 0;\n        }\n\n        .row-group {\n          .row-group-caption + .grid-row {\n            .grid-cell {\n              border-top-width: 0 !important;\n            }\n          }\n\n          .row-group-caption ~ .grid-row:last-child {\n            .grid-cell {\n              border-bottom-width: 0 !important;\n            }\n          }\n        }\n\n        .grid-row {\n          transition-property: background-color, outline-color;\n          transition-duration: 200ms;\n\n          &[tabindex] {\n            cursor: pointer;\n          }\n\n          &:hover {\n            background-color: var(--sui-hover-background-color);\n          }\n\n          &:last-child .grid-cell {\n            border-width: 1px 0;\n          }\n        }\n\n        .grid-cell {\n          overflow: hidden;\n          border-width: 1px 0 0;\n          border-color: var(--sui-secondary-border-color);\n          padding: 0 16px 0 0;\n          height: 40px;\n          max-width: 100%;\n          color: var(--sui-secondary-foreground-color);\n          white-space: nowrap;\n          vertical-align: middle;\n\n          @media (width < 768px) {\n            border-width: 0 !important;\n            height: 64px;\n          }\n\n          &.checkbox {\n            padding-inline-start: 8px !important;\n            width: 44px;\n          }\n\n          &.title {\n            width: 100%; /* flex: auto */\n            color: var(--sui-primary-foreground-color);\n          }\n\n          /*\n           * The column is as wide as the widest Editorial Workflow status badge, so align the\n           * badges to the end of the row rather than letting the narrower ones float mid-column\n           */\n\n          &.status {\n            text-align: end;\n          }\n\n          &:first-child {\n            padding-inline-start: 16px;\n          }\n\n          .label {\n            overflow: hidden;\n\n            @media (width < 768px) {\n              white-space: normal;\n              line-height: var(--sui-line-height-compact);\n            }\n          }\n\n          &.image {\n            width: 48px;\n\n            &:empty::before {\n              display: block;\n              border-radius: var(--sui-control-medium-border-radius);\n              width: var(--icon-size);\n              height: var(--icon-size);\n              background-color: var(--sui-secondary-background-color);\n              content: '';\n            }\n          }\n        }\n      }\n    }\n  }\n\n  /* The table view is a list view with more columns, only shown on a large screen */\n  .table-view {\n    :global {\n      [role='grid'] {\n        /* The header row can be focused, but it doesn’t open anything */\n        .grid-head .grid-row {\n          cursor: default;\n\n          &:hover {\n            background-color: transparent;\n          }\n        }\n\n        .grid-col-header {\n          position: sticky;\n          inset-block-start: 0;\n          z-index: 1;\n          border-bottom: 1px solid var(--sui-secondary-border-color);\n          padding: 0 16px 0 0;\n          height: 40px;\n          background-color: var(--sui-primary-background-color);\n          color: var(--sui-secondary-foreground-color);\n          font-size: var(--sui-font-size-small);\n          font-weight: var(--sui-font-weight-bold);\n          text-align: start;\n          white-space: nowrap;\n          vertical-align: middle;\n\n          &:first-child {\n            padding-inline-start: 16px;\n          }\n        }\n\n        /* Each column is as wide as its content, up to a limit; the text is truncated beyond */\n        .grid-cell.title {\n          width: auto;\n\n          .label {\n            width: max-content;\n            min-width: 160px;\n            max-width: 400px;\n          }\n        }\n\n        .grid-cell.column .label {\n          width: max-content;\n          max-width: 320px;\n        }\n\n        /* The last column takes up the rest of the width, so the others are as wide as their\n          content */\n\n        :is(.grid-cell, .grid-col-header).status {\n          width: 100%;\n        }\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Container of the asset list, shared by repository folders and external locations: a drop zone\n  for uploads around a grid of asset groups, or an empty state with an upload button.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState, GridBody, InfiniteScroll } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n\n  import DropZone from '$lib/components/assets/shared/drop-zone.svelte';\n  import ListContainer from '$lib/components/common/list-container.svelte';\n  import ListingGrid from '$lib/components/common/listing-grid.svelte';\n  import { currentView } from '$lib/services/assets/view/settings';\n  import { getGroupLabel, isGroupCollapsed, setGroupCollapsed } from '$lib/services/common/view';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { Asset, ExternalAsset, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Record<string, (Asset | ExternalAsset)[]>} groups Assets to be listed, grouped by\n   * label. A group labelled `*` has no caption.\n   * @property {string} itemKey Property of an asset that identifies it in the list.\n   * @property {number} totalCount Number of listed assets before any filter is applied, for\n   * `aria-rowcount`.\n   * @property {ViewType} viewType View type.\n   * @property {boolean} uploadDisabled Whether uploads are disabled for the location.\n   * @property {(files: File[]) => void} onDrop Called with the files dropped on the list.\n   * @property {() => void} [onBlankClick] Called when the empty area of the list, outside any row,\n   * is clicked, which is how the focus is taken off an asset.\n   * @property {Snippet<[any, number]>} renderItem Renders a listed asset given the asset and its\n   * index.\n   * @property {Snippet} [subfolders] Rows for the subfolders of a repository folder, listed ahead\n   * of the asset groups.\n   * @property {boolean} [hasSubfolders] Whether there is any subfolder to list, in which case the\n   * grid is shown even when no asset is left to show.\n   * @property {Snippet} [emptyAction] Upload button shown in the empty state, unless uploads are\n   * disabled.\n   */\n\n  /** @type {Props} */\n  let {\n    groups,\n    itemKey,\n    totalCount,\n    viewType,\n    uploadDisabled,\n    onDrop,\n    onBlankClick = undefined,\n    renderItem,\n    subfolders = undefined,\n    hasSubfolders = false,\n    emptyAction = undefined,\n  } = $props();\n\n  /** Whether any asset is left to show once the filter has been applied. */\n  const hasAssets = $derived(Object.values(groups).some((assets) => assets.length));\n</script>\n\n<ListContainer\n  aria-label={_('asset_list')}\n  onclick={(/** @type {MouseEvent} */ event) => {\n    if (\n      !(/** @type {HTMLElement} */ (event.target).closest('[role=\"row\"], button, [role=\"menu\"]'))\n    ) {\n      onBlankClick?.();\n    }\n  }}\n>\n  <DropZone\n    disabled={uploadDisabled}\n    multiple={true}\n    onDrop={({ files }) => {\n      onDrop(files);\n    }}\n  >\n    {#if hasAssets || hasSubfolders}\n      <ListingGrid id=\"asset-list\" {viewType} aria-label={_('assets')} aria-rowcount={totalCount}>\n        {#if hasSubfolders}\n          <GridBody class=\"subfolders\">\n            {@render subfolders?.()}\n          </GridBody>\n        {/if}\n        {#each Object.entries(groups) as [name, assets] (name)}\n          {#await sleep() then}\n            <GridBody\n              label={name !== '*' ? getGroupLabel(name) : undefined}\n              collapsible={name !== '*'}\n              expanded={!isGroupCollapsed(currentView.current, name)}\n              onChange={({ detail: { expanded } }) => {\n                currentView.current = setGroupCollapsed(currentView.current, name, !expanded);\n              }}\n            >\n              <InfiniteScroll items={assets} {itemKey} {renderItem} />\n            </GridBody>\n          {/await}\n        {/each}\n      </ListingGrid>\n    {:else}\n      <EmptyState>\n        <span role=\"none\">{_('no_files_found')}</span>\n        {#if !uploadDisabled}\n          {@render emptyAction?.()}\n        {/if}\n      </EmptyState>\n    {/if}\n  </DropZone>\n</ListContainer>\n\n<style>\n  :global {\n    /* Keep the compact folder tiles apart from the asset tiles below them */\n    .grid-view .grid-body.subfolders:not(:last-child) {\n      margin-bottom: 16px;\n    }\n  }\n</style>\n","<!--\n  @component\n  A row or tile in the asset list, shared by repository folders and external locations. The caller\n  provides the asset’s display properties and handles selection, focus and preview.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Checkbox, GridCell, GridRow, TruncatedText } from '@sveltia/ui';\n\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import { env, opensOnClick } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { Attachment } from 'svelte/attachments';\n   * @import { Asset, AssetKind, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} name File name.\n   * @property {AssetKind} kind Asset kind.\n   * @property {Asset} [asset] Repository asset, whose thumbnail is generated by the CMS.\n   * @property {string} [src] Thumbnail URL for an asset on an external service.\n   * @property {number} rowIndex 0-based index of the asset in the list, for `aria-rowindex`. A\n   * negative index means the position is unknown, and the attribute is omitted.\n   * @property {ViewType} viewType View type.\n   * @property {boolean} selected Whether the asset is selected.\n   * @property {boolean} canPreview Whether the asset can be opened in the details overlay.\n   * @property {(selected: boolean) => void} onSelectionChange Called when the selection changes.\n   * @property {() => void} onFocus Called when the row gets focus.\n   * @property {() => void} onPreview Called when the asset is opened by a click on a small screen\n   * or a double-click.\n   * @property {Snippet} [status] Content of the status cell, shown below the title on a tile or at\n   * the end of a row, e.g. a badge. The cell is left out when not given, so that the rows of a\n   * list without statuses keep their layout, and wherever the title is left out, as the cell is\n   * laid out relative to the title.\n   * @property {Attachment<HTMLElement>} [dragSource] Attachment that lets the row be dragged to a\n   * folder, given when the asset can be moved.\n   */\n\n  /** @type {Props} */\n  let {\n    name,\n    kind,\n    asset = undefined,\n    src = undefined,\n    rowIndex,\n    viewType,\n    selected,\n    canPreview,\n    onSelectionChange,\n    onFocus,\n    onPreview,\n    status = undefined,\n    dragSource = undefined,\n  } = $props();\n\n  /**\n   * Open the details overlay, if the asset can be previewed.\n   */\n  const preview = () => {\n    if (canPreview) {\n      onPreview();\n    }\n  };\n</script>\n\n<GridRow\n  {@attach dragSource}\n  aria-rowindex={rowIndex >= 0 ? rowIndex + 1 : undefined}\n  aria-label={name}\n  onChange={(event) => {\n    onSelectionChange(event.detail.selected);\n  }}\n  onfocus={onFocus}\n  onclick={(/** @type {MouseEvent} */ event) => {\n    if (opensOnClick(event)) {\n      preview();\n    }\n  }}\n  ondblclick={preview}\n>\n  {#if !(env.isSmallScreen || env.isMediumScreen)}\n    <GridCell class=\"checkbox\">\n      <Checkbox\n        tabindex=\"-1\"\n        ariaLabel={_('select_item', { values: { name } })}\n        checked={selected}\n        onChange={({ detail: { checked } }) => {\n          onSelectionChange(checked);\n        }}\n      />\n    </GridCell>\n  {/if}\n  <GridCell class=\"image\">\n    <AssetPreview\n      {kind}\n      {asset}\n      {src}\n      alt={src ? name : ''}\n      variant={viewType === 'list' ? 'icon' : 'tile'}\n      cover={env.isSmallScreen}\n      checkerboard={kind === 'image'}\n    />\n  </GridCell>\n  {#if !env.isSmallScreen || viewType === 'list'}\n    <GridCell class=\"title\">\n      <div role=\"none\" class=\"label\">\n        <TruncatedText lines={2}>\n          <bdi>{name}</bdi>\n        </TruncatedText>\n      </div>\n    </GridCell>\n    {#if status}\n      <GridCell class=\"status\">\n        {@render status()}\n      </GridCell>\n    {/if}\n  {/if}\n</GridRow>\n\n<style>\n  .label {\n    word-break: break-all;\n  }\n</style>\n","<!--\n  @component\n  Pill marking a linked file that couldn’t be loaded, e.g. because it has been deleted, so that it\n  stands out in the asset list. Follows the Editorial Workflow status badge.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n</script>\n\n<span role=\"none\" class=\"badge\">\n  {_('file_unavailable')}\n</span>\n\n<style>\n  /*\n   * Filled pill following the same background/foreground/border recipe as the Alert and Infobar\n   * components, so the colors adapt to both the light and dark themes.\n   */\n\n  .badge {\n    display: inline-block;\n    border-width: 1px;\n    border-style: solid;\n    border-radius: 12px;\n    border-color: var(--sui-error-border-color);\n    padding: 1px 6px;\n    background-color: var(--sui-error-background-color);\n    color: var(--sui-error-foreground-color);\n    font-size: var(--sui-font-size-x-small);\n    line-height: var(--sui-line-height-compact);\n    white-space: nowrap;\n  }\n</style>\n","<script>\n  import AssetListItem from '$lib/components/assets/list/asset-list-item.svelte';\n  import UnavailableBadge from '$lib/components/assets/list/external/unavailable-badge.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { createAssetDragSource } from '$lib/services/assets/drag';\n  import {\n    canPreviewExternalAsset,\n    focusedExternalAsset,\n    focusedExternalSubfolder,\n    getExternalAssetPath,\n    hasFolderSupport,\n    selectedCloudService,\n    selectedExternalAssetIdSet,\n    selectedExternalAssets,\n  } from '$lib/services/assets/external';\n  import { externalAssetAvailability } from '$lib/services/assets/external/availability';\n  import { LINKED_FILES_SERVICE_ID } from '$lib/services/assets/external/linked';\n  import {\n    browsingExternalFolders,\n    listedExternalAssetIndexMap,\n  } from '$lib/services/assets/external/view';\n  import { canMoveExternalAssets, getDraggedExternalAssets } from '$lib/services/assets/movable';\n  import { toggleListItem } from '$lib/services/utils/array';\n\n  /**\n   * @import { ExternalAsset, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {ExternalAsset} asset Asset.\n   * @property {ViewType} viewType View type.\n   */\n\n  /** @type {Props} */\n  let { asset, viewType } = $props();\n\n  const selected = $derived(selectedExternalAssetIdSet.current.has(asset.id));\n  /**\n   * Whether the asset is a file linked from an entry, which is checked for availability. The files\n   * on a cloud storage service are listed by the service, so they always exist.\n   */\n  const isLinkedFile = $derived(\n    selectedCloudService.current?.serviceId === LINKED_FILES_SERVICE_ID,\n  );\n  const unavailable = $derived(externalAssetAvailability.current[asset.id] === false);\n  /** The service the file is on, which the list is only shown for. */\n  const service = $derived(selectedCloudService.current);\n  /**\n   * Attachment that lets the row be dragged onto a folder, when the file can be moved: not a file\n   * linked from an entry, which isn’t on a service the CMS manages.\n   */\n  const dragSource = $derived(\n    service && !isLinkedFile && canMoveExternalAssets(service, [asset])\n      ? createAssetDragSource(() => getDraggedExternalAssets(asset, service))\n      : undefined,\n  );\n  /**\n   * The name shown: the file name while the service is browsed folder by folder, or the path when\n   * a search lists the matches from every folder at once, so they can be told apart.\n   */\n  const name = $derived(\n    hasFolderSupport(selectedCloudService.current) && !browsingExternalFolders.current\n      ? asset.description\n      : asset.fileName,\n  );\n\n  /**\n   * Show the details of the asset.\n   */\n  const showDetails = () => {\n    /* v8 ignore next 3 -- the list is only shown while a service is selected */\n    if (service) {\n      goto(getExternalAssetPath(service, asset), { transitionType: 'forwards' });\n    }\n  };\n\n  /**\n   * Update the asset selection.\n   * @param {boolean} _selected Whether the current asset item is selected.\n   */\n  const updateSelection = (_selected) => {\n    selectedExternalAssets.current = toggleListItem(\n      selectedExternalAssets.current,\n      asset,\n      _selected,\n      (a, b) => a.id === b.id,\n    );\n  };\n</script>\n\n{#snippet status()}\n  {#if unavailable}\n    <UnavailableBadge />\n  {/if}\n{/snippet}\n\n<AssetListItem\n  {name}\n  kind={asset.kind}\n  src={asset.previewURL}\n  rowIndex={listedExternalAssetIndexMap.current.get(asset.id) ?? -1}\n  {viewType}\n  {selected}\n  canPreview={canPreviewExternalAsset(asset)}\n  onSelectionChange={updateSelection}\n  onFocus={() => {\n    focusedExternalAsset.current = asset;\n    focusedExternalSubfolder.current = undefined;\n  }}\n  onPreview={() => {\n    showDetails();\n  }}\n  status={isLinkedFile ? status : undefined}\n  {dragSource}\n/>\n","<!--\n  @component\n  A row or tile for a subfolder in the asset list, shown ahead of the assets, shared by repository\n  folders and cloud storage services. Opening it browses the folder in place of the current one,\n  and a menu offers to rename or delete the folder when the caller can do either.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { GridCell, GridRow, Icon, Menu, MenuButton, MenuItem, TruncatedText } from '@sveltia/ui';\n\n  import { opensOnClick } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Attachment } from 'svelte/attachments';\n   * @import { AssetSubfolder, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {AssetSubfolder} subfolder Subfolder.\n   * @property {number} rowIndex 0-based index of the subfolder in the list, for `aria-rowindex`.\n   * @property {ViewType} viewType View type.\n   * @property {boolean} [hasCheckboxColumn] Whether the asset rows have a checkbox column in the\n   * list view, which the folder row keeps aligned with by an empty cell.\n   * @property {() => void} onOpen Called when the folder is opened.\n   * @property {() => void} [onFocus] Called when the row is focused, to show the folder’s info.\n   * @property {() => void} [onRename] Called from the menu to rename the folder. The menu is shown\n   * only when this or `onDelete` is given.\n   * @property {() => void} [onDelete] Called from the menu to delete the folder.\n   * @property {boolean} [actionsDisabled] Whether the rename and delete actions are disabled.\n   * @property {Attachment<HTMLElement>} [dropTarget] Attachment that lets assets be dropped on the\n   * folder to be moved there.\n   */\n\n  /** @type {Props} */\n  let {\n    subfolder,\n    rowIndex,\n    viewType,\n    hasCheckboxColumn = false,\n    onOpen,\n    onFocus = undefined,\n    onRename = undefined,\n    onDelete = undefined,\n    actionsDisabled = false,\n    dropTarget = undefined,\n  } = $props();\n\n  /**\n   * Keep a click on the menu from reaching the row, where it would open the folder.\n   * @param {Event} event `click` or `dblclick` event.\n   */\n  const stopPropagation = (event) => {\n    event.stopPropagation();\n  };\n</script>\n\n<GridRow\n  {@attach dropTarget}\n  class=\"subfolder\"\n  aria-rowindex={rowIndex + 1}\n  aria-label={subfolder.name}\n  aria-description={_('folder')}\n  onfocus={() => {\n    onFocus?.();\n  }}\n  onclick={(/** @type {MouseEvent} */ event) => {\n    if (opensOnClick(event)) {\n      onOpen();\n    }\n  }}\n  ondblclick={onOpen}\n>\n  {#if viewType === 'list' && hasCheckboxColumn}\n    <!-- Keep the columns aligned with the asset rows, which have a checkbox here -->\n    <GridCell class=\"checkbox\"></GridCell>\n  {/if}\n  <GridCell class=\"image\">\n    <div role=\"none\" class=\"preview\">\n      <Icon name=\"folder\" />\n    </div>\n  </GridCell>\n  <!--\n    Unlike an image, a folder icon says nothing about the folder, so the name is always shown. The\n    menu shares the cell, so the row has the same columns as an asset row in the list view\n  -->\n  <GridCell class=\"title\">\n    <div role=\"none\" class=\"title-inner\">\n      <div role=\"none\" class=\"label\">\n        <TruncatedText lines={viewType === 'list' ? 1 : 2}>\n          <bdi>{subfolder.name}</bdi>\n        </TruncatedText>\n      </div>\n      {#if onRename || onDelete}\n        <div role=\"none\" class=\"menu\" onclick={stopPropagation} ondblclick={stopPropagation}>\n          <MenuButton\n            variant=\"ghost\"\n            iconic\n            size=\"small\"\n            popupPosition=\"bottom-right\"\n            aria-label={_('show_folder_options')}\n          >\n            {#snippet popup()}\n              <Menu ariaLabel={_('folder_options')}>\n                {#if onRename}\n                  <MenuItem\n                    variant=\"ghost\"\n                    label={_('rename')}\n                    aria-label={_('rename_folder')}\n                    disabled={actionsDisabled}\n                    onclick={onRename}\n                  />\n                {/if}\n                {#if onDelete}\n                  <MenuItem\n                    variant=\"ghost\"\n                    label={_('delete')}\n                    aria-label={_('delete_folder')}\n                    disabled={actionsDisabled}\n                    onclick={onDelete}\n                  />\n                {/if}\n              </Menu>\n            {/snippet}\n          </MenuButton>\n        </div>\n      {/if}\n    </div>\n  </GridCell>\n</GridRow>\n\n<style>\n  .preview {\n    display: inline-flex;\n    align-items: center;\n    justify-content: center;\n    color: var(--sui-secondary-foreground-color);\n\n    :global(.sui.icon) {\n      font-size: 24px;\n    }\n  }\n\n  .title-inner {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n  }\n\n  .label {\n    flex: auto;\n    min-width: 0;\n    word-break: break-all;\n  }\n\n  .menu {\n    flex: none;\n  }\n\n  :global {\n    /* Highlight a folder the dragged assets can be dropped on, like a folder in the sidebar */\n    .grid-row.subfolder.dragover {\n      color: var(--sui-primary-accent-color-inverted) !important;\n      background-color: var(--sui-primary-accent-color) !important;\n\n      .preview {\n        color: inherit;\n      }\n    }\n\n    /* A folder is a compact tile in the grid view, with the icon, the name and the menu in a row,\n    unlike an asset, which needs the room for its thumbnail. The selectors are specific enough to\n    win over the tile styles of the listing grid */\n\n    .grid-view .grid-body .grid-row.subfolder {\n      display: flex;\n      align-items: center;\n      gap: 12px;\n      padding: 8px 8px 8px 16px;\n\n      .grid-cell.image {\n        flex: none;\n        display: flex;\n        aspect-ratio: auto;\n      }\n\n      .grid-cell.title {\n        flex: auto;\n        min-width: 0;\n\n        .label {\n          margin: 0;\n          height: auto;\n        }\n      }\n    }\n\n    .list-view .grid-body .grid-row.subfolder {\n      /* The icon sits in a box the size of an asset thumbnail, so the two line up */\n      .preview {\n        width: var(--icon-size);\n        height: var(--icon-size);\n      }\n\n      .grid-cell.title {\n        padding-inline-end: 8px;\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  A row or tile for a subfolder on a cloud storage service in the Asset Library. Opening it browses\n  the folder, and the menu offers to rename or delete the folder where the service’s API allows.\n-->\n<script>\n  import SubfolderListItem from '$lib/components/assets/list/subfolder-list-item.svelte';\n  import { createAssetDropTarget } from '$lib/services/assets/drag';\n  import {\n    browseExternalFolder,\n    deletingExternalSubfolder,\n    focusedExternalAsset,\n    focusedExternalSubfolder,\n    renamingExternalSubfolder,\n    selectedCloudService,\n  } from '$lib/services/assets/external';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { AssetSubfolder, MediaLibraryService, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {AssetSubfolder} subfolder Subfolder.\n   * @property {number} rowIndex 0-based index of the subfolder in the list, for `aria-rowindex`.\n   * @property {ViewType} viewType View type.\n   */\n\n  /** @type {Props} */\n  let { subfolder, rowIndex, viewType } = $props();\n\n  /** The component is only rendered while a service is selected. */\n  const service = $derived(/** @type {MediaLibraryService} */ (selectedCloudService.current));\n  // Renaming a folder moves its files one by one, so it takes a service that can move a file\n  const canRename = $derived(!!service.move && !!service.createFolder && !!service.deleteFolder);\n  const canDelete = $derived(!!service.delete && !!service.deleteFolder);\n</script>\n\n<SubfolderListItem\n  {subfolder}\n  {rowIndex}\n  {viewType}\n  hasCheckboxColumn={!(env.isSmallScreen || env.isMediumScreen)}\n  onOpen={() => {\n    browseExternalFolder(subfolder.path);\n  }}\n  onFocus={() => {\n    // Show the folder’s info in the sidebar in place of an asset’s\n    focusedExternalSubfolder.current = subfolder;\n    focusedExternalAsset.current = undefined;\n  }}\n  onRename={canRename\n    ? () => {\n        renamingExternalSubfolder.current = subfolder;\n      }\n    : undefined}\n  dropTarget={createAssetDropTarget({ service, dirPath: subfolder.path })}\n  onDelete={canDelete\n    ? () => {\n        deletingExternalSubfolder.current = subfolder;\n      }\n    : undefined}\n/>\n","<!--\n  @component Upload button, shared by repository folders and external locations.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon } from '@sveltia/ui';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [label] Button label. If `undefined`, the button will be iconic.\n   * @property {boolean} [disabled] Whether uploads are disabled.\n   * @property {() => void} onclick Click handler.\n   */\n\n  /** @type {Props} */\n  let { label = undefined, disabled = false, onclick } = $props();\n</script>\n\n<Button\n  variant=\"primary\"\n  iconic={!label}\n  {disabled}\n  {label}\n  aria-label={_('upload_assets')}\n  {onclick}\n>\n  {#snippet startIcon()}\n    <Icon name=\"cloud_upload\" />\n  {/snippet}\n</Button>\n","<!--\n  @component Upload button for a cloud storage service, which opens the file picker.\n-->\n<script>\n  import { FilePicker } from '@sveltia/ui';\n\n  import UploadButton from '$lib/components/assets/list/upload-button.svelte';\n  import { hasAuthInfo, selectedCloudService } from '$lib/services/assets/external';\n  import { uploadingExternalAssets } from '$lib/services/assets/external/data';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [label] Button label. If `undefined`, the button will be iconic.\n   */\n\n  /** @type {Props} */\n  let { label = undefined } = $props();\n\n  /** @type {FilePicker | undefined} */\n  let filePicker = $state();\n\n  const service = $derived(selectedCloudService.current);\n  const disabled = $derived(!service?.upload || !hasAuthInfo(service));\n</script>\n\n<UploadButton\n  {label}\n  {disabled}\n  onclick={() => {\n    filePicker?.open();\n  }}\n/>\n\n<FilePicker\n  multiple\n  bind:this={filePicker}\n  onSelect={({ files }) => {\n    uploadingExternalAssets.current = { files };\n  }}\n/>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState } from '@sveltia/ui';\n\n  import CloudinaryPanel from '$lib/components/assets/browser/cloudinary-panel.svelte';\n  import AssetListContainer from '$lib/components/assets/list/asset-list-container.svelte';\n  import AssetListItem from '$lib/components/assets/list/external/asset-list-item.svelte';\n  import SubfolderListItem from '$lib/components/assets/list/external/subfolder-list-item.svelte';\n  import UploadAssetsButton from '$lib/components/assets/list/external/upload-assets-button.svelte';\n  import CloudServiceAuth from '$lib/components/assets/shared/cloud-service-auth.svelte';\n  import ListContainer from '$lib/components/common/list-container.svelte';\n  import {\n    externalAssets,\n    externalAssetsError,\n    focusedExternalAsset,\n    focusedExternalSubfolder,\n    hasAuthInfo,\n    selectedCloudService,\n  } from '$lib/services/assets/external';\n  import { uploadingExternalAssets } from '$lib/services/assets/external/data';\n  import {\n    externalAssetGroups,\n    listedExternalAssets,\n    listedExternalSubfolders,\n  } from '$lib/services/assets/external/view';\n  import { currentView } from '$lib/services/assets/view/settings';\n\n  /**\n   * @import { ExternalAsset, MediaLibraryService } from '$lib/types/private';\n   */\n\n  /** The component is only rendered while a service is selected. */\n  const service = $derived(/** @type {MediaLibraryService} */ (selectedCloudService.current));\n  const viewType = $derived(currentView.current.type);\n  const uploadDisabled = $derived(!service.upload);\n  const subfolderCount = $derived(listedExternalSubfolders.current.length);\n</script>\n\n{#if service.authType === 'widget'}\n  <!-- Cloudinary doesn’t allow API access from the browser, so its own widget is used instead -->\n  <ListContainer aria-label={_('asset_list')}>\n    {#if service.serviceId === 'cloudinary'}\n      <CloudinaryPanel onSelect={() => undefined} />\n    {/if}\n  </ListContainer>\n{:else if !hasAuthInfo(service) || externalAssetsError.current}\n  <!-- The saved credentials may have been rejected, so let the user enter new ones on failure -->\n  <ListContainer aria-label={_('asset_list')}>\n    <CloudServiceAuth\n      serviceProps={service}\n      error={externalAssetsError.current\n        ? _(`assets_dialog.error.${externalAssetsError.current}`)\n        : undefined}\n    />\n  </ListContainer>\n{:else if !externalAssets.current}\n  <ListContainer aria-label={_('asset_list')}>\n    <EmptyState>\n      <span role=\"alert\">{_('loading')}</span>\n    </EmptyState>\n  </ListContainer>\n{:else}\n  <AssetListContainer\n    groups={externalAssetGroups.current}\n    itemKey=\"id\"\n    totalCount={subfolderCount + listedExternalAssets.current.length}\n    hasSubfolders={!!subfolderCount}\n    {viewType}\n    {uploadDisabled}\n    onDrop={(files) => {\n      uploadingExternalAssets.current = { files };\n    }}\n    onBlankClick={() => {\n      // Show the info of the folder being browsed in place of an asset’s or a subfolder’s\n      focusedExternalAsset.current = undefined;\n      focusedExternalSubfolder.current = undefined;\n    }}\n  >\n    {#snippet subfolders()}\n      {#each listedExternalSubfolders.current as subfolder, index (subfolder.path)}\n        <SubfolderListItem {subfolder} rowIndex={index} {viewType} />\n      {/each}\n    {/snippet}\n    {#snippet renderItem(/** @type {ExternalAsset} */ asset)}\n      <AssetListItem {asset} {viewType} />\n    {/snippet}\n    {#snippet emptyAction()}\n      <UploadAssetsButton label={_('upload_assets')} />\n    {/snippet}\n  </AssetListContainer>\n{/if}\n","<!--\n  @component\n  Delete Folder dialog for a cloud storage service, opened for the subfolder set as\n  `deletingExternalSubfolder`. Deleting removes every file in the folder.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { ConfirmationDialog } from '@sveltia/ui';\n\n  import { deletingExternalSubfolder } from '$lib/services/assets/external';\n  import {\n    deleteExternalFolder,\n    getExternalSubfolderAssets,\n  } from '$lib/services/assets/external/data';\n\n  const subfolder = $derived(deletingExternalSubfolder.current);\n  // Open while there’s a folder to act on. Closing the dialog writes `open` back, and the folder is\n  // let go of once the dialog has closed\n  let open = $derived(!!subfolder);\n  /* v8 ignore start -- these are only read while the dialog is open, which takes a folder */\n  const folderName = $derived(subfolder?.name ?? '');\n  /** Number of assets in the folder, at any depth, which will be deleted along. */\n  const assetCount = $derived(subfolder ? getExternalSubfolderAssets(subfolder.path).length : 0);\n  /* v8 ignore stop */\n</script>\n\n<ConfirmationDialog\n  bind:open\n  title={_('delete_folder')}\n  okLabel={_('delete')}\n  onOk={() => {\n    /* v8 ignore next 3 -- the dialog is only open for a folder */\n    if (subfolder) {\n      deleteExternalFolder(subfolder);\n    }\n  }}\n  onClose={() => {\n    // The dialog is closed before the deletion is confirmed, so the folder is let go of here\n    // rather than when `open` turns false\n    deletingExternalSubfolder.current = undefined;\n  }}\n>\n  {_('confirm_deleting_folder', { values: { name: folderName, count: assetCount } })}\n</ConfirmationDialog>\n","<!--\n  @component\n  Info panel for a folder in the Asset Library, shown in the sidebar while no asset is focused: the\n  folder name, its path and what it holds. Shared by repository folders and cloud storage services,\n  which work out the folder to describe.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon } from '@sveltia/ui';\n\n  import InfoPanelLayout from '$lib/components/assets/list/info-panel-layout.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} name Folder name.\n   * @property {string} [path] Folder path, shown with a leading slash. Omitted for a location\n   * without a path, like the All Assets folder.\n   * @property {number} [folderCount] Number of subfolders. Omitted for a location that isn’t\n   * browsed by subfolder, which lists every asset below it at once.\n   * @property {number} assetCount Number of assets.\n   */\n\n  /** @type {Props} */\n  let { name, path = undefined, folderCount = undefined, assetCount } = $props();\n</script>\n\n{#snippet preview()}\n  <div role=\"none\" class=\"folder-preview\">\n    <Icon name=\"folder\" />\n  </div>\n{/snippet}\n\n<InfoPanelLayout {preview}>\n  <section>\n    <h4>{_('folder')}</h4>\n    <p><bdi>{name}</bdi></p>\n  </section>\n  {#if path !== undefined}\n    <section>\n      <h4>{_('folder_path')}</h4>\n      <p><bdi dir=\"ltr\">{`/${path}`}</bdi></p>\n    </section>\n  {/if}\n  <section>\n    <h4>{_('folder_contents')}</h4>\n    {#if folderCount !== undefined}\n      <p>{_('x_folders', { values: { count: folderCount } })}</p>\n    {/if}\n    <p>{_('x_assets', { values: { count: assetCount } })}</p>\n  </section>\n</InfoPanelLayout>\n\n<style>\n  .folder-preview {\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    height: 100%;\n    color: var(--sui-secondary-foreground-color);\n\n    :global(.sui.icon) {\n      font-size: 96px;\n    }\n  }\n</style>\n","<!--\n  @component\n  Info panel for a folder on a cloud storage service, shown in the sidebar while no asset is\n  focused. The folder is the listed subfolder focused with a click or the keyboard, if any, or else\n  the folder being browsed.\n-->\n<script>\n  import FolderInfoPanel from '$lib/components/assets/list/folder-info-panel.svelte';\n  import { externalFolderSummary } from '$lib/services/assets/external/view';\n\n  /**\n   * @import { AssetFolderSummary } from '$lib/types/private';\n   */\n\n  /** The component is only rendered while a service is selected. */\n  const info = $derived(/** @type {AssetFolderSummary} */ (externalFolderSummary.current));\n</script>\n\n<FolderInfoPanel\n  name={info.name}\n  path={info.path}\n  folderCount={info.folderCount}\n  assetCount={info.assetCount}\n/>\n","<!--\n  @component\n  New Folder dialog for a cloud storage service, opened with the New Folder button. It creates a\n  folder in the folder being browsed and reports the result, but leaves the user where they are:\n  the new folder is listed along with the others, ready to be opened.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import SubfolderNameDialog from '$lib/components/assets/list/subfolder-name-dialog.svelte';\n  import {\n    selectedCloudService,\n    selectedExternalDirPath,\n    showNewExternalFolderDialog,\n  } from '$lib/services/assets/external';\n  import { createExternalFolder } from '$lib/services/assets/external/data';\n  import {\n    getExternalFolderLabel,\n    listedExternalAssets,\n    listedExternalSubfolders,\n  } from '$lib/services/assets/external/view';\n  import { getTakenNames } from '$lib/services/assets/subfolders';\n\n  /**\n   * @import { MediaLibraryService } from '$lib/types/private';\n   */\n\n  /** The component is only rendered while a service is selected. */\n  const service = $derived(/** @type {MediaLibraryService} */ (selectedCloudService.current));\n  /** Names already taken in the folder being browsed, which a new folder can’t be given. */\n  const takenNames = $derived(\n    getTakenNames({\n      subfolders: listedExternalSubfolders.current,\n      fileNames: listedExternalAssets.current.map(({ fileName }) => fileName),\n    }),\n  );\n  /** The folder being browsed, named after the service at the root. */\n  const folderLabel = $derived(\n    getExternalFolderLabel({\n      dirPath: selectedExternalDirPath.current,\n      serviceLabel: service.serviceLabel,\n    }),\n  );\n</script>\n\n<SubfolderNameDialog\n  bind:open={showNewExternalFolderDialog.current}\n  title={_('new_folder')}\n  okLabel={_('new_folder_create')}\n  description={_('new_folder_description', { values: { folder: folderLabel } })}\n  {takenNames}\n  onSubmit={(name) => {\n    createExternalFolder(name);\n  }}\n/>\n","<!--\n  @component\n  New Folder button for a cloud storage service, which opens the New Folder dialog. Only rendered\n  when the service can create a folder.\n-->\n<script>\n  import NewFolderButton from '$lib/components/assets/list/new-folder-button.svelte';\n  import { selectedCloudService, showNewExternalFolderDialog } from '$lib/services/assets/external';\n  import { browsingExternalFolders } from '$lib/services/assets/external/view';\n</script>\n\n{#if browsingExternalFolders.current && selectedCloudService.current?.createFolder}\n  <NewFolderButton\n    onclick={() => {\n      showNewExternalFolderDialog.current = true;\n    }}\n  />\n{/if}\n","<!--\n  @component\n  Preview button that opens the asset details overlay, shared by repository assets and assets on\n  external locations.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button } from '@sveltia/ui';\n\n  import { goto } from '$lib/services/app/navigation';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [path] Path of the details overlay, or `undefined` if no asset is selected.\n   * @property {boolean} [disabled] Whether the asset can’t be previewed.\n   * @property {Record<string, any>} [state] History state to navigate with.\n   */\n\n  /** @type {Props} */\n  let { path = undefined, disabled = false, state = undefined } = $props();\n</script>\n\n<Button\n  variant=\"ghost\"\n  disabled={disabled || !path}\n  label={_('preview')}\n  aria-label={_('show_preview')}\n  onclick={() => {\n    goto(/** @type {string} */ (path), { transitionType: 'forwards', state });\n  }}\n/>\n","<!--\n  @component\n  Primary toolbar of the Asset Library, shared by repository folders and external locations: back\n  button on small screens, location title with an optional breadcrumb, action buttons on larger\n  screens and the floating Upload button.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { FloatingActionButtonWrapper, Toolbar } from '@sveltia/ui';\n\n  import Breadcrumb from '$lib/components/common/breadcrumb.svelte';\n  import BackButton from '$lib/components/common/page-toolbar/back-button.svelte';\n  import { goBack } from '$lib/services/app/navigation';\n  import { getFolderBreadcrumbItems } from '$lib/services/assets/subfolders';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} rootLabel Label of the location: the asset folder or the cloud storage\n   * service.\n   * @property {string[]} [subfolderNames] Names of the subfolders leading to the one being browsed,\n   * from the location root down. Empty at the root.\n   * @property {(depth: number, back: boolean) => void} onBrowse Called to browse an ancestor of\n   * the subfolder being browsed, with how many subfolder names to keep, `0` being the root, and\n   * whether the ancestor is the previous page, as it is for the back button on small screens.\n   * @property {Snippet} [actions] Action buttons, shown on large screens only.\n   * @property {Snippet} [fab] Upload button placed in the floating action button wrapper.\n   */\n\n  /** @type {Props} */\n  let { rootLabel, subfolderNames = [], onBrowse, actions = undefined, fab = undefined } = $props();\n\n  /** The subfolder being browsed is the title; at the root, the location itself is. */\n  const title = $derived(subfolderNames.at(-1) ?? rootLabel);\n  /** Trail of the subfolder being browsed, each ancestor leading back to itself. */\n  const breadcrumbs = $derived(\n    getFolderBreadcrumbItems({\n      rootLabel,\n      subfolderNames,\n      /**\n       * Browse the ancestor selected in the breadcrumb.\n       * @param {{ depth: number }} ancestor Ancestor.\n       */\n      onBrowse: ({ depth }) => {\n        onBrowse(depth, false);\n      },\n    }),\n  );\n</script>\n\n<Toolbar variant=\"primary\" class=\"asset-library-toolbar\" ariaLabel={_('folder')}>\n  {#if env.isSmallScreen}\n    <BackButton\n      aria-label={_(subfolderNames.length ? 'back_to_parent_folder' : 'back_to_asset_folder_list')}\n      onclick={() => {\n        if (subfolderNames.length) {\n          onBrowse(subfolderNames.length - 1, true);\n        } else {\n          goBack('/assets');\n        }\n      }}\n    />\n  {/if}\n  <h2 role=\"none\">\n    {#if !env.isSmallScreen && breadcrumbs.length}\n      <Breadcrumb items={breadcrumbs} />\n    {:else}\n      <bdi>{title}</bdi>\n    {/if}\n  </h2>\n  {#if !(env.isSmallScreen || env.isMediumScreen)}\n    {@render actions?.()}\n  {/if}\n  <FloatingActionButtonWrapper>\n    {@render fab?.()}\n  </FloatingActionButtonWrapper>\n</Toolbar>\n\n<style>\n  /* Two floating buttons — New Folder and Upload — sit side by side on a small screen */\n  :global(.asset-library-toolbar .floating-action-button-wrapper) {\n    @media (width < 768px) {\n      display: flex;\n      gap: 12px;\n    }\n  }\n\n  h2 {\n    /* A long name is cut short rather than wrapped, so the toolbar stays one line tall */\n    & > bdi {\n      overflow: hidden;\n      min-width: 0;\n      white-space: nowrap;\n      text-overflow: ellipsis;\n    }\n\n    :global {\n      /* An ancestor folder in the breadcrumb reads as part of the heading, only dimmed to tell it\n      from the current folder. The class is repeated to make the selectors specific enough to exempt\n      the labels and the separators from the small type the toolbar gives any `<span>` in the\n      heading, which is a rule with a scoping class of its own */\n\n      .breadcrumb.breadcrumb.breadcrumb {\n        /* Take the whole heading, so the trail is measured against the room it can actually use */\n        flex: auto;\n        font-size: inherit;\n\n        .sui.button.crumb .label,\n        .sui.icon.separator,\n        span.current {\n          font-size: inherit;\n          opacity: 1;\n        }\n\n        .sui.button.crumb .label {\n          font-weight: var(--sui-font-weight-normal, normal);\n        }\n\n        span.current {\n          font-weight: inherit;\n        }\n      }\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import DeleteAssetsButton from '$lib/components/assets/list/delete-assets-button.svelte';\n  import DownloadAssetsButton from '$lib/components/assets/list/download-assets-button.svelte';\n  import CopyAssetsButton from '$lib/components/assets/list/external/copy-assets-button.svelte';\n  import EditOptionsButton from '$lib/components/assets/list/external/edit-options-button.svelte';\n  import NewFolderButton from '$lib/components/assets/list/external/new-folder-button.svelte';\n  import UploadAssetsButton from '$lib/components/assets/list/external/upload-assets-button.svelte';\n  import PreviewAssetButton from '$lib/components/assets/list/preview-asset-button.svelte';\n  import PrimaryToolbar from '$lib/components/assets/list/primary-toolbar.svelte';\n  import {\n    browseExternalFolder,\n    canPreviewExternalAsset,\n    externalAssets,\n    focusedExternalAsset,\n    getExternalAssetPath,\n    selectedCloudService,\n    selectedExternalDirPath,\n    selectedOrFocusedExternalAssets,\n  } from '$lib/services/assets/external';\n  import { deleteExternalAssets, fetchExternalAssetBlob } from '$lib/services/assets/external/data';\n  import {\n    browsingExternalFolders,\n    listedExternalAssets,\n  } from '$lib/services/assets/external/view';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { MediaLibraryService } from '$lib/types/private';\n   */\n\n  /** The component is only rendered while a service is selected. */\n  const service = $derived(/** @type {MediaLibraryService} */ (selectedCloudService.current));\n  const asset = $derived(focusedExternalAsset.current);\n  /**\n   * Names of the folders leading to the one being browsed, from the service root down. A search\n   * looks through the whole service, so the trail is left out while one is under way.\n   */\n  const subfolderNames = $derived(\n    browsingExternalFolders.current && selectedExternalDirPath.current\n      ? selectedExternalDirPath.current.split('/')\n      : [],\n  );\n  const assets = $derived(selectedOrFocusedExternalAssets.current);\n</script>\n\n<PrimaryToolbar\n  rootLabel={service.serviceLabel}\n  {subfolderNames}\n  onBrowse={(depth) => {\n    browseExternalFolder(subfolderNames.slice(0, depth).join('/'));\n  }}\n>\n  {#snippet actions()}\n    <PreviewAssetButton\n      path={asset ? getExternalAssetPath(service, asset) : undefined}\n      disabled={!asset || !canPreviewExternalAsset(asset)}\n    />\n    <CopyAssetsButton assets={asset ? [asset] : []} />\n    <DownloadAssetsButton {assets} getName={(a) => a.fileName} getBlob={fetchExternalAssetBlob} />\n    <!-- The controls for operations the service doesn’t support are hidden rather than disabled -->\n    {#if service.delete}\n      <DeleteAssetsButton\n        {assets}\n        deleteAssets={deleteExternalAssets}\n        listedCount={listedExternalAssets.current.length}\n      />\n    {/if}\n    {#if service.rename || service.replace || service.delete}\n      <EditOptionsButton {asset} {assets} />\n    {/if}\n  {/snippet}\n  {#snippet fab()}\n    <NewFolderButton />\n    {#if service.upload && (!env.isSmallScreen || externalAssets.current?.length)}\n      <UploadAssetsButton label={env.isSmallScreen ? undefined : _('upload')} />\n    {/if}\n  {/snippet}\n</PrimaryToolbar>\n","<!--\n  @component\n  Rename Asset dialog, shared by repository assets and assets on external locations. It validates\n  the new name against the sibling names, narrows the initial selection to the name without the\n  extension, and asks for confirmation when the extension changes. The caller performs the actual\n  rename.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { getPathInfo } from '@sveltia/utils/file';\n  import { tick } from 'svelte';\n\n  import NameInputDialog from '$lib/components/assets/list/name-input-dialog.svelte';\n  import FileExtensionChangeDialog from '$lib/components/assets/shared/file-extension-change-dialog.svelte';\n  import { formatFileName, validateAssetName } from '$lib/services/assets/file-name';\n  import { showAssetOverlay } from '$lib/services/assets/view';\n  import { isEquivalentFileExtension } from '$lib/services/utils/file';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} open Whether the dialog is open.\n   * @property {string} name Current file name.\n   * @property {string[]} otherNames Names of the other files in the same folder, which the new name\n   * must not duplicate.\n   * @property {string[]} [folderNames] Names of the subfolders in the same folder, which the new\n   * name must not duplicate either.\n   * @property {string[]} [fileNames] Names of the files in the same folder that aren’t assets, like\n   * entry files, which the new name must not duplicate either.\n   * @property {number} [usedEntryCount] Number of entries using the asset, mentioned in the dialog\n   * body because they will be updated as well.\n   * @property {string} [blockedMessage] Why the asset can’t be renamed, e.g. because a read-only\n   * entry uses it. The message is shown in place of the input, and the Rename button is disabled.\n   * @property {boolean} [slugificationEnabled] Whether the new name is slugified, according to the\n   * `slugify_filename` media library option, as an uploaded file’s name is. The resulting name is\n   * shown below the input when it differs from the entered one.\n   * @property {(newName: string) => void} onRename Called with the new name once confirmed.\n   * @property {() => void} [onClose] Called when the dialog is closed for good, as opposed to\n   * while the extension change confirmation is shown.\n   */\n\n  /** @type {Props} */\n  let {\n    open = $bindable(false),\n    name,\n    otherNames,\n    folderNames = [],\n    fileNames = [],\n    usedEntryCount = 0,\n    blockedMessage = undefined,\n    slugificationEnabled = false,\n    onRename,\n    onClose = undefined,\n  } = $props();\n\n  const title = $derived(_('rename_x', { values: { name } }));\n\n  let confirmationOpen = $state(false);\n  /** @type {HTMLInputElement | undefined} */\n  let inputElement = $state();\n  /** Whether to keep the entered name when the dialog is reopened from the confirmation dialog. */\n  let keepName = false;\n  let newName = $state('');\n\n  const { extension: oldExtension } = $derived(getPathInfo(name));\n  const trimmedName = $derived(newName.trim());\n  /**\n   * Name the file will be renamed to, which may be different from the entered name: sanitized like\n   * an uploaded file’s name, and slugified if enabled.\n   */\n  const finalName = $derived(\n    trimmedName ? formatFileName(trimmedName, { slugificationEnabled }) : '',\n  );\n  const newExtension = $derived(getPathInfo(finalName).extension);\n  /** Whether the file extension is being changed in a way that requires confirmation. */\n  const extensionChanged = $derived(!isEquivalentFileExtension(oldExtension, newExtension));\n\n  const error = $derived(\n    validateAssetName({\n      name: trimmedName,\n      fileName: finalName,\n      otherNames,\n      folderNames,\n      fileNames,\n    }),\n  );\n\n  const invalid = $derived(!!error);\n\n  /**\n   * Focus the input field, and select the file name, excluding the extension, just like the macOS\n   * Finder and Windows File Explorer do. This is done once, as soon as the dialog is shown, rather\n   * than in response to a `select` event, which arrives later: the selection would then be narrowed\n   * after the user had already selected the whole name and started typing over it.\n   */\n  const selectFileName = async () => {\n    // Wait for the dialog to become interactive\n    await tick();\n\n    /* v8 ignore next 3 -- the input is rendered along with the dialog */\n    if (!inputElement) {\n      return;\n    }\n\n    inputElement.focus();\n    inputElement.setSelectionRange(0, getPathInfo(inputElement.value).filename.length);\n  };\n\n  // Reset the input whenever the dialog is opened, unless we’re coming back from the confirmation\n  $effect(() => {\n    if (open) {\n      if (!keepName) {\n        newName = name;\n      }\n\n      keepName = false;\n    }\n  });\n\n  // Close the dialog along with the asset details overlay\n  $effect(() => {\n    if (!showAssetOverlay.current) {\n      open = false;\n      confirmationOpen = false;\n      onClose?.();\n    }\n  });\n</script>\n\n<NameInputDialog\n  {title}\n  bind:open\n  okLabel={_('rename')}\n  okDisabled={!!blockedMessage || finalName === name || invalid}\n  onOk={() => {\n    if (extensionChanged) {\n      // Ask for confirmation before renaming\n      confirmationOpen = true;\n    } else {\n      onRename(finalName);\n    }\n  }}\n  onClose={() => {\n    if (!confirmationOpen) {\n      onClose?.();\n    }\n  }}\n  onOpen={() => {\n    selectFileName();\n  }}\n  description={_('enter_new_name_for_asset', { values: { count: usedEntryCount } })}\n  {blockedMessage}\n  bind:value={newName}\n  bind:element={inputElement}\n  ariaLabel={title}\n  note={!invalid && finalName !== trimmedName\n    ? _('file_will_be_saved_as', { values: { name: finalName } })\n    : undefined}\n  error={invalid ? _(`enter_new_name_for_asset_error.${error}`) : undefined}\n/>\n\n<FileExtensionChangeDialog\n  bind:open={confirmationOpen}\n  {oldExtension}\n  {newExtension}\n  okLabel={_('rename')}\n  onOk={() => {\n    onRename(finalName);\n    onClose?.();\n  }}\n  onCancel={() => {\n    // Go back to the rename dialog, keeping the entered name\n    keepName = true;\n    open = true;\n  }}\n/>\n","import { watchAsync } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Entry } from '$lib/types/private';\n */\n\n/**\n * Keep track of the entries using some files, for a dialog that tells how many entries a change\n * will update, or refuses the change because one of them can’t be updated. The entries are looked\n * up again whenever the files change, and are `undefined` until found, so a dialog can wait for\n * them before it opens; a slow lookup for files picked earlier never overwrites the entries of the\n * ones picked now. Call it while a component is being initialized.\n * @param {() => Promise<Entry[]> | undefined} find Function looking up the entries using the\n * current files, or returning `undefined` while there are none.\n * @param {(entries: Entry[]) => void} [onFound] Function called once the entries have been found.\n * @returns {{ readonly entries: Entry[] | undefined }} Entries, or `undefined` while being looked\n * up or without files.\n */\nexport const createUsedEntriesState = (find, onFound) => {\n  /** @type {Entry[] | undefined} */\n  let entries = $state.raw();\n\n  watchAsync(\n    () => {\n      entries = undefined;\n\n      return find();\n    },\n    (result) => {\n      entries = result;\n      onFound?.(result);\n    },\n  );\n\n  return {\n    /**\n     * Get the entries.\n     * @returns {Entry[] | undefined} Entries, or `undefined` while being looked up.\n     */\n    get entries() {\n      return entries;\n    },\n  };\n};\n","<!--\n  @component\n  Rename Asset dialog for an asset on a cloud storage service. As with repository assets, the\n  entries linking to the asset are pointed at its new URL, and the dialog opens once they have been\n  found, so it can tell how many will be updated, or refuse the rename if they can’t be. The new\n  name is checked against the other assets in the same virtual folder on the service.\n-->\n<script>\n  import { getPathInfo } from '@sveltia/utils/file';\n\n  import RenameDialog from '$lib/components/assets/list/rename-dialog.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import {\n    externalAssets,\n    getExternalAssetPath,\n    overlaidExternalAssetId,\n    renamingExternalAsset,\n    selectedCloudService,\n  } from '$lib/services/assets/external';\n  import { renameExternalAsset } from '$lib/services/assets/external/data';\n  import { getExternalAssetUsedEntries } from '$lib/services/assets/external/details';\n  import { getExternalChangeBlockedMessage } from '$lib/services/assets/external/move';\n  import { createUsedEntriesState } from '$lib/services/assets/used-entries.svelte';\n\n  const asset = $derived(renamingExternalAsset.current);\n  /** Entries linking to the asset, which are updated along with the rename. */\n  const usedEntries = createUsedEntriesState(() =>\n    asset ? getExternalAssetUsedEntries(asset) : undefined,\n  );\n  // Open while there’s an asset to act on, once the entries using it have been found, so the rename\n  // can be refused up front. Closing the dialog writes `open` back, and the asset is let go of once\n  // the dialog has closed\n  let open = $derived(!!asset && !!usedEntries.entries);\n  /* v8 ignore start -- the dialog is only shown for a listed asset */\n  const { dirname } = $derived(getPathInfo(asset?.id ?? ''));\n  const listedAssets = $derived(externalAssets.current ?? []);\n  /* v8 ignore stop */\n  /** Names of the other assets in the same folder on the service. */\n  const otherNames = $derived(\n    listedAssets\n      .filter((a) => a.id !== asset?.id && getPathInfo(a.id).dirname === dirname)\n      .map((a) => a.fileName),\n  );\n\n  // The rename is refused up front if the entries can’t be updated\n  const blockedMessage = $derived(getExternalChangeBlockedMessage(usedEntries.entries ?? [], 1));\n\n  /**\n   * Rename the asset. Also, update the URL hash silently to reflect the new asset ID if the rename\n   * dialog was opened in the asset details view.\n   * @param {string} newName New file name.\n   */\n  const renameAsset = async (newName) => {\n    const service = selectedCloudService.current;\n\n    /* v8 ignore next 3 -- the dialog is only shown for an asset on the selected service */\n    if (!asset || !service) {\n      return;\n    }\n\n    const oldId = asset.id;\n    const renamedAsset = await renameExternalAsset(asset, newName);\n\n    if (renamedAsset && overlaidExternalAssetId.current === oldId) {\n      overlaidExternalAssetId.current = renamedAsset.id;\n      await goto(getExternalAssetPath(service, renamedAsset), {\n        replaceState: true,\n        notifyChange: false,\n      });\n    }\n  };\n</script>\n\n<RenameDialog\n  bind:open\n  name={asset?.fileName ?? ''}\n  {otherNames}\n  usedEntryCount={usedEntries.entries?.length}\n  {blockedMessage}\n  onRename={renameAsset}\n  onClose={() => {\n    renamingExternalAsset.current = undefined;\n  }}\n/>\n","<!--\n  @component\n  Rename Folder dialog for a cloud storage service, opened for the subfolder set as\n  `renamingExternalSubfolder`. Renaming moves every file in the folder along, one by one, and\n  points the entries linking to them at their new URLs. The dialog opens once those entries have\n  been found, so it can refuse the rename if they can’t be updated.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import SubfolderNameDialog from '$lib/components/assets/list/subfolder-name-dialog.svelte';\n  import { renamingExternalSubfolder } from '$lib/services/assets/external';\n  import {\n    getExternalSubfolderAssets,\n    renameExternalFolder,\n  } from '$lib/services/assets/external/data';\n  import { getExternalAssetsUsedEntries } from '$lib/services/assets/external/details';\n  import { getExternalChangeBlockedMessage } from '$lib/services/assets/external/move';\n  import {\n    listedExternalAssets,\n    listedExternalSubfolders,\n  } from '$lib/services/assets/external/view';\n  import { getTakenNames } from '$lib/services/assets/subfolders';\n  import { createUsedEntriesState } from '$lib/services/assets/used-entries.svelte';\n\n  const subfolder = $derived(renamingExternalSubfolder.current);\n  /* v8 ignore start -- these are only read while the dialog is open, which takes a folder */\n  const currentName = $derived(subfolder?.name ?? '');\n  /** Assets in the folder, at any depth, which will be moved along. */\n  const assets = $derived(subfolder ? getExternalSubfolderAssets(subfolder.path) : []);\n  /* v8 ignore stop */\n  /** Entries linking to the assets, which are updated along with the rename. */\n  const usedEntries = createUsedEntriesState(() =>\n    subfolder ? getExternalAssetsUsedEntries(assets) : undefined,\n  );\n  // The rename is refused up front if the entries can’t be updated\n  const blockedMessage = $derived(\n    getExternalChangeBlockedMessage(usedEntries.entries ?? [], assets.length),\n  );\n  // Open while there’s a folder to act on, once the entries using its files have been found, so the\n  // rename can be refused up front. Closing the dialog writes `open` back, and the folder is let go\n  // of once the dialog has closed\n  let open = $derived(!!subfolder && !!usedEntries.entries);\n\n  /** Names taken by the siblings of the folder, which it can’t take over. */\n  const takenNames = $derived(\n    getTakenNames({\n      subfolders: listedExternalSubfolders.current,\n      fileNames: listedExternalAssets.current.map(({ fileName }) => fileName),\n      exclude: currentName,\n    }),\n  );\n</script>\n\n<SubfolderNameDialog\n  bind:open\n  title={_('rename_x', { values: { name: currentName } })}\n  okLabel={_('rename')}\n  description={_('enter_new_name_for_folder', { values: { count: assets.length } })}\n  {blockedMessage}\n  name={currentName}\n  {takenNames}\n  onSubmit={(name) => {\n    /* v8 ignore next 3 -- the dialog is only open for a folder */\n    if (subfolder) {\n      renameExternalFolder(subfolder, name);\n    }\n  }}\n  onClose={() => {\n    // The dialog is closed before the name is submitted, so the folder is let go of here rather\n    // than when `open` turns false\n    renamingExternalSubfolder.current = undefined;\n  }}\n/>\n","<!--\n  @component\n  Info pane of the Asset Library, shown on large screens when enabled in the view settings. The\n  content is an info panel for the focused asset, given as children.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState, Group } from '@sveltia/ui';\n\n  import { currentView } from '$lib/services/assets/view/settings';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { Asset, ExternalAsset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Asset | ExternalAsset | undefined} asset Focused asset. The fallback, or an empty\n   * state, is shown when there is none.\n   * @property {Snippet<[any]>} children Info panel, given the focused asset.\n   * @property {Snippet} [fallback] What to show while no asset is focused, e.g. the info of the\n   * folder being browsed.\n   */\n\n  /** @type {Props} */\n  let { asset, children, fallback = undefined } = $props();\n</script>\n\n{#if env.isLargeScreen && currentView.current.showInfo}\n  <Group id=\"asset-info\" class=\"secondary-sidebar\" ariaLabel={_('asset_info')}>\n    {#if asset}\n      {@render children(asset)}\n    {:else if fallback}\n      {@render fallback()}\n    {:else}\n      <EmptyState>\n        <span role=\"none\">{_('select_asset_show_info')}</span>\n      </EmptyState>\n    {/if}\n  </Group>\n{/if}\n","<!--\n  @component\n  Radio menu items of the Filter and Group menus: a None item and one item for each condition. The\n  checked one is applied to the view, or cleared with the None item.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { MenuItemRadio } from '@sveltia/ui';\n\n  import { getConditionKey, getViewConditions } from '$lib/services/common/view';\n\n  /**\n   * @import { AssetListView, EntryListView } from '$lib/types/private';\n   * @import { ViewFilter, ViewGroup } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {{ current: EntryListView | AssetListView }} currentView Current view details.\n   * @property {'filter' | 'group'} viewKey View property holding the selected conditions.\n   * @property {undefined | null} noneValue Value the view property is set to by the None item.\n   * @property {string} [noneLabel] Label to be displayed on the None item.\n   * @property {(ViewFilter | ViewGroup)[]} [options] Filter or group options.\n   */\n\n  /** @type {Props} */\n  let { currentView, viewKey, noneValue, noneLabel = '', options = [] } = $props();\n\n  const selected = $derived(currentView.current[viewKey]);\n</script>\n\n<MenuItemRadio\n  label={noneLabel || _('sort_keys.none')}\n  checked={!selected}\n  onSelect={() => {\n    currentView.current = { ...currentView.current, [viewKey]: noneValue };\n  }}\n/>\n{#each options as option (getConditionKey(getViewConditions(option)))}\n  {@const conditions = getViewConditions(option)}\n  <MenuItemRadio\n    label={option.label}\n    checked={!!selected && getConditionKey(selected) === getConditionKey(conditions)}\n    onSelect={() => {\n      currentView.current = { ...currentView.current, [viewKey]: conditions };\n    }}\n  />\n{/each}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Menu, MenuButton, MenuItemCheckbox } from '@sveltia/ui';\n\n  import ConditionRadioItems from '$lib/components/common/page-toolbar/condition-radio-items.svelte';\n  import { getConditionKey, getViewConditions } from '$lib/services/common/view';\n\n  /**\n   * @import { AssetListView, EntryListView } from '$lib/types/private';\n   * @import { ViewFilter } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {{ current: EntryListView | AssetListView }} currentView Current view details.\n   * @property {string} aria-controls The `aria-controls` attribute for the menu.\n   * @property {string} [label] Menu button label.\n   * @property {boolean} [disabled] Whether to disable the button.\n   * @property {boolean} [multiple] Whether to allow selecting multiple filter conditions.\n   * @property {string} [noneLabel] Label to be displayed on the None item.\n   * @property {ViewFilter[]} [filters] Filter conditions.\n   */\n\n  /** @type {Props} */\n  let {\n    currentView,\n    'aria-controls': ariaControls,\n    label = '',\n    disabled = false,\n    multiple = false,\n    noneLabel = '',\n    filters = [],\n  } = $props();\n</script>\n\n<MenuButton variant=\"ghost\" label={label || _('filter')} {disabled} popupPosition=\"bottom-right\">\n  {#snippet popup()}\n    <Menu ariaLabel={_('filtering_options')} aria-controls={ariaControls}>\n      {#if multiple}\n        {#each filters as filter (getConditionKey(getViewConditions(filter)))}\n          {@const { label: _label } = filter}\n          {@const conditions = getViewConditions(filter)}\n          {@const key = getConditionKey(conditions)}\n          {@const index = (currentView.current.filters || []).findIndex(\n            (f) => getConditionKey(f) === key,\n          )}\n          <MenuItemCheckbox\n            label={_label}\n            checked={index > -1}\n            onChange={() => {\n              const view = currentView.current;\n              const updatedFilters = view.filters ? [...view.filters] : [];\n\n              if (index > -1) {\n                updatedFilters.splice(index, 1);\n              } else {\n                updatedFilters.push(conditions);\n              }\n\n              currentView.current = { ...view, filters: updatedFilters };\n            }}\n          />\n        {/each}\n      {:else}\n        <ConditionRadioItems\n          {currentView}\n          viewKey=\"filter\"\n          noneValue={undefined}\n          {noneLabel}\n          options={filters}\n        />\n      {/if}\n    </Menu>\n  {/snippet}\n</MenuButton>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Menu, MenuButton, MenuItem } from '@sveltia/ui';\n\n  import ConditionRadioItems from '$lib/components/common/page-toolbar/condition-radio-items.svelte';\n  import {\n    getCollapsibleGroupNames,\n    isCollapsedByDefault,\n    isGroupCollapsed,\n    setAllGroupsCollapsed,\n  } from '$lib/services/common/view';\n\n  /**\n   * @import { AssetListView, EntryListView } from '$lib/types/private';\n   * @import { ViewGroup } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {{ current: EntryListView | AssetListView }} currentView Current view details.\n   * @property {string} aria-controls The `aria-controls` attribute for the menu.\n   * @property {string} [label] Menu button label.\n   * @property {boolean} [disabled] Whether to disable the button.\n   * @property {string} [noneLabel] Label to be displayed on the None item.\n   * @property {ViewGroup[]} [groups] Group conditions.\n   * @property {string[]} [groupNames] Names of the groups currently in the list, which the Expand\n   * All and Collapse All items act on.\n   */\n\n  /** @type {Props} */\n  let {\n    currentView,\n    'aria-controls': ariaControls,\n    label = '',\n    disabled = false,\n    noneLabel = '',\n    groups = [],\n    groupNames = [],\n  } = $props();\n\n  const collapsibleGroupNames = $derived(getCollapsibleGroupNames(groupNames));\n  const collapsedByDefault = $derived(isCollapsedByDefault(groups, currentView.current.group));\n  const canExpandAll = $derived(\n    collapsibleGroupNames.some((name) =>\n      isGroupCollapsed(currentView.current, name, collapsedByDefault),\n    ),\n  );\n  const canCollapseAll = $derived(\n    collapsibleGroupNames.some(\n      (name) => !isGroupCollapsed(currentView.current, name, collapsedByDefault),\n    ),\n  );\n</script>\n\n<MenuButton variant=\"ghost\" label={label || _('group')} {disabled} popupPosition=\"bottom-right\">\n  {#snippet popup()}\n    <Menu ariaLabel={_('grouping_options')} aria-controls={ariaControls}>\n      <ConditionRadioItems\n        {currentView}\n        viewKey=\"group\"\n        noneValue={null}\n        {noneLabel}\n        options={groups}\n      />\n      <Divider />\n      <MenuItem\n        label={_('expand_all')}\n        disabled={!canExpandAll}\n        onclick={() => {\n          currentView.current = setAllGroupsCollapsed(\n            currentView.current,\n            collapsibleGroupNames,\n            false,\n            collapsedByDefault,\n          );\n        }}\n      />\n      <MenuItem\n        label={_('collapse_all')}\n        disabled={!canCollapseAll}\n        onclick={() => {\n          currentView.current = setAllGroupsCollapsed(\n            currentView.current,\n            collapsibleGroupNames,\n            true,\n            collapsedByDefault,\n          );\n        }}\n      />\n    </Menu>\n  {/snippet}\n</MenuButton>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Checkbox } from '@sveltia/ui';\n\n  /**\n   * @import { Asset, Entry, ExternalAsset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {Entry | Asset | ExternalAsset} Item\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Item[]} allItems All available items.\n   * @property {{ current: Item[] }} selectedItems Selected items.\n   */\n\n  /** @type {Props} */\n  let { allItems, selectedItems } = $props();\n\n  const totalCount = $derived(allItems.length);\n  const selectedCount = $derived(selectedItems.current.length);\n  const anySelected = $derived(!!selectedCount);\n  const allSelected = $derived(anySelected && selectedCount === totalCount);\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <Checkbox\n    disabled={!totalCount}\n    ariaLabel={_('select_all')}\n    checked={anySelected && !allSelected ? 'mixed' : anySelected}\n    onChange={() => {\n      selectedItems.current = allSelected ? [] : [...allItems];\n    }}\n  />\n  {#if anySelected}\n    <span role=\"none\">\n      {_('x_of_x_selected', { values: { total: totalCount, selected: selectedCount } })}\n    </span>\n  {/if}\n</div>\n\n<style>\n  .wrapper {\n    display: flex;\n    align-items: center;\n    gap: 4px;\n    margin-inline: 20px;\n  }\n\n  span {\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Menu, MenuButton, MenuItemRadio } from '@sveltia/ui';\n\n  import { DATE_FIELDS, SORT_ORDERS } from '$lib/services/contents/collection/view/sort-keys';\n  import { SUMMARY_COLUMN_KEY } from '$lib/services/contents/collection/view/table-keys';\n  import { getField } from '$lib/services/contents/entry/fields';\n\n  /**\n   * @import { AssetListView, EntryListView, SortKey } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {{ current: EntryListView | AssetListView }} currentView Current view details.\n   * @property {string} aria-controls The `aria-controls` attribute for the menu.\n   * @property {string} [label] Menu button label.\n   * @property {boolean} [disabled] Whether to disable the button.\n   * @property {SortKey[]} [sortKeys] Sort keys to display in the menu.\n   * @property {string | undefined} [collectionName] Current collection name.\n   */\n\n  /** @type {Props} */\n  let {\n    currentView,\n    'aria-controls': ariaControls,\n    label = '',\n    disabled = false,\n    sortKeys = [],\n    collectionName = undefined,\n  } = $props();\n\n  /**\n   * Get the localized label for a sort order, worded for the type of the sorted value.\n   * @param {SortKey} sortKey Sort key.\n   * @param {string} order Sort order.\n   * @returns {string} Label.\n   */\n  const getOrderLabel = ({ key, label: _label, type }, order) => {\n    const isDate =\n      type === 'date' ||\n      DATE_FIELDS.includes(key) ||\n      (!!collectionName && getField({ collectionName, keyPath: key })?.widget === 'datetime');\n\n    const suffix = isDate ? '_date' : type === 'number' ? '_number' : '';\n\n    return _(`${order}${suffix}`, { values: { label: _label } });\n  };\n</script>\n\n<MenuButton variant=\"ghost\" label={label || _('sort')} {disabled} popupPosition=\"bottom-right\">\n  {#snippet popup()}\n    <Menu ariaLabel={_('sorting_options')} aria-controls={ariaControls}>\n      {#each sortKeys as sortKey (sortKey.key)}\n        {@const { key } = sortKey}\n        {#each SORT_ORDERS as order (order)}\n          <MenuItemRadio\n            label={getOrderLabel(sortKey, order)}\n            checked={currentView.current.sort?.key === key &&\n              currentView.current.sort.order === order}\n            onSelect={() => {\n              currentView.current = { ...currentView.current, sort: { key, order } };\n            }}\n          />\n        {/each}\n        {#if key === SUMMARY_COLUMN_KEY && sortKeys.length > 1}\n          <Divider />\n        {/if}\n      {/each}\n    </Menu>\n  {/snippet}\n</MenuButton>\n","<!--\n  @component\n  Secondary toolbar of the Asset Library, shared by repository folders and external locations: item\n  selector, optional search box, sort/filter/group menus, view switcher and Info pane toggle. The\n  view settings live in the shared `currentView`.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Divider, Icon, SearchBar, Spacer, Toolbar } from '@sveltia/ui';\n\n  import FilterMenu from '$lib/components/common/page-toolbar/filter-menu.svelte';\n  import GroupMenu from '$lib/components/common/page-toolbar/group-menu.svelte';\n  import ItemSelector from '$lib/components/common/page-toolbar/item-selector.svelte';\n  import SortMenu from '$lib/components/common/page-toolbar/sort-menu.svelte';\n  import ViewSwitcher from '$lib/components/common/page-toolbar/view-switcher.svelte';\n  import { ASSET_KINDS } from '$lib/services/assets/kinds';\n  import { currentView } from '$lib/services/assets/view/settings';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Asset, ExternalAsset, SortKey } from '$lib/types/private';\n   * @import { ViewGroup } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {(Asset | ExternalAsset)[]} allItems Listed items the item selector can select.\n   * @property {{ current: (Asset | ExternalAsset)[] }} selectedItems Selected items.\n   * @property {number} totalCount Number of assets in the location before any filter or search\n   * narrows them down, so that the menus stay enabled and the filter can be reset.\n   * @property {SortKey[]} sortKeys Sort keys shown in the Sort menu.\n   * @property {ViewGroup[]} [groups] Grouping options shown in the Group menu. The menu is omitted\n   * when there are none, as repository assets have nothing to group by.\n   * @property {string[]} [groupNames] Names of the groups currently in the list, which the Group\n   * menu’s Expand All and Collapse All items act on.\n   * @property {{ current: string }} [searchTerms] Search terms to bind a search box to. The box is\n   * omitted when this is not given, as repository assets are searched with the global search.\n   */\n\n  /** @type {Props} */\n  let {\n    allItems,\n    selectedItems,\n    totalCount,\n    sortKeys,\n    groups = [],\n    groupNames = [],\n    searchTerms = undefined,\n  } = $props();\n\n  const hasListedAssets = $derived(!!totalCount);\n  const hasMultipleAssets = $derived(totalCount > 1);\n</script>\n\n<Toolbar variant=\"secondary\" ariaLabel={_('asset_list')}>\n  {#if !(env.isSmallScreen || env.isMediumScreen)}\n    <ItemSelector {allItems} {selectedItems} />\n  {/if}\n  <Spacer flex />\n  {#if searchTerms}\n    <SearchBar\n      dir=\"auto\"\n      flex={env.isSmallScreen}\n      bind:value={searchTerms.current}\n      ariaLabel={_('assets_dialog.search_for_file')}\n      aria-controls=\"asset-list\"\n    />\n  {/if}\n  <SortMenu disabled={!hasMultipleAssets} {currentView} {sortKeys} aria-controls=\"asset-list\" />\n  <FilterMenu\n    label={_('type')}\n    disabled={!hasMultipleAssets}\n    {currentView}\n    noneLabel={_('all')}\n    filters={ASSET_KINDS.map((type) => ({ label: _(type), field: 'fileType', pattern: type }))}\n    aria-controls=\"asset-list\"\n  />\n  {#if groups.length}\n    <GroupMenu\n      disabled={!hasMultipleAssets}\n      {currentView}\n      {groups}\n      {groupNames}\n      aria-controls=\"asset-list\"\n    />\n  {/if}\n  <ViewSwitcher disabled={!hasListedAssets} {currentView} aria-controls=\"asset-list\" />\n  {#if !(env.isSmallScreen || env.isMediumScreen)}\n    {@const label = _(currentView.current.showInfo ? 'hide_info' : 'show_info')}\n    <Divider orientation=\"vertical\" />\n    <Button\n      variant=\"ghost\"\n      iconic\n      disabled={!hasListedAssets}\n      pressed={!!currentView.current.showInfo}\n      tooltip={label}\n      aria-label={label}\n      aria-controls={currentView.current.showInfo ? 'asset-info' : undefined}\n      aria-expanded={!!currentView.current.showInfo}\n      onclick={() => {\n        currentView.current = {\n          ...currentView.current,\n          showInfo: !currentView.current.showInfo,\n        };\n      }}\n    >\n      {#snippet startIcon()}\n        <Icon name=\"info\" />\n      {/snippet}\n    </Button>\n  {/if}\n</Toolbar>\n","<!--\n  @component\n  Main area of the Asset Library for a cloud storage service selected under External Locations. It\n  mirrors the layout used for repository folders — toolbars, list and Info pane — but works on the\n  assets fetched from the service’s API rather than the ones in the repository.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Infobar, Toast } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import AssetList from '$lib/components/assets/list/external/asset-list.svelte';\n  import DeleteFolderDialog from '$lib/components/assets/list/external/delete-folder-dialog.svelte';\n  import FolderInfoPanel from '$lib/components/assets/list/external/folder-info-panel.svelte';\n  import InfoPanel from '$lib/components/assets/list/external/info-panel.svelte';\n  import NewFolderDialog from '$lib/components/assets/list/external/new-folder-dialog.svelte';\n  import PrimaryToolbar from '$lib/components/assets/list/external/primary-toolbar.svelte';\n  import RenameDialog from '$lib/components/assets/list/external/rename-dialog.svelte';\n  import RenameFolderDialog from '$lib/components/assets/list/external/rename-folder-dialog.svelte';\n  import SecondarySidebar from '$lib/components/assets/list/secondary-sidebar.svelte';\n  import SecondaryToolbar from '$lib/components/assets/list/secondary-toolbar.svelte';\n  import RejectedFilesAlertDialog from '$lib/components/assets/shared/rejected-files-alert-dialog.svelte';\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import {\n    externalAssets,\n    externalAssetSearchTerms,\n    externalAssetsTruncated,\n    focusedExternalAsset,\n    hasFolderSupport,\n    selectedCloudService,\n    selectedExternalAssets,\n  } from '$lib/services/assets/external';\n  import {\n    externalAssetsToast,\n    getSharedMediaLibraryOptions,\n    uploadExternalAssets,\n    uploadingExternalAssets,\n  } from '$lib/services/assets/external/data';\n  import {\n    externalAssetGroups,\n    externalAssetSortKeys,\n    externalAssetViewGroups,\n    listedExternalAssets,\n  } from '$lib/services/assets/external/view';\n\n  /**\n   * @import { ExternalAsset, MediaLibraryService } from '$lib/types/private';\n   */\n\n  /** The component is only rendered while a service is selected. */\n  const service = $derived(/** @type {MediaLibraryService} */ (selectedCloudService.current));\n  /* v8 ignore start -- only read to report a file exceeding the configured size */\n  const maxSize = $derived(getSharedMediaLibraryOptions().max_file_size ?? Infinity);\n  /* v8 ignore stop */\n\n  /** @type {RejectedFilesAlertDialog | undefined} */\n  let rejectedFilesAlert = $state();\n\n  // Upload the files dropped on the list, picked with the Upload button or chosen to replace an\n  // existing asset\n  $effect(() => {\n    const { files, originalAsset } = uploadingExternalAssets.current;\n\n    if (!files.length) {\n      return;\n    }\n\n    untrack(async () => {\n      uploadingExternalAssets.current = { files: [] };\n\n      rejectedFilesAlert?.report(await uploadExternalAssets(files, { originalAsset }));\n    });\n  });\n</script>\n\n{#snippet folderInfo()}\n  <FolderInfoPanel />\n{/snippet}\n\n<PageContainerMainArea\n  id=\"assets-container\"\n  aria-label={_('x_asset_folder', { values: { folder: service.serviceLabel } })}\n>\n  {#snippet primaryToolbar()}\n    <PrimaryToolbar />\n  {/snippet}\n  {#snippet secondaryToolbar()}\n    {#if externalAssets.current?.length}\n      <!-- The menus stay enabled while a filter or search narrows the list, so it can be reset -->\n      <SecondaryToolbar\n        allItems={listedExternalAssets.current}\n        selectedItems={selectedExternalAssets}\n        totalCount={externalAssets.current.length}\n        sortKeys={externalAssetSortKeys.current}\n        groups={externalAssetViewGroups.current}\n        groupNames={Object.keys(externalAssetGroups.current)}\n        searchTerms={externalAssetSearchTerms}\n      />\n    {/if}\n  {/snippet}\n  {#snippet mainContent()}\n    {#if externalAssetsTruncated.current}\n      <!-- The service holds more files than are listed at once, so some of them are left out -->\n      <Infobar\n        status=\"warning\"\n        dismissible={false}\n        --sui-infobar-border-width=\"0 0 1px\"\n        --sui-infobar-message-justify-content=\"center\"\n      >\n        {_('external_assets_truncated')}\n      </Infobar>\n    {/if}\n    <AssetList />\n  {/snippet}\n  {#snippet secondarySidebar()}\n    <!-- A service without folders has nothing to describe in place of an asset -->\n    <SecondarySidebar\n      asset={focusedExternalAsset.current}\n      fallback={hasFolderSupport(service) && externalAssets.current ? folderInfo : undefined}\n    >\n      {#snippet children(/** @type {ExternalAsset} */ asset)}\n        <InfoPanel {asset} />\n      {/snippet}\n    </SecondarySidebar>\n  {/snippet}\n</PageContainerMainArea>\n\n<RenameDialog />\n{#if hasFolderSupport(service)}\n  <NewFolderDialog />\n  <RenameFolderDialog />\n  <DeleteFolderDialog />\n{/if}\n\n<Toast bind:show={externalAssetsToast.current.show}>\n  <Alert status={externalAssetsToast.current.status}>\n    {_(externalAssetsToast.current.message)}\n  </Alert>\n</Toast>\n\n<RejectedFilesAlertDialog bind:this={rejectedFilesAlert} {maxSize} />\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * What is being searched, or `null` while the search page is not shown.\n * @type {{ current: 'contents' | 'assets' | null }}\n */\nexport const searchMode = createRawState(null);\n\n/**\n * Current search terms.\n */\nexport const searchTerms = createRawState('');\n","import { searchMode, searchTerms } from '$lib/services/search';\n\nconst ROUTE_REGEX = /^\\/search\\/(?<terms>.+)$/;\n\n/**\n * Check if the given URL path is the search results page, without navigating to it.\n * @param {string} path URL path.\n * @returns {boolean} Result.\n */\nexport const isSearchResultsPath = (path) => ROUTE_REGEX.test(path);\n\n/**\n * Navigate to the search results page with the given path. The path should be in the format of\n * `/search/{terms}`.\n * @param {string} path Path to navigate to.\n * @returns {boolean} Whether the path is a search route.\n */\nexport const isSearchRoute = (path) => {\n  const { groups } = path.match(ROUTE_REGEX) ?? {};\n\n  if (!groups) {\n    // Not a search route\n    return false;\n  }\n\n  const { terms } = groups;\n\n  if (terms && terms !== searchTerms.current) {\n    searchTerms.current = terms;\n  }\n\n  if (!searchMode.current) {\n    searchMode.current = 'contents';\n  }\n\n  return true;\n};\n","import { _, locale as appLocale } from '@sveltia/i18n';\nimport { sleep } from '@sveltia/utils/misc';\nimport equal from 'fast-deep-equal';\n\nimport { announcedPageStatus, goto, parseLocation } from '$lib/services/app/navigation';\nimport {\n  enabledCloudServices,\n  EXTERNAL_LOCATION_PATH_PREFIX,\n  getCloudService,\n  getCloudServicePath,\n  overlaidExternalAssetId,\n  resetExternalAssets,\n  selectedCloudService,\n} from '$lib/services/assets/external';\nimport { linkedFilesService } from '$lib/services/assets/external/linked';\nimport { allAssetFolders, selectedAssetFolder } from '$lib/services/assets/folders';\nimport { allAssets, overlaidAsset } from '$lib/services/assets/state';\nimport { resolveAssetFolderPath, selectedSubfolderPath } from '$lib/services/assets/subfolders';\nimport {\n  getFolderLabelByCollection,\n  listedAssets,\n  showAssetOverlay,\n} from '$lib/services/assets/view';\nimport { gitConfigFiles } from '$lib/services/backends/git/shared/config';\nimport { isSearchRoute } from '$lib/services/search/navigation';\nimport { env } from '$lib/services/user/env.svelte';\nimport { createPath, getBaseName } from '$lib/services/utils/file';\nimport { encodePathSegments } from '$lib/services/utils/url';\n\n/**\n * @import { ViewTransitionType } from '$lib/services/app/navigation';\n * @import { Asset, AssetFolderInfo } from '$lib/types/private';\n */\n\n/**\n * What the Asset Library page shows for the current route.\n * @typedef {object} AssetsRouteState\n * @property {boolean} isIndexPage Whether the page shows the asset folder list only, on a small\n * screen.\n * @property {boolean} isSearchPage Whether the page shows the search results.\n * @property {boolean} notFound Whether the page shows the Not Found view, because the route\n * doesn’t address an asset folder or a cloud storage service.\n */\n\n/**\n * Regular expression matching the routes of the Asset Library page.\n */\nexport const ASSETS_ROUTE_REGEX =\n  /^\\/assets(?:\\/(?<folderPath>.+?)(?:\\/(?<fileName>[^/]+\\.[A-Za-z0-9]+))?)?$/;\n\n/**\n * Check if the given path is a known asset folder: a configured folder, or a subfolder holding an\n * asset or a Git config file such as `.gitkeep`.\n * @param {string} path Folder path.\n * @returns {boolean} Result.\n */\nconst isKnownFolderPath = (path) =>\n  allAssetFolders.current.some(({ internalPath }) => internalPath === path) ||\n  [...allAssets.current, ...gitConfigFiles.current].some((file) =>\n    file.path.startsWith(`${path}/`),\n  );\n\n/**\n * Counter to ignore an outdated navigation once a newer one has started.\n */\nlet navigationCount = 0;\n\n/**\n * Get the label of the selected asset folder. The label is only used for a repository folder, as a\n * cloud storage service has an area of its own. `appLocale.current` is read first, so a derived\n * state calling this is updated once the locale changes, because `getFolderLabelByCollection` can\n * return a localized label.\n * @returns {string} Label, or an empty string if no folder is selected.\n */\nexport const getSelectedAssetFolderLabel = () =>\n  appLocale.current && selectedAssetFolder.current\n    ? getFolderLabelByCollection(selectedAssetFolder.current)\n    : '';\n\n/**\n * Get the history state to navigate with within the Asset Library. The selected asset folder\n * travels as history state, the same way it does from the sidebar, so the page can tell it from\n * another folder sharing its path, and an asset opened from a folder that doesn’t contain it\n * directly, such as All Assets, is shown within that folder rather than its own.\n * @returns {{ folder: AssetFolderInfo | undefined }} History state.\n */\nexport const getAssetFolderHistoryState = () => ({ folder: selectedAssetFolder.current });\n\n/**\n * Update the URL silently once an asset has been renamed or moved, if it’s the asset shown in the\n * details view, so a reload or a copied link finds it at its new path. The folder the asset was\n * opened from, e.g. All Assets, is kept.\n * @param {string} oldPath Asset’s previous path.\n * @param {string} newPath Asset’s new path.\n */\nexport const replaceShownAssetPath = async (oldPath, newPath) => {\n  if (parseLocation().path === `/assets/${oldPath}`) {\n    await goto(encodePathSegments(`/assets/${newPath}`), {\n      replaceState: true,\n      notifyChange: false,\n      state: getAssetFolderHistoryState(),\n    });\n  }\n};\n\n/**\n * Leave the details view of an asset that has been moved to another storage location, e.g. from\n * the repository to a cloud storage service, where it has no details view at the same place. The\n * list it’s been moved out of is shown instead.\n * @param {string} shownPath Path of the asset’s details view, e.g. `/assets/static/uploads/a.png`.\n * @param {string} listPath Path of the list to show, e.g. `/assets/static/uploads`.\n */\nexport const leaveMovedAsset = async (shownPath, listPath) => {\n  if (parseLocation().path === shownPath) {\n    await goto(encodePathSegments(listPath), { replaceState: true, transitionType: 'backwards' });\n  }\n};\n\n/**\n * Show the details of a repository asset in the overlay, within the selected asset folder.\n * @param {Asset} asset Asset.\n * @param {object} [options] Options.\n * @param {ViewTransitionType} [options.transitionType] View transition type.\n * @param {boolean} [options.replaceState] Whether to replace the current history entry.\n */\nexport const showAssetDetails = (\n  { path },\n  { transitionType = 'forwards', replaceState = false } = {},\n) => {\n  goto(encodePathSegments(`/assets/${path}`), {\n    transitionType,\n    replaceState,\n    state: getAssetFolderHistoryState(),\n  });\n};\n\n/**\n * Discard the navigation still in flight, if any, so its delayed announcement is not made. Call\n * this when the Asset Library page is unmounted.\n */\nexport const discardAssetsNavigation = () => {\n  navigationCount += 1;\n};\n\n/**\n * Select a cloud storage service listed under External Locations, whose assets are shown in place\n * of a repository folder, and optionally show the details of an asset on the service.\n * @param {AssetsRouteState} state Initial page state.\n * @param {string} serviceId Service ID.\n * @param {string} assetId ID of the asset to be shown in the details overlay, or an empty string.\n * @returns {AssetsRouteState} What the page shows.\n */\nconst selectCloudService = (state, serviceId, assetId) => {\n  const service = getCloudService(serviceId);\n\n  selectedAssetFolder.current = undefined;\n\n  if (!service) {\n    selectedCloudService.current = undefined;\n    showAssetOverlay.current = false;\n    announcedPageStatus.current = _('asset_folder_not_found');\n\n    return { ...state, notFound: true };\n  }\n\n  if (selectedCloudService.current !== service) {\n    resetExternalAssets();\n    selectedCloudService.current = service;\n  }\n\n  if (assetId) {\n    overlaidExternalAssetId.current = assetId;\n    showAssetOverlay.current = true;\n    announcedPageStatus.current = _('viewing_x_asset_details', {\n      values: { name: getBaseName(assetId) },\n    });\n  } else {\n    overlaidExternalAssetId.current = undefined;\n    showAssetOverlay.current = false;\n    announcedPageStatus.current = _('viewing_x_external_location', {\n      values: { service: service.serviceLabel },\n    });\n  }\n\n  return state;\n};\n\n/**\n * Resolve the index route, `/assets`, which has no folder path.\n * @param {AssetsRouteState} state Initial page state.\n * @returns {AssetsRouteState} What the page shows.\n */\nconst resolveIndexRoute = (state) => {\n  if (env.isSmallScreen) {\n    // Show the asset folder list only\n    selectedAssetFolder.current = undefined;\n    showAssetOverlay.current = false;\n    announcedPageStatus.current = _('viewing_asset_folder_list');\n\n    return { ...state, isIndexPage: true };\n  }\n\n  if (allAssetFolders.current.length) {\n    // Select All Assets right away, because the redirect below takes effect asynchronously in a\n    // view transition, and the folder info panel would be rendered with no folder until then\n    selectedAssetFolder.current = /** @type {{ folder: AssetFolderInfo }} */ (\n      resolveAssetFolderPath('-/all')\n    ).folder;\n    selectedSubfolderPath.current = '';\n    // Redirect to All Assets, replacing the index route in the history, so the browser’s Back\n    // button doesn’t come back here only to be redirected again\n    goto('/assets/-/all', { replaceState: true });\n  } else {\n    // No asset folder is configured, so redirect to the first external location, or to the files\n    // linked from entries if there is none either\n    goto(getCloudServicePath(enabledCloudServices.current[0] ?? linkedFilesService), {\n      replaceState: true,\n    });\n  }\n\n  return state;\n};\n\n/**\n * Announce the selected asset folder after a moment, unless the user has moved on in the\n * meantime.\n * @param {number} currentCount Value of the navigation counter when the folder was selected.\n */\nconst announceAssetFolder = async (currentCount) => {\n  // Wait for the folder label and the listed assets to be updated\n  await sleep(100);\n\n  if (currentCount !== navigationCount) {\n    // The user has moved on in the meantime, and the newer navigation has taken over\n    return;\n  }\n\n  showAssetOverlay.current = false;\n  announcedPageStatus.current = _('viewing_x_asset_folder', {\n    values: {\n      folder: getSelectedAssetFolderLabel(),\n      count: listedAssets.current.length,\n    },\n  });\n};\n\n/**\n * Resolve the current URL hash to what the Asset Library page shows: the asset folder list, a\n * folder’s assets, an asset’s details, a cloud storage service, or the search results. The stores\n * that the page and its parts read are updated along the way. When a folder is selected, it’s\n * announced after a moment, unless another navigation has started or\n * {@link discardAssetsNavigation} has been called in the meantime.\n * @returns {AssetsRouteState} What the page shows.\n */\nexport const resolveAssetsRoute = () => {\n  const { path } = parseLocation();\n  const match = path.match(ASSETS_ROUTE_REGEX);\n  /** @type {AssetsRouteState} */\n  const state = { isIndexPage: false, isSearchPage: false, notFound: false };\n\n  navigationCount += 1;\n\n  const currentCount = navigationCount;\n\n  if (!match?.groups) {\n    showAssetOverlay.current = false;\n\n    // Check if it’s the search page, which has a different URL pattern (`#/search/{query}`)\n    return { ...state, isSearchPage: isSearchRoute(path) }; // Different page\n  }\n\n  /** @type {{ folderPath?: string, fileName?: string }} */\n  let { folderPath, fileName } = match.groups;\n\n  if (\n    folderPath?.startsWith(EXTERNAL_LOCATION_PATH_PREFIX) &&\n    folderPath !== `${EXTERNAL_LOCATION_PATH_PREFIX}all`\n  ) {\n    // The path is `-/{serviceId}` for the asset list, or `-/{serviceId}/{assetId}` for the asset\n    // details. An asset ID can contain slashes, and it doesn’t have to end with a file extension,\n    // so the ID is everything after the service ID, whether the regex has split it or not\n    const [serviceId, ...rest] = folderPath.slice(EXTERNAL_LOCATION_PATH_PREFIX.length).split('/');\n\n    // Only drop a missing file name: an empty segment is significant, as in `https://`\n    return selectCloudService(\n      state,\n      serviceId,\n      [...rest, ...(fileName ? [fileName] : [])].join('/'),\n    );\n  }\n\n  selectedCloudService.current = undefined;\n\n  if (!folderPath) {\n    return resolveIndexRoute(state);\n  }\n\n  // The regex takes a last path segment with a dot for a file name, but a file doesn’t have to have\n  // an extension, e.g. `LICENSE`. Show the asset if there is one at the path. A path without a\n  // parent folder is taken whole as a folder path, e.g. `photo.jpg`, so it also points at an asset\n  // in a root media folder, if one is configured\n  if (!fileName && allAssets.current.some((asset) => asset.path === folderPath)) {\n    const index = folderPath.lastIndexOf('/');\n\n    if (index > -1 || allAssetFolders.current.some(({ internalPath }) => internalPath === '')) {\n      fileName = folderPath.slice(index + 1);\n      folderPath = folderPath.slice(0, Math.max(index, 0));\n    }\n  }\n\n  // Conversely, a folder can have a dot in its name too, e.g. `v1.2`. Browse the folder if there is\n  // no asset at the path\n  if (fileName) {\n    const fullPath = createPath([folderPath, fileName]);\n\n    if (\n      !allAssets.current.some((asset) => asset.path === fullPath) &&\n      isKnownFolderPath(fullPath)\n    ) {\n      folderPath = fullPath;\n      fileName = undefined;\n    }\n  }\n\n  // The path can also point at a subfolder of a configured folder. An internal path can be shared\n  // by multiple collections, files and fields, so the folder passed as history state takes\n  // precedence over the lookup by path\n  const { folder, subfolderPath = '' } =\n    resolveAssetFolderPath(folderPath, window.history.state?.folder) ?? {};\n\n  if (!folder && !fileName) {\n    selectedAssetFolder.current = undefined;\n    selectedSubfolderPath.current = '';\n    showAssetOverlay.current = false;\n    announcedPageStatus.current = _('asset_folder_not_found');\n\n    return { ...state, notFound: true }; // Not Found\n  }\n\n  if (!folder) {\n    // A folder path that comes with a file name doesn’t have to be a configured asset folder,\n    // because an asset can live in a subfolder of one. The asset itself is looked up by its full\n    // path below, so leave the resolution to that\n    selectedAssetFolder.current = undefined;\n    selectedSubfolderPath.current = '';\n  } else {\n    if (!equal(selectedAssetFolder.current, folder)) {\n      selectedAssetFolder.current = folder;\n    }\n\n    selectedSubfolderPath.current = subfolderPath;\n  }\n\n  if (!fileName) {\n    // Not awaited: the page shows the folder right away\n    announceAssetFolder(currentCount);\n\n    return state;\n  }\n\n  const assetPath = createPath([folderPath, fileName]);\n\n  overlaidAsset.current = allAssets.current.find((asset) => asset.path === assetPath);\n  announcedPageStatus.current = overlaidAsset.current\n    ? _('viewing_x_asset_details', { values: { name: overlaidAsset.current.name } })\n    : _('file_not_found');\n  showAssetOverlay.current = true;\n\n  return state;\n};\n","<script>\n  import AssetListItem from '$lib/components/assets/list/asset-list-item.svelte';\n  import { createAssetDragSource } from '$lib/services/assets/drag';\n  import { canPreviewAsset } from '$lib/services/assets/kinds';\n  import { canMoveAssets, getDraggedAssets } from '$lib/services/assets/movable';\n  import { showAssetDetails } from '$lib/services/assets/navigation';\n  import { focusedAsset, selectedAssetPathSet, selectedAssets } from '$lib/services/assets/state';\n  import { focusedSubfolder } from '$lib/services/assets/subfolders';\n  import { listedAssetIndexMap } from '$lib/services/assets/view';\n  import { toggleListItem } from '$lib/services/utils/array';\n\n  /**\n   * @import { Asset, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Asset} asset Asset.\n   * @property {ViewType} viewType View type.\n   */\n\n  /** @type {Props} */\n  let { asset, viewType } = $props();\n\n  /**\n   * Update the asset selection.\n   * @param {boolean} selected Whether the current asset item is selected.\n   */\n  const updateSelection = (selected) => {\n    selectedAssets.current = toggleListItem(selectedAssets.current, asset, selected);\n  };\n</script>\n\n<AssetListItem\n  name={asset.name}\n  kind={asset.kind}\n  {asset}\n  rowIndex={listedAssetIndexMap.current.get(asset.path) ?? -1}\n  {viewType}\n  selected={selectedAssetPathSet.current.has(asset.path)}\n  canPreview={canPreviewAsset(asset)}\n  onSelectionChange={updateSelection}\n  dragSource={canMoveAssets([asset])\n    ? createAssetDragSource(() => getDraggedAssets(asset))\n    : undefined}\n  onFocus={() => {\n    focusedAsset.current = asset;\n    // Show the asset’s info in the sidebar in place of a folder’s\n    focusedSubfolder.current = undefined;\n  }}\n  onPreview={() => {\n    // Stay in the selected folder, e.g. All Assets, rather than moving to the asset’s own folder\n    showAssetDetails(asset);\n  }}\n/>\n","<!--\n  @component\n  A row or tile for a subfolder of a repository folder in the Asset Library. Opening it browses the\n  folder, and the menu offers to rename or delete the folder.\n-->\n<script>\n  import SubfolderListItem from '$lib/components/assets/list/subfolder-list-item.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { createAssetDropTarget } from '$lib/services/assets/drag';\n  import { assetsLocked, selectedAssetFolder } from '$lib/services/assets/folders';\n  import { isCmsFolderPath } from '$lib/services/assets/reserved';\n  import { focusedAsset } from '$lib/services/assets/state';\n  import {\n    deletingSubfolder,\n    focusedSubfolder,\n    renamingSubfolder,\n  } from '$lib/services/assets/subfolders';\n  import { env } from '$lib/services/user/env.svelte';\n  import { encodePathSegments } from '$lib/services/utils/url';\n\n  /**\n   * @import { AssetSubfolder, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {AssetSubfolder} subfolder Subfolder.\n   * @property {number} rowIndex 0-based index of the subfolder in the list, for `aria-rowindex`.\n   * @property {ViewType} viewType View type.\n   */\n\n  /** @type {Props} */\n  let { subfolder, rowIndex, viewType } = $props();\n\n  /**\n   * Browse the subfolder. The selected asset folder travels as history state, the same way it does\n   * from the sidebar, so the page can tell it from another folder sharing its path.\n   */\n  const open = () => {\n    goto(encodePathSegments(`/assets/${subfolder.path}`), {\n      transitionType: 'forwards',\n      state: { folder: selectedAssetFolder.current },\n    });\n  };\n</script>\n\n<!--\n  Renaming or deleting a folder commits straight to the configured branch rather than going through\n  review, so neither is available to an Open Authoring contributor or a user who can’t push to the\n  branch, nor within a read-only folder\n-->\n<SubfolderListItem\n  {subfolder}\n  {rowIndex}\n  {viewType}\n  hasCheckboxColumn={!(env.isSmallScreen || env.isMediumScreen)}\n  onOpen={open}\n  onFocus={() => {\n    // Show the folder’s info in the sidebar in place of an asset’s\n    focusedSubfolder.current = subfolder;\n    focusedAsset.current = undefined;\n  }}\n  onRename={() => {\n    renamingSubfolder.current = subfolder;\n  }}\n  onDelete={() => {\n    deletingSubfolder.current = subfolder;\n  }}\n  dropTarget={selectedAssetFolder.current\n    ? createAssetDropTarget({ folder: selectedAssetFolder.current, dirPath: subfolder.path })\n    : undefined}\n  actionsDisabled={assetsLocked.current ||\n    !!selectedAssetFolder.current?.readonly ||\n    isCmsFolderPath(subfolder.path)}\n/>\n","<!--\n  @component Upload button for a repository folder, which opens the Upload Assets dialog.\n-->\n<script>\n  import UploadButton from '$lib/components/assets/list/upload-button.svelte';\n  import { assetsLocked, canCreateAsset, targetAssetFolder } from '$lib/services/assets/folders';\n  import { browsingCmsFolder } from '$lib/services/assets/subfolders';\n  import { showUploadAssetsDialog } from '$lib/services/assets/view';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [label] Button label. If `undefined`, the button will be iconic.\n   */\n\n  /** @type {Props} */\n  let { label = undefined } = $props();\n\n  // Uploading to the media library commits straight to the configured branch rather than going\n  // through review, so it’s not something an Open Authoring contributor or a user who can’t push to\n  // the branch can do. An asset attached to an entry is committed with that entry, so it’s\n  // unaffected. Nor can anything be added to a folder the CMS itself is served from\n  const disabled = $derived(\n    assetsLocked.current || !canCreateAsset(targetAssetFolder.current) || browsingCmsFolder.current,\n  );\n</script>\n\n<UploadButton\n  {label}\n  {disabled}\n  onclick={() => {\n    showUploadAssetsDialog.current = true;\n  }}\n/>\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import AssetListContainer from '$lib/components/assets/list/asset-list-container.svelte';\n  import AssetListItem from '$lib/components/assets/list/internal/asset-list-item.svelte';\n  import SubfolderListItem from '$lib/components/assets/list/internal/subfolder-list-item.svelte';\n  import UploadAssetsButton from '$lib/components/assets/list/internal/upload-assets-button.svelte';\n  import { assetsLocked, canCreateAsset, targetAssetFolder } from '$lib/services/assets/folders';\n  import { focusedAsset, uploadingAssets } from '$lib/services/assets/state';\n  import {\n    browsingCmsFolder,\n    focusedSubfolder,\n    selectedSubfolderPath,\n  } from '$lib/services/assets/subfolders';\n  import { assetGroups, listedAssets, listedSubfolders } from '$lib/services/assets/view';\n  import { currentView } from '$lib/services/assets/view/settings';\n\n  /**\n   * @import { Asset } from '$lib/types/private';\n   */\n\n  const viewType = $derived(currentView.current.type);\n  const folder = $derived(targetAssetFolder.current);\n  const subfolderCount = $derived(listedSubfolders.current.length);\n  // Uploading to the media library commits straight to the configured branch rather than going\n  // through review, so it’s not something an Open Authoring contributor or a user who can’t push to\n  // the branch can do. An asset attached to an entry is committed with that entry, so it’s\n  // unaffected. Nor can anything be added to a folder the CMS itself is served from\n  const uploadDisabled = $derived(\n    assetsLocked.current || !canCreateAsset(folder) || browsingCmsFolder.current,\n  );\n</script>\n\n<AssetListContainer\n  groups={assetGroups.current}\n  itemKey=\"path\"\n  totalCount={subfolderCount + listedAssets.current.length}\n  {viewType}\n  {uploadDisabled}\n  hasSubfolders={!!subfolderCount}\n  onDrop={(files) => {\n    uploadingAssets.current = { folder, subfolderPath: selectedSubfolderPath.current, files };\n  }}\n  onBlankClick={() => {\n    // Show the info of the folder being browsed in place of an asset’s or a subfolder’s\n    focusedAsset.current = undefined;\n    focusedSubfolder.current = undefined;\n  }}\n>\n  {#snippet subfolders()}\n    {#each listedSubfolders.current as subfolder, index (subfolder.path)}\n      <SubfolderListItem {subfolder} rowIndex={index} {viewType} />\n    {/each}\n  {/snippet}\n  {#snippet renderItem(/** @type {Asset} */ asset)}\n    {#key asset.sha}\n      <AssetListItem {asset} {viewType} />\n    {/key}\n  {/snippet}\n  {#snippet emptyAction()}\n    <UploadAssetsButton label={_('upload_assets')} />\n  {/snippet}\n</AssetListContainer>\n","<!--\n  @component\n  Delete Folder dialog of the Asset Library, opened for the subfolder set as `deletingSubfolder`.\n  Deleting removes every asset in the folder, along with the references to them in the entries,\n  which the dialog reports — or refuses the deletion over, if a field would be left invalid.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { ConfirmationDialog } from '@sveltia/ui';\n\n  import CascadeDeleteNote from '$lib/components/common/cascade-delete-note.svelte';\n  import { planAssetDeletion } from '$lib/services/assets/data/cascade';\n  import { runAssetCommit } from '$lib/services/assets/data/commit';\n  import { deleteSubfolder, getSubfolderAssets } from '$lib/services/assets/data/subfolder';\n  import { deletingSubfolder } from '$lib/services/assets/subfolders';\n\n  /**\n   * @import { CascadeDeletePlan } from '$lib/types/private';\n   */\n\n  let open = $state(false);\n  /**\n   * Plan for the assets in the folder, or `undefined` while it’s being worked out.\n   * @type {CascadeDeletePlan | undefined}\n   */\n  let plan = $state();\n\n  const subfolder = $derived(deletingSubfolder.current);\n  /* v8 ignore start -- these are only read while the dialog is open, which takes a folder */\n  const folderName = $derived(subfolder?.name ?? '');\n  /** Assets in the folder, at any depth, which will be deleted along. */\n  const assets = $derived(subfolder ? getSubfolderAssets(subfolder.path) : []);\n  /* v8 ignore stop */\n  const blocked = $derived(!!plan?.blockers.length);\n\n  /**\n   * Delete the folder.\n   */\n  const remove = () => {\n    /* v8 ignore next 3 -- the dialog is only open for a folder */\n    if (!subfolder) {\n      return;\n    }\n\n    const { path } = subfolder;\n\n    runAssetCommit(() => deleteSubfolder(path), { failure: 'deleting_folder_failed' });\n  };\n\n  // Work out the plan whenever the dialog opens. The lookup is asynchronous, so the dialog starts\n  // without a plan, and the Delete button waits for it. The deletion then reuses the plan, unless\n  // the entries have changed in the meantime\n  $effect(() => {\n    if (!subfolder) {\n      return;\n    }\n\n    const selection = assets;\n\n    plan = undefined;\n    open = true;\n\n    planAssetDeletion(selection).then((result) => {\n      // The dialog may have been reopened for another folder meanwhile\n      /* v8 ignore next 3 -- the plan is worked out too quickly for a test to get in between */\n      if (deletingSubfolder.current === subfolder) {\n        plan = result;\n      }\n    });\n  });\n</script>\n\n<ConfirmationDialog\n  bind:open\n  title={_('delete_folder')}\n  okLabel={_('delete')}\n  okDisabled={!plan || blocked}\n  onOk={() => {\n    // Don’t wait for the commit; the list is updated optimistically\n    remove();\n  }}\n  onClose={() => {\n    // The dialog is closed before the deletion is confirmed, so the folder is let go of here\n    // rather than when `open` turns false\n    deletingSubfolder.current = undefined;\n  }}\n>\n  <!-- There’s nothing to confirm when the deletion is refused; the note explains why -->\n  {#if !blocked}\n    {_('confirm_deleting_folder', { values: { name: folderName, count: assets.length } })}\n  {/if}\n  {#if plan}\n    <CascadeDeleteNote {plan} kind=\"asset\" count={assets.length} />\n  {/if}\n</ConfirmationDialog>\n","import { getAssetBlobURL, getAssetPublicURL } from '$lib/services/assets/info';\nimport { isMediaKind } from '$lib/services/assets/kinds';\nimport { getAssetReferenceTarget } from '$lib/services/assets/reference-target';\nimport { getEntriesByAssets, getEntriesByAssetURL } from '$lib/services/assets/references';\nimport { backend } from '$lib/services/backends';\nimport { getOrCreateAsync } from '$lib/services/utils/cache';\nimport { getMediaMetadata } from '$lib/services/utils/media';\nimport { encodePathSegments } from '$lib/services/utils/url';\n\n/**\n * @import { Asset, AssetDetails, Entry } from '$lib/types/private';\n */\n\n/**\n * The part of {@link AssetDetails} that comes from the file itself.\n * @typedef {Pick<AssetDetails, 'dimensions' | 'duration' | 'createdDate' | 'coordinates'>}\n * MediaMetadata\n */\n\n/**\n * Media metadata for the assets looked at so far, keyed by asset SHA. Collecting it downloads the\n * file, decodes it to read its dimensions and scans it for Exif data, and the result depends on\n * nothing but the file’s content, so it’s gathered once per file rather than once per component\n * asking for it — the info panel and the toolbar both ask as soon as an asset is selected.\n * @type {Map<string, Promise<MediaMetadata>>}\n */\nconst cachedMetadata = new Map();\n\n/* v8 ignore next */\n/**\n * Reset the media metadata cache. This is used in tests to reset the state between tests.\n */\nexport const _resetAssetMetadataCache = () => {\n  cachedMetadata.clear();\n};\n\n/** @type {AssetDetails} */\nexport const defaultAssetDetails = {\n  publicURL: undefined,\n  repoBlobURL: undefined,\n  dimensions: undefined,\n  duration: undefined,\n  usedEntries: [],\n};\n\n/**\n * Collect the media metadata of the given asset, if it’s a kind that has any.\n * @param {Asset} asset Asset.\n * @returns {Promise<MediaMetadata>} Metadata, or an empty object for a file with no media info.\n */\nconst collectMediaMetadata = async (asset) => {\n  const { kind } = asset;\n\n  if (!isMediaKind(kind)) {\n    return {};\n  }\n\n  const blobURL = await getAssetBlobURL(asset);\n\n  return blobURL ? getMediaMetadata(asset, blobURL, kind) : {};\n};\n\n/**\n * Get the media metadata of the given asset, reusing what was collected for the same file before.\n * A failed attempt isn’t remembered, so a later caller can try again.\n * @param {Asset} asset Asset.\n * @returns {Promise<MediaMetadata>} Metadata.\n */\nconst getMediaMetadataOnce = (asset) => {\n  const { sha } = asset;\n\n  if (!sha) {\n    return collectMediaMetadata(asset);\n  }\n\n  return getOrCreateAsync(cachedMetadata, sha, () => collectMediaMetadata(asset));\n};\n\n/**\n * Get the given asset’s extra info. The media metadata is left out if the file can’t be downloaded.\n * @param {Asset} asset Asset.\n * @returns {Promise<Omit<AssetDetails, 'usedEntries'>>} Details. `usedEntries` is not included\n * because it can be expensive to fetch; use `getAssetUsedEntries` to fetch when needed.\n */\nexport const getAssetDetails = async (asset) => {\n  const { path } = asset;\n  const { blobBaseURL } = backend.current?.repository ?? {};\n\n  const metaData = await getMediaMetadataOnce(asset).catch((/** @type {any} */ ex) => {\n    // The file couldn’t be downloaded, so the media info is left out, but not the URLs below\n    // eslint-disable-next-line no-console\n    console.error(ex);\n\n    return {};\n  });\n\n  // The URLs are derived from the asset’s path and the current config rather than its content, so\n  // they’re resolved per call instead of being cached with the metadata\n  return {\n    ...metaData,\n    publicURL: getAssetPublicURL(asset),\n    // Encode the path, as a file name can contain `#`, `?` or `%`, which would break the URL\n    repoBlobURL: blobBaseURL ? `${blobBaseURL}/${encodePathSegments(path)}` : undefined,\n  };\n};\n\n/**\n * Get the list of entries using the given asset. An asset is matched by its public path, in the\n * form it’s stored in a field value, or else by the asset itself, as in an entry-relative folder,\n * where a value like `images/photo.jpg` refers to a different file in each entry’s folder, so only\n * a value resolving to the asset refers to it.\n * @param {Asset} asset Asset.\n * @returns {Promise<Entry[]>} List of entries using the asset.\n */\nexport const getAssetUsedEntries = async (asset) => {\n  const { url } = getAssetReferenceTarget(asset);\n\n  if (url) {\n    return getEntriesByAssetURL(url);\n  }\n\n  const [entries] = await getEntriesByAssets([{ asset }]);\n\n  return entries;\n};\n","<!--\n  @component Copy menu for repository assets: public URLs, file paths and file data.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import CopyMenu from '$lib/components/assets/list/copy-menu.svelte';\n  import { getAssetDetails } from '$lib/services/assets/details';\n  import { getAssetBlob } from '$lib/services/assets/info';\n  import { canCopyFileData, copyFileData } from '$lib/services/utils/clipboard';\n  import { watchAsync } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { Asset, AssetDetails } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Asset[]} [assets] Selected assets.\n   * @property {boolean} [useButton] Whether to use the Button component.\n   */\n\n  /** @type {Props} */\n  let { assets = [], useButton = true } = $props();\n\n  /** @type {AssetDetails[]} */\n  let assetsDetailList = $state([]);\n  let canCopyData = $state(false);\n\n  const publicURLs = $derived(\n    assetsDetailList.filter(({ publicURL }) => !!publicURL).map(({ publicURL }) => publicURL),\n  );\n\n  /** @type {Blob | undefined} */\n  let assetBlob = undefined;\n  const items = $derived([\n    {\n      label: _('public_urls', { values: { count: assets.length } }),\n      disabled: !publicURLs.length,\n      /**\n       * Copy the asset public URL(s) to clipboard.\n       */\n      copy: async () => {\n        await navigator.clipboard.writeText(publicURLs.join('\\n'));\n      },\n      toastKey: 'asset_urls_copied',\n    },\n    {\n      label: _('file_paths', { values: { count: assets.length } }),\n      /**\n       * Copy the asset file path(s) to clipboard.\n       */\n      copy: async () => {\n        await navigator.clipboard.writeText(assets.map(({ path }) => `/${path}`).join('\\n'));\n      },\n      toastKey: 'asset_paths_copied',\n    },\n    {\n      label: _('file_data'),\n      disabled: !canCopyData,\n      /**\n       * Copy the file data to clipboard.\n       */\n      copy: async () => {\n        await copyFileData(/** @type {Blob} */ (assetBlob));\n      },\n      toastKey: 'asset_data_copied',\n    },\n  ]);\n\n  // The menu stays mounted while the focus moves from one asset to another, so a slow lookup for an\n  // asset focused earlier must not overwrite the details of the one focused now, which `watchAsync`\n  // takes care of\n  watchAsync(\n    () => {\n      const _assets = assets;\n\n      // Don’t copy the URLs or data of the assets selected before while the new ones are being\n      // looked up\n      assetsDetailList = [];\n      assetBlob = undefined;\n      canCopyData = false;\n\n      return Promise.all([\n        Promise.all(_assets.map(getAssetDetails)),\n        // Since OSes usually support only one item, the data can be copied only when one file is\n        // selected. The data may not be available, e.g. for a file that can’t be downloaded\n        _assets.length === 1 ? getAssetBlob(_assets[0]).catch(() => undefined) : undefined,\n      ]);\n    },\n    ([detailList, blob]) => {\n      assetsDetailList = detailList;\n      assetBlob = blob;\n      canCopyData = !!blob && canCopyFileData(blob.type);\n    },\n    (ex) => {\n      // The details couldn’t be retrieved, so the public URLs are unknown\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    },\n  );\n</script>\n\n<CopyMenu {items} count={assets.length} {useButton} />\n","<!--\n  @component\n  Delete button for repository assets, which commits the deletion along with the updates to the\n  entries using the assets, and reports a failure.\n-->\n<script>\n  import DeleteAssetsButton from '$lib/components/assets/list/delete-assets-button.svelte';\n  import { planAssetDeletion } from '$lib/services/assets/data/cascade';\n  import { runAssetCommit } from '$lib/services/assets/data/commit';\n  import { deleteAssets } from '$lib/services/assets/data/delete';\n  import { assetsLocked, hasReadonlyAsset } from '$lib/services/assets/folders';\n\n  /**\n   * @import { Asset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Asset[]} [assets] Selected assets.\n   * @property {number} [listedCount] Number of the assets listed in the view, given when the\n   * selected assets are deleted rather than the asset shown in the details overlay.\n   * @property {(() => void) | undefined} [onDelete] Called once the assets have been deleted.\n   * @property {boolean} [useButton] Whether to use the Button component.\n   */\n\n  /** @type {Props} */\n  let { assets = [], listedCount = undefined, onDelete = undefined, useButton = true } = $props();\n</script>\n\n<!--\n  Deleting a file from the media library commits straight to the configured branch rather than\n  going through review, so it’s not something an Open Authoring contributor or a user who can’t\n  push to the branch can do\n-->\n<DeleteAssetsButton\n  {assets}\n  disabled={assetsLocked.current || hasReadonlyAsset(assets)}\n  deleteAssets={async (_assets) =>\n    // On failure, stay on the asset, which is still there\n    (await runAssetCommit(() => deleteAssets(_assets), { failure: 'deleting_assets_failed' })).ok}\n  planDeletion={planAssetDeletion}\n  {listedCount}\n  {onDelete}\n  {useButton}\n/>\n","<!--\n  @component\n  Developer mode menu item that opens a file in the repository, named after the Git hosting service.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { MenuItem } from '@sveltia/ui';\n\n  import { backend } from '$lib/services/backends';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} disabled Whether the item is disabled.\n   * @property {() => void} onclick Click handler, which opens the file.\n   */\n\n  /** @type {Props} */\n  let { disabled, onclick } = $props();\n\n  const serviceLabel = $derived(backend.current?.repository?.label);\n</script>\n\n{#if prefs.devModeEnabled}\n  <MenuItem\n    {disabled}\n    label={serviceLabel\n      ? _('view_on_x', { values: { service: serviceLabel } })\n      : _('view_in_repository')}\n    {onclick}\n  />\n{/if}\n","import { untrack } from 'svelte';\n\nimport {\n  defaultAssetDetails,\n  getAssetDetails,\n  getAssetUsedEntries,\n} from '$lib/services/assets/details';\n\n/**\n * @import { Asset, AssetDetails, Entry } from '$lib/types/private';\n */\n\n/**\n * Keep the details of an asset up to date as the asset changes, for a component that stays mounted\n * while the focus moves from one asset to another. The details of the previous asset are dropped\n * right away, so they’re not shown or acted on while the new ones are being retrieved, and a slow\n * lookup for an asset focused earlier never overwrites the details of the one focused now. Call it\n * while a component is being initialized.\n * @param {() => Asset | undefined} getAsset Function returning the asset, if any.\n * @param {object} [options] Options.\n * @param {boolean} [options.withUsedEntries] Whether to look up the entries using the asset as\n * well, once the details have been retrieved. `usedEntries` is `undefined` until then.\n * @returns {{ current: AssetDetails }} Details, which are the defaults until retrieved, or if they\n * can’t be.\n */\nexport const createAssetDetailsState = (getAsset, { withUsedEntries = false } = {}) => {\n  const state = $state({ current: { ...defaultAssetDetails } });\n\n  $effect(() => {\n    const asset = getAsset();\n    let stale = false;\n\n    untrack(() => {\n      state.current = withUsedEntries\n        ? { ...defaultAssetDetails, usedEntries: undefined }\n        : { ...defaultAssetDetails };\n    });\n\n    if (asset) {\n      (async () => {\n        try {\n          const details = await getAssetDetails(asset);\n\n          if (stale) {\n            return;\n          }\n\n          state.current = details;\n        } catch (/** @type {any} */ ex) {\n          // Only the basic info is shown, as the URLs are unknown, but the used entries don’t\n          // depend on the details\n          // eslint-disable-next-line no-console\n          console.error(ex);\n        }\n\n        if (!withUsedEntries || stale) {\n          return;\n        }\n\n        /** @type {Entry[]} */\n        let usedEntries = [];\n\n        try {\n          usedEntries = await getAssetUsedEntries(asset);\n        } catch (/** @type {any} */ ex) {\n          // Stop showing the used entries as being loaded\n          // eslint-disable-next-line no-console\n          console.error(ex);\n        }\n\n        if (!stale) {\n          state.current.usedEntries = usedEntries;\n        }\n      })();\n    }\n\n    return () => {\n      stale = true;\n    };\n  });\n\n  return state;\n};\n","<!--\n  @component\n  Edit options menu for a repository asset: Edit, Rename, Move, Replace and links to the file.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { MenuItem } from '@sveltia/ui';\n\n  import EditOptionsMenu from '$lib/components/assets/list/edit-options-menu.svelte';\n  import ViewInRepositoryItem from '$lib/components/common/view-in-repository-item.svelte';\n  import { createAssetDetailsState } from '$lib/services/assets/details-state.svelte';\n  import { assetsLocked, hasReadonlyAsset } from '$lib/services/assets/folders';\n  import { canEditAsset } from '$lib/services/assets/kinds';\n  import { canMoveAssets } from '$lib/services/assets/movable';\n  import {\n    assetMoveRequest,\n    editingAsset,\n    renamingAsset,\n    uploadingAssets,\n  } from '$lib/services/assets/state';\n  import { showUploadAssetsDialog } from '$lib/services/assets/view';\n  import { backend } from '$lib/services/backends';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { Asset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Asset} [asset] Selected asset.\n   * @property {Asset[]} [assets] Assets the Move item applies to, as several can be selected in the\n   * list. Default: the selected asset.\n   * @property {Snippet} [extraItems] Slot content.\n   */\n\n  /** @type {Props} */\n  let { asset, assets = asset ? [asset] : [], extraItems = undefined } = $props();\n\n  // The menu stays mounted while the focus moves from one asset to another\n  const details = createAssetDetailsState(() => asset);\n\n  const { publicURL, repoBlobURL } = $derived(details.current);\n  // A file in a read-only folder can’t be edited, renamed or replaced\n  const editable = $derived(!!asset && !hasReadonlyAsset([asset]));\n</script>\n\n<!--\n  Editing, renaming or replacing a file in the media library commits straight to the configured\n  branch rather than going through review, so none of it is available to an Open Authoring\n  contributor or a user who can’t push to the branch, nor for a file in a read-only folder\n-->\n<EditOptionsMenu\n  readOnly={assetsLocked.current}\n  canEdit={editable && canEditAsset(/** @type {Asset} */ (asset))}\n  canRename={editable}\n  canReplace={editable}\n  canMove={canMoveAssets(assets)}\n  onEdit={() => {\n    editingAsset.current = asset;\n  }}\n  onRename={() => {\n    renamingAsset.current = asset;\n  }}\n  onMove={() => {\n    assetMoveRequest.current = { assets: [...assets] };\n  }}\n  onReplace={() => {\n    uploadingAssets.current = {\n      folder: undefined,\n      files: [],\n      // The item is disabled without an asset\n      originalAssets: [/** @type {Asset} */ (asset)],\n    };\n    showUploadAssetsDialog.current = true;\n  }}\n  {extraItems}\n>\n  {#snippet moreItems()}\n    <MenuItem\n      label={_('view_on_live_site')}\n      disabled={!publicURL}\n      onclick={() => {\n        openNewTab(publicURL);\n      }}\n    />\n    <ViewInRepositoryItem\n      disabled={!backend.current?.repository || !repoBlobURL}\n      onclick={() => {\n        openNewTab(`${repoBlobURL}?plain=1`);\n      }}\n    />\n  {/snippet}\n</EditOptionsMenu>\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n\n  import FileInfoSections from '$lib/components/assets/list/file-info-sections.svelte';\n  import InfoPanelLayout from '$lib/components/assets/list/info-panel-layout.svelte';\n  import UsedEntries from '$lib/components/assets/list/used-entries.svelte';\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import LeafletMap from '$lib/components/common/leaflet-map.svelte';\n  import { createAssetDetailsState } from '$lib/services/assets/details-state.svelte';\n  import { isMediaKind, isPDF } from '$lib/services/assets/kinds';\n  import { getCommitAuthorName } from '$lib/services/utils/commit-author';\n  import { formatDate } from '$lib/services/utils/date';\n\n  /**\n   * @import { Asset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Asset} asset Asset.\n   * @property {boolean} [showPreview] Whether to show the media preview.\n   */\n\n  /** @type {Props} */\n  let { asset, showPreview = false } = $props();\n\n  // The panel stays mounted while the focus moves from one asset to another\n  const details = createAssetDetailsState(() => asset, { withUsedEntries: true });\n\n  // @todo Fetch file size and commit info on demand for GitLab\n  const { path, size, kind, commitAuthor, commitDate } = $derived(asset);\n  const { publicURL, repoBlobURL, dimensions, duration, createdDate, coordinates, usedEntries } =\n    $derived(details.current);\n  const canPreview = $derived(isMediaKind(kind) || isPDF(path));\n</script>\n\n{#snippet preview()}\n  <AssetPreview\n    {kind}\n    {asset}\n    variant=\"tile\"\n    checkerboard={kind === 'image'}\n    controls={['audio', 'video'].includes(kind)}\n  />\n{/snippet}\n\n<InfoPanelLayout preview={showPreview && canPreview ? preview : undefined}>\n  <FileInfoSections\n    fileName={path}\n    {kind}\n    {size}\n    hasDimensions={canPreview}\n    {dimensions}\n    {duration}\n  />\n  <section>\n    <h4>{_('public_urls', { values: { count: 1 } })}</h4>\n    <p>\n      {#if publicURL}\n        <a href={publicURL} dir=\"ltr\" target=\"_blank\" rel=\"noopener noreferrer\">{publicURL}</a>\n      {:else}\n        –\n      {/if}\n    </p>\n  </section>\n  <section>\n    <h4>{_('file_paths', { values: { count: 1 } })}</h4>\n    <p>\n      {#if repoBlobURL}\n        <a href={repoBlobURL} dir=\"ltr\">/{path}</a>\n      {:else}\n        <bdi dir=\"ltr\">/{path}</bdi>\n      {/if}\n    </p>\n  </section>\n  <UsedEntries entries={usedEntries} />\n  {#if commitAuthor}\n    <section>\n      <h4>{_('sort_keys.commit_author')}</h4>\n      <p>{getCommitAuthorName(commitAuthor)}</p>\n    </section>\n  {/if}\n  {#if commitDate}\n    <section>\n      <h4>{_('sort_keys.commit_date')}</h4>\n      <p>{formatDate(commitDate, appLocale.current)}</p>\n    </section>\n  {/if}\n  {#if createdDate}\n    <section>\n      <h4>{_('created_date')}</h4>\n      <p>{formatDate(createdDate, appLocale.current)}</p>\n    </section>\n  {/if}\n  {#if coordinates}\n    <section>\n      <h4>{_('location')}</h4>\n      <LeafletMap {coordinates} />\n    </section>\n  {/if}\n</InfoPanelLayout>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { onDestroy, untrack } from 'svelte';\n\n  import AssetPreviewContent from '$lib/components/assets/list/asset-preview-content.svelte';\n  import DetailsOverlay from '$lib/components/assets/list/details-overlay.svelte';\n  import DownloadAssetsButton from '$lib/components/assets/list/download-assets-button.svelte';\n  import CopyAssetsButton from '$lib/components/assets/list/internal/copy-assets-button.svelte';\n  import DeleteAssetsButton from '$lib/components/assets/list/internal/delete-assets-button.svelte';\n  import EditOptionsButton from '$lib/components/assets/list/internal/edit-options-button.svelte';\n  import InfoPanel from '$lib/components/assets/list/internal/info-panel.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import { goBack } from '$lib/services/app/navigation';\n  import { selectedAssetFolder } from '$lib/services/assets/folders';\n  import { getAssetBlob, preloadAssets } from '$lib/services/assets/info';\n  import { canPreviewAsset } from '$lib/services/assets/kinds';\n  import { getAssetFolderHistoryState, showAssetDetails } from '$lib/services/assets/navigation';\n  import { overlaidAsset } from '$lib/services/assets/state';\n  import { browsedDirPath } from '$lib/services/assets/subfolders';\n  import { assetGroups, getAdjacentAssets } from '$lib/services/assets/view';\n  import { isSearchResultsPath } from '$lib/services/search/navigation';\n  import { encodePathSegments } from '$lib/services/utils/url';\n\n  /**\n   * @import { ViewTransitionType } from '$lib/services/app/navigation';\n   * @import { Asset } from '$lib/types/private';\n   */\n\n  /**\n   * The blob most recently loaded, along with the asset it was loaded for. Kept together so the\n   * preview never reads a blob that belongs to another asset: once an asset has been renamed or\n   * moved on the file system, the blob read before the move points at a file that no longer exists.\n   * The blob is missing if it couldn’t be read.\n   * @type {{ asset: Asset, blob?: Blob } | undefined}\n   */\n  let loaded = $state.raw();\n\n  const asset = $derived(overlaidAsset.current);\n  /** Whether the blob of the shown asset is still being read. */\n  const pending = $derived(loaded?.asset !== asset);\n  /* v8 ignore start -- only read while the asset is shown, by which time `loaded` is set */\n  const blob = $derived(pending ? undefined : loaded?.blob);\n  /* v8 ignore stop */\n  const kind = $derived(asset?.kind);\n  const blobURL = $derived(asset?.blobURL);\n  const name = $derived(asset?.name ?? '');\n  const assets = $derived(asset ? [asset] : []);\n  // Back to the subfolder the asset was opened from, if the folder is browsed by subfolder\n  const backPath = $derived(\n    encodePathSegments(\n      `/assets/${browsedDirPath.current ?? selectedAssetFolder.current?.internalPath ?? '-/all'}`,\n    ),\n  );\n  /** The assets right before and after the shown one in the list the overlay was opened from. */\n  const { previous, next } = $derived(\n    getAdjacentAssets(assetGroups.current, (a) => a.path === asset?.path, canPreviewAsset),\n  );\n\n  /**\n   * Show another listed asset in place of the current one. The history entry is replaced, so the\n   * browser’s back button still returns to the list however many assets have been flipped through.\n   * @param {Asset} target Asset to be shown.\n   * @param {ViewTransitionType} transitionType View transition type.\n   */\n  const showAsset = (target, transitionType) => {\n    showAssetDetails(target, { replaceState: true, transitionType });\n  };\n\n  // Load the adjacent images ahead of time, so moving to one of them is instant. Other kinds aren’t\n  // worth downloading in full on the off chance, e.g. a video. The shown asset is kept as well, so\n  // the one just moved to isn’t released before its preview displays it\n  $effect(() => {\n    const targets = /** @type {Asset[]} */ ([previous, next].filter((a) => a?.kind === 'image'));\n    const keep = asset ? [asset] : [];\n\n    untrack(() => preloadAssets(targets, { keep }));\n  });\n\n  onDestroy(() => {\n    preloadAssets([]);\n  });\n\n  $effect(() => {\n    // Hold on to the asset, as the derived value follows the overlay while the blob is being read\n    const current = asset;\n\n    if (current) {\n      (async () => {\n        /** @type {Blob | undefined} */\n        let _blob;\n\n        try {\n          _blob = await getAssetBlob(current);\n        } catch (/** @type {any} */ ex) {\n          // The preview is shown as unavailable\n          // eslint-disable-next-line no-console\n          console.error(ex);\n        }\n\n        // The user may have switched to another asset in the meantime\n        if (overlaidAsset.current === current) {\n          loaded = { asset: current, blob: _blob };\n        }\n      })();\n    }\n  });\n</script>\n\n<DetailsOverlay\n  title={name}\n  contentKey={asset?.sha}\n  onBack={() => {\n    goBack(backPath, { returnTo: isSearchResultsPath, state: getAssetFolderHistoryState() });\n  }}\n  onPrevious={previous ? () => showAsset(previous, 'previous') : undefined}\n  onNext={next ? () => showAsset(next, 'next') : undefined}\n>\n  {#snippet actions(useButton)}\n    <CopyAssetsButton {assets} {useButton} />\n    <DownloadAssetsButton {assets} getName={(a) => a.name} getBlob={getAssetBlob} {useButton} />\n    <DeleteAssetsButton\n      {assets}\n      onDelete={() => {\n        goBack(backPath, { returnTo: isSearchResultsPath, state: getAssetFolderHistoryState() });\n      }}\n      {useButton}\n    />\n  {/snippet}\n  {#snippet editOptions(extraItems)}\n    <EditOptionsButton {asset} {extraItems} />\n  {/snippet}\n  {#snippet preview()}\n    {#if !asset}\n      <NotFound message={_('file_not_found')} {backPath} />\n    {:else}\n      <AssetPreviewContent\n        {kind}\n        {name}\n        type={blob?.type}\n        {asset}\n        src={blobURL}\n        {pending}\n        getText={() => asset.text ?? /** @type {Blob} */ (blob).text()}\n      />\n    {/if}\n  {/snippet}\n  {#snippet info()}\n    {#if asset}\n      <InfoPanel {asset} />\n    {/if}\n  {/snippet}\n</DetailsOverlay>\n","import { getAssetsByDirName, getTakenNamesInDir } from '$lib/services/assets';\nimport { assetUpdatesToast, refreshFocusedAssets } from '$lib/services/assets/data';\nimport { formatFileName } from '$lib/services/assets/file-name';\nimport { getAssetKind } from '$lib/services/assets/kinds';\nimport { assertOutsideCmsFolders } from '$lib/services/assets/reserved';\nimport { getUploadDirPath } from '$lib/services/assets/subfolders';\nimport { isPublishingCommit } from '$lib/services/backends/git/shared/integration';\nimport { saveChanges } from '$lib/services/backends/save';\nimport { UPDATE_TOAST_DEFAULT_STATE } from '$lib/services/contents/collection/data';\nimport { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\nimport { createPath, foldFileName } from '$lib/services/utils/file';\n\n/**\n * @import {\n * Asset,\n * CommitAction,\n * CommitOptions,\n * FileChange,\n * UploadingAssets,\n * } from '$lib/types/private';\n */\n\n/**\n * Create a list of file objects to be uploaded, ensuring that names are unique and sanitized. A\n * file that overwrites an existing asset — because the user picked that asset to be replaced, or\n * because they chose to overwrite a same-named file — takes over the asset’s name and path.\n * @param {UploadingAssets} uploadingAssets Assets to be uploaded.\n * @returns {{ action: CommitAction, name: string, path: string, file: File }[]} An array of objects\n * representing the files to be uploaded, each containing the action type, name, path, and file\n * object.\n */\nexport const createFileList = (uploadingAssets) => {\n  const { files, originalAssets, replaceDuplicates = false } = uploadingAssets;\n  const { slugify_filename: slugificationEnabled = false } = getDefaultMediaLibraryOptions().config;\n  const dirPath = getUploadDirPath(uploadingAssets);\n  const assetsInSameFolder = dirPath !== undefined ? getAssetsByDirName(dirPath) : [];\n  // A file is never named after an entry file or a subfolder there either\n  const assetNamesInSameFolder = dirPath !== undefined ? getTakenNamesInDir(dirPath) : [];\n  // Folded names, so each file is checked against the folder without folding every name again\n  const foldedNamesInSameFolder = new Set(assetNamesInSameFolder.map(foldFileName));\n  /** @type {Map<string, Asset>} */\n  const assetsByFoldedName = new Map();\n  /** @type {Set<string>} */\n  const namesInBatch = new Set();\n\n  assetsInSameFolder.forEach((asset) => {\n    const name = foldFileName(asset.name);\n\n    if (!assetsByFoldedName.has(name)) {\n      assetsByFoldedName.set(name, asset);\n    }\n  });\n\n  return files.map((file, index) => {\n    // The user picked this asset to be replaced, so the file takes over its name and path even\n    // when it’s called something else. Failing that, an ordinary upload overwrites an existing\n    // file of the same name when the user chose to replace it — but only the first of the files\n    // with that name in the batch, e.g. two `photo.png` files from different subfolders of a\n    // dropped folder; another one gets a name of its own, or it would overwrite the first one.\n    const foldedFileName = foldFileName(file.name);\n\n    const replacedAsset =\n      originalAssets?.[index] ??\n      (replaceDuplicates && !namesInBatch.has(foldedFileName)\n        ? assetsByFoldedName.get(foldedFileName)\n        : undefined);\n\n    const fileName =\n      replacedAsset?.name ??\n      formatFileName(file.name, {\n        slugificationEnabled,\n        assetNamesInSameFolder,\n        foldedNamesInSameFolder,\n      });\n\n    const foldedName = foldFileName(fileName);\n\n    if (!foldedNamesInSameFolder.has(foldedName)) {\n      assetNamesInSameFolder.push(fileName);\n      foldedNamesInSameFolder.add(foldedName);\n    }\n\n    namesInBatch.add(foldedName);\n\n    return {\n      action: /** @type {CommitAction} */ (replacedAsset ? 'update' : 'create'),\n      name: fileName,\n      path: replacedAsset?.path ?? createPath([dirPath, fileName]),\n      file,\n    };\n  });\n};\n\n/**\n * Update the asset stores with new assets, ensuring that focused and overlaid assets are refreshed,\n * and displays a toast notification about the asset updates.\n * @param {object} args Arguments.\n * @param {number} args.count The number of files that were updated.\n * @param {CommitOptions} args.options Options the files were committed with.\n */\nexport const updateStores = ({ count, options }) => {\n  refreshFocusedAssets((asset) => asset.path);\n\n  assetUpdatesToast.current = {\n    ...UPDATE_TOAST_DEFAULT_STATE,\n    saved: true,\n    published: isPublishingCommit(options),\n    count,\n  };\n};\n\n/**\n * Prepare files to be saved to a repository folder, named as {@link createFileList} names them:\n * the assets they become and the changes that commit them.\n * @param {UploadingAssets} uploadingAssets Files to be saved.\n * @returns {{ savingAssets: Asset[], changes: FileChange[] }} Assets and changes, in the same\n * order as the files.\n * @throws {Error} When a file would be saved in a folder the CMS is served from.\n */\nexport const prepareAssetChanges = (uploadingAssets) => {\n  const { folder } = uploadingAssets;\n  const fileList = createFileList(uploadingAssets);\n\n  assertOutsideCmsFolders(fileList.map(({ path }) => path));\n\n  return {\n    savingAssets: fileList.map(\n      ({ name, path, file }) =>\n        /** @type {Asset} */ ({ name, path, size: file.size, kind: getAssetKind(name), folder }),\n    ),\n    changes: fileList.map(({ action, path, file }) => ({ action, path, data: file })),\n  };\n};\n\n/**\n * Upload/save the given assets to the backend.\n * @param {UploadingAssets} uploadingAssets Assets to be uploaded.\n * @param {CommitOptions} options Options for the backend handler.\n */\nexport const saveAssets = async (uploadingAssets, options) => {\n  const { savingAssets, changes } = prepareAssetChanges(uploadingAssets);\n\n  await saveChanges({ changes, savingAssets, options });\n\n  updateStores({ count: uploadingAssets.files.length, options });\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Dialog, Switch, TextArea } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import { runAssetCommit } from '$lib/services/assets/data/commit';\n  import { saveAssets } from '$lib/services/assets/data/create';\n  import { getAssetBlob } from '$lib/services/assets/info';\n  import { editingAsset } from '$lib/services/assets/state';\n  import { showAssetOverlay } from '$lib/services/assets/view';\n\n  /**\n   * @import { Asset } from '$lib/types/private';\n   */\n\n  const asset = $derived(editingAsset.current);\n  let open = $state(false);\n  /** @type {Blob | undefined} */\n  let blob = $state();\n  /** @type {string | undefined} */\n  let originalValue = $state();\n  /** @type {string | undefined} */\n  let currentValue = $state();\n  /** @type {boolean | 'mixed'} */\n  let wrap = $state(false);\n  /** Whether the edited text is being saved, during which the state is kept for a retry. */\n  let saving = false;\n  /**\n   * Whether the dialog was opened from the asset details overlay rather than from the asset list.\n   * The dialog closes along with that overlay.\n   */\n  let openedFromOverlay = false;\n\n  /**\n   * Initialize the state.\n   */\n  const initState = async () => {\n    // Called from an effect, which shouldn’t rerun when the overlay is opened or closed\n    openedFromOverlay = untrack(() => showAssetOverlay.current);\n    blob = await getAssetBlob(/** @type {Asset} */ (asset));\n    originalValue = await blob.text();\n    currentValue = originalValue;\n    open = true;\n  };\n\n  /**\n   * Reset the state.\n   */\n  const resetState = () => {\n    editingAsset.current = undefined;\n    blob = undefined;\n    originalValue = undefined;\n    currentValue = undefined;\n  };\n\n  /**\n   * Save the edited asset. If saving fails, the dialog is opened again with the edited text, so the\n   * user can retry without losing it.\n   */\n  const saveAsset = async () => {\n    /* v8 ignore next 3 -- the dialog is only shown once the asset is loaded */\n    if (!asset || !blob || typeof currentValue !== 'string') {\n      return;\n    }\n\n    saving = true;\n\n    const { folder, name } = asset;\n    const text = currentValue;\n    const { type } = blob;\n\n    const { ok } = await runAssetCommit(\n      () =>\n        saveAssets(\n          {\n            folder,\n            files: [new File([text], name, { type })],\n            originalAssets: [asset],\n          },\n          { commitType: 'uploadMedia' },\n        ),\n      { failure: 'saving_asset_failed' },\n    );\n\n    saving = false;\n\n    if (!ok) {\n      // The asset details overlay the dialog was opened from may have been closed in the meantime\n      if (!openedFromOverlay || showAssetOverlay.current) {\n        open = true;\n\n        return;\n      }\n    }\n\n    resetState();\n  };\n\n  /* v8 ignore start -- the title is only read while the dialog is open, for an asset */\n  const title = $derived(_('edit_x', { values: { name: asset?.name ?? '' } }));\n  /* v8 ignore stop */\n\n  $effect(() => {\n    if (asset && blob === undefined) {\n      initState();\n    }\n  });\n\n  $effect(() => {\n    if (!showAssetOverlay.current && openedFromOverlay) {\n      open = false;\n    }\n  });\n</script>\n\n<Dialog\n  size=\"x-large\"\n  {title}\n  bind:open\n  okLabel={_('save')}\n  okDisabled={currentValue === originalValue}\n  okShortcuts=\"Accel+S\"\n  onOk={() => {\n    saveAsset();\n  }}\n  onClose={() => {\n    // Keep the state while saving, in case the dialog has to be reopened\n    if (!saving) {\n      resetState();\n    }\n  }}\n>\n  <div role=\"none\" class=\"wrapper\" class:wrap>\n    <TextArea dir=\"auto\" bind:value={currentValue} flex aria-label={title} />\n  </div>\n  {#snippet footerExtra()}\n    <Switch label={_('wrap_long_lines')} bind:checked={wrap} />\n  {/snippet}\n</Dialog>\n\n<style>\n  .wrapper {\n    display: contents;\n\n    :global {\n      textarea {\n        min-height: 40dvh;\n        max-height: 80dvh;\n        font-family: var(--sui-font-family-monospace);\n        font-size: var(--sui-font-size-monospace);\n        text-wrap: nowrap;\n        resize: vertical;\n      }\n\n      &.wrap textarea {\n        text-wrap: wrap;\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Info panel for a folder in the Asset Library, shown in the sidebar while no asset is focused: the\n  folder name, its path and what it holds. The folder is the listed subfolder focused with a click\n  or the keyboard, if any, or else the folder being browsed.\n-->\n<script>\n  import FolderInfoPanel from '$lib/components/assets/list/folder-info-panel.svelte';\n  import { folderSummary } from '$lib/services/assets/view';\n\n  /**\n   * @import { AssetFolderSummary } from '$lib/types/private';\n   */\n\n  /** The panel is only shown with a folder selected. */\n  const info = $derived(/** @type {AssetFolderSummary} */ (folderSummary.current));\n</script>\n\n<FolderInfoPanel\n  name={info.name}\n  path={info.path}\n  folderCount={info.folderCount}\n  assetCount={info.assetCount}\n/>\n","import { allAssetFolders } from '$lib/services/assets/folders';\nimport { getCollection, getCollectionIndex } from '$lib/services/contents/collection';\nimport { getCollectionFile, getCollectionFileIndex } from '$lib/services/contents/collection/files';\n\n/**\n * @import { AssetFolderInfo } from '$lib/types/private';\n */\n\n/**\n * Get the asset folders listed in the Asset Library sidebar, in the order they appear there: All\n * Assets and Global Assets, then the collection-level and file-level folders in the order of the\n * collections and files in the configuration, then the asset collections. Field-level folders\n * aren’t listed.\n * @returns {AssetFolderInfo[]} Folders.\n */\nexport const getListedAssetFolders = () => [\n  ...allAssetFolders.current\n    .filter(\n      ({ typedKeyPath, isAssetCollection }) => !isAssetCollection && typedKeyPath === undefined,\n    )\n    .sort(\n      (a, b) =>\n        getCollectionFileIndex(a.collectionName, a.fileName) -\n        getCollectionFileIndex(b.collectionName, b.fileName),\n    )\n    .sort((a, b) => getCollectionIndex(a.collectionName) - getCollectionIndex(b.collectionName)),\n  ...allAssetFolders.current.filter(({ isAssetCollection }) => isAssetCollection),\n];\n\n/**\n * Get the icon of an asset folder: its own, or else that of the collection file or collection it\n * belongs to, or a plain folder.\n * @param {AssetFolderInfo} folder Folder.\n * @returns {string} Material Symbols icon name.\n */\nexport const getAssetFolderIcon = (folder) => {\n  const { icon, collectionName, fileName } = folder;\n  const collection = collectionName ? getCollection(collectionName) : undefined;\n\n  const collectionFile =\n    collection && fileName ? getCollectionFile(collection, fileName) : undefined;\n\n  return icon || collectionFile?.icon || collection?.icon || 'folder';\n};\n","import { isAssetInFolder } from '$lib/services/assets';\nimport { canCreateAsset } from '$lib/services/assets/folders';\nimport { isCmsFolderPath } from '$lib/services/assets/reserved';\nimport { publishedAssets } from '$lib/services/assets/state';\nimport { getSubfolderTree } from '$lib/services/assets/subfolders';\nimport { getFolderLabelByCollection } from '$lib/services/assets/view';\nimport { getAssetFolderIcon, getListedAssetFolders } from '$lib/services/assets/view/folder-list';\n\n/**\n * @import { AssetMoveDestination } from '$lib/types/private';\n */\n\n/**\n * Get the directories assets can be moved to: the root of every asset folder files can be uploaded\n * to, in the order the sidebar lists the folders, each with the subfolders below it as a tree.\n * A folder whose path is entry-relative or has template tags is left out, as a file’s path there\n * depends on the entry using it, and so is a read-only folder and one the CMS itself is served\n * from. Folders sharing a path, like an asset collection and the global folder, are the same\n * directory, so only the first is listed.\n * @returns {AssetMoveDestination[]} Destinations.\n */\nexport const getAssetMoveDestinations = () => {\n  /** @type {Set<string>} */\n  const seenPaths = new Set();\n\n  return getListedAssetFolders()\n    .filter((folder) => {\n      const { internalPath } = folder;\n\n      if (\n        internalPath === undefined ||\n        !canCreateAsset(folder) ||\n        isCmsFolderPath(internalPath) ||\n        seenPaths.has(internalPath)\n      ) {\n        return false;\n      }\n\n      seenPaths.add(internalPath);\n\n      return true;\n    })\n    .map((folder) => {\n      const rootPath = /** @type {string} */ (folder.internalPath);\n      const assets = publishedAssets.current.filter((asset) => isAssetInFolder(asset, folder));\n      const getSubfolders = getSubfolderTree({ dirPath: rootPath, assets });\n\n      /**\n       * List the subfolders of a directory, each with its own subfolders.\n       * @param {string} dirPath Directory path.\n       * @returns {AssetMoveDestination[]} Destinations.\n       */\n      const listChildren = (dirPath) =>\n        getSubfolders(dirPath)\n          .filter(({ path }) => !isCmsFolderPath(path))\n          .map(({ name, path }) => ({\n            folder,\n            dirPath: path,\n            label: name,\n            children: listChildren(path),\n          }));\n\n      return {\n        folder,\n        dirPath: rootPath,\n        label: getFolderLabelByCollection(folder),\n        children: listChildren(rootPath),\n      };\n    });\n};\n\n/**\n * Find the destination for a directory in the given tree.\n * @param {AssetMoveDestination[]} destinations Destinations, as returned by\n * {@link getAssetMoveDestinations} or `getExternalMoveDestinations()`.\n * @param {string} dirPath Directory path.\n * @param {string} [serviceId] ID of the cloud storage service the directory is on, or `undefined`\n * for a repository directory.\n * @returns {AssetMoveDestination | undefined} Destination, if the directory is in the tree.\n */\nexport const findAssetMoveDestination = (destinations, dirPath, serviceId = undefined) =>\n  destinations.reduce(\n    (/** @type {AssetMoveDestination | undefined} */ found, destination) =>\n      found ??\n      (destination.dirPath === dirPath && destination.service?.serviceId === serviceId\n        ? destination\n        : findAssetMoveDestination(destination.children, dirPath, serviceId)),\n    undefined,\n  );\n\n/**\n * Whether two destinations are in the same tree: the same cloud storage service, or the same\n * repository asset folder, told apart by its path, as the tree has one folder per path.\n * @param {AssetMoveDestination} a Destination.\n * @param {AssetMoveDestination} b Another destination.\n * @returns {boolean} Result.\n */\nconst isInSameTree = (a, b) =>\n  a.service || b.service\n    ? a.service?.serviceId === b.service?.serviceId\n    : a.folder?.internalPath === b.folder?.internalPath;\n\n/**\n * Whether two destinations are the same directory.\n * @param {AssetMoveDestination} a Destination.\n * @param {AssetMoveDestination | undefined} b Another destination, if any.\n * @returns {boolean} Result.\n */\nexport const isSameMoveDestination = (a, b) => !!b && isInSameTree(a, b) && a.dirPath === b.dirPath;\n\n/**\n * Whether a destination is below another one in the tree, at any depth, which keeps the branch\n * holding a selected destination expanded.\n * @param {AssetMoveDestination} ancestor Destination that may hold the other.\n * @param {AssetMoveDestination | undefined} destination Destination, if any.\n * @returns {boolean} Result.\n */\nexport const isBelowMoveDestination = (ancestor, destination) =>\n  !!destination &&\n  isInSameTree(ancestor, destination) &&\n  destination.dirPath !== ancestor.dirPath &&\n  destination.dirPath.startsWith(ancestor.dirPath ? `${ancestor.dirPath}/` : '');\n\n/**\n * Get the icon of a destination: a cloud for a cloud storage service, the folder’s own for the\n * root of a repository asset folder, and a plain folder otherwise.\n * @param {AssetMoveDestination} destination Destination.\n * @returns {string} Material Symbols icon name.\n */\nexport const getMoveDestinationIcon = (destination) => {\n  const { dirPath } = destination;\n\n  if (destination.service) {\n    return dirPath ? 'folder' : 'cloud';\n  }\n\n  const { folder } = destination;\n\n  return dirPath === folder.internalPath ? getAssetFolderIcon(folder) : 'folder';\n};\n\n/**\n * Get a key that tells destinations apart in a list, as a repository directory and a folder on a\n * service can share a path.\n * @param {AssetMoveDestination} destination Destination.\n * @returns {string} Key.\n */\nexport const getMoveDestinationKey = ({ service, dirPath }) =>\n  `${service?.serviceId ?? ''}:${dirPath}`;\n","<!--\n  @component\n  A folder in the destination tree of the Move dialog, followed by its subfolders: a repository\n  folder, or a cloud storage service or a folder on it.\n-->\n<script>\n  import { Icon, TreeItem } from '@sveltia/ui';\n\n  // The component recursively renders itself for the subfolders\n  import MoveDestinationTreeItem from '$lib/components/assets/list/internal/move-destination-tree-item.svelte';\n  import {\n    getMoveDestinationIcon,\n    getMoveDestinationKey,\n    isBelowMoveDestination,\n    isSameMoveDestination,\n  } from '$lib/services/assets/data/move-destinations';\n\n  /**\n   * @import { AssetMoveDestination } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {AssetMoveDestination} destination Folder to display.\n   * @property {AssetMoveDestination | undefined} selectedDestination Selected folder, if any.\n   * @property {(destination: AssetMoveDestination) => void} onSelectDestination Called with the\n   * chosen folder.\n   */\n\n  /** @type {Props} */\n  let { destination, selectedDestination, onSelectDestination } = $props();\n\n  const { label, children } = $derived(destination);\n  const selected = $derived(isSameMoveDestination(destination, selectedDestination));\n  // Keep the branch that holds the selected folder open, so it can be seen without any digging\n  const expanded = $derived(isBelowMoveDestination(destination, selectedDestination));\n</script>\n\n{#snippet childItems()}\n  {#each children as child (getMoveDestinationKey(child))}\n    <MoveDestinationTreeItem destination={child} {selectedDestination} {onSelectDestination} />\n  {/each}\n{/snippet}\n\n<TreeItem\n  {label}\n  {selected}\n  {expanded}\n  items={children.length ? childItems : undefined}\n  onSelect={() => {\n    onSelectDestination(destination);\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name={getMoveDestinationIcon(destination)} />\n  {/snippet}\n</TreeItem>\n","import { getTakenNamesInDir } from '$lib/services/assets';\nimport { moveAssets } from '$lib/services/assets/data/move';\nimport { getMovableAssets } from '$lib/services/assets/movable';\nimport { getAssetReferenceTarget } from '$lib/services/assets/reference-target';\nimport { getEntriesUsingTargets } from '$lib/services/assets/references';\nimport { createPath, foldFileName } from '$lib/services/utils/file';\n\n/**\n * @import { Asset, AssetFolderInfo, Entry } from '$lib/types/private';\n */\n\n/**\n * Get the entries using any of the given assets, each listed once, which a move updates.\n * @param {Asset[]} assets Assets.\n * @returns {Promise<Entry[]>} Entries.\n */\nexport const getAssetsUsedEntries = async (assets) =>\n  getEntriesUsingTargets(assets.map(getAssetReferenceTarget));\n\n/**\n * Get the names of the assets that can’t be moved to the given directory, because a file or folder\n * there already has the name, or another asset being moved along has it. A moved file would\n * overwrite another, and a Git tree can’t hold a file and a folder under one name.\n * @param {object} args Arguments.\n * @param {Asset[]} args.assets Assets to be moved.\n * @param {string} args.dirPath Destination directory path.\n * @returns {string[]} File names, in the order of the assets.\n */\nexport const getAssetMoveConflicts = ({ assets, dirPath }) => {\n  // Case-insensitive, like an upload or a rename, since `Photo.jpg` and `photo.jpg` clash on a\n  // case-insensitive file system like macOS’s or Windows’s, and Unicode-normalized\n  const takenNames = new Set(getTakenNamesInDir(dirPath).map(foldFileName));\n  /** @type {Set<string>} */\n  const movingNames = new Set();\n  /** @type {Set<string>} */\n  const conflicts = new Set();\n\n  getMovableAssets({ assets, dirPath }).forEach(({ name }) => {\n    const foldedName = foldFileName(name);\n\n    if (takenNames.has(foldedName) || movingNames.has(foldedName)) {\n      conflicts.add(name);\n    }\n\n    movingNames.add(foldedName);\n  });\n\n  return [...conflicts];\n};\n\n/**\n * Move assets to a directory in another folder, or another directory of their own folder, while\n * updating the references to them in the entries, all in one commit. The assets already in the\n * directory are left where they are.\n * @param {object} args Arguments.\n * @param {Asset[]} args.assets Assets to be moved.\n * @param {AssetFolderInfo} args.folder Asset folder the directory belongs to.\n * @param {string} args.dirPath Destination directory path.\n * @throws {Error} When a file name is taken in the directory, an entry using the assets is\n * read-only, or the commit fails.\n */\nexport const moveAssetsToFolder = async ({ assets, folder, dirPath }) => {\n  const conflicts = getAssetMoveConflicts({ assets, dirPath });\n\n  if (conflicts.length) {\n    throw new Error(`These files already exist in the folder: ${conflicts.join(', ')}`);\n  }\n\n  const movingAssets = getMovableAssets({ assets, dirPath }).map((asset) => ({\n    asset,\n    path: createPath([dirPath, asset.name]),\n    folder,\n  }));\n\n  if (!movingAssets.length) {\n    return;\n  }\n\n  await moveAssets('move', movingAssets);\n};\n","import { assetUpdatesToast } from '$lib/services/assets/data';\nimport { prepareAssetChanges } from '$lib/services/assets/data/create';\nimport { updateStores as updateDeletedAssetStores } from '$lib/services/assets/data/delete';\nimport { planReferenceRewrite, saveReferenceChanges } from '$lib/services/assets/data/move';\nimport {\n  getAssetMoveConflicts,\n  getAssetsUsedEntries,\n  moveAssetsToFolder,\n} from '$lib/services/assets/data/move-to-folder';\nimport {\n  getCloudServicePath,\n  getFetchOptions,\n  selectedCloudService,\n} from '$lib/services/assets/external';\nimport {\n  externalAssetsToast,\n  fetchExternalAssetBlob,\n  loadExternalAssets,\n} from '$lib/services/assets/external/data';\nimport { getExternalAssetsUsedEntries } from '$lib/services/assets/external/details';\nimport {\n  moveFilesWithReferences,\n  planExternalReferenceRewrite,\n} from '$lib/services/assets/external/move';\nimport { formatFileName } from '$lib/services/assets/file-name';\nimport { getAssetBlob, getAssetPublicURL } from '$lib/services/assets/info';\nimport { getMovableAssets, getMovableExternalAssets } from '$lib/services/assets/movable';\nimport { leaveMovedAsset, replaceShownAssetPath } from '$lib/services/assets/navigation';\nimport { getAssetReferenceTarget } from '$lib/services/assets/reference-target';\nimport { assertOutsideCmsFolders } from '$lib/services/assets/reserved';\nimport { getRelativePath } from '$lib/services/assets/subfolders';\nimport { UPDATE_TOAST_DEFAULT_STATE } from '$lib/services/contents/collection/data';\nimport { createPath, getBaseName, getDirName, readBlobAsFile } from '$lib/services/utils/file';\nimport { runWithUndo } from '$lib/services/utils/undo';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * AssetMoveDestination,\n * AssetMoveRequest,\n * Entry,\n * ExternalAsset,\n * FileChange,\n * MediaLibraryService,\n * } from '$lib/types/private';\n * @import { ReferenceRewritePlan } from '$lib/services/assets/data/move';\n */\n\n/**\n * Where files are moved to: a directory in a repository asset folder, or a folder on a cloud\n * storage service, an empty path being its root.\n * @typedef {{ folder: AssetFolderInfo, service?: undefined, dirPath: string } | {\n * service: MediaLibraryService, folder?: undefined, dirPath: string }} TransferDestination\n */\n\n/**\n * Delete files from a cloud storage service, without letting a failure get in the way: the files\n * have been copied by then, so the move itself has succeeded.\n * @param {MediaLibraryService} service Service.\n * @param {ExternalAsset[]} assets Files to delete.\n * @returns {Promise<boolean>} Whether the files have been deleted.\n */\nconst deleteQuietly = async (service, assets) => {\n  try {\n    await service.delete?.(assets, getFetchOptions(service));\n\n    return true;\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n\n    return false;\n  }\n};\n\n/**\n * Read the given files one at a time. Reading them all at once would keep many file-system reads\n * in flight, which a browser refuses past a point, and every file in memory at the same time.\n * @template T\n * @param {T[]} items Files to read.\n * @param {(item: T) => Promise<File>} read Function reading a file.\n * @returns {Promise<File[]>} Files, in the same order.\n */\nconst readFiles = async (items, read) => {\n  /** @type {File[]} */\n  const files = [];\n\n  // eslint-disable-next-line no-restricted-syntax\n  for (const item of items) {\n    // eslint-disable-next-line no-await-in-loop\n    files.push(await read(item));\n  }\n\n  return files;\n};\n\n/**\n * Get the names of the files right in a folder on a cloud storage service, listed from the service\n * in full: the listing the folder tree was built from can stop short of the end on a service\n * holding many files, and a move onto a name missing from it would overwrite that file.\n * @param {MediaLibraryService} service Service, which can list a folder.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @returns {Promise<string[]>} File names.\n */\nconst getFileNamesInFolder = async (service, dirPath) => {\n  const { listFolder } = /** @type {Required<MediaLibraryService>} */ (service);\n  const { assets } = await listFolder(dirPath, getFetchOptions(service));\n\n  return assets\n    .map(({ description }) => description)\n    .filter((path) => getDirName(path) === dirPath)\n    .map(getBaseName);\n};\n\n/**\n * Upload files to a folder on a cloud storage service, which renames a file whose name is taken\n * there, then save the entries using them, pointing at the uploaded files, along with any other\n * changes. The files are uploaded one at a time, so each upload is known to belong to its file: a\n * service like Uploadcare takes several files in one request, but its response lists them in no\n * particular order. If an upload or the save fails, the files uploaded so far are deleted again.\n * @param {object} args Arguments.\n * @param {MediaLibraryService} args.service Service, which can upload and delete files.\n * @param {File[]} args.files Files.\n * @param {string} args.dirPath Folder path relative to the configured prefix.\n * @param {ReferenceRewritePlan} args.plan Entries using the files, in the same order.\n * @param {FileChange[]} [args.changes] Changes to other files, e.g. the repository files being\n * deleted.\n * @param {'uploadMedia' | 'deleteMedia'} args.commitType Commit type.\n * @returns {Promise<ExternalAsset[]>} Uploaded files, in the same order.\n */\nconst uploadFilesWithReferences = ({ service, files, dirPath, ...saveOptions }) => {\n  const { upload } = /** @type {Required<MediaLibraryService>} */ (service);\n  const fetchOptions = getFetchOptions(service);\n\n  return runWithUndo(\n    files.map((file) => ({\n      // eslint-disable-next-line jsdoc/require-jsdoc\n      run: async () => (await upload([file], { ...fetchOptions, dirPath }))[0],\n      // eslint-disable-next-line jsdoc/require-jsdoc\n      undo: async (uploadedAsset) => {\n        await service.delete?.([uploadedAsset], fetchOptions);\n      },\n    })),\n    (uploadedAssets) =>\n      saveReferenceChanges({\n        ...saveOptions,\n        newURLs: uploadedAssets.map(({ downloadURL }) => downloadURL),\n      }),\n  );\n};\n\n/**\n * Report a successful move.\n * @param {number} count Number of files moved.\n */\nconst reportMoved = (count) => {\n  assetUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, moved: true, count };\n};\n\n/**\n * Move repository assets to a cloud storage service: upload them, then delete them from the\n * repository while pointing the entries using them at the uploaded files, in one commit. The\n * uploaded files are deleted again if an upload or the commit fails, so nothing is left behind. A\n * file whose name is taken in the folder on the service is renamed, as an upload is.\n * @param {object} args Arguments.\n * @param {Asset[]} args.assets Assets to move.\n * @param {MediaLibraryService} args.service Service to move them to.\n * @param {string} args.dirPath Folder on the service, relative to the configured prefix. An empty\n * string for the root.\n * @throws {Error} When an entry using the assets is read-only, or the upload or the commit fails.\n */\nexport const moveAssetsToService = async ({ assets, service, dirPath }) => {\n  assertOutsideCmsFolders(assets.map(({ path }) => path));\n\n  // Refused up front if a read-only entry uses an asset, before anything is uploaded\n  const plan = await planReferenceRewrite(assets.map(getAssetReferenceTarget));\n\n  const files = await readFiles(assets, async (asset) =>\n    readBlobAsFile(await getAssetBlob(asset), asset.name),\n  );\n\n  await uploadFilesWithReferences({\n    service,\n    files,\n    dirPath,\n    plan,\n    // The assets are deleted from the repository in the same commit as the entries are updated\n    changes: assets.map(({ path, sha }) => ({ action: 'delete', path, previousSha: sha })),\n    commitType: 'deleteMedia',\n  });\n\n  updateDeletedAssetStores({ assets, notify: false });\n  reportMoved(assets.length);\n};\n\n/**\n * Move files on a cloud storage service to another folder on the same service, with its own move\n * operation, renaming a file whose name is taken there. The entries using the files are updated.\n * If a move or the update fails, the files moved so far are moved back.\n * @param {object} args Arguments.\n * @param {ExternalAsset[]} args.assets Files to move.\n * @param {MediaLibraryService} args.service Service.\n * @param {string} args.dirPath Folder to move them to.\n * @param {ReferenceRewritePlan} args.plan Entries using the files, found before they were moved.\n */\nconst moveWithinService = async ({ assets, service, dirPath, plan }) => {\n  const names = await getFileNamesInFolder(service, dirPath);\n\n  await moveFilesWithReferences({\n    service,\n    moves: assets.map((asset) => {\n      const name = formatFileName(asset.fileName, { assetNamesInSameFolder: names });\n\n      names.push(name);\n\n      return { asset, path: createPath([dirPath, name]) };\n    }),\n    plan,\n  });\n};\n\n/**\n * Copy files on a cloud storage service to the repository or to another service, pointing the\n * entries using them at the copies. A copy uploaded to another service is deleted again if the\n * entries can’t be saved.\n * @param {object} args Arguments.\n * @param {ExternalAsset[]} args.assets Files to copy.\n * @param {TransferDestination} args.destination Where to copy them to.\n * @param {ReferenceRewritePlan} args.plan Entries using the files, found before they were moved.\n */\nconst copyFromService = async ({ assets, destination, plan }) => {\n  // A file on a cloud storage service is only available at its public URL, so the service has to\n  // allow cross-origin requests\n  const files = await readFiles(assets, async (asset) =>\n    readBlobAsFile(await fetchExternalAssetBlob(asset), asset.fileName),\n  );\n\n  if (destination.service) {\n    const { service, dirPath } = destination;\n\n    await uploadFilesWithReferences({ service, files, dirPath, plan, commitType: 'uploadMedia' });\n\n    return;\n  }\n\n  const { folder, dirPath } = destination;\n\n  // Named the way an upload to the folder is, which renames a file whose name is taken there\n  const { savingAssets, changes } = prepareAssetChanges({\n    folder,\n    subfolderPath: getRelativePath(dirPath, /** @type {string} */ (folder.internalPath)),\n    files,\n  });\n\n  await saveReferenceChanges({\n    plan,\n    newURLs: savingAssets.map(\n      (asset) =>\n        /** @type {string} */ (getAssetPublicURL(asset, { pathOnly: true, allowSpecial: true })),\n    ),\n    changes,\n    savingAssets,\n    commitType: 'uploadMedia',\n  });\n};\n\n/**\n * Move files on a cloud storage service to a repository folder, to another folder on the same\n * service, or to another service, updating the entries that use them. A file is first copied to\n * the destination, then the entries are saved, then the original is deleted, so a failure along\n * the way never leaves an entry pointing at a file that’s gone. If only the deletion fails, the\n * move has still succeeded, and a warning says the originals are left on the service.\n * @param {object} args Arguments.\n * @param {ExternalAsset[]} args.assets Files to move.\n * @param {MediaLibraryService} args.service Service the files are on.\n * @param {TransferDestination} args.destination Where to move them to.\n * @throws {Error} When an entry using the files is read-only, or the copy or the commit fails.\n */\nexport const moveExternalAssets = async ({ assets, service, destination }) => {\n  const sameService = destination.service?.serviceId === service.serviceId;\n  const movingAssets = getMovableExternalAssets({ assets, service, destination });\n\n  if (!movingAssets.length) {\n    return;\n  }\n\n  // Refused up front if the entries using a file can’t be updated, before anything is copied\n  const plan = await planExternalReferenceRewrite(movingAssets);\n\n  if (sameService) {\n    await moveWithinService({\n      assets: movingAssets,\n      service,\n      dirPath: destination.dirPath,\n      plan,\n    });\n  } else {\n    await copyFromService({ assets: movingAssets, destination, plan });\n\n    if (!(await deleteQuietly(service, movingAssets))) {\n      externalAssetsToast.current = {\n        show: true,\n        status: 'warning',\n        message: 'asset_move_cleanup_failed',\n      };\n    }\n  }\n\n  if (selectedCloudService.current?.serviceId === service.serviceId) {\n    await loadExternalAssets(service);\n  }\n\n  reportMoved(movingAssets.length);\n};\n\n/**\n * Get what moving the requested files to a destination would do: how many files would actually\n * move, and the names of those that can’t, as a file of the same name is in a repository directory.\n * A file moved to a cloud storage service, or from one, is renamed instead, as an upload is.\n * @param {AssetMoveRequest} request Files to move.\n * @param {AssetMoveDestination} destination Destination.\n * @returns {{ movableCount: number, conflicts: string[] }} Summary.\n */\nexport const getMoveSummary = ({ assets = [], externalAssets = [], service }, destination) => {\n  if (service) {\n    return {\n      movableCount: getMovableExternalAssets({\n        assets: externalAssets,\n        service,\n        destination,\n      }).length,\n      conflicts: [],\n    };\n  }\n\n  if (destination.service) {\n    return { movableCount: assets.length, conflicts: [] };\n  }\n\n  const { dirPath } = destination;\n\n  return {\n    movableCount: getMovableAssets({ assets, dirPath }).length,\n    conflicts: getAssetMoveConflicts({ assets, dirPath }),\n  };\n};\n\n/**\n * Get the entries using any of the requested files, each listed once, which a move updates.\n * @param {AssetMoveRequest} request Files to move.\n * @returns {Promise<Entry[]>} Entries.\n */\nexport const getMoveRequestUsedEntries = ({ assets = [], externalAssets = [], service }) =>\n  service ? getExternalAssetsUsedEntries(externalAssets) : getAssetsUsedEntries(assets);\n\n/**\n * Move the requested files to a destination: a repository directory or a folder on a cloud storage\n * service, whichever the files are in now.\n * @param {AssetMoveRequest} request Files to move.\n * @param {AssetMoveDestination} destination Destination.\n * @throws {Error} When the move fails.\n */\nexport const moveToDestination = async (\n  { assets = [], externalAssets = [], service },\n  destination,\n) => {\n  if (service) {\n    await moveExternalAssets({ assets: externalAssets, service, destination });\n  } else if (destination.service) {\n    await moveAssetsToService({\n      assets,\n      service: destination.service,\n      dirPath: destination.dirPath,\n    });\n  } else {\n    await moveAssetsToFolder({ assets, folder: destination.folder, dirPath: destination.dirPath });\n  }\n};\n\n/**\n * Update the details view once the requested files have been moved, if it shows one of them. An\n * asset moved within the repository is followed to its new path; one moved to or from a cloud\n * storage service has no details view at the same place any more, so the list it’s been moved out\n * of is shown instead.\n * @param {AssetMoveRequest} request Files that have been moved.\n * @param {AssetMoveDestination} destination Destination.\n */\nexport const followMovedAssets = async (\n  { assets = [], externalAssets = [], service },\n  destination,\n) => {\n  if (service) {\n    const listPath = getCloudServicePath(service);\n    // A file already in the folder has stayed where it was\n    const movedAssets = getMovableExternalAssets({ assets: externalAssets, service, destination });\n\n    await Promise.all(movedAssets.map(({ id }) => leaveMovedAsset(`${listPath}/${id}`, listPath)));\n  } else if (destination.service) {\n    await Promise.all(\n      assets.map(({ path }) => leaveMovedAsset(`/assets/${path}`, `/assets/${getDirName(path)}`)),\n    );\n  } else {\n    await Promise.all(\n      assets.map(({ path, name }) =>\n        replaceShownAssetPath(path, createPath([destination.dirPath, name])),\n      ),\n    );\n  }\n};\n","import { compare } from '@sveltia/utils/string';\n\nimport {\n  enabledCloudServices,\n  externalAssets,\n  externalFolders,\n  getFetchOptions,\n  selectedCloudService,\n} from '$lib/services/assets/external';\nimport { canMoveToService } from '$lib/services/assets/movable';\nimport { getBaseName, getDirName } from '$lib/services/utils/file';\n\n/**\n * @import {\n * AssetMoveDestination,\n * ExternalFolderListing,\n * MediaLibraryService,\n * } from '$lib/types/private';\n */\n\n/**\n * Get the cloud storage services files can be moved to, as {@link canMoveToService} tells.\n * @returns {MediaLibraryService[]} Services.\n */\nexport const getMoveTargetServices = () => enabledCloudServices.current.filter(canMoveToService);\n\n/**\n * Build the folder tree of a service from the paths of its files and its empty folders.\n * @param {MediaLibraryService} service Service.\n * @param {ExternalFolderListing} listing Files and empty folders on the service.\n * @returns {AssetMoveDestination} Destination for the service root, with the folders below it.\n */\nexport const buildServiceFolderTree = (service, { assets, folders }) => {\n  /** @type {Set<string>} */\n  const dirPaths = new Set(['']);\n\n  /**\n   * Register a folder and every folder above it.\n   * @param {string} dirPath Folder path.\n   */\n  const addFolder = (dirPath) => {\n    if (!dirPaths.has(dirPath)) {\n      dirPaths.add(dirPath);\n      addFolder(getDirName(dirPath));\n    }\n  };\n\n  // The path of a file on a service with folder support is its description\n  assets.forEach(({ description }) => addFolder(getDirName(description)));\n  folders.forEach(addFolder);\n\n  /**\n   * Create the destination for a folder, with its subfolders.\n   * @param {string} dirPath Folder path.\n   * @returns {AssetMoveDestination} Destination.\n   */\n  const createDestination = (dirPath) => ({\n    service,\n    dirPath,\n    label: dirPath ? getBaseName(dirPath) : service.serviceLabel,\n    children: [...dirPaths]\n      .filter((path) => path && getDirName(path) === dirPath)\n      .sort(compare)\n      .map(createDestination),\n  });\n\n  return createDestination('');\n};\n\n/**\n * Get the listing of a service to build its folder tree from. The listing of the service being\n * browsed is at hand; any other service is listed now. A service without folder support has its\n * root only, and so does one that can’t be listed, as the files can still be uploaded there.\n * @param {MediaLibraryService} service Service.\n * @returns {Promise<ExternalFolderListing>} Files and empty folders.\n */\nconst getListing = async (service) => {\n  if (!service.browse) {\n    return { assets: [], folders: [] };\n  }\n\n  if (selectedCloudService.current === service && externalAssets.current) {\n    return { assets: externalAssets.current, folders: externalFolders.current };\n  }\n\n  try {\n    return await service.browse(getFetchOptions(service));\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n\n    return { assets: [], folders: [] };\n  }\n};\n\n/**\n * Get the cloud storage services files can be moved to, each with its folders as a tree.\n * @returns {Promise<AssetMoveDestination[]>} Destinations, one per service.\n */\nexport const getExternalMoveDestinations = async () =>\n  Promise.all(\n    getMoveTargetServices().map(async (service) =>\n      buildServiceFolderTree(service, await getListing(service)),\n    ),\n  );\n","<!--\n  @component\n  Move dialog of the Asset Library, opened for the files set as `assetMoveRequest`: repository\n  assets, or files on a cloud storage service. They are moved to the folder picked in the tree, or\n  the one they have been dropped on, which can be in the repository or on a cloud storage service,\n  and the entries using them are updated.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Dialog, Tree } from '@sveltia/ui';\n\n  import MoveDestinationTreeItem from '$lib/components/assets/list/internal/move-destination-tree-item.svelte';\n  import { runAssetCommit } from '$lib/services/assets/data/commit';\n  import { getMoveBlockedMessage } from '$lib/services/assets/data/move';\n  import {\n    findAssetMoveDestination,\n    getAssetMoveDestinations,\n    getMoveDestinationKey,\n  } from '$lib/services/assets/data/move-destinations';\n  import {\n    followMovedAssets,\n    getMoveRequestUsedEntries,\n    getMoveSummary,\n    moveToDestination,\n  } from '$lib/services/assets/data/transfer';\n  import { getExternalMoveDestinations } from '$lib/services/assets/external/destinations';\n  import { assetMoveRequest } from '$lib/services/assets/state';\n  import { createUsedEntriesState } from '$lib/services/assets/used-entries.svelte';\n  import { watchAsync } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { AssetMoveDestination } from '$lib/types/private';\n   */\n\n  let open = $state(false);\n  /**\n   * Cloud storage services, each with its folders, which are listed once the dialog has opened.\n   * @type {AssetMoveDestination[]}\n   */\n  let externalDestinations = $state.raw([]);\n  /** @type {AssetMoveDestination | undefined} */\n  let destination = $state.raw();\n\n  const request = $derived(assetMoveRequest.current);\n  /* v8 ignore start -- these are only read while the dialog is open, which takes a request */\n  const count = $derived((request?.assets ?? request?.externalAssets ?? []).length);\n  const firstName = $derived(\n    request?.assets?.[0]?.name ?? request?.externalAssets?.[0]?.fileName ?? '',\n  );\n  const title = $derived(_('move_assets_title', { values: { count, name: firstName } }));\n  const destinations = $derived(\n    request ? [...getAssetMoveDestinations(), ...externalDestinations] : [],\n  );\n  /* v8 ignore stop */\n  /**\n   * Select the folder picked up front, by dropping the files on it, once it’s in the tree.\n   */\n  const selectRequestedDestination = () => {\n    if (request?.dirPath !== undefined && !destination) {\n      destination = findAssetMoveDestination(destinations, request.dirPath, request.serviceId);\n    }\n  };\n\n  /**\n   * Entries using the files, found before the dialog opens, so it can tell how many will be\n   * updated. Another request can come in before they are found, which the state takes care of.\n   */\n  const usedEntries = createUsedEntriesState(\n    () => (request ? getMoveRequestUsedEntries(request) : undefined),\n    () => {\n      destination = undefined;\n      // A folder at the repository root has an empty path\n      selectRequestedDestination();\n      open = true;\n    },\n  );\n\n  const summary = $derived(\n    request && destination\n      ? getMoveSummary(request, destination)\n      : { movableCount: 0, conflicts: /** @type {string[]} */ ([]) },\n  );\n  // A read-only entry using the files can’t be updated along with the move, so the move is refused\n  // up front rather than when it’s about to be committed\n  const blockedMessage = $derived(getMoveBlockedMessage(usedEntries.entries ?? []));\n  const error = $derived(\n    summary.conflicts.length\n      ? _('asset_move_conflict', { values: { names: summary.conflicts.join(', ') } })\n      : undefined,\n  );\n\n  /**\n   * Move the files to the selected folder, then update the details view if it shows one of them.\n   */\n  const move = async () => {\n    /* v8 ignore next 3 -- the OK button is disabled until a folder is selected */\n    if (!request || !destination) {\n      return;\n    }\n\n    // Kept, as closing the dialog lets go of the request. Not a snapshot, which would clone the\n    // service, whose methods can’t be cloned\n    const _request = request;\n    const _destination = destination;\n\n    const { ok } = await runAssetCommit(() => moveToDestination(_request, _destination), {\n      progress: 'moving_assets',\n      failure: 'moving_assets_failed',\n    });\n\n    if (ok) {\n      await followMovedAssets(_request, _destination);\n    }\n  };\n\n  // List the cloud storage services alongside, which takes a request to each one that isn’t\n  // being browsed\n  watchAsync(\n    () => {\n      // Let go of the folders listed for an earlier request, which may have changed since\n      externalDestinations = [];\n\n      return request ? getExternalMoveDestinations() : undefined;\n    },\n    (result) => {\n      externalDestinations = result;\n      selectRequestedDestination();\n    },\n  );\n</script>\n\n<Dialog\n  {title}\n  bind:open\n  okLabel={_('move')}\n  okDisabled={!!blockedMessage || !summary.movableCount || !!error}\n  onOk={() => {\n    // Don’t wait for the commit; the toast reports how it goes\n    move();\n  }}\n  onClose={() => {\n    assetMoveRequest.current = undefined;\n  }}\n>\n  {#if blockedMessage}\n    <p role=\"alert\">{blockedMessage}</p>\n  {:else}\n    <p>\n      {_('select_asset_move_destination', { values: { count: usedEntries.entries?.length ?? 0 } })}\n    </p>\n    <Tree ariaLabel={_('asset_move_destination')} class=\"destination-tree\">\n      {#each destinations as item (getMoveDestinationKey(item))}\n        <MoveDestinationTreeItem\n          destination={item}\n          selectedDestination={destination}\n          onSelectDestination={(selected) => {\n            destination = selected;\n          }}\n        />\n      {/each}\n    </Tree>\n    <div role=\"alert\" class={['message', { error: !!error }]}>\n      {#if error}\n        {error}\n      {:else if destination && !summary.movableCount}\n        {_('assets_already_in_folder', { values: { count } })}\n      {/if}\n    </div>\n  {/if}\n</Dialog>\n\n<style>\n  p {\n    margin: 0 0 8px;\n  }\n\n  .message {\n    margin: 8px 0 0;\n    min-height: 1lh;\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n\n    &.error {\n      color: var(--sui-error-foreground-color);\n    }\n  }\n\n  :global(.destination-tree) {\n    border: 1px solid var(--sui-control-border-color);\n    border-radius: var(--sui-control-medium-border-radius);\n    max-height: 50vh;\n    overflow: auto;\n  }\n</style>\n","<!--\n  @component\n  New Folder dialog of the Asset Library, which creates a subfolder in the directory being browsed.\n-->\n<script>\n  import CreateSubfolderDialog from '$lib/components/assets/list/create-subfolder-dialog.svelte';\n  import { browsedDirPath, getTakenNames } from '$lib/services/assets/subfolders';\n  import {\n    listedAssets,\n    listedSubfolders,\n    showNewSubfolderDialog,\n  } from '$lib/services/assets/view';\n\n  /**\n   * Names already taken in the directory, by a subfolder, a file or a folder leading to another\n   * asset folder nested in it.\n   */\n  const takenNames = $derived(\n    getTakenNames({\n      subfolders: listedSubfolders.current,\n      fileNames: listedAssets.current.map(({ name }) => name),\n      dirPath: browsedDirPath.current,\n    }),\n  );\n</script>\n\n<CreateSubfolderDialog\n  bind:open={showNewSubfolderDialog.current}\n  dirPath={browsedDirPath.current ?? ''}\n  {takenNames}\n/>\n","<!--\n  @component\n  New Folder button for a repository folder, which opens the New Folder dialog. Only rendered when\n  the folder can be browsed by subfolder.\n-->\n<script>\n  import NewFolderButton from '$lib/components/assets/list/new-folder-button.svelte';\n  import { assetsLocked, canCreateAsset, selectedAssetFolder } from '$lib/services/assets/folders';\n  import { browsingCmsFolder, canBrowseSubfolders } from '$lib/services/assets/subfolders';\n  import { showNewSubfolderDialog } from '$lib/services/assets/view';\n\n  const folder = $derived(selectedAssetFolder.current);\n  // Creating a folder commits straight to the configured branch rather than going through review,\n  // so it’s not something an Open Authoring contributor or a user who can’t push to the branch can\n  // do, just like uploading. Nor can anything be added to a folder the CMS itself is served from\n  const disabled = $derived(\n    assetsLocked.current || !canCreateAsset(folder) || browsingCmsFolder.current,\n  );\n</script>\n\n{#if canBrowseSubfolders(folder)}\n  <NewFolderButton\n    {disabled}\n    onclick={() => {\n      showNewSubfolderDialog.current = true;\n    }}\n  />\n{/if}\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Infobar } from '@sveltia/ui';\n\n  import DownloadAssetsButton from '$lib/components/assets/list/download-assets-button.svelte';\n  import CopyAssetsButton from '$lib/components/assets/list/internal/copy-assets-button.svelte';\n  import DeleteAssetsButton from '$lib/components/assets/list/internal/delete-assets-button.svelte';\n  import EditOptionsButton from '$lib/components/assets/list/internal/edit-options-button.svelte';\n  import NewFolderButton from '$lib/components/assets/list/internal/new-folder-button.svelte';\n  import UploadAssetsButton from '$lib/components/assets/list/internal/upload-assets-button.svelte';\n  import PreviewAssetButton from '$lib/components/assets/list/preview-asset-button.svelte';\n  import PrimaryToolbar from '$lib/components/assets/list/primary-toolbar.svelte';\n  import { goBack, goto } from '$lib/services/app/navigation';\n  import {\n    assetsLocked,\n    canCreateAsset,\n    selectedAssetFolder,\n    targetAssetFolder,\n  } from '$lib/services/assets/folders';\n  import { getAssetBlob } from '$lib/services/assets/info';\n  import { canPreviewAsset } from '$lib/services/assets/kinds';\n  import { getAssetFolderHistoryState } from '$lib/services/assets/navigation';\n  import { focusedAsset, selectedOrFocusedAssets } from '$lib/services/assets/state';\n  import { browsingCmsFolder, selectedSubfolderPath } from '$lib/services/assets/subfolders';\n  import { getFolderLabelByCollection, listedAssets } from '$lib/services/assets/view';\n  import { lockedBranch } from '$lib/services/backends/branch-access';\n  import { getReadonlyMessage, isViewer } from '$lib/services/config/readonly';\n  import { env } from '$lib/services/user/env.svelte';\n  import { createPath } from '$lib/services/utils/file';\n  import { encodePathSegments } from '$lib/services/utils/url';\n\n  const folder = $derived(selectedAssetFolder.current);\n  // `appLocale.current` is a key, because `getFolderLabelByCollection` can return a localized label\n  const folderLabel = $derived(\n    appLocale.current && folder ? getFolderLabelByCollection(folder) : '',\n  );\n  /** Names of the subfolders leading to the one being browsed, from the folder root down. */\n  const subfolderNames = $derived(\n    selectedSubfolderPath.current ? selectedSubfolderPath.current.split('/') : [],\n  );\n  const asset = $derived(focusedAsset.current);\n\n  const assets = $derived(selectedOrFocusedAssets.current);\n  // The folder is read-only with the `readonly` option, or all the assets are because the user\n  // can’t push to the configured branch or is a viewer\n  const readonly = $derived(!!folder?.readonly || !!lockedBranch.current || isViewer());\n\n  // Uploading to the media library commits straight to the configured branch rather than going\n  // through review, so it’s not something an Open Authoring contributor or a user who can’t push to\n  // the branch can do. An asset attached to an entry is committed with that entry, so it’s\n  // unaffected. Nor can anything be added to a folder the CMS itself is served from\n  const uploadDisabled = $derived(\n    assetsLocked.current || !canCreateAsset(targetAssetFolder.current) || browsingCmsFolder.current,\n  );\n\n  /**\n   * Browse an ancestor of the subfolder being browsed. The selected asset folder travels as history\n   * state, the same way it does from the sidebar, so the page can tell it from another folder\n   * sharing its path.\n   * @param {number} depth How many subfolder names to keep, `0` being the folder root.\n   * @param {boolean} back Whether to go back in the history if the ancestor is the previous page,\n   * as the back button on small screens does.\n   */\n  const browseAncestor = (depth, back) => {\n    const path = encodePathSegments(\n      `/assets/${createPath([folder?.internalPath, ...subfolderNames.slice(0, depth)])}`,\n    );\n\n    const options = { transitionType: /** @type {const} */ ('backwards'), state: { folder } };\n\n    if (back) {\n      goBack(path, options);\n    } else {\n      goto(path, options);\n    }\n  };\n</script>\n\n{#if readonly}\n  <Infobar\n    dismissible={false}\n    --sui-infobar-border-width=\"0 0 1px\"\n    --sui-infobar-message-justify-content=\"center\"\n  >\n    {getReadonlyMessage('asset_folder', { folder })}\n  </Infobar>\n{/if}\n<PrimaryToolbar rootLabel={folderLabel} {subfolderNames} onBrowse={browseAncestor}>\n  {#snippet actions()}\n    <PreviewAssetButton\n      path={asset ? encodePathSegments(`/assets/${asset.path}`) : undefined}\n      disabled={!asset || !canPreviewAsset(asset)}\n      state={getAssetFolderHistoryState()}\n    />\n    <CopyAssetsButton assets={asset ? [asset] : []} />\n    <DownloadAssetsButton {assets} getName={(a) => a.name} getBlob={getAssetBlob} />\n    <DeleteAssetsButton {assets} listedCount={listedAssets.current.length} />\n    <EditOptionsButton {asset} {assets} />\n  {/snippet}\n  {#snippet fab()}\n    <!-- A folder-level action like Upload, so it sits with the Upload button on every screen size\n    rather than with the asset actions, which are hidden on medium screens -->\n    <NewFolderButton />\n    {#if !env.isSmallScreen || (listedAssets.current.length && !uploadDisabled)}\n      <UploadAssetsButton label={env.isSmallScreen ? undefined : _('upload')} />\n    {/if}\n  {/snippet}\n</PrimaryToolbar>\n","<script>\n  import { getPathInfo } from '@sveltia/utils/file';\n\n  import RenameDialog from '$lib/components/assets/list/rename-dialog.svelte';\n  import { getAssetsByDirName } from '$lib/services/assets';\n  import { runAssetCommit } from '$lib/services/assets/data/commit';\n  import { getMoveBlockedMessage, moveAssets } from '$lib/services/assets/data/move';\n  import { getAssetUsedEntries } from '$lib/services/assets/details';\n  import { replaceShownAssetPath } from '$lib/services/assets/navigation';\n  import { renamingAsset } from '$lib/services/assets/state';\n  import { getFolderNamesInDir, getNonAssetFileNamesInDir } from '$lib/services/assets/subfolders';\n  import { createUsedEntriesState } from '$lib/services/assets/used-entries.svelte';\n  import { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\n  import { createPath } from '$lib/services/utils/file';\n\n  let open = $state(false);\n\n  const asset = $derived(renamingAsset.current);\n  /**\n   * Entries using the asset, which are updated along with the rename. The dialog opens once they\n   * have been found. Another asset can be renamed before then, which the state takes care of.\n   */\n  const usedEntries = createUsedEntriesState(\n    () => (asset ? getAssetUsedEntries(asset) : undefined),\n    () => {\n      open = true;\n    },\n  );\n  // A read-only entry using the asset can’t be updated along with the rename, so the rename is\n  // refused up front rather than when it’s about to be committed\n  const blockedMessage = $derived(getMoveBlockedMessage(usedEntries.entries ?? []));\n  const { dirname = '', basename = '' } = $derived(getPathInfo(asset?.path ?? ''));\n  /**\n   * Names of the other files next to the asset, and those of the subfolders there, which a file\n   * can’t take either.\n   */\n  const { otherNames, fileNames, folderNames } = $derived(\n    asset\n      ? {\n          otherNames: getAssetsByDirName(dirname)\n            .map((a) => a.name)\n            .filter((n) => n !== asset.name),\n          // An entry file next to the asset would be overwritten\n          fileNames: getNonAssetFileNamesInDir(dirname),\n          folderNames: getFolderNamesInDir(dirname),\n        }\n      : { otherNames: [], fileNames: [], folderNames: [] },\n  );\n\n  /**\n   * Rename the asset by moving it to a new path. Also, update the URL hash silently to reflect the\n   * new asset name if the rename dialog was opened in the asset details view.\n   * @param {string} newName New file name.\n   */\n  const renameAsset = async (newName) => {\n    /* v8 ignore next 3 -- the dialog is only shown for an asset */\n    if (!asset) {\n      return;\n    }\n\n    const oldPath = asset.path;\n    // An asset in a root media folder has no directory\n    const newPath = createPath([dirname, newName]);\n\n    const { ok } = await runAssetCommit(() => moveAssets('rename', [{ asset, path: newPath }]), {\n      failure: 'renaming_asset_failed',\n    });\n\n    if (ok) {\n      await replaceShownAssetPath(oldPath, newPath);\n    }\n  };\n</script>\n\n<RenameDialog\n  bind:open\n  name={basename}\n  {otherNames}\n  {fileNames}\n  {folderNames}\n  usedEntryCount={usedEntries.entries?.length}\n  {blockedMessage}\n  slugificationEnabled={getDefaultMediaLibraryOptions().config.slugify_filename}\n  onRename={renameAsset}\n  onClose={() => {\n    renamingAsset.current = undefined;\n  }}\n/>\n","<!--\n  @component\n  Rename Folder dialog of the Asset Library, opened for the subfolder set as `renamingSubfolder`.\n  Renaming moves every asset in the folder along, updating the entries using them.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import SubfolderNameDialog from '$lib/components/assets/list/subfolder-name-dialog.svelte';\n  import { runAssetCommit } from '$lib/services/assets/data/commit';\n  import { getSubfolderAssets, renameSubfolder } from '$lib/services/assets/data/subfolder';\n  import {\n    browsedDirPath,\n    getTakenNames,\n    renamingSubfolder,\n  } from '$lib/services/assets/subfolders';\n  import { listedAssets, listedSubfolders } from '$lib/services/assets/view';\n  import { createPath, getDirName } from '$lib/services/utils/file';\n\n  const subfolder = $derived(renamingSubfolder.current);\n  // Open while there’s a folder to act on. Closing the dialog writes `open` back, and the folder is\n  // let go of once the dialog has closed\n  let open = $derived(!!subfolder);\n  /* v8 ignore start -- these are only read while the dialog is open, which takes a folder */\n  const currentName = $derived(subfolder?.name ?? '');\n  /** Number of assets in the folder, at any depth, which will be moved along. */\n  const assetCount = $derived(subfolder ? getSubfolderAssets(subfolder.path).length : 0);\n  /* v8 ignore stop */\n  /**\n   * Names taken by the siblings of the folder, which it can’t take over, including the folders\n   * leading to another asset folder nested in the directory.\n   */\n  const takenNames = $derived(\n    getTakenNames({\n      subfolders: listedSubfolders.current,\n      fileNames: listedAssets.current.map(({ name }) => name),\n      exclude: currentName,\n      dirPath: browsedDirPath.current,\n    }),\n  );\n\n  /**\n   * Rename the folder.\n   * @param {string} newName New folder name.\n   */\n  const rename = (newName) => {\n    /* v8 ignore next 3 -- the dialog is only open for a folder */\n    if (!subfolder) {\n      return;\n    }\n\n    const { path } = subfolder;\n\n    runAssetCommit(\n      () => renameSubfolder({ dirPath: path, newDirPath: createPath([getDirName(path), newName]) }),\n      { progress: 'renaming_folder', failure: 'renaming_folder_failed' },\n    );\n  };\n</script>\n\n<SubfolderNameDialog\n  bind:open\n  title={_('rename_x', { values: { name: currentName } })}\n  okLabel={_('rename')}\n  description={_('enter_new_name_for_folder', { values: { count: assetCount } })}\n  name={currentName}\n  {takenNames}\n  onSubmit={(name) => {\n    rename(name);\n  }}\n  onClose={() => {\n    // The dialog is closed before the name is submitted, so the folder is let go of here rather\n    // than when `open` turns false\n    renamingSubfolder.current = undefined;\n  }}\n/>\n","import { goBack, goto, parseLocation } from '$lib/services/app/navigation';\nimport { searchMode, searchTerms } from '$lib/services/search';\nimport { isSearchResultsPath } from '$lib/services/search/navigation';\n\n/**\n * Path of the page the current search has started from, e.g. an asset folder or a collection, to\n * go back to once the search terms are cleared. `undefined` if the search results page has been\n * opened directly, e.g. by reloading it.\n * @type {string | undefined}\n */\nlet originPath = undefined;\n\n/**\n * Update the search terms typed in the quick search bar. Navigate to the search results page if\n * any terms are given, or back to the page the search has started from if they’re cleared.\n * @param {string} terms New search terms.\n */\nexport const updateSearchTerms = (terms) => {\n  const hadTerms = !!searchTerms.current;\n  const { path } = parseLocation();\n  const searching = isSearchResultsPath(path);\n\n  searchTerms.current = terms;\n\n  if (terms) {\n    if (!searching) {\n      originPath = path;\n    }\n\n    // Encode the terms, or a `?` or `#` would cut them short in the URL, and a stray `%` would make\n    // the path impossible to decode\n    goto(`/search/${encodeURIComponent(terms)}`, { replaceState: searching });\n  } else if (hadTerms && searching) {\n    // Without a known origin, go to the library being searched\n    goBack(originPath ?? (searchMode.current === 'assets' ? '/assets' : '/collections'));\n    originPath = undefined;\n  }\n};\n\n/**\n * Forget the current search once the search results have been left for another page, e.g. with the\n * browser’s Back button, so the search bar doesn’t keep showing terms that no longer apply. The\n * search is kept while an entry or an asset opened from the results is shown, as the user goes\n * back to the results from there. Call this whenever the URL hash changes.\n */\nexport const resetSearchAfterLeaving = () => {\n  if (isSearchResultsPath(parseLocation().path)) {\n    return;\n  }\n\n  /** @type {string | undefined} */\n  const from = window.history.state?.from;\n\n  if (from && isSearchResultsPath(parseLocation(from).path)) {\n    return;\n  }\n\n  originPath = undefined;\n\n  if (searchTerms.current) {\n    searchTerms.current = '';\n  }\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { SearchBar } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import { searchMode, searchTerms } from '$lib/services/search';\n  import { resetSearchAfterLeaving, updateSearchTerms } from '$lib/services/search/input';\n\n  /**\n   * @typedef {object} Props\n   * @property {(event: MouseEvent) => void} [onclick] `click` event handler.\n   */\n\n  /** @type {Props} */\n  let { onclick = undefined } = $props();\n\n  let inputValue = $state('');\n\n  $effect(() => {\n    const terms = searchTerms.current;\n\n    // Restore the search terms when the page is reloaded, or another page changes them. The input\n    // is left alone while it only differs by surrounding spaces, which the terms don’t keep\n    untrack(() => {\n      if (terms !== inputValue.trim()) {\n        inputValue = terms;\n      }\n    });\n  });\n</script>\n\n<svelte:window\n  onhashchange={() => {\n    resetSearchAfterLeaving();\n  }}\n/>\n\n<div role=\"none\" class=\"wrapper\">\n  {#if searchMode.current}\n    <SearchBar\n      bind:value={inputValue}\n      debounce\n      keyShortcuts=\"Accel+F\"\n      placeholder={_(`search_placeholder_${searchMode.current}`)}\n      aria-label={_(`search_placeholder_${searchMode.current}`)}\n      --sui-textbox-placeholder-text-align=\"center\"\n      {onclick}\n      oninput={({ target }) => {\n        // @todo Implement quick search dropdown.\n        updateSearchTerms(/** @type {HTMLInputElement} */ (target).value.trim());\n      }}\n      onClear={() => {\n        updateSearchTerms('');\n      }}\n    />\n  {/if}\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n    --sui-textbox-border-width: 0;\n  }\n</style>\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Divider, Icon, Listbox, Option, OptionGroup } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import equal from 'fast-deep-equal';\n\n  import QuickSearchBar from '$lib/components/global/toolbar/items/quick-search-bar.svelte';\n  import { appNumberFormatter } from '$lib/services/app/i18n';\n  import { goto } from '$lib/services/app/navigation';\n  import { countAssetsInFolder } from '$lib/services/assets';\n  import { createAssetDropTarget } from '$lib/services/assets/drag';\n  import {\n    enabledCloudServices,\n    externalAssetCounts,\n    getCloudServicePath,\n    selectedCloudService,\n  } from '$lib/services/assets/external';\n  import { linkedAssets, linkedFilesService } from '$lib/services/assets/external/linked';\n  import { getAssetFolderKey, selectedAssetFolder } from '$lib/services/assets/folders';\n  import { allAssets } from '$lib/services/assets/state';\n  import { selectedSubfolderPath } from '$lib/services/assets/subfolders';\n  import { getFolderLabelByCollection } from '$lib/services/assets/view';\n  import { getAssetFolderIcon, getListedAssetFolders } from '$lib/services/assets/view/folder-list';\n  import { env } from '$lib/services/user/env.svelte';\n  import { encodePathSegments } from '$lib/services/utils/url';\n\n  /**\n   * @import { AssetFolderInfo } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [isSearchPage] Whether the current page is the search results page.\n   */\n\n  /** @type {Props} */\n  let { isSearchPage = false } = $props();\n\n  /* v8 ignore start -- the app locale is loaded before the sidebar is rendered */\n  /**\n   * Get the label of a folder, which follows the app locale.\n   * @param {AssetFolderInfo} folder Folder.\n   * @returns {string} Label.\n   */\n  const getFolderLabel = (folder) => (appLocale.current ? getFolderLabelByCollection(folder) : '');\n  /* v8 ignore stop */\n\n  // All Assets, Global Assets, then collection-level, file-level folders and asset collections,\n  // sorted by appearance order in the config\n  const folders = $derived(getListedAssetFolders());\n\n  /**\n   * Whether to show a divider after the folder at the given index.\n   * @param {number} index Index of the folder to check.\n   * @returns {boolean} Whether to show a divider after the folder at the given index.\n   */\n  const shouldShowDivider = (index) =>\n    (folders[index].collectionName === undefined &&\n      folders[index + 1]?.collectionName !== undefined) ||\n    (!folders[index].isAssetCollection && !!folders[index + 1]?.isAssetCollection);\n</script>\n\n<nav class=\"primary-sidebar\" aria-label={_('assets')}>\n  {#if env.isSmallScreen}\n    <header>\n      <h2>{_('assets')}</h2>\n    </header>\n    <QuickSearchBar\n      onclick={(event) => {\n        event.preventDefault();\n        goto('/search');\n      }}\n    />\n  {/if}\n  <Listbox\n    ariaLabel={_('asset_folder_list')}\n    aria-controls={isSearchPage || env.isSmallScreen ? undefined : 'assets-container'}\n  >\n    {#if folders.length}\n      <OptionGroup label={_('asset_location.repository')}>\n        {#each folders as folder, index (getAssetFolderKey(folder))}\n          {#await sleep() then}\n            {@const { internalPath } = folder}\n            {@const selected = equal(selectedAssetFolder.current, folder)}\n            <Option\n              selected={env.isSmallScreen || isSearchPage ? false : selected}\n              label={getFolderLabel(folder)}\n              onSelect={() => {\n                goto(encodePathSegments(`/assets/${internalPath ?? '-/all'}`), {\n                  transitionType: 'forwards',\n                  // An internal path can be shared by multiple collections, files and fields. Pass\n                  // the folder info as history state so we can distinguish these different asset\n                  // folders while keeping the URL clean.\n                  state: { folder },\n                });\n              }}\n              onclick={() => {\n                // Selecting the folder already selected doesn’t fire `onSelect` again, but a click\n                // on it while one of its subfolders is browsed should still lead back to its root\n                if (selected && selectedSubfolderPath.current) {\n                  goto(encodePathSegments(`/assets/${internalPath}`), {\n                    transitionType: 'backwards',\n                    state: { folder },\n                  });\n                }\n              }}\n              {@attach internalPath !== undefined &&\n                createAssetDropTarget({ folder, dirPath: internalPath })}\n            >\n              {#snippet startIcon()}\n                <Icon name={getAssetFolderIcon(folder)} />\n              {/snippet}\n              {#snippet endIcon()}\n                {#key allAssets.current}\n                  {#await sleep() then}\n                    {@const count =\n                      internalPath !== undefined\n                        ? countAssetsInFolder(folder)\n                        : allAssets.current.length}\n                    <span class=\"count\" aria-label=\"({_('x_assets', { values: { count } })})\">\n                      {appNumberFormatter.current.format(count)}\n                    </span>\n                  {/await}\n                {/key}\n              {/snippet}\n            </Option>\n          {/await}\n          {#if shouldShowDivider(index)}\n            <Divider />\n          {/if}\n        {/each}\n      </OptionGroup>\n    {/if}\n    <!-- Hide the group if there is nothing to show: no external location and no linked file -->\n    {#if enabledCloudServices.current.length || linkedAssets.current.length}\n      <OptionGroup label={_('asset_location.external')}>\n        {#each enabledCloudServices.current as service (service.serviceId)}\n          {@const { serviceId, serviceLabel } = service}\n          <!-- The count is known once the service has been listed; Cloudinary is never listed -->\n          {@const count = externalAssetCounts.current[serviceId]}\n          <Option\n            selected={env.isSmallScreen || isSearchPage\n              ? false\n              : selectedCloudService.current?.serviceId === serviceId}\n            label={serviceLabel}\n            onSelect={() => {\n              goto(getCloudServicePath(service), { transitionType: 'forwards' });\n            }}\n            {@attach createAssetDropTarget({ service, dirPath: '' })}\n          >\n            {#snippet startIcon()}\n              <Icon name=\"cloud\" />\n            {/snippet}\n            {#snippet endIcon()}\n              {#if count !== undefined}\n                <span class=\"count\" aria-label=\"({_('x_assets', { values: { count } })})\">\n                  {appNumberFormatter.current.format(count)}\n                </span>\n              {/if}\n            {/snippet}\n          </Option>\n        {/each}\n        <!-- Files linked from entries by URL, which can be browsed but not managed -->\n        {@const linkedCount = linkedAssets.current.length}\n        <Option\n          selected={env.isSmallScreen || isSearchPage\n            ? false\n            : selectedCloudService.current?.serviceId === linkedFilesService.serviceId}\n          label={linkedFilesService.serviceLabel}\n          onSelect={() => {\n            goto(getCloudServicePath(linkedFilesService), { transitionType: 'forwards' });\n          }}\n        >\n          {#snippet startIcon()}\n            <Icon name=\"link_2\" />\n          {/snippet}\n          {#snippet endIcon()}\n            <span class=\"count\" aria-label=\"({_('x_assets', { values: { count: linkedCount } })})\">\n              {appNumberFormatter.current.format(linkedCount)}\n            </span>\n          {/snippet}\n        </Option>\n      </OptionGroup>\n    {/if}\n  </Listbox>\n</nav>\n","<script>\n  import { locale as appLocale } from '@sveltia/i18n';\n  import { GridCell, GridRow, TruncatedText } from '@sveltia/ui';\n\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { getFolderLabelByCollection } from '$lib/services/assets/view';\n  import { encodePathSegments } from '$lib/services/utils/url';\n\n  /**\n   * @import { Asset } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Asset} asset Single asset.\n   */\n\n  /** @type {Props} */\n  let { asset } = $props();\n\n  const { path, name, folder, kind } = $derived(asset);\n</script>\n\n<GridRow\n  onclick={() => {\n    goto(encodePathSegments(`/assets/${path}`), { transitionType: 'forwards' });\n  }}\n>\n  <GridCell class=\"image\">\n    <AssetPreview {kind} {asset} variant=\"icon\" cover />\n  </GridCell>\n  <GridCell class=\"collection\">\n    {#key appLocale.current}\n      <bdi>{getFolderLabelByCollection(folder)}</bdi>\n    {/key}\n  </GridCell>\n  <GridCell class=\"title\">\n    <div role=\"none\" class=\"label\">\n      <TruncatedText lines={2}>\n        <bdi>{name}</bdi>\n      </TruncatedText>\n    </div>\n  </GridCell>\n</GridRow>\n","<!--\n  @component\n  Thumbnail of an entry, as shown in the entry list, the search results and the Editorial Workflow\n  page. Nothing is rendered for an entry without one. The thumbnail is loaded right away if it’s in\n  view, or once it has scrolled into view and stayed there for a moment, so the rows a long list is\n  scrolled past don’t queue up thumbnails ahead of the ones the user stops at. Its object URL is\n  released\n  when the entry changes or the thumbnail is removed, so a long list doesn’t keep every thumbnail it\n  has ever shown in memory.\n-->\n<script>\n  import Image from '$lib/components/assets/shared/image.svelte';\n  import { loadEntryThumbnail } from '$lib/services/contents/entry/assets';\n  import { whenThumbnailShown } from '$lib/services/utils/visibility';\n\n  /**\n   * @import { Entry, InternalEntryCollection } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalEntryCollection} collection Entry’s collection.\n   * @property {Entry} entry Entry.\n   * @property {'icon' | 'tile'} variant Image variant.\n   */\n\n  /** @type {Props} */\n  let { collection, entry, variant } = $props();\n\n  /**\n   * Hidden element whose parent, the cell or card holding the thumbnail, is observed to tell when\n   * the thumbnail comes into view: there is no thumbnail to observe until it has been loaded. The\n   * anchor itself is hidden so it takes no part in the layout, and has no box to observe.\n   * @type {HTMLElement | undefined}\n   */\n  let anchor = $state();\n\n  /**\n   * The loaded thumbnail along with the entry it belongs to. A thumbnail is only shown for its own\n   * entry, so a row given another entry stops showing the previous one right away, without the\n   * effect below having to reset anything: a state write from an effect, or from its teardown, is\n   * costly with thousands of rows.\n   * @type {{ entry: Entry, src: string } | undefined}\n   */\n  let loaded = $state.raw();\n\n  const src = $derived(loaded?.entry === entry ? loaded.src : undefined);\n\n  $effect(() => {\n    const container = anchor?.parentElement;\n\n    /* v8 ignore next 3 -- the anchor is bound and mounted before the effect runs */\n    if (!container) {\n      return undefined;\n    }\n\n    const _collection = collection;\n    const _entry = entry;\n    /** @type {(() => void) | undefined} */\n    let release;\n\n    const cancel = whenThumbnailShown(container, () => {\n      release = loadEntryThumbnail(_collection, _entry, (url) => {\n        loaded = { entry: _entry, src: url };\n      });\n    });\n\n    return () => {\n      cancel();\n      release?.();\n    };\n  });\n</script>\n\n<span role=\"none\" hidden bind:this={anchor}></span>\n{#if src}\n  <!-- The thumbnail is only loaded once it’s about to be seen, so it’s shown right away -->\n  <Image {src} {variant} cover loading=\"eager\" />\n{/if}\n","<script>\n  import { locale as appLocale } from '@sveltia/i18n';\n  import { GridCell, GridRow, TruncatedText } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n\n  import EntryThumbnail from '$lib/components/contents/shared/entry-thumbnail.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { getCollectionLabel } from '$lib/services/contents/collection';\n  import { getListedCollections } from '$lib/services/contents/collection/entries';\n  import {\n    getCollectionFileLabel,\n    getCollectionFilesByEntry,\n  } from '$lib/services/contents/collection/files';\n  import { getEntryEditorPath } from '$lib/services/contents/editor/route';\n  import { getEntrySummary } from '$lib/services/contents/entry/summary';\n\n  /**\n   * @import {\n   * EntrySearchResult,\n   * InternalCollection,\n   * InternalCollectionFile,\n   * } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} RowArgs\n   * @property {InternalCollection} collection Collection.\n   * @property {InternalCollectionFile} [collectionFile] Collection file. File/singleton collection\n   * only.\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {EntrySearchResult} result Single search result.\n   */\n\n  /** @type {Props} */\n  let { result } = $props();\n\n  const { entry, locale, keyPath } = $derived(result);\n  const { subPath } = $derived(entry);\n</script>\n\n{#snippet resultRow(/** @type {RowArgs} */ { collection, collectionFile })}\n  <GridRow\n    onclick={() => {\n      goto(getEntryEditorPath(collection.name, collectionFile?.name || subPath), {\n        state: { highlight: { locale, keyPath } },\n        transitionType: 'forwards',\n      });\n    }}\n  >\n    <GridCell class=\"image\">\n      {#if collection._type === 'entry'}\n        <EntryThumbnail {collection} {entry} variant=\"icon\" />\n      {/if}\n    </GridCell>\n    <GridCell class=\"collection\">\n      {#key appLocale.current}\n        <bdi>{getCollectionLabel(collection)}</bdi>\n      {/key}\n    </GridCell>\n    <GridCell class=\"title\">\n      <div role=\"none\" class=\"label\">\n        <TruncatedText lines={2}>\n          <bdi>\n            {#if collectionFile}\n              {getCollectionFileLabel(collectionFile)}\n            {:else}\n              {#key appLocale.current}\n                {@html getEntrySummary(collection, entry, {\n                  useTemplate: true,\n                  allowMarkdown: true,\n                })}\n              {/key}\n            {/if}\n          </bdi>\n        </TruncatedText>\n      </div>\n    </GridCell>\n  </GridRow>\n{/snippet}\n\n{#each getListedCollections(entry) as collection (collection.name)}\n  {#await sleep() then}\n    {#each getCollectionFilesByEntry(collection, entry) as collectionFile (collectionFile.name)}\n      {#await sleep() then}\n        {@render resultRow({ collection, collectionFile })}\n      {/await}\n    {:else}\n      {@render resultRow({ collection })}\n    {/each}\n  {/await}\n{/each}\n","<!--\n  @component\n  List of search results, shared by entries and assets: a grid of the matching items, or an empty\n  state when nothing matches the search terms.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState, Group, InfiniteScroll } from '@sveltia/ui';\n\n  import ListingGrid from '$lib/components/common/listing-grid.svelte';\n  import { announcedPageStatus } from '$lib/services/app/navigation';\n  import { searchTerms } from '$lib/services/search';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {any[]} items Matching items.\n   * @property {string} itemKey Property of an item that identifies it in the list.\n   * @property {string} label Name of the result type, used as the accessible name of the group\n   * and the grid.\n   * @property {string} emptyMessage Message shown when nothing matches the search terms.\n   * @property {string} statusMessageKey Key of the message announced to screen readers, given the\n   * search terms and the result count.\n   * @property {Snippet<[any]>} renderItem Renders a listed item.\n   */\n\n  /** @type {Props} */\n  let { items, itemKey, label, emptyMessage, statusMessageKey, renderItem } = $props();\n\n  $effect(() => {\n    announcedPageStatus.current = _(statusMessageKey, {\n      values: {\n        terms: searchTerms.current,\n        count: items.length,\n      },\n    });\n  });\n</script>\n\n<Group ariaLabel={label}>\n  <div role=\"none\">\n    {#if items.length}\n      <ListingGrid viewType=\"list\" aria-label={label} aria-rowcount={items.length}>\n        {#key searchTerms.current}\n          <InfiniteScroll {items} {itemKey} {renderItem} />\n        {/key}\n      </ListingGrid>\n    {:else if searchTerms.current}\n      <EmptyState>\n        <span role=\"none\">{emptyMessage}</span>\n      </EmptyState>\n    {/if}\n  </div>\n</Group>\n","import { publishedAssets } from '$lib/services/assets/state';\nimport { searchTerms } from '$lib/services/search';\nimport { getNormalizedValueCache, hasAllMatches, tokenize } from '$lib/services/search/util';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Asset } from '$lib/types/private';\n */\n\n/**\n * Search assets based on the given search terms. The terms are split into words, and an asset is\n * listed when its name contains all of them in any order, so the query “annual report cover”\n * matches a file named `annual-report-cover-photo.png`. This is the same rule as the asset picker\n * dialog applies.\n * @param {object} args Arguments.\n * @param {Asset[]} args.assets All assets to search in.\n * @param {string} args.terms Search terms.\n * @returns {Asset[]} Search results.\n */\nexport const searchAssets = ({ assets, terms }) => {\n  const tokens = tokenize(terms);\n\n  if (!assets.length || !tokens.length) {\n    return [];\n  }\n\n  // Each asset’s normalized name is kept for later searches, as long as the asset object is around,\n  // so a keystroke doesn’t normalize every name in the library again\n  return assets.filter((asset) =>\n    hasAllMatches({\n      value: asset.name,\n      tokens,\n      normalizedValueCache: getNormalizedValueCache(asset),\n    }),\n  );\n};\n\n/**\n * Hold asset search results for the current search terms.\n */\nexport const assetSearchResults = createDerivedState(() =>\n  searchAssets({ assets: publishedAssets.current, terms: searchTerms.current }),\n);\n","import { allEntries } from '$lib/services/contents';\nimport { getListedCollections } from '$lib/services/contents/collection/entries';\nimport { getCollectionFilesByEntry } from '$lib/services/contents/collection/files';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { searchTerms } from '$lib/services/search';\nimport { getNormalizedValueCache, hasMatch, normalize } from '$lib/services/search/util';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\nimport { mergeUnpublishedEntries, unpublishedEntries } from '$lib/services/workflow';\n\n/**\n * @import { Entry, EntrySearchResult, InternalLocaleCode } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n * @import { NormalizedValueCache } from '$lib/services/search/util';\n */\n\n/**\n * Scan an entry for matches against the search terms.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry to scan.\n * @param {string} args.terms Search terms.\n * @param {NormalizedValueCache} [args.normalizedValueCache] Normalized value cache shared within\n * one search, for values that many entries have in common, such as collection labels.\n * @returns {EntrySearchResult} Single search result.\n */\nexport const scanEntry = ({ entry, terms, normalizedValueCache = undefined }) => {\n  // Count the number of matches, weighting the collection name and title\n  let points = 0;\n  /** @type {InternalLocaleCode | undefined} */\n  let locale = undefined;\n  /** @type {FieldKeyPath | undefined} */\n  let keyPath = undefined;\n  const collections = getListedCollections(entry);\n\n  // An entry that every associated collection filters out can’t be opened — the content editor\n  // would show “Entry not found” — so it must not be listed as a result at all\n  if (!collections.length) {\n    return { id: entry.id, entry, points: 0, locale, keyPath };\n  }\n\n  collections.forEach((collection) => {\n    // Check if the collection label or name matches\n    if (hasMatch({ value: collection.label || collection.name, terms, normalizedValueCache })) {\n      points += 10;\n    }\n\n    // Check if the file labels or names match\n    points += getCollectionFilesByEntry(collection, entry).filter((file) =>\n      hasMatch({ value: file.label || file.name, terms, normalizedValueCache }),\n    ).length;\n  });\n\n  // Match the plain-text summary, as a user sees it, rather than the HTML rendered from Markdown,\n  // which would match tag names like `strong` and character references like `&lt;`\n  const summary = getEntrySummary(collections[0], entry, { useTemplate: true });\n  // The entry’s own values are normalized once and kept for later searches, as long as the entry\n  // object is around\n  const entryValueCache = getNormalizedValueCache(entry);\n\n  // Check if the entry summary matches\n  if (hasMatch({ value: summary, terms, normalizedValueCache: entryValueCache })) {\n    points += 10;\n  }\n\n  // Check if the entry content matches\n  Object.entries(entry.locales).forEach(([_locale, { content }]) => {\n    points += Object.entries(content).filter(([_keyPath, value]) => {\n      const matched =\n        (typeof value === 'string' &&\n          !!value &&\n          hasMatch({ value, terms, normalizedValueCache: entryValueCache })) ||\n        (typeof value === 'number' &&\n          hasMatch({ value: String(value), terms, normalizedValueCache: entryValueCache }));\n\n      // If this is the first match, store the locale and key path\n      if (matched && !locale && !keyPath) {\n        locale = _locale;\n        keyPath = _keyPath;\n      }\n\n      return matched;\n    }).length;\n  });\n\n  return { id: entry.id, entry, points, locale, keyPath };\n};\n\n/**\n * Search entries based on the given search terms.\n * @param {object} args Arguments.\n * @param {Entry[]} args.entries All entries to search in.\n * @param {string} args.terms Search terms.\n * @returns {EntrySearchResult[]} Search results sorted by relevance.\n */\nexport const searchEntries = ({ entries, terms }) => {\n  terms = normalize(terms);\n\n  if (!entries.length || !terms) {\n    return [];\n  }\n\n  /** @type {NormalizedValueCache} */\n  const normalizedValueCache = new Map();\n\n  return entries\n    .map((entry) => scanEntry({ entry, terms, normalizedValueCache }))\n    .filter(({ points }) => points > 0)\n    .sort((a, b) => b.points - a.points);\n};\n\n/**\n * Hold entry search results for the current search terms. `getEntrySummary()` may return a\n * localized label, and it reads the current app locale, so the results are also recomputed when the\n * locale changes.\n * @type {{ readonly current: EntrySearchResult[] }}\n * @todo Search relation fields.\n */\nexport const entrySearchResults = createDerivedState(() =>\n  searchEntries({\n    entries: mergeUnpublishedEntries(allEntries.current, unpublishedEntries.current),\n    terms: searchTerms.current,\n  }),\n);\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Toolbar } from '@sveltia/ui';\n\n  import AssetResultItem from '$lib/components/search/asset-result-item.svelte';\n  import EntryResultItem from '$lib/components/search/entry-result-item.svelte';\n  import SearchResultList from '$lib/components/search/search-result-list.svelte';\n  import { searchMode } from '$lib/services/search';\n  import { assetSearchResults } from '$lib/services/search/assets';\n  import { entrySearchResults } from '$lib/services/search/entries';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Asset, EntrySearchResult } from '$lib/types/private';\n   */\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  {#if !env.isSmallScreen}\n    <Toolbar variant=\"primary\">\n      <h2 role=\"none\">{_('search_results')}</h2>\n    </Toolbar>\n  {/if}\n  <div role=\"none\" class=\"results\">\n    {#if searchMode.current === 'contents'}\n      <SearchResultList\n        items={entrySearchResults.current}\n        itemKey=\"id\"\n        label={_('entries')}\n        emptyMessage={_('no_entries_found')}\n        statusMessageKey=\"viewing_entry_search_results\"\n      >\n        {#snippet renderItem(/** @type {EntrySearchResult} */ result)}\n          <EntryResultItem {result} />\n        {/snippet}\n      </SearchResultList>\n    {/if}\n    {#if searchMode.current === 'assets'}\n      <SearchResultList\n        items={assetSearchResults.current}\n        itemKey=\"path\"\n        label={_('assets')}\n        emptyMessage={_('no_files_found')}\n        statusMessageKey=\"viewing_asset_search_results\"\n      >\n        {#snippet renderItem(/** @type {Asset} */ asset)}\n          <AssetResultItem {asset} />\n        {/snippet}\n      </SearchResultList>\n    {/if}\n  </div>\n</div>\n\n<style>\n  .wrapper {\n    flex: auto;\n    display: flex;\n    flex-direction: column;\n    overflow: hidden;\n    width: 100%;\n    background-color: var(--sui-primary-background-color);\n  }\n\n  .results {\n    flex: auto;\n    overflow: auto;\n\n    :global {\n      & > .sui.group {\n        display: contents;\n\n        & > .inner > div {\n          display: contents;\n        }\n      }\n\n      h3 {\n        flex: none;\n        margin: 16px;\n        color: var(--sui-secondary-foreground-color);\n        font-size: var(--sui-font-size-large);\n\n        & + div {\n          overflow: auto;\n          flex: auto;\n        }\n\n        @media (width < 768px) {\n          display: none;\n        }\n      }\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Toolbar } from '@sveltia/ui';\n\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import BackButton from '$lib/components/common/page-toolbar/back-button.svelte';\n  import QuickSearchBar from '$lib/components/global/toolbar/items/quick-search-bar.svelte';\n  import SearchResults from '$lib/components/search/search-results.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { searchMode, searchTerms } from '$lib/services/search';\n  import { env } from '$lib/services/user/env.svelte';\n</script>\n\n<PageContainerMainArea>\n  {#snippet primaryToolbar()}\n    {#if env.isSmallScreen}\n      <Toolbar variant=\"primary\">\n        <BackButton\n          aria-label={_(\n            searchMode.current === 'assets'\n              ? 'back_to_asset_folder_list'\n              : 'back_to_collection_list',\n          )}\n          onclick={() => {\n            searchTerms.current = '';\n            goto(searchMode.current === 'assets' ? '/assets' : '/collections', {\n              transitionType: 'backwards',\n            });\n          }}\n        />\n        <div role=\"search\">\n          <QuickSearchBar />\n        </div>\n      </Toolbar>\n    {/if}\n  {/snippet}\n  {#snippet mainContent()}\n    <SearchResults />\n  {/snippet}\n</PageContainerMainArea>\n\n<style>\n  [role='search'] {\n    display: contents;\n\n    :global {\n      .sui.search-bar {\n        flex: auto;\n      }\n    }\n  }\n</style>\n","import { _ } from '@sveltia/i18n';\n\nimport { allAssets } from '$lib/services/assets/state';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * List of available sort keys for the selected asset collection. The labels are localized, and\n * `_()` reads the current app locale, so the list is recomputed when the locale changes.\n * @type {{ readonly current: { key: string, label: string }[] }}\n */\nexport const sortKeys = createDerivedState(() => {\n  const { current: _allAssets } = allAssets;\n  const _sortFields = ['name'];\n\n  if (_allAssets.every((asset) => !!asset.commitAuthor)) {\n    _sortFields.push('commit_author');\n  }\n\n  if (_allAssets.every((asset) => !!asset.commitDate)) {\n    _sortFields.push('commit_date');\n  }\n\n  return _sortFields.map((key) => ({ key, label: _(`sort_keys.${key}`) }));\n});\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { onMount, untrack } from 'svelte';\n\n  import ExternalDetailsOverlay from '$lib/components/assets/list/external/details-overlay.svelte';\n  import ExternalMainArea from '$lib/components/assets/list/external/main-area.svelte';\n  import AssetList from '$lib/components/assets/list/internal/asset-list.svelte';\n  import DeleteFolderDialog from '$lib/components/assets/list/internal/delete-folder-dialog.svelte';\n  import AssetDetailsOverlay from '$lib/components/assets/list/internal/details-overlay.svelte';\n  import EditAssetDialog from '$lib/components/assets/list/internal/edit-asset-dialog.svelte';\n  import FolderInfoPanel from '$lib/components/assets/list/internal/folder-info-panel.svelte';\n  import InfoPanel from '$lib/components/assets/list/internal/info-panel.svelte';\n  import MoveAssetsDialog from '$lib/components/assets/list/internal/move-dialog.svelte';\n  import NewFolderDialog from '$lib/components/assets/list/internal/new-folder-dialog.svelte';\n  import PrimaryToolbar from '$lib/components/assets/list/internal/primary-toolbar.svelte';\n  import RenameAssetDialog from '$lib/components/assets/list/internal/rename-dialog.svelte';\n  import RenameFolderDialog from '$lib/components/assets/list/internal/rename-folder-dialog.svelte';\n  import PrimarySidebar from '$lib/components/assets/list/primary-sidebar.svelte';\n  import SecondarySidebar from '$lib/components/assets/list/secondary-sidebar.svelte';\n  import SecondaryToolbar from '$lib/components/assets/list/secondary-toolbar.svelte';\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import SearchMainArea from '$lib/components/search/search-main-area.svelte';\n  import { updateContentFromHashChange } from '$lib/services/app/navigation';\n  import { hasAuthInfo, selectedCloudService } from '$lib/services/assets/external';\n  import { loadExternalAssets } from '$lib/services/assets/external/data';\n  import { LINKED_FILES_SERVICE_ID, linkedAssets } from '$lib/services/assets/external/linked';\n  import {\n    ASSETS_ROUTE_REGEX,\n    discardAssetsNavigation,\n    getSelectedAssetFolderLabel,\n    resolveAssetsRoute,\n  } from '$lib/services/assets/navigation';\n  import { focusedAsset, selectedAssets } from '$lib/services/assets/state';\n  import {\n    assetGroups,\n    folderSummary,\n    listedAssets,\n    showAssetOverlay,\n  } from '$lib/services/assets/view';\n  import { sortKeys } from '$lib/services/assets/view/sort-keys';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { Asset } from '$lib/types/private';\n   */\n\n  let isIndexPage = $state(false);\n  let isSearchPage = $state(false);\n  let notFound = $state(false);\n\n  const selectedAssetFolderLabel = $derived(getSelectedAssetFolderLabel());\n\n  /**\n   * Navigate to the asset list or asset details page given the URL hash.\n   */\n  const navigate = () => {\n    ({ isIndexPage, isSearchPage, notFound } = resolveAssetsRoute());\n  };\n\n  // Fetch the assets on the selected cloud storage service once the user has provided the\n  // credentials. This lives on the page rather than in the main area, because the main area isn’t\n  // rendered while the details overlay is shown, and a direct link to an asset’s details needs the\n  // list as well. The Cloudinary widget handles authentication and listing on its own\n  $effect(() => {\n    const service = selectedCloudService.current;\n\n    if (service && service.authType !== 'widget' && hasAuthInfo(service)) {\n      // The linked files come from the entries, so reload the list whenever these change\n      if (service.serviceId === LINKED_FILES_SERVICE_ID) {\n        void linkedAssets.current;\n      }\n\n      untrack(() => {\n        loadExternalAssets(service);\n      });\n    }\n  });\n\n  onMount(() => {\n    navigate();\n\n    return () => {\n      // Discard a navigation still in flight\n      discardAssetsNavigation();\n      showAssetOverlay.current = false;\n    };\n  });\n</script>\n\n<svelte:window\n  onhashchange={(event) => {\n    updateContentFromHashChange(event, navigate, ASSETS_ROUTE_REGEX);\n  }}\n/>\n\n{#snippet folderInfo()}\n  <FolderInfoPanel />\n{/snippet}\n\n<PageContainer uiSettingsKey=\"assets-page\" aria-label={_('asset_library')}>\n  {#snippet primarySidebar()}\n    {#if !env.isSmallScreen || isIndexPage}\n      <PrimarySidebar {isSearchPage} />\n    {/if}\n  {/snippet}\n  {#snippet main()}\n    {#if isSearchPage}\n      <SearchMainArea />\n    {:else if notFound}\n      <PageContainerMainArea id=\"assets-container\" aria-label={_('asset_library')}>\n        {#snippet mainContent()}\n          <NotFound message={_('asset_folder_not_found')} backPath=\"/assets\" />\n        {/snippet}\n      </PageContainerMainArea>\n    {:else if selectedCloudService.current}\n      <ExternalMainArea />\n    {:else if !env.isSmallScreen || !isIndexPage}\n      <PageContainerMainArea\n        id=\"assets-container\"\n        aria-label={_('x_asset_folder', { values: { folder: selectedAssetFolderLabel } })}\n      >\n        {#snippet primaryToolbar()}\n          <PrimaryToolbar />\n        {/snippet}\n        {#snippet secondaryToolbar()}\n          {#if listedAssets.current.length}\n            <SecondaryToolbar\n              allItems={Object.values(assetGroups.current).flat(1)}\n              selectedItems={selectedAssets}\n              totalCount={listedAssets.current.length}\n              sortKeys={sortKeys.current}\n            />\n          {/if}\n        {/snippet}\n        {#snippet mainContent()}\n          <AssetList />\n        {/snippet}\n        {#snippet secondarySidebar()}\n          <!-- There is no folder to show the info of while the route leaves none selected, e.g. for\n          an asset outside any configured folder, opened from search results or a link -->\n          <SecondarySidebar\n            asset={focusedAsset.current}\n            fallback={folderSummary.current ? folderInfo : undefined}\n          >\n            {#snippet children(/** @type {Asset} */ asset)}\n              <InfoPanel {asset} showPreview={true} />\n            {/snippet}\n          </SecondarySidebar>\n        {/snippet}\n      </PageContainerMainArea>\n    {/if}\n  {/snippet}\n</PageContainer>\n\n{#if showAssetOverlay.current}\n  {#if selectedCloudService.current}\n    <ExternalDetailsOverlay />\n  {:else}\n    <AssetDetailsOverlay />\n  {/if}\n{/if}\n\n<EditAssetDialog />\n<RenameAssetDialog />\n<MoveAssetsDialog />\n<NewFolderDialog />\n<RenameFolderDialog />\n<DeleteFolderDialog />\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Modal } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import {\n    CONSOLE_BASE_URL,\n    consoleLoaded,\n    dialogOpen,\n    FRAME_SRC_PARAMS,\n    getLibraryOptions,\n    parseMessage,\n  } from '$lib/services/integrations/media-libraries/cloud/cloudinary';\n\n  let src = $state('');\n  let mlId = $state('');\n\n  /**\n   * Handle the `consoleLoaded` message from the iframe. It’s handled here rather than in the\n   * Cloudinary panel, because the iframe is loaded at startup and can send the message before the\n   * panel is mounted, in which case the panel would never configure the widget.\n   * @param {MessageEvent} event The message event.\n   * @see https://github.com/sveltia/sveltia-cms/issues/1125\n   */\n  const onMessage = (event) => {\n    if (parseMessage(event)?.type === 'consoleLoaded') {\n      consoleLoaded.current = true;\n    }\n  };\n\n  onMount(() => {\n    // A new iframe, e.g. after signing in again, has to load the console first\n    consoleLoaded.current = false;\n\n    const options = getLibraryOptions();\n\n    if (!options) {\n      return;\n    }\n\n    const { cloud_name: cloudName, api_key: apiKey } = options.config ?? {};\n\n    if (!cloudName || !apiKey) {\n      return;\n    }\n\n    mlId = window.crypto.randomUUID();\n\n    const params = new URLSearchParams({\n      ...Object.fromEntries(\n        Object.entries(/** @type {Record<string, any>} */ (options.config)).filter(([k]) =>\n          FRAME_SRC_PARAMS.includes(k),\n        ),\n      ),\n      ml_id: mlId,\n      pmHost: window.location.origin,\n      new_cms: 'true',\n    });\n\n    src = `${CONSOLE_BASE_URL}/cms?${params}`;\n  });\n</script>\n\n<svelte:window onmessage={onMessage} />\n\n{#if src}\n  <!-- Keep the content so that the iframe is not destroyed when the modal is closed -->\n  <Modal bind:open={dialogOpen.current} keepContent>\n    <iframe\n      {src}\n      id=\"cloudinary-iframe\"\n      title={_('cloud_storage.cloudinary.iframe_title')}\n      allow=\"camera; storage-access\"\n      sandbox=\"allow-same-origin allow-scripts allow-popups allow-forms\n        allow-storage-access-by-user-activation\"\n      data-ml-id={mlId}\n    >\n    </iframe>\n  </Modal>\n{/if}\n\n<style>\n  iframe {\n    display: block;\n    width: calc(100% - 32px);\n    height: calc(100% - 32px);\n    border: none;\n  }\n\n  /* Avoid scrolling issue https://github.com/sveltia/sveltia-cms/issues/824 */\n  :global(dialog[inert]) > iframe {\n    display: none;\n  }\n</style>\n","<!--\n  @component\n  Toasts reporting the progress and the result of an asset operation. These live outside the Asset\n  Library, because an asset can be saved from anywhere the upload dialog reaches — dropping a file\n  on the collection assets sidebar, say — and the result should be reported wherever the user\n  happens to be.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Toast } from '@sveltia/ui';\n\n  import { assetCommitToast, assetUpdatesToast } from '$lib/services/assets/data';\n</script>\n\n<Toast bind:show={assetUpdatesToast.current.saved}>\n  <Alert status=\"success\">\n    {_(assetUpdatesToast.current.published ? 'assets_saved_and_published' : 'assets_saved', {\n      values: { count: assetUpdatesToast.current.count },\n    })}\n  </Alert>\n</Toast>\n\n<Toast bind:show={assetUpdatesToast.current.moved}>\n  <Alert status=\"success\">\n    {_('assets_moved', { values: { count: assetUpdatesToast.current.count } })}\n  </Alert>\n</Toast>\n\n<Toast bind:show={assetUpdatesToast.current.renamed}>\n  <Alert status=\"success\">\n    {_('assets_renamed', { values: { count: assetUpdatesToast.current.count } })}\n  </Alert>\n</Toast>\n\n<Toast bind:show={assetUpdatesToast.current.folderCreated}>\n  <Alert status=\"success\">{_('folder_created')}</Alert>\n</Toast>\n\n<Toast bind:show={assetUpdatesToast.current.folderRenamed}>\n  <Alert status=\"success\">{_('folder_renamed')}</Alert>\n</Toast>\n\n<Toast bind:show={assetUpdatesToast.current.folderDeleted}>\n  <Alert status=\"success\">{_('folder_deleted')}</Alert>\n</Toast>\n\n<Toast bind:show={assetUpdatesToast.current.deleted}>\n  <Alert status=\"success\">\n    {_('assets_deleted', { values: { count: assetUpdatesToast.current.count } })}\n  </Alert>\n</Toast>\n\n<!-- `duration={0}` keeps this up until the commit settles, however long it takes -->\n<Toast show={assetCommitToast.current.pending > 0} duration={0}>\n  <Alert status=\"info\">{_(assetCommitToast.current.progress)}</Alert>\n</Toast>\n\n<Toast bind:show={assetCommitToast.current.failed}>\n  <Alert status=\"error\">{_(assetCommitToast.current.failure)}</Alert>\n</Toast>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, ConfirmationDialog, Radio, RadioGroup } from '@sveltia/ui';\n  import { getPathInfo } from '@sveltia/utils/file';\n\n  import UploadAssetsPreview from '$lib/components/assets/shared/upload-assets-preview.svelte';\n  import { getAssetsByDirName, getDuplicateFiles } from '$lib/services/assets';\n  import { runAssetCommit } from '$lib/services/assets/data/commit';\n  import { saveAssets } from '$lib/services/assets/data/create';\n  import { formatSize } from '$lib/services/assets/file-size';\n  import { processedAssets } from '$lib/services/assets/process';\n  import { uploadingAssets } from '$lib/services/assets/state';\n  import { getUploadDirPath } from '$lib/services/assets/subfolders';\n  import { showAssetOverlay, showUploadAssetsConfirmDialog } from '$lib/services/assets/view';\n  import { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\n  import { isEquivalentFileExtension } from '$lib/services/utils/file';\n\n  const {\n    files: originalFiles,\n    folder,\n    subfolderPath,\n    originalAssets,\n  } = $derived(uploadingAssets.current);\n  const originalAsset = $derived(originalAssets?.[0]);\n  const { processing, validFiles, oversizedFiles, invalidFiles, transformedFileMap } = $derived(\n    processedAssets.current,\n  );\n  const { max_file_size: maxSize } = $derived(getDefaultMediaLibraryOptions().config);\n  /** Path of the directory the files are saved to, named in the dialog and checked for dupes. */\n  const dirPath = $derived(getUploadDirPath(uploadingAssets.current));\n  const assetsInSameFolder = $derived(\n    originalAsset || dirPath === undefined ? [] : getAssetsByDirName(dirPath),\n  );\n  // A replacement file keeps the name of the asset it replaces, so it has to be in the same\n  // format: `cat.jpg` can be replaced with `cat2.jpeg`, which is that same format under another\n  // extension, while a `cat.png` is a different thing that can’t be saved under the `.jpg` name.\n  // This is checked here, rather than on the file the user picked, because an image is transcoded\n  // first when `transformations` is configured — a `.jpg` chosen for a `.jpg` asset can well\n  // arrive as a `.webp`.\n  const mismatchedFiles = $derived(\n    originalAsset\n      ? validFiles.filter(\n          (file) =>\n            !isEquivalentFileExtension(\n              getPathInfo(file.name).extension,\n              getPathInfo(originalAsset.name).extension,\n            ),\n        )\n      : [],\n  );\n\n  /** Files that can be saved. */\n  const uploadableFiles = $derived(validFiles.filter((file) => !mismatchedFiles.includes(file)));\n  /** Files to be saved, which the user can remove from the list. */\n  let files = $derived(uploadableFiles);\n  // Duplicates are replaced by default, again whenever another set of files comes in\n  let replaceFiles = $derived.by(() => {\n    void uploadableFiles;\n\n    return true;\n  });\n  const dupFiles = $derived(getDuplicateFiles(files, assetsInSameFolder));\n  const dupFileCount = $derived(dupFiles.length);\n\n  $effect(() => {\n    if (!showAssetOverlay.current) {\n      // Close the dialog\n      uploadingAssets.current = { folder: undefined, files: [] };\n    }\n  });\n</script>\n\n<ConfirmationDialog\n  open={showUploadAssetsConfirmDialog.current}\n  title={_(originalAsset ? 'replace_asset' : 'upload_assets')}\n  okLabel={_(originalAsset ? 'replace' : 'upload')}\n  okDisabled={!files.length}\n  onOk={() => {\n    const request = originalAsset\n      ? { files, folder, originalAssets }\n      : { files, folder, subfolderPath, replaceDuplicates: replaceFiles };\n\n    // Clear the selection before the commit, which can take a while: files the user picks or drops\n    // meanwhile then open the dialog again rather than being swallowed by this upload, and a failed\n    // upload doesn’t leave the store holding files that no dialog is showing any more\n    uploadingAssets.current = { folder: undefined, files: [] };\n\n    runAssetCommit(() => saveAssets(request, { commitType: 'uploadMedia' }), {\n      progress: 'uploading_files_progress',\n      failure: 'uploading_files_failed',\n    });\n  }}\n  onCancel={() => {\n    uploadingAssets.current = { folder: undefined, files: [] };\n  }}\n>\n  {#if processing}\n    <div role=\"status\">\n      {_('processing_files', { values: { count: originalFiles.length } })}\n    </div>\n  {/if}\n  {#if files.length}\n    <div role=\"group\" class=\"section uploading\" aria-label={_('uploading_files')}>\n      <div role=\"none\">\n        {#if originalAsset}\n          {_('confirm_replacing_file', {\n            values: { name: originalAsset.name },\n          })}\n        {:else}\n          {_('confirm_uploading_files', {\n            values: { count: files.length, folder: `/${dirPath}` },\n          })}\n        {/if}\n      </div>\n      <UploadAssetsPreview bind:files {transformedFileMap} />\n    </div>\n  {/if}\n  {#if oversizedFiles.length}\n    <div role=\"group\" class=\"section oversized\" aria-label={_('oversized_files')}>\n      <Alert status=\"warning\">\n        {_('warning_oversized_files', {\n          values: {\n            count: oversizedFiles.length,\n            size: formatSize(/** @type {number} */ (maxSize)),\n          },\n        })}\n      </Alert>\n      <UploadAssetsPreview files={oversizedFiles} {transformedFileMap} removable={false} />\n    </div>\n  {/if}\n  {#if invalidFiles.length}\n    <div role=\"group\" class=\"section invalid\" aria-label={_('invalid_files')}>\n      <Alert status=\"warning\">\n        {_('warning_invalid_files', { values: { count: invalidFiles.length } })}\n      </Alert>\n      <!-- An invalid file is never transformed, so there’s no original to map it back to -->\n      <UploadAssetsPreview files={invalidFiles} removable={false} showThumbnail={false} />\n    </div>\n  {/if}\n  {#if mismatchedFiles.length}\n    <div role=\"group\" class=\"section mismatched\" aria-label={_('mismatched_files')}>\n      <Alert status=\"warning\">\n        {_('warning_mismatched_files', {\n          values: { count: mismatchedFiles.length, name: originalAsset?.name },\n        })}\n      </Alert>\n      <UploadAssetsPreview files={mismatchedFiles} {transformedFileMap} removable={false} />\n    </div>\n  {/if}\n  {#if dupFileCount}\n    <div role=\"group\" class=\"section\">\n      {_('file_name_conflict_confirmation', { values: { count: dupFileCount } })}\n      <RadioGroup\n        ariaLabel={_('file_name_conflict_resolution')}\n        onChange={({ detail }) => {\n          replaceFiles = detail.value === 'replace';\n        }}\n      >\n        <Radio value=\"replace\" checked={replaceFiles}>{_('replace')}</Radio>\n        <Radio value=\"keep\" checked={!replaceFiles}>{_('keep_both')}</Radio>\n      </RadioGroup>\n    </div>\n  {/if}\n</ConfirmationDialog>\n\n<style>\n  .section {\n    display: flex;\n    flex-direction: column;\n    gap: 12px;\n\n    &:not(:first-child) {\n      margin-top: 16px;\n    }\n\n    & > :global(*) {\n      flex: none;\n    }\n\n    &.oversized :global(.files),\n    &.invalid :global(.files),\n    &.mismatched :global(.files) {\n      opacity: 0.5;\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Dialog, FilePicker } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import DropZone from '$lib/components/assets/shared/drop-zone.svelte';\n  import { targetAssetFolder } from '$lib/services/assets/folders';\n  import { uploadingAssets } from '$lib/services/assets/state';\n  import { selectedSubfolderPath } from '$lib/services/assets/subfolders';\n  import { showAssetOverlay, showUploadAssetsDialog } from '$lib/services/assets/view';\n  import { env } from '$lib/services/user/env.svelte';\n  import mime from '$lib/services/utils/mime';\n\n  /** @type {FilePicker | undefined} */\n  let filePicker = $state();\n\n  const { originalAssets } = $derived(uploadingAssets.current);\n  // Use the first asset because replacement only supports one asset for now\n  const originalAsset = $derived(originalAssets?.[0]);\n  const multiple = $derived(!originalAsset);\n  const accept = $derived(\n    originalAsset ? (mime.getType(originalAsset.name) ?? undefined) : undefined,\n  );\n\n  /**\n   * Update the asset list, which will show the confirmation dialog.\n   * @param {File[]} files Selected files.\n   */\n  const onSelect = (files) => {\n    if (!files.length) {\n      return;\n    }\n\n    // A replacement takes over the path of the asset it replaces, so it needs no subfolder\n    uploadingAssets.current = originalAsset\n      ? { folder: originalAsset.folder, files, originalAssets }\n      : { folder: targetAssetFolder.current, subfolderPath: selectedSubfolderPath.current, files };\n    showUploadAssetsDialog.current = false;\n  };\n\n  $effect(() => {\n    // Open the file picker directly if drag & drop is not supported (on mobile)\n    if (!env.hasMouse && showUploadAssetsDialog.current) {\n      filePicker?.open();\n    }\n  });\n\n  $effect(() => {\n    if (!showAssetOverlay.current) {\n      showUploadAssetsDialog.current = false;\n    }\n  });\n\n  $effect(() => {\n    if (!showUploadAssetsDialog.current) {\n      // A replacement request is written to the store before this dialog opens, and consumed by\n      // `onSelect` above. Dismissing the dialog would otherwise leave it behind, and the next\n      // ordinary upload would be treated as a replacement of that asset — with the wrong dialog\n      // title, a single-file picker and an `accept` list restricted to the asset’s own type.\n      // `onSelect` stores the files before it closes the dialog, so a non-empty list here means a\n      // selection was made and the request is still in use.\n      untrack(() => {\n        if (!uploadingAssets.current.files.length && uploadingAssets.current.originalAssets) {\n          uploadingAssets.current = { folder: undefined, files: [] };\n        }\n      });\n    }\n  });\n</script>\n\n{#if env.hasMouse}\n  <Dialog\n    title={originalAsset\n      ? _('replace_x', { values: { name: originalAsset.name } })\n      : _('upload_assets')}\n    bind:open={showUploadAssetsDialog.current}\n    showOk={false}\n  >\n    <!--\n      Dropped files are not filtered by `accept` here: `<UploadAssetsConfirmDialog>` checks the\n      format once the files have been processed, which is the only point a transformation could\n      have changed it. The attribute still narrows the file picker.\n    -->\n    <DropZone\n      showUploadButton={true}\n      {accept}\n      {multiple}\n      filterDroppedFiles={false}\n      onDrop={({ files }) => {\n        onSelect(files);\n      }}\n    />\n  </Dialog>\n{:else}\n  <FilePicker\n    bind:this={filePicker}\n    {accept}\n    {multiple}\n    onSelect={({ files }) => {\n      onSelect(files);\n    }}\n    onCancel={() => {\n      showUploadAssetsDialog.current = false;\n    }}\n  />\n{/if}\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Alert, ConfirmationDialog, Toast } from '@sveltia/ui';\n\n  import {\n    backupToastState,\n    cancelRestoreCheck,\n    restoreDialogState,\n  } from '$lib/services/contents/draft/backup';\n  import { showContentOverlay } from '$lib/services/contents/editor';\n  import { formatRecentDateTime } from '$lib/services/utils/date';\n\n  const { resolve } = $derived(restoreDialogState.current);\n  /* v8 ignore start -- the time is only read while the dialog is shown, which has a timestamp */\n  // The dialog state is replaced whenever the dialog is opened, so the backup time is compared with\n  // the time it’s opened, while this component stays mounted with the Content Library\n  const datetime = $derived.by(() => {\n    const { timestamp } = restoreDialogState.current;\n\n    return timestamp ? formatRecentDateTime({ timestamp, locale: appLocale.current }) : undefined;\n  });\n  /* v8 ignore stop */\n\n  $effect(() => {\n    if (!showContentOverlay.current) {\n      // Close the dialog when the Content Editor is closed, or keep it from opening\n      cancelRestoreCheck();\n    }\n  });\n</script>\n\n<!-- Neither modal nor fixed in place, so the user can look through the entry, which is read-only\nmeanwhile, before deciding. The backdrop only dims the editor to draw attention to the dialog; the\nentry can still be scrolled through it -->\n<ConfirmationDialog\n  bind:open={restoreDialogState.current.show}\n  modal={false}\n  showBackdrop\n  movable\n  title={_('restore_backup_title')}\n  okLabel={_('restore')}\n  cancelLabel={_('discard')}\n  onOk={() => {\n    resolve?.(true);\n  }}\n  onCancel={() => {\n    resolve?.(false);\n  }}\n>\n  {_('restore_backup_description', { values: { datetime } })}\n</ConfirmationDialog>\n\n<Toast bind:show={backupToastState.current.saved}>\n  <Alert status=\"info\">\n    {_('draft_backup_saved')}\n  </Alert>\n</Toast>\n\n<Toast bind:show={backupToastState.current.restored}>\n  <Alert status=\"success\">\n    {_('draft_backup_restored')}\n  </Alert>\n</Toast>\n\n<Toast bind:show={backupToastState.current.deleted}>\n  <Alert status=\"info\">\n    {_('draft_backup_deleted')}\n  </Alert>\n</Toast>\n","import { customPreviewTemplateRegistry } from '$lib/services/api/registries';\nimport { escapeAttr } from '$lib/services/utils/string';\n\n/**\n * @import { CustomPreviewTemplate } from '$lib/types/public';\n */\n\n/**\n * Get the custom preview template registered for an entry.\n * @param {object} args Arguments.\n * @param {string} [args.collectionName] Collection name, or `_singletons` for a singleton file.\n * @param {string} [args.fileName] File name in a file/singleton collection.\n * @returns {CustomPreviewTemplate | undefined} Template, if any.\n */\nexport const getPreviewTemplate = ({ collectionName, fileName }) =>\n  customPreviewTemplateRegistry.get(/** @type {string} */ (fileName ?? collectionName));\n\n/**\n * Build the HTML document loaded into the iframe of a preview that uses custom preview styles or a\n * custom preview template.\n * @param {object} args Arguments.\n * @param {string} [args.lang] Language of the document, if any.\n * @param {'ltr' | 'rtl' | 'auto'} [args.dir] Text direction of the document, if any.\n * @param {string[]} args.styleURLs Custom stylesheet URLs to apply.\n * @param {string} args.origin Origin of the CMS, used as the base URL of the document.\n * @returns {string} HTML string.\n */\nexport const buildPreviewFrameHTML = ({ lang, dir, styleURLs, origin }) => `\n    <!DOCTYPE html>\n    <html${lang ? ` lang=\"${escapeAttr(lang)}\"` : ''}${dir ? ` dir=\"${dir}\"` : ''}>\n    <head>\n      <meta charset=\"UTF-8\">\n      <base href=\"${escapeAttr(origin)}\" target=\"_blank\">\n      ${styleURLs.map((url) => `<link rel=\"stylesheet\" href=\"${escapeAttr(url)}\">`).join('\\n')}\n    </head>\n    <body></body>\n    </html>\n  `;\n","<!--\n  @component Implement iframe for custom preview styles and React preview templates.\n  @see https://decapcms.org/docs/customization/\n  @see https://sveltiacms.app/en/docs/api/preview-styles\n  @see https://sveltiacms.app/en/docs/api/preview-templates\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Placeholder } from '@sveltia/ui';\n  import { createElement } from 'react';\n  import { mount, unmount } from 'svelte';\n\n  import { assetURLUpdates } from '$lib/services/api/asset-proxy';\n  import { loadReactDom } from '$lib/services/api/react-dom';\n  import {\n    createEntryDraftMountContext,\n    getEntryDraftContext,\n  } from '$lib/services/contents/draft/state.svelte';\n  import { highlightPreviewTemplateField } from '$lib/services/contents/editor/fields';\n  import { buildPreviewFrameHTML } from '$lib/services/contents/editor/preview-frame';\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { ComponentType } from 'react';\n   * @import { Root } from 'react-dom/client';\n   * @import { Snippet } from 'svelte';\n   * @import { InternalLocaleCode } from '$lib/types/private';\n   * @import { CustomPreviewTemplateProps } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   * @property {string[]} styleURLs Custom stylesheet URLs to apply in the iframe.\n   * @property {Snippet} [children] Preview content to render inside the iframe (for Svelte).\n   * @property {ComponentType<CustomPreviewTemplateProps>} [reactComponent] React component to\n   * render (for custom preview templates).\n   * @property {Omit<CustomPreviewTemplateProps, 'document' | 'window'>} [reactProps] Props for the\n   * React component, except for the `document` and `window` props, which will be automatically\n   * provided by the iframe.\n   * @property {(iframe: HTMLIFrameElement) => void} [onLoad] Function called with the iframe once\n   * its content has been loaded and mounted.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { locale, styleURLs, children, reactComponent, reactProps, onLoad } = $props();\n\n  /**\n   * Track if the iframe has been initialized to avoid duplicate initialization.\n   * @type {boolean}\n   */\n  let initialized = $state(false);\n  /**\n   * Reference to the iframe element used for custom preview.\n   * @type {HTMLIFrameElement | undefined}\n   */\n  let iframe = $state();\n  /**\n   * Reference to the React root inside the iframe.\n   * @type {Root | undefined}\n   */\n  let reactRoot = $state();\n  /**\n   * Svelte placeholder mounted inside the iframe. It’s outside the component tree, so it has to be\n   * unmounted explicitly, or its effects would keep running after the iframe is gone.\n   * @type {Record<string, any> | undefined}\n   */\n  let placeholder;\n\n  /** Language of the frame’s document, unless the locale isn’t a valid language tag. */\n  const lang = $derived(getCanonicalLocale(locale));\n  /**\n   * Text direction of the frame’s document. Without i18n, the locale doesn’t tell the language, so\n   * the direction is left to the template rather than set to `auto`, which would turn the whole\n   * document right-to-left whenever its first text is in a right-to-left script.\n   */\n  const dir = $derived(locale === '_default' ? undefined : getDirection(locale));\n\n  /**\n   * Mount the Svelte placeholder component into the iframe’s body. This way, the iframe content\n   * becomes reactive and can be updated when the fields change. The mounted component is outside\n   * the Svelte component tree, so the entry draft state is passed to it as a mount context; the\n   * field previews rendered by `children` read it from there.\n   */\n  const mountPlaceholder = () => {\n    const target = iframe?.contentDocument?.body;\n\n    /* v8 ignore next 3 -- the frame has just loaded, so it’s there */\n    if (!target) {\n      return;\n    }\n\n    placeholder = mount(Placeholder, {\n      target,\n      context: createEntryDraftMountContext(entryDraft),\n      props: { children },\n    });\n  };\n\n  /**\n   * Render the React component with the current props.\n   */\n  const renderReactComponent = () => {\n    const { contentDocument, contentWindow } = /** @type {HTMLIFrameElement} */ (iframe);\n\n    /* v8 ignore next 3 -- the effect below only calls this once the root is in the frame */\n    if (!reactRoot || !reactComponent || !reactProps || !contentDocument || !contentWindow) {\n      return;\n    }\n\n    const componentProps = {\n      ...reactProps,\n      document: contentDocument,\n      window: contentWindow,\n    };\n\n    reactRoot.render(createElement(reactComponent, componentProps));\n  };\n\n  /**\n   * Mount the React component into the iframe’s body.\n   */\n  const mountReactComponent = async () => {\n    /* v8 ignore next 3 -- only called when a React component is given */\n    if (!reactComponent) {\n      return;\n    }\n\n    // Loaded on demand, as only a custom preview template renders React here. It’s normally on\n    // its way already, as `CMS.registerPreviewTemplate()` starts loading it\n    const { createRoot } = await loadReactDom();\n    const contentDocument = iframe?.contentDocument;\n    const target = contentDocument?.body;\n\n    /* v8 ignore next 3 -- the frame may have been removed while the library was loading */\n    if (!contentDocument || !target) {\n      return;\n    }\n\n    /**\n     * Highlight the Edit Pane field corresponding to an element the template has marked with the\n     * `data-key-path` attribute. The listeners go away with the frame’s document.\n     * @param {MouseEvent | KeyboardEvent} event `click` or `keydown` event.\n     */\n    const listener = (event) => {\n      highlightPreviewTemplateField({ event, locale });\n    };\n\n    contentDocument.addEventListener('click', listener);\n    contentDocument.addEventListener('keydown', listener);\n\n    // Create React root in the iframe; the update $effect will handle the first render\n    reactRoot = createRoot(target);\n  };\n\n  /* v8 ignore start -- mounting only fails when the library can’t be loaded */\n  /**\n   * Report a failure to mount the content.\n   * @param {Error} error Error.\n   */\n  const reportMountError = (error) => {\n    // eslint-disable-next-line no-console\n    console.error(error);\n  };\n  /* v8 ignore stop */\n\n  /**\n   * Initialize the iframe with a custom stylesheet.\n   */\n  const initializeIframe = () => {\n    /* v8 ignore next 3 -- the effect below only calls this once, when the frame is there */\n    if (!iframe || initialized) {\n      return;\n    }\n\n    const mountComponent = reactComponent ? mountReactComponent : mountPlaceholder;\n    const html = buildPreviewFrameHTML({ lang, dir, styleURLs, origin: window.location.origin });\n    const blobURL = URL.createObjectURL(new Blob([html], { type: 'text/html' }));\n\n    /**\n     * Callback function to be called when the iframe has loaded its content. It mounts either the\n     * React component or the Svelte placeholder, depending on which is provided. It also revokes\n     * the iframe’s blob URL, which is no longer needed after the iframe has loaded.\n     */\n    const listener = async () => {\n      try {\n        await mountComponent();\n      } catch (/** @type {any} */ error) {\n        /* v8 ignore next -- mounting only fails when the library can’t be loaded */\n        reportMountError(error);\n      }\n\n      URL.revokeObjectURL(blobURL);\n      initialized = true;\n      onLoad?.(/** @type {HTMLIFrameElement} */ (iframe));\n    };\n\n    iframe.addEventListener('load', listener, { once: true });\n    iframe.src = blobURL;\n  };\n\n  // Initialize iframe once\n  $effect(() => {\n    if (iframe && !initialized) {\n      initializeIframe();\n    }\n  });\n\n  // Update the language and direction once the pane shows another locale, which doesn’t load the\n  // frame again\n  $effect(() => {\n    const root = initialized ? iframe?.contentDocument?.documentElement : undefined;\n\n    if (!root) {\n      return;\n    }\n\n    if (lang) {\n      root.lang = lang;\n    } else {\n      root.removeAttribute('lang');\n    }\n\n    if (dir) {\n      root.dir = dir;\n    } else {\n      root.removeAttribute('dir');\n    }\n  });\n\n  // Update React component when reactProps changes\n  $effect(() => {\n    // Render again once an asset the component got with `getAsset()` has a blob URL\n    void assetURLUpdates.current;\n\n    // Only update if we have a React root and the iframe is initialized\n    if (initialized && reactRoot && reactComponent && reactProps) {\n      renderReactComponent();\n    }\n  });\n\n  // Cleanup on unmount\n  $effect(() => () => {\n    reactRoot?.unmount();\n\n    if (placeholder) {\n      unmount(placeholder);\n    }\n  });\n</script>\n\n<iframe\n  class=\"preview\"\n  title={_('content_preview')}\n  sandbox=\"allow-same-origin allow-scripts allow-popups allow-forms\"\n  bind:this={iframe}\n></iframe>\n\n<style>\n  iframe {\n    display: block;\n    border: none;\n    width: 100%;\n    height: 100%;\n  }\n</style>\n","import { customPreviewStyleRegistry } from '$lib/services/api/registries';\n\n/**\n * Get the URLs of the custom preview stylesheets applied to an entry.\n * @param {object} args Arguments.\n * @param {string} [args.collectionName] Collection name, or `_singletons` for a singleton file.\n * @param {string} [args.fileName] File name in a file/singleton collection.\n * @returns {string[]} Stylesheet URLs, in the order they were registered, without duplicates.\n */\nexport const getPreviewStyleURLs = ({ collectionName, fileName }) => [\n  ...new Set(\n    [...customPreviewStyleRegistry]\n      .filter(\n        ({ collection, file }) =>\n          (collection === undefined || collection === collectionName) &&\n          (file === undefined || file === fileName),\n      )\n      .map(({ url }) => url),\n  ),\n];\n","import { createElement, useLayoutEffect, useRef } from 'react';\nimport { mount, unmount } from 'svelte';\n\nimport FieldPreview from '$lib/components/contents/details/preview/field-preview.svelte';\nimport { getImmutable } from '$lib/services/api/immutable';\nimport {\n  buildPreviewData,\n  convertEntryToMap,\n  getAssociatedPreviewAssets,\n} from '$lib/services/api/preview-data';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { createEntryDraftMountContext } from '$lib/services/contents/draft/state.svelte';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { unflattenMap } from '$lib/services/utils/object';\n\n/**\n * @import { MapOf } from 'immutable';\n * @import { ReactElement, RefObject } from 'react';\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n * @import { Entry, EntryDraft, GetFieldArgs, InternalLocaleCode } from '$lib/types/private';\n * @import {\n * ApiEntry,\n * CustomPreviewTemplateProps,\n * Field,\n * FieldKeyPath,\n * RawEntryContent,\n * } from '$lib/types/public';\n */\n\n/**\n * Mount a Svelte component for field preview.\n * @param {object} args Arguments.\n * @param {HTMLElement} args.target The DOM element to mount the Svelte component into.\n * @param {EntryDraftState} args.entryDraft Entry draft state of the editor. The mounted component\n * is outside the Svelte component tree, so the state has to be passed to it as a mount context.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @param {FieldKeyPath} args.keyPath The key path of the field to preview.\n * @param {Field} args.fieldConfig Configuration of the field.\n * @returns {Record<string, any>} The mounted Svelte component instance.\n */\nexport const mountFieldPreview = ({ target, entryDraft, locale, keyPath, fieldConfig }) =>\n  mount(FieldPreview, {\n    target,\n    context: createEntryDraftMountContext(entryDraft),\n    props: { keyPath, typedKeyPath: '', locale, fieldConfig, showLabel: false },\n  });\n\n/**\n * React component rendering the preview of a field, which `widgetFor()` returns. It’s defined once,\n * so that React keeps the preview mounted when the template renders again, as it does on every\n * change to the entry. The preview follows the draft by itself, so it’s only mounted again when it\n * has to show another field or locale: remounting it on every keystroke would make an image flash,\n * a map reinitialize and the preview lose its state.\n * @param {object} props Props.\n * @param {EntryDraftState} props.entryDraft Entry draft state of the editor.\n * @param {InternalLocaleCode} props.locale Current locale.\n * @param {FieldKeyPath} props.keyPath The key path of the field to preview.\n * @param {Field} props.fieldConfig Configuration of the field.\n * @returns {ReactElement} A div the field preview is mounted into.\n */\nexport const FieldWidget = ({ entryDraft, locale, keyPath, fieldConfig }) => {\n  /** @type {RefObject<HTMLDivElement | null>} */\n  const ref = useRef(null);\n\n  useLayoutEffect(() => {\n    const component = mountFieldPreview({\n      target: /** @type {HTMLDivElement} */ (ref.current),\n      entryDraft,\n      locale,\n      keyPath,\n      fieldConfig,\n    });\n\n    return () => {\n      unmount(component);\n    };\n  }, [entryDraft, locale, keyPath, fieldConfig]);\n\n  return createElement('div', { ref });\n};\n\n/**\n * Create a widget preview function for React preview templates.\n * @param {object} args Arguments.\n * @param {EntryDraftState} args.entryDraft Entry draft state of the editor, used by the field\n * previews.\n * @param {InternalLocaleCode} args.locale Current locale.\n * @param {Omit<GetFieldArgs, 'keyPath'>} args.getFieldArgs Arguments for getField function.\n * @returns {(keyPath: string) => ReactElement | null} Function that creates widget previews.\n */\nexport const createWidgetFor =\n  ({ entryDraft, locale, getFieldArgs }) =>\n  /**\n   * Get a widget preview component for a field.\n   * @param {string} keyPath Field key path.\n   * @returns {ReactElement | null} Widget preview. It’s a React element that renders a Svelte\n   * component inside a div, or `null` if the key path doesn’t point to a configured field, like\n   * Netlify/Decap CMS returns.\n   */\n  (keyPath) => {\n    const fieldConfig = getField({ ...getFieldArgs, keyPath });\n\n    if (!fieldConfig) {\n      return null;\n    }\n\n    return createElement(FieldWidget, { entryDraft, locale, keyPath, fieldConfig });\n  };\n\n/**\n * Create widgets map for an object value. Only the keys pointing to a configured subfield are\n * included.\n * @param {Record<string, any>} obj Object value.\n * @param {string} basePath Base key path.\n * @param {(keyPath: string) => ReactElement | null} widgetFor Function to create widget previews.\n * @returns {MapOf<any>} Immutable Map of widgets.\n */\nexport const createWidgetsMap = (obj, basePath, widgetFor) =>\n  getImmutable().Map(\n    Object.fromEntries(\n      Object.keys(obj)\n        .map((key) => [key, widgetFor(`${basePath}.${key}`)])\n        .filter(([, widget]) => widget !== null),\n    ),\n  );\n\n/**\n * Create a widgetsFor function.\n * @param {RawEntryContent} content Unflattened entry content.\n * @param {(keyPath: string) => ReactElement | null} widgetFor Function to create widget\n * previews.\n * @returns {(name: string) => any} Function that gets widgets data structure for a field.\n */\nexport const createWidgetsFor =\n  (content, widgetFor) =>\n  /**\n   * Get widgets data structure for a given field name. For list fields, returns an array of\n   * ImmutableMaps; for object fields, returns a single ImmutableMap. Each map has `data` and\n   * `widgets` keys containing the field values. Returns the raw value for primitives and `null`/\n   * `undefined` for missing or null fields.\n   * @param {string} name Field name.\n   * @returns {any} Widgets data structure.\n   */\n  (name) => {\n    const value = content[name];\n\n    if (value === null || value === undefined) {\n      return value;\n    }\n\n    const { fromJS, Map: ImmutableMap } = getImmutable();\n\n    if (Array.isArray(value)) {\n      return value.map((item, index) => {\n        const isObject = typeof item === 'object' && item !== null;\n\n        return ImmutableMap({\n          data: fromJS(item),\n          widgets: isObject\n            ? createWidgetsMap(item, `${name}.${index}`, widgetFor)\n            : ImmutableMap({}),\n        });\n      });\n    }\n\n    if (typeof value === 'object') {\n      return ImmutableMap({\n        data: fromJS(value),\n        widgets: createWidgetsMap(value, name, widgetFor),\n      });\n    }\n\n    return value;\n  };\n\n/**\n * Get entries from a collection. If `slug` is provided, returns the entry with the matching slug;\n * otherwise, returns all entries.\n * @param {string} name Collection name.\n * @param {string} [slug] Optional entry slug to filter by.\n * @returns {Promise<(MapOf<ApiEntry>[] | MapOf<ApiEntry>)>} Collection entries.\n */\nexport const getCollectionByName = async (name, slug) => {\n  const collection = getCollection(name);\n\n  if (!collection) {\n    throw new Error(`Collection \"${name}\" not found`);\n  }\n\n  const { defaultLocale } = collection._i18n;\n  const entries = getEntriesByCollection(name);\n\n  const convertArgs = {\n    locale: defaultLocale,\n    collectionName: name,\n    associatedAssets: getAssociatedPreviewAssets({ collectionName: name }),\n  };\n\n  /**\n   * Convert an entry to an Immutable Map with unflattened content and the same metadata shape as\n   * other entry maps.\n   * @param {Entry | undefined} entry Entry object to convert.\n   * @returns {MapOf<ApiEntry>} Immutable Map of entry data.\n   */\n  const convertEntry = (entry) => convertEntryToMap({ ...convertArgs, entry });\n\n  if (slug) {\n    return convertEntry(entries.find((entry) => entry.slug === slug));\n  }\n\n  return entries.map(convertEntry);\n};\n\n/**\n * Prepare props for a custom preview template React component. The `document` and `window` props\n * should be provided by the iframe wrapper.\n * @param {object} options Options.\n * @param {EntryDraftState} options.entryDraft Entry draft state of the editor, used by the field\n * previews mounted by `widgetFor()`.\n * @param {EntryDraft} options.draft Snapshot of the entry draft being previewed.\n * @param {InternalLocaleCode} options.locale Current locale.\n * @returns {Omit<CustomPreviewTemplateProps, 'document' | 'window'>} Props for the React component\n * without `document` and `window`.\n * @see https://decapcms.org/docs/customization/#registerpreviewtemplate\n * @see https://sveltiacms.app/en/docs/api/preview-templates\n */\nexport const preparePreviewTemplateProps = ({ entryDraft, draft, locale }) => {\n  const { entryMap, valueMap, getFieldArgs, fieldsMetaData, getAsset } = buildPreviewData({\n    draft,\n    locale,\n  });\n\n  const widgetFor = createWidgetFor({ entryDraft, locale, getFieldArgs });\n\n  return {\n    entry: entryMap,\n    widgetFor,\n    widgetsFor: createWidgetsFor(unflattenMap(valueMap), widgetFor),\n    getAsset,\n    getCollection: getCollectionByName,\n    fieldsMetaData,\n    // There are some undocumented props in Netlify/Decap CMS that Sveltia CMS doesn’t implement:\n    // boundGetAsset, collection, config, isLoadingAsset, locale, onFieldClick, fields, state\n  };\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { VisibilityObserver } from '@sveltia/ui';\n\n  import EntryPreviewIframe from '$lib/components/contents/details/preview/entry-preview-iframe.svelte';\n  import FieldPreview from '$lib/components/contents/details/preview/field-preview.svelte';\n  import { immutableLoaded, loadImmutable } from '$lib/services/api/immutable';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getValueMapSnapshots } from '$lib/services/contents/draft/value-map.svelte';\n  import { getPreviewTemplate } from '$lib/services/contents/editor/preview-frame';\n  import { getPreviewStyleURLs } from '$lib/services/contents/editor/preview-styles';\n  import { preparePreviewTemplateProps } from '$lib/services/contents/editor/preview-templates';\n\n  /**\n   * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Current pane’s locale.\n   * @property {(iframe: HTMLIFrameElement) => void} [onFrameLoad] Function called with the preview\n   * iframe once its content has been loaded, if a custom preview stylesheet or template is used.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { locale, onFrameLoad } = $props();\n\n  const {\n    collectionName,\n    fileName,\n    fields = [],\n  } = $derived(/** @type {EntryDraft} */ (entryDraft.current ?? {}));\n  const styleURLs = $derived(getPreviewStyleURLs({ collectionName, fileName }));\n  const reactComponent = $derived(getPreviewTemplate({ collectionName, fileName }));\n  // The template receives Immutable Maps, so the props can only be built once the library is loaded\n  const reactProps = $derived(\n    entryDraft.current && reactComponent && immutableLoaded.current\n      ? preparePreviewTemplateProps({\n          entryDraft,\n          // Only the values have to be detached from the draft. Snapshotting the whole draft on\n          // every keystroke would also copy the collection configuration, the original entry and\n          // values and the validation state, and re-render the template whenever any of them\n          // changed, e.g. when a list item is expanded. The shared snapshots are used, so a locale\n          // that hasn’t changed isn’t copied again\n          draft: { ...entryDraft.current, currentValues: getValueMapSnapshots(entryDraft.current) },\n          locale,\n        })\n      : undefined,\n  );\n\n  $effect(() => {\n    if (reactComponent) {\n      // Normally already in flight, as `CMS.registerPreviewTemplate()` starts loading the library\n      /* v8 ignore next 4 -- the library is bundled with the tests, so loading can’t fail */\n      loadImmutable().catch((/** @type {Error} */ error) => {\n        // eslint-disable-next-line no-console\n        console.error(error);\n      });\n    }\n  });\n</script>\n\n{#snippet children()}\n  {#each fields as fieldConfig (fieldConfig.name)}\n    <!-- Mark the field outside its observer, so that focusing it in the Edit Pane can scroll the\n      preview to it even before it’s rendered -->\n    <div role=\"none\" data-lazy-key-path={fieldConfig.name}>\n      <VisibilityObserver>\n        <FieldPreview\n          keyPath={fieldConfig.name}\n          typedKeyPath={fieldConfig.name}\n          {locale}\n          {fieldConfig}\n        />\n      </VisibilityObserver>\n    </div>\n  {/each}\n{/snippet}\n\n<VisibilityObserver>\n  {#if reactComponent && reactProps}\n    <EntryPreviewIframe {locale} {styleURLs} {reactComponent} {reactProps} onLoad={onFrameLoad} />\n  {:else if styleURLs.length}\n    <EntryPreviewIframe {locale} {styleURLs} {children} onLoad={onFrameLoad} />\n  {:else}\n    <div role=\"document\" aria-label={_('content_preview')}>\n      {@render children()}\n    </div>\n  {/if}\n</VisibilityObserver>\n\n<style>\n  [role='document'] {\n    --entry-preview-padding-block: 8px;\n    --entry-preview-padding-inline: 16px;\n    padding-block: var(--entry-preview-padding-block);\n    padding-inline: var(--entry-preview-padding-inline);\n    /* Keep the content written by other users within the preview, even if it’s positioned */\n    contain: paint;\n  }\n</style>\n","import {\n  findLazyFieldElement,\n  getFieldAlignedScrollTop,\n  getProportionalScrollTop,\n  getRevealingScrollTop,\n} from '$lib/services/contents/editor/scroll';\nimport { createLatestGuard } from '$lib/services/utils/scheduling';\n\n/**\n * @import { EntryEditorPane } from '$lib/types/private';\n */\n\n/**\n * Content area the user is scrolling, with the mouse wheel or a touch. Only its scroll events are\n * synced to the other pane: the other pane’s own scroll events come from being synced, and syncing\n * them back would make the panes chase each other. It’s shared by the two panes.\n * @type {HTMLElement | undefined}\n */\nlet scrollSource;\n/**\n * Guard to leave the other pane alone once another field has been focused or either pane has been\n * scrolled by the user.\n */\nconst revealGuard = createLatestGuard();\n/** @type {AddEventListenerOptions} */\nconst eventOptions = { capture: true, passive: true };\n/**\n * Options for the scroll listener, which isn’t capturing: scroll events don’t bubble, and capturing\n * would also get those of a field scrolled within the pane, e.g. a text area.\n * @type {AddEventListenerOptions}\n */\nconst scrollEventOptions = { passive: true };\n\n/**\n * Get the top left corner of a pane’s visible area, in the viewport of the pane’s document.\n * @param {HTMLElement} pane Pane’s content area, or the preview iframe’s root element.\n * @returns {{ x: number, y: number }} Coordinates in pixels.\n */\nconst getViewOrigin = (pane) => {\n  // The preview iframe’s root element is its viewport, while the content area of the main document\n  // is an element in it\n  if (pane === pane.ownerDocument.documentElement) {\n    return { x: 0, y: 0 };\n  }\n\n  const { left, top } = pane.getBoundingClientRect();\n\n  return { x: left, y: top };\n};\n\n/**\n * Get the top of a pane’s visible area, in the viewport of the pane’s document.\n * @param {HTMLElement} pane Pane’s content area, or the preview iframe’s root element.\n * @returns {number} Top in pixels.\n */\nconst getViewTop = (pane) => getViewOrigin(pane).y;\n\n/**\n * Get the top of an element in a pane’s scrollable content: the pane’s scroll position that would\n * bring the element to the top of the pane. The element’s `offsetTop` can’t tell, as it’s\n * relative to its offset parent, which is seldom the pane: the default preview’s root element, the\n * area wrapping the edit pane’s fields, or the preview iframe’s `<body>`.\n * @param {HTMLElement} pane Pane’s content area, or the preview iframe’s root element.\n * @param {HTMLElement} element Element in the pane.\n * @returns {number} Top in pixels.\n */\nexport const getContentTop = (pane, element) =>\n  element.getBoundingClientRect().top - getViewTop(pane) + pane.scrollTop;\n\n/**\n * Get the scroll position of the other pane that reveals the given element in it.\n * @param {HTMLElement} pane The other pane’s content area.\n * @param {HTMLElement} element Element in the pane.\n * @param {boolean} [always] Whether to get the position even if the element is already visible.\n * @returns {number | undefined} Scroll position, or `undefined` if the element is already visible.\n */\nexport const getThatScrollTop = (pane, element, always = false) => {\n  const { top, height } = element.getBoundingClientRect();\n  const { scrollTop, clientHeight } = pane;\n\n  return getRevealingScrollTop({\n    viewTop: getViewTop(pane),\n    viewHeight: clientHeight,\n    scrollTop,\n    top,\n    height,\n    always,\n  });\n};\n\n/**\n * @typedef {object} ScrollSyncPane\n * @property {boolean | undefined} syncScrolling Whether Sync Scrolling is turned on.\n * @property {EntryEditorPane['mode'] | undefined} mode Mode of this pane.\n * @property {HTMLElement | undefined} contentArea Main content area of this pane.\n * @property {HTMLElement | undefined} thisPaneContentArea Element of this pane that is scrolled:\n * the main content area, or the preview iframe’s root element. It’s set by the controller.\n * @property {HTMLElement | undefined} thatPaneContentArea Another pane’s content area.\n */\n\n/**\n * Create a controller that keeps the scroll position of an edit/preview pane in sync with the other\n * pane.\n * @param {ScrollSyncPane} props Properties of the pane, which should be getters (and a setter for\n * `thisPaneContentArea`) so that the controller always sees the latest values of the component.\n * @returns {{\n * initialize: () => void,\n * setPreviewFrame: (iframe: HTMLIFrameElement) => void,\n * onFocusIn: (event: FocusEvent) => void,\n * destroy: () => void,\n * }} Controller.\n */\nexport const createScrollSync = (props) => {\n  /**\n   * Element receiving the scroll events of this pane’s content area: the area itself, or the\n   * preview iframe’s document, whose root element doesn’t get the events of its own scrolling.\n   * @type {HTMLElement | Document | undefined}\n   */\n  let scrollEventTarget;\n  /**\n   * Preview iframe, which is used in the preview mode only when a custom preview stylesheet or\n   * template applies to the entry. It’s set once the frame has loaded its content, which may take a\n   * while: the preview is rendered lazily once it’s visible, and a template waits for Immutable.js\n   * to be loaded.\n   * @type {HTMLIFrameElement | undefined}\n   */\n  let previewFrame;\n\n  /**\n   * Sync the scroll position with the other edit/preview pane.\n   */\n  const syncScrollPosition = () => {\n    window.requestAnimationFrame(() => {\n      const { contentArea } = props;\n      const { thisPaneContentArea } = props;\n      const { thatPaneContentArea } = props;\n\n      if (!props.syncScrolling || !contentArea || !thisPaneContentArea || !thatPaneContentArea) {\n        return;\n      }\n\n      const { x, y } = getViewOrigin(thisPaneContentArea);\n      const { ownerDocument, scrollTop, scrollHeight, clientHeight } = thisPaneContentArea;\n\n      // At the top of this pane, the other one goes to its top as well, rather than bringing the\n      // field there to its top edge, which would scroll the padding and anything else above the\n      // field out of view\n      if (scrollTop <= 0) {\n        thatPaneContentArea.scrollTop = 0;\n\n        return;\n      }\n\n      // Find the field section in the top left corner of the content area. Use `findLast` to\n      // capture the topmost element; otherwise the List field sticky headers will interfere with\n      // the positioning.\n      // @see https://github.com/sveltia/sveltia-cms/issues/883\n      const thisElement = /** @type {HTMLElement | undefined} */ (\n        ownerDocument.elementsFromPoint(x + 80, y).findLast((e) => e.matches('[data-key-path]'))\n      );\n\n      if (!thisElement) {\n        // Calculate the scroll position based on the current scroll position of the this pane\n        thatPaneContentArea.scrollTop = getProportionalScrollTop({\n          scrollTop,\n          scrollHeight,\n          clientHeight,\n          targetScrollHeight: thatPaneContentArea.scrollHeight,\n          targetClientHeight: thatPaneContentArea.clientHeight,\n        });\n\n        return;\n      }\n\n      // The element was found by that very attribute, so the key path is there\n      const { keyPath } = /** @type {{ keyPath: string }} */ (thisElement.dataset);\n      const { top, height } = thisElement.getBoundingClientRect();\n\n      const thatElement = /** @type {HTMLElement | undefined} */ (\n        thatPaneContentArea.querySelector(`[data-key-path=\"${CSS.escape(keyPath)}\"]`)\n      );\n\n      // Scroll the other pane to the corresponding element, adjusting for the current scroll\n      // position and the ratio of the scroll position within the element.\n      const thatScrollTop = thatElement\n        ? getFieldAlignedScrollTop({\n            y,\n            top,\n            height,\n            targetTop: getContentTop(thatPaneContentArea, thatElement),\n            targetHeight: thatElement.getBoundingClientRect().height,\n          })\n        : undefined;\n\n      if (thatScrollTop !== undefined) {\n        thatPaneContentArea.scrollTop = thatScrollTop;\n      }\n    });\n  };\n\n  /**\n   * Mark this pane as the one the user is scrolling. The wheel and touch events come before the\n   * pane is scrolled, so the sync waits for the scroll events that follow.\n   */\n  const markScrollSource = () => {\n    scrollSource = props.thisPaneContentArea;\n    // Stop revealing a focused field, which would undo the user’s scrolling\n    revealGuard.next();\n  };\n\n  /**\n   * Sync the other pane once this pane has been scrolled by the user.\n   */\n  const onScroll = () => {\n    if (scrollSource === props.thisPaneContentArea) {\n      syncScrollPosition();\n    }\n  };\n\n  /**\n   * Scroll the other pane to the given field if it’s not visible there. The default preview renders\n   * fields lazily, so the pane may have to be scrolled towards the field until it’s rendered.\n   * @param {HTMLElement} field Field element in this pane.\n   */\n  const revealField = async (field) => {\n    const { thisPaneContentArea } = props;\n    const { thatPaneContentArea } = props;\n\n    if (\n      !props.syncScrolling ||\n      !thisPaneContentArea ||\n      !thatPaneContentArea ||\n      !field.isConnected\n    ) {\n      return;\n    }\n\n    const isLatest = revealGuard.next();\n    const pane = thatPaneContentArea;\n    const { scrollTop: originalScrollTop } = pane;\n    // The field was found by that very attribute, so the key path is there\n    const { keyPath } = /** @type {{ keyPath: string }} */ (field.dataset);\n\n    const element = await findLazyFieldElement({\n      container: pane,\n      keyPath,\n      /**\n       * Scroll the other pane to an element instantly, so it renders what comes into view.\n       * @param {HTMLElement} target Element.\n       * @returns {boolean} Whether the pane has been scrolled.\n       */\n      scrollTo: (target) => {\n        const { scrollTop } = pane;\n\n        // Make this pane the scroll source, so that the other pane being scrolled doesn’t scroll\n        // this one in turn\n        scrollSource = thisPaneContentArea;\n        pane.scrollTo({\n          // A position is always given when asked for one even if the element is visible\n          top: /** @type {number} */ (getThatScrollTop(pane, target, true)),\n          behavior: 'instant',\n        });\n\n        // Ignore a subpixel difference, which the browser may make when scrolling to where the\n        // pane already is\n        return Math.abs(pane.scrollTop - scrollTop) >= 1;\n      },\n      /**\n       * Tell whether another field has been focused, either pane has been scrolled by the user, or\n       * Sync Scrolling has been turned off since.\n       * @returns {boolean} Result.\n       */\n      isOutdated: () => !isLatest() || !props.syncScrolling,\n    });\n\n    if (!element) {\n      // Put the pane back if it was scrolled towards a field that turned out not to be shown in\n      // it, unless the search was abandoned\n      if (isLatest() && props.syncScrolling && pane.scrollTop !== originalScrollTop) {\n        scrollSource = thisPaneContentArea;\n        pane.scrollTo({ top: originalScrollTop, behavior: 'instant' });\n      }\n\n      return;\n    }\n\n    const thatScrollTop = getThatScrollTop(pane, element);\n\n    if (thatScrollTop === undefined) {\n      return;\n    }\n\n    scrollSource = thisPaneContentArea;\n    pane.scrollTo({ top: thatScrollTop, behavior: 'smooth' });\n  };\n\n  return {\n    /**\n     * Initialize the scroll synchronization by setting up event listeners on this pane’s content\n     * area: the preview iframe’s root element once the frame has loaded, or the main content area.\n     * Until the frame has loaded, the main content area is listened to.\n     */\n    initialize: () => {\n      const { contentArea } = props;\n\n      if (!contentArea) {\n        return;\n      }\n\n      const previous = props.thisPaneContentArea;\n\n      if (previous) {\n        // Remove previous event listeners if they exist\n        previous.removeEventListener('wheel', markScrollSource, eventOptions);\n        previous.removeEventListener('touchstart', markScrollSource, eventOptions);\n        scrollEventTarget?.removeEventListener('scroll', onScroll, scrollEventOptions);\n      }\n\n      // Forget the frame of a previous preview, which is gone once the pane has switched to the\n      // edit mode, so it doesn’t keep the frame’s document from being garbage-collected\n      if (previewFrame && !contentArea.contains(previewFrame)) {\n        previewFrame = undefined;\n      }\n\n      // A frame that has navigated to another origin, e.g. after a link in a preview template was\n      // followed, has no document within reach, so the main content area is listened to instead\n      const frameRoot = previewFrame?.contentDocument?.documentElement ?? undefined;\n      const target = frameRoot ?? contentArea;\n\n      props.thisPaneContentArea = target;\n      scrollEventTarget = frameRoot ? frameRoot.ownerDocument : contentArea;\n      target.scrollTop = 0;\n      // Add event listeners manually to use passive mode\n      target.addEventListener('wheel', markScrollSource, eventOptions);\n      target.addEventListener('touchstart', markScrollSource, eventOptions);\n      scrollEventTarget.addEventListener('scroll', onScroll, scrollEventOptions);\n    },\n\n    /**\n     * Remember the preview iframe once it has loaded its content.\n     * @param {HTMLIFrameElement} iframe Preview iframe.\n     */\n    setPreviewFrame: (iframe) => {\n      previewFrame = iframe;\n    },\n\n    /**\n     * Scroll the other pane to the field focused in this edit pane, so the user can see the field\n     * they’re editing in the preview. Scroll Synchronization follows scrolling only.\n     * @param {FocusEvent} event `focusin` event.\n     * @see https://github.com/sveltia/sveltia-cms/issues/1069\n     */\n    onFocusIn: (event) => {\n      const field = /** @type {HTMLElement | null} */ (\n        /** @type {HTMLElement} */ (event.target).closest('.field[data-key-path]')\n      );\n\n      if (props.mode !== 'edit' || !field) {\n        return;\n      }\n\n      // Focusing the field may scroll this pane to it, and the scroll event that follows syncs the\n      // other pane in an animation frame of its own. Wait for that frame, so that the sync doesn’t\n      // undo the scrolling\n      window.requestAnimationFrame(() => {\n        window.requestAnimationFrame(() => {\n          revealField(field);\n        });\n      });\n    },\n\n    /**\n     * Forget this pane once it’s gone, so the module-level reference doesn’t keep the DOM of a\n     * closed editor from being garbage-collected.\n     */\n    destroy: () => {\n      if (scrollSource === props.thisPaneContentArea) {\n        scrollSource = undefined;\n      }\n    },\n  };\n};\n","<script>\n  import { untrack } from 'svelte';\n\n  import DisabledLocaleState from '$lib/components/contents/details/disabled-locale-state.svelte';\n  import EntryEditor from '$lib/components/contents/details/editor/entry-editor.svelte';\n  import EntryPreview from '$lib/components/contents/details/preview/entry-preview.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { createScrollSync } from '$lib/services/contents/editor/scroll-sync';\n  import { entryEditorSettings } from '$lib/services/contents/editor/settings';\n\n  /**\n   * @import { EntryEditorPane, InternalLocaleCode } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} id The wrapper element’s `id` attribute.\n   * @property {{ current: ?EntryEditorPane }} thisPane This pane’s mode and locale.\n   * @property {HTMLElement} [thisPaneContentArea] This pane’s content area, bound for the parent.\n   * @property {HTMLElement} [thatPaneContentArea] Another pane’s content area.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let {\n    id,\n    thisPane,\n    thisPaneContentArea = $bindable(),\n    thatPaneContentArea = undefined,\n  } = $props();\n\n  const { syncScrolling } = $derived(entryEditorSettings.current ?? {});\n  const locale = $derived(thisPane.current?.locale);\n  const mode = $derived(thisPane.current?.mode);\n  // A pane in the edit mode always has a locale\n  const editLocale = $derived(/** @type {InternalLocaleCode} */ (locale));\n\n  /** @type {HTMLElement | undefined} */\n  let contentArea = $state();\n\n  /* eslint-disable jsdoc/require-jsdoc */\n  const scrollSync = createScrollSync({\n    get syncScrolling() {\n      return syncScrolling;\n    },\n    get mode() {\n      return mode;\n    },\n    get contentArea() {\n      return contentArea;\n    },\n    get thisPaneContentArea() {\n      return thisPaneContentArea;\n    },\n    set thisPaneContentArea(element) {\n      thisPaneContentArea = element;\n    },\n    get thatPaneContentArea() {\n      return thatPaneContentArea;\n    },\n  });\n  /* eslint-enable jsdoc/require-jsdoc */\n\n  $effect(() => {\n    // Initialize the scroll synchronization when the content area is ready. The pane mode is also a\n    // dependency because the edit mode always uses the main content area, while the preview mode\n    // uses an iframe if a custom preview stylesheet or template applies. The iframe is only there\n    // once it has loaded, so it initializes the sync again then.\n    void [thisPane.current?.mode, contentArea];\n    // The initialization writes `thisPaneContentArea`, which it also reads, so it’s left out of\n    // the dependencies to keep the effect from running again on its own account\n    untrack(() => scrollSync.initialize());\n  });\n\n  // Forget this pane once it’s gone, so the module-level reference doesn’t keep the DOM of a closed\n  // editor from being garbage-collected\n  $effect(() => () => {\n    scrollSync.destroy();\n  });\n</script>\n\n<div role=\"none\" {id} class=\"wrapper\">\n  {#if locale && entryDraft.current?.currentLocales[locale]}\n    <div role=\"none\" class=\"content\" bind:this={contentArea} onfocusin={scrollSync.onFocusIn}>\n      {#if mode === 'preview'}\n        <EntryPreview\n          {locale}\n          onFrameLoad={(iframe) => {\n            scrollSync.setPreviewFrame(iframe);\n            scrollSync.initialize();\n          }}\n        />\n      {:else}\n        <EntryEditor {locale} />\n      {/if}\n    </div>\n  {:else if mode === 'edit'}\n    <DisabledLocaleState locale={editLocale} />\n  {/if}\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n  }\n\n  .content {\n    --field-editor-padding: 16px;\n    flex: auto;\n    overflow-y: auto;\n    scroll-behavior: auto; /* Don’t use smooth scroll for syncing */\n    overscroll-behavior-y: contain;\n\n    @media (width < 768px) {\n      --field-editor-padding: 12px;\n    }\n  }\n</style>\n","<!--\n  @component\n  Ask the user to confirm reverting the changes, restoring the default values or clearing the\n  fields of the entry being edited, in a locale or in every locale, and take the action once\n  confirmed. The action can’t be undone, other than by reverting the changes.\n-->\n<script>\n  import { ConfirmationDialog } from '@sveltia/ui';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { resetEntry } from '$lib/services/contents/draft/update/reset';\n  import { revertChanges } from '$lib/services/contents/draft/update/revert';\n  import { getResetConfirmation, getResetLabel } from '$lib/services/contents/editor/reset';\n\n  /**\n   * @import { InternalLocaleCode } from '$lib/types/private';\n   * @import { ResetAction } from '$lib/services/contents/editor/reset';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} open Whether the dialog is open.\n   * @property {ResetAction} action Action to confirm. It’s kept while the dialog closes, so the\n   * dialog doesn’t change its text meanwhile.\n   * @property {InternalLocaleCode} [locale] Locale to take the action in. If omitted, the action\n   * applies to every locale.\n   * @property {() => void} [onClose] Function called once the dialog is closed, e.g. to move the\n   * focus back to the menu button.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { open = $bindable(false), action, locale = undefined, onClose = undefined } = $props();\n\n  const label = $derived(getResetLabel(action, locale ? 'locale' : 'entry'));\n</script>\n\n<ConfirmationDialog\n  bind:open\n  title={label}\n  okLabel={label}\n  onOk={() => {\n    const draft = entryDraft.current;\n\n    /* v8 ignore next 3 -- the dialog is only opened while the draft is there */\n    if (!draft) {\n      return;\n    }\n\n    if (action === 'revert') {\n      revertChanges({ draft, locale });\n    } else {\n      resetEntry({ draft, locale, restore: action === 'restore' });\n    }\n  }}\n  onClose={() => {\n    onClose?.();\n  }}\n>\n  {getResetConfirmation(action, locale)}\n</ConfirmationDialog>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon } from '@sveltia/ui';\n\n  import { afterPendingFieldUpdates } from '$lib/services/contents/editor/pending';\n\n  /**\n   * @import { EntryEditorPane } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {{ current: ?EntryEditorPane }} thisPane This pane’s mode and locale.\n   */\n\n  /** @type {Props} */\n  let { thisPane } = $props();\n</script>\n\n<Button\n  variant=\"ghost\"\n  iconic\n  aria-label={_('preview')}\n  pressed={thisPane.current?.mode === 'preview'}\n  onclick={() => {\n    // The preview replaces the field editors, which would drop an update still in flight\n    afterPendingFieldUpdates(() => {\n      thisPane.current = {\n        mode: thisPane.current?.mode === 'preview' ? 'edit' : 'preview',\n        locale: thisPane.current?.locale ?? '',\n      };\n    });\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name=\"visibility\" />\n  {/snippet}\n</Button>\n","import { getEntryPreviewURL } from '$lib/services/contents/entry';\n\n/**\n * @import {\n * DeployState,\n * DeployStatus,\n * Entry,\n * EntryPreviewLink,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalLocaleCode,\n * PageLiveness,\n * WorkflowPullRequest,\n * } from '$lib/types/private';\n */\n\n/**\n * Combine the state reported by the CI/CD provider with the result of a liveness check on the\n * composed URL. A page that responds beats a stale build status, and a page that doesn’t respond\n * yet keeps a finished build in the pending state, which is what a CDN that hasn’t propagated looks\n * like. An inconclusive check never overrides the provider, and it never reports a failure.\n * @param {DeployState} state State reported by the provider.\n * @param {PageLiveness} [liveness] Result of the liveness check, if one was made.\n * @returns {DeployState} Refined state.\n */\nexport const refineState = (state, liveness) => {\n  if (state === 'error' || !liveness || liveness === 'unknown') {\n    return state;\n  }\n\n  if (liveness === 'ready') {\n    return 'ready';\n  }\n\n  return state === 'ready' ? 'pending' : state;\n};\n\n/**\n * Resolve the preview link for one entry and locale, combining the site configuration with the\n * deployment stores. This is a pure function, so components can call it inside a `$derived` with\n * the store values passed in and stay reactive.\n *\n * The liveness of the composed URL is deliberately not taken into account here. A liveness check is\n * made from an effect that watches this URL, and it writes its result to the `pageLiveness` store,\n * so reading that store to resolve the link would put the store on both ends of the same cycle: the\n * check would change the link, the link would restart the check. Apply {@link refineState} to the\n * returned `state` separately to fold the liveness in.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry.\n * @param {InternalLocaleCode} args.locale Locale.\n * @param {InternalCollection} args.collection Collection.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file. File/singleton collection\n * only.\n * @param {WorkflowPullRequest} [args.pullRequest] Pull request holding the entry, if it’s an\n * unpublished Editorial Workflow entry.\n * @param {Record<string, DeployStatus>} args.deployments Value of the `deployments` store.\n * @param {string} args.productionSHA Value of the {@link productionSHA} store.\n * @param {boolean} [args.pollTimedOut] Value of the `deployPollTimedOut` store. Once the re-checks\n * have given up, the wait is over whatever the last reported state was.\n * @returns {EntryPreviewLink | undefined} Resolved link, or `undefined` when there’s nothing to\n * show.\n * @see https://github.com/sveltia/sveltia-cms/issues/943\n */\nexport const getEntryPreviewLink = ({\n  entry,\n  locale,\n  collection,\n  collectionFile,\n  pullRequest,\n  deployments: deployMap,\n  productionSHA: prodSHA,\n  pollTimedOut = false,\n}) => {\n  /**\n   * Compose the full URL for the entry with the given base.\n   * @param {string} [baseURL] Base URL, or `undefined` to use the configured site URL.\n   * @param {boolean} [fallbackToRoot] Whether to link to the root of the site when the collection\n   * has no `preview_path` option.\n   * @returns {string | undefined} URL.\n   */\n  const compose = (baseURL, fallbackToRoot = false) =>\n    getEntryPreviewURL(entry, locale, collection, collectionFile, { baseURL, fallbackToRoot });\n\n  if (pullRequest) {\n    const deploy = pullRequest.headSHA ? deployMap[pullRequest.headSHA] : undefined;\n    // Without a `preview_path`, the root of the deploy preview is still worth opening, like in\n    // Decap CMS: its address changes with each pull request, and the link carries the build state\n    const previewURL = deploy?.url ? compose(deploy.url, true) : undefined;\n\n    if (deploy && previewURL) {\n      return {\n        url: previewURL,\n        state: deploy.state,\n        isDeployPreview: true,\n        awaitingPreview: false,\n        // A preview address only arrives once the build is done, so the one thing left to check is\n        // whether the page is actually being served yet, exactly as for the live site\n        pingable: true,\n      };\n    }\n\n    // No preview to open: the build may still be queued, or no provider may report one at all.\n    // Either way the live site link is what the CMS has always offered, so it stays where it is\n    // rather than leaving the toolbar empty until a build appears. It isn’t checked for liveness,\n    // because an unpublished entry isn’t on the live site yet. The build state still travels with\n    // it, so the control can say that a preview is on its way\n    const url = compose();\n\n    if (!url) {\n      return undefined;\n    }\n\n    const state = deploy?.state ?? 'unknown';\n\n    return {\n      url,\n      state,\n      isDeployPreview: false,\n      // A build is on its way, so the live site isn’t where this entry can be seen — it holds the\n      // published version, or nothing at all when the entry is new. The control says as much\n      // rather than offering a link that leads somewhere else. Once the re-checks have given up,\n      // nothing is coming, and a control that still says it’s waiting would be lying\n      awaitingPreview: !pollTimedOut && (state === 'checking' || state === 'pending'),\n      pingable: false,\n    };\n  }\n\n  const deploy = prodSHA ? deployMap[prodSHA] : undefined;\n  // The configured site URL wins; the deployment’s own URL fills in when `site_url` is unset\n  const url = compose() ?? compose(deploy?.url);\n\n  if (!url) {\n    return undefined;\n  }\n\n  return {\n    url,\n    state: deploy?.state ?? 'unknown',\n    isDeployPreview: false,\n    // The live site is exactly where a published entry can be seen, whatever a build is doing\n    awaitingPreview: false,\n    pingable: true,\n  };\n};\n","<!--\n  @component\n  Control that opens the preview page for an entry: the deploy preview built for an unpublished\n  Editorial Workflow entry when there is one, otherwise the page on the live site. It reflects the\n  state of the deployment, so a build that hasn’t finished yet is presented as such instead of a\n  link that would only return a 404. It renders as either a toolbar button or a menu item, because\n  the entry editor offers the link in both places.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, MenuItem } from '@sveltia/ui';\n\n  import { deployments, deployPollTimedOut, productionSHA } from '$lib/services/deployments';\n  import { DEPLOY_STATE_MESSAGES } from '$lib/services/deployments/constants';\n  import { getEntryPreviewLink, refineState } from '$lib/services/deployments/link';\n  import { pageLiveness, pingURL } from '$lib/services/deployments/ping';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @import {\n   * DeployState,\n   * Entry,\n   * InternalCollection,\n   * InternalCollectionFile,\n   * InternalLocaleCode,\n   * WorkflowPullRequest,\n   * } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Entry} entry Entry to be previewed.\n   * @property {InternalLocaleCode} locale Locale of the entry to be previewed.\n   * @property {InternalCollection} collection Collection that the entry belongs to.\n   * @property {InternalCollectionFile} [collectionFile] Collection file. File/singleton collection\n   * only.\n   * @property {WorkflowPullRequest} [pullRequest] Pull request holding the entry, if it’s an\n   * unpublished Editorial Workflow entry.\n   * @property {'button' | 'menuitem'} [as] Form to be rendered.\n   * @property {'primary' | 'secondary' | 'tertiary' | 'ghost' | 'link'} [variant] Style variant of\n   * the button. Not used when the control is rendered as a menu item.\n   * @property {'small' | 'medium' | 'large'} [size] Size of the button. Not used when the control\n   * is rendered as a menu item.\n   * @property {boolean} [iconic] Whether to show the icon alone, for a narrow screen where the\n   * label wouldn’t fit alongside the other actions. The label becomes the accessible name. Not\n   * used when the control is rendered as a menu item.\n   */\n\n  /** @type {Props} */\n  let {\n    entry,\n    locale,\n    collection,\n    collectionFile,\n    pullRequest,\n    as = 'button',\n    variant = 'ghost',\n    size = 'medium',\n    iconic = false,\n  } = $props();\n\n  // `pageLiveness.current` is deliberately left out of this derivation. The effect below watches\n  // `url` and writes that state, so reading it here would feed the check’s own result back into the\n  // URL it checks. The liveness is folded into `state` alone, which the effect doesn’t read\n  // @see https://github.com/sveltia/sveltia-cms/issues/943\n  const link = $derived(\n    getEntryPreviewLink({\n      entry,\n      locale,\n      collection,\n      collectionFile,\n      pullRequest,\n      deployments: deployments.current,\n      productionSHA: productionSHA.current,\n      pollTimedOut: deployPollTimedOut.current,\n    }),\n  );\n  const url = $derived(link?.url);\n  /* v8 ignore start -- only read while there’s a link, which always has a URL */\n  const state = $derived(\n    link ? refineState(link.state, url ? pageLiveness.current[url] : undefined) : undefined,\n  );\n  const isDeployPreview = $derived(link?.isDeployPreview ?? false);\n  const pingable = $derived(link?.pingable ?? false);\n  // The URL leads to the published version, or nowhere when the entry is new, so the control waits\n  // rather than sending anyone there\n  const awaitingPreview = $derived(link?.awaitingPreview ?? false);\n  /* v8 ignore stop */\n  // A failed build’s URL is its log rather than a preview, so there’s nothing worth opening. A\n  // link to the live site is always worth offering, whatever the build did\n  const disabled = $derived(awaitingPreview || !url || (isDeployPreview && state === 'error'));\n  const label = $derived(\n    awaitingPreview\n      ? _('deploy_preview.awaiting')\n      : isDeployPreview\n        ? _('deploy_preview.view')\n        : _('view_on_live_site'),\n  );\n  // The label says where the link goes, not what the build is doing, so anything other than a\n  // finished build needs the reason spelled out. The cast is safe: `state` is only missing without\n  // a link, when nothing is rendered\n  const descriptionKey = $derived(DEPLOY_STATE_MESSAGES[/** @type {DeployState} */ (state)]);\n  const description = $derived(descriptionKey ? _(descriptionKey) : undefined);\n\n  /**\n   * Open the resolved preview page in a new browser tab.\n   */\n  const open = () => {\n    /* v8 ignore next 3 -- the control is disabled without a URL */\n    if (url) {\n      openNewTab(url);\n    }\n  };\n\n  $effect(() => {\n    // None of these reads the liveness store this effect writes, so the check can’t retrigger\n    // itself however the URL is composed. The build state reported by the provider is read, so a\n    // page found missing while it was building is checked again once the build has finished\n    const canPing = pingable;\n    const pageURL = url;\n    const buildFinished = link?.state === 'ready';\n\n    if (canPing && pageURL) {\n      pingURL(pageURL, { recheckPending: buildFinished });\n    }\n\n    return undefined;\n  });\n</script>\n\n{#if link}\n  {#if as === 'menuitem'}\n    <MenuItem {label} {disabled} aria-description={description} onclick={open} />\n  {:else}\n    <Button\n      {variant}\n      {size}\n      {iconic}\n      label={iconic ? undefined : label}\n      aria-label={iconic ? label : undefined}\n      {disabled}\n      aria-description={description}\n      onclick={open}\n    >\n      {#snippet endIcon()}\n        <div role=\"none\" class=\"icon-wrapper\">\n          <Icon\n            class={awaitingPreview ? 'spinning' : undefined}\n            name={awaitingPreview ? 'progress_activity' : 'open_in_new'}\n          />\n        </div>\n      {/snippet}\n    </Button>\n  {/if}\n{/if}\n\n<style>\n  .icon-wrapper {\n    display: contents;\n\n    & :global(.spinning) {\n      animation: spin 1.6s linear infinite;\n    }\n\n    @media (prefers-reduced-motion: reduce) {\n      & :global(.spinning) {\n        animation: none;\n      }\n    }\n  }\n\n  @keyframes spin {\n    to {\n      transform: rotate(360deg);\n    }\n  }\n</style>\n","import { _ } from '@sveltia/i18n';\nimport { untrack } from 'svelte';\n\nimport { MIN_PANE_SIZE } from '$lib/services/contents/editor';\nimport { entryEditorSettings } from '$lib/services/contents/editor/settings';\nimport { getLocaleLabel } from '$lib/services/contents/i18n';\nimport { DEFAULT_LOCALE_KEY } from '$lib/services/contents/i18n/config/constants';\n\n/**\n * @import { EntryEditorPane, InternalCollection, InternalCollectionFile, InternalLocaleCode }\n * from '$lib/types/private';\n */\n\n/**\n * I18n keys of the strings naming a locale’s content in the editor, e.g. “Edit English Content”,\n * mapped to the keys of the same strings without the locale, for the content of a monolingual\n * entry, e.g. “Edit Content”.\n */\nconst LOCALE_CONTENT_KEYS = {\n  edit_x_locale: 'edit_content',\n  preview_x_locale: 'preview_content',\n  show_content_options_x_locale: 'show_content_options',\n  content_options_x_locale: 'content_options',\n};\n\n/**\n * Localize a string naming a locale’s content in the editor. The content of a monolingual entry\n * has no locale to name, so the string without it is used rather than the internal locale key.\n * @param {keyof LOCALE_CONTENT_KEYS} key I18n key of the string with the locale.\n * @param {InternalLocaleCode} locale Locale code.\n * @returns {string} Localized string.\n */\nexport const getLocaleContentLabel = (key, locale) =>\n  locale === DEFAULT_LOCALE_KEY\n    ? _(LOCALE_CONTENT_KEYS[key])\n    : _(key, { values: { locale: getLocaleLabel(locale) ?? locale } });\n\n/**\n * Get the key under which the pane state of the given collection or collection file is saved.\n * @param {object} args Arguments.\n * @param {InternalCollection} [args.collection] Collection.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file, if any.\n * @returns {string | undefined} Key, or `undefined` without a collection.\n */\nexport const getPaneStateKey = ({ collection, collectionFile }) =>\n  collectionFile?.name ? [collection?.name, collectionFile.name].join('|') : collection?.name;\n\n/**\n * Get the sizes of the editor panes, in percent. The saved widths are used when both panes are\n * shown and the widths are sound; otherwise the panes are split evenly, or a lone pane takes it\n * all.\n * @param {object} args Arguments.\n * @param {?EntryEditorPane} args.firstPane First pane.\n * @param {?EntryEditorPane} args.secondPane Second pane.\n * @returns {[number, number, number]} Sizes of the first and second panes, and the minimum size\n * of a pane, which is `0` when a pane can’t be resized.\n */\nexport const getPaneSizes = ({ firstPane, secondPane }) => {\n  if (!firstPane && !secondPane) {\n    return [0, 0, 0];\n  }\n\n  if (!firstPane || !secondPane) {\n    return [firstPane ? 100 : 0, secondPane ? 100 : 0, 0];\n  }\n\n  if (\n    typeof firstPane.width === 'number' &&\n    typeof secondPane.width === 'number' &&\n    firstPane.width >= MIN_PANE_SIZE &&\n    secondPane.width >= MIN_PANE_SIZE &&\n    firstPane.width + secondPane.width === 100\n  ) {\n    return [firstPane.width, secondPane.width, MIN_PANE_SIZE];\n  }\n\n  return [50, 50, MIN_PANE_SIZE];\n};\n\n/**\n * Work out the panes to restore for an entry: the saved state of its collection, or the locale\n * given in the URL. Nothing is restored when the saved state doesn’t fit the entry, e.g. a locale\n * that it doesn’t have, or a preview pane while the preview is disabled.\n * @param {object} args Arguments.\n * @param {[?EntryEditorPane, ?EntryEditorPane]} [args.savedPanes] Saved pane state.\n * @param {string} [args.editorLocale] Locale given in the URL, which overrides the saved state.\n * @param {InternalLocaleCode[]} args.allLocales Locales of the entry.\n * @param {InternalLocaleCode} args.defaultLocale Default locale of the entry.\n * @param {boolean} args.canPreview Whether the entry has a preview.\n * @param {boolean} [args.showPreview] Whether the user wants the preview pane.\n * @param {boolean} args.showSecondPane Whether the user wants the second pane.\n * @returns {[EntryEditorPane, EntryEditorPane] | undefined} Panes to restore, or `undefined` if\n * nothing can be restored.\n */\nexport const getRestoredPanes = ({\n  savedPanes = [null, null],\n  editorLocale,\n  allLocales,\n  defaultLocale,\n  canPreview,\n  showPreview,\n  showSecondPane,\n}) => {\n  /** @type {[?EntryEditorPane, ?EntryEditorPane]} */\n  const [firstPane, secondPane] = editorLocale\n    ? [\n        { mode: 'edit', locale: editorLocale },\n        { mode: 'preview', locale: editorLocale },\n      ]\n    : savedPanes;\n\n  if (\n    !firstPane ||\n    !secondPane ||\n    (!!firstPane.locale && !allLocales.includes(firstPane.locale)) ||\n    (!!secondPane.locale && !allLocales.includes(secondPane.locale)) ||\n    !showSecondPane ||\n    ((!showPreview || !canPreview) &&\n      (firstPane.mode === 'preview' || secondPane.mode === 'preview')) ||\n    // If there are only 2 locales and the first pane is not in the default locale, don’t restore\n    // the saved panes so that the default locale is always shown in the first pane. The locale\n    // given in the URL is what the user asked for, so it’s shown anyway\n    (!editorLocale && allLocales.length === 2 && firstPane.locale !== defaultLocale)\n  ) {\n    return undefined;\n  }\n\n  return [firstPane, secondPane];\n};\n\n/**\n * Work out the default panes for an entry, when nothing is restored: the first pane edits the\n * locale given in the URL, or the current or default locale, and the second one holds the preview,\n * or another locale when there’s no preview to show, or nothing at all when there’s no room for\n * it.\n * @param {object} args Arguments.\n * @param {string} [args.editorLocale] Locale given in the URL, which is used if the entry has it.\n * @param {InternalLocaleCode} [args.currentLocale] Locale of the current first pane, if any.\n * @param {InternalLocaleCode} args.defaultLocale Default locale of the entry.\n * @param {InternalLocaleCode[]} args.allLocales Locales of the entry.\n * @param {boolean} args.i18nEnabled Whether the entry has more than one locale.\n * @param {boolean} args.canPreview Whether the entry has a preview.\n * @param {boolean} [args.showPreview] Whether the user wants the preview pane.\n * @param {boolean} args.showSecondPane Whether the user wants the second pane.\n * @param {boolean} args.singlePane Whether the screen only has room for one pane.\n * @returns {[EntryEditorPane, ?EntryEditorPane]} Panes.\n */\nexport const getDefaultPanes = ({\n  editorLocale,\n  currentLocale,\n  defaultLocale,\n  allLocales,\n  i18nEnabled,\n  canPreview,\n  showPreview,\n  showSecondPane,\n  singlePane,\n}) => {\n  const locale =\n    (editorLocale && allLocales.includes(editorLocale) ? editorLocale : undefined) ??\n    currentLocale ??\n    defaultLocale;\n\n  /** @type {EntryEditorPane} */\n  const firstPane = { mode: 'edit', locale };\n\n  if (singlePane || !showSecondPane) {\n    return [firstPane, null];\n  }\n\n  if (!showPreview || !canPreview) {\n    const otherLocale = i18nEnabled ? allLocales.find((l) => l !== locale) : undefined;\n\n    return [firstPane, otherLocale ? { mode: 'edit', locale: otherLocale } : null];\n  }\n\n  return [firstPane, { mode: 'preview', locale }];\n};\n\n/**\n * Work out the panes that show the given locale’s edit pane. A preview pane is switched to edit\n * mode by preference; otherwise the second pane is repurposed, or the only pane in a single-pane\n * layout.\n * @param {object} args Arguments.\n * @param {?EntryEditorPane} args.firstPane First pane.\n * @param {?EntryEditorPane} args.secondPane Second pane.\n * @param {InternalLocaleCode} args.locale Locale to edit.\n * @returns {[?EntryEditorPane, ?EntryEditorPane] | undefined} New panes, or `undefined` if the\n * locale is already being edited in a pane.\n */\nexport const getPanesEditingLocale = ({ firstPane, secondPane, locale }) => {\n  /** @type {EntryEditorPane} */\n  const editPane = { mode: 'edit', locale };\n\n  if (\n    (firstPane?.mode === 'edit' && firstPane.locale === locale) ||\n    (secondPane?.mode === 'edit' && secondPane.locale === locale)\n  ) {\n    return undefined;\n  }\n\n  if (secondPane?.mode === 'preview') {\n    return [firstPane, editPane];\n  }\n\n  if (firstPane?.mode === 'preview') {\n    return [editPane, secondPane];\n  }\n\n  if (secondPane) {\n    // Both are edit panes for other locales; switch the second one\n    return [firstPane, editPane];\n  }\n\n  // Single-pane layout\n  return [editPane, secondPane];\n};\n\n/**\n * Save the pane state of a collection to the editor settings, so it’s restored the next time an\n * entry of the collection is opened.\n * @param {string} key Key from {@link getPaneStateKey}.\n * @param {[EntryEditorPane, EntryEditorPane]} panes Panes.\n */\nexport const savePaneState = (key, panes) => {\n  // Don’t track the settings being updated, as this is called from an effect\n  const settings = untrack(() => entryEditorSettings.current);\n\n  entryEditorSettings.current = {\n    ...settings,\n    paneStates: { ...settings?.paneStates, [key]: panes },\n  };\n};\n","import { untrack } from 'svelte';\n\nimport { deployments, deployPollTimedOut } from '$lib/services/deployments';\nimport {\n  POLL_INTERVAL,\n  POLL_MAX_DURATION,\n  UNKNOWN_GRACE_DURATION,\n} from '$lib/services/deployments/constants';\nimport {\n  cancelDeployResolution,\n  canResolveDeployments,\n  deployTargets,\n  markLookupPending,\n  resolveDeployments,\n} from '$lib/services/deployments/resolve';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { createRootEffect } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { DeployStatus } from '$lib/types/private';\n */\n\n/** Handle of the scheduled re-check, or `0` when nothing is scheduled. */\nlet timer = /** @type {any} */ (0);\n/** Number of views currently interested in the deploy state. */\nlet holders = 0;\n/** Time the current run started, as a Unix timestamp in milliseconds. */\nlet startTime = 0;\n/** Number of checks made in the current run. */\nlet attempts = 0;\n/** Stops the target watcher, which runs only while something is holding the loop. */\nlet unwatch = /** @type {(() => void) | undefined} */ (undefined);\n/** The tracked commits as of the last check, used to notice that a save moved one. */\nlet lastKey = '';\n/**\n * Incremented whenever the current run is superseded. A check whose request was still out when that\n * happened must not schedule the next one, or two loops would run at once and only the newer\n * timer’s handle would be known — leaving the older one running after every holder had released.\n */\nlet generation = 0;\n\n/**\n * Whether every tracked commit has reached a state that won’t change on its own. A commit with\n * nothing reported against it counts, because {@link keepWaiting} holds one back in the `checking`\n * state while the provider is still being given time to report — so an `unknown` that has landed in\n * the store is one the loop has already waited for, or one that was concluded before the run\n * began.\n * @returns {boolean} Result.\n */\nconst isSettled = () => {\n  const map = deployments.current;\n\n  return deployTargets.current.every(({ sha }) => {\n    const state = map[sha]?.state;\n\n    // Nothing recorded yet, or a build still running, is worth another look\n    return state === 'ready' || state === 'error' || state === 'unknown';\n  });\n};\n\n/**\n * Put the given commits back into the `checking` state, so the preview control keeps saying that a\n * preview is on its way rather than offering the live site, and the loop keeps looking at them.\n * @param {string[]} shas Commits to hold back.\n * @param {string} reason Why, for the dev mode report.\n */\nconst holdBack = (shas, reason) => {\n  if (!shas.length) {\n    return;\n  }\n\n  if (prefs.devModeEnabled) {\n    // eslint-disable-next-line no-console\n    console.info(`deployPreview: ${reason}`, {\n      shas,\n      remaining: UNKNOWN_GRACE_DURATION - (Date.now() - startTime),\n    });\n  }\n\n  const map = deployments.current;\n\n  deployments.current = {\n    ...map,\n    ...Object.fromEntries(\n      shas.map((sha) => [sha, /** @type {DeployStatus} */ ({ ...map[sha], state: 'checking' })]),\n    ),\n  };\n};\n\n/**\n * Keep waiting for the commits that were being checked and came back with nothing reported, as long\n * as the run is young enough that the provider may not have posted its first status yet. Once the\n * grace period is over, an empty answer is final. A commit that was already `unknown` when the run\n * began is left alone; it was concluded earlier, and nothing has happened to it since.\n * @param {Record<string, DeployStatus>} before Deploy state as of just before the lookup.\n * @see https://github.com/sveltia/sveltia-cms/issues/991\n */\nconst keepWaiting = (before) => {\n  if (Date.now() - startTime >= UNKNOWN_GRACE_DURATION) {\n    return;\n  }\n\n  const map = deployments.current;\n\n  const shas = deployTargets.current\n    .map(({ sha }) => sha)\n    .filter((sha) => {\n      if (map[sha]?.state !== 'unknown') {\n        return false;\n      }\n\n      const prior = before[sha];\n\n      // A commit with no record yet was marked as being checked by the lookup itself. One that a\n      // lookup made outside the loop — the initial one at sign-in — concluded while this run was\n      // going hasn’t been waited for either\n      return (\n        !prior ||\n        prior.state === 'checking' ||\n        (prior.state === 'unknown' && prior.checkedTime >= startTime)\n      );\n    });\n\n  holdBack(shas, 'nothing reported yet, still waiting');\n};\n\n/**\n * Give a commit that was found to be unreported only moments ago the grace period as well, by\n * putting it back into the `checking` state before the run begins. Such a conclusion comes from the\n * lookup made at sign-in, which runs outside the loop: the CMS may have been reloaded right after a\n * save, before the provider posted anything, and that one lookup would otherwise be the last word\n * for the whole session. A conclusion older than the grace period stands — nothing reports on that\n * commit, and there’s nothing new to learn.\n */\nconst reopenRecentConclusions = () => {\n  const map = deployments.current;\n  const now = Date.now();\n\n  const shas = deployTargets.current\n    .map(({ sha }) => sha)\n    .filter((sha) => {\n      const status = map[sha];\n\n      return status?.state === 'unknown' && now - status.checkedTime < UNKNOWN_GRACE_DURATION;\n    });\n\n  holdBack(shas, 'concluded only moments ago, waiting a little longer');\n};\n\n/**\n * Identify the current set of tracked commits, so a change to it can be noticed.\n * @returns {string} Key.\n */\nconst getTargetKey = () => deployTargets.current.map(({ sha }) => sha).join(',');\n\n/**\n * Drop the scheduled check and retire the current run, so a request still in flight can’t carry the\n * loop forward on its own.\n */\nconst supersede = () => {\n  globalThis.clearTimeout(timer);\n  timer = 0;\n  generation += 1;\n};\n\n/**\n * Stop re-checking and forget the current run’s state.\n */\nconst stop = () => {\n  supersede();\n  cancelDeployResolution();\n};\n\n/**\n * Schedule the next re-check, unless there’s nothing left to wait for.\n */\nconst schedule = () => {\n  if (!holders || !canResolveDeployments() || isSettled()) {\n    if (prefs.devModeEnabled) {\n      // eslint-disable-next-line no-console\n      console.info('deployPreview: not re-checking', {\n        watchers: holders,\n        canResolve: canResolveDeployments(),\n        settled: isSettled(),\n        attempts,\n      });\n    }\n\n    stop();\n\n    return;\n  }\n\n  if (Date.now() - startTime > POLL_MAX_DURATION) {\n    // A build this long is either stuck or reporting through a channel the CMS can’t read, so hand\n    // it over to the manual re-check rather than requesting forever\n    deployPollTimedOut.current = true;\n    stop();\n\n    return;\n  }\n\n  const run = generation;\n\n  timer = globalThis.setTimeout(async () => {\n    timer = 0;\n    attempts += 1;\n\n    const before = deployments.current;\n\n    // A finished build is skipped, so one entry still building doesn’t drag the whole board along\n    await resolveDeployments({ pendingOnly: true });\n\n    // This comes before the run is checked: a save while the request was out retires the run but\n    // not the request, so its answer still lands, and a commit it found nothing on would otherwise\n    // be concluded without its grace period\n    keepWaiting(before);\n\n    // A save or a release while the request was out has already retired this run\n    if (run !== generation) {\n      return;\n    }\n\n    // Reschedule only now, so a slow response can’t let two checks overlap\n    schedule();\n  }, POLL_INTERVAL);\n};\n\n/**\n * Begin a fresh run, discarding whatever the previous one was waiting for.\n */\nconst restart = () => {\n  supersede();\n  attempts = 0;\n  startTime = Date.now();\n  deployPollTimedOut.current = false;\n\n  if (canResolveDeployments()) {\n    // Say a lookup is coming before making it, so nothing shows a stale answer in the meantime\n    markLookupPending();\n    reopenRecentConclusions();\n  }\n\n  schedule();\n};\n\n/**\n * Start re-checking the deploy state, or join a run that’s already going. Re-checks stop once every\n * holder has released, so the entry editor and the Editorial Workflow board can share one loop.\n * @returns {() => void} Function to release this caller’s hold.\n */\nconst retain = () => {\n  holders += 1;\n\n  if (holders === 1) {\n    lastKey = getTargetKey();\n\n    // Saving moves the branch head, or gives a pull request a new head commit, and that’s exactly\n    // when the state needs watching again — by which time the loop has usually stopped, because\n    // everything it knew about had already settled\n    unwatch = createRootEffect(() => {\n      const key = getTargetKey();\n\n      if (key !== lastKey) {\n        lastKey = key;\n        // Only track the targets, not the state the lookup reads and writes\n        untrack(restart);\n      }\n    });\n\n    restart();\n  }\n\n  let released = false;\n\n  return () => {\n    // A component can be destroyed more than once in a hot-reload cycle; only the first release\n    // should count\n    if (released) {\n      return;\n    }\n\n    released = true;\n    holders -= 1;\n\n    if (!holders) {\n      unwatch?.();\n      unwatch = undefined;\n      stop();\n    }\n  };\n};\n\n/**\n * Start re-checking the deploy state, or join a run that’s already going. Re-checks stop once every\n * holder has released, so the entry editor and the Editorial Workflow board can share one loop.\n *\n * A component calls this from an effect, and nothing the loop reads is tracked by that effect: the\n * first check reads the deploy state to decide whether anything is still building, and a lookup\n * writes it, so a tracked read would re-run the effect on every answer — releasing the hold,\n * cancelling the lookup that was just made, and starting over without ever landing a result.\n * @returns {() => void} Function to release this caller’s hold.\n */\nexport const retainDeployPolling = () => untrack(retain);\n\n/**\n * Query the backend right away, ignoring the cached results and the current backoff. This backs the\n * manual re-check offered when the automatic ones gave up.\n * @returns {Promise<void>}\n */\nexport const recheckDeployments = async () => {\n  supersede();\n  deployPollTimedOut.current = false;\n\n  await resolveDeployments({ force: true });\n\n  restart();\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Menu, MenuButton, MenuItem, Spacer, Toolbar } from '@sveltia/ui';\n\n  import ViewInRepositoryItem from '$lib/components/common/view-in-repository-item.svelte';\n  import CopyMenuItems from '$lib/components/contents/details/editor/copy-menu-items.svelte';\n  import ResetDialog from '$lib/components/contents/details/editor/reset-dialog.svelte';\n  import ResetMenuItems from '$lib/components/contents/details/editor/reset-menu-items.svelte';\n  import TranslateButton from '$lib/components/contents/details/editor/translate-button.svelte';\n  import LocaleSwitcher from '$lib/components/contents/details/locale-switcher.svelte';\n  import PreviewButton from '$lib/components/contents/details/preview-button.svelte';\n  import PreviewLinkButton from '$lib/components/contents/details/preview-link-button.svelte';\n  import { backend } from '$lib/services/backends';\n  import { isDraftReadonly } from '$lib/services/config/readonly';\n  import { isValueMapModified } from '$lib/services/contents/draft';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { toggleLocale } from '$lib/services/contents/draft/update/locale';\n  import { canResetEntry } from '$lib/services/contents/draft/update/reset';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getLocaleContentLabel } from '$lib/services/contents/editor/panes';\n  import { createResetMenuState } from '$lib/services/contents/editor/reset-menu.svelte';\n  import { entryEditorSettings } from '$lib/services/contents/editor/settings';\n  import { getEntryRepoBlobURL } from '$lib/services/contents/entry';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n  import { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\n  import { deployments, deployPollTimedOut, productionSHA } from '$lib/services/deployments';\n  import { getEntryPreviewLink } from '$lib/services/deployments/link';\n  import { recheckDeployments } from '$lib/services/deployments/poll';\n  import { env } from '$lib/services/user/env.svelte';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import { createRawState } from '$lib/services/utils/state.svelte';\n  import { openNewTab } from '$lib/services/utils/window';\n  import {\n    getUnpublishedEntryByDraft,\n    isPendingDeletion,\n    workflowEnabled,\n  } from '$lib/services/workflow';\n\n  /**\n   * @import { EntryEditorPane } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} id The wrapper element’s `id` attribute.\n   * @property {{ current: ?EntryEditorPane }} thisPane This pane’s mode and locale.\n   * @property {{ current: ?EntryEditorPane }} [thatPane] Another pane’s mode and locale.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { id, thisPane, thatPane = createRawState(null) } = $props();\n\n  const collection = $derived(entryDraft.current?.collection);\n  const collectionFile = $derived(entryDraft.current?.collectionFile);\n  const originalEntry = $derived(entryDraft.current?.originalEntry);\n  /* v8 ignore start -- the header is only rendered for a pane while the draft is there */\n  const originalValues = $derived(entryDraft.current?.originalValues ?? {});\n  const { i18nEnabled, saveAllLocales, allLocales, defaultLocale } = $derived(\n    getDraftI18nConfig(entryDraft.current),\n  );\n  const isLocaleEnabled = $derived(\n    entryDraft.current?.currentLocales[thisPane.current?.locale ?? ''],\n  );\n  const isOnlyLocale = $derived(\n    Object.values(entryDraft.current?.currentLocales ?? {}).filter((enabled) => enabled).length ===\n      1,\n  );\n  /* v8 ignore stop */\n  const otherLocales = $derived(\n    i18nEnabled ? allLocales.filter((l) => l !== thisPane.current?.locale) : [],\n  );\n  const canCopy = $derived(!!otherLocales.length);\n  // Every option in the menu edits the content, which an entry awaiting deletion doesn’t allow\n  const pendingDeletion = $derived(isPendingDeletion(entryDraft.current?.originalEntry));\n  // Nor does a read-only entry, but it can still be viewed on the site or in the repository, so the\n  // menu keeps the links to it\n  const readonly = $derived(isDraftReadonly(entryDraft.current));\n  // This is recomputed on every change, so the values are compared in place rather than by\n  // deep-comparing a filtered copy of the whole locale\n  const canRevert = $derived(\n    !!thisPane.current?.locale &&\n      isValueMapModified(\n        originalValues[thisPane.current.locale] ?? {},\n        getValueMapSnapshot(entryDraft.current, thisPane.current.locale),\n      ),\n  );\n  const resetMenu = createResetMenuState(() => {\n    const draft = entryDraft.current;\n    const locale = thisPane.current?.locale;\n\n    /* v8 ignore next 3 -- the menu is only offered for an edit pane while the draft is there */\n    if (!draft || !locale) {\n      return undefined;\n    }\n\n    return {\n      restore: canResetEntry({ draft, locale, restore: true }),\n      clear: canResetEntry({ draft, locale }),\n    };\n  });\n  /** @type {MenuButton | undefined} */\n  let menuButton = $state();\n\n  /* v8 ignore next -- the header is only rendered for a pane while the draft is there */\n  const canPreview = $derived(entryDraft.current?.canPreview ?? true);\n  // Without another pane on a large screen, the switcher offers the preview in this pane, even when\n  // there’s only one locale to switch between\n  const previewInThisPane = $derived(\n    !(env.isSmallScreen || env.isMediumScreen) &&\n      !thatPane.current &&\n      canPreview &&\n      !!entryEditorSettings.current?.showPreview,\n  );\n  // Look the entry up in the store rather than reading the draft, so the preview link follows the\n  // head commit as it moves with each save, the same way the entry toolbar does\n  const pullRequest = $derived(\n    workflowEnabled.current && entryDraft.current\n      ? getUnpublishedEntryByDraft(entryDraft.current)?.workflow.pullRequest\n      : undefined,\n  );\n  // `PreviewLinkButton` renders nothing when there’s no link to offer, so the link is resolved\n  // here as well — the divider above the button has to know whether anything will follow it\n  /* v8 ignore start -- only read for an existing entry, once the pane is set up */\n  const previewLink = $derived(\n    originalEntry && collection && thisPane.current\n      ? getEntryPreviewLink({\n          entry: originalEntry,\n          locale: thisPane.current.locale,\n          collection,\n          collectionFile,\n          pullRequest,\n          deployments: deployments.current,\n          productionSHA: productionSHA.current,\n          pollTimedOut: deployPollTimedOut.current,\n        })\n      : undefined,\n  );\n  /* v8 ignore stop */\n  // Whether the menu has anything that doesn’t edit the content, all a read-only entry gets\n  const hasLinkItems = $derived(\n    !!originalEntry &&\n      !!collection &&\n      !!(previewLink || deployPollTimedOut.current || prefs.devModeEnabled),\n  );\n</script>\n\n<div role=\"none\" {id} class=\"header\">\n  <Toolbar variant=\"secondary\" ariaLabel={_('secondary')}>\n    {#if (i18nEnabled && allLocales.length > 1) || previewInThisPane}\n      <LocaleSwitcher {id} {thisPane} {thatPane} {previewInThisPane} />\n      {#if (env.isSmallScreen || env.isMediumScreen) && canPreview}\n        <PreviewButton {thisPane} />\n      {/if}\n    {:else if !(env.isSmallScreen || env.isMediumScreen)}\n      <h3 role=\"none\">{thisPane.current?.mode === 'preview' ? _('preview') : _('edit')}</h3>\n    {:else if canPreview}\n      <PreviewButton {thisPane} />\n    {/if}\n    <Spacer flex />\n    {#if thisPane.current?.mode === 'edit'}\n      {@const paneLocale = thisPane.current.locale}\n      {@const localeLabel = getLocaleLabel(paneLocale) ?? paneLocale}\n      {#if canCopy && !readonly}\n        <TranslateButton locale={thisPane.current.locale} {otherLocales} />\n      {/if}\n      {#if !readonly || hasLinkItems}\n        <MenuButton\n          variant=\"ghost\"\n          iconic\n          disabled={pendingDeletion}\n          popupPosition=\"bottom-right\"\n          aria-label={getLocaleContentLabel('show_content_options_x_locale', paneLocale)}\n          onclick={resetMenu.update}\n          onkeydown={resetMenu.update}\n          bind:this={menuButton}\n        >\n          {#snippet popup()}\n            <Menu ariaLabel={getLocaleContentLabel('content_options_x_locale', paneLocale)}>\n              {#if !readonly}\n                {#if canCopy && thisPane.current?.locale}\n                  <CopyMenuItems locale={thisPane.current.locale} {otherLocales} submenu />\n                {/if}\n                <ResetMenuItems\n                  scope=\"locale\"\n                  separator={canCopy}\n                  available={{ revert: !!canRevert, ...resetMenu.availability }}\n                  onSelect={resetMenu.select}\n                />\n                {#if !saveAllLocales && thisPane.current?.locale}\n                  <Divider />\n                  <MenuItem\n                    label={_(\n                      isLocaleEnabled\n                        ? 'disable_x_locale'\n                        : entryDraft.current?.currentValues[thisPane.current.locale]\n                          ? 'reenable_x_locale'\n                          : 'enable_x_locale',\n                      { values: { locale: localeLabel } },\n                    )}\n                    disabled={thisPane.current.locale === defaultLocale ||\n                      (isLocaleEnabled && isOnlyLocale)}\n                    onclick={() => {\n                      /* v8 ignore next 6 -- the menu is only offered for a pane with a locale */\n                      if (entryDraft.current) {\n                        toggleLocale({\n                          draft: entryDraft.current,\n                          locale: thisPane.current?.locale ?? '',\n                        });\n                      }\n                    }}\n                  />\n                {/if}\n              {/if}\n              {#if originalEntry && collection && thisPane.current}\n                {#if !readonly && hasLinkItems}\n                  <Divider />\n                {/if}\n                <PreviewLinkButton\n                  as=\"menuitem\"\n                  entry={originalEntry}\n                  locale={thisPane.current.locale}\n                  {collection}\n                  {collectionFile}\n                  {pullRequest}\n                />\n                {#if deployPollTimedOut.current}\n                  <MenuItem\n                    label={_('deploy_preview.check_again')}\n                    onclick={() => {\n                      recheckDeployments();\n                    }}\n                  />\n                {/if}\n                <ViewInRepositoryItem\n                  disabled={!backend.current?.repository?.blobBaseURL}\n                  onclick={() => {\n                    /* v8 ignore next 3 -- the item is only offered for an existing entry */\n                    if (originalEntry && thisPane.current) {\n                      openNewTab(getEntryRepoBlobURL(originalEntry, thisPane.current.locale));\n                    }\n                  }}\n                />\n              {/if}\n            </Menu>\n          {/snippet}\n        </MenuButton>\n      {/if}\n    {/if}\n  </Toolbar>\n</div>\n\n<ResetDialog\n  bind:open={resetMenu.dialogOpen}\n  action={resetMenu.action}\n  locale={thisPane.current?.locale}\n  onClose={() => {\n    menuButton?.focus();\n  }}\n/>\n\n<style>\n  .header {\n    flex: none !important;\n\n    :global {\n      & > .sui.toolbar {\n        margin-inline: auto;\n        max-width: 800px;\n\n        @media (width < 768px) {\n          padding: 0;\n        }\n\n        h3 {\n          margin: 0 8px;\n          font-size: var(--sui-font-size-default);\n        }\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Notice shown at the top of the entry editor when the entry has been edited from a Relation field\n  of another entry, and the changes wait in that entry’s pull request to be published along with it.\n  The user can still save the entry on its own; Git then combines the two changes when the pull\n  request is published, or refuses to if they touch the same lines.\n  @see https://github.com/sveltia/sveltia-cms/issues/1129\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Infobar } from '@sveltia/ui';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getEditingHostName } from '$lib/services/contents/fields/relation/quick-add';\n\n  const entryDraft = getEntryDraftContext();\n  const hostName = $derived(getEditingHostName(entryDraft.current));\n</script>\n\n{#if hostName !== undefined}\n  <Infobar status=\"warning\" --sui-infobar-message-justify-content=\"center\">\n    {_('relation_field.edited_with_entry', { values: { name: hostName } })}\n  </Infobar>\n{/if}\n","import { checkForRemoteChanges, MIN_CHECK_GAP } from '$lib/services/backends/refresh';\nimport { isDraftModified } from '$lib/services/contents/draft';\nimport {\n  cancelBackup,\n  deleteBackup,\n  getBackup,\n  getBackupSlug,\n} from '$lib/services/contents/draft/backup';\nimport { createDraft } from '$lib/services/contents/draft/create';\nimport { compareWithStore } from '$lib/services/contents/draft/save/conflict';\nimport { isWorkflowDraft } from '$lib/services/workflow';\n\n/**\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n * @import { Entry, EntryDraft } from '$lib/types/private';\n */\n\n/**\n * Replace the draft in the editor with a fresh one made from the given version of its entry — the\n * one now on the branch, after someone else has changed it. Whatever the user had typed is dropped,\n * along with the backup made of it; otherwise the new draft would offer to restore the edits that\n * were just given up. The caller asks the user first when there is anything to lose.\n * @param {object} args Arguments.\n * @param {EntryDraftState} args.entryDraft Entry draft state of the editor.\n * @param {Entry} args.entry Entry to make the new draft from.\n * @returns {Promise<EntryDraft>} The new draft.\n */\nexport const reloadDraft = async ({ entryDraft, entry }) => {\n  const draft = /** @type {EntryDraft} */ (entryDraft.current);\n  const { collectionName, collection, collectionFile, expanderStates } = draft;\n\n  // A backup scheduled for the edits being dropped would otherwise bring them back\n  cancelBackup();\n  await deleteBackup(collectionName, getBackupSlug(draft));\n\n  return createDraft({\n    entryDraft,\n    collection,\n    collectionFile,\n    originalEntry: entry,\n    // Keep the fields expanded or collapsed as the user had them\n    expanderStates,\n  });\n};\n\n/**\n * Check if the given draft is still the one in the editor, and the user hasn’t touched it yet.\n * @param {EntryDraftState} entryDraft Entry draft state of the editor.\n * @param {EntryDraft} draft Draft opened in the editor.\n * @returns {boolean} Result.\n */\nconst isDraftUntouched = (entryDraft, draft) =>\n  entryDraft.current === draft && !draft.interacted && !isDraftModified(draft);\n\n/**\n * Bring a draft that has just been opened for an existing entry up to date with the repository, so\n * the editor shows the entry as it is rather than as it was when the site data was loaded. The\n * check is made in passing, so an entry opened right after another costs nothing. If the entry has\n * been changed in the meantime and the user hasn’t touched the draft yet, it’s quietly made again\n * from the new version. Otherwise — the user has started editing, has a backup to be asked about,\n * or the entry is gone — the notice in the editor takes over, so nothing is lost.\n * @param {EntryDraftState} entryDraft Entry draft state of the editor.\n * @returns {Promise<void>}\n */\nexport const refreshOpenedDraft = async (entryDraft) => {\n  const draft = entryDraft.current;\n\n  // A new entry has nothing to compare. A workflow draft isn’t refreshed here either: this check\n  // watches the configured branch, while the draft lives on a branch of its own. That branch is\n  // compared with the draft when it’s saved, by {@link detectWorkflowConflict}\n  if (!draft || draft.isNew || !draft.originalEntry || isWorkflowDraft(draft)) {\n    return;\n  }\n\n  try {\n    await checkForRemoteChanges({ maxAge: MIN_CHECK_GAP });\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to check the repository for changes.', ex);\n\n    return;\n  }\n\n  if (!isDraftUntouched(entryDraft, draft)) {\n    return;\n  }\n\n  const conflict = compareWithStore(draft.originalEntry);\n\n  // An entry stored in a file with the other entries of the collection is told by its position, and\n  // the item at the position may now be another entry that has moved there, which would silently\n  // take the place of the entry being viewed\n  if (conflict?.type !== 'modified' || !conflict.canOverwrite) {\n    return;\n  }\n\n  const { collectionName, collection, collectionFile, expanderStates } = draft;\n\n  // A backup from an earlier session is being offered, or about to be — the draft looks it up on\n  // its own time, so the dialog can’t be relied upon to be showing yet. Restoring it into a draft\n  // that has just been replaced would lose the restored edits, so the draft is left alone\n  if (await getBackup(collectionName, getBackupSlug(draft))) {\n    return;\n  }\n\n  // The user may have started on the draft, or moved on, while the backup was being looked up\n  if (!isDraftUntouched(entryDraft, draft)) {\n    return;\n  }\n\n  createDraft({\n    entryDraft,\n    collection,\n    collectionFile,\n    originalEntry: conflict.entry,\n    expanderStates,\n  });\n};\n","<!--\n  @component\n  Notice shown at the top of the entry editor when someone else has changed or deleted the entry in\n  the repository while the user has it open. The background checks bring such a change into the\n  entry store; this compares the entry the draft was made from with the entry as it is now. The\n  user can reload the entry to start from the new version, or carry on: their work is left alone\n  either way, and saving asks before overwriting the other change. An entry stored in a file with\n  the other entries can’t be reloaded or saved over the change; the user is asked to open it again\n  from the entry list.\n-->\n<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Button, ConfirmationDialog, Infobar } from '@sveltia/ui';\n\n  import { isDraftModified } from '$lib/services/contents/draft';\n  import { reloadDraft } from '$lib/services/contents/draft/reload';\n  import { compareWithStore, describeConflict } from '$lib/services/contents/draft/save/conflict';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { isWorkflowDraft } from '$lib/services/workflow';\n\n  /**\n   * @import { Entry, EntryDraft } from '$lib/types/private';\n   */\n\n  const entryDraft = getEntryDraftContext();\n  const draft = $derived(entryDraft.current);\n  /**\n   * The entry the draft was made from, if it’s one that the background checks watch: an existing\n   * entry on the configured branch. A workflow draft lives on a branch of its own, which those\n   * checks don’t look at; it’s compared with its branch when the draft is saved instead.\n   */\n  const originalEntry = $derived(\n    draft && !draft.isNew && !isWorkflowDraft(draft) ? draft.originalEntry : undefined,\n  );\n  const conflict = $derived(originalEntry ? compareWithStore(originalEntry) : undefined);\n  /**\n   * The version of the entry the user has dismissed the notice for, so the notice comes back if the\n   * entry is changed again. A deletion has no version; it’s dismissed for good. Raw, so the entry\n   * object is kept as is and can be compared with the one in the store.\n   * @type {Entry | 'deleted' | undefined}\n   */\n  let dismissedFor = $state.raw();\n  let showReloadDialog = $state(false);\n\n  const show = $derived(!!conflict && dismissedFor !== (conflict.entry ?? 'deleted'));\n\n  /**\n   * Start over from the entry as it is now on the branch.\n   */\n  const reload = async () => {\n    /* v8 ignore next 3 -- only reachable if the entry was deleted while the dialog was open */\n    if (!conflict?.entry) {\n      return;\n    }\n\n    await reloadDraft({ entryDraft, entry: conflict.entry });\n  };\n\n  /**\n   * Reload the entry, asking first if there is anything to lose.\n   */\n  const onReloadClick = () => {\n    // Nothing to lose unless the user has edited the entry, or is being asked whether to restore\n    // the edits backed up earlier, which a reload deletes. The button is only shown with a draft\n    if (isDraftModified(draft) || /** @type {EntryDraft} */ (draft).restorePending) {\n      showReloadDialog = true;\n    } else {\n      reload();\n    }\n  };\n</script>\n\n{#if conflict && show}\n  {@const { description, warning } = describeConflict(conflict, appLocale.current)}\n  <Infobar\n    status=\"warning\"\n    --sui-infobar-message-justify-content=\"center\"\n    onDismiss={() => {\n      dismissedFor = conflict.entry ?? 'deleted';\n    }}\n  >\n    {description}\n    {warning}\n    <!-- An entry stored in a file with the other entries is told by its position, so reloading it\n    could load another entry that has moved there -->\n    {#if conflict.type === 'modified' && conflict.canOverwrite}\n      <Button variant=\"link\" label={_('remote_change.reload_entry')} onclick={onReloadClick} />\n    {/if}\n  </Infobar>\n{/if}\n\n<ConfirmationDialog\n  bind:open={showReloadDialog}\n  title={_('remote_change.reload_entry')}\n  okLabel={_('remote_change.reload_entry')}\n  onOk={async () => {\n    await reload();\n  }}\n>\n  {_('remote_change.confirm_reloading_entry')}\n</ConfirmationDialog>\n","import { collectors } from '$lib/services/config';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getCollectionFile } from '$lib/services/contents/collection/files';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getListItemKeys, getWildcardKeyPathPattern } from '$lib/services/contents/entry/key-paths';\nimport { getEntryOptions } from '$lib/services/contents/fields/relation/helpers';\n\n/**\n * @import {\n * CollectedRelationField,\n * ConfigParserContext,\n * Entry,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * ResolvedRelationField,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, ListFieldWithSubField, RelationField } from '$lib/types/public';\n */\n\n/**\n * Check whether the given stored value is absent. `false`, `0` and an empty string are all valid\n * relation values, so only `undefined` and `null` count as absent.\n * @param {any} value Value to check.\n * @returns {boolean} Whether the value is absent.\n */\nconst isNullish = (value) => value === undefined || value === null;\n\n/**\n * Drop the subfield names of single-subfield List fields from the given typed key path. The parser\n * records the subfield name after the list item wildcard, e.g. `authors.*.author`, but the item\n * value is stored directly under the item index, e.g. `authors.0`.\n * @param {ConfigParserContext} context Field parser context.\n * @returns {string} Typed key path in the shape of the flattened content, e.g. `authors.*`.\n */\nconst getContentTypedKeyPath = ({\n  collection,\n  collectionFile,\n  componentName,\n  isIndexFile,\n  typedKeyPath = '',\n}) => {\n  const segments = typedKeyPath.split('.');\n\n  if (!segments.includes('*')) {\n    return typedKeyPath;\n  }\n\n  const getFieldArgs = {\n    collectionName: /** @type {string} */ (collection?.name),\n    fileName: collectionFile?.name,\n    componentName,\n    isIndexFile,\n  };\n\n  /** @type {string[]} */\n  const contentSegments = [];\n\n  for (let index = 0; index < segments.length; index += 1) {\n    const segment = segments[index];\n\n    if (segment === '*' && contentSegments.length) {\n      const listField = getField({ ...getFieldArgs, keyPath: contentSegments.join('.') });\n      const { field: subField } = /** @type {ListFieldWithSubField} */ (listField ?? {});\n\n      contentSegments.push(segment);\n\n      if (listField?.widget === 'list' && subField?.name === segments[index + 1]) {\n        // Skip the subfield name\n        index += 1;\n      }\n    } else {\n      contentSegments.push(segment);\n    }\n  }\n\n  return contentSegments.join('.');\n};\n\n/**\n * Resolve the key path of a Relation field within an entry’s flattened content, from the parser\n * context recorded while the config was parsed.\n * @param {CollectedRelationField} collected Collected Relation field.\n * @returns {{ keyPath: FieldKeyPath, valuePattern: RegExp | undefined }} Key path and, when it\n * contains a `*` wildcard, a pattern matching the concrete key paths holding the field’s values.\n */\nexport const resolveRelationKeyPath = ({ fieldConfig, context }) => {\n  // The `typedKeyPath` may carry type annotations like `blocks.*<image>.src`; strip them. A `*`\n  // stands for a list item index and is kept, because the field then occurs once per list item\n  const keyPath = getContentTypedKeyPath(context).replace(/<[^>]+>/g, '') || fieldConfig.name;\n\n  if (!keyPath.includes('*')) {\n    return { keyPath, valuePattern: undefined };\n  }\n\n  // A multi-value field stores each of its values under its own index, one level below the field’s\n  // own key path, e.g. `blocks.0.tags.0`\n  const suffix = fieldConfig.multiple ? '\\\\.\\\\d+' : '';\n\n  return {\n    keyPath,\n    valuePattern: new RegExp(`^${getWildcardKeyPathPattern(keyPath)}${suffix}$`),\n  };\n};\n\n/**\n * Get the concrete key paths holding a Relation field’s stored values in the given content map. A\n * multi-value field expands to one key path per value, and a field nested in a list expands to one\n * set of key paths per list item.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.content Flattened entry content.\n * @param {FieldKeyPath} args.keyPath Field key path, possibly containing `*` wildcards.\n * @param {RegExp} [args.valuePattern] Pattern from {@link resolveRelationKeyPath}, required when\n * the key path contains a wildcard.\n * @param {boolean} [args.multiple] Whether the field accepts multiple values.\n * @returns {FieldKeyPath[]} Key paths whose values are relation references.\n */\nexport const getRelationKeyPaths = ({ content, keyPath, valuePattern, multiple = false }) => {\n  // A wildcard key path can only be expanded by looking at the content’s own key paths\n  if (valuePattern) {\n    return Object.keys(content).filter((key) => valuePattern.test(key) && !isNullish(content[key]));\n  }\n\n  if (multiple) {\n    return getListItemKeys(content, keyPath).filter((key) => !isNullish(content[key]));\n  }\n\n  return isNullish(content[keyPath]) ? [] : [keyPath];\n};\n\n/**\n * Get the stored relation values for a field in a given entry content map.\n * @param {object} args Arguments. Same as {@link getRelationKeyPaths}.\n * @param {FlattenedEntryContent} args.content Flattened entry content.\n * @param {FieldKeyPath} args.keyPath Field key path.\n * @param {RegExp} [args.valuePattern] Wildcard key path pattern.\n * @param {boolean} [args.multiple] Whether the field accepts multiple values.\n * @returns {any[]} Stored values.\n */\nexport const getRelationValues = (args) =>\n  getRelationKeyPaths(args).map((key) => args.content[key]);\n\n/**\n * Get the value(s) identifying the given entry in a Relation field, in other words what is stored\n * in the field when the entry is selected. There can be more than one when the field’s\n * `value_field` template references a list field.\n * @param {object} args Arguments.\n * @param {RelationField} args.fieldConfig Relation field config.\n * @param {Entry} args.entry Referenced entry.\n * @param {InternalLocaleCode} args.locale Locale of the entry holding the Relation field.\n * @returns {any[]} Stored values.\n */\nexport const getEntryRelationValues = ({ fieldConfig, entry, locale }) =>\n  getEntryOptions({ locale, fieldConfig, refEntry: entry }).map(({ value }) => value);\n\n/**\n * Find every Relation field configured anywhere in the site that points at the given collection —\n * and, for a file/singleton collection, at the given file — resolved down to the collection and key\n * path where its values are stored.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Target collection name.\n * @param {string} [args.fileName] Target file name, for file/singleton collections.\n * @returns {ResolvedRelationField[]} Resolved Relation fields. Fields whose holding collection is\n * no longer configured are omitted.\n */\nexport const getReferencingRelationFields = ({ collectionName, fileName }) =>\n  [...collectors.relationFields]\n    .filter(\n      ({ fieldConfig }) =>\n        fieldConfig.collection === collectionName &&\n        // A Relation field may target one specific file in a file/singleton collection. When it\n        // does, it can only reference the target entry if that’s the very file\n        !(fileName && fieldConfig.file && fieldConfig.file !== fileName),\n    )\n    .map((collected) => {\n      const { fieldConfig, context } = collected;\n      const sourceCollectionName = context.collection?.name;\n\n      const sourceCollection = sourceCollectionName\n        ? getCollection(sourceCollectionName)\n        : undefined;\n\n      if (!sourceCollection) {\n        return undefined;\n      }\n\n      const sourceFileName = context.collectionFile?.name;\n\n      return /** @type {ResolvedRelationField} */ ({\n        fieldConfig,\n        sourceCollection,\n        sourceCollectionFile: sourceFileName\n          ? getCollectionFile(sourceCollection, sourceFileName)\n          : undefined,\n        ...resolveRelationKeyPath(collected),\n        multiple: !!fieldConfig.multiple,\n      });\n    })\n    .filter((field) => !!field);\n","import { compare } from '@sveltia/utils/string';\n\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\nimport {\n  getEntryRelationValues,\n  getReferencingRelationFields,\n  getRelationValues,\n} from '$lib/services/contents/entry/relations';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n/**\n * @import { Entry, EntryBacklink } from '$lib/types/private';\n */\n\n/**\n * Find all entries that reference the given target entry through Relation fields.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Target collection name.\n * @param {string} [args.fileName] Target file name, for file/singleton collections.\n * @param {Entry} args.entry Target entry.\n * @returns {EntryBacklink[]} Backlinks referencing the target entry. Each referencing entry appears\n * once, even if several of its Relation fields point at the target. They’re sorted by summary\n * within each collection, and the collections keep the order they were found in.\n */\nexport const getBacklinks = ({ collectionName, fileName, entry }) => {\n  /** @type {Set<string>} */\n  const seenEntryIds = new Set();\n\n  const backlinks = getReferencingRelationFields({ collectionName, fileName }).flatMap(\n    ({ fieldConfig, sourceCollection, sourceCollectionFile, keyPath, valuePattern, multiple }) => {\n      // Relation values can vary by the locale of the entry holding the field, e.g. when the\n      // `value_field` template contains `{{locale}}`. Only the default locale is inspected here:\n      // the panel lists entries, not individual locale files\n      const locale = (sourceCollectionFile ?? sourceCollection)._i18n.defaultLocale;\n      const targetValues = new Set(getEntryRelationValues({ fieldConfig, entry, locale }));\n\n      if (!targetValues.size) {\n        return [];\n      }\n\n      const sourceCollectionName = sourceCollection.name;\n      const sourceFileName = sourceCollectionFile?.name;\n\n      return getEntriesByCollection(sourceCollectionName)\n        .filter(\n          (sourceEntry) =>\n            // An entry never counts as a backlink to itself\n            sourceEntry.id !== entry.id &&\n            // An entry already found through another Relation field is not listed again\n            !seenEntryIds.has(sourceEntry.id) &&\n            // In a file/singleton collection, only the file holding the field can reference it\n            (!sourceFileName || sourceEntry.slug === sourceFileName),\n        )\n        .map((sourceEntry) => {\n          const content = getEntryLocaleFile(sourceEntry, { locale })?.content;\n\n          if (\n            !content ||\n            !getRelationValues({ content, keyPath, valuePattern, multiple }).some((value) =>\n              targetValues.has(value),\n            )\n          ) {\n            return undefined;\n          }\n\n          seenEntryIds.add(sourceEntry.id);\n\n          return /** @type {EntryBacklink} */ ({\n            collectionName: sourceCollectionName,\n            collectionLabel: sourceCollection.label || sourceCollectionName,\n            fileName: sourceFileName,\n            fieldLabel: getFieldLabel({ config: fieldConfig }),\n            entry: sourceEntry,\n            // A collection file is listed by its label, as in the file list\n            summary: getEntrySummary(sourceCollection, sourceEntry, { fileName: sourceFileName }),\n          });\n        })\n        .filter((backlink) => !!backlink);\n    },\n  );\n\n  // A collection can be found through several Relation fields, so its entries aren’t necessarily\n  // next to each other yet\n  const collectionNames = [...new Set(backlinks.map((backlink) => backlink.collectionName))];\n\n  return backlinks.sort(\n    (a, b) =>\n      collectionNames.indexOf(a.collectionName) - collectionNames.indexOf(b.collectionName) ||\n      compare(a.summary, b.summary),\n  );\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button } from '@sveltia/ui';\n\n  import PanelContainer from '$lib/components/contents/details/sidebar/panels/panel-container.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getEntryEditorPath } from '$lib/services/contents/editor/route';\n  import { getBacklinks } from '$lib/services/contents/entry/relations/backlinks';\n\n  /**\n   * @import { EntryBacklink } from '$lib/types/private';\n   */\n\n  const entryDraft = getEntryDraftContext();\n  const id = $props.id();\n\n  /** @type {EntryBacklink[]} */\n  const backlinks = $derived.by(() => {\n    const draft = entryDraft.current;\n\n    if (!draft?.originalEntry) {\n      return [];\n    }\n\n    return getBacklinks({\n      collectionName: draft.collectionName,\n      fileName: draft.fileName,\n      entry: draft.originalEntry,\n    });\n  });\n\n  /**\n   * @typedef {{ collectionLabel: string, items: EntryBacklink[] }} EntryBacklinkGroup\n   */\n\n  /** @type {EntryBacklinkGroup[]} */\n  const groupedEntries = $derived.by(() => {\n    /** @type {EntryBacklinkGroup[]} */\n    const groups = [];\n\n    backlinks.forEach((ref) => {\n      const existing = groups.find((g) => g.collectionLabel === ref.collectionLabel);\n\n      if (existing) {\n        existing.items.push(ref);\n      } else {\n        groups.push({ collectionLabel: ref.collectionLabel, items: [ref] });\n      }\n    });\n\n    return groups;\n  });\n</script>\n\n<PanelContainer title={_('entry_sidebar.backlinks.title')}>\n  {#if backlinks.length > 0}\n    {#each groupedEntries as { collectionLabel, items }, index (collectionLabel)}\n      <section class=\"collection\" role=\"group\" aria-labelledby=\"{id}-{index}-label\">\n        <h4 id=\"{id}-{index}-label\">{collectionLabel}</h4>\n        {#each items as ref (ref.entry.id)}\n          <Button\n            class=\"ref\"\n            variant=\"ghost\"\n            onclick={() => {\n              goto(getEntryEditorPath(ref.collectionName, ref.fileName ?? ref.entry.subPath), {\n                transitionType: 'forwards',\n              });\n            }}\n          >\n            <span class=\"summary\"><bdi>{ref.summary}</bdi></span>\n          </Button>\n        {/each}\n      </section>\n    {/each}\n  {:else}\n    <div class=\"empty\">{_('entry_sidebar.backlinks.no_entries')}</div>\n  {/if}\n</PanelContainer>\n\n<style>\n  .collection {\n    padding: 4px;\n\n    &:not(:first-child) {\n      border-top: 2px solid var(--sui-secondary-background-color);\n    }\n  }\n</style>\n","import { backend } from '$lib/services/backends';\nimport { getEarlierEntryPaths } from '$lib/services/contents/entry/earlier-paths';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\n\n/**\n * @import { Entry, FileCommit, InternalCollection } from '$lib/types/private';\n * @import { Field } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} EntryHistory\n * @property {FileCommit[]} commits Fetched commits.\n * @property {boolean} loading Whether commits are being fetched.\n * @property {boolean} error Whether the fetch failed.\n */\n\n/** @type {Map<string, EntryHistory>} */\nconst historyCache = new Map();\n\n/**\n * Fetch the commit history for the current entry draft, using a cache to avoid redundant requests.\n * Returns immediately if the data is already cached for the same entry.\n * @param {Entry} entry The entry to fetch the history for.\n * @param {object} [options] Options.\n * @param {InternalCollection} [options.collection] Collection of the entry, to include the history\n * of the files it had before it was renamed outside the CMS, which the Git host doesn’t carry over;\n * see {@link getEarlierEntryPaths}.\n * @param {Field[]} [options.fields] Field list of the collection.\n * @returns {Promise<EntryHistory>} The commit history result.\n */\nexport const fetchEntryHistory = async (entry, { collection, fields } = {}) => {\n  const { id } = entry;\n  const cached = historyCache.get(id);\n\n  if (cached) {\n    return cached;\n  }\n\n  const _backend = backend.current;\n\n  if (!_backend?.fetchFileCommits) {\n    return { commits: [], loading: false, error: false };\n  }\n\n  const paths = [\n    ...getEntryPaths(entry),\n    ...(collection\n      ? getEarlierEntryPaths({ collection, fields, entry }).flatMap((earlier) => earlier.paths)\n      : []),\n  ];\n\n  try {\n    const commits = await _backend.fetchFileCommits(paths);\n    const result = { commits, loading: false, error: false };\n\n    historyCache.set(id, result);\n\n    return result;\n  } catch {\n    const result = { commits: [], loading: false, error: true };\n\n    historyCache.set(id, result);\n\n    return result;\n  }\n};\n\n/**\n * Clear the cached commit history for the given entry ID, so that the next call to\n * {@link fetchEntryHistory} fetches fresh data.\n * @param {string} entryId The ID of the entry to clear from the cache.\n */\nexport const clearEntryHistoryCache = (entryId) => {\n  historyCache.delete(entryId);\n};\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Button } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import Avatar from '$lib/components/common/avatar.svelte';\n  import PanelContainer from '$lib/components/contents/details/sidebar/panels/panel-container.svelte';\n  import { backend } from '$lib/services/backends';\n  import { getCommitMessagePromptMode } from '$lib/services/backends/commit-prompt';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { fetchEntryHistory } from '$lib/services/contents/entry/history';\n  import { formatRecentDateTime } from '$lib/services/utils/date';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @import { Entry, EntryDraft, FileCommit } from '$lib/types/private';\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FileCommit[]} */\n  let commits = $state([]);\n  let loading = $state(false);\n  let error = $state(false);\n\n  /**\n   * Whether to show the commit messages. Without the commit message prompt, the CMS’s own commit\n   * messages for an entry are all the same generated text, so they add nothing.\n   */\n  const showMessages = $derived(!!getCommitMessagePromptMode());\n\n  /**\n   * The entry whose history is shown. Saving without closing the editor replaces the draft with one\n   * for the saved entry while the panel stays mounted, so the history is reloaded then.\n   */\n  const entry = $derived(entryDraft.current?.originalEntry);\n\n  /**\n   * Load the commit history for the given entry, using the external cache. A result that arrives\n   * after the entry has been replaced again is discarded.\n   * @param {Entry} target Entry.\n   */\n  const load = async (target) => {\n    loading = true;\n\n    // Including the files it had before it was renamed outside the CMS\n    const { collection, fields } = /** @type {EntryDraft} */ (entryDraft.current);\n    const result = await fetchEntryHistory(target, { collection, fields });\n\n    if (target === entry) {\n      ({ commits, error } = result);\n      loading = false;\n    }\n  };\n\n  $effect(() => {\n    /* v8 ignore next 3 -- the panel is only offered for an existing entry */\n    if (!entry) {\n      return;\n    }\n\n    const target = entry;\n\n    // Don’t let anything the fetch reads become a dependency of the effect\n    untrack(() => load(target));\n  });\n</script>\n\n<PanelContainer title={_('entry_sidebar.history.title')}>\n  {#if loading}\n    <div class=\"empty\">{_('loading')}</div>\n  {:else if error}\n    <div class=\"empty\">{_('entry_sidebar.history.fetch_failed')}</div>\n  {:else if commits.length > 0}\n    <div role=\"list\" class=\"commits\">\n      {#each commits as commit (commit.sha)}\n        {@const commitURL = backend.current?.repository?.commitBaseURL\n          ? `${backend.current.repository.commitBaseURL}/${commit.sha}`\n          : undefined}\n        {@const message = showMessages ? commit.message : ''}\n        <div role=\"listitem\">\n          <Button\n            class=\"ref\"\n            variant=\"ghost\"\n            role=\"link\"\n            disabled={!commitURL}\n            onclick={() => {\n              // The button is disabled without a URL\n              openNewTab(/** @type {string} */ (commitURL));\n            }}\n          >\n            <!-- Initials for someone GitHub doesn’t know, e.g. whom an app committed for -->\n            <Avatar\n              name={commit.authorName}\n              username={commit.authorLogin}\n              src={commit.authorAvatarURL}\n            />\n            <span class=\"details\">\n              {#if message}\n                <span class=\"message\" title={message}><bdi>{message}</bdi></span>\n              {/if}\n              <span class=\"meta\" class:secondary={!!message}>\n                <span class=\"author\"><bdi>{commit.authorName}</bdi></span>\n                <span class=\"date\">\n                  {formatRecentDateTime({ timestamp: commit.date, locale: appLocale.current })}\n                </span>\n              </span>\n            </span>\n          </Button>\n        </div>\n      {/each}\n    </div>\n  {:else}\n    <div class=\"empty\">{_('entry_sidebar.history.no_history')}</div>\n  {/if}\n</PanelContainer>\n\n<style>\n  .commits {\n    padding: 4px;\n  }\n\n  .details {\n    display: flex;\n    flex-direction: column;\n    gap: 2px;\n    overflow: hidden;\n    font-size: var(--sui-font-size-small);\n  }\n\n  .message,\n  .author {\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n  }\n\n  .meta {\n    display: flex;\n    flex-direction: column;\n    gap: 2px;\n    overflow: hidden;\n\n    &.secondary {\n      flex-direction: row;\n      gap: 8px;\n      color: var(--sui-tertiary-foreground-color);\n      font-size: var(--sui-font-size-x-small);\n    }\n  }\n\n  .date {\n    flex: none;\n    color: var(--sui-tertiary-foreground-color);\n  }\n</style>\n","<!--\n  @component\n  Show a section of a sidebar panel, e.g. for a locale, headed with its label the way the Validation\n  panel does. A section without a heading, e.g. for the only value in a panel, keeps its label for\n  assistive technology.\n-->\n<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} label Label of the section.\n   * @property {boolean} [showLabel] Whether to show the label as the section heading.\n   * @property {Snippet<[string]>} children Section content, given the ID of the label element to\n   * label a field with.\n   */\n\n  /** @type {Props} */\n  let { label, showLabel = true, children } = $props();\n\n  const id = $props.id();\n  const labelId = `${id}-label`;\n</script>\n\n<!-- Only a headed section is a group of its own; the only value in a panel is the panel’s -->\n<section\n  role={showLabel ? 'group' : 'none'}\n  class=\"section\"\n  aria-labelledby={showLabel ? labelId : undefined}\n>\n  {#if showLabel}\n    <h4 id={labelId}>{label}</h4>\n  {:else}\n    <span id={labelId} hidden>{label}</span>\n  {/if}\n  <div role=\"none\" class=\"content\">\n    {@render children(labelId)}\n  </div>\n</section>\n\n<style>\n  .section {\n    padding: 4px;\n\n    &:not(:first-child) {\n      border-top: 2px solid var(--sui-secondary-background-color);\n    }\n  }\n\n  h4 {\n    margin: 0 !important;\n    padding: 12px;\n  }\n\n  .content {\n    padding: 4px 8px 8px;\n  }\n</style>\n","import { _ } from '@sveltia/i18n';\n\nimport { validateNewFolderName } from '$lib/services/common/slug';\nimport { getSlugOptions, hasLocalizedSlugs } from '$lib/services/contents/collection/slug';\nimport {\n  getSlugValidationMessage,\n  validateSlug,\n} from '$lib/services/contents/draft/validate/slugs';\nimport { getLocaleLabel } from '$lib/services/contents/i18n';\nimport { getBaseName } from '$lib/services/utils/file';\n\n/**\n * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * A value the Slug panel lets the user edit: a slug, or the name of the folder the entry occupies.\n * @typedef {object} SlugEditRow\n * @property {InternalLocaleCode} locale Locale.\n * @property {string} label Label of the value.\n * @property {boolean} showLabel Whether to show the label, which is the locale of the value. A\n * value shared by every locale is the only one, which needs no heading.\n * @property {string} value Current slug or folder name.\n */\n\n/**\n * Get the values the Slug panel lets the user edit: the entry’s folder names, in a collection where\n * every entry is an index file within a folder of its own, or else its slugs. A locale the entry\n * has no file for has no slug to rename.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Record<InternalLocaleCode, string> | undefined} args.ownFolderPaths Folder the entry\n * occupies in each locale, if any.\n * @returns {SlugEditRow[]} Values.\n */\nexport const getSlugEditRows = ({ draft, ownFolderPaths }) => {\n  // Each locale has a folder of its own when the slugs are localized, as the folder is named after\n  // the slug. Otherwise, the folder is shared by every locale\n  // @see https://github.com/sveltia/sveltia-cms/issues/962\n  const localized = hasLocalizedSlugs(draft.collection);\n\n  /**\n   * Get the label of a value: its locale, or what it is if it’s shared by every locale.\n   * @param {InternalLocaleCode} locale Locale, or `_` or `_default` for a slug shared by every\n   * locale.\n   * @returns {{ label: string, showLabel: boolean }} Label and whether to show it.\n   */\n  const getLabel = (locale) => {\n    const shared = ownFolderPaths ? !localized : ['_', '_default'].includes(locale);\n\n    return shared\n      ? { label: _(ownFolderPaths ? 'folder' : 'slug'), showLabel: false }\n      : { label: getLocaleLabel(locale) ?? locale, showLabel: true };\n  };\n\n  if (ownFolderPaths) {\n    return Object.entries(ownFolderPaths).map(([locale, dirPath]) => ({\n      locale,\n      ...getLabel(locale),\n      value: getBaseName(dirPath),\n    }));\n  }\n\n  return Object.entries(draft.currentSlugs)\n    .filter(([, slug]) => slug !== undefined)\n    .map(([locale, slug]) => ({\n      locale,\n      ...getLabel(locale),\n      value: /** @type {string} */ (slug),\n    }));\n};\n\n/**\n * Get the error message for a slug or folder name being edited in the Slug panel.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {Record<InternalLocaleCode, string> | undefined} args.ownFolderPaths Folder the entry\n * occupies in each locale, if any, in which case the folder name is edited.\n * @param {Record<InternalLocaleCode, string[]>} args.takenFolderNames Names of the folders\n * sharing a parent with the entry’s own folder in each locale.\n * @param {Record<InternalLocaleCode, string[]>} args.takenSlugs Slugs taken by the other entries,\n * in each locale.\n * @param {InternalLocaleCode} args.locale Locale of the value.\n * @param {string} args.text Value as typed.\n * @returns {string | undefined} Error message, or `undefined` if the value can be used.\n */\nexport const getSlugEditError = ({\n  draft,\n  ownFolderPaths,\n  takenFolderNames,\n  takenSlugs,\n  locale,\n  text,\n}) => {\n  if (ownFolderPaths) {\n    // A folder name goes by different rules than a slug: it’s slugified on the way out, so what\n    // matters is that something usable survives and the folder doesn’t end up hidden behind a\n    // leading dot\n    const error = validateNewFolderName({ takenNames: takenFolderNames[locale], name: text });\n\n    return error ? _(`new_parent_folder_error.${error}`) : undefined;\n  }\n\n  const { pattern } = getSlugOptions(draft.collection);\n  const error = validateSlug({ slug: text, pattern, takenSlugs: takenSlugs[locale], locale });\n\n  return error ? getSlugValidationMessage({ error, pattern }) : undefined;\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import EditableText from '$lib/components/common/editable-text.svelte';\n  import PanelSection from '$lib/components/contents/details/sidebar/panels/panel-section.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getTakenSlugs } from '$lib/services/contents/draft/validate/slugs';\n  import {\n    getOwnFolderPaths,\n    getTakenFolderNames,\n    renameEntryFolders,\n    updateSlugs,\n  } from '$lib/services/contents/editor/slug';\n  import { getSlugEditError, getSlugEditRows } from '$lib/services/contents/editor/slug-form';\n\n  /**\n   * @import { SlugEditRow } from '$lib/services/contents/editor/slug-form';\n   * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  // The form is only rendered while the draft is there\n  const draft = $derived(/** @type {EntryDraft} */ (entryDraft.current));\n  /**\n   * Folder the entry occupies in each locale, in a collection where every entry is an index file\n   * within one. The folder name is what identifies the entry, so renaming it is what the slug\n   * editor does there, and the entry keeps its place in the tree.\n   */\n  const ownFolderPaths = $derived(getOwnFolderPaths(draft));\n  /**\n   * Slugs taken by the other entries, in each locale.\n   */\n  const takenSlugs = $derived(getTakenSlugs(draft));\n  /**\n   * Names of the folders sharing a parent with the entry’s own folder in each locale, which are the\n   * only ones that can be in the way.\n   */\n  const takenFolderNames = $derived(\n    ownFolderPaths ? getTakenFolderNames({ draft, ownFolderPaths }) : {},\n  );\n\n  /**\n   * Values to edit: the entry’s folder names or slugs.\n   */\n  const rows = $derived(getSlugEditRows({ draft, ownFolderPaths }));\n\n  /** @type {Record<InternalLocaleCode, boolean>} */\n  const editing = $state({});\n  /** @type {Record<InternalLocaleCode, string>} */\n  const texts = $state({});\n\n  /**\n   * Get the error message for the value being edited in the given locale, checked as it’s typed.\n   * @param {InternalLocaleCode} locale Locale.\n   * @returns {string | undefined} Error message, or `undefined` if the value can be used.\n   */\n  const getEditError = (locale) => {\n    if (!editing[locale]) {\n      return undefined;\n    }\n\n    return getSlugEditError({\n      draft,\n      ownFolderPaths,\n      takenFolderNames,\n      takenSlugs,\n      locale,\n      text: texts[locale],\n    });\n  };\n\n  /**\n   * Apply the edited value of the given locale to the draft. It’s saved along with the entry.\n   * @param {SlugEditRow} row Edited value.\n   * @param {string} text Edited text.\n   * @returns {boolean} Whether the editing ends, which it doesn’t while the value is invalid.\n   */\n  const apply = ({ locale, value }, text) => {\n    if (getEditError(locale)) {\n      return false;\n    }\n\n    if (text !== value) {\n      if (ownFolderPaths) {\n        // Renaming the folder is what moves the entry, so the rest of the save takes care of the\n        // entries and assets stored below it\n        renameEntryFolders({ draft, ownFolderPaths, folderNames: { [locale]: text } });\n      } else {\n        updateSlugs({ draft, slugs: { [locale]: text } });\n      }\n    }\n\n    return true;\n  };\n</script>\n\n{#each rows as row (row.locale)}\n  {@const { locale, label, showLabel, value } = row}\n  {@const error = getEditError(locale)}\n  <PanelSection {label} {showLabel}>\n    {#snippet children(labelId)}\n      <EditableText\n        id=\"{labelId}-value\"\n        {value}\n        bind:editing={editing[locale]}\n        bind:text={texts[locale]}\n        editLabel={ownFolderPaths ? _('rename_folder') : _('edit_slug')}\n        invalid={!!error}\n        applyDisabled={!!error}\n        ariaLabelledby={labelId}\n        ariaErrormessage=\"{labelId}-error\"\n        onApply={(text) => apply(row, text)}\n      />\n      <p id=\"{labelId}-error\" class=\"error\">\n        {#if error}\n          {error}\n        {/if}\n      </p>\n    {/snippet}\n  </PanelSection>\n{/each}\n\n<style>\n  p.error:empty {\n    display: none;\n  }\n\n  p.error {\n    margin: 0;\n    padding: 0 4px;\n    color: var(--sui-error-foreground-color);\n    font-size: var(--sui-font-size-small);\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import EditableText from '$lib/components/common/editable-text.svelte';\n  import SlugEditor from '$lib/components/contents/details/editor/slug-editor.svelte';\n  import PanelContainer from '$lib/components/contents/details/sidebar/panels/panel-container.svelte';\n  import PanelSection from '$lib/components/contents/details/sidebar/panels/panel-section.svelte';\n  import SlugUpdateForm from '$lib/components/contents/details/sidebar/panels/slug-update-form.svelte';\n  import { getSlugOptions, hasLocalizedSlugs } from '$lib/services/contents/collection/slug';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    canUpdateSlug,\n    getReadonlySlugs,\n    hasEntrySlug,\n  } from '$lib/services/contents/editor/slug';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n\n  const entryDraft = getEntryDraftContext();\n\n  const draft = $derived(entryDraft.current);\n  const available = $derived(hasEntrySlug(draft));\n  const canUpdate = $derived(canUpdateSlug(draft));\n  /* v8 ignore start -- only read while the entry has a slug, which needs the draft */\n  const hint = $derived(available && draft ? getSlugOptions(draft.collection).hint : undefined);\n  /**\n   * Whether each locale has a slug of its own. Otherwise, the slug is shared by every locale, so\n   * there’s a single value without a locale heading.\n   */\n  const localized = $derived(available && !!draft && hasLocalizedSlugs(draft.collection));\n  /**\n   * Locales whose slug editor is shown in a new entry. A read-only one only shares the default\n   * locale’s slug, so it’s left out.\n   */\n  const editorLocales = $derived(\n    Object.entries(draft?.slugEditor ?? {})\n      .filter(([locale, enabled]) => enabled === true && !!draft?.currentLocales[locale])\n      .map(([locale]) => locale),\n  );\n  /**\n   * Slugs to show read-only. See {@link getReadonlySlugs}.\n   */\n  const readonlySlugs = $derived(draft ? getReadonlySlugs(draft) : []);\n  /* v8 ignore stop */\n\n  /**\n   * Get the label of a slug: its locale, which heads the section, or Slug for the only slug shared\n   * by every locale, which needs no heading.\n   * @param {string} locale Locale, or `_` or `_default` for a slug shared by every locale.\n   * @returns {{ label: string, showLabel: boolean }} Label and whether to show it.\n   */\n  const getSectionLabel = (locale) =>\n    localized && !['_', '_default'].includes(locale)\n      ? { label: getLocaleLabel(locale) ?? locale, showLabel: true }\n      : { label: _('slug'), showLabel: false };\n</script>\n\n<PanelContainer title={_('entry_sidebar.slug.title')}>\n  {#if !available}\n    <div class=\"empty\">{_('entry_sidebar.slug.unavailable')}</div>\n  {:else}\n    {#if hint}\n      <p class=\"hint\">{hint}</p>\n    {/if}\n    {#if draft?.isNew && editorLocales.length}\n      {#each editorLocales as locale (locale)}\n        <PanelSection {...getSectionLabel(locale)}>\n          {#snippet children(labelId)}\n            <div role=\"none\" class=\"editor\">\n              <SlugEditor {locale} ariaLabelledby={labelId} />\n            </div>\n          {/snippet}\n        </PanelSection>\n      {/each}\n    {:else if canUpdate}\n      <SlugUpdateForm />\n    {:else}\n      {#each readonlySlugs as [locale, { slug, takenSlug }] (locale)}\n        <PanelSection {...getSectionLabel(locale)}>\n          {#snippet children(labelId)}\n            <EditableText\n              id=\"{labelId}-value\"\n              value={slug}\n              canEdit={false}\n              ariaLabelledby={labelId}\n            />\n            <!-- Kept in place so a screen reader announces the note when it appears -->\n            <div role=\"status\">\n              {#if takenSlug}\n                <p class=\"taken\">{_('slug_numbered', { values: { slug: takenSlug } })}</p>\n              {/if}\n            </div>\n          {/snippet}\n        </PanelSection>\n      {/each}\n      {#if draft?.isNew}\n        <p class=\"note\">{_('entry_sidebar.slug.generated_on_save')}</p>\n      {/if}\n    {/if}\n  {/if}\n</PanelContainer>\n\n<style>\n  .editor {\n    /* The section has padding of its own */\n    --field-editor-padding: 0;\n  }\n\n  .hint,\n  .empty {\n    margin: 0;\n    padding: 12px 16px;\n  }\n\n  .hint {\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n  }\n\n  .taken {\n    margin: 4px 0 0;\n    color: var(--sui-tertiary-foreground-color);\n    font-size: var(--sui-font-size-small);\n    line-height: var(--sui-line-height-compact);\n  }\n\n  .note {\n    margin: 0;\n    padding: 0 16px 16px;\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n  }\n</style>\n","import { _ } from '@sveltia/i18n';\n\nimport { isAdditionsEnabled, requireAdditions } from '$lib/services/app/additions';\nimport { backend } from '$lib/services/backends';\nimport { entryEditorSettings } from '$lib/services/contents/editor/settings';\nimport { hasEntrySlug } from '$lib/services/contents/editor/slug';\nimport { getDraftEntryKey } from '$lib/services/contents/entry/entry-key';\nimport { getReferencingRelationFields } from '$lib/services/contents/entry/relations';\nimport { env } from '$lib/services/user/env.svelte';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { EntryDraft } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} SidebarPanelDef\n * @property {string} key Unique key of the panel, also used in its i18n keys, e.g.\n * `entry_sidebar.validation.title`. See {@link getSidebarPanelTitle}.\n * @property {string} icon Material icon name.\n * @property {boolean} disabled Whether the panel is unavailable for the draft.\n * @property {number} [badge] Count to show on the panel’s button, e.g. of comments, if any.\n */\n\n/**\n * Get the title of a sidebar panel. The strings of the Conversation panel come with the chunk of\n * Sveltia CMS Additions, along with its others.\n * @param {string} key Panel key.\n * @returns {string} Title.\n */\nexport const getSidebarPanelTitle = (key) =>\n  _(key === 'conversation' ? 'additions.conversation.title' : `entry_sidebar.${key}.title`);\n\n/**\n * Get the label of a sidebar panel’s button or menu item, with the count shown on its badge, if\n * any, e.g. “Conversation (3)”.\n * @param {SidebarPanelDef} panel Panel.\n * @returns {string} Label.\n */\nexport const getSidebarPanelLabel = ({ key, badge }) => {\n  const title = getSidebarPanelTitle(key);\n\n  return badge ? _('entry_sidebar.title_with_count', { values: { title, count: badge } }) : title;\n};\n\n/**\n * Key of the sidebar panel shown in the bottom sheet on a small screen, where the sidebar doesn’t\n * fit, or `null` if the sheet is closed. Unlike the sidebar’s own panel, it’s not remembered, so\n * the sheet doesn’t cover the editor whenever an entry is opened.\n * @type {{ current: string | null }}\n */\nexport const sidebarSheetPanel = createRawState(null);\n\n/**\n * Get the entry editor sidebar panels, in the order they’re listed.\n * @param {EntryDraft | null | undefined} draft Entry draft.\n * @returns {SidebarPanelDef[]} Panels.\n */\nexport const getSidebarPanels = (draft) => {\n  const { collectionName, fileName, isNew = true } = draft ?? {};\n\n  return [\n    {\n      key: 'slug',\n      icon: 'anchor',\n      // Available if the entry has a slug of its own, which the panel shows, and lets the user edit\n      // if allowed\n      disabled: !hasEntrySlug(draft),\n    },\n    {\n      key: 'validation',\n      icon: 'check_circle',\n      disabled: false,\n    },\n    {\n      key: 'history',\n      icon: 'history',\n      disabled: !backend.current?.isGit || isNew,\n    },\n    // Comments kept by Sveltia CMS Additions. A new entry has nothing to attach them to yet\n    ...(isAdditionsEnabled()\n      ? [\n          {\n            key: 'conversation',\n            icon: 'forum',\n            disabled: !getDraftEntryKey(draft),\n            // Its chunk is loaded along with the backend, before the user could sign in\n            badge: requireAdditions().getConversationCount(draft),\n          },\n        ]\n      : []),\n    {\n      key: 'backlinks',\n      icon: 'article_shortcut',\n      // Available if any Relation field anywhere in the site can reference the entry\n      disabled:\n        !collectionName || !getReferencingRelationFields({ collectionName, fileName }).length,\n    },\n  ];\n};\n\n/**\n * Show the given sidebar panel: in the sidebar, or in the bottom sheet on a small screen.\n * @param {string} key Panel key.\n */\nexport const showSidebarPanel = (key) => {\n  if (env.isSmallScreen) {\n    sidebarSheetPanel.current = key;\n  } else {\n    entryEditorSettings.current = { ...entryEditorSettings.current, sidebarPanel: key };\n  }\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button } from '@sveltia/ui';\n\n  import ValidationError from '$lib/components/contents/details/editor/validation-error.svelte';\n  import PanelContainer from '$lib/components/contents/details/sidebar/panels/panel-container.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    getInvalidFields,\n    getPathValidationMessages,\n  } from '$lib/services/contents/draft/validate/messages';\n  import { validateAndRevealErrors } from '$lib/services/contents/draft/validate/reveal';\n  import { highlightEditorField } from '$lib/services/contents/editor/fields';\n  import { showSidebarPanel } from '$lib/services/contents/editor/sidebar';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { EntryDraft, EntryValidityState, InternalLocaleCode } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {typeof highlightEditorField} [onSelectField] Called when an invalid field is\n   * selected. Defaults to highlighting the field in the editor.\n   */\n\n  /** @type {Props} */\n  let { onSelectField = highlightEditorField } = $props();\n\n  const entryDraft = getEntryDraftContext();\n\n  const { validationMessages, validities } = $derived(\n    /** @type {EntryDraft} */ (entryDraft.current ?? {}),\n  );\n\n  const hasResults = $derived(\n    Object.values(validities ?? {}).some((map) => !!Object.keys(map).length),\n  );\n\n  let validating = $state(false);\n\n  /**\n   * List the validation errors in the given locale: the slug, the folder chosen with the path\n   * editor and the fields. The folder is entry-wide and chosen in the default locale’s pane, so\n   * its error is only listed for the default locale, even though every locale has its validity.\n   * @param {InternalLocaleCode} locale Locale code.\n   * @returns {{\n   * slugValidity: EntryValidityState | undefined,\n   * pathMessages: string[],\n   * invalidFields: ReturnType<typeof getInvalidFields>,\n   * }} Invalid slug validity, if any, path error messages and invalid fields.\n   */\n  const listErrors = (locale) => {\n    // The results are only shown while the draft is there\n    const draft = /** @type {EntryDraft} */ (entryDraft.current);\n    const { _slug: slugValidity, _path: pathValidity } = draft.validities[locale];\n\n    return {\n      slugValidity: slugValidity?.valid === false ? slugValidity : undefined,\n      pathMessages: getPathValidationMessages(\n        locale === draft.defaultLocale ? pathValidity : undefined,\n      ),\n      invalidFields: getInvalidFields({ draft, locale }),\n    };\n  };\n\n  /**\n   * Validate the entry on demand, so what’s left to do can be checked without attempting a save.\n   * Every rule is applied, including the required fields that an Editorial Workflow draft can be\n   * saved without: the question this answers is what stands between the entry and being published,\n   * not whether it can be saved as it stands.\n   */\n  const validate = async () => {\n    const draft = entryDraft.current;\n\n    /* v8 ignore next 3 -- the panel is only shown while the draft is there, one check at a time */\n    if (!draft || validating) {\n      return;\n    }\n\n    validating = true;\n\n    // Custom field validators can be async, so this waits for any in-flight results, as a save does\n    await validateAndRevealErrors({ draft, awaitFieldUpdates: false });\n\n    validating = false;\n  };\n</script>\n\n<PanelContainer title={_('entry_sidebar.validation.title')}>\n  {#snippet actions()}\n    <Button\n      variant=\"tertiary\"\n      size=\"small\"\n      label={_('entry_sidebar.validation.validate')}\n      disabled={!entryDraft.current || validating}\n      onclick={() => {\n        validate();\n      }}\n    />\n  {/snippet}\n  {#if hasResults}\n    {#each Object.keys(validationMessages) as locale (locale)}\n      {@const label = getLocaleLabel(locale)}\n      {@const { slugValidity, pathMessages, invalidFields } = listErrors(locale)}\n      <section class=\"locale\" role=\"group\">\n        {#if label}\n          <h4>{label}</h4>\n        {/if}\n        {#if slugValidity || pathMessages.length || invalidFields.length}\n          {#if slugValidity}\n            <!-- The slug is edited in the Slug panel rather than in the editor -->\n            <Button\n              class=\"ref\"\n              variant=\"ghost\"\n              onclick={() => {\n                showSidebarPanel('slug');\n              }}\n            >\n              <span class=\"summary\">{_('slug')}</span>\n              <ValidationError live=\"off\">\n                {slugValidity.customErrorMessage}\n              </ValidationError>\n            </Button>\n          {/if}\n          {#if pathMessages.length}\n            <Button\n              class=\"ref\"\n              variant=\"ghost\"\n              onclick={() => {\n                onSelectField({ locale, keyPath: '_path' });\n              }}\n            >\n              <span class=\"summary\">{_('entry_parent_folder')}</span>\n              {#each pathMessages as message, index (index)}\n                <ValidationError live=\"off\">\n                  {message}\n                </ValidationError>\n              {/each}\n            </Button>\n          {/if}\n          {#each invalidFields as { keyPath, label: fieldLabel, messages } (keyPath)}\n            <Button\n              class=\"ref\"\n              variant=\"ghost\"\n              onclick={() => {\n                onSelectField({ locale, keyPath });\n              }}\n            >\n              <span class=\"summary\">{fieldLabel}</span>\n              {#each messages as message, index (index)}\n                <ValidationError live=\"off\">\n                  {message}\n                </ValidationError>\n              {/each}\n            </Button>\n          {/each}\n        {:else}\n          <div class=\"empty\">{_('entry_sidebar.validation.no_errors_found')}</div>\n        {/if}\n      </section>\n    {/each}\n  {:else}\n    <div class=\"empty\">{_('entry_sidebar.validation.placeholder')}</div>\n  {/if}\n</PanelContainer>\n\n<style>\n  .locale {\n    padding: 4px;\n\n    &:not(:first-child) {\n      border-top: 2px solid var(--sui-secondary-background-color);\n    }\n\n    h4,\n    .empty {\n      margin: 0 !important;\n      padding: 12px;\n    }\n\n    .summary {\n      display: block;\n      color: var(--sui-secondary-foreground-color);\n      font-size: var(--sui-font-size-small);\n      font-weight: var(--sui-heading-font-weight);\n    }\n\n    :global {\n      .sui.button.ref {\n        flex-direction: column;\n        align-items: flex-start;\n        gap: 4px;\n      }\n    }\n  }\n</style>\n","<script>\n  import BacklinksPanel from '$lib/components/contents/details/sidebar/panels/backlinks-panel.svelte';\n  import HistoryPanel from '$lib/components/contents/details/sidebar/panels/history-panel.svelte';\n  import SlugPanel from '$lib/components/contents/details/sidebar/panels/slug-panel.svelte';\n  import ValidationPanel from '$lib/components/contents/details/sidebar/panels/validation-panel.svelte';\n  import { requireAdditions } from '$lib/services/app/additions';\n\n  /**\n   * @import { highlightEditorField } from '$lib/services/contents/editor/fields';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} key Key of the panel to render. See `getSidebarPanels()`.\n   * @property {typeof highlightEditorField} [onSelectField] Called when a field is selected in the\n   * Validation panel, instead of highlighting it directly.\n   */\n\n  /** @type {Props} */\n  let { key, onSelectField = undefined } = $props();\n\n  // The Conversation panel is only offered with Sveltia CMS Additions, whose chunk is loaded along\n  // with the backend, so it’s there whenever the panel is\n  const additions = $derived(requireAdditions());\n</script>\n\n{#if key === 'slug'}\n  <SlugPanel />\n{:else if key === 'history'}\n  <HistoryPanel />\n{:else if key === 'backlinks'}\n  <BacklinksPanel />\n{:else if key === 'conversation'}\n  <additions.ConversationPanel />\n{:else}\n  <ValidationPanel {onSelectField} />\n{/if}\n","<!--\n  @component\n  Bottom sheet that shows an entry editor sidebar panel on a small screen, where the sidebar doesn’t\n  fit. It’s opened from the editor options menu or the validation toast.\n-->\n<script>\n  import { Drawer } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import SidebarPanel from '$lib/components/contents/details/sidebar/sidebar-panel.svelte';\n  import { highlightEditorField } from '$lib/services/contents/editor/fields';\n  import { getSidebarPanelTitle, sidebarSheetPanel } from '$lib/services/contents/editor/sidebar';\n\n  /**\n   * @import { InternalLocaleCode } from '$lib/types/private';\n   * @import { FieldKeyPath } from '$lib/types/public';\n   */\n\n  /**\n   * Panel shown while the sheet slides away, or `null` if it’s not closing. The request is cleared\n   * as soon as the sheet starts closing, so a panel requested again meanwhile, even the same one,\n   * reopens the sheet once it’s closed, but the content stays until then.\n   * @type {string | null}\n   */\n  let closingKey = $state(null);\n  /**\n   * Field to highlight once the sheet is closed. The rest of the page is inert while the sheet is\n   * open, so the field can’t be focused before then.\n   * @type {{ locale: InternalLocaleCode, keyPath: FieldKeyPath } | undefined}\n   */\n  let fieldToHighlight;\n\n  const key = $derived(closingKey ?? sidebarSheetPanel.current);\n  const open = $derived(!!sidebarSheetPanel.current && !closingKey);\n\n  /**\n   * Start closing the sheet.\n   */\n  const close = () => {\n    closingKey = sidebarSheetPanel.current;\n    sidebarSheetPanel.current = null;\n  };\n\n  onMount(() => () => {\n    // The editor can go away with the sheet open, e.g. when a backlink is followed or the browser\n    // goes back, and the next editor shouldn’t open with the sheet\n    sidebarSheetPanel.current = null;\n  });\n</script>\n\n<Drawer\n  // The drawer only writes the flag back when it closes itself\n  bind:open={() => open, close}\n  class=\"entry-sidebar-sheet\"\n  position=\"bottom\"\n  size=\"medium\"\n  swipeDismiss\n  title={key ? getSidebarPanelTitle(key) : ''}\n  onClose={() => {\n    closingKey = null;\n\n    // Unless another panel has been requested in the meantime, which reopens the sheet\n    if (fieldToHighlight && !sidebarSheetPanel.current) {\n      highlightEditorField(fieldToHighlight);\n    }\n\n    fieldToHighlight = undefined;\n  }}\n>\n  <!-- The panel has a header of its own, with the title and controls; the title above still names\n    the sheet -->\n  {#snippet header()}{/snippet}\n  {#if key}\n    <SidebarPanel\n      {key}\n      onSelectField={(target) => {\n        fieldToHighlight = target;\n        close();\n      }}\n    />\n  {/if}\n</Drawer>\n\n<style>\n  :global {\n    .entry-sidebar-sheet {\n      --sui-drawer-bottom-content-border-start-start-radius: 16px;\n      --sui-drawer-bottom-content-border-start-end-radius: 16px;\n      /* The panel scrolls its own content below the header */\n      --sui-drawer-main-padding: 0;\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, SelectButton, SelectButtonGroup } from '@sveltia/ui';\n\n  import SidebarPanel from '$lib/components/contents/details/sidebar/sidebar-panel.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { entryEditorSettings } from '$lib/services/contents/editor/settings';\n  import { getSidebarPanelLabel, getSidebarPanels } from '$lib/services/contents/editor/sidebar';\n  import { needsSlugInput } from '$lib/services/contents/editor/slug';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  const entryDraft = getEntryDraftContext();\n\n  const panels = $derived(getSidebarPanels(entryDraft.current));\n  // The panel is remembered in the settings, which can also be updated from elsewhere, e.g. the\n  // Show Errors button on the validation toast\n  const savedKey = $derived(entryEditorSettings.current?.sidebarPanel ?? null);\n  /**\n   * Panel opened for the current draft without being remembered: the Slug panel for a new entry\n   * whose slug has to be typed in, so the field isn’t missed. `null` shows the remembered panel.\n   * @type {string | null}\n   */\n  let draftPanelKey = $state(null);\n  /** @type {string | undefined} */\n  let lastDraftId;\n\n  /**\n   * The displayed panel, falling back to Validation if the saved panel is unknown, or doesn’t apply\n   * to the draft, e.g. History or Conversation for a new entry.\n   */\n  const activeKey = $derived(\n    draftPanelKey ??\n      (savedKey\n        ? (panels.find((p) => p.key === savedKey && !p.disabled)?.key ?? 'validation')\n        : null),\n  );\n\n  watch(\n    () => [entryDraft.current?.id, savedKey],\n    () => {\n      const draft = entryDraft.current;\n\n      if (draft?.id !== lastDraftId) {\n        lastDraftId = draft?.id;\n        draftPanelKey = needsSlugInput(draft) ? 'slug' : null;\n      } else {\n        // A panel opened elsewhere, e.g. with the Show Errors button, takes over\n        draftPanelKey = null;\n      }\n    },\n  );\n</script>\n\n<div role=\"none\" class=\"sidebar\">\n  <SelectButtonGroup\n    class=\"tabs\"\n    ariaLabel={_('entry_sidebar.sidebar_panels')}\n    aria-controls={activeKey ? 'entry-sidebar-content' : undefined}\n  >\n    {#each panels as panel (panel.key)}\n      {@const { key, icon, disabled, badge } = panel}\n      {@const label = getSidebarPanelLabel(panel)}\n      <SelectButton\n        iconic\n        tooltip={label}\n        tooltipPosition=\"left\"\n        aria-label={label}\n        selected={activeKey === key}\n        {disabled}\n        onclick={() => {\n          // Clicking the active tab closes the panel. Read it before the panel opened for the\n          // draft is dismissed, as that changes the active tab\n          const sidebarPanel = activeKey === key ? null : key;\n\n          draftPanelKey = null;\n          entryEditorSettings.current = { ...entryEditorSettings.current, sidebarPanel };\n        }}\n      >\n        <span role=\"none\" class=\"icon\">\n          <Icon name={icon} />\n          {#if badge}\n            <span class=\"badge\" aria-hidden=\"true\">{badge > 99 ? '99+' : badge}</span>\n          {/if}\n        </span>\n      </SelectButton>\n    {/each}\n  </SelectButtonGroup>\n  {#if activeKey}\n    <div role=\"none\" class=\"content\" id=\"entry-sidebar-content\">\n      <SidebarPanel key={activeKey} />\n    </div>\n  {/if}\n</div>\n\n<style>\n  .icon {\n    position: relative;\n    display: inline-flex;\n  }\n\n  .badge {\n    position: absolute;\n    inset-block-start: -6px;\n    inset-inline-end: -8px;\n    border-radius: 8px;\n    padding: 0 4px;\n    min-width: 16px;\n    height: 16px;\n    background-color: var(--sui-primary-accent-color);\n    color: var(--sui-primary-accent-color-inverted, #fff);\n    font-size: 10px;\n    line-height: 16px;\n    text-align: center;\n    pointer-events: none;\n  }\n\n  .sidebar {\n    flex: none;\n    display: flex;\n    flex-direction: row-reverse;\n\n    :global {\n      .tabs {\n        flex: none;\n        display: flex;\n        flex-direction: column;\n        align-items: center;\n        gap: 8px;\n        margin: 0;\n        padding: 8px 0;\n        width: 48px;\n\n        button {\n          border-radius: 4px !important;\n        }\n      }\n    }\n  }\n\n  .content {\n    flex: none;\n    width: 320px;\n    margin-inline-start: 8px;\n    border: var(--area-border);\n    border-block-end: 0;\n    border-radius: 16px 16px 0 0;\n    background-color: var(--sui-primary-background-color);\n  }\n</style>\n","<!--\n  @component\n  Render the menu items that show or hide the second pane and the preview, and turn the scroll\n  syncing on or off, preceded by a separator. The editor options menu lists them on a large screen.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, MenuItemCheckbox } from '@sveltia/ui';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    entryEditorSettings,\n    toggleEntryEditorSetting,\n  } from '$lib/services/contents/editor/settings';\n  import { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\n\n  const entryDraft = getEntryDraftContext();\n\n  const { i18nEnabled, allLocales } = $derived(getDraftI18nConfig(entryDraft.current));\n  const canPreview = $derived(entryDraft.current?.canPreview ?? true);\n  // The `editor.second_pane` option can turn the second pane off for good\n  const secondPaneAllowed = $derived(entryDraft.current?.canShowSecondPane ?? true);\n  const showSecondPane = $derived(\n    secondPaneAllowed && (entryEditorSettings.current?.showSecondPane ?? true),\n  );\n  // There’s only something to put in the second pane when another locale can be edited alongside\n  // the first one, or when the entry has a preview\n  const secondPaneAvailable = $derived(\n    secondPaneAllowed && ((i18nEnabled && allLocales.length > 1) || canPreview),\n  );\n  // Whether the preview is shown in the second pane, which is all the pane shows for an entry with\n  // a single locale, so there’s nothing to sync the scrolling with otherwise\n  const previewShown = $derived(canPreview && !!entryEditorSettings.current?.showPreview);\n  /* v8 ignore start -- only read while the draft is there, and the preview is hidden */\n  const hasSingleLocale = $derived(\n    Object.keys(entryDraft.current?.currentValues ?? {}).length === 1,\n  );\n  /* v8 ignore stop */\n</script>\n\n<Divider />\n<MenuItemCheckbox\n  label={_('show_second_pane')}\n  checked={showSecondPane}\n  disabled={!secondPaneAvailable}\n  onChange={() => {\n    toggleEntryEditorSetting('showSecondPane', true);\n  }}\n/>\n<!-- Without the second pane, the preview takes turns with the editor in the first one -->\n<MenuItemCheckbox\n  label={_('show_preview')}\n  checked={entryEditorSettings.current?.showPreview}\n  disabled={!canPreview}\n  onChange={() => {\n    toggleEntryEditorSetting('showPreview');\n  }}\n/>\n<MenuItemCheckbox\n  label={_('sync_scrolling')}\n  checked={entryEditorSettings.current?.syncScrolling}\n  disabled={!showSecondPane || (!previewShown && hasSingleLocale)}\n  onChange={() => {\n    toggleEntryEditorSetting('syncScrolling');\n  }}\n/>\n","import { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import {\n * CascadeTarget,\n * Entry,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * ResolvedRelationField,\n * } from '$lib/types/private';\n */\n\n/**\n * Get the entries that may hold a reference to the given entries through the given Relation field.\n * @param {object} args Arguments.\n * @param {ResolvedRelationField} args.relation Relation field.\n * @param {Set<string>} args.excludeIds IDs of the entries being saved or deleted on their own,\n * which are never rewritten here: a renamed entry is saved along with any self-reference it holds,\n * and a deleted entry takes its references away with it.\n * @returns {Entry[]} Candidate entries. Whether each one actually holds a reference is up to the\n * caller to find out.\n */\nexport const getCandidateEntries = ({ relation, excludeIds }) => {\n  const { sourceCollection, sourceCollectionFile } = relation;\n  const sourceFileName = sourceCollectionFile?.name;\n\n  return getEntriesByCollection(sourceCollection.name).filter(\n    (entry) =>\n      !excludeIds.has(entry.id) &&\n      // In a file/singleton collection, only the file holding the field can reference it\n      (!sourceFileName || entry.slug === sourceFileName),\n  );\n};\n\n/**\n * Update a copy of the content of an entry holding a Relation field in the given locale.\n * @template T\n * @callback CascadeContentUpdater\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Locale of the content.\n * @param {FlattenedEntryContent} args.content Flattened entry content. Not modified.\n * @param {T} args.values Values to look for in the locale, from `getLocaleValues`.\n * @returns {FlattenedEntryContent | undefined} Updated content, or `undefined` if the content holds\n * no reference.\n */\n\n/**\n * Update every entry that may hold a reference through the given Relation field, collecting the\n * results into the shared target map so that an entry referencing the same entries through more\n * than one field is only written once.\n * @template {{ size: number }} T\n * @param {object} args Arguments.\n * @param {ResolvedRelationField} args.relation Relation field to update.\n * @param {Set<string>} args.excludeIds IDs of the entries never to update. See\n * {@link getCandidateEntries}.\n * @param {Map<string, CascadeTarget>} args.targets Cascade targets, keyed by entry ID.\n * @param {(locale: InternalLocaleCode) => T} args.getLocaleValues Function to get the values to\n * look for in the entries holding the field in the given locale, such as a map of old value to new\n * value. An empty collection means there’s nothing to update in that locale.\n * @param {(sourceEntry: Entry) => CascadeContentUpdater<T>} args.getContentUpdater Function to get\n * the content updater for a candidate entry.\n */\nexport const collectCascadeTargets = ({\n  relation,\n  excludeIds,\n  targets,\n  getLocaleValues,\n  getContentUpdater,\n}) => {\n  const { sourceCollection, sourceCollectionFile } = relation;\n  const { allLocales } = sourceCollectionFile?._i18n ?? sourceCollection._i18n;\n  // Relation values can vary by the locale of the entry holding the field, e.g. when the\n  // `value_field` template contains `{{locale}}`, so each locale gets its own values. Building them\n  // up front means a field with nothing to look for is skipped without touching a single entry\n  /** @type {Map<InternalLocaleCode, T>} */\n  const valueCache = new Map(allLocales.map((locale) => [locale, getLocaleValues(locale)]));\n\n  if (![...valueCache.values()].some(({ size }) => size > 0)) {\n    return;\n  }\n\n  getCandidateEntries({ relation, excludeIds }).forEach((sourceEntry) => {\n    // Pick up any update another Relation field has already made to the same entry\n    const entry = targets.get(sourceEntry.id)?.entry ?? sourceEntry;\n    /** @type {Entry['locales']} */\n    const updatedLocales = {};\n    const updateContent = getContentUpdater(sourceEntry);\n\n    Object.entries(entry.locales).forEach(([locale, localizedEntry]) => {\n      const { content } = localizedEntry;\n\n      if (!content) {\n        return;\n      }\n\n      // A locale that’s no longer configured can still exist in an entry loaded earlier\n      const values = getOrCreate(valueCache, locale, () => getLocaleValues(locale));\n\n      if (!values.size) {\n        return;\n      }\n\n      const updatedContent = updateContent({ locale, content, values });\n\n      if (updatedContent) {\n        updatedLocales[locale] = { ...localizedEntry, content: updatedContent };\n      }\n    });\n\n    if (Object.keys(updatedLocales).length) {\n      targets.set(sourceEntry.id, {\n        entry: { ...entry, locales: { ...entry.locales, ...updatedLocales } },\n        collection: sourceCollection,\n        collectionFile: sourceCollectionFile,\n      });\n    }\n  });\n};\n","import { unique } from '@sveltia/utils/array';\n\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport {\n  buildTargetChanges,\n  compactList,\n  dedupeBlockers,\n  getFieldBlockers,\n} from '$lib/services/contents/entry/cascade';\nimport { createSyntheticDraft } from '$lib/services/contents/entry/changes';\nimport { ITEM_INDEX_SUFFIX_REGEX } from '$lib/services/contents/entry/key-paths';\nimport {\n  getEntryRelationValues,\n  getReferencingRelationFields,\n  getRelationKeyPaths,\n} from '$lib/services/contents/entry/relations';\nimport { collectCascadeTargets } from '$lib/services/contents/entry/relations/cascade';\nimport { getPublishedVersion } from '$lib/services/workflow';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * CascadeDeleteBlocker,\n * CascadeDeletePlan,\n * CascadeTarget,\n * Entry,\n * FileChange,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalLocaleCode,\n * ResolvedRelationField,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, RelationField } from '$lib/types/public';\n * @import { CascadeContentUpdater } from '$lib/services/contents/entry/relations/cascade';\n */\n\n/**\n * Get the values identifying the entries being deleted in a Relation field, for entries holding\n * the field in the given locale.\n * @param {object} args Arguments.\n * @param {RelationField} args.fieldConfig Relation field config.\n * @param {Entry[]} args.entries Entries being deleted.\n * @param {InternalLocaleCode} args.locale Locale of the entries holding the field.\n * @returns {Set<any>} Stored values.\n */\nexport const getDeletedValues = ({ fieldConfig, entries, locale }) =>\n  new Set(entries.flatMap((entry) => getEntryRelationValues({ fieldConfig, entry, locale })));\n\n/**\n * Remove the references to the deleted entries from a copy of the given content map. A single-value\n * field is left empty, the way the editor leaves it when nothing is selected; a multi-value field\n * loses the values in question and has its remaining items renumbered, since they are stored under\n * consecutive indexes.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.content Flattened entry content. Not modified.\n * @param {ResolvedRelationField} args.relation Relation field to update.\n * @param {Set<any>} args.values Values to remove.\n * @returns {{ content: FlattenedEntryContent, fieldKeyPaths: FieldKeyPath[] } | undefined} Updated\n * content and the key paths of the fields that lost a reference — the field itself rather than an\n * item within it, which is what the validator looks at — or `undefined` if the content holds no\n * reference to the deleted entries.\n */\nexport const removeReferences = ({ content, relation, values }) => {\n  const { keyPath, valuePattern, multiple } = relation;\n\n  const staleKeyPaths = getRelationKeyPaths({ content, keyPath, valuePattern, multiple }).filter(\n    (key) => values.has(content[key]),\n  );\n\n  if (!staleKeyPaths.length) {\n    return undefined;\n  }\n\n  const updatedContent = { ...content };\n\n  if (!multiple) {\n    staleKeyPaths.forEach((key) => {\n      // A field whose `value_field` is a number holds `null` when unselected, like the editor’s\n      // unselected option\n      updatedContent[key] = typeof content[key] === 'number' ? null : '';\n    });\n\n    return { content: updatedContent, fieldKeyPaths: staleKeyPaths };\n  }\n\n  // The field occurs once per list item when it’s nested in a list, so there can be several lists\n  // to compact, each under its own key path\n  const listKeyPaths = /** @type {FieldKeyPath[]} */ (\n    unique(staleKeyPaths.map((key) => key.replace(ITEM_INDEX_SUFFIX_REGEX, '')))\n  );\n\n  /**\n   * Check whether an item holds a reference to a deleted entry.\n   * @param {FieldKeyPath} _key Item key path.\n   * @param {any} value Stored value.\n   * @returns {boolean} Result.\n   */\n  const isStale = (_key, value) => values.has(value);\n\n  listKeyPaths.forEach((listKeyPath) => {\n    compactList({ content: updatedContent, listKeyPath, isStale });\n  });\n\n  return { content: updatedContent, fieldKeyPaths: listKeyPaths };\n};\n\n/**\n * Check the fields that lost a reference against their own validation rules, such as `required`\n * and `min`, and describe each one that no longer passes. See {@link getFieldBlockers}.\n * @param {object} args Arguments.\n * @param {any} args.draft Synthetic draft for the entry holding the fields.\n * @param {Entry} args.entry Entry holding the fields, as stored.\n * @param {ResolvedRelationField} args.relation Relation field.\n * @param {InternalLocaleCode} args.locale Locale of the updated content.\n * @param {FlattenedEntryContent} args.content Updated content.\n * @param {FieldKeyPath[]} args.fieldKeyPaths Key paths of the fields to check.\n * @returns {CascadeDeleteBlocker[]} Blockers, one per invalid field.\n */\nexport const getBlockers = ({ draft, entry, relation, locale, content, fieldKeyPaths }) =>\n  getFieldBlockers({\n    draft,\n    entry,\n    collection: relation.sourceCollection,\n    collectionFile: relation.sourceCollectionFile,\n    locale,\n    content,\n    fields: new Map(fieldKeyPaths.map((keyPath) => [keyPath, relation.fieldConfig])),\n  });\n\n/**\n * Remove the references to the deleted entries from every entry holding the given Relation field,\n * collecting the results into the shared target map so that an entry referencing the deleted\n * entries through more than one field is only written once, and noting every field the removal\n * would leave invalid.\n * @param {object} args Arguments.\n * @param {ResolvedRelationField} args.relation Relation field to update.\n * @param {Entry[]} args.entries Entries being deleted.\n * @param {Set<string>} args.deletedIds IDs of the entries being deleted.\n * @param {Map<string, CascadeTarget>} args.targets Cascade targets, keyed by entry ID.\n * @param {CascadeDeleteBlocker[]} args.blockers Blockers found so far.\n */\nconst collectDeleteTargets = ({ relation, entries, deletedIds, targets, blockers }) => {\n  const { fieldConfig, sourceCollection, sourceCollectionFile } = relation;\n\n  collectCascadeTargets({\n    relation,\n    excludeIds: deletedIds,\n    targets,\n    /**\n     * Get the values identifying the entries being deleted in the given locale.\n     * @param {InternalLocaleCode} locale Locale of the entries holding the field.\n     * @returns {Set<any>} Stored values.\n     */\n    getLocaleValues: (locale) => getDeletedValues({ fieldConfig, entries, locale }),\n    /**\n     * Get the function that removes the references to the deleted entries from an entry’s content\n     * and notes every field the removal would leave invalid.\n     * @param {Entry} sourceEntry Entry holding the field.\n     * @returns {CascadeContentUpdater<Set<any>>} Content updater.\n     */\n    getContentUpdater: (sourceEntry) => {\n      const draft = createSyntheticDraft({\n        collection: sourceCollection,\n        collectionFile: sourceCollectionFile,\n        isIndexFile: isCollectionIndexFile(sourceCollection, sourceEntry),\n      });\n\n      return ({ locale, content, values }) => {\n        const result = removeReferences({ content, relation, values });\n\n        if (!result) {\n          return undefined;\n        }\n\n        blockers.push(\n          ...getBlockers({\n            draft,\n            entry: sourceEntry,\n            relation,\n            locale,\n            content: result.content,\n            fieldKeyPaths: result.fieldKeyPaths,\n          }),\n        );\n\n        return result.content;\n      };\n    },\n  });\n};\n\n/**\n * Get every version of the entries being deleted that a reference can point at. Under Editorial\n * Workflow, an entry being edited in a pull request may have been renamed there, or had the field\n * its `value_field` points at edited, while the published entries still reference it as it stands\n * on the configured branch, so its published version is looked at as well. Its own version can’t\n * be left out either: the pull request may have brought the referencing entries along with it.\n * @param {Entry[]} entries Entries being deleted.\n * @returns {Entry[]} Entries, followed by the published versions of the unpublished ones.\n */\nexport const getDeletedVersions = (entries) => {\n  const published = entries.flatMap((entry) => {\n    const version = getPublishedVersion(entry);\n\n    return version && !entries.includes(version) ? [version] : [];\n  });\n\n  return published.length ? [...entries, ...new Set(published)] : entries;\n};\n\n/**\n * Plan with nothing to update and nothing blocking the deletion.\n * @type {CascadeDeletePlan}\n */\nexport const EMPTY_CASCADE_DELETE_PLAN = { targets: [], blockers: [] };\n\n/**\n * Work out what deleting the given entries means for the entries referencing them through Relation\n * fields, the way a database cascades a delete to the rows referencing the deleted key: each\n * reference is removed, unless doing so would leave the referencing field in breach of its own\n * validation rules — a `required` field with nothing left selected, a multi-value field with fewer\n * than `min` items — in which case the deletion is reported as blocked, so the referencing entries\n * stay valid. Nothing is planned for an entry no one references, so a deletion in a collection no\n * Relation field points at costs a single lookup.\n *\n * The plan is computed from the entries as currently loaded; it’s meant to be shown for\n * confirmation and then carried out with {@link buildCascadeDeleteChanges} straight away.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection of the entries being deleted.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file of the entries being\n * deleted.\n * @param {Entry[]} args.entries Entries being deleted.\n * @returns {CascadeDeletePlan} Plan.\n */\nexport const planCascadeDelete = ({ collection, collectionFile, entries }) => {\n  /** @type {Map<string, CascadeTarget>} */\n  const targets = new Map();\n  /** @type {CascadeDeleteBlocker[]} */\n  const blockers = [];\n\n  if (entries.length) {\n    const versions = getDeletedVersions(entries);\n    const deletedIds = new Set(versions.map(({ id }) => id));\n\n    getReferencingRelationFields({\n      collectionName: collection.name,\n      fileName: collectionFile?.name,\n    }).forEach((relation) => {\n      collectDeleteTargets({ relation, entries: versions, deletedIds, targets, blockers });\n    });\n  }\n\n  return { targets: [...targets.values()], blockers: dedupeBlockers(blockers) };\n};\n\n/**\n * Run {@link planCascadeDelete} and throw if anything blocks the deletion.\n * @param {object} args Arguments for {@link planCascadeDelete}.\n * @param {InternalCollection} args.collection Collection of the entries being deleted.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file of the entries being\n * deleted.\n * @param {Entry[]} args.entries Entries being deleted.\n * @param {string} message Error message used when the deletion is blocked.\n * @returns {CascadeTarget[]} Targets from the plan.\n * @throws {Error} When removing the references would leave another entry invalid. The blockers are\n * attached as the error’s `cause`.\n */\nexport const planCascadeDeleteOrThrow = (args, message) => {\n  const { targets, blockers } = planCascadeDelete(args);\n\n  if (blockers.length) {\n    throw new Error(message, { cause: blockers });\n  }\n\n  return targets;\n};\n\n/**\n * Build the file changes that carry out a {@link planCascadeDelete} plan, so that the references\n * are removed in the same commit as the entries they point at.\n * @param {object} args Arguments.\n * @param {CascadeTarget[]} args.targets Targets from the plan. A caller that has already rewritten\n * some of the entries as part of the same operation leaves those out, so that no file is written\n * twice.\n * @param {IndexedDB} [args.cacheDB] Pre-opened file-cache database to reuse.\n * @returns {Promise<{ changes: FileChange[], savingEntries: Entry[] }>} Collected changes and the\n * entries to be saved.\n */\nexport const buildCascadeDeleteChanges = async ({ targets, cacheDB }) =>\n  buildTargetChanges({ targets, cacheDB });\n","<!--\n  @component\n  Ask the user to confirm the deletion of the entry being edited, explaining what it means for the\n  entry and for the entries referencing it through Relation fields. The deletion is refused when\n  it would leave another entry invalid.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { ConfirmationDialog } from '@sveltia/ui';\n\n  import CascadeDeleteNote from '$lib/components/common/cascade-delete-note.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    EMPTY_CASCADE_DELETE_PLAN,\n    planCascadeDelete,\n  } from '$lib/services/contents/entry/relations/cascade/delete';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} open Whether the dialog is open.\n   * @property {boolean} discardsDraft Whether the deletion throws away an unpublished entry that\n   * has never been published.\n   * @property {boolean} useWorkflow Whether the removal goes through Editorial Workflow.\n   * @property {boolean} withAssets Whether the assets stored alongside the entry are deleted too.\n   * @property {() => Promise<void>} onOk Function called once the deletion is confirmed.\n   * @property {() => void} onClose Function called once the dialog is closed, e.g. to move the\n   * focus back to the menu button.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { open = $bindable(false), discardsDraft, useWorkflow, withAssets, onOk, onClose } = $props();\n\n  const collection = $derived(entryDraft.current?.collection);\n  const collectionFile = $derived(entryDraft.current?.collectionFile);\n  const originalEntry = $derived(entryDraft.current?.originalEntry);\n  // What the deletion means for the entries referencing this one through Relation fields. Nothing\n  // on the configured branch can reference a draft that has never been published, and the scan is\n  // only worth doing while the dialog is open\n  const cascadePlan = $derived(\n    open && collection && originalEntry && !discardsDraft\n      ? planCascadeDelete({ collection, collectionFile, entries: [originalEntry] })\n      : EMPTY_CASCADE_DELETE_PLAN,\n  );\n</script>\n\n<ConfirmationDialog\n  bind:open\n  title={_('delete_entries', { values: { count: 1 } })}\n  okLabel={_('delete')}\n  okDisabled={!!cascadePlan.blockers.length}\n  {onOk}\n  {onClose}\n>\n  <!-- There’s nothing to confirm when the deletion is refused; the note explains why -->\n  {#if cascadePlan.blockers.length}\n    <CascadeDeleteNote plan={cascadePlan} count={1} />\n  {:else}\n    {#if discardsDraft}\n      {_('workflow.confirm_deleting_unpublished_entry')}\n    {:else if useWorkflow}\n      <!-- The removal is committed to a pull request rather than to the configured branch -->\n      {_('workflow.confirm_deleting_published_entry')}\n    {:else}\n      {_(withAssets ? 'confirm_deleting_this_entry_with_assets' : 'confirm_deleting_this_entry')}\n    {/if}\n    <CascadeDeleteNote plan={cascadePlan} count={1} />\n  {/if}\n</ConfirmationDialog>\n","import { isPublishingCommit } from '$lib/services/backends/git/shared/integration';\nimport { saveChanges } from '$lib/services/backends/save';\nimport {\n  contentUpdatesToast,\n  UPDATE_TOAST_DEFAULT_STATE,\n} from '$lib/services/contents/collection/data';\n\n/**\n * @import {\n * CommitOptions,\n * Entry,\n * FileChange,\n * InternalEntryCollection,\n * } from '$lib/types/private';\n */\n\n/**\n * Commit changes made to existing entries of a collection from the entry list, like a bulk edit or\n * a new order, in a single commit, and tell the user how many entries were saved.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {FileChange[]} args.changes File changes to commit.\n * @param {Entry[]} args.savingEntries Entries being saved.\n * @returns {Promise<number>} Number of entries saved. `0` if there’s nothing to commit.\n */\nexport const saveEntryUpdates = async ({ collection, changes, savingEntries }) => {\n  if (!changes.length) {\n    return 0;\n  }\n\n  /** @type {CommitOptions} */\n  const options = { commitType: 'update', collection };\n\n  await saveChanges({ changes, savingEntries, options });\n\n  contentUpdatesToast.current = {\n    ...UPDATE_TOAST_DEFAULT_STATE,\n    saved: true,\n    // The changes go straight to the branch, like an entry saved without Editorial Workflow\n    published: isPublishingCommit(options),\n    count: savingEntries.length,\n  };\n\n  return savingEntries.length;\n};\n","import { isConfigReadonly } from '$lib/services/config/readonly';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { sortEntriesByOrderField } from '$lib/services/contents/collection/entries/reorder/sort';\nimport { saveEntryUpdates } from '$lib/services/contents/collection/entries/save';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { resolveCacheDB } from '$lib/services/contents/draft/save/file-changes';\nimport {\n  buildEntryUpdateChanges,\n  createSyntheticDraft,\n} from '$lib/services/contents/entry/changes';\nimport { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import { Entry, FileChange, InternalEntryCollection } from '$lib/types/private';\n */\n\n/**\n * Apply a new order value to all locales of an entry that have content. Locales without content are\n * passed through unchanged so that they can still be referenced (e.g. for paths) without adding an\n * `order` field to an empty content object.\n * @param {Entry} entry Source entry.\n * @param {string} orderKey Order field key.\n * @param {number} newOrder New order value.\n * @returns {Entry} Updated entry (the original entry is not mutated).\n */\nconst withUpdatedOrder = (entry, orderKey, newOrder) => {\n  /** @type {Entry['locales']} */\n  const updatedLocales = Object.fromEntries(\n    Object.entries(entry.locales).map(([locale, le]) => [\n      locale,\n      le.content ? { ...le, content: { ...le.content, [orderKey]: newOrder } } : { ...le },\n    ]),\n  );\n\n  return { ...entry, locales: updatedLocales };\n};\n\n/**\n * Build the {@link FileChange}s needed to renumber the given entries with new 1-based order values.\n * Entries whose order field already matches the target value are skipped so no empty commits are\n * produced. The returned `savingEntries` are clones with the new order applied.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {Entry[]} orderedEntries Entries in the desired display order.\n * @param {object} [options] Options.\n * @param {IndexedDB} [options.cacheDB] Pre-opened file-cache database to reuse.\n * @returns {Promise<{ changes: FileChange[], savingEntries: Entry[] }>} Collected changes and the\n * entries to be saved.\n */\nconst buildReorderChanges = async (collection, orderedEntries, { cacheDB } = {}) => {\n  const orderKey = getOrderFieldKey(collection);\n\n  if (!orderKey) {\n    return { changes: [], savingEntries: [] };\n  }\n\n  const {\n    _i18n: { defaultLocale },\n  } = collection;\n\n  const db = resolveCacheDB(cacheDB);\n  const savingEntries = [];\n\n  // Single pass: skip entries whose order already matches the target value (so unchanged entries\n  // don’t trigger a normalize-only commit) and re-tag the rest with the new 1-based order. The\n  // existing value is coerced to a number so that a string-typed `order` (e.g. `\"5\"`) is treated as\n  // already-correct when it matches the new numeric order.\n  // eslint-disable-next-line no-restricted-syntax\n  for (const [index, entry] of orderedEntries.entries()) {\n    const newOrder = index + 1;\n    // The value is read like the entries are sorted, from another locale if the default one is\n    // missing\n    const currentOrder = getEntryLocaleFile(entry, { defaultLocale })?.content?.[orderKey];\n\n    if (Number(currentOrder) !== newOrder) {\n      savingEntries.push(withUpdatedOrder(entry, orderKey, newOrder));\n    }\n  }\n\n  // Build the synthetic draft once for the whole batch — its shape is identical across entries.\n  const draft = createSyntheticDraft({ collection });\n\n  // Build file changes in parallel\n  const perEntryChanges = await Promise.all(\n    savingEntries.map((entry) =>\n      buildEntryUpdateChanges({ collection, entry, draft, cacheDB: db }),\n    ),\n  );\n\n  return { changes: perEntryChanges.flat(), savingEntries };\n};\n\n/**\n * Build the change needed to reorder the entries of a collection storing all the entries in one\n * file, which rewrites the file with the items in the new order.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {Entry[]} orderedEntries Entries in the desired display order.\n * @returns {{ changes: FileChange[], savingEntries: Entry[] }} The change, if the order has\n * changed, and the entries that have moved.\n */\nconst buildArrayFileReorderChanges = (collection, orderedEntries) => {\n  // The entries take the positions they occupy now, so an entry has moved if it doesn’t take its\n  // own position\n  const positions = orderedEntries\n    .map(({ arrayIndex }) => /** @type {number} */ (arrayIndex))\n    .sort((a, b) => a - b);\n\n  const savingEntries = orderedEntries.filter(\n    ({ arrayIndex }, index) => arrayIndex !== positions[index],\n  );\n\n  if (!savingEntries.length) {\n    return { changes: [], savingEntries: [] };\n  }\n\n  /** @type {FileChange} */\n  const change = {\n    action: 'update',\n    path: /** @type {string} */ (collection._file.fullPath),\n    arrayOrder: orderedEntries.map(({ arrayIndex, locales }) => ({\n      index: /** @type {number} */ (arrayIndex),\n      locales,\n    })),\n  };\n\n  return { changes: [change], savingEntries };\n};\n\n/**\n * Re-save entries in the given collection with updated order values. Entries whose order field\n * value is unchanged are skipped to avoid unnecessary commits. Files are written using the\n * collection’s configured format and i18n structure.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {Entry[]} orderedEntries Entries in the desired display order. The new order value\n * assigned to each entry is its 1-based index in this list.\n * @returns {Promise<number>} Number of entries actually updated.\n */\nexport const reorderEntries = async (collection, orderedEntries) => {\n  // The collection could have been made read-only since the entries were put in reorder mode, e.g.\n  // by a configuration reload, in which case nothing is written, like with a bulk edit\n  if (isConfigReadonly({ collection })) {\n    return 0;\n  }\n\n  const { changes, savingEntries } = isArrayFileCollection(collection)\n    ? buildArrayFileReorderChanges(collection, orderedEntries)\n    : await buildReorderChanges(collection, orderedEntries);\n\n  return saveEntryUpdates({ collection, changes, savingEntries });\n};\n\n/**\n * Compute the renumbered list of remaining entries for the given collection, in the order their\n * `order` field should be persisted. Entries currently lacking a valid numeric order are placed at\n * the end. The collection’s index file (if any) is excluded.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {object} [options] Options.\n * @param {Set<string>} [options.excludeIds] IDs of entries to omit (e.g. entries about to be\n * deleted). The collection’s current entries are read from {@link getEntriesByCollection}.\n * @param {Map<string, Entry>} [options.updatedEntries] Entries already rewritten by the same\n * operation, keyed by ID, which stand in for their stored counterparts so that the renumbered file\n * carries both updates.\n * @returns {Entry[]} Entries in the desired display order, with the index file removed.\n */\nconst computeRenumberedEntries = (collection, { excludeIds, updatedEntries } = {}) => {\n  // The index file (e.g. Hugo `_index.md`) is always pinned to the top of the list by the sort\n  // pipeline regardless of its `order` value, so it should never participate in numbering. It’s\n  // told by its path, as another collection’s index file within this folder has the same slug\n  const remaining = getEntriesByCollection(collection.name)\n    .filter(\n      (entry) =>\n        !isCollectionIndexFile(collection, entry) && !(excludeIds && excludeIds.has(entry.id)),\n    )\n    .map((entry) => updatedEntries?.get(entry.id) ?? entry);\n\n  return sortEntriesByOrderField(remaining, collection);\n};\n\n/**\n * Build the renumber {@link FileChange}s for a collection without saving them. Useful when the\n * caller wants to bundle the renumber into another commit (e.g. delete).\n * @param {InternalEntryCollection | undefined} collection Entry collection.\n * @param {object} [options] Options.\n * @param {Set<string>} [options.excludeIds] IDs of entries to omit (e.g. entries about to be\n * deleted).\n * @param {Map<string, Entry>} [options.updatedEntries] Entries already rewritten by the same\n * operation, keyed by ID. See {@link computeRenumberedEntries}.\n * @param {IndexedDB} [options.cacheDB] Pre-opened file-cache database to reuse.\n * @returns {Promise<{ changes: FileChange[], savingEntries: Entry[] }>} Collected changes and the\n * entries to be saved. Empty when reordering is not enabled or nothing changed.\n */\nexport const buildRenumberChanges = async (\n  collection,\n  { excludeIds, updatedEntries, cacheDB } = {},\n) => {\n  if (!collection || collection._type !== 'entry' || !getOrderFieldKey(collection)) {\n    return { changes: [], savingEntries: [] };\n  }\n\n  return buildReorderChanges(\n    collection,\n    computeRenumberedEntries(collection, { excludeIds, updatedEntries }),\n    { cacheDB },\n  );\n};\n","import { getAdditions } from '$lib/services/app/additions';\nimport { allAssets } from '$lib/services/assets/state';\nimport { saveChanges } from '$lib/services/backends/save';\nimport { allEntries } from '$lib/services/contents';\nimport { selectedCollection } from '$lib/services/contents/collection';\nimport {\n  contentUpdatesToast,\n  UPDATE_TOAST_DEFAULT_STATE,\n} from '$lib/services/contents/collection/data';\nimport { buildRenumberChanges } from '$lib/services/contents/collection/entries/reorder';\nimport { getArrayItemTarget } from '$lib/services/contents/draft/save/changes';\nimport { getPreviousSha, resolveCacheDB } from '$lib/services/contents/draft/save/file-changes';\nimport { getEntryKey } from '$lib/services/contents/entry/entry-key';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport {\n  buildCascadeDeleteChanges,\n  planCascadeDeleteOrThrow,\n} from '$lib/services/contents/entry/relations/cascade/delete';\n\n/**\n * @import { Asset, Entry, FileChange, InternalEntryCollection } from '$lib/types/private';\n */\n\n/**\n * Update the stores after deleting entries.\n * @param {object} args Arguments.\n * @param {string[]} args.ids List of entry IDs.\n * @param {string[]} args.assetPaths List of associated asset paths.\n */\nexport const updateStores = ({ ids, assetPaths }) => {\n  const _allEntries = allEntries.current;\n  const idSet = new Set(ids);\n\n  allEntries.current = _allEntries.filter((file) => !idSet.has(file.id));\n\n  contentUpdatesToast.current = {\n    ...UPDATE_TOAST_DEFAULT_STATE,\n    deleted: true,\n    count: ids.length,\n  };\n\n  if (assetPaths.length) {\n    const assetPathSet = new Set(assetPaths);\n\n    allAssets.current = allAssets.current.filter((asset) => !assetPathSet.has(asset.path));\n  }\n};\n\n/**\n * Delete entries by slugs. The entries referencing them through Relation fields are rewritten in\n * the same commit so that no reference is left dangling.\n * @param {Entry[]} entries List of entries to be deleted.\n * @param {Asset[]} [assets] List of associated assets to be deleted.\n * @throws {Error} When removing the references would leave another entry invalid. The dialogs\n * report this before the deletion is confirmed, so this is only a safeguard.\n */\nexport const deleteEntries = async (entries, assets = []) => {\n  const collection = /** @type {InternalEntryCollection | undefined} */ (\n    selectedCollection.current\n  );\n\n  const targets = collection\n    ? planCascadeDeleteOrThrow(\n        { collection, entries },\n        'Cannot delete entries that other entries require',\n      )\n    : [];\n\n  const cacheDB = resolveCacheDB();\n  const changes = /** @type {FileChange[]} */ ([]);\n  const action = 'delete';\n\n  const ids = await Promise.all(\n    entries.map(async (entry) => {\n      const { id, slug } = entry;\n      // A single-file i18n entry lists its file once\n      const paths = getEntryPaths(entry);\n\n      await Promise.all(\n        paths.map(async (path) => {\n          const previousSha = await getPreviousSha({ cacheDB, previousPath: path });\n\n          // An entry stored in a file with the other entries is removed from the array instead\n          changes.push({ action, slug, path, previousSha, ...getArrayItemTarget(entry) });\n        }),\n      );\n\n      return id;\n    }),\n  );\n\n  const assetPaths = assets.map(({ path, sha }) => {\n    changes.push({ action, path, previousSha: sha });\n\n    return path;\n  });\n\n  // When the collection has manual reordering enabled, bundle the renumber updates of the remaining\n  // entries into the same commit so that delete + renumber is one atomic operation. The same\n  // file-cache handle is reused to avoid opening a second IndexedDB connection. An entry that both\n  // referenced a deleted entry and moves up in the order is written once, by the renumber, with\n  // the reference already removed\n  const { changes: renumberChanges, savingEntries: renumberSavingEntries } =\n    await buildRenumberChanges(collection, {\n      excludeIds: new Set(ids),\n      updatedEntries: new Map(targets.map(({ entry }) => [entry.id, entry])),\n      cacheDB,\n    });\n\n  const renumberedIds = new Set(renumberSavingEntries.map(({ id }) => id));\n\n  const { changes: cascadeChanges, savingEntries: cascadeSavingEntries } =\n    await buildCascadeDeleteChanges({\n      targets: targets.filter(({ entry }) => !renumberedIds.has(entry.id)),\n      cacheDB,\n    });\n\n  changes.push(...renumberChanges, ...cascadeChanges);\n\n  await saveChanges({\n    changes,\n    savingEntries: [...renumberSavingEntries, ...cascadeSavingEntries],\n    options: {\n      commitType: 'delete',\n      collection: selectedCollection.current,\n    },\n  });\n\n  updateStores({ ids, assetPaths });\n\n  // Comments kept by Sveltia CMS Additions go with their entry, in the background\n  if (collection) {\n    entries.forEach(({ subPath }) => {\n      getAdditions()?.deleteEntryComments(getEntryKey(collection.name, subPath));\n    });\n  }\n};\n","import equal from 'fast-deep-equal';\n\nimport { fillTemplate } from '$lib/services/common/template';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport {\n  getEntryDirPath,\n  getSharedEntryFileName,\n  isDescendantPath,\n} from '$lib/services/contents/collection/nested';\nimport { hasLocalizedSlugs } from '$lib/services/contents/collection/slug';\nimport { rewriteEntryAssetReferences } from '$lib/services/contents/draft/save/asset-references';\nimport {\n  buildEntryFileChanges,\n  resolveCacheDB,\n} from '$lib/services/contents/draft/save/file-changes';\nimport { createSyntheticDraft } from '$lib/services/contents/entry/changes';\nimport { mapEntryContent } from '$lib/services/contents/entry/locales';\nimport { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\nimport { refreshPermalinks } from '$lib/services/contents/entry/permalink';\nimport { resolveFileConfig } from '$lib/services/contents/file/config';\nimport { getBaseName } from '$lib/services/utils/file';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * Entry,\n * FileChange,\n * InternalCollection,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * LocalizedEntry,\n * } from '$lib/types/private';\n * @import { EntryFilePlan } from '$lib/services/contents/draft/save/file-changes';\n */\n\n/**\n * Folder an entry is being moved out of and into, in one locale.\n * @typedef {object} DirMove\n * @property {string} oldDir Folder the entry has been stored in.\n * @property {string} newDir Folder the entry is going to.\n */\n\n/**\n * Swap the old folder path for the new one within a sub path.\n * @param {string} subPath Sub path below the old folder.\n * @param {DirMove} move Folder move.\n * @returns {string} Sub path below the new folder.\n */\nconst moveSubPath = (subPath, { oldDir, newDir }) => {\n  const restPath = subPath.slice(oldDir.length + 1);\n\n  return newDir ? `${newDir}/${restPath}` : restPath;\n};\n\n/**\n * Rewrite an entry’s file paths and slugs for its new location. The folders can go by a different\n * name in each locale, so each locale’s file is moved on its own, from and to the folder the moved\n * ancestor has in that locale. A file that isn’t stored below the ancestor’s folder in its locale\n * is left where it is.\n * @param {object} args Arguments.\n * @param {Entry} args.entry Entry to be moved.\n * @param {DirMove} args.dirMove Folder move in the default locale.\n * @param {Record<InternalLocaleCode, DirMove>} args.localeDirMoves Folder move in each locale.\n * @returns {Entry | undefined} Moved entry, or `undefined` if none of its files moves. The original\n * is left untouched.\n * @see https://github.com/sveltia/sveltia-cms/issues/962\n */\nconst moveEntry = ({ entry, dirMove, localeDirMoves }) => {\n  const { subPath } = entry;\n  const newSubPath = moveSubPath(subPath, dirMove);\n  let moved = false;\n\n  const locales = Object.fromEntries(\n    Object.entries(entry.locales).map(([locale, localizedEntry]) => {\n      const { slug, path } = localizedEntry;\n      const localeDirMove = localeDirMoves[locale];\n\n      // A locale that was disabled leaves the entry with a path but no slug to move\n      if (!slug || !isDescendantPath(localeDirMove.oldDir, slug)) {\n        return [locale, localizedEntry];\n      }\n\n      const newLocaleSubPath = moveSubPath(slug, localeDirMove);\n\n      // The folder may keep its name in this locale while it’s renamed in another\n      if (newLocaleSubPath === slug) {\n        return [locale, localizedEntry];\n      }\n\n      // Swap the old sub path for the new one within the full file path, leaving the collection\n      // folder, any locale folder and the file extension in place\n      const index = path.lastIndexOf(slug);\n\n      /* v8 ignore next */\n      if (index === -1) {\n        return [locale, localizedEntry];\n      }\n\n      moved = true;\n\n      return [\n        locale,\n        {\n          ...localizedEntry,\n          slug: newLocaleSubPath,\n          path: `${path.slice(0, index)}${newLocaleSubPath}${path.slice(index + slug.length)}`,\n        },\n      ];\n    }),\n  );\n\n  if (!moved) {\n    return undefined;\n  }\n\n  return { ...entry, slug: newSubPath, subPath: newSubPath, locales };\n};\n\n/**\n * Refresh the canonical slug of a moved entry. Among nested entries with localized slugs, the\n * localized files are linked by the default locale’s sub path, which has just changed, so each file\n * gets the new one, or the link would go stale and stop matching the entry’s own location.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {Entry} args.entry Moved entry.\n * @returns {Entry} Entry with the canonical slug updated in every locale that has content. The\n * given entry is returned as is when the slugs aren’t localized, because the canonical slug is\n * then not maintained by the CMS.\n * @see https://github.com/sveltia/sveltia-cms/issues/962\n */\nconst updateCanonicalSlug = ({ collection, entry }) => {\n  if (!hasLocalizedSlugs(collection)) {\n    return entry;\n  }\n\n  const {\n    _i18n: {\n      defaultLocale,\n      canonicalSlug: { key, value: template },\n    },\n  } = collection;\n\n  const { subPath, locales } = entry;\n\n  const canonicalSlug =\n    template === '{{slug}}'\n      ? subPath\n      : fillTemplate(template, {\n          collection: /** @type {InternalEntryCollection} */ (collection),\n          locale: defaultLocale,\n          content: locales[defaultLocale]?.content ?? {},\n          currentSlug: subPath,\n        });\n\n  // Copy the content, which is shared with the entry in the store\n  return mapEntryContent(entry, ({ localizedEntry: { content } }) => ({\n    ...content,\n    [key]: canonicalSlug,\n  }));\n};\n\n/**\n * Build the `move` file changes for one entry that’s being relocated along with its ancestor.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {Entry} args.originalEntry Entry as it is stored now.\n * @param {Entry} args.movedEntry Same entry with its new paths.\n * @param {any} args.draft Synthetic draft used for serialization.\n * @param {IndexedDB} [args.cacheDB] File cache database, when available.\n * @returns {Promise<FileChange[]>} Changes, one per file the entry occupies: a `move` for a file\n * that goes elsewhere, or an `update` for one that stays put but has its canonical slug refreshed.\n * @see https://github.com/sveltia/sveltia-cms/issues/984\n */\nconst buildMoveChanges = async ({ collection, originalEntry, movedEntry, draft, cacheDB }) => {\n  const { defaultLocale } = collection._i18n;\n\n  return buildEntryFileChanges({\n    draft,\n    config: collection,\n    _file: resolveFileConfig({ collection, isIndexFile: draft.isIndexFile }),\n    entry: movedEntry,\n    cacheDB,\n    /**\n     * Plan the change to a file of the entry.\n     * @param {InternalLocaleCode} [locale] Locale of the file, or `undefined` for the single file.\n     * @returns {EntryFilePlan | undefined} Planned change.\n     */\n    planChange: (locale) => {\n      if (locale === undefined) {\n        // The default locale can be missing from a single-file i18n entry; another locale then\n        // has the same path\n        const { path: previousPath } = /** @type {LocalizedEntry} */ (\n          getEntryLocaleFile(originalEntry, { defaultLocale })\n        );\n\n        const { slug, path } = /** @type {LocalizedEntry} */ (\n          getEntryLocaleFile(movedEntry, { defaultLocale })\n        );\n\n        return { action: 'move', slug, path, previousPath, currentPath: previousPath };\n      }\n\n      const localizedEntry = movedEntry.locales[locale];\n\n      if (!localizedEntry?.content) {\n        return undefined;\n      }\n\n      const originalLocalizedEntry = originalEntry.locales[locale];\n      const { path: previousPath } = originalLocalizedEntry;\n      const moved = previousPath !== localizedEntry.path;\n\n      // The file stays where it is when the folder isn’t localized the same way in this locale.\n      // It still has to be rewritten if its canonical slug has been refreshed, though, or it would\n      // no longer link to the files that have moved and the entry would fall apart on reload\n      if (!moved && equal(localizedEntry.content, originalLocalizedEntry.content)) {\n        return undefined;\n      }\n\n      return {\n        action: moved ? 'move' : 'update',\n        slug: localizedEntry.slug,\n        path: localizedEntry.path,\n        previousPath: moved ? previousPath : undefined,\n        currentPath: previousPath,\n      };\n    },\n  });\n};\n\n/**\n * Build the file changes that move the whole subtree of a nested entry along with the\n * entry itself. In the `subfolders` mode, an entry stored as the index file owns the folder it’s\n * stored in, so relocating it with the path editor has to take everything below that folder with\n * it, or the descendants would be orphaned in a folder that no longer has an entry of its own.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection of the moved entry.\n * @param {Entry} [args.originalEntry] Moved entry as it was before the save. `undefined` for a new\n * entry, which has nothing below it yet.\n * @param {Entry} args.savingEntry Moved entry being saved.\n * @param {IndexedDB} [args.cacheDB] Pre-opened file-cache database to reuse.\n * @returns {Promise<{ changes: FileChange[], savingEntries: Entry[] }>} Collected changes and the\n * entries to be saved.\n * @see https://decapcms.org/docs/collection-nested/\n */\nexport const buildNestedMoveChanges = async ({\n  collection,\n  originalEntry,\n  savingEntry,\n  cacheDB,\n}) => {\n  /** @type {{ changes: FileChange[], savingEntries: Entry[] }} */\n  const noChanges = { changes: [], savingEntries: [] };\n  const indexFileName = getSharedEntryFileName(collection);\n\n  // An entry only owns its folder when it’s stored as the index file that names every entry in the\n  // `subfolders` mode. Otherwise it’s a regular file sharing the folder with its siblings and with\n  // whatever is below, none of which moves with it\n  if (!originalEntry || !indexFileName || getBaseName(originalEntry.subPath) !== indexFileName) {\n    return noChanges;\n  }\n\n  const oldDirPath = getEntryDirPath(originalEntry.subPath);\n  const newDirPath = getEntryDirPath(savingEntry.subPath);\n\n  // A folder can’t be moved into itself; the path editor rejects that before the save\n  if (!oldDirPath || isDescendantPath(oldDirPath, newDirPath)) {\n    return noChanges;\n  }\n\n  const descendants = getEntriesByCollection(collection.name).filter(\n    (entry) => entry.id !== originalEntry.id && isDescendantPath(oldDirPath, entry.subPath),\n  );\n\n  if (!descendants.length) {\n    return noChanges;\n  }\n\n  const {\n    _i18n: { allLocales },\n  } = /** @type {InternalEntryCollection} */ (collection);\n\n  /** @type {DirMove} */\n  const dirMove = { oldDir: oldDirPath, newDir: newDirPath };\n\n  // With localized slugs, the ancestor’s folder goes by a different name in each locale, and so\n  // does its destination. A locale the ancestor doesn’t have, or is only getting now, falls back to\n  // the default locale’s folder on that side\n  const localeDirMoves = Object.fromEntries(\n    allLocales.map((locale) => [\n      locale,\n      {\n        oldDir: getEntryDirPath(originalEntry.locales[locale]?.slug ?? '') || oldDirPath,\n        newDir: getEntryDirPath(savingEntry.locales[locale]?.slug ?? '') || newDirPath,\n      },\n    ]),\n  );\n\n  const movedEntries = (\n    await Promise.all(\n      descendants.map(async (entry) => {\n        const movedEntry = moveEntry({ entry, dirMove, localeDirMoves });\n\n        return movedEntry\n          ? [\n              {\n                originalEntry: entry,\n                movedEntry: refreshPermalinks({\n                  collection,\n                  // The references to the entry’s own assets by an absolute path filled with its\n                  // slug, e.g. `/blog/{{slug}}/images/photo.jpg`, follow the entry\n                  entry: await rewriteEntryAssetReferences({\n                    collection,\n                    originalEntry: entry,\n                    savingEntry: updateCanonicalSlug({ collection, entry: movedEntry }),\n                  }),\n                }),\n              },\n            ]\n          : [];\n      }),\n    )\n  ).flat();\n\n  // Nothing moves when the folder keeps its name in every locale\n  if (!movedEntries.length) {\n    return noChanges;\n  }\n\n  const db = resolveCacheDB(cacheDB);\n  const draft = createSyntheticDraft({ collection });\n\n  const perEntryChanges = await Promise.all(\n    movedEntries.map(({ originalEntry: source, movedEntry }) =>\n      buildMoveChanges({ collection, originalEntry: source, movedEntry, draft, cacheDB: db }),\n    ),\n  );\n\n  return {\n    changes: perEntryChanges.flat(),\n    savingEntries: movedEntries.map(({ movedEntry }) => movedEntry),\n  };\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { isConfigReadonly } from '$lib/services/config/readonly';\nimport { buildTargetChanges } from '$lib/services/contents/entry/cascade';\nimport { getReadonlyEntryLabel, isEntryReadonly } from '$lib/services/contents/entry/readonly';\nimport {\n  getEntryRelationValues,\n  getReferencingRelationFields,\n  getRelationKeyPaths,\n} from '$lib/services/contents/entry/relations';\nimport { collectCascadeTargets } from '$lib/services/contents/entry/relations/cascade';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * CascadeTarget,\n * Entry,\n * FileChange,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalCollectionFile,\n * InternalLocaleCode,\n * ResolvedRelationField,\n * } from '$lib/types/private';\n * @import { RelationField } from '$lib/types/public';\n * @import { CascadeContentUpdater } from '$lib/services/contents/entry/relations/cascade';\n */\n\n/**\n * Build a copy of the entry as it will exist once the save completes, but with everything except\n * its identity left untouched. Relation values are derived from templates that may combine the\n * entry slug with content fields, so recomputing them against the original content isolates the\n * effect of the rename: the two value lists are then guaranteed to line up one to one, whereas\n * content edits made in the same save could add or remove values and make them impossible to pair.\n * @param {object} args Arguments.\n * @param {Entry} args.originalEntry Entry as it was before the save.\n * @param {Entry} args.savingEntry Entry being saved.\n * @param {string} [args.canonicalSlugKey] Property name of the canonical slug, which mirrors the\n * default locale’s slug and therefore changes along with it.\n * @returns {Entry} Renamed entry.\n */\nexport const createRenamedEntry = ({ originalEntry, savingEntry, canonicalSlugKey }) => ({\n  ...originalEntry,\n  slug: savingEntry.slug,\n  locales: Object.fromEntries(\n    Object.entries(originalEntry.locales).map(([locale, localizedEntry]) => {\n      const { slug, content } = savingEntry.locales[locale] ?? {};\n      const canonicalSlug = canonicalSlugKey ? content?.[canonicalSlugKey] : undefined;\n\n      return [\n        locale,\n        {\n          ...localizedEntry,\n          slug: slug ?? localizedEntry.slug,\n          content:\n            canonicalSlugKey && canonicalSlug !== undefined && localizedEntry.content\n              ? { ...localizedEntry.content, [canonicalSlugKey]: canonicalSlug }\n              : localizedEntry.content,\n        },\n      ];\n    }),\n  ),\n});\n\n/**\n * Work out how the values identifying the renamed entry in a Relation field change, for entries\n * holding the field in the given locale.\n * @param {object} args Arguments.\n * @param {RelationField} args.fieldConfig Relation field config.\n * @param {Entry} args.originalEntry Entry as it was before the save.\n * @param {Entry} args.renamedEntry Entry from {@link createRenamedEntry}.\n * @param {InternalLocaleCode} args.locale Locale of the entries holding the field.\n * @returns {Map<any, any>} Map of old value to new value, holding only the values that change.\n */\nexport const getReplacementMap = ({ fieldConfig, originalEntry, renamedEntry, locale }) => {\n  const getValuesArgs = { fieldConfig, locale };\n  const oldValues = getEntryRelationValues({ ...getValuesArgs, entry: originalEntry });\n  const newValues = getEntryRelationValues({ ...getValuesArgs, entry: renamedEntry });\n  /** @type {Map<any, any>} */\n  const map = new Map();\n\n  // Both lists are produced from the same content, so a mismatch means the templates couldn’t be\n  // resolved consistently. Rewriting references on a guess would corrupt them, so do nothing\n  if (oldValues.length !== newValues.length) {\n    return map;\n  }\n\n  oldValues.forEach((oldValue, index) => {\n    if (oldValue !== newValues[index]) {\n      map.set(oldValue, newValues[index]);\n    }\n  });\n\n  return map;\n};\n\n/**\n * Replace the outdated references in a copy of the given content map.\n * @param {object} args Arguments.\n * @param {FlattenedEntryContent} args.content Flattened entry content. Not modified.\n * @param {ResolvedRelationField} args.relation Relation field to update.\n * @param {Map<any, any>} args.replacements Map of old value to new value.\n * @returns {FlattenedEntryContent | undefined} Updated content, or `undefined` if the content holds\n * no outdated reference.\n */\nexport const replaceReferences = ({ content, relation, replacements }) => {\n  const { keyPath, valuePattern, multiple } = relation;\n\n  const outdatedKeyPaths = getRelationKeyPaths({ content, keyPath, valuePattern, multiple }).filter(\n    (key) => replacements.has(content[key]),\n  );\n\n  if (!outdatedKeyPaths.length) {\n    return undefined;\n  }\n\n  const updatedContent = { ...content };\n\n  outdatedKeyPaths.forEach((key) => {\n    updatedContent[key] = replacements.get(content[key]);\n  });\n\n  return updatedContent;\n};\n\n/**\n * Find the entries referencing an entry whose slug has been edited, which have to be rewritten so\n * their references keep pointing at it. See {@link buildCascadeChanges}.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection of the renamed entry.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file of the renamed entry.\n * @param {Entry} [args.originalEntry] Renamed entry as it was before the save. `undefined` for a\n * new entry, which nothing can reference yet.\n * @param {Entry} args.savingEntry Renamed entry being saved.\n * @returns {CascadeTarget[]} Referencing entries, with their references updated.\n */\nexport const collectRenameTargets = ({\n  collection,\n  collectionFile,\n  originalEntry,\n  savingEntry,\n}) => {\n  if (!originalEntry || originalEntry.slug === savingEntry.slug) {\n    return [];\n  }\n\n  const relations = getReferencingRelationFields({\n    collectionName: collection.name,\n    fileName: collectionFile?.name,\n  });\n\n  if (!relations.length) {\n    return [];\n  }\n\n  const {\n    _i18n: {\n      canonicalSlug: { key: canonicalSlugKey },\n    },\n  } = collectionFile ?? collection;\n\n  const renamedEntry = createRenamedEntry({ originalEntry, savingEntry, canonicalSlugKey });\n  /** @type {Map<string, CascadeTarget>} */\n  const targets = new Map();\n\n  relations.forEach((relation) => {\n    const { fieldConfig } = relation;\n\n    collectCascadeTargets({\n      relation,\n      excludeIds: new Set([originalEntry.id]),\n      targets,\n      /**\n       * Get the values identifying the renamed entry that change in the given locale.\n       * @param {InternalLocaleCode} locale Locale of the entries holding the field.\n       * @returns {Map<any, any>} Map of old value to new value.\n       */\n      getLocaleValues: (locale) =>\n        getReplacementMap({ fieldConfig, originalEntry, renamedEntry, locale }),\n      /**\n       * Get the function that replaces the outdated references in an entry’s content.\n       * @returns {CascadeContentUpdater<Map<any, any>>} Content updater.\n       */\n      getContentUpdater:\n        () =>\n        ({ content, values: replacements }) =>\n          replaceReferences({ content, relation, replacements }),\n    });\n  });\n\n  return [...targets.values()];\n};\n\n/**\n * Build the file changes that keep Relation field references pointing at an entry whose slug has\n * been edited, the way a database cascades an update of a referenced key to the rows referencing\n * it. Nothing is written for an entry whose references still resolve, so a save that doesn’t rename\n * anything costs a single comparison.\n *\n * References are matched on the value the Relation field stores, which is the entry slug unless a\n * `value_field` is configured. A `value_field` pointing at a content field doesn’t depend on the\n * slug, so those references are left alone; one combining the slug with other fields, such as\n * `{{locale}}/{{slug}}`, is recomputed in full.\n *\n * A referencing entry that is read-only can’t be rewritten, so the rename is refused rather than\n * leaving that entry pointing at an entry that no longer exists under that name.\n * @param {object} args Arguments.\n * @param {InternalCollection} args.collection Collection of the renamed entry.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file of the renamed entry.\n * @param {Entry} [args.originalEntry] Renamed entry as it was before the save. `undefined` for a\n * new entry, which nothing can reference yet.\n * @param {Entry} args.savingEntry Renamed entry being saved.\n * @param {IndexedDB} [args.cacheDB] Pre-opened file-cache database to reuse.\n * @returns {Promise<{ changes: FileChange[], savingEntries: Entry[] }>} Collected changes and the\n * entries to be saved.\n * @throws {Error} When a referencing entry is read-only, with a message naming the entries.\n */\nexport const buildCascadeChanges = async ({\n  collection,\n  collectionFile,\n  originalEntry,\n  savingEntry,\n  cacheDB,\n}) => {\n  /** @type {{ changes: FileChange[], savingEntries: Entry[] }} */\n  const noChanges = { changes: [], savingEntries: [] };\n  const targets = collectRenameTargets({ collection, collectionFile, originalEntry, savingEntry });\n\n  if (!targets.length) {\n    return noChanges;\n  }\n\n  // An entry can also be locked by another collection it belongs to. Only the `readonly` option\n  // counts, as explained in `isEntryReadonly()`\n  const readonlyTargets = targets.filter(\n    (target) =>\n      isConfigReadonly({ collection: target.collection, collectionFile: target.collectionFile }) ||\n      isEntryReadonly(target.entry),\n  );\n\n  if (readonlyTargets.length) {\n    const entries = readonlyTargets\n      .map((target) => getReadonlyEntryLabel(target.entry, target.collection))\n      .join(', ');\n\n    throw new Error(_('cannot_rename_referenced_entry', { values: { entries } }));\n  }\n\n  return buildTargetChanges({ targets, cacheDB });\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { getAssetFolder } from '$lib/services/assets/folders';\nimport { isInCmsFolder } from '$lib/services/assets/reserved';\nimport { allAssets } from '$lib/services/assets/state';\nimport { getErrorMessage } from '$lib/services/backends/git/shared/errors';\nimport { toFileListItem } from '$lib/services/backends/git/shared/tree';\nimport { createFileList } from '$lib/services/backends/process';\nimport { findEntryByPaths } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getCollectionFile } from '$lib/services/contents/collection/files';\nimport { buildNestedMoveChanges } from '$lib/services/contents/collection/nested/move';\nimport { getMovedFolders } from '$lib/services/contents/draft/save/asset-move';\nimport { getEntryRelativeAssets } from '$lib/services/contents/entry/assets';\nimport { buildTargetChanges } from '$lib/services/contents/entry/cascade';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport { planCascadeDelete } from '$lib/services/contents/entry/relations/cascade/delete';\nimport { collectRenameTargets } from '$lib/services/contents/entry/relations/cascade/update';\nimport { getDeletionSelection, getEditedCompanionPaths } from '$lib/services/workflow';\nimport { getEntryAssetVersion, getUsedAssetPaths } from '$lib/services/workflow/assets';\n\n/**\n * @import {\n * Asset,\n * CascadeTarget,\n * Entry,\n * InternalCollection,\n * UnpublishedEntry,\n * WorkflowBackendService,\n * WorkflowChangedFile,\n * WorkflowMergeState,\n * } from '$lib/types/private';\n */\n\n/**\n * Message of the error thrown when publishing is refused, whose `cause` is a\n * {@link PublishRefusal}.\n */\nexport const PUBLISH_REFUSED = 'publish_refused';\n\n/**\n * Why publishing an entry was refused.\n * @typedef {object} PublishRefusal\n * @property {'entry_changed' | 'other_changes'} reason `entry_changed` when the branch has moved on\n * since the entry was loaded or saved, so what would be merged isn’t what was reviewed;\n * `other_changes` when the pull request changes something the CMS doesn’t show for the entry, goes\n * somewhere other than the configured branch, or has too many files to tell.\n * @property {string[]} paths Paths of the files the CMS doesn’t account for, if any.\n */\n\n/**\n * Git file modes of a regular file, executable or not. Anything else — a symbolic link, which a\n * site build would follow to a file outside the content, or a submodule, which brings in another\n * repository — isn’t something the CMS ever commits, and can’t be shown as an entry or an asset.\n */\nconst REGULAR_FILE_MODES = ['100644', '100755'];\n/**\n * How a pull request touches a single path: a rename touches two, removing one and adding the\n * other.\n * @typedef {{ path: string, change: 'added' | 'modified' | 'removed', mode?: string }} PathChange\n */\n\n/**\n * Split the given changed files into the paths they touch.\n * @param {WorkflowChangedFile[]} files Changed files.\n * @returns {PathChange[]} Path changes.\n */\nconst getPathChanges = (files) =>\n  files.flatMap(({ path, status, previousPath, mode }) => {\n    if (status === 'renamed') {\n      return /** @type {PathChange[]} */ ([\n        ...(previousPath ? [{ path: previousPath, change: 'removed' }] : []),\n        { path, change: 'added', mode },\n      ]);\n    }\n\n    return [{ path, change: status, mode }];\n  });\n\n/**\n * Classify the given path the way the file list is built on load.\n * @param {string} path File path.\n * @returns {{ type: 'entry', collectionName: string } | { type: 'asset' } | undefined} Entry\n * file with the collection it belongs to, asset file, or `undefined` for anything else, including\n * Git config files, which the CMS never commits to a workflow branch.\n */\nconst classifyPath = (path) => {\n  const { entryFiles, assetFiles } = createFileList([toFileListItem(path)]);\n\n  if (entryFiles.length) {\n    return { type: 'entry', collectionName: entryFiles[0].folder.collectionName };\n  }\n\n  if (assetFiles.length) {\n    return { type: 'asset' };\n  }\n\n  return undefined;\n};\n\n/**\n * Get the published entry the given unpublished entry updates. Unlike `getPublishedVersion()`, an\n * entry that still sits at one of its paths is matched by those alone: the paths the pull request\n * vacates are only consulted for a renamed entry, so a pull request that edits one entry while\n * deleting another can’t pass the deletion off as the rename of the first. Moving a nested entry\n * vacates the paths of the entries below it as well, so of the entries found there, the one\n * highest up the tree is the one that moved.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {Entry | undefined} Published entry, if any.\n */\nconst getUpdatedEntry = (entry) => {\n  const current = findEntryByPaths(getEntryPaths(entry));\n\n  if (current) {\n    return current;\n  }\n\n  /**\n   * Get the depth of the given entry in its collection.\n   * @param {Entry} e Entry.\n   * @returns {number} Number of path segments in its sub path.\n   */\n  const getDepth = (e) => e.subPath.split('/').length;\n\n  return (entry.workflow.previousPaths ?? [])\n    .map((path) => findEntryByPaths([path]))\n    .filter((e) => !!e)\n    .reduce(\n      (highest, e) => (!highest || getDepth(e) < getDepth(highest) ? e : highest),\n      /** @type {Entry | undefined} */ (undefined),\n    );\n};\n\n/**\n * Get the entries whose references to the given entry the CMS rewrites along with it: those\n * referencing its published version when it’s renamed, or when it’s deleted. A selection of entries\n * is deleted with the same rewrite in each pull request, so the references to the other entries\n * deleted with it count as well: see `getDeletionSelection()`. The entries are worked out from the\n * published ones, the way the CMS did when it committed the rewrite.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry} args.entry Unpublished entry being published.\n * @param {InternalCollection} args.collection Collection the entry belongs to.\n * @param {Entry | undefined} args.updatedEntry Published version of the entry.\n * @param {boolean} args.deletion Whether the entry is being deleted.\n * @returns {CascadeTarget[]} Referencing entries, with their references rewritten.\n */\nconst getReferencingTargets = ({ entry, collection, updatedEntry, deletion }) => {\n  const { fileName } = entry.workflow;\n  const collectionFile = fileName ? getCollectionFile(collection, fileName) : undefined;\n\n  return deletion\n    ? planCascadeDelete({\n        collection,\n        collectionFile,\n        entries: getDeletionSelection(entry),\n      }).targets\n    : collectRenameTargets({\n        collection,\n        collectionFile,\n        originalEntry: updatedEntry,\n        savingEntry: entry,\n      });\n};\n\n/**\n * Get the other entries’ files the CMS writes along with the given entry: those of the entries\n * whose references to it a rename or a deletion rewrites, and, in a nested collection with\n * subfolders, those of the entries below the folder of an entry being moved, which move along with\n * it. They’re worked out from the published entries with the same functions the CMS committed them\n * with, so the pull request has to hold them exactly as written: the board doesn’t show them, and\n * checking their paths alone would let any change to such an entry through.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry} args.entry Unpublished entry being published.\n * @param {InternalCollection | undefined} args.collection Collection the entry belongs to.\n * @param {Entry | undefined} args.updatedEntry Published version of the entry.\n * @param {boolean} args.deletion Whether the entry is being deleted.\n * @param {boolean} args.moved Whether the entry is being moved.\n * @returns {Promise<Map<string, string | null>>} Text of each file written, keyed by path, or\n * `null` for a file moved away.\n */\nconst getExpectedRewrites = async ({ entry, collection, updatedEntry, deletion, moved }) => {\n  /** @type {Map<string, string | null>} */\n  const rewrites = new Map();\n\n  if (!collection) {\n    return rewrites;\n  }\n\n  const [{ changes: cascadeChanges }, { changes: moveChanges }] = await Promise.all([\n    buildTargetChanges({\n      targets: getReferencingTargets({ entry, collection, updatedEntry, deletion }),\n    }),\n    moved\n      ? buildNestedMoveChanges({ collection, originalEntry: updatedEntry, savingEntry: entry })\n      : { changes: [] },\n  ]);\n\n  // In the order the save commits them, so a file written twice is left the way the last write\n  // leaves it\n  [...cascadeChanges, ...moveChanges].forEach(({ path, previousPath, data }) => {\n    if (previousPath) {\n      rewrites.set(previousPath, null);\n    }\n\n    rewrites.set(path, /** @type {string} */ (data));\n  });\n\n  return rewrites;\n};\n\n/**\n * Get the assets the CMS moves along with the given entry, in a collection storing them with the\n * entries: everything below a folder the entry occupies by itself goes to the folder it occupies\n * now, as is.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry} args.entry Unpublished entry being published.\n * @param {InternalCollection | undefined} args.collection Collection the entry belongs to.\n * @param {Entry} args.updatedEntry Published version of the entry.\n * @returns {{ removedPaths: Set<string>, addedSHAs: Map<string, string> }} Paths the assets are\n * moved from, and the Git object ID of each asset keyed by the path it’s moved to.\n */\nconst getMovedAssets = ({ entry, collection, updatedEntry }) => {\n  const { fileName } = entry.workflow;\n  const removedPaths = new Set();\n  /** @type {Map<string, string>} */\n  const addedSHAs = new Map();\n\n  if (\n    !collection ||\n    !getAssetFolder({ collectionName: collection.name, fileName })?.entryRelative\n  ) {\n    return { removedPaths, addedSHAs };\n  }\n\n  const movedFolders = getMovedFolders({\n    collection,\n    originalEntry: updatedEntry,\n    savingEntry: entry,\n  });\n\n  // Only the versions of the assets the published entry has, like the save moves\n  const assets = /** @type {Asset[]} */ (\n    allAssets.current.map((asset) => getEntryAssetVersion(asset, updatedEntry)).filter(Boolean)\n  );\n\n  movedFolders.forEach((newFolderPath, oldFolderPath) => {\n    assets\n      .filter(({ path }) => path.startsWith(`${oldFolderPath}/`))\n      .forEach(({ path, sha }) => {\n        removedPaths.add(path);\n        addedSHAs.set(`${newFolderPath}${path.slice(oldFolderPath.length)}`, sha);\n      });\n  });\n\n  return { removedPaths, addedSHAs };\n};\n\n/**\n * Find the changes in a pull request that the CMS doesn’t account for. The board shows an entry\n * and its assets, but publishing merges the whole pull request, so anything else on the branch —\n * code, workflows, configuration, another entry, a file in a media folder — would otherwise go\n * live without having been seen. What the CMS itself commits along with an entry is allowed: the\n * entry’s own files, and those of its published version, which a rename removes; the assets the\n * entry uses, which the editor shows, except for any file in an `admin` or `cms` folder, where the\n * CMS itself is served from; in a collection storing assets with the entries, those of the\n * published entry, which are removed when it’s deleted, or moved as they are when it’s moved; the\n * files of the other entries the CMS rewrites along with it, exactly as it writes them (see\n * {@link getExpectedRewrites}); and the entries of other collections created or edited from a\n * Relation field of the entry, which the board lists on the entry’s card. A new one has to be new\n * on the configured branch as well: one that has appeared there since would be overwritten. An\n * edited one can have its published files changed or removed, a locale turned off removing one,\n * and new ones added for a locale turned on, but not have a published file added: that’s an entry\n * that has appeared on the configured branch since.\n *\n * The content of the files is that of the pull request as loaded, which is that of the commit the\n * merge is pinned to: see {@link verifyMergeState}.\n * @param {UnpublishedEntry} entry Unpublished entry being published.\n * @param {WorkflowChangedFile[]} files Files the pull request changes.\n * @returns {Promise<string[]>} Paths of the files that aren’t accounted for.\n */\nexport const findUnexpectedChanges = async (entry, files) => {\n  const { collectionName, fileName, pullRequest } = entry.workflow;\n  const collection = getCollection(collectionName);\n  const updatedEntry = getUpdatedEntry(entry);\n  const deletion = entry.workflow.status === 'pending_deletion';\n  const currentPaths = getEntryPaths(entry);\n  const updatedPaths = updatedEntry ? getEntryPaths(updatedEntry) : [];\n  const ownPaths = new Set([...currentPaths, ...updatedPaths]);\n  const branchFiles = new Map(pullRequest.files.map((file) => [file.path, file]));\n  const { companions = [] } = entry.workflow;\n\n  const companionPaths = new Set(\n    companions.flatMap(({ entry: companion, edited }) => (edited ? [] : getEntryPaths(companion))),\n  );\n\n  // The files the edited entries have on the configured branch, which the pull request can only\n  // change or remove: one it adds is an entry that has appeared there since, which would be\n  // overwritten\n  const { paths: editedPaths, publishedPaths: editedPublishedPaths } =\n    getEditedCompanionPaths(companions);\n\n  const editedCompanionPaths = new Set([...editedPaths, ...editedPublishedPaths]);\n  // Whether the pull request moves the entry: a rename, or a move to another folder of a nested\n  // collection, which takes the entries below it and the assets beside it along. Its location is\n  // compared rather than its files, as dropping a locale’s file leaves the entry where it is\n  const moved = !deletion && !!updatedEntry && updatedEntry.subPath !== entry.subPath;\n  const rewrites = await getExpectedRewrites({ entry, collection, updatedEntry, deletion, moved });\n\n  const { removedPaths: movedAssetPaths, addedSHAs: movedAssetSHAs } = moved\n    ? getMovedAssets({ entry, collection, updatedEntry: /** @type {Entry} */ (updatedEntry) })\n    : { removedPaths: new Set(), addedSHAs: new Map() };\n\n  const deletedAssetPaths = new Set(\n    deletion && updatedEntry\n      ? getEntryRelativeAssets({ entry: updatedEntry, collectionName, fileName }).map(\n          ({ path }) => path,\n        )\n      : [],\n  );\n\n  const pathChanges = getPathChanges(files).map((pathChange) => ({\n    ...pathChange,\n    kind: classifyPath(pathChange.path),\n  }));\n\n  // A removal adds nothing, so it has no asset of its own to bring in\n  const usedAssetPaths = deletion\n    ? new Set()\n    : getUsedAssetPaths(\n        entry,\n        companions,\n        pathChanges\n          .filter(({ change, kind }) => change !== 'removed' && kind?.type === 'asset')\n          .map(({ path }) => path),\n      );\n\n  /**\n   * Check whether the given change is one the CMS makes along with the entry.\n   * @param {PathChange & { kind: ReturnType<typeof classifyPath> }} pathChange Path change.\n   * @returns {boolean} Result.\n   */\n  const isExpected = ({ path, change, mode, kind }) => {\n    // A file that’s still there after the merge has to be a regular one, whatever its path\n    if (change !== 'removed' && !REGULAR_FILE_MODES.includes(/** @type {string} */ (mode))) {\n      return false;\n    }\n\n    if (ownPaths.has(path)) {\n      return true;\n    }\n\n    if (companionPaths.has(path)) {\n      return change === 'added';\n    }\n\n    if (editedCompanionPaths.has(path)) {\n      return change !== 'added' || !editedPublishedPaths.has(path);\n    }\n\n    if (!kind) {\n      return false;\n    }\n\n    // Nothing in the folder the CMS is served from is an asset of an entry, whatever the change\n    if (kind.type === 'asset') {\n      if (isInCmsFolder(path)) {\n        return false;\n      }\n\n      if (change === 'removed') {\n        return deletedAssetPaths.has(path) || movedAssetPaths.has(path);\n      }\n\n      const sha = movedAssetSHAs.get(path);\n\n      return usedAssetPaths.has(path) || (sha !== undefined && branchFiles.get(path)?.sha === sha);\n    }\n\n    if (!rewrites.has(path)) {\n      return false;\n    }\n\n    const text = rewrites.get(path);\n\n    return change === 'removed'\n      ? text === null\n      : typeof text === 'string' && branchFiles.get(path)?.text === text;\n  };\n\n  return [\n    ...new Set(pathChanges.filter((pathChange) => !isExpected(pathChange)).map(({ path }) => path)),\n  ];\n};\n\n/**\n * Create the error thrown when publishing is refused.\n * @param {PublishRefusal} refusal Refusal.\n * @returns {Error} Error.\n */\nconst createRefusal = (refusal) => new Error(PUBLISH_REFUSED, { cause: refusal });\n\n/**\n * Check that the given pull request can be merged as the entry the CMS has shown. It has to go to\n * the configured branch from a branch of the configured repository, its branch has to point at the\n * commit the entry was loaded or saved at, and every file it changes has to be accounted for by\n * {@link findUnexpectedChanges}, or be left as it is by the merge: a file the pull request has the\n * same as the configured branch already does publishes nothing. That’s the case of the reference\n * rewrite every pull request of a selection deleted at once carries, once the first of them has\n * been published.\n * @param {UnpublishedEntry} entry Unpublished entry being published.\n * @param {WorkflowMergeState} state Pull request state read right before the merge.\n * @param {WorkflowBackendService['fetchUnchangedPaths']} fetchUnchangedPaths Function to find the\n * files that are the same at the head commit as on the configured branch.\n * @throws {Error} A {@link PUBLISH_REFUSED} error when the pull request can’t be merged.\n */\nexport const verifyMergeState = async (entry, state, fetchUnchangedPaths) => {\n  const { headSHA } = entry.workflow.pullRequest;\n\n  if (!state.onConfiguredBranches || !state.complete) {\n    throw createRefusal({ reason: 'other_changes', paths: [] });\n  }\n\n  if (!headSHA || state.headSHA !== headSHA) {\n    throw createRefusal({ reason: 'entry_changed', paths: [] });\n  }\n\n  const unexpected = await findUnexpectedChanges(entry, state.files);\n\n  if (!unexpected.length) {\n    return;\n  }\n\n  const unchanged = new Set(await fetchUnchangedPaths({ headSHA, paths: unexpected }));\n  const paths = unexpected.filter((path) => !unchanged.has(path));\n\n  if (paths.length) {\n    throw createRefusal({ reason: 'other_changes', paths });\n  }\n};\n\n/**\n * Check that the given entry is the version of it the user has reviewed. The pull requests are read\n * again from time to time, so the entry in the store can carry a commit pushed since the editor or\n * the confirmation dialog was opened; merging that one would take content along that nobody has\n * seen. Nor can the files read at that commit vouch for the reviewed one, should the branch go back\n * to it: {@link verifyMergeState} compares the pull request with them. So the publish is refused,\n * and the user is asked to review the latest version first.\n * @param {UnpublishedEntry} entry Entry from the store.\n * @param {string | undefined} headSHA Head commit the user has reviewed. `undefined` if the user\n * hasn’t seen any version of the pull request, e.g. when the editor was opened before it existed,\n * which has the publish refused as well.\n * @throws {Error} A {@link PUBLISH_REFUSED} error when the entry is another version.\n */\nexport const checkReviewedHead = (entry, headSHA) => {\n  if (entry.workflow.pullRequest.headSHA !== headSHA) {\n    throw createRefusal({ reason: 'entry_changed', paths: [] });\n  }\n};\n\n/**\n * Get the message to show when an Editorial Workflow action has failed. A refused publish says what\n * the pull request holds, and a localized error from the backend what stands in the way, e.g.\n * another request open from the workflow branch, neither of which trying again would change. See\n * {@link getErrorMessage}.\n * @param {any} ex Error thrown by the action.\n * @param {string} fallback I18n key of the message for any other failure.\n * @returns {string} Localized message.\n */\nexport const getWorkflowErrorMessage = (ex, fallback) => {\n  if (ex?.message !== PUBLISH_REFUSED) {\n    return getErrorMessage(ex, fallback);\n  }\n\n  return _(\n    /** @type {PublishRefusal} */ (ex.cause).reason === 'entry_changed'\n      ? 'workflow.publish_refused_entry_changed'\n      : 'workflow.publish_refused_other_changes',\n  );\n};\n","import { unique } from '@sveltia/utils/array';\nimport { generateUUID } from '@sveltia/utils/crypto';\n\nimport { callEventHooks } from '$lib/services/api/events';\nimport { getAdditions } from '$lib/services/app/additions';\nimport { getAssetBlob } from '$lib/services/assets/info';\nimport { allAssets } from '$lib/services/assets/state';\nimport { backend } from '$lib/services/backends';\nimport { promptCommitMessage } from '$lib/services/backends/commit-prompt';\nimport { createCommitMessage } from '$lib/services/backends/git/shared/commits';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { toFileListItem } from '$lib/services/backends/git/shared/tree';\nimport { createFileList } from '$lib/services/backends/process';\nimport { toRepoChanges } from '$lib/services/backends/root-dir';\nimport { getCommitAuthor } from '$lib/services/backends/save';\nimport { allEntries, findEntryByPaths } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { getCollectionFile } from '$lib/services/contents/collection/files';\nimport { resolveCacheDB } from '$lib/services/contents/draft/save/file-changes';\nimport { getEntryKey } from '$lib/services/contents/entry/entry-key';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport {\n  buildCascadeDeleteChanges,\n  planCascadeDelete,\n  planCascadeDeleteOrThrow,\n} from '$lib/services/contents/entry/relations/cascade/delete';\nimport { forgetDeployments } from '$lib/services/deployments';\nimport { refreshProductionSHA } from '$lib/services/deployments/resolve';\nimport { user } from '$lib/services/user/account.svelte';\nimport { shareInFlight } from '$lib/services/utils/cache';\nimport {\n  allUnpublishedEntries,\n  getDeletionSelection,\n  getEditedCompanionPaths,\n  getUnpublishedEntryByBranch,\n  getUnpublishedEntryBySlug,\n  publishingBranches,\n} from '$lib/services/workflow';\nimport {\n  getUsedAssetPaths,\n  mergeWorkflowAssets,\n  publishWorkflowAssets,\n  removeWorkflowAssets,\n  removeWorkflowAssetsAt,\n} from '$lib/services/workflow/assets';\nimport { getBranchName } from '$lib/services/workflow/branch';\nimport { trackDeployingEntry } from '$lib/services/workflow/deploy';\nimport { createUnpublishedEntryProps } from '$lib/services/workflow/entries';\nimport { isForkEntry, parseForkBranchName } from '$lib/services/workflow/forks';\nimport { isEntryAlreadyPublished, openAuthoring } from '$lib/services/workflow/open-authoring';\nimport { checkReviewedHead, verifyMergeState } from '$lib/services/workflow/verify';\n\n/**\n * @import {\n * Asset,\n * CascadeTarget,\n * ChangeResults,\n * CompanionEntry,\n * Entry,\n * FileChange,\n * CommitOptions,\n * CommitResults,\n * InternalCollection,\n * InternalCollectionFile,\n * RepositoryFileInfo,\n * UnpublishedEntry,\n * WorkflowBackendService,\n * WorkflowFile,\n * WorkflowPullRequest,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Get the backend’s Editorial Workflow implementation.\n * @returns {WorkflowBackendService} Implementation.\n * @throws {Error} When the current backend doesn’t support Editorial Workflow.\n */\nconst getWorkflowService = () => {\n  const workflow = backend.current?.workflow;\n\n  if (!workflow) {\n    throw new Error('Editorial Workflow is not supported by the current backend');\n  }\n\n  return workflow;\n};\n\n/**\n * Resolve the arguments the event hooks need for the given unpublished entry.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {{ entry: UnpublishedEntry, collection: InternalCollection,\n * collectionFile: InternalCollectionFile | undefined } | undefined} Arguments, or `undefined` if\n * the collection is no longer configured, in which case no hook can be called.\n */\nconst getEventHookArgs = (entry) => {\n  const { collectionName, fileName } = entry.workflow;\n  const collection = getCollection(collectionName);\n\n  if (!collection) {\n    return undefined;\n  }\n\n  return {\n    entry,\n    collection,\n    collectionFile: fileName ? getCollectionFile(collection, fileName) : undefined,\n  };\n};\n\n/**\n * Resolve the arguments the event hooks need for the new entries that ride along in the pull\n * request of the given unpublished entry, which are published with it. An entry whose collection\n * is no longer configured has no hook to call.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {{ entry: Entry, collection: InternalCollection }[]} Arguments for each entry.\n */\nconst getCompanionHookArgs = (entry) =>\n  (entry.workflow.companions ?? []).flatMap(({ collectionName, entry: companion }) => {\n    const collection = getCollection(collectionName);\n\n    return collection ? [{ entry: companion, collection }] : [];\n  });\n\n/**\n * Find the pull request an entry’s changes belong to, and the branch they go to. The branch name is\n * derived from the slug, so looking the pull request up by branch alone would miss it after the\n * slug has been edited and start a second pull request for the same entry. The branch the entry\n * already carries is used when there is one, and kept even though it no longer matches the slug:\n * only the collection name is read back from it.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} args.slug Entry slug used for the workflow branch name.\n * @param {Entry} [args.entry] Entry being saved or deleted, as it stands before the changes.\n * @returns {{ existingEntry: UnpublishedEntry | undefined, branch: string }} Unpublished entry the\n * changes belong to, if the entry is already under review, and the branch to commit them to.\n * @throws {Error} When the entry comes from a contributor’s pull request that is no longer open.\n */\nconst resolveWorkflowBranch = ({ collectionName, slug, entry }) => {\n  const currentBranch = /** @type {UnpublishedEntry | undefined} */ (entry)?.workflow?.pullRequest\n    .branch;\n\n  const currentEntry = currentBranch ? getUnpublishedEntryByBranch(currentBranch) : undefined;\n\n  // A contributor’s pull request that has been merged or closed since the editor was opened leaves\n  // nothing to save to. Their changes must not go into a pull request of the maintainers’ own, nor\n  // straight to the configured branch, without anyone meaning to put them there\n  if (currentBranch && !currentEntry && parseForkBranchName(currentBranch)) {\n    throw createLocalizedError('The pull request is no longer open.', 'workflow.fork_entry_gone');\n  }\n\n  const existingEntry = currentEntry ?? getUnpublishedEntryBySlug({ collectionName, slug, entry });\n\n  const branch =\n    existingEntry?.workflow.pullRequest.branch ?? getBranchName({ collectionName, slug });\n\n  return { existingEntry, branch };\n};\n\n/**\n * Get the paths the entry occupied before its pull request. Once recorded, they are the published\n * ones, so an existing pull request keeps them; an empty list means nothing has been recorded yet.\n * @param {UnpublishedEntry | undefined} existingEntry Unpublished entry the changes belong to.\n * @param {string[]} paths Paths to record when there are none yet.\n * @returns {string[]} Previous paths.\n */\nconst getPreviousPaths = (existingEntry, paths) =>\n  existingEntry?.workflow.previousPaths?.length ? existingEntry.workflow.previousPaths : paths;\n\n/**\n * Bring the files of the given pull request in line with the given commit made to its branch, so\n * they describe the branch at its new head until the pull request is read again. Publishing checks\n * the files the CMS writes along with an entry against their text, and the assets it moves against\n * their Git object ID, so publishing right after a save would otherwise be refused, or compared\n * with the branch as it stood before.\n * @param {WorkflowFile[]} files Files of the pull request before the commit.\n * @param {FileChange[]} changes Changes committed.\n * @param {CommitResults} commit Commit results.\n * @returns {WorkflowFile[]} Files.\n */\nconst applyCommitToFiles = (files, changes, commit) => {\n  /** @type {Map<string, WorkflowFile>} */\n  const fileMap = new Map(files.map((file) => [file.path, file]));\n\n  /**\n   * Record the given file as deleted.\n   * @param {string} path File path.\n   */\n  const remove = (path) => {\n    fileMap.set(path, { path, sha: '', size: 0, deleted: true });\n  };\n\n  changes.forEach(({ action, path, previousPath, data }) => {\n    if (previousPath) {\n      remove(previousPath);\n    }\n\n    if (action === 'delete') {\n      remove(path);\n\n      return;\n    }\n\n    const text = typeof data === 'string' ? data : undefined;\n\n    fileMap.set(path, {\n      path,\n      sha: commit.files[path]?.sha ?? '',\n      size: typeof data === 'string' ? new Blob([data]).size : (data?.size ?? 0),\n      text,\n      deleted: false,\n    });\n  });\n\n  return [...fileMap.values()];\n};\n\n/**\n * Replace or append the given unpublished entry in the {@link allUnpublishedEntries} store, keyed\n * by the workflow branch name. An existing entry is replaced in place, so a status change doesn’t\n * make the entry jump to the end of the list on the Editorial Workflow page.\n * @param {UnpublishedEntry} entry Unpublished entry.\n */\nexport const upsertUnpublishedEntry = (entry) => {\n  const { branch } = entry.workflow.pullRequest;\n  const entries = allUnpublishedEntries.current;\n  const index = entries.findIndex((e) => e.workflow.pullRequest.branch === branch);\n\n  allUnpublishedEntries.current = index === -1 ? [...entries, entry] : entries.with(index, entry);\n};\n\n/**\n * Remove the unpublished entry associated with the given workflow branch from the store.\n * @param {string} branch Branch name.\n */\nexport const removeUnpublishedEntry = (branch) => {\n  allUnpublishedEntries.current = allUnpublishedEntries.current.filter(\n    (e) => e.workflow.pullRequest.branch !== branch,\n  );\n};\n\n/**\n * Attach the given pull request to the entry, and add the resulting unpublished entry to the\n * {@link allUnpublishedEntries} store or replace the one already there.\n * @param {Entry} entry Entry the pull request holds.\n * @param {object} args Arguments.\n * @param {WorkflowPullRequest} args.pullRequest Pull request.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string[]} args.previousPaths Paths the entry occupied before the pull request.\n * @param {CompanionEntry[]} args.companions New entries of other collections in the pull request.\n * @returns {UnpublishedEntry} Unpublished entry.\n */\nconst storeUnpublishedEntry = (\n  entry,\n  { pullRequest, collectionName, fileName, previousPaths, companions },\n) => {\n  /** @type {UnpublishedEntry} */\n  const unpublishedEntry = {\n    ...entry,\n    workflow: createUnpublishedEntryProps({\n      pullRequest,\n      collectionName,\n      fileName,\n      previousPaths,\n      companions,\n    }),\n  };\n\n  upsertUnpublishedEntry(unpublishedEntry);\n\n  return unpublishedEntry;\n};\n\n/**\n * Remove the entry of the given merged or closed pull request from the\n * {@link allUnpublishedEntries} store, settle the assets committed to its branch, and forget the\n * deployments of its head commit.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {(branch: string) => void} settleAssets Function to publish or remove the assets committed\n * to the branch: {@link publishWorkflowAssets} or {@link removeWorkflowAssets}.\n */\nconst clearUnpublishedEntry = (pullRequest, settleAssets) => {\n  removeUnpublishedEntry(pullRequest.branch);\n  settleAssets(pullRequest.branch);\n  forgetDeployments([pullRequest.headSHA]);\n};\n\n/**\n * Remove the assets at the given paths from the asset list, as the merge of a pull request has\n * removed the files from the configured branch: the assets stored with an entry that the pull\n * request deletes, or moves to another folder along with the entry. An asset that another pull\n * request has committed to the same path stays, but no longer has a published version to restore\n * if that pull request is discarded.\n * @param {Set<string>} paths File paths.\n */\nconst removePublishedAssets = (paths) => {\n  if (!paths.size) {\n    return;\n  }\n\n  allAssets.current = allAssets.current.flatMap((asset) => {\n    if (!paths.has(asset.path)) {\n      return [asset];\n    }\n\n    if (!asset.workflow) {\n      return [];\n    }\n\n    return [{ ...asset, workflow: { branch: asset.workflow.branch } }];\n  });\n};\n\n/**\n * Move the given entry, whose pull request has been merged, from the unpublished entry list to the\n * regular entry list, along with its assets.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {object} [options] Options.\n * @param {boolean} [options.deletion] Whether the merge was a removal, which takes the entry off\n * the configured branch rather than putting a new version on it.\n * @param {Map<string, Entry>} [options.cascadedEntries] Entries the removal rewrote, keyed by ID,\n * to replace in the store.\n * @param {Set<string>} [options.removedPaths] Paths of the files the merge removed from the\n * configured branch, deleted or moved elsewhere, whose assets are taken off the asset list.\n */\nconst settlePublishedEntry = (\n  entry,\n  { deletion = false, cascadedEntries = new Map(), removedPaths = new Set() } = {},\n) => {\n  const { workflow, ...publishedEntry } = entry;\n  // The new entries that rode along in the pull request are published with the entry\n  const companionEntries = deletion ? [] : (workflow.companions ?? []).map(({ entry: e }) => e);\n\n  // Include the pre-rename paths, so the entry that the pull request renamed is replaced rather\n  // than left behind as a duplicate\n  const paths = new Set(\n    [publishedEntry, ...companionEntries].flatMap((e) =>\n      getEntryPaths(e, { includePrevious: true }),\n    ),\n  );\n\n  const remaining = allEntries.current\n    .filter((e) => !Object.values(e.locales).some(({ path }) => paths.has(path)))\n    .map((e) => cascadedEntries.get(e.id) ?? e);\n\n  allEntries.current = deletion ? remaining : [...remaining, publishedEntry, ...companionEntries];\n\n  clearUnpublishedEntry(workflow.pullRequest, publishWorkflowAssets);\n  removePublishedAssets(removedPaths);\n};\n\n/**\n * Add the given new entries to the ones an earlier save has committed to the pull request, which\n * are still on the branch. An entry committed again replaces its earlier version.\n * @param {CompanionEntry[]} existing Entries already in the pull request.\n * @param {CompanionEntry[]} added Entries committed now.\n * @returns {CompanionEntry[]} Entries.\n */\nconst mergeCompanions = (existing, added) => {\n  const addedPaths = new Set(added.flatMap(({ entry }) => getEntryPaths(entry)));\n\n  return [\n    ...existing.filter(({ entry }) => !getEntryPaths(entry).some((path) => addedPaths.has(path))),\n    ...added,\n  ];\n};\n\n/**\n * Get the published version of the asset at the given path: the asset itself, or the one an asset\n * committed to a workflow branch shadows.\n * @param {string} path Asset path.\n * @returns {Asset | undefined} Asset, or `undefined` if the configured branch has none there.\n */\nconst getPublishedAsset = (path) => {\n  const asset = allAssets.current.find((a) => a.path === path);\n\n  return asset?.workflow ? asset.workflow.replacedAsset : asset;\n};\n\n/**\n * Get the change that puts the given file of a pull request back the way it is on the configured\n * branch: a file it has added is removed, one it has changed or removed gets the content the\n * configured branch has.\n * @param {WorkflowFile} file File to put back.\n * @param {string} slug Slug of the entry, for the commit message.\n * @param {ReturnType<typeof resolveCacheDB>} cacheDB File cache database.\n * @returns {Promise<FileChange>} Change.\n * @throws {Error} When the content of the file on the configured branch isn’t known.\n */\nconst getFileRevertChange = async ({ path, deleted }, slug, cacheDB) => {\n  const cache = /** @type {RepositoryFileInfo | undefined} */ (await cacheDB?.get(path));\n  const publishedAsset = getPublishedAsset(path);\n\n  // A file removed by the pull request is on the configured branch, by definition\n  if (!deleted && !cache && !publishedAsset && !findEntryByPaths([path])) {\n    return { action: 'delete', slug, path };\n  }\n\n  const action = deleted ? 'create' : 'update';\n\n  if (cache?.text !== undefined) {\n    return { action, slug, path, data: cache.text };\n  }\n\n  if (publishedAsset) {\n    return /** @type {FileChange} */ ({\n      action,\n      slug,\n      path,\n      data: await getAssetBlob(publishedAsset),\n    });\n  }\n\n  throw new Error(`The published version of ${path} could not be found.`);\n};\n\n/**\n * Get the changes that take off the workflow branch the assets an earlier save committed for the\n * given entry that it no longer uses, e.g. an image replaced with another upload while the entry\n * is still a draft. Nothing references them anymore, so they would be published for nothing, and\n * the publish check would refuse the pull request because of them. A file the pull request has\n * added is removed, and one it has changed gets the content the configured branch has. Only the\n * assets the entry or its companions used before the save are touched: a file committed to the\n * branch outside the CMS is left for the publish check to refuse.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry} args.existingEntry Unpublished entry as it stood before the save.\n * @param {Entry} args.savingEntry Entry being saved.\n * @param {CompanionEntry[]} args.companions Entries of other collections in the pull request\n * after the save.\n * @param {FileChange[]} args.changes Changes being committed.\n * @param {string} args.slug Slug of the entry, for the commit message.\n * @returns {Promise<FileChange[]>} Changes to commit for the assets taken off the branch.\n * @see https://github.com/sveltia/sveltia-cms/issues/1162\n */\nconst getReplacedAssetChanges = async ({\n  existingEntry,\n  savingEntry,\n  companions,\n  changes,\n  slug,\n}) => {\n  const changedPaths = new Set(\n    changes.flatMap(({ path, previousPath }) => (previousPath ? [path, previousPath] : [path])),\n  );\n\n  const files = existingEntry.workflow.pullRequest.files.filter(\n    ({ path, deleted }) => !deleted && !changedPaths.has(path),\n  );\n\n  const { assetFiles } = createFileList(files.map(({ path }) => toFileListItem(path)));\n\n  const usedPaths = getUsedAssetPaths(\n    existingEntry,\n    existingEntry.workflow.companions ?? [],\n    assetFiles.map(({ path }) => path),\n  );\n\n  const stillUsedPaths = getUsedAssetPaths(savingEntry, companions, [...usedPaths]);\n  const cacheDB = resolveCacheDB();\n\n  // Putting a file back is a bonus on top of the save, so one whose published version can’t be\n  // read is left on the branch for the publish check to report, rather than failing the save\n  const results = await Promise.all(\n    files\n      .filter(({ path }) => usedPaths.has(path) && !stillUsedPaths.has(path))\n      .map(async (file) => {\n        try {\n          return await getFileRevertChange(file, slug, cacheDB);\n        } catch (ex) {\n          // eslint-disable-next-line no-console\n          console.error(ex);\n\n          return undefined;\n        }\n      }),\n  );\n\n  return /** @type {FileChange[]} */ (results.filter(Boolean));\n};\n\n/**\n * Save the given entry changes as a pull request instead of committing them directly to the\n * configured branch. The pull request and the workflow branch are created on the first save, and\n * updated on subsequent saves.\n * @param {object} args Arguments.\n * @param {FileChange[]} args.changes Changes to be committed.\n * @param {Entry} args.savingEntry Entry being saved.\n * @param {Asset[]} [args.savingAssets] Assets to be saved along with the entry.\n * @param {CommitOptions} args.options Commit options.\n * @param {string} args.collectionName Collection name.\n * @param {string} [args.fileName] Collection file name. File/singleton collection only.\n * @param {string} args.slug Entry slug used for the workflow branch name.\n * @param {Entry} [args.originalEntry] Entry being edited, before the changes.\n * @param {CompanionEntry[]} [args.companions] New entries of other collections created from a\n * Relation field of the entry, whose changes are among the ones to be committed.\n * @returns {Promise<ChangeResults>} Change results.\n */\nexport const saveWorkflowChanges = async ({\n  changes,\n  savingEntry,\n  savingAssets = [],\n  options,\n  collectionName,\n  fileName,\n  slug,\n  originalEntry,\n  companions = [],\n}) => {\n  const workflow = getWorkflowService();\n  // The message the user enters goes into the title of a new pull request as well as the commit\n  const commitOptions = await promptCommitMessage(changes, options);\n\n  const { existingEntry, branch } = resolveWorkflowBranch({\n    collectionName,\n    slug,\n    entry: originalEntry,\n  });\n\n  const allCompanions = mergeCompanions(existingEntry?.workflow.companions ?? [], companions);\n\n  // The assets the draft no longer uses go along with the changes, but not into the commit message\n  // or the title, which describe what the user has done\n  const replacedAssetChanges = existingEntry\n    ? await getReplacedAssetChanges({\n        existingEntry,\n        savingEntry,\n        companions: allCompanions,\n        changes,\n        slug,\n      })\n    : [];\n\n  const allChanges = [...changes, ...replacedAssetChanges];\n\n  const { commit, pullRequest } = await workflow.savePullRequest({\n    changes: allChanges,\n    options: commitOptions,\n    branch,\n    // The commit message the backend writes names the paths relative to the repository root, so\n    // the title does as well\n    title: createCommitMessage(toRepoChanges(changes), commitOptions),\n    status: 'draft',\n    pullRequest: existingEntry?.workflow.pullRequest,\n  });\n\n  const commitAuthor = getCommitAuthor();\n  const { date: commitDate } = commit;\n\n  // Remember where the entry lived before the pull request, so the entry list can still match it\n  // with its published counterpart after the slug — and therefore the file path — has changed. Once\n  // recorded, the paths are the published ones, so keep them on later saves. An empty list means\n  // nothing has been recorded yet, which is not the same as having no previous location: a pull\n  // request that hasn’t renamed anything still needs the paths captured when the slug is edited.\n  const previousPaths = getPreviousPaths(\n    existingEntry,\n    originalEntry ? getEntryPaths(originalEntry) : [],\n  );\n\n  // The assets are committed to the workflow branch only, but add them to the regular asset list\n  // right away, so the image attached to the entry can be previewed before it’s published\n  const savedAssets = savingAssets.map((asset) => ({\n    ...asset,\n    sha: commit.files[asset.path]?.sha ?? asset.sha,\n    commitAuthor,\n    commitDate,\n    workflow: { branch },\n  }));\n\n  const unpublishedEntry = storeUnpublishedEntry(\n    {\n      ...savingEntry,\n      // Reuse the existing ID so the editor doesn’t lose track of the entry after a save\n      id: existingEntry?.id ?? savingEntry.id,\n      commitAuthor,\n      commitDate,\n    },\n    {\n      // The backend returns the existing pull request as is when there already is one, so the head\n      // commit it carries is the one from before this save. Point it at the new commit, so the\n      // deploy preview lookup doesn’t keep reporting the previous build until the next full load\n      pullRequest: {\n        ...pullRequest,\n        headSHA: commit.sha,\n        files: applyCommitToFiles(pullRequest.files, allChanges, commit),\n      },\n      collectionName,\n      fileName,\n      previousPaths,\n      companions: allCompanions,\n    },\n  );\n\n  removeWorkflowAssetsAt(branch, new Set(replacedAssetChanges.map(({ path }) => path)));\n  mergeWorkflowAssets(savedAssets);\n\n  return {\n    commit: { ...commit, author: commitAuthor },\n    savedEntries: [unpublishedEntry],\n    savedAssets,\n  };\n};\n\n/**\n * Approve the given pull request on behalf of the signed-in user, or withdraw their approval.\n * Moving an entry to the ready stage is the CMS’s way of approving it, so the approval is recorded\n * on the Git service too, where a branch protection rule may require one before the pull request\n * can be merged; moving it back withdraws the approval, so it can’t be merged there on the strength\n * of it. The Git services don’t let anyone approve their own pull request, and an Open Authoring\n * contributor’s approval doesn’t count, so neither is attempted. Nor is a pull request a\n * contributor opened from their fork approved: the CMS has only shown the entry, not whatever else\n * their branch holds, so the approval is left to the review on the Git service. The review is a\n * bonus on top of the status change, which has already been made, so a failure is only logged: the\n * user may not be allowed to review, or to dismiss a review on GitHub.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @param {boolean} approved Whether to approve the pull request rather than withdraw the approval.\n */\nconst reviewPullRequest = async (pullRequest, approved) => {\n  const { number, author } = pullRequest;\n\n  if (\n    openAuthoring.current ||\n    pullRequest.fork ||\n    number === undefined ||\n    (!!author?.login && author.login === user.account?.login)\n  ) {\n    return;\n  }\n\n  const workflow = getWorkflowService();\n\n  try {\n    await (approved ? workflow.approve(pullRequest) : workflow.withdrawApproval(pullRequest));\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.warn(\n      `Failed to ${approved ? 'approve' : 'withdraw the approval of'} the pull request.`,\n      ex,\n    );\n  }\n};\n\n/**\n * Change the Editorial Workflow status of the given unpublished entry, which updates the label and\n * the draft state on the corresponding pull request. Moving the entry from the drafting or review\n * stage to the ready stage also approves the pull request, and moving it back withdraws the\n * approval; see {@link reviewPullRequest}.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @param {WorkflowStatus} status New status.\n * @returns {Promise<UnpublishedEntry>} Updated entry.\n */\nexport const updateWorkflowStatus = async (entry, status) => {\n  const workflow = getWorkflowService();\n  const { pullRequest } = entry.workflow;\n\n  // Update the store before the request so the UI reflects the new status right away, rather than\n  // after the round trip to the backend. The change is rolled back if the request fails.\n  upsertUnpublishedEntry({\n    ...entry,\n    workflow: { ...entry.workflow, status, pullRequest: { ...pullRequest, status } },\n  });\n\n  /** @type {WorkflowPullRequest} */\n  let newPullRequest;\n\n  try {\n    newPullRequest = await workflow.updateStatus(pullRequest, status);\n  } catch (/** @type {any} */ ex) {\n    // A maintainer has merged the entry’s pull request since the board was loaded, and the branch\n    // held nothing more, so the entry is published: it leaves the board for the entry list, the\n    // way it does once published from the CMS. Anything else puts the entry back as it was\n    if (isEntryAlreadyPublished(ex)) {\n      settlePublishedEntry(entry);\n    } else {\n      upsertUnpublishedEntry(entry);\n    }\n\n    throw ex;\n  }\n\n  const updatedEntry = {\n    ...entry,\n    workflow: { ...entry.workflow, pullRequest: newPullRequest, status },\n  };\n\n  upsertUnpublishedEntry(updatedEntry);\n\n  const { status: prevStatus } = entry.workflow;\n  const editable = ['draft', 'pending_review'];\n\n  // The approval is awaited, so a publish right after doesn’t race it to the merge\n  if (status === 'pending_publish' && editable.includes(prevStatus)) {\n    await reviewPullRequest(newPullRequest, true);\n  } else if (prevStatus === 'pending_publish' && editable.includes(status)) {\n    await reviewPullRequest(newPullRequest, false);\n  }\n\n  return updatedEntry;\n};\n\n/**\n * Publishes in flight, keyed by workflow branch. See {@link publishWorkflowEntry}.\n * @type {Map<string, Promise<void>>}\n */\nconst pendingPublishes = new Map();\n\n/**\n * Merge the pull request of the given unpublished entry, and move the entry from the unpublished\n * entry list to the regular entry list once it has.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {Promise<void>}\n * @throws {Error} When the pull request comes from a contributor’s fork.\n */\nconst mergeWorkflowEntry = async (entry) => {\n  const workflow = getWorkflowService();\n  const { status } = entry.workflow;\n  let { pullRequest } = entry.workflow;\n  const deletion = status === 'pending_deletion';\n  const hookArgs = getEventHookArgs(entry);\n  // A removal has taken any new entry off the branch along with it; see `deleteWorkflowEntry()`\n  const companionHookArgs = deletion ? [] : getCompanionHookArgs(entry);\n\n  // Merging a removal is what takes the entry off the configured branch, so that’s when the\n  // unpublish hooks fire. Nothing is being published, so the publish hooks don’t apply\n  const [preType, postType] = deletion\n    ? /** @type {const} */ (['preUnpublish', 'postUnpublish'])\n    : /** @type {const} */ (['prePublish', 'postPublish']);\n\n  // A contributor’s pull request is merged on the Git service, where the maintainer can review the\n  // whole of it, including any changes the CMS doesn’t show; see `getPublishAction()`\n  if (pullRequest.fork) {\n    throw new Error('A pull request from a fork cannot be published from the CMS.');\n  }\n\n  // The board shows the entry, but the merge takes the whole pull request as its branch stands. So\n  // the pull request is read afresh and checked against what has been shown before anything else\n  // happens; the merge is then pinned to the commit that was checked\n  const mergeState = await workflow.fetchMergeState(pullRequest);\n\n  await verifyMergeState(entry, mergeState, workflow.fetchUnchangedPaths);\n\n  if (hookArgs) {\n    await callEventHooks({ ...hookArgs, type: preType });\n  }\n\n  await Promise.all(companionHookArgs.map((args) => callEventHooks({ ...args, type: preType })));\n\n  // An entry in the drafting stage is kept as a draft pull request, which the Git service refuses\n  // to merge. It’s published from there with Preview Workflow or direct publishing, so it’s marked\n  // ready first, which also takes the draft marker off the pull request. This is left until the\n  // hooks have let the publish go ahead, so an entry isn’t marked ready for nothing\n  if (status === 'draft') {\n    ({ pullRequest } = (await updateWorkflowStatus(entry, 'pending_publish')).workflow);\n  }\n\n  await workflow.publish(pullRequest);\n\n  // A removal also rewrote the entries referencing the deleted one and the rest of the selection it\n  // was deleted with, so the store is brought up to date with those as well, or they would show the\n  // stale references until the next reload. The references are worked out again rather than\n  // remembered from when the pull request was opened, because the entries may have been reloaded\n  // since; this has to happen while the deleted entry is still in the store, as it’s what the\n  // references are matched against\n  /** @type {Map<string, Entry>} */\n  const cascadedEntries = new Map(\n    deletion && hookArgs\n      ? planCascadeDelete({\n          collection: hookArgs.collection,\n          collectionFile: hookArgs.collectionFile,\n          entries: getDeletionSelection(entry),\n        }).targets.map(({ entry: target }) => [target.id, target])\n      : [],\n  );\n\n  // The files the pull request removes or moves elsewhere are gone from the configured branch now,\n  // which includes the assets stored with an entry that has been deleted or renamed. They’re still\n  // on the asset list, as the pull request only added its own files there\n  const removedPaths = new Set(\n    mergeState.files.flatMap(({ status: fileStatus, path, previousPath }) =>\n      fileStatus === 'removed'\n        ? [path]\n        : fileStatus === 'renamed' && previousPath\n          ? [previousPath]\n          : [],\n    ),\n  );\n\n  settlePublishedEntry(entry, { deletion, cascadedEntries, removedPaths });\n  // The merge put a new commit on the configured branch, so the production build to watch is a\n  // different one now. The entry is listed as on its way until that build is done, so the head has\n  // to be known before it’s recorded\n  await refreshProductionSHA();\n  trackDeployingEntry(entry);\n\n  if (hookArgs) {\n    await callEventHooks({ ...hookArgs, type: postType });\n  }\n\n  await Promise.all(companionHookArgs.map((args) => callEventHooks({ ...args, type: postType })));\n};\n\n/**\n * Publish the given unpublished entry by merging the corresponding pull request. The entry is then\n * moved from the unpublished entry list to the regular entry list. The merge can take minutes when\n * the Git service waits for a pipeline, long enough for the user to leave and come back to the\n * entry, so publishing it again meanwhile joins the merge in progress rather than starting another:\n * the hooks would otherwise fire twice, and so would everything after the merge.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {Promise<void>}\n */\nexport const publishWorkflowEntry = async (entry) => {\n  const { branch } = entry.workflow.pullRequest;\n\n  return shareInFlight(pendingPublishes, branch, () => {\n    const promise = mergeWorkflowEntry(entry).finally(() => {\n      publishingBranches.current = publishingBranches.current.filter((b) => b !== branch);\n    });\n\n    publishingBranches.current = [...publishingBranches.current, branch];\n\n    return promise;\n  });\n};\n\n/**\n * Publish the given entry as the user has reviewed it. The entry comes from the store, which a\n * reload may have brought a commit pushed since the editor or the confirmation dialog was opened;\n * that commit isn’t published unseen. See {@link checkReviewedHead}.\n * @param {UnpublishedEntry} entry Entry from the store.\n * @param {Entry | undefined} reviewed Version of the entry the user has reviewed, e.g. the one the\n * confirmation dialog was opened for, or the original entry of the draft being edited. An entry\n * without a pull request, or `undefined`, has the publish refused.\n * @returns {Promise<void>}\n */\nexport const publishReviewedEntry = async (entry, reviewed) => {\n  checkReviewedHead(\n    entry,\n    /** @type {UnpublishedEntry | undefined} */ (reviewed)?.workflow?.pullRequest.headSHA,\n  );\n\n  return publishWorkflowEntry(entry);\n};\n\n/**\n * Discard the given unpublished entry by closing the corresponding pull request without merging it.\n * @param {UnpublishedEntry} entry Unpublished entry.\n * @returns {Promise<void>}\n */\nexport const discardWorkflowEntry = async (entry) => {\n  const workflow = getWorkflowService();\n  const { pullRequest } = entry.workflow;\n\n  await workflow.discard(pullRequest);\n  clearUnpublishedEntry(pullRequest, removeWorkflowAssets);\n\n  const { collectionName } = entry.workflow;\n  const key = getEntryKey(collectionName, entry.subPath);\n  // Paths of the files the pull request renamed, if it renames a published entry\n  const previousPaths = new Set(pullRequest.files.map(({ previousPath }) => previousPath));\n\n  const publishedEntry = getEntriesByCollection(collectionName).find(\n    ({ subPath, locales }) =>\n      subPath === entry.subPath ||\n      Object.values(locales).some(({ path }) => previousPaths.has(path)),\n  );\n\n  if (!publishedEntry) {\n    // A draft that was never published takes its comments along\n    getAdditions()?.deleteEntryComments(key);\n  } else if (publishedEntry.subPath !== entry.subPath) {\n    // The comments moved with the rename when the draft was saved; give them back\n    getAdditions()?.moveEntryConversation(key, getEntryKey(collectionName, publishedEntry.subPath));\n  }\n};\n\n/**\n * Get the changes that stand for the deletion of an entry in the commit message prompt and the\n * pull request title: a single change naming the entry’s first file.\n * @param {Entry} entry Entry to be deleted.\n * @returns {FileChange[]} Changes.\n */\nconst getDeletionTitleChanges = (entry) => [\n  { action: 'delete', slug: entry.slug, path: getEntryPaths(entry)[0] },\n];\n\n/**\n * Get the changes that put the existing entries a pull request has changed along with its entry\n * back the way they are on the configured branch, which is where the pull request will land, so\n * publishing it leaves them alone. Only the files the pull request changes are written: those it\n * has added are removed, and the others get the text the configured branch has.\n * @param {UnpublishedEntry} unpublishedEntry Unpublished entry whose pull request is reused.\n * @param {string} slug Slug of the entry, for the commit message.\n * @returns {Promise<FileChange[]>} Changes.\n * @throws {Error} When the text of a file on the configured branch isn’t known.\n */\nconst getEditedCompanionRevertChanges = async (unpublishedEntry, slug) => {\n  const { companions = [], pullRequest } = unpublishedEntry.workflow;\n  const changedPaths = new Set(pullRequest.files.map(({ path }) => path));\n  const { paths, publishedPaths } = getEditedCompanionPaths(companions);\n  const cacheDB = resolveCacheDB();\n\n  return Promise.all(\n    unique([...paths, ...publishedPaths])\n      .filter((path) => changedPaths.has(path))\n      .map(async (path) => {\n        if (!publishedPaths.has(path)) {\n          return /** @type {FileChange} */ ({ action: 'delete', slug, path });\n        }\n\n        const text = /** @type {RepositoryFileInfo | undefined} */ (await cacheDB?.get(path))?.text;\n\n        if (text === undefined) {\n          throw new Error(`The published version of ${path} could not be found.`);\n        }\n\n        // A file the pull request deletes, e.g. that of a locale turned off, is created again\n        return /** @type {FileChange} */ ({\n          action: paths.includes(path) ? 'update' : 'create',\n          slug,\n          path,\n          data: text,\n        });\n      }),\n  );\n};\n\n/**\n * Get the changes that put back the rest of the files a reused pull request changes, other than\n * those the deletion of its entry handles itself, so publishing the removal leaves them as they are\n * on the configured branch: an asset uploaded for the entry, or the entries a rename rewrote or\n * moved along with it. See {@link getFileRevertChange}. Only the entry and asset files the CMS\n * commits are touched: a change made outside the CMS is left for the publish check to refuse, as\n * nothing tells whether the file is new or what it held.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry} args.unpublishedEntry Unpublished entry whose pull request is reused.\n * @param {string} args.slug Slug of the entry, for the commit message.\n * @param {Set<string>} args.handledPaths Paths the deletion takes care of otherwise.\n * @returns {Promise<FileChange[]>} Changes.\n * @throws {Error} When the content of a file on the configured branch isn’t known.\n */\nconst getOtherFileRevertChanges = async ({ unpublishedEntry, slug, handledPaths }) => {\n  const files = unpublishedEntry.workflow.pullRequest.files.filter(\n    ({ path }) => !handledPaths.has(path),\n  );\n\n  if (!files.length) {\n    return [];\n  }\n\n  const { entryFiles, assetFiles } = createFileList(files.map(({ path }) => toFileListItem(path)));\n  const knownPaths = new Set([...entryFiles, ...assetFiles].map(({ path }) => path));\n  const cacheDB = resolveCacheDB();\n\n  return Promise.all(\n    files\n      .filter(({ path }) => knownPaths.has(path))\n      .map((file) => getFileRevertChange(file, slug, cacheDB)),\n  );\n};\n\n/**\n * Delete the given published entry through Editorial Workflow: instead of committing the removal\n * straight to the configured branch, open a pull request that removes it, so taking an entry off\n * the site is reviewed and released like any other change. The entry stays on the site until that\n * pull request is published. The entries referencing it through Relation fields are rewritten in\n * the same pull request, so that no reference is left dangling once the removal lands.\n * @param {Entry} entry Entry to be deleted.\n * @param {InternalCollection} collection Collection the entry belongs to.\n * @param {InternalCollectionFile} [collectionFile] Collection file, if the entry is one.\n * @param {Asset[]} [assets] Assets stored alongside the entry, which are removed with it. Only\n * applies to a collection with an entry-relative asset folder.\n * @param {object} [options] Options.\n * @param {CascadeTarget[]} [options.targets] Referencing entries to rewrite, already worked out\n * by {@link deleteWorkflowEntries} for a whole selection. Worked out for the entry alone if\n * omitted.\n * @param {string} [options.userMessage] Commit message the user has entered, already asked for by\n * {@link deleteWorkflowEntries} for a whole selection. Asked for if omitted and configured.\n * @param {string} [options.deletionGroup] ID of the selection the entry is deleted with, recorded\n * in the pull request so publishing can tell which references it removes. Omitted for an entry\n * deleted on its own.\n * @returns {Promise<UnpublishedEntry>} Entry with the pull request attached.\n * @throws {Error} When the user has cancelled the commit when asked for a commit message.\n * @throws {Error} When removing the references would leave another entry invalid. The dialogs\n * report this before the deletion is confirmed, so this is only a safeguard.\n * @throws {Error} When the entry comes from a contributor’s pull request.\n * @see https://github.com/sveltia/sveltia-cms/issues/770\n */\nexport const deleteWorkflowEntry = async (\n  entry,\n  collection,\n  collectionFile,\n  assets = [],\n  { targets = undefined, userMessage = undefined, deletionGroup = undefined } = {},\n) => {\n  // Taking a published entry off the site is a maintainer’s call. A contributor can discard their\n  // own draft, which leaves the published version alone, but not propose a removal\n  if (openAuthoring.current) {\n    throw createLocalizedError(\n      'Cannot delete a published entry as an Open Authoring contributor',\n      'open_authoring.direct_commit_unsupported',\n    );\n  }\n\n  targets ??= planCascadeDeleteOrThrow(\n    { collection, collectionFile, entries: [entry] },\n    'Cannot delete an entry that other entries require',\n  );\n\n  const workflow = getWorkflowService();\n  const collectionName = collection.name;\n  const { slug } = entry;\n  const { existingEntry, branch } = resolveWorkflowBranch({ collectionName, slug, entry });\n\n  // A contributor’s pull request is theirs: a maintainer can close it, but not turn it into the\n  // removal of the published entry. The editor doesn’t offer it, so this is only a safeguard\n  if (isForkEntry(existingEntry)) {\n    throw new Error('Cannot delete an entry through a pull request from a fork');\n  }\n\n  // Remove the files as they stand on the branch. A pull request that renamed the entry has already\n  // staged the deletion of the old paths there, so removing the new ones leaves nothing behind once\n  // the merge lands\n  const paths = getEntryPaths(entry);\n  const titleChanges = getDeletionTitleChanges(entry);\n\n  const options = await promptCommitMessage(titleChanges, {\n    commitType: 'delete',\n    collection,\n    userMessage,\n  });\n\n  // An entry-relative asset lives with the entry, so it goes in the same pull request rather than\n  // being left behind once the removal lands\n  const assetPaths = unique(assets.map(({ path }) => path));\n\n  // A reused pull request may hold new entries created from a Relation field of the entry, which\n  // would otherwise be published along with the removal. They have never been published, so taking\n  // them off the branch is all it takes. The existing entries edited along with it are put back\n  const companionPaths = (existingEntry?.workflow.companions ?? []).flatMap(\n    ({ entry: e, edited }) => (edited ? [] : getEntryPaths(e)),\n  );\n\n  const companionRevertChanges = existingEntry\n    ? await getEditedCompanionRevertChanges(existingEntry, slug)\n    : [];\n\n  // The references are removed from the published entries as they stand on the configured branch,\n  // which is where the pull request will land\n  const { changes: cascadeChanges } = await buildCascadeDeleteChanges({ targets });\n  const previousPaths = getPreviousPaths(existingEntry, paths);\n\n  // Anything else the reused pull request holds would be published along with the removal, which\n  // the publish check refuses, so it’s put back as well. The paths the entry has on the configured\n  // branch, which a rename has already removed, stay removed\n  const otherRevertChanges = existingEntry\n    ? await getOtherFileRevertChanges({\n        unpublishedEntry: existingEntry,\n        slug,\n        handledPaths: new Set([\n          ...paths,\n          ...previousPaths,\n          ...assetPaths,\n          ...companionPaths,\n          ...[...companionRevertChanges, ...cascadeChanges].map(({ path }) => path),\n        ]),\n      })\n    : [];\n\n  // Reuse any open pull request rather than discarding it first: closing it up front would throw\n  // the pending changes away with no way back if opening the replacement then failed\n  /** @type {FileChange[]} */\n  const changes = [\n    ...[...paths, ...assetPaths, ...companionPaths].map(\n      (path) => /** @type {FileChange} */ ({ action: 'delete', slug, path }),\n    ),\n    // A file the references are removed from is written from the configured branch anyway\n    ...companionRevertChanges.filter(({ path }) => !cascadeChanges.some((c) => c.path === path)),\n    ...otherRevertChanges,\n    ...cascadeChanges,\n  ];\n\n  const { commit, pullRequest } = await workflow.savePullRequest({\n    changes,\n    options,\n    branch,\n    title: createCommitMessage(toRepoChanges(titleChanges), options),\n    // The removal is complete as committed, so it skips the review stages entirely. Opening it at\n    // this status avoids the churn of creating a draft and relabelling it a moment later\n    status: 'pending_deletion',\n    pullRequest: existingEntry?.workflow.pullRequest,\n    deletionGroup,\n  });\n\n  // A reused pull request carries the files and the head commit from before this one, which\n  // publishing compares with the branch\n  const files = applyCommitToFiles(pullRequest.files, changes, commit);\n\n  // Every asset the reused pull request committed is now off its branch, or back as published\n  if (existingEntry) {\n    removeWorkflowAssets(branch);\n  }\n\n  /**\n   * Store the entry with the given pull request, pointed at the new commit.\n   * @param {WorkflowPullRequest} pr Pull request.\n   * @returns {UnpublishedEntry} Unpublished entry.\n   */\n  const store = (pr) =>\n    storeUnpublishedEntry(entry, {\n      pullRequest: { ...pr, headSHA: commit.sha, files },\n      collectionName,\n      fileName: collectionFile?.name,\n      // Where the entry lives on the configured branch, which a rename has already moved away from\n      previousPaths,\n      companions: [],\n    });\n\n  if (pullRequest.status === 'pending_deletion') {\n    return store(pullRequest);\n  }\n\n  // A reused pull request keeps the status it already had, so it still needs the switch. The\n  // commit has landed by now, so the entry is stored first with the status it has: if the switch\n  // then fails, the entry still follows the branch rather than its previous head commit, which\n  // would hold up publishing and saving until the next reload\n  store(pullRequest);\n\n  return store(await workflow.updateStatus(pullRequest, 'pending_deletion'));\n};\n\n/**\n * Discard the given unpublished entries. Used when multiple entries are deleted at once from the\n * entry list. Each entry takes a couple of requests — closing the pull request and deleting the\n * branch — so the batch is throttled like any other, rather than firing them all at once.\n * @param {UnpublishedEntry[]} entries Unpublished entries.\n * @returns {Promise<void>}\n */\nexport const discardWorkflowEntries = async (entries) => {\n  await runConcurrently(entries, discardWorkflowEntry);\n};\n\n/**\n * Delete the given published entries through Editorial Workflow. A branch is named after the entry\n * it holds, so a selection can’t share one pull request: each entry gets its own, and the requests\n * are throttled like any other batch.\n *\n * The entries referencing the selection are another matter. An entry referencing two of the\n * selected entries can’t be rewritten one reference at a time, one pull request each: the second\n * pull request to be published would conflict with the first, as both change the same lines of the\n * same file, and there’s no way to resolve that from the CMS. So the references to the whole\n * selection are worked out once, and every pull request carries the same rewrite; identical changes\n * merge cleanly whichever is published first. The trade-off is that the selection is taken as a\n * whole: if one of the pull requests is then cancelled, the others still remove the references to\n * that entry when they’re published. Each pull request records the selection it belongs to, so\n * publishing it works out the same rewrite, rather than taking in the entries of the collection\n * deleted one at a time, whose pull requests rewrite only the references to their own entry.\n * @param {{ entry: Entry, collection: InternalCollection,\n * collectionFile?: InternalCollectionFile, assets?: Asset[] }[]} items Entries to be deleted, with\n * the context each one needs.\n * @throws {Error} When removing the references would leave another entry invalid. The dialog\n * reports this before the deletion is confirmed, so this is only a safeguard.\n */\nexport const deleteWorkflowEntries = async (items) => {\n  /**\n   * Get the key of the group the given item belongs to: its collection and collection file.\n   * @param {(typeof items)[number]} item Item.\n   * @returns {string} Group key.\n   */\n  const getKey = ({ collection, collectionFile }) =>\n    `${collection.name}\\0${collectionFile?.name ?? ''}`;\n\n  // A selection comes from one entry list, so it’s normally a single group\n  const groups = Map.groupBy(items, getKey);\n  /** @type {Map<string, { targets: CascadeTarget[], deletionGroup?: string }>} */\n  const planMap = new Map();\n\n  groups.forEach((group, key) => {\n    const [{ collection, collectionFile }] = group;\n\n    planMap.set(key, {\n      targets: planCascadeDeleteOrThrow(\n        { collection, collectionFile, entries: group.map(({ entry }) => entry) },\n        'Cannot delete entries that other entries require',\n      ),\n      // An entry deleted alone in its group is planned on its own, which needs no record\n      deletionGroup: group.length > 1 ? generateUUID() : undefined,\n    });\n  });\n\n  // Ask for a commit message once for the whole selection rather than for each pull request. Each\n  // pull request is titled after its own entry, so the first one stands for the rest\n  const [{ entry: firstEntry, collection: firstCollection }] = items;\n\n  const { userMessage } = await promptCommitMessage(getDeletionTitleChanges(firstEntry), {\n    commitType: 'delete',\n    collection: firstCollection,\n  });\n\n  await runConcurrently(items, async (item) => {\n    const { entry, collection, collectionFile, assets } = item;\n\n    await deleteWorkflowEntry(entry, collection, collectionFile, assets, {\n      ...planMap.get(getKey(item)),\n      // A string, even an empty one, tells the user has been asked already\n      userMessage,\n    });\n  });\n};\n","import { deleteEntries } from '$lib/services/contents/collection/data/delete';\nimport { cancelBackup, deleteBackup, getBackupSlug } from '$lib/services/contents/draft/backup';\nimport { deleteWorkflowEntries, discardWorkflowEntries } from '$lib/services/workflow/save';\n\n/**\n * @import {\n * Asset,\n * Entry,\n * InternalCollection,\n * InternalCollectionFile,\n * UnpublishedEntry,\n * UpdateToastState,\n * } from '$lib/types/private';\n */\n\n/**\n * Delete the draft backups of the given entries, which are gone or about to be. A backup is stored\n * under the collection name and the entry slug, so one left behind would be offered to restore to\n * a new entry created with the same slug. A backup scheduled for a change made just before the\n * deletion is dropped as well, so it doesn’t take the place of the one deleted here. The entries\n * are deleted already, so a backup that can’t be deleted doesn’t fail the deletion.\n * @param {object} args Arguments.\n * @param {Entry[]} args.entries Deleted or discarded entries.\n * @param {InternalCollection} [args.collection] Collection the entries belong to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file, if the entry is one.\n */\nconst deleteBackups = async ({ entries, collection, collectionFile }) => {\n  cancelBackup();\n\n  if (!collection) {\n    return;\n  }\n\n  await Promise.all(\n    entries.map(async (entry) => {\n      try {\n        await deleteBackup(\n          collection.name,\n          getBackupSlug({ collection, fileName: collectionFile?.name, originalEntry: entry }),\n        );\n      } catch (ex) {\n        // eslint-disable-next-line no-console\n        console.error(ex);\n      }\n    }),\n  );\n};\n\n/**\n * Take the given entries off the site, each in the way that suits it. An unpublished entry that has\n * never been published is discarded by closing its pull request, because there’s nothing on the\n * configured branch to remove. A published entry is deleted through Editorial Workflow when it’s in\n * use, so the removal is reviewed and released like any other change, or committed straight to the\n * configured branch otherwise.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry[]} [args.drafts] Unpublished entries that have never been published.\n * @param {{ entry: Entry, assets: Asset[] }[]} [args.items] Published entries, each with the assets\n * stored alongside it, which are removed with it.\n * @param {InternalCollection} [args.collection] Collection the published entries belong to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file, if the entry is one.\n * @param {boolean} args.useWorkflow Whether the published entries go through Editorial Workflow.\n * @returns {Promise<Partial<UpdateToastState> | undefined>} State of the toast that reports the\n * outcome, or `undefined` if there’s nothing to report, or the deletion has reported it itself.\n * @throws {Error} When a discard or a deletion fails.\n */\nexport const deleteOrDiscardEntries = async ({\n  drafts = [],\n  items = [],\n  collection = undefined,\n  collectionFile = undefined,\n  useWorkflow,\n}) => {\n  /**\n   * Discard the drafts. It’s done after the published entries are deleted, which may ask the user\n   * for a commit message: cancelling it then leaves the whole selection as it was.\n   */\n  const discardDrafts = async () => {\n    if (drafts.length) {\n      await discardWorkflowEntries(drafts);\n      await deleteBackups({ entries: drafts, collection, collectionFile });\n    }\n  };\n\n  if (items.length) {\n    const entries = items.map(({ entry }) => entry);\n\n    if (useWorkflow && collection) {\n      // Committing the removals straight to the configured branch would bypass review and be\n      // rejected outright when the branch is protected\n      // @see https://github.com/decaporg/decap-cms/issues/6610\n      await deleteWorkflowEntries(\n        items.map(({ entry, assets }) => ({ entry, collection, collectionFile, assets })),\n      );\n      // The deletion asked for drops the unsaved changes as well\n      await deleteBackups({ entries, collection, collectionFile });\n      await discardDrafts();\n\n      // The entries stay on the site until the deletion is published\n      return { deleted: true, deletionPending: true, count: items.length };\n    }\n\n    // `deleteEntries()` reports the outcome itself\n    await deleteEntries(\n      entries,\n      items.flatMap(({ assets }) => assets),\n    );\n    await deleteBackups({ entries, collection, collectionFile });\n    await discardDrafts();\n\n    return undefined;\n  }\n\n  await discardDrafts();\n\n  // Nothing was published, so the entries really are gone\n  return drafts.length ? { deleted: true, count: drafts.length } : undefined;\n};\n","import { _ } from '@sveltia/i18n';\n\n/**\n * Strings of a confirmation dialog, and of the control that opens it.\n * @typedef {object} WorkflowDialogStrings\n * @property {string} label Short label of the control and the dialog’s OK button, e.g. `Discard`.\n * @property {string} title Dialog title, which is also the control’s accessible name because the\n * short label alone doesn’t say what it acts on.\n * @property {string} message Confirmation message.\n */\n\n/**\n * Get the strings of the dialog that throws an unpublished entry away. What that means depends on\n * the entry: a pending removal is cancelled, the changes to an entry that is already published are\n * discarded, and an entry that only exists in the pull request is deleted outright.\n * @param {object} args Arguments.\n * @param {boolean} args.pendingDeletion Whether the entry is a pending removal.\n * @param {boolean} args.publishedVersionExists Whether the entry has a published version.\n * @returns {WorkflowDialogStrings} Strings.\n */\nexport const getDiscardDialogStrings = ({ pendingDeletion, publishedVersionExists }) => {\n  if (pendingDeletion) {\n    return {\n      label: _('workflow.cancel_deletion'),\n      title: _('workflow.cancel_deletion'),\n      message: _('workflow.confirm_cancelling_deletion'),\n    };\n  }\n\n  if (publishedVersionExists) {\n    return {\n      label: _('discard'),\n      title: _('workflow.discard_changes'),\n      message: _('workflow.confirm_discarding_entry_changes'),\n    };\n  }\n\n  return {\n    label: _('delete'),\n    title: _('delete_entries', { values: { count: 1 } }),\n    message: _('workflow.confirm_deleting_unpublished_entry'),\n  };\n};\n\n/**\n * Get the strings of the dialog that publishes an unpublished entry. Publishing a pending removal\n * is what deletes the entry, so it’s presented as a deletion.\n * @param {object} args Arguments.\n * @param {boolean} args.deletion Whether the entry is a pending removal.\n * @returns {WorkflowDialogStrings} Strings.\n */\nexport const getPublishDialogStrings = ({ deletion }) =>\n  deletion\n    ? {\n        label: _('delete'),\n        title: _('delete_entries', { values: { count: 1 } }),\n        message: _('workflow.confirm_completing_deletion'),\n      }\n    : {\n        label: _('publish'),\n        title: _('workflow.publish_entry'),\n        message: _('workflow.confirm_publishing_entry_after_build'),\n      };\n","<!--\n  @component\n  Delete the entry being edited, or discard its unpublished changes, once the user has confirmed it\n  in a dialog. The progress and any error are reported with a toast. Use `confirmDelete()` and\n  `confirmDiscard()` to open the dialogs.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, ConfirmationDialog, Toast } from '@sveltia/ui';\n\n  import DeleteEntryDialog from '$lib/components/contents/details/delete-entry-dialog.svelte';\n  import { runCommit } from '$lib/services/backends/commit-prompt';\n  import { getErrorMessage } from '$lib/services/backends/git/shared/errors';\n  import {\n    contentUpdatesToast,\n    UPDATE_TOAST_DEFAULT_STATE,\n  } from '$lib/services/contents/collection/data';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { deleteOrDiscardEntries } from '$lib/services/workflow/delete';\n  import { getDiscardDialogStrings } from '$lib/services/workflow/dialogs';\n  import { discardWorkflowEntry } from '$lib/services/workflow/save';\n\n  /**\n   * @import {\n   * Asset,\n   * Entry,\n   * InternalCollection,\n   * InternalCollectionFile,\n   * UnpublishedEntry,\n   * UpdateToastState,\n   * } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [deleting] Whether a deletion is in flight.\n   * @property {InternalCollection | undefined} collection Collection of the entry.\n   * @property {InternalCollectionFile | undefined} collectionFile Collection file, if the entry is\n   * one.\n   * @property {Entry | undefined} originalEntry The entry as it was opened.\n   * @property {UnpublishedEntry | undefined} unpublishedEntry The entry’s pull request with\n   * Editorial Workflow, if any.\n   * @property {Asset[]} associatedAssets Assets stored alongside the entry, deleted along with it.\n   * @property {boolean} discardsDraft Whether the deletion throws away an unpublished entry that\n   * has never been published.\n   * @property {boolean} useWorkflow Whether the removal goes through Editorial Workflow.\n   * @property {boolean} pendingDeletion Whether the entry is awaiting deletion, in which case the\n   * discard calls off the deletion.\n   * @property {() => void} onDone Function called once the entry has been deleted or discarded, to\n   * close the editor. It’s not called if the user has left the entry, or opened another one, in the\n   * meantime.\n   * @property {() => void} onClose Function called once a dialog is closed, e.g. to move the focus\n   * back to the menu button.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let {\n    deleting = $bindable(false),\n    collection,\n    collectionFile,\n    originalEntry,\n    unpublishedEntry,\n    associatedAssets,\n    discardsDraft,\n    useWorkflow,\n    pendingDeletion,\n    onDone,\n    onClose,\n  } = $props();\n\n  let showDeleteDialog = $state(false);\n  let showDiscardDialog = $state(false);\n  let showDeleteErrorToast = $state(false);\n  let deleteErrorMessage = $state('');\n  /** I18n key of the message shown while a deletion is in flight. */\n  let progressMessage = $state('');\n\n  // The discard dialog is only opened for an entry with a published version. Its text is kept as it\n  // is when the discarded entry goes away, so it doesn’t change while the dialog is closing\n  const discardDialogStrings = $derived(\n    getDiscardDialogStrings({ pendingDeletion, publishedVersionExists: true }),\n  );\n\n  /**\n   * Ask the user to confirm the deletion of the entry.\n   */\n  export const confirmDelete = () => {\n    showDeleteDialog = true;\n  };\n\n  /**\n   * Ask the user to confirm discarding the unpublished changes.\n   */\n  export const confirmDiscard = () => {\n    showDiscardDialog = true;\n  };\n\n  /**\n   * Run the given deletion action, then go back to the entry list. The action reports what happened\n   * by returning a toast state, which is shown by the content library page: the editor is closed by\n   * then, so a toast rendered here would go with it. Errors are reported with a toast and leave the\n   * editor open.\n   * @param {() => Promise<Partial<UpdateToastState> | undefined>} action Action to be performed.\n   * @param {string} progressKey I18n key of the message shown while the action is in flight.\n   */\n  const runDeletion = async (action, progressKey) => {\n    const draft = entryDraft.current;\n\n    progressMessage = progressKey;\n    deleting = true;\n\n    const { ok, cancelled, result, error } = await runCommit(action);\n\n    deleting = false;\n\n    if (!ok) {\n      // The user has cancelled the commit at the commit message prompt, which isn’t a failure\n      if (!cancelled) {\n        deleteErrorMessage = getErrorMessage(error, 'deleting_entry_failed');\n        showDeleteErrorToast = true;\n      }\n\n      return;\n    }\n\n    if (result) {\n      contentUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, count: 1, ...result };\n    }\n\n    // The Back button stays available while the request is in flight; if the user has moved on,\n    // going back would take them away from where they are now\n    if (entryDraft.current === draft) {\n      onDone();\n    }\n  };\n\n  /**\n   * Delete the entry. With Editorial Workflow the removal goes through a pull request like any\n   * other change, so the entry stays on the site until that is published. An unpublished entry that\n   * has never been published is discarded instead, because there’s nothing on the configured branch\n   * to remove.\n   */\n  const deleteEntry = async () => {\n    await runDeletion(\n      () =>\n        deleteOrDiscardEntries({\n          drafts: discardsDraft ? [/** @type {UnpublishedEntry} */ (unpublishedEntry)] : [],\n          // The option is only offered for an existing entry\n          items: discardsDraft\n            ? []\n            : [{ entry: /** @type {Entry} */ (originalEntry), assets: associatedAssets }],\n          collection,\n          collectionFile,\n          useWorkflow,\n        }),\n      'workflow.deleting_entry',\n    );\n  };\n\n  /**\n   * Discard the unpublished changes by closing the pull request, leaving the published version of\n   * the entry untouched.\n   */\n  const discardChanges = async () => {\n    await runDeletion(\n      async () => {\n        /* v8 ignore next 3 -- the option is only offered for an unpublished entry */\n        if (unpublishedEntry) {\n          await discardWorkflowEntry(unpublishedEntry);\n        }\n\n        return pendingDeletion ? { deletionCancelled: true } : { discarded: true };\n      },\n      pendingDeletion ? 'workflow.cancelling_deletion' : 'workflow.discarding_changes',\n    );\n  };\n</script>\n\n<DeleteEntryDialog\n  bind:open={showDeleteDialog}\n  {discardsDraft}\n  {useWorkflow}\n  withAssets={!!associatedAssets.length}\n  onOk={async () => {\n    await deleteEntry();\n  }}\n  {onClose}\n/>\n\n<ConfirmationDialog\n  bind:open={showDiscardDialog}\n  title={discardDialogStrings.title}\n  okLabel={discardDialogStrings.label}\n  onOk={async () => {\n    await discardChanges();\n  }}\n  {onClose}\n>\n  {discardDialogStrings.message}\n</ConfirmationDialog>\n\n<!-- Shown while the request is in flight. The result is reported by the content library page,\nbecause this toast goes away with the editor once the deletion has completed -->\n{#if progressMessage}\n  <Toast id={progressMessage} show={deleting} duration={0}>\n    <Alert status=\"info\">{_(progressMessage)}</Alert>\n  </Toast>\n{/if}\n\n<Toast bind:show={showDeleteErrorToast}>\n  <Alert status=\"error\">{deleteErrorMessage}</Alert>\n</Toast>\n","<!--\n  @component\n  Tell the user that someone else has changed or removed the entry since it was opened, and offer\n  to save over the change when that’s possible. An entry stored in a file with the other entries\n  can’t be saved over the change, so the dialog only tells what happened.\n-->\n<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { AlertDialog, ConfirmationDialog } from '@sveltia/ui';\n\n  import { describeConflict } from '$lib/services/contents/draft/save/conflict';\n\n  /**\n   * @import { EntryConflict } from '$lib/services/contents/draft/save/conflict';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} open Whether the dialog is open.\n   * @property {EntryConflict | undefined} conflict Someone else’s change to the entry.\n   * @property {() => Promise<void>} onOverwrite Function called once the user agrees to save over\n   * the change.\n   * @property {() => void} onClose Function called once the dialog is closed, e.g. to move the\n   * focus back to the menu button.\n   */\n\n  /** @type {Props} */\n  let { open = $bindable(false), conflict, onOverwrite, onClose } = $props();\n</script>\n\n{#snippet conflictDescription()}\n  {#if conflict}\n    {@const { description, warning } = describeConflict(conflict, appLocale.current)}\n    {description}\n    {warning}\n  {/if}\n{/snippet}\n\n{#if conflict?.canOverwrite === false}\n  <AlertDialog bind:open title={_('save_conflict.title')} {onClose}>\n    {@render conflictDescription()}\n  </AlertDialog>\n{:else}\n  <ConfirmationDialog\n    bind:open\n    title={_('save_conflict.title')}\n    okLabel={_('save_conflict.save_anyway')}\n    onOk={onOverwrite}\n    {onClose}\n  >\n    {@render conflictDescription()}\n  </ConfirmationDialog>\n{/if}\n","<!--\n  @component\n  Small filled pill showing a status label, such as the Editorial Workflow status or the deploy\n  preview state of an unpublished entry.\n-->\n<script>\n  /**\n   * @import { StatusPillTone } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {StatusPillTone} tone Color tone of the pill.\n   * @property {string} label Text to be shown.\n   * @property {string} [title] Further detail shown as a tooltip on hover.\n   * @property {string} [class] Additional class names for the element.\n   */\n\n  /** @type {Props} */\n  let { tone, label, title, class: className = '' } = $props();\n</script>\n\n<span role=\"none\" class={['status-pill', tone, className]} {title}>\n  {label}\n</span>\n\n<style>\n  /*\n   * Filled pill following the same background/foreground/border recipe as the Alert and Infobar\n   * components, so the colors adapt to both the light and dark themes. The border does most of the\n   * work in dark mode, where the alert background is nearly the same as the row background.\n   */\n\n  .status-pill {\n    display: inline-block;\n    border-width: 1px;\n    border-style: solid;\n    border-radius: 12px;\n    padding: 1px 6px;\n    font-size: var(--sui-font-size-x-small);\n    line-height: var(--sui-line-height-compact);\n    white-space: nowrap;\n\n    &.info {\n      border-color: var(--sui-info-border-color);\n      background-color: var(--sui-info-background-color);\n      color: var(--sui-info-foreground-color);\n    }\n\n    &.warning {\n      border-color: var(--sui-warning-border-color);\n      background-color: var(--sui-warning-background-color);\n      color: var(--sui-warning-foreground-color);\n    }\n\n    &.success {\n      border-color: var(--sui-success-border-color);\n      background-color: var(--sui-success-background-color);\n      color: var(--sui-success-foreground-color);\n    }\n\n    &.error {\n      border-color: var(--sui-error-border-color);\n      background-color: var(--sui-error-background-color);\n      color: var(--sui-error-foreground-color);\n    }\n  }\n</style>\n","<!--\n  @component\n  Pill showing the Editorial Workflow status of an unpublished entry, used in the entry and file\n  lists.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import StatusPill from '$lib/components/common/status-pill.svelte';\n  import { WORKFLOW_STATUS_LABELS } from '$lib/services/workflow/constants';\n\n  /**\n   * @import { StatusPillTone, WorkflowStatus } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {WorkflowStatus} status Workflow status to be shown.\n   */\n\n  /** @type {Props} */\n  let { status } = $props();\n\n  /**\n   * Pill color tone for each status.\n   * @type {Record<WorkflowStatus, StatusPillTone>}\n   */\n  const TONES = {\n    draft: 'info',\n    pending_review: 'warning',\n    pending_publish: 'success',\n    pending_deletion: 'error',\n  };\n</script>\n\n<StatusPill\n  tone={TONES[status]}\n  label={_(WORKFLOW_STATUS_LABELS[status])}\n  class=\"status-badge {status}\"\n/>\n","import { goBack } from '$lib/services/app/navigation';\nimport {\n  contentUpdatesToast,\n  UPDATE_TOAST_DEFAULT_STATE,\n} from '$lib/services/contents/collection/data';\nimport { isEntryAlreadyPublished } from '$lib/services/workflow/open-authoring';\nimport { getWorkflowErrorMessage } from '$lib/services/workflow/verify';\n\n/**\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n * @import { UnpublishedEntry } from '$lib/types/private';\n */\n\n/**\n * Close the editor on an unpublished entry that has just left the board, because it has been\n * published, and go back to its collection. The editor can have moved on by then: a merge can take\n * minutes when the Git service waits for a pipeline, and the draft state is shared by the whole\n * page, so the draft open now may be another entry’s, with unsaved changes. Only the given entry’s\n * draft is closed.\n * @param {object} args Arguments.\n * @param {EntryDraftState} args.entryDraft Draft state of the editor.\n * @param {string} args.branch Workflow branch of the entry, read before it left the board.\n * @param {string} args.collectionName Collection of the entry.\n */\nexport const closeWorkflowEntryEditor = ({ entryDraft, branch, collectionName }) => {\n  const originalEntry = /** @type {UnpublishedEntry | undefined} */ (\n    entryDraft.current?.originalEntry\n  );\n\n  if (originalEntry?.workflow?.pullRequest.branch === branch) {\n    entryDraft.current = null;\n    goBack(`/collections/${collectionName}`);\n  }\n};\n\n/**\n * Handle an error from changing the status of the entry open in the editor, if it says that the\n * entry has been published since: a maintainer merged an Open Authoring contributor’s request, and\n * nothing has been committed to its branch since. The entry has left the board, so the editor is\n * closed, and the global toast says why: the editor’s own controls go away with the entry. Unlike\n * publishing, a status change can be made with unsaved changes in the editor, which would be lost,\n * so the editor then stays open: saving them starts a new draft of the published entry.\n * @param {any} ex Error thrown by the status change.\n * @param {object} args Arguments.\n * @param {EntryDraftState} args.entryDraft Draft state of the editor.\n * @param {string} args.branch Workflow branch of the entry, read before the status change.\n * @param {string} args.collectionName Collection of the entry.\n * @returns {boolean} Whether the error was handled. Any other error is left to the caller.\n */\nexport const handleEntryAlreadyPublished = (ex, { entryDraft, branch, collectionName }) => {\n  if (!isEntryAlreadyPublished(ex)) {\n    return false;\n  }\n\n  if (!entryDraft.modified) {\n    closeWorkflowEntryEditor({ entryDraft, branch, collectionName });\n  }\n\n  contentUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, alreadyPublished: true };\n\n  return true;\n};\n\n/**\n * Run an Editorial Workflow action on the entry open in the editor, such as a status change or\n * publishing, once the draft has passed the validation the action calls for: an entry can be saved\n * as a draft with its required fields left empty, so it has to be checked before it moves towards\n * being published. An error is logged and turned into a message for the caller to show.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry} args.entry Unpublished entry being edited.\n * @param {EntryDraftState} args.entryDraft Draft state of the editor.\n * @param {boolean} args.valid Whether the draft has passed the validation. The action isn’t run\n * otherwise.\n * @param {() => Promise<unknown>} args.action Action to run. It’s called synchronously, so it can\n * flag the action as under way before anything else gets in.\n * @param {string} args.failure I18n key of the message for a failure that has no more specific\n * message. See {@link getWorkflowErrorMessage}.\n * @param {boolean} [args.closeOnSuccess] Whether to close the editor once the action has succeeded,\n * as the entry has left the board, e.g. when it has been published.\n * @param {boolean} [args.handleAlreadyPublished] Whether to close the editor if the action fails\n * because the entry has been published since it was opened. See\n * {@link handleEntryAlreadyPublished}.\n * @returns {Promise<{ blocked: boolean, errorMessage: string | undefined }>} Outcome: whether the\n * action has been refused for the validation, and the localized message if it has failed.\n */\nexport const runWorkflowEditorAction = async ({\n  entry,\n  entryDraft,\n  valid,\n  action,\n  failure,\n  closeOnSuccess = false,\n  handleAlreadyPublished = false,\n}) => {\n  if (!valid) {\n    return { blocked: true, errorMessage: undefined };\n  }\n\n  // Read these up front: an entry that has been published leaves `unpublishedEntries`, and the\n  // caller’s `entry` is typically derived from that store\n  const { collectionName, pullRequest } = entry.workflow;\n  const args = { entryDraft, branch: pullRequest.branch, collectionName };\n\n  try {\n    await action();\n\n    if (closeOnSuccess) {\n      closeWorkflowEntryEditor(args);\n    }\n  } catch (/** @type {any} */ ex) {\n    // An entry published since it was opened closes the editor instead\n    if (!handleAlreadyPublished || !handleEntryAlreadyPublished(ex, args)) {\n      // eslint-disable-next-line no-console\n      console.error(ex);\n\n      return { blocked: false, errorMessage: getWorkflowErrorMessage(ex, failure) };\n    }\n  }\n\n  return { blocked: false, errorMessage: undefined };\n};\n","import { resolveCollectionAndFile } from '$lib/services/contents/collection/files';\nimport { buildDraft } from '$lib/services/contents/draft/create';\nimport { validateDraft } from '$lib/services/contents/draft/validate';\nimport { revealInvalidFields } from '$lib/services/contents/draft/validate/reveal';\n\n/**\n * @import { EntryDraft, UnpublishedEntry, WorkflowStatus } from '$lib/types/private';\n */\n\n/**\n * Check that the given unpublished entry is complete before it moves out of the drafting stage.\n * Required fields aren’t enforced while an entry is a draft, so an incomplete entry has to be\n * caught here instead: handing it over for review, marking it ready and publishing it are all steps\n * towards putting it on the site.\n *\n * The entry may be open in the editor, in which case the values being edited are what’s checked,\n * and the invalid fields are expanded to show the errors just as a failed save does. Otherwise —\n * the Editorial Workflow board — a throwaway draft is built from the entry’s saved content, leaving\n * the editor state alone.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry} args.entry Entry to check.\n * @param {EntryDraft | null} [args.draft] Draft open in the editor, if any.\n * @returns {boolean} Whether the entry can move on. An entry whose collection is no longer\n * configured can’t be checked against anything, so it’s left alone.\n * @see https://github.com/decaporg/decap-cms/issues/464\n */\nexport const validateWorkflowEntry = ({ entry, draft }) => {\n  if (draft?.originalEntry?.id === entry.id) {\n    return revealInvalidFields({ draft });\n  }\n\n  const { collectionName, fileName } = entry.workflow;\n  const resolved = resolveCollectionAndFile(collectionName, fileName);\n\n  if (!resolved) {\n    return true;\n  }\n\n  const { collection, collectionFile } = resolved;\n\n  return validateDraft({ draft: buildDraft({ collection, collectionFile, originalEntry: entry }) })\n    .valid;\n};\n\n/**\n * Check whether the given unpublished entry can be moved to the given status. Only moving it\n * towards publication requires it to be complete; it can always go back to the drafting stage.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry} args.entry Entry to move.\n * @param {WorkflowStatus} args.status New status.\n * @param {EntryDraft | null} [args.draft] Draft open in the editor, if any.\n * @returns {boolean} Whether the entry can be moved.\n */\nexport const canMoveToStatus = ({ entry, status, draft }) =>\n  status === 'draft' || validateWorkflowEntry({ entry, draft });\n\n/**\n * Check whether the given unpublished entry can be published. A pull request labelled ready\n * elsewhere — by another CMS, or by hand — may never have been checked, so the entry has to be\n * complete. A removal has no content to check; publishing it is what carries the deletion out.\n * @param {object} args Arguments.\n * @param {UnpublishedEntry} args.entry Entry to publish.\n * @param {EntryDraft | null} [args.draft] Draft open in the editor, if any.\n * @returns {boolean} Whether the entry can be published.\n */\nexport const canPublish = ({ entry, draft }) =>\n  entry.workflow.status === 'pending_deletion' || validateWorkflowEntry({ entry, draft });\n","<!--\n  @component\n  Editor toolbar menu button to change the Editorial Workflow status of the entry being edited. With\n  Preview Workflow, there’s only the drafting stage to be in, so the status is shown as a badge.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Menu, MenuButton, MenuItemRadio, Toast } from '@sveltia/ui';\n\n  import StatusBadge from '$lib/components/workflow/status-badge.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { env } from '$lib/services/user/env.svelte';\n  import { WORKFLOW_STATUS_LABELS } from '$lib/services/workflow/constants';\n  import { runWorkflowEditorAction } from '$lib/services/workflow/editor';\n  import { updateWorkflowStatus } from '$lib/services/workflow/save';\n  import { getStageOfEntry, getStagesOfEntry } from '$lib/services/workflow/stages';\n  import { canMoveToStatus } from '$lib/services/workflow/validate';\n\n  /**\n   * @import { UnpublishedEntry, WorkflowStatus } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {UnpublishedEntry} entry Unpublished entry being edited.\n   * @property {boolean} [disabled] Whether to disable the control.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { entry, disabled = false } = $props();\n\n  let updating = $state(false);\n  let showErrorToast = $state(false);\n  let errorMessage = $state('');\n  let showValidationToast = $state(false);\n  /**\n   * Incremented when a status change fails or is blocked, to render the menu items again: a menu\n   * item checks itself once clicked, and would otherwise stay checked, so the stage couldn’t be\n   * picked again to retry.\n   */\n  let itemsVersion = $state(0);\n\n  // The stages the collection is configured with, and the one the entry is in. A pull request whose\n  // label isn’t among the stages is shown in the nearest earlier one\n  const stages = $derived(getStagesOfEntry(entry));\n  const status = $derived(getStageOfEntry(entry));\n  const statusName = $derived(_(WORKFLOW_STATUS_LABELS[status]));\n  // The status name alone doesn’t say what it refers to, so spell it out where there’s room. A\n  // small screen only gets the name, but the accessible name keeps the prefix for context\n  const qualifiedStatusName = $derived(\n    _('workflow.entry_status_value', { values: { status: statusName } }),\n  );\n\n  /**\n   * Change the entry’s status, which updates the label and draft state on the pull request.\n   * @param {WorkflowStatus} newStatus New status.\n   */\n  const changeStatus = async (newStatus) => {\n    if (newStatus === status || updating) {\n      return;\n    }\n\n    const { blocked, errorMessage: message } = await runWorkflowEditorAction({\n      entry,\n      entryDraft,\n      valid: canMoveToStatus({ entry, status: newStatus, draft: entryDraft.current }),\n      /**\n       * Change the status, flagging the change as under way.\n       * @returns {Promise<UnpublishedEntry>} Updated entry.\n       */\n      action: () => {\n        updating = true;\n\n        return updateWorkflowStatus(entry, newStatus);\n      },\n      failure: 'workflow.status_change_failed',\n      handleAlreadyPublished: true,\n    });\n\n    updating = false;\n\n    if (blocked) {\n      showValidationToast = true;\n    } else if (message) {\n      errorMessage = message;\n      showErrorToast = true;\n    } else {\n      return;\n    }\n\n    itemsVersion += 1;\n  };\n</script>\n\n{#if stages.length === 1}\n  <StatusBadge {status} />\n{:else}\n  <MenuButton\n    variant=\"ghost\"\n    label={updating\n      ? _('workflow.changing_status')\n      : env.isLargeScreen\n        ? qualifiedStatusName\n        : statusName}\n    disabled={disabled || updating}\n    popupPosition=\"bottom-right\"\n    aria-label={updating ? _('workflow.changing_status') : qualifiedStatusName}\n  >\n    {#snippet popup()}\n      <Menu ariaLabel={_('workflow.change_entry_status')}>\n        {#key itemsVersion}\n          {#each stages as _status (_status)}\n            <MenuItemRadio\n              label={_(WORKFLOW_STATUS_LABELS[_status])}\n              checked={_status === status}\n              onChange={() => {\n                changeStatus(_status);\n              }}\n            />\n          {/each}\n        {/key}\n      </Menu>\n    {/snippet}\n  </MenuButton>\n{/if}\n\n<Toast bind:show={showErrorToast}>\n  <Alert status=\"error\">{errorMessage}</Alert>\n</Toast>\n\n<Toast bind:show={showValidationToast}>\n  <Alert status=\"error\">{_('workflow.status_change_blocked')}</Alert>\n</Toast>\n","<!--\n  @component\n  Control that opens the pull request of an unpublished entry on the Git service, shown in place of\n  the Publish control for a pull request a contributor has opened from their fork. Such a pull\n  request is reviewed and merged there, where everything on the contributor’s branch can be seen.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon } from '@sveltia/ui';\n\n  import { backend } from '$lib/services/backends';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @import { UnpublishedEntry } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {UnpublishedEntry} entry Unpublished entry.\n   * @property {'small' | 'medium'} [size] Button size.\n   * @property {boolean} [iconic] Whether to show the icon only, with the label as the accessible\n   * name.\n   * @property {boolean} [disabled] Whether to disable the control.\n   */\n\n  /** @type {Props} */\n  let { entry, size = 'medium', iconic = false, disabled = false } = $props();\n\n  const label = $derived(\n    _('workflow.review_on_x', { values: { service: backend.current?.repository?.label ?? '' } }),\n  );\n</script>\n\n<Button\n  variant={iconic ? 'ghost' : 'primary'}\n  {size}\n  {iconic}\n  {disabled}\n  label={iconic ? undefined : label}\n  aria-label={iconic ? label : undefined}\n  onclick={() => {\n    openNewTab(entry.workflow.pullRequest.url);\n  }}\n>\n  {#snippet endIcon()}\n    <!-- The card’s preview link already has the new tab icon, so the iconic control has its own -->\n    <Icon name={iconic ? 'rate_review' : 'open_in_new'} />\n  {/snippet}\n</Button>\n","<!--\n  @component\n  Editor toolbar button to publish the entry being edited, shown once it’s ready to be published.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Button, ConfirmationDialog, Toast } from '@sveltia/ui';\n\n  import ExternalReviewButton from '$lib/components/workflow/external-review-button.svelte';\n  import { getCollection } from '$lib/services/contents/collection';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getPublishAction, publishingBranches } from '$lib/services/workflow';\n  import { getPublishDialogStrings } from '$lib/services/workflow/dialogs';\n  import { runWorkflowEditorAction } from '$lib/services/workflow/editor';\n  import { publishReviewedEntry } from '$lib/services/workflow/save';\n  import { canPublish } from '$lib/services/workflow/validate';\n\n  /**\n   * @import { UnpublishedEntry } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {UnpublishedEntry} entry Unpublished entry being edited.\n   * @property {boolean} [disabled] Whether to disable the control.\n   * @property {boolean} [modified] Whether the draft has unsaved changes. Publishing would merge\n   * the pull request as it stands and throw those changes away, so the control is disabled until\n   * they’re saved. It doesn’t apply to a removal, which has no content to publish.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let { entry, disabled = false, modified = false } = $props();\n\n  let showPublishDialog = $state(false);\n  let showErrorToast = $state(false);\n  /** Message the error toast shows, which says why publishing has failed if it can. */\n  let errorMessage = $state('');\n  let showValidationToast = $state(false);\n\n  // Publishing a removal is what deletes the entry, so the control is presented as Delete\n  const deletion = $derived(entry.workflow.status === 'pending_deletion');\n  const dialogStrings = $derived(getPublishDialogStrings({ deletion }));\n  // The service records the merge in flight, rather than this component: a merge can take minutes\n  // and outlive the editor, and the control stays disabled when the entry is reopened meanwhile\n  const publishing = $derived(\n    publishingBranches.current.includes(entry.workflow.pullRequest.branch),\n  );\n  // Only a user who can merge the pull request gets the control, once the entry is ready. A pull\n  // request a contributor has opened from their fork is merged on the Git service instead\n  const publishAction = $derived(\n    getPublishAction(entry, getCollection(entry.workflow.collectionName)),\n  );\n\n  /**\n   * Publish the entry by merging the pull request, then go back to the entry list.\n   */\n  const publish = async () => {\n    const { blocked, errorMessage: message } = await runWorkflowEditorAction({\n      entry,\n      entryDraft,\n      valid: canPublish({ entry, draft: entryDraft.current }),\n      /**\n       * Merge the pull request, pinned to the version the editor shows.\n       * @returns {Promise<void>} Result.\n       */\n      action: () => publishReviewedEntry(entry, entryDraft.current?.originalEntry),\n      failure: 'workflow.publishing_entry_failed',\n      closeOnSuccess: true,\n    });\n\n    if (blocked) {\n      showValidationToast = true;\n    } else if (message) {\n      errorMessage = message;\n      showErrorToast = true;\n    }\n  };\n</script>\n\n{#if publishAction === 'publish'}\n  <Button\n    variant=\"primary\"\n    label={publishing && !deletion ? _('publishing') : dialogStrings.label}\n    aria-label={dialogStrings.title}\n    disabled={disabled || (modified && !deletion) || publishing}\n    onclick={() => {\n      showPublishDialog = true;\n    }}\n  />\n{:else if publishAction === 'review'}\n  <ExternalReviewButton {entry} {disabled} />\n{/if}\n\n<ConfirmationDialog\n  bind:open={showPublishDialog}\n  title={dialogStrings.title}\n  okLabel={dialogStrings.label}\n  onOk={() => {\n    publish();\n  }}\n>\n  {dialogStrings.message}\n</ConfirmationDialog>\n\n<Toast bind:show={showErrorToast}>\n  <Alert status=\"error\">{errorMessage}</Alert>\n</Toast>\n\n<Toast bind:show={showValidationToast}>\n  <Alert status=\"error\">{_('workflow.publish_blocked')}</Alert>\n</Toast>\n","import { isObject } from '@sveltia/utils/object';\n\nimport { isInlineComponentFieldList } from '$lib/services/config/parser/editor-components';\nimport { isAutoNowField } from '$lib/services/contents/fields/date-time/auto-now';\n\n/**\n * @import { InternalEntryCollection } from '$lib/types/private';\n * @import { Field, NumberField } from '$lib/types/public';\n */\n\n/**\n * Find a top-level field by name.\n * @param {Field[]} fields Fields.\n * @param {string} name Field name.\n * @returns {Field | undefined} Field configuration.\n */\nexport const findFieldByName = (fields, name) => fields.find((field) => field.name === name);\n\n/**\n * Check whether a top-level field of an entry collection can be edited in the bulk editor. Only a\n * field holding a single simple value edited with a compact control fits in a table cell: the same\n * field types as a rich text editor component in the `inline` mode, without the `multiple` option.\n * A read-only field, and a field whose value is set on save — an auto-increment Number field or a\n * DateTime field with the `auto_now` option — don’t qualify either.\n * @param {Field} fieldConfig Field configuration.\n * @returns {boolean} Result.\n */\nexport const isBulkEditableField = (fieldConfig) =>\n  isInlineComponentFieldList([fieldConfig]) &&\n  !(/** @type {{ readonly?: boolean }} */ (fieldConfig).readonly) &&\n  !(fieldConfig.widget === 'number' && /** @type {NumberField} */ (fieldConfig).auto_increment) &&\n  !isAutoNowField(fieldConfig);\n\n/**\n * Check whether the bulk editor is enabled for a collection with the `bulk_edit` option.\n * @param {any} collection Collection. Anything other than an entry collection returns `false`.\n * @returns {boolean} Result.\n */\nexport const isBulkEditEnabled = (collection) =>\n  collection?._type === 'entry' && !!collection.bulk_edit;\n\n/**\n * Get the fields of an entry collection that can be edited in the bulk editor. With the `fields`\n * sub-option, those are the listed fields in the listed order, leaving out any that can’t be edited\n * in bulk, which the configuration parser reports; otherwise, every eligible field in the\n * configured order.\n * @param {InternalEntryCollection | undefined} collection Entry collection.\n * @returns {Field[]} Fields. Empty if the bulk editor is not enabled.\n */\nexport const getBulkEditableFields = (collection) => {\n  if (!collection || !isBulkEditEnabled(collection)) {\n    return [];\n  }\n\n  const { bulk_edit: options } = collection;\n  const names = isObject(options) && Array.isArray(options.fields) ? options.fields : undefined;\n\n  const fields = names\n    ? names.map((name) => findFieldByName(collection.fields, name))\n    : collection.fields;\n\n  return /** @type {Field[]} */ (fields.filter((field) => !!field && isBulkEditableField(field)));\n};\n","import { getDateTimeParts } from '@sveltia/utils/datetime';\n\nimport {\n  DATE_TIME_FIELDS,\n  TEMPLATE_TAG_REPLACE_REGEX,\n} from '$lib/services/common/template/constants';\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport { COMPARISON_OPERATORS, matchesFilter } from '$lib/services/common/view';\nimport { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\nimport { getDate, isValidDate } from '$lib/services/contents/fields/date-time/parse';\nimport { isValueEmpty } from '$lib/services/utils/object';\nimport { getRegex } from '$lib/services/utils/regex';\n\n/**\n * @import { ViewConditions } from '$lib/services/common/view';\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { DateTimeField, ViewComparisonValue } from '$lib/types/public';\n */\n\n/**\n * A comparison value with its template tags resolved. The `{{now}}` tag resolves to a `Date` rather\n * than a string, so that it can be compared with a DateTime field value regardless of the field’s\n * `format`, which the parser would otherwise be applied to.\n * @typedef {ViewComparisonValue | Date} ResolvedValue\n */\n\n/**\n * A comparison operator with its resolved target value.\n * @typedef {object} PreparedComparison\n * @property {(typeof COMPARISON_OPERATORS)[number]} operator Operator.\n * @property {any} target Target value. An array for `in` and `not_in`, a `Date` or `undefined` for\n * an ordinal comparison on a DateTime field, and a {@link ResolvedValue} otherwise.\n */\n\n/**\n * Conditions ready to be tested against a series of entries, with the template tags resolved and\n * the pattern compiled once.\n * @typedef {object} PreparedConditions\n * @property {ResolvedValue | RegExp | undefined} pattern Pattern with its template tags resolved.\n * @property {RegExp | undefined} regex Compiled pattern, if it’s a regular expression.\n * @property {PreparedComparison[]} comparisons Comparisons to be satisfied.\n * @property {DateTimeField | undefined} dateFieldConfig DateTime field configuration, if the\n * target field is a DateTime field.\n * @property {InternalLocaleCode | undefined} locale Locale of the entry values the conditions are\n * tested against, which a DateTime field value may be written in.\n */\n\n/**\n * Strict `YYYY-MM-DD` date, which `new Date()` would parse as UTC midnight rather than local.\n */\nconst DATE_ONLY_REGEX = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/**\n * Check whether a comparison value holds a template tag, so that the conditions depend on the\n * current time.\n * @param {any} value Value from the configuration, or an array of them.\n * @returns {boolean} Whether a string with a tag is found.\n */\nconst hasTemplateTag = (value) =>\n  Array.isArray(value)\n    ? value.some(hasTemplateTag)\n    : typeof value === 'string' && hasTemplateTags(value);\n\n/**\n * Check whether the conditions of a view filter or group depend on the current time, which is the\n * case when the pattern or a comparison value holds a template tag like `{{today}}`. The entry list\n * then has to be recomputed as time goes by, not only when the view or the entries change.\n * @param {ViewConditions | null | undefined} conditions Conditions.\n * @returns {boolean} Result.\n */\nexport const usesCurrentTime = (conditions) =>\n  !!conditions &&\n  (hasTemplateTag(conditions.pattern) ||\n    COMPARISON_OPERATORS.some((operator) => hasTemplateTag(conditions[operator])));\n\n/**\n * Resolve the template tags in a comparison value. A string can hold `{{now}}`, `{{today}}` and\n * the parts of the current date and time, like `{{year}}`, all in the user’s local time zone.\n * @param {any} value Value from the configuration.\n * @param {Date} [now] Current date and time.\n * @returns {any} Value with the tags resolved. A string that is nothing but `{{now}}` resolves to\n * a `Date`, so that it stands for the exact instant however the target field is formatted; within\n * a longer string, it’s written in the `YYYY-MM-DDTHH:mm:ss` format. `{{today}}` resolves to the\n * `YYYY-MM-DD` format, which is what a date-only field stores, so the two sides of a comparison are\n * parsed the same way. Anything but a string is returned as is, and so is an unknown tag.\n */\nexport const resolveComparisonValue = (value, now = new Date()) => {\n  if (typeof value !== 'string' || !hasTemplateTags(value)) {\n    return value;\n  }\n\n  if (value === '{{now}}') {\n    return now;\n  }\n\n  const { year, month, day, hour, minute, second } = getDateTimeParts({ date: now });\n  const today = `${year}-${month}-${day}`;\n  /** @type {Record<string, string>} */\n  const parts = { year, month, day, hour, minute, second };\n\n  return value.replace(TEMPLATE_TAG_REPLACE_REGEX, (match, /** @type {string} */ tag) => {\n    if (tag === 'now') {\n      return `${today}T${hour}:${minute}:${second}`;\n    }\n\n    if (tag === 'today') {\n      return today;\n    }\n\n    if (DATE_TIME_FIELDS.includes(tag)) {\n      return parts[tag];\n    }\n\n    return match;\n  });\n};\n\n/**\n * Check whether a DateTime field holds a date and time in the user’s local time zone, in the\n * default format.\n * @param {DateTimeField} dateFieldConfig DateTime field configuration.\n * @returns {boolean} Result.\n */\nconst isLocalDateTime = (dateFieldConfig) => {\n  const { format, dateOnly, timeOnly, utc } = parseDateTimeConfig(dateFieldConfig);\n\n  return !format && !dateOnly && !timeOnly && !utc;\n};\n\n/**\n * Parse a value as a date the way the target field’s value is parsed.\n * @param {any} value Field value or resolved comparison value.\n * @param {DateTimeField | undefined} dateFieldConfig DateTime field configuration, if any.\n * @param {InternalLocaleCode} [locale] Locale the value may be written in.\n * @returns {Date | undefined} Date, or `undefined` if the value can’t be parsed.\n */\nconst toDate = (value, dateFieldConfig, locale) => {\n  if (value instanceof Date) {\n    return isValidDate(value) ? value : undefined;\n  }\n\n  if (value === undefined || value === null || value === '') {\n    return undefined;\n  }\n\n  // A date-only value, such as the `{{today}}` tag compared with an entry’s `commit_date` or with a\n  // date and time field, stands for the local day, whereas `new Date()` would parse it as UTC\n  // midnight and shift the day boundary by the user’s UTC offset. A field without a time, whose\n  // values are parsed that way as well, and a field edited in UTC or in a custom format keep the\n  // field’s own parsing\n  if (\n    DATE_ONLY_REGEX.test(String(value)) &&\n    (!dateFieldConfig || isLocalDateTime(dateFieldConfig))\n  ) {\n    const [year, month, day] = String(value).split('-').map(Number);\n\n    return new Date(year, month - 1, day);\n  }\n\n  if (dateFieldConfig) {\n    return getDate(String(value), dateFieldConfig, locale);\n  }\n\n  const date = new Date(value);\n\n  return isValidDate(date) ? date : undefined;\n};\n\n/**\n * Check whether a value can be compared as a number.\n * @param {any} value Value to check.\n * @returns {boolean} Whether the value is a finite number or a string holding one.\n */\nconst isNumberLike = (value) =>\n  (typeof value === 'number' && Number.isFinite(value)) ||\n  (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value)));\n\n/**\n * Compare a field value with a comparison target for an ordinal operator.\n * @param {object} args Arguments.\n * @param {any} args.value Field value.\n * @param {any} args.target Prepared target value.\n * @param {DateTimeField | undefined} args.dateFieldConfig DateTime field configuration, if the\n * target field is a DateTime field.\n * @param {InternalLocaleCode} [args.locale] Locale the DateTime field value may be written in.\n * @returns {number | undefined} Negative if the value is less than the target, positive if\n * greater, zero if equal, or `undefined` if the two can’t be compared, which never satisfies the\n * operator. The two are compared as dates if the field is a DateTime field or either side is a\n * `Date`, such as an entry’s `commit_date` or the `{{now}}` tag, as numbers if both are numeric,\n * and as strings otherwise.\n */\nconst compareValues = ({ value, target, dateFieldConfig, locale }) => {\n  if (value === undefined || value === null || target === undefined || target === null) {\n    return undefined;\n  }\n\n  if (dateFieldConfig || value instanceof Date || target instanceof Date) {\n    const date = toDate(value, dateFieldConfig, locale);\n    const targetDate = toDate(target, dateFieldConfig, locale);\n\n    return date && targetDate ? date.getTime() - targetDate.getTime() : undefined;\n  }\n\n  if (isNumberLike(value) && isNumberLike(target)) {\n    return Number(value) - Number(target);\n  }\n\n  const str = String(value);\n  const targetStr = String(target);\n\n  return str < targetStr ? -1 : str > targetStr ? 1 : 0;\n};\n\n/**\n * Check whether a field value equals a comparison target. A number or boolean in the configuration\n * equals its string form in the entry, and vice versa, as the file format decides which one is\n * stored.\n * @param {any} value Field value.\n * @param {any} target Prepared target value.\n * @returns {boolean} Whether the two are equal.\n */\nconst isEqual = (value, target) =>\n  value === target ||\n  (value !== undefined &&\n    value !== null &&\n    target !== undefined &&\n    String(value) === String(target));\n\n/**\n * Prepare the conditions of a view filter or group to be tested against a series of entries.\n * @param {ViewConditions} conditions Conditions.\n * @param {object} [options] Options.\n * @param {DateTimeField} [options.dateFieldConfig] DateTime field configuration, if the target\n * field is a DateTime field. The target of an ordinal comparison is then parsed as a date once,\n * rather than for every entry.\n * @param {Date} [options.now] Current date and time, which the template tags resolve to.\n * @param {InternalLocaleCode} [options.locale] Locale of the entry values the conditions are tested\n * against, which a DateTime field value may be written in with the `localize_format` option.\n * @returns {PreparedConditions} Prepared conditions.\n */\nexport const prepareConditions = (\n  conditions,\n  { dateFieldConfig, now = new Date(), locale = undefined } = {},\n) => {\n  const pattern = resolveComparisonValue(conditions.pattern, now);\n\n  const comparisons = COMPARISON_OPERATORS.filter(\n    (operator) => conditions[operator] !== undefined,\n  ).map((operator) => {\n    const value = conditions[operator];\n\n    if (operator === 'empty') {\n      return { operator, target: value };\n    }\n\n    if (operator === 'in' || operator === 'not_in') {\n      return {\n        operator,\n        target: (Array.isArray(value) ? value : [value]).map((item) =>\n          resolveComparisonValue(item, now),\n        ),\n      };\n    }\n\n    const target = resolveComparisonValue(value, now);\n\n    if (dateFieldConfig && operator !== 'eq' && operator !== 'ne') {\n      return { operator, target: toDate(target, dateFieldConfig, locale) };\n    }\n\n    return { operator, target };\n  });\n\n  return { pattern, regex: getRegex(pattern), comparisons, dateFieldConfig, locale };\n};\n\n/**\n * Check whether a field value satisfies the prepared conditions.\n * @param {object} args Arguments.\n * @param {any} args.rawValue Field value as stored in the entry. An array for a multi-value field,\n * such as a List field or a Relation field with `multiple: true`, which is matched item by item:\n * the entry satisfies a condition when any of its items does, and `ne` and `not_in` when none does.\n * @param {any} [args.refValue] Field value as displayed, when it differs from the stored value: the\n * label of the option a relation field refers to, or an array of labels for a multi-value field. An\n * equality check accepts either, so a filter can name the option the way the editor sees it or the\n * way it’s stored.\n * @param {PreparedConditions} args.conditions Prepared conditions.\n * @returns {boolean} Whether the value matches the pattern, if any, and satisfies every\n * comparison. An entry without a value for the field only satisfies `ne`, `not_in` and `empty:\n * true`.\n * @see https://github.com/sveltia/sveltia-cms/issues/997\n * @see https://github.com/sveltia/sveltia-cms/issues/1004\n */\nexport const matchesConditions = ({ rawValue, refValue, conditions }) => {\n  const { pattern, regex, comparisons, dateFieldConfig, locale } = conditions;\n  const rawValues = [rawValue].flat().filter((value) => value !== undefined);\n\n  // A label that can’t be resolved falls back to the stored value, so the two lists can overlap\n  const values = [\n    ...new Set([...rawValues, ...[refValue].flat().filter((value) => value !== undefined)]),\n  ];\n\n  if (pattern !== undefined && !values.some((value) => matchesFilter(value, pattern, regex))) {\n    return false;\n  }\n\n  return comparisons.every(({ operator, target }) => {\n    switch (operator) {\n      case 'eq':\n        return values.some((value) => isEqual(value, target));\n      case 'ne':\n        return !values.some((value) => isEqual(value, target));\n      case 'in':\n        return values.some((value) => target.some((/** @type {any} */ t) => isEqual(value, t)));\n      case 'not_in':\n        return !values.some((value) => target.some((/** @type {any} */ t) => isEqual(value, t)));\n      case 'empty':\n        // A multi-value or Object field is empty when none of its items has a value\n        return [rawValue].flat().every(isValueEmpty) === target;\n\n      default:\n        return rawValues.some((value) => {\n          const result = compareValues({ value, target, dateFieldConfig, locale });\n\n          if (result === undefined) {\n            return false;\n          }\n\n          if (operator === 'lt') {\n            return result < 0;\n          }\n\n          if (operator === 'lte') {\n            return result <= 0;\n          }\n\n          if (operator === 'gt') {\n            return result > 0;\n          }\n\n          return result >= 0;\n        });\n    }\n  });\n};\n","import { getConditionKey, getViewConditions } from '$lib/services/common/view';\nimport { selectedCollection } from '$lib/services/contents/collection';\nimport {\n  matchesConditions,\n  prepareConditions,\n} from '$lib/services/contents/collection/view/conditions';\nimport { parseViewOptions } from '$lib/services/contents/collection/view/options';\nimport { getListedEntryValue } from '$lib/services/contents/collection/view/values';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * Entry,\n * FilteringConditions,\n * GroupingConditions,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { DateTimeField, ViewFilter, ViewFilters, ViewGroup } from '$lib/types/public';\n */\n\n/**\n * Parse view filters configuration. This supports both an array, which is compatible with\n * Netlify/Decap CMS, and an object, which is compatible with Static CMS.\n * @param {ViewFilter[] | ViewFilters | undefined} filters View filters configuration.\n * @returns {{ options: ViewFilter[], default?: FilteringConditions }} Parsed view filters.\n * @see https://decapcms.org/docs/configuration-options/#view_filters\n * @see https://staticjscms.netlify.app/docs/collection-overview#view-filters\n * @see https://sveltiacms.app/en/docs/collections/entries/views#filtering\n */\nexport const parseFilterConfig = (filters) =>\n  /** @type {{ options: ViewFilter[], default?: FilteringConditions }} */\n  (parseViewOptions(filters, 'filters'));\n\n/**\n * Create a function that checks if an entry satisfies the given filtering or grouping conditions.\n * The template tags are resolved and the regexes compiled once, rather than for every entry. Both\n * the raw value of the field and the value it references are checked.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {InternalLocaleCode} args.locale Locale to get the values in.\n * @param {FilteringConditions | GroupingConditions} args.conditions Conditions.\n * @param {Date} args.now Current date and time, which the template tags in the conditions resolve\n * to.\n * @returns {(entry: Entry) => boolean} Function returning whether an entry matches.\n */\nexport const createEntryMatcher = ({ collectionName, locale, conditions, now }) => {\n  const { field: key } = conditions;\n  const fieldConfig = getField({ collectionName, keyPath: key });\n\n  const dateFieldConfig =\n    fieldConfig?.widget === 'datetime' ? /** @type {DateTimeField} */ (fieldConfig) : undefined;\n\n  const prepared = prepareConditions(conditions, { dateFieldConfig, now, locale });\n\n  return (entry) => {\n    const args = { entry, locale, collectionName, key };\n\n    return matchesConditions({\n      rawValue: getListedEntryValue({ ...args, resolveRef: false }),\n      refValue: getListedEntryValue(args),\n      conditions: prepared,\n    });\n  };\n};\n\n/**\n * Create the view filters or groups for the selected entry collection.\n * @template {ViewFilter | ViewGroup} T\n * @param {'filters' | 'groups'} type Option type.\n * @returns {{ readonly current: T[] }} Options. Empty for a file/singleton collection.\n */\nexport const createViewOptionsState = (type) =>\n  createDerivedState(() => {\n    const collection = selectedCollection.current;\n\n    return collection?._type === 'entry'\n      ? /** @type {T[]} */ (parseViewOptions(collection[`view_${type}`], type).options)\n      : [];\n  });\n\n/**\n * Filter the given entries.\n * @param {Entry[]} entries Entry list.\n * @param {InternalEntryCollection} collection Collection that the entries belong to.\n * @param {FilteringConditions[]} filters One or more filtering conditions.\n * @param {Date} [now] Current date and time, which the template tags in the conditions resolve to.\n * @returns {Entry[]} Filtered entry list.\n * @see https://decapcms.org/docs/configuration-options/#view_filters\n * @see https://sveltiacms.app/en/docs/collections/entries/views#filtering\n */\nexport const filterEntries = (entries, collection, filters, now = new Date()) => {\n  const {\n    name: collectionName,\n    view_filters: configuredFilters = [],\n    _i18n: { defaultLocale: locale },\n  } = collection;\n\n  const { options } = parseFilterConfig(configuredFilters);\n  const optionKeys = options.map((option) => getConditionKey(getViewConditions(option)));\n\n  // Ignore invalid filters, such as one saved in the view settings and removed from the\n  // configuration since\n  const validFilters = filters.filter(\n    (conditions) =>\n      conditions.field !== undefined && optionKeys.includes(getConditionKey(conditions)),\n  );\n\n  const matchers = validFilters.map((conditions) =>\n    createEntryMatcher({ collectionName, locale, conditions, now }),\n  );\n\n  return entries.filter((entry) => matchers.every((matches) => matches(entry)));\n};\n\n/**\n * View filters for the selected entry collection.\n * @type {{ readonly current: ViewFilter[] }}\n */\nexport const viewFilters = createViewOptionsState('filters');\n","import {\n  buildGroupMap,\n  getConditionKey,\n  getViewConditions,\n  hasComparison,\n  OTHER_GROUP_NAME,\n} from '$lib/services/common/view';\nimport { getReorderGroupName } from '$lib/services/contents/collection/entries/reorder/config';\nimport {\n  createEntryMatcher,\n  createViewOptionsState,\n} from '$lib/services/contents/collection/view/filter';\nimport { parseViewOptions } from '$lib/services/contents/collection/view/options';\nimport {\n  getListedEntryValue,\n  normalizeMultiValue,\n} from '$lib/services/contents/collection/view/values';\n\n/**\n * @import {\n * Entry,\n * GroupingConditions,\n * InternalCollection,\n * InternalEntryCollection,\n * SortingConditions,\n * } from '$lib/types/private';\n * @import { ViewGroup, ViewGroups } from '$lib/types/public';\n */\n\n/**\n * Parse view groups configuration. This supports both an array, which is compatible with\n * Netlify/Decap CMS, and an object, which is compatible with Static CMS.\n * @param {ViewGroup[] | ViewGroups | undefined} filters View groups configuration.\n * @returns {{ options: ViewGroup[], default?: GroupingConditions }} Parsed view groups.\n * @see https://decapcms.org/docs/configuration-options/#view_groups\n * @see https://staticjscms.netlify.app/docs/collection-overview#view-groups\n * @see https://sveltiacms.app/en/docs/collections/entries/views#grouping\n */\nexport const parseGroupConfig = (filters) =>\n  /** @type {{ options: ViewGroup[], default?: GroupingConditions }} */\n  (parseViewOptions(filters, 'groups'));\n\n/**\n * Get the grouping conditions to be applied while the given collection is in reorder mode, by\n * resolving the group named with the collection’s `reorder.group` option against its `view_groups`\n * definitions. Entries are then reordered within their own group, which is useful when the order\n * field is only consumed per group.\n * @param {InternalCollection | undefined} collection Collection.\n * @returns {GroupingConditions | undefined} Conditions, or `undefined` if reorder grouping is not\n * configured or the named group is not defined in `view_groups`.\n * @see https://sveltiacms.app/en/docs/collections/entries/views#grouping\n */\nexport const getReorderGroupingConditions = (collection) => {\n  // Grouping is only available for entry collections\n  if (collection?._type !== 'entry') {\n    return undefined;\n  }\n\n  const name = getReorderGroupName(collection);\n\n  if (!name) {\n    return undefined;\n  }\n\n  const group = parseGroupConfig(collection.view_groups).options.find((g) => g.name === name);\n\n  return group ? getViewConditions(group) : undefined;\n};\n\n/**\n * Split the given entries into the ones satisfying a group’s comparison conditions and the rest.\n * @param {Entry[]} entries Entry list.\n * @param {InternalEntryCollection} collection Collection that the entries belong to. Grouping is\n * only available for entry collections, which are the ones with `view_groups`.\n * @param {GroupingConditions} conditions Grouping conditions with a comparison operator.\n * @param {Date} now Current date and time, which the template tags in the conditions resolve to.\n * @returns {{ name: string, entries: Entry[] }[]} The group of matching entries, named after the\n * label of the view group the conditions came from, so that a group labelled “Upcoming” lists the\n * upcoming events under that heading, followed by the {@link OTHER_GROUP_NAME} group. An empty\n * group is left out.\n */\nconst groupEntriesByComparison = (entries, collection, conditions, now) => {\n  const {\n    name: collectionName,\n    view_groups: viewGroups,\n    _i18n: { defaultLocale: locale },\n  } = collection;\n\n  const { field } = conditions;\n  const key = getConditionKey(conditions);\n  const matches = createEntryMatcher({ collectionName, locale, conditions, now });\n\n  // The conditions are what the view holds, so the label has to be looked up. It can be missing\n  // from a group that has been removed from the configuration since the view was saved\n  const label =\n    parseGroupConfig(viewGroups).options.find(\n      (option) => getConditionKey(getViewConditions(option)) === key,\n    )?.label || field;\n\n  /** @type {Entry[]} */\n  const matched = [];\n  /** @type {Entry[]} */\n  const others = [];\n\n  entries.forEach((entry) => {\n    (matches(entry) ? matched : others).push(entry);\n  });\n\n  return [\n    { name: label, entries: matched },\n    { name: OTHER_GROUP_NAME, entries: others },\n  ].filter((group) => group.entries.length);\n};\n\n/**\n * Group the given entries.\n * @param {Entry[]} entries Entry list.\n * @param {InternalCollection} collection Collection that the entries belong to.\n * @param {GroupingConditions | null | undefined} conditions Grouping conditions.\n * @param {Date} [now] Current date and time, which the template tags in the conditions resolve to.\n * @param {SortingConditions} [sortCondition] Sorting conditions of the view. The groups follow a\n * descending sort on the field they’re grouped by. This is passed in rather than read from the\n * current view, so the groups aren’t made anew when any other part of the view changes, such as a\n * group being collapsed.\n * @returns {{ name: string, entries: Entry[] }[]} Grouped entries, where each group object contains\n * a name, displayed with `getGroupLabel()`, and an entry list. When ungrouped, there will still be\n * one group object named `*`.\n * @see https://decapcms.org/docs/configuration-options/#view_groups\n * @see https://sveltiacms.app/en/docs/collections/entries/views#grouping\n */\nexport const groupEntries = (\n  entries,\n  collection,\n  conditions,\n  now = new Date(),\n  sortCondition = undefined,\n) => {\n  const { field, pattern } = conditions ?? { field: '', pattern: undefined };\n\n  if (!field) {\n    return entries.length ? [{ name: '*', entries }] : [];\n  }\n\n  if (hasComparison(conditions)) {\n    return groupEntriesByComparison(\n      entries,\n      /** @type {InternalEntryCollection} */ (collection),\n      /** @type {GroupingConditions} */ (conditions),\n      now,\n    );\n  }\n\n  const {\n    name: collectionName,\n    _i18n: { defaultLocale: locale },\n  } = collection;\n\n  const sortedGroups = buildGroupMap(entries, pattern, (entry) =>\n    normalizeMultiValue(getListedEntryValue({ entry, locale, collectionName, key: field })),\n  ).map(([name, _entries]) => ({ name, entries: _entries }));\n\n  // Keep the descending order if already sorted, especially on the date field\n  if (sortCondition?.key === field && sortCondition.order === 'descending') {\n    sortedGroups.reverse();\n  }\n\n  return sortedGroups;\n};\n\n/**\n * View groups for the selected entry collection.\n * @type {{ readonly current: ViewGroup[] }}\n */\nexport const viewGroups = createViewOptionsState('groups');\n","import equal from 'fast-deep-equal';\nimport { untrack } from 'svelte';\n\nimport { backend } from '$lib/services/backends';\nimport { lockedBranch } from '$lib/services/backends/branch-access';\nimport { getConditionKey, getGroupingKey, getViewConditions } from '$lib/services/common/view';\nimport { isReadonly } from '$lib/services/config/readonly';\nimport { allEntries } from '$lib/services/contents';\nimport { selectedCollection } from '$lib/services/contents/collection';\nimport { getEntriesByCollection, selectedEntries } from '$lib/services/contents/collection/entries';\nimport { getBulkEditableFields } from '$lib/services/contents/collection/entries/bulk-edit/config';\nimport { countQuotaEntries } from '$lib/services/contents/collection/entries/count';\nimport { isManuallyOrdered } from '$lib/services/contents/collection/entries/reorder/config';\nimport { getCollectionFilesByEntry } from '$lib/services/contents/collection/files';\nimport { filterNestedEntries, nestedFilterPath } from '$lib/services/contents/collection/nested';\nimport { usesCurrentTime } from '$lib/services/contents/collection/view/conditions';\nimport { filterEntries, parseFilterConfig } from '$lib/services/contents/collection/view/filter';\nimport {\n  getReorderGroupingConditions,\n  groupEntries,\n  parseGroupConfig,\n} from '$lib/services/contents/collection/view/group';\nimport {\n  currentView,\n  entryListSettings,\n  initSettings,\n  viewBeforeReorder,\n} from '$lib/services/contents/collection/view/settings';\nimport { sortEntries } from '$lib/services/contents/collection/view/sort';\nimport { getSortConfig } from '$lib/services/contents/collection/view/sort-keys';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport {\n  createDerivedState,\n  createRawState,\n  createRootEffect,\n  createStableDerivedState,\n} from '$lib/services/utils/state.svelte';\nimport { swapUnpublishedEntries, unpublishedEntries } from '$lib/services/workflow';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * BulkEditErrors,\n * BulkEdits,\n * } from '$lib/services/contents/collection/entries/bulk-edit';\n * @import {\n * Entry,\n * EntryListView,\n * GroupingConditions,\n * InternalEntryCollection,\n * } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} CollectionState\n * @property {boolean} isEntryCollection Whether the selected collection is an entry collection.\n * @property {boolean} readonly Whether the selected collection is read-only, because of its own or\n * the global `readonly` option. Nothing can be created, deleted or reordered in it then.\n * @property {boolean} canCreate Whether new entries can be created in the selected collection. It’s\n * `false` with the `create: false` option, and also with `limit: 0`, which forbids creating entries\n * the same way rather than being a quota to reach.\n * @property {boolean} canDelete Whether entries can be deleted from the selected collection.\n * @property {boolean} canReorder Whether entries in the selected collection can be reordered.\n * @property {boolean} canBulkEdit Whether entries in the selected collection can be edited in bulk.\n * @property {number} quota The maximum number of entries allowed in the selected collection.\n * @property {number} remaining The number of additional entries that can be added to the selected\n * collection before reaching the quota.\n * @property {boolean} nearingQuota Whether the number of remaining entries is at or below the\n * warning threshold.\n * @property {boolean} creationDisabled Whether creating new entries is currently disabled, due to\n * permissions, because the collection is read-only or because the quota has been reached.\n */\n\n/**\n * Whether the entry collection is in reorder mode, which allows users to reorder entries with a\n * drag-and-drop UI. This is used to control the UI state and behavior when reordering entries in a\n * collection. Use {@link setReorderMode} to change it, so the view is adjusted at the same time.\n */\nexport const reordering = createRawState(false);\n\n/**\n * Pending reorder result while the entry collection is in reorder mode. The list contains the\n * collection’s entries in the order the user has arranged them in the UI. It is consumed when the\n * user confirms the reorder, then reset.\n * @type {{ current: Entry[] }}\n */\nexport const reorderedEntries = createRawState([]);\n\n/**\n * Whether the user has actually moved an entry while in reorder mode. The toolbar Save button uses\n * this to stay disabled until at least one move has happened, so a simple Enter → Save round-trip\n * doesn’t cause a no-op commit.\n */\nexport const reorderDirty = createRawState(false);\n\n/**\n * Whether the entry collection is in bulk edit mode, which shows the listed entries in a table\n * where their simple fields can be edited at once. Use {@link setBulkEditMode} to change it, so the\n * pending edits are reset at the same time.\n */\nexport const bulkEditing = createRawState(false);\n\n/**\n * Pending edits made in bulk edit mode, keyed by entry ID, then by field name. Only the values that\n * differ from the stored ones are kept, so the mode has unsaved changes if this isn’t empty.\n * @type {{ current: BulkEdits }}\n */\nexport const bulkEdits = createRawState({});\n\n/**\n * Whether the pending edits made in bulk edit mode are being saved. The cells are read-only then,\n * as the mode is left once the commit is made, which would discard an edit made in the meantime.\n */\nexport const bulkEditSaving = createRawState(false);\n\n/**\n * Entries shown in bulk edit mode, published by the bulk editor when it’s opened so the toolbar\n * Save button can read them. The list is a snapshot, so a background refresh doesn’t pull the rows\n * from under the user.\n * @type {{ current: Entry[] }}\n */\nexport const bulkEditedEntries = createRawState([]);\n\n/**\n * Validation messages of the pending edits made in bulk edit mode, keyed by entry ID, then by field\n * name. Empty until the user tries to save invalid edits; it’s then kept up to date as the edits\n * change, so a fixed field stops being reported.\n * @type {{ current: BulkEditErrors }}\n */\nexport const bulkEditErrors = createRawState({});\n\n/**\n * Check whether the entry collection is in reorder or bulk edit mode, which rewrite the published\n * entries.\n * @returns {boolean} Result.\n */\nconst isRewriting = () => reordering.current || bulkEditing.current;\n/**\n * How often {@link viewTime} is updated while a time-based view filter or group is applied. A\n * minute keeps the list close to the clock without recomputing it for nothing.\n */\nconst VIEW_TIME_INTERVAL = 60000;\n\n/**\n * Current date and time that the template tags in the view filters and groups resolve to, such as\n * `{{today}}` in an “Upcoming events” filter. It’s updated every minute while the current view has\n * such a condition, so that the list is recomputed as time goes by, e.g. when an event starts or\n * the day changes, and not only when the view or the entries change. See {@link viewUsesTime}.\n * @type {{ current: Date }}\n */\nexport const viewTime = createRawState(new Date());\n\n/**\n * Whether the current view has a filter or group depending on the current time.\n * @type {{ readonly current: boolean }}\n */\nexport const viewUsesTime = createDerivedState(() => {\n  const { filters = [], group } = currentView.current;\n\n  return filters.some(usesCurrentTime) || usesCurrentTime(group);\n});\n\n/**\n * Sorting conditions of the current view. This and the other view conditions below are picked out\n * of {@link currentView} one by one, so replacing the view to switch between list and grid, or to\n * collapse a group, doesn’t sort, filter and group the entries all over again: each step only\n * reruns when the conditions it uses have actually changed.\n */\nconst sortConditions = createStableDerivedState(() => currentView.current.sort);\n/**\n * Filtering conditions of the current view. See {@link sortConditions}.\n */\nconst filterConditions = createStableDerivedState(() => currentView.current.filters);\n/**\n * Grouping conditions of the current view. See {@link sortConditions}.\n */\nconst groupConditions = createStableDerivedState(() => currentView.current.group);\n\n/**\n * List of the entries shown in the entry list for the selected entry collection. For a nested\n * collection, only the entries in the folder the user is currently browsing are included; the\n * deeper ones are reachable through the collection tree in the primary sidebar.\n * @type {{ readonly current: Entry[] }}\n */\nexport const listedEntries = createDerivedState(() => {\n  const { current: _allEntries } = allEntries;\n  const { current: _collection } = selectedCollection;\n  const { current: _nestedFilterPath } = nestedFilterPath;\n\n  if (!_allEntries || !_collection) {\n    return [];\n  }\n\n  /**\n   * Limit the entries to the folder currently browsed in a collection with nested entries.\n   * @param {Entry[]} entries Entries to be filtered.\n   * @returns {Entry[]} Filtered entries.\n   */\n  const filterNested = (entries) =>\n    filterNestedEntries({ collection: _collection, entries, dirPath: _nestedFilterPath });\n\n  const entries = getEntriesByCollection(_collection.name);\n\n  // Don’t swap while reordering or bulk editing, because these modes rewrite the published entries,\n  // and the draft version must not leak into that commit\n  if (isRewriting()) {\n    return filterNested(entries);\n  }\n\n  // Show the pending changes rather than what’s live, so the list sorts, filters and groups by\n  // them\n  return filterNested(\n    swapUnpublishedEntries(\n      entries,\n      unpublishedEntries.current.filter(\n        ({ workflow }) => workflow.collectionName === _collection.name,\n      ),\n    ),\n  );\n});\n\n/**\n * Unpublished entries for the selected entry collection that have never been published, before the\n * view settings are applied. Unlike an update to an existing entry, which replaces the published\n * version in {@link listedEntries}, these are listed in a separate group above the published\n * entries.\n * @type {{ readonly current: Entry[] }}\n */\nconst newUnpublishedEntries = createDerivedState(() => {\n  const { current: _collection } = selectedCollection;\n\n  if (_collection?._type !== 'entry' || isRewriting()) {\n    return [];\n  }\n\n  // A draft that replaced a published entry is already in `listedEntries`, so match by identity\n  // rather than by path, which a rename would break\n  const swappedIn = new Set(listedEntries.current);\n\n  return filterNestedEntries({\n    collection: _collection,\n    entries: unpublishedEntries.current.filter(\n      (entry) => entry.workflow.collectionName === _collection.name && !swappedIn.has(entry),\n    ),\n    dirPath: nestedFilterPath.current,\n  });\n});\n\n/**\n * List of unpublished entries for the selected entry collection that have never been published,\n * sorted and filtered with the same view settings as {@link entryGroups}. See\n * {@link newUnpublishedEntries}.\n * @type {{ readonly current: Entry[] }}\n */\nexport const listedUnpublishedEntries = createDerivedState(() => {\n  let entries = newUnpublishedEntries.current;\n\n  if (!entries.length) {\n    return [];\n  }\n\n  const _collection = /** @type {InternalEntryCollection} */ (selectedCollection.current);\n  const { current: sort } = sortConditions;\n  const { current: filters } = filterConditions;\n\n  if (sort) {\n    entries = sortEntries(entries, _collection, sort);\n  }\n\n  if (filters) {\n    entries = filterEntries(entries, _collection, filters, viewTime.current);\n  }\n\n  return entries;\n});\n\n/**\n * Number of entries in the entry list for the selected entry collection, published or not, before\n * the view filters narrow them down. The list controls depend on this rather than on what’s shown,\n * so that they stay available, and a filter hiding every entry can be reset.\n * @type {{ readonly current: number }}\n */\nexport const listedEntryCount = createDerivedState(\n  () => listedEntries.current.length + newUnpublishedEntries.current.length,\n);\n\n/**\n * Threshold for when to show a warning about nearing the quota of entries in an entry collection.\n * This is used in the UI to provide feedback to users when they are close to reaching the maximum\n * number of entries allowed in a collection, based on the collection’s quota settings.\n * @type {number}\n */\nconst QUOTA_WARNING_THRESHOLD = 5;\n\n/**\n * State of the selected collection, including permissions and quota information, used for\n * controlling the UI and providing feedback to users.\n * @type {{ readonly current: CollectionState }}\n */\nexport const collectionState = createDerivedState(() => {\n  const { current: _selectedCollection } = selectedCollection;\n  const readonly = !!_selectedCollection && isReadonly({ collection: _selectedCollection });\n\n  if (_selectedCollection?._type === 'entry') {\n    // `limit: 0` means no entries can ever be created, so it’s treated like `create: false`\n    const canCreate = (_selectedCollection.create ?? true) && _selectedCollection.limit !== 0;\n    const canDelete = !readonly && (_selectedCollection.delete ?? true);\n    // Reordering writes the new order straight to the configured branch rather than going through\n    // review, even in a collection using Editorial Workflow, so it’s not something an Open\n    // Authoring contributor or a user who can’t push to the branch can do. An entry collection\n    // storing all the entries in one file can always be reordered\n    const canWriteToBranch = !readonly && !openAuthoring.current && !lockedBranch.current;\n    const canReorder = canWriteToBranch && isManuallyOrdered(_selectedCollection);\n    // Bulk editing writes straight to the configured branch as well, for the same reasons\n    const canBulkEdit = canWriteToBranch && !!getBulkEditableFields(_selectedCollection).length;\n    const quota = _selectedCollection?.limit ?? Infinity;\n    // The quota applies to the whole collection, including the entries that only exist in a pull\n    // request, so it agrees with the count shown next to the collection in the sidebar\n    const entryCount = countQuotaEntries(_selectedCollection.name);\n    const remaining = quota < Infinity ? quota - entryCount : Infinity;\n\n    return {\n      isEntryCollection: true,\n      readonly,\n      canCreate,\n      canDelete,\n      canReorder,\n      canBulkEdit,\n      quota,\n      remaining,\n      nearingQuota: remaining > 0 && remaining <= QUOTA_WARNING_THRESHOLD,\n      creationDisabled: !canCreate || readonly || remaining <= 0,\n    };\n  }\n\n  return {\n    isEntryCollection: false,\n    readonly,\n    canCreate: false,\n    canDelete: false,\n    canReorder: false,\n    canBulkEdit: false,\n    quota: Infinity,\n    remaining: Infinity,\n    nearingQuota: false,\n    creationDisabled: false,\n  };\n});\n\n/**\n * {@link listedEntries} sorted with the current view’s conditions. Sorting is the costliest step,\n * as it reads a value from every entry, so it comes first: changing a filter, or {@link viewTime}\n * ticking, then only reruns the cheaper steps below. `sortEntries()` reads the current app locale,\n * so this is also recomputed when the locale changes.\n * @type {{ readonly current: Entry[] }}\n */\nconst sortedEntries = createDerivedState(() => {\n  const collection = /** @type {InternalEntryCollection} */ (selectedCollection.current);\n  const { current: entries } = listedEntries;\n  const { current: sort } = sortConditions;\n\n  return sort ? sortEntries(entries, collection, sort) : entries;\n});\n\n/**\n * {@link sortedEntries} filtered with the current view’s conditions.\n * @type {{ readonly current: Entry[] }}\n */\nconst filteredEntries = createDerivedState(() => {\n  const collection = /** @type {InternalEntryCollection} */ (selectedCollection.current);\n  const { current: entries } = sortedEntries;\n  const { current: filters } = filterConditions;\n\n  return filters ? filterEntries(entries, collection, filters, viewTime.current) : entries;\n});\n\n/**\n * Sorted, filtered and grouped entries for the selected entry collection. `groupEntries()` may\n * return localized labels, as it reads the current app locale, so the groups are also recomputed\n * when the locale changes. They are also recomputed as {@link viewTime} ticks while a time-based\n * filter or group is applied.\n * @type {{ readonly current: { name: string, entries: Entry[] }[] }}\n */\nexport const entryGroups = createDerivedState(() => {\n  const collection = /** @type {InternalEntryCollection} */ (selectedCollection.current);\n  const { current: entries } = listedEntries;\n\n  // Reset the groups if the current collection is empty or a file/singleton collection. This is\n  // checked before the entries are sorted and filtered, so neither is done for nothing\n  if (!entries.length || !!getCollectionFilesByEntry(collection, entries[0]).length) {\n    return [];\n  }\n\n  const { current: group } = groupConditions;\n\n  return groupEntries(\n    filteredEntries.current,\n    collection,\n    group,\n    viewTime.current,\n    sortConditions.current,\n  );\n});\n\n/**\n * Entries the entry list shows, the unpublished ones included, which the selection is limited to.\n * The entries in a collapsed group count as shown, as Select All selects them too.\n * @type {{ readonly current: Set<Entry> }}\n */\nconst shownEntries = createDerivedState(\n  () =>\n    new Set([\n      ...listedUnpublishedEntries.current,\n      ...entryGroups.current.flatMap(({ entries }) => entries),\n    ]),\n);\n\n/**\n * Map from entry ID to the entry’s row index in the list, used by list rows to resolve their\n * `aria-rowindex` in O(1). The index follows the displayed order of {@link shownEntries}: the\n * unpublished entries come first, then the entries of every group, sorted and filtered, as the rows\n * of every group make up one grid. Rows are appended by an infinite scroller and never unmounted,\n * so once a large collection has been scrolled through, an `indexOf()` per row would make every\n * subsequent list update O(n²).\n */\nexport const listedEntryIndexMap = createDerivedState(\n  () => new Map([...shownEntries.current].map((entry, index) => [entry.id, index])),\n);\n\n/**\n * Restore the view settings of the given entry collection from {@link entryListSettings}, falling\n * back to the collection’s default sort, filter and grouping options where the saved view has none.\n * @param {InternalEntryCollection} collection Collection.\n * @param {Entry[]} _allEntries All the entries.\n */\nconst restoreView = (collection, _allEntries) => {\n  const { view_filters: viewFilters, view_groups: viewGroups } = collection;\n  /** @type {EntryListView} */\n  // The view type is only set once the user picks one; until then, the default applies. See\n  // `getEntryViewType()`\n  const view = { ...entryListSettings.current?.[collection.name] };\n\n  const { default: defaultSort } = getSortConfig({\n    collection,\n    isCommitAuthorAvailable: _allEntries.some((entry) => !!entry.commitAuthor),\n    isCommitDateAvailable: _allEntries.some((entry) => !!entry.commitDate),\n  });\n\n  // The commit metadata may arrive after the entries, so a saved sort key depending on it is\n  // validated as if it were there, rather than dropped while it’s on its way\n  const { keys: sortKeys } = getSortConfig({\n    collection,\n    isCommitAuthorAvailable: true,\n    isCommitDateAvailable: true,\n  });\n\n  const { default: defaultFilter } = parseFilterConfig(viewFilters);\n  const { options: groupOptions, default: defaultGroup } = parseGroupConfig(viewGroups);\n\n  // Drop a saved sort key or group that has been removed from the configuration since the view was\n  // saved, so the defaults apply instead. A stale group would otherwise stay applied while the menu\n  // no longer offers a way to undo it. Stale filters are ignored by `filterEntries()` instead\n  if (view.sort?.key !== undefined && !sortKeys.includes(view.sort.key)) {\n    delete view.sort;\n  }\n\n  if (\n    view.group &&\n    !groupOptions.some(\n      (option) =>\n        getConditionKey(getViewConditions(option)) ===\n        getConditionKey(/** @type {GroupingConditions} */ (view.group)),\n    )\n  ) {\n    delete view.group;\n  }\n\n  if (view.sort === undefined && defaultSort) {\n    view.sort = defaultSort;\n  }\n\n  if (view.filters === undefined && defaultFilter) {\n    view.filters = [defaultFilter];\n  }\n\n  if (view.group === undefined && defaultGroup) {\n    view.group = defaultGroup;\n  }\n\n  if (!equal(view, currentView.current)) {\n    currentView.current = view;\n  }\n};\n\n/**\n * Enter or exit reorder mode, updating the view accordingly. The view is updated synchronously,\n * before `reordering` is flipped, so that the components reacting to `reordering` — such as the\n * entry reorder list, which snapshots `entryGroups` on mount — always see the adjusted view rather\n * than depending on the order in which effects happen to run.\n * @param {boolean} value Whether to enter reorder mode.\n */\nexport const setReorderMode = (value) => {\n  if (!value) {\n    reorderedEntries.current = [];\n    reorderDirty.current = false;\n\n    // Restore the snapshot taken when entering reorder mode, if any.\n    if (viewBeforeReorder.current) {\n      currentView.current = viewBeforeReorder.current.view;\n      viewBeforeReorder.current = undefined;\n    }\n\n    reordering.current = false;\n\n    return;\n  }\n\n  // When entering reorder mode, force the entry list to be sorted by the manual order so users see\n  // and arrange entries in the same order they will be persisted. Also clear any active filters or\n  // grouping: reordering operates on the visible entry list, and the order field is a single global\n  // sequence. Filters would cause hidden entries to retain their old order values and collide with\n  // the new 1..N numbering, while grouping splits the list into buckets that can’t be reordered\n  // across, producing global numbers that don’t match user intent.\n  //\n  // A collection whose order field is only consumed within a group can opt into grouped reordering\n  // with `reorder: { group: '…' }`. That group replaces whatever grouping the user has active, so\n  // the buckets — and therefore the numbering, which runs group by group — are always the same.\n  // Nothing is hidden either way, so what the user sees is still exactly what gets persisted.\n  const view = currentView.current;\n  const reorderGroup = getReorderGroupingConditions(selectedCollection.current);\n\n  // Snapshot so we can restore on exit. The view settings save it in place of the reorder view, so\n  // the user’s own view is kept even if reordering is never finished\n  viewBeforeReorder.current = { collectionName: selectedCollection.current?.name, view };\n\n  /** @type {Partial<EntryListView>} */\n  const overrides = {};\n\n  if (view.sort?.key !== '_manual') {\n    overrides.sort = { key: '_manual', order: 'ascending' };\n  }\n\n  if (view.filters?.length) {\n    overrides.filters = [];\n  }\n\n  if (reorderGroup) {\n    if (getGroupingKey(view.group) !== getGroupingKey(reorderGroup)) {\n      overrides.group = reorderGroup;\n    }\n  } else if (view.group) {\n    overrides.group = null;\n  }\n\n  if (Object.keys(overrides).length) {\n    currentView.current = { ...view, ...overrides };\n  }\n\n  reordering.current = true;\n};\n\n/**\n * Enter or exit bulk edit mode. The pending edits are discarded either way: on entering, so the\n * mode starts afresh, and on exiting, whether they have been saved or cancelled. Unlike reorder\n * mode, the view is kept as it is, so the user can pick the entries to edit by filtering the list\n * first.\n * @param {boolean} value Whether to enter bulk edit mode.\n */\nexport const setBulkEditMode = (value) => {\n  bulkEdits.current = {};\n  bulkEditErrors.current = {};\n  bulkEditedEntries.current = [];\n  bulkEditing.current = value;\n};\n\n// Restore the view settings when a different entry collection is selected. The entries are also\n// tracked, because the available sort keys depend on them. While the collection is being reordered,\n// the saved view is the one from before reordering, which exiting the mode restores, so a change to\n// the entries, like an asset upload or the commit metadata arriving, mustn’t restore it midway. The\n// snapshot is only there in reorder mode, and switching collections discards it after this runs\ncreateRootEffect(() => {\n  const collection = selectedCollection.current;\n  const { current: _allEntries } = allEntries;\n\n  if (collection?._type === 'entry') {\n    untrack(() => {\n      if (viewBeforeReorder.current?.collectionName !== collection.name) {\n        restoreView(collection, _allEntries);\n      }\n    });\n  }\n});\n\n// Keep the time-based view filters and groups up to date. The time is reset as soon as such a\n// condition is applied, as the last tick may date from long ago\ncreateRootEffect(() => {\n  if (!viewUsesTime.current) {\n    return undefined;\n  }\n\n  viewTime.current = new Date();\n\n  const timer = setInterval(() => {\n    viewTime.current = new Date();\n  }, VIEW_TIME_INTERVAL);\n\n  return () => {\n    clearInterval(timer);\n  };\n});\n\ncreateRootEffect(() => {\n  const { current: _backend } = backend;\n\n  if (_backend && !untrack(() => entryListSettings.current)) {\n    initSettings(_backend);\n  }\n});\n\n// Clear the selection when the listed entries or the filters change, so it never includes an entry\n// the current view hides, which a bulk action like Delete would otherwise apply to\ncreateRootEffect(() => {\n  const entries = listedEntries.current;\n\n  void filterConditions.current;\n  selectedEntries.current = [];\n\n  if (untrack(() => prefs.devModeEnabled)) {\n    // eslint-disable-next-line no-console\n    console.info('listedEntries', entries);\n  }\n});\n\n// Drop the entries the view no longer shows from the selection, e.g. an event that a `{{now}}`\n// filter hides as time goes by, which doesn’t change the listed entries or the filters. The shown\n// entries are only computed while something is selected, as nothing else may need them\ncreateRootEffect(() => {\n  const selected = selectedEntries.current;\n\n  if (!selected.length) {\n    return;\n  }\n\n  const { current: shown } = shownEntries;\n\n  if (selected.some((entry) => !shown.has(entry))) {\n    selectedEntries.current = selected.filter((entry) => shown.has(entry));\n  }\n});\n\ncreateRootEffect(() => {\n  const collection = selectedCollection.current;\n\n  // Reset the reorder and bulk edit states when switching collections, to avoid accidentally saving\n  // entries in the wrong collection or leaving the UI in a broken state if the new collection\n  // doesn’t support the mode. Discard any view snapshot first so it isn’t restored against the\n  // wrong collection, which would otherwise corrupt the new collection’s persisted view via\n  // `entryListSettings`.\n  untrack(() => {\n    viewBeforeReorder.current = undefined;\n\n    if (reordering.current) {\n      setReorderMode(false);\n    }\n\n    if (bulkEditing.current) {\n      setBulkEditMode(false);\n    }\n  });\n\n  if (collection && untrack(() => prefs.devModeEnabled)) {\n    // eslint-disable-next-line no-console\n    console.info('selectedCollection', collection);\n  }\n});\n","import { getAssetByPath } from '$lib/services/assets';\nimport {\n  createPendingFileAdder,\n  getAssetFile,\n  rewriteAssetReferences,\n} from '$lib/services/assets/copy';\nimport { getOwnedEntryFolderPath } from '$lib/services/assets/entry-folder';\nimport { getAssetFoldersByPath } from '$lib/services/assets/folders';\nimport { getDraftFieldArgs, getField, getTypedKeyPath } from '$lib/services/contents/entry/fields';\nimport { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\nimport { MEDIA_FIELD_TYPES, RICH_TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { getFieldAssetFolder } from '$lib/services/contents/fields/file/helpers';\nimport { getValueFormat } from '$lib/services/contents/fields/rich-text';\nimport { getEntryAssetVersion } from '$lib/services/workflow/assets';\n\n/**\n * @import {\n * AssetFolderInfo,\n * EntryDraft,\n * EntryFileMap,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * LocaleContentMap,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, MarkdownField, RichTextField } from '$lib/types/public';\n */\n\n/**\n * Field types whose value can reference an asset.\n * @type {string[]}\n */\nconst ASSET_FIELD_TYPES = [...MEDIA_FIELD_TYPES, ...RICH_TEXT_FIELD_TYPES];\n\n/**\n * Copy the original entry’s own assets into a duplicate of the entry. Assets stored at an\n * entry-relative path are referenced with a path relative to the entry, so a duplicate saved in a\n * folder of its own, like a Hugo page bundle, would point at files that don’t exist there. Each\n * such asset is turned into a pending upload cached in the draft, and the references to it in the\n * given values are replaced with the blob URL of the copy, the same as if the user had picked the\n * file for the field, so saving the duplicate writes the copy alongside it. Assets in a folder the\n * entry shares with the rest of the collection are left alone, because the duplicate is saved there\n * as well and the references keep resolving.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft of the original entry.\n * @param {LocaleContentMap} args.currentValues Detached copies of the draft values, to be used for\n * the duplicate. Updated in place.\n * @returns {Promise<EntryFileMap>} Copied files, keyed by blob URL, to be added to the duplicate.\n */\nexport const copyEntryRelativeAssets = async ({ draft, currentValues }) => {\n  const { originalEntry: entry, collection, collectionName, fileName, isIndexFile } = draft;\n  /** @type {EntryFileMap} */\n  const files = {};\n\n  if (!entry) {\n    return files;\n  }\n\n  const { defaultLocale } = draft;\n  const entryFilePath = getEntryLocaleFile(entry, { defaultLocale })?.path;\n  const ownsFolder = !!entryFilePath && !!getOwnedEntryFolderPath(collection, entryFilePath);\n  // Copies are keyed by asset path, so an asset referenced more than once, from another locale or\n  // field, is copied once and shares the blob URL\n  const addPendingFile = createPendingFileAdder({ files });\n\n  /**\n   * Copy the asset referenced by the given value, if it’s the entry’s own.\n   * @param {object} args Arguments.\n   * @param {string} args.value Field value or image source: an asset path relative to the entry.\n   * @param {AssetFolderInfo} args.folder Folder the field saves a new file to.\n   * @param {TypedFieldKeyPath} args.typedKeyPath Typed key path of the field.\n   * @param {InternalLocaleCode} args.locale Locale the value is found in, which the path is\n   * relative to.\n   * @returns {Promise<string | undefined>} Blob URL of the copy, or `undefined` if there’s nothing\n   * to copy.\n   */\n  const copyAsset = async ({ value, folder, typedKeyPath, locale }) => {\n    // Only the version the source entry has: another pull request’s file isn’t copied along\n    const asset = getEntryAssetVersion(\n      getAssetByPath({ value, entry, collectionName, fileName, typedKeyPath, locale }),\n      entry,\n    );\n\n    if (!asset) {\n      return undefined;\n    }\n\n    if (\n      !getAssetFoldersByPath(asset.path).some(\n        (f) => f.collectionName === collectionName && f.fileName === fileName && f.entryRelative,\n      )\n    ) {\n      return undefined;\n    }\n\n    return addPendingFile(\n      asset.path,\n      async () => {\n        try {\n          return await getAssetFile(asset);\n        } catch {\n          // The reference is left as is, pointing at the original’s file, rather than failing the\n          // whole duplication\n          return undefined;\n        }\n      },\n      folder,\n    );\n  };\n\n  /**\n   * Copy the assets referenced by a field, and update its value.\n   * @param {object} args Arguments.\n   * @param {FlattenedEntryContent} args.valueMap Values of one locale.\n   * @param {InternalLocaleCode} args.locale Locale of the values.\n   * @param {FieldKeyPath} args.keyPath Key path of the field.\n   */\n  const copyFieldAssets = async ({ valueMap, locale, keyPath }) => {\n    const value = valueMap[keyPath];\n\n    if (typeof value !== 'string' || !value) {\n      return;\n    }\n\n    const getFieldArgs = getDraftFieldArgs(draft, { valueMap, keyPath });\n    const field = getField(getFieldArgs);\n    const { widget: fieldType = 'string' } = field ?? {};\n\n    if (!ASSET_FIELD_TYPES.includes(fieldType)) {\n      return;\n    }\n\n    const typedKeyPath = getTypedKeyPath(getFieldArgs);\n    // Where the field editor puts a newly picked file, so the copy ends up in the same place\n    const folder = getFieldAssetFolder({ collectionName, fileName, typedKeyPath, isIndexFile });\n\n    // The asset location is the entry’s own only if the entry has a folder of its own, or the\n    // folder is named after the entry with a template tag like `{{slug}}`. Otherwise the folder is\n    // shared with the rest of the collection, and the duplicate can keep referencing the asset.\n    // There’s no folder at all if only an external media library is configured\n    if (!folder?.entryRelative || !(ownsFolder || folder.hasTemplateTags)) {\n      return;\n    }\n\n    // The format is that of the Markdown or HTML body, where images and other media are embedded\n    const format = MEDIA_FIELD_TYPES.includes(fieldType)\n      ? undefined\n      : getValueFormat(/** @type {MarkdownField | RichTextField} */ (field));\n\n    // The value is replaced once every copy is ready\n    const newValue = await rewriteAssetReferences({\n      value,\n      format,\n      /**\n       * Copy the asset the reference points at.\n       * @param {string} src Reference.\n       * @returns {Promise<string | undefined>} Blob URL of the copy.\n       */\n      rewrite: (src) => copyAsset({ value: src, folder, typedKeyPath, locale }),\n    });\n\n    if (newValue !== undefined) {\n      valueMap[keyPath] = newValue;\n    }\n  };\n\n  await Promise.all(\n    Object.entries(currentValues).flatMap(([locale, valueMap]) =>\n      Object.keys(valueMap).map((keyPath) => copyFieldAssets({ valueMap, locale, keyPath })),\n    ),\n  );\n\n  return files;\n};\n","import { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { getEntryDirPath, getSharedEntryFileName } from '$lib/services/contents/collection/nested';\nimport { STATIC_DRAFT_KEYS } from '$lib/services/contents/draft';\nimport { getSlugEditorProp } from '$lib/services/contents/draft/create';\nimport { copyEntryRelativeAssets } from '$lib/services/contents/draft/create/duplicate-assets';\nimport { createProxy } from '$lib/services/contents/draft/create/proxy.svelte';\nimport {\n  fillUuidValues,\n  getRenewedUniqueValue,\n} from '$lib/services/contents/draft/create/unique-values';\nimport { showDuplicateToast } from '$lib/services/contents/editor';\nimport { getAliasesKey, removeAliases } from '$lib/services/contents/entry/aliases';\nimport { getDraftFieldArgs, getField } from '$lib/services/contents/entry/fields';\nimport { getInitialValue as getInitialUuidValue } from '$lib/services/contents/fields/uuid/helpers';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\nimport { isDuplicatedField } from '$lib/services/contents/i18n/shared-values';\nimport { createState, getSnapshot } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n * @import {\n * EntryDraft,\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalLocaleCode,\n * LocaleContentMap,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, HiddenField, UuidField } from '$lib/types/public';\n */\n\n/**\n * Find the Hidden field the given key path belongs to. A Hidden field takes a value of any shape,\n * and an object or array value is flattened into key paths below the field’s own, like `tags.0`,\n * which no field configuration describes, so look for the field along the key path from the top.\n * @param {GetFieldArgs} args Arguments.\n * @returns {{ fieldConfig: HiddenField, keyPath: FieldKeyPath } | undefined} The field and its key\n * path, or `undefined` if the key path doesn’t belong to a Hidden field.\n */\nconst findHiddenField = ({ keyPath, ...getFieldArgs }) => {\n  const segments = keyPath.split('.');\n\n  for (let length = 1; length <= segments.length; length += 1) {\n    const parentKeyPath = segments.slice(0, length).join('.');\n    const fieldConfig = getField({ ...getFieldArgs, keyPath: parentKeyPath });\n\n    if (fieldConfig?.widget === 'hidden') {\n      return { fieldConfig: /** @type {HiddenField} */ (fieldConfig), keyPath: parentKeyPath };\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Reset the values of a locale that must be unique to each entry: remove the canonical slug, the\n * URL aliases and the manual sort order, and give the UUID, Compute and Hidden fields new values.\n * The value map is modified in place.\n * @param {object} args Arguments.\n * @param {Omit<GetFieldArgs, 'valueMap' | 'keyPath'>} args.getFieldArgs Arguments for\n * `getField()`, without the value map and the key path.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {InternalLocaleCode} args.defaultLocale Default locale code.\n * @param {FlattenedEntryContent} args.valueMap Detached copy of the locale’s values.\n * @param {string} args.canonicalSlugKey Property name of the canonical slug.\n * @param {string | undefined} args.aliasesKey Property name of the entry’s URL aliases.\n * @param {string | undefined} args.orderFieldKey Property name of the entry order field.\n * @returns {{ duplicatedHiddenKeyPaths: Set<FieldKeyPath>, clearedUuidFields: Map<FieldKeyPath,\n * UuidField> }} Key paths of the duplicated Hidden fields, which take the default locale’s new\n * values once those are in place, and the duplicated UUID fields cleared for the same reason, along\n * with their configuration. Both are only populated in a non-default locale.\n */\nexport const resetUniqueValues = ({\n  getFieldArgs: baseGetFieldArgs,\n  locale,\n  defaultLocale,\n  valueMap,\n  canonicalSlugKey,\n  aliasesKey,\n  orderFieldKey,\n}) => {\n  /** @type {Set<FieldKeyPath>} */\n  const duplicatedHiddenKeyPaths = new Set();\n  /** @type {Map<FieldKeyPath, UuidField>} */\n  const clearedUuidFields = new Map();\n\n  // Remove the canonical slug\n  delete valueMap[canonicalSlugKey];\n\n  // Remove any redirects from the original entry’s previous paths, which must not be claimed by\n  // more than one entry\n  removeAliases(valueMap, aliasesKey);\n\n  // Drop the manual sort order; a fresh value will be assigned at save time so the duplicate gets a\n  // unique order even after backup/restore round trips\n  if (orderFieldKey) {\n    delete valueMap[orderFieldKey];\n  }\n\n  const getFieldArgs = { ...baseGetFieldArgs, valueMap };\n  /** @type {Map<FieldKeyPath, HiddenField>} */\n  const hiddenFields = new Map();\n\n  // Reset some unique values\n  Object.keys(valueMap).forEach((keyPath) => {\n    const hidden = findHiddenField({ ...getFieldArgs, keyPath });\n    const fieldConfig = hidden?.fieldConfig ?? getField({ ...getFieldArgs, keyPath });\n\n    if (!fieldConfig) {\n      return;\n    }\n\n    if (locale === defaultLocale || isFieldTranslatable(fieldConfig.i18n)) {\n      if (hidden) {\n        // An object or array value is flattened into key paths below the field’s own, e.g.\n        // `tags.0`, which are replaced along with it once all the old values are gone\n        delete valueMap[keyPath];\n        hiddenFields.set(hidden.keyPath, hidden.fieldConfig);\n      } else {\n        valueMap[keyPath] = getRenewedUniqueValue({\n          fieldConfig,\n          keyPath,\n          value: valueMap[keyPath],\n          locale,\n          defaultLocale,\n        });\n      }\n    } else if (\n      // A duplicated field takes the default locale’s new value, once that’s in place. A Compute\n      // field is left alone, as the default locale’s new value is copied to it, so every locale\n      // shares the same UUIDs\n      (hidden || fieldConfig.widget === 'uuid') &&\n      isDuplicatedField({\n        fieldConfig,\n        getFieldArgs: { ...getFieldArgs, keyPath: hidden?.keyPath ?? keyPath },\n      })\n    ) {\n      if (hidden) {\n        delete valueMap[keyPath];\n        duplicatedHiddenKeyPaths.add(hidden.keyPath);\n      } else {\n        // Cleared for `fillUuidValues()` to copy the default locale’s new value\n        valueMap[keyPath] = '';\n        clearedUuidFields.set(keyPath, /** @type {UuidField} */ (fieldConfig));\n      }\n    }\n  });\n\n  // Fill in the defaults once all the old values are gone, so a key path that comes after its own\n  // items, like `tags` after `tags.0`, doesn’t take the default away again\n  hiddenFields.forEach((fieldConfig, keyPath) => {\n    valueMap[keyPath] = getRenewedUniqueValue({ fieldConfig, keyPath, locale, defaultLocale });\n  });\n\n  return { duplicatedHiddenKeyPaths, clearedUuidFields };\n};\n\n/**\n * Give the duplicated fields in the non-default locales the default locale’s new values, once\n * {@link resetUniqueValues} has run for every locale. The content map is modified in place.\n * @param {object} args Arguments.\n * @param {LocaleContentMap} args.currentValues Detached copies of the values of every locale.\n * @param {InternalLocaleCode} args.defaultLocale Default locale code.\n * @param {Omit<GetFieldArgs, 'valueMap' | 'keyPath'>} args.getFieldArgs Arguments for\n * `getField()`, without the value map and the key path.\n * @param {Map<InternalLocaleCode, Set<FieldKeyPath>>} args.duplicatedHiddenFieldMap Key paths of\n * the duplicated Hidden fields in each non-default locale.\n * @param {Map<InternalLocaleCode, Map<FieldKeyPath, UuidField>>} args.clearedUuidFieldMap\n * Duplicated UUID fields cleared in each non-default locale, along with their configuration.\n */\nexport const propagateDuplicatedValues = ({\n  currentValues,\n  defaultLocale,\n  getFieldArgs,\n  duplicatedHiddenFieldMap,\n  clearedUuidFieldMap,\n}) => {\n  const defaultValueMap = currentValues[defaultLocale];\n\n  // A duplicated field holds the same value in every locale, so the other locales take the default\n  // locale’s new value rather than keeping the original entry’s or getting one of their own\n  duplicatedHiddenFieldMap.forEach((keyPaths, locale) => {\n    keyPaths.forEach((keyPath) => {\n      if (keyPath in defaultValueMap) {\n        currentValues[locale][keyPath] = structuredClone(defaultValueMap[keyPath]);\n      }\n    });\n  });\n\n  fillUuidValues({ contentMap: currentValues, defaultLocale, getFieldArgs });\n\n  // A list item that only exists in another locale has no default locale’s value to copy, so it\n  // gets a UUID of its own rather than keeping the original entry’s or being left empty\n  clearedUuidFieldMap.forEach((fieldMap, locale) => {\n    fieldMap.forEach((fieldConfig, keyPath) => {\n      if (!currentValues[locale][keyPath]) {\n        currentValues[locale][keyPath] = getInitialUuidValue(fieldConfig);\n      }\n    });\n  });\n};\n\n/**\n * Create the state of the duplicate draft from the original draft, along with the value proxies.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Original draft, which is discarded.\n * @param {LocaleContentMap} args.currentValues Reset values of the duplicate.\n * @param {EntryDraft['files']} args.files Files of the duplicate.\n * @returns {EntryDraft} New draft.\n */\nexport const createDuplicateDraftState = ({ draft, currentValues, files }) => {\n  const { collection, collectionFile, currentPath } = draft;\n\n  const duplicatePath =\n    currentPath !== undefined && getSharedEntryFileName(collection)\n      ? getEntryDirPath(currentPath)\n      : currentPath;\n\n  // The original draft is discarded, so the rest of its state can be carried over as is\n  /** @type {EntryDraft} */\n  const newDraft = createState(\n    {\n      ...draft,\n      id: crypto.randomUUID(),\n      createdAt: Date.now(),\n      isNew: true,\n      originalEntry: undefined,\n      originalSlugs: {},\n      currentSlugs: {},\n      // The duplicate is filed alongside the original, not inside it. Where every entry owns a\n      // folder, `currentPath` is the original’s own folder, so the copy has to start from its\n      // parent and get a folder of its own there\n      originalPath: duplicatePath,\n      currentPath: duplicatePath,\n      // The duplicate starts from its own values and locales, not the original’s, so that a revert\n      // doesn’t bring back the original’s UUIDs, aliases or asset paths. The draft is new, so it\n      // can still be saved without any change\n      originalLocales: getSnapshot(draft.currentLocales),\n      currentLocales: getSnapshot(draft.currentLocales),\n      originalValues: structuredClone(currentValues),\n      // The value proxies are created below, as they need a reference to the new draft\n      currentValues: {},\n      files,\n      // Reset the validities\n      validities: Object.fromEntries(Object.keys(draft.validities).map((locale) => [locale, {}])),\n      slugEditor: getSlugEditorProp({ collection, collectionFile, originalSlugs: {} }),\n      interacted: false,\n    },\n    STATIC_DRAFT_KEYS,\n  );\n\n  Object.entries(currentValues).forEach(([locale, valueMap]) => {\n    newDraft.currentValues[locale] = createProxy({ draft: newDraft, locale, target: valueMap });\n  });\n\n  return newDraft;\n};\n\n/**\n * Duplicate the entry draft open in the editor, replacing it with the duplicate.\n * @param {EntryDraftState} entryDraft Entry draft state.\n * @returns {Promise<EntryDraft | undefined>} Duplicated draft, or `undefined` if the editor was\n * closed or given another draft while the original’s assets were being copied.\n */\nexport const duplicateDraft = async (entryDraft) => {\n  const draft = /** @type {EntryDraft} */ (entryDraft.current);\n  const { collection, fields } = draft;\n\n  const {\n    defaultLocale,\n    canonicalSlug: { key: canonicalSlugKey },\n  } = getDraftI18nConfig(draft);\n\n  const getFieldArgs = getDraftFieldArgs(draft);\n  const orderFieldKey = getOrderFieldKey(collection);\n  const aliasesKey = getAliasesKey({ collection, fields });\n\n  // Work on detached copies of the values: the duplicate gets value proxies of its own below, and\n  // changing the original draft’s values here would needlessly run their revalidation\n  /** @type {LocaleContentMap} */\n  const currentValues = Object.fromEntries(\n    Object.entries(draft.currentValues).map(([locale, valueMap]) => [\n      locale,\n      getSnapshot(valueMap),\n    ]),\n  );\n\n  /** @type {Map<InternalLocaleCode, Set<FieldKeyPath>>} */\n  const duplicatedHiddenFieldMap = new Map();\n  /** @type {Map<InternalLocaleCode, Map<FieldKeyPath, UuidField>>} */\n  const clearedUuidFieldMap = new Map();\n\n  Object.entries(currentValues).forEach(([locale, valueMap]) => {\n    const { duplicatedHiddenKeyPaths, clearedUuidFields } = resetUniqueValues({\n      getFieldArgs,\n      locale,\n      defaultLocale,\n      valueMap,\n      canonicalSlugKey,\n      aliasesKey,\n      orderFieldKey,\n    });\n\n    duplicatedHiddenFieldMap.set(locale, duplicatedHiddenKeyPaths);\n    clearedUuidFieldMap.set(locale, clearedUuidFields);\n  });\n\n  propagateDuplicatedValues({\n    currentValues,\n    defaultLocale,\n    getFieldArgs,\n    duplicatedHiddenFieldMap,\n    clearedUuidFieldMap,\n  });\n\n  // The original’s own assets have to be copied along with the entry, or the duplicate would\n  // reference files that only exist next to the original\n  // @see https://github.com/sveltia/sveltia-cms/issues/526\n  const files = { ...draft.files, ...(await copyEntryRelativeAssets({ draft, currentValues })) };\n\n  if (entryDraft.current !== draft) {\n    return undefined;\n  }\n\n  const newDraft = createDuplicateDraftState({ draft, currentValues, files });\n\n  entryDraft.current = newDraft;\n  showDuplicateToast.current = true;\n\n  return newDraft;\n};\n","import { backend } from '$lib/services/backends';\nimport { compareEntries } from '$lib/services/contents/draft/save/conflict';\nimport { getUnpublishedEntryByDraft } from '$lib/services/workflow';\nimport { reloadUnpublishedEntries } from '$lib/services/workflow/load';\n\n/**\n * @import { EntryDraft, UnpublishedEntry } from '$lib/types/private';\n * @import { EntryConflict } from '$lib/services/contents/draft/save/conflict';\n */\n\n/**\n * Find out whether saving the given workflow draft would overwrite someone else’s change. An\n * entry’s branch is named after the entry, not the editor, so two people working on the same entry\n * share it, and a save goes on top of whatever the branch holds — including a commit made from\n * another tab, from the Git service, or by a colleague who opened the same entry.\n *\n * The branch head is a small request, and only a branch that has moved since this draft’s own last\n * commit costs the reload that reads the entry back. A draft with no pull request yet has nothing\n * to overwrite, as the branch doesn’t exist. If the branch can’t be read, the comparison is\n * skipped and the commit that follows is left to fail on its own if the backend is really down.\n * @param {EntryDraft} draft Draft about to be saved.\n * @returns {Promise<EntryConflict | undefined>} The conflict, if any.\n */\nexport const detectWorkflowConflict = async (draft) => {\n  const { isNew, originalEntry, collectionName, fileName } = draft;\n\n  const { branch, headSHA } =\n    /** @type {UnpublishedEntry | undefined} */ (originalEntry)?.workflow?.pullRequest ?? {};\n\n  const workflow = backend.current?.workflow;\n\n  // Without a head on record there’s nothing to compare, so the save goes ahead rather than\n  // reporting a conflict it can’t describe\n  if (isNew || !originalEntry || !branch || !headSHA || !workflow) {\n    return undefined;\n  }\n\n  /** @type {string | undefined} */\n  let head;\n\n  try {\n    head = await workflow.fetchBranchHead(branch);\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to check the workflow branch for changes.', ex);\n\n    return undefined;\n  }\n\n  if (head === headSHA) {\n    return undefined;\n  }\n\n  // The branch has moved, or gone, so read the pull requests again. A failure leaves the stores as\n  // they were, and the comparison below with nothing to report\n  try {\n    // A reload already in flight may have listed the pull requests before the branch moved\n    await reloadUnpublishedEntries({ fresh: true });\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to reload the unpublished entries.', ex);\n  }\n\n  // A branch that’s gone is what a pull request merged or closed outside the CMS leaves behind. The\n  // reload has taken the pull request off the store, so the save starts a new one rather than\n  // failing on the missing branch, and there’s nothing on the branch to save over\n  if (!head) {\n    return undefined;\n  }\n\n  return compareEntries(\n    originalEntry,\n    getUnpublishedEntryByDraft({ collectionName, fileName, originalEntry }),\n  );\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { callEventHooks } from '$lib/services/api/events';\nimport { getAdditions } from '$lib/services/app/additions';\nimport { isCommitCancelled } from '$lib/services/backends/commit-prompt';\nimport { isPublishingCommit } from '$lib/services/backends/git/shared/integration';\nimport { checkForRemoteChanges } from '$lib/services/backends/refresh';\nimport { saveChanges } from '$lib/services/backends/save';\nimport { getReadonlyMessage, isDraftReadonly } from '$lib/services/config/readonly';\nimport { allEntries } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport {\n  contentUpdatesToast,\n  UPDATE_TOAST_DEFAULT_STATE,\n} from '$lib/services/contents/collection/data';\nimport { buildNestedMoveChanges } from '$lib/services/contents/collection/nested/move';\nimport { cancelBackup, deleteBackup, getBackupSlug } from '$lib/services/contents/draft/backup';\nimport {\n  getNewPendingEntriesByCollection,\n  getReferencedEditedEntries,\n  getReferencedPendingEntries,\n} from '$lib/services/contents/draft/pending-entries';\nimport { buildEntryAssetMoveChanges } from '$lib/services/contents/draft/save/asset-move';\nimport {\n  createSavingEntryData,\n  preparePendingEntryCommit,\n  removeDisabledLocales,\n} from '$lib/services/contents/draft/save/changes';\nimport { detectEntryConflict } from '$lib/services/contents/draft/save/conflict';\nimport { assignSaveTimeValues } from '$lib/services/contents/draft/save/save-time';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { updateComputedValues } from '$lib/services/contents/draft/update/compute';\nimport { isRequiredEnforced } from '$lib/services/contents/draft/validate/required';\nimport { validateAndRevealErrors } from '$lib/services/contents/draft/validate/reveal';\nimport { getEntryKey } from '$lib/services/contents/entry/entry-key';\nimport { clearEntryHistoryCache } from '$lib/services/contents/entry/history';\nimport { buildCascadeChanges } from '$lib/services/contents/entry/relations/cascade/update';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { compareWithLatest } from '$lib/services/contents/fields/relation/quick-add';\nimport {\n  getUnpublishedEntryByDraft,\n  isOrphanedForkDraft,\n  isWorkflowDraft,\n} from '$lib/services/workflow';\nimport { detectWorkflowConflict } from '$lib/services/workflow/conflict';\nimport { saveWorkflowChanges } from '$lib/services/workflow/save';\n\n/**\n * @import {\n * Asset,\n * ChangeResults,\n * CommitOptions,\n * Entry,\n * EntryDraft,\n * EntrySlugVariants,\n * FileChange,\n * InternalCollection,\n * PendingEntry,\n * } from '$lib/types/private';\n * @import { EntryConflict } from '$lib/services/contents/draft/save/conflict';\n */\n\n/**\n * Tell the user the entry has been saved, and whether it’s being published. What the commit is\n * expected to do is recorded by {@link saveChanges}, which every commit to the branch goes through.\n * @param {object} args Arguments.\n * @param {boolean} args.useWorkflow Whether the changes went to a pull request rather than the\n * configured branch.\n * @param {boolean | undefined} args.skipCI Whether to disable automatic deployments for the change.\n * @param {number} args.count Number of entries saved, including any entry rewritten to keep its\n * references to the saved entry up to date.\n */\nconst updateStores = ({ useWorkflow, skipCI, count }) => {\n  contentUpdatesToast.current = {\n    ...UPDATE_TOAST_DEFAULT_STATE,\n    saved: true,\n    // With Editorial Workflow, changes go to a pull request, so nothing is published yet\n    published: !useWorkflow && isPublishingCommit({ skipCI }),\n    count,\n  };\n};\n\n/**\n * Work out the file changes for saving the entry draft, including those of the entries and assets\n * the save takes along. An entry file that can’t be formatted, e.g. in a custom format registered\n * without a formatter, fails the save rather than being written empty.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft to save.\n * @param {EntrySlugVariants} args.slugs Entry slugs.\n * @param {boolean} args.recreate Whether to write the entry anew, because someone else has deleted\n * it since the draft was opened. See {@link createSavingEntryData}.\n * @returns {Promise<{ savingEntry: Entry, changes: FileChange[], savingAssets: Asset[],\n * cascadeEntries: Entry[], movedEntries: Entry[] }>} Saving entry, file changes, assets, and the\n * other entries rewritten in the same commit.\n * @throws {Error} A `saving_failed` error when the changes could not be worked out, with the\n * original error as its `cause`, so the message can be shown to the user.\n */\nconst buildChanges = async ({ draft, slugs, recreate }) => {\n  const { collection, fileName, originalEntry } = draft;\n\n  try {\n    const { savingEntry, changes, savingAssets } = await createSavingEntryData({\n      draft,\n      slugs,\n      recreate,\n    });\n\n    // When the slug has been edited, the entries referencing this one through a Relation field have\n    // to be rewritten in the same commit, or they would be left pointing at an entry that no longer\n    // exists under that name\n    const { changes: cascadeChanges, savingEntries: cascadeEntries } = await buildCascadeChanges({\n      collection,\n      collectionFile: draft.collectionFile,\n      originalEntry,\n      savingEntry,\n    });\n\n    changes.push(...cascadeChanges);\n\n    // Moving an entry in a collection with nested entries takes everything below it to the new\n    // location\n    const { changes: moveChanges, savingEntries: movedEntries } = await buildNestedMoveChanges({\n      collection,\n      originalEntry,\n      savingEntry,\n    });\n\n    changes.push(...moveChanges);\n\n    // Assets stored next to the entry belong to it, so they follow it to its new folder. An entry\n    // someone else has deleted has taken its assets along, so there’s nothing left to move\n    const { changes: assetMoveChanges, savingAssets: movedAssets } =\n      await buildEntryAssetMoveChanges({\n        collection,\n        fileName,\n        originalEntry: recreate ? undefined : originalEntry,\n        savingEntry,\n        changes,\n      });\n\n    changes.push(...assetMoveChanges);\n    savingAssets.push(...movedAssets);\n\n    return {\n      // The locales turned off have served their purpose in the change plan, deleting their files\n      savingEntry: removeDisabledLocales(savingEntry),\n      changes,\n      savingAssets,\n      cascadeEntries,\n      movedEntries,\n    };\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n\n    throw new Error('saving_failed', { cause: ex });\n  }\n};\n\n/**\n * Make sure no one else has changed the existing entries edited from a Relation field since the\n * edits were made, which saving them would undo. With Editorial Workflow, an entry an earlier save\n * has changed in the pull request is compared with its version there. Unlike the entry being\n * edited, such an entry can’t be saved over the change: its edits are only reviewed in the\n * quick-add dialog, which picks up the latest version of the entry when it’s opened again.\n * @param {EntryDraft} draft Draft to save.\n * @param {object} options Options.\n * @param {boolean} options.remoteChecked Whether the repository has just been checked for changes,\n * which then isn’t done again.\n * @throws {Error} A `saving_failed` error naming the entry that has been changed or deleted.\n */\nconst checkPendingEntryConflicts = async (draft, { remoteChecked }) => {\n  // The entries are only read, so they’re not copied\n  const editedEntries = getReferencedEditedEntries(draft);\n\n  if (!editedEntries.length) {\n    return;\n  }\n\n  if (!remoteChecked) {\n    try {\n      await checkForRemoteChanges();\n    } catch (ex) {\n      // eslint-disable-next-line no-console\n      console.error('Failed to check the repository for changes.', ex);\n    }\n  }\n\n  // eslint-disable-next-line no-restricted-syntax\n  for (const { collectionName, entry, baseEntry } of editedEntries) {\n    const conflict = compareWithLatest(draft, /** @type {Entry} */ (baseEntry));\n\n    if (conflict) {\n      const collection = /** @type {InternalCollection} */ (getCollection(collectionName));\n      const name = getEntrySummary(collection, entry);\n\n      // A deleted entry can’t be edited again, so it has to be deselected instead\n      throw new Error('saving_failed', {\n        cause: new Error(\n          _(\n            conflict.type === 'deleted'\n              ? 'relation_field.edit_deleted'\n              : 'relation_field.edit_conflict',\n            { values: { name } },\n          ),\n        ),\n      });\n    }\n  }\n};\n\n/**\n * Make sure the entry draft can be saved: it’s editable, its values are valid, and no one else has\n * changed the entry since the draft was opened, unless the user has said to save over it.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft to save.\n * @param {boolean} args.useWorkflow Whether the changes go to a pull request rather than the\n * configured branch.\n * @param {boolean} args.overwrite Whether to save even if someone else has changed the entry.\n * @param {boolean} args.publish Whether the entry is published along with the save, in which case\n * its required fields have to be filled in, even if it’s a workflow draft.\n * @returns {Promise<EntryConflict | undefined>} Conflict found, if any, which the save overwrites.\n * @throws {Error} When the entry is read-only, comes from a contributor’s pull request that is no\n * longer open, could not be validated, or would overwrite someone else’s change.\n */\nconst checkSavable = async ({ draft, useWorkflow, overwrite, publish }) => {\n  // The editor offers no way to save a read-only entry, but make sure nothing is written anyway\n  if (isDraftReadonly(draft)) {\n    const { collection, collectionFile } = draft;\n\n    throw new Error('saving_failed', {\n      cause: new Error(getReadonlyMessage('entry', { collection, collectionFile })),\n    });\n  }\n\n  if (isOrphanedForkDraft(draft)) {\n    throw new Error('saving_failed', { cause: new Error(_('workflow.fork_entry_gone')) });\n  }\n\n  // Wait for what was just typed to reach the draft first. Otherwise a save right after typing\n  // would validate the field’s previous value, e.g. an empty required field, and the error would\n  // clear itself moments later\n  const enforceRequired = publish || isRequiredEnforced(draft);\n\n  if (!(await validateAndRevealErrors({ draft, enforceRequired }))) {\n    throw new Error('validation_failed');\n  }\n\n  // Bring the site data up to date before the changes are worked out from it, and refuse to save\n  // over someone else’s change to this entry unless the user has said so. A workflow draft is\n  // compared with its own branch instead of the configured one: the branch is named after the\n  // entry, not the editor, so a colleague working on the same entry writes to it too\n  const conflict = useWorkflow\n    ? await detectWorkflowConflict(draft)\n    : await detectEntryConflict(draft);\n\n  if (conflict && !overwrite) {\n    throw new Error('save_conflict', { cause: conflict });\n  }\n\n  // `detectEntryConflict()` checks the repository for an existing entry saved on the branch\n  await checkPendingEntryConflicts(draft, {\n    remoteChecked: !useWorkflow && !draft.isNew && !!draft.originalEntry,\n  });\n\n  return conflict;\n};\n\n/**\n * Prepare the commit of the entries created from a Relation field that the entry draft refers to.\n * They go into the same commit as the entry referring to them, so neither can end up without the\n * other.\n * @param {EntryDraft} draft Draft to save.\n * @returns {Promise<PendingEntry[]>} Pending entries, with their file changes and assets.\n */\nconst preparePendingEntries = async (draft) => {\n  /** @type {PendingEntry[]} */\n  const pendingEntries = [];\n\n  // Call the `preSave` event hooks one entry after another, like for the hooks of a single entry\n  // eslint-disable-next-line no-restricted-syntax\n  for (const pendingEntry of getReferencedPendingEntries(draft)) {\n    // eslint-disable-next-line no-await-in-loop\n    pendingEntries.push(await preparePendingEntryCommit(pendingEntry));\n  }\n\n  return pendingEntries;\n};\n\n/**\n * Commit the file changes, to a pull request or the configured branch.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft to save.\n * @param {boolean} args.useWorkflow Whether the changes go to a pull request rather than the\n * configured branch.\n * @param {FileChange[]} args.changes File changes.\n * @param {Entry} args.savingEntry Entry to save.\n * @param {Entry[]} args.otherSavingEntries Other entries rewritten or created in the same commit.\n * @param {PendingEntry[]} args.pendingEntries Entries created from a Relation field, among the\n * other entries. With Editorial Workflow, they ride along in the entry’s pull request.\n * @param {Asset[]} args.savingAssets Assets to save.\n * @param {CommitOptions} args.options Commit options.\n * @returns {Promise<ChangeResults>} Results.\n * @throws {Error} A `saving_failed` error when the changes could not be saved, with the original\n * error as its `cause`, or the cancellation error when the user has cancelled the commit.\n */\nconst commitChanges = async ({\n  draft,\n  useWorkflow,\n  changes,\n  savingEntry,\n  otherSavingEntries,\n  pendingEntries,\n  savingAssets,\n  options,\n}) => {\n  const { collectionName, fileName, originalEntry } = draft;\n\n  try {\n    return useWorkflow\n      ? await saveWorkflowChanges({\n          changes,\n          savingEntry,\n          savingAssets,\n          options,\n          collectionName,\n          fileName,\n          // The slug the entry goes by, which is its path within the collection folder in a nested\n          // collection, so an entry doesn’t take the branch of another with the same file name\n          slug: savingEntry.slug,\n          originalEntry,\n          companions: pendingEntries.map(({ collectionName: name, entry, baseEntry }) => ({\n            collectionName: name,\n            entry,\n            // A new entry an earlier save has committed to the pull request can be edited again\n            // too, but it’s still a new one\n            ...(baseEntry && allEntries.current.some(({ id }) => id === entry.id)\n              ? { edited: true }\n              : {}),\n          })),\n        })\n      : await saveChanges({\n          changes,\n          savingEntries: [savingEntry, ...otherSavingEntries],\n          savingAssets,\n          options,\n        });\n  } catch (/** @type {any} */ ex) {\n    // Nothing has been saved if the user has cancelled the commit, which is not a failure\n    if (isCommitCancelled(ex)) {\n      throw ex;\n    }\n\n    // eslint-disable-next-line no-console\n    console.error(ex.cause ?? ex);\n\n    throw new Error('saving_failed', { cause: ex.cause ?? ex });\n  }\n};\n\n/**\n * Clean up after the entry draft has been saved: delete its backup, call the `postSave` event\n * hooks and tell the user.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Saved draft.\n * @param {Entry} args.savingEntry Saved entry.\n * @param {PendingEntry[]} args.pendingEntries Entries created from a Relation field, saved along.\n * @param {boolean} args.useWorkflow Whether the changes went to a pull request.\n * @param {boolean | undefined} args.skipCI Whether automatic deployments were disabled.\n * @param {number} args.count Number of entries saved.\n */\nconst finishSave = async ({ draft, savingEntry, pendingEntries, useWorkflow, skipCI, count }) => {\n  const { isNew, collection, collectionName, originalEntry } = draft;\n\n  // Delete the backup as soon as the changes are saved. A dev server that watches the content files\n  // may reload the page right after they’re written, e.g. Eleventy, and a backup that outlives the\n  // save would then offer to restore a draft that has already been saved. The changes are saved\n  // already, so a backup that can’t be deleted doesn’t fail the save. The backup is stored under\n  // the path the entry had when it was opened, which a rename leaves behind. A backup scheduled for\n  // a change made just before the save is dropped as well: the editor may stay open on the saved\n  // draft for a while, e.g. while asking whether to send it for review, and the backup made then\n  // would take the place of the one deleted here and be offered the next time the entry is opened\n  cancelBackup();\n\n  try {\n    await deleteBackup(collectionName, getBackupSlug(draft));\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  }\n\n  await callEventHooks({\n    type: 'postSave',\n    entry: savingEntry,\n    collection,\n    collectionFile: draft.collectionFile,\n    isNew,\n  });\n\n  await Promise.all(\n    pendingEntries.map(({ collectionName: pendingCollectionName, entry, baseEntry }) =>\n      callEventHooks({\n        type: 'postSave',\n        entry,\n        collection: /** @type {InternalCollection} */ (getCollection(pendingCollectionName)),\n        isNew: !baseEntry,\n      }),\n    ),\n  );\n\n  updateStores({ useWorkflow, skipCI, count });\n\n  [originalEntry, ...pendingEntries.map(({ baseEntry }) => baseEntry)].forEach((entry) => {\n    if (entry) {\n      clearEntryHistoryCache(entry.id);\n    }\n  });\n\n  // Comments kept by Sveltia CMS Additions follow an entry whose slug or path has changed. It runs\n  // in the background, as the save is done\n  if (originalEntry && originalEntry.subPath !== savingEntry.subPath) {\n    getAdditions()?.moveEntryConversation(\n      getEntryKey(collectionName, originalEntry.subPath),\n      getEntryKey(collectionName, savingEntry.subPath),\n    );\n  }\n};\n\n/**\n * Save the entry draft.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Draft to save.\n * @param {boolean} [args.skipCI] Whether to disable automatic deployments for the change.\n * @param {boolean} [args.overwrite] Whether to save even if someone else has changed the entry\n * since the draft was opened. Without it, such a save is refused with a `save_conflict` error whose\n * `cause` is the conflict found by {@link detectEntryConflict}, so the user can be asked first.\n * An entry stored in a file with the other entries of the collection is still refused if its item\n * has changed, as it’s told by its position, and the item at the position may now be another entry\n * that has moved there.\n * @param {boolean} [args.publish] Whether to publish the entry along with the save, bypassing the\n * review: see the `direct_publish` publish mode option. A workflow draft without a pull request is\n * then committed straight to the configured branch. One with a pull request is still saved to it,\n * as the pull request may hold earlier changes too, and it’s up to the caller to merge it.\n * @returns {Promise<Entry>} Saved entry.\n * @throws {Error} When the entry is read-only, could not be validated or saved, or would overwrite\n * someone else’s change.\n */\nexport const saveEntry = async ({\n  draft,\n  skipCI = undefined,\n  overwrite = false,\n  publish = false,\n}) => {\n  // A collection can opt in or out of Editorial Workflow on its own, but an entry that already has\n  // a pull request stays in it\n  const useWorkflow = publish ? !!getUnpublishedEntryByDraft(draft) : isWorkflowDraft(draft);\n  const conflict = await checkSavable({ draft, useWorkflow, overwrite, publish });\n\n  // The entries added to the same collection from a Relation field have already taken the orders\n  // and numbers after the highest ones, so the new entry comes after them\n  assignSaveTimeValues(draft, getNewPendingEntriesByCollection(draft, draft.collectionName).length);\n  // The values are copied for the save right away, while the Compute fields are otherwise only\n  // resolved again by the editor later, so resolve them now: one can refer to a value assigned\n  // above, e.g. `INV-{{fields.number}}` with an auto-increment `number`\n  updateComputedValues(draft);\n\n  const slugs = getSlugs({ draft });\n  // Saving over a deletion writes the entry anew, as its files and the assets stored with it are\n  // gone\n  const recreate = conflict?.type === 'deleted';\n\n  const { savingEntry, changes, savingAssets, cascadeEntries, movedEntries } = await buildChanges({\n    draft,\n    slugs,\n    recreate,\n  });\n\n  const pendingEntries = await preparePendingEntries(draft);\n\n  changes.push(...pendingEntries.flatMap((pendingEntry) => pendingEntry.changes));\n  savingAssets.push(...pendingEntries.flatMap((pendingEntry) => pendingEntry.savingAssets));\n\n  const results = await commitChanges({\n    draft,\n    useWorkflow,\n    changes,\n    savingEntry,\n    otherSavingEntries: [\n      ...cascadeEntries,\n      ...movedEntries,\n      ...pendingEntries.map((pendingEntry) => pendingEntry.entry),\n    ],\n    pendingEntries,\n    savingAssets,\n    options: {\n      commitType: draft.isNew || recreate ? 'create' : 'update',\n      collection: draft.collection,\n      skipCI,\n    },\n  });\n\n  await finishSave({\n    draft,\n    savingEntry,\n    pendingEntries,\n    useWorkflow,\n    skipCI,\n    count: 1 + cascadeEntries.length + movedEntries.length + pendingEntries.length,\n  });\n\n  return results.savedEntries[0];\n};\n","import { isLockedFork } from '$lib/services/workflow/forks';\n\n/**\n * @import { ForkHead, InternalCollection, InternalCollectionFile } from '$lib/types/private';\n * @import { EntryConflict } from '$lib/services/contents/draft/save/conflict';\n */\n\n/**\n * Check whether the entry being edited can be duplicated from the editor options menu.\n * @param {object} args Arguments.\n * @param {InternalCollection} [args.collection] Collection the entry belongs to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file, if the entry is one. A\n * collection file is part of the collection definition, so it can’t be duplicated.\n * @param {boolean} args.isIndexFile Whether the entry is the index file of a collection with nested\n * entries.\n * @param {boolean} args.readonly Whether the entry is read-only.\n * @param {boolean} args.creationDisabled Whether creating new entries is currently disabled.\n * @returns {boolean} Result.\n */\nexport const canDuplicateEntry = ({\n  collection,\n  collectionFile,\n  isIndexFile,\n  readonly,\n  creationDisabled,\n}) =>\n  !readonly &&\n  !collectionFile &&\n  !isIndexFile &&\n  !(collection?._type === 'entry' && collection.duplicate === false) &&\n  !creationDisabled;\n\n/**\n * Get which of the menu items that take the entry being edited off the site are offered.\n * @param {object} args Arguments.\n * @param {boolean} args.publishedVersionExists Whether the entry has a published version, which\n * means it’s also under review when it has a pull request.\n * @param {boolean} args.canDeleteEntry Whether the user can delete the entry.\n * @param {boolean} args.isCollectionFile Whether the entry is a collection file, which is part of\n * the collection definition, so it can only be discarded.\n * @param {boolean} args.readonly Whether the entry is read-only.\n * @param {boolean} args.locked Whether the entry’s content can’t be changed: it’s read-only, or\n * awaiting deletion.\n * @returns {{ discard: boolean, delete: boolean }} Whether to offer the item that discards the pull\n * request, or deletes an entry that has never been published, and the one that deletes a published\n * entry under review.\n */\nexport const getRemovalMenuItems = ({\n  publishedVersionExists,\n  canDeleteEntry,\n  isCollectionFile,\n  readonly,\n  locked,\n}) => ({\n  discard: !readonly && (publishedVersionExists || (canDeleteEntry && !isCollectionFile)),\n  delete: publishedVersionExists && canDeleteEntry && !isCollectionFile && !locked,\n});\n\n/**\n * How a failed save is reported to the user.\n * @typedef {{ type: 'conflict', conflict: EntryConflict } | { type: 'validation' } |\n * { type: 'error', message: string, unexpected: boolean }} SaveFailure\n */\n\n/**\n * Work out how to report the given error thrown while saving an entry: invalid fields are pointed\n * out, someone else’s change to the entry is left for the user to decide on, and anything else is\n * shown as an error, with the backend’s message if there is one. A server error without a message,\n * e.g. a gateway’s HTML error page, leaves only the generic description, rather than the\n * `saving_failed` key.\n * @param {any} ex Error.\n * @returns {SaveFailure} Report. `unexpected` is `true` for an error that doesn’t come from the\n * save itself, which is worth logging.\n */\nexport const getSaveFailure = (ex) => {\n  if (ex.message === 'validation_failed') {\n    return { type: 'validation' };\n  }\n\n  if (ex.message === 'save_conflict') {\n    return { type: 'conflict', conflict: ex.cause };\n  }\n\n  if (ex.message === 'saving_failed') {\n    return { type: 'error', message: ex.cause?.message ?? '', unexpected: false };\n  }\n\n  return { type: 'error', message: '', unexpected: true };\n};\n\n/**\n * Get what the entry editor toolbar offers for the entry being edited.\n * @param {object} args Arguments.\n * @param {InternalCollection} [args.collection] Collection the entry belongs to.\n * @param {InternalCollectionFile} [args.collectionFile] Collection file, if the entry is one.\n * @param {boolean} args.isIndexFile Whether the entry is the index file of a collection with nested\n * entries.\n * @param {boolean} args.hasPullRequest Whether the entry has a pull request.\n * @param {boolean} args.workflowEnabled Whether the collection uses Editorial Workflow.\n * @param {boolean} args.publishedVersionExists Whether the entry has a published version.\n * @param {boolean} args.discardsDraft Whether deleting the entry just throws the draft away, as it\n * was never published. See `isDiscardableDraft()`.\n * @param {boolean} args.pendingDeletion Whether the entry is awaiting deletion.\n * @param {boolean} args.readonly Whether the entry is read-only.\n * @param {boolean} args.openAuthoring Whether the user is an Open Authoring contributor.\n * @param {ForkHead} [args.fork] Fork the entry’s pull request comes from, if a contributor opened\n * it from their fork.\n * @param {boolean} args.creationDisabled Whether creating new entries is currently disabled.\n * @returns {{ useWorkflow: boolean, discardsDraft: boolean, locked: boolean,\n * canDuplicate: boolean, removalMenuItems: { discard: boolean, delete: boolean },\n * showPublishControl: boolean }} Whether the entry is saved to a pull request, whether deleting it\n * just throws the draft away, whether its content can’t be changed, whether it can be duplicated,\n * which removal menu items are offered, and whether the control to publish the entry, or to review\n * its pull request on the Git service, has a place in the toolbar.\n */\nexport const getEntryToolbarState = ({\n  collection,\n  collectionFile,\n  isIndexFile,\n  hasPullRequest,\n  workflowEnabled,\n  publishedVersionExists,\n  discardsDraft,\n  pendingDeletion,\n  readonly,\n  openAuthoring,\n  fork = undefined,\n  creationDisabled,\n}) => {\n  // A collection can opt in or out of Editorial Workflow with its own `publish_mode` option, but an\n  // entry that already has a pull request stays in it until it’s published or discarded\n  const useWorkflow = hasPullRequest || workflowEnabled;\n  // The `delete` option only blocks taking an entry off the site. Discarding a pull request leaves\n  // the published version untouched, so it stays available even when deletion is disabled\n  const canDelete = !(collection?._type === 'entry' && collection.delete === false);\n  // Taking a published entry off the site is a maintainer’s call. An Open Authoring contributor can\n  // discard their own draft, but not propose the removal of something already live. Nor does a\n  // maintainer propose it in a contributor’s pull request, which they can only close\n  const canDeleteEntry = canDelete && (discardsDraft || (!openAuthoring && !fork));\n  // An entry awaiting deletion is read-only: there’s nothing to save or move through the stages,\n  // only the deletion itself to carry out or call off. An entry in a read-only collection, or a\n  // read-only collection file, can only be viewed: there’s nothing to save, move through the\n  // stages, publish, discard or delete. Neither kind of entry can have its content changed\n  const locked = pendingDeletion || readonly;\n\n  return {\n    useWorkflow,\n    discardsDraft,\n    locked,\n    canDuplicate: canDuplicateEntry({\n      collection,\n      collectionFile,\n      isIndexFile,\n      readonly,\n      creationDisabled,\n    }),\n    // A collection file is part of the collection definition, so it can only be discarded\n    removalMenuItems: getRemovalMenuItems({\n      publishedVersionExists,\n      canDeleteEntry,\n      isCollectionFile: !!collectionFile,\n      readonly,\n      locked,\n    }),\n    // A read-only entry has nothing to publish, except one from a contributor’s pull request that\n    // maintainers can’t push to: it still gets the link to review the pull request on the Git\n    // service, the only place it can be dealt with\n    showPublishControl: hasPullRequest && (!readonly || isLockedFork(fork)),\n  };\n};\n","import { clearSaveProgress, startPreparing } from '$lib/services/backends/commit-progress';\nimport { isCommitCancelled } from '$lib/services/backends/commit-prompt';\nimport { duplicateDraft } from '$lib/services/contents/draft/create/duplicate';\nimport { saveEntry } from '$lib/services/contents/draft/save';\nimport { validateDraft } from '$lib/services/contents/draft/validate';\nimport { countInvalidFields } from '$lib/services/contents/draft/validate/reveal';\nimport { awaitPendingFieldUpdates } from '$lib/services/contents/editor/pending';\nimport { getEntryEditorPath } from '$lib/services/contents/editor/route';\nimport { getSaveFailure } from '$lib/services/contents/editor/toolbar';\nimport { publishWorkflowEntry, updateWorkflowStatus } from '$lib/services/workflow/save';\nimport { getEntryStage, getNextStage } from '$lib/services/workflow/stages';\nimport { getWorkflowErrorMessage } from '$lib/services/workflow/verify';\n\n/**\n * @import { Entry, EntryDraft, UnpublishedEntry, WorkflowStatus } from '$lib/types/private';\n * @import { EntryConflict } from '$lib/services/contents/draft/save/conflict';\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n */\n\n/**\n * What came of saving the entry draft open in the editor, for the toolbar to act on.\n * @typedef {{ type: 'conflict', conflict: EntryConflict } | { type: 'skipped' } |\n * { type: 'saved', savedEntry: Entry, statusError?: string, path?: string,\n * next?: 'close' | 'reset' } | { type: 'invalid', errorCount: number } |\n * { type: 'error', message: string }} SaveOutcome\n * - `skipped`: nothing was saved, because the draft was closed or turned out to be unchanged, or\n * the user cancelled the commit when asked for a commit message.\n * - `saved`: the entry was saved. `statusError` is the message to show when it couldn’t be moved\n * to the next stage, or published after being saved to its pull request. `path` is the URL to\n * replace the `new` route with, for a new entry. `next` says whether to close the editor or reset\n * the draft; neither is done when another draft is now open.\n * - `invalid`: the draft has invalid fields, `errorCount` of them.\n * - `conflict`: someone else has changed the entry since it was opened; the user decides.\n * - `error`: the save failed, with the backend’s message if there is one.\n */\n\n/**\n * Save the entry draft open in the editor, offering to move it to the next review stage afterwards,\n * or publishing it right away if asked, and work out\n * what the editor should do next. The Back button stays available during a save, so the user may\n * have closed the entry, or opened another one, by the time the commit has landed; the editor and\n * the URL then belong to that one and are left alone.\n * @param {object} args Arguments.\n * @param {EntryDraftState} args.entryDraft Entry draft state. Its `current` draft is saved.\n * @param {() => boolean} args.useWorkflow Function that tells whether the entry is saved to a pull\n * request. It’s called once the entry is saved.\n * @param {boolean} [args.skipCI] Whether to disable automatic deployments for the change.\n * @param {boolean} [args.overwrite] Whether to save over someone else’s change to the entry, once\n * the user has been asked.\n * @param {boolean} [args.publish] Whether to publish the entry along with the save, bypassing the\n * review: see the `direct_publish` publish mode option. An entry without a pull request is\n * committed straight to the configured branch, while one with a pull request is saved to it, which\n * is then merged.\n * @param {(stage: WorkflowStatus) => Promise<boolean>} args.askForReview Function that asks whether\n * the entry just saved should be moved to the given stage, e.g. handed over for review, resolving\n * to `true` if the user wants to move it.\n * @param {() => boolean} args.closeOnSave Function that tells whether the editor is to be closed\n * once the entry is saved.\n * @returns {Promise<SaveOutcome>} Outcome.\n */\nexport const saveEntryDraftFlow = async ({\n  entryDraft,\n  useWorkflow,\n  skipCI = undefined,\n  overwrite = false,\n  publish = false,\n  askForReview,\n  closeOnSave,\n}) => {\n  const draft = /** @type {EntryDraft} */ (entryDraft.current);\n  const { isNew, collection, collectionFile } = draft;\n  /**\n   * Check whether the draft being saved is still the one in the editor.\n   * @returns {boolean} Result.\n   */\n  const isDraftOpen = () => entryDraft.current === draft;\n\n  try {\n    // A change still on its way to the draft enabled the button, but may turn out to change\n    // nothing, e.g. a trailing space typed in a rich text editor\n    await awaitPendingFieldUpdates();\n\n    if (!isDraftOpen() || (!isNew && !entryDraft.modified)) {\n      return { type: 'skipped' };\n    }\n\n    startPreparing(Object.keys(draft.files ?? {}).length);\n\n    let savedEntry = await saveEntry({ draft, skipCI, overwrite, publish });\n    const savedDraft = /** @type {UnpublishedEntry} */ (savedEntry);\n    /** @type {string | undefined} */\n    let statusError = undefined;\n\n    // The entry already had a pull request, so the change went there; merging it is what publishes\n    // the change, along with anything saved to the pull request earlier. This is done even when the\n    // editor has been closed meanwhile, as the user has asked for it. A failed merge leaves the\n    // entry saved as a draft, which is reported like a failed status change\n    if (publish && savedDraft.workflow) {\n      try {\n        await publishWorkflowEntry(savedDraft);\n\n        // The entry is now the published one, which the editor is reset to if it stays open\n        const { workflow: _workflow, ...publishedEntry } = savedDraft;\n\n        savedEntry = publishedEntry;\n      } catch (/** @type {any} */ ex) {\n        statusError = getWorkflowErrorMessage(ex, 'workflow.publishing_entry_failed');\n        // eslint-disable-next-line no-console\n        console.error(ex);\n      }\n    }\n\n    if (!isDraftOpen()) {\n      return { type: 'saved', savedEntry, statusError };\n    }\n\n    // Saving with a workflow leaves the entry as a draft, which nothing on screen says: it hasn’t\n    // been handed to anyone yet, and the status menu that would do it is easy to miss. Offer it as\n    // the next step instead, once, while the entry is still in the drafting stage. With Preview\n    // Workflow, there’s no next stage: the entry can be published from the drafting stage\n    const nextStage =\n      !publish && useWorkflow() && savedDraft.workflow\n        ? getNextStage(savedDraft, collection)\n        : undefined;\n\n    if (\n      nextStage &&\n      getEntryStage(savedDraft, collection) === 'draft' &&\n      // An incomplete entry isn’t ready to be handed over; the status menu is still there once the\n      // remaining fields have been filled in. Required fields aren’t enforced while an entry is a\n      // draft, so it may have been saved with some of them empty. The check leaves the editor state\n      // alone: nothing is wrong with the draft as saved, so no errors are shown for it\n      validateDraft({ draft }).valid &&\n      (await askForReview(nextStage))\n    ) {\n      try {\n        await updateWorkflowStatus(savedDraft, nextStage);\n      } catch (/** @type {any} */ ex) {\n        statusError = getWorkflowErrorMessage(ex, 'workflow.status_change_failed');\n        // eslint-disable-next-line no-console\n        console.error(ex);\n      }\n    }\n\n    if (!isDraftOpen()) {\n      return { type: 'saved', savedEntry, statusError };\n    }\n\n    // Update the URL of a new entry. A collection file is addressed by its name, while its\n    // `subPath` is the whole file path. This is done even when the editor is about to be closed, so\n    // the `new` route doesn’t stay in the session history: moving forward from the entry list then\n    // reopens the entry that was just created instead of a blank editor\n    const path = isNew\n      ? getEntryEditorPath(collection.name, collectionFile?.name ?? savedEntry.subPath)\n      : undefined;\n\n    // The entry itself is saved, so a failed status change leaves the editor open rather than\n    // navigating away from something the user may want to retry from the status menu. Otherwise\n    // the draft is reset: the next save compares the draft’s original entry with the branch, so\n    // leaving the pre-save one in place would report the save that just landed as someone else’s\n    // change to the entry\n    const next = closeOnSave() && statusError === undefined ? 'close' : 'reset';\n\n    return { type: 'saved', savedEntry, statusError, path, next };\n  } catch (/** @type {any} */ ex) {\n    // The user has dismissed the commit message prompt; the draft is left as it is to save again\n    if (isCommitCancelled(ex)) {\n      return { type: 'skipped' };\n    }\n\n    const failure = getSaveFailure(ex);\n\n    if (failure.type === 'validation') {\n      return { type: 'invalid', errorCount: countInvalidFields(draft.validities) };\n    }\n\n    if (failure.type === 'conflict') {\n      // Saving over the change saves the draft in the editor, which may now be another one, so the\n      // save is then only reported as failed\n      return isDraftOpen()\n        ? { type: 'conflict', conflict: failure.conflict }\n        : { type: 'error', message: '' };\n    }\n\n    if (failure.unexpected) {\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    }\n\n    return { type: 'error', message: failure.message };\n  } finally {\n    clearSaveProgress();\n  }\n};\n\n/**\n * Duplicate the entry draft open in the editor, replacing it with the duplicate. The original’s own\n * assets are copied along with the entry, so this can take a moment.\n * @param {EntryDraftState} entryDraft Entry draft state.\n * @returns {Promise<string | undefined>} Path of the editor for the duplicate, to replace the URL\n * with, or `undefined` if the editor was closed or given another draft meanwhile.\n */\nexport const duplicateEntryDraft = async (entryDraft) => {\n  const { collectionName } = /** @type {EntryDraft} */ (entryDraft.current);\n\n  return (await duplicateDraft(entryDraft)) ? `/collections/${collectionName}/new` : undefined;\n};\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import {\n    Alert,\n    AlertDialog,\n    Button,\n    ConfirmationDialog,\n    Divider,\n    Menu,\n    MenuButton,\n    MenuItem,\n    Spacer,\n    SplitButton,\n    Toast,\n    Toolbar,\n    TruncatedText,\n  } from '@sveltia/ui';\n\n  import BackButton from '$lib/components/common/page-toolbar/back-button.svelte';\n  import ResetDialog from '$lib/components/contents/details/editor/reset-dialog.svelte';\n  import ResetMenuItems from '$lib/components/contents/details/editor/reset-menu-items.svelte';\n  import ValidationErrorsToast from '$lib/components/contents/details/editor/validation-errors-toast.svelte';\n  import ViewMenuItems from '$lib/components/contents/details/editor/view-menu-items.svelte';\n  import EntryRemoval from '$lib/components/contents/details/entry-removal.svelte';\n  import PreviewLinkButton from '$lib/components/contents/details/preview-link-button.svelte';\n  import SaveConflictDialog from '$lib/components/contents/details/save-conflict-dialog.svelte';\n  import EntryStatusMenu from '$lib/components/workflow/entry-status-menu.svelte';\n  import PublishEntryButton from '$lib/components/workflow/publish-entry-button.svelte';\n  import { getAdditions } from '$lib/services/app/additions';\n  import { getEntryEditorBackPath, goBack, goto, overlayTitle } from '$lib/services/app/navigation';\n  import { saveProgress } from '$lib/services/backends/commit-progress';\n  import { skipCIConfigured, skipCIEnabled } from '$lib/services/backends/git/shared/integration';\n  import { isDraftReadonly } from '$lib/services/config/readonly';\n  import { getCollectionLabel } from '$lib/services/contents/collection';\n  import { getCollectionFileLabel } from '$lib/services/contents/collection/files';\n  import { hasNestedEntries, nestedFilterPath } from '$lib/services/contents/collection/nested';\n  import { collectionState } from '$lib/services/contents/collection/view';\n  import { createDraft } from '$lib/services/contents/draft/create';\n  import { getReferencedPendingEntrySet } from '$lib/services/contents/draft/pending-entries';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { canResetEntry } from '$lib/services/contents/draft/update/reset';\n  import {\n    activeInlineEditors,\n    copyFromLocaleToast,\n    listItemClipboardToast,\n  } from '$lib/services/contents/editor';\n  import { fieldUpdatePending } from '$lib/services/contents/editor/pending';\n  import { createResetMenuState } from '$lib/services/contents/editor/reset-menu.svelte';\n  import { duplicateEntryDraft, saveEntryDraftFlow } from '$lib/services/contents/editor/save';\n  import {\n    getSidebarPanelLabel,\n    getSidebarPanels,\n    showSidebarPanel,\n  } from '$lib/services/contents/editor/sidebar';\n  import { canUpdateSlug } from '$lib/services/contents/editor/slug';\n  import { getEntryToolbarState } from '$lib/services/contents/editor/toolbar';\n  import { getEntryRelativeAssets } from '$lib/services/contents/entry/assets';\n  import { getEntrySummary } from '$lib/services/contents/entry/summary';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n  import { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\n  import { deployPollTimedOut } from '$lib/services/deployments';\n  import { recheckDeployments, retainDeployPolling } from '$lib/services/deployments/poll';\n  import { isSearchResultsPath } from '$lib/services/search/navigation';\n  import { env } from '$lib/services/user/env.svelte';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import {\n    canSkipReviewAlong,\n    checkPublishedVersion,\n    getUnpublishedEntryByDraft,\n    isDirectPublishAllowed,\n    isDiscardableDraft,\n    isOrphanedForkDraft,\n    isPendingDeletion,\n    isWorkflowEnabled,\n    workflowEnabled,\n  } from '$lib/services/workflow';\n  import { getDiscardDialogStrings } from '$lib/services/workflow/dialogs';\n  import { getForkHead } from '$lib/services/workflow/forks';\n  import { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n  /**\n   * @import { EntryConflict } from '$lib/services/contents/draft/save/conflict';\n   * @import { WorkflowStatus } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [disabled] Whether to disable controls other than the Back button.\n   */\n\n  const entryDraft = getEntryDraftContext();\n  // Sveltia CMS Additions, which shows who else has the entry open\n  const additions = $derived(getAdditions());\n\n  /** @type {Props} */\n  let { disabled = false } = $props();\n\n  let showValidationToast = $state(false);\n  // Number of invalid fields when the last save failed validation. A snapshot rather than a live\n  // count: the fields are revalidated as they’re corrected, and a toast counting down to “0 fields\n  // have errors” while it’s still on screen would be confusing\n  let errorCount = $state(0);\n  let showReviewDialog = $state(false);\n  /**\n   * Stage the review prompt offers to move the entry just saved to.\n   * @type {WorkflowStatus | undefined}\n   */\n  let reviewStage = $state();\n  /**\n   * Resolver for the review prompt, so the save can wait for the answer.\n   * @type {((sendForReview: boolean) => void) | undefined}\n   */\n  let resolveReviewPrompt = $state();\n  let showConflictDialog = $state(false);\n  /**\n   * Someone else’s change to the entry that the last save attempt would have overwritten, along\n   * with the options of that attempt, so the save can be repeated as asked once the user agrees.\n   * @type {{ conflict: EntryConflict, skipCI: boolean | undefined, publish: boolean } | undefined}\n   */\n  let saveConflict = $state();\n  let showErrorDialog = $state(false);\n  let errorMessage = $state('');\n  let saving = $state(false);\n  /** Whether the entry being saved is also being published, bypassing the review. */\n  let publishing = $state(false);\n  let deleting = $state(false);\n  /** Whether the entry is being duplicated, which takes a moment when it has assets to copy. */\n  let duplicating = $state(false);\n  /** @type {MenuButton | undefined} */\n  let menuButton = $state();\n  /** @type {EntryRemoval | undefined} */\n  let entryRemoval = $state();\n  const resetMenu = createResetMenuState(() => {\n    const draft = entryDraft.current;\n\n    return {\n      restore: !!draft && canResetEntry({ draft, restore: true }),\n      clear: !!draft && canResetEntry({ draft }),\n    };\n  });\n\n  const notFound = $derived(entryDraft.current === undefined);\n  const isNew = $derived(entryDraft.current?.isNew ?? true);\n  const isIndexFile = $derived(!!entryDraft.current?.isIndexFile);\n  const collection = $derived(entryDraft.current?.collection);\n  const collectionFile = $derived(entryDraft.current?.collectionFile);\n  const originalEntry = $derived(entryDraft.current?.originalEntry);\n  const { defaultLocale } = $derived(getDraftI18nConfig(entryDraft.current));\n  const collectionName = $derived(collection?.name);\n  const fileName = $derived(collectionFile?.name);\n  /* v8 ignore start -- only read for an existing entry, which has a collection */\n  // `appLocale.current` is a key, because `getCollectionLabel` can return a localized label\n  const collectionLabel = $derived(\n    appLocale.current && collection ? getCollectionLabel(collection) : '',\n  );\n  /* v8 ignore stop */\n  const collectionLabelSingular = $derived(\n    // `appLocale.current` is a key, because `getCollectionLabel` can return a localized label\n    appLocale.current && collection ? getCollectionLabel(collection, { useSingular: true }) : '',\n  );\n  /* v8 ignore start -- only read for an existing entry, which has a collection */\n  const entrySummary = $derived(\n    collectionFile\n      ? getCollectionFileLabel(collectionFile)\n      : collection && originalEntry && appLocale.current\n        ? getEntrySummary(collection, originalEntry)\n        : '',\n  );\n  /* v8 ignore stop */\n  // Heading of the toolbar, also used as the document title while the editor is open\n  const title = $derived(\n    notFound\n      ? ''\n      : isNew\n        ? _('create_entry_title', { values: { name: collectionLabelSingular } })\n        : `${collectionLabel} › ${entrySummary}`,\n  );\n\n  $effect(() => {\n    overlayTitle.current = title;\n\n    return () => {\n      overlayTitle.current = '';\n    };\n  });\n  // Saving, deleting or duplicating takes a moment and navigates away when it’s done, so the whole\n  // control group is locked meanwhile rather than just the button that started it\n  const busy = $derived(saving || deleting || duplicating);\n  const controlsDisabled = $derived(disabled || busy);\n  // A change still on its way to the draft counts, so a save can be started right after it\n  const modified = $derived(isNew || entryDraft.modified || fieldUpdatePending.current);\n  /* v8 ignore start -- only read in the deletion dialog, which a new entry doesn’t offer */\n  const associatedAssets = $derived(\n    collectionName && originalEntry\n      ? getEntryRelativeAssets({ entry: originalEntry, collectionName, fileName })\n      : [],\n  );\n  /* v8 ignore stop */\n  // Look the entry up in the store rather than using `originalEntry` directly, so the status button\n  // stays in sync when the status is changed elsewhere, e.g. on the Editorial Workflow page\n  const unpublishedEntry = $derived(\n    workflowEnabled.current && collectionName\n      ? getUnpublishedEntryByDraft({ collectionName, fileName, originalEntry })\n      : undefined,\n  );\n  // The entry can be published from another view, so the check depends on `allEntries`\n  const publishedVersionExists = $derived(checkPublishedVersion(unpublishedEntry));\n  const pendingDeletion = $derived(isPendingDeletion(unpublishedEntry));\n  const readonly = $derived(isDraftReadonly(entryDraft.current));\n  const { useWorkflow, discardsDraft, locked, canDuplicate, removalMenuItems, showPublishControl } =\n    $derived(\n      getEntryToolbarState({\n        collection,\n        collectionFile,\n        isIndexFile,\n        hasPullRequest: !!unpublishedEntry,\n        workflowEnabled: isWorkflowEnabled(collection),\n        publishedVersionExists,\n        // Deleting an entry that was never published just throws the draft away; anything else\n        // takes an entry off the site\n        discardsDraft: isDiscardableDraft(unpublishedEntry),\n        pendingDeletion,\n        readonly,\n        openAuthoring: openAuthoring.current,\n        fork: getForkHead(unpublishedEntry),\n        creationDisabled: collectionState.current.creationDisabled,\n      }),\n    );\n  // A workflow draft can also be saved and published in one go, if the publish mode allows it\n  // An entry from a contributor’s pull request that has been merged or closed since has nothing\n  // left to publish, nor to save, which the save refuses\n  const directPublish = $derived(\n    useWorkflow &&\n      !isOrphanedForkDraft(entryDraft.current) &&\n      isDirectPublishAllowed(collection, unpublishedEntry),\n  );\n  // The entries created or edited from the Relation fields would be published along with it, and\n  // one in a collection whose review can’t be skipped would miss its review\n  const directPublishBlocked = $derived(\n    directPublish &&\n      !canSkipReviewAlong([\n        // A deselected entry isn’t saved at all\n        ...(entryDraft.current?.pendingEntries.length\n          ? getReferencedPendingEntrySet(entryDraft.current)\n          : []),\n        ...(unpublishedEntry?.workflow.companions ?? []),\n      ]),\n  );\n  // The review prompt hands the entry over for review, or marks it ready when there’s no review\n  const reviewDialogLabel = $derived(\n    _(reviewStage === 'pending_publish' ? 'workflow.mark_as_ready' : 'workflow.send_for_review'),\n  );\n  // The menu item either throws the pull request away or deletes the entry outright, depending on\n  // whether it has been published\n  const discardItemStrings = $derived(\n    getDiscardDialogStrings({ pendingDeletion, publishedVersionExists }),\n  );\n\n  // Keep the deploy state fresh while the editor is open, so a build that finishes in the\n  // background turns the preview link live without the user reloading. The release function is\n  // returned synchronously; awaiting anything first would lose the handle and leak the hold\n  $effect(() => retainDeployPolling());\n\n  /**\n   * Go back to the previous page: the search results if the entry was opened from them, or the\n   * path given by `getEntryEditorBackPath()` otherwise.\n   */\n  const _goBack = () => {\n    const dirPath = collection && hasNestedEntries(collection) ? nestedFilterPath.current : '';\n\n    goBack(getEntryEditorBackPath({ collectionName, dirPath }), {\n      returnTo: isSearchResultsPath,\n    });\n  };\n\n  /**\n   * Ask whether the entry just saved should be moved to the given stage, e.g. handed over for\n   * review, and wait for the answer.\n   * @param {WorkflowStatus} stage Next stage.\n   * @returns {Promise<boolean>} `true` if the user wants to move it.\n   */\n  const askForReview = (stage) =>\n    new Promise((resolve) => {\n      reviewStage = stage;\n      resolveReviewPrompt = resolve;\n      showReviewDialog = true;\n    });\n\n  /**\n   * Check whether the entry is saved to a pull request. Read once the entry is saved, as saving it\n   * may have opened a pull request.\n   * @returns {boolean} Result.\n   */\n  const isWorkflowUsed = () => useWorkflow;\n\n  /**\n   * Check whether the editor is to be closed once the entry is saved.\n   * @returns {boolean} Result.\n   */\n  const isCloseOnSaveEnabled = () => prefs.closeOnSave ?? true;\n\n  /**\n   * Save the entry draft.\n   * @param {object} [options] Options.\n   * @param {boolean} [options.skipCI] Whether to disable automatic deployments for the change.\n   * @param {boolean} [options.overwrite] Whether to save over someone else’s change to the entry,\n   * once the user has been asked.\n   * @param {boolean} [options.publish] Whether to publish the entry along with the save, bypassing\n   * the review.\n   */\n  const save = async ({ skipCI = undefined, overwrite = false, publish = false } = {}) => {\n    const draft = entryDraft.current;\n\n    if (!collection || !draft) {\n      return;\n    }\n\n    saving = true;\n    publishing = publish;\n\n    try {\n      const outcome = await saveEntryDraftFlow({\n        entryDraft,\n        useWorkflow: isWorkflowUsed,\n        skipCI,\n        overwrite,\n        publish,\n        askForReview,\n        closeOnSave: isCloseOnSaveEnabled,\n      });\n\n      if (outcome.type === 'saved') {\n        if (outcome.statusError !== undefined) {\n          showErrorDialog = true;\n          errorMessage = outcome.statusError;\n        }\n\n        if (outcome.path) {\n          goto(outcome.path, { replaceState: true, notifyChange: false });\n        }\n\n        if (outcome.next === 'close') {\n          _goBack();\n          entryDraft.current = null;\n        } else if (outcome.next === 'reset') {\n          createDraft({\n            entryDraft,\n            collection,\n            collectionFile,\n            originalEntry: outcome.savedEntry,\n            extraValues: draft.extraValues,\n            expanderStates: draft.expanderStates,\n          });\n        }\n      } else if (outcome.type === 'invalid') {\n        errorCount = outcome.errorCount;\n        showValidationToast = true;\n      } else if (outcome.type === 'conflict') {\n        // Someone else has changed the entry since it was opened; let the user decide\n        saveConflict = { conflict: outcome.conflict, skipCI, publish };\n        showConflictDialog = true;\n      } else if (outcome.type === 'error') {\n        showErrorDialog = true;\n        errorMessage = outcome.message;\n      }\n    } finally {\n      saving = false;\n      publishing = false;\n    }\n  };\n</script>\n\n{#snippet overflowButtons()}\n  {#if !disabled && collection && originalEntry}\n    <PreviewLinkButton\n      entry={originalEntry}\n      locale={defaultLocale}\n      {collection}\n      {collectionFile}\n      pullRequest={unpublishedEntry?.workflow?.pullRequest}\n      iconic={!env.isLargeScreen}\n      as={env.isSmallScreen ? 'menuitem' : 'button'}\n    />\n  {/if}\n{/snippet}\n\n<Toolbar variant=\"primary\" ariaLabel={_('primary')}>\n  <BackButton\n    aria-label={_('cancel_editing')}\n    useShortcut={prefs.closeWithEscape && !activeInlineEditors.current}\n    onclick={() => {\n      _goBack();\n    }}\n  />\n  {#if env.isSmallScreen}\n    <Spacer flex />\n  {:else}\n    <h2 role=\"none\">\n      {#if !notFound}\n        <TruncatedText>\n          {#if isNew}\n            {title}\n          {:else}\n            <bdi>{collectionLabel}</bdi> › <bdi>{entrySummary}</bdi>\n          {/if}\n        </TruncatedText>\n      {/if}\n    </h2>\n  {/if}\n  {#if additions}\n    <additions.EntryViewers />\n  {/if}\n  {#if !env.isSmallScreen}\n    {@render overflowButtons()}\n  {/if}\n  {#if unpublishedEntry && !locked}\n    <EntryStatusMenu entry={unpublishedEntry} disabled={controlsDisabled} />\n  {/if}\n  <!-- Announced politely as the count changes, for a save that takes a while -->\n  <span class=\"save-progress\" aria-live=\"polite\">\n    {#if saving && saveProgress.current}\n      {_(`save_progress.${saveProgress.current.phase}`, {\n        values: { done: saveProgress.current.done, total: saveProgress.current.total },\n      })}\n    {/if}\n  </span>\n  {#if locked}\n    <!-- Nothing to save: the entry is read-only, or shown for reference until the deletion is\n    carried out -->\n  {:else if skipCIConfigured.current && !useWorkflow}\n    <SplitButton\n      variant=\"primary\"\n      label={_(\n        skipCIEnabled.current ? (saving ? 'saving' : 'save') : saving ? 'publishing' : 'publish',\n      )}\n      disabled={controlsDisabled || !modified}\n      keyShortcuts=\"Accel+S\"\n      onclick={() => {\n        save();\n      }}\n    >\n      {#snippet popup()}\n        <!-- Show the opposite option: if automatic deployments are enabled, allow to disable it -->\n        <Menu>\n          <MenuItem\n            label={_(skipCIEnabled.current ? 'save_and_publish' : 'save_without_publishing')}\n            onclick={() => {\n              save({ skipCI: !skipCIEnabled.current });\n            }}\n          />\n        </Menu>\n      {/snippet}\n    </SplitButton>\n  {:else if directPublish}\n    <!-- Saving keeps the entry as a draft for review, while the popup item publishes it now -->\n    <SplitButton\n      variant=\"primary\"\n      label={_(saving ? (publishing ? 'publishing' : 'saving') : 'save')}\n      disabled={controlsDisabled || !modified}\n      keyShortcuts=\"Accel+S\"\n      onclick={() => {\n        save();\n      }}\n    >\n      {#snippet popup()}\n        <Menu>\n          <MenuItem\n            label={_(directPublishBlocked ? 'save_and_publish_needs_review' : 'save_and_publish')}\n            disabled={directPublishBlocked}\n            onclick={() => {\n              // A change published directly has to be deployed, whatever the `skip_ci` option says\n              save({ publish: true, skipCI: false });\n            }}\n          />\n        </Menu>\n      {/snippet}\n    </SplitButton>\n  {:else}\n    <Button\n      variant=\"primary\"\n      label={_(saving ? 'saving' : 'save')}\n      disabled={controlsDisabled || !modified}\n      keyShortcuts=\"Accel+S\"\n      onclick={() => {\n        save();\n      }}\n    />\n  {/if}\n  {#if unpublishedEntry && showPublishControl}\n    <PublishEntryButton entry={unpublishedEntry} disabled={controlsDisabled} {modified} />\n  {/if}\n  <MenuButton\n    disabled={controlsDisabled}\n    variant=\"ghost\"\n    iconic\n    popupPosition=\"bottom-right\"\n    aria-label={_('show_editor_options')}\n    onclick={resetMenu.update}\n    onkeydown={resetMenu.update}\n    bind:this={menuButton}\n  >\n    {#snippet popup()}\n      <Menu ariaLabel={_('editor_options')}>\n        {#if env.isSmallScreen}\n          {@render overflowButtons()}\n          <!-- The sidebar doesn’t fit on a small screen, so its panels open in a bottom sheet. The\n            menu can’t be opened while the toolbar is disabled -->\n          {#if !notFound}\n            {#each getSidebarPanels(entryDraft.current) as panel (panel.key)}\n              <!-- With the count shown on the sidebar button’s badge, e.g. of comments -->\n              <MenuItem\n                label={getSidebarPanelLabel(panel)}\n                disabled={panel.disabled}\n                onclick={() => {\n                  showSidebarPanel(panel.key);\n                }}\n              />\n            {/each}\n            <Divider />\n          {/if}\n        {/if}\n        {#if !disabled && !isNew}\n          {#if canDuplicate}\n            <MenuItem\n              variant=\"ghost\"\n              disabled={controlsDisabled}\n              label={_('duplicate')}\n              aria-label={_('duplicate_entry')}\n              onclick={async () => {\n                duplicating = true;\n\n                // The URL is updated only once the duplicate is in place\n                const path = await duplicateEntryDraft(entryDraft);\n\n                duplicating = false;\n\n                if (path) {\n                  goto(path, {\n                    replaceState: true,\n                    notifyChange: false,\n                    transitionType: 'forwards',\n                  });\n                }\n              }}\n            />\n          {/if}\n          {#if removalMenuItems.discard}\n            <MenuItem\n              variant=\"ghost\"\n              disabled={controlsDisabled}\n              label={discardItemStrings.label}\n              aria-label={discardItemStrings.title}\n              onclick={() => {\n                if (publishedVersionExists) {\n                  entryRemoval?.confirmDiscard();\n                } else {\n                  entryRemoval?.confirmDelete();\n                }\n              }}\n            />\n          {/if}\n        {/if}\n        {#if removalMenuItems.delete}\n          <MenuItem\n            label={_('delete')}\n            onclick={() => {\n              entryRemoval?.confirmDelete();\n            }}\n          />\n        {/if}\n        <!-- A shortcut to the Slug panel, which a small screen lists above along with the other\n          sidebar panels -->\n        {#if !env.isSmallScreen}\n          <MenuItem\n            label={_('edit_slug')}\n            disabled={!canUpdateSlug(entryDraft.current)}\n            onclick={() => {\n              showSidebarPanel('slug');\n            }}\n          />\n        {/if}\n        <!-- A small screen lists the sidebar panels above, ending with a separator of their own -->\n        <ResetMenuItems\n          scope=\"entry\"\n          separator={!env.isSmallScreen || (!disabled && !isNew)}\n          available={{\n            revert: modified && !locked,\n            restore: resetMenu.availability.restore && !locked,\n            clear: resetMenu.availability.clear && !locked,\n          }}\n          onSelect={resetMenu.select}\n        />\n        {#if deployPollTimedOut.current}\n          <Divider />\n          <MenuItem\n            label={_('deploy_preview.check_again')}\n            onclick={() => {\n              recheckDeployments();\n            }}\n          />\n        {/if}\n        {#if env.isLargeScreen}\n          <ViewMenuItems />\n        {/if}\n      </Menu>\n    {/snippet}\n  </MenuButton>\n</Toolbar>\n\n<ValidationErrorsToast\n  bind:show={showValidationToast}\n  count={errorCount}\n  onShowErrors={() => {\n    showSidebarPanel('validation');\n  }}\n/>\n\n<Toast id={copyFromLocaleToast.current.id} bind:show={copyFromLocaleToast.current.show}>\n  {@const { status, message, count, sourceLanguage } = copyFromLocaleToast.current}\n  <Alert {status}>\n    {_(`editor.${message}`, {\n      values: {\n        count,\n        source: sourceLanguage ? (getLocaleLabel(sourceLanguage) ?? sourceLanguage) : '',\n      },\n    })}\n  </Alert>\n</Toast>\n\n<Toast id={listItemClipboardToast.current.id} bind:show={listItemClipboardToast.current.show}>\n  <Alert status={listItemClipboardToast.current.status}>\n    {listItemClipboardToast.current.message}\n  </Alert>\n</Toast>\n\n<ResetDialog\n  bind:open={resetMenu.dialogOpen}\n  action={resetMenu.action}\n  onClose={() => {\n    menuButton?.focus();\n  }}\n/>\n\n<ConfirmationDialog\n  bind:open={showReviewDialog}\n  title={reviewDialogLabel}\n  okLabel={reviewDialogLabel}\n  cancelLabel={_('later')}\n  onOk={() => {\n    resolveReviewPrompt?.(true);\n  }}\n  onClose={() => {\n    // Covers the Later button, the Escape key and any other way out. Sending has already settled\n    // the prompt, so this leaves it alone\n    resolveReviewPrompt?.(false);\n  }}\n>\n  {_(\n    reviewStage === 'pending_publish'\n      ? 'workflow.confirm_marking_as_ready'\n      : 'workflow.confirm_sending_for_review',\n  )}\n</ConfirmationDialog>\n\n<EntryRemoval\n  bind:this={entryRemoval}\n  bind:deleting\n  {collection}\n  {collectionFile}\n  {originalEntry}\n  {unpublishedEntry}\n  {associatedAssets}\n  {discardsDraft}\n  {useWorkflow}\n  {pendingDeletion}\n  onDone={() => {\n    _goBack();\n  }}\n  onClose={() => {\n    menuButton?.focus();\n  }}\n/>\n\n<SaveConflictDialog\n  bind:open={showConflictDialog}\n  conflict={saveConflict?.conflict}\n  onOverwrite={async () => {\n    await save({ skipCI: saveConflict?.skipCI, overwrite: true, publish: saveConflict?.publish });\n  }}\n  onClose={() => {\n    menuButton?.focus();\n  }}\n/>\n\n<!-- @todo make the error message more informative -->\n<AlertDialog\n  bind:open={showErrorDialog}\n  title={_('saving_entry.error.title')}\n  onClose={() => {\n    menuButton?.focus();\n  }}\n>\n  {_('saving_entry.error.description')}\n  {#if errorMessage}\n    <div role=\"none\" class=\"error\">\n      {errorMessage}\n    </div>\n  {/if}\n</AlertDialog>\n\n<style>\n  .save-progress {\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n    white-space: nowrap;\n    min-width: 0;\n    overflow: hidden;\n    text-overflow: ellipsis;\n  }\n\n  .error {\n    margin-top: 8px;\n    border-radius: var(--sui-control-medium-border-radius);\n    padding: 12px;\n    background-color: var(--sui-secondary-background-color);\n    font-size: var(--sui-font-size-default);\n    line-height: 1.5;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import {\n    Alert,\n    Button,\n    EmptyState,\n    Group,\n    Icon,\n    Infobar,\n    ResizableHandle,\n    ResizablePane,\n    ResizablePaneGroup,\n    Spacer,\n    Toast,\n  } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import { onMount, tick, untrack } from 'svelte';\n\n  import PaneBody from '$lib/components/contents/details/pane-body.svelte';\n  import PaneHeader from '$lib/components/contents/details/pane-header.svelte';\n  import PendingEditInfobar from '$lib/components/contents/details/pending-edit-infobar.svelte';\n  import RemoteChangeInfobar from '$lib/components/contents/details/remote-change-infobar.svelte';\n  import SidebarSheet from '$lib/components/contents/details/sidebar/sidebar-sheet.svelte';\n  import Sidebar from '$lib/components/contents/details/sidebar/sidebar.svelte';\n  import Toolbar from '$lib/components/contents/details/toolbar.svelte';\n  import { getAdditions, requireAdditions } from '$lib/services/app/additions';\n  import { focusOverlay, rememberFocus } from '$lib/services/app/focus';\n  import { goto } from '$lib/services/app/navigation';\n  import {\n    getReadonlyMessage,\n    isDraftConfigReadonly,\n    isDraftLockedByOthers,\n  } from '$lib/services/config/readonly';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import { collectionState } from '$lib/services/contents/collection/view';\n  import { resetBackupToastState, scheduleBackup } from '$lib/services/contents/draft/backup';\n  import { getValueMapVersion } from '$lib/services/contents/draft/create/versioned-map.svelte';\n  import { initEntryDraftEditor } from '$lib/services/contents/draft/editor.svelte';\n  import { setEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import {\n    editorFirstPane,\n    editorSecondPane,\n    showContentOverlay,\n    showDuplicateToast,\n  } from '$lib/services/contents/editor';\n  import { revealEditorField } from '$lib/services/contents/editor/fields';\n  import {\n    getDefaultPanes,\n    getLocaleContentLabel,\n    getPanesEditingLocale,\n    getPaneSizes,\n    getPaneStateKey,\n    getRestoredPanes,\n    savePaneState,\n  } from '$lib/services/contents/editor/panes';\n  import {\n    afterPendingFieldUpdates,\n    awaitPendingFieldUpdates,\n  } from '$lib/services/contents/editor/pending';\n  import { entryEditorSettings } from '$lib/services/contents/editor/settings';\n  import { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\n  import { env } from '$lib/services/user/env.svelte';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import { createLatestGuard } from '$lib/services/utils/scheduling';\n  import { watch } from '$lib/services/utils/state.svelte';\n  import { isOrphanedForkDraft } from '$lib/services/workflow';\n  import { getForkEntryNotice, isLockedForkEntry } from '$lib/services/workflow/forks';\n\n  /**\n   * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n   * @import { EntryDraft, EntryEditorPane, InternalLocaleCode } from '$lib/types/private';\n   * @import { FieldKeyPath } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {EntryDraftState} entryDraft Draft to edit. The editor components below read it\n   * from the context.\n   * @property {string | undefined} [editorLocale] The locale to open the editor in.\n   * @property {boolean} [loading] Whether the entry is still being resolved. That happens when it\n   * was opened with a deep link before the Editorial Workflow drafts have been fetched.\n   */\n\n  /** @type {Props} */\n  let { entryDraft, editorLocale = undefined, loading = false } = $props();\n\n  // svelte-ignore state_referenced_locally\n  setEntryDraftContext(entryDraft);\n\n  let restoring = false;\n  let switching = false;\n  /**\n   * Guard for field highlight requests, so a request still looking for its field can tell whether a\n   * newer one has come in.\n   */\n  const highlightRequestGuard = createLatestGuard();\n  /**\n   * Width of the first pane in pixels, used to place the pane swap button over the gutter between\n   * the panes. The button sits next to the resize handle rather than inside it: the handle is a\n   * focusable `separator`, and a button nested in it is an interactive control inside another one.\n   * @type {number}\n   */\n  let firstPaneWidth = $state(0);\n\n  let hidden = $state(true);\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n  /** @type {HTMLElement | undefined} */\n  let firstPaneContentArea = $state();\n  /** @type {HTMLElement | undefined} */\n  let secondPaneContentArea = $state();\n\n  const notFound = $derived(entryDraft.current === undefined);\n  const {\n    isNew = true,\n    canPreview = true,\n    canShowSecondPane = true,\n    collection,\n    collectionName,\n    collectionFile,\n    fileName,\n    isIndexFile,\n  } = $derived(/** @type {EntryDraft} */ (entryDraft.current ?? {}));\n  const { showPreview, showSecondPane: secondPaneShown = true } = $derived(\n    entryEditorSettings.current ?? {},\n  );\n  // The user’s choice only applies where the `editor.second_pane` option allows the second pane\n  const showSecondPane = $derived(canShowSecondPane && secondPaneShown);\n  const { i18nEnabled, allLocales, defaultLocale } = $derived(\n    getDraftI18nConfig(entryDraft.current),\n  );\n  const paneStateKey = $derived(getPaneStateKey({ collection, collectionFile }));\n  const {\n    readonly: collectionReadonly,\n    canCreate,\n    quota,\n    creationDisabled,\n  } = $derived(collectionState.current);\n  // The entry can be viewed but not changed, which the editor says up front. It’s also read-only\n  // while the user is asked whether to restore a backup, which the dialog says itself\n  const readonly = $derived(isDraftConfigReadonly(entryDraft.current));\n  // An entry from a contributor’s pull request is edited in their branch, or only viewed if they\n  // don’t let maintainers push to it, which the editor says up front as well. Once the pull request\n  // is no longer open, there’s nowhere left to save it, which the editor says instead\n  const forkNotice = $derived(\n    isOrphanedForkDraft(entryDraft.current)\n      ? _('workflow.fork_entry_gone')\n      : getForkEntryNotice(entryDraft.current?.originalEntry),\n  );\n  // Sveltia CMS Additions, whose chunk is loaded along with the backend if it’s enabled\n  const additions = $derived(getAdditions());\n  // Sveltia CMS Additions entry lock, which tells others the entry is being edited\n  const lockKey = $derived(additions?.getDraftLockKey(entryDraft.current));\n  // A new entry that can’t be created gets the message in place of the editor instead, and someone\n  // else editing the entry is what the lock infobar says\n  const showReadonlyInfobar = $derived(\n    readonly &&\n      !loading &&\n      !(isNew && creationDisabled) &&\n      !isDraftLockedByOthers(entryDraft.current),\n  );\n  // Only someone who can edit the entry takes its lock, or they would keep those who can from\n  // editing it. A viewer, or anyone else who can’t, only sees whether someone else is editing it\n  const holdsLock = $derived(!readonly && !isLockedForkEntry(entryDraft.current?.originalEntry));\n  const [firstPaneSize, secondPaneSize, minPaneSize] = $derived(\n    getPaneSizes({ firstPane: editorFirstPane.current, secondPane: editorSecondPane.current }),\n  );\n\n  /**\n   * Restore the pane state from IndexedDB.\n   * @returns {Promise<boolean>} Whether the panes are restored.\n   */\n  const restorePanes = async () => {\n    // Guard against re-entrance while the panes are being applied, which the `await`s below leave\n    // room for\n    /* v8 ignore next 3 */\n    if (restoring) {\n      return false;\n    }\n\n    const panes = getRestoredPanes({\n      /* v8 ignore next -- there’s no key without a collection, and then no draft to restore for */\n      savedPanes: entryEditorSettings.current?.paneStates?.[paneStateKey ?? ''],\n      editorLocale,\n      allLocales,\n      defaultLocale,\n      canPreview,\n      showPreview,\n      showSecondPane,\n    });\n\n    if (!panes) {\n      return false;\n    }\n\n    restoring = true;\n    await tick();\n    [editorFirstPane.current, editorSecondPane.current] = panes;\n\n    if (env.isSmallScreen || env.isMediumScreen) {\n      editorSecondPane.current = null;\n    }\n\n    await tick();\n    restoring = false;\n\n    return true;\n  };\n\n  /**\n   * Hide the preview pane if it’s disabled by the user or the collection/file.\n   */\n  const switchPanes = async () => {\n    if (!entryDraft.current || switching) {\n      return;\n    }\n\n    switching = true;\n\n    if (!(await restorePanes())) {\n      [editorFirstPane.current, editorSecondPane.current] = getDefaultPanes({\n        editorLocale,\n        currentLocale: editorFirstPane.current?.locale,\n        defaultLocale,\n        allLocales,\n        i18nEnabled,\n        canPreview,\n        showPreview,\n        showSecondPane,\n        singlePane: env.isSmallScreen || env.isMediumScreen,\n      });\n    }\n\n    switching = false;\n  };\n\n  /**\n   * Save the pane state to IndexedDB.\n   */\n  const savePanes = () => {\n    const firstPane = editorFirstPane.current;\n    const secondPane = editorSecondPane.current;\n\n    if (collection && !restoring && firstPane && secondPane && paneStateKey) {\n      savePaneState(paneStateKey, [firstPane, secondPane]);\n    }\n  };\n\n  /**\n   * Swap the panes.\n   */\n  const swapPanes = () => {\n    afterPendingFieldUpdates(() => {\n      [editorFirstPane.current, editorSecondPane.current] = [\n        editorSecondPane.current,\n        editorFirstPane.current,\n      ];\n    });\n  };\n\n  /**\n   * Mark the draft as manually interacted when the user performs an action in the editor body.\n   * @param {Event} event DOM event.\n   */\n  const markInteracted = (event) => {\n    if (event.isTrusted && entryDraft.current && !entryDraft.current.interacted) {\n      entryDraft.current.interacted = true;\n    }\n  };\n\n  /**\n   * Ensure the given locale’s edit pane is visible, switching panes if needed.\n   * @param {InternalLocaleCode} locale Locale code.\n   */\n  const ensureEditPaneVisible = async (locale) => {\n    // The panes are about to change, so let what was just typed reach the draft first\n    await awaitPendingFieldUpdates();\n\n    const panes = getPanesEditingLocale({\n      firstPane: editorFirstPane.current,\n      secondPane: editorSecondPane.current,\n      locale,\n    });\n\n    // Already visible in an edit pane\n    if (!panes) {\n      return;\n    }\n\n    [editorFirstPane.current, editorSecondPane.current] = panes;\n\n    // Wait for the DOM to update after the pane switch\n    await sleep(100);\n  };\n\n  /**\n   * Reveal the requested editor field: switch to an edit pane for the locale if needed, then expand\n   * the parent list/object(s), move the field into the viewport and focus a control within it.\n   * @param {object} args Arguments.\n   * @param {InternalLocaleCode} args.locale Locale code.\n   * @param {FieldKeyPath} args.keyPath Key path of the field.\n   */\n  const revealRequestedField = async ({ locale, keyPath }) => {\n    const isLatest = highlightRequestGuard.next();\n\n    await ensureEditPaneVisible(locale);\n\n    const draft = entryDraft.current;\n\n    // The draft may have gone away while the pane was switched\n    /* v8 ignore next 3 */\n    if (!draft) {\n      return;\n    }\n\n    /**\n     * Check whether a newer request has come in.\n     * @returns {boolean} Result.\n     */\n    const isOutdated = () => !isLatest();\n\n    await revealEditorField({ draft, locale, keyPath, isOutdated });\n  };\n\n  /**\n   * Highlight the editor field if the URL state contains a highlight object, such as when the user\n   * clicks a search result or validation error. Then clear the highlight state so that it doesn’t\n   * trigger again on navigation.\n   */\n  const revealRequestedFieldIfNeeded = async () => {\n    const { state } = window.history;\n    const { locale, keyPath } = state?.highlight ?? {};\n\n    if (typeof locale === 'string' && typeof keyPath === 'string' && locale && keyPath) {\n      await revealRequestedField({ locale, keyPath });\n      window.history.replaceState({ ...state, highlight: null }, '');\n    }\n  };\n\n  /**\n   * Called when a message event is received. If the event is a highlight event, calls\n   * {@link revealRequestedField} with the event payload.\n   * @param {MessageEvent} event The message event.\n   */\n  const onmessage = (event) => {\n    // Only accept messages from the same window to prevent potential security issues\n    if (event.source !== window) {\n      return;\n    }\n\n    if (event.data?.type === 'highlight-editor-field' && event.data.payload) {\n      revealRequestedField(event.data.payload);\n    }\n  };\n\n  onMount(() => {\n    if (!showContentOverlay.current) {\n      entryDraft.current = null;\n    }\n\n    // The row or the New button that opened the editor gets the focus back once it closes\n    const restoreFocus = rememberFocus();\n\n    window.addEventListener('message', onmessage);\n\n    return () => {\n      window.removeEventListener('message', onmessage);\n      restoreFocus();\n    };\n  });\n\n  $effect(() => {\n    if (prefs.devModeEnabled) {\n      // Log a plain copy rather than the `$state` proxy. Taking it reads every value in the draft,\n      // so the draft is logged again whenever a value or its validity changes\n      // eslint-disable-next-line no-console\n      console.info('entryDraft', $state.snapshot(entryDraft.current));\n    }\n  });\n\n  // Register the editor root, which the rich text editor components look the draft up with, and\n  // resolve the Compute fields\n  initEntryDraftEditor(\n    () => entryDraft,\n    () => wrapper,\n  );\n\n  $effect(() => {\n    const draft = entryDraft.current;\n\n    if (draft) {\n      // Depend on everything that goes into a backup\n      Object.values(draft.currentValues).forEach(getValueMapVersion);\n      void $state.snapshot(draft.currentLocales);\n      void $state.snapshot(draft.currentSlugs);\n      // The files map holds `File` objects, which can’t be snapshotted; a file can be replaced\n      Object.values(draft.files).forEach(({ file }) => void file);\n      // A pending entry opened again and changed takes the place of its earlier version\n      draft.pendingEntries.forEach((pendingEntry) => void pendingEntry);\n      void draft.interacted;\n    }\n\n    // Back up the draft automatically whenever it changes, or drop a pending backup once it’s gone\n    untrack(() => scheduleBackup(draft));\n  });\n\n  // Tell others the entry is open, read-only or not, so they can see who else is looking at it, and\n  // hold its lock while it’s open, if the user can edit it\n  $effect(() => {\n    const key = lockKey;\n    const hold = holdsLock;\n\n    if (!key) {\n      return undefined;\n    }\n\n    // There’s only a key with Sveltia CMS Additions\n    const { watchEntry } = requireAdditions();\n\n    return untrack(() => watchEntry(key, { hold }));\n  });\n\n  $effect(() => {\n    if (paneStateKey) {\n      // Reset the editor panes\n      editorFirstPane.current = null;\n      editorSecondPane.current = null;\n    }\n  });\n\n  // The pane state key also changes between the files of a file/singleton collection, which share\n  // the collection\n  watch(\n    () => [\n      paneStateKey,\n      collection,\n      showSecondPane,\n      showPreview,\n      canPreview,\n      env.isSmallScreen,\n      env.isMediumScreen,\n    ],\n    () => {\n      switchPanes();\n    },\n  );\n\n  $effect(() => {\n    void [editorFirstPane.current, editorSecondPane.current];\n    savePanes();\n  });\n\n  $effect(() => {\n    /* v8 ignore next -- the wrapper is bound as long as the overlay is mounted */\n    if (wrapper) {\n      (async () => {\n        // The overlay is only rendered while it’s shown, so there is nothing to do once it’s\n        // closed; the page shows the backup toast then\n        if (hidden) {\n          hidden = false;\n          await switchPanes();\n          await focusOverlay(() => wrapper);\n          await revealRequestedFieldIfNeeded();\n          resetBackupToastState();\n        }\n      })();\n    }\n  });\n</script>\n\n{#snippet pane(\n  /** @type {'first' | 'second'} */ position,\n  /** @type {EntryEditorPane} */ { locale, mode },\n)}\n  {@const thisPane = position === 'first' ? editorFirstPane : editorSecondPane}\n  {@const thatPane = position === 'first' ? editorSecondPane : editorFirstPane}\n  <div class=\"pane-wrapper\">\n    <Group\n      class=\"pane\"\n      ariaLabel={getLocaleContentLabel(\n        mode === 'edit' ? 'edit_x_locale' : 'preview_x_locale',\n        locale,\n      )}\n      data-locale={locale}\n      data-mode={mode}\n    >\n      <PaneHeader id={`${position}-pane-header`} {thisPane} {thatPane} />\n      {#if position === 'first'}\n        <PaneBody\n          id=\"first-pane-body\"\n          {thisPane}\n          bind:thisPaneContentArea={firstPaneContentArea}\n          thatPaneContentArea={secondPaneContentArea}\n        />\n      {:else}\n        <PaneBody\n          id=\"second-pane-body\"\n          {thisPane}\n          bind:thisPaneContentArea={secondPaneContentArea}\n          thatPaneContentArea={firstPaneContentArea}\n        />\n      {/if}\n    </Group>\n  </div>\n{/snippet}\n\n<div\n  role=\"group\"\n  class=\"wrapper content-editor\"\n  aria-label={_('content_editor')}\n  bind:this={wrapper}\n>\n  {#key entryDraft.current?.id}\n    {#if additions}\n      <additions.EntryLockInfobar {lockKey} />\n    {/if}\n    {#if showReadonlyInfobar}\n      <Infobar\n        dismissible={false}\n        --sui-infobar-border-width=\"0 0 1px\"\n        --sui-infobar-message-justify-content=\"center\"\n      >\n        {getReadonlyMessage('entry', { collection, collectionFile })}\n      </Infobar>\n    {:else if forkNotice && !loading}\n      <Infobar\n        dismissible={false}\n        --sui-infobar-border-width=\"0 0 1px\"\n        --sui-infobar-message-justify-content=\"center\"\n      >\n        {forkNotice}\n      </Infobar>\n    {/if}\n    <Toolbar disabled={loading || (isNew && creationDisabled)} />\n    {#if loading}\n      <EmptyState>\n        <div role=\"none\">{_('loading_entries', { values: { count: 1 } })}</div>\n      </EmptyState>\n    {:else if entryDraft.current === null}\n      <!-- Hide the content after saving a draft -->\n    {:else if notFound || (isNew && creationDisabled)}\n      <EmptyState>\n        <div role=\"none\">\n          {#if notFound}\n            {_('entry_not_found')}\n          {:else if collectionReadonly}\n            {getReadonlyMessage('collection', { collection })}\n          {:else if !canCreate}\n            {_('creating_entries_disabled_by_admin')}\n          {:else}\n            {_('creating_entries_disabled_by_quota', { values: { quota } })}\n          {/if}\n        </div>\n        <div role=\"none\">\n          <Button\n            variant=\"primary\"\n            onclick={() => {\n              // The draft is gone when the entry couldn’t be found, so fall back to the collection\n              // the URL pointed at\n              const targetCollection = collectionName ?? selectedCollection.current?.name;\n\n              goto(targetCollection ? `/collections/${targetCollection}` : '/collections', {\n                replaceState: true,\n                transitionType: 'backwards',\n              });\n            }}\n          >\n            {_('back_to_collection')}\n          </Button>\n        </div>\n      </EmptyState>\n    {:else}\n      <RemoteChangeInfobar />\n      <PendingEditInfobar />\n      <div role=\"none\" class=\"body\" onpointerdown={markInteracted} onkeydown={markInteracted}>\n        {#key `${collectionName}|${fileName}|${isIndexFile}`}\n          <div role=\"none\" class=\"content-area\">\n            {#if editorFirstPane.current && editorSecondPane.current}\n              <ResizablePaneGroup\n                onResize={({ sizes }) => {\n                  /* v8 ignore next -- the group is only rendered with both panes */\n                  if (editorFirstPane.current && editorSecondPane.current) {\n                    const [firstWidth, secondWidth] = sizes;\n\n                    // Replace the objects rather than mutating them, so the change is noticed\n                    editorFirstPane.current = { ...editorFirstPane.current, width: firstWidth };\n                    editorSecondPane.current = {\n                      ...editorSecondPane.current,\n                      width: secondWidth,\n                    };\n                  }\n                }}\n              >\n                <ResizablePane defaultSize={firstPaneSize} minSize={minPaneSize}>\n                  <div role=\"none\" class=\"pane-measure\" bind:clientWidth={firstPaneWidth}>\n                    {@render pane('first', editorFirstPane.current)}\n                  </div>\n                </ResizablePane>\n                <ResizableHandle />\n                <ResizablePane defaultSize={secondPaneSize} minSize={minPaneSize}>\n                  {@render pane('second', editorSecondPane.current)}\n                </ResizablePane>\n              </ResizablePaneGroup>\n              <Button\n                class=\"swap-button\"\n                iconic\n                size=\"small\"\n                variant=\"tertiary\"\n                tooltip={_('swap_panes')}\n                aria-label={_('swap_panes')}\n                style=\"--gutter-position: {firstPaneWidth}px\"\n                onclick={swapPanes}\n              >\n                <Icon name=\"swap_horiz\" />\n              </Button>\n            {:else if editorFirstPane.current}\n              {@render pane('first', editorFirstPane.current)}\n            {:else if editorSecondPane.current}\n              {@render pane('second', editorSecondPane.current)}\n            {:else}\n              <Spacer flex />\n            {/if}\n          </div>\n          <!-- The sidebar doesn’t fit on a small screen, so its panels open in a bottom sheet -->\n          {#if env.isSmallScreen}\n            <SidebarSheet />\n          {:else}\n            <Sidebar />\n          {/if}\n        {/key}\n      </div>\n    {/if}\n  {/key}\n</div>\n\n<Toast bind:show={showDuplicateToast.current}>\n  <Alert status=\"success\">\n    {_('entry_duplicated')}\n  </Alert>\n</Toast>\n\n<style>\n  .wrapper {\n    position: fixed;\n    inset: 0;\n    z-index: 100;\n    display: flex;\n    flex-direction: column;\n    background-color: var(--sui-secondary-background-color);\n  }\n\n  .pane-wrapper {\n    display: contents;\n\n    :global {\n      & > .pane {\n        flex: auto;\n        height: 100%;\n        overflow: hidden;\n        display: flex;\n        flex-direction: column;\n      }\n    }\n  }\n\n  .body {\n    flex: auto;\n    display: flex;\n    overflow: hidden;\n  }\n\n  .content-area {\n    position: relative;\n    flex: auto;\n    border-block-start: var(--area-border); /* below the toolbar */\n    background-color: var(--sui-primary-background-color);\n\n    &:not(:only-child) {\n      border-inline-end: var(--area-border); /* sidebar is present */\n      border-start-end-radius: 16px;\n    }\n\n    :global {\n      .sui.resizable-handle {\n        border-inline: var(--area-border); /* between the panes */\n        background-color: var(--sui-secondary-background-color); /* same as toolbar */\n      }\n\n      /* Centred over the gutter, whose position is the first pane’s width */\n      .swap-button {\n        position: absolute;\n        top: calc(50% - 12px);\n        inset-inline-start: calc(\n          var(--gutter-position) + var(--sui-resizable-handle-size, 4px) / 2\n        );\n        /* Above the handle’s hit area, a positioned `::before` pseudo-element at `z-index: 1` */\n        z-index: 2;\n        margin: 0;\n        border-radius: 50%;\n        opacity: 0.5;\n        translate: -50%;\n        /* Not `all`: the position would animate from the unmeasured width and lag behind a drag */\n        transition-property: opacity, color, background-color;\n\n        &:dir(rtl) {\n          translate: 50%;\n        }\n\n        &:hover,\n        &:focus-visible {\n          opacity: 1;\n        }\n      }\n    }\n  }\n\n  .pane-measure {\n    display: flex;\n    flex-direction: column;\n    height: 100%;\n  }\n</style>\n","<!--\n  @component\n  Render a cell of the bulk editor: the control of a field for an entry, the same one the entry\n  editor shows, without the label or the hint, the way an editor component in the `inline` mode\n  renders it. The value is read from and written to the pending bulk edits rather than a draft.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import { editors } from '$lib/components/contents/details/fields';\n  import {\n    getBulkEditRowSlug,\n    getBulkEditRowValues,\n    setBulkEditRowContext,\n  } from '$lib/services/contents/editor/bulk-edit-row';\n  import { getEditorFieldConfig } from '$lib/services/contents/editor/field-flags';\n  import { isFieldRequired } from '$lib/services/contents/entry/fields';\n  import { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n  /**\n   * @import { Entry, FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n   * @import { Field, FieldKeyPath } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalLocaleCode} locale Locale of the edited values, which is the default locale.\n   * @property {Field} fieldConfig Field configuration.\n   * @property {string} entryLabel Plain-text summary of the entry, naming the control together with\n   * the field label.\n   * @property {any} value Current value: the pending edit if any, or else the stored value.\n   * @property {Entry} entry Entry of the row, which the control reads in place of an entry draft,\n   * e.g. to resolve the templates in the filters of a Relation field.\n   * @property {Record<FieldKeyPath, any>} [entryEdits] Pending edits of the entry, applied to its\n   * values as the control reads them.\n   * @property {boolean} [edited] Whether the value has a pending edit.\n   * @property {string[]} [errors] Validation messages of the pending edit.\n   * @property {boolean} [readonly] Whether to make the control read-only, e.g. while the edits are\n   * being saved.\n   * @property {(value: any) => void} onChange Called with a new value.\n   */\n\n  /** @type {Props} */\n  const {\n    locale,\n    fieldConfig,\n    entryLabel,\n    value,\n    entry,\n    entryEdits,\n    edited = false,\n    errors = [],\n    readonly = false,\n    onChange,\n  } = $props();\n\n  const fieldId = $props.id();\n  const { name: keyPath, widget: fieldType = 'string' } = $derived(fieldConfig);\n  const fieldLabel = $derived(getFieldLabel({ config: fieldConfig, locale }));\n  const Editor = $derived(editors[fieldType]);\n  const invalid = $derived(!!errors.length);\n  // A Select or Relation field always shows a dropdown list, as radio buttons wouldn’t fit in a\n  // cell\n  const editorFieldConfig = $derived(getEditorFieldConfig({ fieldConfig, inline: true }));\n\n  // The edits of every row are replaced together, while those of the other rows keep their\n  // identity, so going through this derived spares the control of this row from working its values\n  // out again on an edit made in another row\n  const edits = $derived(entryEdits);\n  const entryValues = $derived(getBulkEditRowValues({ entry, locale, edits }));\n  const entrySlug = $derived(getBulkEditRowSlug(entry, locale));\n\n  // There is no draft in the bulk editor, so the control reads the entry of the row from here,\n  // through `getEditorEntryValues()`\n  setBulkEditRowContext({\n    /**\n     * Get the entry’s values.\n     * @returns {FlattenedEntryContent} Values.\n     */\n    get values() {\n      return entryValues;\n    },\n    /**\n     * Get the entry’s slug.\n     * @returns {string} Slug.\n     */\n    get slug() {\n      return entrySlug;\n    },\n  });\n</script>\n\n<div role=\"none\" class=\"cell\" class:edited class:invalid data-field-type={fieldType}>\n  <span id=\"{fieldId}-label\" hidden>\n    {_('bulk_edit_cell', { values: { field: fieldLabel, entry: entryLabel } })}\n  </span>\n  <Editor\n    {locale}\n    {keyPath}\n    typedKeyPath={keyPath}\n    {fieldId}\n    {fieldLabel}\n    fieldConfig={editorFieldConfig}\n    bind:currentValue={() => value, (newValue) => onChange(newValue)}\n    required={isFieldRequired({ fieldConfig, locale })}\n    {readonly}\n    {invalid}\n  />\n  {#if invalid}\n    <div role=\"alert\" id=\"{fieldId}-error\" class=\"error\">\n      {#each errors as message, index (index)}\n        <div role=\"none\">{message}</div>\n      {/each}\n    </div>\n  {/if}\n</div>\n\n<style>\n  .cell {\n    --sui-textbox-singleline-min-width: 10em;\n    --sui-combobox-min-width: 10em;\n    display: flex;\n    flex-direction: column;\n    gap: 4px;\n    border-radius: var(--sui-control-medium-border-radius);\n    padding: 2px;\n\n    &.edited {\n      background-color: var(--sui-secondary-background-color);\n    }\n\n    :global {\n      .sui:is(.text-input, .number-input, .combobox) {\n        margin: 0;\n      }\n    }\n  }\n\n  .error {\n    color: var(--sui-error-foreground-color);\n    font-size: var(--sui-font-size-small);\n  }\n</style>\n","import equal from 'fast-deep-equal';\n\nimport { checkForRemoteChanges } from '$lib/services/backends/refresh';\nimport { isConfigReadonly } from '$lib/services/config/readonly';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { findFieldByName } from '$lib/services/contents/collection/entries/bulk-edit/config';\nimport { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { saveEntryUpdates } from '$lib/services/contents/collection/entries/save';\nimport { resolveCacheDB } from '$lib/services/contents/draft/save/file-changes';\nimport { validateAnyField } from '$lib/services/contents/draft/validate/fields';\nimport { getFieldValidationMessages } from '$lib/services/contents/draft/validate/messages';\nimport { isUniqueField, normalizeUniqueValue } from '$lib/services/contents/draft/validate/unique';\nimport { finalizeValidity } from '$lib/services/contents/draft/validate/validity';\nimport {\n  buildEntryUpdateChanges,\n  createSyntheticDraft,\n} from '$lib/services/contents/entry/changes';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport { refreshPermalinks } from '$lib/services/contents/entry/permalink';\nimport { isEntryReadonly } from '$lib/services/contents/entry/readonly';\nimport { assignAutoNowValues } from '$lib/services/contents/fields/date-time/auto-now';\nimport { getLocalizedFieldValue } from '$lib/services/contents/fields/locale';\nimport {\n  followsDefaultLocale,\n  isDuplicateIfEmptyField,\n} from '$lib/services/contents/i18n/duplicate-if-empty';\nimport { isFieldMirrored } from '$lib/services/contents/i18n/fields';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { isValueEmpty } from '$lib/services/utils/object';\nimport { getCompanionEntries, getUnpublishedEntriesByCollection } from '$lib/services/workflow';\n\n/**\n * @import {\n * Entry,\n * FileChange,\n * InternalEntryCollection,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Pending edits made in the bulk editor, keyed by entry ID, then by field name. Only the values\n * that differ from the stored ones are kept.\n * @typedef {Record<string, Record<FieldKeyPath, any>>} BulkEdits\n */\n\n/**\n * Validation messages of the pending edits, keyed by entry ID, then by field name. Only the fields\n * with an error are listed.\n * @typedef {Record<string, Record<FieldKeyPath, string[]>>} BulkEditErrors\n */\n\n/**\n * Check whether an entry can be edited in the bulk editor. The collection’s index file, which may\n * have fields of its own, an entry without content in the default locale and an entry locked by\n * the `readonly` option are left out.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {Entry} entry Entry.\n * @returns {boolean} Result.\n */\nexport const isBulkEditableEntry = (collection, entry) =>\n  !!entry.locales[collection._i18n.defaultLocale]?.content &&\n  !isCollectionIndexFile(collection, entry) &&\n  !isEntryReadonly(entry);\n\n/**\n * Get the stored value of a field in the default locale of an entry.\n * @param {InternalEntryCollection} collection Entry collection.\n * @param {Entry} entry Entry.\n * @param {FieldKeyPath} keyPath Field name.\n * @returns {any} Value.\n */\nexport const getStoredValue = (collection, entry, keyPath) =>\n  entry.locales[collection._i18n.defaultLocale]?.content[keyPath];\n\n/**\n * Get the value of a field as it is shown in the bulk editor: the pending edit if any, or else the\n * stored value.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {Entry} args.entry Entry.\n * @param {FieldKeyPath} args.keyPath Field name.\n * @param {BulkEdits} args.edits Pending edits.\n * @returns {any} Value.\n */\nexport const getBulkEditValue = ({ collection, entry, keyPath, edits }) => {\n  const entryEdits = edits[entry.id];\n\n  return entryEdits && Object.hasOwn(entryEdits, keyPath)\n    ? entryEdits[keyPath]\n    : getStoredValue(collection, entry, keyPath);\n};\n\n/**\n * Check whether two field values mean the same thing to the bulk editor. A missing value and an\n * empty one are the same, so clearing a field that has no value isn’t a change.\n * @param {any} a Value.\n * @param {any} b Another value.\n * @returns {boolean} Result.\n */\nconst isSameValue = (a, b) => {\n  /**\n   * Normalize an empty value.\n   * @param {any} value Value.\n   * @returns {any} Normalized value.\n   */\n  const normalize = (value) => (isValueEmpty(value) ? '' : value);\n\n  return equal(normalize(a), normalize(b));\n};\n\n/**\n * Record an edit made in the bulk editor, returning the updated edits. An edit that brings the\n * value back to the stored one is dropped, so the entry isn’t counted as changed.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {Entry} args.entry Entry.\n * @param {FieldKeyPath} args.keyPath Field name.\n * @param {any} args.value New value.\n * @param {BulkEdits} args.edits Current edits, which are not modified.\n * @returns {BulkEdits} Updated edits.\n */\nexport const setBulkEditValue = ({ collection, entry, keyPath, value, edits }) => {\n  const { [keyPath]: _previous, ...otherFieldEdits } = edits[entry.id] ?? {};\n  const { [entry.id]: _entryEdits, ...otherEntryEdits } = edits;\n  const storedValue = getStoredValue(collection, entry, keyPath);\n  const fieldConfig = findFieldByName(collection.fields, keyPath);\n  // A Boolean field without a value is shown as off, so turning it off isn’t a change\n  const shownValue = fieldConfig?.widget === 'boolean' ? (storedValue ?? false) : storedValue;\n\n  const entryEdits = isSameValue(value, shownValue)\n    ? otherFieldEdits\n    : { ...otherFieldEdits, [keyPath]: value };\n\n  return Object.keys(entryEdits).length\n    ? { ...otherEntryEdits, [entry.id]: entryEdits }\n    : otherEntryEdits;\n};\n\n/**\n * Count the fields with a pending edit.\n * @param {BulkEdits} edits Pending edits.\n * @returns {number} Count.\n */\nexport const countBulkEdits = (edits) =>\n  Object.values(edits).reduce((count, entryEdits) => count + Object.keys(entryEdits).length, 0);\n\n/**\n * Apply the pending edits to a copy of an entry. A field with the `duplicate` i18n option gets the\n * same value in every locale that has content, localized for each the way the entry editor copies\n * it, e.g. a DateTime field value written in the locale, and one with the `duplicate_if_empty`\n * option gets it in the locales where it’s empty or still holds the default locale’s value; any\n * other field is only changed in the default locale. The DateTime fields with the `auto_now` option\n * are updated too, as a save in the entry editor would.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {Entry} args.entry Entry, which is not modified.\n * @param {Record<FieldKeyPath, any>} args.entryEdits Pending edits of the entry.\n * @returns {Entry} Updated entry.\n */\nexport const applyBulkEdits = ({ collection, entry, entryEdits }) => {\n  const { defaultLocale } = collection._i18n;\n\n  /** @type {Record<string, Record<string, any>>} */\n  const currentValues = Object.fromEntries(\n    Object.entries(entry.locales)\n      .filter(([, { content }]) => !!content)\n      .map(([locale, { content }]) => [locale, { ...content }]),\n  );\n\n  Object.entries(entryEdits).forEach(([keyPath, value]) => {\n    const fieldConfig = findFieldByName(collection.fields, keyPath);\n    // A `duplicate_if_empty` field is updated in the other locales where it’s empty or still holds\n    // the default locale’s value\n    const fillEmpty = !!fieldConfig && isDuplicateIfEmptyField(fieldConfig);\n    const previousValue = currentValues[defaultLocale][keyPath];\n\n    Object.entries(currentValues).forEach(([locale, content]) => {\n      if (locale === defaultLocale) {\n        content[keyPath] = value;\n\n        return;\n      }\n\n      if (\n        isFieldMirrored(fieldConfig?.i18n) ||\n        (fillEmpty &&\n          followsDefaultLocale({\n            fieldConfig: /** @type {Field} */ (fieldConfig),\n            targetValue: content[keyPath],\n            previousValue,\n            sourceLocale: defaultLocale,\n            targetLocale: locale,\n          }))\n      ) {\n        content[keyPath] = getLocalizedFieldValue({\n          fieldConfig: /** @type {Field} */ (fieldConfig),\n          value,\n          sourceLocale: defaultLocale,\n          targetLocale: locale,\n        });\n      }\n    });\n  });\n\n  assignAutoNowValues({ ...createSyntheticDraft({ collection }), isNew: false, currentValues });\n\n  return {\n    ...entry,\n    locales: Object.fromEntries(\n      Object.entries(entry.locales).map(([locale, localizedEntry]) => [\n        locale,\n        currentValues[locale]\n          ? { ...localizedEntry, content: currentValues[locale] }\n          : { ...localizedEntry },\n      ]),\n    ),\n  };\n};\n\n/**\n * Find the values of the unique fields that the pending edits would leave in more than one entry,\n * looking at the collection as it would be once the edits are saved. Unlike the check done in the\n * entry editor, this takes the other pending edits into account, so two entries swapping their\n * values isn’t reported, while two entries given the same new value are.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {FieldKeyPath} args.keyPath Field name.\n * @param {string} args.fieldType Field type.\n * @param {BulkEdits} args.edits Pending edits.\n * @returns {Map<string | number, number>} Number of entries holding each normalized value.\n */\nconst countUniqueValues = ({ collection, keyPath, fieldType, edits }) => {\n  /** @type {Map<string | number, number>} */\n  const counts = new Map();\n\n  const published = getEntriesByCollection(collection.name).filter(\n    (entry) => !isCollectionIndexFile(collection, entry),\n  );\n\n  const publishedPaths = new Set(published.flatMap((entry) => getEntryPaths(entry)));\n\n  // An unpublished version of a published entry is another version of the same entry, not another\n  // entry, so it’s left out; it’s told by its paths, including the ones it had before a rename. An\n  // entry that has never been published is another entry. Entries stored in one file share a path,\n  // but such a collection can’t use the Editorial Workflow, so none of them is unpublished\n  const unpublished = getUnpublishedEntriesByCollection(collection.name).filter(\n    (entry) =>\n      !isCollectionIndexFile(collection, entry) &&\n      !getEntryPaths(entry, { includePrevious: true }).some((path) => publishedPaths.has(path)),\n  );\n\n  // The new entries riding along in the pull request of an entry of another collection have never\n  // been published either\n  [...published, ...unpublished, ...getCompanionEntries(collection.name)].forEach((entry) => {\n    const value = normalizeUniqueValue(\n      getBulkEditValue({ collection, entry, keyPath, edits }),\n      fieldType,\n    );\n\n    if (value !== undefined) {\n      counts.set(value, (counts.get(value) ?? 0) + 1);\n    }\n  });\n\n  return counts;\n};\n\n/**\n * Validate the pending edits against the field configuration, the way a save in the entry editor\n * would. Only the edited fields are checked, so an entry that was already invalid can still have\n * another field changed.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {Entry[]} args.entries Entries shown in the bulk editor.\n * @param {BulkEdits} args.edits Pending edits.\n * @returns {BulkEditErrors} Validation messages of the invalid fields.\n */\nexport const validateBulkEdits = ({ collection, entries, edits }) => {\n  const { defaultLocale } = collection._i18n;\n  const draft = createSyntheticDraft({ collection });\n  /** @type {Map<FieldKeyPath, Map<string | number, number>>} */\n  const uniqueValueCounts = new Map();\n  /** @type {BulkEditErrors} */\n  const errors = {};\n\n  entries.forEach((entry) => {\n    const entryEdits = edits[entry.id];\n\n    if (!entryEdits) {\n      return;\n    }\n\n    const content = { ...entry.locales[defaultLocale]?.content, ...entryEdits };\n\n    Object.entries(entryEdits).forEach(([keyPath, value]) => {\n      const fieldConfig = /** @type {Field} */ (findFieldByName(collection.fields, keyPath));\n\n      let validity = validateAnyField({\n        draft: { ...draft, originalEntry: entry },\n        locale: defaultLocale,\n        keyPath,\n        value,\n        valueMap: content,\n        validities: { [defaultLocale]: {} },\n      });\n\n      // The validator compares a unique value with the other entries as they are stored, which\n      // doesn’t account for the other pending edits, so the check is made again across the batch\n      if (validity && isUniqueField({ draft, fieldConfig, keyPath })) {\n        const fieldType = fieldConfig.widget ?? 'string';\n        const normalized = normalizeUniqueValue(value, fieldType);\n\n        const valueCounts = getOrCreate(uniqueValueCounts, keyPath, () =>\n          countUniqueValues({ collection, keyPath, fieldType, edits }),\n        );\n\n        const updated = { ...validity };\n\n        delete updated.valid;\n        updated.duplicateError =\n          normalized !== undefined && /** @type {number} */ (valueCounts.get(normalized)) > 1;\n        validity = finalizeValidity(updated);\n      }\n\n      if (validity && !validity.valid) {\n        errors[entry.id] = {\n          ...errors[entry.id],\n          [keyPath]: getFieldValidationMessages({ validity, fieldConfig }),\n        };\n      }\n    });\n  });\n\n  return errors;\n};\n\n/**\n * Build the {@link FileChange}s that save the pending edits, one or more per edited entry. The\n * edits are applied to each entry as it is in the store now rather than as it was when the editor\n * was opened, so a change someone else has made to another field of the entry in the meantime isn’t\n * reverted. An entry deleted in the meantime is left out.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {Entry[]} args.entries Entries shown in the bulk editor.\n * @param {BulkEdits} args.edits Pending edits.\n * @returns {Promise<{ changes: FileChange[], savingEntries: Entry[] }>} Collected changes and the\n * entries to be saved.\n */\nexport const buildBulkEditChanges = async ({ collection, entries, edits }) => {\n  // A fetch carries an entry’s ID over to its changed version\n  const currentEntries = new Map(\n    getEntriesByCollection(collection.name).map((entry) => [entry.id, entry]),\n  );\n\n  const savingEntries = entries\n    .filter((entry) => !!edits[entry.id] && currentEntries.has(entry.id))\n    .map((entry) =>\n      refreshPermalinks({\n        collection,\n        entry: applyBulkEdits({\n          collection,\n          entry: /** @type {Entry} */ (currentEntries.get(entry.id)),\n          entryEdits: edits[entry.id],\n        }),\n      }),\n    );\n\n  const draft = createSyntheticDraft({ collection });\n  const cacheDB = resolveCacheDB();\n\n  const perEntryChanges = await Promise.all(\n    savingEntries.map((entry) => buildEntryUpdateChanges({ collection, entry, draft, cacheDB })),\n  );\n\n  return { changes: perEntryChanges.flat(), savingEntries };\n};\n\n/**\n * Save the pending edits made in the bulk editor in a single commit.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {Entry[]} args.entries Entries shown in the bulk editor.\n * @param {BulkEdits} args.edits Pending edits.\n * @returns {Promise<number>} Number of entries saved.\n */\nexport const saveBulkEdits = async ({ collection, entries, edits }) => {\n  // The collection could have been made read-only since the editor was opened, e.g. by a\n  // configuration reload, in which case nothing is written\n  if (isConfigReadonly({ collection })) {\n    return 0;\n  }\n\n  // Bring the store up to date first, so the edits are applied to the entries as they are now. The\n  // check is a nicety: if it fails, the backend still has the last word on the commit\n  try {\n    await checkForRemoteChanges();\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to check the repository for changes.', ex);\n  }\n\n  const { changes, savingEntries } = await buildBulkEditChanges({ collection, entries, edits });\n\n  return saveEntryUpdates({ collection, changes, savingEntries });\n};\n","import {\n  isBulkEditableEntry,\n  setBulkEditValue,\n  validateBulkEdits,\n} from '$lib/services/contents/collection/entries/bulk-edit';\nimport {\n  bulkEditedEntries,\n  bulkEditErrors,\n  bulkEdits,\n  entryGroups,\n} from '$lib/services/contents/collection/view';\n\n/**\n * @import { Entry, InternalEntryCollection } from '$lib/types/private';\n * @import { FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Take a snapshot of the entry groups of the current view when the bulk editor is opened, without\n * the entries that can’t be edited and the groups left empty, and publish the listed entries as\n * {@link bulkEditedEntries} for the toolbar Save button.\n * @param {InternalEntryCollection} collection Entry collection.\n * @returns {{ name: string, entries: Entry[] }[]} Entry groups.\n */\nexport const snapshotBulkEditGroups = (collection) => {\n  const groups = entryGroups.current\n    .map(({ name, entries }) => ({\n      name,\n      entries: entries.filter((entry) => isBulkEditableEntry(collection, entry)),\n    }))\n    .filter(({ entries }) => entries.length);\n\n  bulkEditedEntries.current = groups.flatMap(({ entries }) => entries);\n\n  return groups;\n};\n\n/**\n * Record a new value of a field in {@link bulkEdits}, and validate the edits again if the user has\n * been told some of them are invalid, so a fixed field stops being reported.\n * @param {object} args Arguments.\n * @param {InternalEntryCollection} args.collection Entry collection.\n * @param {Entry} args.entry Entry.\n * @param {FieldKeyPath} args.keyPath Field name.\n * @param {any} args.value New value.\n */\nexport const updateBulkEditValue = ({ collection, entry, keyPath, value }) => {\n  bulkEdits.current = setBulkEditValue({\n    collection,\n    entry,\n    keyPath,\n    value,\n    edits: bulkEdits.current,\n  });\n\n  if (Object.keys(bulkEditErrors.current).length) {\n    bulkEditErrors.current = validateBulkEdits({\n      collection,\n      entries: bulkEditedEntries.current,\n      edits: bulkEdits.current,\n    });\n  }\n};\n","<!--\n  @component\n  Render the entry list in bulk edit mode: a spreadsheet-like table with a row for each listed entry\n  and a column for each field that can be edited in bulk, holding the field’s own control. The\n  edits are kept in the `bulkEdits` store until the toolbar Save button writes them in one commit.\n\n  The entries are snapshotted when the mode is entered, in the order and groups of the current view,\n  so a background refresh doesn’t move the rows from under the user. The view can’t be changed while\n  the mode is on, as the secondary toolbar is hidden.\n-->\n<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { InfiniteScroll, TruncatedText } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import BulkEditCell from '$lib/components/contents/list/bulk-edit-cell.svelte';\n  import { getGroupLabel } from '$lib/services/common/view';\n  import { getBulkEditValue } from '$lib/services/contents/collection/entries/bulk-edit';\n  import { getBulkEditableFields } from '$lib/services/contents/collection/entries/bulk-edit/config';\n  import {\n    snapshotBulkEditGroups,\n    updateBulkEditValue,\n  } from '$lib/services/contents/collection/entries/bulk-edit/session';\n  import {\n    bulkEditedEntries,\n    bulkEditErrors,\n    bulkEdits,\n    bulkEditSaving,\n  } from '$lib/services/contents/collection/view';\n  import { setEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getEntrySummary } from '$lib/services/contents/entry/summary';\n  import { getFieldLabel } from '$lib/services/contents/i18n/options';\n\n  /**\n   * @import { Entry, InternalEntryCollection } from '$lib/types/private';\n   * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n   * @import { FieldKeyPath } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalEntryCollection} collection Selected entry collection.\n   */\n\n  /** @type {Props} */\n  const { collection } = $props();\n\n  // The field controls are those of the entry editor, some of which look for the draft being\n  // edited, e.g. to offer the entries a Relation field can create. There is no draft here, as the\n  // values are kept in the bulk edits, so the controls are given an empty one, which keeps the\n  // draft-only features off. Each cell provides the values and slug of its row instead, which the\n  // controls read through `getEditorEntryValues()`\n  setEntryDraftContext(/** @type {EntryDraftState} */ ({ current: undefined }));\n\n  const fields = $derived(getBulkEditableFields(collection));\n  const locale = $derived(collection._i18n.defaultLocale);\n\n  /**\n   * Entry groups as they were when the mode was entered, without the entries that can’t be edited.\n   * @type {{ name: string, entries: Entry[] }[]}\n   */\n  let groups = $state.raw([]);\n\n  /**\n   * Record a new value of a field.\n   * @param {Entry} entry Entry.\n   * @param {FieldKeyPath} keyPath Field name.\n   * @param {any} value New value.\n   */\n  const updateValue = (entry, keyPath, value) => {\n    updateBulkEditValue({ collection, entry, keyPath, value });\n  };\n\n  /* v8 ignore start -- the app locale is always set once the UI strings are loaded */\n  /**\n   * Get the plain-text summary of an entry, which names its controls. `appLocale.current` is a key,\n   * because the summary can include a localized label.\n   * @param {Entry} entry Entry.\n   * @returns {string} Summary.\n   */\n  const getSummary = (entry) => (appLocale.current ? getEntrySummary(collection, entry) : '');\n  /* v8 ignore stop */\n\n  /**\n   * 1-based `aria-rowindex` of each entry, keyed by entry ID, after the header row.\n   */\n  const rowIndexMap = $derived(\n    new Map(bulkEditedEntries.current.map((entry, index) => [entry.id, index + 2])),\n  );\n\n  // Snapshot the entry groups once, when the mode is entered. See the component description\n  onMount(() => {\n    groups = snapshotBulkEditGroups(collection);\n  });\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <div\n    role=\"table\"\n    class=\"table\"\n    aria-label={_('bulk_edit_table')}\n    aria-rowcount={bulkEditedEntries.current.length + 1}\n    style:--column-count={fields.length}\n  >\n    <div role=\"row\" class=\"row header\" aria-rowindex={1}>\n      <div role=\"columnheader\" class=\"cell title\">{_('bulk_edit_entry')}</div>\n      {#each fields as field (field.name)}\n        <div role=\"columnheader\" class=\"cell\">{getFieldLabel({ config: field, locale })}</div>\n      {/each}\n      <div role=\"none\" class=\"cell filler\"></div>\n    </div>\n    {#each groups as { name, entries } (name)}\n      {@const groupLabel = name !== '*' ? getGroupLabel(name) : undefined}\n      <!-- The group is named by its row group, so its header isn’t a row that would throw off the\n      row count and indexes -->\n      <div role=\"rowgroup\" class=\"rowgroup\" aria-label={groupLabel}>\n        {#if groupLabel}\n          <div class=\"group-header\" aria-hidden=\"true\">{groupLabel}</div>\n        {/if}\n        <InfiniteScroll items={entries} itemKey=\"id\">\n          {#snippet renderItem(/** @type {Entry} */ entry)}\n            {@const summary = getSummary(entry)}\n            <div role=\"row\" class=\"row\" aria-rowindex={rowIndexMap.get(entry.id)}>\n              <div role=\"rowheader\" class=\"cell title\">\n                <TruncatedText lines={2}>\n                  <!-- `appLocale.current` is a key, because the summary can include a localized\n                label -->\n                  {#key appLocale.current}\n                    <bdi>\n                      {@html getEntrySummary(collection, entry, {\n                        useTemplate: true,\n                        allowMarkdown: true,\n                      })}\n                    </bdi>\n                  {/key}\n                </TruncatedText>\n              </div>\n              {#each fields as fieldConfig (fieldConfig.name)}\n                {@const keyPath = fieldConfig.name}\n                {@const edits = bulkEdits.current[entry.id]}\n                <div role=\"cell\" class=\"cell\">\n                  <BulkEditCell\n                    {locale}\n                    {fieldConfig}\n                    entryLabel={summary}\n                    value={getBulkEditValue({\n                      collection,\n                      entry,\n                      keyPath,\n                      edits: bulkEdits.current,\n                    })}\n                    {entry}\n                    entryEdits={edits}\n                    edited={!!edits && Object.hasOwn(edits, keyPath)}\n                    errors={bulkEditErrors.current[entry.id]?.[keyPath]}\n                    readonly={bulkEditSaving.current}\n                    onChange={(value) => {\n                      updateValue(entry, keyPath, value);\n                    }}\n                  />\n                </div>\n              {/each}\n              <div role=\"none\" class=\"cell filler\"></div>\n            </div>\n          {/snippet}\n        </InfiniteScroll>\n      </div>\n    {/each}\n  </div>\n</div>\n\n<style>\n  .wrapper {\n    height: 100%;\n    overflow: auto;\n    overscroll-behavior: contain;\n  }\n\n  .table {\n    display: grid;\n    /* The entry titles, a column sized to its control for each field, and a filler taking up the\n      rest of the width so the row borders run across the list */\n    grid-template-columns: minmax(160px, 280px) repeat(var(--column-count), max-content) 1fr;\n    width: max-content;\n    min-width: 100%;\n\n    :global {\n      .spinner {\n        grid-column: 1 / -1;\n      }\n    }\n  }\n\n  .rowgroup,\n  .row {\n    display: contents;\n  }\n\n  .group-header {\n    grid-column: 1 / -1;\n    border-bottom: 1px solid var(--sui-secondary-border-color);\n    padding: 4px 8px;\n    font-weight: var(--sui-font-weight-bold);\n    background-color: var(--sui-secondary-background-color);\n  }\n\n  .cell {\n    display: flex;\n    align-items: center;\n    border-bottom: 1px solid var(--sui-secondary-border-color);\n    padding: 4px 8px;\n    min-width: 0;\n\n    &.filler {\n      padding: 0;\n    }\n\n    /* The entry titles stay in view as the table is scrolled sideways, like a frozen column */\n    &.title {\n      position: sticky;\n      inset-inline-start: 0;\n      z-index: 1;\n      border-inline-end: 1px solid var(--sui-secondary-border-color);\n      background-color: var(--sui-primary-background-color);\n    }\n  }\n\n  .header .cell {\n    position: sticky;\n    top: 0;\n    z-index: 2;\n    background-color: var(--sui-primary-background-color);\n    font-size: var(--sui-font-size-small);\n    font-weight: var(--sui-font-weight-bold);\n\n    &.title {\n      z-index: 3;\n    }\n  }\n</style>\n","<!--\n  @component\n  Shared cells (checkbox, thumbnail image, title) used by both the read-only entry list row and the\n  reorder list row. In the table view, the title is replaced by a cell for each column.\n-->\n<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Checkbox, GridCell, Icon, TruncatedText } from '@sveltia/ui';\n\n  import EntryThumbnail from '$lib/components/contents/shared/entry-thumbnail.svelte';\n  import StatusBadge from '$lib/components/workflow/status-badge.svelte';\n  import { getAdditions } from '$lib/services/app/additions';\n  import { selectedEntryIdSet } from '$lib/services/contents/collection/entries';\n  import {\n    getIndexFile,\n    isCollectionIndexFile,\n  } from '$lib/services/contents/collection/entries/index-file';\n  import { getTableCellValue } from '$lib/services/contents/collection/view/table';\n  import { SUMMARY_COLUMN_KEY } from '$lib/services/contents/collection/view/table-keys';\n  import { getEntrySummary } from '$lib/services/contents/entry/summary';\n  import { env } from '$lib/services/user/env.svelte';\n  import { getEntryStage } from '$lib/services/workflow/stages';\n\n  /**\n   * @import {\n   * Entry,\n   * EntryTableColumn,\n   * InternalEntryCollection,\n   * UnpublishedEntry,\n   * ViewType,\n   * } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalEntryCollection} collection Selected collection.\n   * @property {Entry} entry Entry.\n   * @property {ViewType} viewType View type.\n   * @property {boolean} [showCheckbox] Whether to render the selection checkbox cell. Defaults to\n   * `false`; the read-only list row passes `true`, while the reorder row leaves it off.\n   * @property {(selected: boolean) => void} [onSelect] Selection change handler.\n   * @property {EntryTableColumn[]} [columns] Columns of the table view, which take the place of the\n   * title. Only used when `viewType` is `table`.\n   */\n\n  /** @type {Props} */\n  let {\n    collection,\n    entry,\n    viewType,\n    showCheckbox = false,\n    onSelect = undefined,\n    columns = [],\n  } = $props();\n\n  // Editorial Workflow information, only present on an unpublished entry\n  const workflow = $derived(/** @type {UnpublishedEntry} */ (entry).workflow);\n  // Sveltia CMS Additions, which tells who else is editing or viewing the entry\n  const additions = $derived(getAdditions());\n  /* v8 ignore start -- the app locale is always set once the UI strings are loaded */\n  // Plain-text summary naming the selection checkbox, so a screen reader hears which entry it\n  // selects rather than an unlabelled checkbox. `appLocale.current` is a key, because the summary\n  // can include a localized label\n  const summary = $derived(appLocale.current ? getEntrySummary(collection, entry) : '');\n  /* v8 ignore stop */\n</script>\n\n{#snippet title()}\n  <GridCell class=\"title\">\n    <div role=\"none\" class=\"label\">\n      <TruncatedText lines={2}>\n        {#key appLocale.current}\n          <bdi>\n            {@html getEntrySummary(collection, entry, { useTemplate: true, allowMarkdown: true })}\n          </bdi>\n        {/key}\n        {#if isCollectionIndexFile(collection, entry)}\n          <Icon name={getIndexFile(collection)?.icon} class=\"home\" />\n        {/if}\n      </TruncatedText>\n    </div>\n  </GridCell>\n{/snippet}\n\n{#if showCheckbox && !(env.isSmallScreen || env.isMediumScreen)}\n  <GridCell class=\"checkbox\">\n    <Checkbox\n      tabindex=\"-1\"\n      ariaLabel={_('select_item', { values: { name: summary } })}\n      checked={selectedEntryIdSet.current.has(entry.id)}\n      onChange={({ detail: { checked } }) => {\n        onSelect?.(checked);\n      }}\n    />\n  </GridCell>\n{/if}\n{#if collection._thumbnailFieldNames.length}\n  <GridCell class=\"image\">\n    <EntryThumbnail {collection} {entry} variant={viewType === 'grid' ? 'tile' : 'icon'} />\n  </GridCell>\n{/if}\n{#if viewType === 'table'}\n  {#each columns as column (column.key)}\n    {#if column.key === SUMMARY_COLUMN_KEY}\n      {@render title()}\n    {:else}\n      {@const { type, value } = getTableCellValue({ collection, entry, column })}\n      <GridCell class=\"column\" data-key={column.key}>\n        {#if type === 'boolean'}\n          {#if value}\n            <Icon name=\"check\" role=\"img\" aria-label={_('boolean.true')} />\n          {/if}\n        {:else}\n          <div role=\"none\" class=\"label\">\n            <TruncatedText><bdi>{value}</bdi></TruncatedText>\n          </div>\n        {/if}\n      </GridCell>\n    {/if}\n  {/each}\n{:else}\n  {@render title()}\n{/if}\n<GridCell class=\"status\">\n  {#if additions}\n    <additions.EntryActivity collectionName={collection.name} subPath={entry.subPath} />\n  {/if}\n  {#if workflow}\n    <StatusBadge status={getEntryStage(/** @type {UnpublishedEntry} */ (entry), collection)} />\n  {/if}\n</GridCell>\n\n<style>\n  .label {\n    :global {\n      .icon.home {\n        opacity: 0.5;\n        font-size: 20px;\n        vertical-align: -4px;\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Render a read-only entry row. Clicking the row navigates to the entry edit page.\n-->\n<script>\n  import { locale as appLocale } from '@sveltia/i18n';\n  import { GridRow } from '@sveltia/ui';\n\n  import EntryListItemCells from '$lib/components/contents/list/entry-list-item-cells.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { selectedEntries } from '$lib/services/contents/collection/entries';\n  import { listedEntryIndexMap } from '$lib/services/contents/collection/view';\n  import { getEntryEditorPath } from '$lib/services/contents/editor/route';\n  import { getEntrySummary } from '$lib/services/contents/entry/summary';\n  import { toggleListItem } from '$lib/services/utils/array';\n  import { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n  /**\n   * @import {\n   * Entry,\n   * EntryTableColumn,\n   * InternalEntryCollection,\n   * ViewType,\n   * } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalEntryCollection} collection Selected collection.\n   * @property {Entry} entry Entry.\n   * @property {ViewType} viewType View type.\n   * @property {EntryTableColumn[]} [columns] Columns of the table view.\n   */\n\n  /** @type {Props} */\n  let { collection, entry, viewType, columns = [] } = $props();\n\n  // `aria-rowindex` is 1-based, unlike the index map. `undefined` for an entry that isn’t listed,\n  // e.g. one filtered out, so the attribute is omitted rather than set to an invalid index.\n  const rowIndex = $derived.by(() => {\n    const index = listedEntryIndexMap.current.get(entry.id);\n\n    if (index === undefined) {\n      return undefined;\n    }\n\n    // The table view’s header row comes first\n    return viewType === 'table' ? index + 2 : index + 1;\n  });\n\n  /* v8 ignore start -- the app locale is always set once the UI strings are loaded */\n  // Names the row, so that it’s announced by the entry it holds rather than by the text of every\n  // cell, including the selection checkbox’s own label. `appLocale.current` is a key, because the\n  // summary can include a localized label\n  const summary = $derived(appLocale.current ? getEntrySummary(collection, entry) : '');\n  /* v8 ignore stop */\n\n  /**\n   * Update the entry selection.\n   * @param {boolean} selected Whether the current entry item is selected.\n   */\n  const updateSelection = (selected) => {\n    selectedEntries.current = toggleListItem(selectedEntries.current, entry, selected);\n  };\n</script>\n\n<GridRow\n  aria-rowindex={rowIndex}\n  aria-label={summary}\n  onChange={(event) => {\n    updateSelection(event.detail.selected);\n  }}\n  onclick={() => {\n    goto(getEntryEditorPath(collection.name, entry.subPath), {\n      transitionType: 'forwards',\n    });\n  }}\n>\n  <!-- Deleting entries is the only bulk action, and it’s not available to an Open Authoring\n  contributor, so the selection checkboxes would do nothing for them -->\n  <EntryListItemCells\n    {collection}\n    {entry}\n    {viewType}\n    {columns}\n    showCheckbox={!openAuthoring.current}\n    onSelect={updateSelection}\n  />\n</GridRow>\n","<!--\n  @component\n  Render the contents of an entry row in reorder mode: the regular list cells, plus the Move Up /\n  Move Down buttons that reorder the entry without a pointer.\n\n  The row element itself lives in `entry-reorder-list.svelte`. It has to be a plain element there —\n  `animate:` only works on an element at the top level of a keyed `each` block, never on a component\n  — so the drag handling stays with the list and this component supplies only what goes inside.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, GridCell, Icon } from '@sveltia/ui';\n  import { tick } from 'svelte';\n\n  import EntryListItemCells from '$lib/components/contents/list/entry-list-item-cells.svelte';\n  import { focusItemReorderControl } from '$lib/services/utils/drag-sorting';\n\n  /**\n   * @import { Entry, InternalEntryCollection, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalEntryCollection} collection Selected collection.\n   * @property {Entry} entry Entry.\n   * @property {ViewType} viewType View type.\n   * @property {boolean} [canMoveUp] Whether the Move Up action is available.\n   * @property {boolean} [canMoveDown] Whether the Move Down action is available.\n   * @property {() => void} [onMoveUp] Move up handler.\n   * @property {() => void} [onMoveDown] Move down handler.\n   */\n\n  /** @type {Props} */\n  let {\n    collection,\n    entry,\n    viewType,\n    canMoveUp = false,\n    canMoveDown = false,\n    onMoveUp = undefined,\n    onMoveDown = undefined,\n  } = $props();\n\n  /**\n   * Move the entry with one of the buttons, and keep the focus on the row once it has moved: the\n   * row element may be moved along with the button, which loses the focus, and the button may be\n   * disabled now that the entry has reached either end of the list.\n   * @param {MouseEvent} event `click` event.\n   * @param {string} action `data-action` of the button.\n   * @param {(() => void) | undefined} handler Move handler.\n   */\n  const move = async (event, action, handler) => {\n    event.stopPropagation();\n\n    const row = /** @type {HTMLElement} */ (event.currentTarget).closest('[role=\"row\"]');\n\n    handler?.();\n    await tick();\n    focusItemReorderControl({ item: row, action });\n  };\n</script>\n\n<EntryListItemCells {collection} {entry} {viewType} />\n<GridCell class=\"reorder-actions\">\n  <Button\n    variant=\"ghost\"\n    iconic\n    disabled={!canMoveUp}\n    data-action=\"move-up\"\n    aria-label={_('move_up')}\n    onclick={(event) => move(event, 'move-up', onMoveUp)}\n  >\n    {#snippet startIcon()}\n      <Icon name=\"arrow_upward\" />\n    {/snippet}\n  </Button>\n  <Button\n    variant=\"ghost\"\n    iconic\n    disabled={!canMoveDown}\n    data-action=\"move-down\"\n    aria-label={_('move_down')}\n    onclick={(event) => move(event, 'move-down', onMoveDown)}\n  >\n    {#snippet startIcon()}\n      <Icon name=\"arrow_downward\" />\n    {/snippet}\n  </Button>\n</GridCell>\n","<!--\n  @component\n  Render the entry list in reorder mode. Each group is shown as its own `GridBody` with\n  drag-and-drop reordering. The flattened ordered entries are published to the `reorderedEntries`\n  store so the toolbar Save button can read it.\n\n  There is normally a single, unnamed group because entering reorder mode clears the active\n  grouping. A collection using `reorder: { group: '…' }` is grouped by the named view group instead,\n  in which case dragging is locked within a group: entries are renumbered group by group, and moving\n  an entry across groups wouldn’t update the field that determines which group it belongs to.\n-->\n<script>\n  import { GridBody } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import { onMount } from 'svelte';\n  import { flip } from 'svelte/animate';\n\n  import EntryReorderListItem from '$lib/components/contents/list/entry-reorder-list-item.svelte';\n  import { getGroupLabel } from '$lib/services/common/view';\n  import { isCollectionIndexFile } from '$lib/services/contents/collection/entries/index-file';\n  import { sortEntriesByOrderField } from '$lib/services/contents/collection/entries/reorder/sort';\n  import {\n    entryGroups,\n    reorderDirty,\n    reorderedEntries,\n  } from '$lib/services/contents/collection/view';\n  import { getDropIndex, getMoveTarget, moveListItem } from '$lib/services/utils/drag-sorting';\n\n  /**\n   * @import { Entry, InternalEntryCollection, ViewType } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalEntryCollection} collection Selected entry collection.\n   * @property {ViewType} viewType View type passed through to entry items.\n   */\n\n  /** @type {Props} */\n  const { collection, viewType } = $props();\n\n  // The entry lists, and the entries in them, are kept raw rather than deeply proxied by `$state`:\n  // they’re published to `reorderedEntries`, and the saved entries end up in the entry store, where\n  // the content editor clones them with `structuredClone()`, which throws on a proxy. Each change\n  // therefore replaces the object rather than mutating it\n  /**\n   * Per-group entry lists maintained during reorder mode.\n   * @type {{ [groupName: string]: Entry[] }}\n   */\n  let reorderGroups = $state.raw({});\n\n  /**\n   * The group name and entry order as they were when the current drag started, so that an abandoned\n   * drag can put the entries back, and so drops in any other group can be rejected. `undefined`\n   * while no drag is in progress.\n   * @type {{ name: string, entries: Entry[] } | undefined}\n   */\n  let dragOrigin = $state.raw();\n\n  /**\n   * The entry currently being dragged.\n   * @type {Entry | undefined}\n   */\n  let draggedEntry = $state.raw();\n\n  /**\n   * Sync the flattened ordered entries back to the shared store so the toolbar Save button can read\n   * it.\n   * @param {{ [groupName: string]: Entry[] }} groups Per-group entry lists. Defaults to the current\n   * {@link reorderGroups}.\n   */\n  const publishOrder = (groups = reorderGroups) => {\n    /* v8 ignore next 3 -- every group has been snapshotted on mount */\n    reorderedEntries.current = entryGroups.current.flatMap(\n      ({ name, entries }) => groups[name] ?? entries,\n    );\n  };\n\n  /* v8 ignore start -- every group has been snapshotted on mount */\n  /**\n   * Get the entries of a group as they are being reordered.\n   * @param {string} name Group name.\n   * @param {Entry[]} entries Entries as listed, used until the group is snapshotted on mount.\n   * @returns {Entry[]} Entries.\n   */\n  const getLocalEntries = (name, entries) => reorderGroups[name] ?? entries;\n  /* v8 ignore stop */\n\n  // Map from entry ID to the entry’s 0-based row index, which follows the order being edited across\n  // the groups, as the rows of every group make up one grid\n  const rowIndexMap = $derived(\n    new Map(\n      entryGroups.current\n        .flatMap(({ name, entries }) => getLocalEntries(name, entries))\n        .map((entry, index) => [entry.id, index]),\n    ),\n  );\n\n  /**\n   * Get the 1-based `aria-rowindex` of a listed entry.\n   * @param {Entry} entry Entry.\n   * @returns {number} Row index.\n   */\n  const rowIndex = (entry) => /** @type {number} */ (rowIndexMap.get(entry.id)) + 1;\n\n  /**\n   * Move an entry within a group from one index to another, and mark the new order as unsaved.\n   * This is the committed move behind the Move Up / Move Down buttons; a drag previews the move\n   * first and only commits it on drop.\n   * @param {string} groupName Group name.\n   * @param {number} from Source index.\n   * @param {number} to Destination index.\n   */\n  const moveEntry = (groupName, from, to) => {\n    /* v8 ignore next -- the buttons are disabled at either end of the list */\n    if (from === to) return;\n\n    /* v8 ignore next -- every group has been snapshotted on mount */\n    const list = reorderGroups[groupName] ?? [];\n\n    reorderGroups = { ...reorderGroups, [groupName]: moveListItem(list, from, to) };\n    reorderDirty.current = true;\n    publishOrder();\n  };\n\n  /**\n   * End the current drag, either keeping the previewed order or restoring the one from before it.\n   *\n   * `drop` fires before `dragend`, so a completed drop clears the origin here and the `dragend`\n   * that follows finds nothing left to undo.\n   * @param {boolean} commit Whether to keep the previewed order.\n   */\n  const finishDrag = (commit) => {\n    if (dragOrigin) {\n      const { name, entries } = dragOrigin;\n\n      if (commit) {\n        // The pointer may well have returned to where it started, in which case nothing moved\n        /* v8 ignore next -- every group has been snapshotted on mount */\n        if ((reorderGroups[name] ?? []).some((entry, index) => entry.id !== entries[index]?.id)) {\n          reorderDirty.current = true;\n          publishOrder();\n        }\n      } else {\n        reorderGroups = { ...reorderGroups, [name]: entries };\n      }\n    }\n\n    dragOrigin = undefined;\n    draggedEntry = undefined;\n  };\n\n  // Snapshot the entry groups exactly once when this component mounts (i.e. when the user enters\n  // reorder mode). Any subsequent reactive updates to `entryGroups.current` — for example, a\n  // background refresh after another tab’s commit — must not clobber the user’s in-progress drag\n  // arrangement.\n  // The reorder UI takes ownership of the list until Save or Cancel. `onMount` runs once and never\n  // re-subscribes, which is exactly the lifetime we need here (vs. `$effect` + `untrack`).\n  onMount(() => {\n    // Exclude the index file (e.g. Hugo `_index.md`) from reorder: it is always pinned to the top\n    // of the list regardless of its `order` value, so dragging it has no effect.\n    const initial = Object.fromEntries(\n      entryGroups.current.map(({ name, entries }) => [\n        name,\n        sortEntriesByOrderField(\n          entries.filter((entry) => !isCollectionIndexFile(collection, entry)),\n          collection,\n        ),\n      ]),\n    );\n\n    reorderGroups = initial;\n    publishOrder(initial);\n  });\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  {#each entryGroups.current as { name, entries } (name)}\n    {#await sleep() then}\n      <GridBody label={name !== '*' ? getGroupLabel(name) : undefined}>\n        {@const localEntries = getLocalEntries(name, entries)}\n        {#each localEntries as entry, index (entry.id)}\n          <!--\n            The row is written out here rather than with `<GridRow>` because `animate:` only works\n            on an element at the top level of a keyed `each` block, never on a component. Dragging\n            reorders `reorderGroups` as the pointer moves, so the other rows slide out of the way\n            and the gap the entry would land in follows the pointer.\n          -->\n          <div\n            role=\"row\"\n            class=\"sui grid-row\"\n            class:drag-placeholder={draggedEntry?.id === entry.id}\n            tabindex=\"0\"\n            aria-rowindex={rowIndex(entry)}\n            aria-selected=\"false\"\n            draggable=\"true\"\n            ondragstart={(/** @type {DragEvent} */ event) => {\n              dragOrigin = { name, entries: [...localEntries] };\n              draggedEntry = entry;\n\n              if (event.dataTransfer) {\n                event.dataTransfer.effectAllowed = 'move';\n              }\n            }}\n            ondragover={(/** @type {DragEvent & { currentTarget: HTMLElement }} */ event) => {\n              // Reject the drop when it targets another group, so the browser shows a “no drop”\n              // cursor. This also rejects anything dragged in from outside the list, where there is\n              // no drag origin at all.\n              const accepted = name === dragOrigin?.name;\n\n              if (accepted) {\n                event.preventDefault();\n\n                /* v8 ignore next -- every group has been snapshotted on mount */\n                const list = reorderGroups[name] ?? [];\n                const from = list.findIndex(({ id }) => id === draggedEntry?.id);\n\n                const to = getMoveTarget({\n                  dragIndex: from,\n                  dropIndex: getDropIndex({\n                    index,\n                    clientY: event.clientY,\n                    rect: event.currentTarget.getBoundingClientRect(),\n                  }),\n                });\n\n                if (to !== undefined) {\n                  reorderGroups = { ...reorderGroups, [name]: moveListItem(list, from, to) };\n                }\n              }\n\n              if (event.dataTransfer) {\n                event.dataTransfer.dropEffect = accepted ? 'move' : 'none';\n              }\n            }}\n            ondrop={(/** @type {DragEvent} */ event) => {\n              event.preventDefault();\n              // `AppShell` accepts every drop so the browser doesn’t navigate away from a stray\n              // file, which means a drop rejected above can still land here. Releasing over another\n              // group shows the “no drop” cursor, so it has to put the entries back rather than\n              // commit the arrangement the pointer left behind.\n              finishDrag(name === dragOrigin?.name);\n            }}\n            ondragend={() => {\n              finishDrag(false);\n            }}\n            animate:flip={{ duration: 200 }}\n          >\n            <EntryReorderListItem\n              {collection}\n              {entry}\n              {viewType}\n              canMoveUp={index > 0}\n              canMoveDown={index < localEntries.length - 1}\n              onMoveUp={() => {\n                moveEntry(name, index, index - 1);\n              }}\n              onMoveDown={() => {\n                moveEntry(name, index, index + 1);\n              }}\n            />\n          </div>\n        {/each}\n      </GridBody>\n    {/await}\n  {/each}\n</div>\n\n<style>\n  .wrapper {\n    :global {\n      /* The rows aren’t `<GridRow>` components, so they don’t get its scoped layout rules */\n      .grid-row {\n        display: table-row;\n        height: var(--sui-primary-row-height);\n      }\n\n      /* The dragged row is left as a faint placeholder by the global `drag-placeholder` rule */\n      .grid-row.drag-placeholder {\n        cursor: grabbing;\n      }\n\n      .grid-row[draggable='true']:not(.drag-placeholder) {\n        cursor: grab;\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Render the header row of the entry list’s table view, with a header for each column. A column the\n  entries can be sorted by has a button that sorts them, the same way the Sort menu does.\n-->\n<script>\n  import { GridColHeader, GridHead, GridRow } from '@sveltia/ui';\n\n  import { currentView } from '$lib/services/contents/collection/view/settings';\n  import { sortKeys } from '$lib/services/contents/collection/view/sort-keys';\n  import { getColumnSortKey } from '$lib/services/contents/collection/view/table';\n  import { SUMMARY_COLUMN_KEY } from '$lib/services/contents/collection/view/table-keys';\n\n  /**\n   * @import { EntryTableColumn, InternalEntryCollection } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {InternalEntryCollection} collection Selected collection.\n   * @property {EntryTableColumn[]} columns Columns.\n   * @property {boolean} showCheckbox Whether the rows have a selection checkbox cell.\n   */\n\n  /** @type {Props} */\n  const { collection, columns, showCheckbox } = $props();\n\n  const availableSortKeys = $derived(sortKeys.current.map(({ key }) => key));\n</script>\n\n<GridHead>\n  <GridRow aria-rowindex={1}>\n    {#if showCheckbox}\n      <GridColHeader class=\"checkbox\" />\n    {/if}\n    {#if collection._thumbnailFieldNames.length}\n      <GridColHeader class=\"image\" />\n    {/if}\n    {#each columns as column (column.key)}\n      {@const sortKey = getColumnSortKey({ collection, column, sortKeys: availableSortKeys })}\n      {@const { sort } = currentView.current}\n      {#if sortKey}\n        <GridColHeader\n          class={column.key === SUMMARY_COLUMN_KEY ? 'title' : 'column'}\n          sortOrder={sort?.key === sortKey ? sort.order : 'none'}\n          onSort={(/** @type {CustomEvent} */ event) => {\n            currentView.current = {\n              ...currentView.current,\n              sort: { key: sortKey, order: event.detail.sortOrder },\n            };\n          }}\n        >\n          {column.label}\n        </GridColHeader>\n      {:else}\n        <GridColHeader class={column.key === SUMMARY_COLUMN_KEY ? 'title' : 'column'}>\n          {column.label}\n        </GridColHeader>\n      {/if}\n    {/each}\n    <GridColHeader class=\"status\" />\n  </GridRow>\n</GridHead>\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Button, Icon, Menu, MenuItem, SplitButton } from '@sveltia/ui';\n\n  import { goto } from '$lib/services/app/navigation';\n  import { allEntries } from '$lib/services/contents';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import { canCreateIndexFile } from '$lib/services/contents/collection/entries';\n  import { getIndexFile } from '$lib/services/contents/collection/entries/index-file';\n  import { getMetaPathConfig, nestedFilterPath } from '$lib/services/contents/collection/nested';\n  import { collectionState } from '$lib/services/contents/collection/view';\n  import { encodeFilePath } from '$lib/services/utils/file';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} collectionName Collection name.\n   * @property {string} [label] Button label. If `undefined`, the button will be iconic.\n   * @property {string} [keyShortcuts] Keyboard shortcuts.\n   */\n\n  /** @type {Props} */\n  let { collectionName, label = undefined, keyShortcuts = undefined } = $props();\n\n  /* v8 ignore start -- only rendered while a collection is selected, once the locale is loaded */\n  const hasOptions = $derived(\n    // Use `allEntries.current` as a trigger to update the state when a new entry is created\n    allEntries.current && selectedCollection.current\n      ? canCreateIndexFile(selectedCollection.current)\n      : false,\n  );\n  const indexFileLabel = $derived(\n    // `appLocale.current` is a key, because `getIndexFile` can return a localized label\n    appLocale.current && selectedCollection.current\n      ? getIndexFile(selectedCollection.current)?.label\n      : '',\n  );\n  /* v8 ignore stop */\n  const ButtonComponent = $derived(hasOptions ? SplitButton : Button);\n\n  /**\n   * Open the content editor.\n   * @param {boolean} [index] Whether to create the index file instead of a regular entry.\n   */\n  const openEditor = (index = false) => {\n    // Start a new entry in the folder the user is browsing, which the path editor picks up\n    const path =\n      !index &&\n      selectedCollection.current &&\n      getMetaPathConfig(selectedCollection.current) &&\n      nestedFilterPath.current\n        ? `?path=${encodeFilePath(nestedFilterPath.current)}`\n        : '';\n\n    goto(`/collections/${collectionName}/new${path}`, {\n      state: { index },\n      transitionType: 'forwards',\n    });\n  };\n</script>\n\n{#snippet optionMenu()}\n  <Menu>\n    <MenuItem label={_('entry')} onclick={() => openEditor()} />\n    <MenuItem label={indexFileLabel} onclick={() => openEditor(true)} />\n  </Menu>\n{/snippet}\n\n<!-- A plain `Button` opens a popup on click whenever it’s given one, even an empty one, which\nwould take the focus and make the content editor inert while it closes -->\n<ButtonComponent\n  variant=\"primary\"\n  iconic={!label}\n  disabled={collectionState.current.creationDisabled}\n  {label}\n  aria-label={_('create_new_entry')}\n  {keyShortcuts}\n  onclick={() => openEditor()}\n  popup={hasOptions ? optionMenu : undefined}\n>\n  {#snippet startIcon()}\n    <Icon name=\"edit\" />\n  {/snippet}\n</ButtonComponent>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState, GridBody, InfiniteScroll } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import { untrack } from 'svelte';\n\n  import ListContainer from '$lib/components/common/list-container.svelte';\n  import ListingGrid from '$lib/components/common/listing-grid.svelte';\n  import EntryBulkEditList from '$lib/components/contents/list/entry-bulk-edit-list.svelte';\n  import EntryListItem from '$lib/components/contents/list/entry-list-item.svelte';\n  import EntryReorderList from '$lib/components/contents/list/entry-reorder-list.svelte';\n  import EntryTableHead from '$lib/components/contents/list/entry-table-head.svelte';\n  import CreateEntryButton from '$lib/components/contents/toolbar/create-entry-button.svelte';\n  import {\n    getGroupLabel,\n    isCollapsedByDefault,\n    isGroupCollapsed,\n    setGroupCollapsed,\n  } from '$lib/services/common/view';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import {\n    bulkEditing,\n    entryGroups,\n    listedEntries,\n    listedUnpublishedEntries,\n    reordering,\n  } from '$lib/services/contents/collection/view';\n  import { viewGroups } from '$lib/services/contents/collection/view/group';\n  import {\n    currentView,\n    getEntryOrderKey,\n    getEntryViewType,\n    getEntryViewTypes,\n  } from '$lib/services/contents/collection/view/settings';\n  import { sortKeys } from '$lib/services/contents/collection/view/sort-keys';\n  import { getTableColumns } from '$lib/services/contents/collection/view/table';\n  import { getEntryLocaleFile } from '$lib/services/contents/entry/paths';\n  import { env } from '$lib/services/user/env.svelte';\n  import { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n  /**\n   * @import { Entry, EntryTableColumn, InternalEntryCollection } from '$lib/types/private';\n   */\n\n  const collection = $derived(\n    /** @type {InternalEntryCollection | undefined} */ (selectedCollection.current),\n  );\n  const viewType = $derived(\n    getEntryViewType({\n      type: currentView.current.type,\n      types: getEntryViewTypes(collection),\n      isLargeScreen: env.isLargeScreen,\n      reordering: reordering.current,\n    }),\n  );\n  /** @type {EntryTableColumn[]} */\n  const columns = $derived(\n    viewType === 'table' && collection\n      ? getTableColumns({ collection, sortKeys: sortKeys.current.map(({ key }) => key) })\n      : [],\n  );\n  const collapsedByDefault = $derived(\n    isCollapsedByDefault(viewGroups.current, currentView.current.group),\n  );\n  const hasEntries = $derived(entryGroups.current.some(({ entries }) => entries.length));\n  // Changes when the entries are sorted, filtered or grouped differently, which starts the list\n  // again from the top: the rows are rendered anew a chunk at a time, rather than every row loaded\n  // so far being rendered at once in the new order, and the list is scrolled back to the top\n  const orderKey = $derived(getEntryOrderKey(currentView.current));\n\n  /**\n   * Get a promise that defers rendering the rows of a group by a tick, so the toolbar stays\n   * responsive while the groups are rendered anew, e.g. after a sort. The table view renders them\n   * right away instead: waiting would leave the table with its header alone for a moment, and its\n   * columns, sized to fit the cells, would collapse and spring back. The view type is read without\n   * being tracked, so switching views later doesn’t render the groups anew and lose the rows loaded\n   * so far.\n   * @returns {Promise<void> | undefined} Promise, or `undefined` to render right away.\n   */\n  const deferRows = () => (untrack(() => viewType) === 'table' ? undefined : sleep());\n</script>\n\n{#snippet group(\n  /** @type {InternalEntryCollection} */ _collection,\n  /** @type {string} */ name,\n  /** @type {Entry[]} */ entries,\n)}\n  {@const { defaultLocale } = _collection._i18n}\n  <GridBody\n    label={name !== '*'\n      ? getGroupLabel(name)\n      : listedUnpublishedEntries.current.length\n        ? _('workflow.published_entries')\n        : undefined}\n    collapsible={name !== '*'}\n    expanded={!isGroupCollapsed(currentView.current, name, collapsedByDefault)}\n    onChange={({ detail: { expanded } }) => {\n      currentView.current = setGroupCollapsed(\n        currentView.current,\n        name,\n        !expanded,\n        collapsedByDefault,\n      );\n    }}\n  >\n    <InfiniteScroll\n      items={entries.filter((entry) => !!getEntryLocaleFile(entry, { defaultLocale })?.content)}\n      itemKey=\"id\"\n    >\n      {#snippet renderItem(/** @type {Entry} */ entry)}\n        <EntryListItem collection={_collection} {entry} {viewType} {columns} />\n      {/snippet}\n    </InfiniteScroll>\n  </GridBody>\n{/snippet}\n\n<ListContainer aria-label={_('entry_list')}>\n  {#if collection}\n    {#if bulkEditing.current}\n      <EntryBulkEditList {collection} />\n    {:else if hasEntries || listedUnpublishedEntries.current.length}\n      <ListingGrid\n        {viewType}\n        id=\"entry-list\"\n        aria-label={_('entries')}\n        scrollKey={orderKey}\n        aria-rowcount={listedEntries.current.length +\n          listedUnpublishedEntries.current.length +\n          (viewType === 'table' ? 1 : 0)}\n      >\n        {#if reordering.current}\n          <EntryReorderList {collection} {viewType} />\n        {:else}\n          {#if viewType === 'table'}\n            <!-- The table view is only shown on a large screen, where the rows have checkboxes -->\n            <EntryTableHead {collection} {columns} showCheckbox={!openAuthoring.current} />\n          {/if}\n          {#if listedUnpublishedEntries.current.length}\n            <GridBody label={_('workflow.unpublished_entries')}>\n              {#each listedUnpublishedEntries.current as entry (entry.id)}\n                <EntryListItem {collection} {entry} {viewType} {columns} />\n              {/each}\n            </GridBody>\n          {/if}\n          {#key orderKey}\n            {#each entryGroups.current as { name, entries } (name)}\n              {#await deferRows() then}\n                {@render group(collection, name, entries)}\n              {/await}\n            {/each}\n          {/key}\n        {/if}\n      </ListingGrid>\n    {:else if listedEntries.current.length}\n      <EmptyState>\n        <span role=\"none\">{_('no_entries_found')}</span>\n      </EmptyState>\n    {:else}\n      <EmptyState>\n        <span role=\"none\">{_('no_entries_created')}</span>\n        <CreateEntryButton collectionName={collection.name} label={_('create_new_entry')} />\n      </EmptyState>\n    {/if}\n  {:else}\n    <EmptyState>\n      <span role=\"none\">{_('collection_not_found')}</span>\n    </EmptyState>\n  {/if}\n</ListContainer>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState, GridCell, GridRow, Icon, InfiniteScroll, TruncatedText } from '@sveltia/ui';\n\n  import ListContainer from '$lib/components/common/list-container.svelte';\n  import ListingGrid from '$lib/components/common/listing-grid.svelte';\n  import StatusBadge from '$lib/components/workflow/status-badge.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import { isValidCollectionFile } from '$lib/services/contents/collection/predicates';\n  import { getEntryEditorPath } from '$lib/services/contents/editor/route';\n  import { getCollectionFileSummary } from '$lib/services/contents/entry/summary';\n  import { unpublishedEntries } from '$lib/services/workflow';\n  import { getEntryStage } from '$lib/services/workflow/stages';\n\n  /**\n   * @import { CollectionFile } from '$lib/types/public';\n   * @import { InternalFileCollection, WorkflowStatus } from '$lib/types/private';\n   */\n\n  const files = $derived(\n    /** @type {InternalFileCollection} */ (selectedCollection.current)?.files.filter(\n      isValidCollectionFile,\n    ) ?? [],\n  );\n\n  /**\n   * Editorial Workflow stage of each file that has an open pull request, keyed by file name. A\n   * file collection needs no Unpublished/Published sections like an entry collection, because every\n   * file is published from the start and can only be updated, never added or removed.\n   * @type {Record<string, WorkflowStatus>}\n   */\n  const statuses = $derived(\n    Object.fromEntries(\n      unpublishedEntries.current\n        .filter(({ workflow }) => workflow.collectionName === selectedCollection.current?.name)\n        .map((entry) => [\n          entry.workflow.fileName,\n          getEntryStage(entry, selectedCollection.current),\n        ]),\n    ),\n  );\n</script>\n\n<ListContainer aria-label={_('file_list')}>\n  {#if files?.length}\n    <ListingGrid viewType=\"list\" aria-label={_('files')} aria-rowcount={files.length}>\n      <InfiniteScroll items={files} itemKey=\"name\">\n        {#snippet renderItem(/** @type {CollectionFile} */ { name, label, icon })}\n          <!-- HTML, as the summary can contain Markdown, like an entry collection’s -->\n          {@const summary = getCollectionFileSummary(\n            /** @type {InternalFileCollection} */ (selectedCollection.current),\n            name,\n          )}\n          <GridRow\n            onclick={() => {\n              goto(getEntryEditorPath(`${selectedCollection.current?.name}`, name), {\n                transitionType: 'forwards',\n              });\n            }}\n          >\n            <GridCell class=\"title\">\n              <div role=\"none\" class=\"label\">\n                {#if icon}\n                  <Icon name={icon} />\n                {/if}\n                <TruncatedText lines={2}>\n                  {#if summary !== undefined}\n                    <bdi>{@html summary}</bdi>\n                  {:else}\n                    {label || name}\n                  {/if}\n                </TruncatedText>\n              </div>\n            </GridCell>\n            <GridCell class=\"status\">\n              {#if statuses[name]}\n                <StatusBadge status={statuses[name]} />\n              {/if}\n            </GridCell>\n          </GridRow>\n        {/snippet}\n      </InfiniteScroll>\n    </ListingGrid>\n  {:else}\n    <EmptyState>\n      <span role=\"none\">{_('no_files_in_collection')}</span>\n    </EmptyState>\n  {/if}\n</ListContainer>\n\n<style>\n  .label {\n    display: flex;\n    align-items: center;\n    gap: 16px;\n\n    :global(.icon) {\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      border-radius: var(--sui-control-medium-border-radius);\n      width: var(--icon-size);\n      height: var(--icon-size);\n      background-color: var(--sui-secondary-background-color);\n    }\n  }\n</style>\n","<script>\n  import { Icon, TreeItem } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  // The component recursively renders itself for the child folders\n  import NestedTreeItem from '$lib/components/contents/list/nested-tree-item.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import { isDescendantPath, nestedFilterPath } from '$lib/services/contents/collection/nested';\n  import { encodePathSegments } from '$lib/services/utils/url';\n\n  /**\n   * @import { NestedTreeNode } from '$lib/services/contents/collection/nested/tree';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {NestedTreeNode} node Folder to display.\n   * @property {string} collectionName Name of the collection the folder belongs to.\n   */\n\n  /** @type {Props} */\n  let { node, collectionName } = $props();\n\n  const { path, label, children } = $derived(node);\n  const isCurrentCollection = $derived(selectedCollection.current?.name === collectionName);\n  const selected = $derived(isCurrentCollection && nestedFilterPath.current === path);\n  const hasCurrentDescendant = $derived(\n    isCurrentCollection && isDescendantPath(path, nestedFilterPath.current),\n  );\n\n  let expanded = $state(false);\n\n  // Open the tree down to the folder being browsed, but leave the folders the user has opened or\n  // closed by hand alone\n  $effect(() => {\n    if (selected || hasCurrentDescendant) {\n      untrack(() => {\n        expanded = true;\n      });\n    }\n  });\n</script>\n\n{#snippet childItems()}\n  {#each children as child (child.path)}\n    <NestedTreeItem node={child} {collectionName} />\n  {/each}\n{/snippet}\n\n<TreeItem\n  {label}\n  {selected}\n  bind:expanded\n  items={children.length ? childItems : undefined}\n  onSelect={() => {\n    goto(encodePathSegments(`/collections/${collectionName}/filter/${path}`), {\n      transitionType: 'forwards',\n    });\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name=\"folder\" />\n  {/snippet}\n</TreeItem>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, TreeItem } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import NestedTreeItem from '$lib/components/contents/list/nested-tree-item.svelte';\n  import { appNumberFormatter } from '$lib/services/app/i18n';\n  import { goto } from '$lib/services/app/navigation';\n  import { getCollection, selectedCollection } from '$lib/services/contents/collection';\n  import { countCollectionEntries } from '$lib/services/contents/collection/entries';\n  import { nestedFilterPath } from '$lib/services/contents/collection/nested';\n  import { getAllEntries } from '$lib/services/contents/collection/nested/i18n';\n  import { getNestedTree } from '$lib/services/contents/collection/nested/tree';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { InternalCollection } from '$lib/types/private';\n   * @import { Collection } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Collection} collection Collection to display.\n   * @property {boolean} [isSearchPage] Whether the current page is the search results page.\n   */\n\n  /** @type {Props} */\n  let { collection, isSearchPage = false } = $props();\n\n  const { name, label, icon } = $derived(collection);\n  const isCurrentCollection = $derived(selectedCollection.current?.name === name);\n\n  const selected = $derived(\n    env.isSmallScreen || isSearchPage ? false : isCurrentCollection && !nestedFilterPath.current,\n  );\n\n  /**\n   * Entries in the collection, with the pending changes merged in: an entry updated in a pull\n   * request is swapped for its draft, and one that’s never been published is added, so the count\n   * and the folder tree reflect what the entry list shows. A folder that only exists in a pull\n   * request — a section started under Editorial Workflow, or a page moved there — can then be\n   * browsed before it’s published. Without it, a draft filed below another draft is nowhere to be\n   * found.\n   */\n  const entries = $derived('files' in collection ? [] : getAllEntries(collection));\n\n  // Hugo’s special index file stands for the collection’s own page rather than for one of the\n  // entries in it, so it’s not counted here, while it’s still shown in the entry list\n  const entryCount = $derived(\n    'files' in collection ? collection.files.length : countCollectionEntries(name, entries),\n  );\n\n  // The collection comes from the configuration, which only has valid ones once it’s loaded\n  const treeNodes = $derived(\n    getNestedTree({\n      collection: /** @type {InternalCollection} */ (getCollection(name)),\n      entries,\n    }),\n  );\n\n  let expanded = $state(false);\n\n  // Open the collection’s folder tree as soon as the user starts browsing it\n  $effect(() => {\n    if (isCurrentCollection) {\n      untrack(() => {\n        expanded = true;\n      });\n    }\n  });\n</script>\n\n{#snippet folderItems()}\n  {#each treeNodes as node (node.path)}\n    <NestedTreeItem {node} collectionName={name} />\n  {/each}\n{/snippet}\n\n<TreeItem\n  label={label || name}\n  {selected}\n  bind:expanded\n  items={treeNodes.length ? folderItems : undefined}\n  onSelect={() => {\n    goto(`/collections/${name}`, { transitionType: 'forwards' });\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name={icon || 'bookmark_manager'} />\n  {/snippet}\n  {#snippet endIcon()}\n    <span\n      class=\"count\"\n      aria-label={entryCount ? _('x_entries', { values: { count: entryCount } }) : undefined}\n    >\n      {appNumberFormatter.current.format(entryCount)}\n    </span>\n  {/snippet}\n</TreeItem>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, TreeItem } from '@sveltia/ui';\n\n  import { announcedPageStatus, goto } from '$lib/services/app/navigation';\n  import { getEntryEditorPath } from '$lib/services/contents/editor/route';\n\n  /**\n   * @import { CollectionFile } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {CollectionFile} file The singleton file to display.\n   */\n\n  /** @type {Props} */\n  let { file } = $props();\n\n  const { name, icon } = $derived(file);\n  const label = $derived(file.label || name);\n\n  /** @type {boolean} */\n  let selected = $state(false);\n  /** @type {HTMLElement | undefined} */\n  let wrapper = $state();\n</script>\n\n<div class=\"wrapper\" bind:this={wrapper}>\n  <TreeItem\n    bind:selected\n    {label}\n    onSelect={() => {\n      // Announce the selected singleton file. The Content Editor will not open until\n      // the user presses Enter.\n      announcedPageStatus.current = _('singleton_selected_announcement', {\n        values: { file: label },\n      });\n    }}\n    onclick={() => {\n      goto(getEntryEditorPath('_singletons', name), {\n        transitionType: 'forwards',\n      });\n      // Reset the selected state and remove the focused class from the option\n      // @todo Handle this in Sveltia UI\n      selected = false;\n      wrapper?.querySelector('[role=\"treeitem\"]')?.classList.remove('focused');\n    }}\n  >\n    {#snippet startIcon()}\n      <Icon name={icon || 'edit_document'} />\n    {/snippet}\n  </TreeItem>\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n  }\n</style>\n","import { backend } from '$lib/services/backends';\nimport { isViewer } from '$lib/services/config/readonly';\nimport {\n  deployments,\n  lastCommitPublishHint,\n  productionSHA,\n  setLastCommitPublishHint,\n} from '$lib/services/deployments';\nimport { getDeployHook } from '$lib/services/user/api-keys';\nimport { isSecureURL } from '$lib/services/utils/networking';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * Whether the last commit on the production branch has been deployed. It decides whether the\n * Publish Changes button in the global toolbar offers to trigger a deployment.\n *\n * What the CI/CD provider reports for the commit is preferred, as long as it was read after the\n * expectation recorded by {@link setLastCommitPublishHint} was formed. A build that ran — whether\n * it’s still running or has finished — means the commit went out, and one that failed means it\n * didn’t, so the site is stale and worth deploying again.\n *\n * Everything else falls back to the expectation. Nothing reported is ambiguous: the provider may\n * have skipped the commit, or the repository may have no CI connected to the Git service at all,\n * and the two are indistinguishable from a single commit.\n */\nexport const isLastCommitPublished = createDerivedState(() => {\n  const { published, time } = lastCommitPublishHint.current;\n  const { current: sha } = productionSHA;\n  const status = sha ? deployments.current[sha] : undefined;\n\n  // A commit still being looked up reports no time, so it falls back here as well\n  if (!status || status.checkedTime <= time) {\n    return published;\n  }\n\n  if (status.state === 'ready' || status.state === 'pending') {\n    return true;\n  }\n\n  if (status.state === 'error') {\n    return false;\n  }\n\n  return published;\n});\n\n/**\n * Whether a deployment can be triggered by hand: there has to be a way to do it — a deploy hook\n * URL configured by the user or shared by an admin, or a backend that can trigger a build itself —\n * and the last commit has to be out of date. A viewer can’t change the site, which includes\n * publishing it.\n */\nexport const canTriggerDeployment = createDerivedState(\n  () =>\n    (!!getDeployHook() || typeof backend.current?.triggerDeployment === 'function') &&\n    !isLastCommitPublished.current &&\n    !isViewer(),\n);\n\n/**\n * Trigger a manual deployment on the CI/CD provider, by calling the deploy hook if there is one,\n * or the backend’s own API otherwise. Once the request has been accepted,\n * the last commit is expected to have started a deployment.\n * @throws {Error} When the deploy hook URL is not secure, or the request has failed.\n */\nexport const triggerDeployment = async () => {\n  const { url: deployHookURL, authHeader: deployHookAuthHeader } = getDeployHook() ?? {};\n\n  if (deployHookURL && !isSecureURL(deployHookURL)) {\n    throw new Error('Deploy hook URL must use HTTPS or localhost');\n  }\n\n  const { ok, status } = deployHookURL\n    ? await fetch(deployHookURL, {\n        method: 'POST',\n        mode: deployHookAuthHeader ? 'cors' : 'no-cors',\n        headers: deployHookAuthHeader ? { Authorization: deployHookAuthHeader } : {},\n      })\n    : ((await backend.current?.triggerDeployment?.()) ?? {});\n\n  // If the `mode` is `no-cors`, the regular response status will be `0`\n  if (!ok && (deployHookAuthHeader || status !== 0)) {\n    throw new Error(`Webhook returned ${status} error`);\n  }\n\n  // The provider hasn’t been asked about the new run yet, so record that one was requested.\n  // Anything it reported about the commit before this point describes the state being replaced\n  setLastCommitPublishHint(true);\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Button, Toast } from '@sveltia/ui';\n\n  import { skipCIConfigured } from '$lib/services/backends/git/shared/integration';\n  import { canTriggerDeployment, triggerDeployment } from '$lib/services/deployments/publish';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /** @type {'info' | 'error'} */\n  let toastStatus = $state('info');\n  /** @type {boolean} */\n  let showToast = $state(false);\n\n  /**\n   * Trigger a manual deployment on the CI/CD provider.\n   */\n  const publish = async () => {\n    toastStatus = 'info';\n    showToast = true;\n\n    try {\n      await triggerDeployment();\n    } catch (ex) {\n      toastStatus = 'error';\n      showToast = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    }\n  };\n</script>\n\n{#if skipCIConfigured.current}\n  <Button\n    variant=\"secondary\"\n    size={env.isSmallScreen ? 'small' : 'medium'}\n    label={_('publish_changes')}\n    disabled={!canTriggerDeployment.current}\n    onclick={() => publish()}\n  />\n  <Toast bind:show={showToast}>\n    <Alert status={toastStatus}>\n      {_(toastStatus === 'error' ? 'publishing_changes_failed' : 'publishing_changes')}\n    </Alert>\n  </Toast>\n{/if}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Icon, OptionGroup, Tree, TreeItem } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n\n  import CollectionTreeItem from '$lib/components/contents/list/collection-tree-item.svelte';\n  import SingletonTreeItem from '$lib/components/contents/list/singleton-tree-item.svelte';\n  import PublishButton from '$lib/components/global/toolbar/items/publish-button.svelte';\n  import QuickSearchBar from '$lib/components/global/toolbar/items/quick-search-bar.svelte';\n  import { appNumberFormatter } from '$lib/services/app/i18n';\n  import { goto } from '$lib/services/app/navigation';\n  import { cmsConfig } from '$lib/services/config';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import { hasNestedEntries } from '$lib/services/contents/collection/nested';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [isSearchPage] Whether the current page is the search results page.\n   */\n\n  /** @type {Props} */\n  let { isSearchPage = false } = $props();\n\n  // @ts-ignore Dividers can be included in the collection list\n  const collections = $derived(cmsConfig.current?.collections?.filter(({ hide }) => !hide) ?? []);\n  const singletons = $derived(cmsConfig.current?.singletons ?? []);\n  // Only a collection with nested entries has a folder tree, and with it a chevron in front of its\n  // icon. Without one, nothing in the list can expand, so the space kept for the chevrons is\n  // dropped.\n  const hasAnyNestedEntries = $derived(\n    collections.some((collection) => !('divider' in collection) && hasNestedEntries(collection)),\n  );\n</script>\n\n<nav class=\"primary-sidebar\" aria-label={_('contents')}>\n  {#if env.isSmallScreen}\n    <header>\n      <h2>{_('contents')}</h2>\n      <PublishButton />\n    </header>\n    <QuickSearchBar\n      onclick={(event) => {\n        event.preventDefault();\n        goto('/search');\n      }}\n    />\n  {/if}\n  <!-- The chevron is the only way to expand or collapse a folder, so that activating a collection\n  or a folder always navigates to it -->\n  <Tree\n    class={hasAnyNestedEntries ? undefined : 'flat'}\n    ariaLabel={_('collection_list')}\n    aria-controls={isSearchPage || env.isSmallScreen ? undefined : 'collection-container'}\n    expandOnSelect={false}\n  >\n    {#if collections.length}\n      <OptionGroup label={_('collections')}>\n        {#each collections as collection, index (collection.name ?? index)}\n          {#await sleep() then}\n            {#if !('divider' in collection)}\n              <CollectionTreeItem {collection} {isSearchPage} />\n            {:else if collection.divider}\n              <Divider />\n            {/if}\n          {/await}\n        {/each}\n      </OptionGroup>\n    {/if}\n    {#if singletons.length}\n      {#if env.isSmallScreen || collections.length}\n        <!-- Use the user-friendly “Files” label instead of “Singletons” -->\n        <OptionGroup label={_('files')}>\n          {#each singletons as file, index (file.name ?? index)}\n            {#await sleep() then}\n              {#if !('divider' in file)}\n                <SingletonTreeItem {file} />\n              {:else if file.divider}\n                <Divider />\n              {/if}\n            {/await}\n          {/each}\n        </OptionGroup>\n      {:else}\n        <!-- Show the singletons just like a file collection -->\n        {@const count = singletons.filter((file) => !('divider' in file)).length}\n        <OptionGroup label={_('collections')}>\n          <TreeItem\n            label={_('files')}\n            selected={selectedCollection.current?.name === '_singletons'}\n            onSelect={() => {\n              goto('/collections/_singletons', { transitionType: 'forwards' });\n            }}\n          >\n            {#snippet startIcon()}\n              <Icon name=\"bookmark_manager\" />\n            {/snippet}\n            {#snippet endIcon()}\n              <span class=\"count\" aria-label={_('x_entries', { values: { count } })}>\n                {appNumberFormatter.current.format(count)}\n              </span>\n            {/snippet}\n          </TreeItem>\n        </OptionGroup>\n      {/if}\n    {/if}\n  </Tree>\n</nav>\n","<!--\n  @component\n  Save/Cancel buttons shown in the collection toolbar while the entry list is in a mode that makes\n  pending changes, such as the bulk edit or reorder mode. Owns the saving flow, the error toasts\n  and, optionally, the validation step and the confirmation to discard unsaved changes.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Button, ConfirmationDialog, Toast } from '@sveltia/ui';\n  import { tick } from 'svelte';\n\n  import { runCommit } from '$lib/services/backends/commit-prompt';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} saveLabel Visible label of the primary button.\n   * @property {string} saveAriaLabel Accessible name of the primary button.\n   * @property {string} cancelAriaLabel Accessible name of the Cancel button, also the title of the\n   * discard confirmation.\n   * @property {string} savingFailedMessage Message of the toast shown when saving fails.\n   * @property {() => Promise<unknown>} commit Save the pending changes.\n   * @property {() => void} exitMode Leave the mode.\n   * @property {boolean} [canSave] Whether there is anything to save.\n   * @property {boolean} [saving] Whether the changes are being saved. Bindable.\n   * @property {() => boolean} [validate] Check the pending changes before saving. Returns `false`\n   * to stop the save and show the `invalidMessage` toast.\n   * @property {string} [invalidMessage] Message of the toast shown when `validate` fails.\n   * @property {string} [discardMessage] Message of the confirmation asked before leaving the mode\n   * with unsaved changes. Without it, the Cancel button leaves the mode straight away.\n   * @property {() => void} [onExit] Called once the mode has been left, so the parent can move the\n   * focus to the button that took the place of these.\n   * @property {import('svelte').Snippet} [leading] Content shown before the buttons.\n   */\n\n  /** @type {Props} */\n  let {\n    saveLabel,\n    saveAriaLabel,\n    cancelAriaLabel,\n    savingFailedMessage,\n    commit,\n    exitMode,\n    canSave = true,\n    saving = $bindable(false),\n    validate = undefined,\n    invalidMessage = '',\n    discardMessage = '',\n    onExit = undefined,\n    leading = undefined,\n  } = $props();\n\n  let showDiscardDialog = $state(false);\n  let invalidToast = $state(false);\n  let errorToast = $state(false);\n  /** @type {HTMLButtonElement | undefined} */\n  let saveButton = $state();\n  /** @type {HTMLButtonElement | undefined} */\n  let cancelButton = $state();\n\n  /**\n   * Move the focus to the primary button, or the Cancel button while there is nothing to save, e.g.\n   * once the mode has been entered with the button these take the place of.\n   */\n  export const focus = () => {\n    const save = /** @type {HTMLButtonElement} */ (saveButton);\n\n    /** @type {HTMLButtonElement} */ (save.disabled ? cancelButton : save).focus();\n  };\n\n  /**\n   * Leave the mode.\n   */\n  const exit = () => {\n    exitMode();\n    onExit?.();\n  };\n\n  /**\n   * Validate and save the pending changes, then leave the mode.\n   */\n  const save = async () => {\n    if (validate && !validate()) {\n      invalidToast = true;\n\n      return;\n    }\n\n    saving = true;\n\n    const { ok, cancelled } = await runCommit(commit);\n\n    saving = false;\n\n    if (ok) {\n      exit();\n    } else {\n      // A cancellation at the commit message prompt isn’t a failure\n      if (!cancelled) {\n        errorToast = true;\n      }\n\n      // The button lost the focus while it was disabled during the save, so give it back\n      await tick();\n      /** @type {HTMLButtonElement} */ (saveButton).focus();\n    }\n  };\n</script>\n\n{@render leading?.()}\n<Button\n  bind:element={saveButton}\n  variant=\"primary\"\n  label={saveLabel}\n  aria-label={saveAriaLabel}\n  disabled={saving || !canSave}\n  onclick={() => {\n    save();\n  }}\n/>\n<Button\n  bind:element={cancelButton}\n  variant=\"secondary\"\n  label={_('cancel')}\n  aria-label={cancelAriaLabel}\n  disabled={saving}\n  onclick={() => {\n    if (discardMessage && canSave) {\n      showDiscardDialog = true;\n    } else {\n      exit();\n    }\n  }}\n/>\n\n{#if discardMessage}\n  <ConfirmationDialog\n    bind:open={showDiscardDialog}\n    title={cancelAriaLabel}\n    okLabel={_('discard')}\n    onOk={() => {\n      exit();\n    }}\n  >\n    {discardMessage}\n  </ConfirmationDialog>\n{/if}\n\n{#if invalidMessage}\n  <Toast bind:show={invalidToast}>\n    <Alert status=\"error\">\n      {invalidMessage}\n    </Alert>\n  </Toast>\n{/if}\n\n<Toast bind:show={errorToast}>\n  <Alert status=\"error\">\n    {savingFailedMessage}\n  </Alert>\n</Toast>\n","<!--\n  @component\n  Save/Cancel buttons shown in the collection toolbar while the entry list is in bulk edit mode.\n  Owns the saving flow, the confirmation to discard unsaved edits and the error toasts, so the\n  parent toolbar only needs to render this component when `bulkEditing.current` is `true`.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Spacer } from '@sveltia/ui';\n\n  import ListModeControls from '$lib/components/contents/list/list-mode-controls.svelte';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import {\n    countBulkEdits,\n    saveBulkEdits,\n    validateBulkEdits,\n  } from '$lib/services/contents/collection/entries/bulk-edit';\n  import {\n    bulkEditedEntries,\n    bulkEditErrors,\n    bulkEdits,\n    bulkEditSaving,\n    setBulkEditMode,\n  } from '$lib/services/contents/collection/view';\n\n  /**\n   * @import { InternalEntryCollection } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {() => void} [onExit] Called once the bulk edit mode has been left, so the parent can\n   * move the focus to the button that took the place of these.\n   */\n\n  /** @type {Props} */\n  const { onExit = undefined } = $props();\n\n  /** @type {ListModeControls | undefined} */\n  let controls = $state();\n\n  const count = $derived(countBulkEdits(bulkEdits.current));\n\n  /**\n   * Move the focus to the Save button, or the Cancel button while there is nothing to save, e.g.\n   * once the bulk edit mode has been entered with the button these take the place of.\n   */\n  export const focus = () => {\n    /** @type {ListModeControls} */ (controls).focus();\n  };\n\n  /**\n   * Get the arguments of the bulk edit functions.\n   * @returns {Parameters<typeof saveBulkEdits>[0]} Arguments.\n   */\n  const getArgs = () => ({\n    collection: /** @type {InternalEntryCollection} */ (selectedCollection.current),\n    entries: bulkEditedEntries.current,\n    edits: bulkEdits.current,\n  });\n</script>\n\n<ListModeControls\n  bind:this={controls}\n  bind:saving={bulkEditSaving.current}\n  saveLabel={_('save')}\n  saveAriaLabel={_('save_bulk_edits')}\n  cancelAriaLabel={_('cancel_bulk_edits')}\n  savingFailedMessage={_('saving_bulk_edits_failed')}\n  invalidMessage={_('bulk_edit_invalid')}\n  discardMessage={_('discard_bulk_edits_confirm')}\n  canSave={!!count}\n  validate={() => {\n    const errors = validateBulkEdits(getArgs());\n\n    if (Object.keys(errors).length) {\n      bulkEditErrors.current = errors;\n\n      return false;\n    }\n\n    return true;\n  }}\n  commit={() => saveBulkEdits(getArgs())}\n  exitMode={() => setBulkEditMode(false)}\n  {onExit}\n>\n  {#snippet leading()}\n    <div role=\"status\" class=\"count\">{_('bulk_edit_count', { values: { count } })}</div>\n    <Spacer />\n  {/snippet}\n</ListModeControls>\n\n<style>\n  .count {\n    font-size: var(--sui-font-size-small);\n    opacity: 0.8;\n    white-space: nowrap;\n  }\n</style>\n","<!--\n  @component\n  Save/Cancel buttons shown in the collection toolbar while the entry list is in reorder mode. Owns\n  the saving state and the error toast, so the parent toolbar only needs to render this component\n  when `reordering.current` is `true`.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import ListModeControls from '$lib/components/contents/list/list-mode-controls.svelte';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import { reorderEntries } from '$lib/services/contents/collection/entries/reorder';\n  import {\n    reorderDirty,\n    reorderedEntries,\n    setReorderMode,\n  } from '$lib/services/contents/collection/view';\n\n  /**\n   * @import { InternalEntryCollection } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {() => void} [onExit] Called once the reorder mode has been left, so the parent can\n   * move the focus to the button that took the place of these.\n   */\n\n  /** @type {Props} */\n  const { onExit = undefined } = $props();\n\n  /** @type {ListModeControls | undefined} */\n  let controls = $state();\n\n  /**\n   * Move the focus to the Done button, or the Cancel button while there is nothing to save, e.g.\n   * once the reorder mode has been entered with the button these take the place of.\n   */\n  export const focus = () => {\n    /** @type {ListModeControls} */ (controls).focus();\n  };\n</script>\n\n<ListModeControls\n  bind:this={controls}\n  saveLabel={_('done')}\n  saveAriaLabel={_('done_reordering_entries')}\n  cancelAriaLabel={_('cancel_reordering_entries')}\n  savingFailedMessage={_('saving_reorder_failed')}\n  canSave={reorderDirty.current}\n  commit={() =>\n    reorderEntries(\n      /** @type {InternalEntryCollection} */ (selectedCollection.current),\n      reorderedEntries.current,\n    )}\n  exitMode={() => setReorderMode(false)}\n  {onExit}\n/>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, ConfirmationDialog, Toast } from '@sveltia/ui';\n\n  import CascadeDeleteNote from '$lib/components/common/cascade-delete-note.svelte';\n  import { runCommit } from '$lib/services/backends/commit-prompt';\n  import { getErrorMessage } from '$lib/services/backends/git/shared/errors';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import {\n    contentUpdatesToast,\n    UPDATE_TOAST_DEFAULT_STATE,\n  } from '$lib/services/contents/collection/data';\n  import { selectedEntries } from '$lib/services/contents/collection/entries';\n  import { listedEntries, listedUnpublishedEntries } from '$lib/services/contents/collection/view';\n  import { getEntriesRelativeAssets } from '$lib/services/contents/entry/assets';\n  import {\n    EMPTY_CASCADE_DELETE_PLAN,\n    planCascadeDelete,\n  } from '$lib/services/contents/entry/relations/cascade/delete';\n  import { isDiscardableDraft, isWorkflowEnabled } from '$lib/services/workflow';\n  import { deleteOrDiscardEntries } from '$lib/services/workflow/delete';\n\n  /**\n   * @import { Entry, UnpublishedEntry } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [open] Whether the dialog is open.\n   */\n\n  /** @type {Props} */\n  let { open = $bindable(false) } = $props();\n\n  let showErrorToast = $state(false);\n  let errorMessage = $state('');\n\n  // Deleting an unpublished entry that has never been published discards the draft instead of\n  // committing a deletion, so the two kinds of entries have to be handled separately. An entry with\n  // pending changes to a published version, which the list shows in place of that version, is\n  // deleted like a published one, as the entry editor does: discarding its pull request would leave\n  // the published version on the site\n  const { draftEntries, publishedEntries } = $derived.by(() => {\n    /** @type {UnpublishedEntry[]} */\n    const drafts = [];\n    /** @type {Entry[]} */\n    const published = [];\n\n    selectedEntries.current.forEach((entry) => {\n      if (isDiscardableDraft(entry)) {\n        drafts.push(/** @type {UnpublishedEntry} */ (entry));\n      } else {\n        published.push(entry);\n      }\n    });\n\n    return { draftEntries: drafts, publishedEntries: published };\n  });\n\n  // What the deletion means for the entries referencing the published ones through Relation fields.\n  // Only worked out while the dialog is open: it scans every entry that could hold a reference,\n  // which is too much to do on every change of the selection\n  const cascadePlan = $derived.by(() => {\n    const collection = selectedCollection.current;\n\n    return open && collection && publishedEntries.length\n      ? planCascadeDelete({ collection, entries: publishedEntries })\n      : EMPTY_CASCADE_DELETE_PLAN;\n  });\n\n  // Assets committed alongside an unpublished entry don’t exist on the configured branch yet, so\n  // only look at the published entries here\n  const publishedEntryAssets = $derived.by(() => {\n    // Looked up for all the entries at once, as finding the assets other entries use as well takes\n    // a pass over the collection. Entries are only selected within a collection, and without one\n    // the helper finds no assets anyway\n    const assetLists = getEntriesRelativeAssets({\n      entries: publishedEntries,\n      collectionName: /** @type {string} */ (selectedCollection.current?.name),\n    });\n\n    return publishedEntries.map((entry, index) => ({ entry, assets: assetLists[index] }));\n  });\n  const associatedAssets = $derived(publishedEntryAssets.flatMap(({ assets }) => assets));\n\n  /**\n   * Delete the selected entries, discarding any unpublished draft rather than committing a deletion\n   * for it.\n   */\n  const deleteSelectedEntries = async () => {\n    const collection = selectedCollection.current;\n\n    const { ok, cancelled, result, error } = await runCommit(() =>\n      deleteOrDiscardEntries({\n        drafts: draftEntries,\n        items: publishedEntryAssets,\n        collection,\n        // An entry with a pull request stays in it until it’s published or discarded, even if the\n        // collection has opted out of Editorial Workflow since, as in the entry editor\n        useWorkflow:\n          isWorkflowEnabled(collection) || publishedEntries.some((entry) => 'workflow' in entry),\n      }),\n    );\n\n    if (!ok) {\n      // The user has cancelled the commit at the commit message prompt, which isn’t a failure\n      if (!cancelled) {\n        errorMessage = getErrorMessage(error, 'deleting_entry_failed');\n        showErrorToast = true;\n      }\n\n      return;\n    }\n\n    if (result) {\n      contentUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, ...result };\n    }\n\n    // Discarding a draft doesn’t change `listedEntries`, which is what normally resets the\n    // selection, so clear it here to avoid a stale selection\n    selectedEntries.current = [];\n  };\n</script>\n\n<ConfirmationDialog\n  bind:open\n  title={_('delete_entries', { values: { count: selectedEntries.current.length } })}\n  okLabel={_('delete')}\n  okDisabled={!!cascadePlan.blockers.length}\n  onOk={async () => {\n    await deleteSelectedEntries();\n  }}\n>\n  {@const all =\n    selectedEntries.current.length > 1 &&\n    selectedEntries.current.length ===\n      listedEntries.current.length + listedUnpublishedEntries.current.length}\n  <!-- There’s nothing to confirm when the deletion is refused; the note explains why -->\n  {#if !cascadePlan.blockers.length}\n    {_(\n      associatedAssets.length\n        ? all\n          ? 'confirm_deleting_all_entries_with_assets'\n          : 'confirm_deleting_selected_entries_with_assets'\n        : all\n          ? 'confirm_deleting_all_entries'\n          : 'confirm_deleting_selected_entries',\n      { values: { count: selectedEntries.current.length } },\n    )}\n    {#if draftEntries.length}\n      {_(\n        publishedEntries.length\n          ? 'workflow.deleting_unpublished_note_some'\n          : 'workflow.deleting_unpublished_note_all',\n        { values: { count: draftEntries.length } },\n      )}\n    {/if}\n  {/if}\n  <CascadeDeleteNote plan={cascadePlan} count={publishedEntries.length} />\n</ConfirmationDialog>\n\n<Toast bind:show={showErrorToast}>\n  <Alert status=\"error\">{errorMessage}</Alert>\n</Toast>\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import {\n    Button,\n    FloatingActionButtonWrapper,\n    Infobar,\n    Spacer,\n    Toolbar,\n    TruncatedText,\n  } from '@sveltia/ui';\n  import { tick } from 'svelte';\n\n  import BackButton from '$lib/components/common/page-toolbar/back-button.svelte';\n  import BulkEditControls from '$lib/components/contents/list/bulk-edit-controls.svelte';\n  import ReorderControls from '$lib/components/contents/list/reorder-controls.svelte';\n  import DeleteEntriesDialog from '$lib/components/contents/shared/delete-entries-dialog.svelte';\n  import CreateEntryButton from '$lib/components/contents/toolbar/create-entry-button.svelte';\n  import { focusList } from '$lib/services/app/focus';\n  import { goBack } from '$lib/services/app/navigation';\n  import { getReadonlyMessage } from '$lib/services/config/readonly';\n  import { getCollectionLabel, selectedCollection } from '$lib/services/contents/collection';\n  import { selectedEntries } from '$lib/services/contents/collection/entries';\n  import {\n    bulkEditing,\n    collectionState,\n    listedEntries,\n    listedUnpublishedEntries,\n    reordering,\n    setBulkEditMode,\n    setReorderMode,\n  } from '$lib/services/contents/collection/view';\n  import { env } from '$lib/services/user/env.svelte';\n  import { sanitizeInlineMarkdown } from '$lib/services/utils/string';\n  import { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n  let showDeleteDialog = $state(false);\n  /** @type {HTMLButtonElement | undefined} */\n  let deleteButton = $state();\n  /** @type {HTMLButtonElement | undefined} */\n  let reorderButton = $state();\n  /** @type {ReorderControls | undefined} */\n  let reorderControls = $state();\n  /** @type {HTMLButtonElement | undefined} */\n  let bulkEditButton = $state();\n  /** @type {BulkEditControls | undefined} */\n  let bulkEditControls = $state();\n\n  /* v8 ignore start -- only read while a collection is selected, once the app locale is loaded */\n  const name = $derived(selectedCollection.current?.name ?? '');\n  const collectionLabel = $derived(\n    // `appLocale.current` is a key, because `getCollectionLabel` can return a localized label\n    appLocale.current && selectedCollection.current\n      ? getCollectionLabel(selectedCollection.current)\n      : name,\n  );\n  /* v8 ignore stop */\n  const description = $derived(selectedCollection.current?.description);\n  const {\n    isEntryCollection,\n    readonly,\n    canCreate,\n    canDelete,\n    canReorder,\n    canBulkEdit,\n    quota,\n    remaining,\n    nearingQuota,\n    creationDisabled,\n  } = $derived(collectionState.current);\n  const deleteDisabled = $derived(!selectedEntries.current.length || !canDelete);\n  // The empty entry list offers a Create button of its own, so the floating one is only needed once\n  // the list has entries, including unpublished ones, which can be the only ones in the collection\n  const hasEntries = $derived(\n    !!(listedEntries.current.length || listedUnpublishedEntries.current.length),\n  );\n\n  // The Delete button is disabled once the selected entries are deleted, which would drop its focus\n  // on `<body>`, so move it to the entry list. This runs before the button is updated, while it\n  // still has the focus\n  $effect.pre(() => {\n    if (deleteDisabled && document.activeElement === deleteButton) {\n      tick().then(() => focusList());\n    }\n  });\n</script>\n\n{#if selectedCollection.current}\n  {#if readonly}\n    <Infobar\n      dismissible={false}\n      --sui-infobar-border-width=\"0 0 1px\"\n      --sui-infobar-message-justify-content=\"center\"\n    >\n      {getReadonlyMessage('collection', { collection: selectedCollection.current })}\n    </Infobar>\n  {:else if isEntryCollection && (creationDisabled || nearingQuota)}\n    <!-- Only when not read-only, as the read-only message already says nothing can be created -->\n    <Infobar\n      dismissible={false}\n      --sui-infobar-border-width=\"0 0 1px\"\n      --sui-infobar-message-justify-content=\"center\"\n    >\n      {#if !canCreate}\n        {_('creating_entries_disabled_by_admin')}\n      {:else if creationDisabled}\n        {_('creating_entries_disabled_by_quota', { values: { quota } })}\n      {:else}\n        {_('creating_entries_nearing_quota', { values: { quota, remaining } })}\n      {/if}\n    </Infobar>\n  {/if}\n  <Toolbar variant=\"primary\" ariaLabel={_('collection')}>\n    {#if env.isSmallScreen}\n      <BackButton\n        aria-label={_('back_to_collection_list')}\n        onclick={() => {\n          goBack('/collections');\n        }}\n      />\n    {/if}\n    <h2 role=\"none\"><bdi>{collectionLabel}</bdi></h2>\n    {#if env.isSmallScreen}\n      <Spacer flex />\n    {:else}\n      <div role=\"none\" class=\"description\">\n        <TruncatedText>\n          <bdi>{@html sanitizeInlineMarkdown(description || '')}</bdi>\n        </TruncatedText>\n      </div>\n    {/if}\n    {#if isEntryCollection && reordering.current}\n      <ReorderControls\n        bind:this={reorderControls}\n        onExit={async () => {\n          // The Reorder button takes the place of the focused button\n          await tick();\n          /** @type {HTMLButtonElement} */ (reorderButton).focus();\n        }}\n      />\n    {:else if isEntryCollection && bulkEditing.current}\n      <BulkEditControls\n        bind:this={bulkEditControls}\n        onExit={async () => {\n          // The Edit button takes the place of the focused button\n          await tick();\n          /** @type {HTMLButtonElement} */ (bulkEditButton).focus();\n        }}\n      />\n    {:else if isEntryCollection}\n      <!-- Taking a published entry off the site is a maintainer’s call, and the entry list has no\n      other bulk action, so a contributor has nothing to select entries for -->\n      {#if !env.isSmallScreen && !openAuthoring.current}\n        <Button\n          bind:element={deleteButton}\n          variant=\"ghost\"\n          label={_('delete')}\n          aria-label={_('delete_selected_entries', {\n            values: { count: selectedEntries.current.length },\n          })}\n          disabled={deleteDisabled}\n          onclick={() => {\n            showDeleteDialog = true;\n          }}\n        />\n      {/if}\n      <!-- A table of controls doesn’t fit on a small screen -->\n      {#if canBulkEdit && !env.isSmallScreen}\n        <Button\n          bind:element={bulkEditButton}\n          variant=\"ghost\"\n          label={_('edit')}\n          aria-label={_('bulk_edit_entries')}\n          disabled={!listedEntries.current.length}\n          onclick={async () => {\n            setBulkEditMode(true);\n            // The Save and Cancel buttons take the place of this one\n            await tick();\n            /** @type {BulkEditControls} */ (bulkEditControls).focus();\n          }}\n        />\n      {/if}\n      {#if canReorder}\n        <Button\n          bind:element={reorderButton}\n          variant=\"ghost\"\n          label={_('reorder')}\n          aria-label={_('reorder_entries')}\n          disabled={!listedEntries.current.length}\n          onclick={async () => {\n            setReorderMode(true);\n            // The Done and Cancel buttons take the place of this one\n            await tick();\n            /** @type {ReorderControls} */ (reorderControls).focus();\n          }}\n        />\n      {/if}\n      <FloatingActionButtonWrapper>\n        {#if !env.isSmallScreen || (hasEntries && !creationDisabled)}\n          <CreateEntryButton\n            collectionName={name}\n            label={env.isSmallScreen ? undefined : _('create')}\n            keyShortcuts=\"Accel+E\"\n          />\n        {/if}\n      </FloatingActionButtonWrapper>\n    {/if}\n  </Toolbar>\n{/if}\n\n<DeleteEntriesDialog bind:open={showDeleteDialog} />\n\n<style>\n  h2 {\n    flex: none !important;\n  }\n\n  .description {\n    flex: auto;\n    font-size: var(--sui-font-size-small);\n    opacity: 0.8;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Group } from '@sveltia/ui';\n\n  import AssetsPanel from '$lib/components/assets/browser/assets-panel.svelte';\n  import DropZone from '$lib/components/assets/shared/drop-zone.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { isAssetInFolder } from '$lib/services/assets';\n  import { assetsLocked, canCreateAsset, getAssetFolder } from '$lib/services/assets/folders';\n  import { allAssets, uploadingAssets } from '$lib/services/assets/state';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import { currentView } from '$lib/services/contents/collection/view/settings';\n  import { env } from '$lib/services/user/env.svelte';\n  import { encodePathSegments } from '$lib/services/utils/url';\n\n  /**\n   * @import { AssetFolderInfo } from '$lib/types/private';\n   */\n\n  const folder = $derived(getAssetFolder({ collectionName: selectedCollection.current?.name }));\n  // Only read while the folder is shown below, so the folder is always there\n  const assets = $derived(\n    allAssets.current.filter((asset) =>\n      isAssetInFolder(asset, /** @type {AssetFolderInfo} */ (folder)),\n    ),\n  );\n  const internalPath = $derived(folder?.internalPath);\n  // Can’t upload assets if collection assets are saved at entry-relative paths, or the folder is\n  // read-only. An Open Authoring contributor or a user who can’t push to the branch can’t either:\n  // this uploads to the collection’s media folder, which is a commit straight to the configured\n  // branch rather than something that goes through review\n  const uploadDisabled = $derived(!canCreateAsset(folder) || assetsLocked.current);\n</script>\n\n{#if internalPath !== undefined && env.isLargeScreen && currentView.current.showMedia}\n  <Group id=\"collection-assets\" class=\"secondary-sidebar\" ariaLabel={_('collection_assets')}>\n    <DropZone\n      disabled={uploadDisabled}\n      multiple={true}\n      onDrop={({ files }) => {\n        uploadingAssets.current = { folder, files };\n      }}\n    >\n      <AssetsPanel\n        {assets}\n        onSelect={({ asset }) => {\n          goto(encodePathSegments(`/assets/${asset.path}`), { transitionType: 'forwards' });\n        }}\n      />\n    </DropZone>\n  </Group>\n{/if}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Divider, Icon, Spacer, Toolbar } from '@sveltia/ui';\n\n  import FilterMenu from '$lib/components/common/page-toolbar/filter-menu.svelte';\n  import GroupMenu from '$lib/components/common/page-toolbar/group-menu.svelte';\n  import ItemSelector from '$lib/components/common/page-toolbar/item-selector.svelte';\n  import SortMenu from '$lib/components/common/page-toolbar/sort-menu.svelte';\n  import ViewSwitcher from '$lib/components/common/page-toolbar/view-switcher.svelte';\n  import { getAssetFolder } from '$lib/services/assets/folders';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import { selectedEntries } from '$lib/services/contents/collection/entries';\n  import {\n    bulkEditing,\n    entryGroups,\n    listedEntryCount,\n    listedUnpublishedEntries,\n    reordering,\n  } from '$lib/services/contents/collection/view';\n  import { viewFilters } from '$lib/services/contents/collection/view/filter';\n  import { viewGroups } from '$lib/services/contents/collection/view/group';\n  import { currentView, getEntryViewTypes } from '$lib/services/contents/collection/view/settings';\n  import { sortKeys } from '$lib/services/contents/collection/view/sort-keys';\n  import { env } from '$lib/services/user/env.svelte';\n  import { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n  /**\n   * @import { InternalEntryCollection } from '$lib/types/private';\n   */\n\n  const entryCollection = $derived(\n    selectedCollection.current?._type === 'entry'\n      ? /** @type {InternalEntryCollection} */ (selectedCollection.current)\n      : undefined,\n  );\n  const collectionName = $derived(entryCollection?.name);\n  // The count includes the entries hidden by a filter, so the menus stay enabled to reset it\n  const hasListedEntries = $derived(!!listedEntryCount.current);\n  const hasMultipleEntries = $derived(listedEntryCount.current > 1);\n</script>\n\n{#if entryCollection && !reordering.current && !bulkEditing.current}\n  <Toolbar variant=\"secondary\" ariaLabel={_('entry_list')}>\n    {#if !(env.isSmallScreen || env.isMediumScreen) && !openAuthoring.current}\n      <ItemSelector\n        allItems={[\n          ...listedUnpublishedEntries.current,\n          ...entryGroups.current.flatMap(({ entries }) => entries),\n        ]}\n        selectedItems={selectedEntries}\n      />\n    {/if}\n    <Spacer flex />\n    <SortMenu\n      disabled={!hasMultipleEntries || !sortKeys.current.length}\n      {currentView}\n      sortKeys={sortKeys.current}\n      {collectionName}\n      aria-controls=\"entry-list\"\n    />\n    {#if viewFilters.current?.length}\n      <FilterMenu\n        disabled={!hasMultipleEntries}\n        {currentView}\n        filters={viewFilters.current}\n        multiple={true}\n        aria-controls=\"entry-list\"\n      />\n    {/if}\n    {#if viewGroups.current?.length}\n      <GroupMenu\n        disabled={!hasMultipleEntries}\n        {currentView}\n        groups={viewGroups.current}\n        groupNames={entryGroups.current.map(({ name }) => name)}\n        aria-controls=\"entry-list\"\n      />\n    {/if}\n    <ViewSwitcher\n      disabled={!hasListedEntries}\n      {currentView}\n      types={getEntryViewTypes(entryCollection)}\n      aria-controls=\"entry-list\"\n    />\n    {#if !(env.isSmallScreen || env.isMediumScreen)}\n      {@const label = _(currentView.current.showMedia ? 'hide_assets' : 'show_assets')}\n      <Divider orientation=\"vertical\" />\n      <Button\n        variant=\"ghost\"\n        iconic\n        disabled={!hasListedEntries || !getAssetFolder({ collectionName })}\n        pressed={!!currentView.current.showMedia}\n        tooltip={label}\n        aria-label={label}\n        aria-controls={currentView.current.showMedia ? 'collection-assets' : undefined}\n        aria-expanded={!!currentView.current.showMedia}\n        onclick={() => {\n          currentView.current = {\n            ...currentView.current,\n            showMedia: !currentView.current.showMedia,\n          };\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"photo_library\" />\n        {/snippet}\n      </Button>\n    {/if}\n  </Toolbar>\n{/if}\n","import { _, locale as appLocale } from '@sveltia/i18n';\n\nimport { announcedPageStatus, goto, parseLocation } from '$lib/services/app/navigation';\nimport {\n  getCollection,\n  getCollectionLabel,\n  getFirstCollection,\n  getSingletonCollection,\n  getValidCollections,\n  selectedCollection,\n} from '$lib/services/contents/collection';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport {\n  getCollectionFileEntry,\n  getCollectionFileLabel,\n} from '$lib/services/contents/collection/files';\nimport {\n  getMetaPathConfig,\n  isNestedFolder,\n  nestedFilterPath,\n} from '$lib/services/contents/collection/nested';\nimport { listedEntries } from '$lib/services/contents/collection/view';\nimport { createDraft } from '$lib/services/contents/draft/create';\nimport { refreshOpenedDraft } from '$lib/services/contents/draft/reload';\nimport { showContentOverlay } from '$lib/services/contents/editor';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { isSearchRoute } from '$lib/services/search/navigation';\nimport { env } from '$lib/services/user/env.svelte';\nimport {\n  getForkUnpublishedEntry,\n  getUnpublishedEntriesByCollection,\n  getUnpublishedEntry,\n  mergeUnpublishedEntries,\n  workflowDataReady,\n} from '$lib/services/workflow';\n\n/**\n * @import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n * @import {\n * InternalCollection,\n * InternalCollectionFile,\n * UnpublishedEntry,\n * } from '$lib/types/private';\n */\n\n/**\n * What the Content Library page shows for the current route.\n * @typedef {object} ContentsRouteState\n * @property {boolean} isIndexPage Whether the page shows the collection list only, on a small\n * screen.\n * @property {boolean} isSearchPage Whether the page shows the search results.\n * @property {string} notFoundKey Message key shown on the Not Found view, or an empty string when\n * the route resolved.\n * @property {boolean} awaitingDrafts Whether the route can’t be resolved until the Editorial\n * Workflow drafts are in, which happens after the initial data load. The route should be tried\n * again once they are.\n * @property {string} [editorLocale] Locale to open the editor in, given in the URL params, e.g.\n * `?_locale=fr`.\n */\n\n/**\n * Arguments shared by the resolvers of a collection’s routes.\n * @typedef {object} CollectionRouteArgs\n * @property {ContentsRouteState} state Initial page state.\n * @property {EntryDraftState} entryDraft Draft open in the content editor overlay.\n * @property {InternalCollection} collection Collection named in the route.\n * @property {string} collectionName Name of the selected collection.\n * @property {string} collectionLabel Label of the selected collection.\n * @property {string | undefined} routeType Route type: `new`, `entries` or `filter`.\n * @property {string | undefined} subPath Path following the collection name or route type.\n * @property {number} [pullRequestNumber] Number of the pull request from a contributor’s fork the\n * entry is to be opened from, given in the URL params, e.g. `?_pr=12`.\n */\n\n/**\n * Regular expression matching the routes of the Content Library page.\n */\nexport const CONTENTS_ROUTE_REGEX =\n  /^\\/collections(?:\\/(?<_collectionName>[^/]+)(?:\\/(?<routeType>new|entries|filter))?(?:\\/(?<subPath>.+?))?)?$/;\n\n/**\n * Hide the content editor and show the Not Found view with the given message.\n * @param {ContentsRouteState} state Initial page state.\n * @param {string} notFoundKey Message key shown on the Not Found view.\n * @returns {ContentsRouteState} What the page shows.\n */\nconst showNotFound = (state, notFoundKey) => {\n  showContentOverlay.current = false;\n  announcedPageStatus.current = _(notFoundKey);\n\n  return { ...state, notFoundKey };\n};\n\n/**\n * Leave the content editor empty, because the route doesn’t address an existing file or entry.\n * @param {ContentsRouteState} state Initial page state.\n * @param {EntryDraftState} entryDraft Draft open in the content editor overlay.\n * @param {string} messageKey Message key of the announced page status.\n * @returns {ContentsRouteState} What the page shows.\n */\nconst clearEditor = (state, entryDraft, messageKey) => {\n  entryDraft.current = undefined;\n  announcedPageStatus.current = _(messageKey);\n\n  return state;\n};\n\n/**\n * Find the unpublished entry an editor route addresses, which the editor opens in place of the\n * published version. A route naming a pull request is for an entry a contributor has opened from\n * their fork, which is only reached from the Editorial Workflow board. Nothing stands in for that\n * entry when it can’t be found, e.g. once the pull request has been closed: the published\n * version, or the maintainers’ own pull request, isn’t what the link was for, and editing it by\n * mistake could mix the two up.\n * @param {object} args Arguments.\n * @param {string} args.collectionName Collection name.\n * @param {string} args.subPath Entry sub path, or collection file name.\n * @param {number} [args.pullRequestNumber] Pull request number given in the route.\n * @returns {{ unpublishedEntry: UnpublishedEntry | undefined, missing: boolean }} Unpublished\n * entry, if any, and whether the entry the route names is missing.\n */\nconst findRouteUnpublishedEntry = ({ collectionName, subPath, pullRequestNumber }) => {\n  if (pullRequestNumber === undefined) {\n    return { unpublishedEntry: getUnpublishedEntry({ collectionName, subPath }), missing: false };\n  }\n\n  const unpublishedEntry = getForkUnpublishedEntry({\n    collectionName,\n    subPath,\n    number: pullRequestNumber,\n  });\n\n  return { unpublishedEntry, missing: !unpublishedEntry };\n};\n\n/**\n * Resolve `/collections`, which shows the collection list only on a small screen and redirects to\n * a collection otherwise.\n * @param {ContentsRouteState} state Initial page state.\n * @returns {ContentsRouteState} What the page shows.\n */\nconst resolveCollectionIndexRoute = (state) => {\n  if (env.isSmallScreen) {\n    // Show the collection list only\n    selectedCollection.current = undefined;\n    showContentOverlay.current = false;\n    announcedPageStatus.current = _('viewing_collection_list');\n\n    return { ...state, isIndexPage: true };\n  }\n\n  // Redirect to the selected, first or singleton collection\n  const collection = selectedCollection.current || getFirstCollection() || getSingletonCollection();\n\n  goto(`/collections/${collection?.name}`, { replaceState: true });\n\n  return state;\n};\n\n/**\n * Select the collection named in the route, or deselect any collection if it doesn’t exist or is\n * hidden.\n * @param {InternalCollection | undefined} collection Collection named in the route.\n */\nconst selectRouteCollection = (collection) => {\n  if (!collection || collection.hide) {\n    selectedCollection.current = undefined;\n  } else if (selectedCollection.current?.name !== collection.name) {\n    selectedCollection.current = collection;\n    // The folder being browsed belongs to the collection it was opened from, so it can’t carry\n    // over to another one — a new entry would be created in a folder of the previous collection\n    nestedFilterPath.current = '';\n  }\n};\n\n/**\n * Resolve a route listing a collection’s entries: the collection itself, or a folder of a nested\n * collection.\n * @param {CollectionRouteArgs} args Arguments.\n * @returns {ContentsRouteState} What the page shows.\n */\nconst resolveListingRoute = ({\n  state,\n  collection,\n  collectionName,\n  collectionLabel,\n  routeType,\n  subPath,\n}) => {\n  if (\n    routeType === 'filter' &&\n    !isNestedFolder({\n      collection,\n      // A folder that only exists in a pull request is listed in the sidebar tree, so it has to\n      // open from there as well\n      entries: mergeUnpublishedEntries(\n        getEntriesByCollection(collectionName),\n        getUnpublishedEntriesByCollection(collectionName),\n      ),\n      dirPath: subPath ?? '',\n    })\n  ) {\n    // The folder may live in a draft that hasn’t been fetched yet, as when the page is reloaded\n    // while browsing it. Only an absent folder has to wait: one the published entries hold is\n    // resolved right away\n    if (!workflowDataReady.current) {\n      showContentOverlay.current = false;\n      announcedPageStatus.current = _('loading');\n\n      return { ...state, awaitingDrafts: true };\n    }\n\n    // The URL names a folder that no entry lives in, or a collection with no folders at all\n    return showNotFound(state, 'page_not_found');\n  }\n\n  // A folder of nested entries is browsed at `/collections/{name}/filter/{path}`, while the\n  // collection route itself always shows the root folder. The editor routes leave the folder\n  // alone, so closing the editor returns the user to where they were.\n  nestedFilterPath.current = routeType === 'filter' ? (subPath ?? '') : '';\n  showContentOverlay.current = false;\n  announcedPageStatus.current = _('viewing_x_collection', {\n    values: { collection: collectionLabel, count: listedEntries.current.length },\n  });\n\n  return state;\n};\n\n/**\n * Resolve an editor route of a file/singleton collection, which only has\n * `/collections/{name}/entries/{file}`.\n * @param {CollectionRouteArgs & { fileMap: Record<string, InternalCollectionFile> }} args\n * Arguments. `fileMap` is the collection’s file map.\n * @returns {ContentsRouteState} What the page shows.\n */\nconst resolveFileRoute = ({\n  state,\n  entryDraft,\n  collection,\n  collectionName,\n  collectionLabel,\n  routeType,\n  subPath,\n  pullRequestNumber,\n  fileMap,\n}) => {\n  if (routeType !== 'entries' || !subPath) {\n    // A file collection has no `new` route, and `entries` needs a file name\n    return clearEditor(state, entryDraft, 'file_not_found');\n  }\n\n  // The file name comes from the URL, so it may be the name of an `Object.prototype` member\n  const collectionFile = Object.hasOwn(fileMap, subPath) ? fileMap[subPath] : undefined;\n\n  if (!collectionFile) {\n    // The URL names a file that isn’t part of this collection\n    return clearEditor(state, entryDraft, 'file_not_found');\n  }\n\n  const { unpublishedEntry, missing } = findRouteUnpublishedEntry({\n    collectionName,\n    subPath,\n    pullRequestNumber,\n  });\n\n  if (missing) {\n    return clearEditor(state, entryDraft, 'file_not_found');\n  }\n\n  // An unpublished entry takes precedence over the published version, so the user can keep\n  // editing the draft stored in the pull request\n  const originalEntry = unpublishedEntry ??\n    getCollectionFileEntry(collectionName, subPath) ??\n      // File is not yet created\n      {\n        slug: collectionFile.name,\n        locales: Object.fromEntries(\n          collectionFile._i18n.initialLocales.map((_locale) => [_locale, {}]),\n        ),\n      };\n\n  createDraft({ entryDraft, collection, collectionFile, originalEntry });\n  // Not awaited: the draft is shown right away, and made again if the entry has changed\n  refreshOpenedDraft(entryDraft);\n\n  announcedPageStatus.current = _(`edit_${collection._type}_announcement`, {\n    values: { collection: collectionLabel, file: getCollectionFileLabel(collectionFile) },\n  });\n\n  return state;\n};\n\n/**\n * Resolve an editor route of an entry collection: `/collections/{name}/new` or\n * `/collections/{name}/entries/{subPath}`.\n * @param {CollectionRouteArgs & { params: Record<string, string> }} args Arguments. `params` are\n * the URL params, which give a new entry its dynamic default values.\n * @returns {ContentsRouteState} What the page shows.\n */\nconst resolveEntryRoute = ({\n  state,\n  entryDraft,\n  collection,\n  collectionName,\n  collectionLabel,\n  routeType,\n  subPath,\n  pullRequestNumber,\n  params,\n}) => {\n  if (routeType === 'new' && !subPath) {\n    // Decap CMS passes the folder for a new entry in a collection with nested entries as `?path=`\n    const initialPath = getMetaPathConfig(collection) ? params.path : undefined;\n\n    if (initialPath !== undefined) {\n      delete params.path;\n    }\n\n    // The slug can be given as `?_slug=`, which is used where the slug is editable. It’s not a\n    // field value, so it’s left out of the dynamic default values either way\n    // @see https://github.com/sveltia/sveltia-cms/discussions/938\n    const { _slug: initialSlug } = params;\n\n    delete params._slug;\n\n    createDraft({\n      entryDraft,\n      collection,\n      dynamicValues: params,\n      initialPath,\n      initialSlug,\n      isIndexFile: !!window.history.state?.index,\n    });\n\n    announcedPageStatus.current = _('create_entry_announcement', {\n      values: { collection: collectionLabel },\n    });\n\n    return state;\n  }\n\n  if (routeType === 'entries' && subPath) {\n    const { unpublishedEntry, missing } = findRouteUnpublishedEntry({\n      collectionName,\n      subPath,\n      pullRequestNumber,\n    });\n\n    const originalEntry = missing\n      ? undefined\n      : (unpublishedEntry ??\n        // Not `listedEntries`, which a collection with nested entries limits to the folder being\n        // browsed, while an entry can also be opened with a deep link\n        getEntriesByCollection(collectionName).find((entry) => entry.subPath === subPath));\n\n    if (!originalEntry) {\n      return clearEditor(state, entryDraft, 'entry_not_found');\n    }\n\n    if (appLocale.current) {\n      createDraft({ entryDraft, collection, originalEntry });\n      refreshOpenedDraft(entryDraft);\n\n      announcedPageStatus.current = _('edit_entry_announcement', {\n        values: {\n          collection: collectionLabel,\n          entry: getEntrySummary(\n            /** @type {InternalCollection} */ (selectedCollection.current),\n            originalEntry,\n          ),\n        },\n      });\n    }\n\n    return state;\n  }\n\n  // `new` with a sub path or `entries` without one, e.g. `#/collections/posts/new/foo`\n  return clearEditor(state, entryDraft, 'entry_not_found');\n};\n\n/**\n * Resolve the current URL hash to what the Content Library page shows: the collection list, a\n * collection’s entries, the search results, or the content editor with the addressed entry loaded\n * into the given draft. The stores that the page and its parts read are updated along the way.\n * @param {object} args Arguments.\n * @param {EntryDraftState} args.entryDraft Draft open in the content editor overlay.\n * @returns {ContentsRouteState} What the page shows.\n */\nexport const resolveContentsRoute = ({ entryDraft }) => {\n  const { path, params } = parseLocation();\n  const match = path.match(CONTENTS_ROUTE_REGEX);\n\n  /** @type {ContentsRouteState} */\n  const state = {\n    isIndexPage: false,\n    isSearchPage: false,\n    notFoundKey: '',\n    awaitingDrafts: false,\n    editorLocale: params._locale,\n  };\n\n  delete params._locale;\n\n  const pullRequestNumber = params._pr === undefined ? undefined : Number(params._pr);\n\n  delete params._pr;\n\n  // `/collections/_singletons` should not be used unless there is only the singleton collection\n  if (selectedCollection.current?.name === '_singletons' && getValidCollections().length) {\n    selectedCollection.current = undefined;\n  }\n\n  if (!match?.groups) {\n    showContentOverlay.current = false;\n\n    // Check if it’s the search page, which has a different URL pattern (`#/search/{query}`)\n    return { ...state, isSearchPage: isSearchRoute(path) }; // Different page\n  }\n\n  const { _collectionName, routeType, subPath } = match.groups;\n\n  if (!_collectionName) {\n    return resolveCollectionIndexRoute(state);\n  }\n\n  /** @type {InternalCollection | undefined} */\n  const collection = getCollection(_collectionName);\n\n  selectRouteCollection(collection);\n\n  if (!collection || !selectedCollection.current) {\n    return showNotFound(state, 'collection_not_found');\n  }\n\n  const { name: collectionName } = selectedCollection.current;\n  const collectionLabel = getCollectionLabel(selectedCollection.current);\n\n  const _fileMap =\n    '_fileMap' in selectedCollection.current ? selectedCollection.current._fileMap : undefined;\n\n  if (!routeType && subPath) {\n    // A collection route takes no path of its own, so anything between the collection name and\n    // an `entries`/`new`/`filter` segment is a dead link, e.g. `#/collections/pages/foo/ever`\n    return showNotFound(state, 'page_not_found');\n  }\n\n  /** @type {CollectionRouteArgs} */\n  const args = {\n    state,\n    entryDraft,\n    collection,\n    collectionName,\n    collectionLabel,\n    routeType,\n    subPath,\n    pullRequestNumber,\n  };\n\n  if (!routeType || routeType === 'filter') {\n    return resolveListingRoute(args);\n  }\n\n  showContentOverlay.current = true;\n\n  // An entry opened with a deep link can’t be resolved until the drafts are in either. Show a\n  // loading state in the meantime\n  if (routeType === 'entries' && subPath && !workflowDataReady.current) {\n    announcedPageStatus.current = _('loading_entries', { values: { count: 1 } });\n\n    return { ...state, awaitingDrafts: true };\n  }\n\n  if (_fileMap) {\n    // File/singleton collection\n    return resolveFileRoute({ ...args, fileMap: _fileMap });\n  }\n\n  // Entry collection\n  return resolveEntryRoute({ ...args, params });\n};\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { onMount, untrack } from 'svelte';\n\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import BackupFeedback from '$lib/components/contents/details/backup-feedback.svelte';\n  import ContentDetailsOverlay from '$lib/components/contents/details/content-details-overlay.svelte';\n  import EntryList from '$lib/components/contents/list/entry-list.svelte';\n  import FileList from '$lib/components/contents/list/file-list.svelte';\n  import PrimarySidebar from '$lib/components/contents/list/primary-sidebar.svelte';\n  import PrimaryToolbar from '$lib/components/contents/list/primary-toolbar.svelte';\n  import SecondarySidebar from '$lib/components/contents/list/secondary-sidebar.svelte';\n  import SecondaryToolbar from '$lib/components/contents/list/secondary-toolbar.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import SearchMainArea from '$lib/components/search/search-main-area.svelte';\n  import { updateContentFromHashChange } from '$lib/services/app/navigation';\n  import { getCollectionLabel, selectedCollection } from '$lib/services/contents/collection';\n  import { listedEntryCount } from '$lib/services/contents/collection/view';\n  import { showBackupToastIfNeeded } from '$lib/services/contents/draft/backup';\n  import { EntryDraftState } from '$lib/services/contents/draft/state.svelte';\n  import { showContentOverlay } from '$lib/services/contents/editor';\n  import { CONTENTS_ROUTE_REGEX, resolveContentsRoute } from '$lib/services/contents/navigation';\n  import { env } from '$lib/services/user/env.svelte';\n  import { watch } from '$lib/services/utils/state.svelte';\n  import { workflowDataReady } from '$lib/services/workflow';\n\n  /**\n   * Draft open in the content editor overlay, if any.\n   */\n  const entryDraft = new EntryDraftState();\n\n  let isIndexPage = $state(false);\n  let isSearchPage = $state(false);\n  /** Message key shown on the Not Found view, or an empty string when the route resolved. */\n  let notFoundKey = $state('');\n  /**\n   * Whether the route can’t be resolved until the Editorial Workflow drafts are in. The route is\n   * tried again once they are; the effect below re-runs {@link navigate}.\n   */\n  let awaitingDrafts = $state(false);\n  /** @type {string | undefined} */\n  let editorLocale = $state();\n\n  const MainContent = $derived(\n    'files' in (selectedCollection.current ?? {}) ? FileList : EntryList,\n  );\n\n  /**\n   * Navigate to the content list or content details page given the URL hash.\n   */\n  const navigate = () => {\n    ({ isIndexPage, isSearchPage, notFoundKey, awaitingDrafts, editorLocale } =\n      resolveContentsRoute({ entryDraft }));\n  };\n\n  onMount(() => {\n    navigate();\n\n    return () => {\n      showContentOverlay.current = false;\n    };\n  });\n\n  watch(\n    () => showContentOverlay.current,\n    () => {\n      if (!showContentOverlay.current) {\n        // The draft is kept once the editor is closed, so its backup can be looked up. There is no\n        // draft before an entry has been opened\n        showBackupToastIfNeeded(entryDraft.current);\n      }\n    },\n  );\n\n  $effect(() => {\n    if (awaitingDrafts && workflowDataReady.current) {\n      // Opening an entry reads and replaces the draft, which is no reason to navigate again\n      untrack(() => navigate());\n    }\n  });\n</script>\n\n<svelte:window\n  onhashchange={(event) => {\n    updateContentFromHashChange(event, navigate, CONTENTS_ROUTE_REGEX);\n  }}\n/>\n\n<PageContainer uiSettingsKey=\"contents-page\" aria-label={_('content_library')}>\n  {#snippet primarySidebar()}\n    {#if !env.isSmallScreen || isIndexPage}\n      <PrimarySidebar {isSearchPage} />\n    {/if}\n  {/snippet}\n  {#snippet main()}\n    {#if isSearchPage}\n      <SearchMainArea />\n    {:else if notFoundKey}\n      <PageContainerMainArea id=\"collection-container\" aria-label={_('content_library')}>\n        {#snippet mainContent()}\n          <NotFound message={_(notFoundKey)} />\n        {/snippet}\n      </PageContainerMainArea>\n    {:else if !env.isSmallScreen || !isIndexPage}\n      <PageContainerMainArea\n        id=\"collection-container\"\n        aria-label={_('x_collection', {\n          values: {\n            collection:\n              // `appLocale.current` is a key, because `getCollectionLabel` can return a localized\n              // label\n              appLocale.current && selectedCollection.current\n                ? getCollectionLabel(selectedCollection.current)\n                : '',\n          },\n        })}\n        aria-description={selectedCollection.current?.description}\n      >\n        {#snippet primaryToolbar()}\n          <PrimaryToolbar />\n        {/snippet}\n        {#snippet secondaryToolbar()}\n          <!-- The count includes the entries hidden by a filter, so the filter can be reset -->\n          {#if selectedCollection.current?._type === 'entry' && listedEntryCount.current}\n            <SecondaryToolbar />\n          {/if}\n        {/snippet}\n        {#snippet mainContent()}\n          <MainContent />\n        {/snippet}\n        {#snippet secondarySidebar()}\n          <SecondarySidebar />\n        {/snippet}\n      </PageContainerMainArea>\n    {/if}\n  {/snippet}\n</PageContainer>\n\n{#if showContentOverlay.current}\n  <ContentDetailsOverlay {entryDraft} {editorLocale} loading={awaitingDrafts} />\n{/if}\n\n<!-- Outside the overlay, so the toast can tell the user about the backup once it’s closed -->\n<BackupFeedback />\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Option, Select } from '@sveltia/ui';\n\n  import { allTranslationServices } from '$lib/services/integrations/translators';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n</script>\n\n<Select\n  ariaLabel={_('prefs.i18n.translators.default.select_service')}\n  value={prefs.defaultTranslationService}\n  onChange={(event) => {\n    prefs.defaultTranslationService = event.detail.value;\n  }}\n>\n  {#each Object.entries(allTranslationServices) as [key, { serviceLabel: label }] (key)}\n    <Option {label} value={key} selected={key === prefs.defaultTranslationService} />\n  {/each}\n</Select>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { PromptDialog, Spacer } from '@sveltia/ui';\n\n  import TranslatorSelector from '$lib/components/settings/controls/translator-selector.svelte';\n  import { showContentOverlay, translatorApiKeyDialogState } from '$lib/services/contents/editor';\n  import { getServiceDescription } from '$lib/services/integrations/service-description';\n  import { translator } from '$lib/services/integrations/translators';\n  import { saveApiKey } from '$lib/services/user/api-keys';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n\n  const { serviceId, apiLabel, developerURL, apiKeyURL, apiKeyPattern } = $derived(\n    translator.current,\n  );\n\n  // eslint-disable-next-line svelte/prefer-writable-derived\n  let inputValue = $state('');\n\n  /**\n   * Whether the entered key matches the expected pattern, which is required to confirm the dialog.\n   */\n  const isKeyValid = $derived(!!apiKeyPattern?.test(inputValue.trim()));\n\n  $effect(() => {\n    // Update the input value when a different translator service is selected\n    inputValue = prefs.apiKeys?.[serviceId] ?? '';\n  });\n\n  /**\n   * Settle the promise the translation is waiting for, once. The dialog closes in any case: with a\n   * key saved, or cancelled or dismissed, which leaves the translation undone.\n   * @param {string} [apiKey] Saved API key.\n   */\n  const settle = (apiKey) => {\n    const { resolve } = translatorApiKeyDialogState.current;\n\n    translatorApiKeyDialogState.current.show = false;\n    translatorApiKeyDialogState.current.resolve = undefined;\n    resolve?.(apiKey);\n  };\n\n  $effect(() => {\n    if (!showContentOverlay.current && translatorApiKeyDialogState.current.show) {\n      // Close the dialog when the Content Editor is closed\n      settle();\n    }\n  });\n\n  /**\n   * Saves the API key to the user preferences if it matches the expected pattern. It’s called when\n   * the dialog is confirmed or a key is pasted, not while a key is being typed, because a pattern\n   * without a maximum length would match a key cut short.\n   */\n  const saveKey = () => {\n    const apiKey = saveApiKey(serviceId, inputValue, apiKeyPattern);\n\n    if (apiKey !== undefined) {\n      settle(apiKey);\n    }\n  };\n</script>\n\n<PromptDialog\n  bind:open={translatorApiKeyDialogState.current.show}\n  bind:value={inputValue}\n  title={_('translate_fields', {\n    values: { count: translatorApiKeyDialogState.current.multiple ? 2 : 1 },\n  })}\n  textboxAttrs={{\n    spellcheck: false,\n    monospace: true,\n    ariaLabel: _('api_key'),\n  }}\n  oninput={(event) => {\n    if (/** @type {InputEvent} */ (event).inputType === 'insertFromPaste') {\n      saveKey();\n    }\n  }}\n  okDisabled={!isKeyValid}\n  onOk={() => saveKey()}\n  onClose={() => {\n    // Settle the translation when the dialog is closed without a key being saved, whether it’s\n    // cancelled or dismissed. An OK button click has already saved the key, as the button is\n    // disabled for an invalid one, and settled it. The dialog doesn’t call this when it has been\n    // opened again before it finished closing\n    settle();\n  }}\n>\n  <TranslatorSelector />\n  <Spacer />\n  {@html getServiceDescription('prefs.i18n.translators.description', {\n    service: apiLabel,\n    developerURL,\n    apiKeyURL,\n  })}\n</PromptDialog>\n","<!--\n  @component\n  Toasts reporting the result of an entry operation. These live outside the content library,\n  because the editor can close onto another page — the search results an entry was opened from,\n  say — and the result should be reported wherever the user lands.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Toast } from '@sveltia/ui';\n\n  import { contentUpdatesToast } from '$lib/services/contents/collection/data';\n</script>\n\n<Toast bind:show={contentUpdatesToast.current.saved}>\n  <Alert status=\"success\">\n    {_(contentUpdatesToast.current.published ? 'entry_saved_and_published' : 'entry_saved', {\n      values: { count: contentUpdatesToast.current.count },\n    })}\n  </Alert>\n</Toast>\n\n<Toast bind:show={contentUpdatesToast.current.deletionCancelled}>\n  <Alert status=\"success\">{_('workflow.deletion_cancelled')}</Alert>\n</Toast>\n\n<Toast bind:show={contentUpdatesToast.current.discarded}>\n  <Alert status=\"success\">\n    {_('workflow.changes_discarded', { values: { count: contentUpdatesToast.current.count } })}\n  </Alert>\n</Toast>\n\n<Toast bind:show={contentUpdatesToast.current.deleted}>\n  <Alert status=\"success\">\n    {_(\n      contentUpdatesToast.current.deletionPending ? 'workflow.deletion_pending' : 'entries_deleted',\n      {\n        values: { count: contentUpdatesToast.current.count },\n      },\n    )}\n  </Alert>\n</Toast>\n\n<Toast bind:show={contentUpdatesToast.current.alreadyPublished}>\n  <Alert status=\"error\">{_('open_authoring.entry_already_published')}</Alert>\n</Toast>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Toast } from '@sveltia/ui';\n\n  import { entryParseErrors } from '$lib/services/contents';\n\n  let showParseErrorToast = $state(!!entryParseErrors.current.length);\n</script>\n\n<Toast bind:show={showParseErrorToast}>\n  <Alert status=\"error\">\n    {_('entry_parse_errors', { values: { count: entryParseErrors.current.length } })}\n  </Alert>\n</Toast>\n","import { customPageRegistry } from '$lib/services/api/registries';\nimport { goto } from '$lib/services/app/navigation';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\nimport { openNewTab } from '$lib/services/utils/window';\n\n/**\n * @import { CustomPage } from '$lib/types/private';\n */\n\n/**\n * Route pattern for a custom page, e.g. `/pages/analytics`.\n */\nconst CUSTOM_PAGE_ROUTE_REGEX = /^\\/pages\\/(?<id>[^/]+)$/;\n\n/**\n * ID of the custom page the URL points to, set by the main router. Empty on any other page.\n */\nexport const selectedCustomPageId = createRawState('');\n\n/**\n * Custom page the URL points to, or `undefined` if the URL points to another page, or to a custom\n * page that hasn’t been registered (yet).\n */\nexport const selectedCustomPage = createDerivedState(() =>\n  selectedCustomPageId.current ? customPageRegistry.get(selectedCustomPageId.current) : undefined,\n);\n\n/**\n * All the registered custom pages, in the order of registration.\n */\nexport const customPages = createDerivedState(() => [...customPageRegistry.values()]);\n\n/**\n * Get the ID of the custom page the given URL path points to.\n * @param {string} path URL path, as returned by `parseLocation()`.\n * @returns {string} Page ID, or an empty string if the path is not a custom page route.\n */\nexport const getCustomPageId = (path) => path.match(CUSTOM_PAGE_ROUTE_REGEX)?.groups?.id ?? '';\n\n/**\n * Get the URL path of the given custom page. The ID only consists of characters that need no\n * encoding, as `CMS.registerCustomPage()` makes sure of it.\n * @param {CustomPage} page Custom page.\n * @returns {string} URL path.\n */\nexport const getCustomPagePath = ({ id }) => `/pages/${id}`;\n\n/**\n * Open the given custom page: navigate to it, or open its web page in a new browser tab if it’s a\n * link.\n * @param {CustomPage} page Custom page.\n */\nexport const openCustomPage = (page) => {\n  if (page.newTab) {\n    openNewTab(page.url);\n  } else {\n    goto(getCustomPagePath(page));\n  }\n};\n","<!--\n  @component\n  Render a custom page registered via `CMS.registerCustomPage()`: a React component, or a web page\n  embedded in an iframe.\n  @see https://sveltiacms.app/en/docs/api/custom-pages\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Spacer, Toolbar } from '@sveltia/ui';\n  import { createElement } from 'react';\n\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import BackButton from '$lib/components/common/page-toolbar/back-button.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import { mountReactNode } from '$lib/services/api/react-dom';\n  import { selectedCustomPage } from '$lib/services/app/custom-pages';\n  import { announcedPageStatus, goBack } from '$lib/services/app/navigation';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { ComponentType } from 'react';\n   * @import { Attachment } from 'svelte/attachments';\n   */\n\n  const page = $derived(selectedCustomPage.current);\n  // A page that opens in a new tab has nothing to show here, so its route is a dead link too\n  const shownPage = $derived(page && !page.newTab ? page : undefined);\n  const label = $derived(shownPage?.label ?? _('page_not_found'));\n  // The component on its own, so the page registered again with only a new label, for example,\n  // keeps the rendered component and its state rather than mounting it anew\n  const pageComponent = $derived(shownPage?.component);\n\n  /**\n   * Create an attachment rendering the given React component in the element, which is unmounted\n   * along with the element, or when another component is given.\n   * @param {ComponentType} component React component.\n   * @returns {Attachment<HTMLElement>} Attachment.\n   */\n  const renderComponent = (component) => (element) =>\n    mountReactNode(element, createElement(component));\n\n  $effect(() => {\n    if (!shownPage) {\n      announcedPageStatus.current = _('page_not_found');\n    }\n  });\n</script>\n\n<PageContainer aria-label={label}>\n  {#snippet main()}\n    <PageContainerMainArea aria-label={label}>\n      {#snippet primaryToolbar()}\n        <Toolbar variant=\"primary\">\n          {#if env.isSmallScreen}\n            <BackButton onclick={() => goBack('/menu')} />\n          {/if}\n          <h2 role=\"none\">{label}</h2>\n          <Spacer flex />\n        </Toolbar>\n      {/snippet}\n      {#snippet mainContent()}\n        {#if !shownPage}\n          <NotFound message={_('page_not_found')} />\n        {:else if pageComponent}\n          <div role=\"none\" class=\"content\" {@attach renderComponent(pageComponent)}></div>\n        {:else}\n          <iframe src={shownPage.url} title={shownPage.label}></iframe>\n        {/if}\n      {/snippet}\n    </PageContainerMainArea>\n  {/snippet}\n</PageContainer>\n\n<style>\n  .content {\n    flex: auto;\n    overflow: auto;\n  }\n\n  iframe {\n    flex: auto;\n    border: 0;\n    width: 100%;\n  }\n</style>\n","import { IndexedDB, LocalStorage } from '@sveltia/utils/storage';\n\nimport { backend } from '$lib/services/backends';\nimport {\n  getBackupDatabaseName,\n  TEST_BACKEND_NAME,\n  TEST_BACKEND_ROOT_DIR_NAME,\n} from '$lib/services/backends/fs/test';\nimport { gitBackendServices } from '$lib/services/backends/git/services';\nimport { LEGACY_USER_STORAGE_KEYS } from '$lib/services/user/constants';\n\n/**\n * Names of the IndexedDB object stores holding cached file contents and directory listings,\n * generated asset thumbnails and the asset hashes computed by the local backend. The data in these\n * stores can always be re-fetched or regenerated, so it’s safe to delete.\n * @type {string[]}\n */\nconst CACHE_STORE_NAMES = ['file-cache', 'tree-cache', 'asset-thumbnails', 'asset-hashes'];\n\n/**\n * Prefix shared by all the local storage keys written by the CMS, such as `sveltia-cms.prefs`.\n */\nexport const LOCAL_STORAGE_KEY_PREFIX = 'sveltia-cms.';\n\n/**\n * Pattern matching the IndexedDB database names created by the CMS, which are made up of a backend\n * name and a repository path, e.g. `github:owner/repo`, or the test backend’s own database name.\n * Used to leave any database owned by the site hosting the CMS untouched.\n */\nconst DATABASE_NAME_REGEX = new RegExp(\n  `^(?:${[...Object.keys(gitBackendServices), TEST_BACKEND_NAME].join('|')}):`,\n);\n\n/**\n * Delete the directory in the origin private file system (OPFS) where the `test-repo` backend keeps\n * entry and asset files. This is the backend’s only storage, so removing it resets the test site to\n * an empty state.\n * @returns {Promise<void>}\n */\nconst clearTestBackendFiles = async () => {\n  try {\n    const rootDirHandle = await navigator.storage.getDirectory();\n\n    await rootDirHandle.removeEntry(TEST_BACKEND_ROOT_DIR_NAME, { recursive: true });\n  } catch {\n    // The directory may not exist yet, or the handle may not be available for security reasons\n  }\n};\n\n/**\n * Delete all the locally cached files, including remote file contents and asset thumbnails.\n * @returns {Promise<void>}\n */\nexport const clearFileCache = async () => {\n  const _backend = backend.current;\n  const { databaseName } = _backend?.repository ?? {};\n\n  if (databaseName) {\n    // One store at a time: clearing a store the database doesn’t have yet bumps the database\n    // version to create it, and two of those at once leave one connection without its store\n    await CACHE_STORE_NAMES.reduce(\n      (previous, storeName) => previous.then(() => new IndexedDB(databaseName, storeName).clear()),\n      Promise.resolve(),\n    );\n  }\n\n  if (_backend?.name === TEST_BACKEND_NAME) {\n    await clearTestBackendFiles();\n  }\n};\n\n/**\n * Get the names of the IndexedDB databases created by the CMS. The database for the current\n * repository is always included, while any database left behind by another repository or backend is\n * picked up only where `IDBFactory.databases()` is available; Firefox doesn’t implement it.\n * @returns {Promise<string[]>} Database names.\n */\nconst getDatabaseNames = async () => {\n  const databaseName = getBackupDatabaseName(backend.current);\n  const names = new Set(databaseName ? [databaseName] : []);\n\n  try {\n    (await globalThis.indexedDB.databases?.())?.forEach(({ name }) => {\n      if (name && DATABASE_NAME_REGEX.test(name)) {\n        names.add(name);\n      }\n    });\n  } catch {\n    // Enumeration is best-effort; fall back to the current repository’s database alone\n  }\n\n  return [...names];\n};\n\n/**\n * Delete an IndexedDB database.\n * @param {string} name Database name.\n * @returns {Promise<void>}\n */\nconst deleteDatabase = async (name) =>\n  new Promise((resolve) => {\n    /**\n     * Stop waiting for the deletion. This is also called on `blocked`, which fires when another\n     * open connection keeps the deletion pending: the app is about to be reloaded anyway, and the\n     * deletion goes through once the page unloads, so there’s no point in blocking on it.\n     * @returns {void}\n     */\n    const done = () => resolve();\n    const request = globalThis.indexedDB.deleteDatabase(name);\n\n    request.onsuccess = done;\n    request.onerror = done;\n    request.onblocked = done;\n  });\n\n/**\n * Delete the local storage entries written by the CMS, leaving any entry owned by the site hosting\n * the CMS untouched.\n * @returns {Promise<void>}\n */\nconst clearLocalStorage = async () => {\n  try {\n    const keys = (await LocalStorage.keys()).filter(\n      (key) => key.startsWith(LOCAL_STORAGE_KEY_PREFIX) || LEGACY_USER_STORAGE_KEYS.includes(key),\n    );\n\n    await Promise.all(keys.map((key) => LocalStorage.delete(key)));\n  } catch {\n    // Storage access may be denied, e.g. when third-party cookies are blocked\n  }\n};\n\n/**\n * Delete all the data the CMS keeps in the browser: the IndexedDB databases holding cached files,\n * asset thumbnails, draft backups and UI settings, the local storage entries holding the user’s\n * sign-in state and preferences, and the files stored by the `test-repo` backend.\n * @returns {Promise<void>}\n */\nexport const eraseAllData = async () => {\n  const names = await getDatabaseNames();\n\n  // None of these reject, so they can all run at once\n  await Promise.all([\n    ...names.map((name) => deleteDatabase(name)),\n    clearLocalStorage(),\n    clearTestBackendFiles(),\n  ]);\n};\n","import { LocalStorage } from '@sveltia/utils/storage';\n\nimport { isAdditionsEnabled } from '$lib/services/app/additions';\nimport { LOCAL_STORAGE_KEY_PREFIX } from '$lib/services/app/cache';\nimport { getUISettingsDB } from '$lib/services/app/ui-settings';\nimport { backend } from '$lib/services/backends';\nimport { isDemoSite } from '$lib/services/backends/fs/seed';\nimport { user } from '$lib/services/user/account.svelte';\nimport { env } from '$lib/services/user/env.svelte';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * Whether the dialog offering to sign in on a mobile device can be shown. The link carries the\n * backend token, which with Sveltia CMS Additions is a GitHub token that only works with the\n * session it was issued for, so it couldn’t sign anyone in and would only expose the token.\n */\nexport const canShowMobileSignInDialog = createDerivedState(\n  () =>\n    env.isLargeScreen &&\n    env.hasMouse &&\n    !env.isLocalHost &&\n    !!backend.current?.isGit &&\n    !!user.account?.token &&\n    !isAdditionsEnabled(),\n);\n\n/**\n * Whether to show the dialog offering to sign in on a mobile device.\n */\nexport const showMobileSignInDialog = createRawState(false);\n\n/**\n * Get a state value from the UI settings database.\n * @param {string} name State name to get from the UI settings database.\n * @returns {Promise<any>} The state value, or `undefined` if not found.\n */\nexport const getState = async (name) => {\n  const db = getUISettingsDB();\n\n  if (!db) {\n    return undefined;\n  }\n\n  const onboardingState = (await db.get('onboarding')) ?? {};\n\n  return onboardingState[name];\n};\n\n/**\n * Set a state value in the UI settings database.\n * @param {string} name State name to set in the UI settings database.\n * @param {any} value State value to set in the UI settings database.\n * @returns {Promise<void>}\n */\nexport const setState = async (name, value) => {\n  const db = getUISettingsDB();\n\n  if (!db) {\n    return;\n  }\n\n  const onboardingState = (await db.get('onboarding')) ?? {};\n\n  await db.set('onboarding', { ...onboardingState, [name]: value });\n};\n\n/**\n * @typedef {object} OneOffNoticeStorage\n * @property {(name: string) => Promise<any>} get Function to read the stored dismissal.\n * @property {(name: string, value: boolean) => Promise<void>} set Function to store the dismissal.\n */\n\n/**\n * @typedef {object} OneOffNotice\n * @property {{ current: boolean }} show Whether the notice is shown.\n * @property {() => Promise<void>} showIfNeeded Show the notice unless it has been dismissed.\n * @property {() => void} hide Hide the notice and remember it, so it doesn’t come back.\n */\n\n/**\n * Storage keeping the dismissal of a one-off notice in the UI settings database.\n * @type {OneOffNoticeStorage}\n */\nconst uiSettingsNoticeStorage = { get: getState, set: setState };\n\n/**\n * Create the state of a one-off notice, such as an infobar, that stays hidden once dismissed.\n * @param {string} name State name to store the dismissal under.\n * @param {OneOffNoticeStorage} [storage] Storage to keep the dismissal in. The UI settings database\n * by default.\n * @returns {OneOffNotice} Notice state.\n */\nexport const createOneOffNotice = (name, storage = uiSettingsNoticeStorage) => {\n  const show = createRawState(false);\n\n  return {\n    show,\n    /**\n     * Show the notice unless it has been dismissed.\n     */\n    showIfNeeded: async () => {\n      show.current = !(await storage.get(name));\n    },\n    /**\n     * Hide the notice and remember it, so it doesn’t come back.\n     */\n    hide: () => {\n      show.current = false;\n      storage.set(name, true);\n    },\n  };\n};\n\n/**\n * Local storage key remembering that the user has seen the demo welcome dialog. The test backend\n * has no repository database to keep it in, unlike the notices above. The Erase All Data option\n * deletes it along with the demo repository, so the dialog greets the user again when the demo\n * starts over.\n */\nexport const DEMO_WELCOME_STORAGE_KEY = `${LOCAL_STORAGE_KEY_PREFIX}demo-welcome-seen`;\n\n/**\n * Storage keeping the dismissal of a one-off notice in local storage.\n * @type {OneOffNoticeStorage}\n */\nconst localNoticeStorage = {\n  /**\n   * Read the stored dismissal.\n   * @param {string} key Local storage key.\n   * @returns {Promise<any>} Stored value, or `undefined` if the storage can’t be read.\n   */\n  get: async (key) => {\n    try {\n      return await LocalStorage.get(key);\n    } catch {\n      // Storage access may be denied, e.g. when third-party cookies are blocked. Better to show the\n      // notice on every visit than never\n      return undefined;\n    }\n  },\n  /**\n   * Store the dismissal, ignoring any error.\n   * @param {string} key Local storage key.\n   * @param {boolean} value Value to store.\n   */\n  set: async (key, value) => {\n    try {\n      await LocalStorage.set(key, value);\n    } catch {\n      //\n    }\n  },\n};\n\n/**\n * State of the dialog welcoming the user to the demo.\n */\nexport const demoWelcomeNotice = createOneOffNotice(DEMO_WELCOME_STORAGE_KEY, localNoticeStorage);\n\n/**\n * Show the demo welcome dialog if the CMS runs as a demo and the user hasn’t seen it yet.\n * @returns {Promise<void>}\n */\nexport const showDemoWelcomeDialogIfNeeded = async () => {\n  if (!isDemoSite(backend.current?.name)) {\n    return;\n  }\n\n  await demoWelcomeNotice.showIfNeeded();\n};\n","<!--\n  @component\n  Welcome the user to the demo once they’ve signed in, and tell them that their changes are only\n  saved in the browser, not published online.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Dialog } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import { demoWelcomeNotice, showDemoWelcomeDialogIfNeeded } from '$lib/services/app/onboarding';\n\n  onMount(() => {\n    showDemoWelcomeDialogIfNeeded();\n  });\n</script>\n\n<Dialog\n  bind:open={demoWelcomeNotice.show.current}\n  title={_('demo_welcome.title')}\n  size=\"small\"\n  okLabel={_('demo_welcome.button_label')}\n  showCancel={false}\n  onClose={() => {\n    // Covers the button, the Escape key and any other way out\n    demoWelcomeNotice.hide();\n  }}\n>\n  <p>{_('demo_welcome.description')}</p>\n  <p>{_('demo_welcome.reset_hint')}</p>\n</Dialog>\n\n<style>\n  p {\n    margin: 0;\n\n    &:not(:first-child) {\n      margin-top: 1em;\n    }\n  }\n</style>\n","import { DOCS_BASE_URL } from '$lib/services/app';\n\n/**\n * Documentation explaining why the CMS must be served as a static file.\n */\nexport const LIVE_RELOAD_DOCS_URL = `${DOCS_BASE_URL}/workflows/local#troubleshooting`;\n\n/**\n * Check if the CMS is running on a page that a framework’s development server renders and reloads\n * on every file change, e.g. `src/pages/admin.astro` with Astro, instead of a static HTML file such\n * as `public/admin/index.html`. Vite, which powers Astro, SvelteKit, Nuxt, VitePress and others,\n * injects its client script into such a page, which then reloads while the CMS is writing files\n * with the local backend, leaving a file empty or a temporary file behind.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/issues/1061\n */\nexport const isLiveReloadedPage = () =>\n  // The CMS’s own development server injects the script too\n  !import.meta.env.DEV && !!document.querySelector('script[src*=\"/@vite/client\"]');\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Infobar } from '@sveltia/ui';\n\n  import { isLiveReloadedPage, LIVE_RELOAD_DOCS_URL } from '$lib/services/app/dev-server';\n  import { backendName } from '$lib/services/backends';\n  import { makeLink } from '$lib/services/utils/string';\n\n  // A reload only does harm while the CMS is writing files to the local repository\n  const show = $derived(backendName.current === 'local' && isLiveReloadedPage());\n</script>\n\n<Infobar {show} status=\"warning\" --sui-infobar-message-justify-content=\"center\">\n  {@html makeLink(_('live_reload_warning'), LIVE_RELOAD_DOCS_URL)}\n</Infobar>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Infobar } from '@sveltia/ui';\n\n  import { createOneOffNotice, showMobileSignInDialog } from '$lib/services/app/onboarding';\n\n  const notice = createOneOffNotice('mobileCta');\n\n  $effect(() => {\n    notice.showIfNeeded();\n  });\n</script>\n\n<Infobar\n  show={notice.show.current}\n  dismissible={false}\n  --sui-infobar-message-justify-content=\"center\"\n>\n  {_('mobile_promo_title')}\n  <Button\n    variant=\"link\"\n    label={_('mobile_promo_button')}\n    onclick={() => {\n      showMobileSignInDialog.current = true;\n      notice.hide();\n    }}\n  />\n  <Button\n    variant=\"link\"\n    label={_('later')}\n    onclick={() => {\n      notice.hide();\n    }}\n  />\n</Infobar>\n","<script>\n  import { _, locale as appLocale, locales as availableLocales } from '@sveltia/i18n';\n  import { Button, Infobar } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import { getState, setState } from '$lib/services/app/onboarding';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n  import { AUTO_PREF_VALUE, prefs } from '$lib/services/user/prefs.svelte';\n\n  let newLocale = $state('');\n  let showInfobar = $state(false);\n  /** Whether the check below has already been made, so it’s not repeated on a preference change. */\n  let checked = false;\n\n  /**\n   * Show the infobar if the user has not seen it yet, the user’s browser language is different from\n   * the current app locale, and the user’s browser language is available in the app. Only relevant\n   * when the user has explicitly picked a language; see the effect below.\n   */\n  const showInfobarIfNeeded = async () => {\n    if (await getState('newLanguageCta')) {\n      return;\n    }\n\n    const currentLocale = appLocale.current;\n    const longLang = navigator.language;\n    const [shortLang] = longLang.split('-');\n\n    if (longLang === currentLocale || shortLang === currentLocale) {\n      return;\n    }\n\n    newLocale =\n      availableLocales.find((locale) => locale === longLang) ??\n      availableLocales.find((locale) => locale.split('-')[0] === shortLang) ??\n      '';\n\n    if (newLocale && newLocale !== currentLocale) {\n      showInfobar = true;\n    }\n  };\n\n  /**\n   * Hide the infobar and set the state to indicate that the user has seen it.\n   */\n  const hideInfobar = () => {\n    showInfobar = false;\n    setState('newLanguageCta', true);\n  };\n\n  $effect(() => {\n    const { locale } = prefs;\n\n    untrack(() => {\n      // Wait for the preferences to be loaded\n      if (checked || !locale) {\n        return;\n      }\n\n      // Make the check only once, when the preferences are loaded, so that the infobar never shows\n      // up right after the user has picked a language on the Settings dialog\n      checked = true;\n\n      // The infobar is pointless while the language preference is `auto`, because the UI already\n      // follows the browser’s language settings\n      if (locale !== AUTO_PREF_VALUE) {\n        showInfobarIfNeeded();\n      }\n    });\n  });\n</script>\n\n<Infobar show={showInfobar} dismissible={false} --sui-infobar-message-justify-content=\"center\">\n  {_('new_language_available', {\n    locale: newLocale,\n    values: { locale: getLocaleLabel(newLocale, { displayLocale: newLocale }) },\n  })}\n  <Button\n    variant=\"link\"\n    label={_('change_language', { locale: newLocale })}\n    onclick={() => {\n      prefs.locale = newLocale;\n      hideInfobar();\n    }}\n  />\n  <Button\n    variant=\"link\"\n    label={_('later', { locale: newLocale })}\n    onclick={() => {\n      hideInfobar();\n    }}\n  />\n</Infobar>\n","import { _ } from '@sveltia/i18n';\n\n/**\n * @import { LocalGitNotice, LocalGitStatus } from '$lib/types/private';\n */\n\n/**\n * Get the localized explanation of why changes can’t be committed to the local Git repository.\n * @param {LocalGitNotice} notice Reason, and its details if any: the operation for\n * `operation_in_progress`, the file path for `lfs`, and the error message for `error`.\n * @returns {string} Explanation.\n */\nexport const getLocalGitReasonLabel = ({ reason, detail = '' }) =>\n  reason === 'operation_in_progress'\n    ? _(`local_git_skip_reasons.operation_in_progress.${detail}`)\n    : _(`local_git_skip_reasons.${reason}`, { values: { path: detail, message: detail } });\n\n/**\n * Get the localized summary of whether changes can be committed to the local Git repository, for\n * the Settings.\n * @param {LocalGitStatus} status Status.\n * @returns {string} Summary.\n */\nexport const getLocalGitStatusLabel = ({ ready, reason, detail, branch, author }) => {\n  if (!ready) {\n    return _('prefs.developer.local_git.not_ready', {\n      values: {\n        reason: getLocalGitReasonLabel(/** @type {LocalGitNotice} */ ({ reason, detail })),\n      },\n    });\n  }\n\n  // The branch and author are always known once the changes can be committed\n  const { name, email } = /** @type {NonNullable<LocalGitStatus['author']>} */ (author);\n\n  return _('prefs.developer.local_git.ready', {\n    values: { branch: /** @type {string} */ (branch).replace(/^refs\\/heads\\//, ''), name, email },\n  });\n};\n","<!--\n  @component\n  Notify the user that the changes they’ve saved with the local backend have been saved but not\n  committed to Git, and why.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Toast } from '@sveltia/ui';\n\n  import { localGitNotice } from '$lib/services/backends/fs/git';\n  import { getLocalGitReasonLabel } from '$lib/services/backends/fs/git/messages';\n\n  let showToast = $state(false);\n  /**\n   * Notice shown last. It starts as the notice there was before the component was mounted, e.g.\n   * before the user signed out and in again, which mustn’t be shown again.\n   */\n  let shownNotice = localGitNotice.current;\n\n  $effect(() => {\n    const notice = localGitNotice.current;\n\n    if (notice && notice !== shownNotice) {\n      shownNotice = notice;\n      showToast = true;\n    }\n  });\n</script>\n\n<!-- Every save gets a new notice, which shows the toast again for the full duration -->\n{#key localGitNotice.current}\n  {#if localGitNotice.current}\n    <Toast bind:show={showToast}>\n      <Alert status=\"warning\">\n        {_('local_git_not_committed', {\n          values: { reason: getLocalGitReasonLabel(localGitNotice.current) },\n        })}\n      </Alert>\n    </Toast>\n  {/if}\n{/key}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { onMount } from 'svelte';\n\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import { announcedPageStatus } from '$lib/services/app/navigation';\n\n  onMount(() => {\n    announcedPageStatus.current = _('page_not_found');\n  });\n</script>\n\n<PageContainer aria-label={_('page_not_found')}>\n  {#snippet main()}\n    <PageContainerMainArea>\n      {#snippet mainContent()}\n        <NotFound message={_('page_not_found')} />\n      {/snippet}\n    </PageContainerMainArea>\n  {/snippet}\n</PageContainer>\n","import { _ } from '@sveltia/i18n';\n\nimport { getCustomPagePath } from '$lib/services/app/custom-pages';\n\n/**\n * @import { CustomPage } from '$lib/types/private';\n */\n\n/**\n * Page to switch to with the page switcher in the toolbar or the bottom navigation.\n * @typedef {object} ToolbarPage\n * @property {string} key Unique key.\n * @property {string} label Label.\n * @property {string} icon Icon name.\n * @property {string} link Path to go to.\n * @property {boolean} selected Whether the page is the current one.\n */\n\n/**\n * Get the pages to switch between with the page switcher: Contents, followed by Assets if there is\n * anything to show, the Editorial Workflow, Administration, the custom pages and, on a small\n * screen, Menu, which lists the Administration sections instead.\n * @param {object} args Arguments.\n * @param {string} args.selectedPageName Name of the current page.\n * @param {'contents' | 'assets' | null} args.searchMode Search mode, which makes the page\n * being searched the selected one.\n * @param {boolean} args.hasAssets Whether there is anything to show on the Assets page: an asset\n * folder, an external location or a linked file.\n * @param {string} args.assetsLink Path of the Assets page.\n * @param {boolean} args.workflowEnabled Whether the Editorial Workflow is enabled.\n * @param {string} args.workflowLabelKey Message key of the Editorial Workflow page label.\n * @param {string | undefined} args.adminLink Path of the Administration page, if the user can see\n * any of it.\n * @param {CustomPage[]} args.customPages Custom pages to switch to, which don’t open in a new tab.\n * @param {string} args.selectedCustomPageId ID of the current custom page, if any.\n * @param {boolean} args.isSmallScreen Whether the screen is small.\n * @returns {ToolbarPage[]} Pages.\n */\nexport const getToolbarPages = ({\n  selectedPageName,\n  searchMode,\n  hasAssets,\n  assetsLink,\n  workflowEnabled,\n  workflowLabelKey,\n  adminLink,\n  customPages,\n  selectedCustomPageId,\n  isSmallScreen,\n}) => {\n  /** @type {ToolbarPage[]} */\n  const pages = [\n    {\n      key: 'collections',\n      label: _('contents'),\n      icon: 'article',\n      link: '/collections',\n      selected: selectedPageName === 'collections' || searchMode === 'contents',\n    },\n  ];\n\n  if (hasAssets) {\n    pages.push({\n      key: 'assets',\n      label: _('assets'),\n      icon: 'photo',\n      link: assetsLink,\n      selected: selectedPageName === 'assets' || searchMode === 'assets',\n    });\n  }\n\n  if (workflowEnabled) {\n    pages.push({\n      key: 'workflow',\n      label: _(workflowLabelKey),\n      icon: 'rebase_edit',\n      link: '/workflow',\n      selected: selectedPageName === 'workflow',\n    });\n  }\n\n  if (adminLink && !isSmallScreen) {\n    pages.push({\n      key: 'admin',\n      label: _('administration'),\n      icon: 'settings_applications',\n      link: adminLink,\n      selected: selectedPageName === 'admin',\n    });\n  }\n\n  customPages.forEach((page) => {\n    pages.push({\n      key: `pages/${page.id}`,\n      label: page.label,\n      icon: page.icon,\n      link: getCustomPagePath(page),\n      selected: selectedCustomPageId === page.id,\n    });\n  });\n\n  if (isSmallScreen) {\n    pages.push({\n      key: 'menu',\n      label: _('menu'),\n      icon: 'menu',\n      link: '/menu',\n      selected: selectedPageName === 'menu',\n    });\n  }\n\n  return pages;\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, SelectButton, SelectButtonGroup } from '@sveltia/ui';\n\n  import { getAdminLink } from '$lib/services/app/admin';\n  import {\n    customPages,\n    openCustomPage,\n    selectedCustomPageId,\n  } from '$lib/services/app/custom-pages';\n  import { goto, selectedPageName } from '$lib/services/app/navigation';\n  import { getToolbarPages } from '$lib/services/app/toolbar-pages';\n  import {\n    enabledCloudServices,\n    getCloudServicePath,\n    selectedCloudService,\n  } from '$lib/services/assets/external';\n  import { linkedAssets, linkedFilesService } from '$lib/services/assets/external/linked';\n  import { allAssetFolders, selectedAssetFolder } from '$lib/services/assets/folders';\n  import { searchMode } from '$lib/services/search';\n  import { env } from '$lib/services/user/env.svelte';\n  import { encodePathSegments } from '$lib/services/utils/url';\n  import { workflowEnabled } from '$lib/services/workflow';\n  import { workflowPageLabelKey } from '$lib/services/workflow/stages';\n\n  /**\n   * Link to the Asset Library: the folder list on small screens, otherwise the location shown\n   * last, falling back to All Assets or, when no asset folder is configured, the first external\n   * location or Linked Files.\n   */\n  const assetsLink = $derived.by(() => {\n    if (env.isSmallScreen) {\n      return '/assets';\n    }\n\n    if (selectedCloudService.current) {\n      return getCloudServicePath(selectedCloudService.current);\n    }\n\n    if (allAssetFolders.current.length) {\n      return encodePathSegments(`/assets/${selectedAssetFolder.current?.internalPath ?? '-/all'}`);\n    }\n\n    return getCloudServicePath(enabledCloudServices.current[0] ?? linkedFilesService);\n  });\n\n  /**\n   * Custom pages listed here. On small screens, they’re listed on the Menu page instead, as the\n   * bottom navigation has little room.\n   */\n  const listedCustomPages = $derived(env.isSmallScreen ? [] : customPages.current);\n  /**\n   * Custom pages opening in a new tab, which are not pages to switch to, so they’re listed after\n   * the page buttons.\n   */\n  const customLinks = $derived(listedCustomPages.filter(({ newTab }) => newTab));\n\n  const pages = $derived(\n    getToolbarPages({\n      selectedPageName: selectedPageName.current,\n      searchMode: searchMode.current,\n      // Hide the Assets page if there is nothing to show: no asset folder, no external location and\n      // no linked file\n      hasAssets: !!(\n        allAssetFolders.current.length ||\n        enabledCloudServices.current.length ||\n        linkedAssets.current.length\n      ),\n      assetsLink,\n      workflowEnabled: workflowEnabled.current,\n      workflowLabelKey: workflowPageLabelKey.current,\n      adminLink: getAdminLink(),\n      customPages: listedCustomPages.filter(({ newTab }) => !newTab),\n      selectedCustomPageId: selectedCustomPageId.current,\n      isSmallScreen: env.isSmallScreen,\n    }),\n  );\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <SelectButtonGroup ariaLabel={_('switch_page')} aria-controls=\"page-container\">\n    {#each pages as { key, label, icon, link, selected }, index (key)}\n      <SelectButton\n        variant=\"ghost\"\n        iconic\n        {selected}\n        tooltip={label}\n        aria-label={label}\n        keyShortcuts={index < 9 ? `Alt+${index + 1}` : undefined}\n        onclick={() => {\n          goto(link);\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name={icon} />\n        {/snippet}\n      </SelectButton>\n    {/each}\n  </SelectButtonGroup>\n  {#each customLinks as page (page.id)}\n    <Button\n      variant=\"ghost\"\n      iconic\n      tooltip={page.label}\n      aria-label={page.label}\n      onclick={() => {\n        openCustomPage(page);\n      }}\n    >\n      {#snippet startIcon()}\n        <Icon name={page.icon} />\n      {/snippet}\n    </Button>\n  {/each}\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n\n    :global {\n      .sui.select-button-group {\n        gap: 4px;\n\n        @media (width < 768px) {\n          justify-content: space-evenly;\n          width: 100%;\n        }\n      }\n\n      .sui.button {\n        border-radius: var(--sui-button-medium-border-radius) !important;\n      }\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { BottomNavigation, Toolbar } from '@sveltia/ui';\n\n  import PageSwitcher from '$lib/components/global/toolbar/items/page-switcher.svelte';\n  import { hasOverlay } from '$lib/services/app/navigation';\n</script>\n\n<BottomNavigation inert={hasOverlay.current}>\n  <Toolbar variant=\"primary\" ariaLabel={_('global')}>\n    <div role=\"none\" class=\"buttons\">\n      <PageSwitcher />\n    </div>\n  </Toolbar>\n</BottomNavigation>\n","import { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * `BeforeInstallPromptEvent` the browser fired to offer installing the app, kept until the app is\n * installed. Browsers fire it once, shortly after the page loads, so it’s captured at the app level\n * rather than by the menu item offering the installation, which is only rendered while the account\n * menu is open.\n * @type {{ current: any }}\n * @see https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/How_to/Trigger_install_prompt\n */\nexport const installPrompt = createRawState(null);\n\n/**\n * Keep the install prompt, and stop the browser from showing its own install UI.\n * @param {Event} event `BeforeInstallPromptEvent`.\n */\nconst beforeInstallPromptHandler = (event) => {\n  event.preventDefault();\n  installPrompt.current = event;\n};\n\n/**\n * Drop the install prompt once the app is installed.\n */\nconst appInstalledHandler = () => {\n  installPrompt.current = null;\n};\n\n/**\n * Start listening to the events telling whether the app can be installed. This should be called\n * when the app is initialized, before the browser offers to install it.\n * @returns {() => void} Function to stop listening.\n */\nexport const initAppInstallDetection = () => {\n  window.addEventListener('beforeinstallprompt', beforeInstallPromptHandler);\n  window.addEventListener('appinstalled', appInstalledHandler);\n\n  return () => {\n    window.removeEventListener('beforeinstallprompt', beforeInstallPromptHandler);\n    window.removeEventListener('appinstalled', appInstalledHandler);\n  };\n};\n\n/**\n * Show the browser’s install prompt, if it has offered to install the app. A prompt can only be\n * shown once, so it’s dropped right away; if the user dismisses it, the browser may fire another\n * `beforeinstallprompt` event later.\n * @returns {Promise<void>}\n */\nexport const promptAppInstall = async () => {\n  const prompt = installPrompt.current;\n\n  if (!prompt) {\n    return;\n  }\n\n  installPrompt.current = null;\n  await prompt.prompt();\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { MenuItem } from '@sveltia/ui';\n\n  import { installPrompt, promptAppInstall } from '$lib/services/app/install';\n</script>\n\n{#if installPrompt.current}\n  <MenuItem\n    label={_('install_as_app')}\n    onclick={async () => {\n      await promptAppInstall();\n    }}\n  />\n{/if}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Dialog, Table, TableCell, TableRow } from '@sveltia/ui';\n\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [open] Whether to open the dialog.\n   * @property {() => void} [onClose] Custom `close` event handler.\n   */\n\n  /** @type {Props} */\n  let { open = $bindable(false), onClose = undefined } = $props();\n\n  const shortcuts = [\n    { feature: 'view_content_library', keys: 'Alt+1' },\n    { feature: 'view_asset_library', keys: 'Alt+2' },\n    { feature: 'search', keys: 'Accel+F' },\n    { feature: 'create_entry', keys: 'Accel+E' },\n    { feature: 'save_entry', keys: 'Accel+S' },\n    { feature: 'cancel_editing', keys: 'Escape' },\n  ];\n</script>\n\n<Dialog\n  title={_('keyboard_shortcuts')}\n  size=\"small\"\n  bind:open\n  showOk={false}\n  showCancel={false}\n  showClose={true}\n  style=\"--sui-dialog-small-content-max-height:auto\"\n  onClose={() => {\n    onClose?.();\n  }}\n>\n  <div role=\"none\" class=\"wrapper\">\n    <Table ariaLabel={_('keyboard_shortcuts')}>\n      {#each shortcuts as { feature, keys } (keys)}\n        <TableRow>\n          <TableCell class=\"feature\">{_(`keyboard_shortcuts_.${feature}`)}</TableCell>\n          <TableCell class=\"keys\">\n            {#each keys.split('+') as key (key)}\n              <kbd>{key.replace('Accel', env.isMacOS ? '⌘' : 'Ctrl')}</kbd>\n            {/each}\n          </TableCell>\n        </TableRow>\n      {/each}\n    </Table>\n  </div>\n</Dialog>\n\n<style>\n  .wrapper {\n    display: contents;\n\n    :global {\n      .table-row {\n        display: flex;\n        align-items: center;\n        gap: 16px;\n        padding: 8px 0;\n        border-top: 1px solid var(--sui-secondary-border-color);\n\n        &:last-child {\n          border-bottom: 1px solid var(--sui-secondary-border-color);\n        }\n\n        .feature {\n          flex: auto;\n        }\n\n        .keys {\n          display: flex;\n          gap: 8px;\n        }\n      }\n    }\n  }\n\n  kbd {\n    display: inline-flex;\n    align-items: center;\n    justify-content: center;\n    box-sizing: border-box;\n    border-color: var(--sui-primary-accent-color);\n    border-radius: 4px;\n    padding: 0 8px;\n    height: 32px;\n    min-width: 32px;\n    background-color: var(--sui-tertiary-background-color);\n    font-family: var(--sui-control-font-family);\n    font-size: var(--sui-control-font-size);\n    line-height: var(--sui-control-line-height);\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { MenuItem } from '@sveltia/ui';\n\n  import ShortcutsDialog from '$lib/components/help/shortcuts-dialog.svelte';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {import('@sveltia/ui').MenuButton} [menuButton] Menu button.\n   */\n\n  /** @type {Props} */\n  let { menuButton } = $props();\n\n  let showDialog = $state(false);\n</script>\n\n<!-- Assume the user has a physical keyboard if the pointer is mouse (on desktop) -->\n{#if env.hasMouse}\n  <MenuItem\n    label={_('keyboard_shortcuts')}\n    onclick={() => {\n      showDialog = true;\n    }}\n  />\n{/if}\n\n<ShortcutsDialog\n  bind:open={showDialog}\n  onClose={() => {\n    menuButton?.focus();\n  }}\n/>\n","<script>\n  import { Switch } from '@sveltia/ui';\n\n  import { prefs } from '$lib/services/user/prefs.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {string} key Preference key.\n   * @property {string} label UI label on the switch.\n   * @property {boolean} [defaultValue] Default value.\n   */\n\n  /** @type {Props} */\n  let { key, label, defaultValue = true } = $props();\n\n  /**\n   * Preferences, cast to allow access by an arbitrary key.\n   */\n  const _prefs = /** @type {Record<string, any>} */ (prefs);\n</script>\n\n<Switch\n  bind:checked={\n    () => Boolean(_prefs[key] ?? defaultValue),\n    (value) => {\n      _prefs[key] = value;\n    }\n  }\n  {label}\n/>\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import PrefSwitch from '$lib/components/settings/controls/pref-switch.svelte';\n</script>\n\n<section>\n  <h3>\n    {_('prefs.accessibility.underline_links.title')}\n  </h3>\n  <p>\n    {_('prefs.accessibility.underline_links.description')}\n  </p>\n  <div role=\"none\">\n    <PrefSwitch\n      key=\"underlineLinks\"\n      label={_('prefs.accessibility.underline_links.switch_label')}\n    />\n  </div>\n</section>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { SecretInput } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import { isInvalidApiKey, isSharedApiKey, setApiKey } from '$lib/services/user/api-keys';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n\n  /**\n   * @import {\n   * AiService,\n   * MediaLibraryService,\n   * SettingsPanelOnChangeArgs,\n   * TranslationService,\n   * } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} serviceId The ID of the service for which the API key is being input.\n   * @property {AiService | MediaLibraryService | TranslationService} service The service for\n   * which the API key is being input.\n   * @property {string} [ariaLabel] Custom aria-label for the input.\n   * @property {(detail: SettingsPanelOnChangeArgs) => void} [onChange] `change` event handler.\n   */\n\n  /** @type {Props} */\n  let { serviceId, service, ariaLabel, onChange = undefined } = $props();\n\n  const { apiKeyPattern } = $derived(service);\n\n  let value = $state('');\n\n  /**\n   * Handler for `change` event of the text input.\n   */\n  const onchange = () => {\n    const apiKey = value.trim();\n    const invalid = isInvalidApiKey(apiKey, apiKeyPattern);\n\n    setApiKey(serviceId, invalid ? '' : apiKey);\n\n    onChange?.({\n      message: invalid\n        ? _('prefs.changes.api_key_invalid')\n        : apiKey\n          ? _('prefs.changes.api_key_saved')\n          : _('prefs.changes.api_key_removed'),\n      status: invalid ? 'error' : 'success',\n    });\n  };\n\n  onMount(() => {\n    value = prefs.apiKeys?.[serviceId] ?? '';\n  });\n</script>\n\n<!-- An admin’s key is used until the user enters their own, so say so rather than show it -->\n<SecretInput\n  bind:value\n  flex\n  autocomplete=\"off\"\n  spellcheck=\"false\"\n  placeholder={isSharedApiKey(serviceId) ? _('additions.provided_by_admin') : undefined}\n  {ariaLabel}\n  {onchange}\n/>\n","<script>\n  import ApiKeyInput from '$lib/components/settings/controls/api-key-input.svelte';\n  import { makeLink } from '$lib/services/utils/string';\n\n  /**\n   * @import {\n   * AiService,\n   * MediaLibraryService,\n   * SettingsPanelOnChangeArgs,\n   * TranslationService,\n   * } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} title Section heading.\n   * @property {string} description Description shown below the heading. Its `<a>` tag links to\n   * `docsURL`, if given.\n   * @property {string} [docsURL] URL of the relevant documentation.\n   * @property {[string, AiService | MediaLibraryService | TranslationService][]} entries\n   * Services listed in the section, as `[serviceId, service]` pairs.\n   * @property {(serviceLabel: string) => string} getFieldLabel Function to get the accessible label\n   * of the API key input for the given service label.\n   * @property {(detail: SettingsPanelOnChangeArgs) => void} [onChange] `change` event handler.\n   */\n\n  /** @type {Props} */\n  let {\n    title,\n    description,\n    docsURL = undefined,\n    entries,\n    getFieldLabel,\n    onChange = undefined,\n  } = $props();\n</script>\n\n<section>\n  <h3>{title}</h3>\n  <p>\n    {#if docsURL}\n      {@html makeLink(description, docsURL)}\n    {:else}\n      {description}\n    {/if}\n  </p>\n  {#each entries as [serviceId, service] (serviceId)}\n    {@const label = service.serviceLabel}\n    <section>\n      <h4>{label}</h4>\n      <div role=\"none\">\n        <ApiKeyInput {serviceId} {service} ariaLabel={getFieldLabel(label)} {onChange} />\n      </div>\n    </section>\n  {/each}\n</section>\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import ApiKeySection from '$lib/components/settings/controls/api-key-section.svelte';\n  import { allAiServices } from '$lib/services/integrations/ai';\n\n  /**\n   * @import { SettingsPanelOnChangeArgs } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {(detail: SettingsPanelOnChangeArgs) => void} [onChange] `change` event handler.\n   */\n\n  /** @type {Props} */\n  let { onChange = undefined } = $props();\n</script>\n\n<ApiKeySection\n  title={_('prefs.ai.api_keys.title')}\n  description={_('prefs.ai.api_keys.description')}\n  entries={Object.entries(allAiServices)}\n  getFieldLabel={(service) => _('prefs.ai.field_label', { values: { service } })}\n  {onChange}\n/>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { SelectButton, SelectButtonGroup } from '@sveltia/ui';\n\n  import { AUTO_PREF_VALUE, prefs } from '$lib/services/user/prefs.svelte';\n</script>\n\n<section>\n  <h3>{_('prefs.appearance.theme')}</h3>\n  <div role=\"none\">\n    <SelectButtonGroup\n      ariaLabel={_('prefs.appearance.select_theme')}\n      onChange={(event) => {\n        prefs.theme = event.detail.value;\n      }}\n    >\n      {#each [AUTO_PREF_VALUE, 'dark', 'light'] as value (value)}\n        <SelectButton\n          variant=\"tertiary\"\n          label={value === AUTO_PREF_VALUE ? _('automatic') : _(`prefs.theme.${value}`)}\n          {value}\n          selected={(!prefs.theme && value === AUTO_PREF_VALUE) || prefs.theme === value}\n        />\n      {/each}\n    </SelectButtonGroup>\n  </div>\n</section>\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import PrefSwitch from '$lib/components/settings/controls/pref-switch.svelte';\n</script>\n\n<section>\n  <h3>{_('prefs.contents.editor.title')}</h3>\n  <div role=\"none\">\n    <PrefSwitch\n      key=\"useDraftBackup\"\n      label={_('prefs.contents.editor.use_draft_backup.switch_label')}\n    />\n  </div>\n  <div role=\"none\">\n    <PrefSwitch key=\"closeOnSave\" label={_('prefs.contents.editor.close_on_save.switch_label')} />\n  </div>\n  <div role=\"none\">\n    <PrefSwitch\n      key=\"closeWithEscape\"\n      label={_('prefs.contents.editor.close_with_escape.switch_label')}\n    />\n  </div>\n</section>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, ConfirmationDialog } from '@sveltia/ui';\n\n  import { clearFileCache, eraseAllData } from '$lib/services/app/cache';\n\n  let showClearCacheDialog = $state(false);\n  let showEraseDataDialog = $state(false);\n\n  /* v8 ignore start -- reloading the page would tear the test down */\n  /**\n   * Clear the file cache, then reload the page to start over.\n   */\n  const clearCache = async () => {\n    await clearFileCache();\n    window.location.reload();\n  };\n\n  /**\n   * Erase all the data stored in the browser, then reload the page to start over.\n   */\n  const eraseData = async () => {\n    await eraseAllData();\n    window.location.reload();\n  };\n  /* v8 ignore stop */\n</script>\n\n<section>\n  <h3>\n    {_('prefs.data.clear_data.title')}\n  </h3>\n  <p>\n    {_('prefs.data.clear_data.file_cache.description')}\n  </p>\n  <div role=\"none\">\n    <Button\n      variant=\"tertiary\"\n      label={_('prefs.data.clear_data.file_cache.button_label')}\n      onclick={() => {\n        showClearCacheDialog = true;\n      }}\n    />\n  </div>\n  <p>\n    {_('prefs.data.clear_data.all_data.description')}\n  </p>\n  <div role=\"none\">\n    <Button\n      variant=\"tertiary\"\n      label={_('prefs.data.clear_data.all_data.button_label')}\n      onclick={() => {\n        showEraseDataDialog = true;\n      }}\n    />\n  </div>\n</section>\n\n<ConfirmationDialog\n  bind:open={showClearCacheDialog}\n  title={_('prefs.data.clear_data.file_cache.button_label')}\n  okLabel={_('prefs.data.clear_data.file_cache.button_label')}\n  onOk={clearCache}\n>\n  {_('prefs.data.clear_data.file_cache.confirmation')}\n</ConfirmationDialog>\n\n<ConfirmationDialog\n  bind:open={showEraseDataDialog}\n  title={_('prefs.data.clear_data.all_data.button_label')}\n  okLabel={_('prefs.data.clear_data.all_data.button_label')}\n  onOk={eraseData}\n>\n  {_('prefs.data.clear_data.all_data.confirmation')}\n</ConfirmationDialog>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, TextInput } from '@sveltia/ui';\n\n  import PrefSwitch from '$lib/components/settings/controls/pref-switch.svelte';\n  import { backendName } from '$lib/services/backends';\n  import { getLocalGitStatusLabel } from '$lib/services/backends/fs/git/messages';\n  import { checkLocalGitStatus } from '$lib/services/backends/fs/local';\n  import { skipCIConfigured } from '$lib/services/backends/git/shared/integration';\n  import { getDeployHook, isSharedDeployHook } from '$lib/services/user/api-keys';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n\n  /**\n   * @import { LocalGitStatus, SettingsPanelOnChangeArgs } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {(detail: SettingsPanelOnChangeArgs) => void} [onChange] `change` event handler.\n   */\n\n  /** @type {Props} */\n  let { onChange = undefined } = $props();\n\n  /**\n   * Check whether the saved changes can be committed to the local Git repository. The Settings are\n   * only shown once the user has signed in, so the status is always known.\n   * @returns {Promise<LocalGitStatus>} Status.\n   */\n  const getLocalGitStatus = async () => /** @type {LocalGitStatus} */ (await checkLocalGitStatus());\n\n  // An admin’s hook is used until the user enters their own, with its header, if it has one\n  const deployHookShared = $derived(isSharedDeployHook());\n  const deployHookAuthShared = $derived(deployHookShared && !!getDeployHook()?.authHeader);\n</script>\n\n{#snippet deployHookInput(\n  /** @type {'deployHookURL' | 'deployHookAuthHeader'} */ prop,\n  /** @type {string} */ ariaLabel,\n  /** @type {string} */ savedMessage,\n  /** @type {string} */ removedMessage,\n  /** @type {boolean} */ shared,\n)}\n  <div role=\"none\">\n    <TextInput\n      dir=\"ltr\"\n      bind:value={prefs[prop]}\n      flex\n      {ariaLabel}\n      showInlineLabel={true}\n      placeholder={shared ? _('additions.provided_by_admin') : undefined}\n      onchange={() => {\n        onChange?.({ message: prefs[prop] ? savedMessage : removedMessage });\n      }}\n    />\n  </div>\n{/snippet}\n\n<section>\n  <h3>\n    {_('prefs.developer.developer_mode.title')}\n  </h3>\n  <p>\n    {_('prefs.developer.developer_mode.description')}\n  </p>\n  <div role=\"none\">\n    <PrefSwitch\n      key=\"devModeEnabled\"\n      label={_('prefs.developer.developer_mode.switch_label')}\n      defaultValue={false}\n    />\n  </div>\n</section>\n{#if backendName.current === 'local'}\n  <section>\n    <h3>\n      {_('prefs.developer.local_git.title')}\n    </h3>\n    <p>\n      {_('prefs.developer.local_git.description')}\n    </p>\n    <div role=\"none\">\n      <PrefSwitch\n        key=\"localGitCommits\"\n        label={_('prefs.developer.local_git.switch_label')}\n        defaultValue={false}\n      />\n    </div>\n    {#if prefs.localGitCommits}\n      <div role=\"none\">\n        {#await getLocalGitStatus()}\n          <p>{_('prefs.developer.local_git.checking')}</p>\n        {:then status}\n          <Alert status={status.ready ? 'success' : 'warning'}>\n            {getLocalGitStatusLabel(status)}\n          </Alert>\n        {/await}\n      </div>\n    {/if}\n  </section>\n{/if}\n{#if skipCIConfigured.current}\n  <section>\n    <h3>\n      {_('prefs.developer.deploy_hook.title')}\n    </h3>\n    <p>\n      {_('prefs.developer.deploy_hook.description')}\n    </p>\n    {@render deployHookInput(\n      'deployHookURL',\n      _('prefs.developer.deploy_hook.url.field_label'),\n      _('prefs.developer.deploy_hook.url.saved'),\n      _('prefs.developer.deploy_hook.url.removed'),\n      deployHookShared,\n    )}\n    {@render deployHookInput(\n      'deployHookAuthHeader',\n      _('prefs.developer.deploy_hook.auth.field_label'),\n      _('prefs.developer.deploy_hook.auth.saved'),\n      _('prefs.developer.deploy_hook.auth.removed'),\n      deployHookAuthShared,\n    )}\n  </section>\n{/if}\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import ApiKeySection from '$lib/components/settings/controls/api-key-section.svelte';\n  import TranslatorSelector from '$lib/components/settings/controls/translator-selector.svelte';\n  import { DOCS_BASE_URL } from '$lib/services/app';\n  import { machineTranslationServices } from '$lib/services/integrations/translators';\n\n  /**\n   * @import { SettingsPanelOnChangeArgs } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {(detail: SettingsPanelOnChangeArgs) => void} [onChange] `change` event handler.\n   */\n\n  /** @type {Props} */\n  let { onChange = undefined } = $props();\n</script>\n\n<section>\n  <h3>{_('prefs.i18n.translators.default.title')}</h3>\n  <div role=\"none\">\n    <TranslatorSelector />\n  </div>\n</section>\n\n<ApiKeySection\n  title={_('prefs.i18n.translators.api_keys.title')}\n  description={_('prefs.i18n.translators.api_keys.description')}\n  docsURL=\"{DOCS_BASE_URL}/integrations/translations\"\n  entries={Object.entries(machineTranslationServices)}\n  getFieldLabel={(service) => _('prefs.i18n.translators.field_label', { values: { service } })}\n  {onChange}\n/>\n","<script>\n  import { _, locale as appLocale, locales as appLocales } from '@sveltia/i18n';\n  import { Alert, Divider, Option, Select, Toast } from '@sveltia/ui';\n\n  import { appLocaleLoading } from '$lib/services/app/i18n';\n  import { setState } from '$lib/services/app/onboarding';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n  import { AUTO_PREF_VALUE, prefs } from '$lib/services/user/prefs.svelte';\n\n  /**\n   * Locale list sorted by label.\n   */\n  const locales = $derived(\n    appLocales\n      .map((code) => {\n        /* v8 ignore start -- every supported locale has a label */\n        const localizedLabel = getLocaleLabel(code, { displayLocale: appLocale.current }) ?? code;\n        const nativeLabel = getLocaleLabel(code, { displayLocale: code }) ?? code;\n        /* v8 ignore stop */\n\n        const label =\n          localizedLabel === nativeLabel ? localizedLabel : `${localizedLabel} — ${nativeLabel}`;\n\n        return {\n          value: code,\n          searchValue: `${label} (${code})`,\n          label,\n        };\n      })\n      .sort((a, b) => a.label.localeCompare(b.label)),\n  );\n\n  /**\n   * Selected language preference, which is {@link AUTO_PREF_VALUE} rather than a locale code while\n   * the UI follows the browser’s language settings.\n   */\n  const selectedLocale = $derived(prefs.locale ?? AUTO_PREF_VALUE);\n\n  /**\n   * Locale being switched to. Unlike `appLocaleLoading.current`, this keeps the last value, so the\n   * message doesn’t disappear while the toast is fading out.\n   */\n  let switchingLocale = $state('');\n  const switchingLocaleLabel = $derived(getLocaleLabel(switchingLocale) ?? switchingLocale);\n\n  $effect(() => {\n    if (appLocaleLoading.current) {\n      switchingLocale = appLocaleLoading.current;\n    }\n  });\n</script>\n\n<section>\n  <h3>{_('prefs.language.ui_language.title')}</h3>\n  <div role=\"none\">\n    {#key appLocale.current}\n      <Select\n        ariaLabel={_('prefs.language.ui_language.select_language')}\n        value={selectedLocale}\n        onChange={(event) => {\n          prefs.locale = event.detail.value;\n          // Suppress the new language infobar, which is pointless once the user has explicitly\n          // picked a language here\n          setState('newLanguageCta', true);\n        }}\n      >\n        <Option\n          value={AUTO_PREF_VALUE}\n          label={_('automatic')}\n          selected={selectedLocale === AUTO_PREF_VALUE}\n        />\n        <Divider />\n        {#each locales as { value, searchValue, label } (value)}\n          <Option {value} {searchValue} {label} selected={value === selectedLocale} />\n        {/each}\n      </Select>\n    {/key}\n  </div>\n</section>\n\n<!-- Hidden automatically once the strings are loaded, hence `duration={0}` -->\n<Toast show={!!appLocaleLoading.current} duration={0}>\n  <Alert status=\"info\">\n    {#if switchingLocaleLabel}\n      {_('switching_language', { values: { locale: switchingLocaleLabel } })}\n    {/if}\n  </Alert>\n</Toast>\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import ApiKeySection from '$lib/components/settings/controls/api-key-section.svelte';\n  import { DOCS_BASE_URL } from '$lib/services/app';\n  import {\n    getCloudStorageServiceEntries,\n    getStockPhotoServiceEntries,\n  } from '$lib/services/integrations/api-key-services';\n\n  /**\n   * @import { SettingsPanelOnChangeArgs } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {(detail: SettingsPanelOnChangeArgs) => void} [onChange] `change` event handler.\n   */\n\n  /** @type {Props} */\n  let { onChange = undefined } = $props();\n\n  const enabledStockAssetProviderEntries = $derived(getStockPhotoServiceEntries());\n  const enabledCloudServiceEntries = $derived(getCloudStorageServiceEntries());\n</script>\n\n<ApiKeySection\n  title={_('prefs.media.cloud_storage.api_keys.title')}\n  description={enabledCloudServiceEntries.length\n    ? _('prefs.media.cloud_storage.api_keys.description')\n    : _('prefs.media.cloud_storage.no_services')}\n  docsURL=\"{DOCS_BASE_URL}/media\"\n  entries={enabledCloudServiceEntries}\n  getFieldLabel={(service) => _('prefs.media.cloud_storage.field_label', { values: { service } })}\n  {onChange}\n/>\n<ApiKeySection\n  title={_('prefs.media.stock_photos.api_keys.title')}\n  description={enabledStockAssetProviderEntries.length\n    ? _('prefs.media.stock_photos.api_keys.description')\n    : _('prefs.media.stock_photos.no_services')}\n  docsURL=\"{DOCS_BASE_URL}/integrations/stock-photos\"\n  entries={enabledStockAssetProviderEntries}\n  getFieldLabel={(service) => _('prefs.media.stock_photos.field_label', { values: { service } })}\n  {onChange}\n/>\n","import AccessibilityPanel from '$lib/components/settings/panels/accessibility-panel.svelte';\nimport AiPanel from '$lib/components/settings/panels/ai-panel.svelte';\nimport AppearancePanel from '$lib/components/settings/panels/appearance-panel.svelte';\nimport ContentsPanel from '$lib/components/settings/panels/contents-panel.svelte';\nimport DataPanel from '$lib/components/settings/panels/data-panel.svelte';\nimport DeveloperPanel from '$lib/components/settings/panels/developer-panel.svelte';\nimport I18nPanel from '$lib/components/settings/panels/i18n-panel.svelte';\nimport LanguagePanel from '$lib/components/settings/panels/language-panel.svelte';\nimport MediaPanel from '$lib/components/settings/panels/media-panel.svelte';\nimport { getAdditions } from '$lib/services/app/additions';\nimport { backendName } from '$lib/services/backends';\nimport { cmsConfig } from '$lib/services/config';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Component } from 'svelte';\n */\n\n/**\n * Settings panels available with the current configuration. The settings dialog and page both list\n * these, so a panel left out, like Internationalization for a monolingual site, can’t be reached\n * through either of them, not even by URL. The Account panel comes with Sveltia CMS Additions,\n * whose chunk holds it, for a user signed in to it rather than working with a local repository.\n * @type {{ readonly current: { key: string, icon: string, component: Component }[] }}\n */\nexport const panels = createDerivedState(() => {\n  const additions = getAdditions();\n\n  return [\n    ...(additions && backendName.current !== 'local'\n      ? [{ key: 'account', icon: 'account_circle', component: additions.AccountPanel }]\n      : []),\n    { key: 'appearance', icon: 'palette', component: AppearancePanel },\n    { key: 'language', icon: 'language', component: LanguagePanel },\n    { key: 'contents', icon: 'library_books', component: ContentsPanel },\n    ...((cmsConfig.current?.i18n?.locales?.length ?? 0) > 1\n      ? [{ key: 'i18n', icon: 'translate', component: I18nPanel }]\n      : []),\n    { key: 'media', icon: 'photo_library', component: MediaPanel },\n    { key: 'ai', icon: 'auto_awesome', component: AiPanel },\n    { key: 'accessibility', icon: 'accessibility_new', component: AccessibilityPanel },\n    { key: 'developer', icon: 'code_xml', component: DeveloperPanel },\n    { key: 'data', icon: 'database', component: DataPanel },\n  ];\n});\n","<script>\n  import { Alert, Toast } from '@sveltia/ui';\n\n  /**\n   * @import { Component } from 'svelte';\n   * @import { SettingsPanelOnChangeArgs } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Component} [Panel] Panel component.\n   */\n\n  /** @type {Props} */\n  let { Panel } = $props();\n\n  let toastMessage = $state('');\n  /** @type {'success' | 'error'} */\n  let toastStatus = $state('success');\n  let showToast = $state(false);\n</script>\n\n<div class=\"container\" role=\"none\">\n  <Panel\n    onChange={(/** @type {SettingsPanelOnChangeArgs} */ { message, status }) => {\n      toastMessage = message;\n      toastStatus = status ?? 'success';\n      showToast = true;\n    }}\n  />\n</div>\n\n<Toast bind:show={showToast}>\n  <Alert status={toastStatus}>{toastMessage}</Alert>\n</Toast>\n\n<style>\n  .container {\n    display: contents;\n\n    :global {\n      section:not(:first-child) {\n        margin: 16px 0 0;\n      }\n\n      p {\n        margin-top: 0;\n      }\n\n      h3 {\n        font-size: inherit;\n\n        & ~ div {\n          margin: 8px 0 0;\n        }\n\n        & ~ p {\n          margin: 8px 0 0;\n          color: var(--sui-secondary-foreground-color);\n          font-size: var(--sui-font-size-small);\n        }\n      }\n\n      h4 {\n        margin-bottom: 4px;\n        font-size: var(--sui-font-size-small);\n      }\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Dialog, Icon, Tab, TabList, TabPanel } from '@sveltia/ui';\n\n  import { panels } from '$lib/components/settings';\n  import PanelContainer from '$lib/components/settings/panel-container.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [open] Whether to open the dialog.\n   * @property {(() => void) | undefined} [onClose] Custom `close` event handler.\n   */\n\n  /** @type {Props} */\n  let { open = $bindable(false), onClose = undefined } = $props();\n\n  /** @type {string | undefined} */\n  let selectedPanel = $state();\n\n  // The first panel until another is selected: Account when it’s there, otherwise Appearance. Also\n  // the first one when the selected panel is no longer offered\n  const currentPanel = $derived(\n    panels.current.some(({ key }) => key === selectedPanel)\n      ? /** @type {string} */ (selectedPanel)\n      : panels.current[0].key,\n  );\n</script>\n\n<Dialog\n  title={_('settings')}\n  size=\"large\"\n  bind:open\n  showOk={false}\n  showCancel={false}\n  showClose={true}\n  onClose={() => {\n    onClose?.();\n  }}\n>\n  <div role=\"none\" class=\"wrapper\">\n    <TabList orientation=\"vertical\" ariaLabel={_('categories')}>\n      {#each panels.current as { key, icon } (key)}\n        <Tab\n          label={_(`prefs.${key}.title`)}\n          selected={key === currentPanel}\n          aria-controls=\"prefs-tab-{key}\"\n          onSelect={() => {\n            selectedPanel = key;\n          }}\n        >\n          {#snippet startIcon()}\n            <Icon name={icon} />\n          {/snippet}\n        </Tab>\n      {/each}\n    </TabList>\n    {#each panels.current as { key, component } (key)}\n      <TabPanel id=\"prefs-tab-{key}\">\n        <PanelContainer Panel={component} />\n      </TabPanel>\n    {/each}\n  </div>\n</Dialog>\n\n<style>\n  .wrapper {\n    display: flex;\n\n    :global {\n      .sui.tab-list {\n        flex: none;\n      }\n\n      .sui.tab-panel {\n        flex: auto;\n        border-width: 0;\n      }\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { AlertDialog, Divider, Menu, MenuItem } from '@sveltia/ui';\n\n  import AppInstallMenuItem from '$lib/components/global/toolbar/items/app-install-menu-item.svelte';\n  import ShortcutsMenuItem from '$lib/components/help/shortcuts-menu-item.svelte';\n  import SettingsDialog from '$lib/components/settings/settings-dialog.svelte';\n  import { getAdditions } from '$lib/services/app/additions';\n  import { goto, openProductionSite } from '$lib/services/app/navigation';\n  import { canShowMobileSignInDialog, showMobileSignInDialog } from '$lib/services/app/onboarding';\n  import { backend, backendName } from '$lib/services/backends';\n  import { isDemoSite } from '$lib/services/backends/fs/seed';\n  import { user } from '$lib/services/user/account.svelte';\n  import { signOut } from '$lib/services/user/auth.svelte';\n  import { env } from '$lib/services/user/env.svelte';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @typedef {object} Props\n   * @property {import('@sveltia/ui').MenuButton} [menuButton] Menu button.\n   */\n\n  /** @type {Props} */\n  let { menuButton } = $props();\n\n  let showPrefsDialog = $state(false);\n  /** Why linking a GitHub account failed, if it did. */\n  let linkError = $state('');\n\n  /** Sveltia CMS Additions, whose chunk is loaded along with the backend if it’s enabled. */\n  const additions = $derived(getAdditions());\n  const isLocalRepo = $derived(backendName.current === 'local');\n  const isTestRepo = $derived(backendName.current === 'test-repo');\n  const isDemo = $derived(isDemoSite(backendName.current));\n</script>\n\n<Menu ariaLabel={_('account')}>\n  <MenuItem\n    label={isLocalRepo\n      ? _('working_with_local_repo')\n      : isDemo\n        ? _('working_in_demo_mode')\n        : isTestRepo\n          ? _('working_with_test_repo')\n          : user.account?.role\n            ? _('additions.signed_in_as_x_with_role', {\n                values: {\n                  name: user.account.login,\n                  role: _(`additions.users.roles.${user.account.role}`),\n                },\n              })\n            : _('signed_in_as_x', { values: { name: user.account?.login } })}\n    disabled={isLocalRepo || isTestRepo}\n    onclick={() => {\n      openNewTab(user.account?.profileURL);\n    }}\n  />\n  <Divider />\n  <MenuItem\n    label={_('live_site')}\n    onclick={() => {\n      openProductionSite();\n    }}\n  />\n  {#if prefs.devModeEnabled}\n    <MenuItem\n      label={_('git_repository')}\n      disabled={!backend.current?.repository?.treeBaseURL}\n      onclick={() => {\n        openNewTab(backend.current?.repository?.treeBaseURL);\n      }}\n    />\n  {/if}\n  <Divider />\n  <!--\n    A local repository can be used without signing in to Sveltia CMS Additions. The password is\n    changed in the Account settings panel\n  -->\n  {#if additions && !isLocalRepo}\n    <!-- Someone with their own GitHub token is the author of their commits -->\n    {#if additions.additionsAuth.signInMethods.includes('github') && !user.account?.ownGitHubToken}\n      <MenuItem\n        label={_('additions.link_github')}\n        onclick={async () => {\n          try {\n            await additions.linkGitHubAccount();\n          } catch (/** @type {any} */ ex) {\n            linkError = ex.cause?.message ?? ex.message;\n          }\n        }}\n      />\n    {/if}\n  {/if}\n  <MenuItem\n    label={_('settings')}\n    onclick={() => {\n      if (env.isSmallScreen) {\n        goto('/settings', { transitionType: 'forwards' });\n      } else {\n        showPrefsDialog = true;\n      }\n    }}\n  />\n  <!-- When dev mode is enabled, the shortcuts menu item appears in the Help menu -->\n  {#if !prefs.devModeEnabled}\n    <ShortcutsMenuItem {menuButton} />\n  {/if}\n  {#if canShowMobileSignInDialog.current}\n    <MenuItem\n      label={_('sign_in_with_mobile')}\n      onclick={() => {\n        showMobileSignInDialog.current = true;\n      }}\n    />\n  {/if}\n  <AppInstallMenuItem />\n  <Divider />\n  <MenuItem\n    label={_('sign_out')}\n    onclick={async () => {\n      // Wait a bit before the menu is closed\n      window.requestAnimationFrame(() => {\n        signOut();\n      });\n    }}\n  />\n</Menu>\n\n<AlertDialog\n  open={!!linkError}\n  title={_('additions.link_github_error')}\n  onClose={() => {\n    linkError = '';\n  }}\n>\n  {linkError}\n</AlertDialog>\n\n<SettingsDialog\n  bind:open={showPrefsDialog}\n  onClose={() => {\n    menuButton?.focus();\n  }}\n/>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, MenuButton } from '@sveltia/ui';\n\n  import AccountMenu from '$lib/components/global/toolbar/items/account-menu.svelte';\n  import { backendName } from '$lib/services/backends';\n  import { user } from '$lib/services/user/account.svelte';\n\n  /** @type {MenuButton | undefined} */\n  let menuButton = $state();\n\n  const isLocalRepo = $derived(backendName.current === 'local');\n  const hasAvatar = $derived(!!user.account?.avatarURL);\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <MenuButton\n    variant=\"ghost\"\n    iconic={!isLocalRepo}\n    label={isLocalRepo ? _('local_workflow.indicator') : undefined}\n    class={hasAvatar ? 'avatar' : ''}\n    popupPosition=\"bottom-right\"\n    tooltip={_('account')}\n    aria-label={_('show_account_menu')}\n    bind:this={menuButton}\n  >\n    {#snippet endIcon()}\n      {#if isLocalRepo}\n        <Icon name=\"arrow_drop_down\" class=\"small-arrow\" />\n      {:else if hasAvatar}\n        <img class=\"avatar\" loading=\"lazy\" src={user.account?.avatarURL} alt=\"\" />\n      {:else}\n        <Icon name=\"account_circle\" />\n      {/if}\n    {/snippet}\n    {#snippet popup()}\n      <AccountMenu {menuButton} />\n    {/snippet}\n  </MenuButton>\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n\n    :global {\n      button.avatar {\n        border-width: 0;\n        background-color: transparent;\n      }\n    }\n  }\n\n  .avatar {\n    width: 32px;\n    height: 32px;\n    border-radius: 32px;\n    object-fit: cover;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Icon, Menu, MenuButton, MenuItem } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n\n  import { goto } from '$lib/services/app/navigation';\n  import { assetsLocked, canCreateAsset, globalAssetFolder } from '$lib/services/assets/folders';\n  import { showUploadAssetsDialog } from '$lib/services/assets/view';\n  import { isReadonly } from '$lib/services/config/readonly';\n  import { getValidCollections } from '$lib/services/contents/collection';\n  import { countQuotaEntries } from '$lib/services/contents/collection/entries/count';\n\n  /**\n   * @import { EntryCollection } from '$lib/types/public';\n   */\n\n  const entryCollections = $derived(\n    /** @type {EntryCollection[]} */ (getValidCollections({ visible: true, type: 'entry' })),\n  );\n  // An entry can’t be created where the collection says so, is read-only or has reached its limit,\n  // which the entries only existing in a pull request count toward as well\n  const collectionItems = $derived(\n    entryCollections.map((collection) => {\n      const {\n        name,\n        label,\n        label_singular: labelSingular,\n        create = true,\n        limit = Infinity,\n      } = collection;\n\n      return {\n        name,\n        label: labelSingular || label || name,\n        disabled:\n          !create ||\n          isReadonly({ collection }) ||\n          (limit < Infinity && countQuotaEntries(name) >= limit),\n      };\n    }),\n  );\n  // The assets are uploaded to the global media folder, which is read-only along with the whole\n  // CMS, and missing when only a cloud media library is configured. Uploading commits straight to\n  // the configured branch, so an Open Authoring contributor or a user who can’t push to the branch\n  // can’t do it either\n  const assetsDisabled = $derived(\n    assetsLocked.current || isReadonly() || !canCreateAsset(globalAssetFolder.current),\n  );\n  // A menu with nothing to choose from isn’t worth opening, e.g. while the whole CMS is read-only\n  const allDisabled = $derived(assetsDisabled && collectionItems.every(({ disabled }) => disabled));\n</script>\n\n<MenuButton\n  variant=\"ghost\"\n  iconic\n  disabled={allDisabled}\n  popupPosition=\"bottom-right\"\n  tooltip={_('create_entry_or_assets')}\n  aria-label={_('create_entry_or_assets')}\n>\n  {#snippet endIcon()}\n    <Icon name=\"add\" />\n  {/snippet}\n  {#snippet popup()}\n    <Menu ariaLabel={_('create_entry_or_assets')}>\n      {#if collectionItems.length}\n        {#each collectionItems as { name, label, disabled } (name)}\n          <MenuItem\n            {label}\n            {disabled}\n            onclick={() => {\n              goto(`/collections/${name}/new`, { transitionType: 'forwards' });\n            }}\n          />\n        {/each}\n        <Divider />\n      {/if}\n      <MenuItem\n        label={_('assets')}\n        disabled={assetsDisabled}\n        onclick={async () => {\n          goto('/assets', { transitionType: 'forwards' });\n          await sleep(100);\n          showUploadAssetsDialog.current = true;\n        }}\n      />\n    </Menu>\n  {/snippet}\n</MenuButton>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { MenuItem } from '@sveltia/ui';\n\n  import { REPOSITORY_URL, version } from '$lib/services/app';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import { openNewTab } from '$lib/services/utils/window';\n</script>\n\n<MenuItem\n  label={_('release_notes')}\n  onclick={() => {\n    openNewTab(`${REPOSITORY_URL}/releases`);\n  }}\n>\n  {#snippet endIcon()}\n    {#if prefs.devModeEnabled}\n      <span class=\"version\" aria-label=\"({_('version_x', { values: { version } })})\">\n        v{version}\n      </span>\n    {/if}\n  {/snippet}\n</MenuItem>\n\n<style>\n  .version {\n    border-radius: 4px;\n    padding: 0 6px;\n    color: var(--sui-secondary-foreground-color);\n    background-color: var(--sui-selected-background-color);\n    font-size: var(--sui-font-size-small);\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Menu, MenuItem } from '@sveltia/ui';\n\n  import ReleaseNotesMenuItem from '$lib/components/help/release-notes-menu-item.svelte';\n  import ShortcutsMenuItem from '$lib/components/help/shortcuts-menu-item.svelte';\n  import { DOCS_BASE_URL, REPOSITORY_URL } from '$lib/services/app';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @typedef {object} Props\n   * @property {import('@sveltia/ui').MenuButton} [menuButton] Menu button.\n   */\n\n  /** @type {Props} */\n  let { menuButton } = $props();\n</script>\n\n{#snippet link(/** @type {string} */ labelKey, /** @type {string} */ url)}\n  <MenuItem\n    label={_(labelKey)}\n    onclick={() => {\n      openNewTab(url);\n    }}\n  />\n{/snippet}\n\n<Menu ariaLabel={_('help')}>\n  <ShortcutsMenuItem {menuButton} />\n  {#if prefs.devModeEnabled}\n    {@render link('documentation', DOCS_BASE_URL)}\n    <ReleaseNotesMenuItem />\n    {@render link('announcements', `${REPOSITORY_URL}/discussions/categories/announcements`)}\n    <Divider />\n    {@render link('report_issue', `${REPOSITORY_URL}/issues`)}\n    {@render link('share_feedback', `${REPOSITORY_URL}/discussions/categories/ideas`)}\n    {@render link('get_help', `${REPOSITORY_URL}/discussions/categories/q-a`)}\n    {@render link('donate', 'https://github.com/sponsors/kyoshino')}\n    <Divider />\n    {@render link('bluesky', 'https://bsky.app/profile/sveltiacms.app')}\n    {@render link('join_discord', 'https://discord.com/invite/5hwCGqup5b')}\n  {/if}\n</Menu>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, MenuButton } from '@sveltia/ui';\n\n  import HelpMenu from '$lib/components/global/toolbar/items/help-menu.svelte';\n\n  /** @type {MenuButton | undefined} */\n  let menuButton = $state();\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <MenuButton\n    variant=\"ghost\"\n    iconic\n    popupPosition=\"bottom-right\"\n    tooltip={_('help')}\n    aria-label={_('show_help_menu')}\n    bind:this={menuButton}\n  >\n    {#snippet endIcon()}\n      <Icon name=\"help\" />\n    {/snippet}\n    {#snippet popup()}\n      <HelpMenu {menuButton} />\n    {/snippet}\n  </MenuButton>\n</div>\n\n<style>\n  .wrapper {\n    display: contents;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon } from '@sveltia/ui';\n</script>\n\n<Button\n  variant=\"ghost\"\n  iconic\n  hidden\n  aria-label={_('show_notifications')}\n  onclick={() => {\n    // @todo Implement this!\n  }}\n>\n  {#snippet startIcon()}\n    <Icon name=\"notifications\" />\n  {/snippet}\n</Button>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button } from '@sveltia/ui';\n\n  import { appLogoURL, DEFAULT_APP_LOGO_URL } from '$lib/services/app/branding';\n  import { openProductionSite } from '$lib/services/app/navigation';\n  import { cmsConfig } from '$lib/services/config';\n\n  const showInHeader = $derived(\n    appLogoURL.current !== DEFAULT_APP_LOGO_URL &&\n      (cmsConfig.current?.logo?.show_in_header ?? true),\n  );\n</script>\n\n{#if showInHeader}\n  <Button\n    variant=\"ghost\"\n    iconic\n    tooltip={_('visit_live_site')}\n    aria-label={_('visit_live_site')}\n    onclick={() => {\n      openProductionSite();\n    }}\n  >\n    <img src={appLogoURL.current} alt=\"\" class=\"logo\" />\n  </Button>\n{/if}\n\n<style>\n  img {\n    width: 24px;\n    height: 24px;\n    object-fit: contain;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Toolbar } from '@sveltia/ui';\n\n  import AccountButton from '$lib/components/global/toolbar/items/account-button.svelte';\n  import CreateButton from '$lib/components/global/toolbar/items/create-button.svelte';\n  import HelpButton from '$lib/components/global/toolbar/items/help-button.svelte';\n  import NotificationsButton from '$lib/components/global/toolbar/items/notifications-button.svelte';\n  import PageSwitcher from '$lib/components/global/toolbar/items/page-switcher.svelte';\n  import PublishButton from '$lib/components/global/toolbar/items/publish-button.svelte';\n  import QuickSearchBar from '$lib/components/global/toolbar/items/quick-search-bar.svelte';\n  import SiteLogo from '$lib/components/global/toolbar/items/site-logo.svelte';\n  import { hasOverlay } from '$lib/services/app/navigation';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n</script>\n\n<div role=\"none\" class=\"toolbar-wrapper\" inert={hasOverlay.current}>\n  <Toolbar variant=\"primary\" ariaLabel={_('global')}>\n    <div role=\"none\" class=\"buttons\">\n      <SiteLogo />\n      <PageSwitcher />\n    </div>\n    <QuickSearchBar />\n    <div role=\"none\" class=\"buttons\">\n      <PublishButton />\n      <CreateButton />\n      <NotificationsButton />\n      {#if prefs.devModeEnabled}\n        <HelpButton />\n      {/if}\n      <AccountButton />\n    </div>\n  </Toolbar>\n</div>\n\n<style>\n  .toolbar-wrapper {\n    display: contents;\n\n    &[inert] {\n      :global {\n        .sui.search-bar {\n          /* Disable the keyboard shortcut for the search bar */\n          display: none !important;\n        }\n      }\n    }\n\n    :global {\n      & > .sui.toolbar {\n        @media (width < 768px) {\n          padding: 0 4px;\n        }\n\n        .buttons {\n          flex: auto;\n          display: flex;\n          align-items: center;\n          width: 50%;\n\n          &:last-child {\n            justify-content: flex-end;\n          }\n        }\n\n        .sui.search-bar {\n          flex: none;\n          width: 640px;\n          max-width: 50%;\n\n          @media (width < 768px) {\n            flex: auto;\n            width: -moz-available;\n            width: -webkit-fill-available;\n            width: stretch;\n            max-width: none;\n          }\n        }\n      }\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, Menu, MenuItem, Spacer, Toolbar } from '@sveltia/ui';\n\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import AccountMenu from '$lib/components/global/toolbar/items/account-menu.svelte';\n  import HelpMenu from '$lib/components/global/toolbar/items/help-menu.svelte';\n  import { getAdminSectionPath, getAdminSections } from '$lib/services/app/admin';\n  import { customPages, openCustomPage } from '$lib/services/app/custom-pages';\n  import { goto } from '$lib/services/app/navigation';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n\n  // Listed here rather than in the bottom navigation, which has little room\n  const adminSections = $derived(getAdminSections());\n</script>\n\n<PageContainer aria-label={_('menu')}>\n  {#snippet main()}\n    <PageContainerMainArea>\n      {#snippet primaryToolbar()}\n        <Toolbar variant=\"primary\">\n          <h2 role=\"none\">{_('menu')}</h2>\n          <Spacer flex />\n        </Toolbar>\n      {/snippet}\n      {#snippet mainContent()}\n        <div role=\"none\" class=\"wrapper\">\n          {#if customPages.current.length}\n            <section>\n              <h3>{_('custom_pages')}</h3>\n              <Menu ariaLabel={_('custom_pages')}>\n                {#each customPages.current as page (page.id)}\n                  <MenuItem\n                    label={page.label}\n                    onclick={() => {\n                      openCustomPage(page);\n                    }}\n                  >\n                    {#snippet startIcon()}\n                      <Icon name={page.icon} />\n                    {/snippet}\n                  </MenuItem>\n                {/each}\n              </Menu>\n            </section>\n          {/if}\n          {#if adminSections.length}\n            <section>\n              <h3>{_('administration')}</h3>\n              <Menu ariaLabel={_('administration')}>\n                {#each adminSections as { key, labelKey, icon } (key)}\n                  <MenuItem\n                    label={_(labelKey)}\n                    onclick={() => {\n                      goto(getAdminSectionPath(key), { transitionType: 'forwards' });\n                    }}\n                  >\n                    {#snippet startIcon()}\n                      <Icon name={icon} />\n                    {/snippet}\n                  </MenuItem>\n                {/each}\n              </Menu>\n            </section>\n          {/if}\n          <section>\n            <h3>{_('account')}</h3>\n            <AccountMenu />\n          </section>\n          {#if prefs.devModeEnabled}\n            <section>\n              <h3>{_('help')}</h3>\n              <HelpMenu />\n            </section>\n          {/if}\n        </div>\n      {/snippet}\n    </PageContainerMainArea>\n  {/snippet}\n</PageContainer>\n\n<style>\n  .wrapper {\n    overflow-y: auto;\n    height: 100%;\n    --sui-menu-border-width: 0;\n    --sui-menu-border-radius: 0;\n    --sui-menu-padding: 8px 0;\n    --sui-menu-divider-margin: 4px 0;\n  }\n\n  h3 {\n    padding: 8px 16px;\n    background-color: var(--sui-tertiary-background-color);\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-normal);\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Dialog } from '@sveltia/ui';\n\n  import { loadChunk } from '$lib/services/app/dependencies';\n  import { showMobileSignInDialog } from '$lib/services/app/onboarding';\n  import { user } from '$lib/services/user/account.svelte';\n  import { encodeMagicLinkData } from '$lib/services/user/magic-link';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import { watchAsync } from '$lib/services/utils/state.svelte';\n\n  /** @type {HTMLCanvasElement | undefined} */\n  let canvas = $state();\n\n  // The QR code library is only loaded once the dialog is opened, as few users ever open it\n  watchAsync(\n    () => {\n      if (!canvas || !showMobileSignInDialog.current) {\n        return undefined;\n      }\n\n      const target = canvas;\n      const { origin, pathname } = window.location;\n      const snapshot = $state.snapshot(prefs);\n      const encodedData = encodeMagicLinkData({ token: user.account?.token, prefs: snapshot });\n      const url = `${origin}${pathname}#/signin/${encodedData}`;\n\n      if (prefs.devModeEnabled) {\n        // eslint-disable-next-line no-console\n        console.info('Mobile sign-in URL:', url);\n      }\n\n      return loadChunk('qrcode').then(({ toCanvas }) => ({ toCanvas, target, url }));\n    },\n    ({ toCanvas, target, url }) => {\n      toCanvas(target, url);\n    },\n    (error) => {\n      // eslint-disable-next-line no-console\n      console.error(error);\n    },\n  );\n</script>\n\n<Dialog\n  bind:open={showMobileSignInDialog.current}\n  title={_('sign_in_with_mobile')}\n  size=\"small\"\n  showOk={false}\n  showCancel={false}\n  showClose={true}\n  style=\"--sui-dialog-small-content-max-height:auto\"\n>\n  <div>{_('sign_in_with_mobile_instruction')}</div>\n  <canvas bind:this={canvas}></canvas>\n</Dialog>\n\n<style>\n  canvas {\n    display: block;\n    margin: 32px auto 16px;\n    width: 200px !important;\n    height: 200px !important;\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { onMount } from 'svelte';\n\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import SearchMainArea from '$lib/components/search/search-main-area.svelte';\n  import { parseLocation } from '$lib/services/app/navigation';\n  import { searchMode, searchTerms } from '$lib/services/search';\n\n  const ROUTE_REGEX = /^\\/search\\/(?<terms>.+)$/;\n\n  /**\n   * Navigate to the search page given the URL hash.\n   */\n  const navigate = () => {\n    const { path } = parseLocation();\n    const { terms } = path.match(ROUTE_REGEX)?.groups ?? {};\n\n    if (terms && terms !== searchTerms.current) {\n      searchTerms.current = terms;\n    }\n\n    searchMode.current ??= 'contents';\n  };\n\n  onMount(() => {\n    navigate();\n\n    /** @type {HTMLInputElement} */ (document.querySelector('.sui.search-bar input'))?.focus();\n  });\n</script>\n\n<svelte:window\n  onhashchange={() => {\n    navigate();\n  }}\n/>\n\n<PageContainer aria-label={_('search_results_for_x', { values: { terms: searchTerms.current } })}>\n  {#snippet main()}\n    <SearchMainArea />\n  {/snippet}\n</PageContainer>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, Menu, MenuItem, Spacer, Toolbar } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import BackButton from '$lib/components/common/page-toolbar/back-button.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import { panels } from '$lib/components/settings';\n  import PanelContainer from '$lib/components/settings/panel-container.svelte';\n  import {\n    announcedPageStatus,\n    goBack,\n    goto,\n    parseLocation,\n    updateContentFromHashChange,\n  } from '$lib/services/app/navigation';\n\n  const ROUTE_REGEX = /^\\/settings(?:\\/(?<panelKey>.+))?$/;\n\n  /** @type {{ key: string, icon: string, component: import('svelte').Component } | undefined} */\n  let selectedPanel = $state(undefined);\n  let notFound = $state(false);\n\n  /**\n   * Navigate to the index page or a specific page given the URL hash.\n   */\n  const navigate = () => {\n    const { path } = parseLocation();\n    const match = path.match(ROUTE_REGEX);\n\n    if (!match?.groups) {\n      return; // Different page\n    }\n\n    const { panelKey } = match.groups;\n\n    selectedPanel = panelKey ? panels.current.find((panel) => panel.key === panelKey) : undefined;\n    notFound = !!panelKey && !selectedPanel;\n\n    if (notFound) {\n      announcedPageStatus.current = _('page_not_found');\n    }\n  };\n\n  onMount(() => {\n    navigate();\n  });\n</script>\n\n<svelte:window\n  onhashchange={(event) => {\n    updateContentFromHashChange(event, navigate, ROUTE_REGEX);\n  }}\n/>\n\n<PageContainer aria-label={_('settings')}>\n  {#snippet main()}\n    <PageContainerMainArea>\n      {#snippet primaryToolbar()}\n        <Toolbar variant=\"primary\">\n          {#if selectedPanel}\n            <BackButton onclick={() => goBack('/settings')} />\n            <h2 role=\"none\">{_(`prefs.${selectedPanel.key}.title`)}</h2>\n          {:else if notFound}\n            <BackButton onclick={() => goBack('/settings')} />\n            <h2 role=\"none\">{_('page_not_found')}</h2>\n          {:else}\n            <BackButton onclick={() => goBack('/menu')} />\n            <h2 role=\"none\">{_('settings')}</h2>\n          {/if}\n          <Spacer flex />\n        </Toolbar>\n      {/snippet}\n      {#snippet mainContent()}\n        <div role=\"none\" class=\"wrapper\">\n          {#if selectedPanel}\n            <PanelContainer Panel={selectedPanel.component} />\n          {:else if notFound}\n            <NotFound message={_('page_not_found')} backPath=\"/settings\" />\n          {:else}\n            <Menu ariaLabel={_('settings')}>\n              {#each panels.current as { key, icon } (key)}\n                <MenuItem\n                  label={_(`prefs.${key}.title`)}\n                  onclick={() => goto(`/settings/${key}`, { transitionType: 'forwards' })}\n                >\n                  {#snippet startIcon()}\n                    <Icon name={icon} />\n                  {/snippet}\n                </MenuItem>\n              {/each}\n            </Menu>\n          {/if}\n        </div>\n      {/snippet}\n    </PageContainerMainArea>\n  {/snippet}\n</PageContainer>\n\n<style>\n  .wrapper {\n    overflow-y: auto;\n    height: 100%;\n    --sui-menu-border-width: 0;\n    --sui-menu-border-radius: 0;\n    --sui-menu-padding: 8px 0;\n\n    :global {\n      & > .container {\n        display: block;\n        padding: 16px;\n      }\n    }\n  }\n</style>\n","<!--\n  @component\n  Pill showing the state of the deploy preview built for an unpublished entry, used alongside the\n  Editorial Workflow status in the entry list and on the workflow board.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  import StatusPill from '$lib/components/common/status-pill.svelte';\n  import { DEPLOY_STATE_MESSAGES } from '$lib/services/deployments/constants';\n\n  /**\n   * @import { DeployState, StatusPillTone } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {DeployState} state Deploy state to be shown.\n   */\n\n  /** @type {Props} */\n  let { state } = $props();\n\n  /**\n   * Labels and pill color tones for the states worth showing. A finished build needs no badge,\n   * because the preview link itself says the preview is available, and an unknown state has\n   * nothing to report. Neither does a lookup in flight, which is over in moments — a pill that\n   * flashed up on every card as the board opened would be noise rather than information. Each\n   * pill gets the full message as its tooltip, the same one the entry editor gives its preview\n   * button. For a failed build, that tells the editor the failure isn’t necessarily theirs and who\n   * to ask, as the pill alone leaves them guessing.\n   * @type {Record<string, { label: string, tone: StatusPillTone }>}\n   */\n  const BADGES = {\n    pending: { label: 'deploy_preview.short.building', tone: 'warning' },\n    error: { label: 'deploy_preview.short.failed', tone: 'error' },\n  };\n\n  const badge = $derived(BADGES[state]);\n</script>\n\n{#if badge}\n  <StatusPill\n    tone={badge.tone}\n    label={_(badge.label)}\n    title={_(/** @type {string} */ (DEPLOY_STATE_MESSAGES[state]))}\n    class=\"deploy-status-badge {state}\"\n  />\n{/if}\n","<!--\n  @component\n  Render a draggable card for an unpublished entry on the Editorial Workflow page. Clicking the card\n  opens the entry editor; dragging it to another column changes the entry’s status. The card also\n  stands for an entry whose change has been published but hasn’t reached the site yet, in which case\n  it only reports the build.\n-->\n<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Button, Icon } from '@sveltia/ui';\n\n  import PreviewLinkButton from '$lib/components/contents/details/preview-link-button.svelte';\n  import EntryThumbnail from '$lib/components/contents/shared/entry-thumbnail.svelte';\n  import DeployStatusBadge from '$lib/components/workflow/deploy-status-badge.svelte';\n  import ExternalReviewButton from '$lib/components/workflow/external-review-button.svelte';\n  import { goto } from '$lib/services/app/navigation';\n  import { isReadonly } from '$lib/services/config/readonly';\n  import { getCollection, getCollectionLabel } from '$lib/services/contents/collection';\n  import { getCollectionFile } from '$lib/services/contents/collection/files';\n  import { getUnpublishedEntryEditorPath } from '$lib/services/contents/editor/route';\n  import { deployments, productionSHA } from '$lib/services/deployments';\n  import { checkPublishedVersion, getPublishAction } from '$lib/services/workflow';\n  import { getCompanionNotes, getUnpublishedEntryLabel } from '$lib/services/workflow/board';\n  import { getWorkflowStages } from '$lib/services/workflow/stages';\n\n  /**\n   * @import { UnpublishedEntry } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {UnpublishedEntry} entry Unpublished entry.\n   * @property {boolean} [dragging] Whether this card is currently being dragged.\n   * @property {boolean} [busy] Whether an action is in flight for this entry. The controls are\n   * disabled meanwhile, so a second request can’t be sent against the same pull request.\n   * @property {boolean} [deploying] Whether the entry’s pull request has been merged and the site\n   * is being rebuilt from it. There’s nothing left to do with the entry, so the card can’t be\n   * dragged and has no actions; it shows the state of the production build instead of a preview’s.\n   * @property {() => void} [onDragStart] Drag start handler.\n   * @property {() => void} [onDragEnd] Drag end handler.\n   * @property {() => void} [onDelete] Delete button click handler.\n   * @property {() => void} [onPublish] Publish button click handler.\n   */\n\n  /** @type {Props} */\n  let {\n    entry,\n    dragging = false,\n    busy = false,\n    deploying = false,\n    onDragStart = undefined,\n    onDragEnd = undefined,\n    onDelete = undefined,\n    onPublish = undefined,\n  } = $props();\n\n  const { collectionName, fileName, status, pullRequest } = $derived(entry.workflow);\n  const deletion = $derived(status === 'pending_deletion');\n  const collection = $derived(getCollection(collectionName));\n  const collectionFile = $derived(\n    collection && fileName ? getCollectionFile(collection, fileName) : undefined,\n  );\n  // A read-only entry can be opened and viewed, but not moved through the stages, published or\n  // discarded\n  const readonly = $derived(isReadonly({ collection, collectionFile }));\n  // With Preview Workflow, the drafting stage is the only one, so there’s nowhere to move the entry\n  const movable = $derived(\n    !deletion && !deploying && !readonly && getWorkflowStages(collection).length > 1,\n  );\n  // The card has no locale of its own, so the link points at the entry’s default one\n  const defaultLocale = $derived((collectionFile ?? collection)?._i18n?.defaultLocale);\n  // A merged change goes out with the production build, which is a different commit from the pull\n  // request’s, and a later one if another change has been merged since\n  const deploySHA = $derived(deploying ? productionSHA.current : pullRequest.headSHA);\n  const deployState = $derived(\n    (deploySHA ? deployments.current[deploySHA]?.state : undefined) ?? 'unknown',\n  );\n  /* v8 ignore start -- the app locale is always set once the UI strings are loaded */\n  // `appLocale.current` is a key, because the labels can be localized\n  const summary = $derived(appLocale.current ? getUnpublishedEntryLabel(entry) : entry.slug);\n  /* v8 ignore stop */\n  // The entries created or edited from a Relation field of the entry are published along with it\n  const companionNotes = $derived(getCompanionNotes(entry, appLocale.current));\n  const collectionLabel = $derived(\n    appLocale.current && collection ? getCollectionLabel(collection, { useSingular: true }) : '',\n  );\n  // The entry can only be published from the last column, and only by a user who can merge it. A\n  // pull request a contributor has opened from their fork is reviewed and merged on the Git service\n  // instead, so the card links to it from the same place\n  const publishAction = $derived(\n    !deploying && !readonly ? getPublishAction(entry, collection) : undefined,\n  );\n  // Deleting an entry that has a published version only throws away the pending changes.\n  // The entry can be published from another view, so the check depends on `allEntries`\n  const publishedVersionExists = $derived(checkPublishedVersion(entry));\n  // The `delete` option only blocks taking an entry off the site. Discarding a pull request leaves\n  // the published version untouched, so it stays available even when deletion is disabled\n  const canDelete = $derived(\n    !deploying &&\n      !readonly &&\n      (publishedVersionExists ||\n        (collection?._type === 'entry' ? collection.delete !== false : true)),\n  );\n  // An entry being removed from the site has left the CMS as well, so there’s nothing to open, and\n  // its page isn’t worth a link either: it’s about to return a 404\n  const gone = $derived(deploying && deletion);\n  // The left action does one of three things depending on the entry, and with the labels gone the\n  // icon is all that says which: it reverses a pending deletion, throws away the changes a pull\n  // request was about to make, or takes an unpublished entry away for good\n  const deleteIcon = $derived(deletion || publishedVersionExists ? 'undo' : 'delete');\n</script>\n\n<!-- A pending deletion has no stages to move through, so its card doesn’t drag, and neither does\na merged or read-only one, or one with no other stage to move to -->\n<div\n  role=\"listitem\"\n  class=\"card\"\n  class:dragging\n  class:static={!movable}\n  draggable={!busy && movable}\n  ondragstart={(/** @type {DragEvent} */ event) => {\n    if (event.dataTransfer) {\n      event.dataTransfer.effectAllowed = 'move';\n      // Some browsers require data to be set for the drag to start\n      event.dataTransfer.setData('text/plain', pullRequest.branch);\n    }\n\n    onDragStart?.();\n  }}\n  ondragend={() => {\n    onDragEnd?.();\n  }}\n>\n  <button\n    type=\"button\"\n    class=\"summary\"\n    aria-label={summary}\n    disabled={gone}\n    onclick={() => {\n      goto(getUnpublishedEntryEditorPath(entry), { transitionType: 'forwards' });\n    }}\n  >\n    {#if collection?._type === 'entry'}\n      <EntryThumbnail {collection} {entry} variant=\"icon\" />\n    {/if}\n    <span role=\"none\" class=\"text\">\n      <span role=\"none\" class=\"collection\"><bdi>{collectionLabel}</bdi></span>\n      <span role=\"none\" class=\"title\"><bdi>{summary}</bdi></span>\n    </span>\n  </button>\n  {#each companionNotes as note (note)}\n    <p class=\"companions\">{note}</p>\n  {/each}\n  <footer role=\"none\">\n    <div role=\"none\" class=\"meta\">\n      {#if pullRequest.author?.name}\n        <span role=\"none\" class=\"author\"><bdi>{pullRequest.author.name}</bdi></span>\n      {/if}\n      <span role=\"none\" class=\"date\">\n        {pullRequest.updatedDate.toLocaleDateString(appLocale.current, {\n          month: 'short',\n          day: 'numeric',\n        })}\n      </span>\n      {#if pullRequest.fork}\n        <span role=\"none\" class=\"note\">{_('workflow.from_fork')}</span>\n      {/if}\n      {#if gone}\n        <span role=\"none\" class=\"note\">{_('workflow.deploying_deletion')}</span>\n      {/if}\n      <DeployStatusBadge state={deployState} />\n    </div>\n    <div role=\"none\" class=\"actions\">\n      {#if collection && defaultLocale && !gone}\n        <!-- A merged change is on the live site, or on its way there, rather than on a preview -->\n        <PreviewLinkButton\n          {entry}\n          locale={defaultLocale}\n          {collection}\n          {collectionFile}\n          pullRequest={deploying ? undefined : pullRequest}\n          size=\"small\"\n          iconic\n        />\n      {/if}\n      {#if canDelete}\n        <Button\n          variant=\"ghost\"\n          size=\"small\"\n          iconic\n          disabled={busy}\n          aria-label={deletion\n            ? _('workflow.cancel_deletion')\n            : publishedVersionExists\n              ? _('workflow.discard_changes')\n              : _('delete_entries', { values: { count: 1 } })}\n          onclick={() => {\n            onDelete?.();\n          }}\n        >\n          {#snippet startIcon()}\n            <Icon name={deleteIcon} />\n          {/snippet}\n        </Button>\n      {/if}\n      {#if publishAction === 'publish'}\n        <Button\n          variant=\"primary\"\n          size=\"small\"\n          iconic\n          disabled={busy}\n          aria-label={deletion\n            ? _('delete_entries', { values: { count: 1 } })\n            : _('workflow.publish_entry')}\n          onclick={() => {\n            onPublish?.();\n          }}\n        >\n          {#snippet startIcon()}\n            <Icon name={deletion ? 'delete' : 'publish'} />\n          {/snippet}\n        </Button>\n      {:else if publishAction === 'review'}\n        <ExternalReviewButton {entry} size=\"small\" iconic disabled={busy} />\n      {/if}\n    </div>\n  </footer>\n</div>\n\n<style>\n  .card {\n    display: flex;\n    flex-direction: column;\n    gap: 4px;\n    border: 1px solid var(--sui-secondary-border-color);\n    border-radius: var(--sui-control-medium-border-radius);\n    padding: 8px 12px;\n    background-color: var(--sui-primary-background-color);\n    cursor: grab;\n\n    &.dragging {\n      opacity: 0.5;\n    }\n\n    &.static {\n      cursor: default;\n    }\n  }\n\n  .summary {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    border: 0;\n    padding: 0;\n    background: none;\n    color: inherit;\n    font-family: inherit;\n    text-align: left;\n    cursor: pointer;\n\n    &:disabled {\n      cursor: default;\n    }\n\n    /* Let the label column shrink instead of pushing the thumbnail out of the card */\n    .text {\n      display: flex;\n      flex-direction: column;\n      gap: 2px;\n      min-width: 0;\n    }\n  }\n\n  .collection {\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n  }\n\n  .title {\n    font-size: var(--sui-font-size-default);\n    line-height: 1.4;\n    overflow-wrap: anywhere;\n  }\n\n  .companions {\n    margin: 0;\n    color: var(--sui-secondary-foreground-color);\n    font-size: var(--sui-font-size-small);\n    overflow-wrap: anywhere;\n  }\n\n  footer {\n    display: flex;\n    align-items: center;\n    justify-content: space-between;\n    gap: 8px;\n\n    .meta {\n      display: flex;\n      align-items: center;\n      gap: 6px;\n      min-width: 0;\n      color: var(--sui-secondary-foreground-color);\n      font-size: var(--sui-font-size-small);\n    }\n\n    /* Let a long user name truncate rather than push the date out of the card */\n    .author {\n      overflow: hidden;\n      text-overflow: ellipsis;\n      white-space: nowrap;\n    }\n\n    .date,\n    .note {\n      flex: none;\n    }\n\n    .author + .date::before,\n    .date + .note::before {\n      margin-inline-end: 6px;\n      content: '\\00B7'; /* middle dot */\n    }\n\n    .actions {\n      display: flex;\n      flex: none;\n      align-items: center;\n    }\n  }\n</style>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import {\n    Alert,\n    Button,\n    ConfirmationDialog,\n    EmptyState,\n    Group,\n    Icon,\n    Spacer,\n    Toast,\n    Toolbar,\n  } from '@sveltia/ui';\n\n  import PageContainerMainArea from '$lib/components/common/page-container-main-area.svelte';\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import WorkflowEntryCard from '$lib/components/workflow/workflow-entry-card.svelte';\n  import { announcedPageStatus } from '$lib/services/app/navigation';\n  import { retainDeployPolling } from '$lib/services/deployments/poll';\n  import {\n    allUnpublishedEntries,\n    checkPublishedVersion,\n    getUnpublishedEntryById,\n    isPendingDeletion,\n    publishingBranches,\n    workflowDataReady,\n  } from '$lib/services/workflow';\n  import {\n    COLUMN_LABELS,\n    getBoardAnnouncement,\n    getDiscardMessages,\n    getPublishMessages,\n    groupEntriesByStatus,\n    REFRESH_MESSAGES,\n    STATUS_UPDATE_MESSAGES,\n  } from '$lib/services/workflow/board';\n  import { deployingEntries } from '$lib/services/workflow/deploy';\n  import { getDiscardDialogStrings, getPublishDialogStrings } from '$lib/services/workflow/dialogs';\n  import { reloadUnpublishedEntries } from '$lib/services/workflow/load';\n  import {\n    discardWorkflowEntry,\n    publishReviewedEntry,\n    updateWorkflowStatus,\n  } from '$lib/services/workflow/save';\n  import {\n    boardStages,\n    getStageOfEntry,\n    isStageAvailable,\n    workflowPageLabelKey,\n  } from '$lib/services/workflow/stages';\n  import { canMoveToStatus, canPublish } from '$lib/services/workflow/validate';\n  import { getWorkflowErrorMessage } from '$lib/services/workflow/verify';\n\n  /**\n   * @import { UnpublishedEntry, WorkflowStatus } from '$lib/types/private';\n   * @import { ToastMessages } from '$lib/services/workflow/board';\n   */\n\n  // `$state.raw` rather than `$state`, because the latter deeply proxies the entry, and the proxy\n  // would end up back in the store when the status is saved. `structuredClone()` throws on a proxy,\n  // so the entry editor would then fail to open the entry\n  /** @type {UnpublishedEntry | undefined} */\n  let draggedEntry = $state.raw();\n  /** @type {WorkflowStatus | undefined} */\n  let dropTarget = $state();\n  /**\n   * Entry targeted by the Delete or Publish confirmation dialog. Kept raw for the same reason as\n   * {@link draggedEntry}.\n   * @type {UnpublishedEntry | undefined}\n   */\n  let targetEntry = $state.raw();\n  let showDeleteDialog = $state(false);\n  let showPublishDialog = $state(false);\n  /** @type {'info' | 'success' | 'error'} */\n  let toastStatus = $state('info');\n  let toastMessage = $state('');\n  let showToast = $state(false);\n  /**\n   * Branches of the entries with an action in flight. `$state.raw` because the list is replaced\n   * rather than mutated.\n   * @type {string[]}\n   */\n  let busyBranches = $state.raw([]);\n  /** Whether the pull requests are being read again at the user’s request. */\n  let refreshing = $state(false);\n\n  /**\n   * Whether an action is in flight for the given entry. A publish is recorded by the service as\n   * well, because the merge can take minutes and outlive this page: a card for an entry whose\n   * merge was started before the page was opened is busy all the same.\n   * @param {UnpublishedEntry} entry Entry.\n   * @returns {boolean} Result.\n   */\n  const isBusy = ({\n    workflow: {\n      pullRequest: { branch },\n    },\n  }) => busyBranches.includes(branch) || publishingBranches.current.includes(branch);\n\n  // The entry can be published from another view, so the check depends on `allEntries`\n  const publishedVersionExists = $derived(checkPublishedVersion(targetEntry));\n  // For an entry awaiting deletion the two actions are reversed: the first one calls the removal\n  // off, and the second one carries it out\n  const targetIsDeletion = $derived(targetEntry?.workflow.status === 'pending_deletion');\n  const discardDialogStrings = $derived(\n    getDiscardDialogStrings({ pendingDeletion: targetIsDeletion, publishedVersionExists }),\n  );\n  const publishDialogStrings = $derived(getPublishDialogStrings({ deletion: targetIsDeletion }));\n\n  // A pending deletion has a status of its own, so it never lands in a stage column. It’s listed\n  // below the board instead, and its cards don’t drag: there are no stages to move it through\n  const { columns, pendingDeletions } = $derived(\n    groupEntriesByStatus(boardStages.current, allUnpublishedEntries.current, getStageOfEntry),\n  );\n  const deploying = $derived(deployingEntries.current);\n\n  // Keep the deploy state fresh while the board is open, so a preview link turns live as soon as\n  // its build finishes. One hold covers every card, because the lookup batches across all the open\n  // pull requests. The release function is returned synchronously; awaiting anything first would\n  // lose the handle and leak the hold\n  $effect(() => retainDeployPolling());\n\n  /** Whether the page has already been announced, so a later status change doesn’t repeat it. */\n  let announced = false;\n\n  /**\n   * Show the given message with a toast notification.\n   * @param {'info' | 'success' | 'error'} status Status of the message.\n   * @param {string} message Localized message.\n   */\n  const notify = (status, message) => {\n    toastStatus = status;\n    toastMessage = message;\n    showToast = true;\n  };\n\n  /**\n   * Report the progress and the result of a request with a toast notification.\n   * @param {Promise<any>} request Request being performed.\n   * @param {ToastMessages} messages I18n string keys for each state.\n   * @param {() => void} onSettled Function called once the request has settled.\n   * @param {(ex: any) => string} [getErrorMessage] Function returning the localized message for\n   * the given failure. The `error` message by default.\n   */\n  const reportRequest = async (\n    request,\n    messages,\n    onSettled,\n    getErrorMessage = () => _(messages.error),\n  ) => {\n    notify('info', _(messages.info));\n\n    // The toast is shown again with the result in case it has already been dismissed while the\n    // request was in flight\n    try {\n      await request;\n      notify('success', _(messages.success));\n    } catch (/** @type {any} */ ex) {\n      notify('error', getErrorMessage(ex));\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      onSettled();\n    }\n  };\n\n  /**\n   * Report the progress and the result of an Editorial Workflow action with a toast notification.\n   * The entry’s controls stay disabled until the request settles, so a second action can’t be\n   * started against the same pull request while the first one is still in flight.\n   * @param {UnpublishedEntry} entry Entry the action applies to.\n   * @param {Promise<any>} request Request being performed.\n   * @param {ToastMessages} messages I18n string keys for each state.\n   */\n  const runAction = async (entry, request, messages) => {\n    // Key the busy state on the branch rather than the entry object, which is replaced in the store\n    // once the request completes\n    const { branch } = entry.workflow.pullRequest;\n\n    busyBranches = [...busyBranches, branch];\n\n    await reportRequest(\n      request,\n      messages,\n      () => {\n        busyBranches = busyBranches.filter((_branch) => _branch !== branch);\n      },\n      // A failure that trying again wouldn’t fix says why, e.g. a publish refused over what the\n      // pull request holds, or another request open from the branch\n      (ex) => getWorkflowErrorMessage(ex, messages.error),\n    );\n  };\n\n  /**\n   * Read the pull requests again, to pick up what anyone else has changed since the board was\n   * loaded, without waiting for the next scheduled check, and report the result with a toast\n   * notification. A reload already in flight, such as a scheduled check, may have listed the pull\n   * requests before the button was clicked, so the board is reloaded again after it rather than\n   * joining it.\n   */\n  const refresh = async () => {\n    refreshing = true;\n\n    await reportRequest(reloadUnpublishedEntries({ fresh: true }), REFRESH_MESSAGES, () => {\n      refreshing = false;\n    });\n  };\n\n  /**\n   * Report that an action couldn’t be performed because the entry has validation errors. An entry\n   * can be saved as a draft with its required fields left empty, so it has to be checked before it\n   * moves towards being published.\n   * @param {string} messageKey I18n string key of the message to show.\n   */\n  const reportValidationErrors = (messageKey) => {\n    notify('error', _(messageKey));\n  };\n\n  /**\n   * Ask for confirmation before deleting the given entry, or calling its pending deletion off.\n   * @param {UnpublishedEntry} entry Entry.\n   */\n  const confirmDelete = (entry) => {\n    targetEntry = entry;\n    showDeleteDialog = true;\n  };\n\n  /**\n   * Ask for confirmation before publishing the given entry, or carrying out its pending deletion.\n   * @param {UnpublishedEntry} entry Entry.\n   */\n  const confirmPublish = (entry) => {\n    targetEntry = entry;\n    showPublishDialog = true;\n  };\n\n  /**\n   * Move the dragged entry to the given column, which changes the label on the pull request.\n   * @param {WorkflowStatus} status New status.\n   */\n  const moveEntry = async (status) => {\n    const entry = getUnpublishedEntryById(draggedEntry?.id);\n\n    draggedEntry = undefined;\n    dropTarget = undefined;\n\n    if (!entry || getStageOfEntry(entry) === status || !isStageAvailable(entry, status)) {\n      return;\n    }\n\n    if (!canMoveToStatus({ entry, status })) {\n      reportValidationErrors('workflow.status_change_blocked');\n\n      return;\n    }\n\n    await runAction(entry, updateWorkflowStatus(entry, status), STATUS_UPDATE_MESSAGES);\n  };\n\n  // Announce the page once the pull requests have been fetched, so the counts are accurate. It’s a\n  // one-shot announcement like the other pages; a status change is reported with a toast instead.\n  $effect(() => {\n    if (announced || !workflowDataReady.current) {\n      return;\n    }\n\n    announced = true;\n\n    const { key, values } = getBoardAnnouncement(columns, pendingDeletions);\n\n    announcedPageStatus.current = _(key, { values });\n  });\n</script>\n\n<PageContainer aria-label={_(workflowPageLabelKey.current)}>\n  {#snippet main()}\n    <PageContainerMainArea aria-label={_(workflowPageLabelKey.current)}>\n      {#snippet primaryToolbar()}\n        <Toolbar variant=\"primary\">\n          <h2 role=\"none\">{_(workflowPageLabelKey.current)}</h2>\n          <Spacer flex />\n          <Button\n            variant=\"ghost\"\n            iconic\n            aria-label={_('workflow.refresh')}\n            disabled={!workflowDataReady.current || refreshing}\n            onclick={refresh}\n          >\n            {#snippet startIcon()}\n              <Icon name=\"refresh\" />\n            {/snippet}\n          </Button>\n        </Toolbar>\n      {/snippet}\n      {#snippet mainContent()}\n        {#if !workflowDataReady.current}\n          <EmptyState>\n            <span role=\"none\">{_('loading_entries', { values: { count: 2 } })}</span>\n          </EmptyState>\n        {:else}\n          <!-- The board and the trays below it share a wrapper carrying the column count, which\n          varies: an Open Authoring contributor can’t publish, so the board leaves out the stage\n          that says an entry is ready to go live -->\n          <div\n            role=\"none\"\n            class=\"board\"\n            class:single={columns.length === 1}\n            style:--column-count={columns.length}\n          >\n            <div role=\"none\" class=\"columns\">\n              {#each columns as { status, entries } (status)}\n                <Group class=\"column\" aria-labelledby=\"{status}-column-title\">\n                  <header role=\"none\">\n                    <h3 role=\"none\" id=\"{status}-column-title\">{_(COLUMN_LABELS[status])}</h3>\n                  </header>\n                  <div\n                    role=\"list\"\n                    class=\"entries\"\n                    class:drop-target={dropTarget === status}\n                    aria-label={_(COLUMN_LABELS[status])}\n                    ondragover={(/** @type {DragEvent} */ event) => {\n                      if (!draggedEntry || !isStageAvailable(draggedEntry, status)) {\n                        return;\n                      }\n\n                      event.preventDefault();\n\n                      if (event.dataTransfer) {\n                        event.dataTransfer.dropEffect = 'move';\n                      }\n\n                      dropTarget = status;\n                    }}\n                    ondragleave={() => {\n                      if (dropTarget === status) {\n                        dropTarget = undefined;\n                      }\n                    }}\n                    ondrop={(/** @type {DragEvent} */ event) => {\n                      event.preventDefault();\n                      moveEntry(status);\n                    }}\n                  >\n                    {#each entries as entry (entry.id)}\n                      <WorkflowEntryCard\n                        {entry}\n                        busy={isBusy(entry)}\n                        dragging={draggedEntry?.id === entry.id}\n                        onDragStart={() => {\n                          draggedEntry = entry;\n                        }}\n                        onDragEnd={() => {\n                          draggedEntry = undefined;\n                          dropTarget = undefined;\n                        }}\n                        onDelete={() => confirmDelete(entry)}\n                        onPublish={() => confirmPublish(entry)}\n                      />\n                    {:else}\n                      <EmptyState>\n                        <span role=\"none\">{_('workflow.no_entries')}</span>\n                      </EmptyState>\n                    {/each}\n                  </div>\n                </Group>\n              {/each}\n            </div>\n            <!-- Only rendered when something is pending, so the board keeps the height\n            otherwise -->\n            {#if pendingDeletions.length}\n              <div role=\"none\" class=\"tray\">\n                <Group class=\"group\" aria-labelledby=\"deletions-title\">\n                  <header role=\"none\">\n                    <h3 role=\"none\" id=\"deletions-title\">{_('status.pending_deletion')}</h3>\n                  </header>\n                  <div role=\"list\" class=\"entries\" aria-label={_('status.pending_deletion')}>\n                    {#each pendingDeletions as entry (entry.id)}\n                      <WorkflowEntryCard\n                        {entry}\n                        busy={isBusy(entry)}\n                        onDelete={() => confirmDelete(entry)}\n                        onPublish={() => confirmPublish(entry)}\n                      />\n                    {/each}\n                  </div>\n                </Group>\n              </div>\n            {/if}\n            <!-- Merged changes the site hasn’t caught up with yet. A deletion is gone from the\n            entry list once merged, so this is the only place left to say the site still has it -->\n            {#if deploying.length}\n              <div role=\"none\" class=\"tray\">\n                <Group class=\"group\" aria-labelledby=\"deploying-title\">\n                  <header role=\"none\">\n                    <h3 role=\"none\" id=\"deploying-title\">{_('status.deploying')}</h3>\n                  </header>\n                  <div role=\"list\" class=\"entries\" aria-label={_('status.deploying')}>\n                    {#each deploying as { entry } (entry.workflow.pullRequest.branch)}\n                      <WorkflowEntryCard {entry} deploying />\n                    {/each}\n                  </div>\n                </Group>\n              </div>\n            {/if}\n          </div>\n        {/if}\n      {/snippet}\n    </PageContainerMainArea>\n  {/snippet}\n</PageContainer>\n\n<ConfirmationDialog\n  bind:open={showDeleteDialog}\n  title={discardDialogStrings.title}\n  okLabel={discardDialogStrings.label}\n  onOk={async () => {\n    const entry = getUnpublishedEntryById(targetEntry?.id);\n\n    if (entry) {\n      await runAction(\n        entry,\n        discardWorkflowEntry(entry),\n        getDiscardMessages(isPendingDeletion(entry)),\n      );\n    }\n  }}\n>\n  {discardDialogStrings.message}\n</ConfirmationDialog>\n\n<ConfirmationDialog\n  bind:open={showPublishDialog}\n  title={publishDialogStrings.title}\n  okLabel={publishDialogStrings.label}\n  onOk={async () => {\n    const entry = getUnpublishedEntryById(targetEntry?.id);\n\n    if (!entry) {\n      return;\n    }\n\n    if (!canPublish({ entry })) {\n      reportValidationErrors('workflow.publish_blocked');\n\n      return;\n    }\n\n    await runAction(\n      entry,\n      // Pinned to the version the dialog was opened for\n      publishReviewedEntry(entry, targetEntry),\n      getPublishMessages(isPendingDeletion(entry)),\n    );\n  }}\n>\n  {publishDialogStrings.message}\n</ConfirmationDialog>\n\n<!-- The `id` makes the auto-hide timer restart when the message changes -->\n{#if toastMessage}\n  <Toast id={toastMessage} bind:show={showToast}>\n    <Alert status={toastStatus}>{toastMessage}</Alert>\n  </Toast>\n{/if}\n\n<style>\n  /*\n   * Entries awaiting removal, and merged ones the site hasn’t caught up with, are listed in trays\n   * below the board rather than as extra columns: they have no stages to move through, and a\n   * column would take a share of the width for something rare\n   */\n\n  .board {\n    flex: auto;\n    display: flex;\n    flex-direction: column;\n    overflow: hidden;\n  }\n\n  /*\n   * With a single column, as with Preview Workflow, the cards would be stretched across the page,\n   * so they’re laid out in a grid instead, both in the column and in the trays below it\n   */\n\n  .board.single .entries {\n    display: grid;\n    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));\n    align-content: start;\n  }\n\n  .tray {\n    flex: none;\n    display: flex;\n    flex-direction: column;\n    max-height: 33%;\n    border-block-start: 1px solid var(--sui-secondary-border-color);\n    background-color: var(--sui-primary-background-color);\n\n    :global {\n      .group {\n        display: flex;\n        flex-direction: column;\n        overflow: hidden;\n      }\n    }\n\n    header {\n      display: flex;\n      align-items: center;\n      padding: 0 16px;\n      height: 40px;\n      background-color: var(--sui-tertiary-background-color);\n\n      h3 {\n        font-size: var(--sui-font-size-x-large);\n      }\n    }\n\n    /* Mirror the board’s track count, so a card here is the same size as one in a column */\n    .entries {\n      display: grid;\n      grid-template-columns: repeat(var(--column-count), 1fr);\n      gap: 8px;\n      padding: 8px;\n      overflow-y: auto;\n\n      @media (width < 768px) {\n        grid-template-columns: 1fr;\n      }\n    }\n  }\n\n  .columns {\n    flex: auto;\n    display: flex;\n    gap: 4px;\n    background-color: var(--sui-secondary-background-color); /* same as toolbar */\n\n    @media (width < 768px) {\n      flex-direction: column;\n      gap: 0;\n    }\n\n    :global {\n      .column {\n        flex: auto;\n        display: flex;\n        flex-direction: column;\n        width: calc(100% / var(--column-count));\n        background-color: var(--sui-primary-background-color);\n\n        @media (width < 768px) {\n          width: 100%;\n          height: calc(100% / var(--column-count));\n        }\n      }\n    }\n\n    header {\n      flex: none;\n      display: flex;\n      align-items: center;\n      padding: 0 16px;\n      height: 40px;\n      background-color: var(--sui-tertiary-background-color);\n\n      h3 {\n        font-size: var(--sui-font-size-x-large);\n      }\n    }\n\n    .entries {\n      flex: auto;\n      display: flex;\n      flex-direction: column;\n      gap: 8px;\n      padding: 8px;\n      overflow-y: auto;\n\n      &.drop-target {\n        background-color: var(--sui-selected-background-color);\n      }\n    }\n  }\n</style>\n","<script>\n  import { onMount } from 'svelte';\n\n  import AdminPage from '$lib/components/admin/admin-page.svelte';\n  import AssetsPage from '$lib/components/assets/assets-page.svelte';\n  import CloudinaryIframe from '$lib/components/assets/browser/cloudinary-iframe.svelte';\n  import AssetUpdatesToast from '$lib/components/assets/shared/asset-updates-toast.svelte';\n  import UploadAssetsConfirmDialog from '$lib/components/assets/shared/upload-assets-confirm-dialog.svelte';\n  import UploadAssetsDialog from '$lib/components/assets/shared/upload-assets-dialog.svelte';\n  import ContentsPage from '$lib/components/contents/contents-page.svelte';\n  import TranslatorApiKeyDialog from '$lib/components/contents/details/editor/translator-api-key-dialog.svelte';\n  import ContentUpdatesToast from '$lib/components/contents/shared/content-updates-toast.svelte';\n  import EntryParseErrorsToast from '$lib/components/contents/shared/entry-parse-errors-toast.svelte';\n  import CustomPage from '$lib/components/custom-pages/custom-page.svelte';\n  import DemoWelcomeDialog from '$lib/components/global/demo-welcome-dialog.svelte';\n  import LiveReloadInfobar from '$lib/components/global/infobars/live-reload-infobar.svelte';\n  import MobilePromoInfobar from '$lib/components/global/infobars/mobile-promo-infobar.svelte';\n  import NewLanguageInfobar from '$lib/components/global/infobars/new-language-infobar.svelte';\n  import LocalGitNoticeToast from '$lib/components/global/local-git-notice-toast.svelte';\n  import NotFoundPage from '$lib/components/global/not-found-page.svelte';\n  import BottomNavigation from '$lib/components/global/toolbar/bottom-navigation.svelte';\n  import GlobalToolbar from '$lib/components/global/toolbar/global-toolbar.svelte';\n  import MenuPage from '$lib/components/menu/menu-page.svelte';\n  import MobileSignInDialog from '$lib/components/menu/mobile-sign-in-dialog.svelte';\n  import SearchPage from '$lib/components/search/search-page.svelte';\n  import SettingsPage from '$lib/components/settings/settings-page.svelte';\n  import WorkflowPage from '$lib/components/workflow/workflow-page.svelte';\n  import { getAdditions } from '$lib/services/app/additions';\n  import { getAdminSections } from '$lib/services/app/admin';\n  import { getCustomPageId, selectedCustomPageId } from '$lib/services/app/custom-pages';\n  import {\n    parseLocation,\n    redirectLegacyEntryLink,\n    resolveRoute,\n    selectedPageName,\n  } from '$lib/services/app/navigation';\n  import { canShowMobileSignInDialog } from '$lib/services/app/onboarding';\n  import { searchMode } from '$lib/services/search';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * Page name used while the URL matches none of the routes below. It’s deliberately not a route\n   * itself, so `#/not-found` is a dead link like any other unknown path.\n   */\n  const NOT_FOUND_PAGE_NAME = 'not-found';\n\n  /** @type {Record<string, any>} */\n  const pages = $derived({\n    collections: ContentsPage,\n    assets: AssetsPage,\n    search: env.isSmallScreen\n      ? SearchPage\n      : searchMode.current\n        ? { contents: ContentsPage, assets: AssetsPage }[searchMode.current]\n        : SearchPage,\n    workflow: WorkflowPage,\n    pages: CustomPage,\n    // Only for those who can see any of its sections; for anyone else, it’s a dead link\n    ...(getAdminSections().length ? { admin: AdminPage } : {}),\n    // For small screens\n    menu: MenuPage,\n    settings: SettingsPage,\n  });\n\n  const SelectedPage = $derived.by(() => {\n    const name = selectedPageName.current;\n\n    if (name === NOT_FOUND_PAGE_NAME) {\n      return NotFoundPage;\n    }\n\n    // A page that’s no longer offered, e.g. Administration once developer mode is turned off, can’t\n    // be found any more. Nothing is selected until the route is first resolved\n    return pages[name] ?? (name ? NotFoundPage : undefined);\n  });\n\n  /**\n   * Select one of the pages given the URL path.\n   */\n  const selectPage = () => {\n    // A Netlify/Decap CMS shorthand link to an entry has to be caught before the route is resolved,\n    // which would otherwise drop the user on the collection list with no sign of where they meant\n    // to go. The redirect triggers another `hashchange`, so this runs again with the real route\n    if (redirectLegacyEntryLink()) {\n      return;\n    }\n\n    const { path } = parseLocation();\n    const route = resolveRoute(path, Object.keys(pages));\n\n    // The custom page is looked up by the page itself, as it may be registered after the app has\n    // been mounted\n    selectedCustomPageId.current = getCustomPageId(path);\n\n    if ('redirect' in route) {\n      window.location.replace(route.redirect);\n\n      return;\n    }\n\n    if ('notFound' in route) {\n      selectedPageName.current = NOT_FOUND_PAGE_NAME;\n      searchMode.current = null;\n\n      return;\n    }\n\n    if (selectedPageName.current !== route.pageName) {\n      selectedPageName.current = route.pageName;\n    }\n\n    if (route.searchMode !== undefined) {\n      searchMode.current = route.searchMode;\n    }\n  };\n\n  onMount(() => {\n    selectPage();\n\n    // With Sveltia CMS Additions, entry locks, comment counts and credentials are shared, and the\n    // GitHub token kept fresh, while the user is signed in, which is while this is mounted. Its\n    // chunk was loaded along with the backend, before the user could sign in\n    return getAdditions()?.startSession();\n  });\n</script>\n\n<svelte:window\n  onhashchange={() => {\n    selectPage();\n  }}\n/>\n\n<LiveReloadInfobar />\n<NewLanguageInfobar />\n\n{#if canShowMobileSignInDialog.current}\n  <MobilePromoInfobar />\n  <MobileSignInDialog />\n{/if}\n\n{#if !env.isSmallScreen}\n  <GlobalToolbar />\n{/if}\n\n<div role=\"none\" class=\"page-root\">\n  <SelectedPage />\n</div>\n\n{#if env.isSmallScreen}\n  <BottomNavigation />\n{/if}\n\n<UploadAssetsDialog />\n<UploadAssetsConfirmDialog />\n<AssetUpdatesToast />\n<ContentUpdatesToast />\n<TranslatorApiKeyDialog />\n<EntryParseErrorsToast />\n<LocalGitNoticeToast />\n<DemoWelcomeDialog />\n<CloudinaryIframe />\n\n<style>\n  .page-root {\n    position: relative;\n    flex: auto;\n    display: flex;\n    flex-direction: column;\n    overflow: hidden;\n    view-transition-name: page-root;\n  }\n</style>\n","<!--\n  @component\n  Confirmation dialog asking an Open Authoring contributor whether the CMS may fork the repository\n  on their behalf. Creating a repository on someone’s account isn’t something to do behind their\n  back, so the sign-in waits here until they answer.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { ConfirmationDialog } from '@sveltia/ui';\n\n  import { forkPermissionRequest } from '$lib/services/workflow/open-authoring';\n\n  /**\n   * @import { ForkPermissionRequest } from '$lib/types/private';\n   */\n\n  const request = $derived(forkPermissionRequest.current);\n  // Writable, because the dialog sets it back to `false` when it’s dismissed\n  let open = $derived(!!request);\n</script>\n\n<ConfirmationDialog\n  bind:open\n  title={_('open_authoring.fork_repository')}\n  okLabel={_('open_authoring.fork')}\n  onOk={() => {\n    request?.respond(true);\n  }}\n  onClose={() => {\n    // Covers the Cancel button, the Escape key and any other way out of the dialog. Granting\n    // permission has already settled the request, so this leaves it alone\n    request?.respond(false);\n  }}\n>\n  <!-- The content is only rendered while the dialog is open, for a request -->\n  {_('open_authoring.confirm_forking_repository', {\n    values: { repo: /** @type {ForkPermissionRequest} */ (request).repo },\n  })}\n</ConfirmationDialog>\n","<!--\n  @component\n  Infobar telling an Open Authoring contributor that their changes go to a fork and reach the site\n  through a pull request. Without it there’s nothing to explain why the entries they save don’t show\n  up on the site, or why the publishing controls are missing. It’s a one-off notice: once dismissed,\n  it stays dismissed.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Infobar } from '@sveltia/ui';\n\n  import { createOneOffNotice } from '$lib/services/app/onboarding';\n  import { backend } from '$lib/services/backends';\n  import { openNewTab } from '$lib/services/utils/window';\n  import { forkedRepository, getForkPath, getForkURL } from '$lib/services/workflow/open-authoring';\n\n  // The dismissal is stored alongside the other one-off notices\n  const notice = createOneOffNotice('openAuthoringNotice');\n\n  const fork = $derived(forkedRepository.current);\n  const repoPath = $derived(getForkPath(fork));\n  const forkURL = $derived(getForkURL(backend.current?.repository, fork));\n\n  // Only a contributor sees this, so the stored state isn’t read for anyone else\n  $effect(() => {\n    if (fork) {\n      notice.showIfNeeded();\n    }\n  });\n</script>\n\n{#if fork}\n  <Infobar\n    show={notice.show.current}\n    onDismiss={() => {\n      notice.hide();\n    }}\n    --sui-infobar-message-justify-content=\"center\"\n  >\n    {_('open_authoring.contributing_via_fork', { values: { repo: repoPath } })}\n    {#if forkURL}\n      <Button\n        variant=\"link\"\n        label={_('open_authoring.view_fork')}\n        onclick={() => {\n          openNewTab(forkURL);\n          notice.hide();\n        }}\n      />\n    {/if}\n  </Infobar>\n{/if}\n","'use strict'\n\n// based on https://github.com/TehShrike/deepmerge\n// MIT License\n// Copyright (c) 2012 - 2022 James Halliday, Josh Duff, and other contributors of deepmerge\n\nconst JSON_PROTO = Object.getPrototypeOf({})\n\nfunction defaultIsMergeableObjectFactory () {\n  return function defaultIsMergeableObject (value) {\n    return typeof value === 'object' && value !== null && !(value instanceof RegExp) && !(value instanceof Date)\n  }\n}\n\nfunction deepmergeConstructor (options) {\n  function isNotPrototypeKey (value) {\n    return (\n      value !== 'constructor' &&\n      value !== 'prototype' &&\n      value !== '__proto__'\n    )\n  }\n\n  function cloneArray (value) {\n    let i = 0\n    const il = value.length\n    const result = new Array(il)\n    for (i; i < il; ++i) {\n      result[i] = clone(value[i])\n    }\n    return result\n  }\n\n  function cloneObject (target) {\n    const result = {}\n\n    if (cloneProtoObject && Object.getPrototypeOf(target) !== JSON_PROTO) {\n      return cloneProtoObject(target)\n    }\n\n    const targetKeys = getKeys(target)\n    let i, il, key\n    for (i = 0, il = targetKeys.length; i < il; ++i) {\n      isNotPrototypeKey(key = targetKeys[i]) &&\n        (result[key] = clone(target[key]))\n    }\n    return result\n  }\n\n  function concatArrays (target, source) {\n    const tl = target.length\n    const sl = source.length\n    let i = 0\n    const result = new Array(tl + sl)\n    for (i; i < tl; ++i) {\n      result[i] = clone(target[i])\n    }\n    for (i = 0; i < sl; ++i) {\n      result[i + tl] = clone(source[i])\n    }\n    return result\n  }\n\n  const propertyIsEnumerable = Object.prototype.propertyIsEnumerable\n  function getSymbolsAndKeys (value) {\n    const result = Object.keys(value)\n    const keys = Object.getOwnPropertySymbols(value)\n    for (let i = 0, il = keys.length; i < il; ++i) {\n      propertyIsEnumerable.call(value, keys[i]) && result.push(keys[i])\n    }\n    return result\n  }\n\n  const getKeys = options?.symbols\n    ? getSymbolsAndKeys\n    : Object.keys\n\n  const cloneProtoObject = typeof options?.cloneProtoObject === 'function'\n    ? options.cloneProtoObject\n    : undefined\n\n  const isMergeableObject = typeof options?.isMergeableObject === 'function'\n    ? options.isMergeableObject\n    : defaultIsMergeableObjectFactory()\n\n  const onlyDefinedProperties = options?.onlyDefinedProperties === true\n\n  function isPrimitive (value) {\n    return typeof value !== 'object' || value === null\n  }\n\n  const mergeArray = options && typeof options.mergeArray === 'function'\n    ? options.mergeArray({ clone, deepmerge: _deepmerge, getKeys, isMergeableObject })\n    : concatArrays\n\n  function clone (entry) {\n    return isMergeableObject(entry)\n      ? Array.isArray(entry)\n        ? cloneArray(entry)\n        : cloneObject(entry)\n      : entry\n  }\n\n  function mergeObject (target, source) {\n    const result = {}\n    const targetKeys = getKeys(target)\n    const sourceKeys = getKeys(source)\n    let i, il, key\n    for (i = 0, il = targetKeys.length; i < il; ++i) {\n      isNotPrototypeKey(key = targetKeys[i]) &&\n      (sourceKeys.indexOf(key) === -1) &&\n      (result[key] = clone(target[key]))\n    }\n\n    for (i = 0, il = sourceKeys.length; i < il; ++i) {\n      if (!isNotPrototypeKey(key = sourceKeys[i])) {\n        continue\n      }\n\n      if (key in target) {\n        if (targetKeys.indexOf(key) !== -1) {\n          if (cloneProtoObject && isMergeableObject(source[key]) && Object.getPrototypeOf(source[key]) !== JSON_PROTO) {\n            result[key] = cloneProtoObject(source[key])\n          } else {\n            result[key] = _deepmerge(target[key], source[key])\n          }\n        }\n      } else {\n        if (onlyDefinedProperties && typeof source[key] === 'undefined') {\n          continue\n        }\n        result[key] = clone(source[key])\n      }\n    }\n    return result\n  }\n\n  function _deepmerge (target, source) {\n    if (onlyDefinedProperties && typeof source === 'undefined') {\n      return clone(target)\n    }\n\n    const sourceIsArray = Array.isArray(source)\n    const targetIsArray = Array.isArray(target)\n\n    if (isPrimitive(source)) {\n      return source\n    } else if (!isMergeableObject(target)) {\n      return clone(source)\n    } else if (sourceIsArray && targetIsArray) {\n      return mergeArray(target, source)\n    } else if (sourceIsArray !== targetIsArray) {\n      return clone(source)\n    } else {\n      return mergeObject(target, source)\n    }\n  }\n\n  function _deepmergeAll () {\n    switch (arguments.length) {\n      case 0:\n        return {}\n      case 1:\n        return clone(arguments[0])\n      case 2:\n        return _deepmerge(arguments[0], arguments[1])\n    }\n    let result\n    for (let i = 0, il = arguments.length; i < il; ++i) {\n      result = _deepmerge(result, arguments[i])\n    }\n    return result\n  }\n\n  return options?.all\n    ? _deepmergeAll\n    : _deepmerge\n}\n\nmodule.exports = deepmergeConstructor\nmodule.exports.default = deepmergeConstructor\nmodule.exports.deepmerge = deepmergeConstructor\n\nObject.defineProperty(module.exports, 'isMergeableObject', {\n  get: defaultIsMergeableObjectFactory\n})\n","import { compare, stripSlashes } from '@sveltia/utils/string';\n\nimport { getValidCollections } from '$lib/services/contents/collection';\nimport {\n  getValidCollectionFiles,\n  isValidCollectionFile,\n} from '$lib/services/contents/collection/predicates';\nimport { getLocalePath } from '$lib/services/contents/i18n';\nimport { normalizeI18nConfig } from '$lib/services/contents/i18n/config';\nimport { hasLocalePlaceholder } from '$lib/services/contents/i18n/placeholder';\n\n/**\n * @import { EntryFolderInfo, InternalCmsConfig, InternalLocaleCode } from '$lib/types/private';\n * @import { Collection, CollectionFile, EntryCollection, FileCollection } from '$lib/types/public';\n */\n\n/**\n * Get a map of file paths for the given collection and file.\n * @param {object} args Arguments.\n * @param {Collection} args.collection Collection.\n * @param {CollectionFile} args.file Collection file.\n * @returns {Record<InternalLocaleCode, string>} Map of file paths for each locale.\n */\nexport const getFilePathMap = ({ collection, file }) => {\n  const path = stripSlashes(file.file);\n\n  if (!path.includes('{{locale}}')) {\n    return { _default: path };\n  }\n\n  const _i18n = normalizeI18nConfig(collection, file);\n\n  return Object.fromEntries(\n    _i18n.allLocales.map((locale) => [locale, getLocalePath({ _i18n, locale, path })]),\n  );\n};\n\n/**\n * Get a collection file folder information.\n * @param {Collection} collection Collection.\n * @param {CollectionFile} file Collection file.\n * @returns {EntryFolderInfo | undefined} Collection file folder information.\n */\nexport const getCollectionFileFolder = (collection, file) => {\n  if (!isValidCollectionFile(file)) {\n    return undefined;\n  }\n\n  return {\n    collectionName: collection.name,\n    fileName: file.name,\n    filePathMap: getFilePathMap({ collection, file }),\n  };\n};\n\n/**\n * Compare two entry folders by their file paths. This is used to sort entry folders.\n * @param {EntryFolderInfo} a One entry folder.\n * @param {EntryFolderInfo} b Another entry folder.\n * @returns {number} Comparison result.\n */\nexport const compareFilePath = (a, b) =>\n  compare(Object.values(a.filePathMap ?? {})[0], Object.values(b.filePathMap ?? {})[0]);\n\n/**\n * Get entry collection folders.\n * @param {InternalCmsConfig} config CMS configuration.\n * @returns {EntryFolderInfo[]} Entry folders.\n */\nexport const getEntryCollectionFolders = ({ collections }) =>\n  getValidCollections({ collections, type: 'entry' })\n    .map((collection) => {\n      const { name: collectionName, folder, file } = /** @type {EntryCollection} */ (collection);\n\n      // All the entries are stored in one file, which is matched by its path like a file\n      // collection’s file. A collection file name is not given, as the file is not one\n      if (typeof file === 'string') {\n        return { collectionName, filePathMap: { _default: stripSlashes(file) } };\n      }\n\n      const folderPath = stripSlashes(/** @type {string} */ (folder));\n      const _i18n = normalizeI18nConfig(collection);\n\n      const {\n        allLocales,\n        defaultLocale,\n        omitDefaultLocaleFromFilePath,\n        structureMap: { i18nMultiRootFolder },\n      } = _i18n;\n\n      /**\n       * Get the folder path for the given locale.\n       * @param {InternalLocaleCode} locale Locale code.\n       * @returns {string} Folder path.\n       */\n      const getFolderPath = (locale) => {\n        // The `{{locale}}` placeholder says where the locale folder goes\n        if (hasLocalePlaceholder(folderPath)) {\n          return getLocalePath({ _i18n, locale, path: folderPath });\n        }\n\n        if (i18nMultiRootFolder) {\n          return omitDefaultLocaleFromFilePath && locale === defaultLocale\n            ? folderPath\n            : `${locale}/${folderPath}`;\n        }\n\n        return folderPath;\n      };\n\n      return {\n        collectionName,\n        folderPath,\n        folderPathMap: Object.fromEntries(\n          allLocales.map((locale) => [locale, getFolderPath(locale)]),\n        ),\n      };\n    })\n    .sort((a, b) =>\n      // A collection storing all the entries in one file has a file path instead of a folder path\n      compare(\n        a.folderPath ?? /** @type {Record<string, string>} */ (a.filePathMap)._default,\n        b.folderPath ?? /** @type {Record<string, string>} */ (b.filePathMap)._default,\n      ),\n    );\n\n/**\n * Get file collection folders.\n * @param {InternalCmsConfig} config CMS configuration.\n * @returns {EntryFolderInfo[]} Entry folders.\n */\nexport const getFileCollectionFolders = ({ collections }) =>\n  getValidCollections({ collections, type: 'file' })\n    .flatMap((collection) =>\n      // prettier-ignore\n      (/** @type {FileCollection} */ (collection).files ?? []).map((file) =>\n        getCollectionFileFolder(collection, file),\n      ),\n    )\n    .filter((file) => !!file)\n    .sort(compareFilePath);\n\n/**\n * Get singleton collection folders.\n * @param {InternalCmsConfig} config CMS configuration.\n * @returns {EntryFolderInfo[]} Entry folders.\n */\nexport const getSingletonCollectionFolders = ({ singletons }) => {\n  const files = Array.isArray(singletons) ? getValidCollectionFiles(singletons) : [];\n\n  if (!files.length) {\n    return [];\n  }\n\n  const singletonCollection = { name: '_singletons', files };\n\n  return files\n    .map((file) => getCollectionFileFolder(singletonCollection, file))\n    .filter((file) => !!file)\n    .sort(compareFilePath);\n};\n\n/**\n * Get all entry folders.\n * @param {InternalCmsConfig} config CMS configuration.\n * @returns {EntryFolderInfo[]} Entry folders.\n */\nexport const getAllEntryFolders = (config) => [\n  ...getEntryCollectionFolders(config),\n  ...getFileCollectionFolders(config),\n  ...getSingletonCollectionFolders(config),\n];\n","import deepmerge from '@fastify/deepmerge';\nimport { _ } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { DOCS_BASE_URL } from '$lib/services/app';\nimport {\n  DEV_CONFIG_PATH,\n  DEV_SITE_URL,\n  SCHEMA_URL,\n  SUPPORTED_TYPES,\n} from '$lib/services/config/constants';\nimport { parseTOML, parseYAML } from '$lib/services/contents/file/parse';\nimport { env } from '$lib/services/user/env.svelte';\nimport { isSecureURL } from '$lib/services/utils/networking';\nimport { makeLink } from '$lib/services/utils/string';\n\n/**\n * @typedef {object} ConfigLink\n * @property {string} href File path or URL.\n * @property {string} [type] MIME type.\n */\n\nconst LOAD_CONFIG_DOC_URL = `${DOCS_BASE_URL}/api/initialization#providing-a-full-configuration`;\nconst SCHEMA_TIP_URL = `${DOCS_BASE_URL}/config-basics#validation-and-autocomplete`;\n/**\n * Deep merge any number of config objects, concatenating arrays.\n */\nconst mergeAll = deepmerge({ all: true });\n/**\n * Responses of config files requested ahead of time with {@link prefetchCmsConfig}, keyed by the\n * absolute file URL. Each is consumed once by {@link fetchFile}.\n * @type {Map<string, Promise<Response>>}\n */\nconst prefetchedResponses = new Map();\n\n/**\n * Request the config file at the given URL. A timestamp is appended to the URL to prevent caching\n * issues.\n * @param {URL} url File URL.\n * @returns {Promise<Response>} Response.\n */\nconst requestFile = (url) => {\n  const requestURL = new URL(url);\n\n  requestURL.searchParams.set('_', Date.now().toString());\n\n  return fetch(requestURL);\n};\n\n/**\n * Fetch a single configuration file.\n * @param {object} link Link attributes.\n * @param {string} link.href File path.\n * @param {string} [link.type] MIME type.\n * @param {object} [options] Options.\n * @param {boolean} [options.manualInit] Whether a manual config is provided. This can affect error\n * handling.\n * @param {boolean} [options.showSchemaTip] Whether to show schema help in the browser console.\n * @returns {Promise<object>} Configuration.\n * @throws {Error} When fetching or parsing has failed.\n */\nexport const fetchFile = async (\n  { href, type = 'application/yaml' },\n  { manualInit = false, showSchemaTip } = {},\n) => {\n  /** @type {Response} */\n  let response;\n\n  if (!SUPPORTED_TYPES.includes(type)) {\n    throw new Error(_('config.error.parse_failed'), {\n      cause: new Error(_('config.error.parse_failed_unsupported_type')),\n    });\n  }\n\n  const fetchErrorKey = manualInit\n    ? 'config.error.fetch_failed_with_manual_init'\n    : 'config.error.fetch_failed';\n\n  const errorMessage = makeLink(_(fetchErrorKey), LOAD_CONFIG_DOC_URL);\n\n  try {\n    const url = new URL(href, window.location.href);\n    const prefetched = prefetchedResponses.get(url.href);\n\n    // A response requested ahead of time is used once, so a later reload of the config is fresh\n    prefetchedResponses.delete(url.href);\n    response = await (prefetched ?? requestFile(url));\n  } catch (ex) {\n    throw new Error(errorMessage, { cause: ex });\n  }\n\n  const { ok, status } = response;\n\n  if (!ok) {\n    throw new Error(errorMessage, {\n      cause: new Error(_('config.error.fetch_failed_not_ok', { values: { status } })),\n    });\n  }\n\n  let schemaMissing = false;\n  /** @type {object} */\n  let result;\n\n  try {\n    if (type === 'application/json') {\n      result = await response.json();\n\n      if (isObject(result) && result.$schema !== SCHEMA_URL) {\n        schemaMissing = true;\n      }\n    } else {\n      const text = await response.text();\n\n      if (type === 'application/toml') {\n        result = parseTOML(text);\n\n        if (!text.includes(`#:schema ${SCHEMA_URL}`)) {\n          schemaMissing = true;\n        }\n      } else {\n        result = parseYAML(text, { merge: true, maxAliasCount: -1 });\n\n        if (!text.includes(`# yaml-language-server: $schema=${SCHEMA_URL}`)) {\n          schemaMissing = true;\n        }\n      }\n    }\n  } catch (ex) {\n    throw new Error(_('config.error.parse_failed'), { cause: ex });\n  }\n\n  if (!isObject(result)) {\n    throw new Error(_('config.error.parse_failed'), {\n      cause: new Error(_('config.error.parse_failed_invalid_object')),\n    });\n  }\n\n  if (showSchemaTip && schemaMissing) {\n    // eslint-disable-next-line no-console\n    console.info(_('config.schema_tip', { values: { link: SCHEMA_TIP_URL } }));\n  }\n\n  return result;\n};\n\n/**\n * Get the path to the configuration file. Depending on the server or framework configuration, a\n * trailing slash may be removed from the CMS `/admin/` URL. In that case, we need to determine the\n * correct path to the configuration file.\n * @param {string} path Current `location.pathname` starting with a slash, like `/admin/`, `/admin`,\n * or `/admin/index.html`.\n * @returns {string} Path to the configuration file. It’s always on the same origin as the page.\n */\nexport const getConfigPath = (path) => {\n  // Collapse leading slashes, because a path like `//evil.example/` would otherwise resolve to a\n  // protocol-relative URL on another host, where anyone could serve a config file that points the\n  // backend at their own server and receives the cached token when the CMS signs in automatically\n  path = path.replace(/^\\/+/, '/');\n\n  // If the path ends with a slash, like `/admin/`, we can safely assume it is a directory and\n  // append `config.yml`.\n  if (path.endsWith('/')) {\n    return `${path}config.yml`;\n  }\n\n  const parts = path.split('/');\n  const lastPart = parts.pop();\n\n  // If the last part of the path contains a dot, like `/admin/index.html`, we assume it is a file\n  // and append `config.yml` to the directory part of the path. For example, `/admin/index.html`\n  // becomes `/admin/config.yml`.\n  if (lastPart?.includes('.')) {\n    return `${parts.join('/')}/config.yml`;\n  }\n\n  // If the last part does not contain a dot, we assume it is a directory and append `config.yml`.\n  // For example, `/admin` becomes `/admin/config.yml`.\n  return `${path}/config.yml`;\n};\n\n/**\n * Verify that all provided links are in a secure context. A secure context is defined as either an\n * HTTPS URL or a localhost address.\n * @param {ConfigLink[]} links Links to verify.\n * @returns {boolean} True if all links are secure, false otherwise.\n */\nexport const verifyLinksAreSecure = (links) => {\n  const { origin } = window.location;\n\n  return links.every(({ href }) => isSecureURL(href, origin));\n};\n\n/**\n * Get the links to the config files: the `<link rel=\"cms-config-url\">` elements on the page, or\n * the default file next to the admin page if there is none. During development, the config file\n * is loaded from the local live site instead.\n * @returns {ConfigLink[]} Links.\n */\nexport const getConfigLinks = () => {\n  const links = /** @type {HTMLLinkElement[]} */ ([\n    ...document.querySelectorAll('link[rel=\"cms-config-url\"]'),\n  ]).map(\n    // A link element without the `type` attribute has an empty `type`, which has to fall back to\n    // the default type like a missing one\n    ({ href, type }) => /** @type {ConfigLink} */ ({ href, type: type || undefined }),\n  );\n\n  if (!links.length) {\n    links.push(\n      DEV_SITE_URL\n        ? { href: `${DEV_SITE_URL}${DEV_CONFIG_PATH}` }\n        : { href: getConfigPath(window.location.pathname) },\n    );\n  }\n\n  return links;\n};\n\n/**\n * Start requesting the config files, so the response is on its way while the app is being mounted\n * rather than requested afterwards. This is called as soon as the CMS is initialized. The links\n * are resolved again when the config is actually loaded, and a response is only reused if it was\n * requested for the same URL, so a `<link>` that appears later is still honoured. Any failure is\n * reported then as well.\n */\nexport const prefetchCmsConfig = () => {\n  const links = getConfigLinks();\n\n  if (!verifyLinksAreSecure(links)) {\n    return;\n  }\n\n  links.forEach(({ href }) => {\n    try {\n      const url = new URL(href, window.location.href);\n\n      if (!prefetchedResponses.has(url.href)) {\n        const promise = requestFile(url);\n\n        // Reported by `fetchFile()` when the response is consumed\n        promise.catch(() => {});\n        prefetchedResponses.set(url.href, promise);\n      }\n    } catch {\n      // An invalid URL is reported by `fetchFile()` as well\n    }\n  });\n};\n\n/**\n * Fetch the YAML/JSON CMS configuration file(s) and return a parsed, merged object.\n * @param {object} [options] Options.\n * @param {boolean} [options.manualInit] Whether a manual config is provided. This can affect error\n * handling.\n * @returns {Promise<object>} Configuration.\n * @throws {Error} When fetching or parsing has failed.\n */\nexport const fetchCmsConfig = async ({ manualInit = false } = {}) => {\n  const links = getConfigLinks();\n\n  if (!verifyLinksAreSecure(links)) {\n    throw new Error(_('config.error.insecure_urls', { values: { count: links.length } }));\n  }\n\n  const showSchemaTip = env.isLocalHost && !manualInit && links.length === 1;\n  /** @type {Record<string, any>[]} */\n  let objects;\n\n  try {\n    objects = await Promise.all(\n      links.map((link) => fetchFile(link, { manualInit, showSchemaTip })),\n    );\n  } finally {\n    // Drop a response requested ahead of time for a file that wasn’t named after all\n    prefetchedResponses.clear();\n  }\n\n  if (objects.length === 1) {\n    return objects[0];\n  }\n\n  return mergeAll(...objects);\n};\n","import { _ } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { COMPATIBILITY_URL } from '$lib/services/api/compatibility';\nimport { DOCS_BASE_URL } from '$lib/services/app';\nimport { unsupportedBackends, validBackendNames } from '$lib/services/backends';\nimport {\n  FORGEJO_BACKEND_NAME,\n  isGiteaBackendName,\n} from '$lib/services/backends/git/gitea/constants';\nimport { gitBackendServices } from '$lib/services/backends/git/services';\nimport { normalizeRootDir } from '$lib/services/backends/root-dir';\nimport { warnDeprecation } from '$lib/services/config/deprecations';\nimport { addMessage, checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\nimport { isHttpURL, makeLink } from '$lib/services/utils/string';\nimport {\n  getPublishMode,\n  isWorkflowConfigured,\n  isWorkflowMode,\n} from '$lib/services/workflow/config';\n\n/**\n * @import { CmsConfig, GitBackend } from '$lib/types/public';\n * @import { ConfigParserCollectors, UnsupportedOption } from '$lib/types/private';\n */\n\n/**\n * Unsupported options for Relation fields.\n * @type {UnsupportedOption[]}\n */\nconst UNSUPPORTED_OPTIONS = [\n  // Sveltia CMS always uses GraphQL for Git backends, so this option is not applicable.\n  { type: 'warning', prop: 'use_graphql', strKey: 'unsupported_ignored_option' },\n];\n\nconst UNSUPPORTED_BACKEND_SUGGESTION_URL = `${DOCS_BASE_URL}/backends#supported-backends`;\nconst AUTH_DOC_URL = `${DOCS_BASE_URL}/backends/BACKEND_NAME#authentication`;\n/**\n * Backend names whose documentation page has a different slug.\n * @type {Record<string, string>}\n */\nconst BACKEND_DOC_SLUGS = { gitea: 'gitea-forgejo', forgejo: 'gitea-forgejo' };\nconst OPEN_AUTHORING_DOC_URL = `${DOCS_BASE_URL}/workflows/open`;\n/**\n * Backend options that hold the URL of an API or authentication server and have to be absolute. A\n * relative or scheme-less URL would either make the backend throw while it’s being set up, leaving\n * the user unable to sign in without any explanation, or send the requests to the CMS origin.\n */\nconst URL_OPTIONS = ['api_root', 'graphql_api_root', 'base_url'];\n/**\n * Regular expression matching a path segment Git doesn’t allow in a branch name: one starting with\n * a dot or ending with `.lock`, or one containing a control character, a space, any of `~^:?*[\\`\n * or `@{`.\n * @see https://git-scm.com/docs/git-check-ref-format\n */\n// eslint-disable-next-line no-control-regex\nconst INVALID_BRANCH_SEGMENT_REGEX = /^\\.|\\.lock$|[\\x00-\\x20\\x7f~^:?*[\\\\]|@\\{/;\n\n/**\n * Check whether the given directory path can be part of a Git branch name.\n * @param {string} path Normalized directory path.\n * @returns {boolean} Result.\n */\nconst isValidBranchPath = (path) =>\n  path.split('/').every((segment) => !INVALID_BRANCH_SEGMENT_REGEX.test(segment));\n\n/**\n * Parse and validate the backend configuration from the site config.\n * @param {CmsConfig} cmsConfig Raw CMS configuration.\n * @param {ConfigParserCollectors} collectors Collectors.\n * @throws {Error} If there is an error in the backend config.\n */\nexport const parseBackendConfig = (cmsConfig, collectors) => {\n  const { backend } = cmsConfig;\n  const { errors, warnings } = collectors;\n\n  if (!isObject(backend)) {\n    errors.add(_('config.error.missing_backend'));\n\n    return;\n  }\n\n  const { name } = backend;\n\n  if (!name) {\n    errors.add(_('config.error.missing_backend_name'));\n\n    return;\n  }\n\n  if (!validBackendNames.includes(name)) {\n    const _backend = unsupportedBackends[name];\n    const type = _backend ? (_backend.deprecated ? 'deprecated' : 'known') : 'custom';\n    const label = _backend?.label;\n\n    const message = makeLink(\n      _(`config.error.unsupported_${type}_backend`, { values: { name: label } }),\n      COMPATIBILITY_URL,\n    );\n\n    const suggestion = makeLink(\n      _('config.error.unsupported_backend_suggestion'),\n      UNSUPPORTED_BACKEND_SUGGESTION_URL,\n    );\n\n    errors.add(`${message} ${suggestion}`);\n\n    return;\n  }\n\n  const { root_dir: rootDir } = backend;\n\n  if (typeof rootDir === 'string') {\n    // The CMS can’t see anything outside the repository, so a root directory that climbs out of it\n    // could only ever lead to a confusing error later\n    if (rootDir.split('/').includes('..')) {\n      errors.add(_('config.error.invalid_root_dir'));\n    } else if (isWorkflowConfigured(cmsConfig) && !isValidBranchPath(normalizeRootDir(rootDir))) {\n      // Editorial Workflow names its branches after the directory, which Git would refuse\n      errors.add(_('config.error.invalid_root_dir_branch'));\n    }\n  }\n\n  if (name in gitBackendServices) {\n    const {\n      repo,\n      automatic_deployments: autoDeploy,\n      auth_methods: authMethods,\n      // @ts-ignore GitHub/GitLab only\n      auth_type: authType,\n      // @ts-ignore GitLab/Gitea/Forgejo only\n      app_id: appId,\n      open_authoring: openAuthoring,\n      // @ts-ignore GitHub only\n      auth_scope: authScope,\n      api_root: apiRoot,\n    } = /** @type {GitBackend} */ (backend);\n\n    if (Array.isArray(authMethods) && !authMethods.length) {\n      errors.add(_('config.error.no_auth_methods'));\n    }\n\n    // A list of scopes can add `workflow`, which is no use on its own: without a repository scope\n    // the CMS can’t write to the repository or a fork of it. The schema only checks each scope\n    if (\n      name === 'github' &&\n      Array.isArray(authScope) &&\n      !authScope.some((scope) => scope === 'repo' || scope === 'public_repo')\n    ) {\n      errors.add(_('config.error.auth_scope_no_repo'));\n    }\n\n    const allowTokenAuth = !authMethods || authMethods.includes('token');\n    const authDocURL = AUTH_DOC_URL.replace('BACKEND_NAME', BACKEND_DOC_SLUGS[name] ?? name);\n\n    if (repo === undefined) {\n      errors.add(_('config.error.missing_repository'));\n    } else if (typeof repo !== 'string' || !/^[^/:]+(?:\\/[^/:]+)+$/.test(repo)) {\n      // A configured but malformed repository is a separate problem from a missing one, and\n      // reporting both for the same option only reads as noise\n      errors.add(_('config.error.invalid_repository'));\n    }\n\n    // The Forgejo backend has no default instance: unlike the Gitea backend, which falls back to\n    // Gitea.com, it derives the instance URL from the API root, as Decap CMS does\n    if (name === FORGEJO_BACKEND_NAME && apiRoot === undefined) {\n      errors.add(_('config.error.missing_api_root'));\n    }\n\n    if (authType === 'implicit') {\n      errors.add(makeLink(_('config.error.oauth_implicit_flow'), authDocURL));\n    }\n\n    if (name === 'github' && authType === 'pkce') {\n      errors.add(makeLink(_('config.error.github_pkce_unsupported'), authDocURL));\n    }\n\n    if (name === 'gitlab' && authType === 'pkce' && !appId) {\n      errors.add(_('config.error.oauth_no_app_id'));\n    }\n\n    // Sveltia CMS Additions has no default location: each site deploys its own\n    if (\n      name === 'github' &&\n      authType === 'additions' &&\n      // @ts-ignore GitHub only\n      !(typeof backend.base_url === 'string' && URL.canParse(backend.base_url))\n    ) {\n      errors.add(_('config.error.additions_no_base_url'));\n    }\n\n    if (openAuthoring) {\n      // Open Authoring turns each change into a pull request from the contributor’s fork, so it\n      // only makes sense on top of Editorial Workflow or Preview Workflow. The site-level option is\n      // what counts here: a collection can opt out with its own `publish_mode`, but that only\n      // affects maintainers, who write to the configured repository; a contributor’s fork always\n      // goes through pull requests\n      if (!isWorkflowMode(getPublishMode({ cmsConfig }))) {\n        errors.add(makeLink(_('config.error.open_authoring_no_workflow'), OPEN_AUTHORING_DOC_URL));\n      }\n\n      // The default scope grants access to every repository the contributor owns, including their\n      // private ones. That’s a lot to ask of someone who just wants to fix a typo, and a public\n      // repository doesn’t need it. The visibility of the repository isn’t known until someone\n      // signs in, so this can’t be decided automatically. GitLab has no equivalent option: its\n      // single `api` scope covers everything the CMS does. Gitea/Forgejo scopes are already\n      // limited to what the CMS uses\n      if (name === 'github' && authScope === undefined) {\n        // Warnings are logged to the console for whoever set the CMS up, so this is plain English\n        // with a plain URL rather than a localized string with a link in it\n        warnings.add(\n          'The `open_authoring` option is enabled without `auth_scope`, so contributors are ' +\n            'asked for access to all their repositories, including private ones. Set ' +\n            '`auth_scope: public_repo` if your repository is public, or `auth_scope: repo` to ' +\n            `confirm the broader scope is needed. ${OPEN_AUTHORING_DOC_URL}`,\n        );\n      }\n    }\n\n    // Gitea requires an app ID for OAuth authentication, but also supports token-based sign-in,\n    // which doesn’t require one. If no app ID is configured and token auth is allowed (the\n    // default), we issue a warning and disable the OAuth Sign In button in the UI — users can still\n    // sign in with a token. If token auth is explicitly disabled as well, we issue an error because\n    // there is no working sign-in method available.\n    // @see https://github.com/sveltia/sveltia-cms/issues/721\n    if (isGiteaBackendName(name) && !appId) {\n      if (allowTokenAuth) {\n        warnings.add(_('config.warning.oauth_no_app_id'));\n      } else {\n        errors.add(_('config.error.oauth_no_app_id'));\n      }\n    }\n\n    URL_OPTIONS.forEach((option) => {\n      const url = /** @type {Record<string, any>} */ (backend)[option];\n\n      // A value of another type is reported against the JSON schema\n      if (typeof url === 'string' && !isHttpURL(url)) {\n        addMessage({\n          strKey: 'invalid_url_option',\n          values: { option, url },\n          context: { cmsConfig },\n          collectors,\n        });\n      }\n    });\n\n    // @todo Remove the option prior to the 1.0 release.\n    if (autoDeploy !== undefined) {\n      warnDeprecation('automatic_deployments');\n    }\n\n    checkUnsupportedOptions({\n      UNSUPPORTED_OPTIONS,\n      config: backend,\n      context: { cmsConfig },\n      collectors,\n    });\n  }\n};\n","import { customFileFormatRegistry } from '$lib/services/api/registries';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { storesNumber } from '$lib/services/contents/fields/number/helpers';\nimport { detectFileExtension, detectFileFormat } from '$lib/services/contents/file/config';\nimport { EXTENSION_FORMAT_MAP, MARKDOWN_EXTENSIONS } from '$lib/services/contents/file/constants';\n\n/**\n * @import {\n * BodyFieldOptions,\n * Field,\n * FileExtension,\n * FileFormat,\n * NumberField,\n * } from '$lib/types/public';\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n */\n\n/**\n * Field types that can be used for the single `body` field special case.\n * @type {string[]}\n */\nconst BODY_FIELD_TYPES = ['code', 'markdown', 'richtext', 'text'];\n/**\n * Known file formats.\n * @type {FileFormat[]}\n */\nconst KNOWN_FORMATS = ['yaml', 'toml', 'json'];\n\n/**\n * Check if there is a mismatch between the file extension and format.\n * @param {FileExtension | undefined} extension File extension.\n * @param {FileFormat | undefined} format File format.\n * @param {Field[]} [fields] Fields.\n * @returns {boolean} Whether there is a mismatch between the file extension and format.\n * @see https://decapcms.org/docs/configuration-options/#extension-and-format\n * @see https://sveltiacms.app/en/docs/collections/entries/formats\n */\nexport const isFormatMismatch = (extension, format, fields = []) => {\n  // If either is undefined, there’s no mismatch\n  if (!extension || !format) {\n    return false;\n  }\n\n  // Raw format never mismatches, and neither does a custom format registered with\n  // `CMS.registerCustomFormat()`, which can take any extension, including `md`. Custom formats are\n  // registered before the configuration is parsed\n  if (format === 'raw' || customFileFormatRegistry.has(format)) {\n    return false;\n  }\n\n  const isFrontMatterFormat = format.endsWith('-frontmatter') || format === 'frontmatter';\n\n  // Special case: single `body` code or rich text field in a front-matter format. Treat as no\n  // mismatch to allow editing the raw file content directly, e.g. .json, .yaml, .toml files.\n  if (isFrontMatterFormat && fields.length === 1) {\n    const [{ name, widget = 'string' }] = fields;\n\n    if (name === 'body' && BODY_FIELD_TYPES.includes(widget)) {\n      return false;\n    }\n  }\n\n  // Normalize extensions (yml and yaml are interchangeable)\n  const normalizedExtension = extension === 'yml' ? 'yaml' : extension;\n  // Normalize formats (yml and yaml are interchangeable)\n  const normalizedFormat = format === 'yml' ? 'yaml' : format;\n\n  // For md/markdown/mdx extensions, only -frontmatter formats are valid\n  if (MARKDOWN_EXTENSIONS.includes(normalizedExtension)) {\n    // Valid formats: 'frontmatter' (auto-detect) or any *-frontmatter format\n    return !isFrontMatterFormat;\n  }\n\n  // Any other extension, such as `html` or `njk`, works with every front-matter format, like in\n  // Decap CMS, where the `format` option takes precedence over the extension. The exceptions are\n  // the data file extensions (`yaml`, `toml`, `json`), which only work with the matching\n  // front-matter format, if any, and `astro`, whose front matter is JavaScript, not YAML\n  if (isFrontMatterFormat) {\n    const extensionFormat = EXTENSION_FORMAT_MAP[normalizedExtension];\n\n    return (\n      extensionFormat !== undefined &&\n      extensionFormat !== normalizedFormat.replace('-frontmatter', '')\n    );\n  }\n\n  // For known formats, ensure extension matches (yaml/toml/json)\n  // For custom extensions, only validate against known formats they explicitly don’t support\n  if (KNOWN_FORMATS.includes(normalizedFormat)) {\n    // If format is yaml/toml/json, extension should match or be custom\n    return KNOWN_FORMATS.includes(normalizedExtension) && normalizedExtension !== normalizedFormat;\n  }\n\n  // Unknown format - don’t enforce mismatch\n  return false;\n};\n\n/**\n * Field types whose value is never text, so it can’t be stored as the body below the front matter.\n */\nconst NON_TEXT_FIELD_TYPES = ['boolean', 'keyvalue', 'list', 'number', 'object'];\n\n/**\n * Check whether the given field holds something other than text: an object, an array, a number or\n * a boolean.\n * @param {Field} field Field configuration.\n * @returns {boolean} Result.\n */\nconst isNonTextField = (field) => {\n  const { widget = 'string' } = field;\n\n  // A Number field with a `*/string` value type stores what the user typed as a string\n  if (widget === 'number') {\n    // prettier-ignore\n    return !(/** @type {NumberField} */ (field).value_type ?? '').endsWith('/string');\n  }\n\n  // A Compute field holds a number with the `int` and `float` value types, and a string otherwise\n  if (widget === 'compute') {\n    return storesNumber(field);\n  }\n\n  return NON_TEXT_FIELD_TYPES.includes(widget) || isFieldMultiple(field);\n};\n\n/**\n * Check that the field storing the body below the front matter, `body` by default, holds text. Only\n * a string can be written there, so any other value would be lost on save.\n * @param {object} args Arguments.\n * @param {FileExtension} [args.extension] Developer-defined file extension.\n * @param {FileFormat} [args.format] Developer-defined file format.\n * @param {BodyFieldOptions} [args.bodyField] Developer-defined `body_field` option.\n * @param {Field[]} [args.fields] Fields of the collection or collection file.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkBodyField = ({ extension, format, bodyField, fields, context, collectors }) => {\n  const { key = 'body', inline = false } = bodyField ?? {};\n  const field = Array.isArray(fields) ? fields.find(({ name }) => name === key) : undefined;\n\n  // The type of the options is checked against the JSON schema\n  if (inline || !field || typeof key !== 'string') {\n    return;\n  }\n\n  const _format = detectFileFormat({\n    extension: detectFileExtension({ extension, format }),\n    format,\n  });\n\n  if ((_format === 'frontmatter' || _format.endsWith('-frontmatter')) && isNonTextField(field)) {\n    addMessage({\n      strKey: 'front_matter_body_field_not_text',\n      // A field without the `widget` option is a String field, which holds text\n      values: { name: key, widget: /** @type {string} */ (field.widget) },\n      context: { ...context, typedKeyPath: key },\n      collectors,\n    });\n  }\n};\n","import { METADATA_KEYS } from '$lib/services/contents/collection/view/table-keys';\nimport { isCodeValueKey } from '$lib/services/contents/fields/code/helpers';\nimport { DEFAULT_CANONICAL_SLUG } from '$lib/services/contents/i18n/config/constants';\nimport { mergeI18nConfigs } from '$lib/services/contents/i18n/config/merge';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import { ConfigParserContext, InternalSingletonCollection } from '$lib/types/private';\n * @import {\n * CmsConfig,\n * CodeField,\n * Collection,\n * CollectionDivider,\n * CollectionFile,\n * EntryCollection,\n * Field,\n * FieldKeyPath,\n * FieldWithSubFields,\n * FieldWithTypes,\n * ListFieldWithSubField,\n * } from '$lib/types/public';\n */\n\n/**\n * Get the canonical slug key of the given collection or file. When i18n is enabled, the key —\n * `translationKey` by default — is added to the content of each localized entry, allowing entries\n * to be matched across locales. It can therefore be used wherever a field key path is expected,\n * such as the `value_field` of a Relation field or the `filter` option of a collection, even though\n * it’s not defined as a field.\n * @param {object} args Arguments.\n * @param {CmsConfig | undefined} args.cmsConfig The site configuration.\n * @param {Collection | CollectionDivider | InternalSingletonCollection} args.collection Collection.\n * @param {CollectionFile} [args.file] Collection file, if the collection is a file collection.\n * @returns {string | undefined} The key, or `undefined` if i18n is not enabled for the collection\n * or file.\n * @see https://sveltiacms.app/en/docs/i18n/slugs#localizing-entry-slugs\n */\nexport const getCanonicalSlugKey = ({ cmsConfig, collection, file }) => {\n  const config = mergeI18nConfigs({ cmsConfig, collection, file });\n\n  if (!config?.locales?.length) {\n    return undefined;\n  }\n\n  return config.canonical_slug?.key ?? DEFAULT_CANONICAL_SLUG.key;\n};\n\n/**\n * Regular expression to match the explicit variable type in a key path segment, e.g. the `<button>`\n * part of `body<button>`.\n * @type {RegExp}\n */\nconst EXPLICIT_TYPE_REGEX = /<[^>]+>$/;\n\n/**\n * Get the sub fields of the given field configuration: the single subfield of a List field, the\n * subfields of a List or Object field, or the subfields of all the variable types.\n * @param {Field} field Field configuration.\n * @returns {Field[]} Sub fields. An empty array if the field doesn’t have any.\n */\nexport const getSubFields = (field) => {\n  const { field: subField } = /** @type {ListFieldWithSubField} */ (field);\n  const { fields: subFields } = /** @type {FieldWithSubFields} */ (field);\n  const { types, typeKey = 'type' } = /** @type {FieldWithTypes} */ (field);\n\n  if (subField) {\n    return [subField];\n  }\n\n  if (subFields) {\n    return subFields;\n  }\n\n  if (types) {\n    return [\n      // Any of the types could be used for an item, so accept a subfield of any of them\n      ...types.flatMap(({ fields: typeFields = [] }) => typeFields),\n      // The type key, e.g. `blocks.0.type`, is a valid property although it’s not a field\n      /** @type {Field} */ ({ name: typeKey }),\n    ];\n  }\n\n  return [];\n};\n\n/**\n * Check if the given field stores its value as an object whose keys aren’t subfields, so a key path\n * can point to one of its keys: any key of a KeyValue field, or the code or language key of a Code\n * field without the `output_code_only` option, e.g. `meta.author` or `snippet.lang`.\n * @param {Field} field Field configuration.\n * @param {string} key Key.\n * @returns {boolean} Result.\n */\nconst hasValueKey = (field, key) => {\n  const { widget: fieldType = 'string' } = field;\n\n  if (fieldType === 'keyvalue') {\n    return true;\n  }\n\n  return fieldType === 'code' && isCodeValueKey(/** @type {CodeField} */ (field), key);\n};\n\n/**\n * Find the fields the given key path can point to in the given field list. This is a lenient\n * version of `getField()`, which lives in the runtime module graph (stores, backends) this parser\n * runs before, and which needs entry values to resolve variable types. Without those values, a\n * name shared by the subfields of several variable types resolves to each of them. A key path\n * pointing to a key of a KeyValue or Code field’s value, e.g. `meta.author`, resolves to the field,\n * as the value is stored under that key path.\n * @param {Field[]} fields Field list.\n * @param {FieldKeyPath} keyPath Field key path, e.g. `author.name` or `images.0.src`.\n * @returns {Field[]} Field configurations. An empty array if the field is not defined.\n */\nexport const findFields = (fields, keyPath) => {\n  /** @type {Field[]} */\n  let matches = [];\n  let isFirstSegment = true;\n  let isValueKey = false;\n\n  const isResolved = keyPath.split('.').every((segment) => {\n    // Strip the explicit variable type, which is not part of the field name\n    const key = segment.replace(EXPLICIT_TYPE_REGEX, '');\n\n    // A key of a field’s value has nothing below it, not even a list item\n    if (isValueKey) {\n      return false;\n    }\n\n    // A list item index (`authors.0`) or wildcard (`images.*.src`) doesn’t point to a field itself,\n    // so stay at the same level\n    if (!key || key === '*' || isNumeric(key)) {\n      return true;\n    }\n\n    const candidates = isFirstSegment ? fields : matches.flatMap((field) => getSubFields(field));\n    const valueKeyFields = isFirstSegment ? [] : matches.filter((field) => hasValueKey(field, key));\n\n    isFirstSegment = false;\n    matches = candidates.filter(({ name }) => name === key);\n\n    if (!matches.length && valueKeyFields.length) {\n      matches = valueKeyFields;\n      isValueKey = true;\n    }\n\n    return !!matches.length;\n  });\n\n  return isResolved ? matches : [];\n};\n\n/**\n * Check if the given key path points to a field defined in the given field list.\n * @param {Field[]} fields Field list.\n * @param {FieldKeyPath} keyPath Field key path, e.g. `author.name` or `images.0.src`.\n * @returns {boolean} Whether the field is defined.\n */\nexport const hasField = (fields, keyPath) => !!findFields(fields, keyPath).length;\n\n/**\n * Get the top-level fields of the entry a field being parsed belongs to: those of the collection\n * file, or the index file, or the collection. These are the fields an option that refers to the\n * entry’s fields, such as a template, can name.\n * @param {ConfigParserContext} context Context.\n * @returns {Field[] | undefined} Fields, or `undefined` outside a collection, e.g. for a field of a\n * custom editor component.\n */\nexport const getRootFields = ({ collection, collectionFile, isIndexFile }) => {\n  if (collectionFile) {\n    return collectionFile.fields;\n  }\n\n  if (!collection || 'files' in collection) {\n    return undefined;\n  }\n\n  const { fields, index_file: indexFile } = /** @type {EntryCollection} */ (collection);\n\n  if (isIndexFile && typeof indexFile === 'object' && indexFile.fields) {\n    return indexFile.fields;\n  }\n\n  return fields;\n};\n\n/**\n * Check if the given sort key can be used without referring to a field, in the `sortable_fields`\n * option of a collection or the `sort_by` option of a Relation field: an entry metadata key like\n * `slug`, `_manual` for the manual order, the canonical slug key, which is part of the content\n * without being a field, or the reorder field, which may not be defined under `fields`.\n * @param {string} key Sort key.\n * @param {object} args Arguments.\n * @param {string | undefined} args.canonicalSlugKey Canonical slug key of the collection.\n * @param {string | undefined} args.orderFieldKey Reorder field key of the collection.\n * @returns {boolean} Result.\n */\nexport const isNonFieldSortKey = (key, { canonicalSlugKey, orderFieldKey }) =>\n  METADATA_KEYS.includes(key) ||\n  key === '_manual' ||\n  key === canonicalSlugKey ||\n  key === orderFieldKey;\n","import {\n  DEFAULT_TRANSFORMATION_REGEX,\n  FIELD_TAG_PREFIX_REGEX,\n} from '$lib/services/common/template/constants';\nimport { getTemplateTags } from '$lib/services/common/template/tags';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { findFields, hasField } from '$lib/services/config/parser/utils/fields';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { MEDIA_FIELD_TYPES } from '$lib/services/contents/fields';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import { Field } from '$lib/types/public';\n */\n\n/**\n * Check that the fields an option refers to are defined, and report each one that isn’t. The\n * option is either a template, whose `{{tags}}` are checked, or a list of key paths.\n * @param {object} args Arguments.\n * @param {string} args.option Name of the option, for the message.\n * @param {any} [args.template] Template to check, e.g. `{{year}}-{{title}}`. A value of another\n * type is reported against the JSON schema, so it’s ignored here.\n * @param {any} [args.keyPaths] Key path or key paths to check instead of a template.\n * @param {string[]} [args.specialTags] Template tags that the runtime handles without reading a\n * field, such as `slug`. A tag with the `fields.` prefix always refers to a field, so `slug` can be\n * special while `fields.slug` is the field of that name.\n * @param {boolean} [args.prefixedOnly] Whether only the tags with the explicit `fields.` prefix\n * refer to fields, as in a template whose bare tags mean something else.\n * @param {'error' | 'warning'} [args.type] Type of the message reported for a missing field.\n * Defaults to an error.\n * @param {string} [args.strKey] Key of the message reported for a missing field. The message can\n * use the `option` and `name` values.\n * @param {Field[]} args.fields Fields the option can refer to.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkFieldReferences = ({\n  option,\n  template,\n  keyPaths,\n  specialTags = [],\n  prefixedOnly = false,\n  type,\n  strKey = 'option_field_not_found',\n  fields,\n  context,\n  collectors,\n}) => {\n  /** @type {string[]} */\n  const references = [];\n\n  if (typeof template === 'string') {\n    getTemplateTags(template).forEach(({ content: tag, name: keyPath }) => {\n      if (\n        DEFAULT_TRANSFORMATION_REGEX.test(tag) ||\n        (prefixedOnly && !FIELD_TAG_PREFIX_REGEX.test(keyPath)) ||\n        specialTags.includes(keyPath)\n      ) {\n        return;\n      }\n\n      references.push(keyPath);\n    });\n  } else {\n    /** @type {any[]} */ (Array.isArray(keyPaths) ? keyPaths : [keyPaths]).forEach((keyPath) => {\n      if (typeof keyPath === 'string' && keyPath) {\n        references.push(keyPath);\n      }\n    });\n  }\n\n  references.forEach((keyPath) => {\n    if (!hasField(fields, stripFieldTagPrefix(keyPath))) {\n      addMessage({\n        type,\n        strKey,\n        values: { option, name: keyPath },\n        context,\n        collectors,\n      });\n    }\n  });\n};\n\n/**\n * Check that the `thumbnail` option of a List or Object field names an Image or File subfield. Any\n * other field type is skipped at runtime, so no thumbnail is shown.\n * @param {object} args Arguments.\n * @param {any} args.thumbnail The `thumbnail` option. A value of another type is reported against\n * the JSON schema, so it’s ignored here.\n * @param {Field[]} args.fields Subfields the option can refer to.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkThumbnailField = ({ thumbnail, fields, context, collectors }) => {\n  checkFieldReferences({ option: 'thumbnail', keyPaths: thumbnail, fields, context, collectors });\n\n  if (typeof thumbnail !== 'string' || !thumbnail) {\n    return;\n  }\n\n  // A name shared by the subfields of several variable types resolves to each of them, and the\n  // runtime looks the field up per item type, so any Image or File field among them will do\n  const fieldTypes = findFields(fields, stripFieldTagPrefix(thumbnail)).map(\n    ({ widget: fieldType = 'string' }) => fieldType,\n  );\n\n  // A missing field is reported above\n  if (fieldTypes.length && !fieldTypes.some((fieldType) => MEDIA_FIELD_TYPES.includes(fieldType))) {\n    addMessage({\n      strKey: 'thumbnail_field_not_media',\n      values: { name: thumbnail, widget: fieldTypes[0] },\n      context,\n      collectors,\n    });\n  }\n};\n","import { DATE_TIME_TEMPLATE_REGEX } from '$lib/services/common/template/constants';\nimport { checkFieldReferences } from '$lib/services/config/parser/utils/references';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import { Field } from '$lib/types/public';\n */\n\n/**\n * Check the date and time tags in the `preview_path` option. A template with such tags needs a\n * DateTime field to read them from, and without one the preview link is dropped without\n * explanation, which looks the same as a collection that has no preview link configured at all.\n * @param {object} args Arguments.\n * @param {string} args.pathTemplate The `preview_path` option value.\n * @param {string} [args.dateFieldName] The `preview_path_date_field` option value.\n * @param {Field[]} args.fields Fields the template can read a date from.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst checkDateTimeTags = ({ pathTemplate, dateFieldName, fields, context, collectors }) => {\n  if (!DATE_TIME_TEMPLATE_REGEX.test(pathTemplate)) {\n    return;\n  }\n\n  // Mirrors how `extractDateTime()` looks the field up at runtime: a named field must be a DateTime\n  // field, and without a name the first DateTime field is used\n  const found = dateFieldName\n    ? fields.some(({ widget, name }) => widget === 'datetime' && name === dateFieldName)\n    : fields.some(({ widget }) => widget === 'datetime');\n\n  if (found) {\n    return;\n  }\n\n  addMessage({\n    type: 'warning',\n    strKey: dateFieldName ? 'preview_path_date_field_not_found' : 'preview_path_no_date_field',\n    values: { name: dateFieldName },\n    context,\n    collectors,\n  });\n};\n\n/**\n * Validate the `preview_path` option against the fields available to fill it in.\n *\n * Only the configuration can be checked here. A field that exists but holds no value produces the\n * same missing link, and that isn’t known until an entry is loaded.\n * @param {object} args Arguments.\n * @param {string} [args.pathTemplate] The `preview_path` option value.\n * @param {string} [args.dateFieldName] The `preview_path_date_field` option value.\n * @param {Field[]} args.fields Fields the template can read a value from.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkPreviewPath = ({ pathTemplate, dateFieldName, fields, context, collectors }) => {\n  if (!pathTemplate) {\n    return;\n  }\n\n  checkDateTimeTags({ pathTemplate, dateFieldName, fields, context, collectors });\n  // A tag that names no field can’t be filled in, and the preview link is dropped rather than\n  // pointing at a URL built from a missing value, so the collection silently loses its link. Only\n  // tags carrying the explicit `fields.` prefix are checked: a bare tag such as `{{title}}` may be\n  // either a field or one of the special tags the replacer handles first, and telling the two apart\n  // here would report the special ones as missing fields\n  checkFieldReferences({\n    option: 'preview_path',\n    template: pathTemplate,\n    prefixedOnly: true,\n    type: 'warning',\n    strKey: 'preview_path_field_not_found',\n    fields,\n    context,\n    collectors,\n  });\n};\n","import { DATE_TIME_FIELDS, UUID_TYPES } from '$lib/services/common/template/constants';\nimport { checkFieldReferences } from '$lib/services/config/parser/utils/references';\nimport { getConfiguredSlugTemplate } from '$lib/services/contents/collection/slug';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import { EntryCollection, Field } from '$lib/types/public';\n */\n\n/**\n * Template tags a slug or path template can use that don’t refer to a field: the date and time of\n * creation, a random ID, and the slug of the entry itself, which `{{slug}}` derives from the\n * identifier field and the legacy `{{fields._slug}}` reads from the slug editor.\n * @type {string[]}\n */\nconst SLUG_SPECIAL_TAGS = [\n  ...DATE_TIME_FIELDS,\n  ...Object.keys(UUID_TYPES),\n  'slug',\n  '_slug',\n  'fields._slug',\n];\n\n/**\n * Template tags a summary template can use that don’t refer to a field: the entry’s slug, locales,\n * file path parts and commit information. The `title` tag is included because it falls back to the\n * entry’s summary whether or not a `title` field is defined.\n * @type {string[]}\n */\nexport const SUMMARY_SPECIAL_TAGS = [\n  'slug',\n  'locales',\n  'dirname',\n  'filename',\n  'extension',\n  'commit_date',\n  'commit_author',\n  'title',\n  'fields.title',\n];\n\n/**\n * Check the `summary` option of an entry collection, a collection file or an index file against\n * the fields it can refer to. Nothing is checked without fields, which is reported separately.\n * @param {object} args Arguments.\n * @param {any} args.template The `summary` option value.\n * @param {Field[] | undefined} args.fields Fields the template can refer to.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkSummaryTemplate = ({ template, fields, context, collectors }) => {\n  if (!fields?.length) {\n    return;\n  }\n\n  checkFieldReferences({\n    option: 'summary',\n    template,\n    specialTags: SUMMARY_SPECIAL_TAGS,\n    fields,\n    context,\n    collectors,\n  });\n};\n\n/**\n * Check the templates of an entry collection that refer to its fields: the `slug`, `path` and\n * `summary` options, along with the `thumbnail` option, which names fields directly. A tag that\n * names no field isn’t reported at runtime — a slug or path tag falls back to a random ID, and a\n * summary tag to nothing — so a typo only shows once entries have been saved under unexpected\n * names.\n *\n * Every tag is checked, not just the ones with the explicit `fields.` prefix, because the set of\n * special tags these templates support is known and small, unlike a `preview_path`.\n * @param {object} args Arguments.\n * @param {EntryCollection} args.collection Collection config to check.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkCollectionTemplates = ({ collection, context, collectors }) => {\n  const { fields, path, summary, thumbnail } = collection;\n\n  // A collection without fields is reported separately\n  if (!fields?.length) {\n    return;\n  }\n\n  const args = { fields, context, collectors };\n\n  checkFieldReferences({\n    ...args,\n    option: 'slug',\n    template: getConfiguredSlugTemplate(collection),\n    specialTags: SLUG_SPECIAL_TAGS,\n  });\n\n  checkFieldReferences({\n    ...args,\n    option: 'path',\n    template: path,\n    specialTags: SLUG_SPECIAL_TAGS,\n  });\n\n  checkSummaryTemplate({ ...args, template: summary });\n\n  // The `thumbnail` option lists key paths rather than a template; a boolean turns the thumbnails\n  // on or off\n  if (typeof thumbnail === 'string' || Array.isArray(thumbnail)) {\n    /** @type {any[]} */ (Array.isArray(thumbnail) ? thumbnail : [thumbnail]).forEach((item) => {\n      // A path starting with a slash is a template like `preview_path`, whose bare tags may be\n      // special ones such as `{{slug}}`, so only the tags with the `fields.` prefix are checked\n      if (typeof item === 'string' && item.startsWith('/')) {\n        checkFieldReferences({ ...args, option: 'thumbnail', template: item, prefixedOnly: true });\n      } else {\n        checkFieldReferences({ ...args, option: 'thumbnail', keyPaths: item });\n      }\n    });\n  }\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { getCodeKeys } from '$lib/services/contents/fields/code/helpers';\n\n/**\n * @import { FieldParserArgs } from '$lib/types/private';\n * @import { CodeField } from '$lib/types/public';\n */\n\n/**\n * Parse and validate a Code field configuration. The `default` is a string when the field outputs\n * the code only, or an object whose properties are named by the `keys` option, and a mismatch is\n * silently dropped at runtime.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseCodeFieldConfig = ({ config, context, collectors }) => {\n  const { default: defaultValue } = /** @type {CodeField} */ (config);\n\n  // A string default is the code in either mode; a value of another type is reported against the\n  // JSON schema\n  if (!isObject(defaultValue)) {\n    return;\n  }\n\n  const keys = getCodeKeys(/** @type {CodeField} */ (config));\n\n  if (!keys) {\n    addMessage({ strKey: 'code_field_invalid_default_object', context, collectors });\n\n    return;\n  }\n\n  const { code, lang } = keys;\n\n  Object.keys(defaultValue)\n    .filter((key) => ![code, lang].includes(key))\n    .forEach((key) => {\n      addMessage({\n        strKey: 'code_field_invalid_default_key',\n        values: { key, code, lang },\n        context,\n        collectors,\n      });\n    });\n};\n","import { FIELD_TAG_PREFIX_REGEX, UUID_TYPES } from '$lib/services/common/template/constants';\nimport { processNestedTemplates } from '$lib/services/common/template/nested';\nimport { splitTemplateTags } from '$lib/services/common/template/tags';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { parseTransformations } from '$lib/services/common/transformations';\nimport { getRootFields } from '$lib/services/config/parser/utils/fields';\nimport { checkFieldReferences } from '$lib/services/config/parser/utils/references';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { parseExpression } from '$lib/services/contents/fields/compute/expression';\nimport { forEachSubFieldConfig } from '$lib/services/contents/fields/list/subfields';\nimport { yieldsNumber } from '$lib/services/contents/fields/number/helpers';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { FieldParserArgs } from '$lib/types/private';\n * @import { ExpressionTag } from '$lib/services/contents/fields/compute/expression';\n * @import { ComputeField } from '$lib/types/public';\n */\n\n/**\n * Check the arithmetic expression of a Compute field with a numeric `value_type`. An invalid one,\n * or one with a UUID tag, which never resolves to a number, would leave the value empty.\n * @param {FieldParserArgs} args Arguments.\n */\nconst checkExpression = ({ config, context, collectors }) => {\n  const { value, value_type: valueType } = /** @type {ComputeField} */ (config);\n  const { tree, tags } = parseExpression(value);\n\n  if (!tree) {\n    addMessage({\n      strKey: 'compute_field_invalid_expression',\n      values: { valueType },\n      context,\n      collectors,\n    });\n\n    return;\n  }\n\n  if (tags.some(({ content }) => Object.hasOwn(UUID_TYPES, parseTransformations(content).value))) {\n    addMessage({\n      strKey: 'compute_field_uuid_in_expression',\n      values: { valueType },\n      context,\n      collectors,\n    });\n  }\n};\n\n/**\n * Get the template tags in the `value` option of a Compute field.\n * @param {string} value The `value` option.\n * @param {boolean} numeric Whether the field has a numeric `value_type`, which makes the option an\n * arithmetic expression.\n * @returns {ExpressionTag[]} Tags. `allItems` is only set for a tag passed to an aggregate function\n * in an arithmetic expression. Empty for an invalid expression.\n */\nconst getTags = (value, numeric) => {\n  if (numeric) {\n    const { tree, tags } = parseExpression(value);\n\n    // Which tag is passed to an aggregate function isn’t known for an invalid expression, which is\n    // reported anyway\n    return tree ? tags : [];\n  }\n\n  return splitTemplateTags(value).tags.map((content) => ({ content, allItems: false }));\n};\n\n/**\n * Regular expression matching a variable type name in a typed key path, e.g. `<product>`.\n */\nconst TYPE_NAME_REGEX = /<[^>]*>/g;\n/**\n * Regular expression matching a list index in a key path, e.g. `.0` in `lines.0.price`.\n */\nconst LIST_INDEX_REGEX = /(?<=^|\\.)\\d+(?=\\.|$)/g;\n\n/**\n * Get the fields the given template tag refers to: the tag itself, if it’s a `{{fields.*}}` tag,\n * and the tags in its transformation arguments, like `{{fields.title}}` in\n * `default('{{fields.title}}')`, which the runtime resolves as well.\n * @param {string} content Content of the tag, e.g. `fields.title | upper`.\n * @returns {{ tagName: string, keyPath: string }[]} The name of each tag, e.g.\n * `fields.lines.0.price`, and the key path it refers to, with a `*` for every list index as in the\n * key path of the field, e.g. `lines.*.price`.\n */\nconst getFieldReferences = (content) => {\n  const { value: tagName, transformations } = parseTransformations(content);\n  /** @type {{ tagName: string, keyPath: string }[]} */\n  const references = [];\n\n  if (FIELD_TAG_PREFIX_REGEX.test(tagName)) {\n    references.push({\n      tagName,\n      keyPath: stripFieldTagPrefix(tagName).replace(LIST_INDEX_REGEX, '*'),\n    });\n  }\n\n  processNestedTemplates(transformations, (innerTag) => {\n    references.push(...getFieldReferences(innerTag));\n\n    return '';\n  });\n\n  return references;\n};\n\n/**\n * Check the `{{fields.*}}` tags of a Compute field. A tag referring to the field itself, like\n * `{{fields.lines.*.amount}}` in `lines.*.amount`, makes the value change whenever it’s resolved,\n * which happens again whenever a value changes, so it never settles. Every `*` has to stand for an\n * item the field is in, like `{{fields.lines.*.price}}` for a field in the `lines` list. Any other\n * `*` resolves to nothing, unless the tag is passed to an aggregate function like `sum()`, where it\n * covers every item.\n * @param {FieldParserArgs} args Arguments.\n * @param {ExpressionTag[]} tags Template tags in the `value` option.\n */\nconst checkFieldTags = ({ context, collectors }, tags) => {\n  // Drop the variable type names, as in `lines.*<product>.amount`\n  const ownKeyPath = (context.typedKeyPath ?? '').replace(TYPE_NAME_REGEX, '');\n  const ownSegments = ownKeyPath.split('.');\n\n  tags.forEach(({ content, allItems }) => {\n    const selfReference = getFieldReferences(content).find(({ keyPath }) => keyPath === ownKeyPath);\n\n    if (selfReference) {\n      addMessage({\n        type: 'warning',\n        strKey: 'compute_field_self_reference',\n        values: { name: selfReference.tagName },\n        context,\n        collectors,\n      });\n\n      return;\n    }\n\n    const { value: tagName } = parseTransformations(content);\n\n    if (!FIELD_TAG_PREFIX_REGEX.test(tagName)) {\n      return;\n    }\n\n    const keyPath = stripFieldTagPrefix(tagName);\n\n    if (allItems) {\n      return;\n    }\n\n    const segments = keyPath.split('.');\n\n    const valid = segments.every(\n      (segment, index) =>\n        segment !== '*' || segments.slice(0, index + 1).every((s, i) => s === ownSegments[i]),\n    );\n\n    if (!valid) {\n      addMessage({\n        type: 'warning',\n        strKey: 'compute_field_wildcard_without_item',\n        values: { name: tagName },\n        context,\n        collectors,\n      });\n    }\n  });\n};\n\n/**\n * A Compute field in the field list of a collection or file, with the fields it refers to.\n * @typedef {object} ComputeFieldNode\n * @property {string} typedKeyPath Key path of the field as given to the field parser, including any\n * variable type name, e.g. `lines.*<product>.amount`.\n * @property {string} keyPath The same without the type names, e.g. `lines.*.amount`.\n * @property {Set<string>} references Key paths of the `{{fields.*}}` tags in the `value` option,\n * with a `*` for every list index, e.g. `lines.*.price` for `{{fields.lines.0.price}}`.\n */\n\n/**\n * Collect the given field if it’s a Compute field, or the Compute fields below it otherwise. The\n * key paths are built the same way as the field parser builds `typedKeyPath`.\n * @param {any} field Field configuration.\n * @param {string} typedKeyPath Typed key path of the field.\n * @returns {ComputeFieldNode[]} Fields.\n */\nconst collectFromField = (field, typedKeyPath) => {\n  const { widget = 'string', value } = field ?? {};\n\n  if (widget === 'compute') {\n    const references = new Set(\n      (typeof value === 'string' ? getTags(value, yieldsNumber(field)) : []).flatMap(\n        ({ content }) => getFieldReferences(content).map(({ keyPath }) => keyPath),\n      ),\n    );\n\n    return [{ typedKeyPath, keyPath: typedKeyPath.replace(TYPE_NAME_REGEX, ''), references }];\n  }\n\n  /** @type {ComputeFieldNode[]} */\n  const nodes = [];\n\n  forEachSubFieldConfig(\n    field ?? {},\n    typedKeyPath,\n    (subField, subKeyPath) => {\n      nodes.push(...collectFromField(subField, subKeyPath));\n    },\n    true,\n  );\n\n  return nodes;\n};\n\n/**\n * Reference cycles among the Compute fields of a field list, keyed by the list. A list is shared by\n * every Compute field in it, so the cycles are found once for all of them.\n * @type {WeakMap<object, Map<string, string>>}\n */\nconst referenceCycleCacheMap = new WeakMap();\n\n/**\n * Find the reference cycles among the Compute fields in the given field list, like `a` referring\n * to `b` and `b` referring back to `a`, possibly through others. Each such group of fields is\n * found as a strongly connected component of the reference graph, in a single depth-first search.\n * A field referring to itself alone is reported separately, so it’s not a cycle here.\n * @param {object} fields Root field list of a collection or file.\n * @returns {Map<string, string>} Key path of another field of the cycle, keyed by the typed key\n * path of the field the cycle is reported for: the first field of each cycle in key path order, so\n * each one is reported once.\n */\nconst getReferenceCycles = (fields) =>\n  getOrCreate(referenceCycleCacheMap, fields, () => {\n    // The list holds the Compute field being parsed, so it’s an array, unlike a nested one\n    const nodes = /** @type {any[]} */ (fields).flatMap((field) =>\n      collectFromField(field, `${field?.name}`),\n    );\n\n    // A reference matches every variable type of the field, as a tag can’t name the type. A field\n    // referring to the same key path, in its own type or another, is reported as referring to\n    // itself instead\n    const targets = new Map(\n      nodes.map((node) => [\n        node,\n        nodes.filter(\n          (other) => other.keyPath !== node.keyPath && node.references.has(other.keyPath),\n        ),\n      ]),\n    );\n\n    /** @type {Map<ComputeFieldNode, { index: number, lowLink: number }>} */\n    const visited = new Map();\n    /** @type {ComputeFieldNode[]} */\n    const stack = [];\n    /** @type {Set<ComputeFieldNode>} */\n    const onStack = new Set();\n    /** @type {Map<string, string>} */\n    const cycles = new Map();\n\n    /**\n     * Visit the given node and the nodes it refers to, recording each strongly connected component\n     * of more than one node.\n     * @param {ComputeFieldNode} node Node.\n     */\n    const visit = (node) => {\n      const state = { index: visited.size, lowLink: visited.size };\n\n      visited.set(node, state);\n      stack.push(node);\n      onStack.add(node);\n\n      /** @type {ComputeFieldNode[]} */ (targets.get(node)).forEach((target) => {\n        if (!visited.has(target)) {\n          visit(target);\n          state.lowLink = Math.min(\n            state.lowLink,\n            /** @type {{ lowLink: number }} */ (visited.get(target)).lowLink,\n          );\n        } else if (onStack.has(target)) {\n          state.lowLink = Math.min(\n            state.lowLink,\n            /** @type {{ index: number }} */ (visited.get(target)).index,\n          );\n        }\n      });\n\n      if (state.lowLink !== state.index) {\n        return;\n      }\n\n      /** @type {ComputeFieldNode[]} */\n      const component = [];\n      /** @type {ComputeFieldNode | undefined} */\n      let member;\n\n      do {\n        member = /** @type {ComputeFieldNode} */ (stack.pop());\n        onStack.delete(member);\n        component.push(member);\n      } while (member !== node);\n\n      if (component.length > 1) {\n        const [first] = component.toSorted((a, b) => a.typedKeyPath.localeCompare(b.typedKeyPath));\n\n        const next = /** @type {ComputeFieldNode} */ (\n          /** @type {ComputeFieldNode[]} */ (targets.get(first)).find((target) =>\n            component.includes(target),\n          )\n        );\n\n        cycles.set(first.typedKeyPath, next.keyPath);\n      }\n    };\n\n    nodes.forEach((node) => {\n      if (!visited.has(node)) {\n        visit(node);\n      }\n    });\n\n    return cycles;\n  });\n\n/**\n * Parse and validate a Compute field configuration. The `value` template reads other fields of the\n * entry through `{{fields.*}}` tags, and a tag that names no field yields an empty string, so the\n * computed value silently comes out wrong. Bare tags are not field references: `{{index}}` is the\n * position of the item in a list, `{{uuid}}` and its shorter variants are generated, and any other\n * one yields nothing, so there is no point checking them against the fields. With a numeric\n * `value_type`, the `value` is also checked as an arithmetic expression. A tag is checked not to\n * refer to the field itself, and a `*` in it to stand for an item the field is in. A reference\n * cycle among the Compute fields of the collection or file is reported for one of its fields.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseComputeFieldConfig = ({ config, context, collectors }) => {\n  const { value } = /** @type {ComputeField} */ (config);\n  const numeric = yieldsNumber(config);\n  // The fields of a custom editor component aren’t known here, so only a field of a collection or\n  // file can be checked\n  const fields = getRootFields(context);\n\n  // A value of another type is reported against the JSON schema\n  if (typeof value === 'string') {\n    if (numeric) {\n      checkExpression({ config, context, collectors });\n    }\n\n    // The key path of a field of a custom editor component is relative to the component, while a\n    // tag can refer to a field of the entry as well\n    if (!context.componentName) {\n      checkFieldTags({ config, context, collectors }, getTags(value, numeric));\n    }\n  }\n\n  if (fields?.length) {\n    // The values of the fields in a cycle keep changing each other, so they never settle\n    const otherKeyPath = getReferenceCycles(fields).get(context.typedKeyPath ?? '');\n\n    if (otherKeyPath !== undefined) {\n      addMessage({\n        type: 'warning',\n        strKey: 'compute_field_reference_cycle',\n        values: { name: `fields.${otherKeyPath}` },\n        context,\n        collectors,\n      });\n    }\n\n    checkFieldReferences({\n      option: 'value',\n      template: value,\n      prefixedOnly: true,\n      fields,\n      context,\n      collectors,\n    });\n  }\n};\n","import { addMessage, checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\nimport {\n  isCustomTimeZone,\n  parseDateTimeConfig,\n} from '$lib/services/contents/fields/date-time/config';\nimport { getDayjsLocaleKey } from '$lib/services/contents/fields/date-time/locales';\nimport { mergeI18nConfigs } from '$lib/services/contents/i18n/config/merge';\n\n/**\n * @import { FieldParserArgs, UnsupportedOption } from '$lib/types/private';\n * @import { DateTimeField } from '$lib/types/public';\n */\n\n/**\n * Unsupported options for DateTime fields.\n * @type {UnsupportedOption[]}\n */\nconst UNSUPPORTED_OPTIONS = [\n  // Deprecated camelCase options in Netlify/Decap CMS config, should be converted to snake_case.\n  { prop: 'dateFormat', newProp: 'date_format' },\n  { prop: 'timeFormat', newProp: 'time_format' },\n  { prop: 'pickerUtc', newProp: 'picker_utc' },\n];\n\n/**\n * Validate an IANA timezone identifier.\n * @param {string} timeZone IANA timezone identifier to validate.\n * @returns {boolean} True if valid, false otherwise.\n */\nconst validateTimeZone = (timeZone) => {\n  try {\n    // Attempt to use the timezone - will throw `RangeError` if invalid.\n    Intl.DateTimeFormat('en-US', { timeZone });\n\n    return true;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Validate timezone-related options in the DateTime field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nconst validateTimeZoneOptions = (args) => {\n  const { config, context, collectors } = args;\n\n  const {\n    picker_utc: pickerUTC,\n    input_timezone: inputTimeZone,\n    output_utc: outputUTC,\n  } = /** @type {DateTimeField} */ (config);\n\n  // Warn when both old and new options are present\n  if (pickerUTC !== undefined && (inputTimeZone !== undefined || outputUTC !== undefined)) {\n    addMessage({\n      type: 'warning',\n      strKey: 'conflicting_timezone_options',\n      context,\n      collectors,\n    });\n  }\n\n  if (isCustomTimeZone(inputTimeZone) && !validateTimeZone(inputTimeZone)) {\n    addMessage({\n      strKey: 'invalid_timezone',\n      values: { timeZone: inputTimeZone },\n      context,\n      collectors,\n    });\n  }\n};\n\n/**\n * Validate the `localize_format` option in the DateTime field configuration, and collect the\n * locales the field writes its values in, so their Day.js locales can be loaded.\n * @param {FieldParserArgs} args Arguments.\n */\nconst parseLocalizeFormatOption = (args) => {\n  const { config, context, collectors } = args;\n  const fieldConfig = /** @type {DateTimeField} */ (config);\n  const { localize_format: localizeFormat } = fieldConfig;\n\n  if (!localizeFormat) {\n    return;\n  }\n\n  if (!parseDateTimeConfig(fieldConfig).format) {\n    addMessage({ type: 'warning', strKey: 'localize_format_without_format', context, collectors });\n\n    return;\n  }\n\n  if (typeof localizeFormat === 'string') {\n    if (!getDayjsLocaleKey(localizeFormat)) {\n      addMessage({\n        type: 'warning',\n        strKey: 'localize_format_unsupported_locale',\n        values: { locale: localizeFormat },\n        context,\n        collectors,\n      });\n\n      return;\n    }\n\n    collectors.formatLocales.add(localizeFormat);\n\n    return;\n  }\n\n  const { cmsConfig, collection, collectionFile: file } = context;\n\n  // An editor component’s content can be in any of the site’s locales\n  const locales = collection\n    ? (mergeI18nConfigs({ cmsConfig, collection, file })?.locales ?? [])\n    : (cmsConfig?.i18n?.locales ?? []);\n\n  if (!locales.length) {\n    addMessage({ type: 'warning', strKey: 'localize_format_without_i18n', context, collectors });\n\n    return;\n  }\n\n  locales.forEach((locale) => {\n    collectors.formatLocales.add(locale);\n  });\n};\n\n/**\n * Parse and validate a DateTime field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseDateTimeFieldConfig = (args) => {\n  checkUnsupportedOptions({ ...args, UNSUPPORTED_OPTIONS });\n  validateTimeZoneOptions(args);\n  parseLocalizeFormatOption(args);\n};\n","import { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { splitTransformations } from '$lib/services/common/transformations';\n\n/**\n * Normalize the template tags in a string to their canonical form, without spaces after the opening\n * curly braces or before the closing ones, and with a single space on either side of each pipe\n * separating transformations, e.g. `{{ title|upper }}` becomes `{{title | upper}}`. Spaces in a\n * quoted transformation argument are kept, and so is an escaped tag, e.g. `\\{{ title }}`, along\n * with its backslash. This lets the code that looks for a specific tag, like `{{slug}}` or\n * `{{locale}}`, compare the template as is.\n * @param {string} str String that may contain template tags.\n * @returns {string} Normalized string.\n */\nexport const normalizeTemplateTags = (str) =>\n  str.includes('{{')\n    ? replaceTemplateTags(\n        str,\n        (_match, placeholder) => `{{${splitTransformations(placeholder).join(' | ')}}}`,\n        { unescape: false },\n      )\n    : str;\n","import { isObject } from '@sveltia/utils/object';\n\nimport { normalizeTemplateTags } from '$lib/services/common/template/normalize';\nimport { COMPARISON_OPERATORS } from '$lib/services/common/view';\nimport { getSubFields } from '$lib/services/config/parser/utils/fields';\n\n/**\n * @import { CmsConfig, EditorComponentDefinition, Field } from '$lib/types/public';\n */\n\n/**\n * Options of a collection, a collection file or a field that hold an asset folder path, which can\n * contain template tags.\n */\nexport const FOLDER_OPTIONS = ['media_folder', 'public_folder'];\n\n/**\n * Options of each field type, besides {@link FOLDER_OPTIONS}, that hold a template. A field type’s\n * other string options, e.g. the `default` option of a String field, are content and left as is.\n * @type {Record<string, string[]>}\n */\nconst FIELD_TEMPLATE_OPTIONS = {\n  compute: ['value'],\n  datetime: ['default'],\n  hidden: ['default'],\n  list: ['summary'],\n  object: ['summary'],\n  relation: ['value_field', 'display_fields', 'search_fields'],\n};\n\n/**\n * Options of a view filter or group that match or compare a field value with another value, which\n * can contain a template tag like `{{now}}`. The `empty` operator takes a boolean, which\n * {@link normalizeOptions} leaves as is.\n */\nconst VIEW_COMPARISON_OPTIONS = ['pattern', ...COMPARISON_OPERATORS];\n\n/**\n * Normalize the template tags in the given options of an object, in place. An option can be a\n * string or a list of strings; any other value is left as is.\n * @param {any} target Object holding the options. Ignored if it’s not an object.\n * @param {string[]} options Option names.\n */\nconst normalizeOptions = (target, options) => {\n  if (!isObject(target)) {\n    return;\n  }\n\n  options.forEach((option) => {\n    const value = target[option];\n\n    if (typeof value === 'string') {\n      target[option] = normalizeTemplateTags(value);\n    } else if (Array.isArray(value)) {\n      target[option] = value.map((item) =>\n        typeof item === 'string' ? normalizeTemplateTags(item) : item,\n      );\n    }\n  });\n};\n\n/**\n * Normalize the `filename_template` option of the media libraries configured in an object: the\n * root config or a field.\n * @param {any} target Object holding the `media_libraries` or legacy `media_library` option.\n */\nconst normalizeMediaLibraryTemplates = (target) => {\n  const { media_libraries: libraries, media_library: legacyLibrary } = target;\n\n  if (isObject(libraries)) {\n    Object.values(libraries).forEach((library) => {\n      normalizeOptions(library?.config, ['filename_template']);\n    });\n  }\n\n  normalizeOptions(legacyLibrary?.config, ['filename_template']);\n};\n\n/**\n * Normalize the template tags in the `canonical_slug` i18n option of an object: the root config, a\n * collection or a collection file.\n * @param {any} target Object holding the `i18n` option.\n */\nconst normalizeI18nTemplates = (target) => {\n  normalizeOptions(target.i18n?.canonical_slug, ['value']);\n};\n\n/**\n * Normalize the template tags in the options of the given fields and their subfields, in place.\n * @param {any} fields Field list. Ignored if it’s not an array.\n */\nexport const normalizeFieldTemplates = (fields) => {\n  if (!Array.isArray(fields)) {\n    return;\n  }\n\n  fields.forEach((field) => {\n    if (!isObject(field)) {\n      return;\n    }\n\n    const { widget = 'string', filters, types } = field;\n\n    normalizeOptions(field, [...FOLDER_OPTIONS, ...(FIELD_TEMPLATE_OPTIONS[widget] ?? [])]);\n    normalizeMediaLibraryTemplates(field);\n\n    // A variable type of a List or Object field can have a `summary` of its own\n    if (Array.isArray(types)) {\n      types.forEach((type) => normalizeOptions(type, ['summary']));\n    }\n\n    if (widget === 'relation' && Array.isArray(filters)) {\n      filters.forEach((filter) => normalizeOptions(filter, ['values']));\n    }\n\n    normalizeFieldTemplates(getSubFields(/** @type {Field} */ (field)));\n  });\n};\n\n/**\n * Normalize the template tags in the options of a collection file or a singleton, in place.\n * @param {any} file Collection file.\n */\nconst normalizeCollectionFileTemplates = (file) => {\n  if (!isObject(file)) {\n    return;\n  }\n\n  normalizeOptions(file, ['file', 'summary', 'preview_path', ...FOLDER_OPTIONS]);\n  normalizeI18nTemplates(file);\n  normalizeFieldTemplates(file.fields);\n};\n\n/**\n * Normalize the template tags in the view filters or groups of a collection, in place.\n * @param {any} views The `view_filters` or `view_groups` option: a list of filters or groups, or an\n * object holding the list in the given property.\n * @param {'filters' | 'groups'} listName Name of the property holding the list.\n */\nconst normalizeViewTemplates = (views, listName) => {\n  const list = Array.isArray(views) ? views : views?.[listName];\n\n  if (Array.isArray(list)) {\n    list.forEach((view) => normalizeOptions(view, VIEW_COMPARISON_OPTIONS));\n  }\n};\n\n/**\n * Normalize the template tags in the options of a collection, in place.\n * @param {any} collection Collection.\n */\nconst normalizeCollectionTemplates = (collection) => {\n  if (!isObject(collection)) {\n    return;\n  }\n\n  const { slug, nested, table_columns: tableColumns, index_file: indexFile, files } = collection;\n\n  // `folder` and `file` (an entry collection stored in one file) can contain `{{locale}}`\n  normalizeOptions(collection, [\n    'folder',\n    'file',\n    'slug',\n    'path',\n    'summary',\n    'preview_path',\n    'table_columns',\n    'summary_fields',\n    // A file path among key paths, e.g. `/images/{{slug}}.webp`\n    'thumbnail',\n    ...FOLDER_OPTIONS,\n  ]);\n  normalizeOptions(slug, ['template']);\n  normalizeOptions(nested, ['summary']);\n  normalizeI18nTemplates(collection);\n  normalizeViewTemplates(collection.view_filters, 'filters');\n  normalizeViewTemplates(collection.view_groups, 'groups');\n\n  // A column can also be an object with the template in its `field` option\n  if (Array.isArray(tableColumns)) {\n    tableColumns.forEach((column) => normalizeOptions(column, ['field']));\n  }\n\n  normalizeFieldTemplates(collection.fields);\n\n  // An index file can have a `summary` and fields of its own\n  if (isObject(indexFile)) {\n    normalizeOptions(indexFile, ['summary']);\n    normalizeFieldTemplates(indexFile.fields);\n  }\n\n  if (Array.isArray(files)) {\n    files.forEach(normalizeCollectionFileTemplates);\n  }\n};\n\n/**\n * Normalize the template tags in the options of the given configuration that hold a template, in\n * place, so spaces inside a tag, e.g. `{{ slug }}`, and around a pipe don’t matter anywhere. See\n * {@link normalizeTemplateTags}.\n * @param {CmsConfig} config Configuration. It must be a copy of the one given by the user.\n * @returns {CmsConfig} The same configuration.\n */\nexport const normalizeConfigTemplates = (config) => {\n  /** @type {any} */\n  const { backend, collections, singletons, asset_collections: assetCollections } = config;\n\n  normalizeOptions(config, FOLDER_OPTIONS);\n  normalizeMediaLibraryTemplates(config);\n  normalizeI18nTemplates(config);\n\n  if (isObject(backend?.commit_messages)) {\n    normalizeOptions(backend.commit_messages, Object.keys(backend.commit_messages));\n  }\n\n  if (Array.isArray(collections)) {\n    collections.forEach(normalizeCollectionTemplates);\n  }\n\n  if (Array.isArray(singletons)) {\n    singletons.forEach(normalizeCollectionFileTemplates);\n  }\n\n  if (Array.isArray(assetCollections)) {\n    assetCollections.forEach((collection) => normalizeOptions(collection, FOLDER_OPTIONS));\n  }\n\n  return config;\n};\n\n/**\n * Normalize the template tags in the `summary` option and the fields of an editor component\n * definition, in place.\n * @param {EditorComponentDefinition} definition Definition.\n */\nexport const normalizeEditorComponentTemplates = (definition) => {\n  normalizeOptions(definition, ['summary']);\n  normalizeFieldTemplates(definition.fields);\n};\n","/* eslint-disable camelcase */\n\nimport { _ } from '@sveltia/i18n';\n\nimport { DATE_TIME_FIELDS, UUID_TYPES } from '$lib/services/common/template/constants';\nimport { getTemplateTags } from '$lib/services/common/template/tags';\nimport { addMessage, checkName } from '$lib/services/config/parser/utils/validator';\nimport { FOLDER_OPTIONS } from '$lib/services/config/templates';\nimport { CLOUD_MEDIA_LIBRARY_NAMES } from '$lib/services/integrations/media-libraries/cloud';\n\n/**\n * @import { CmsConfig } from '$lib/types/public';\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n */\n\n/**\n * Template tags that the `media_folder` and `public_folder` options of a collection, a collection\n * file or a field can use, which may be followed by transformations: the slug template tags and the\n * entry file path parts. Any other tag, such as a field name, resolves to a random ID that changes\n * with every entry draft.\n * @type {string[]}\n */\nconst FOLDER_TEMPLATE_TAGS = [\n  ...DATE_TIME_FIELDS,\n  ...Object.keys(UUID_TYPES),\n  'slug',\n  'dirname',\n  'filename',\n  'extension',\n];\n\n/**\n * Template tags standing for the global `media_folder` and `public_folder` options. They are\n * replaced as they are, so they can’t have spaces or transformations.\n * @type {string[]}\n */\nconst GLOBAL_FOLDER_TAGS = ['{{media_folder}}', '{{public_folder}}'];\n\n/**\n * Check the template tags in the `media_folder` and `public_folder` options. The global options\n * can’t have any, as there is no entry to fill them in with, so they would be used literally.\n * @param {object} args Arguments.\n * @param {Record<string, any>} args.config Configuration holding the options: the site\n * configuration, a collection, a collection file or a field.\n * @param {boolean} [args.isGlobal] Whether the configuration is the site configuration.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkFolderTemplateTags = ({ config, isGlobal = false, context, collectors }) => {\n  FOLDER_OPTIONS.forEach((option) => {\n    const folder = config[option];\n\n    // A value of another type is reported against the JSON schema\n    if (typeof folder !== 'string') {\n      return;\n    }\n\n    getTemplateTags(folder).forEach(({ tag, name }) => {\n      if (!isGlobal && (GLOBAL_FOLDER_TAGS.includes(tag) || FOLDER_TEMPLATE_TAGS.includes(name))) {\n        return;\n      }\n\n      addMessage({\n        strKey: isGlobal ? 'global_folder_template_tag' : 'unsupported_folder_template_tag',\n        values: { option, tag },\n        context,\n        collectors,\n      });\n    });\n  });\n};\n\n/**\n * Check whether a cloud media library is configured, in which case an internal media folder is not\n * needed.\n * @param {CmsConfig} cmsConfig Raw CMS configuration.\n * @returns {boolean} Result.\n */\nconst hasCloudMediaLibrary = ({ media_library, media_libraries }) =>\n  CLOUD_MEDIA_LIBRARY_NAMES.includes(/** @type {any} */ (media_library?.name ?? '')) ||\n  Object.keys(media_libraries ?? {}).some((name) =>\n    CLOUD_MEDIA_LIBRARY_NAMES.includes(/** @type {any} */ (name)),\n  );\n\n/**\n * Parse and validate media folder configuration. The type of each option is checked against the\n * JSON schema, so only the rules the schema can’t express are verified here.\n * @param {CmsConfig} cmsConfig Raw CMS configuration.\n * @param {ConfigParserCollectors} collectors Collectors.\n * @throws {Error} If there is an error in the media folder config.\n */\nexport const parseMediaConfig = (cmsConfig, collectors) => {\n  const { media_folder, public_folder, asset_collections } = cmsConfig;\n  const { errors, warnings } = collectors;\n\n  if (media_folder === undefined && !hasCloudMediaLibrary(cmsConfig)) {\n    errors.add(_('config.error.missing_media_folder'));\n  }\n\n  // An empty site-level public folder is treated like an unset one, so the media folder path is\n  // used instead of storing bare file names as Netlify/Decap CMS does. Let the user know\n  if (public_folder === '' && media_folder !== undefined) {\n    warnings.add(_('config.warning.empty_public_folder'));\n  }\n\n  if (typeof public_folder === 'string') {\n    if (/^\\.{1,2}\\//.test(public_folder)) {\n      errors.add(_('config.error.public_folder_relative_path'));\n    }\n\n    if (/^https?:/.test(public_folder)) {\n      errors.add(_('config.error.public_folder_absolute_url'));\n    }\n  }\n\n  checkFolderTemplateTags({\n    config: cmsConfig,\n    isGlobal: true,\n    context: { cmsConfig },\n    collectors,\n  });\n\n  if (Array.isArray(asset_collections)) {\n    const checkNameArgs = { nameCounts: {}, strKeyBase: 'asset_collection_name', collectors };\n\n    asset_collections.forEach((assetCollection, index) => {\n      const { name } = assetCollection;\n\n      checkName({ ...checkNameArgs, name, index, context: { cmsConfig } });\n      // An asset collection has no entry to fill in template tags with either\n      checkFolderTemplateTags({\n        config: assetCollection,\n        isGlobal: true,\n        context: { cmsConfig },\n        collectors,\n      });\n    });\n  }\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { RASTER_IMAGE_FORMATS, VECTOR_IMAGE_FORMATS } from '$lib/services/utils/media/image';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n */\n\n/**\n * Keys accepted by the `transformations` option. `raster_image` matches any supported raster image\n * format, while the other keys match a specific source format.\n * @type {string[]}\n */\nconst TRANSFORMATION_KEYS = ['raster_image', ...RASTER_IMAGE_FORMATS, ...VECTOR_IMAGE_FORMATS];\n\n/**\n * Parse and validate raster image transformation options.\n * @param {object} args Arguments.\n * @param {string} args.key Transformation key, such as `raster_image` or `jpeg`.\n * @param {Record<string, any>} args.options Transformation options.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst parseRasterImageTransformation = ({ key, options, context, collectors }) => {\n  const { quality } = options;\n  const args = { values: { key }, context, collectors };\n\n  if (quality !== undefined && !(Number.isSafeInteger(quality) && quality >= 0 && quality <= 100)) {\n    addMessage({ ...args, strKey: 'invalid_transformation_quality' });\n  }\n\n  ['width', 'height'].forEach((prop) => {\n    const value = options[prop];\n\n    if (value !== undefined && !(Number.isSafeInteger(value) && value > 0)) {\n      addMessage({ ...args, strKey: 'invalid_transformation_size', values: { key, prop } });\n    }\n  });\n};\n\n/**\n * Parse and validate the `transformations` option of the default media library. The options are\n * applied to files being uploaded, so any problem must be reported here rather than silently\n * ignored at upload time. Option types are checked against the JSON schema; what’s left is the\n * numeric ranges and the set of accepted keys, neither of which the schema can express.\n * @param {object} args Arguments.\n * @param {any} args.transformations File transformation option map.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst parseTransformations = ({ transformations, context, collectors }) => {\n  if (!isObject(transformations)) {\n    return;\n  }\n\n  Object.entries(transformations).forEach(([key, options]) => {\n    // Unknown keys are silently ignored at upload time, and the schema allows them because unknown\n    // options are tolerated everywhere else\n    if (!TRANSFORMATION_KEYS.includes(key)) {\n      addMessage({ strKey: 'invalid_transformation_key', values: { key }, context, collectors });\n\n      return;\n    }\n\n    // Vector images only take an `optimize` flag, whose type the schema checks\n    if (!isObject(options) || /** @type {string[]} */ (VECTOR_IMAGE_FORMATS).includes(key)) {\n      return;\n    }\n\n    parseRasterImageTransformation({\n      key,\n      options: /** @type {Record<string, any>} */ (options),\n      context,\n      collectors,\n    });\n  });\n};\n\n/**\n * Parse and validate the default media library options defined in the given site or field\n * configuration. Options for the other libraries are passed to their own SDK or API client, so they\n * are not validated here.\n * @param {object} args Arguments.\n * @param {Record<string, any>} args.config Site or field configuration.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const parseMediaLibraries = ({ config, context, collectors }) => {\n  const { media_library: mediaLibrary, media_libraries: mediaLibraries } = config;\n  /** @type {any[]} */\n  const configs = [];\n\n  if (isObject(mediaLibraries)) {\n    // The `all` options are shared defaults for the default library\n    configs.push(mediaLibraries.all);\n\n    if (isObject(mediaLibraries.default)) {\n      configs.push(mediaLibraries.default.config);\n    }\n  }\n\n  // The legacy `media_library` option supports one library only, defaulting to the internal one\n  if (isObject(mediaLibrary) && (mediaLibrary.name ?? 'default') === 'default') {\n    configs.push(mediaLibrary.config);\n  }\n\n  configs.forEach((libraryConfig) => {\n    if (isObject(libraryConfig)) {\n      parseTransformations({ transformations: libraryConfig.transformations, context, collectors });\n    }\n  });\n\n  // There’s no entry to fill the tags with at the site level, unlike in a field\n  if (config === context.cmsConfig) {\n    [mediaLibrary, ...(isObject(mediaLibraries) ? Object.values(mediaLibraries) : [])].forEach(\n      (options) => {\n        if (typeof options?.prefix === 'string' && hasTemplateTags(options.prefix)) {\n          addMessage({\n            type: 'warning',\n            strKey: 'site_library_prefix_template',\n            context,\n            collectors,\n          });\n        }\n      },\n    );\n  }\n};\n","import { addMessage } from '$lib/services/config/parser/utils/validator';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import { Field, VariableFieldType } from '$lib/types/public';\n */\n\n/**\n * Check that the `default` option of a field with the `multiple` option has the matching shape: an\n * array of values when `multiple` is `true`, a single value otherwise. A mismatch is not an error\n * at runtime — the default is dropped, or the whole array is stored as one value — so a new entry\n * comes up empty or with an unexpected value.\n * @param {object} args Arguments.\n * @param {any} args.defaultValue The `default` option. `null` counts as no default.\n * @param {boolean} [args.multiple] The `multiple` option. Default: `false`.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkMultipleDefault = ({ defaultValue, multiple = false, context, collectors }) => {\n  // An empty `default:` line in YAML is `null`, which means no default just like an omitted option\n  if (defaultValue === undefined || defaultValue === null) {\n    return;\n  }\n\n  const isArray = Array.isArray(defaultValue);\n\n  if (multiple && !isArray) {\n    addMessage({ strKey: 'invalid_default_multiple', context, collectors });\n  }\n\n  if (!multiple && isArray) {\n    addMessage({ strKey: 'invalid_default_single', context, collectors });\n  }\n};\n\n/**\n * Report the properties of a default object that don’t name a subfield. Such a property would be\n * saved to the entry file as-is, so it’s most likely a typo.\n * @param {object} args Arguments.\n * @param {Record<string, any>} args.value Default object.\n * @param {Field[]} args.fields Subfields the object can have.\n * @param {string} args.strKeyBase Base of the i18n string key, e.g. `list_field`.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst checkObjectDefaultKeys = ({ value, fields, strKeyBase, context, collectors }) => {\n  const names = fields.map(({ name }) => name);\n\n  Object.keys(value)\n    .filter((key) => !names.includes(key))\n    .forEach((key) => {\n      addMessage({\n        strKey: `${strKeyBase}_invalid_default_key`,\n        values: { key },\n        context,\n        collectors,\n      });\n    });\n};\n\n/**\n * Check a default object of an Object field or a List field item against the subfields it can\n * have: the `fields`, or the fields of the variable type it names with the `typeKey` property.\n * @param {object} args Arguments.\n * @param {Record<string, any>} args.value Default object.\n * @param {Field[]} [args.fields] The `fields` option.\n * @param {VariableFieldType[]} [args.types] The `types` option, used if `fields` is not defined.\n * @param {string} [args.typeKey] The `typeKey` option. Default: `type`.\n * @param {string} args.strKeyBase Base of the i18n string keys, e.g. `list_field`, which the\n * `_invalid_default_key`, `_default_missing_type` and `_invalid_default_type` suffixes are added\n * to.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkObjectDefault = ({\n  value,\n  fields,\n  types,\n  typeKey = 'type',\n  strKeyBase,\n  context,\n  collectors,\n}) => {\n  const keysArgs = { value, strKeyBase, context, collectors };\n\n  if (fields) {\n    checkObjectDefaultKeys({ ...keysArgs, fields });\n\n    return;\n  }\n\n  const typeName = value[typeKey];\n\n  if (typeName === undefined) {\n    addMessage({\n      strKey: `${strKeyBase}_default_missing_type`,\n      values: { typeKey },\n      context,\n      collectors,\n    });\n\n    return;\n  }\n\n  const type = types?.find(({ name }) => name === typeName);\n\n  if (!type) {\n    addMessage({\n      strKey: `${strKeyBase}_invalid_default_type`,\n      values: { typeKey, value: String(typeName) },\n      context,\n      collectors,\n    });\n\n    return;\n  }\n\n  // The type key is a valid property although it’s not a field\n  checkObjectDefaultKeys({\n    ...keysArgs,\n    fields: [...(type.fields ?? []), /** @type {Field} */ ({ name: typeKey })],\n  });\n};\n","/* eslint-disable camelcase */\n\nimport { checkFolderTemplateTags } from '$lib/services/config/parser/media';\nimport { parseMediaLibraries } from '$lib/services/config/parser/media-libraries';\nimport { checkMultipleDefault } from '$lib/services/config/parser/utils/defaults';\nimport { checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\n\n/**\n * @import { FileField } from '$lib/types/public';\n * @import { FieldParserArgs, UnsupportedOption } from '$lib/types/private';\n */\n\n/**\n * Unsupported options for Number fields.\n * @type {UnsupportedOption[]}\n */\nconst UNSUPPORTED_OPTIONS = [\n  // Sveltia CMS doesn’t support the confusing option.\n  { prop: 'allow_multiple', newProp: 'multiple', strKey: 'allow_multiple' },\n];\n\n/**\n * Parse and validate a File field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseFileFieldConfig = (args) => {\n  const { config, context, collectors } = args;\n  const { media_folder, default: defaultValue, multiple } = /** @type {FileField} */ (config);\n\n  // Without the field’s own `multiple` option, whether the field takes several files depends on\n  // the media library options, which are resolved at runtime, so the default is only checked\n  // against an explicit option\n  if (multiple !== undefined) {\n    checkMultipleDefault({ defaultValue, multiple, context, collectors });\n  }\n\n  // Collect media folder information for later processing\n  if (media_folder !== undefined) {\n    collectors.mediaFields.add({\n      fieldConfig: /** @type {FileField} */ (config),\n      context,\n    });\n  }\n\n  checkFolderTemplateTags({ config, context, collectors });\n  parseMediaLibraries({ config, context, collectors });\n  checkUnsupportedOptions({ ...args, UNSUPPORTED_OPTIONS });\n};\n","import { processNestedTemplates } from '$lib/services/common/template/nested';\nimport { splitTemplateTags } from '$lib/services/common/template/tags';\nimport { parseTransformations } from '$lib/services/common/transformations';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { mergeI18nConfigs } from '$lib/services/contents/i18n/config/merge';\n\n/**\n * @import { FieldParserArgs } from '$lib/types/private';\n * @import { HiddenField } from '$lib/types/public';\n */\n\n/**\n * Check whether the given template uses the `{{locale}}` tag, with or without transformations, also\n * in a transformation argument, e.g. `default('{{locale}}')`.\n * @param {string} template Template.\n * @returns {boolean} Result.\n */\nconst hasLocaleTag = (template) =>\n  splitTemplateTags(template).tags.some((placeholder) => {\n    const { value, transformations } = parseTransformations(placeholder);\n    let found = value === 'locale';\n\n    processNestedTemplates(transformations, (innerTag) => {\n      if (hasLocaleTag(`{{${innerTag}}}`)) {\n        found = true;\n      }\n\n      return '';\n    });\n\n    return found;\n  });\n\n/**\n * Parse and validate a Hidden field configuration. The `{{locale}}` tag in the `default` option is\n * replaced with the locale of the content, which a collection or file without i18n doesn’t have,\n * so the value would be the key the CMS uses internally for such content instead.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseHiddenFieldConfig = ({ config, context, collectors }) => {\n  const { default: defaultValue } = /** @type {HiddenField} */ (config);\n  const { cmsConfig, collection, collectionFile: file } = context;\n\n  // The locale of an editor component’s content isn’t known here\n  if (typeof defaultValue !== 'string' || !collection || !hasLocaleTag(defaultValue)) {\n    return;\n  }\n\n  if (!mergeI18nConfigs({ cmsConfig, collection, file })?.locales?.length) {\n    addMessage({ strKey: 'hidden_field_locale_without_i18n', context, collectors });\n  }\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { addMessage, checkRegex } from '$lib/services/config/parser/utils/validator';\nimport { MULTI_VALUE_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { mergeI18nConfigs } from '$lib/services/contents/i18n/config/merge';\n\n/**\n * @import { FieldParserArgs } from '$lib/types/private';\n */\n\n/**\n * Pairs of options that bound a value from both sides, in the order they have to be in. Each pair\n * belongs to some field types only, but a pair that isn’t in a field’s configuration is simply not\n * checked, so it’s not worth spelling out which.\n * @type {[string, string][]}\n */\nconst RANGE_OPTIONS = [\n  ['min', 'max'],\n  ['minlength', 'maxlength'],\n];\n\n/**\n * Check the `default_localized` option. Its values are matched against the content locales only, so\n * a value for a locale the collection doesn’t have is never used, and none of them is without i18n.\n * The locales of an editor component’s content aren’t known here, so its fields aren’t checked.\n * @param {FieldParserArgs} args Arguments.\n */\nconst checkLocalizedDefault = ({ config, context, collectors }) => {\n  const { default_localized: localizedDefault } = /** @type {Record<string, any>} */ (config);\n  const { cmsConfig, collection, collectionFile: file } = context;\n\n  if (!isObject(localizedDefault) || !collection) {\n    return;\n  }\n\n  const locales = mergeI18nConfigs({ cmsConfig, collection, file })?.locales ?? [];\n\n  if (!locales.length) {\n    addMessage({ type: 'warning', strKey: 'default_localized_without_i18n', context, collectors });\n\n    return;\n  }\n\n  Object.keys(localizedDefault)\n    .filter((locale) => !locales.includes(locale))\n    .forEach((locale) => {\n      addMessage({\n        type: 'warning',\n        strKey: 'default_localized_unknown_locale',\n        values: { locale },\n        context,\n        collectors,\n      });\n    });\n};\n\n/**\n * Check the options that any field type can have. A `pattern` that can’t be compiled makes the\n * field skip its validation, and a range whose lower bound is above its upper bound can’t be\n * satisfied, but neither is reported at runtime, nor is a localized default value that’s unused.\n * The `duplicate_if_empty` i18n strategy only supports a single value, so a field taking several\n * works like a translatable one, which is reported too.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const checkCommonFieldOptions = ({ config, context, collectors }) => {\n  const {\n    widget: fieldType = 'string',\n    pattern,\n    multiple,\n    i18n,\n  } = /** @type {Record<string, any>} */ (config);\n\n  // Without a File or Image field’s own `multiple` option, whether the field takes several files\n  // depends on the media library options, which are resolved at runtime, so only an explicit option\n  // is checked. Any other field type doesn’t support the strategy at all, whatever its options\n  if (\n    MULTI_VALUE_FIELD_TYPES.includes(fieldType) &&\n    multiple === true &&\n    i18n === 'duplicate_if_empty'\n  ) {\n    addMessage({ type: 'warning', strKey: 'duplicate_if_empty_multiple', context, collectors });\n  }\n\n  // The `pattern` option is a `[regex, message]` pair; anything else is reported against the JSON\n  // schema\n  if (Array.isArray(pattern)) {\n    checkRegex({ option: 'pattern', pattern: pattern[0], context, collectors });\n  }\n\n  RANGE_OPTIONS.forEach(([minOption, maxOption]) => {\n    const { [minOption]: min, [maxOption]: max } = /** @type {Record<string, any>} */ (config);\n\n    if (typeof min === 'number' && typeof max === 'number' && min > max) {\n      addMessage({\n        strKey: 'invalid_range_options',\n        values: { min: minOption, max: maxOption },\n        context,\n        collectors,\n      });\n    }\n  });\n\n  checkLocalizedDefault({ config, context, collectors });\n};\n","import { checkFolderTemplateTags } from '$lib/services/config/parser/media';\n\n/**\n * @import { FieldParserArgs } from '$lib/types/private';\n * @import { CustomField } from '$lib/types/public';\n */\n\n/**\n * Parse a field configuration using a custom field type registered with `CMS.registerFieldType()`.\n * The options such a field accepts are validated against the registered schema, so the parser has\n * nothing else to check. A custom field control can still add files to the entry draft with the\n * `addFile` prop, though, and those files go to the field’s own `media_folder` if it has one, so\n * the option is collected and its template tags are checked the same way as for a File/Image\n * field.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseCustomFieldConfig = ({ config, context, collectors }) => {\n  const { media_folder: mediaFolder } = /** @type {CustomField} */ (config);\n\n  if (mediaFolder !== undefined) {\n    collectors.mediaFields.add({ fieldConfig: /** @type {CustomField} */ (config), context });\n  }\n\n  checkFolderTemplateTags({ config, context, collectors });\n};\n","import { checkCommonFieldOptions } from '$lib/services/config/parser/fields/common';\nimport { parseCustomFieldConfig } from '$lib/services/config/parser/fields/custom';\nimport { addMessage, checkName } from '$lib/services/config/parser/utils/validator';\nimport { BUILTIN_FIELD_TYPES } from '$lib/services/contents/fields';\n\n/**\n * @import { Field } from '$lib/types/public';\n * @import {\n * ConfigParserCollectors,\n * ConfigParserContext,\n * FieldParserArgs,\n * } from '$lib/types/private';\n */\n\n/**\n * Parsers for each field type, keyed by field type. The built-in parsers are registered by the\n * `fields` index module rather than imported here, because the List and Object field parsers\n * recurse into their subfields with {@link parseFields}: importing them from this module would make\n * the module graph circular.\n * @type {Record<string, (args: FieldParserArgs) => void>}\n */\nexport const fieldParsers = {};\n\n/**\n * Parse and validate a single field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseFieldConfig = (args) => {\n  const { config, context } = args;\n  const { name, widget: fieldType = 'string' } = config;\n  const { typedKeyPath } = context;\n\n  const newArgs = {\n    ...args,\n    context: {\n      ...context,\n      typedKeyPath: typedKeyPath ? `${typedKeyPath}.${name}` : name,\n    },\n  };\n\n  // A field type that isn’t built in is a custom one. It’s parsed whether or not it has been\n  // registered, because the registration itself isn’t the parser’s concern.\n  const isBuiltIn = /** @type {string[]} */ (BUILTIN_FIELD_TYPES).includes(fieldType);\n  const parser = fieldParsers[fieldType] ?? (isBuiltIn ? undefined : parseCustomFieldConfig);\n\n  checkCommonFieldOptions(newArgs);\n  parser?.(newArgs);\n\n  if (fieldType === 'date') {\n    addMessage({ ...newArgs, strKey: 'date_field_type' });\n  }\n};\n\n/**\n * Parse and validate multiple field configurations.\n * @param {Field[]} fields Array of field configs to parse.\n * @param {ConfigParserContext} context Context.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nexport const parseFields = (fields, context, collectors) => {\n  const checkNameArgs = { nameCounts: {}, strKeyBase: 'field_name', context, collectors };\n\n  fields?.forEach((config, index) => {\n    const { name } = config;\n\n    if (checkName({ ...checkNameArgs, name, index })) {\n      parseFieldConfig({ config, context, collectors });\n    }\n  });\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { parseFieldConfig, parseFields } from '$lib/services/config/parser/fields/registry';\nimport { checkObjectDefault } from '$lib/services/config/parser/utils/defaults';\nimport { getSubFields } from '$lib/services/config/parser/utils/fields';\nimport { checkThumbnailField } from '$lib/services/config/parser/utils/references';\nimport { addMessage, checkName } from '$lib/services/config/parser/utils/validator';\nimport { BUILTIN_FIELD_TYPES } from '$lib/services/contents/fields';\n\n/**\n * @import {\n * ComplexListFieldBaseProps,\n * Field,\n * ListField,\n * ListFieldWithSubField,\n * ListFieldWithSubFields,\n * ListFieldWithTypes,\n * RelationField,\n * SelectField,\n * StringField,\n * } from '$lib/types/public';\n * @import {\n * ConfigParserCollectors,\n * ConfigParserContext,\n * FieldParserArgs,\n * } from '$lib/types/private';\n */\n\n/**\n * Field types that can hold the key of a List field item stored as a map, as each of them has a\n * single string value.\n */\nconst MAP_KEY_FIELD_TYPES = ['string', 'relation', 'select'];\n\n/**\n * Check if the field type is valid for a List field’s variable type.\n * @param {string} fieldType Field type.\n * @param {ConfigParserContext} context Context.\n * @param {ConfigParserCollectors} collectors Collectors.\n * @returns {boolean} Whether the field type is valid.\n */\nexport const checkFieldType = (fieldType, context, collectors) => {\n  if (fieldType !== 'object') {\n    addMessage({\n      strKey: 'invalid_list_variable_type',\n      context,\n      values: { widget: fieldType },\n      collectors,\n    });\n\n    return false;\n  }\n\n  return true;\n};\n\n/**\n * Field types whose value is an object, so a List field with one of them as its single `field`\n * holds objects rather than plain values.\n */\nconst OBJECT_FIELD_TYPES = ['keyvalue', 'object'];\n\n/**\n * Check the shape of the `default` option, which depends on how the field is configured. The JSON\n * schema only ensures it’s an array of strings or objects; what’s checked here is whether each item\n * is what the field holds: a plain value for a simple list or a list with a single `field` of a\n * plain type, an object with known properties for a list with `fields`, and an object naming one\n * of the `types` for a list with variable types. A mismatched item would be dropped or saved as-is,\n * so the user would find nothing or something unexpected in a new entry.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const checkDefaultValue = ({ config, context, collectors }) => {\n  const { default: defaultValue } = /** @type {ListField} */ (config);\n  const { field: subfield } = /** @type {ListFieldWithSubField} */ (config);\n  const { fields: subfields } = /** @type {ListFieldWithSubFields} */ (config);\n  const { types, typeKey = 'type' } = /** @type {ListFieldWithTypes} */ (config);\n\n  if (!Array.isArray(defaultValue)) {\n    return;\n  }\n\n  /** @type {any[]} */ (defaultValue).forEach((item) => {\n    if (!subfields && !types) {\n      // A simple list holds plain values; so does a list whose single `field` is a plain type. A\n      // custom field type can hold anything, so it’s left alone\n      const { widget: subfieldType = 'string' } = subfield ?? {};\n\n      const holdsObjects =\n        !!subfield &&\n        (OBJECT_FIELD_TYPES.includes(subfieldType) ||\n          !(/** @type {string[]} */ (BUILTIN_FIELD_TYPES).includes(subfieldType)));\n\n      if (isObject(item) && !holdsObjects) {\n        addMessage({ strKey: 'list_field_invalid_default_object', context, collectors });\n      }\n\n      return;\n    }\n\n    if (!isObject(item)) {\n      addMessage({\n        strKey: 'list_field_invalid_default_item',\n        values: { value: String(item) },\n        context,\n        collectors,\n      });\n\n      return;\n    }\n\n    checkObjectDefault({\n      value: item,\n      fields: subfields,\n      types,\n      typeKey,\n      strKeyBase: 'list_field',\n      context,\n      collectors,\n    });\n  });\n};\n\n/**\n * Check the `map_key_field` option, which names the subfield whose value becomes the key of each\n * item when the list is stored as a map. The subfield has to be a required String, Relation or\n * Select field that exists in every locale, and with variable types, every type has to have it, or\n * some items would have no key. A Relation or Select field can’t take multiple values, which can’t\n * make a single key, and a Select field’s options must have string values, as a key read back from\n * a file is always a string. A list of plain values or with a single `field` has no subfields to\n * take a key from.\n * @param {FieldParserArgs} args Arguments.\n * @see https://github.com/sveltia/sveltia-cms/issues/1077\n * @see https://github.com/sveltia/sveltia-cms/issues/1082\n */\nexport const checkMapKeyField = ({ config, context, collectors }) => {\n  const { fields: subfields } = /** @type {ListFieldWithSubFields} */ (config);\n  const { types } = /** @type {ListFieldWithTypes} */ (config);\n\n  const { map_key_field: name } = /** @type {ListFieldWithSubFields | ListFieldWithTypes} */ (\n    config\n  );\n\n  // A value of another type is reported against the JSON schema\n  if (typeof name !== 'string' || !name) {\n    return;\n  }\n\n  if (!subfields && !types) {\n    addMessage({ strKey: 'list_field_map_key_no_subfields', context, collectors });\n\n    return;\n  }\n\n  /**\n   * Check the key subfield among the given fields.\n   * @param {Field[]} fields Subfields of the list, or of one of its types.\n   * @param {string} [type] Name of the variable type, if any.\n   */\n  const checkSubFields = (fields, type) => {\n    const subfield = fields.find((field) => field.name === name);\n\n    if (!subfield) {\n      addMessage({\n        strKey: type ? 'list_field_map_key_missing_in_type' : 'list_field_map_key_not_found',\n        values: { name, type },\n        context,\n        collectors,\n      });\n\n      return;\n    }\n\n    const { widget: fieldType = 'string', i18n } = subfield;\n    const { required = true } = /** @type {StringField} */ (subfield);\n\n    if (!MAP_KEY_FIELD_TYPES.includes(fieldType)) {\n      addMessage({\n        strKey: 'list_field_map_key_invalid_type',\n        values: { name, widget: fieldType },\n        context,\n        collectors,\n      });\n    }\n\n    if (/** @type {RelationField | SelectField} */ (subfield).multiple === true) {\n      addMessage({\n        strKey: 'list_field_map_key_multiple',\n        values: { name },\n        context,\n        collectors,\n      });\n    }\n\n    const { options } = /** @type {SelectField} */ (subfield);\n\n    // Options of another type are reported against the JSON schema\n    if (\n      fieldType === 'select' &&\n      Array.isArray(options) &&\n      options.some((option) => typeof (isObject(option) ? option.value : option) !== 'string')\n    ) {\n      addMessage({\n        strKey: 'list_field_map_key_option_not_string',\n        values: { name },\n        context,\n        collectors,\n      });\n    }\n\n    // An item can’t be saved without a key, so the subfield can’t be optional in any locale\n    if (required !== true) {\n      addMessage({\n        strKey: 'list_field_map_key_not_required',\n        values: { name },\n        context,\n        collectors,\n      });\n    }\n\n    // A subfield that only exists in the default locale would leave the items in the other locales\n    // without a key\n    if (i18n === false || i18n === 'none') {\n      addMessage({\n        strKey: 'list_field_map_key_not_localized',\n        values: { name },\n        context,\n        collectors,\n      });\n    }\n  };\n\n  if (subfields) {\n    checkSubFields(subfields);\n  } else {\n    types.forEach(({ name: type, fields = [] }) => checkSubFields(fields, type));\n  }\n};\n\n/**\n * Parse and validate a List field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseListFieldConfig = (args) => {\n  const { config, context, collectors } = args;\n  const { field: subfield } = /** @type {ListFieldWithSubField} */ (config);\n  const { fields: subfields } = /** @type {ListFieldWithSubFields} */ (config);\n  const { types } = /** @type {ListFieldWithTypes} */ (config);\n  const { thumbnail } = /** @type {ComplexListFieldBaseProps} */ (config);\n  const { typedKeyPath } = context;\n  const checkNameArgs = { nameCounts: {}, strKeyBase: 'variable_type', collectors };\n\n  // Validate mutually exclusive options\n  if ((subfield && subfields) || (subfield && types) || (subfields && types)) {\n    addMessage({\n      strKey: 'invalid_list_field',\n      context,\n      collectors,\n    });\n\n    return;\n  }\n\n  // An empty list of subfields or variable types makes every item an empty object. A list without\n  // any of the options is a plain list of strings, so only an explicit empty list is a mistake\n  if (subfields?.length === 0 || types?.length === 0) {\n    addMessage({ strKey: 'list_field_no_subfields', context, collectors });\n\n    return;\n  }\n\n  checkDefaultValue(args);\n  checkMapKeyField(args);\n\n  // The `thumbnail` option names a subfield of an item, or the single subfield\n  checkThumbnailField({ thumbnail, fields: getSubFields(config), context, collectors });\n\n  // Handle single subfield\n  if (subfield) {\n    parseFieldConfig({\n      config: subfield,\n      context: { ...context, typedKeyPath: `${typedKeyPath}.*` },\n      collectors,\n    });\n  }\n\n  // Handle subfields\n  if (subfields) {\n    parseFields(subfields, { ...context, typedKeyPath: `${typedKeyPath}.*` }, collectors);\n  }\n\n  // Handle variable types\n  types?.forEach(({ name, widget: fieldType = 'object', fields: typedFields }, index) => {\n    const newContext = { ...context, typedKeyPath: `${typedKeyPath}.*<${name}>` };\n\n    if (\n      checkName({ ...checkNameArgs, name, index, context: newContext }) &&\n      checkFieldType(fieldType, newContext, collectors) &&\n      typedFields\n    ) {\n      parseFields(typedFields, newContext, collectors);\n    }\n  });\n};\n","import { addMessage, checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\nimport { parseNumber } from '$lib/services/contents/fields/number/helpers';\n\n/**\n * @import { FieldParserArgs, UnsupportedOption } from '$lib/types/private';\n * @import { NumberField } from '$lib/types/public';\n */\n\n/**\n * Unsupported options for Number fields.\n * @type {UnsupportedOption[]}\n */\nconst UNSUPPORTED_OPTIONS = [\n  // Deprecated camelCase option in Netlify/Decap CMS config, should be converted to snake_case.\n  { prop: 'valueType', newProp: 'value_type' },\n];\n\n/**\n * Value types that store an integer.\n */\nconst INTEGER_VALUE_TYPES = ['int', 'int/string'];\n/**\n * Value types that store a floating-point number.\n */\nconst FLOAT_VALUE_TYPES = ['float', 'float/string'];\n\n/**\n * Check that the `default` option is a number of the `value_type`. A default that doesn’t parse as\n * one is dropped at runtime, so the field comes up empty in a new entry.\n * @param {FieldParserArgs} args Arguments.\n */\nconst checkDefaultValue = ({ config, context, collectors }) => {\n  const { default: defaultValue, value_type: valueType = 'int' } = /** @type {NumberField} */ (\n    config\n  );\n\n  // A default or value type of the wrong type is reported against the JSON schema\n  if (!['string', 'number'].includes(typeof defaultValue)) {\n    return;\n  }\n\n  const isInteger = INTEGER_VALUE_TYPES.includes(valueType);\n\n  if (!isInteger && !FLOAT_VALUE_TYPES.includes(valueType)) {\n    return;\n  }\n\n  // Parse a string the same way the runtime does: as a whole, so a default like `10px` is reported\n  const value = parseNumber(defaultValue);\n\n  if (isInteger ? !Number.isInteger(value) : !Number.isFinite(value)) {\n    addMessage({\n      strKey: isInteger ? 'number_field_default_not_integer' : 'number_field_default_not_number',\n      values: { value: String(defaultValue), valueType },\n      context,\n      collectors,\n    });\n  }\n};\n\n/**\n * Parse and validate a Number field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseNumberFieldConfig = (args) => {\n  const { config, context, collectors } = args;\n  const { step } = /** @type {NumberField} */ (config);\n\n  checkDefaultValue(args);\n\n  // A step of zero or less leaves the arrow keys and buttons with nowhere to go, except `-1`, which\n  // turns them off. A value of another type is reported against the JSON schema\n  if (typeof step === 'number' && step <= 0 && step !== -1) {\n    addMessage({ strKey: 'invalid_step', values: { step: String(step) }, context, collectors });\n  }\n\n  checkUnsupportedOptions({ ...args, UNSUPPORTED_OPTIONS });\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { parseFields } from '$lib/services/config/parser/fields/registry';\nimport { checkObjectDefault } from '$lib/services/config/parser/utils/defaults';\nimport { getSubFields } from '$lib/services/config/parser/utils/fields';\nimport { checkThumbnailField } from '$lib/services/config/parser/utils/references';\nimport { addMessage, checkName } from '$lib/services/config/parser/utils/validator';\n\n/**\n * @import { ObjectField, ObjectFieldWithSubFields, ObjectFieldWithTypes } from '$lib/types/public';\n * @import { FieldParserArgs } from '$lib/types/private';\n */\n\n/**\n * Parse and validate an Object field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseObjectFieldConfig = (args) => {\n  const { config, context, collectors } = args;\n  const { fields: subfields } = /** @type {ObjectFieldWithSubFields} */ (config);\n  const { types, typeKey } = /** @type {ObjectFieldWithTypes} */ (config);\n  const { default: defaultValue, thumbnail } = /** @type {ObjectField} */ (config);\n  const { typedKeyPath } = context;\n  const checkNameArgs = { nameCounts: {}, strKeyBase: 'variable_type', collectors };\n\n  // Validate mutually exclusive options\n  if (subfields && types) {\n    addMessage({\n      strKey: 'invalid_object_field',\n      context,\n      collectors,\n    });\n\n    return;\n  }\n\n  // An empty list of subfields or variable types makes the field an empty object. One of the\n  // options is required by the JSON schema, so only an explicit empty list is checked here\n  if (subfields?.length === 0 || types?.length === 0) {\n    addMessage({ strKey: 'object_field_no_subfields', context, collectors });\n\n    return;\n  }\n\n  // The `default` object holds subfield values, or names a variable type. A value of another type\n  // is reported against the JSON schema\n  if (isObject(defaultValue)) {\n    checkObjectDefault({\n      value: defaultValue,\n      fields: subfields,\n      types,\n      typeKey,\n      strKeyBase: 'object_field',\n      context,\n      collectors,\n    });\n  }\n\n  // The `thumbnail` option names a subfield\n  checkThumbnailField({ thumbnail, fields: getSubFields(config), context, collectors });\n\n  // Handle subfields\n  if (subfields) {\n    parseFields(subfields, context, collectors);\n  }\n\n  // Handle variable types\n  types?.forEach(({ name, fields: typedFields }, index) => {\n    const newContext = { ...context, typedKeyPath: `${typedKeyPath}<${name}>` };\n\n    if (checkName({ ...checkNameArgs, name, index, context: newContext }) && typedFields) {\n      parseFields(typedFields, newContext, collectors);\n    }\n  });\n};\n","import { getPathInfo } from '@sveltia/utils/file';\n\nimport { getTemplateTags } from '$lib/services/common/template/tags';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { hasLocalePlaceholder } from '$lib/services/contents/i18n/placeholder';\nimport { getPublishMode, isWorkflowMode } from '$lib/services/workflow/config';\n\n/**\n * @import { CmsConfig, EntryCollection, GitHubBackend } from '$lib/types/public';\n * @import { ConfigParserCollectors } from '$lib/types/private';\n */\n\n/**\n * Entry collection options that assume one file per entry, which a collection storing all the\n * entries in one file can’t have.\n * @type {string[]}\n */\nconst UNSUPPORTED_OPTIONS = [\n  'extension',\n  'path',\n  'slug',\n  'slug_length',\n  'nested',\n  'meta',\n  'index_file',\n  'reorder',\n];\n\n/**\n * Check if the given template contains the `{{slug}}` tag. In a collection storing all the entries\n * in one file, the slug of an entry is its position in the array, which changes when the entries\n * are reordered or one is deleted, so it can’t identify the entry outside the CMS.\n * @param {string} template Template, e.g. `/members/{{slug}}`.\n * @returns {boolean} Result.\n */\nexport const hasSlugTag = (template) =>\n  // A tag can come with transformations, e.g. `{{slug | upper}}`\n  getTemplateTags(template).some(({ name }) => name === 'slug');\n\n/**\n * Validate an entry collection storing all the entries in one file, defined with the `file` option.\n * The file must be a JSON file, which holds the entries as an array of objects.\n * @param {object} context Context.\n * @param {CmsConfig} context.cmsConfig Raw CMS configuration.\n * @param {EntryCollection} context.collection Collection config to parse.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nexport const checkArrayFileOptions = (context, collectors) => {\n  const { cmsConfig, collection } = context;\n  const { file, format, preview_path: previewPath, thumbnail } = collection;\n\n  // The type of the `file` option is checked against the JSON schema\n  if (typeof file !== 'string') {\n    return;\n  }\n\n  // A translation is stored in each object, so the file can’t be localized\n  if (getPathInfo(file).extension !== 'json' || hasLocalePlaceholder(file)) {\n    addMessage({ strKey: 'invalid_collection_data_file', values: { file }, context, collectors });\n  }\n\n  if (format !== undefined && format !== 'json') {\n    addMessage({\n      strKey: 'file_format_mismatch',\n      values: { extension: 'json', format },\n      context,\n      collectors,\n    });\n  }\n\n  UNSUPPORTED_OPTIONS.forEach((prop) => {\n    if (prop in collection) {\n      addMessage({\n        strKey: 'unsupported_collection_data_file_option',\n        values: { prop },\n        context,\n        collectors,\n      });\n    }\n  });\n\n  // A preview URL or a thumbnail file path made from the position would point to another entry once\n  // the entries have been reordered. A value of the wrong type is reported against the JSON schema\n  /** @type {[string, unknown][]} */ ([\n    ['preview_path', previewPath],\n    // A thumbnail path starts with a slash, while a field key path can’t contain the tag\n    ...(Array.isArray(thumbnail) ? thumbnail : [thumbnail]).map((path) => ['thumbnail', path]),\n  ]).forEach(([prop, template]) => {\n    if (typeof template === 'string' && hasSlugTag(template)) {\n      addMessage({\n        strKey: 'collection_data_file_slug_tag',\n        values: { prop },\n        context,\n        collectors,\n      });\n    }\n  });\n\n  // A workflow saves each entry on a branch of its own, so two entries would be two pull\n  // requests changing the same file, and merging or deleting one could remove the other entries.\n  // An Open Authoring contributor always goes through the workflow\n  if (\n    isWorkflowMode(getPublishMode({ cmsConfig, collection })) ||\n    /** @type {GitHubBackend | undefined} */ (cmsConfig.backend)?.open_authoring\n  ) {\n    addMessage({ strKey: 'collection_data_file_workflow', context, collectors });\n  }\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { getTemplateTags } from '$lib/services/common/template/tags';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { hasSlugTag } from '$lib/services/config/parser/collections/array-file';\nimport { checkMultipleDefault } from '$lib/services/config/parser/utils/defaults';\nimport {\n  getCanonicalSlugKey,\n  hasField,\n  isNonFieldSortKey,\n} from '$lib/services/config/parser/utils/fields';\nimport { addMessage, checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\nimport { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { getPublishMode, isWorkflowMode } from '$lib/services/workflow/config';\n\n/**\n * @import {\n * ConfigParserCollectors,\n * ConfigParserContext,\n * FieldParserArgs,\n * InternalSingletonCollection,\n * UnsupportedOption,\n * } from '$lib/types/private';\n * @import {\n * Collection,\n * CollectionDivider,\n * CollectionFile,\n * EntryCollection,\n * Field,\n * RelationField,\n * } from '$lib/types/public';\n */\n\n/**\n * Template tags that can be used in the `value_field` option but don’t refer to a field in the\n * referenced collection or file: `{{slug}}` is the entry slug and `{{locale}}` is the locale of the\n * entry. Note that the `slug` field of an entry is referenced as `{{fields.slug}}` or `slug`.\n * @type {string[]}\n */\nconst SPECIAL_TEMPLATE_TAGS = ['slug', 'locale'];\n\n/**\n * Unsupported options for Relation fields.\n * @type {UnsupportedOption[]}\n */\nconst UNSUPPORTED_OPTIONS = [\n  // Deprecated camelCase options in Netlify/Decap CMS config, should be converted to snake_case.\n  { prop: 'displayFields', newProp: 'display_fields' },\n  { prop: 'searchFields', newProp: 'search_fields' },\n  { prop: 'valueField', newProp: 'value_field' },\n  // Sveltia CMS doesn’t have performance issues with many related entries, so this option is not\n  // applicable.\n  { type: 'warning', prop: 'options_length', strKey: 'unsupported_ignored_option' },\n];\n\n/**\n * Options of a Relation field that refer to fields defined in the referenced collection or file,\n * with the i18n string key used to report an unknown one. A reference is either a plain field name\n * or a template, with the same syntax; `display_fields` and `search_fields` hold a list of them.\n * @type {{ option: string, strKey: string, list: boolean }[]}\n */\nconst FIELD_REFERENCE_OPTIONS = [\n  { option: 'value_field', strKey: 'relation_field_invalid_value_field', list: false },\n  { option: 'display_fields', strKey: 'relation_field_invalid_display_field', list: true },\n  { option: 'search_fields', strKey: 'relation_field_invalid_search_field', list: true },\n];\n\n/**\n * Validate a field reference in a Relation field option, which refers to one or more fields defined\n * in the referenced collection or file. An unknown key path is not reported at runtime — the widget\n * silently falls back to the entry summary or slug — so the stored, displayed or searched values\n * end up being something other than what the configuration asks for.\n * @param {object} args Arguments.\n * @param {string} args.reference The reference, e.g. `userId`, `name.first`, `cities.*.id` or\n * `{{locale}}/{{slug}}`.\n * @param {string} args.strKey The i18n string key for an unknown field.\n * @param {Field[]} args.fields Fields defined in the referenced collection or file.\n * @param {string | undefined} args.canonicalSlugKey The canonical slug key of the referenced\n * collection or file, if i18n is enabled. It’s not a field but can be referred to as one.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst checkFieldReference = ({\n  reference,\n  strKey,\n  fields,\n  canonicalSlugKey,\n  context,\n  collectors,\n}) => {\n  const tags = getTemplateTags(reference).map(({ content }) => content);\n\n  // A plain field name like `userId` is equivalent to `{{userId}}`, meaning that `slug` refers to\n  // the `slug` field while `{{slug}}` refers to the entry slug\n  const keyPaths = tags.length\n    ? tags.filter((tag) => !SPECIAL_TEMPLATE_TAGS.includes(tag))\n    : [reference];\n\n  keyPaths.forEach((keyPath) => {\n    // The `fields.` prefix is supported for compatibility with other config options\n    const key = stripFieldTagPrefix(keyPath);\n\n    if (key !== canonicalSlugKey && !hasField(fields, key)) {\n      addMessage({ strKey, context, collectors, values: { field: keyPath } });\n    }\n  });\n};\n\n/**\n * Validate the `value_field`, `display_fields` and `search_fields` options of a Relation field\n * against the fields defined in the referenced collection or file.\n * @param {object} args Arguments.\n * @param {RelationField} args.fieldConfig Relation field configuration.\n * @param {Field[]} args.fields Fields defined in the referenced collection or file.\n * @param {string | undefined} args.canonicalSlugKey The canonical slug key of the referenced\n * collection or file, if i18n is enabled.\n * @param {string | undefined} args.orderFieldKey The reorder field key of the referenced\n * collection, if any. It can be a sort key without being defined as a field.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst checkFieldReferences = ({\n  fieldConfig,\n  fields,\n  canonicalSlugKey,\n  orderFieldKey,\n  context,\n  collectors,\n}) => {\n  const { file: fileName, filters, sort_by: sortBy } = fieldConfig;\n\n  // A filter’s `field` is a single key path, where `slug` is the entry slug and the `fields.`\n  // prefix marks a field, the same as in a template. A filter on an unknown field matches no\n  // entry, so the field is left with nothing to choose from\n  if (Array.isArray(filters)) {\n    filters.forEach((filter) => {\n      const field = isObject(filter) ? filter.field : undefined;\n\n      if (typeof field === 'string' && field && field !== 'slug') {\n        const key = stripFieldTagPrefix(field);\n\n        if (key !== canonicalSlugKey && !hasField(fields, key)) {\n          addMessage({\n            strKey: 'relation_field_invalid_filter_field',\n            context,\n            collectors,\n            values: { field },\n          });\n        }\n      }\n    });\n  }\n\n  // The sort field is a single key path like a `sortable_fields` key, where `slug` is the entry\n  // slug. An unknown field leaves every entry without a value, so the options aren’t sorted. The\n  // option is ignored for a referenced file, which is reported separately\n  const sortField = isObject(sortBy) ? sortBy.field : undefined;\n\n  if (\n    !fileName &&\n    typeof sortField === 'string' &&\n    sortField &&\n    !isNonFieldSortKey(sortField, { canonicalSlugKey, orderFieldKey }) &&\n    !hasField(fields, sortField)\n  ) {\n    addMessage({\n      strKey: 'relation_field_invalid_sort_field',\n      context,\n      collectors,\n      values: { field: sortField },\n    });\n  }\n\n  FIELD_REFERENCE_OPTIONS.forEach(({ option, strKey, list }) => {\n    const value = /** @type {Record<string, any>} */ (fieldConfig)[option];\n\n    // A value of the wrong type is reported against the JSON schema, so it’s skipped here, and so\n    // is an empty reference\n    if (Array.isArray(value) !== list) {\n      return;\n    }\n\n    /** @type {any[]} */ (list ? value : [value]).forEach((reference) => {\n      if (typeof reference === 'string' && reference) {\n        checkFieldReference({ reference, strKey, fields, canonicalSlugKey, context, collectors });\n      }\n    });\n  });\n};\n\n/**\n * Validate the `value_field` option of a Relation field referring to an entry collection that\n * stores all the entries in one file. The slug of such an entry is its position in the array, which\n * changes when the entries are reordered or one is deleted, so a stored reference would silently\n * point to another entry. The value has to come from a field instead.\n * @param {object} args Arguments.\n * @param {RelationField} args.fieldConfig Relation field configuration.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst checkArrayFileValueField = ({ fieldConfig, context, collectors }) => {\n  const { collection, value_field: valueField = '{{slug}}' } = fieldConfig;\n\n  if (hasSlugTag(valueField)) {\n    addMessage({\n      strKey: 'relation_field_array_file_slug',\n      context,\n      collectors,\n      values: { collection },\n    });\n  }\n};\n\n/**\n * Validate a Relation field in an entry collection that stores all the entries in one file, which\n * can’t refer to a collection with Editorial Workflow. Renaming or deleting an entry there updates\n * the references to it in the same pull request, but the file can only be written as a whole on\n * the configured branch, so the pull request would replace the file with the one entry holding the\n * reference.\n * @param {object} args Arguments.\n * @param {Collection | CollectionDivider | InternalSingletonCollection} args.collection Referenced\n * collection.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst checkArrayFileWorkflowRelation = ({ collection, context, collectors }) => {\n  const { cmsConfig, collection: parentCollection } = context;\n\n  if (\n    !parentCollection ||\n    !('file' in parentCollection) ||\n    typeof parentCollection.file !== 'string' ||\n    // A file/singleton collection’s entry can’t be renamed or deleted\n    'divider' in collection ||\n    'files' in collection ||\n    !isWorkflowMode(getPublishMode({ cmsConfig, collection }))\n  ) {\n    return;\n  }\n\n  addMessage({\n    strKey: 'relation_field_array_file_workflow',\n    context,\n    collectors,\n    values: { collection: collection.name },\n  });\n};\n\n/**\n * Parse and validate a Relation field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseRelationFieldConfig = (args) => {\n  const { config, context, collectors } = args;\n  const fieldConfig = /** @type {RelationField} */ (config);\n\n  const {\n    collection: collectionName,\n    file: fileName,\n    default: defaultValue,\n    multiple,\n  } = fieldConfig;\n\n  const { cmsConfig } = context;\n\n  // Whether the default matches an entry can only be known once the entries are loaded, but its\n  // shape is known here\n  checkMultipleDefault({ defaultValue, multiple, context, collectors });\n\n  const collection =\n    collectionName === '_singletons'\n      ? /** @type {InternalSingletonCollection} */ ({\n          name: collectionName,\n          files: cmsConfig?.singletons,\n        })\n      : cmsConfig?.collections?.find((col) => col.name === collectionName);\n\n  /** @type {CollectionFile | undefined} */\n  let file = undefined;\n  /** @type {string | undefined} */\n  let canonicalSlugKey = undefined;\n\n  // Check if the collection exists\n  if (collection) {\n    const hasFiles = 'files' in collection && Array.isArray(collection.files);\n\n    if (fileName) {\n      // Check if the file exists in the collection\n      if (hasFiles) {\n        file = /** @type {CollectionFile | undefined} */ (\n          collection.files.find((f) => 'file' in f && f.name === fileName)\n        );\n      }\n\n      if (!file) {\n        addMessage({\n          strKey: 'relation_field_invalid_collection_file',\n          context,\n          collectors,\n          values: { file: fileName },\n        });\n      }\n    } else if (hasFiles) {\n      addMessage({\n        strKey: 'relation_field_missing_file_name',\n        context,\n        collectors,\n        values: { collection: collectionName },\n      });\n    }\n\n    canonicalSlugKey = getCanonicalSlugKey({ cmsConfig, collection, file });\n\n    // A value of the wrong type is reported against the JSON schema\n    if (\n      'file' in collection &&\n      typeof collection.file === 'string' &&\n      (fieldConfig.value_field === undefined || typeof fieldConfig.value_field === 'string')\n    ) {\n      checkArrayFileValueField({ fieldConfig, context, collectors });\n    }\n\n    checkArrayFileWorkflowRelation({ collection, context, collectors });\n  } else {\n    addMessage({\n      strKey: 'relation_field_invalid_collection',\n      context,\n      collectors,\n      values: { collection: collectionName },\n    });\n  }\n\n  // The options taken from a list in a single file follow the order of the list items\n  if (fileName && fieldConfig.sort_by !== undefined) {\n    addMessage({\n      type: 'warning',\n      strKey: 'relation_field_sort_by_file_ignored',\n      context,\n      collectors,\n    });\n  }\n\n  // Check if the referenced fields exist in the target collection/file. A collection or file\n  // without fields is reported separately, so skip the check in that case to avoid a duplicate\n  // error\n  const targetFields = fileName\n    ? file?.fields\n    : /** @type {EntryCollection | undefined} */ (collection)?.fields;\n\n  if (targetFields?.length) {\n    checkFieldReferences({\n      fieldConfig,\n      fields: targetFields,\n      canonicalSlugKey,\n      orderFieldKey: getOrderFieldKey(collection),\n      context,\n      collectors,\n    });\n  }\n\n  checkUnsupportedOptions({ ...args, UNSUPPORTED_OPTIONS });\n\n  // Collect relation information for later processing\n  collectors.relationFields.add({ fieldConfig, context });\n};\n","import { addMessage, checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\nimport { BLOCK_BUTTONS, BUTTON_COMPONENTS } from '$lib/services/contents/fields/rich-text';\nimport { getComponentDef } from '$lib/services/contents/fields/rich-text/components/definitions';\nimport { isInlineComponentDef } from '$lib/services/contents/fields/rich-text/components/utils';\n\n/**\n * @import { FieldParserArgs, UnsupportedOption } from '$lib/types/private';\n * @import { MarkdownField, RichTextField } from '$lib/types/public';\n */\n\n/**\n * Unsupported options for RichText fields.\n * @type {UnsupportedOption[]}\n */\nconst UNSUPPORTED_OPTIONS = [\n  // Deprecated camelCase option in Netlify/Decap CMS config, should be converted to snake_case.\n  { prop: 'editorComponents', newProp: 'editor_components' },\n];\n\n/**\n * Check whether the given editor component is a block, which a single-line field can’t hold. The\n * built-in ones implemented as buttons are, while any other one is unless its resolved definition\n * is matched within a paragraph, as a pattern-based inline component or the built-in `image` is.\n * An unknown component isn’t reported here.\n * @param {string} name Component name.\n * @returns {boolean} Result.\n */\nconst isBlockComponent = (name) => {\n  if (/** @type {string[]} */ (BUTTON_COMPONENTS).includes(name)) {\n    return true;\n  }\n\n  const definition = getComponentDef(name);\n\n  return !!definition && !isInlineComponentDef(definition);\n};\n\n/**\n * Warn about the block-level buttons and editor components listed for a single-line field, which\n * the editor leaves out, as it only holds inline content.\n * @param {FieldParserArgs} args Arguments.\n */\nconst checkSingleLineOptions = ({ config, context, collectors }) => {\n  const {\n    multiline = context.cmsConfig?.field_defaults?.richtext?.multiline ?? true,\n    buttons,\n    editor_components: editorComponents,\n  } = /** @type {MarkdownField | RichTextField} */ (config);\n\n  if (multiline !== false) {\n    return;\n  }\n\n  /**\n   * Each option with its listed names, and the check for a block-level item.\n   * @type {[string, string[] | undefined, (name: string) => boolean][]}\n   */\n  const options = [\n    // An unknown button name is reported against the JSON schema instead\n    ['buttons', buttons, (name) => /** @type {string[]} */ (BLOCK_BUTTONS).includes(name)],\n    ['editor_components', editorComponents, isBlockComponent],\n  ];\n\n  options.forEach(([option, names, isBlock]) => {\n    if (!Array.isArray(names)) {\n      return;\n    }\n\n    names.filter(isBlock).forEach((name) => {\n      addMessage({\n        type: 'warning',\n        strKey: 'single_line_block_item',\n        values: { option, name },\n        context,\n        collectors,\n      });\n    });\n  });\n};\n\n/**\n * Parse and validate a RichText field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseRichTextFieldConfig = (args) => {\n  checkUnsupportedOptions({ ...args, UNSUPPORTED_OPTIONS });\n  checkSingleLineOptions(args);\n};\n","import { parseCodeFieldConfig } from '$lib/services/config/parser/fields/code';\nimport { parseComputeFieldConfig } from '$lib/services/config/parser/fields/compute';\nimport { parseDateTimeFieldConfig } from '$lib/services/config/parser/fields/datetime';\nimport { parseFileFieldConfig } from '$lib/services/config/parser/fields/file';\nimport { parseHiddenFieldConfig } from '$lib/services/config/parser/fields/hidden';\nimport { parseListFieldConfig } from '$lib/services/config/parser/fields/list';\nimport { parseNumberFieldConfig } from '$lib/services/config/parser/fields/number';\nimport { parseObjectFieldConfig } from '$lib/services/config/parser/fields/object';\nimport { fieldParsers } from '$lib/services/config/parser/fields/registry';\nimport { parseRelationFieldConfig } from '$lib/services/config/parser/fields/relation';\nimport { parseRichTextFieldConfig } from '$lib/services/config/parser/fields/rich-text';\nimport { parseSelectFieldConfig } from '$lib/services/config/parser/fields/select';\n\nexport { parseFieldConfig, parseFields } from '$lib/services/config/parser/fields/registry';\n\n// Register the built-in field parsers. See `registry.js` for why they aren’t imported there.\nObject.assign(fieldParsers, {\n  code: parseCodeFieldConfig,\n  compute: parseComputeFieldConfig,\n  datetime: parseDateTimeFieldConfig,\n  file: parseFileFieldConfig,\n  hidden: parseHiddenFieldConfig,\n  image: parseFileFieldConfig, // alias\n  list: parseListFieldConfig,\n  markdown: parseRichTextFieldConfig, // alias\n  number: parseNumberFieldConfig,\n  object: parseObjectFieldConfig,\n  relation: parseRelationFieldConfig,\n  richtext: parseRichTextFieldConfig,\n  select: parseSelectFieldConfig,\n});\n","import { isObject } from '@sveltia/utils/object';\n\nimport { checkMultipleDefault } from '$lib/services/config/parser/utils/defaults';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\n\n/**\n * @import { FieldParserArgs } from '$lib/types/private';\n * @import { SelectField, SelectFieldValue } from '$lib/types/public';\n */\n\n/**\n * Parse and validate a Select field configuration. The shape of the `options` list is checked\n * against the JSON schema; what’s checked here is whether the list makes a usable field: one with\n * something to choose from, where each choice can be told apart, and where the `default` is one of\n * the choices rather than a value that can never be selected again once changed, in the shape the\n * `multiple` option calls for.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseSelectFieldConfig = ({ config, context, collectors }) => {\n  const { options, default: defaultValue, multiple } = /** @type {SelectField} */ (config);\n\n  checkMultipleDefault({ defaultValue, multiple, context, collectors });\n\n  if (!Array.isArray(options)) {\n    return;\n  }\n\n  if (!options.length) {\n    addMessage({ strKey: 'select_field_no_options', context, collectors });\n\n    return;\n  }\n\n  /** @type {SelectFieldValue[]} */\n  const values = options.map((option) => (isObject(option) ? option.value : option));\n\n  new Set(values.filter((value, index) => values.indexOf(value) !== index)).forEach((value) => {\n    addMessage({\n      strKey: 'select_field_duplicate_option',\n      values: { value: String(value) },\n      context,\n      collectors,\n    });\n  });\n\n  // An empty `default:` line in YAML is `null`, which means no default unless `null` is an option\n  if (defaultValue === undefined || (defaultValue === null && !values.includes(null))) {\n    return;\n  }\n\n  // A default can be given as an option object, whose `value` is what gets saved\n  /** @type {any[]} */ (Array.isArray(defaultValue) ? defaultValue : [defaultValue]).forEach(\n    (option) => {\n      const value = isObject(option) ? option.value : option;\n\n      if (!values.includes(value)) {\n        addMessage({\n          strKey: 'select_field_invalid_default',\n          values: { value: String(value) },\n          context,\n          collectors,\n        });\n      }\n    },\n  );\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { warnDeprecation } from '$lib/services/config/deprecations';\nimport { getSubFields } from '$lib/services/config/parser/utils/fields';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { I18N_STRUCTURES } from '$lib/services/contents/i18n/config/constants';\nimport { mergeI18nConfigs } from '$lib/services/contents/i18n/config/merge';\nimport { isFieldLocalized } from '$lib/services/contents/i18n/fields';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import {\n * CmsConfig,\n * CollectionFile,\n * EntryCollection,\n * Field,\n * FileCollection,\n * I18nOptions,\n * } from '$lib/types/public';\n */\n\n/**\n * Options of an i18n configuration that define or refer to the locales. A collection or file that\n * overrides one of them changes what the others have to agree with, so the merged result is checked\n * again at that level.\n * @type {(keyof I18nOptions)[]}\n */\nconst LOCALE_OPTIONS = ['locales', 'default_locale', 'initial_locales'];\n\n/**\n * Warn about the deprecated options in an i18n configuration. This looks at the options as written\n * at each level rather than the normalized configuration, which only exists for the collections and\n * files that enable i18n, and whose structure is replaced based on the collection type and the\n * `{{locale}}` placeholder. Either would hide an option that’s about to stop working.\n * @param {I18nOptions} config I18n options as defined at the site, collection or file level.\n * @todo Remove the options prior to the 1.0 release.\n */\nconst warnDeprecatedOptions = (config) => {\n  if (config.save_all_locales !== undefined) {\n    warnDeprecation('save_all_locales');\n  }\n\n  if (config.omit_default_locale_from_filename !== undefined) {\n    warnDeprecation('omit_default_locale_from_filename');\n  }\n\n  if (config.structure === I18N_STRUCTURES.MULTIPLE_FOLDERS_I18N_ROOT) {\n    warnDeprecation('multiple_folders_i18n_root');\n  }\n};\n\n/**\n * Check that the locales of an i18n configuration agree with each other. The runtime doesn’t\n * complain about a mismatch: an empty `locales` list quietly disables i18n, a `default_locale`\n * that isn’t listed is replaced with the first locale, and an unknown locale in `initial_locales`\n * is dropped, each of which looks like a working configuration until content is saved in the wrong\n * place.\n * @param {I18nOptions} config Merged i18n configuration.\n * @param {ConfigParserContext} context Context.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nconst checkLocales = (config, context, collectors) => {\n  const { locales, default_locale: defaultLocale, initial_locales: initialLocales } = config;\n\n  // The type of each option is checked against the JSON schema\n  if (!Array.isArray(locales)) {\n    return;\n  }\n\n  if (!locales.length) {\n    addMessage({ strKey: 'i18n_no_locales', context, collectors });\n\n    return;\n  }\n\n  if (typeof defaultLocale === 'string' && !locales.includes(defaultLocale)) {\n    addMessage({\n      strKey: 'i18n_invalid_default_locale',\n      values: { locale: defaultLocale },\n      context,\n      collectors,\n    });\n  }\n\n  if (Array.isArray(initialLocales)) {\n    initialLocales.forEach((locale) => {\n      if (typeof locale === 'string' && !locales.includes(locale)) {\n        addMessage({\n          strKey: 'i18n_invalid_initial_locale',\n          values: { locale },\n          context,\n          collectors,\n        });\n      }\n    });\n  }\n};\n\n/**\n * Check if any of the given fields, or their subfields at any depth, is localized with the `i18n`\n * option. A subfield inherits the option from its parent, so a localized parent counts for all of\n * its subfields.\n * @param {Field[]} fields Field list.\n * @returns {boolean} Result.\n */\nconst hasLocalizedField = (fields) =>\n  fields.some((field) => isFieldLocalized(field.i18n) || hasLocalizedField(getSubFields(field)));\n\n/**\n * Check if the given value is an array with at least one item.\n * @param {unknown} value Value.\n * @returns {value is any[]} Result.\n */\nconst isNonEmptyArray = (value) => Array.isArray(value) && !!value.length;\n\n/**\n * Parse and validate the site-level i18n configuration.\n * @param {CmsConfig} cmsConfig Raw CMS configuration.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nexport const parseI18nConfig = (cmsConfig, collectors) => {\n  const { i18n, collections, singletons } = cmsConfig;\n\n  if (!isObject(i18n)) {\n    return;\n  }\n\n  warnDeprecatedOptions(/** @type {I18nOptions} */ (i18n));\n  checkLocales(/** @type {I18nOptions} */ (i18n), { cmsConfig }, collectors);\n\n  // The site-level configuration only takes effect in the collections and singletons that enable\n  // i18n with their own `i18n` option, so without any of them, nothing can be translated. A missing\n  // or empty collection list is reported on its own\n  if (!isNonEmptyArray(collections) && !isNonEmptyArray(singletons)) {\n    return;\n  }\n\n  const isI18nEnabled = [...(collections ?? []), ...(singletons ?? [])].some(\n    (item) => !('divider' in item) && !!(/** @type {any} */ (item).i18n),\n  );\n\n  if (!isI18nEnabled) {\n    addMessage({ strKey: 'i18n_no_collections', context: { cmsConfig }, collectors });\n  }\n};\n\n/**\n * Check that a collection or collection file with i18n enabled has something to translate: an entry\n * collection or a file needs at least one localized field, and a file collection at least one file\n * with the `i18n` option, as the option of each level only takes effect on top of the one above it.\n * Without any, the other locales are left empty, which looks like a bug rather than a mistake in\n * the configuration.\n * @param {ConfigParserContext} context Context, with the `collection` and optionally the\n * `collectionFile` to check.\n * @param {ConfigParserCollectors} collectors Collectors.\n * @see https://github.com/sveltia/sveltia-cms/issues/577\n */\nconst checkI18nTargets = (context, collectors) => {\n  const { collection, collectionFile } = context;\n\n  if (collectionFile) {\n    const { fields } = /** @type {CollectionFile} */ (collectionFile);\n\n    // A missing or empty field list is reported on its own\n    if (isNonEmptyArray(fields) && !hasLocalizedField(fields)) {\n      addMessage({ strKey: 'collection_file_i18n_no_fields', context, collectors });\n    }\n\n    return;\n  }\n\n  if ('files' in /** @type {any} */ (collection)) {\n    const { files } = /** @type {FileCollection} */ (collection);\n    // A file divider doesn’t count, and a collection without files is reported on its own\n    const fileList = Array.isArray(files) ? files.filter((file) => !('divider' in file)) : [];\n\n    if (fileList.length && !fileList.some((file) => !!file.i18n)) {\n      addMessage({ strKey: 'collection_i18n_no_files', context, collectors });\n    }\n\n    return;\n  }\n\n  const { fields, index_file: indexFile } = /** @type {EntryCollection} */ (collection);\n\n  // A missing or empty field list is reported on its own. An index file can define its own fields,\n  // which count as well\n  if (\n    isNonEmptyArray(fields) &&\n    !hasLocalizedField([...fields, ...(isObject(indexFile) ? (indexFile.fields ?? []) : [])])\n  ) {\n    addMessage({ strKey: 'collection_i18n_no_fields', context, collectors });\n  }\n};\n\n/**\n * Check the `i18n` option of a collection or collection file, whichever the context names.\n *\n * The option only takes effect on top of the site-level configuration, and a file’s only on top of\n * its collection’s, so one set without the other silently leaves the collection or file\n * monolingual. When the option overrides the locales, the merged result is checked the same way as\n * the site-level configuration: a `default_locale` inherited from the site may not be among the\n * locales a collection lists for itself.\n * @param {ConfigParserContext} context Context, with the `collection` and optionally the\n * `collectionFile` to check.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nexport const checkI18nOverrides = (context, collectors) => {\n  const { cmsConfig, collection, collectionFile } = context;\n\n  const { i18n: option } =\n    collectionFile ?? /** @type {{ i18n?: boolean | I18nOptions }} */ (collection);\n\n  if (!option) {\n    return;\n  }\n\n  if (isObject(option)) {\n    warnDeprecatedOptions(option);\n  }\n\n  const merged = mergeI18nConfigs({\n    cmsConfig,\n    collection: /** @type {any} */ (collection),\n    file: collectionFile,\n  });\n\n  if (!merged) {\n    // A file inherits the problem from its collection, which is reported on the collection unless\n    // the collection has no option of its own\n    const reportedOnCollection =\n      !!collectionFile && !!(/** @type {any} */ (collection).i18n) && !isObject(cmsConfig?.i18n);\n\n    if (!reportedOnCollection) {\n      addMessage({ type: 'warning', strKey: 'i18n_not_configured', context, collectors });\n    }\n\n    return;\n  }\n\n  if (isObject(option) && LOCALE_OPTIONS.some((key) => key in option)) {\n    checkLocales(merged, context, collectors);\n  }\n\n  checkI18nTargets(context, collectors);\n};\n","import { getPathInfo } from '@sveltia/utils/file';\n\nimport { checkBodyField, isFormatMismatch } from '$lib/services/config/parser/collections/format';\nimport { checkPreviewPath } from '$lib/services/config/parser/collections/preview';\nimport { checkSummaryTemplate } from '$lib/services/config/parser/collections/templates';\nimport { parseFields } from '$lib/services/config/parser/fields';\nimport { checkI18nOverrides } from '$lib/services/config/parser/i18n';\nimport { checkFolderTemplateTags } from '$lib/services/config/parser/media';\nimport { addMessage, checkName } from '$lib/services/config/parser/utils/validator';\nimport {\n  getOmitDefaultLocaleOption,\n  mergeI18nConfigs,\n} from '$lib/services/contents/i18n/config/merge';\nimport {\n  canOmitLocalePlaceholder,\n  hasLocalePlaceholder,\n} from '$lib/services/contents/i18n/placeholder';\n\n/**\n * @import { CmsConfig, CollectionFile, FileCollection } from '$lib/types/public';\n * @import { ConfigParserCollectors, InternalSingletonCollection } from '$lib/types/private';\n */\n\n/**\n * Parse and validate a single collection file configuration.\n * @param {object} context Context.\n * @param {CmsConfig} context.cmsConfig Raw CMS configuration.\n * @param {FileCollection | InternalSingletonCollection} context.collection Collection config to\n * parse.\n * @param {CollectionFile} context.collectionFile File config to parse.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nexport const parseCollectionFile = (context, collectors) => {\n  const { cmsConfig, collection, collectionFile } = context;\n  // @ts-ignore singleton files don’t have `format` property on their files\n  const { file, format = collection.format, fields, i18n, summary } = collectionFile;\n\n  const { preview_path: previewPath, preview_path_date_field: previewPathDateField } =\n    collectionFile;\n\n  const { extension } = getPathInfo(file);\n\n  if (isFormatMismatch(extension, format, fields)) {\n    addMessage({\n      strKey: 'file_format_mismatch',\n      context,\n      values: { extension, format },\n      collectors,\n    });\n  }\n\n  if (!fields?.length) {\n    addMessage({ strKey: 'collection_file_no_fields', context, collectors });\n  }\n\n  if (hasLocalePlaceholder(file) && !i18n) {\n    // The `{{locale}}` placeholder in the `file` path is only valid if i18n is enabled for the\n    // collection file. Otherwise, it will be replaced with the internal `_default` locale code,\n    // which is likely not the intended behavior.\n    addMessage({ strKey: 'collection_file_i18n_required', context, collectors });\n  }\n\n  if (hasLocalePlaceholder(file) && !canOmitLocalePlaceholder(file)) {\n    // The `omit_default_locale_from_file_path` option can be set at the site, collection or file\n    // level, as can its deprecated alias. With the placeholder anywhere it can’t be removed without\n    // breaking the rest of the path, like `i18n/{{locale}}.yaml`, the option can’t apply, and the\n    // default locale is kept in the path instead, which is worth a warning\n    const config = mergeI18nConfigs({ cmsConfig, collection, file: collectionFile });\n\n    if (config?.locales?.length && getOmitDefaultLocaleOption(config)) {\n      addMessage({\n        type: 'warning',\n        strKey: 'locale_not_omitted_from_file_path',\n        values: { file },\n        context,\n        collectors,\n      });\n    }\n  }\n\n  // Validate the `i18n` option against the collection’s configuration it builds on\n  checkI18nOverrides(context, collectors);\n\n  checkFolderTemplateTags({ config: collectionFile, context, collectors });\n\n  parseFields(fields, context, collectors);\n\n  checkBodyField({\n    extension,\n    format,\n    // @ts-ignore A singleton collection doesn’t have the `body_field` option\n    bodyField: collectionFile.body_field ?? collection.body_field,\n    fields,\n    context,\n    collectors,\n  });\n\n  // A collection file’s own `preview_path` is used instead of the collection’s, not merged with\n  // it, so the fields available to fill it in are the file’s own\n  checkPreviewPath({\n    pathTemplate: previewPath,\n    dateFieldName: previewPathDateField,\n    fields: fields ?? [],\n    context,\n    collectors,\n  });\n\n  // Validate the `summary` option against the file’s fields, like an entry collection’s\n  checkSummaryTemplate({ template: summary, fields, context, collectors });\n};\n\n/**\n * Parse and validate multiple collection file configurations.\n * @param {object} context Context.\n * @param {CmsConfig} context.cmsConfig Raw CMS configuration.\n * @param {FileCollection | InternalSingletonCollection} context.collection Collection config to\n * parse.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nexport const parseCollectionFiles = (context, collectors) => {\n  const { cmsConfig, collection } = context;\n  const { files } = collection;\n  const checkNameArgs = { nameCounts: {}, strKeyBase: 'collection_file_name', collectors };\n\n  files.forEach((collectionFile, index) => {\n    // Skip file dividers\n    if ('divider' in collectionFile) return;\n\n    const { name } = collectionFile;\n    const newContext = { cmsConfig, collection, collectionFile };\n\n    if (checkName({ ...checkNameArgs, name, index, context: newContext })) {\n      parseCollectionFile(newContext, collectors);\n    }\n  });\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport {\n  findFieldByName,\n  isBulkEditableField,\n} from '$lib/services/contents/collection/entries/bulk-edit/config';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import { BulkEditOptions, Field } from '$lib/types/public';\n */\n\n/**\n * Validate the fields named with the `fields` sub-option of the collection’s `bulk_edit` option. A\n * field that doesn’t exist at the top level of the collection, or can’t be edited in bulk, is left\n * out of the bulk editor, which is hard to tell from a working configuration, so it’s reported. The\n * option type is checked against the JSON schema.\n * @param {object} args Arguments.\n * @param {boolean | BulkEditOptions | undefined} args.bulkEdit `bulk_edit` option value.\n * @param {Field[] | undefined} args.fields Collection fields.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkBulkEditFields = ({ bulkEdit, fields = [], context, collectors }) => {\n  if (!isObject(bulkEdit) || !Array.isArray(bulkEdit.fields)) {\n    return;\n  }\n\n  bulkEdit.fields.forEach((name) => {\n    const fieldConfig = findFieldByName(fields, name);\n\n    if (!fieldConfig) {\n      addMessage({\n        strKey: 'invalid_bulk_edit_field',\n        values: { name: String(name) },\n        context,\n        collectors,\n      });\n    } else if (!isBulkEditableField(fieldConfig)) {\n      addMessage({\n        strKey: 'unsupported_bulk_edit_field',\n        values: { name: String(name) },\n        context,\n        collectors,\n      });\n    }\n  });\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { getCanonicalSlugKey, hasField } from '$lib/services/config/parser/utils/fields';\nimport { addMessage, checkRegex } from '$lib/services/config/parser/utils/validator';\nimport { METADATA_KEYS } from '$lib/services/contents/collection/view/table-keys';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import { EntryCollection } from '$lib/types/public';\n */\n\n/**\n * Check the `filter` option of an entry collection. An entry that doesn’t pass the filter is left\n * out of the collection, so a filter that can never pass — one on a field no entry has, or one\n * with nothing to match against — shows up as an empty collection rather than as an error.\n * @param {object} args Arguments.\n * @param {EntryCollection} args.collection Collection config to check.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n * @see https://decapcms.org/docs/collection-folder/#filtered-folder-collections\n */\nexport const checkCollectionFilter = ({ collection, context, collectors }) => {\n  const { fields, filter } = collection;\n\n  // The type of the option is checked against the JSON schema\n  if (!isObject(filter)) {\n    return;\n  }\n\n  const { field, value, pattern } = filter;\n\n  // A collection without fields is reported separately, and a field of the wrong type against the\n  // JSON schema. A metadata key such as `slug` is read from the entry rather than its content, and\n  // the canonical slug key such as `translationKey` is part of the content without being a field\n  if (\n    typeof field === 'string' &&\n    field &&\n    !METADATA_KEYS.includes(field) &&\n    field !== getCanonicalSlugKey({ cmsConfig: context.cmsConfig, collection }) &&\n    fields?.length &&\n    !hasField(fields, field)\n  ) {\n    addMessage({ strKey: 'invalid_filter_field', values: { name: field }, context, collectors });\n  }\n\n  if (value === undefined && pattern === undefined) {\n    addMessage({ strKey: 'invalid_filter_no_condition', context, collectors });\n  }\n\n  checkRegex({ option: 'filter', pattern, context, collectors });\n};\n","import { hasField } from '$lib/services/config/parser/utils/fields';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { DEFAULT_IDENTIFIER_FIELD } from '$lib/services/contents/collection/identifier';\nimport { getConfiguredSlugTemplate, getSlugOptions } from '$lib/services/contents/collection/slug';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import { EntryCollection } from '$lib/types/public';\n */\n\n/**\n * Check the field an entry collection identifies its entries by. The field names the entry in the\n * list and, unless the `slug` option says otherwise, provides the slug of a new entry, so a field\n * that isn’t there is not a problem the runtime can report: the summary falls back to another\n * field, and a slug template tag that resolves to nothing falls back to a random ID, which is hard\n * to tell from a working configuration until the content folder fills up with such file names.\n * @param {object} args Arguments.\n * @param {EntryCollection} args.collection Collection config to check.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n * @see https://decapcms.org/docs/configuration-options/#identifier_field\n */\nexport const checkIdentifierField = ({ collection, context, collectors }) => {\n  const { create = true, fields, identifier_field: identifierField } = collection;\n\n  // A collection without fields is reported as such, and no field can be found in it anyway\n  if (!fields?.length) {\n    return;\n  }\n\n  // A field named by the option is a mistake, most likely a typo, wherever the collection uses it\n  if (identifierField !== undefined) {\n    if (typeof identifierField === 'string' && !hasField(fields, identifierField)) {\n      addMessage({\n        strKey: 'invalid_identifier_field',\n        values: { name: identifierField },\n        context,\n        collectors,\n      });\n    }\n\n    return;\n  }\n\n  const slugOptions = getSlugOptions(collection);\n\n  // Without the option, the default is only relied on to make the slug of a new entry, which a\n  // custom slug template, a slug that has to be typed in, or a numbered slug makes its own way.\n  // Netlify/Decap CMS refuses to save such an entry, but its collections can’t be created in by\n  // default, so a configuration that worked there may simply never have needed the field; it’s a\n  // warning rather than an error for that reason\n  if (\n    create &&\n    getConfiguredSlugTemplate(collection) === undefined &&\n    !slugOptions.editorRequired &&\n    !slugOptions.autoIncrement &&\n    !hasField(fields, DEFAULT_IDENTIFIER_FIELD)\n  ) {\n    addMessage({\n      type: 'warning',\n      strKey: 'missing_identifier_field',\n      values: { name: DEFAULT_IDENTIFIER_FIELD },\n      context,\n      collectors,\n    });\n  }\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { splitTemplateTags } from '$lib/services/common/template/tags';\nimport { warnDeprecation } from '$lib/services/config/deprecations';\nimport { addMessage, checkRegex } from '$lib/services/config/parser/utils/validator';\nimport {\n  getConfiguredSlugTemplate,\n  hasLegacySlugEditorTag,\n} from '$lib/services/contents/collection/slug';\nimport { I18N_STRUCTURES } from '$lib/services/contents/i18n/config/constants';\nimport { mergeI18nConfigs } from '$lib/services/contents/i18n/config/merge';\nimport { hasLocalePlaceholder } from '$lib/services/contents/i18n/placeholder';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import { CollectionSlugOptions, EntryCollection } from '$lib/types/public';\n */\n\n/**\n * I18n structures that store every locale in one file, so an entry can’t have a slug of its own in\n * each locale.\n * @type {string[]}\n */\nconst SINGLE_FILE_STRUCTURES = [\n  I18N_STRUCTURES.SINGLE_FILE,\n  I18N_STRUCTURES.SINGLE_FILE_DEFAULT_ROOT,\n];\n\n/**\n * Check the `slug` option of an entry collection. The shape of the option is checked against the\n * JSON schema; this checks what the schema can’t: the template, the validation pattern, and whether\n * the slug can be localized at all.\n * @param {object} args Arguments.\n * @param {EntryCollection} args.collection Collection config to check.\n * @param {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n * @see https://github.com/sveltia/sveltia-cms/issues/999\n */\nexport const checkSlugOptions = ({ collection, context, collectors }) => {\n  const { cmsConfig } = context;\n  const { slug, folder } = collection;\n  const template = getConfiguredSlugTemplate(collection);\n\n  // @todo Remove the legacy tags prior to the 1.0 release.\n  if (hasLegacySlugEditorTag(template)) {\n    warnDeprecation('slug_editor_tag');\n  }\n\n  // Validate slug template: should not contain slashes to avoid confusion with `path` option. Only\n  // the literal text counts: a slash in a transformation argument, as in `date('DD/MM/YYYY')`,\n  // never makes it into the slug, because a tag value is slugified\n  // @see https://github.com/decaporg/decap-cms/issues/513\n  if (template && splitTemplateTags(template).literals.some((literal) => literal.includes('/'))) {\n    addMessage({\n      strKey: 'invalid_slug_slash',\n      values: { slug: template },\n      context,\n      collectors,\n    });\n  }\n\n  if (!isObject(slug)) {\n    return;\n  }\n\n  const {\n    pattern,\n    i18n,\n    auto_increment: autoIncrement,\n  } = /** @type {CollectionSlugOptions} */ (slug);\n\n  // A numbered slug isn’t made from a template\n  if (autoIncrement === true && template !== undefined) {\n    addMessage({ type: 'warning', strKey: 'slug_template_ignored', context, collectors });\n  }\n\n  // The `pattern` option is a `[regex, message]` pair; anything else is reported against the JSON\n  // schema\n  if (Array.isArray(pattern)) {\n    checkRegex({ option: 'pattern', pattern: pattern[0], context, collectors });\n  }\n\n  if (i18n === true) {\n    const i18nConfig = mergeI18nConfigs({ cmsConfig, collection });\n    const structure = i18nConfig?.structure ?? I18N_STRUCTURES.SINGLE_FILE;\n\n    // The slug can only be localized when each locale has a file of its own. The `{{locale}}`\n    // placeholder in the `folder` option makes a folder for each locale, whatever the configured\n    // structure\n    if (\n      !i18nConfig?.locales?.length ||\n      (SINGLE_FILE_STRUCTURES.includes(structure) &&\n        !(typeof folder === 'string' && hasLocalePlaceholder(folder)))\n    ) {\n      addMessage({ type: 'warning', strKey: 'slug_i18n_ineffective', context, collectors });\n    }\n  }\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { hasComparison } from '$lib/services/common/view';\nimport { SUMMARY_SPECIAL_TAGS } from '$lib/services/config/parser/collections/templates';\nimport {\n  getCanonicalSlugKey,\n  hasField,\n  isNonFieldSortKey,\n} from '$lib/services/config/parser/utils/fields';\nimport { checkFieldReferences } from '$lib/services/config/parser/utils/references';\nimport { addMessage, checkName } from '$lib/services/config/parser/utils/validator';\nimport { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport {\n  hasDefaultSort,\n  parseCustomSortableFields,\n  parseViewOptions,\n} from '$lib/services/contents/collection/view/options';\nimport {\n  getConfiguredTableColumns,\n  isTemplateColumnKey,\n  METADATA_KEYS,\n  SUMMARY_COLUMN_KEY,\n} from '$lib/services/contents/collection/view/table-keys';\n\n/**\n * @import { ConfigParserCollectors } from '$lib/types/private';\n * @import {\n * CmsConfig,\n * EntryCollection,\n * Field,\n * ViewFilter,\n * ViewFilters,\n * ViewGroup,\n * ViewGroups,\n * } from '$lib/types/public';\n */\n\n/**\n * Validate the name and field key path of each option in the `view_groups` or `view_filters`\n * option.\n * @param {object} args Arguments.\n * @param {ViewGroup[] | ViewGroups | ViewFilter[] | ViewFilters | undefined} args.config Raw\n * configuration value.\n * @param {(ViewGroup | ViewFilter)[]} args.options Parsed view group or filter options.\n * @param {Field[]} args.fields Collection fields.\n * @param {string[]} args.specialKeys Keys that are resolved without a field definition.\n * @param {'view_group' | 'view_filter'} args.optionType Option type, used for message keys.\n * @param {object} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst checkNamedViewOptions = ({\n  config,\n  options,\n  fields,\n  specialKeys,\n  optionType,\n  context,\n  collectors,\n}) => {\n  // A `name` is required in the object (Static CMS) format, where an option is referenced by name\n  // from the `default` option, as well as the `reorder` option in the case of a group. It’s\n  // optional in the array (Netlify/Decap CMS) format, but must still be unique when provided\n  const isNameRequired = isObject(config);\n  /** @type {Record<string, number>} */\n  const nameCounts = {};\n\n  options.forEach((option, index) => {\n    const { name, field: key, pattern } = isObject(option) ? option : {};\n\n    checkName({\n      name,\n      index,\n      nameCounts,\n      strKeyBase: `${optionType}_name`,\n      context,\n      collectors,\n      required: isNameRequired,\n    });\n\n    // A group without a pattern or comparison groups the entries by the field value, but a filter\n    // has nothing to match against. The option type is checked against the JSON schema\n    if (optionType === 'view_filter' && isObject(option) && pattern === undefined) {\n      if (!hasComparison(option)) {\n        addMessage({\n          strKey: 'invalid_view_filter_no_condition',\n          values: { count: String(index + 1) },\n          context,\n          collectors,\n        });\n      }\n    }\n\n    // A missing field is not validated here, as it just disables grouping or filtering\n    if (typeof key !== 'string' || !key || specialKeys.includes(key)) {\n      return;\n    }\n\n    if (!hasField(fields, key)) {\n      addMessage({\n        strKey: `invalid_${optionType}_field`,\n        values: { name: key },\n        context,\n        collectors,\n      });\n    }\n  });\n\n  // The `default` option of the object format names one of the options. A name that matches none\n  // is silently ignored at runtime, so the collection opens without the intended view\n  const defaultName = isObject(config)\n    ? /** @type {ViewFilters | ViewGroups} */ (config).default\n    : undefined;\n\n  if (typeof defaultName === 'string' && defaultName) {\n    if (!options.some((option) => isObject(option) && option.name === defaultName)) {\n      addMessage({\n        strKey: `invalid_${optionType}_default`,\n        values: { name: defaultName },\n        context,\n        collectors,\n      });\n    }\n  }\n};\n\n/**\n * Validate the `sortable_fields`, `view_groups` and `view_filters` options of an entry collection:\n * the field key paths they refer to, and the name of each view group and filter. An unknown key\n * path is silently ignored at runtime — a sort key disappears from the Sort menu, and a group or\n * filter yields no result — which is hard to tell from a working configuration. Each of these\n * options supports both an array (Netlify/Decap CMS compatible) and an object (Static CMS\n * compatible) format, so the raw options are read through the same parsers the runtime uses, and\n * the option lookup can’t diverge from it.\n * @param {object} context Context.\n * @param {CmsConfig} context.cmsConfig Raw CMS configuration.\n * @param {EntryCollection} context.collection Collection config to parse.\n * @param {ConfigParserCollectors} collectors Collectors.\n * @see https://sveltiacms.app/en/docs/collections/entries/views\n */\nexport const checkViewOptions = (context, collectors) => {\n  const {\n    fields,\n    sortable_fields: sortableFields,\n    table_columns: tableColumns,\n    view_groups: viewGroups,\n    view_filters: viewFilters,\n  } = context.collection;\n\n  // A collection without fields is reported separately; checking key paths against an empty field\n  // list would only repeat that error for every view option\n  if (!fields?.length) {\n    return;\n  }\n\n  // A metadata key such as `slug` is read from the entry rather than its content, and the canonical\n  // slug key such as `translationKey` is part of the content without being a field\n  const canonicalSlugKey = getCanonicalSlugKey({\n    cmsConfig: context.cmsConfig,\n    collection: context.collection,\n  });\n\n  const specialKeys = [...METADATA_KEYS, ...(canonicalSlugKey ? [canonicalSlugKey] : [])];\n\n  if (sortableFields) {\n    const { keys, defaultKey } = parseCustomSortableFields(sortableFields);\n    const orderFieldKey = getOrderFieldKey(context.collection);\n\n    // `_summary` sorts by the generated entry summary, which only the entry list has. The default\n    // key is also in the list in the Decap CMS format, so it’s checked once\n    new Set([...keys, defaultKey]).forEach((key) => {\n      if (\n        key &&\n        key !== SUMMARY_COLUMN_KEY &&\n        !isNonFieldSortKey(key, { canonicalSlugKey, orderFieldKey }) &&\n        !hasField(fields, key)\n      ) {\n        addMessage({\n          strKey: 'invalid_sortable_field',\n          values: { name: key },\n          context,\n          collectors,\n        });\n      }\n    });\n\n    // Only one item in the Decap CMS format can have `default_sort`; the first one is used\n    if (Array.isArray(sortableFields) && sortableFields.filter(hasDefaultSort).length > 1) {\n      addMessage({ strKey: 'multiple_sortable_field_defaults', context, collectors });\n    }\n  }\n\n  // The columns of the table view, given with `table_columns` or its Static CMS alias\n  // `summary_fields`. The entry summary is `_summary`, the same as its sort key, or `summary` in\n  // the alias. A column naming no field would be silently left out of the table. The option types\n  // are checked against the JSON schema\n  const columns = getConfiguredTableColumns(context.collection);\n\n  if (columns) {\n    const columnOption = Array.isArray(tableColumns) ? 'table_columns' : 'summary_fields';\n\n    columns.forEach(({ key }) => {\n      // A template, e.g. `{{dirname}}/{{filename}}`, can use the same tags as a summary template\n      if (typeof key === 'string' && isTemplateColumnKey(key)) {\n        checkFieldReferences({\n          option: columnOption,\n          template: key,\n          specialTags: SUMMARY_SPECIAL_TAGS,\n          fields,\n          context,\n          collectors,\n        });\n\n        return;\n      }\n\n      if (\n        typeof key === 'string' &&\n        key &&\n        key !== SUMMARY_COLUMN_KEY &&\n        !specialKeys.includes(key) &&\n        !hasField(fields, key)\n      ) {\n        addMessage({\n          strKey: 'invalid_table_column_field',\n          values: { option: columnOption, name: key },\n          context,\n          collectors,\n        });\n      }\n    });\n  }\n\n  checkNamedViewOptions({\n    config: viewGroups,\n    options: parseViewOptions(viewGroups, 'groups').options,\n    fields,\n    specialKeys,\n    optionType: 'view_group',\n    context,\n    collectors,\n  });\n\n  checkNamedViewOptions({\n    config: viewFilters,\n    options: parseViewOptions(viewFilters, 'filters').options,\n    fields,\n    specialKeys,\n    optionType: 'view_filter',\n    context,\n    collectors,\n  });\n};\n","import { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { WORKFLOW_STAGES } from '$lib/services/workflow/constants';\n\n/**\n * @import { ConfigParserCollectors, ConfigParserContext } from '$lib/types/private';\n * @import { CmsConfig, Collection } from '$lib/types/public';\n */\n\n/**\n * Check whether the given `stages` option value lists the review stages in the canonical order,\n * starting with the drafting stage, without repeating any. The JSON schema has already checked the\n * values themselves.\n * @param {unknown[]} stages Option value.\n * @returns {boolean} Result.\n */\nconst isValidStageList = (stages) =>\n  stages[0] === 'draft' &&\n  stages.every(\n    (stage, index) =>\n      index === 0 ||\n      WORKFLOW_STAGES.indexOf(/** @type {any} */ (stage)) >\n        WORKFLOW_STAGES.indexOf(/** @type {any} */ (stages[index - 1])),\n  );\n\n/**\n * Parse and validate the `publish_mode` option, either the site-level one or a collection-level\n * one. Its type is checked against the JSON schema, so only the rules the schema can’t express are\n * checked here.\n * @param {object} args Arguments.\n * @param {CmsConfig['publish_mode'] | Collection['publish_mode']} args.value Option value.\n * @param {ConfigParserContext} args.context Context, with the collection for a collection-level\n * option.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const parsePublishMode = ({ value, context, collectors }) => {\n  if (!value || typeof value !== 'object' || !Array.isArray(value.stages)) {\n    return;\n  }\n\n  // Every pull request starts in the drafting stage, and an entry can only be published from the\n  // last stage, so the order matters\n  if (!isValidStageList(value.stages)) {\n    addMessage({ strKey: 'invalid_publish_mode_stages', context, collectors });\n  }\n\n  // The stages only apply to Editorial Workflow: Preview Workflow has the drafting stage alone, and\n  // the simple publish mode has none. A collection-level option without a type inherits the\n  // site-level one, which may well be Editorial Workflow, so it’s left alone\n  if (value.type === 'preview' || value.type === 'simple') {\n    addMessage({\n      type: 'warning',\n      strKey: 'publish_mode_stages_ignored',\n      values: { type: value.type },\n      context,\n      collectors,\n    });\n  }\n};\n","/* eslint-disable camelcase */\n\nimport { _ } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { warnDeprecation } from '$lib/services/config/deprecations';\nimport { parseCollectionFiles } from '$lib/services/config/parser/collection-files';\nimport { checkArrayFileOptions } from '$lib/services/config/parser/collections/array-file';\nimport { checkBulkEditFields } from '$lib/services/config/parser/collections/bulk-edit';\nimport { checkCollectionFilter } from '$lib/services/config/parser/collections/filter';\nimport { checkBodyField, isFormatMismatch } from '$lib/services/config/parser/collections/format';\nimport { checkIdentifierField } from '$lib/services/config/parser/collections/identifier';\nimport { checkPreviewPath } from '$lib/services/config/parser/collections/preview';\nimport { checkSlugOptions } from '$lib/services/config/parser/collections/slug';\nimport {\n  checkCollectionTemplates,\n  checkSummaryTemplate,\n} from '$lib/services/config/parser/collections/templates';\nimport { checkViewOptions } from '$lib/services/config/parser/collections/views';\nimport { parseFields } from '$lib/services/config/parser/fields';\nimport { checkI18nOverrides } from '$lib/services/config/parser/i18n';\nimport { checkFolderTemplateTags } from '$lib/services/config/parser/media';\nimport { parsePublishMode } from '$lib/services/config/parser/publish-mode';\nimport {\n  addMessage,\n  checkName,\n  checkUnsupportedOptions,\n} from '$lib/services/config/parser/utils/validator';\nimport { getReorderGroupName } from '$lib/services/contents/collection/entries/reorder/config';\nimport { parseViewOptions } from '$lib/services/contents/collection/view/options';\nimport { mergeI18nConfigs } from '$lib/services/contents/i18n/config/merge';\nimport {\n  hasLocalePlaceholder,\n  isValidLocaleFolderPath,\n} from '$lib/services/contents/i18n/placeholder';\n\n/**\n * @import {\n * CmsConfig,\n * Collection,\n * CollectionDivider,\n * CollectionIndexFile,\n * EntryCollection,\n * } from '$lib/types/public';\n * @import {\n * ConfigParserCollectors,\n * InternalSingletonCollection,\n * UnsupportedOption,\n * } from '$lib/types/private';\n */\n\n/**\n * Unsupported options for Number fields.\n * @type {UnsupportedOption[]}\n */\nconst UNSUPPORTED_OPTIONS = [\n  // Deprecated camelCase option in Netlify/Decap CMS config, should be converted to snake_case.\n  { prop: 'sortableFields', newProp: 'sortable_fields' },\n];\n\n/**\n * Parse and validate a single entry collection configuration.\n * @param {object} context Context.\n * @param {CmsConfig} context.cmsConfig Raw CMS configuration.\n * @param {EntryCollection} context.collection Collection config to parse.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nexport const parseEntryCollection = (context, collectors) => {\n  const { cmsConfig, collection } = context;\n\n  const {\n    body_field: bodyField,\n    extension,\n    fields,\n    folder,\n    format,\n    index_file,\n    preview_path,\n    preview_path_date_field,\n    reorder,\n    bulk_edit: bulkEdit,\n    slug_length: legacySlugLength,\n    view_groups,\n  } = collection;\n\n  if (isFormatMismatch(extension, format)) {\n    addMessage({\n      strKey: 'file_format_mismatch',\n      values: { extension, format },\n      context,\n      collectors,\n    });\n  }\n\n  // @todo Remove the legacy option prior to the 1.0 release.\n  if (legacySlugLength !== undefined) {\n    warnDeprecation('slug_length');\n  }\n\n  checkUnsupportedOptions({ UNSUPPORTED_OPTIONS, config: collection, context, collectors });\n\n  if (!fields?.length) {\n    addMessage({ strKey: 'collection_no_fields', context, collectors });\n  }\n\n  // Validate the `file` option and the options that can’t go with it\n  checkArrayFileOptions(context, collectors);\n\n  // The type of the `folder` option is checked against the JSON schema\n  if (typeof folder === 'string' && hasLocalePlaceholder(folder)) {\n    // The `{{locale}}` placeholder in the `folder` path is only valid if i18n is enabled for the\n    // collection, which takes the site-level configuration as well as the collection’s own `i18n`\n    // option: with either missing, `checkI18nOverrides()` merely warns that the collection stays\n    // monolingual, but the placeholder would then be replaced with the internal `_default` locale\n    // code, hiding the existing entries and saving new ones in the wrong place\n    if (!mergeI18nConfigs({ cmsConfig, collection })?.locales?.length) {\n      addMessage({ strKey: 'collection_folder_i18n_required', context, collectors });\n    }\n\n    // The placeholder stands for a folder named after the locale, and the entry path matcher can\n    // only capture one\n    if (!isValidLocaleFolderPath(folder)) {\n      addMessage({\n        strKey: 'invalid_collection_folder_locale',\n        values: { folder },\n        context,\n        collectors,\n      });\n    }\n  }\n\n  parseFields(fields, context, collectors);\n  checkBodyField({ extension, format, bodyField, fields, context, collectors });\n\n  // Validate the `identifier_field` option, and the `title` field it defaults to, against the\n  // fields. An index file has a fixed name, so its own fields don’t count\n  checkIdentifierField({ collection, context, collectors });\n\n  // Validate the `slug` option itself\n  checkSlugOptions({ collection, context, collectors });\n\n  // Validate the `slug`, `path`, `summary` and `thumbnail` options against the fields\n  checkCollectionTemplates({ collection, context, collectors });\n\n  // Validate the `filter` option, including the field it refers to\n  checkCollectionFilter({ collection, context, collectors });\n\n  if (index_file) {\n    // The index file can have an extension and format of its own, which have to agree with each\n    // other like the collection’s\n    if (\n      isObject(index_file) &&\n      isFormatMismatch(\n        /** @type {CollectionIndexFile} */ (index_file).extension,\n        /** @type {CollectionIndexFile} */ (index_file).format,\n      )\n    ) {\n      addMessage({\n        strKey: 'file_format_mismatch',\n        values: {\n          extension: /** @type {CollectionIndexFile} */ (index_file).extension,\n          format: /** @type {CollectionIndexFile} */ (index_file).format,\n        },\n        context: { cmsConfig, collection, isIndexFile: true },\n        collectors,\n      });\n    }\n\n    const indexFileContext = { cmsConfig, collection, isIndexFile: true };\n    const indexFileFields = index_file === true ? fields : (index_file.fields ?? fields);\n\n    parseFields(indexFileFields, indexFileContext, collectors);\n\n    // The index file can have fields or a format of its own, unlike the collection’s checked above.\n    // Its extension and format replace the collection’s together, as in `getIndexFileFormat()`\n    if (isObject(index_file)) {\n      const {\n        extension: indexExtension,\n        format: indexFormat,\n        fields: indexFields,\n        summary: indexSummary,\n      } = /** @type {CollectionIndexFile} */ (index_file);\n\n      const hasOwnFormat = indexExtension !== undefined || indexFormat !== undefined;\n\n      if (indexFields || hasOwnFormat) {\n        checkBodyField({\n          ...(hasOwnFormat\n            ? { extension: indexExtension, format: indexFormat }\n            : { extension, format }),\n          bodyField,\n          fields: indexFileFields,\n          context: indexFileContext,\n          collectors,\n        });\n      }\n\n      // Validate the index file’s `summary` option against the fields it uses\n      checkSummaryTemplate({\n        template: indexSummary,\n        fields: indexFileFields,\n        context: indexFileContext,\n        collectors,\n      });\n    }\n  }\n\n  // Validate the group named with the `reorder` option: an unknown name would silently fall back to\n  // an ungrouped list in reorder mode, which is hard to tell from a working configuration.\n  // `parseViewOptions()` is what `parseGroupConfig()` calls, so group lookup can’t diverge from the\n  // runtime.\n  const reorderGroupName = getReorderGroupName({ reorder });\n\n  if (reorderGroupName) {\n    const { options } = parseViewOptions(view_groups, 'groups');\n\n    if (!options.some(({ name }) => name === reorderGroupName)) {\n      addMessage({\n        strKey: 'invalid_reorder_group',\n        values: { name: reorderGroupName },\n        context,\n        collectors,\n      });\n    }\n  }\n\n  // Validate the fields named with the `bulk_edit` option: one that doesn’t exist, or can’t be\n  // edited in bulk, would silently be left out of the bulk editor\n  checkBulkEditFields({ bulkEdit, fields, context, collectors });\n\n  // Validate the `preview_path` option against the fields that can fill in its date and time tags.\n  // An index file can define its own fields, and the preview path reads from those for that entry,\n  // so a date field defined only there still counts\n  checkPreviewPath({\n    pathTemplate: preview_path,\n    dateFieldName: preview_path_date_field,\n    fields: [...(fields ?? []), ...(isObject(index_file) ? (index_file.fields ?? []) : [])],\n    context,\n    collectors,\n  });\n\n  // Validate the `sortable_fields`, `view_groups` and `view_filters` options, including the fields\n  // they refer to and the view group and filter names\n  checkViewOptions(context, collectors);\n};\n\n/**\n * Parse and validate a collection or divider configuration.\n * @param {object} context Context.\n * @param {CmsConfig} context.cmsConfig Raw CMS configuration.\n * @param {Collection | CollectionDivider} context.collection Collection config to parse.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nexport const parseCollection = ({ cmsConfig, collection }, collectors) => {\n  const hasDivider = 'divider' in collection;\n  const hasFiles = 'files' in collection;\n  const hasFolder = 'folder' in collection;\n  const hasFile = 'file' in collection;\n  const optionCount = [hasDivider, hasFiles, hasFolder, hasFile].filter(Boolean).length;\n\n  // Validate at least one option\n  if (!optionCount) {\n    addMessage({\n      strKey: 'invalid_collection_no_options',\n      context: { cmsConfig, collection: /** @type {Collection} */ (collection) },\n      collectors,\n    });\n\n    return;\n  }\n\n  // Validate mutually exclusive options\n  if (optionCount > 1) {\n    addMessage({\n      strKey: 'invalid_collection_multiple_options',\n      // @ts-ignore\n      context: { cmsConfig, collection },\n      collectors,\n    });\n\n    return;\n  }\n\n  // @todo Remove the option prior to the 1.0 release.\n  if (/** @type {Collection} */ (collection).yaml_quote !== undefined) {\n    warnDeprecation('yaml_quote');\n  }\n\n  // Validate the `i18n` option against the site-level configuration it builds on. A divider has\n  // been ruled out above\n  checkI18nOverrides({ cmsConfig, collection: /** @type {Collection} */ (collection) }, collectors);\n\n  checkFolderTemplateTags({\n    config: collection,\n    context: { cmsConfig, collection: /** @type {Collection} */ (collection) },\n    collectors,\n  });\n\n  parsePublishMode({\n    value: /** @type {Collection} */ (collection).publish_mode,\n    context: { cmsConfig, collection: /** @type {Collection} */ (collection) },\n    collectors,\n  });\n\n  if (hasFiles) {\n    parseCollectionFiles({ cmsConfig, collection }, collectors);\n  } else if (hasFolder || hasFile) {\n    parseEntryCollection({ cmsConfig, collection }, collectors);\n  }\n};\n\n/**\n * Parse and validate the collections configuration from the site config.\n * @param {CmsConfig} cmsConfig Raw CMS configuration.\n * @param {ConfigParserCollectors} collectors Collectors.\n * @throws {Error} If there is an error in the collections config.\n */\nexport const parseCollections = (cmsConfig, collectors) => {\n  const { collections, singletons } = cmsConfig;\n  const { errors } = collectors;\n\n  if (!Array.isArray(collections) && !Array.isArray(singletons)) {\n    errors.add(_('config.error.no_collection'));\n\n    return;\n  }\n\n  // Validate that at least one collection is visible in the sidebar. A config where every\n  // collection is hidden with the `hide` option — or where the list contains nothing but dividers —\n  // leaves the user with an empty UI, which looks like a broken CMS rather than a configuration\n  // mistake. Singletons are always visible, so they satisfy the requirement on their own.\n  const hasVisibleCollection =\n    !!collections?.some((collection) => !('divider' in collection) && !collection.hide) ||\n    !!singletons?.length;\n\n  if (!hasVisibleCollection) {\n    errors.add(_('config.error.no_visible_collection'));\n  }\n\n  const checkNameArgs = { nameCounts: {}, strKeyBase: 'collection_name', collectors };\n\n  collections?.forEach((collection, index) => {\n    // Skip collection dividers\n    if ('divider' in collection) return;\n\n    const { name } = collection;\n    const newContext = { cmsConfig, collection };\n\n    if (checkName({ ...checkNameArgs, name, index, context: newContext })) {\n      parseCollection(newContext, collectors);\n    }\n  });\n\n  if (Array.isArray(singletons)) {\n    /** @type {InternalSingletonCollection} */\n    const collection = {\n      name: '_singletons',\n      label: _('singletons'),\n      label_singular: _('singleton'),\n      files: singletons,\n    };\n\n    parseCollectionFiles({ cmsConfig, collection }, collectors);\n  }\n};\n","import {\n  UNSAFE_ASCII_SLUG_CHARS_REGEX,\n  UNSAFE_UNICODE_SLUG_CHARS_REGEX,\n} from '$lib/services/common/slug/constants';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\n\n/**\n * @import { CmsConfig } from '$lib/types/public';\n * @import { ConfigParserCollectors } from '$lib/types/private';\n */\n\n/**\n * Parse and validate the global `slug` options. The type of each option is checked against the JSON\n * schema, so only the rules the schema can’t express are verified here.\n * @param {CmsConfig} cmsConfig Raw CMS configuration.\n * @param {ConfigParserCollectors} collectors Collectors.\n */\nexport const parseSlugConfig = (cmsConfig, collectors) => {\n  const { encoding = 'unicode', sanitize_replacement: replacement } = cmsConfig.slug ?? {};\n\n  // The replacement stands in for the characters a slug can’t contain, so it can’t contain one of\n  // them itself: the slug would still end up with the very character the option was meant to\n  // remove, and a slash would even turn the slug into a path. An empty string is fine; it just\n  // joins the words together. So is a plain space, for file names read by people and tools rather\n  // than used as URLs, e.g. an Obsidian vault resolving `[[Sourdough focaccia]]` by file name;\n  // `slugify` still collapses and trims it like any other replacement\n  // @see https://github.com/sveltia/sveltia-cms/issues/1093\n  if (typeof replacement !== 'string' || !replacement) {\n    return;\n  }\n\n  const unsafeCharsRegex =\n    encoding === 'ascii' ? UNSAFE_ASCII_SLUG_CHARS_REGEX : UNSAFE_UNICODE_SLUG_CHARS_REGEX;\n\n  if (unsafeCharsRegex.test(replacement.replaceAll(' ', ''))) {\n    addMessage({\n      strKey: 'invalid_sanitize_replacement',\n      values: { replacement },\n      context: { cmsConfig },\n      collectors,\n    });\n  }\n};\n","import { customComponentRegistry } from '$lib/services/api/registries';\nimport { warnDeprecation } from '$lib/services/config/deprecations';\nimport { parseBackendConfig } from '$lib/services/config/parser/backend';\nimport { parseCollections } from '$lib/services/config/parser/collections';\nimport { parseEditorComponent } from '$lib/services/config/parser/editor-components';\nimport { parseFields } from '$lib/services/config/parser/fields';\nimport { parseI18nConfig } from '$lib/services/config/parser/i18n';\nimport { parseMediaConfig } from '$lib/services/config/parser/media';\nimport { parseMediaLibraries } from '$lib/services/config/parser/media-libraries';\nimport { parsePublishMode } from '$lib/services/config/parser/publish-mode';\nimport { parseSlugConfig } from '$lib/services/config/parser/slug';\nimport { addMessage, checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\nimport { isInlinePatternComponent } from '$lib/services/contents/fields/rich-text/components/inline-pattern';\nimport { isHttpURL, isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { CmsConfig } from '$lib/types/public';\n * @import { ConfigParserCollectors, UnsupportedOption } from '$lib/types/private';\n */\n\n/**\n * Unsupported options.\n * @type {UnsupportedOption[]}\n */\nconst UNSUPPORTED_OPTIONS = [\n  // Sveltia CMS doesn’t use a proxy server for local workflow, so this option is not applicable.\n  { type: 'warning', prop: 'local_backend', strKey: 'unsupported_ignored_option' },\n  // Sveltia CMS detects user’s locale from the browser, so this option is not applicable.\n  { type: 'warning', prop: 'locale', strKey: 'unsupported_ignored_option' },\n  // Sveltia CMS doesn’t have performance issues with searching content, so this option is not\n  // applicable.\n  { type: 'warning', prop: 'search', strKey: 'unsupported_ignored_option' },\n];\n\n/**\n * Options that hold the URL of the site and have to be absolute. A `site_url` that isn’t a URL\n * isn’t rejected at runtime, but it’s then unusable as the base of every preview link, so the links\n * are silently dropped. The `display_url` option is only ever opened in a new tab, where a relative\n * path resolves against the CMS origin as well as an absolute URL does, so it’s not checked.\n * @type {(keyof CmsConfig)[]}\n */\nconst URL_OPTIONS = ['site_url'];\n\n/**\n * Parse and validate the CMS configuration.\n * @param {CmsConfig} cmsConfig Raw CMS configuration.\n * @param {ConfigParserCollectors} collectors Collectors.\n * @throws {Error} If there is an error in the config.\n * @see https://decapcms.org/docs/configuration-options/\n */\nexport const parseCmsConfig = (cmsConfig, collectors) => {\n  parseBackendConfig(cmsConfig, collectors);\n\n  URL_OPTIONS.forEach((option) => {\n    const url = cmsConfig[option];\n\n    // An empty string is as good as none, and a value of another type is reported against the\n    // JSON schema\n    if (isNonEmptyString(url) && !isHttpURL(url)) {\n      addMessage({\n        strKey: 'invalid_url_option',\n        values: { option, url },\n        context: { cmsConfig },\n        collectors,\n      });\n    }\n  });\n\n  // The option still works, but `logo.src` replaces it\n  if (cmsConfig.logo_url !== undefined) {\n    warnDeprecation('logo_url');\n  }\n\n  parsePublishMode({ value: cmsConfig.publish_mode, context: { cmsConfig }, collectors });\n  parseMediaConfig(cmsConfig, collectors);\n  parseMediaLibraries({ config: cmsConfig, context: { cmsConfig }, collectors });\n  parseSlugConfig(cmsConfig, collectors);\n  parseI18nConfig(cmsConfig, collectors);\n  parseCollections(cmsConfig, collectors);\n\n  checkUnsupportedOptions({\n    UNSUPPORTED_OPTIONS,\n    config: cmsConfig,\n    context: { cmsConfig },\n    collectors,\n  });\n\n  // Parse fields in custom editor components registered with `CMS.registerEditorComponent()`.\n  // @todo Figure out how to handle lazy-loaded components, as they may not be parsed here.\n  customComponentRegistry.forEach((definition, componentName) => {\n    parseEditorComponent({ definition, componentName, cmsConfig, collectors });\n\n    // A pattern-based inline component has no fields\n    if (!isInlinePatternComponent(definition)) {\n      parseFields(definition.fields, { cmsConfig, componentName }, collectors);\n    }\n  });\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { getRootDir } from '$lib/services/backends/root-dir';\n\n/**\n * @import {\n * AssetFolderInfo,\n * ConfigParserCollectors,\n * EntryFolderInfo,\n * InternalCmsConfig,\n * } from '$lib/types/private';\n */\n\n/**\n * Count how many levels the given path climbs above the folder it starts from with `..` segments.\n * @param {string} path Path, e.g. `content/../../shared`.\n * @returns {number} Number of levels, e.g. `1`, or `0` if it stays within the folder.\n */\nconst countLevelsUp = (path) => {\n  let depth = 0;\n  let lowest = 0;\n\n  path.split('/').forEach((segment) => {\n    if (segment === '..') {\n      depth -= 1;\n      lowest = Math.min(lowest, depth);\n    } else if (segment && segment !== '.') {\n      depth += 1;\n    }\n  });\n\n  return -lowest;\n};\n\n/**\n * Get how many levels below its base folder the deepest entry of a collection can be, which an\n * entry-relative media folder can climb back up from.\n * @param {InternalCmsConfig} config CMS configuration.\n * @param {AssetFolderInfo} folder Asset folder.\n * @returns {number | undefined} Number of levels, or `undefined` if it can’t be told, as for\n * nested entries, or for an editor component used anywhere.\n */\nconst getEntryDepth = (config, { collectionName, fileName }) => {\n  // A file is where it’s configured to be\n  if (fileName || collectionName === '_singletons') {\n    return 0;\n  }\n\n  const collection = config.collections?.find(\n    (c) => !('divider' in c) && 'name' in c && c.name === collectionName,\n  );\n\n  if (!collection || !('folder' in collection) || collection.nested) {\n    return undefined;\n  }\n\n  // An entry path like `{{slug}}/index` puts the entry in a subfolder, and so does a folder for\n  // each locale. Count it in whenever i18n may be on, so a valid folder is never refused\n  const pathDepth = (collection.path ?? '').split('/').length - 1;\n  const localeDepth = collection.i18n || config.i18n ? 1 : 0;\n\n  return pathDepth + localeDepth;\n};\n\n/**\n * Check that no folder or file path in the configuration leads outside the directory set with the\n * `root_dir` backend option. The CMS only lists the files in the directory, so anything saved\n * outside it would seem to disappear.\n * @param {object} args Arguments.\n * @param {InternalCmsConfig} args.config CMS configuration.\n * @param {EntryFolderInfo[]} args.entryFolders All entry folders.\n * @param {AssetFolderInfo[]} args.assetFolders All asset folders.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const checkRootDirPaths = ({ config, entryFolders, assetFolders, collectors }) => {\n  if (!getRootDir()) {\n    return;\n  }\n\n  /** @type {Set<string>} */\n  const paths = new Set();\n\n  entryFolders.forEach(({ folderPath, folderPathMap, filePathMap }) => {\n    [folderPath, ...Object.values(folderPathMap ?? {}), ...Object.values(filePathMap ?? {})]\n      .filter((path) => path !== undefined && countLevelsUp(path) > 0)\n      .forEach((path) => paths.add(/** @type {string} */ (path)));\n  });\n\n  assetFolders.forEach((folder) => {\n    const { internalPath, internalSubPath, entryRelative } = folder;\n\n    if (internalPath === undefined) {\n      return;\n    }\n\n    if (!entryRelative) {\n      if (countLevelsUp(internalPath) > 0) {\n        paths.add(internalPath);\n      }\n\n      return;\n    }\n\n    const entryDepth = getEntryDepth(config, folder);\n    const path = [internalPath, internalSubPath].filter(Boolean).join('/');\n\n    if (entryDepth !== undefined && countLevelsUp(path) > entryDepth) {\n      paths.add(path);\n    }\n  });\n\n  paths.forEach((path) => {\n    collectors.errors.add(_('config.error.path_outside_root_dir', { values: { path } }));\n  });\n};\n","/**\n * Decode the escape sequences of a JSON pointer segment.\n * @param {string} segment Segment to decode.\n * @returns {string} Decoded segment.\n */\nexport const decodeSegment = (segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~');\n\n/**\n * Split a JSON pointer, or a URI fragment holding one, into decoded segments.\n * @param {string} pointer Pointer, such as `#/properties/backend/$ref/properties/name/const`.\n * @returns {string[]} Segments.\n */\nexport const getSegments = (pointer) =>\n  pointer.replace(/^#/, '').split('/').filter(Boolean).map(decodeSegment);\n\n/**\n * Get the value a JSON pointer, or a URI fragment holding one, points to.\n * @param {any} root Document the pointer is resolved against.\n * @param {string} pointer Pointer.\n * @returns {any} Value, or `undefined` if the pointer can’t be resolved.\n */\nexport const resolvePointer = (root, pointer) =>\n  getSegments(pointer).reduce((/** @type {any} */ value, key) => value?.[key], root);\n","import { isObject } from '@sveltia/utils/object';\n\nimport { resolvePointer } from '$lib/services/config/schema/pointer';\n\n/**\n * Properties that can discriminate a union of object schemas. The generated schema pins these to a\n * constant in each branch: `widget` identifies a field type and `name` identifies a backend\n * service.\n */\nconst TAG_PROPERTIES = ['widget', 'name'];\n/**\n * Maximum depth to follow while collecting the leaf schemas of a nested union. The generated schema\n * nests unions three levels deep at most; the limit only guards against a malformed schema.\n */\nconst MAX_UNION_DEPTH = 8;\n\n/**\n * Resolve a local `$ref` pointer, following a chain of references.\n * @param {Record<string, any>} schema Root schema.\n * @param {any} node Node that may be a reference.\n * @returns {Record<string, any> | undefined} Resolved schema object, or `undefined` if the node is\n * not an object or the reference is circular or unresolvable.\n */\nconst resolveRef = (schema, node) => {\n  /** @type {Set<string>} */\n  const visited = new Set();\n  let current = node;\n\n  while (isObject(current) && typeof current.$ref === 'string') {\n    if (visited.has(current.$ref)) {\n      return undefined;\n    }\n\n    visited.add(current.$ref);\n\n    current = resolvePointer(schema, current.$ref);\n  }\n\n  return isObject(current) ? current : undefined;\n};\n\n/**\n * Collect the leaf object schemas of a union branch. A branch can be a union itself, as `Field` is\n * a union of `StandardField` and `CustomField`, and `StandardField` in turn is a union of every\n * field type.\n * @param {Record<string, any>} schema Root schema.\n * @param {any} node Branch to inspect.\n * @param {number} [depth] Current recursion depth.\n * @returns {Record<string, any>[]} Leaf schemas, or an empty array if the branch is not made of\n * object schemas.\n */\nconst getLeaves = (schema, node, depth = 0) => {\n  const resolved = resolveRef(schema, node);\n\n  if (!resolved || depth > MAX_UNION_DEPTH) {\n    return [];\n  }\n\n  if (Array.isArray(resolved.anyOf)) {\n    return resolved.anyOf.flatMap((branch) => getLeaves(schema, branch, depth + 1));\n  }\n\n  return isObject(resolved.properties) ? [resolved] : [];\n};\n\n/**\n * Get the constant values a leaf schema allows for the given property.\n * @param {Record<string, any>} leaf Leaf schema.\n * @param {string} key Property name.\n * @returns {any[] | undefined} Allowed values, or `undefined` if the property is not pinned to a\n * constant or an enumeration.\n */\nconst getConstValues = (leaf, key) => {\n  const property = leaf.properties?.[key];\n\n  if (!isObject(property)) {\n    return undefined;\n  }\n\n  if (property.const !== undefined) {\n    return [property.const];\n  }\n\n  return Array.isArray(property.enum) ? property.enum : undefined;\n};\n\n/**\n * Describe how a union branch uses the given tag property.\n * @param {Record<string, any>} schema Root schema.\n * @param {any} branch Branch to inspect.\n * @param {string} key Tag property name.\n * @returns {{ values: any[], optional: boolean } | undefined} The values the branch accepts and\n * whether the tag can be omitted, or `undefined` if the branch is not tagged.\n */\nconst describeTag = (schema, branch, key) => {\n  const leaves = getLeaves(schema, branch);\n\n  if (!leaves.length) {\n    return undefined;\n  }\n\n  /** @type {any[]} */\n  const values = [];\n  let optional = false;\n\n  // Every leaf has to be tagged, or the branch can’t be selected by the tag alone\n  if (\n    !leaves.every((leaf) => {\n      const leafValues = getConstValues(leaf, key);\n\n      if (!leafValues) {\n        return false;\n      }\n\n      values.push(...leafValues);\n      optional ||= !(leaf.required ?? []).includes(key);\n\n      return true;\n    })\n  ) {\n    return undefined;\n  }\n\n  return { values: [...new Set(values)], optional };\n};\n\n/**\n * Get the properties a union branch always requires, which is the intersection of what its leaves\n * require.\n * @param {Record<string, any>} schema Root schema.\n * @param {any} branch Branch to inspect.\n * @returns {Set<string> | undefined} Property names, or `undefined` if the branch is not made of\n * object schemas.\n */\nconst getRequired = (schema, branch) => {\n  const leaves = getLeaves(schema, branch);\n\n  if (!leaves.length) {\n    return undefined;\n  }\n\n  return leaves.map((leaf) => new Set(leaf.required ?? [])).reduce((a, b) => a.intersection(b));\n};\n\n/**\n * Get the names of every property a union branch defines, including those of its leaves.\n * @param {Record<string, any>} schema Root schema.\n * @param {any} branch Branch to inspect.\n * @returns {Set<string>} Property names.\n */\nconst getPropertyNames = (schema, branch) =>\n  new Set(getLeaves(schema, branch).flatMap((leaf) => Object.keys(leaf.properties)));\n\n/**\n * Build a schema that matches an object whose given property holds one of the given values.\n * @param {string} key Property name.\n * @param {any[]} values Allowed values.\n * @returns {Record<string, any>} Schema.\n */\nconst matchProperty = (key, values) => ({\n  properties: { [key]: values.length === 1 ? { const: values[0] } : { enum: values } },\n});\n\n/**\n * Fold a list of conditional branches into a nested `if`/`then`/`else` chain.\n * @param {{ condition: Record<string, any>, branch: any }[]} entries Branches to chain, in the\n * order they should be tested.\n * @param {any} fallback Schema to apply when no condition matches.\n * @returns {Record<string, any>} Schema.\n */\nconst buildChain = (entries, fallback) =>\n  entries.reduceRight(\n    // oxlint-disable-next-line unicorn/no-thenable -- `then` is a JSON Schema keyword here\n    (rest, { condition, branch }) => ({ if: condition, then: branch, else: rest }),\n    fallback,\n  );\n\n/**\n * Rewrite a union whose branches are identified by a constant tag property, such as the field type\n * in `widget` or the backend service in `name`.\n * @param {Record<string, any>} schema Root schema.\n * @param {any[]} branches Original union branches.\n * @param {any[]} rewritten Branches with their own unions already rewritten.\n * @returns {Record<string, any> | undefined} Schema, or `undefined` if no tag identifies the\n * branches.\n */\nconst discriminateByTag = (schema, branches, rewritten) =>\n  TAG_PROPERTIES.reduce((result, key) => {\n    if (result) {\n      return result;\n    }\n\n    const tags = branches.map((branch) => describeTag(schema, branch, key));\n    const tagged = /** @type {{ values: any[], optional: boolean }[]} */ (tags.filter(Boolean));\n    const values = tagged.flatMap((tag) => tag.values);\n\n    // One untagged branch can serve as the fallback, as `CustomField` does for `Field`. Any more\n    // than that, or overlapping values, and the tag doesn’t identify a single branch.\n    if (\n      !tagged.length ||\n      tags.length - tagged.length > 1 ||\n      values.length !== new Set(values).size\n    ) {\n      return undefined;\n    }\n\n    const entries = rewritten\n      .map((branch, index) => ({ branch, tag: tags[index] }))\n      .filter((entry) => !!entry.tag)\n      // A branch that allows the tag to be omitted matches an object without one, so it has to be\n      // tested after the branches that require it\n      .sort((a, b) => Number(a.tag?.optional) - Number(b.tag?.optional))\n      .map(({ branch, tag }) => ({\n        branch,\n        condition: tag?.optional\n          ? matchProperty(key, tag.values)\n          : { required: [key], ...matchProperty(key, /** @type {any[]} */ (tag?.values)) },\n      }));\n\n    const untagged = rewritten.filter((_branch, index) => !tags[index]);\n\n    // Without an untagged branch, an unmatched object gets an error naming every allowed value\n    return buildChain(entries, untagged[0] ?? { required: [key], ...matchProperty(key, values) });\n  }, /** @type {Record<string, any> | undefined} */ (undefined));\n\n/**\n * Rewrite a union whose branches are identified by the properties they require, such as `folder`\n * for an entry collection and `files` for a file collection.\n * @param {Record<string, any>} schema Root schema.\n * @param {any[]} branches Original union branches.\n * @param {any[]} rewritten Branches with their own unions already rewritten.\n * @returns {Record<string, any> | undefined} Schema, or `undefined` if no required property\n * identifies the branches.\n */\nconst discriminateByRequired = (schema, branches, rewritten) => {\n  const required = branches.map((branch) => getRequired(schema, branch));\n\n  if (required.some((names) => !names)) {\n    return undefined;\n  }\n\n  const signatures = /** @type {Set<string>[]} */ (required);\n  const propertyNames = branches.map((branch) => getPropertyNames(schema, branch));\n\n  // A required property only identifies a branch if the other branches don’t accept it at all. A\n  // collection divider may have a `name`, for instance, so `name` can’t select a collection.\n  const markers = signatures.map((names, index) => {\n    const others = propertyNames.reduce(\n      (acc, otherNames, otherIndex) => (index === otherIndex ? acc : acc.union(otherNames)),\n      /** @type {Set<string>} */ (new Set()),\n    );\n\n    return [...names.difference(others)];\n  });\n\n  // As with tags, one branch without a marker can serve as the fallback\n  if (markers.filter((names) => !names.length).length > 1) {\n    return undefined;\n  }\n\n  const entries = rewritten\n    .map((branch, index) => ({ branch, markers: markers[index] }))\n    .filter((entry) => entry.markers.length)\n    .map(({ branch, markers: names }) => ({\n      branch,\n      condition:\n        names.length === 1\n          ? { required: [names[0]] }\n          : { anyOf: names.map((name) => ({ required: [name] })) },\n    }));\n\n  const fallbackIndex = markers.findIndex((names) => !names.length);\n\n  const fallback =\n    fallbackIndex > -1\n      ? rewritten[fallbackIndex]\n      : { anyOf: entries.map(({ condition }) => condition) };\n\n  return buildChain(entries, fallback);\n};\n\n/**\n * Adapt the published JSON schema for runtime validation.\n *\n * Each union of object schemas becomes an `if`/`then`/`else` chain keyed on whatever identifies its\n * branches, so that a mistyped option in a Markdown field is reported once against the Markdown\n * field, instead of once for every field type the object failed to be.\n *\n * An unknown property is kept a violation, so that a typo or a mistake like a YAML flow mapping\n * that silently gains a key is caught. It’s reported as a warning rather than an error, because a\n * configuration written for another CMS, or for a newer version of Sveltia CMS, carries options\n * that are simply ignored and shouldn’t stop anyone from signing in.\n * @param {Record<string, any>} schema Published schema.\n * @param {object} [options] Options.\n * @param {boolean} [options.allowUnknownProperties] Whether to drop every `additionalProperties:\n * false` from the schema, so an object may hold properties the schema doesn’t describe.\n * @returns {Record<string, any>} Schema to validate against.\n */\nexport const prepareSchema = (schema, { allowUnknownProperties = false } = {}) => {\n  /**\n   * Rewrite a node and everything below it.\n   * @param {any} node Node to rewrite.\n   * @returns {any} Rewritten node.\n   */\n  const rewrite = (node) => {\n    if (Array.isArray(node)) {\n      return node.map(rewrite);\n    }\n\n    if (!isObject(node)) {\n      return node;\n    }\n\n    /** @type {Record<string, any>} */\n    const result = {};\n\n    Object.entries(node).forEach(([key, value]) => {\n      // `anyOf` is handled below, once its branches have been rewritten\n      if (\n        key !== 'anyOf' &&\n        !(allowUnknownProperties && key === 'additionalProperties' && value === false)\n      ) {\n        result[key] = rewrite(value);\n      }\n    });\n\n    if (Array.isArray(node.anyOf)) {\n      const rewritten = node.anyOf.map(rewrite);\n\n      const replacement =\n        node.anyOf.length > 1\n          ? (discriminateByTag(schema, node.anyOf, rewritten) ??\n            discriminateByRequired(schema, node.anyOf, rewritten))\n          : undefined;\n\n      if (replacement) {\n        Object.assign(result, replacement);\n      } else {\n        result.anyOf = rewritten;\n      }\n    }\n\n    return result;\n  };\n\n  return rewrite(schema);\n};\n","export function deepCompareStrict(a, b) {\n    const typeofa = typeof a;\n    if (typeofa !== typeof b) {\n        return false;\n    }\n    const aIsArray = Array.isArray(a);\n    const bIsArray = Array.isArray(b);\n    if (aIsArray !== bIsArray) {\n        return false;\n    }\n    if (aIsArray) {\n        const length = a.length;\n        if (length !== b.length) {\n            return false;\n        }\n        for (let i = 0; i < length; i++) {\n            if (!deepCompareStrict(a[i], b[i])) {\n                return false;\n            }\n        }\n        return true;\n    }\n    if (typeofa === 'object') {\n        if (!a || !b) {\n            return a === b;\n        }\n        const aKeys = Object.keys(a);\n        const bKeys = Object.keys(b);\n        const length = aKeys.length;\n        if (length !== bKeys.length) {\n            return false;\n        }\n        for (const k of aKeys) {\n            if (!Object.prototype.hasOwnProperty.call(b, k)) {\n                return false;\n            }\n            if (!deepCompareStrict(a[k], b[k])) {\n                return false;\n            }\n        }\n        return true;\n    }\n    return a === b;\n}\n//# sourceMappingURL=deep-compare-strict.js.map","export function encodePointer(p) {\n    return encodeURI(escapePointer(p)).replace(/#/g, '%23');\n}\nexport function escapePointer(p) {\n    return p.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n//# sourceMappingURL=pointer.js.map","import { encodePointer } from './pointer.js';\nconst uriFragmentCharacter = /^[A-Za-z0-9._~!$&'()*+,;=:@/?-]$/;\nconst uriPercentEncoding = /^%[0-9A-Fa-f]{2}$/;\nconst uriUnreservedCharacter = /^[A-Za-z0-9._~-]$/;\nfunction normalizeURIFragment(fragment) {\n    let normalized = '';\n    for (let index = 0; index < fragment.length;) {\n        const character = fragment[index];\n        const encoded = fragment.slice(index, index + 3);\n        if (character === '%' && uriPercentEncoding.test(encoded)) {\n            const decoded = String.fromCharCode(parseInt(encoded.slice(1), 16));\n            normalized += uriUnreservedCharacter.test(decoded)\n                ? decoded\n                : encoded.toUpperCase();\n            index += 3;\n            continue;\n        }\n        const codePoint = String.fromCodePoint(fragment.codePointAt(index));\n        normalized += uriFragmentCharacter.test(codePoint)\n            ? codePoint\n            : encodeURIComponent(codePoint);\n        index += codePoint.length;\n    }\n    return normalized;\n}\nfunction resolveURI(reference, baseURI) {\n    const url = new URL(reference, baseURI.href);\n    url.hash = url.hash ? normalizeURIFragment(url.hash.slice(1)) : '';\n    return url;\n}\nexport const schemaKeyword = {\n    additionalItems: true,\n    unevaluatedItems: true,\n    items: true,\n    contains: true,\n    additionalProperties: true,\n    unevaluatedProperties: true,\n    propertyNames: true,\n    not: true,\n    if: true,\n    then: true,\n    else: true\n};\nexport const schemaArrayKeyword = {\n    prefixItems: true,\n    items: true,\n    allOf: true,\n    anyOf: true,\n    oneOf: true\n};\nexport const schemaMapKeyword = {\n    $defs: true,\n    definitions: true,\n    properties: true,\n    patternProperties: true,\n    dependentSchemas: true\n};\nexport const ignoredKeyword = {\n    id: true,\n    $id: true,\n    $ref: true,\n    $schema: true,\n    $anchor: true,\n    $vocabulary: true,\n    $comment: true,\n    default: true,\n    enum: true,\n    const: true,\n    required: true,\n    dependentRequired: true,\n    type: true,\n    maximum: true,\n    minimum: true,\n    exclusiveMaximum: true,\n    exclusiveMinimum: true,\n    multipleOf: true,\n    maxLength: true,\n    minLength: true,\n    pattern: true,\n    format: true,\n    maxItems: true,\n    minItems: true,\n    uniqueItems: true,\n    maxProperties: true,\n    minProperties: true\n};\nexport let initialBaseURI = typeof self !== 'undefined' &&\n    self.location &&\n    self.location.origin !== 'null'\n    ?\n        new URL(self.location.origin + self.location.pathname + location.search)\n    : new URL('https://github.com/cfworker');\nexport function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') {\n    if (schema && typeof schema === 'object' && !Array.isArray(schema)) {\n        const id = schema.$id || schema['id'];\n        if (id) {\n            const url = resolveURI(id, baseURI);\n            if (url.hash.length > 1) {\n                lookup[url.href] = schema;\n            }\n            else {\n                url.hash = '';\n                if (basePointer === '') {\n                    baseURI = url;\n                }\n                else {\n                    dereference(schema, lookup, baseURI);\n                }\n            }\n        }\n    }\n    else if (schema !== true && schema !== false) {\n        return lookup;\n    }\n    const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : '');\n    if (lookup[schemaURI] !== undefined && lookup[schemaURI] !== schema) {\n        throw new Error(`Duplicate schema URI \"${schemaURI}\".`);\n    }\n    lookup[schemaURI] = schema;\n    if (schema === true || schema === false) {\n        return lookup;\n    }\n    if (schema.__absolute_uri__ === undefined) {\n        Object.defineProperty(schema, '__absolute_uri__', {\n            enumerable: false,\n            value: schemaURI\n        });\n    }\n    if (schema.$ref && schema.__absolute_ref__ === undefined) {\n        const url = resolveURI(schema.$ref, baseURI);\n        Object.defineProperty(schema, '__absolute_ref__', {\n            enumerable: false,\n            value: url.href\n        });\n    }\n    if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) {\n        const url = resolveURI(schema.$recursiveRef, baseURI);\n        Object.defineProperty(schema, '__absolute_recursive_ref__', {\n            enumerable: false,\n            value: url.href\n        });\n    }\n    if (schema.$anchor) {\n        const url = resolveURI('#' + schema.$anchor, baseURI);\n        lookup[url.href] = schema;\n    }\n    for (let key in schema) {\n        if (ignoredKeyword[key]) {\n            continue;\n        }\n        const keyBase = `${basePointer}/${encodePointer(key)}`;\n        const subSchema = schema[key];\n        if (Array.isArray(subSchema)) {\n            if (schemaArrayKeyword[key]) {\n                const length = subSchema.length;\n                for (let i = 0; i < length; i++) {\n                    dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`);\n                }\n            }\n        }\n        else if (schemaMapKeyword[key]) {\n            for (let subKey in subSchema) {\n                dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`);\n            }\n        }\n        else {\n            dereference(subSchema, lookup, baseURI, keyBase);\n        }\n    }\n    return lookup;\n}\n//# sourceMappingURL=dereference.js.map","const DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst TIME = /^(\\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::\\d{2,5})?(?:\\/[^\\s]*)?$/iu;\nconst UUID = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;\nconst JSON_POINTER = /^(?:\\/(?:[^~/]|~0|~1)*)*$/;\nconst JSON_POINTER_URI_FRAGMENT = /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;\nconst RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/;\nconst EMAIL_ADDRESS = /^(\"(?:[\\x20-\\x21\\x23-\\x5b\\x5d-\\x7e]|\\\\[\\x20-\\x7e])*\"|[a-z0-9.!#$%&'*+/=?^_`{|}~-]+)@(.+)$/i;\nconst EMAIL = (input) => {\n    const matches = input.match(EMAIL_ADDRESS);\n    if (!matches)\n        return false;\n    const name = matches[1];\n    const host = matches[2];\n    if (!name || !host || name.length > 64 || host.length > 253)\n        return false;\n    if (name[0] !== '\"' &&\n        (name[0] === '.' || name.endsWith('.') || name.includes('..'))) {\n        return false;\n    }\n    if (host.startsWith('[') && host.endsWith(']')) {\n        const address = host.slice(1, -1);\n        if (/^ipv6:/i.test(address))\n            return IPV6.test(address.slice(5));\n        return IPV4.test(address);\n    }\n    return HOSTNAME.test(host);\n};\nconst IPV4 = /^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$/;\nconst IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i;\nconst DURATION = (input) => /^P(?:\\d+W|(?:(?:\\d+Y(?:\\d+M(?:\\d+D)?)?|\\d+M(?:\\d+D)?|\\d+D)(?:T(?:\\d+H(?:\\d+M(?:\\d+S)?)?|\\d+M(?:\\d+S)?|\\d+S))?|T(?:\\d+H(?:\\d+M(?:\\d+S)?)?|\\d+M(?:\\d+S)?|\\d+S)))$/.test(input);\nfunction bind(r) {\n    return r.test.bind(r);\n}\nexport const format = {\n    date,\n    time: time.bind(undefined, true),\n    'date-time': date_time,\n    duration: DURATION,\n    uri,\n    'uri-reference': bind(URIREF),\n    'uri-template': bind(URITEMPLATE),\n    url: bind(URL_),\n    email: EMAIL,\n    hostname: bind(HOSTNAME),\n    ipv4: bind(IPV4),\n    ipv6: bind(IPV6),\n    regex: regex,\n    uuid: bind(UUID),\n    'json-pointer': bind(JSON_POINTER),\n    'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT),\n    'relative-json-pointer': bind(RELATIVE_JSON_POINTER)\n};\nfunction isLeapYear(year) {\n    return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nfunction date(str) {\n    const matches = str.match(DATE);\n    if (!matches)\n        return false;\n    const yearPart = matches[1];\n    const monthPart = matches[2];\n    const dayPart = matches[3];\n    if (!yearPart || !monthPart || !dayPart)\n        return false;\n    const year = +yearPart;\n    const month = +monthPart;\n    const day = +dayPart;\n    const maxDay = month == 2 && isLeapYear(year) ? 29 : DAYS[month];\n    return (month >= 1 &&\n        month <= 12 &&\n        day >= 1 &&\n        maxDay !== undefined &&\n        day <= maxDay);\n}\nfunction time(full, str) {\n    const matches = str.match(TIME);\n    if (!matches)\n        return false;\n    const hourPart = matches[1];\n    const minutePart = matches[2];\n    const secondPart = matches[3];\n    if (!hourPart || !minutePart || !secondPart)\n        return false;\n    const hour = +hourPart;\n    const minute = +minutePart;\n    const second = +secondPart;\n    const timeZone = matches[5];\n    const offsetSign = matches[6];\n    const offsetHour = +(matches[7] ?? 0);\n    const offsetMinute = +(matches[8] ?? 0);\n    if (hour > 23 ||\n        minute > 59 ||\n        second > 60 ||\n        offsetHour > 23 ||\n        offsetMinute > 59 ||\n        (full && timeZone === undefined)) {\n        return false;\n    }\n    if (second < 60)\n        return true;\n    const offsetDirection = offsetSign === '+' ? 1 : offsetSign === '-' ? -1 : 0;\n    const utcMinute = (hour * 60 +\n        minute -\n        offsetDirection * (offsetHour * 60 + offsetMinute) +\n        24 * 60) %\n        (24 * 60);\n    return utcMinute === 23 * 60 + 59;\n}\nconst DATE_TIME_SEPARATOR = /t|\\s/i;\nfunction date_time(str) {\n    const [datePart, timePart, extra] = str.split(DATE_TIME_SEPARATOR);\n    return (datePart !== undefined &&\n        timePart !== undefined &&\n        extra === undefined &&\n        date(datePart) &&\n        time(true, timePart));\n}\nconst NOT_URI_FRAGMENT = /\\/|:/;\nconst URI_PATTERN = /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\\?(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;\nfunction uri(str) {\n    return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str);\n}\nconst Z_ANCHOR = /[^\\\\]\\\\Z/;\nfunction regex(str) {\n    if (Z_ANCHOR.test(str))\n        return false;\n    try {\n        new RegExp(str, 'u');\n        return true;\n    }\n    catch (e) {\n        return false;\n    }\n}\n//# sourceMappingURL=format.js.map","export function ucs2length(s) {\n    let result = 0;\n    let length = s.length;\n    let index = 0;\n    let charCode;\n    while (index < length) {\n        result++;\n        charCode = s.charCodeAt(index++);\n        if (charCode >= 0xd800 && charCode <= 0xdbff && index < length) {\n            charCode = s.charCodeAt(index);\n            if ((charCode & 0xfc00) == 0xdc00) {\n                index++;\n            }\n        }\n    }\n    return result;\n}\n//# sourceMappingURL=ucs2-length.js.map","import { deepCompareStrict } from './deep-compare-strict.js';\nimport { dereference } from './dereference.js';\nimport { format } from './format.js';\nimport { encodePointer } from './pointer.js';\nimport { ucs2length } from './ucs2-length.js';\nfunction hasOwnProperty(instance, key) {\n    return Object.prototype.hasOwnProperty.call(instance, key);\n}\nfunction decimalInteger(value) {\n    const coefficientAndExponent = Math.abs(value).toString().split('e');\n    const coefficient = coefficientAndExponent[0];\n    const exponent = coefficientAndExponent[1] ?? '0';\n    const point = coefficient.indexOf('.');\n    const fractionLength = point === -1 ? 0 : coefficient.length - point - 1;\n    return [\n        BigInt(coefficient.replace('.', '')),\n        Number(exponent) - fractionLength\n    ];\n}\nfunction isMultipleOf(instance, divisor) {\n    if (!Number.isFinite(instance) || !Number.isFinite(divisor) || divisor <= 0) {\n        return false;\n    }\n    const [instanceCoefficient, instanceExponent] = decimalInteger(instance);\n    const [divisorCoefficient, divisorExponent] = decimalInteger(divisor);\n    const exponentDifference = instanceExponent - divisorExponent;\n    if (exponentDifference >= 0) {\n        return ((instanceCoefficient * 10n ** BigInt(exponentDifference)) %\n            divisorCoefficient ===\n            0n);\n    }\n    return (instanceCoefficient %\n        (divisorCoefficient * 10n ** BigInt(-exponentDifference)) ===\n        0n);\n}\nexport function validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) {\n    if (schema === true) {\n        return { valid: true, errors: [] };\n    }\n    if (schema === false) {\n        return {\n            valid: false,\n            errors: [\n                {\n                    instanceLocation,\n                    keyword: 'false',\n                    keywordLocation: instanceLocation,\n                    error: 'False boolean schema.'\n                }\n            ]\n        };\n    }\n    const rawInstanceType = typeof instance;\n    let instanceType;\n    switch (rawInstanceType) {\n        case 'boolean':\n        case 'number':\n        case 'string':\n            instanceType = rawInstanceType;\n            break;\n        case 'object':\n            if (instance === null) {\n                instanceType = 'null';\n            }\n            else if (Array.isArray(instance)) {\n                instanceType = 'array';\n            }\n            else {\n                instanceType = 'object';\n            }\n            break;\n        default:\n            throw new Error(`Instances of \"${rawInstanceType}\" type are not supported.`);\n    }\n    const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema;\n    const errors = [];\n    if ($recursiveAnchor === true && recursiveAnchor === null) {\n        recursiveAnchor = schema;\n    }\n    if ($recursiveRef === '#') {\n        const refSchema = recursiveAnchor === null\n            ? lookup[__absolute_recursive_ref__]\n            : recursiveAnchor;\n        const keywordLocation = `${schemaLocation}/$recursiveRef`;\n        const result = validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated);\n        if (!result.valid) {\n            errors.push({\n                instanceLocation,\n                keyword: '$recursiveRef',\n                keywordLocation,\n                error: 'A subschema had errors.'\n            }, ...result.errors);\n        }\n    }\n    if ($ref !== undefined) {\n        const uri = __absolute_ref__ || $ref;\n        const refSchema = lookup[uri];\n        if (refSchema === undefined) {\n            let message = `Unresolved $ref \"${$ref}\".`;\n            if (__absolute_ref__ && __absolute_ref__ !== $ref) {\n                message += `  Absolute URI \"${__absolute_ref__}\".`;\n            }\n            message += `\\nKnown schemas:\\n- ${Object.keys(lookup).join('\\n- ')}`;\n            throw new Error(message);\n        }\n        const keywordLocation = `${schemaLocation}/$ref`;\n        const result = validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated);\n        if (!result.valid) {\n            errors.push({\n                instanceLocation,\n                keyword: '$ref',\n                keywordLocation,\n                error: 'A subschema had errors.'\n            }, ...result.errors);\n        }\n        if (draft === '4' || draft === '7') {\n            return { valid: errors.length === 0, errors };\n        }\n    }\n    if (Array.isArray($type)) {\n        let length = $type.length;\n        let valid = false;\n        for (let i = 0; i < length; i++) {\n            if (instanceType === $type[i] ||\n                ($type[i] === 'integer' &&\n                    instanceType === 'number' &&\n                    instance % 1 === 0 &&\n                    instance === instance)) {\n                valid = true;\n                break;\n            }\n        }\n        if (!valid) {\n            errors.push({\n                instanceLocation,\n                keyword: 'type',\n                keywordLocation: `${schemaLocation}/type`,\n                error: `Instance type \"${instanceType}\" is invalid. Expected \"${$type.join('\", \"')}\".`\n            });\n        }\n    }\n    else if ($type === 'integer') {\n        if (instanceType !== 'number' || instance % 1 || instance !== instance) {\n            errors.push({\n                instanceLocation,\n                keyword: 'type',\n                keywordLocation: `${schemaLocation}/type`,\n                error: `Instance type \"${instanceType}\" is invalid. Expected \"${$type}\".`\n            });\n        }\n    }\n    else if ($type !== undefined && instanceType !== $type) {\n        errors.push({\n            instanceLocation,\n            keyword: 'type',\n            keywordLocation: `${schemaLocation}/type`,\n            error: `Instance type \"${instanceType}\" is invalid. Expected \"${$type}\".`\n        });\n    }\n    if ($const !== undefined) {\n        if (instanceType === 'object' || instanceType === 'array') {\n            if (!deepCompareStrict(instance, $const)) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'const',\n                    keywordLocation: `${schemaLocation}/const`,\n                    error: `Instance does not match ${JSON.stringify($const)}.`\n                });\n            }\n        }\n        else if (instance !== $const) {\n            errors.push({\n                instanceLocation,\n                keyword: 'const',\n                keywordLocation: `${schemaLocation}/const`,\n                error: `Instance does not match ${JSON.stringify($const)}.`\n            });\n        }\n    }\n    if ($enum !== undefined) {\n        if (instanceType === 'object' || instanceType === 'array') {\n            if (!$enum.some(value => deepCompareStrict(instance, value))) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'enum',\n                    keywordLocation: `${schemaLocation}/enum`,\n                    error: `Instance does not match any of ${JSON.stringify($enum)}.`\n                });\n            }\n        }\n        else if (!$enum.some(value => instance === value)) {\n            errors.push({\n                instanceLocation,\n                keyword: 'enum',\n                keywordLocation: `${schemaLocation}/enum`,\n                error: `Instance does not match any of ${JSON.stringify($enum)}.`\n            });\n        }\n    }\n    if ($not !== undefined) {\n        const keywordLocation = `${schemaLocation}/not`;\n        const result = validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation);\n        if (result.valid) {\n            errors.push({\n                instanceLocation,\n                keyword: 'not',\n                keywordLocation,\n                error: 'Instance matched \"not\" schema.'\n            });\n        }\n    }\n    let subEvaluateds = [];\n    if ($anyOf !== undefined) {\n        const keywordLocation = `${schemaLocation}/anyOf`;\n        const errorsLength = errors.length;\n        let anyValid = false;\n        for (const [i, subSchema] of $anyOf.entries()) {\n            const subEvaluated = Object.create(evaluated);\n            const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);\n            errors.push(...result.errors);\n            anyValid = anyValid || result.valid;\n            if (result.valid) {\n                subEvaluateds.push(subEvaluated);\n            }\n        }\n        if (anyValid) {\n            errors.length = errorsLength;\n        }\n        else {\n            errors.splice(errorsLength, 0, {\n                instanceLocation,\n                keyword: 'anyOf',\n                keywordLocation,\n                error: 'Instance does not match any subschemas.'\n            });\n        }\n    }\n    if ($allOf !== undefined) {\n        const keywordLocation = `${schemaLocation}/allOf`;\n        const errorsLength = errors.length;\n        let allValid = true;\n        for (const [i, subSchema] of $allOf.entries()) {\n            const subEvaluated = Object.create(evaluated);\n            const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);\n            errors.push(...result.errors);\n            allValid = allValid && result.valid;\n            if (result.valid) {\n                subEvaluateds.push(subEvaluated);\n            }\n        }\n        if (allValid) {\n            errors.length = errorsLength;\n        }\n        else {\n            errors.splice(errorsLength, 0, {\n                instanceLocation,\n                keyword: 'allOf',\n                keywordLocation,\n                error: `Instance does not match every subschema.`\n            });\n        }\n    }\n    if ($oneOf !== undefined) {\n        const keywordLocation = `${schemaLocation}/oneOf`;\n        const errorsLength = errors.length;\n        const matches = $oneOf.filter((subSchema, i) => {\n            const subEvaluated = Object.create(evaluated);\n            const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);\n            errors.push(...result.errors);\n            if (result.valid) {\n                subEvaluateds.push(subEvaluated);\n            }\n            return result.valid;\n        }).length;\n        if (matches === 1) {\n            errors.length = errorsLength;\n        }\n        else {\n            errors.splice(errorsLength, 0, {\n                instanceLocation,\n                keyword: 'oneOf',\n                keywordLocation,\n                error: `Instance does not match exactly one subschema (${matches} matches).`\n            });\n        }\n    }\n    if (instanceType === 'object' || instanceType === 'array') {\n        Object.assign(evaluated, ...subEvaluateds);\n    }\n    if ($if !== undefined) {\n        const keywordLocation = `${schemaLocation}/if`;\n        const ifEvaluated = Object.create(null);\n        const conditionResult = validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, ifEvaluated).valid;\n        if (conditionResult) {\n            Object.assign(evaluated, ifEvaluated);\n            if ($then !== undefined) {\n                const thenResult = validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated);\n                if (!thenResult.valid) {\n                    errors.push({\n                        instanceLocation,\n                        keyword: 'if',\n                        keywordLocation,\n                        error: `Instance does not match \"then\" schema.`\n                    }, ...thenResult.errors);\n                }\n            }\n        }\n        else if ($else !== undefined) {\n            const elseResult = validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated);\n            if (!elseResult.valid) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'if',\n                    keywordLocation,\n                    error: `Instance does not match \"else\" schema.`\n                }, ...elseResult.errors);\n            }\n        }\n    }\n    if (instanceType === 'object') {\n        if ($required !== undefined) {\n            for (const key of $required) {\n                if (!hasOwnProperty(instance, key)) {\n                    errors.push({\n                        instanceLocation,\n                        keyword: 'required',\n                        keywordLocation: `${schemaLocation}/required`,\n                        error: `Instance does not have required property \"${key}\".`\n                    });\n                }\n            }\n        }\n        const keys = Object.keys(instance);\n        if ($minProperties !== undefined && keys.length < $minProperties) {\n            errors.push({\n                instanceLocation,\n                keyword: 'minProperties',\n                keywordLocation: `${schemaLocation}/minProperties`,\n                error: `Instance does not have at least ${$minProperties} properties.`\n            });\n        }\n        if ($maxProperties !== undefined && keys.length > $maxProperties) {\n            errors.push({\n                instanceLocation,\n                keyword: 'maxProperties',\n                keywordLocation: `${schemaLocation}/maxProperties`,\n                error: `Instance does not have at least ${$maxProperties} properties.`\n            });\n        }\n        if ($propertyNames !== undefined) {\n            const keywordLocation = `${schemaLocation}/propertyNames`;\n            for (const key in instance) {\n                const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n                const result = validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);\n                if (!result.valid) {\n                    errors.push({\n                        instanceLocation,\n                        keyword: 'propertyNames',\n                        keywordLocation,\n                        error: `Property name \"${key}\" does not match schema.`\n                    }, ...result.errors);\n                }\n            }\n        }\n        if ($dependentRequired !== undefined) {\n            const keywordLocation = `${schemaLocation}/dependantRequired`;\n            for (const key in $dependentRequired) {\n                if (hasOwnProperty(instance, key)) {\n                    const required = $dependentRequired[key];\n                    for (const dependantKey of required) {\n                        if (!hasOwnProperty(instance, dependantKey)) {\n                            errors.push({\n                                instanceLocation,\n                                keyword: 'dependentRequired',\n                                keywordLocation,\n                                error: `Instance has \"${key}\" but does not have \"${dependantKey}\".`\n                            });\n                        }\n                    }\n                }\n            }\n        }\n        if ($dependentSchemas !== undefined) {\n            for (const [key, dependentSchema] of Object.entries($dependentSchemas)) {\n                const keywordLocation = `${schemaLocation}/dependentSchemas`;\n                if (hasOwnProperty(instance, key)) {\n                    const result = validate(instance, dependentSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated);\n                    if (!result.valid) {\n                        errors.push({\n                            instanceLocation,\n                            keyword: 'dependentSchemas',\n                            keywordLocation,\n                            error: `Instance has \"${key}\" but does not match dependant schema.`\n                        }, ...result.errors);\n                    }\n                }\n            }\n        }\n        if ($dependencies !== undefined) {\n            const keywordLocation = `${schemaLocation}/dependencies`;\n            for (const key in $dependencies) {\n                if (hasOwnProperty(instance, key)) {\n                    const propsOrSchema = $dependencies[key];\n                    if (Array.isArray(propsOrSchema)) {\n                        for (const dependantKey of propsOrSchema) {\n                            if (!hasOwnProperty(instance, dependantKey)) {\n                                errors.push({\n                                    instanceLocation,\n                                    keyword: 'dependencies',\n                                    keywordLocation,\n                                    error: `Instance has \"${key}\" but does not have \"${dependantKey}\".`\n                                });\n                            }\n                        }\n                    }\n                    else {\n                        const result = validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`);\n                        if (!result.valid) {\n                            errors.push({\n                                instanceLocation,\n                                keyword: 'dependencies',\n                                keywordLocation,\n                                error: `Instance has \"${key}\" but does not match dependant schema.`\n                            }, ...result.errors);\n                        }\n                    }\n                }\n            }\n        }\n        const thisEvaluated = Object.create(null);\n        let stop = false;\n        if ($properties !== undefined) {\n            const keywordLocation = `${schemaLocation}/properties`;\n            for (const [key, propertySchema] of Object.entries($properties)) {\n                if (!hasOwnProperty(instance, key)) {\n                    continue;\n                }\n                const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n                const result = validate(instance[key], propertySchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`);\n                thisEvaluated[key] = true;\n                if (result.valid) {\n                    evaluated[key] = true;\n                }\n                else {\n                    stop = shortCircuit;\n                    errors.push({\n                        instanceLocation,\n                        keyword: 'properties',\n                        keywordLocation,\n                        error: `Property \"${key}\" does not match schema.`\n                    }, ...result.errors);\n                    if (stop)\n                        break;\n                }\n            }\n        }\n        if (!stop && $patternProperties !== undefined) {\n            const keywordLocation = `${schemaLocation}/patternProperties`;\n            for (const [pattern, subSchema] of Object.entries($patternProperties)) {\n                const regex = new RegExp(pattern, 'u');\n                for (const key in instance) {\n                    if (!regex.test(key)) {\n                        continue;\n                    }\n                    const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n                    const result = validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`);\n                    thisEvaluated[key] = true;\n                    if (result.valid) {\n                        evaluated[key] = true;\n                    }\n                    else {\n                        stop = shortCircuit;\n                        errors.push({\n                            instanceLocation,\n                            keyword: 'patternProperties',\n                            keywordLocation,\n                            error: `Property \"${key}\" matches pattern \"${pattern}\" but does not match associated schema.`\n                        }, ...result.errors);\n                    }\n                }\n            }\n        }\n        if (!stop && $additionalProperties !== undefined) {\n            const keywordLocation = `${schemaLocation}/additionalProperties`;\n            for (const key in instance) {\n                if (thisEvaluated[key]) {\n                    continue;\n                }\n                const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n                const result = validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);\n                if (result.valid) {\n                    evaluated[key] = true;\n                }\n                else {\n                    stop = shortCircuit;\n                    errors.push({\n                        instanceLocation,\n                        keyword: 'additionalProperties',\n                        keywordLocation,\n                        error: `Property \"${key}\" does not match additional properties schema.`\n                    }, ...result.errors);\n                }\n            }\n        }\n        else if (!stop && $unevaluatedProperties !== undefined) {\n            const keywordLocation = `${schemaLocation}/unevaluatedProperties`;\n            for (const key in instance) {\n                if (!evaluated[key]) {\n                    const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n                    const result = validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);\n                    if (result.valid) {\n                        evaluated[key] = true;\n                    }\n                    else {\n                        errors.push({\n                            instanceLocation,\n                            keyword: 'unevaluatedProperties',\n                            keywordLocation,\n                            error: `Property \"${key}\" does not match unevaluated properties schema.`\n                        }, ...result.errors);\n                    }\n                }\n            }\n        }\n    }\n    else if (instanceType === 'array') {\n        if ($maxItems !== undefined && instance.length > $maxItems) {\n            errors.push({\n                instanceLocation,\n                keyword: 'maxItems',\n                keywordLocation: `${schemaLocation}/maxItems`,\n                error: `Array has too many items (${instance.length} > ${$maxItems}).`\n            });\n        }\n        if ($minItems !== undefined && instance.length < $minItems) {\n            errors.push({\n                instanceLocation,\n                keyword: 'minItems',\n                keywordLocation: `${schemaLocation}/minItems`,\n                error: `Array has too few items (${instance.length} < ${$minItems}).`\n            });\n        }\n        const length = instance.length;\n        let i = 0;\n        let stop = false;\n        if ($prefixItems !== undefined) {\n            const keywordLocation = `${schemaLocation}/prefixItems`;\n            const length2 = Math.min($prefixItems.length, length);\n            for (; i < length2; i++) {\n                const result = validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`);\n                evaluated[i] = true;\n                if (!result.valid) {\n                    stop = shortCircuit;\n                    errors.push({\n                        instanceLocation,\n                        keyword: 'prefixItems',\n                        keywordLocation,\n                        error: `Items did not match schema.`\n                    }, ...result.errors);\n                    if (stop)\n                        break;\n                }\n            }\n        }\n        if ($items !== undefined) {\n            const keywordLocation = `${schemaLocation}/items`;\n            if (Array.isArray($items)) {\n                const length2 = Math.min($items.length, length);\n                for (; i < length2; i++) {\n                    const result = validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`);\n                    evaluated[i] = true;\n                    if (!result.valid) {\n                        stop = shortCircuit;\n                        errors.push({\n                            instanceLocation,\n                            keyword: 'items',\n                            keywordLocation,\n                            error: `Items did not match schema.`\n                        }, ...result.errors);\n                        if (stop)\n                            break;\n                    }\n                }\n            }\n            else {\n                for (; i < length; i++) {\n                    const result = validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);\n                    evaluated[i] = true;\n                    if (!result.valid) {\n                        stop = shortCircuit;\n                        errors.push({\n                            instanceLocation,\n                            keyword: 'items',\n                            keywordLocation,\n                            error: `Items did not match schema.`\n                        }, ...result.errors);\n                        if (stop)\n                            break;\n                    }\n                }\n            }\n            if (!stop && $additionalItems !== undefined) {\n                const keywordLocation = `${schemaLocation}/additionalItems`;\n                for (; i < length; i++) {\n                    const result = validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);\n                    evaluated[i] = true;\n                    if (!result.valid) {\n                        stop = shortCircuit;\n                        errors.push({\n                            instanceLocation,\n                            keyword: 'additionalItems',\n                            keywordLocation,\n                            error: `Items did not match additional items schema.`\n                        }, ...result.errors);\n                    }\n                }\n            }\n        }\n        if ($contains !== undefined) {\n            if (length === 0 && $minContains === undefined) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'contains',\n                    keywordLocation: `${schemaLocation}/contains`,\n                    error: `Array is empty. It must contain at least one item matching the schema.`\n                });\n            }\n            else if ($minContains !== undefined && length < $minContains) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'minContains',\n                    keywordLocation: `${schemaLocation}/minContains`,\n                    error: `Array has less items (${length}) than minContains (${$minContains}).`\n                });\n            }\n            else {\n                const keywordLocation = `${schemaLocation}/contains`;\n                const errorsLength = errors.length;\n                let contained = 0;\n                for (let j = 0; j < length; j++) {\n                    const result = validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation);\n                    if (result.valid) {\n                        evaluated[j] = true;\n                        contained++;\n                    }\n                    else {\n                        errors.push(...result.errors);\n                    }\n                }\n                if (contained >= ($minContains || 0)) {\n                    errors.length = errorsLength;\n                }\n                if ($minContains === undefined && contained === 0) {\n                    errors.splice(errorsLength, 0, {\n                        instanceLocation,\n                        keyword: 'contains',\n                        keywordLocation,\n                        error: `Array does not contain item matching schema.`\n                    });\n                }\n                else if ($minContains !== undefined && contained < $minContains) {\n                    errors.push({\n                        instanceLocation,\n                        keyword: 'minContains',\n                        keywordLocation: `${schemaLocation}/minContains`,\n                        error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.`\n                    });\n                }\n                else if ($maxContains !== undefined && contained > $maxContains) {\n                    errors.push({\n                        instanceLocation,\n                        keyword: 'maxContains',\n                        keywordLocation: `${schemaLocation}/maxContains`,\n                        error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.`\n                    });\n                }\n            }\n        }\n        if (!stop && $unevaluatedItems !== undefined) {\n            const keywordLocation = `${schemaLocation}/unevaluatedItems`;\n            for (i; i < length; i++) {\n                if (evaluated[i]) {\n                    continue;\n                }\n                const result = validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);\n                evaluated[i] = true;\n                if (!result.valid) {\n                    errors.push({\n                        instanceLocation,\n                        keyword: 'unevaluatedItems',\n                        keywordLocation,\n                        error: `Items did not match unevaluated items schema.`\n                    }, ...result.errors);\n                }\n            }\n        }\n        if ($uniqueItems) {\n            for (let j = 0; j < length; j++) {\n                const a = instance[j];\n                const ao = typeof a === 'object' && a !== null;\n                for (let k = 0; k < length; k++) {\n                    if (j === k) {\n                        continue;\n                    }\n                    const b = instance[k];\n                    const bo = typeof b === 'object' && b !== null;\n                    if (a === b || (ao && bo && deepCompareStrict(a, b))) {\n                        errors.push({\n                            instanceLocation,\n                            keyword: 'uniqueItems',\n                            keywordLocation: `${schemaLocation}/uniqueItems`,\n                            error: `Duplicate items at indexes ${j} and ${k}.`\n                        });\n                        j = Number.MAX_SAFE_INTEGER;\n                        k = Number.MAX_SAFE_INTEGER;\n                    }\n                }\n            }\n        }\n    }\n    else if (instanceType === 'number') {\n        if (draft === '4') {\n            if ($minimum !== undefined &&\n                (($exclusiveMinimum === true && instance <= $minimum) ||\n                    instance < $minimum)) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'minimum',\n                    keywordLocation: `${schemaLocation}/minimum`,\n                    error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.`\n                });\n            }\n            if ($maximum !== undefined &&\n                (($exclusiveMaximum === true && instance >= $maximum) ||\n                    instance > $maximum)) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'maximum',\n                    keywordLocation: `${schemaLocation}/maximum`,\n                    error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.`\n                });\n            }\n        }\n        else {\n            if ($minimum !== undefined && instance < $minimum) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'minimum',\n                    keywordLocation: `${schemaLocation}/minimum`,\n                    error: `${instance} is less than ${$minimum}.`\n                });\n            }\n            if ($maximum !== undefined && instance > $maximum) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'maximum',\n                    keywordLocation: `${schemaLocation}/maximum`,\n                    error: `${instance} is greater than ${$maximum}.`\n                });\n            }\n            if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'exclusiveMinimum',\n                    keywordLocation: `${schemaLocation}/exclusiveMinimum`,\n                    error: `${instance} is less than ${$exclusiveMinimum}.`\n                });\n            }\n            if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'exclusiveMaximum',\n                    keywordLocation: `${schemaLocation}/exclusiveMaximum`,\n                    error: `${instance} is greater than or equal to ${$exclusiveMaximum}.`\n                });\n            }\n        }\n        if ($multipleOf !== undefined) {\n            if (!isMultipleOf(instance, $multipleOf)) {\n                errors.push({\n                    instanceLocation,\n                    keyword: 'multipleOf',\n                    keywordLocation: `${schemaLocation}/multipleOf`,\n                    error: `${instance} is not a multiple of ${$multipleOf}.`\n                });\n            }\n        }\n    }\n    else if (instanceType === 'string') {\n        const length = $minLength === undefined && $maxLength === undefined\n            ? 0\n            : ucs2length(instance);\n        if ($minLength !== undefined && length < $minLength) {\n            errors.push({\n                instanceLocation,\n                keyword: 'minLength',\n                keywordLocation: `${schemaLocation}/minLength`,\n                error: `String is too short (${length} < ${$minLength}).`\n            });\n        }\n        if ($maxLength !== undefined && length > $maxLength) {\n            errors.push({\n                instanceLocation,\n                keyword: 'maxLength',\n                keywordLocation: `${schemaLocation}/maxLength`,\n                error: `String is too long (${length} > ${$maxLength}).`\n            });\n        }\n        if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) {\n            errors.push({\n                instanceLocation,\n                keyword: 'pattern',\n                keywordLocation: `${schemaLocation}/pattern`,\n                error: `String does not match pattern.`\n            });\n        }\n        if ($format !== undefined &&\n            format[$format] &&\n            !format[$format](instance)) {\n            errors.push({\n                instanceLocation,\n                keyword: 'format',\n                keywordLocation: `${schemaLocation}/format`,\n                error: `String does not match format \"${$format}\".`\n            });\n        }\n    }\n    return { valid: errors.length === 0, errors };\n}\n//# sourceMappingURL=validate.js.map","import { dereference } from './dereference.js';\nimport { validate } from './validate.js';\nexport class Validator {\n    schema;\n    draft;\n    shortCircuit;\n    lookup;\n    constructor(schema, draft = '2019-09', shortCircuit = true) {\n        this.schema = schema;\n        this.draft = draft;\n        this.shortCircuit = shortCircuit;\n        this.lookup = dereference(schema);\n    }\n    validate(instance) {\n        return validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit);\n    }\n    addSchema(schema, id) {\n        if (id) {\n            schema = { ...schema, $id: id };\n        }\n        dereference(schema, this.lookup);\n    }\n}\n//# sourceMappingURL=validator.js.map","import { Validator } from '@cfworker/json-schema';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { decodeSegment, getSegments, resolvePointer } from '$lib/services/config/schema/pointer';\n\n/**\n * @import { OutputUnit } from '@cfworker/json-schema';\n * @import { SchemaValidationError } from '$lib/types/private';\n */\n\n/**\n * The JSON Schema draft the published schema is written against.\n */\nconst SCHEMA_DRAFT = '7';\n\n/**\n * Keywords that only report that something below them failed. The keyword that describes the\n * actual problem is reported separately, so these would be noise. `additionalProperties` belongs\n * here because the property it rejected is reported separately, by\n * {@link FALSE_SCHEMA_KEYWORD}, which is where its name can be read.\n */\nconst CONTAINER_KEYWORDS = [\n  '$ref',\n  'properties',\n  'items',\n  'if',\n  'allOf',\n  'oneOf',\n  'additionalProperties',\n];\n\n/**\n * Keyword the validator reports at the location of a property that `additionalProperties: false`\n * rejected, the boolean schema being what the property was matched against.\n */\nconst FALSE_SCHEMA_KEYWORD = 'false';\n\n/**\n * Keywords whose constraint is the value found at the keyword’s own location in the schema.\n */\nconst CONSTRAINT_PARAMS = {\n  type: 'type',\n  enum: 'allowedValues',\n  const: 'allowedValue',\n  minItems: 'limit',\n  maxItems: 'limit',\n  minLength: 'limit',\n  maxLength: 'limit',\n};\n\n/**\n * Resolve a keyword location within the schema. A `$ref` segment means the reference at that point\n * was followed, so the pointer it holds is resolved before the walk continues.\n * @param {Record<string, any>} schema Root schema.\n * @param {string} location Keyword location.\n * @returns {any} Value at that location, or `undefined` if it can’t be resolved.\n */\nconst resolveKeyword = (schema, location) =>\n  getSegments(location).reduce((/** @type {any} */ node, segment) => {\n    if (segment === '$ref' && isObject(node) && typeof node.$ref === 'string') {\n      return resolvePointer(schema, node.$ref);\n    }\n\n    return node?.[segment];\n  }, schema);\n\n/**\n * Convert one validator output unit into the errors the reporter works with. A unit says which\n * keyword failed but not what it expected, so the constraint is read back from the schema. For\n * `required` the unit doesn’t name the missing property either, so every property the object lacks\n * is reported, one error each, matching how the rest of the reporting is keyed on a single option.\n * @param {OutputUnit} unit Output unit.\n * @param {Record<string, any>} schema Root schema.\n * @param {any} config Raw CMS configuration.\n * @returns {SchemaValidationError[]} Errors.\n */\nconst normalizeUnit = ({ keyword, keywordLocation, instanceLocation }, schema, config) => {\n  const instancePath = instanceLocation.replace(/^#/, '');\n\n  if (keyword === 'required') {\n    const required = resolveKeyword(schema, keywordLocation);\n    const value = resolvePointer(config, instanceLocation);\n\n    /* v8 ignore next 3 -- the validator only reports `required` for an object, against a schema\n    whose `required` is an array; the guard is here in case a location can’t be resolved */\n    if (!Array.isArray(required) || !isObject(value)) {\n      return [];\n    }\n\n    return required\n      .filter((name) => !(name in value))\n      .map((name) => ({ instancePath, keyword, params: { missingProperty: name } }));\n  }\n\n  const param = CONSTRAINT_PARAMS[/** @type {keyof CONSTRAINT_PARAMS} */ (keyword)];\n\n  return [\n    {\n      instancePath,\n      keyword,\n      params: param ? { [param]: resolveKeyword(schema, keywordLocation) } : {},\n    },\n  ];\n};\n\n/**\n * Collect the properties the configuration holds that the schema doesn’t describe.\n *\n * A property rejected by `additionalProperties: false` is reported at its own location, against the\n * boolean schema it was matched against. The validator reports a property whose value simply failed\n * its own subschema the same way, so a property is only unknown when nothing else was reported for\n * it or anything below it.\n * @param {OutputUnit[]} errors Validator output.\n * @returns {SchemaValidationError[]} Errors, each naming one unknown property of the object it\n * belongs to.\n */\nconst findUnknownProperties = (errors) => {\n  const failedLocations = errors\n    .filter(({ keyword }) => keyword !== FALSE_SCHEMA_KEYWORD)\n    .map(({ instanceLocation }) => instanceLocation);\n\n  return errors\n    .filter(\n      ({ keyword, instanceLocation }) =>\n        keyword === FALSE_SCHEMA_KEYWORD &&\n        !failedLocations.some(\n          (location) =>\n            location === instanceLocation || location.startsWith(`${instanceLocation}/`),\n        ),\n    )\n    .map(({ instanceLocation }) => {\n      const path = instanceLocation.replace(/^#/, '');\n      const index = path.lastIndexOf('/');\n\n      return {\n        instancePath: path.slice(0, index),\n        keyword: 'additionalProperties',\n        params: { additionalProperty: decodeSegment(path.slice(index + 1)) },\n      };\n    });\n};\n\n/**\n * Compile a schema into a function that validates a configuration against it.\n *\n * The validator interprets the schema rather than generating code for it, so the CMS never needs\n * `unsafe-eval` in its content security policy. Its output describes each problem by pointing into\n * the schema, so the expected type, values or limit are read back from there.\n * @param {Record<string, any>} schema Schema to validate against.\n * @returns {(config: any) => SchemaValidationError[]} Function returning the problems found, which\n * is empty when the configuration is valid.\n * @see https://github.com/cfworker/cfworker/tree/main/packages/json-schema\n */\nexport const compileSchema = (schema) => {\n  // The validator mutates the schema it’s given while resolving references\n  const validator = new Validator(structuredClone(schema), SCHEMA_DRAFT, false);\n\n  return (config) => {\n    const { valid, errors } = validator.validate(config);\n\n    if (valid) {\n      return [];\n    }\n\n    /** @type {Set<string>} */\n    const seen = new Set();\n\n    return findUnknownProperties(errors).concat(\n      errors\n        .filter(\n          ({ keyword }) =>\n            keyword !== FALSE_SCHEMA_KEYWORD && !CONTAINER_KEYWORDS.includes(keyword),\n        )\n        // The validator reports `required` once per missing property, while `normalizeUnit` covers\n        // them all at once, so only the first unit for a given object is expanded\n        .filter(({ keyword, instanceLocation, keywordLocation }) => {\n          if (keyword !== 'required') {\n            return true;\n          }\n\n          const key = `${instanceLocation}|${keywordLocation}`;\n\n          if (seen.has(key)) {\n            return false;\n          }\n\n          seen.add(key);\n\n          return true;\n        })\n        .flatMap((unit) => normalizeUnit(unit, schema, config)),\n    );\n  };\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { customFieldTypeRegistry } from '$lib/services/api/registries';\nimport metaSchema from '$lib/services/config/schema/draft-07.json';\nimport { prepareSchema } from '$lib/services/config/schema/transform';\nimport { compileSchema } from '$lib/services/config/schema/validator';\n\n/**\n * Build a conditional schema for each field type registered with a schema, applying that schema to\n * the fields that use the type. A schema that can’t be compiled is dropped with a warning, so one\n * bad registration can’t stop the rest of the configuration from being validated.\n * @returns {Record<string, any>[]} Conditional schemas.\n */\nconst getCustomFieldSchemas = () => {\n  /** @type {Record<string, any>[]} */\n  const schemas = [];\n  /** @type {((schema: any) => any[]) | undefined} */\n  let validateSchema;\n\n  customFieldTypeRegistry.forEach(({ schema }, name) => {\n    if (!isObject(schema)) {\n      return;\n    }\n\n    // The validator interprets a schema rather than compiling it, so it accepts a malformed one and\n    // then rejects everything it’s applied to. Checking against the JSON Schema meta-schema catches\n    // that here, where the field type can be named, instead of at every field using it.\n    validateSchema ??= compileSchema(metaSchema);\n\n    if (validateSchema(schema).length) {\n      // eslint-disable-next-line no-console\n      console.warn(`Ignoring the invalid schema registered for the \\`${name}\\` field type`);\n\n      return;\n    }\n\n    // A registered schema describes the options the field type adds, not the whole field, so an\n    // `additionalProperties: false` in it would reject the common options every field has. The\n    // `CustomField` definition it’s applied alongside doesn’t constrain its properties either, so\n    // a custom field type accepts any option it hasn’t described.\n    schemas.push({\n      if: { required: ['widget'], properties: { widget: { const: name } } },\n      // oxlint-disable-next-line unicorn/no-thenable -- `then` is a JSON Schema keyword here\n      then: prepareSchema(schema, { allowUnknownProperties: true }),\n    });\n  });\n\n  return schemas;\n};\n\n/**\n * Extend the configuration schema with the field type schemas registered through the\n * `CMS.registerFieldType()` API, so that the options a custom field type accepts are validated\n * alongside the built-in ones.\n *\n * A field whose type isn’t built in is validated as a `CustomField`, so that’s where the registered\n * options belong. The registry is read on every configuration load rather than baked into the\n * downloaded schema, because field types are registered by the site’s own script.\n * @param {Record<string, any>} schema Schema to extend.\n * @returns {Record<string, any>} Extended schema, or the original one if no field type has been\n * registered with a schema.\n * @see https://decapcms.org/docs/custom-widgets/#registerwidget\n * @see https://sveltiacms.app/en/docs/api/field-types\n */\nexport const applyCustomFieldSchemas = (schema) => {\n  const customField = schema.definitions?.CustomField;\n  const schemas = isObject(customField) ? getCustomFieldSchemas() : [];\n\n  if (!schemas.length) {\n    return schema;\n  }\n\n  return {\n    ...schema,\n    definitions: {\n      ...schema.definitions,\n      CustomField: { allOf: [customField, ...schemas] },\n    },\n  };\n};\n","import { _, locale as appLocale } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { decodeSegment } from '$lib/services/config/schema/pointer';\nimport { getListFormatter } from '$lib/services/contents/i18n';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import {\n * ConfigParserCollectors,\n * ConfigParserContext,\n * SchemaValidationError,\n * } from '$lib/types/private';\n * @import { CmsConfig } from '$lib/types/public';\n */\n\n/**\n * Value types the schema uses, each with a localized name in `config.error.schema_value_type`.\n */\nconst VALUE_TYPES = ['string', 'number', 'integer', 'boolean', 'array', 'object', 'null'];\n\n/**\n * Format the given items as a localized list of alternatives.\n * @param {string[]} items Items to format.\n * @returns {string} Formatted list, such as `a, b or c`.\n */\nconst formatList = (items) =>\n  getListFormatter(appLocale.current, { type: 'disjunction' }).format(items);\n\n/**\n * Format a value the configuration is expected to hold. An empty string is written as a pair of\n * quotes, which is easier to read than the nothing it would otherwise render as.\n * @param {any} value Value to format.\n * @returns {string} Quoted value.\n */\nconst formatValue = (value) =>\n  `\\`${typeof value === 'string' && value ? value : JSON.stringify(value)}\\``;\n\n/**\n * Get the localized name of a value type.\n * @param {string} type Type name from the schema.\n * @returns {string} Localized name, such as `a string`.\n */\nconst formatType = (type) => _(`config.error.schema_value_type.${type}`);\n\n/**\n * Join the segments of an option path, writing array indexes in brackets.\n * @param {string[]} segments Segments to join.\n * @returns {string} Option path, such as `view_filters[0].pattern`.\n */\nconst formatOption = (segments) =>\n  segments.reduce((path, segment) => {\n    if (isNumeric(segment)) {\n      return `${path}[${segment}]`;\n    }\n\n    return path ? `${path}.${segment}` : segment;\n  }, '');\n\n/**\n * Extend a field key path with the name of one of its sub-fields, following the same convention as\n * the configuration parser: sub-fields of a List field are addressed with a wildcard.\n * @param {string} keyPath Key path of the parent field, which is empty at the collection level.\n * @param {any} parent Parent field configuration.\n * @param {string} name Sub-field name.\n * @returns {string} Extended key path.\n */\nconst appendFieldName = (keyPath, parent, name) => {\n  const base = parent?.widget === 'list' ? `${keyPath}.*` : keyPath;\n\n  return base ? `${base}.${name}` : name;\n};\n\n/**\n * Work out which part of the configuration a JSON pointer refers to, so that the problem can be\n * reported the same way as the ones the configuration parser finds: located by collection, file and\n * field, with the remaining path naming the offending option.\n * @param {CmsConfig} config Raw CMS configuration.\n * @param {string} instancePath JSON pointer, such as `/collections/0/fields/2/widget`.\n * @returns {{ context: ConfigParserContext, option: string[] }} Parser context and the segments of\n * the option path relative to the located item.\n */\nexport const locateError = (config, instancePath) => {\n  const segments = instancePath.split('/').slice(1).map(decodeSegment);\n  /** @type {ConfigParserContext} */\n  const context = {};\n  /** @type {string[]} */\n  const option = [];\n  /** @type {any} */\n  let node = config;\n  let keyPath = '';\n  let index = 0;\n  // Walk the structural part of the pointer; everything from the first unrecognized segment on\n  // names an option\n  let structural = true;\n\n  while (index < segments.length && structural) {\n    const key = segments[index];\n    const next = segments[index + 1];\n    const item = next !== undefined && isNumeric(next) ? node?.[key]?.[next] : undefined;\n\n    if (isObject(item) && node === config && (key === 'collections' || key === 'singletons')) {\n      // A singleton is a file that doesn’t belong to a collection\n      context[key === 'collections' ? 'collection' : 'collectionFile'] = /** @type {any} */ (item);\n      node = item;\n      index += 2;\n    } else if (isObject(item) && key === 'files' && context.collection) {\n      context.collectionFile = /** @type {any} */ (item);\n      node = item;\n      index += 2;\n    } else if (isObject(item) && key === 'fields') {\n      keyPath = appendFieldName(keyPath, node, item.name);\n      node = item;\n      index += 2;\n    } else if (isObject(item) && key === 'types') {\n      keyPath = `${keyPath}${node?.widget === 'list' ? '.*' : ''}<${item.name}>`;\n      node = item;\n      index += 2;\n    } else if (key === 'field' && isObject(node?.field)) {\n      keyPath = appendFieldName(keyPath, node, node.field.name);\n      node = node.field;\n      index += 1;\n    } else {\n      structural = false;\n    }\n  }\n\n  option.push(...segments.slice(index));\n\n  if (keyPath) {\n    context.typedKeyPath = keyPath;\n  }\n\n  return { context, option };\n};\n\n/**\n * Describe a single schema violation.\n * @param {SchemaValidationError} error Validation error.\n * @param {string} option Option path the error applies to.\n * @returns {{ strKey: string, values: Record<string, string> }} I18n string key and values.\n */\nconst describeError = ({ keyword, params }, option) => {\n  if (keyword === 'enum') {\n    return {\n      strKey: 'schema_invalid_enum',\n      values: { option, values: formatList(params.allowedValues.map(formatValue)) },\n    };\n  }\n\n  if (keyword === 'const') {\n    return params.allowedValue === ''\n      ? { strKey: 'schema_invalid_empty_value', values: { option } }\n      : { strKey: 'schema_invalid_const', values: { option, value: String(params.allowedValue) } };\n  }\n\n  if (keyword === 'minItems' || keyword === 'maxItems') {\n    return { strKey: 'schema_invalid_item_count', values: { option, count: String(params.limit) } };\n  }\n\n  return { strKey: 'schema_invalid_value', values: { option } };\n};\n\n/**\n * Turn the validator’s output into configuration errors.\n *\n * The validator reports one error for every constraint the configuration failed, which includes the\n * branches of a union it was never meant to match and every object enclosing the actual mistake. To\n * keep the report readable, the branch selections the adapted schema introduces are dropped, only\n * the innermost location is kept, and the alternatives of a union are merged into a single message.\n *\n * An unknown property is reported as a warning rather than an error, because a configuration\n * written for another CMS, or for a newer version of Sveltia CMS, carries options that are simply\n * ignored. It’s reported on its own, before the rest, so that it survives the grouping below: the\n * object holding it may well have another, unrelated problem deeper inside.\n * @param {object} args Arguments.\n * @param {CmsConfig} args.config Raw CMS configuration.\n * @param {SchemaValidationError[]} args.errors Validation errors.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const reportSchemaErrors = ({ config, errors, collectors }) => {\n  errors\n    .filter(({ keyword }) => keyword === 'additionalProperties')\n    .forEach(({ instancePath, params }) => {\n      const { context, option } = locateError(config, instancePath);\n\n      addMessage({\n        type: 'warning',\n        strKey: 'schema_unknown_option',\n        values: { option: formatOption([...option, params.additionalProperty]) },\n        context,\n        collectors,\n      });\n    });\n\n  // `if` errors only say which branch of a union was selected, which is never the problem\n  const relevant = errors.filter(\n    ({ keyword }) => keyword !== 'if' && keyword !== 'additionalProperties',\n  );\n\n  const paths = [...new Set(relevant.map(({ instancePath }) => instancePath))];\n  // Anything wrong inside an object also fails the object itself, and the enclosing report is\n  // always the vaguer of the two\n  const innermost = paths.filter((path) => !paths.some((other) => other.startsWith(`${path}/`)));\n\n  innermost.forEach((path) => {\n    const group = relevant.filter(({ instancePath }) => instancePath === path);\n    const { context, option } = locateError(config, path);\n    const hasAlternatives = group.some(({ keyword }) => keyword === 'anyOf');\n\n    const missing = group\n      .filter(({ keyword }) => keyword === 'required')\n      .map(({ params }) => formatOption([...option, params.missingProperty]));\n\n    const others = group.filter(({ keyword }) => keyword !== 'required' && keyword !== 'anyOf');\n\n    // A value that fails several type constraints belongs to a union that couldn’t be reduced to a\n    // single branch, so the types it may take are reported together\n    const types = [\n      ...new Set(\n        others\n          .filter(({ keyword, params }) => keyword === 'type' && VALUE_TYPES.includes(params.type))\n          .map(({ params }) => /** @type {string} */ (params.type)),\n      ),\n    ];\n\n    // Several missing properties across the branches of a union mean any one of them will do\n    if (missing.length > 1 && hasAlternatives) {\n      addMessage({\n        strKey: 'schema_missing_one_of',\n        values: { options: formatList([...new Set(missing)].map(formatValue)) },\n        context,\n        collectors,\n      });\n    } else {\n      [...new Set(missing)].forEach((name) => {\n        addMessage({\n          strKey: 'schema_missing_option',\n          values: { option: name },\n          context,\n          collectors,\n        });\n      });\n    }\n\n    if (types.length) {\n      addMessage({\n        strKey: 'schema_invalid_type',\n        values: { option: formatOption(option), type: formatList(types.map(formatType)) },\n        context,\n        collectors,\n      });\n    }\n\n    others\n      .filter(({ keyword, params }) => !(keyword === 'type' && VALUE_TYPES.includes(params.type)))\n      .forEach((error) => {\n        addMessage({ ...describeError(error, formatOption(option)), context, collectors });\n      });\n\n    // A union that failed without any usable detail still needs to be reported\n    if (!missing.length && !others.length) {\n      addMessage({\n        strKey: 'schema_invalid_value',\n        values: { option: formatOption(option) },\n        context,\n        collectors,\n      });\n    }\n  });\n};\n","import configSchema from 'virtual:config-schema';\n\nimport { prepareSchema } from '$lib/services/config/schema/transform';\n\n/**\n * @import { ConfigSchemas } from '$lib/types/private';\n */\n\n/**\n * The schemas adapted for validation. Preparing them walks the whole schema, so the result is kept\n * for the next configuration load.\n * @type {ConfigSchemas | undefined}\n */\nlet preparedSchemas = undefined;\n\n/**\n * Get the JSON schemas to validate a configuration file against. The schema is bundled with the\n * app, so nothing is downloaded and validation works offline.\n *\n * Two variants are prepared from it, because an unknown property is only worth a warning while\n * anything else is an error, and the two can’t be told apart in a single pass: an unknown property\n * fails the object holding it, and with it the branch of a union that object was meant to match.\n * The strict variant is what finds the unknown properties; the lenient one, which accepts them,\n * is what finds the violations.\n * @returns {ConfigSchemas | undefined} Schemas, or `undefined` when the app was built without one,\n * which only happens on a dev server that has never run a production build. Schema validation is\n * skipped in that case.\n */\nexport const getConfigSchemas = () => {\n  if (!configSchema) {\n    return undefined;\n  }\n\n  preparedSchemas ??= {\n    strict: prepareSchema(configSchema),\n    lenient: prepareSchema(configSchema, { allowUnknownProperties: true }),\n  };\n\n  return preparedSchemas;\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { applyCustomFieldSchemas } from '$lib/services/config/schema/custom-fields';\nimport { reportSchemaErrors } from '$lib/services/config/schema/errors';\nimport { compileSchema } from '$lib/services/config/schema/validator';\n\n/**\n * @import { ConfigParserCollectors, ConfigSchemas } from '$lib/types/private';\n * @import { CmsConfig } from '$lib/types/public';\n */\n\nexport { getConfigSchemas } from '$lib/services/config/schema/loader';\n\n/**\n * Replace every regular expression object in a configuration with its source string, so it can be\n * validated as the pattern it stands for. A configuration file can only hold a pattern as a\n * string, which is what the schema describes, while the JS API also accepts a `RegExp` object\n * wherever a pattern is expected.\n * @param {any} value Configuration, or any value within it.\n * @returns {any} Value with every `RegExp` replaced.\n */\nconst replaceRegExps = (value) => {\n  if (value instanceof RegExp) {\n    return value.source;\n  }\n\n  if (Array.isArray(value)) {\n    return value.map(replaceRegExps);\n  }\n\n  if (isObject(value)) {\n    return Object.fromEntries(\n      Object.entries(value).map(([key, item]) => [key, replaceRegExps(item)]),\n    );\n  }\n\n  return value;\n};\n\n/**\n * Validate a CMS configuration against the JSON schema and collect any violation as a\n * configuration error.\n *\n * Nothing here can keep a user out of the CMS by accident: an unexpected failure skips validation\n * instead of failing the configuration.\n * @param {object} args Arguments.\n * @param {CmsConfig} args.config Raw CMS configuration.\n * @param {ConfigSchemas | undefined} args.schemas Schemas to validate against, if the app was\n * built with one.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nexport const validateConfigSchema = ({ config, schemas, collectors }) => {\n  if (!schemas) {\n    return;\n  }\n\n  try {\n    const target = replaceRegExps(config);\n    const errors = compileSchema(applyCustomFieldSchemas(schemas.strict))(target);\n\n    if (!errors.length) {\n      return;\n    }\n\n    const unknown = errors.filter(({ keyword }) => keyword === 'additionalProperties');\n\n    // A property the schema doesn’t describe is only worth a warning, but it fails the object\n    // holding it, and with it the branch of a union that object was meant to match — an\n    // `index_file` written as an object would be reported as having to be a boolean, the only\n    // branch left. So once an unknown property is found, everything else is collected again from\n    // the schema that accepts one, where only the genuine violations remain.\n    const violations = unknown.length\n      ? compileSchema(applyCustomFieldSchemas(schemas.lenient))(target)\n      : errors;\n\n    reportSchemaErrors({ config, errors: [...unknown, ...violations], collectors });\n  } catch (ex) {\n    // eslint-disable-next-line no-console\n    console.warn('Skipping configuration schema validation', ex);\n  }\n};\n","import deepmerge from '@fastify/deepmerge';\nimport { _ } from '@sveltia/i18n';\nimport { getHash } from '@sveltia/utils/crypto';\nimport { isObject } from '@sveltia/utils/object';\nimport { isURL } from '@sveltia/utils/string';\n\nimport { allAssetFolders } from '$lib/services/assets/folders';\nimport { loadTransliterator } from '$lib/services/common/slug/transliterate';\nimport {\n  cmsConfig,\n  cmsConfigErrors,\n  cmsConfigVersion,\n  collectors,\n  rawCmsConfig,\n} from '$lib/services/config';\nimport { DEV_SITE_URL } from '$lib/services/config/constants';\nimport { getAllAssetFolders } from '$lib/services/config/folders/assets';\nimport { getAllEntryFolders } from '$lib/services/config/folders/entries';\nimport { fetchCmsConfig } from '$lib/services/config/loader';\nimport { parseCmsConfig } from '$lib/services/config/parser';\nimport { checkRootDirPaths } from '$lib/services/config/parser/root-dir';\nimport { getConfigSchemas, validateConfigSchema } from '$lib/services/config/schema';\nimport { normalizeConfigTemplates } from '$lib/services/config/templates';\nimport { allEntryFolders } from '$lib/services/contents';\nimport { loadDayjsLocales } from '$lib/services/contents/fields/date-time/locales';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { stripLeadingDotSlash } from '$lib/services/utils/file';\n\n/**\n * @import { InternalCmsConfig } from '$lib/types/private';\n * @import { CmsConfig } from '$lib/types/public';\n */\n\nconst { DEV } = import.meta.env;\n/**\n * Deep merge two config objects, concatenating arrays.\n */\nconst merge = deepmerge();\n\n/**\n * Update the entry and asset folder lists based on the given configuration.\n * @param {InternalCmsConfig} config Parsed configuration.\n */\nconst updateFolders = (config) => {\n  const _allEntryFolders = getAllEntryFolders(config);\n  const _allAssetFolders = getAllAssetFolders(config, [...collectors.mediaFields]);\n\n  // `getCollection` depends on `allAssetFolders`\n  allEntryFolders.current = _allEntryFolders;\n  allAssetFolders.current = _allAssetFolders;\n\n  if (prefs.devModeEnabled) {\n    // eslint-disable-next-line no-console\n    console.info('allEntryFolders', _allEntryFolders);\n    // eslint-disable-next-line no-console\n    console.info('allAssetFolders', _allAssetFolders);\n  }\n};\n\n/**\n * Initialize the CMS configuration state by loading the YAML file and optionally merge the object\n * with one specified with `CMS.init()`.\n * @param {CmsConfig} [manualConfig] Raw configuration specified with manual initialization.\n */\nexport const initCmsConfig = async (manualConfig) => {\n  cmsConfig.current = undefined;\n  cmsConfigErrors.current = [];\n\n  Object.assign(collectors, {\n    errors: new Set(),\n    warnings: new Set(),\n    mediaFields: new Set(),\n    relationFields: new Set(),\n    formatLocales: new Set(),\n  });\n\n  try {\n    // Not a config error but `getHash` below and some other features require a secure context\n    if (!window.isSecureContext) {\n      throw new Error(_('config.error.no_secure_context'));\n    }\n\n    /** @type {any} */\n    let rawConfig;\n\n    if (manualConfig) {\n      if (!isObject(manualConfig)) {\n        throw new Error(_('config.error.parse_failed'));\n      }\n\n      rawConfig = manualConfig;\n\n      if (rawConfig.load_config_file !== false) {\n        rawConfig = merge(await fetchCmsConfig({ manualInit: true }), rawConfig);\n      }\n    } else {\n      rawConfig = await fetchCmsConfig();\n    }\n\n    // Store the raw config so it can be used in the config viewer\n    Object.assign(rawCmsConfig, rawConfig);\n\n    // Write the template tags in their canonical form, e.g. `{{ slug }}` as `{{slug}}`, before\n    // anything reads them. The copy also keeps the user’s object as it is\n    const config = /** @type {InternalCmsConfig} */ (\n      normalizeConfigTemplates(structuredClone(rawConfig))\n    );\n\n    validateConfigSchema({ config, schemas: getConfigSchemas(), collectors });\n    parseCmsConfig(config, collectors);\n\n    if (collectors.errors.size) {\n      collectors.errors.forEach((warning) => {\n        // eslint-disable-next-line no-console\n        console.error(warning);\n      });\n\n      throw new Error('Errors found in configuration');\n    }\n\n    if (collectors.warnings.size) {\n      collectors.warnings.forEach((warning) => {\n        // eslint-disable-next-line no-console\n        console.warn(warning);\n      });\n    }\n\n    // Set the site URL for development or production. See also `/src/lib/components/app.svelte`\n    config._siteURL =\n      config.site_url?.trim() || (DEV ? DEV_SITE_URL : /* v8 ignore next */ window.location.origin);\n    // The parser has rejected a `site_url` that isn’t a URL, but the fallback can still be the\n    // opaque `null` origin of a `file:` page or a sandboxed frame, which leaves no base for links\n    config._baseURL = isURL(config._siteURL) ? new URL(config._siteURL).origin : '';\n\n    // Handle root collection folder variants, particularly for VitePress: `.`, `./` and `/` all\n    // mean the root folder. A leading `./` is removed from any other folder, e.g. `./content`\n    config.collections?.forEach((collection) => {\n      // The JSON schema has checked that `folder` is a string\n      if ('folder' in collection) {\n        const folder = stripLeadingDotSlash(/** @type {string} */ (collection.folder));\n\n        collection.folder = folder === '/' ? '' : folder;\n      }\n    });\n\n    // DateTime field values are parsed and formatted synchronously, so the locales they’re written\n    // in have to be ready before the content is loaded. So does the library cleaning the accents of\n    // slugs, which are made synchronously as well\n    await Promise.all([\n      loadDayjsLocales(collectors.formatLocales),\n      config.slug?.clean_accents ? loadTransliterator() : undefined,\n    ]);\n\n    cmsConfig.current = config;\n    updateFolders(config);\n\n    // The paths can only be told once they’re resolved to folders, after the parser has run\n    checkRootDirPaths({\n      config,\n      entryFolders: allEntryFolders.current,\n      assetFolders: allAssetFolders.current,\n      collectors,\n    });\n\n    if (collectors.errors.size) {\n      cmsConfig.current = undefined;\n\n      throw new Error('Errors found in configuration');\n    }\n\n    // JSON is serialized far faster than YAML, which takes tens of milliseconds for a configuration\n    // with hundreds of collections. A big integer, which a TOML file can hold, is written as text,\n    // as `JSON.stringify()` can’t serialize it otherwise\n    cmsConfigVersion.current = await getHash(\n      JSON.stringify(config, (_key, value) =>\n        typeof value === 'bigint' ? value.toString() : value,\n      ),\n    );\n\n    // eslint-disable-next-line no-console\n    console.debug('CMS configuration:', config);\n\n    if (prefs.devModeEnabled) {\n      // eslint-disable-next-line no-console\n      console.info('collectors', collectors);\n    }\n  } catch (/** @type {any} */ ex) {\n    cmsConfigErrors.current = collectors.errors.size\n      ? [...collectors.errors]\n      : [ex.name === 'Error' ? ex.message : _('config.error.unexpected')];\n\n    // eslint-disable-next-line no-console\n    console.error(ex, ex.cause);\n  }\n};\n","<script>\n  import { AppShell } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import ErrorBoundary from '$lib/components/common/error-boundary.svelte';\n  import EntrancePage from '$lib/components/entrance/entrance-page.svelte';\n  import CommitMessageDialog from '$lib/components/global/commit-message-dialog.svelte';\n  import BackendStatusIndicator from '$lib/components/global/infobars/backend-status-indicator.svelte';\n  import UpdateNotification from '$lib/components/global/infobars/update-notification.svelte';\n  import LocaleLoadErrorToast from '$lib/components/global/locale-load-error-toast.svelte';\n  import MainRouter from '$lib/components/global/main-router.svelte';\n  import ForkPermissionDialog from '$lib/components/workflow/fork-permission-dialog.svelte';\n  import OpenAuthoringIndicator from '$lib/components/workflow/open-authoring-indicator.svelte';\n  import {\n    appIconURLs,\n    appLogoType,\n    appLogoURL,\n    appManifestURL,\n    appTitle,\n  } from '$lib/services/app/branding';\n  import { missingBrowserFeatures } from '$lib/services/app/browser-support';\n  import { initAppLocale } from '$lib/services/app/i18n';\n  import { initAppInstallDetection } from '$lib/services/app/install';\n  import {\n    announcedPageStatus,\n    hasOverlay,\n    mainAreaTitle,\n    overlayTitle,\n    startViewTransition,\n  } from '$lib/services/app/navigation';\n  import { backend } from '$lib/services/backends';\n  import { cmsConfigLoaded, DEV_SITE_URL } from '$lib/services/config';\n  import { initCmsConfig } from '$lib/services/config/init';\n  import { dataLoaded } from '$lib/services/contents';\n  import { user } from '$lib/services/user/account.svelte';\n  import { initUserEnvDetection } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { CmsConfig } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {CmsConfig} [config] Configuration specified with manual initialization.\n   */\n\n  /** @type {Props} */\n  let { config } = $props();\n\n  // The strings for the default locale are always bundled with the app, so the UI can be rendered\n  // right away, even while the strings for another locale are being fetched from the CDN\n  initAppLocale();\n\n  $effect.pre(() => {\n    initUserEnvDetection();\n  });\n\n  onMount(() => {\n    // An outdated browser would fail while loading the configuration; the entrance page asks the\n    // user to update it instead\n    if (missingBrowserFeatures.current.length) {\n      // eslint-disable-next-line no-console\n      console.error('Unsupported browser. Missing features:', missingBrowserFeatures.current);\n\n      return;\n    }\n\n    initCmsConfig(config);\n  });\n\n  // Listen from the start: the browser offers to install the app only once, shortly after the\n  // page loads, when the account menu holding the Install as App item is usually closed\n  onMount(() => initAppInstallDetection());\n\n  // Fix the position of the custom mount element if needed\n  // @see https://decapcms.org/docs/custom-mounting/\n  // @see https://sveltiacms.app/en/docs/customization#custom-mount-element\n  onMount(() => {\n    const ncRoot = /** @type {HTMLElement | null} */ (document.querySelector('#nc-root'));\n\n    if (!!ncRoot && window.getComputedStyle(ncRoot).position === 'static') {\n      // Wait for the next frame to ensure the element is rendered before calculating its position\n      window.requestAnimationFrame(() => {\n        const { top, height } = ncRoot.getBoundingClientRect();\n\n        if (height) {\n          ncRoot.style.position = 'relative';\n        } else {\n          // Make sure the CMS UI won’t overlap with a header\n          ncRoot.style.position = 'fixed';\n          ncRoot.style.inset = `${top}px 0 0 0`;\n        }\n      });\n    }\n  });\n\n  let transitioned = $state(false);\n\n  // “Posts › Hello – Acme CMS” while editing, “Posts Collection – Acme CMS” on the list, and just\n  // the app name on the sign-in page, so each view has its own title (WCAG 2.4.2)\n  const documentTitle = $derived(\n    [overlayTitle.current || mainAreaTitle.current, appTitle.current].filter(Boolean).join(' – '),\n  );\n\n  $effect(() => {\n    if (dataLoaded.current && user.account) {\n      startViewTransition('forwards', () => {\n        transitioned = true;\n      });\n    } else {\n      startViewTransition('backwards', () => {\n        transitioned = false;\n      });\n    }\n  });\n</script>\n\n<svelte:head>\n  <meta name=\"referrer\" content=\"same-origin\" />\n  <meta name=\"robots\" content=\"noindex\" />\n  {#if cmsConfigLoaded.current}\n    <title>{documentTitle}</title>\n    <link rel=\"icon\" href={appLogoURL.current} type={appLogoType.current} />\n    {#if appIconURLs.current}\n      <link rel=\"apple-touch-icon\" href={appIconURLs.current.large} />\n    {/if}\n    {#if appManifestURL.current}\n      <link rel=\"manifest\" href={appManifestURL.current} />\n    {/if}\n  {/if}\n  {#if DEV_SITE_URL}\n    <link href=\"{DEV_SITE_URL}/admin/config.yml\" type=\"application/yaml\" rel=\"cms-config-url\" />\n  {/if}\n</svelte:head>\n\n<svelte:body\n  onmousedown={(event) => {\n    // The press can land on an element within the link, e.g. `<strong>` in a Markdown field hint\n    const link = /** @type {HTMLElement | null} */ (event.target)?.closest('a');\n\n    if (link) {\n      const { origin, pathname } = link;\n\n      // Open external links and links to different paths in a new tab\n      if (origin !== window.location.origin || pathname !== window.location.pathname) {\n        link.rel = 'noopener noreferrer';\n        link.target = '_blank';\n      }\n    }\n  }}\n/>\n\n<AppShell>\n  <div role=\"none\" class=\"outer\">\n    <!-- The page has a boundary of its own, so a failing page leaves the infobars and dialogs\n    around it working; this one catches a failure in those -->\n    <ErrorBoundary scope=\"page\">\n      <LocaleLoadErrorToast />\n      <ForkPermissionDialog />\n      <CommitMessageDialog />\n      <!-- The infobars are covered by the content and asset overlays, so they mustn’t take the\n      focus then. The dialogs stay outside: the commit message one is opened from the editor -->\n      <div role=\"none\" class=\"infobars\" inert={hasOverlay.current}>\n        <UpdateNotification />\n        {#if backend.current}\n          <BackendStatusIndicator />\n        {/if}\n        {#if user.account && dataLoaded.current}\n          <OpenAuthoringIndicator />\n        {/if}\n      </div>\n      <div role=\"none\" class=\"main\">\n        <ErrorBoundary scope=\"page\">\n          {#if user.account && dataLoaded.current && transitioned}\n            <MainRouter />\n          {:else}\n            <EntrancePage />\n          {/if}\n        </ErrorBoundary>\n      </div>\n    </ErrorBoundary>\n  </div>\n  <div role=\"status\">{announcedPageStatus.current}</div>\n</AppShell>\n\n<style>\n  @view-transition {\n    navigation: auto;\n  }\n\n  @keyframes slide-out-to-left {\n    from {\n      transform: translateX(0);\n      filter: brightness(1);\n    }\n\n    to {\n      transform: translateX(-20%);\n      filter: brightness(0.5);\n    }\n  }\n\n  @keyframes slide-out-to-right {\n    from {\n      transform: translateX(0);\n      opacity: 1;\n    }\n\n    to {\n      transform: translateX(100%);\n      opacity: 0;\n    }\n  }\n\n  @keyframes slide-in-from-right {\n    from {\n      transform: translateX(100%);\n      opacity: 0;\n    }\n\n    to {\n      transform: translateX(0);\n      opacity: 1;\n    }\n  }\n\n  @keyframes slide-in-from-left {\n    from {\n      transform: translateX(-20%);\n      filter: brightness(0.5);\n    }\n\n    to {\n      transform: translateX(0);\n      filter: brightness(1);\n    }\n  }\n\n  /* RTL-specific keyframes that mirror the depth effect */\n  @keyframes slide-out-to-left-rtl {\n    from {\n      transform: translateX(0);\n      opacity: 1;\n    }\n\n    to {\n      transform: translateX(-100%);\n      opacity: 0;\n    }\n  }\n\n  @keyframes slide-out-to-right-rtl {\n    from {\n      transform: translateX(0);\n      filter: brightness(1);\n    }\n\n    to {\n      transform: translateX(20%);\n      filter: brightness(0.5);\n    }\n  }\n\n  @keyframes slide-in-from-right-rtl {\n    from {\n      transform: translateX(20%);\n      filter: brightness(0.5);\n    }\n\n    to {\n      transform: translateX(0);\n      filter: brightness(1);\n    }\n  }\n\n  @keyframes slide-in-from-left-rtl {\n    from {\n      transform: translateX(-100%);\n      opacity: 0;\n    }\n\n    to {\n      transform: translateX(0);\n      opacity: 1;\n    }\n  }\n\n  @keyframes fade-out {\n    from {\n      opacity: 1;\n    }\n\n    to {\n      opacity: 0;\n    }\n  }\n\n  @keyframes fade-in {\n    from {\n      opacity: 0;\n    }\n\n    to {\n      opacity: 1;\n    }\n  }\n\n  :global {\n    /* The dragged item of a sortable list is left as a faint placeholder marking the gap it would\n      drop into. The pointer already carries the browser’s own drag image of it, so showing it\n      twice at full strength would just be confusing. */\n\n    .drag-placeholder {\n      opacity: 0.25;\n    }\n\n    html:active-view-transition-type(forwards) {\n      @media (width < 768px) {\n        &::view-transition-old(page-root) {\n          z-index: 999;\n          animation: 100ms ease-in both slide-out-to-left;\n\n          @media (prefers-reduced-motion) {\n            animation: none;\n          }\n        }\n\n        &::view-transition-new(page-root) {\n          @media (width < 768px) {\n            z-index: 1000;\n            animation: 100ms ease-in both slide-in-from-right;\n          }\n\n          @media (prefers-reduced-motion) {\n            animation: none;\n          }\n        }\n\n        &:dir(rtl) {\n          &::view-transition-old(page-root) {\n            animation: 100ms ease-in both slide-out-to-right-rtl;\n\n            @media (prefers-reduced-motion) {\n              animation: none;\n            }\n          }\n\n          &::view-transition-new(page-root) {\n            animation: 100ms ease-in both slide-in-from-left-rtl;\n\n            @media (prefers-reduced-motion) {\n              animation: none;\n            }\n          }\n        }\n      }\n    }\n\n    html:active-view-transition-type(backwards) {\n      @media (width < 768px) {\n        &::view-transition-old(page-root) {\n          z-index: 1000;\n          animation: 100ms ease-in both slide-out-to-right;\n\n          @media (prefers-reduced-motion) {\n            animation: none;\n          }\n        }\n\n        &::view-transition-new(page-root) {\n          z-index: 999;\n          animation: 100ms ease-in both slide-in-from-left;\n\n          @media (prefers-reduced-motion) {\n            animation: none;\n          }\n        }\n\n        &:dir(rtl) {\n          &::view-transition-old(page-root) {\n            animation: 100ms ease-in both slide-out-to-left-rtl;\n\n            @media (prefers-reduced-motion) {\n              animation: none;\n            }\n          }\n\n          &::view-transition-new(page-root) {\n            animation: 100ms ease-in both slide-in-from-right-rtl;\n\n            @media (prefers-reduced-motion) {\n              animation: none;\n            }\n          }\n        }\n      }\n    }\n\n    html:active-view-transition-type(unknown) {\n      &::view-transition-old(page-main) {\n        animation: 100ms ease-in both fade-out;\n\n        @media (prefers-reduced-motion) {\n          animation: none;\n        }\n      }\n\n      &::view-transition-new(page-main) {\n        animation: 100ms ease-in both fade-in;\n\n        @media (prefers-reduced-motion) {\n          animation: none;\n        }\n      }\n    }\n\n    body:not(:has(#nc-root)) {\n      overflow: hidden;\n    }\n\n    #nc-root > .sui.app-shell {\n      position: absolute;\n    }\n\n    .sui.app-shell {\n      /* A placeholder is often the only visible label of a search box, so it has to meet the 4.5:1\n        text contrast. Sveltia UI only renders it at full strength in the high-contrast themes; the\n        default themes leave it at 50% opacity, which is 2.6:1 on white. */\n      --sui-textbox-placeholder-foreground-color: var(--sui-tertiary-foreground-color);\n      --sui-textbox-placeholder-opacity: 1;\n      /* Border drawn where a primary area (page content, editor panes, asset preview) meets a\n        secondary one (sidebars, toolbars, the gutter between panes). The default themes tell them\n        apart by background alone, so the width is zero; the high-contrast themes, which set\n        `--sui-modal-border-width` to outline dialogs for the same reason, get a visible line. */\n      --area-border: var(--sui-modal-border-width) solid var(--sui-primary-border-color);\n    }\n  }\n\n  .outer {\n    display: flex;\n    flex-direction: column;\n    position: absolute;\n    inset: 0;\n    overflow: hidden;\n  }\n\n  .infobars {\n    display: contents;\n  }\n\n  .main {\n    position: relative;\n    flex: auto;\n    display: flex;\n    flex-direction: column;\n    overflow: hidden;\n    background-color: var(--sui-secondary-background-color);\n  }\n\n  [role='status'] {\n    position: absolute;\n    z-index: -1;\n    opacity: 0;\n    pointer-events: none;\n    -webkit-user-select: none;\n    user-select: none;\n  }\n</style>\n","import { isObject } from '@sveltia/utils/object';\nimport { mount } from 'svelte';\n\nimport App from '$lib/components/app.svelte';\nimport { assertOption } from '$lib/services/api/validate';\nimport { prefetchCmsConfig } from '$lib/services/config/loader';\n\n/**\n * @import { CmsConfig } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\nlet initialized = false;\n\n/**\n * Initialize the CMS, optionally with the given CMS configuration. When the CMS is loaded with a\n * classic `<script>` tag, e.g. from a CDN, it initializes itself automatically unless\n * `window.CMS_MANUAL_INIT` is set to `true` before the script is loaded. When it’s imported as a\n * module, e.g. from the npm package, this method always has to be called. It mounts the app on the\n * `<div id=\"nc-root\">` element if present, or the `<body>` element otherwise, waiting for the page\n * content to be loaded if needed. Calls after the first one are ignored.\n * @param {object} [options] Options.\n * @param {CmsConfig} [options.config] Configuration to be merged with the configuration file, such\n * as `config.yml`. Its options override the file’s, except for arrays such as `collections`, which\n * are concatenated, so an array item can be added but not replaced. Include\n * `load_config_file: false` to prevent the configuration file from being loaded, in which case\n * this has to be a complete configuration.\n * @returns {Promise<void>} Promise that resolves once the app has been mounted.\n * @throws {TypeError} If `config` is neither an object nor `undefined`. As this is an async\n * function, the error is thrown as a rejection of the returned Promise.\n * @see https://decapcms.org/docs/manual-initialization/\n * @see https://sveltiacms.app/en/docs/api/initialization\n */\nconst init = async ({ config } = {}) => {\n  assertOption(config === undefined || isObject(config), 'init', 'config', 'an object');\n\n  if (initialized) {\n    return;\n  }\n\n  initialized = true;\n\n  if (document.readyState === 'loading' && !document.querySelector('#nc-root')) {\n    // A custom mount element (`<div id=\"nc-root\">`) could appear after the CMS `<script>`, so just\n    // wait until the page content is loaded.\n    // @see https://decapcms.org/docs/custom-mounting/\n    // @see https://sveltiacms.app/en/docs/customization#custom-mount-element\n    await new Promise((resolve) => {\n      window.addEventListener('DOMContentLoaded', () => resolve(undefined), { once: true });\n    });\n  }\n\n  // Request the config file now rather than once the app has mounted and asks for it, so the\n  // network round trip overlaps the mount. A manual configuration can opt out of the file\n  if (config?.load_config_file !== false) {\n    prefetchCmsConfig();\n  }\n\n  mount(App, {\n    target: document.querySelector('#nc-root') ?? document.body,\n    props: { config },\n  });\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `init.d.ts` file\nexport { init };\n","import { customFileFormatRegistry } from '$lib/services/api/registries';\nimport { assertOption } from '$lib/services/api/validate';\nimport { BUILTIN_FILE_FORMATS } from '$lib/services/contents/file/constants';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { FileFormatter, FileParser } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\n/**\n * Register a custom entry file format. A custom format with the same name as a built-in one, such\n * as `json`, takes precedence over it, and registering a format again replaces the previous one.\n * @param {string} name Format name. This should match the `format` option of a collection where the\n * custom format will be used.\n * @param {string} extension File extension without a leading dot, e.g. `json5`. Files in a\n * collection with the custom format use this extension, regardless of the collection’s `extension`\n * option.\n * @param {{ fromFile?: FileParser, toFile?: FileFormatter }} methods Parser and/or formatter\n * methods. Async functions can be used. Without `fromFile`, files in the format are parsed with the\n * built-in parser for the format name, if any; without `toFile`, they are formatted likewise. If\n * the format name isn’t a built-in one, such as `yaml` or `json`, omit neither: without `fromFile`,\n * files in the format can’t be loaded, and without `toFile`, saving an entry fails with an error,\n * leaving the file untouched. A warning is logged when either is missing. `toFile` is also given a\n * context with a `serialize` function, which formats the content with the built-in formatter for\n * a built-in format name, so its output can be post-processed, e.g. with a code formatter.\n * @throws {TypeError} If `name` or `extension` is not a non-empty string, or if `fromFile` or\n * `toFile` is given but not a function.\n * @throws {Error} If neither `fromFile` nor `toFile` is provided.\n * @see https://decapcms.org/docs/custom-formatters/\n * @see https://sveltiacms.app/en/docs/api/file-formats\n */\nconst registerCustomFormat = (name, extension, { fromFile, toFile } = {}) => {\n  assertOption(isNonEmptyString(name), 'registerCustomFormat', 'name', 'a non-empty string');\n  assertOption(\n    isNonEmptyString(extension),\n    'registerCustomFormat',\n    'extension',\n    'a non-empty string',\n  );\n\n  // Check the types first, so a method given by mistake as a non-function is reported as such\n  // rather than as a missing method\n  assertOption(\n    fromFile === undefined || typeof fromFile === 'function',\n    'registerCustomFormat',\n    'fromFile',\n    'a function',\n  );\n\n  assertOption(\n    toFile === undefined || typeof toFile === 'function',\n    'registerCustomFormat',\n    'toFile',\n    'a function',\n  );\n\n  if (typeof fromFile !== 'function' && typeof toFile !== 'function') {\n    throw new Error(\n      'At least one of `fromFile` or `toFile` must be provided to `CMS.registerCustomFormat()`',\n    );\n  }\n\n  // Without a built-in method to fall back to, the format can only go one way\n  if (!BUILTIN_FILE_FORMATS.includes(name)) {\n    if (!fromFile) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `The custom “${name}” format has no \\`fromFile\\` method, so its entries can’t be loaded`,\n      );\n    }\n\n    if (!toFile) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `The custom “${name}” format has no \\`toFile\\` method, so its entries can’t be saved`,\n      );\n    }\n  }\n\n  customFileFormatRegistry.set(name, { extension, parser: fromFile, formatter: toFile });\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `register-custom-format.d.ts` file\nexport { registerCustomFormat };\n","import { isObject } from '@sveltia/utils/object';\n\nimport { isReactComponent } from '$lib/services/api/react';\nimport { preloadReactDom } from '$lib/services/api/react-dom';\nimport { customPageRegistry } from '$lib/services/api/registries';\nimport {\n  assertDefinition,\n  assertOption,\n  assertValid,\n  parseURLFromPage,\n} from '$lib/services/api/validate';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { CustomPageDefinition } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\n/**\n * Register a custom page, which is listed in the global toolbar, or in the Menu on small screens.\n * The page renders a React component, or embeds a web page in an iframe. With the `newTab` option,\n * the web page is opened in a new browser tab instead. Pages are listed in the order of\n * registration, and registering a page with the same `id` again replaces the previous one in place.\n * @param {CustomPageDefinition} definition Page definition.\n * @throws {TypeError} If `definition` is not an object, `id` is not a string of alphanumeric\n * characters, hyphens and underscores, `label` is not a non-empty string, `icon` is given but not a\n * non-empty string, neither or both of `component` and `url` are given, `component` is not a React\n * component, `url` is not a valid `http` or `https` URL or file path, or `newTab` is given but not\n * a boolean or along with `component`.\n * @see https://sveltiacms.app/en/docs/api/custom-pages\n */\nconst registerCustomPage = (definition) => {\n  assertOption(isObject(definition), 'registerCustomPage', 'definition', 'an object');\n\n  const { id, label, icon, component, url, newTab } = definition;\n\n  // The ID goes into the page’s URL path as is, so keep it to characters that need no encoding\n  assertDefinition(\n    typeof id === 'string' && /^[\\w-]+$/.test(id),\n    'id',\n    'a non-empty string of alphanumeric characters, hyphens and underscores',\n  );\n\n  assertDefinition(isNonEmptyString(label), 'label', 'a non-empty string');\n  assertDefinition(icon === undefined || isNonEmptyString(icon), 'icon', 'a non-empty string');\n\n  assertValid(\n    (component === undefined) !== (url === undefined),\n    'Either `definition.component` or `definition.url` must be given',\n  );\n\n  assertDefinition(\n    component === undefined || isReactComponent(component),\n    'component',\n    'a React component',\n  );\n\n  assertDefinition(\n    newTab === undefined || (typeof newTab === 'boolean' && component === undefined),\n    'newTab',\n    'a boolean given along with `url`',\n  );\n\n  /** @type {string | undefined} */\n  let resolvedURL = undefined;\n\n  if (url !== undefined) {\n    // Resolve a relative URL now. Other schemes are rejected, so that a `javascript:` URL can’t run\n    // in the CMS\n    const parsedURL = isNonEmptyString(url) ? parseURLFromPage(url) : null;\n\n    assertDefinition(\n      !!parsedURL && ['http:', 'https:'].includes(parsedURL.protocol),\n      'url',\n      'a valid `http` or `https` URL or file path',\n    );\n\n    resolvedURL = /** @type {URL} */ (parsedURL).href;\n  }\n\n  customPageRegistry.set(id, {\n    id,\n    label,\n    icon: icon ?? 'extension',\n    component,\n    url: resolvedURL,\n    newTab: newTab ?? false,\n  });\n\n  if (component) {\n    preloadReactDom();\n  }\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `register-custom-page.d.ts` file\nexport { registerCustomPage };\n","import { isObject } from '@sveltia/utils/object';\n\nimport { preloadImmutable } from '$lib/services/api/immutable';\nimport { customComponentRegistry } from '$lib/services/api/registries';\nimport { assertDefinition, assertOption, assertValid } from '$lib/services/api/validate';\nimport { normalizeEditorComponentTemplates } from '$lib/services/config/templates';\nimport { isInlinePatternComponent } from '$lib/services/contents/fields/rich-text/components/inline-pattern';\nimport {\n  getSelectorTagNames,\n  isValidSelector,\n} from '$lib/services/contents/fields/rich-text/components/utils';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import {\n * CustomEditorComponentDefinition,\n * EditorComponentDefinition,\n * InlineEditorComponentDefinition,\n * } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\n/**\n * Assert that the given option of a definition is a function, if given.\n * @param {any} value Option value.\n * @param {string} name Option name.\n */\nconst assertOptionalFunction = (value, name) => {\n  assertDefinition(value === undefined || typeof value === 'function', name, 'a function');\n};\n\n/**\n * Validate the options of a pattern-based inline component, which has the `type` option set to\n * `inline`. Like Decap CMS, `fromBlock` and `toBlock` are accepted in place of `fromInline` and\n * `toInline`.\n * @param {InlineEditorComponentDefinition} definition Component definition.\n */\nconst validateInlineDefinition = (definition) => {\n  const { fromInline, toInline, trigger, toPreview, onInsert, onEdit } = definition;\n  const { fromBlock, toBlock } = /** @type {Record<string, any>} */ (definition);\n\n  assertDefinition(typeof (toInline ?? toBlock) === 'function', 'toInline', 'a function');\n  assertOptionalFunction(fromInline ?? fromBlock, 'fromInline');\n  assertOptionalFunction(toPreview, 'toPreview');\n  assertOptionalFunction(onInsert, 'onInsert');\n  assertOptionalFunction(onEdit, 'onEdit');\n\n  assertDefinition(\n    trigger === undefined || isNonEmptyString(trigger),\n    'trigger',\n    'a non-empty string',\n  );\n};\n\n/**\n * Validate the options of a field-based component.\n * @param {EditorComponentDefinition} definition Component definition.\n */\nconst validateBlockDefinition = (definition) => {\n  assertDefinition(typeof definition.toBlock === 'function', 'toBlock', 'a function');\n  assertOptionalFunction(definition.toPreview, 'toPreview');\n  assertDefinition(Array.isArray(definition.fields), 'fields', 'an array');\n\n  const { htmlSelector, fromBlockHTML, toBlockHTML } = definition;\n  const htmlOptions = [htmlSelector, fromBlockHTML, toBlockHTML];\n\n  if (htmlOptions.some((option) => option !== undefined)) {\n    assertValid(\n      !htmlOptions.includes(undefined),\n      'The `definition.htmlSelector`, `definition.fromBlockHTML` and `definition.toBlockHTML` ' +\n        'must be given together',\n    );\n\n    assertDefinition(\n      isNonEmptyString(htmlSelector) && isValidSelector(htmlSelector),\n      'htmlSelector',\n      'a valid CSS selector',\n    );\n\n    assertValid(\n      !!getSelectorTagNames(/** @type {string} */ (htmlSelector)),\n      'Each selector in the `definition.htmlSelector` must name the element type it matches',\n    );\n\n    assertDefinition(typeof fromBlockHTML === 'function', 'fromBlockHTML', 'a function');\n    assertDefinition(typeof toBlockHTML === 'function', 'toBlockHTML', 'a function');\n  }\n};\n\n/**\n * Register a custom rich text editor component, which can be used in RichText and Markdown fields.\n * Registering a component with the same `id` again replaces the previous one. A component with the\n * `type` option set to `inline` is a pattern-based inline component, compatible with Decap CMS,\n * which has no fields.\n * @param {CustomEditorComponentDefinition} definition Component definition.\n * @throws {TypeError} If `definition` is not an object, `id` is not a non-empty string, `label` is\n * given but not a non-empty string, `pattern` is not a regular expression, `toPreview` is given\n * but not a function, or the other options are invalid. A field-based component must have\n * `toBlock` as a function and `fields` as an array, and the HTML options must be valid:\n * `htmlSelector`, `fromBlockHTML` and `toBlockHTML` must be given together, and `htmlSelector`\n * must be a valid CSS selector naming the element types it matches. An inline component must have\n * `toInline` as a function, `fromInline`, `onInsert` and `onEdit` must be functions if given, and\n * `trigger` must be a non-empty string if given.\n * @see https://decapcms.org/docs/custom-widgets/#registereditorcomponent\n * @see https://sveltiacms.app/en/docs/api/editor-components\n */\nconst registerEditorComponent = (definition) => {\n  assertOption(isObject(definition), 'registerEditorComponent', 'definition', 'an object');\n  assertDefinition(isNonEmptyString(definition.id), 'id', 'a non-empty string');\n\n  assertDefinition(\n    definition.label === undefined || isNonEmptyString(definition.label),\n    'label',\n    'a non-empty string',\n  );\n\n  assertDefinition(definition.pattern instanceof RegExp, 'pattern', 'a RegExp');\n\n  if (isInlinePatternComponent(definition)) {\n    validateInlineDefinition(definition);\n  } else {\n    validateBlockDefinition(definition);\n    // Like the configuration, the templates are written in their canonical form, e.g. `{{ slug }}`\n    // as `{{slug}}`\n    normalizeEditorComponentTemplates(definition);\n  }\n\n  customComponentRegistry.set(definition.id, definition);\n\n  // `toPreview()` receives the component’s fields as an Immutable List, like Netlify/Decap CMS, so\n  // start loading the library now if the function takes them, rather than for every component\n  if ((definition.toPreview?.length ?? 0) >= 3) {\n    preloadImmutable();\n  }\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `register-editor-component.d.ts` file\nexport { registerEditorComponent };\n","import { isObject } from '@sveltia/utils/object';\n\nimport { SUPPORTED_EVENT_TYPES } from '$lib/services/api/events';\nimport { preloadImmutable } from '$lib/services/api/immutable';\nimport { eventHookRegistry } from '$lib/services/api/registries';\n\n/**\n * @import { AppEventListener } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\n/**\n * Register an event listener. Multiple listeners can be registered for the same event; they are\n * called in the order of registration.\n * @param {AppEventListener} eventListener Event listener.\n * @throws {TypeError} If the event listener is not an object, `name` is not a string, or `handler`\n * is not a function.\n * @throws {RangeError} If the event listener name is not a supported event type.\n * @see https://decapcms.org/docs/registering-events/\n * @see https://sveltiacms.app/en/docs/api/events\n */\nconst registerEventListener = (eventListener) => {\n  if (!isObject(eventListener)) {\n    throw new TypeError('The event listener must be an object');\n  }\n\n  const { name, handler } = eventListener;\n\n  if (typeof name !== 'string' || typeof handler !== 'function') {\n    throw new TypeError(\n      'The event listener must have a string `name` property and a function `handler` property',\n    );\n  }\n\n  if (!SUPPORTED_EVENT_TYPES.includes(name)) {\n    throw new RangeError(\n      `Unsupported event listener name \"${name}\". ` +\n        `Supported names are: ${SUPPORTED_EVENT_TYPES.join(', ')}`,\n    );\n  }\n\n  eventHookRegistry.add(eventListener);\n  // The handler receives an Immutable Map, so start loading the library now rather than when the\n  // event fires\n  preloadImmutable();\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `register-event-listener.d.ts` file\nexport { registerEventListener };\n","import { isObject } from '@sveltia/utils/object';\n\nimport { preloadImmutable } from '$lib/services/api/immutable';\nimport { isReactComponent } from '$lib/services/api/react';\nimport { preloadReactDom } from '$lib/services/api/react-dom';\nimport { customFieldTypeRegistry } from '$lib/services/api/registries';\nimport { assertNotReserved, assertOption } from '$lib/services/api/validate';\nimport { BUILTIN_FIELD_TYPES } from '$lib/services/contents/fields';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import {\n * CustomFieldControl,\n * CustomFieldPreview,\n * CustomFieldSchema,\n * CustomFieldTypeDefinition,\n * } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\n/**\n * Register a custom field type (widget), which can be used with the `widget` field option.\n * Registering a field type with the same name again replaces the previous one.\n * `CMS.registerWidget()` is an alias of this method for compatibility with Netlify/Decap CMS. The\n * field type can be given either as positional arguments or as a single definition object, which\n * also takes a summary component.\n * @param {string | CustomFieldTypeDefinition} name Field type name, which cannot be the name of a\n * built-in field type, or a field type definition. With a definition, the other arguments are\n * ignored.\n * @param {CustomFieldControl | string} [control] React component for the edit pane, or the name of\n * another custom field type whose control is reused. Required unless a definition is given.\n * @param {CustomFieldPreview} [preview] React component for the preview pane. If omitted, no\n * preview is rendered for the field.\n * @param {CustomFieldSchema} [schema] JSON schema to validate the field type’s options in the CMS\n * configuration.\n * @throws {TypeError} If `name` is neither a non-empty string nor a definition object, the control\n * is neither a React component nor a string, the preview or the summary is given but not a React\n * component, or the schema is given but not an object.\n * @throws {Error} If `name` is the name of a built-in field type.\n * @see https://decapcms.org/docs/custom-widgets/\n * @see https://sveltiacms.app/en/docs/api/field-types\n */\nconst registerFieldType = (name, control, preview, schema) => {\n  const isDefinition = isObject(name);\n\n  /** @type {Partial<CustomFieldTypeDefinition>} */\n  const definition = isDefinition\n    ? /** @type {CustomFieldTypeDefinition} */ (name)\n    : { name, controlComponent: control, previewComponent: preview, schema };\n\n  // Name the options in error messages the way they were given\n  const [controlOption, previewOption] = isDefinition\n    ? ['controlComponent', 'previewComponent']\n    : ['control', 'preview'];\n\n  const {\n    name: typeName,\n    controlComponent,\n    previewComponent,\n    summaryComponent,\n    schema: typeSchema,\n  } = definition;\n\n  assertOption(isNonEmptyString(typeName), 'registerFieldType', 'name', 'a non-empty string');\n\n  assertNotReserved({\n    name: /** @type {string} */ (typeName),\n    reserved: BUILTIN_FIELD_TYPES,\n    subject: 'field type',\n    builtin: 'built-in field type',\n    custom: 'custom field type',\n  });\n\n  assertOption(\n    isReactComponent(controlComponent) || typeof controlComponent === 'string',\n    'registerFieldType',\n    controlOption,\n    'a React component or a string',\n  );\n\n  assertOption(\n    previewComponent === undefined || isReactComponent(previewComponent),\n    'registerFieldType',\n    previewOption,\n    'a React component',\n  );\n\n  assertOption(\n    summaryComponent === undefined || isReactComponent(summaryComponent),\n    'registerFieldType',\n    'summaryComponent',\n    'a React component',\n  );\n\n  assertOption(\n    typeSchema === undefined || isObject(typeSchema),\n    'registerFieldType',\n    'schema',\n    'an object',\n  );\n\n  customFieldTypeRegistry.set(/** @type {string} */ (typeName), {\n    control: /** @type {NonNullable<typeof controlComponent>} */ (controlComponent),\n    preview: previewComponent,\n    summary: summaryComponent,\n    schema: typeSchema,\n  });\n  // The components are React components receiving Immutable Maps, so start loading the libraries\n  // now rather than when the editor opens\n  preloadImmutable();\n  preloadReactDom();\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `register-field-type.d.ts` file\nexport { registerFieldType };\n","import { customPreviewStyleRegistry } from '$lib/services/api/registries';\nimport { assertOption, assertValid, parseURLFromPage } from '$lib/services/api/validate';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * Register a custom stylesheet to be applied to the entry preview pane. Multiple stylesheets can\n * be registered. A stylesheet can be limited to the entries of a collection, or to a file in a\n * file/singleton collection.\n * @param {string} style URL or file path of a stylesheet, or a raw CSS string if the `raw` option\n * is `true`. A relative path is resolved against the current page URL.\n * @param {object} [options] Options.\n * @param {boolean} [options.raw] Whether `style` is a raw CSS string. Default: `false`.\n * @param {string} [options.collection] Name of the collection whose entries the stylesheet is\n * applied to. Use `_singletons` for the singleton collection. Default: all collections.\n * @param {string} [options.file] Name of the file in the file/singleton collection given with the\n * `collection` option that the stylesheet is applied to. Default: all files in the collection.\n * @throws {TypeError} If `style` is not a non-empty string, `raw` is not a boolean, `style` is not\n * a valid URL or file path when `raw` is `false`, `collection` or `file` is given but not a\n * non-empty string, or `file` is given without `collection`.\n * @see https://decapcms.org/docs/customization/#registerpreviewstyle\n * @see https://sveltiacms.app/en/docs/api/preview-styles\n */\nconst registerPreviewStyle = (style, { raw = false, collection, file } = {}) => {\n  assertOption(isNonEmptyString(style), 'registerPreviewStyle', 'style', 'a non-empty string');\n  assertOption(typeof raw === 'boolean', 'registerPreviewStyle', 'raw', 'a boolean');\n\n  assertOption(\n    collection === undefined || isNonEmptyString(collection),\n    'registerPreviewStyle',\n    'collection',\n    'a non-empty string',\n  );\n\n  assertOption(\n    file === undefined || isNonEmptyString(file),\n    'registerPreviewStyle',\n    'file',\n    'a non-empty string',\n  );\n\n  assertValid(\n    file === undefined || collection !== undefined,\n    'The `file` option for `CMS.registerPreviewStyle()` requires the `collection` option',\n  );\n\n  // Convert a relative URL to absolute to ensure it works in the preview iframe, which has a\n  // unique blob URL as its origin\n  const parsedURL = raw ? null : parseURLFromPage(style);\n\n  assertOption(\n    raw || !!parsedURL,\n    'registerPreviewStyle',\n    'style',\n    'a valid URL or file path when `raw` is false',\n  );\n\n  const url = raw\n    ? // Create a blob URL for the raw CSS string\n      URL.createObjectURL(new Blob([style], { type: 'text/css' }))\n    : /** @type {URL} */ (parsedURL).href;\n\n  const registered = [...customPreviewStyleRegistry].some(\n    (entry) => entry.url === url && entry.collection === collection && entry.file === file,\n  );\n\n  if (!registered) {\n    customPreviewStyleRegistry.add({ url, collection, file });\n  }\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `register-preview-style.d.ts` file\nexport { registerPreviewStyle };\n","import { preloadImmutable } from '$lib/services/api/immutable';\nimport { isReactComponent } from '$lib/services/api/react';\nimport { preloadReactDom } from '$lib/services/api/react-dom';\nimport { customPreviewTemplateRegistry } from '$lib/services/api/registries';\nimport { assertOption } from '$lib/services/api/validate';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { CustomPreviewTemplate } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\n/**\n * Register a custom preview template, which replaces the default entry preview. Registering a\n * template with the same name again replaces the previous one.\n * @param {string} name Name of the entry collection, or of the file in a file/singleton collection,\n * whose entries are previewed with the template.\n * @param {CustomPreviewTemplate} component React component.\n * @throws {TypeError} If `name` is not a non-empty string or `component` is not a React component.\n * @see https://decapcms.org/docs/customization/#registerpreviewtemplate\n * @see https://sveltiacms.app/en/docs/api/preview-templates\n */\nconst registerPreviewTemplate = (name, component) => {\n  assertOption(isNonEmptyString(name), 'registerPreviewTemplate', 'name', 'a non-empty string');\n  assertOption(\n    isReactComponent(component),\n    'registerPreviewTemplate',\n    'component',\n    'a React component',\n  );\n\n  customPreviewTemplateRegistry.set(name, component);\n  // The template is a React component receiving Immutable Maps, so start loading the libraries\n  // now rather than when the preview opens\n  preloadImmutable();\n  preloadReactDom();\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `register-preview-template.d.ts` file\nexport { registerPreviewTemplate };\n","import { customStringTransformationRegistry } from '$lib/services/api/registries';\nimport { assertNotReserved, assertOption } from '$lib/services/api/validate';\nimport {\n  BUILTIN_STRING_TRANSFORMATIONS,\n  STRING_TRANSFORMATION_NAME_REGEX,\n} from '$lib/services/common/transformations';\n\n/**\n * @import { StringTransformer } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\n/**\n * Register a custom string transformation, which can be used in template tags like the built-in\n * ones, e.g. `{{title | reverse}}` or `{{title | wrap('[', ']')}}`, in the contexts where string\n * transformations are supported, such as the `summary` collection option and the Compute field’s\n * `value` option. Registering a transformation with the same name again replaces the previous one.\n * The transformation should be registered before the CMS is initialized, so it’s available when\n * entry summaries and field values are first rendered.\n * @param {string} name Transformation name, which can contain letters, digits and underscores, and\n * cannot start with a digit or be the name of a built-in transformation, such as `upper`.\n * @param {StringTransformer} transform Function that receives the value and a context\n * object containing the `args` given to the transformation and the content `locale`, and returns\n * the transformed string synchronously. If it throws an error or returns a Promise, the value is\n * passed through unchanged, and the first such failure of the function is logged to the console.\n * @throws {TypeError} If `name` is not a valid transformation name or `transform` is not a\n * function.\n * @throws {Error} If `name` is the name of a built-in transformation.\n * @see https://github.com/decaporg/decap-cms/issues/3677\n * @see https://sveltiacms.app/en/docs/api/string-transformations\n */\nconst registerStringTransformation = (name, transform) => {\n  assertOption(\n    typeof name === 'string' && STRING_TRANSFORMATION_NAME_REGEX.test(name),\n    'registerStringTransformation',\n    'name',\n    'a string consisting of letters, digits and underscores, not starting with a digit',\n  );\n\n  assertNotReserved({\n    name,\n    reserved: BUILTIN_STRING_TRANSFORMATIONS,\n    subject: 'string transformation',\n    builtin: 'built-in transformation',\n    custom: 'custom transformation',\n  });\n\n  assertOption(\n    typeof transform === 'function',\n    'registerStringTransformation',\n    'transform',\n    'a function',\n  );\n\n  customStringTransformationRegistry.set(name, transform);\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `register-string-transformation.d.ts` file\nexport { registerStringTransformation };\n","import { isObject } from '@sveltia/utils/object';\nimport { mount, unmount } from 'svelte';\n\nimport RichTextPreview from '$lib/components/contents/details/fields/rich-text/rich-text-preview.svelte';\nimport { assertOption } from '$lib/services/api/validate';\n\n/**\n * @import { RenderRichTextOptions } from '../../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\n\n/**\n * Render a Markdown/rich text value into the given element with the same pipeline as the built-in\n * RichText field preview: editor component previews (including nested components), Markdown\n * parsing, syntax highlighting, image URL resolution and HTML sanitization. This is primarily\n * intended for an editor component `toPreview()` that returns an `HTMLElement`, so the verbatim\n * value of a nested RichText or Markdown field can be rendered recursively.\n * @param {HTMLElement} target The element to render the preview into. The content is rendered\n * asynchronously, and the element doesn’t have to be attached to the document yet.\n * @param {string} value Markdown string.\n * @param {RenderRichTextOptions} [options] Options.\n * @returns {() => void} Function to remove the rendered preview and destroy any editor component\n * previews within it. Call it when the target element is no longer needed, e.g. when the element\n * preview receives an `Unmount` event.\n * @throws {TypeError} If `target` is not an element, `value` is not a string, or `fieldConfig` is\n * given but not an object.\n * @see https://sveltiacms.app/en/docs/api/editor-components\n */\nconst renderRichText = (target, value, { fieldConfig } = {}) => {\n  assertOption(target instanceof Element, 'renderRichText', 'target', 'an element');\n  assertOption(typeof value === 'string', 'renderRichText', 'value', 'a string');\n\n  assertOption(\n    fieldConfig === undefined || isObject(fieldConfig),\n    'renderRichText',\n    'fieldConfig',\n    'an object',\n  );\n\n  const component = mount(RichTextPreview, {\n    target,\n    props: {\n      locale: '',\n      keyPath: '',\n      typedKeyPath: '',\n      fieldConfig: {\n        name: 'body',\n        // Always sanitize the output unless explicitly disabled by the developer, regardless of the\n        // `field_defaults` config, because the value typically comes from a nested field edited by\n        // other users\n        sanitize_preview: true,\n        ...fieldConfig,\n        widget: 'richtext',\n      },\n      currentValue: value,\n    },\n  });\n\n  return () => {\n    unmount(component);\n  };\n};\n\n// Export the function this way instead of `export const` to prevent the annotations from being\n// stripped in the generated `render-rich-text.d.ts` file\nexport { renderRichText };\n","import BundledReact from 'react';\n\nimport { COMPATIBILITY_URL, UNSUPPORTED_FUNC_NAMES } from '$lib/services/api/compatibility';\n\nimport { getFieldType } from './methods/get-field-type';\nimport { init } from './methods/init';\nimport { registerCustomFormat } from './methods/register-custom-format';\nimport { registerCustomPage } from './methods/register-custom-page';\nimport { registerEditorComponent } from './methods/register-editor-component';\nimport { registerEventListener } from './methods/register-event-listener';\nimport { registerFieldType } from './methods/register-field-type';\nimport { registerPreviewStyle } from './methods/register-preview-style';\nimport { registerPreviewTemplate } from './methods/register-preview-template';\nimport { registerStringTransformation } from './methods/register-string-transformation';\nimport { renderRichText } from './methods/render-rich-text';\n// Don’t use `$lib` above, or the functions will not be declared in the generated `index.d.ts` file\n\n/**\n * The React instance bundled with the CMS, which renders custom preview templates, custom field\n * types and editor component previews. Hooks such as `useState` only work when taken from this\n * instance, not from another copy of React, e.g. the `react` package installed by the user.\n * @type {typeof import('react')}\n * @see https://sveltiacms.app/en/docs/api#writing-react-components\n */\nconst React = BundledReact;\n\n/**\n * The CMS object is a proxy that intercepts access to unsupported functions and logs a warning.\n * This allows users to call unsupported functions without breaking their code, while still being\n * informed that the function is not supported.\n */\nconst CMS = new Proxy(\n  {\n    React,\n    getFieldType,\n    getWidget: getFieldType, // alias for backward compatibility with Netlify/Decap CMS\n    init,\n    registerCustomFormat,\n    registerCustomPage,\n    registerEditorComponent,\n    registerEventListener,\n    registerFieldType,\n    registerPreviewStyle,\n    registerPreviewTemplate,\n    registerStringTransformation,\n    registerWidget: registerFieldType, // alias for backward compatibility with Netlify/Decap CMS\n    renderRichText,\n  },\n  {\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    get: (obj, /** @type {string} */ key) => {\n      if (key in obj) {\n        // @ts-ignore\n        return obj[key];\n      }\n\n      if (UNSUPPORTED_FUNC_NAMES.includes(key)) {\n        // eslint-disable-next-line no-console\n        console.warn(\n          'CMS.%s() is not supported in Sveltia CMS, and we don’t have any plans to implement it. ' +\n            'See %s for compatibility information.',\n          key,\n          COMPATIBILITY_URL,\n        );\n\n        // eslint-disable-next-line jsdoc/require-description\n        /** @returns {void} */\n        return () => undefined;\n      }\n\n      return undefined;\n    },\n  },\n);\n\nexport default CMS;\n\n// Export all the functions at once instead of `export const init`, etc. to prevent annotations from\n// being stripped in the generated `index.d.ts` file\nexport {\n  getFieldType,\n  getFieldType as getWidget, // alias for backward compatibility with Netlify/Decap CMS\n  init,\n  React,\n  registerCustomFormat,\n  registerCustomPage,\n  registerEditorComponent,\n  registerEventListener,\n  registerFieldType,\n  registerPreviewStyle,\n  registerPreviewTemplate,\n  registerStringTransformation,\n  registerFieldType as registerWidget, // alias for backward compatibility with Netlify/Decap CMS\n  renderRichText,\n};\n","var n=function(t,s,r,e){var u;s[0]=0;for(var h=1;h<s.length;h++){var p=s[h++],a=s[h]?(s[0]|=p?1:2,r[s[h++]]):s[++h];3===p?e[0]=a:4===p?e[1]=Object.assign(e[1]||{},a):5===p?(e[1]=e[1]||{})[s[++h]]=a:6===p?e[1][s[++h]]+=a+\"\":p?(u=t.apply(a,n(t,a,r,[\"\",null])),e.push(u),a[0]?s[0]|=2:(s[h-2]=0,s[h]=u)):e.push(a)}return e},t=new Map;export default function(s){var r=t.get(this);return r||(r=new Map,t.set(this,r)),(r=n(this,r.get(s)||(r.set(s,r=function(n){for(var t,s,r=1,e=\"\",u=\"\",h=[0],p=function(n){1===r&&(n||(e=e.replace(/^\\s*\\n\\s*|\\s*\\n\\s*$/g,\"\")))?h.push(0,n,e):3===r&&(n||e)?(h.push(3,n,e),r=2):2===r&&\"...\"===e&&n?h.push(4,n,0):2===r&&e&&!n?h.push(5,0,!0,e):r>=5&&((e||!n&&5===r)&&(h.push(r,0,e,s),r=6),n&&(h.push(r,n,0,s),r=6)),e=\"\"},a=0;a<n.length;a++){a&&(1===r&&p(),p(a));for(var l=0;l<n[a].length;l++)t=n[a][l],1===r?\"<\"===t?(p(),h=[h],r=3):e+=t:4===r?\"--\"===e&&\">\"===t?(r=1,e=\"\"):e=t+e[0]:u?t===u?u=\"\":e+=t:'\"'===t||\"'\"===t?u=t:\">\"===t?(p(),r=1):r&&(\"=\"===t?(r=5,s=e,e=\"\"):\"/\"===t&&(r<5||\">\"===n[a][l+1])?(p(),3===r&&(h=h[0]),r=h,(h=h[0]).push(2,0,r),r=0):\" \"===t||\"\\t\"===t||\"\\n\"===t||\"\\r\"===t?(p(),r=2):e+=t),3===r&&\"!--\"===e&&(r=4,h=h[0])}return p(),h}(s)),r),arguments,[])).length>1?r:r[0]}\n","import htm from 'htm';\nimport { createElement } from 'react';\n\n/**\n * @import { ReactElement } from 'react';\n */\n\n/**\n * Convert an inline style string, which Preact accepts but React rejects, to a style object. The\n * string is split into declarations rather than parsed by the browser, which would expand a\n * shorthand into its individual properties and lose those of a shorthand referring to a custom\n * property, e.g. `padding: var(--x)`. A semicolon within parentheses or quotes, e.g. in a data URL,\n * doesn’t end a declaration. `!important` is dropped, as React can’t set a priority.\n * @param {string} cssText Inline style string, e.g. `color: red; font-size: 2em`.\n * @returns {Record<string, string>} Style object, e.g. `{ color: 'red', fontSize: '2em' }`.\n */\nexport const parseStyle = (cssText) => {\n  /** @type {Record<string, string>} */\n  const style = {};\n  let declaration = '';\n  let depth = 0;\n  let quote = '';\n\n  /**\n   * Add the declaration read so far to the style object, unless it’s incomplete.\n   */\n  const addDeclaration = () => {\n    const index = declaration.indexOf(':');\n    const name = declaration.slice(0, index).trim();\n\n    // React can’t set a priority, and a value with one would be rejected altogether\n    const value = declaration\n      .slice(index + 1)\n      .replace(/!\\s*important\\s*$/i, '')\n      .trim();\n\n    if (index > 0 && name && value) {\n      style[\n        name.startsWith('--')\n          ? name\n          : name.toLowerCase().replace(/-([a-z])/g, (_, char) => char.toUpperCase())\n      ] = value;\n    }\n\n    declaration = '';\n  };\n\n  [...cssText].forEach((char) => {\n    if (quote) {\n      quote = char === quote ? '' : quote;\n    } else if (char === '\"' || char === \"'\") {\n      quote = char;\n    } else if (char === '(') {\n      depth += 1;\n    } else if (char === ')') {\n      depth -= 1;\n    } else if (char === ';' && depth <= 0) {\n      addDeclaration();\n\n      return;\n    }\n\n    declaration += char;\n  });\n\n  addDeclaration();\n\n  return style;\n};\n\n/**\n * Create a React element from what HTM parsed. Same as `React.createElement()`, except that a\n * string `style` prop is converted to an object, so markup copied from HTML or a Preact example\n * doesn’t crash. Other HTML attribute names like `class` and `for` already work in React 19.\n * @param {any} type Element type.\n * @param {Record<string, any> | null} props Props.\n * @param {any[]} children Children.\n * @returns {ReactElement} React element.\n */\nconst h = (type, props, ...children) =>\n  createElement(\n    type,\n    typeof props?.style === 'string' ? { ...props, style: parseStyle(props.style) } : props,\n    ...children,\n  );\n\n/**\n * Tagged template that creates React elements from HTML-like markup, powered by HTM. It lets you\n * write custom preview templates, field types and editor component previews in a JSX-like syntax\n * without a build step. Components are embedded with `<${Component} prop=${value} />`.\n * @type {(strings: TemplateStringsArray, ...values: any[]) => ReactElement | ReactElement[]}\n * @see https://github.com/developit/htm\n */\nexport const html = htm.bind(h);\n","/* eslint-disable no-console */\n\nimport createClass from 'create-react-class';\nimport DOMPurify from 'isomorphic-dompurify';\nimport { marked } from 'marked';\nimport React, { createElement, Fragment } from 'react';\nimport sharedModules, { sharedModulesKey } from 'virtual:shared-modules';\n\nimport { SHARED_REACT_KEY } from './chunks/constants';\nimport CMS, { init } from './services/api';\nimport { html } from './services/api/htm';\n\nexport default CMS;\nexport * from './services/api';\n// Don’t use `$lib` above, or type declarations will not be exported\n\nwindow.CMS = CMS;\nwindow.initCMS = init;\n\n// Expose React APIs for custom field types, custom preview templates and custom editor components.\n// React itself is available as `CMS.React` and the `React` export rather than on `window`.\n// `html` is the HTM tagged template bound to that React, for components without a build step\n// @see https://decapcms.org/docs/custom-widgets/\n// @see https://decapcms.org/docs/customization/\n// @see https://sveltiacms.app/en/docs/api/field-types\n// @see https://sveltiacms.app/en/docs/api/preview-templates\nwindow.createClass = createClass;\nwindow.createElement = createElement;\nwindow.h = createElement;\nwindow.rf = Fragment;\nwindow.html = html;\n\n// Share the React instance with the `react-dom` chunk, which is loaded on demand and has to render\n// the elements created with the React above rather than bring a copy of its own\n// @ts-ignore\nglobalThis[SHARED_REACT_KEY] = React;\n\n// Share the modules the backend chunks import with them, as they’re built separately and would\n// otherwise bring copies of their own, which wouldn’t share the state of the app’s modules. Only\n// the CDN builds have such chunks\nif (sharedModulesKey) {\n  // @ts-ignore\n  globalThis[sharedModulesKey] = sharedModules;\n}\n\n// Expose the Markdown parser and HTML sanitizer used by the CMS, so custom editor component\n// previews can render the value of a nested RichText or Markdown field, which is passed as is.\n// These are the same instances the CMS uses internally, meaning any Marked extension added with\n// `marked.use()` also affects the built-in preview.\n// @see https://marked.js.org/\n// @see https://github.com/cure53/DOMPurify\n// @see https://sveltiacms.app/en/docs/api/editor-components\nwindow.marked = marked;\nwindow.DOMPurify = DOMPurify;\n\nconst cssLinkElement = document.querySelector('link[rel=\"stylesheet\"][href$=\"/sveltia-cms.css\"]');\n\n// Warn if an invalid stylesheet is included. Claude tends to add it when setting up Sveltia CMS.\nif (cssLinkElement) {\n  console.warn(\n    'Sveltia CMS does not require a stylesheet. Remove the invalid `<link>` tag referencing ' +\n      '`sveltia-cms.css` to avoid unnecessary network requests.',\n  );\n}\n\nconst scriptElement = /** @type {HTMLScriptElement | null} */ (\n  document.querySelector('script[src$=\"/sveltia-cms.js\"]')\n);\n\n// Warn if the CMS script comes with `type=\"module\"`. Earlier versions of Sveltia CMS were built and\n// shipped as ES modules. Therefore, some users may have added the attribute to the script tag.\n// Additionally, Claude tends to add it due to outdated/inaccurate knowledge. We recommend removing\n// the attribute from the CMS script tag to avoid unexpected behavior.\nif (scriptElement?.type === 'module') {\n  console.warn(\n    'The Sveltia CMS script is not an ES module. Remove the \"type=\"module\" attribute from the ' +\n      '`<script>` tag to avoid unexpected behavior when using the JavaScript API.',\n  );\n}\n\nconst netlifyIdentityScriptElement = /** @type {HTMLScriptElement | null} */ (\n  document.querySelector('script[src=\"https://identity.netlify.com/v1/netlify-identity-widget.js\"]')\n);\n\n// Warn if Netlify Identity Widget is included, as it’s not compatible with Sveltia CMS.\nif (netlifyIdentityScriptElement) {\n  console.warn('Netlify Identity Widget is not supported in Sveltia CMS.');\n}\n\n// Automatically initialize the CMS if manual initialization is not requested AND the script is NOT\n// a module; We can’t just use `document.currentScript` for module detection because the earlier\n// versions of Sveltia CMS were built and shipped as modules\nif (!window.CMS_MANUAL_INIT && (document.currentScript || scriptElement || import.meta.env.DEV)) {\n  init();\n}\n"],"file":"sveltia-cms.mjs"}